(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define([], factory);
	else if(typeof exports === 'object')
		exports["QdtComponents"] = factory();
	else
		root["QdtComponents"] = factory();
})(window, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// 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 = 129);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


if (true) {
  module.exports = __webpack_require__(82);
} else {}


/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

/**
 * 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 (false) { var throwOnDirectAccess, ReactIs; } else {
  // By explicitly using `prop-types` you are opting into new production behavior.
  // http://fb.me/prop-types-in-prod
  module.exports = __webpack_require__(86)();
}


/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _extends; });
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);
}

/***/ }),
/* 3 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var deepmerge__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(46);
/* harmony import */ var deepmerge__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(deepmerge__WEBPACK_IMPORTED_MODULE_0__);


var merge = function merge(x, y) {
  return deepmerge__WEBPACK_IMPORTED_MODULE_0___default()(x, y, {
    arrayMerge: function arrayMerge(destinationArray, sourceArray) {
      return sourceArray;
    }
  });
};

merge.all = function (arr) {
  return deepmerge__WEBPACK_IMPORTED_MODULE_0___default.a.all(arr, {
    arrayMerge: function arrayMerge(destinationArray, sourceArray) {
      return sourceArray;
    }
  });
};

/* harmony default export */ __webpack_exports__["a"] = (merge);

/***/ }),
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// CONCATENATED MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js
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;
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _objectWithoutProperties; });

function _objectWithoutProperties(source, excluded) {
  if (source == null) return {};
  var target = _objectWithoutPropertiesLoose(source, excluded);
  var key, i;

  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);

    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key = sourceSymbolKeys[i];
      if (excluded.indexOf(key) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
      target[key] = source[key];
    }
  }

  return target;
}

/***/ }),
/* 5 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
function toVal(mix) {
	var k, y, str='';
	if (mix) {
		if (typeof mix === 'object') {
			if (Array.isArray(mix)) {
				for (k=0; k < mix.length; k++) {
					if (mix[k] && (y = toVal(mix[k]))) {
						str && (str += ' ');
						str += y;
					}
				}
			} else {
				for (k in mix) {
					if (mix[k] && (y = toVal(k))) {
						str && (str += ' ');
						str += y;
					}
				}
			}
		} else if (typeof mix !== 'boolean' && !mix.call) {
			str && (str += ' ');
			str += mix;
		}
	}
	return str;
}

/* harmony default export */ __webpack_exports__["a"] = (function () {
	var i=0, x, str='';
	while (i < arguments.length) {
		if (x = toVal(arguments[i++])) {
			str && (str += ' ');
			str += x
		}
	}
	return str;
});


/***/ }),
/* 6 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXTERNAL MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/extends.js
var esm_extends = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/@material-ui/styles/node_modules/@babel/runtime/helpers/esm/extends.js
var helpers_esm_extends = __webpack_require__(17);

// EXTERNAL MODULE: ./node_modules/@material-ui/styles/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js + 1 modules
var objectWithoutProperties = __webpack_require__(24);

// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__(0);
var react_default = /*#__PURE__*/__webpack_require__.n(react);

// EXTERNAL MODULE: ./node_modules/prop-types/index.js
var prop_types = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js
var hoist_non_react_statics_cjs = __webpack_require__(66);
var hoist_non_react_statics_cjs_default = /*#__PURE__*/__webpack_require__.n(hoist_non_react_statics_cjs);

// EXTERNAL MODULE: ./node_modules/@material-ui/styles/esm/makeStyles/makeStyles.js + 31 modules
var makeStyles = __webpack_require__(157);

// EXTERNAL MODULE: ./node_modules/@material-ui/styles/esm/getThemeProps/getThemeProps.js
var getThemeProps = __webpack_require__(155);

// EXTERNAL MODULE: ./node_modules/@material-ui/styles/esm/useTheme/useTheme.js
var useTheme = __webpack_require__(154);

// CONCATENATED MODULE: ./node_modules/@material-ui/styles/esm/withStyles/withStyles.js








 // Link a style sheet with a component.
// It does not modify the component passed to it;
// instead, it returns a new component, with a `classes` property.

var withStyles_withStyles = function withStyles(stylesOrCreator) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  return function (Component) {
    var defaultTheme = options.defaultTheme,
        _options$withTheme = options.withTheme,
        withTheme = _options$withTheme === void 0 ? false : _options$withTheme,
        name = options.name,
        stylesOptions = Object(objectWithoutProperties["a" /* default */])(options, ["defaultTheme", "withTheme", "name"]);

    if (false) {}

    var classNamePrefix = name;

    if (false) { var displayName; }

    var useStyles = Object(makeStyles["a" /* default */])(stylesOrCreator, Object(helpers_esm_extends["a" /* default */])({
      defaultTheme: defaultTheme,
      Component: Component,
      name: name || Component.displayName,
      classNamePrefix: classNamePrefix
    }, stylesOptions));
    var WithStyles = react_default.a.forwardRef(function WithStyles(props, ref) {
      var classesProp = props.classes,
          innerRef = props.innerRef,
          other = Object(objectWithoutProperties["a" /* default */])(props, ["classes", "innerRef"]);

      var classes = useStyles(props);
      var theme;
      var more = other;

      if (typeof name === 'string' || withTheme) {
        // name and withTheme are invariant in the outer scope
        // eslint-disable-next-line react-hooks/rules-of-hooks
        theme = Object(useTheme["a" /* default */])() || defaultTheme;

        if (name) {
          more = Object(getThemeProps["a" /* default */])({
            theme: theme,
            name: name,
            props: other
          });
        } // Provide the theme to the wrapped component.
        // So we don't have to use the `withTheme()` Higher-order Component.


        if (withTheme && !more.theme) {
          more.theme = theme;
        }
      }

      return react_default.a.createElement(Component, Object(helpers_esm_extends["a" /* default */])({
        ref: innerRef || ref,
        classes: classes
      }, more));
    });
     false ? undefined : void 0; // The wrapper receives only user supplied props, which could be a subset of
    // the actual props Component might receive due to merging with defaultProps.
    // So copying it here would give us the same result in the wrapper as well.

    WithStyles.defaultProps = Component.defaultProps;

    if (false) {}

    hoist_non_react_statics_cjs_default()(WithStyles, Component);

    if (false) {}

    return WithStyles;
  };
};

/* harmony default export */ var esm_withStyles_withStyles = (withStyles_withStyles);
// EXTERNAL MODULE: ./node_modules/@material-ui/core/esm/styles/defaultTheme.js
var styles_defaultTheme = __webpack_require__(26);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/withStyles.js




function styles_withStyles_withStyles(stylesOrCreator, options) {
  return esm_withStyles_withStyles(stylesOrCreator, Object(esm_extends["a" /* default */])({
    defaultTheme: styles_defaultTheme["a" /* default */]
  }, options));
}

/* harmony default export */ var styles_withStyles = __webpack_exports__["a"] = (styles_withStyles_withStyles);

/***/ }),
/* 7 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return capitalize; });
// It should to be noted that this function isn't equivalent to `text-transform: capitalize`.
//
// A strict capitalization should uppercase the first letter of each word a the sentence.
// We only handle the first word.
function capitalize(string) {
  if (false) {}

  return string.charAt(0).toUpperCase() + string.slice(1);
}

/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(88);


/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
  Copyright (c) 2017 Jed Watson.
  Licensed under the MIT License (MIT), see
  http://jedwatson.github.io/classnames
*/
/* global define */

(function () {
	'use strict';

	var hasOwn = {}.hasOwnProperty;

	function classNames () {
		var classes = [];

		for (var i = 0; i < arguments.length; i++) {
			var arg = arguments[i];
			if (!arg) continue;

			var argType = typeof arg;

			if (argType === 'string' || argType === 'number') {
				classes.push(arg);
			} else if (Array.isArray(arg) && arg.length) {
				var inner = classNames.apply(null, arg);
				if (inner) {
					classes.push(inner);
				}
			} else if (argType === 'object') {
				for (var key in arg) {
					if (hasOwn.call(arg, key) && arg[key]) {
						classes.push(key);
					}
				}
			}
		}

		return classes.join(' ');
	}

	if ( true && module.exports) {
		classNames.default = classNames;
		module.exports = classNames;
	} else if (true) {
		// register as 'classnames', consistent with npm package name
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () {
			return classNames;
		}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {}
}());


/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function checkDCE() {
  /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
  if (
    typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||
    typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'
  ) {
    return;
  }
  if (false) {}
  try {
    // Verify that the code above has been dead code eliminated (DCE'd).
    __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
  } catch (err) {
    // DevTools shouldn't crash React, no matter what.
    // We should still report in case we break this code.
    console.error(err);
  }
}

if (true) {
  // DCE check should happen before ReactDOM bundle executes so that
  // DevTools can report bad minification during injection.
  checkDCE();
  module.exports = __webpack_require__(83);
} else {}


/***/ }),
/* 11 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export hexToRgb */
/* unused harmony export rgbToHex */
/* unused harmony export hslToRgb */
/* unused harmony export decomposeColor */
/* unused harmony export recomposeColor */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return getContrastRatio; });
/* unused harmony export getLuminance */
/* unused harmony export emphasize */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return fade; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return darken; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return lighten; });
/* eslint-disable no-use-before-define */

/**
 * Returns a number whose value is limited to the given range.
 *
 * @param {number} value The value to be clamped
 * @param {number} min The lower boundary of the output range
 * @param {number} max The upper boundary of the output range
 * @returns {number} A number in the range [min, max]
 */
function clamp(value) {
  var min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var max = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;

  if (false) {}

  return Math.min(Math.max(min, value), max);
}
/**
 * Converts a color from CSS hex format to CSS rgb format.
 *
 * @param {string} color - Hex color, i.e. #nnn or #nnnnnn
 * @returns {string} A CSS rgb color string
 */


function hexToRgb(color) {
  color = color.substr(1);
  var re = new RegExp(".{1,".concat(color.length / 3, "}"), 'g');
  var colors = color.match(re);

  if (colors && colors[0].length === 1) {
    colors = colors.map(function (n) {
      return n + n;
    });
  }

  return colors ? "rgb(".concat(colors.map(function (n) {
    return parseInt(n, 16);
  }).join(', '), ")") : '';
}

function intToHex(int) {
  var hex = int.toString(16);
  return hex.length === 1 ? "0".concat(hex) : hex;
}
/**
 * Converts a color from CSS rgb format to CSS hex format.
 *
 * @param {string} color - RGB color, i.e. rgb(n, n, n)
 * @returns {string} A CSS rgb color string, i.e. #nnnnnn
 */


function rgbToHex(color) {
  // Idempotent
  if (color.indexOf('#') === 0) {
    return color;
  }

  var _decomposeColor = decomposeColor(color),
      values = _decomposeColor.values;

  return "#".concat(values.map(function (n) {
    return intToHex(n);
  }).join(''));
}
/**
 * Converts a color from hsl format to rgb format.
 *
 * @param {string} color - HSL color values
 * @returns {string} rgb color values
 */

function hslToRgb(color) {
  color = decomposeColor(color);
  var _color = color,
      values = _color.values;
  var h = values[0];
  var s = values[1] / 100;
  var l = values[2] / 100;
  var a = s * Math.min(l, 1 - l);

  var f = function f(n) {
    var k = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (n + h / 30) % 12;
    return l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
  };

  var type = 'rgb';
  var rgb = [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];

  if (color.type === 'hsla') {
    type += 'a';
    rgb.push(values[3]);
  }

  return recomposeColor({
    type: type,
    values: rgb
  });
}
/**
 * Returns an object with the type and values of a color.
 *
 * Note: Does not support rgb % values.
 *
 * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
 * @returns {object} - A MUI color object: {type: string, values: number[]}
 */

function decomposeColor(color) {
  // Idempotent
  if (color.type) {
    return color;
  }

  if (color.charAt(0) === '#') {
    return decomposeColor(hexToRgb(color));
  }

  var marker = color.indexOf('(');
  var type = color.substring(0, marker);

  if (['rgb', 'rgba', 'hsl', 'hsla'].indexOf(type) === -1) {
    throw new Error(["Material-UI: unsupported `".concat(color, "` color."), 'We support the following formats: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla().'].join('\n'));
  }

  var values = color.substring(marker + 1, color.length - 1).split(',');
  values = values.map(function (value) {
    return parseFloat(value);
  });
  return {
    type: type,
    values: values
  };
}
/**
 * Converts a color object with type and values to a string.
 *
 * @param {object} color - Decomposed color
 * @param {string} color.type - One of: 'rgb', 'rgba', 'hsl', 'hsla'
 * @param {array} color.values - [n,n,n] or [n,n,n,n]
 * @returns {string} A CSS color string
 */

function recomposeColor(color) {
  var type = color.type;
  var values = color.values;

  if (type.indexOf('rgb') !== -1) {
    // Only convert the first 3 values to int (i.e. not alpha)
    values = values.map(function (n, i) {
      return i < 3 ? parseInt(n, 10) : n;
    });
  } else if (type.indexOf('hsl') !== -1) {
    values[1] = "".concat(values[1], "%");
    values[2] = "".concat(values[2], "%");
  }

  return "".concat(type, "(").concat(values.join(', '), ")");
}
/**
 * Calculates the contrast ratio between two colors.
 *
 * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
 *
 * @param {string} foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
 * @param {string} background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
 * @returns {number} A contrast ratio value in the range 0 - 21.
 */

function getContrastRatio(foreground, background) {
  var lumA = getLuminance(foreground);
  var lumB = getLuminance(background);
  return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);
}
/**
 * The relative brightness of any point in a color space,
 * normalized to 0 for darkest black and 1 for lightest white.
 *
 * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
 *
 * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
 * @returns {number} The relative brightness of the color in the range 0 - 1
 */

function getLuminance(color) {
  color = decomposeColor(color);
  var rgb = color.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : color.values;
  rgb = rgb.map(function (val) {
    val /= 255; // normalized

    return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4);
  }); // Truncate at 3 digits

  return Number((0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]).toFixed(3));
}
/**
 * Darken or lighten a color, depending on its luminance.
 * Light colors are darkened, dark colors are lightened.
 *
 * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
 * @param {number} coefficient=0.15 - multiplier in the range 0 - 1
 * @returns {string} A CSS color string. Hex input values are returned as rgb
 */

function emphasize(color) {
  var coefficient = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.15;
  return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient);
}
/**
 * Set the absolute transparency of a color.
 * Any existing alpha values are overwritten.
 *
 * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
 * @param {number} value - value to set the alpha channel to in the range 0 -1
 * @returns {string} A CSS color string. Hex input values are returned as rgb
 */

function fade(color, value) {
  color = decomposeColor(color);
  value = clamp(value);

  if (color.type === 'rgb' || color.type === 'hsl') {
    color.type += 'a';
  }

  color.values[3] = value;
  return recomposeColor(color);
}
/**
 * Darkens a color.
 *
 * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
 * @param {number} coefficient - multiplier in the range 0 - 1
 * @returns {string} A CSS color string. Hex input values are returned as rgb
 */

function darken(color, coefficient) {
  color = decomposeColor(color);
  coefficient = clamp(coefficient);

  if (color.type.indexOf('hsl') !== -1) {
    color.values[2] *= 1 - coefficient;
  } else if (color.type.indexOf('rgb') !== -1) {
    for (var i = 0; i < 3; i += 1) {
      color.values[i] *= 1 - coefficient;
    }
  }

  return recomposeColor(color);
}
/**
 * Lightens a color.
 *
 * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
 * @param {number} coefficient - multiplier in the range 0 - 1
 * @returns {string} A CSS color string. Hex input values are returned as rgb
 */

function lighten(color, coefficient) {
  color = decomposeColor(color);
  coefficient = clamp(coefficient);

  if (color.type.indexOf('hsl') !== -1) {
    color.values[2] += (100 - color.values[2]) * coefficient;
  } else if (color.type.indexOf('rgb') !== -1) {
    for (var i = 0; i < 3; i += 1) {
      color.values[i] += (255 - color.values[i]) * coefficient;
    }
  }

  return recomposeColor(color);
}

/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {

(function (global, factory) {
	 true ? factory(exports) :
	undefined;
}(this, (function (exports) { 'use strict';

	// Polyfills

	if ( Number.EPSILON === undefined ) {

		Number.EPSILON = Math.pow( 2, - 52 );

	}

	if ( Number.isInteger === undefined ) {

		// Missing in IE
		// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger

		Number.isInteger = function ( value ) {

			return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;

		};

	}

	//

	if ( Math.sign === undefined ) {

		// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign

		Math.sign = function ( x ) {

			return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;

		};

	}

	if ( 'name' in Function.prototype === false ) {

		// Missing in IE
		// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name

		Object.defineProperty( Function.prototype, 'name', {

			get: function () {

				return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];

			}

		} );

	}

	if ( Object.assign === undefined ) {

		// Missing in IE
		// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

		Object.assign = function ( target ) {

			if ( target === undefined || target === null ) {

				throw new TypeError( 'Cannot convert undefined or null to object' );

			}

			var output = Object( target );

			for ( var index = 1; index < arguments.length; index ++ ) {

				var source = arguments[ index ];

				if ( source !== undefined && source !== null ) {

					for ( var nextKey in source ) {

						if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {

							output[ nextKey ] = source[ nextKey ];

						}

					}

				}

			}

			return output;

		};

	}

	var REVISION = '113';
	var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
	var TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
	var CullFaceNone = 0;
	var CullFaceBack = 1;
	var CullFaceFront = 2;
	var CullFaceFrontBack = 3;
	var FrontFaceDirectionCW = 0;
	var FrontFaceDirectionCCW = 1;
	var BasicShadowMap = 0;
	var PCFShadowMap = 1;
	var PCFSoftShadowMap = 2;
	var VSMShadowMap = 3;
	var FrontSide = 0;
	var BackSide = 1;
	var DoubleSide = 2;
	var FlatShading = 1;
	var SmoothShading = 2;
	var NoColors = 0;
	var FaceColors = 1;
	var VertexColors = 2;
	var NoBlending = 0;
	var NormalBlending = 1;
	var AdditiveBlending = 2;
	var SubtractiveBlending = 3;
	var MultiplyBlending = 4;
	var CustomBlending = 5;
	var AddEquation = 100;
	var SubtractEquation = 101;
	var ReverseSubtractEquation = 102;
	var MinEquation = 103;
	var MaxEquation = 104;
	var ZeroFactor = 200;
	var OneFactor = 201;
	var SrcColorFactor = 202;
	var OneMinusSrcColorFactor = 203;
	var SrcAlphaFactor = 204;
	var OneMinusSrcAlphaFactor = 205;
	var DstAlphaFactor = 206;
	var OneMinusDstAlphaFactor = 207;
	var DstColorFactor = 208;
	var OneMinusDstColorFactor = 209;
	var SrcAlphaSaturateFactor = 210;
	var NeverDepth = 0;
	var AlwaysDepth = 1;
	var LessDepth = 2;
	var LessEqualDepth = 3;
	var EqualDepth = 4;
	var GreaterEqualDepth = 5;
	var GreaterDepth = 6;
	var NotEqualDepth = 7;
	var MultiplyOperation = 0;
	var MixOperation = 1;
	var AddOperation = 2;
	var NoToneMapping = 0;
	var LinearToneMapping = 1;
	var ReinhardToneMapping = 2;
	var Uncharted2ToneMapping = 3;
	var CineonToneMapping = 4;
	var ACESFilmicToneMapping = 5;

	var UVMapping = 300;
	var CubeReflectionMapping = 301;
	var CubeRefractionMapping = 302;
	var EquirectangularReflectionMapping = 303;
	var EquirectangularRefractionMapping = 304;
	var SphericalReflectionMapping = 305;
	var CubeUVReflectionMapping = 306;
	var CubeUVRefractionMapping = 307;
	var RepeatWrapping = 1000;
	var ClampToEdgeWrapping = 1001;
	var MirroredRepeatWrapping = 1002;
	var NearestFilter = 1003;
	var NearestMipmapNearestFilter = 1004;
	var NearestMipMapNearestFilter = 1004;
	var NearestMipmapLinearFilter = 1005;
	var NearestMipMapLinearFilter = 1005;
	var LinearFilter = 1006;
	var LinearMipmapNearestFilter = 1007;
	var LinearMipMapNearestFilter = 1007;
	var LinearMipmapLinearFilter = 1008;
	var LinearMipMapLinearFilter = 1008;
	var UnsignedByteType = 1009;
	var ByteType = 1010;
	var ShortType = 1011;
	var UnsignedShortType = 1012;
	var IntType = 1013;
	var UnsignedIntType = 1014;
	var FloatType = 1015;
	var HalfFloatType = 1016;
	var UnsignedShort4444Type = 1017;
	var UnsignedShort5551Type = 1018;
	var UnsignedShort565Type = 1019;
	var UnsignedInt248Type = 1020;
	var AlphaFormat = 1021;
	var RGBFormat = 1022;
	var RGBAFormat = 1023;
	var LuminanceFormat = 1024;
	var LuminanceAlphaFormat = 1025;
	var RGBEFormat = RGBAFormat;
	var DepthFormat = 1026;
	var DepthStencilFormat = 1027;
	var RedFormat = 1028;
	var RedIntegerFormat = 1029;
	var RGFormat = 1030;
	var RGIntegerFormat = 1031;
	var RGBIntegerFormat = 1032;
	var RGBAIntegerFormat = 1033;

	var RGB_S3TC_DXT1_Format = 33776;
	var RGBA_S3TC_DXT1_Format = 33777;
	var RGBA_S3TC_DXT3_Format = 33778;
	var RGBA_S3TC_DXT5_Format = 33779;
	var RGB_PVRTC_4BPPV1_Format = 35840;
	var RGB_PVRTC_2BPPV1_Format = 35841;
	var RGBA_PVRTC_4BPPV1_Format = 35842;
	var RGBA_PVRTC_2BPPV1_Format = 35843;
	var RGB_ETC1_Format = 36196;
	var RGBA_ASTC_4x4_Format = 37808;
	var RGBA_ASTC_5x4_Format = 37809;
	var RGBA_ASTC_5x5_Format = 37810;
	var RGBA_ASTC_6x5_Format = 37811;
	var RGBA_ASTC_6x6_Format = 37812;
	var RGBA_ASTC_8x5_Format = 37813;
	var RGBA_ASTC_8x6_Format = 37814;
	var RGBA_ASTC_8x8_Format = 37815;
	var RGBA_ASTC_10x5_Format = 37816;
	var RGBA_ASTC_10x6_Format = 37817;
	var RGBA_ASTC_10x8_Format = 37818;
	var RGBA_ASTC_10x10_Format = 37819;
	var RGBA_ASTC_12x10_Format = 37820;
	var RGBA_ASTC_12x12_Format = 37821;
	var LoopOnce = 2200;
	var LoopRepeat = 2201;
	var LoopPingPong = 2202;
	var InterpolateDiscrete = 2300;
	var InterpolateLinear = 2301;
	var InterpolateSmooth = 2302;
	var ZeroCurvatureEnding = 2400;
	var ZeroSlopeEnding = 2401;
	var WrapAroundEnding = 2402;
	var TrianglesDrawMode = 0;
	var TriangleStripDrawMode = 1;
	var TriangleFanDrawMode = 2;
	var LinearEncoding = 3000;
	var sRGBEncoding = 3001;
	var GammaEncoding = 3007;
	var RGBEEncoding = 3002;
	var LogLuvEncoding = 3003;
	var RGBM7Encoding = 3004;
	var RGBM16Encoding = 3005;
	var RGBDEncoding = 3006;
	var BasicDepthPacking = 3200;
	var RGBADepthPacking = 3201;
	var TangentSpaceNormalMap = 0;
	var ObjectSpaceNormalMap = 1;

	var ZeroStencilOp = 0;
	var KeepStencilOp = 7680;
	var ReplaceStencilOp = 7681;
	var IncrementStencilOp = 7682;
	var DecrementStencilOp = 7683;
	var IncrementWrapStencilOp = 34055;
	var DecrementWrapStencilOp = 34056;
	var InvertStencilOp = 5386;

	var NeverStencilFunc = 512;
	var LessStencilFunc = 513;
	var EqualStencilFunc = 514;
	var LessEqualStencilFunc = 515;
	var GreaterStencilFunc = 516;
	var NotEqualStencilFunc = 517;
	var GreaterEqualStencilFunc = 518;
	var AlwaysStencilFunc = 519;

	var StaticDrawUsage = 35044;
	var DynamicDrawUsage = 35048;
	var StreamDrawUsage = 35040;
	var StaticReadUsage = 35045;
	var DynamicReadUsage = 35049;
	var StreamReadUsage = 35041;
	var StaticCopyUsage = 35046;
	var DynamicCopyUsage = 35050;
	var StreamCopyUsage = 35042;

	/**
	 * https://github.com/mrdoob/eventdispatcher.js/
	 */

	function EventDispatcher() {}

	Object.assign( EventDispatcher.prototype, {

		addEventListener: function ( type, listener ) {

			if ( this._listeners === undefined ) { this._listeners = {}; }

			var listeners = this._listeners;

			if ( listeners[ type ] === undefined ) {

				listeners[ type ] = [];

			}

			if ( listeners[ type ].indexOf( listener ) === - 1 ) {

				listeners[ type ].push( listener );

			}

		},

		hasEventListener: function ( type, listener ) {

			if ( this._listeners === undefined ) { return false; }

			var listeners = this._listeners;

			return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;

		},

		removeEventListener: function ( type, listener ) {

			if ( this._listeners === undefined ) { return; }

			var listeners = this._listeners;
			var listenerArray = listeners[ type ];

			if ( listenerArray !== undefined ) {

				var index = listenerArray.indexOf( listener );

				if ( index !== - 1 ) {

					listenerArray.splice( index, 1 );

				}

			}

		},

		dispatchEvent: function ( event ) {

			if ( this._listeners === undefined ) { return; }

			var listeners = this._listeners;
			var listenerArray = listeners[ event.type ];

			if ( listenerArray !== undefined ) {

				event.target = this;

				var array = listenerArray.slice( 0 );

				for ( var i = 0, l = array.length; i < l; i ++ ) {

					array[ i ].call( this, event );

				}

			}

		}

	} );

	/**
	 * @author alteredq / http://alteredqualia.com/
	 * @author mrdoob / http://mrdoob.com/
	 * @author WestLangley / http://github.com/WestLangley
	 * @author thezwap
	 */

	var _lut = [];

	for ( var i = 0; i < 256; i ++ ) {

		_lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );

	}

	var MathUtils = {

		DEG2RAD: Math.PI / 180,
		RAD2DEG: 180 / Math.PI,

		generateUUID: function () {

			// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136

			var d0 = Math.random() * 0xffffffff | 0;
			var d1 = Math.random() * 0xffffffff | 0;
			var d2 = Math.random() * 0xffffffff | 0;
			var d3 = Math.random() * 0xffffffff | 0;
			var uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
				_lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
				_lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
				_lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];

			// .toUpperCase() here flattens concatenated strings to save heap memory space.
			return uuid.toUpperCase();

		},

		clamp: function ( value, min, max ) {

			return Math.max( min, Math.min( max, value ) );

		},

		// compute euclidian modulo of m % n
		// https://en.wikipedia.org/wiki/Modulo_operation

		euclideanModulo: function ( n, m ) {

			return ( ( n % m ) + m ) % m;

		},

		// Linear mapping from range <a1, a2> to range <b1, b2>

		mapLinear: function ( x, a1, a2, b1, b2 ) {

			return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );

		},

		// https://en.wikipedia.org/wiki/Linear_interpolation

		lerp: function ( x, y, t ) {

			return ( 1 - t ) * x + t * y;

		},

		// http://en.wikipedia.org/wiki/Smoothstep

		smoothstep: function ( x, min, max ) {

			if ( x <= min ) { return 0; }
			if ( x >= max ) { return 1; }

			x = ( x - min ) / ( max - min );

			return x * x * ( 3 - 2 * x );

		},

		smootherstep: function ( x, min, max ) {

			if ( x <= min ) { return 0; }
			if ( x >= max ) { return 1; }

			x = ( x - min ) / ( max - min );

			return x * x * x * ( x * ( x * 6 - 15 ) + 10 );

		},

		// Random integer from <low, high> interval

		randInt: function ( low, high ) {

			return low + Math.floor( Math.random() * ( high - low + 1 ) );

		},

		// Random float from <low, high> interval

		randFloat: function ( low, high ) {

			return low + Math.random() * ( high - low );

		},

		// Random float from <-range/2, range/2> interval

		randFloatSpread: function ( range ) {

			return range * ( 0.5 - Math.random() );

		},

		degToRad: function ( degrees ) {

			return degrees * MathUtils.DEG2RAD;

		},

		radToDeg: function ( radians ) {

			return radians * MathUtils.RAD2DEG;

		},

		isPowerOfTwo: function ( value ) {

			return ( value & ( value - 1 ) ) === 0 && value !== 0;

		},

		ceilPowerOfTwo: function ( value ) {

			return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );

		},

		floorPowerOfTwo: function ( value ) {

			return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );

		},

		setQuaternionFromProperEuler: function ( q, a, b, c, order ) {

			// Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles

			// rotations are applied to the axes in the order specified by 'order'
			// rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
			// angles are in radians

			var cos = Math.cos;
			var sin = Math.sin;

			var c2 = cos( b / 2 );
			var s2 = sin( b / 2 );

			var c13 = cos( ( a + c ) / 2 );
			var s13 = sin( ( a + c ) / 2 );

			var c1_3 = cos( ( a - c ) / 2 );
			var s1_3 = sin( ( a - c ) / 2 );

			var c3_1 = cos( ( c - a ) / 2 );
			var s3_1 = sin( ( c - a ) / 2 );

			if ( order === 'XYX' ) {

				q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );

			} else if ( order === 'YZY' ) {

				q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );

			} else if ( order === 'ZXZ' ) {

				q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );

			} else if ( order === 'XZX' ) {

				q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );

			} else if ( order === 'YXY' ) {

				q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );

			} else if ( order === 'ZYZ' ) {

				q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );

			} else {

				console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order.' );

			}

		}

	};

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author philogb / http://blog.thejit.org/
	 * @author egraether / http://egraether.com/
	 * @author zz85 / http://www.lab4games.net/zz85/blog
	 */

	function Vector2( x, y ) {

		this.x = x || 0;
		this.y = y || 0;

	}

	Object.defineProperties( Vector2.prototype, {

		"width": {

			get: function () {

				return this.x;

			},

			set: function ( value ) {

				this.x = value;

			}

		},

		"height": {

			get: function () {

				return this.y;

			},

			set: function ( value ) {

				this.y = value;

			}

		}

	} );

	Object.assign( Vector2.prototype, {

		isVector2: true,

		set: function ( x, y ) {

			this.x = x;
			this.y = y;

			return this;

		},

		setScalar: function ( scalar ) {

			this.x = scalar;
			this.y = scalar;

			return this;

		},

		setX: function ( x ) {

			this.x = x;

			return this;

		},

		setY: function ( y ) {

			this.y = y;

			return this;

		},

		setComponent: function ( index, value ) {

			switch ( index ) {

				case 0: this.x = value; break;
				case 1: this.y = value; break;
				default: throw new Error( 'index is out of range: ' + index );

			}

			return this;

		},

		getComponent: function ( index ) {

			switch ( index ) {

				case 0: return this.x;
				case 1: return this.y;
				default: throw new Error( 'index is out of range: ' + index );

			}

		},

		clone: function () {

			return new this.constructor( this.x, this.y );

		},

		copy: function ( v ) {

			this.x = v.x;
			this.y = v.y;

			return this;

		},

		add: function ( v, w ) {

			if ( w !== undefined ) {

				console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
				return this.addVectors( v, w );

			}

			this.x += v.x;
			this.y += v.y;

			return this;

		},

		addScalar: function ( s ) {

			this.x += s;
			this.y += s;

			return this;

		},

		addVectors: function ( a, b ) {

			this.x = a.x + b.x;
			this.y = a.y + b.y;

			return this;

		},

		addScaledVector: function ( v, s ) {

			this.x += v.x * s;
			this.y += v.y * s;

			return this;

		},

		sub: function ( v, w ) {

			if ( w !== undefined ) {

				console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
				return this.subVectors( v, w );

			}

			this.x -= v.x;
			this.y -= v.y;

			return this;

		},

		subScalar: function ( s ) {

			this.x -= s;
			this.y -= s;

			return this;

		},

		subVectors: function ( a, b ) {

			this.x = a.x - b.x;
			this.y = a.y - b.y;

			return this;

		},

		multiply: function ( v ) {

			this.x *= v.x;
			this.y *= v.y;

			return this;

		},

		multiplyScalar: function ( scalar ) {

			this.x *= scalar;
			this.y *= scalar;

			return this;

		},

		divide: function ( v ) {

			this.x /= v.x;
			this.y /= v.y;

			return this;

		},

		divideScalar: function ( scalar ) {

			return this.multiplyScalar( 1 / scalar );

		},

		applyMatrix3: function ( m ) {

			var x = this.x, y = this.y;
			var e = m.elements;

			this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
			this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];

			return this;

		},

		min: function ( v ) {

			this.x = Math.min( this.x, v.x );
			this.y = Math.min( this.y, v.y );

			return this;

		},

		max: function ( v ) {

			this.x = Math.max( this.x, v.x );
			this.y = Math.max( this.y, v.y );

			return this;

		},

		clamp: function ( min, max ) {

			// assumes min < max, componentwise

			this.x = Math.max( min.x, Math.min( max.x, this.x ) );
			this.y = Math.max( min.y, Math.min( max.y, this.y ) );

			return this;

		},

		clampScalar: function ( minVal, maxVal ) {

			this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
			this.y = Math.max( minVal, Math.min( maxVal, this.y ) );

			return this;

		},

		clampLength: function ( min, max ) {

			var length = this.length();

			return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );

		},

		floor: function () {

			this.x = Math.floor( this.x );
			this.y = Math.floor( this.y );

			return this;

		},

		ceil: function () {

			this.x = Math.ceil( this.x );
			this.y = Math.ceil( this.y );

			return this;

		},

		round: function () {

			this.x = Math.round( this.x );
			this.y = Math.round( this.y );

			return this;

		},

		roundToZero: function () {

			this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
			this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );

			return this;

		},

		negate: function () {

			this.x = - this.x;
			this.y = - this.y;

			return this;

		},

		dot: function ( v ) {

			return this.x * v.x + this.y * v.y;

		},

		cross: function ( v ) {

			return this.x * v.y - this.y * v.x;

		},

		lengthSq: function () {

			return this.x * this.x + this.y * this.y;

		},

		length: function () {

			return Math.sqrt( this.x * this.x + this.y * this.y );

		},

		manhattanLength: function () {

			return Math.abs( this.x ) + Math.abs( this.y );

		},

		normalize: function () {

			return this.divideScalar( this.length() || 1 );

		},

		angle: function () {

			// computes the angle in radians with respect to the positive x-axis

			var angle = Math.atan2( this.y, this.x );

			if ( angle < 0 ) { angle += 2 * Math.PI; }

			return angle;

		},

		distanceTo: function ( v ) {

			return Math.sqrt( this.distanceToSquared( v ) );

		},

		distanceToSquared: function ( v ) {

			var dx = this.x - v.x, dy = this.y - v.y;
			return dx * dx + dy * dy;

		},

		manhattanDistanceTo: function ( v ) {

			return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );

		},

		setLength: function ( length ) {

			return this.normalize().multiplyScalar( length );

		},

		lerp: function ( v, alpha ) {

			this.x += ( v.x - this.x ) * alpha;
			this.y += ( v.y - this.y ) * alpha;

			return this;

		},

		lerpVectors: function ( v1, v2, alpha ) {

			return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );

		},

		equals: function ( v ) {

			return ( ( v.x === this.x ) && ( v.y === this.y ) );

		},

		fromArray: function ( array, offset ) {

			if ( offset === undefined ) { offset = 0; }

			this.x = array[ offset ];
			this.y = array[ offset + 1 ];

			return this;

		},

		toArray: function ( array, offset ) {

			if ( array === undefined ) { array = []; }
			if ( offset === undefined ) { offset = 0; }

			array[ offset ] = this.x;
			array[ offset + 1 ] = this.y;

			return array;

		},

		fromBufferAttribute: function ( attribute, index, offset ) {

			if ( offset !== undefined ) {

				console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );

			}

			this.x = attribute.getX( index );
			this.y = attribute.getY( index );

			return this;

		},

		rotateAround: function ( center, angle ) {

			var c = Math.cos( angle ), s = Math.sin( angle );

			var x = this.x - center.x;
			var y = this.y - center.y;

			this.x = x * c - y * s + center.x;
			this.y = x * s + y * c + center.y;

			return this;

		}

	} );

	/**
	 * @author alteredq / http://alteredqualia.com/
	 * @author WestLangley / http://github.com/WestLangley
	 * @author bhouston / http://clara.io
	 * @author tschw
	 */

	function Matrix3() {

		this.elements = [

			1, 0, 0,
			0, 1, 0,
			0, 0, 1

		];

		if ( arguments.length > 0 ) {

			console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );

		}

	}

	Object.assign( Matrix3.prototype, {

		isMatrix3: true,

		set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {

			var te = this.elements;

			te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
			te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
			te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;

			return this;

		},

		identity: function () {

			this.set(

				1, 0, 0,
				0, 1, 0,
				0, 0, 1

			);

			return this;

		},

		clone: function () {

			return new this.constructor().fromArray( this.elements );

		},

		copy: function ( m ) {

			var te = this.elements;
			var me = m.elements;

			te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
			te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
			te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];

			return this;

		},

		setFromMatrix4: function ( m ) {

			var me = m.elements;

			this.set(

				me[ 0 ], me[ 4 ], me[ 8 ],
				me[ 1 ], me[ 5 ], me[ 9 ],
				me[ 2 ], me[ 6 ], me[ 10 ]

			);

			return this;

		},

		multiply: function ( m ) {

			return this.multiplyMatrices( this, m );

		},

		premultiply: function ( m ) {

			return this.multiplyMatrices( m, this );

		},

		multiplyMatrices: function ( a, b ) {

			var ae = a.elements;
			var be = b.elements;
			var te = this.elements;

			var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
			var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
			var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];

			var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
			var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
			var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];

			te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
			te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
			te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;

			te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
			te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
			te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;

			te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
			te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
			te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;

			return this;

		},

		multiplyScalar: function ( s ) {

			var te = this.elements;

			te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
			te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
			te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;

			return this;

		},

		determinant: function () {

			var te = this.elements;

			var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
				d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
				g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];

			return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;

		},

		getInverse: function ( matrix, throwOnDegenerate ) {

			if ( matrix && matrix.isMatrix4 ) {

				console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." );

			}

			var me = matrix.elements,
				te = this.elements,

				n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
				n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
				n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],

				t11 = n33 * n22 - n32 * n23,
				t12 = n32 * n13 - n33 * n12,
				t13 = n23 * n12 - n22 * n13,

				det = n11 * t11 + n21 * t12 + n31 * t13;

			if ( det === 0 ) {

				var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";

				if ( throwOnDegenerate === true ) {

					throw new Error( msg );

				} else {

					console.warn( msg );

				}

				return this.identity();

			}

			var detInv = 1 / det;

			te[ 0 ] = t11 * detInv;
			te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
			te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;

			te[ 3 ] = t12 * detInv;
			te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
			te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;

			te[ 6 ] = t13 * detInv;
			te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
			te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;

			return this;

		},

		transpose: function () {

			var tmp, m = this.elements;

			tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
			tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
			tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;

			return this;

		},

		getNormalMatrix: function ( matrix4 ) {

			return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();

		},

		transposeIntoArray: function ( r ) {

			var m = this.elements;

			r[ 0 ] = m[ 0 ];
			r[ 1 ] = m[ 3 ];
			r[ 2 ] = m[ 6 ];
			r[ 3 ] = m[ 1 ];
			r[ 4 ] = m[ 4 ];
			r[ 5 ] = m[ 7 ];
			r[ 6 ] = m[ 2 ];
			r[ 7 ] = m[ 5 ];
			r[ 8 ] = m[ 8 ];

			return this;

		},

		setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) {

			var c = Math.cos( rotation );
			var s = Math.sin( rotation );

			this.set(
				sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
				- sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
				0, 0, 1
			);

		},

		scale: function ( sx, sy ) {

			var te = this.elements;

			te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
			te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;

			return this;

		},

		rotate: function ( theta ) {

			var c = Math.cos( theta );
			var s = Math.sin( theta );

			var te = this.elements;

			var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
			var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];

			te[ 0 ] = c * a11 + s * a21;
			te[ 3 ] = c * a12 + s * a22;
			te[ 6 ] = c * a13 + s * a23;

			te[ 1 ] = - s * a11 + c * a21;
			te[ 4 ] = - s * a12 + c * a22;
			te[ 7 ] = - s * a13 + c * a23;

			return this;

		},

		translate: function ( tx, ty ) {

			var te = this.elements;

			te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
			te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];

			return this;

		},

		equals: function ( matrix ) {

			var te = this.elements;
			var me = matrix.elements;

			for ( var i = 0; i < 9; i ++ ) {

				if ( te[ i ] !== me[ i ] ) { return false; }

			}

			return true;

		},

		fromArray: function ( array, offset ) {

			if ( offset === undefined ) { offset = 0; }

			for ( var i = 0; i < 9; i ++ ) {

				this.elements[ i ] = array[ i + offset ];

			}

			return this;

		},

		toArray: function ( array, offset ) {

			if ( array === undefined ) { array = []; }
			if ( offset === undefined ) { offset = 0; }

			var te = this.elements;

			array[ offset ] = te[ 0 ];
			array[ offset + 1 ] = te[ 1 ];
			array[ offset + 2 ] = te[ 2 ];

			array[ offset + 3 ] = te[ 3 ];
			array[ offset + 4 ] = te[ 4 ];
			array[ offset + 5 ] = te[ 5 ];

			array[ offset + 6 ] = te[ 6 ];
			array[ offset + 7 ] = te[ 7 ];
			array[ offset + 8 ] = te[ 8 ];

			return array;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author alteredq / http://alteredqualia.com/
	 * @author szimek / https://github.com/szimek/
	 */

	var _canvas;

	var ImageUtils = {

		getDataURL: function ( image ) {

			var canvas;

			if ( typeof HTMLCanvasElement == 'undefined' ) {

				return image.src;

			} else if ( image instanceof HTMLCanvasElement ) {

				canvas = image;

			} else {

				if ( _canvas === undefined ) { _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); }

				_canvas.width = image.width;
				_canvas.height = image.height;

				var context = _canvas.getContext( '2d' );

				if ( image instanceof ImageData ) {

					context.putImageData( image, 0, 0 );

				} else {

					context.drawImage( image, 0, 0, image.width, image.height );

				}

				canvas = _canvas;

			}

			if ( canvas.width > 2048 || canvas.height > 2048 ) {

				return canvas.toDataURL( 'image/jpeg', 0.6 );

			} else {

				return canvas.toDataURL( 'image/png' );

			}

		}

	};

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author alteredq / http://alteredqualia.com/
	 * @author szimek / https://github.com/szimek/
	 */

	var textureId = 0;

	function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {

		Object.defineProperty( this, 'id', { value: textureId ++ } );

		this.uuid = MathUtils.generateUUID();

		this.name = '';

		this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
		this.mipmaps = [];

		this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;

		this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
		this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;

		this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
		this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;

		this.anisotropy = anisotropy !== undefined ? anisotropy : 1;

		this.format = format !== undefined ? format : RGBAFormat;
		this.internalFormat = null;
		this.type = type !== undefined ? type : UnsignedByteType;

		this.offset = new Vector2( 0, 0 );
		this.repeat = new Vector2( 1, 1 );
		this.center = new Vector2( 0, 0 );
		this.rotation = 0;

		this.matrixAutoUpdate = true;
		this.matrix = new Matrix3();

		this.generateMipmaps = true;
		this.premultiplyAlpha = false;
		this.flipY = true;
		this.unpackAlignment = 4;	// valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)

		// Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
		//
		// Also changing the encoding after already used by a Material will not automatically make the Material
		// update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
		this.encoding = encoding !== undefined ? encoding : LinearEncoding;

		this.version = 0;
		this.onUpdate = null;

	}

	Texture.DEFAULT_IMAGE = undefined;
	Texture.DEFAULT_MAPPING = UVMapping;

	Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {

		constructor: Texture,

		isTexture: true,

		updateMatrix: function () {

			this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		copy: function ( source ) {

			this.name = source.name;

			this.image = source.image;
			this.mipmaps = source.mipmaps.slice( 0 );

			this.mapping = source.mapping;

			this.wrapS = source.wrapS;
			this.wrapT = source.wrapT;

			this.magFilter = source.magFilter;
			this.minFilter = source.minFilter;

			this.anisotropy = source.anisotropy;

			this.format = source.format;
			this.internalFormat = source.internalFormat;
			this.type = source.type;

			this.offset.copy( source.offset );
			this.repeat.copy( source.repeat );
			this.center.copy( source.center );
			this.rotation = source.rotation;

			this.matrixAutoUpdate = source.matrixAutoUpdate;
			this.matrix.copy( source.matrix );

			this.generateMipmaps = source.generateMipmaps;
			this.premultiplyAlpha = source.premultiplyAlpha;
			this.flipY = source.flipY;
			this.unpackAlignment = source.unpackAlignment;
			this.encoding = source.encoding;

			return this;

		},

		toJSON: function ( meta ) {

			var isRootObject = ( meta === undefined || typeof meta === 'string' );

			if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {

				return meta.textures[ this.uuid ];

			}

			var output = {

				metadata: {
					version: 4.5,
					type: 'Texture',
					generator: 'Texture.toJSON'
				},

				uuid: this.uuid,
				name: this.name,

				mapping: this.mapping,

				repeat: [ this.repeat.x, this.repeat.y ],
				offset: [ this.offset.x, this.offset.y ],
				center: [ this.center.x, this.center.y ],
				rotation: this.rotation,

				wrap: [ this.wrapS, this.wrapT ],

				format: this.format,
				type: this.type,
				encoding: this.encoding,

				minFilter: this.minFilter,
				magFilter: this.magFilter,
				anisotropy: this.anisotropy,

				flipY: this.flipY,

				premultiplyAlpha: this.premultiplyAlpha,
				unpackAlignment: this.unpackAlignment

			};

			if ( this.image !== undefined ) {

				// TODO: Move to THREE.Image

				var image = this.image;

				if ( image.uuid === undefined ) {

					image.uuid = MathUtils.generateUUID(); // UGH

				}

				if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {

					var url;

					if ( Array.isArray( image ) ) {

						// process array of images e.g. CubeTexture

						url = [];

						for ( var i = 0, l = image.length; i < l; i ++ ) {

							url.push( ImageUtils.getDataURL( image[ i ] ) );

						}

					} else {

						// process single image

						url = ImageUtils.getDataURL( image );

					}

					meta.images[ image.uuid ] = {
						uuid: image.uuid,
						url: url
					};

				}

				output.image = image.uuid;

			}

			if ( ! isRootObject ) {

				meta.textures[ this.uuid ] = output;

			}

			return output;

		},

		dispose: function () {

			this.dispatchEvent( { type: 'dispose' } );

		},

		transformUv: function ( uv ) {

			if ( this.mapping !== UVMapping ) { return uv; }

			uv.applyMatrix3( this.matrix );

			if ( uv.x < 0 || uv.x > 1 ) {

				switch ( this.wrapS ) {

					case RepeatWrapping:

						uv.x = uv.x - Math.floor( uv.x );
						break;

					case ClampToEdgeWrapping:

						uv.x = uv.x < 0 ? 0 : 1;
						break;

					case MirroredRepeatWrapping:

						if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {

							uv.x = Math.ceil( uv.x ) - uv.x;

						} else {

							uv.x = uv.x - Math.floor( uv.x );

						}
						break;

				}

			}

			if ( uv.y < 0 || uv.y > 1 ) {

				switch ( this.wrapT ) {

					case RepeatWrapping:

						uv.y = uv.y - Math.floor( uv.y );
						break;

					case ClampToEdgeWrapping:

						uv.y = uv.y < 0 ? 0 : 1;
						break;

					case MirroredRepeatWrapping:

						if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {

							uv.y = Math.ceil( uv.y ) - uv.y;

						} else {

							uv.y = uv.y - Math.floor( uv.y );

						}
						break;

				}

			}

			if ( this.flipY ) {

				uv.y = 1 - uv.y;

			}

			return uv;

		}

	} );

	Object.defineProperty( Texture.prototype, "needsUpdate", {

		set: function ( value ) {

			if ( value === true ) { this.version ++; }

		}

	} );

	/**
	 * @author supereggbert / http://www.paulbrunt.co.uk/
	 * @author philogb / http://blog.thejit.org/
	 * @author mikael emtinger / http://gomo.se/
	 * @author egraether / http://egraether.com/
	 * @author WestLangley / http://github.com/WestLangley
	 */

	function Vector4( x, y, z, w ) {

		this.x = x || 0;
		this.y = y || 0;
		this.z = z || 0;
		this.w = ( w !== undefined ) ? w : 1;

	}

	Object.defineProperties( Vector4.prototype, {

		"width": {

			get: function () {

				return this.z;

			},

			set: function ( value ) {

				this.z = value;

			}

		},

		"height": {

			get: function () {

				return this.w;

			},

			set: function ( value ) {

				this.w = value;

			}

		}

	} );

	Object.assign( Vector4.prototype, {

		isVector4: true,

		set: function ( x, y, z, w ) {

			this.x = x;
			this.y = y;
			this.z = z;
			this.w = w;

			return this;

		},

		setScalar: function ( scalar ) {

			this.x = scalar;
			this.y = scalar;
			this.z = scalar;
			this.w = scalar;

			return this;

		},

		setX: function ( x ) {

			this.x = x;

			return this;

		},

		setY: function ( y ) {

			this.y = y;

			return this;

		},

		setZ: function ( z ) {

			this.z = z;

			return this;

		},

		setW: function ( w ) {

			this.w = w;

			return this;

		},

		setComponent: function ( index, value ) {

			switch ( index ) {

				case 0: this.x = value; break;
				case 1: this.y = value; break;
				case 2: this.z = value; break;
				case 3: this.w = value; break;
				default: throw new Error( 'index is out of range: ' + index );

			}

			return this;

		},

		getComponent: function ( index ) {

			switch ( index ) {

				case 0: return this.x;
				case 1: return this.y;
				case 2: return this.z;
				case 3: return this.w;
				default: throw new Error( 'index is out of range: ' + index );

			}

		},

		clone: function () {

			return new this.constructor( this.x, this.y, this.z, this.w );

		},

		copy: function ( v ) {

			this.x = v.x;
			this.y = v.y;
			this.z = v.z;
			this.w = ( v.w !== undefined ) ? v.w : 1;

			return this;

		},

		add: function ( v, w ) {

			if ( w !== undefined ) {

				console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
				return this.addVectors( v, w );

			}

			this.x += v.x;
			this.y += v.y;
			this.z += v.z;
			this.w += v.w;

			return this;

		},

		addScalar: function ( s ) {

			this.x += s;
			this.y += s;
			this.z += s;
			this.w += s;

			return this;

		},

		addVectors: function ( a, b ) {

			this.x = a.x + b.x;
			this.y = a.y + b.y;
			this.z = a.z + b.z;
			this.w = a.w + b.w;

			return this;

		},

		addScaledVector: function ( v, s ) {

			this.x += v.x * s;
			this.y += v.y * s;
			this.z += v.z * s;
			this.w += v.w * s;

			return this;

		},

		sub: function ( v, w ) {

			if ( w !== undefined ) {

				console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
				return this.subVectors( v, w );

			}

			this.x -= v.x;
			this.y -= v.y;
			this.z -= v.z;
			this.w -= v.w;

			return this;

		},

		subScalar: function ( s ) {

			this.x -= s;
			this.y -= s;
			this.z -= s;
			this.w -= s;

			return this;

		},

		subVectors: function ( a, b ) {

			this.x = a.x - b.x;
			this.y = a.y - b.y;
			this.z = a.z - b.z;
			this.w = a.w - b.w;

			return this;

		},

		multiplyScalar: function ( scalar ) {

			this.x *= scalar;
			this.y *= scalar;
			this.z *= scalar;
			this.w *= scalar;

			return this;

		},

		applyMatrix4: function ( m ) {

			var x = this.x, y = this.y, z = this.z, w = this.w;
			var e = m.elements;

			this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
			this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
			this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
			this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;

			return this;

		},

		divideScalar: function ( scalar ) {

			return this.multiplyScalar( 1 / scalar );

		},

		setAxisAngleFromQuaternion: function ( q ) {

			// http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm

			// q is assumed to be normalized

			this.w = 2 * Math.acos( q.w );

			var s = Math.sqrt( 1 - q.w * q.w );

			if ( s < 0.0001 ) {

				this.x = 1;
				this.y = 0;
				this.z = 0;

			} else {

				this.x = q.x / s;
				this.y = q.y / s;
				this.z = q.z / s;

			}

			return this;

		},

		setAxisAngleFromRotationMatrix: function ( m ) {

			// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm

			// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)

			var angle, x, y, z,		// variables for result
				epsilon = 0.01,		// margin to allow for rounding errors
				epsilon2 = 0.1,		// margin to distinguish between 0 and 180 degrees

				te = m.elements,

				m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
				m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
				m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];

			if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
			     ( Math.abs( m13 - m31 ) < epsilon ) &&
			     ( Math.abs( m23 - m32 ) < epsilon ) ) {

				// singularity found
				// first check for identity matrix which must have +1 for all terms
				// in leading diagonal and zero in other terms

				if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
				     ( Math.abs( m13 + m31 ) < epsilon2 ) &&
				     ( Math.abs( m23 + m32 ) < epsilon2 ) &&
				     ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {

					// this singularity is identity matrix so angle = 0

					this.set( 1, 0, 0, 0 );

					return this; // zero angle, arbitrary axis

				}

				// otherwise this singularity is angle = 180

				angle = Math.PI;

				var xx = ( m11 + 1 ) / 2;
				var yy = ( m22 + 1 ) / 2;
				var zz = ( m33 + 1 ) / 2;
				var xy = ( m12 + m21 ) / 4;
				var xz = ( m13 + m31 ) / 4;
				var yz = ( m23 + m32 ) / 4;

				if ( ( xx > yy ) && ( xx > zz ) ) {

					// m11 is the largest diagonal term

					if ( xx < epsilon ) {

						x = 0;
						y = 0.707106781;
						z = 0.707106781;

					} else {

						x = Math.sqrt( xx );
						y = xy / x;
						z = xz / x;

					}

				} else if ( yy > zz ) {

					// m22 is the largest diagonal term

					if ( yy < epsilon ) {

						x = 0.707106781;
						y = 0;
						z = 0.707106781;

					} else {

						y = Math.sqrt( yy );
						x = xy / y;
						z = yz / y;

					}

				} else {

					// m33 is the largest diagonal term so base result on this

					if ( zz < epsilon ) {

						x = 0.707106781;
						y = 0.707106781;
						z = 0;

					} else {

						z = Math.sqrt( zz );
						x = xz / z;
						y = yz / z;

					}

				}

				this.set( x, y, z, angle );

				return this; // return 180 deg rotation

			}

			// as we have reached here there are no singularities so we can handle normally

			var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
			                   ( m13 - m31 ) * ( m13 - m31 ) +
			                   ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize

			if ( Math.abs( s ) < 0.001 ) { s = 1; }

			// prevent divide by zero, should not happen if matrix is orthogonal and should be
			// caught by singularity test above, but I've left it in just in case

			this.x = ( m32 - m23 ) / s;
			this.y = ( m13 - m31 ) / s;
			this.z = ( m21 - m12 ) / s;
			this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );

			return this;

		},

		min: function ( v ) {

			this.x = Math.min( this.x, v.x );
			this.y = Math.min( this.y, v.y );
			this.z = Math.min( this.z, v.z );
			this.w = Math.min( this.w, v.w );

			return this;

		},

		max: function ( v ) {

			this.x = Math.max( this.x, v.x );
			this.y = Math.max( this.y, v.y );
			this.z = Math.max( this.z, v.z );
			this.w = Math.max( this.w, v.w );

			return this;

		},

		clamp: function ( min, max ) {

			// assumes min < max, componentwise

			this.x = Math.max( min.x, Math.min( max.x, this.x ) );
			this.y = Math.max( min.y, Math.min( max.y, this.y ) );
			this.z = Math.max( min.z, Math.min( max.z, this.z ) );
			this.w = Math.max( min.w, Math.min( max.w, this.w ) );

			return this;

		},

		clampScalar: function ( minVal, maxVal ) {

			this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
			this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
			this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
			this.w = Math.max( minVal, Math.min( maxVal, this.w ) );

			return this;

		},

		clampLength: function ( min, max ) {

			var length = this.length();

			return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );

		},

		floor: function () {

			this.x = Math.floor( this.x );
			this.y = Math.floor( this.y );
			this.z = Math.floor( this.z );
			this.w = Math.floor( this.w );

			return this;

		},

		ceil: function () {

			this.x = Math.ceil( this.x );
			this.y = Math.ceil( this.y );
			this.z = Math.ceil( this.z );
			this.w = Math.ceil( this.w );

			return this;

		},

		round: function () {

			this.x = Math.round( this.x );
			this.y = Math.round( this.y );
			this.z = Math.round( this.z );
			this.w = Math.round( this.w );

			return this;

		},

		roundToZero: function () {

			this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
			this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
			this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
			this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );

			return this;

		},

		negate: function () {

			this.x = - this.x;
			this.y = - this.y;
			this.z = - this.z;
			this.w = - this.w;

			return this;

		},

		dot: function ( v ) {

			return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;

		},

		lengthSq: function () {

			return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;

		},

		length: function () {

			return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );

		},

		manhattanLength: function () {

			return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );

		},

		normalize: function () {

			return this.divideScalar( this.length() || 1 );

		},

		setLength: function ( length ) {

			return this.normalize().multiplyScalar( length );

		},

		lerp: function ( v, alpha ) {

			this.x += ( v.x - this.x ) * alpha;
			this.y += ( v.y - this.y ) * alpha;
			this.z += ( v.z - this.z ) * alpha;
			this.w += ( v.w - this.w ) * alpha;

			return this;

		},

		lerpVectors: function ( v1, v2, alpha ) {

			return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );

		},

		equals: function ( v ) {

			return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );

		},

		fromArray: function ( array, offset ) {

			if ( offset === undefined ) { offset = 0; }

			this.x = array[ offset ];
			this.y = array[ offset + 1 ];
			this.z = array[ offset + 2 ];
			this.w = array[ offset + 3 ];

			return this;

		},

		toArray: function ( array, offset ) {

			if ( array === undefined ) { array = []; }
			if ( offset === undefined ) { offset = 0; }

			array[ offset ] = this.x;
			array[ offset + 1 ] = this.y;
			array[ offset + 2 ] = this.z;
			array[ offset + 3 ] = this.w;

			return array;

		},

		fromBufferAttribute: function ( attribute, index, offset ) {

			if ( offset !== undefined ) {

				console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );

			}

			this.x = attribute.getX( index );
			this.y = attribute.getY( index );
			this.z = attribute.getZ( index );
			this.w = attribute.getW( index );

			return this;

		}

	} );

	/**
	 * @author szimek / https://github.com/szimek/
	 * @author alteredq / http://alteredqualia.com/
	 * @author Marius Kintel / https://github.com/kintel
	 */

	/*
	 In options, we can specify:
	 * Texture parameters for an auto-generated target texture
	 * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
	*/
	function WebGLRenderTarget( width, height, options ) {

		this.width = width;
		this.height = height;

		this.scissor = new Vector4( 0, 0, width, height );
		this.scissorTest = false;

		this.viewport = new Vector4( 0, 0, width, height );

		options = options || {};

		this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );

		this.texture.image = {};
		this.texture.image.width = width;
		this.texture.image.height = height;

		this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
		this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;

		this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
		this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
		this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;

	}

	WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {

		constructor: WebGLRenderTarget,

		isWebGLRenderTarget: true,

		setSize: function ( width, height ) {

			if ( this.width !== width || this.height !== height ) {

				this.width = width;
				this.height = height;

				this.texture.image.width = width;
				this.texture.image.height = height;

				this.dispose();

			}

			this.viewport.set( 0, 0, width, height );
			this.scissor.set( 0, 0, width, height );

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		copy: function ( source ) {

			this.width = source.width;
			this.height = source.height;

			this.viewport.copy( source.viewport );

			this.texture = source.texture.clone();

			this.depthBuffer = source.depthBuffer;
			this.stencilBuffer = source.stencilBuffer;
			this.depthTexture = source.depthTexture;

			return this;

		},

		dispose: function () {

			this.dispatchEvent( { type: 'dispose' } );

		}

	} );

	/**
	 * @author Mugen87 / https://github.com/Mugen87
	 * @author Matt DesLauriers / @mattdesl
	 */

	function WebGLMultisampleRenderTarget( width, height, options ) {

		WebGLRenderTarget.call( this, width, height, options );

		this.samples = 4;

	}

	WebGLMultisampleRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), {

		constructor: WebGLMultisampleRenderTarget,

		isWebGLMultisampleRenderTarget: true,

		copy: function ( source ) {

			WebGLRenderTarget.prototype.copy.call( this, source );

			this.samples = source.samples;

			return this;

		}

	} );

	/**
	 * @author mikael emtinger / http://gomo.se/
	 * @author alteredq / http://alteredqualia.com/
	 * @author WestLangley / http://github.com/WestLangley
	 * @author bhouston / http://clara.io
	 */

	function Quaternion( x, y, z, w ) {

		this._x = x || 0;
		this._y = y || 0;
		this._z = z || 0;
		this._w = ( w !== undefined ) ? w : 1;

	}

	Object.assign( Quaternion, {

		slerp: function ( qa, qb, qm, t ) {

			return qm.copy( qa ).slerp( qb, t );

		},

		slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {

			// fuzz-free, array-based Quaternion SLERP operation

			var x0 = src0[ srcOffset0 + 0 ],
				y0 = src0[ srcOffset0 + 1 ],
				z0 = src0[ srcOffset0 + 2 ],
				w0 = src0[ srcOffset0 + 3 ],

				x1 = src1[ srcOffset1 + 0 ],
				y1 = src1[ srcOffset1 + 1 ],
				z1 = src1[ srcOffset1 + 2 ],
				w1 = src1[ srcOffset1 + 3 ];

			if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {

				var s = 1 - t,

					cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,

					dir = ( cos >= 0 ? 1 : - 1 ),
					sqrSin = 1 - cos * cos;

				// Skip the Slerp for tiny steps to avoid numeric problems:
				if ( sqrSin > Number.EPSILON ) {

					var sin = Math.sqrt( sqrSin ),
						len = Math.atan2( sin, cos * dir );

					s = Math.sin( s * len ) / sin;
					t = Math.sin( t * len ) / sin;

				}

				var tDir = t * dir;

				x0 = x0 * s + x1 * tDir;
				y0 = y0 * s + y1 * tDir;
				z0 = z0 * s + z1 * tDir;
				w0 = w0 * s + w1 * tDir;

				// Normalize in case we just did a lerp:
				if ( s === 1 - t ) {

					var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );

					x0 *= f;
					y0 *= f;
					z0 *= f;
					w0 *= f;

				}

			}

			dst[ dstOffset ] = x0;
			dst[ dstOffset + 1 ] = y0;
			dst[ dstOffset + 2 ] = z0;
			dst[ dstOffset + 3 ] = w0;

		}

	} );

	Object.defineProperties( Quaternion.prototype, {

		x: {

			get: function () {

				return this._x;

			},

			set: function ( value ) {

				this._x = value;
				this._onChangeCallback();

			}

		},

		y: {

			get: function () {

				return this._y;

			},

			set: function ( value ) {

				this._y = value;
				this._onChangeCallback();

			}

		},

		z: {

			get: function () {

				return this._z;

			},

			set: function ( value ) {

				this._z = value;
				this._onChangeCallback();

			}

		},

		w: {

			get: function () {

				return this._w;

			},

			set: function ( value ) {

				this._w = value;
				this._onChangeCallback();

			}

		}

	} );

	Object.assign( Quaternion.prototype, {

		isQuaternion: true,

		set: function ( x, y, z, w ) {

			this._x = x;
			this._y = y;
			this._z = z;
			this._w = w;

			this._onChangeCallback();

			return this;

		},

		clone: function () {

			return new this.constructor( this._x, this._y, this._z, this._w );

		},

		copy: function ( quaternion ) {

			this._x = quaternion.x;
			this._y = quaternion.y;
			this._z = quaternion.z;
			this._w = quaternion.w;

			this._onChangeCallback();

			return this;

		},

		setFromEuler: function ( euler, update ) {

			if ( ! ( euler && euler.isEuler ) ) {

				throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );

			}

			var x = euler._x, y = euler._y, z = euler._z, order = euler.order;

			// http://www.mathworks.com/matlabcentral/fileexchange/
			// 	20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
			//	content/SpinCalc.m

			var cos = Math.cos;
			var sin = Math.sin;

			var c1 = cos( x / 2 );
			var c2 = cos( y / 2 );
			var c3 = cos( z / 2 );

			var s1 = sin( x / 2 );
			var s2 = sin( y / 2 );
			var s3 = sin( z / 2 );

			if ( order === 'XYZ' ) {

				this._x = s1 * c2 * c3 + c1 * s2 * s3;
				this._y = c1 * s2 * c3 - s1 * c2 * s3;
				this._z = c1 * c2 * s3 + s1 * s2 * c3;
				this._w = c1 * c2 * c3 - s1 * s2 * s3;

			} else if ( order === 'YXZ' ) {

				this._x = s1 * c2 * c3 + c1 * s2 * s3;
				this._y = c1 * s2 * c3 - s1 * c2 * s3;
				this._z = c1 * c2 * s3 - s1 * s2 * c3;
				this._w = c1 * c2 * c3 + s1 * s2 * s3;

			} else if ( order === 'ZXY' ) {

				this._x = s1 * c2 * c3 - c1 * s2 * s3;
				this._y = c1 * s2 * c3 + s1 * c2 * s3;
				this._z = c1 * c2 * s3 + s1 * s2 * c3;
				this._w = c1 * c2 * c3 - s1 * s2 * s3;

			} else if ( order === 'ZYX' ) {

				this._x = s1 * c2 * c3 - c1 * s2 * s3;
				this._y = c1 * s2 * c3 + s1 * c2 * s3;
				this._z = c1 * c2 * s3 - s1 * s2 * c3;
				this._w = c1 * c2 * c3 + s1 * s2 * s3;

			} else if ( order === 'YZX' ) {

				this._x = s1 * c2 * c3 + c1 * s2 * s3;
				this._y = c1 * s2 * c3 + s1 * c2 * s3;
				this._z = c1 * c2 * s3 - s1 * s2 * c3;
				this._w = c1 * c2 * c3 - s1 * s2 * s3;

			} else if ( order === 'XZY' ) {

				this._x = s1 * c2 * c3 - c1 * s2 * s3;
				this._y = c1 * s2 * c3 - s1 * c2 * s3;
				this._z = c1 * c2 * s3 + s1 * s2 * c3;
				this._w = c1 * c2 * c3 + s1 * s2 * s3;

			}

			if ( update !== false ) { this._onChangeCallback(); }

			return this;

		},

		setFromAxisAngle: function ( axis, angle ) {

			// http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm

			// assumes axis is normalized

			var halfAngle = angle / 2, s = Math.sin( halfAngle );

			this._x = axis.x * s;
			this._y = axis.y * s;
			this._z = axis.z * s;
			this._w = Math.cos( halfAngle );

			this._onChangeCallback();

			return this;

		},

		setFromRotationMatrix: function ( m ) {

			// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm

			// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)

			var te = m.elements,

				m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
				m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
				m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],

				trace = m11 + m22 + m33,
				s;

			if ( trace > 0 ) {

				s = 0.5 / Math.sqrt( trace + 1.0 );

				this._w = 0.25 / s;
				this._x = ( m32 - m23 ) * s;
				this._y = ( m13 - m31 ) * s;
				this._z = ( m21 - m12 ) * s;

			} else if ( m11 > m22 && m11 > m33 ) {

				s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );

				this._w = ( m32 - m23 ) / s;
				this._x = 0.25 * s;
				this._y = ( m12 + m21 ) / s;
				this._z = ( m13 + m31 ) / s;

			} else if ( m22 > m33 ) {

				s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );

				this._w = ( m13 - m31 ) / s;
				this._x = ( m12 + m21 ) / s;
				this._y = 0.25 * s;
				this._z = ( m23 + m32 ) / s;

			} else {

				s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );

				this._w = ( m21 - m12 ) / s;
				this._x = ( m13 + m31 ) / s;
				this._y = ( m23 + m32 ) / s;
				this._z = 0.25 * s;

			}

			this._onChangeCallback();

			return this;

		},

		setFromUnitVectors: function ( vFrom, vTo ) {

			// assumes direction vectors vFrom and vTo are normalized

			var EPS = 0.000001;

			var r = vFrom.dot( vTo ) + 1;

			if ( r < EPS ) {

				r = 0;

				if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {

					this._x = - vFrom.y;
					this._y = vFrom.x;
					this._z = 0;
					this._w = r;

				} else {

					this._x = 0;
					this._y = - vFrom.z;
					this._z = vFrom.y;
					this._w = r;

				}

			} else {

				// crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3

				this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
				this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
				this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
				this._w = r;

			}

			return this.normalize();

		},

		angleTo: function ( q ) {

			return 2 * Math.acos( Math.abs( MathUtils.clamp( this.dot( q ), - 1, 1 ) ) );

		},

		rotateTowards: function ( q, step ) {

			var angle = this.angleTo( q );

			if ( angle === 0 ) { return this; }

			var t = Math.min( 1, step / angle );

			this.slerp( q, t );

			return this;

		},

		inverse: function () {

			// quaternion is assumed to have unit length

			return this.conjugate();

		},

		conjugate: function () {

			this._x *= - 1;
			this._y *= - 1;
			this._z *= - 1;

			this._onChangeCallback();

			return this;

		},

		dot: function ( v ) {

			return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;

		},

		lengthSq: function () {

			return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;

		},

		length: function () {

			return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );

		},

		normalize: function () {

			var l = this.length();

			if ( l === 0 ) {

				this._x = 0;
				this._y = 0;
				this._z = 0;
				this._w = 1;

			} else {

				l = 1 / l;

				this._x = this._x * l;
				this._y = this._y * l;
				this._z = this._z * l;
				this._w = this._w * l;

			}

			this._onChangeCallback();

			return this;

		},

		multiply: function ( q, p ) {

			if ( p !== undefined ) {

				console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
				return this.multiplyQuaternions( q, p );

			}

			return this.multiplyQuaternions( this, q );

		},

		premultiply: function ( q ) {

			return this.multiplyQuaternions( q, this );

		},

		multiplyQuaternions: function ( a, b ) {

			// from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm

			var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
			var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;

			this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
			this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
			this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
			this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;

			this._onChangeCallback();

			return this;

		},

		slerp: function ( qb, t ) {

			if ( t === 0 ) { return this; }
			if ( t === 1 ) { return this.copy( qb ); }

			var x = this._x, y = this._y, z = this._z, w = this._w;

			// http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/

			var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;

			if ( cosHalfTheta < 0 ) {

				this._w = - qb._w;
				this._x = - qb._x;
				this._y = - qb._y;
				this._z = - qb._z;

				cosHalfTheta = - cosHalfTheta;

			} else {

				this.copy( qb );

			}

			if ( cosHalfTheta >= 1.0 ) {

				this._w = w;
				this._x = x;
				this._y = y;
				this._z = z;

				return this;

			}

			var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;

			if ( sqrSinHalfTheta <= Number.EPSILON ) {

				var s = 1 - t;
				this._w = s * w + t * this._w;
				this._x = s * x + t * this._x;
				this._y = s * y + t * this._y;
				this._z = s * z + t * this._z;

				this.normalize();
				this._onChangeCallback();

				return this;

			}

			var sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
			var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
			var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
				ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;

			this._w = ( w * ratioA + this._w * ratioB );
			this._x = ( x * ratioA + this._x * ratioB );
			this._y = ( y * ratioA + this._y * ratioB );
			this._z = ( z * ratioA + this._z * ratioB );

			this._onChangeCallback();

			return this;

		},

		equals: function ( quaternion ) {

			return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );

		},

		fromArray: function ( array, offset ) {

			if ( offset === undefined ) { offset = 0; }

			this._x = array[ offset ];
			this._y = array[ offset + 1 ];
			this._z = array[ offset + 2 ];
			this._w = array[ offset + 3 ];

			this._onChangeCallback();

			return this;

		},

		toArray: function ( array, offset ) {

			if ( array === undefined ) { array = []; }
			if ( offset === undefined ) { offset = 0; }

			array[ offset ] = this._x;
			array[ offset + 1 ] = this._y;
			array[ offset + 2 ] = this._z;
			array[ offset + 3 ] = this._w;

			return array;

		},

		_onChange: function ( callback ) {

			this._onChangeCallback = callback;

			return this;

		},

		_onChangeCallback: function () {}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author kile / http://kile.stravaganza.org/
	 * @author philogb / http://blog.thejit.org/
	 * @author mikael emtinger / http://gomo.se/
	 * @author egraether / http://egraether.com/
	 * @author WestLangley / http://github.com/WestLangley
	 */

	var _vector = new Vector3();
	var _quaternion = new Quaternion();

	function Vector3( x, y, z ) {

		this.x = x || 0;
		this.y = y || 0;
		this.z = z || 0;

	}

	Object.assign( Vector3.prototype, {

		isVector3: true,

		set: function ( x, y, z ) {

			this.x = x;
			this.y = y;
			this.z = z;

			return this;

		},

		setScalar: function ( scalar ) {

			this.x = scalar;
			this.y = scalar;
			this.z = scalar;

			return this;

		},

		setX: function ( x ) {

			this.x = x;

			return this;

		},

		setY: function ( y ) {

			this.y = y;

			return this;

		},

		setZ: function ( z ) {

			this.z = z;

			return this;

		},

		setComponent: function ( index, value ) {

			switch ( index ) {

				case 0: this.x = value; break;
				case 1: this.y = value; break;
				case 2: this.z = value; break;
				default: throw new Error( 'index is out of range: ' + index );

			}

			return this;

		},

		getComponent: function ( index ) {

			switch ( index ) {

				case 0: return this.x;
				case 1: return this.y;
				case 2: return this.z;
				default: throw new Error( 'index is out of range: ' + index );

			}

		},

		clone: function () {

			return new this.constructor( this.x, this.y, this.z );

		},

		copy: function ( v ) {

			this.x = v.x;
			this.y = v.y;
			this.z = v.z;

			return this;

		},

		add: function ( v, w ) {

			if ( w !== undefined ) {

				console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
				return this.addVectors( v, w );

			}

			this.x += v.x;
			this.y += v.y;
			this.z += v.z;

			return this;

		},

		addScalar: function ( s ) {

			this.x += s;
			this.y += s;
			this.z += s;

			return this;

		},

		addVectors: function ( a, b ) {

			this.x = a.x + b.x;
			this.y = a.y + b.y;
			this.z = a.z + b.z;

			return this;

		},

		addScaledVector: function ( v, s ) {

			this.x += v.x * s;
			this.y += v.y * s;
			this.z += v.z * s;

			return this;

		},

		sub: function ( v, w ) {

			if ( w !== undefined ) {

				console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
				return this.subVectors( v, w );

			}

			this.x -= v.x;
			this.y -= v.y;
			this.z -= v.z;

			return this;

		},

		subScalar: function ( s ) {

			this.x -= s;
			this.y -= s;
			this.z -= s;

			return this;

		},

		subVectors: function ( a, b ) {

			this.x = a.x - b.x;
			this.y = a.y - b.y;
			this.z = a.z - b.z;

			return this;

		},

		multiply: function ( v, w ) {

			if ( w !== undefined ) {

				console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
				return this.multiplyVectors( v, w );

			}

			this.x *= v.x;
			this.y *= v.y;
			this.z *= v.z;

			return this;

		},

		multiplyScalar: function ( scalar ) {

			this.x *= scalar;
			this.y *= scalar;
			this.z *= scalar;

			return this;

		},

		multiplyVectors: function ( a, b ) {

			this.x = a.x * b.x;
			this.y = a.y * b.y;
			this.z = a.z * b.z;

			return this;

		},

		applyEuler: function ( euler ) {

			if ( ! ( euler && euler.isEuler ) ) {

				console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );

			}

			return this.applyQuaternion( _quaternion.setFromEuler( euler ) );

		},

		applyAxisAngle: function ( axis, angle ) {

			return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) );

		},

		applyMatrix3: function ( m ) {

			var x = this.x, y = this.y, z = this.z;
			var e = m.elements;

			this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
			this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
			this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;

			return this;

		},

		applyNormalMatrix: function ( m ) {

			return this.applyMatrix3( m ).normalize();

		},

		applyMatrix4: function ( m ) {

			var x = this.x, y = this.y, z = this.z;
			var e = m.elements;

			var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );

			this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
			this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
			this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;

			return this;

		},

		applyQuaternion: function ( q ) {

			var x = this.x, y = this.y, z = this.z;
			var qx = q.x, qy = q.y, qz = q.z, qw = q.w;

			// calculate quat * vector

			var ix = qw * x + qy * z - qz * y;
			var iy = qw * y + qz * x - qx * z;
			var iz = qw * z + qx * y - qy * x;
			var iw = - qx * x - qy * y - qz * z;

			// calculate result * inverse quat

			this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
			this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
			this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;

			return this;

		},

		project: function ( camera ) {

			return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );

		},

		unproject: function ( camera ) {

			return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );

		},

		transformDirection: function ( m ) {

			// input: THREE.Matrix4 affine matrix
			// vector interpreted as a direction

			var x = this.x, y = this.y, z = this.z;
			var e = m.elements;

			this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
			this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
			this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;

			return this.normalize();

		},

		divide: function ( v ) {

			this.x /= v.x;
			this.y /= v.y;
			this.z /= v.z;

			return this;

		},

		divideScalar: function ( scalar ) {

			return this.multiplyScalar( 1 / scalar );

		},

		min: function ( v ) {

			this.x = Math.min( this.x, v.x );
			this.y = Math.min( this.y, v.y );
			this.z = Math.min( this.z, v.z );

			return this;

		},

		max: function ( v ) {

			this.x = Math.max( this.x, v.x );
			this.y = Math.max( this.y, v.y );
			this.z = Math.max( this.z, v.z );

			return this;

		},

		clamp: function ( min, max ) {

			// assumes min < max, componentwise

			this.x = Math.max( min.x, Math.min( max.x, this.x ) );
			this.y = Math.max( min.y, Math.min( max.y, this.y ) );
			this.z = Math.max( min.z, Math.min( max.z, this.z ) );

			return this;

		},

		clampScalar: function ( minVal, maxVal ) {

			this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
			this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
			this.z = Math.max( minVal, Math.min( maxVal, this.z ) );

			return this;

		},

		clampLength: function ( min, max ) {

			var length = this.length();

			return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );

		},

		floor: function () {

			this.x = Math.floor( this.x );
			this.y = Math.floor( this.y );
			this.z = Math.floor( this.z );

			return this;

		},

		ceil: function () {

			this.x = Math.ceil( this.x );
			this.y = Math.ceil( this.y );
			this.z = Math.ceil( this.z );

			return this;

		},

		round: function () {

			this.x = Math.round( this.x );
			this.y = Math.round( this.y );
			this.z = Math.round( this.z );

			return this;

		},

		roundToZero: function () {

			this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
			this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
			this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );

			return this;

		},

		negate: function () {

			this.x = - this.x;
			this.y = - this.y;
			this.z = - this.z;

			return this;

		},

		dot: function ( v ) {

			return this.x * v.x + this.y * v.y + this.z * v.z;

		},

		// TODO lengthSquared?

		lengthSq: function () {

			return this.x * this.x + this.y * this.y + this.z * this.z;

		},

		length: function () {

			return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );

		},

		manhattanLength: function () {

			return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );

		},

		normalize: function () {

			return this.divideScalar( this.length() || 1 );

		},

		setLength: function ( length ) {

			return this.normalize().multiplyScalar( length );

		},

		lerp: function ( v, alpha ) {

			this.x += ( v.x - this.x ) * alpha;
			this.y += ( v.y - this.y ) * alpha;
			this.z += ( v.z - this.z ) * alpha;

			return this;

		},

		lerpVectors: function ( v1, v2, alpha ) {

			return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );

		},

		cross: function ( v, w ) {

			if ( w !== undefined ) {

				console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
				return this.crossVectors( v, w );

			}

			return this.crossVectors( this, v );

		},

		crossVectors: function ( a, b ) {

			var ax = a.x, ay = a.y, az = a.z;
			var bx = b.x, by = b.y, bz = b.z;

			this.x = ay * bz - az * by;
			this.y = az * bx - ax * bz;
			this.z = ax * by - ay * bx;

			return this;

		},

		projectOnVector: function ( v ) {

			var denominator = v.lengthSq();

			if ( denominator === 0 ) { return this.set( 0, 0, 0 ); }

			var scalar = v.dot( this ) / denominator;

			return this.copy( v ).multiplyScalar( scalar );

		},

		projectOnPlane: function ( planeNormal ) {

			_vector.copy( this ).projectOnVector( planeNormal );

			return this.sub( _vector );

		},

		reflect: function ( normal ) {

			// reflect incident vector off plane orthogonal to normal
			// normal is assumed to have unit length

			return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );

		},

		angleTo: function ( v ) {

			var denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );

			if ( denominator === 0 ) { return Math.PI / 2; }

			var theta = this.dot( v ) / denominator;

			// clamp, to handle numerical problems

			return Math.acos( MathUtils.clamp( theta, - 1, 1 ) );

		},

		distanceTo: function ( v ) {

			return Math.sqrt( this.distanceToSquared( v ) );

		},

		distanceToSquared: function ( v ) {

			var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;

			return dx * dx + dy * dy + dz * dz;

		},

		manhattanDistanceTo: function ( v ) {

			return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );

		},

		setFromSpherical: function ( s ) {

			return this.setFromSphericalCoords( s.radius, s.phi, s.theta );

		},

		setFromSphericalCoords: function ( radius, phi, theta ) {

			var sinPhiRadius = Math.sin( phi ) * radius;

			this.x = sinPhiRadius * Math.sin( theta );
			this.y = Math.cos( phi ) * radius;
			this.z = sinPhiRadius * Math.cos( theta );

			return this;

		},

		setFromCylindrical: function ( c ) {

			return this.setFromCylindricalCoords( c.radius, c.theta, c.y );

		},

		setFromCylindricalCoords: function ( radius, theta, y ) {

			this.x = radius * Math.sin( theta );
			this.y = y;
			this.z = radius * Math.cos( theta );

			return this;

		},

		setFromMatrixPosition: function ( m ) {

			var e = m.elements;

			this.x = e[ 12 ];
			this.y = e[ 13 ];
			this.z = e[ 14 ];

			return this;

		},

		setFromMatrixScale: function ( m ) {

			var sx = this.setFromMatrixColumn( m, 0 ).length();
			var sy = this.setFromMatrixColumn( m, 1 ).length();
			var sz = this.setFromMatrixColumn( m, 2 ).length();

			this.x = sx;
			this.y = sy;
			this.z = sz;

			return this;

		},

		setFromMatrixColumn: function ( m, index ) {

			return this.fromArray( m.elements, index * 4 );

		},

		setFromMatrix3Column: function ( m, index ) {

			return this.fromArray( m.elements, index * 3 );

		},

		equals: function ( v ) {

			return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );

		},

		fromArray: function ( array, offset ) {

			if ( offset === undefined ) { offset = 0; }

			this.x = array[ offset ];
			this.y = array[ offset + 1 ];
			this.z = array[ offset + 2 ];

			return this;

		},

		toArray: function ( array, offset ) {

			if ( array === undefined ) { array = []; }
			if ( offset === undefined ) { offset = 0; }

			array[ offset ] = this.x;
			array[ offset + 1 ] = this.y;
			array[ offset + 2 ] = this.z;

			return array;

		},

		fromBufferAttribute: function ( attribute, index, offset ) {

			if ( offset !== undefined ) {

				console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );

			}

			this.x = attribute.getX( index );
			this.y = attribute.getY( index );
			this.z = attribute.getZ( index );

			return this;

		}

	} );

	var _v1 = new Vector3();
	var _m1 = new Matrix4();
	var _zero = new Vector3( 0, 0, 0 );
	var _one = new Vector3( 1, 1, 1 );
	var _x = new Vector3();
	var _y = new Vector3();
	var _z = new Vector3();

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author supereggbert / http://www.paulbrunt.co.uk/
	 * @author philogb / http://blog.thejit.org/
	 * @author jordi_ros / http://plattsoft.com
	 * @author D1plo1d / http://github.com/D1plo1d
	 * @author alteredq / http://alteredqualia.com/
	 * @author mikael emtinger / http://gomo.se/
	 * @author timknip / http://www.floorplanner.com/
	 * @author bhouston / http://clara.io
	 * @author WestLangley / http://github.com/WestLangley
	 */

	function Matrix4() {

		this.elements = [

			1, 0, 0, 0,
			0, 1, 0, 0,
			0, 0, 1, 0,
			0, 0, 0, 1

		];

		if ( arguments.length > 0 ) {

			console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );

		}

	}

	Object.assign( Matrix4.prototype, {

		isMatrix4: true,

		set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {

			var te = this.elements;

			te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
			te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
			te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
			te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;

			return this;

		},

		identity: function () {

			this.set(

				1, 0, 0, 0,
				0, 1, 0, 0,
				0, 0, 1, 0,
				0, 0, 0, 1

			);

			return this;

		},

		clone: function () {

			return new Matrix4().fromArray( this.elements );

		},

		copy: function ( m ) {

			var te = this.elements;
			var me = m.elements;

			te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
			te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
			te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
			te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];

			return this;

		},

		copyPosition: function ( m ) {

			var te = this.elements, me = m.elements;

			te[ 12 ] = me[ 12 ];
			te[ 13 ] = me[ 13 ];
			te[ 14 ] = me[ 14 ];

			return this;

		},

		extractBasis: function ( xAxis, yAxis, zAxis ) {

			xAxis.setFromMatrixColumn( this, 0 );
			yAxis.setFromMatrixColumn( this, 1 );
			zAxis.setFromMatrixColumn( this, 2 );

			return this;

		},

		makeBasis: function ( xAxis, yAxis, zAxis ) {

			this.set(
				xAxis.x, yAxis.x, zAxis.x, 0,
				xAxis.y, yAxis.y, zAxis.y, 0,
				xAxis.z, yAxis.z, zAxis.z, 0,
				0, 0, 0, 1
			);

			return this;

		},

		extractRotation: function ( m ) {

			// this method does not support reflection matrices

			var te = this.elements;
			var me = m.elements;

			var scaleX = 1 / _v1.setFromMatrixColumn( m, 0 ).length();
			var scaleY = 1 / _v1.setFromMatrixColumn( m, 1 ).length();
			var scaleZ = 1 / _v1.setFromMatrixColumn( m, 2 ).length();

			te[ 0 ] = me[ 0 ] * scaleX;
			te[ 1 ] = me[ 1 ] * scaleX;
			te[ 2 ] = me[ 2 ] * scaleX;
			te[ 3 ] = 0;

			te[ 4 ] = me[ 4 ] * scaleY;
			te[ 5 ] = me[ 5 ] * scaleY;
			te[ 6 ] = me[ 6 ] * scaleY;
			te[ 7 ] = 0;

			te[ 8 ] = me[ 8 ] * scaleZ;
			te[ 9 ] = me[ 9 ] * scaleZ;
			te[ 10 ] = me[ 10 ] * scaleZ;
			te[ 11 ] = 0;

			te[ 12 ] = 0;
			te[ 13 ] = 0;
			te[ 14 ] = 0;
			te[ 15 ] = 1;

			return this;

		},

		makeRotationFromEuler: function ( euler ) {

			if ( ! ( euler && euler.isEuler ) ) {

				console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );

			}

			var te = this.elements;

			var x = euler.x, y = euler.y, z = euler.z;
			var a = Math.cos( x ), b = Math.sin( x );
			var c = Math.cos( y ), d = Math.sin( y );
			var e = Math.cos( z ), f = Math.sin( z );

			if ( euler.order === 'XYZ' ) {

				var ae = a * e, af = a * f, be = b * e, bf = b * f;

				te[ 0 ] = c * e;
				te[ 4 ] = - c * f;
				te[ 8 ] = d;

				te[ 1 ] = af + be * d;
				te[ 5 ] = ae - bf * d;
				te[ 9 ] = - b * c;

				te[ 2 ] = bf - ae * d;
				te[ 6 ] = be + af * d;
				te[ 10 ] = a * c;

			} else if ( euler.order === 'YXZ' ) {

				var ce = c * e, cf = c * f, de = d * e, df = d * f;

				te[ 0 ] = ce + df * b;
				te[ 4 ] = de * b - cf;
				te[ 8 ] = a * d;

				te[ 1 ] = a * f;
				te[ 5 ] = a * e;
				te[ 9 ] = - b;

				te[ 2 ] = cf * b - de;
				te[ 6 ] = df + ce * b;
				te[ 10 ] = a * c;

			} else if ( euler.order === 'ZXY' ) {

				var ce = c * e, cf = c * f, de = d * e, df = d * f;

				te[ 0 ] = ce - df * b;
				te[ 4 ] = - a * f;
				te[ 8 ] = de + cf * b;

				te[ 1 ] = cf + de * b;
				te[ 5 ] = a * e;
				te[ 9 ] = df - ce * b;

				te[ 2 ] = - a * d;
				te[ 6 ] = b;
				te[ 10 ] = a * c;

			} else if ( euler.order === 'ZYX' ) {

				var ae = a * e, af = a * f, be = b * e, bf = b * f;

				te[ 0 ] = c * e;
				te[ 4 ] = be * d - af;
				te[ 8 ] = ae * d + bf;

				te[ 1 ] = c * f;
				te[ 5 ] = bf * d + ae;
				te[ 9 ] = af * d - be;

				te[ 2 ] = - d;
				te[ 6 ] = b * c;
				te[ 10 ] = a * c;

			} else if ( euler.order === 'YZX' ) {

				var ac = a * c, ad = a * d, bc = b * c, bd = b * d;

				te[ 0 ] = c * e;
				te[ 4 ] = bd - ac * f;
				te[ 8 ] = bc * f + ad;

				te[ 1 ] = f;
				te[ 5 ] = a * e;
				te[ 9 ] = - b * e;

				te[ 2 ] = - d * e;
				te[ 6 ] = ad * f + bc;
				te[ 10 ] = ac - bd * f;

			} else if ( euler.order === 'XZY' ) {

				var ac = a * c, ad = a * d, bc = b * c, bd = b * d;

				te[ 0 ] = c * e;
				te[ 4 ] = - f;
				te[ 8 ] = d * e;

				te[ 1 ] = ac * f + bd;
				te[ 5 ] = a * e;
				te[ 9 ] = ad * f - bc;

				te[ 2 ] = bc * f - ad;
				te[ 6 ] = b * e;
				te[ 10 ] = bd * f + ac;

			}

			// bottom row
			te[ 3 ] = 0;
			te[ 7 ] = 0;
			te[ 11 ] = 0;

			// last column
			te[ 12 ] = 0;
			te[ 13 ] = 0;
			te[ 14 ] = 0;
			te[ 15 ] = 1;

			return this;

		},

		makeRotationFromQuaternion: function ( q ) {

			return this.compose( _zero, q, _one );

		},

		lookAt: function ( eye, target, up ) {

			var te = this.elements;

			_z.subVectors( eye, target );

			if ( _z.lengthSq() === 0 ) {

				// eye and target are in the same position

				_z.z = 1;

			}

			_z.normalize();
			_x.crossVectors( up, _z );

			if ( _x.lengthSq() === 0 ) {

				// up and z are parallel

				if ( Math.abs( up.z ) === 1 ) {

					_z.x += 0.0001;

				} else {

					_z.z += 0.0001;

				}

				_z.normalize();
				_x.crossVectors( up, _z );

			}

			_x.normalize();
			_y.crossVectors( _z, _x );

			te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
			te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
			te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;

			return this;

		},

		multiply: function ( m, n ) {

			if ( n !== undefined ) {

				console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
				return this.multiplyMatrices( m, n );

			}

			return this.multiplyMatrices( this, m );

		},

		premultiply: function ( m ) {

			return this.multiplyMatrices( m, this );

		},

		multiplyMatrices: function ( a, b ) {

			var ae = a.elements;
			var be = b.elements;
			var te = this.elements;

			var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
			var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
			var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
			var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];

			var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
			var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
			var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
			var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];

			te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
			te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
			te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
			te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;

			te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
			te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
			te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
			te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;

			te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
			te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
			te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
			te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;

			te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
			te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
			te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
			te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;

			return this;

		},

		multiplyScalar: function ( s ) {

			var te = this.elements;

			te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
			te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
			te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
			te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;

			return this;

		},

		determinant: function () {

			var te = this.elements;

			var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
			var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
			var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
			var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];

			//TODO: make this more efficient
			//( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )

			return (
				n41 * (
					+ n14 * n23 * n32
					 - n13 * n24 * n32
					 - n14 * n22 * n33
					 + n12 * n24 * n33
					 + n13 * n22 * n34
					 - n12 * n23 * n34
				) +
				n42 * (
					+ n11 * n23 * n34
					 - n11 * n24 * n33
					 + n14 * n21 * n33
					 - n13 * n21 * n34
					 + n13 * n24 * n31
					 - n14 * n23 * n31
				) +
				n43 * (
					+ n11 * n24 * n32
					 - n11 * n22 * n34
					 - n14 * n21 * n32
					 + n12 * n21 * n34
					 + n14 * n22 * n31
					 - n12 * n24 * n31
				) +
				n44 * (
					- n13 * n22 * n31
					 - n11 * n23 * n32
					 + n11 * n22 * n33
					 + n13 * n21 * n32
					 - n12 * n21 * n33
					 + n12 * n23 * n31
				)

			);

		},

		transpose: function () {

			var te = this.elements;
			var tmp;

			tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
			tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
			tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;

			tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
			tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
			tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;

			return this;

		},

		setPosition: function ( x, y, z ) {

			var te = this.elements;

			if ( x.isVector3 ) {

				te[ 12 ] = x.x;
				te[ 13 ] = x.y;
				te[ 14 ] = x.z;

			} else {

				te[ 12 ] = x;
				te[ 13 ] = y;
				te[ 14 ] = z;

			}

			return this;

		},

		getInverse: function ( m, throwOnDegenerate ) {

			// based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
			var te = this.elements,
				me = m.elements,

				n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
				n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
				n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
				n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],

				t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
				t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
				t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
				t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;

			var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;

			if ( det === 0 ) {

				var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";

				if ( throwOnDegenerate === true ) {

					throw new Error( msg );

				} else {

					console.warn( msg );

				}

				return this.identity();

			}

			var detInv = 1 / det;

			te[ 0 ] = t11 * detInv;
			te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
			te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
			te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;

			te[ 4 ] = t12 * detInv;
			te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
			te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
			te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;

			te[ 8 ] = t13 * detInv;
			te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
			te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
			te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;

			te[ 12 ] = t14 * detInv;
			te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
			te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
			te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;

			return this;

		},

		scale: function ( v ) {

			var te = this.elements;
			var x = v.x, y = v.y, z = v.z;

			te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
			te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
			te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
			te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;

			return this;

		},

		getMaxScaleOnAxis: function () {

			var te = this.elements;

			var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
			var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
			var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];

			return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );

		},

		makeTranslation: function ( x, y, z ) {

			this.set(

				1, 0, 0, x,
				0, 1, 0, y,
				0, 0, 1, z,
				0, 0, 0, 1

			);

			return this;

		},

		makeRotationX: function ( theta ) {

			var c = Math.cos( theta ), s = Math.sin( theta );

			this.set(

				1, 0, 0, 0,
				0, c, - s, 0,
				0, s, c, 0,
				0, 0, 0, 1

			);

			return this;

		},

		makeRotationY: function ( theta ) {

			var c = Math.cos( theta ), s = Math.sin( theta );

			this.set(

				 c, 0, s, 0,
				 0, 1, 0, 0,
				- s, 0, c, 0,
				 0, 0, 0, 1

			);

			return this;

		},

		makeRotationZ: function ( theta ) {

			var c = Math.cos( theta ), s = Math.sin( theta );

			this.set(

				c, - s, 0, 0,
				s, c, 0, 0,
				0, 0, 1, 0,
				0, 0, 0, 1

			);

			return this;

		},

		makeRotationAxis: function ( axis, angle ) {

			// Based on http://www.gamedev.net/reference/articles/article1199.asp

			var c = Math.cos( angle );
			var s = Math.sin( angle );
			var t = 1 - c;
			var x = axis.x, y = axis.y, z = axis.z;
			var tx = t * x, ty = t * y;

			this.set(

				tx * x + c, tx * y - s * z, tx * z + s * y, 0,
				tx * y + s * z, ty * y + c, ty * z - s * x, 0,
				tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
				0, 0, 0, 1

			);

			 return this;

		},

		makeScale: function ( x, y, z ) {

			this.set(

				x, 0, 0, 0,
				0, y, 0, 0,
				0, 0, z, 0,
				0, 0, 0, 1

			);

			return this;

		},

		makeShear: function ( x, y, z ) {

			this.set(

				1, y, z, 0,
				x, 1, z, 0,
				x, y, 1, 0,
				0, 0, 0, 1

			);

			return this;

		},

		compose: function ( position, quaternion, scale ) {

			var te = this.elements;

			var x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
			var x2 = x + x,	y2 = y + y, z2 = z + z;
			var xx = x * x2, xy = x * y2, xz = x * z2;
			var yy = y * y2, yz = y * z2, zz = z * z2;
			var wx = w * x2, wy = w * y2, wz = w * z2;

			var sx = scale.x, sy = scale.y, sz = scale.z;

			te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
			te[ 1 ] = ( xy + wz ) * sx;
			te[ 2 ] = ( xz - wy ) * sx;
			te[ 3 ] = 0;

			te[ 4 ] = ( xy - wz ) * sy;
			te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
			te[ 6 ] = ( yz + wx ) * sy;
			te[ 7 ] = 0;

			te[ 8 ] = ( xz + wy ) * sz;
			te[ 9 ] = ( yz - wx ) * sz;
			te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
			te[ 11 ] = 0;

			te[ 12 ] = position.x;
			te[ 13 ] = position.y;
			te[ 14 ] = position.z;
			te[ 15 ] = 1;

			return this;

		},

		decompose: function ( position, quaternion, scale ) {

			var te = this.elements;

			var sx = _v1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
			var sy = _v1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
			var sz = _v1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();

			// if determine is negative, we need to invert one scale
			var det = this.determinant();
			if ( det < 0 ) { sx = - sx; }

			position.x = te[ 12 ];
			position.y = te[ 13 ];
			position.z = te[ 14 ];

			// scale the rotation part
			_m1.copy( this );

			var invSX = 1 / sx;
			var invSY = 1 / sy;
			var invSZ = 1 / sz;

			_m1.elements[ 0 ] *= invSX;
			_m1.elements[ 1 ] *= invSX;
			_m1.elements[ 2 ] *= invSX;

			_m1.elements[ 4 ] *= invSY;
			_m1.elements[ 5 ] *= invSY;
			_m1.elements[ 6 ] *= invSY;

			_m1.elements[ 8 ] *= invSZ;
			_m1.elements[ 9 ] *= invSZ;
			_m1.elements[ 10 ] *= invSZ;

			quaternion.setFromRotationMatrix( _m1 );

			scale.x = sx;
			scale.y = sy;
			scale.z = sz;

			return this;

		},

		makePerspective: function ( left, right, top, bottom, near, far ) {

			if ( far === undefined ) {

				console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );

			}

			var te = this.elements;
			var x = 2 * near / ( right - left );
			var y = 2 * near / ( top - bottom );

			var a = ( right + left ) / ( right - left );
			var b = ( top + bottom ) / ( top - bottom );
			var c = - ( far + near ) / ( far - near );
			var d = - 2 * far * near / ( far - near );

			te[ 0 ] = x;	te[ 4 ] = 0;	te[ 8 ] = a;	te[ 12 ] = 0;
			te[ 1 ] = 0;	te[ 5 ] = y;	te[ 9 ] = b;	te[ 13 ] = 0;
			te[ 2 ] = 0;	te[ 6 ] = 0;	te[ 10 ] = c;	te[ 14 ] = d;
			te[ 3 ] = 0;	te[ 7 ] = 0;	te[ 11 ] = - 1;	te[ 15 ] = 0;

			return this;

		},

		makeOrthographic: function ( left, right, top, bottom, near, far ) {

			var te = this.elements;
			var w = 1.0 / ( right - left );
			var h = 1.0 / ( top - bottom );
			var p = 1.0 / ( far - near );

			var x = ( right + left ) * w;
			var y = ( top + bottom ) * h;
			var z = ( far + near ) * p;

			te[ 0 ] = 2 * w;	te[ 4 ] = 0;	te[ 8 ] = 0;	te[ 12 ] = - x;
			te[ 1 ] = 0;	te[ 5 ] = 2 * h;	te[ 9 ] = 0;	te[ 13 ] = - y;
			te[ 2 ] = 0;	te[ 6 ] = 0;	te[ 10 ] = - 2 * p;	te[ 14 ] = - z;
			te[ 3 ] = 0;	te[ 7 ] = 0;	te[ 11 ] = 0;	te[ 15 ] = 1;

			return this;

		},

		equals: function ( matrix ) {

			var te = this.elements;
			var me = matrix.elements;

			for ( var i = 0; i < 16; i ++ ) {

				if ( te[ i ] !== me[ i ] ) { return false; }

			}

			return true;

		},

		fromArray: function ( array, offset ) {

			if ( offset === undefined ) { offset = 0; }

			for ( var i = 0; i < 16; i ++ ) {

				this.elements[ i ] = array[ i + offset ];

			}

			return this;

		},

		toArray: function ( array, offset ) {

			if ( array === undefined ) { array = []; }
			if ( offset === undefined ) { offset = 0; }

			var te = this.elements;

			array[ offset ] = te[ 0 ];
			array[ offset + 1 ] = te[ 1 ];
			array[ offset + 2 ] = te[ 2 ];
			array[ offset + 3 ] = te[ 3 ];

			array[ offset + 4 ] = te[ 4 ];
			array[ offset + 5 ] = te[ 5 ];
			array[ offset + 6 ] = te[ 6 ];
			array[ offset + 7 ] = te[ 7 ];

			array[ offset + 8 ] = te[ 8 ];
			array[ offset + 9 ] = te[ 9 ];
			array[ offset + 10 ] = te[ 10 ];
			array[ offset + 11 ] = te[ 11 ];

			array[ offset + 12 ] = te[ 12 ];
			array[ offset + 13 ] = te[ 13 ];
			array[ offset + 14 ] = te[ 14 ];
			array[ offset + 15 ] = te[ 15 ];

			return array;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author WestLangley / http://github.com/WestLangley
	 * @author bhouston / http://clara.io
	 */

	var _matrix = new Matrix4();
	var _quaternion$1 = new Quaternion();

	function Euler( x, y, z, order ) {

		this._x = x || 0;
		this._y = y || 0;
		this._z = z || 0;
		this._order = order || Euler.DefaultOrder;

	}

	Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];

	Euler.DefaultOrder = 'XYZ';

	Object.defineProperties( Euler.prototype, {

		x: {

			get: function () {

				return this._x;

			},

			set: function ( value ) {

				this._x = value;
				this._onChangeCallback();

			}

		},

		y: {

			get: function () {

				return this._y;

			},

			set: function ( value ) {

				this._y = value;
				this._onChangeCallback();

			}

		},

		z: {

			get: function () {

				return this._z;

			},

			set: function ( value ) {

				this._z = value;
				this._onChangeCallback();

			}

		},

		order: {

			get: function () {

				return this._order;

			},

			set: function ( value ) {

				this._order = value;
				this._onChangeCallback();

			}

		}

	} );

	Object.assign( Euler.prototype, {

		isEuler: true,

		set: function ( x, y, z, order ) {

			this._x = x;
			this._y = y;
			this._z = z;
			this._order = order || this._order;

			this._onChangeCallback();

			return this;

		},

		clone: function () {

			return new this.constructor( this._x, this._y, this._z, this._order );

		},

		copy: function ( euler ) {

			this._x = euler._x;
			this._y = euler._y;
			this._z = euler._z;
			this._order = euler._order;

			this._onChangeCallback();

			return this;

		},

		setFromRotationMatrix: function ( m, order, update ) {

			var clamp = MathUtils.clamp;

			// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)

			var te = m.elements;
			var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
			var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
			var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];

			order = order || this._order;

			if ( order === 'XYZ' ) {

				this._y = Math.asin( clamp( m13, - 1, 1 ) );

				if ( Math.abs( m13 ) < 0.9999999 ) {

					this._x = Math.atan2( - m23, m33 );
					this._z = Math.atan2( - m12, m11 );

				} else {

					this._x = Math.atan2( m32, m22 );
					this._z = 0;

				}

			} else if ( order === 'YXZ' ) {

				this._x = Math.asin( - clamp( m23, - 1, 1 ) );

				if ( Math.abs( m23 ) < 0.9999999 ) {

					this._y = Math.atan2( m13, m33 );
					this._z = Math.atan2( m21, m22 );

				} else {

					this._y = Math.atan2( - m31, m11 );
					this._z = 0;

				}

			} else if ( order === 'ZXY' ) {

				this._x = Math.asin( clamp( m32, - 1, 1 ) );

				if ( Math.abs( m32 ) < 0.9999999 ) {

					this._y = Math.atan2( - m31, m33 );
					this._z = Math.atan2( - m12, m22 );

				} else {

					this._y = 0;
					this._z = Math.atan2( m21, m11 );

				}

			} else if ( order === 'ZYX' ) {

				this._y = Math.asin( - clamp( m31, - 1, 1 ) );

				if ( Math.abs( m31 ) < 0.9999999 ) {

					this._x = Math.atan2( m32, m33 );
					this._z = Math.atan2( m21, m11 );

				} else {

					this._x = 0;
					this._z = Math.atan2( - m12, m22 );

				}

			} else if ( order === 'YZX' ) {

				this._z = Math.asin( clamp( m21, - 1, 1 ) );

				if ( Math.abs( m21 ) < 0.9999999 ) {

					this._x = Math.atan2( - m23, m22 );
					this._y = Math.atan2( - m31, m11 );

				} else {

					this._x = 0;
					this._y = Math.atan2( m13, m33 );

				}

			} else if ( order === 'XZY' ) {

				this._z = Math.asin( - clamp( m12, - 1, 1 ) );

				if ( Math.abs( m12 ) < 0.9999999 ) {

					this._x = Math.atan2( m32, m22 );
					this._y = Math.atan2( m13, m11 );

				} else {

					this._x = Math.atan2( - m23, m33 );
					this._y = 0;

				}

			} else {

				console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );

			}

			this._order = order;

			if ( update !== false ) { this._onChangeCallback(); }

			return this;

		},

		setFromQuaternion: function ( q, order, update ) {

			_matrix.makeRotationFromQuaternion( q );

			return this.setFromRotationMatrix( _matrix, order, update );

		},

		setFromVector3: function ( v, order ) {

			return this.set( v.x, v.y, v.z, order || this._order );

		},

		reorder: function ( newOrder ) {

			// WARNING: this discards revolution information -bhouston

			_quaternion$1.setFromEuler( this );

			return this.setFromQuaternion( _quaternion$1, newOrder );

		},

		equals: function ( euler ) {

			return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );

		},

		fromArray: function ( array ) {

			this._x = array[ 0 ];
			this._y = array[ 1 ];
			this._z = array[ 2 ];
			if ( array[ 3 ] !== undefined ) { this._order = array[ 3 ]; }

			this._onChangeCallback();

			return this;

		},

		toArray: function ( array, offset ) {

			if ( array === undefined ) { array = []; }
			if ( offset === undefined ) { offset = 0; }

			array[ offset ] = this._x;
			array[ offset + 1 ] = this._y;
			array[ offset + 2 ] = this._z;
			array[ offset + 3 ] = this._order;

			return array;

		},

		toVector3: function ( optionalResult ) {

			if ( optionalResult ) {

				return optionalResult.set( this._x, this._y, this._z );

			} else {

				return new Vector3( this._x, this._y, this._z );

			}

		},

		_onChange: function ( callback ) {

			this._onChangeCallback = callback;

			return this;

		},

		_onChangeCallback: function () {}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function Layers() {

		this.mask = 1 | 0;

	}

	Object.assign( Layers.prototype, {

		set: function ( channel ) {

			this.mask = 1 << channel | 0;

		},

		enable: function ( channel ) {

			this.mask |= 1 << channel | 0;

		},

		enableAll: function () {

			this.mask = 0xffffffff | 0;

		},

		toggle: function ( channel ) {

			this.mask ^= 1 << channel | 0;

		},

		disable: function ( channel ) {

			this.mask &= ~ ( 1 << channel | 0 );

		},

		disableAll: function () {

			this.mask = 0;

		},

		test: function ( layers ) {

			return ( this.mask & layers.mask ) !== 0;

		}

	} );

	var _object3DId = 0;

	var _v1$1 = new Vector3();
	var _q1 = new Quaternion();
	var _m1$1 = new Matrix4();
	var _target = new Vector3();

	var _position = new Vector3();
	var _scale = new Vector3();
	var _quaternion$2 = new Quaternion();

	var _xAxis = new Vector3( 1, 0, 0 );
	var _yAxis = new Vector3( 0, 1, 0 );
	var _zAxis = new Vector3( 0, 0, 1 );

	var _addedEvent = { type: 'added' };
	var _removedEvent = { type: 'removed' };

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author mikael emtinger / http://gomo.se/
	 * @author alteredq / http://alteredqualia.com/
	 * @author WestLangley / http://github.com/WestLangley
	 * @author elephantatwork / www.elephantatwork.ch
	 */

	function Object3D() {

		Object.defineProperty( this, 'id', { value: _object3DId ++ } );

		this.uuid = MathUtils.generateUUID();

		this.name = '';
		this.type = 'Object3D';

		this.parent = null;
		this.children = [];

		this.up = Object3D.DefaultUp.clone();

		var position = new Vector3();
		var rotation = new Euler();
		var quaternion = new Quaternion();
		var scale = new Vector3( 1, 1, 1 );

		function onRotationChange() {

			quaternion.setFromEuler( rotation, false );

		}

		function onQuaternionChange() {

			rotation.setFromQuaternion( quaternion, undefined, false );

		}

		rotation._onChange( onRotationChange );
		quaternion._onChange( onQuaternionChange );

		Object.defineProperties( this, {
			position: {
				configurable: true,
				enumerable: true,
				value: position
			},
			rotation: {
				configurable: true,
				enumerable: true,
				value: rotation
			},
			quaternion: {
				configurable: true,
				enumerable: true,
				value: quaternion
			},
			scale: {
				configurable: true,
				enumerable: true,
				value: scale
			},
			modelViewMatrix: {
				value: new Matrix4()
			},
			normalMatrix: {
				value: new Matrix3()
			}
		} );

		this.matrix = new Matrix4();
		this.matrixWorld = new Matrix4();

		this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
		this.matrixWorldNeedsUpdate = false;

		this.layers = new Layers();
		this.visible = true;

		this.castShadow = false;
		this.receiveShadow = false;

		this.frustumCulled = true;
		this.renderOrder = 0;

		this.userData = {};

	}

	Object3D.DefaultUp = new Vector3( 0, 1, 0 );
	Object3D.DefaultMatrixAutoUpdate = true;

	Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {

		constructor: Object3D,

		isObject3D: true,

		onBeforeRender: function () {},
		onAfterRender: function () {},

		applyMatrix4: function ( matrix ) {

			if ( this.matrixAutoUpdate ) { this.updateMatrix(); }

			this.matrix.premultiply( matrix );

			this.matrix.decompose( this.position, this.quaternion, this.scale );

		},

		applyQuaternion: function ( q ) {

			this.quaternion.premultiply( q );

			return this;

		},

		setRotationFromAxisAngle: function ( axis, angle ) {

			// assumes axis is normalized

			this.quaternion.setFromAxisAngle( axis, angle );

		},

		setRotationFromEuler: function ( euler ) {

			this.quaternion.setFromEuler( euler, true );

		},

		setRotationFromMatrix: function ( m ) {

			// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)

			this.quaternion.setFromRotationMatrix( m );

		},

		setRotationFromQuaternion: function ( q ) {

			// assumes q is normalized

			this.quaternion.copy( q );

		},

		rotateOnAxis: function ( axis, angle ) {

			// rotate object on axis in object space
			// axis is assumed to be normalized

			_q1.setFromAxisAngle( axis, angle );

			this.quaternion.multiply( _q1 );

			return this;

		},

		rotateOnWorldAxis: function ( axis, angle ) {

			// rotate object on axis in world space
			// axis is assumed to be normalized
			// method assumes no rotated parent

			_q1.setFromAxisAngle( axis, angle );

			this.quaternion.premultiply( _q1 );

			return this;

		},

		rotateX: function ( angle ) {

			return this.rotateOnAxis( _xAxis, angle );

		},

		rotateY: function ( angle ) {

			return this.rotateOnAxis( _yAxis, angle );

		},

		rotateZ: function ( angle ) {

			return this.rotateOnAxis( _zAxis, angle );

		},

		translateOnAxis: function ( axis, distance ) {

			// translate object by distance along axis in object space
			// axis is assumed to be normalized

			_v1$1.copy( axis ).applyQuaternion( this.quaternion );

			this.position.add( _v1$1.multiplyScalar( distance ) );

			return this;

		},

		translateX: function ( distance ) {

			return this.translateOnAxis( _xAxis, distance );

		},

		translateY: function ( distance ) {

			return this.translateOnAxis( _yAxis, distance );

		},

		translateZ: function ( distance ) {

			return this.translateOnAxis( _zAxis, distance );

		},

		localToWorld: function ( vector ) {

			return vector.applyMatrix4( this.matrixWorld );

		},

		worldToLocal: function ( vector ) {

			return vector.applyMatrix4( _m1$1.getInverse( this.matrixWorld ) );

		},

		lookAt: function ( x, y, z ) {

			// This method does not support objects having non-uniformly-scaled parent(s)

			if ( x.isVector3 ) {

				_target.copy( x );

			} else {

				_target.set( x, y, z );

			}

			var parent = this.parent;

			this.updateWorldMatrix( true, false );

			_position.setFromMatrixPosition( this.matrixWorld );

			if ( this.isCamera || this.isLight ) {

				_m1$1.lookAt( _position, _target, this.up );

			} else {

				_m1$1.lookAt( _target, _position, this.up );

			}

			this.quaternion.setFromRotationMatrix( _m1$1 );

			if ( parent ) {

				_m1$1.extractRotation( parent.matrixWorld );
				_q1.setFromRotationMatrix( _m1$1 );
				this.quaternion.premultiply( _q1.inverse() );

			}

		},

		add: function ( object ) {

			if ( arguments.length > 1 ) {

				for ( var i = 0; i < arguments.length; i ++ ) {

					this.add( arguments[ i ] );

				}

				return this;

			}

			if ( object === this ) {

				console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
				return this;

			}

			if ( ( object && object.isObject3D ) ) {

				if ( object.parent !== null ) {

					object.parent.remove( object );

				}

				object.parent = this;
				this.children.push( object );

				object.dispatchEvent( _addedEvent );

			} else {

				console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );

			}

			return this;

		},

		remove: function ( object ) {

			if ( arguments.length > 1 ) {

				for ( var i = 0; i < arguments.length; i ++ ) {

					this.remove( arguments[ i ] );

				}

				return this;

			}

			var index = this.children.indexOf( object );

			if ( index !== - 1 ) {

				object.parent = null;
				this.children.splice( index, 1 );

				object.dispatchEvent( _removedEvent );

			}

			return this;

		},

		attach: function ( object ) {

			// adds object as a child of this, while maintaining the object's world transform

			this.updateWorldMatrix( true, false );

			_m1$1.getInverse( this.matrixWorld );

			if ( object.parent !== null ) {

				object.parent.updateWorldMatrix( true, false );

				_m1$1.multiply( object.parent.matrixWorld );

			}

			object.applyMatrix4( _m1$1 );

			object.updateWorldMatrix( false, false );

			this.add( object );

			return this;

		},

		getObjectById: function ( id ) {

			return this.getObjectByProperty( 'id', id );

		},

		getObjectByName: function ( name ) {

			return this.getObjectByProperty( 'name', name );

		},

		getObjectByProperty: function ( name, value ) {

			if ( this[ name ] === value ) { return this; }

			for ( var i = 0, l = this.children.length; i < l; i ++ ) {

				var child = this.children[ i ];
				var object = child.getObjectByProperty( name, value );

				if ( object !== undefined ) {

					return object;

				}

			}

			return undefined;

		},

		getWorldPosition: function ( target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
				target = new Vector3();

			}

			this.updateMatrixWorld( true );

			return target.setFromMatrixPosition( this.matrixWorld );

		},

		getWorldQuaternion: function ( target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
				target = new Quaternion();

			}

			this.updateMatrixWorld( true );

			this.matrixWorld.decompose( _position, target, _scale );

			return target;

		},

		getWorldScale: function ( target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
				target = new Vector3();

			}

			this.updateMatrixWorld( true );

			this.matrixWorld.decompose( _position, _quaternion$2, target );

			return target;

		},

		getWorldDirection: function ( target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
				target = new Vector3();

			}

			this.updateMatrixWorld( true );

			var e = this.matrixWorld.elements;

			return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();

		},

		raycast: function () {},

		traverse: function ( callback ) {

			callback( this );

			var children = this.children;

			for ( var i = 0, l = children.length; i < l; i ++ ) {

				children[ i ].traverse( callback );

			}

		},

		traverseVisible: function ( callback ) {

			if ( this.visible === false ) { return; }

			callback( this );

			var children = this.children;

			for ( var i = 0, l = children.length; i < l; i ++ ) {

				children[ i ].traverseVisible( callback );

			}

		},

		traverseAncestors: function ( callback ) {

			var parent = this.parent;

			if ( parent !== null ) {

				callback( parent );

				parent.traverseAncestors( callback );

			}

		},

		updateMatrix: function () {

			this.matrix.compose( this.position, this.quaternion, this.scale );

			this.matrixWorldNeedsUpdate = true;

		},

		updateMatrixWorld: function ( force ) {

			if ( this.matrixAutoUpdate ) { this.updateMatrix(); }

			if ( this.matrixWorldNeedsUpdate || force ) {

				if ( this.parent === null ) {

					this.matrixWorld.copy( this.matrix );

				} else {

					this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );

				}

				this.matrixWorldNeedsUpdate = false;

				force = true;

			}

			// update children

			var children = this.children;

			for ( var i = 0, l = children.length; i < l; i ++ ) {

				children[ i ].updateMatrixWorld( force );

			}

		},

		updateWorldMatrix: function ( updateParents, updateChildren ) {

			var parent = this.parent;

			if ( updateParents === true && parent !== null ) {

				parent.updateWorldMatrix( true, false );

			}

			if ( this.matrixAutoUpdate ) { this.updateMatrix(); }

			if ( this.parent === null ) {

				this.matrixWorld.copy( this.matrix );

			} else {

				this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );

			}

			// update children

			if ( updateChildren === true ) {

				var children = this.children;

				for ( var i = 0, l = children.length; i < l; i ++ ) {

					children[ i ].updateWorldMatrix( false, true );

				}

			}

		},

		toJSON: function ( meta ) {

			// meta is a string when called from JSON.stringify
			var isRootObject = ( meta === undefined || typeof meta === 'string' );

			var output = {};

			// meta is a hash used to collect geometries, materials.
			// not providing it implies that this is the root object
			// being serialized.
			if ( isRootObject ) {

				// initialize meta obj
				meta = {
					geometries: {},
					materials: {},
					textures: {},
					images: {},
					shapes: {}
				};

				output.metadata = {
					version: 4.5,
					type: 'Object',
					generator: 'Object3D.toJSON'
				};

			}

			// standard Object3D serialization

			var object = {};

			object.uuid = this.uuid;
			object.type = this.type;

			if ( this.name !== '' ) { object.name = this.name; }
			if ( this.castShadow === true ) { object.castShadow = true; }
			if ( this.receiveShadow === true ) { object.receiveShadow = true; }
			if ( this.visible === false ) { object.visible = false; }
			if ( this.frustumCulled === false ) { object.frustumCulled = false; }
			if ( this.renderOrder !== 0 ) { object.renderOrder = this.renderOrder; }
			if ( JSON.stringify( this.userData ) !== '{}' ) { object.userData = this.userData; }

			object.layers = this.layers.mask;
			object.matrix = this.matrix.toArray();

			if ( this.matrixAutoUpdate === false ) { object.matrixAutoUpdate = false; }

			// object specific properties

			if ( this.isInstancedMesh ) {

				object.type = 'InstancedMesh';
				object.count = this.count;
				object.instanceMatrix = this.instanceMatrix.toJSON();

			}

			//

			function serialize( library, element ) {

				if ( library[ element.uuid ] === undefined ) {

					library[ element.uuid ] = element.toJSON( meta );

				}

				return element.uuid;

			}

			if ( this.isMesh || this.isLine || this.isPoints ) {

				object.geometry = serialize( meta.geometries, this.geometry );

				var parameters = this.geometry.parameters;

				if ( parameters !== undefined && parameters.shapes !== undefined ) {

					var shapes = parameters.shapes;

					if ( Array.isArray( shapes ) ) {

						for ( var i = 0, l = shapes.length; i < l; i ++ ) {

							var shape = shapes[ i ];

							serialize( meta.shapes, shape );

						}

					} else {

						serialize( meta.shapes, shapes );

					}

				}

			}

			if ( this.material !== undefined ) {

				if ( Array.isArray( this.material ) ) {

					var uuids = [];

					for ( var i = 0, l = this.material.length; i < l; i ++ ) {

						uuids.push( serialize( meta.materials, this.material[ i ] ) );

					}

					object.material = uuids;

				} else {

					object.material = serialize( meta.materials, this.material );

				}

			}

			//

			if ( this.children.length > 0 ) {

				object.children = [];

				for ( var i = 0; i < this.children.length; i ++ ) {

					object.children.push( this.children[ i ].toJSON( meta ).object );

				}

			}

			if ( isRootObject ) {

				var geometries = extractFromCache( meta.geometries );
				var materials = extractFromCache( meta.materials );
				var textures = extractFromCache( meta.textures );
				var images = extractFromCache( meta.images );
				var shapes = extractFromCache( meta.shapes );

				if ( geometries.length > 0 ) { output.geometries = geometries; }
				if ( materials.length > 0 ) { output.materials = materials; }
				if ( textures.length > 0 ) { output.textures = textures; }
				if ( images.length > 0 ) { output.images = images; }
				if ( shapes.length > 0 ) { output.shapes = shapes; }

			}

			output.object = object;

			return output;

			// extract data from the cache hash
			// remove metadata on each item
			// and return as array
			function extractFromCache( cache ) {

				var values = [];
				for ( var key in cache ) {

					var data = cache[ key ];
					delete data.metadata;
					values.push( data );

				}
				return values;

			}

		},

		clone: function ( recursive ) {

			return new this.constructor().copy( this, recursive );

		},

		copy: function ( source, recursive ) {

			if ( recursive === undefined ) { recursive = true; }

			this.name = source.name;

			this.up.copy( source.up );

			this.position.copy( source.position );
			this.quaternion.copy( source.quaternion );
			this.scale.copy( source.scale );

			this.matrix.copy( source.matrix );
			this.matrixWorld.copy( source.matrixWorld );

			this.matrixAutoUpdate = source.matrixAutoUpdate;
			this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;

			this.layers.mask = source.layers.mask;
			this.visible = source.visible;

			this.castShadow = source.castShadow;
			this.receiveShadow = source.receiveShadow;

			this.frustumCulled = source.frustumCulled;
			this.renderOrder = source.renderOrder;

			this.userData = JSON.parse( JSON.stringify( source.userData ) );

			if ( recursive === true ) {

				for ( var i = 0; i < source.children.length; i ++ ) {

					var child = source.children[ i ];
					this.add( child.clone() );

				}

			}

			return this;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function Scene() {

		Object3D.call( this );

		this.type = 'Scene';

		this.background = null;
		this.environment = null;
		this.fog = null;

		this.overrideMaterial = null;

		this.autoUpdate = true; // checked by the renderer

		if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {

			__THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef

		}

	}

	Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {

		constructor: Scene,

		isScene: true,

		copy: function ( source, recursive ) {

			Object3D.prototype.copy.call( this, source, recursive );

			if ( source.background !== null ) { this.background = source.background.clone(); }
			if ( source.environment !== null ) { this.environment = source.environment.clone(); }
			if ( source.fog !== null ) { this.fog = source.fog.clone(); }

			if ( source.overrideMaterial !== null ) { this.overrideMaterial = source.overrideMaterial.clone(); }

			this.autoUpdate = source.autoUpdate;
			this.matrixAutoUpdate = source.matrixAutoUpdate;

			return this;

		},

		toJSON: function ( meta ) {

			var data = Object3D.prototype.toJSON.call( this, meta );

			if ( this.background !== null ) { data.object.background = this.background.toJSON( meta ); }
			if ( this.environment !== null ) { data.object.environment = this.environment.toJSON( meta ); }
			if ( this.fog !== null ) { data.object.fog = this.fog.toJSON(); }

			return data;

		},

		dispose: function () {

			this.dispatchEvent( { type: 'dispose' } );

		}

	} );

	var _points = [
		new Vector3(),
		new Vector3(),
		new Vector3(),
		new Vector3(),
		new Vector3(),
		new Vector3(),
		new Vector3(),
		new Vector3()
	];

	var _vector$1 = new Vector3();

	var _box = new Box3();

	// triangle centered vertices

	var _v0 = new Vector3();
	var _v1$2 = new Vector3();
	var _v2 = new Vector3();

	// triangle edge vectors

	var _f0 = new Vector3();
	var _f1 = new Vector3();
	var _f2 = new Vector3();

	var _center = new Vector3();
	var _extents = new Vector3();
	var _triangleNormal = new Vector3();
	var _testAxis = new Vector3();

	/**
	 * @author bhouston / http://clara.io
	 * @author WestLangley / http://github.com/WestLangley
	 */

	function Box3( min, max ) {

		this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
		this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );

	}


	Object.assign( Box3.prototype, {

		isBox3: true,

		set: function ( min, max ) {

			this.min.copy( min );
			this.max.copy( max );

			return this;

		},

		setFromArray: function ( array ) {

			var minX = + Infinity;
			var minY = + Infinity;
			var minZ = + Infinity;

			var maxX = - Infinity;
			var maxY = - Infinity;
			var maxZ = - Infinity;

			for ( var i = 0, l = array.length; i < l; i += 3 ) {

				var x = array[ i ];
				var y = array[ i + 1 ];
				var z = array[ i + 2 ];

				if ( x < minX ) { minX = x; }
				if ( y < minY ) { minY = y; }
				if ( z < minZ ) { minZ = z; }

				if ( x > maxX ) { maxX = x; }
				if ( y > maxY ) { maxY = y; }
				if ( z > maxZ ) { maxZ = z; }

			}

			this.min.set( minX, minY, minZ );
			this.max.set( maxX, maxY, maxZ );

			return this;

		},

		setFromBufferAttribute: function ( attribute ) {

			var minX = + Infinity;
			var minY = + Infinity;
			var minZ = + Infinity;

			var maxX = - Infinity;
			var maxY = - Infinity;
			var maxZ = - Infinity;

			for ( var i = 0, l = attribute.count; i < l; i ++ ) {

				var x = attribute.getX( i );
				var y = attribute.getY( i );
				var z = attribute.getZ( i );

				if ( x < minX ) { minX = x; }
				if ( y < minY ) { minY = y; }
				if ( z < minZ ) { minZ = z; }

				if ( x > maxX ) { maxX = x; }
				if ( y > maxY ) { maxY = y; }
				if ( z > maxZ ) { maxZ = z; }

			}

			this.min.set( minX, minY, minZ );
			this.max.set( maxX, maxY, maxZ );

			return this;

		},

		setFromPoints: function ( points ) {

			this.makeEmpty();

			for ( var i = 0, il = points.length; i < il; i ++ ) {

				this.expandByPoint( points[ i ] );

			}

			return this;

		},

		setFromCenterAndSize: function ( center, size ) {

			var halfSize = _vector$1.copy( size ).multiplyScalar( 0.5 );

			this.min.copy( center ).sub( halfSize );
			this.max.copy( center ).add( halfSize );

			return this;

		},

		setFromObject: function ( object ) {

			this.makeEmpty();

			return this.expandByObject( object );

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		copy: function ( box ) {

			this.min.copy( box.min );
			this.max.copy( box.max );

			return this;

		},

		makeEmpty: function () {

			this.min.x = this.min.y = this.min.z = + Infinity;
			this.max.x = this.max.y = this.max.z = - Infinity;

			return this;

		},

		isEmpty: function () {

			// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes

			return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );

		},

		getCenter: function ( target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Box3: .getCenter() target is now required' );
				target = new Vector3();

			}

			return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );

		},

		getSize: function ( target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Box3: .getSize() target is now required' );
				target = new Vector3();

			}

			return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );

		},

		expandByPoint: function ( point ) {

			this.min.min( point );
			this.max.max( point );

			return this;

		},

		expandByVector: function ( vector ) {

			this.min.sub( vector );
			this.max.add( vector );

			return this;

		},

		expandByScalar: function ( scalar ) {

			this.min.addScalar( - scalar );
			this.max.addScalar( scalar );

			return this;

		},

		expandByObject: function ( object ) {

			// Computes the world-axis-aligned bounding box of an object (including its children),
			// accounting for both the object's, and children's, world transforms

			object.updateWorldMatrix( false, false );

			var geometry = object.geometry;

			if ( geometry !== undefined ) {

				if ( geometry.boundingBox === null ) {

					geometry.computeBoundingBox();

				}

				_box.copy( geometry.boundingBox );
				_box.applyMatrix4( object.matrixWorld );

				this.expandByPoint( _box.min );
				this.expandByPoint( _box.max );

			}

			var children = object.children;

			for ( var i = 0, l = children.length; i < l; i ++ ) {

				this.expandByObject( children[ i ] );

			}

			return this;

		},

		containsPoint: function ( point ) {

			return point.x < this.min.x || point.x > this.max.x ||
				point.y < this.min.y || point.y > this.max.y ||
				point.z < this.min.z || point.z > this.max.z ? false : true;

		},

		containsBox: function ( box ) {

			return this.min.x <= box.min.x && box.max.x <= this.max.x &&
				this.min.y <= box.min.y && box.max.y <= this.max.y &&
				this.min.z <= box.min.z && box.max.z <= this.max.z;

		},

		getParameter: function ( point, target ) {

			// This can potentially have a divide by zero if the box
			// has a size dimension of 0.

			if ( target === undefined ) {

				console.warn( 'THREE.Box3: .getParameter() target is now required' );
				target = new Vector3();

			}

			return target.set(
				( point.x - this.min.x ) / ( this.max.x - this.min.x ),
				( point.y - this.min.y ) / ( this.max.y - this.min.y ),
				( point.z - this.min.z ) / ( this.max.z - this.min.z )
			);

		},

		intersectsBox: function ( box ) {

			// using 6 splitting planes to rule out intersections.
			return box.max.x < this.min.x || box.min.x > this.max.x ||
				box.max.y < this.min.y || box.min.y > this.max.y ||
				box.max.z < this.min.z || box.min.z > this.max.z ? false : true;

		},

		intersectsSphere: function ( sphere ) {

			// Find the point on the AABB closest to the sphere center.
			this.clampPoint( sphere.center, _vector$1 );

			// If that point is inside the sphere, the AABB and sphere intersect.
			return _vector$1.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );

		},

		intersectsPlane: function ( plane ) {

			// We compute the minimum and maximum dot product values. If those values
			// are on the same side (back or front) of the plane, then there is no intersection.

			var min, max;

			if ( plane.normal.x > 0 ) {

				min = plane.normal.x * this.min.x;
				max = plane.normal.x * this.max.x;

			} else {

				min = plane.normal.x * this.max.x;
				max = plane.normal.x * this.min.x;

			}

			if ( plane.normal.y > 0 ) {

				min += plane.normal.y * this.min.y;
				max += plane.normal.y * this.max.y;

			} else {

				min += plane.normal.y * this.max.y;
				max += plane.normal.y * this.min.y;

			}

			if ( plane.normal.z > 0 ) {

				min += plane.normal.z * this.min.z;
				max += plane.normal.z * this.max.z;

			} else {

				min += plane.normal.z * this.max.z;
				max += plane.normal.z * this.min.z;

			}

			return ( min <= - plane.constant && max >= - plane.constant );

		},

		intersectsTriangle: function ( triangle ) {

			if ( this.isEmpty() ) {

				return false;

			}

			// compute box center and extents
			this.getCenter( _center );
			_extents.subVectors( this.max, _center );

			// translate triangle to aabb origin
			_v0.subVectors( triangle.a, _center );
			_v1$2.subVectors( triangle.b, _center );
			_v2.subVectors( triangle.c, _center );

			// compute edge vectors for triangle
			_f0.subVectors( _v1$2, _v0 );
			_f1.subVectors( _v2, _v1$2 );
			_f2.subVectors( _v0, _v2 );

			// test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
			// make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
			// axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
			var axes = [
				0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
				_f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
				- _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
			];
			if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) {

				return false;

			}

			// test 3 face normals from the aabb
			axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
			if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) {

				return false;

			}

			// finally testing the face normal of the triangle
			// use already existing triangle edge vectors here
			_triangleNormal.crossVectors( _f0, _f1 );
			axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];

			return satForAxes( axes, _v0, _v1$2, _v2, _extents );

		},

		clampPoint: function ( point, target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Box3: .clampPoint() target is now required' );
				target = new Vector3();

			}

			return target.copy( point ).clamp( this.min, this.max );

		},

		distanceToPoint: function ( point ) {

			var clampedPoint = _vector$1.copy( point ).clamp( this.min, this.max );

			return clampedPoint.sub( point ).length();

		},

		getBoundingSphere: function ( target ) {

			if ( target === undefined ) {

				console.error( 'THREE.Box3: .getBoundingSphere() target is now required' );
				//target = new Sphere(); // removed to avoid cyclic dependency

			}

			this.getCenter( target.center );

			target.radius = this.getSize( _vector$1 ).length() * 0.5;

			return target;

		},

		intersect: function ( box ) {

			this.min.max( box.min );
			this.max.min( box.max );

			// ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
			if ( this.isEmpty() ) { this.makeEmpty(); }

			return this;

		},

		union: function ( box ) {

			this.min.min( box.min );
			this.max.max( box.max );

			return this;

		},

		applyMatrix4: function ( matrix ) {

			// transform of empty box is an empty box.
			if ( this.isEmpty() ) { return this; }

			// NOTE: I am using a binary pattern to specify all 2^3 combinations below
			_points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
			_points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
			_points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
			_points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
			_points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
			_points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
			_points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
			_points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111

			this.setFromPoints( _points );

			return this;

		},

		translate: function ( offset ) {

			this.min.add( offset );
			this.max.add( offset );

			return this;

		},

		equals: function ( box ) {

			return box.min.equals( this.min ) && box.max.equals( this.max );

		}

	} );

	function satForAxes( axes, v0, v1, v2, extents ) {

		var i, j;

		for ( i = 0, j = axes.length - 3; i <= j; i += 3 ) {

			_testAxis.fromArray( axes, i );
			// project the aabb onto the seperating axis
			var r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
			// project all 3 vertices of the triangle onto the seperating axis
			var p0 = v0.dot( _testAxis );
			var p1 = v1.dot( _testAxis );
			var p2 = v2.dot( _testAxis );
			// actual test, basically see if either of the most extreme of the triangle points intersects r
			if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {

				// points of the projected triangle are outside the projected half-length of the aabb
				// the axis is seperating and we can exit
				return false;

			}

		}

		return true;

	}

	var _box$1 = new Box3();

	/**
	 * @author bhouston / http://clara.io
	 * @author mrdoob / http://mrdoob.com/
	 */

	function Sphere( center, radius ) {

		this.center = ( center !== undefined ) ? center : new Vector3();
		this.radius = ( radius !== undefined ) ? radius : 0;

	}

	Object.assign( Sphere.prototype, {

		set: function ( center, radius ) {

			this.center.copy( center );
			this.radius = radius;

			return this;

		},

		setFromPoints: function ( points, optionalCenter ) {

			var center = this.center;

			if ( optionalCenter !== undefined ) {

				center.copy( optionalCenter );

			} else {

				_box$1.setFromPoints( points ).getCenter( center );

			}

			var maxRadiusSq = 0;

			for ( var i = 0, il = points.length; i < il; i ++ ) {

				maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );

			}

			this.radius = Math.sqrt( maxRadiusSq );

			return this;

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		copy: function ( sphere ) {

			this.center.copy( sphere.center );
			this.radius = sphere.radius;

			return this;

		},

		empty: function () {

			return ( this.radius <= 0 );

		},

		containsPoint: function ( point ) {

			return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );

		},

		distanceToPoint: function ( point ) {

			return ( point.distanceTo( this.center ) - this.radius );

		},

		intersectsSphere: function ( sphere ) {

			var radiusSum = this.radius + sphere.radius;

			return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );

		},

		intersectsBox: function ( box ) {

			return box.intersectsSphere( this );

		},

		intersectsPlane: function ( plane ) {

			return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;

		},

		clampPoint: function ( point, target ) {

			var deltaLengthSq = this.center.distanceToSquared( point );

			if ( target === undefined ) {

				console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
				target = new Vector3();

			}

			target.copy( point );

			if ( deltaLengthSq > ( this.radius * this.radius ) ) {

				target.sub( this.center ).normalize();
				target.multiplyScalar( this.radius ).add( this.center );

			}

			return target;

		},

		getBoundingBox: function ( target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
				target = new Box3();

			}

			target.set( this.center, this.center );
			target.expandByScalar( this.radius );

			return target;

		},

		applyMatrix4: function ( matrix ) {

			this.center.applyMatrix4( matrix );
			this.radius = this.radius * matrix.getMaxScaleOnAxis();

			return this;

		},

		translate: function ( offset ) {

			this.center.add( offset );

			return this;

		},

		equals: function ( sphere ) {

			return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );

		}

	} );

	var _vector$2 = new Vector3();
	var _segCenter = new Vector3();
	var _segDir = new Vector3();
	var _diff = new Vector3();

	var _edge1 = new Vector3();
	var _edge2 = new Vector3();
	var _normal = new Vector3();

	/**
	 * @author bhouston / http://clara.io
	 */

	function Ray( origin, direction ) {

		this.origin = ( origin !== undefined ) ? origin : new Vector3();
		this.direction = ( direction !== undefined ) ? direction : new Vector3( 0, 0, - 1 );

	}

	Object.assign( Ray.prototype, {

		set: function ( origin, direction ) {

			this.origin.copy( origin );
			this.direction.copy( direction );

			return this;

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		copy: function ( ray ) {

			this.origin.copy( ray.origin );
			this.direction.copy( ray.direction );

			return this;

		},

		at: function ( t, target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Ray: .at() target is now required' );
				target = new Vector3();

			}

			return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );

		},

		lookAt: function ( v ) {

			this.direction.copy( v ).sub( this.origin ).normalize();

			return this;

		},

		recast: function ( t ) {

			this.origin.copy( this.at( t, _vector$2 ) );

			return this;

		},

		closestPointToPoint: function ( point, target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
				target = new Vector3();

			}

			target.subVectors( point, this.origin );

			var directionDistance = target.dot( this.direction );

			if ( directionDistance < 0 ) {

				return target.copy( this.origin );

			}

			return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );

		},

		distanceToPoint: function ( point ) {

			return Math.sqrt( this.distanceSqToPoint( point ) );

		},

		distanceSqToPoint: function ( point ) {

			var directionDistance = _vector$2.subVectors( point, this.origin ).dot( this.direction );

			// point behind the ray

			if ( directionDistance < 0 ) {

				return this.origin.distanceToSquared( point );

			}

			_vector$2.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );

			return _vector$2.distanceToSquared( point );

		},

		distanceSqToSegment: function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {

			// from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
			// It returns the min distance between the ray and the segment
			// defined by v0 and v1
			// It can also set two optional targets :
			// - The closest point on the ray
			// - The closest point on the segment

			_segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
			_segDir.copy( v1 ).sub( v0 ).normalize();
			_diff.copy( this.origin ).sub( _segCenter );

			var segExtent = v0.distanceTo( v1 ) * 0.5;
			var a01 = - this.direction.dot( _segDir );
			var b0 = _diff.dot( this.direction );
			var b1 = - _diff.dot( _segDir );
			var c = _diff.lengthSq();
			var det = Math.abs( 1 - a01 * a01 );
			var s0, s1, sqrDist, extDet;

			if ( det > 0 ) {

				// The ray and segment are not parallel.

				s0 = a01 * b1 - b0;
				s1 = a01 * b0 - b1;
				extDet = segExtent * det;

				if ( s0 >= 0 ) {

					if ( s1 >= - extDet ) {

						if ( s1 <= extDet ) {

							// region 0
							// Minimum at interior points of ray and segment.

							var invDet = 1 / det;
							s0 *= invDet;
							s1 *= invDet;
							sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;

						} else {

							// region 1

							s1 = segExtent;
							s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
							sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;

						}

					} else {

						// region 5

						s1 = - segExtent;
						s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
						sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;

					}

				} else {

					if ( s1 <= - extDet ) {

						// region 4

						s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
						s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
						sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;

					} else if ( s1 <= extDet ) {

						// region 3

						s0 = 0;
						s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
						sqrDist = s1 * ( s1 + 2 * b1 ) + c;

					} else {

						// region 2

						s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
						s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
						sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;

					}

				}

			} else {

				// Ray and segment are parallel.

				s1 = ( a01 > 0 ) ? - segExtent : segExtent;
				s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
				sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;

			}

			if ( optionalPointOnRay ) {

				optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );

			}

			if ( optionalPointOnSegment ) {

				optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );

			}

			return sqrDist;

		},

		intersectSphere: function ( sphere, target ) {

			_vector$2.subVectors( sphere.center, this.origin );
			var tca = _vector$2.dot( this.direction );
			var d2 = _vector$2.dot( _vector$2 ) - tca * tca;
			var radius2 = sphere.radius * sphere.radius;

			if ( d2 > radius2 ) { return null; }

			var thc = Math.sqrt( radius2 - d2 );

			// t0 = first intersect point - entrance on front of sphere
			var t0 = tca - thc;

			// t1 = second intersect point - exit point on back of sphere
			var t1 = tca + thc;

			// test to see if both t0 and t1 are behind the ray - if so, return null
			if ( t0 < 0 && t1 < 0 ) { return null; }

			// test to see if t0 is behind the ray:
			// if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
			// in order to always return an intersect point that is in front of the ray.
			if ( t0 < 0 ) { return this.at( t1, target ); }

			// else t0 is in front of the ray, so return the first collision point scaled by t0
			return this.at( t0, target );

		},

		intersectsSphere: function ( sphere ) {

			return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );

		},

		distanceToPlane: function ( plane ) {

			var denominator = plane.normal.dot( this.direction );

			if ( denominator === 0 ) {

				// line is coplanar, return origin
				if ( plane.distanceToPoint( this.origin ) === 0 ) {

					return 0;

				}

				// Null is preferable to undefined since undefined means.... it is undefined

				return null;

			}

			var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;

			// Return if the ray never intersects the plane

			return t >= 0 ? t : null;

		},

		intersectPlane: function ( plane, target ) {

			var t = this.distanceToPlane( plane );

			if ( t === null ) {

				return null;

			}

			return this.at( t, target );

		},

		intersectsPlane: function ( plane ) {

			// check if the ray lies on the plane first

			var distToPoint = plane.distanceToPoint( this.origin );

			if ( distToPoint === 0 ) {

				return true;

			}

			var denominator = plane.normal.dot( this.direction );

			if ( denominator * distToPoint < 0 ) {

				return true;

			}

			// ray origin is behind the plane (and is pointing behind it)

			return false;

		},

		intersectBox: function ( box, target ) {

			var tmin, tmax, tymin, tymax, tzmin, tzmax;

			var invdirx = 1 / this.direction.x,
				invdiry = 1 / this.direction.y,
				invdirz = 1 / this.direction.z;

			var origin = this.origin;

			if ( invdirx >= 0 ) {

				tmin = ( box.min.x - origin.x ) * invdirx;
				tmax = ( box.max.x - origin.x ) * invdirx;

			} else {

				tmin = ( box.max.x - origin.x ) * invdirx;
				tmax = ( box.min.x - origin.x ) * invdirx;

			}

			if ( invdiry >= 0 ) {

				tymin = ( box.min.y - origin.y ) * invdiry;
				tymax = ( box.max.y - origin.y ) * invdiry;

			} else {

				tymin = ( box.max.y - origin.y ) * invdiry;
				tymax = ( box.min.y - origin.y ) * invdiry;

			}

			if ( ( tmin > tymax ) || ( tymin > tmax ) ) { return null; }

			// These lines also handle the case where tmin or tmax is NaN
			// (result of 0 * Infinity). x !== x returns true if x is NaN

			if ( tymin > tmin || tmin !== tmin ) { tmin = tymin; }

			if ( tymax < tmax || tmax !== tmax ) { tmax = tymax; }

			if ( invdirz >= 0 ) {

				tzmin = ( box.min.z - origin.z ) * invdirz;
				tzmax = ( box.max.z - origin.z ) * invdirz;

			} else {

				tzmin = ( box.max.z - origin.z ) * invdirz;
				tzmax = ( box.min.z - origin.z ) * invdirz;

			}

			if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) { return null; }

			if ( tzmin > tmin || tmin !== tmin ) { tmin = tzmin; }

			if ( tzmax < tmax || tmax !== tmax ) { tmax = tzmax; }

			//return point closest to the ray (positive side)

			if ( tmax < 0 ) { return null; }

			return this.at( tmin >= 0 ? tmin : tmax, target );

		},

		intersectsBox: function ( box ) {

			return this.intersectBox( box, _vector$2 ) !== null;

		},

		intersectTriangle: function ( a, b, c, backfaceCulling, target ) {

			// Compute the offset origin, edges, and normal.

			// from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h

			_edge1.subVectors( b, a );
			_edge2.subVectors( c, a );
			_normal.crossVectors( _edge1, _edge2 );

			// Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
			// E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
			//   |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
			//   |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
			//   |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
			var DdN = this.direction.dot( _normal );
			var sign;

			if ( DdN > 0 ) {

				if ( backfaceCulling ) { return null; }
				sign = 1;

			} else if ( DdN < 0 ) {

				sign = - 1;
				DdN = - DdN;

			} else {

				return null;

			}

			_diff.subVectors( this.origin, a );
			var DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );

			// b1 < 0, no intersection
			if ( DdQxE2 < 0 ) {

				return null;

			}

			var DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );

			// b2 < 0, no intersection
			if ( DdE1xQ < 0 ) {

				return null;

			}

			// b1+b2 > 1, no intersection
			if ( DdQxE2 + DdE1xQ > DdN ) {

				return null;

			}

			// Line intersects triangle, check if ray does.
			var QdN = - sign * _diff.dot( _normal );

			// t < 0, no intersection
			if ( QdN < 0 ) {

				return null;

			}

			// Ray intersects triangle.
			return this.at( QdN / DdN, target );

		},

		applyMatrix4: function ( matrix4 ) {

			this.origin.applyMatrix4( matrix4 );
			this.direction.transformDirection( matrix4 );

			return this;

		},

		equals: function ( ray ) {

			return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );

		}

	} );

	/**
	 * @author bhouston / http://clara.io
	 */

	var _vector1 = new Vector3();
	var _vector2 = new Vector3();
	var _normalMatrix = new Matrix3();

	function Plane( normal, constant ) {

		// normal is assumed to be normalized

		this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
		this.constant = ( constant !== undefined ) ? constant : 0;

	}

	Object.assign( Plane.prototype, {

		isPlane: true,

		set: function ( normal, constant ) {

			this.normal.copy( normal );
			this.constant = constant;

			return this;

		},

		setComponents: function ( x, y, z, w ) {

			this.normal.set( x, y, z );
			this.constant = w;

			return this;

		},

		setFromNormalAndCoplanarPoint: function ( normal, point ) {

			this.normal.copy( normal );
			this.constant = - point.dot( this.normal );

			return this;

		},

		setFromCoplanarPoints: function ( a, b, c ) {

			var normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();

			// Q: should an error be thrown if normal is zero (e.g. degenerate plane)?

			this.setFromNormalAndCoplanarPoint( normal, a );

			return this;

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		copy: function ( plane ) {

			this.normal.copy( plane.normal );
			this.constant = plane.constant;

			return this;

		},

		normalize: function () {

			// Note: will lead to a divide by zero if the plane is invalid.

			var inverseNormalLength = 1.0 / this.normal.length();
			this.normal.multiplyScalar( inverseNormalLength );
			this.constant *= inverseNormalLength;

			return this;

		},

		negate: function () {

			this.constant *= - 1;
			this.normal.negate();

			return this;

		},

		distanceToPoint: function ( point ) {

			return this.normal.dot( point ) + this.constant;

		},

		distanceToSphere: function ( sphere ) {

			return this.distanceToPoint( sphere.center ) - sphere.radius;

		},

		projectPoint: function ( point, target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Plane: .projectPoint() target is now required' );
				target = new Vector3();

			}

			return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );

		},

		intersectLine: function ( line, target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Plane: .intersectLine() target is now required' );
				target = new Vector3();

			}

			var direction = line.delta( _vector1 );

			var denominator = this.normal.dot( direction );

			if ( denominator === 0 ) {

				// line is coplanar, return origin
				if ( this.distanceToPoint( line.start ) === 0 ) {

					return target.copy( line.start );

				}

				// Unsure if this is the correct method to handle this case.
				return undefined;

			}

			var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;

			if ( t < 0 || t > 1 ) {

				return undefined;

			}

			return target.copy( direction ).multiplyScalar( t ).add( line.start );

		},

		intersectsLine: function ( line ) {

			// Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.

			var startSign = this.distanceToPoint( line.start );
			var endSign = this.distanceToPoint( line.end );

			return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );

		},

		intersectsBox: function ( box ) {

			return box.intersectsPlane( this );

		},

		intersectsSphere: function ( sphere ) {

			return sphere.intersectsPlane( this );

		},

		coplanarPoint: function ( target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
				target = new Vector3();

			}

			return target.copy( this.normal ).multiplyScalar( - this.constant );

		},

		applyMatrix4: function ( matrix, optionalNormalMatrix ) {

			var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );

			var referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );

			var normal = this.normal.applyMatrix3( normalMatrix ).normalize();

			this.constant = - referencePoint.dot( normal );

			return this;

		},

		translate: function ( offset ) {

			this.constant -= offset.dot( this.normal );

			return this;

		},

		equals: function ( plane ) {

			return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );

		}

	} );

	/**
	 * @author bhouston / http://clara.io
	 * @author mrdoob / http://mrdoob.com/
	 */

	var _v0$1 = new Vector3();
	var _v1$3 = new Vector3();
	var _v2$1 = new Vector3();
	var _v3 = new Vector3();

	var _vab = new Vector3();
	var _vac = new Vector3();
	var _vbc = new Vector3();
	var _vap = new Vector3();
	var _vbp = new Vector3();
	var _vcp = new Vector3();

	function Triangle( a, b, c ) {

		this.a = ( a !== undefined ) ? a : new Vector3();
		this.b = ( b !== undefined ) ? b : new Vector3();
		this.c = ( c !== undefined ) ? c : new Vector3();

	}

	Object.assign( Triangle, {

		getNormal: function ( a, b, c, target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Triangle: .getNormal() target is now required' );
				target = new Vector3();

			}

			target.subVectors( c, b );
			_v0$1.subVectors( a, b );
			target.cross( _v0$1 );

			var targetLengthSq = target.lengthSq();
			if ( targetLengthSq > 0 ) {

				return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );

			}

			return target.set( 0, 0, 0 );

		},

		// static/instance method to calculate barycentric coordinates
		// based on: http://www.blackpawn.com/texts/pointinpoly/default.html
		getBarycoord: function ( point, a, b, c, target ) {

			_v0$1.subVectors( c, a );
			_v1$3.subVectors( b, a );
			_v2$1.subVectors( point, a );

			var dot00 = _v0$1.dot( _v0$1 );
			var dot01 = _v0$1.dot( _v1$3 );
			var dot02 = _v0$1.dot( _v2$1 );
			var dot11 = _v1$3.dot( _v1$3 );
			var dot12 = _v1$3.dot( _v2$1 );

			var denom = ( dot00 * dot11 - dot01 * dot01 );

			if ( target === undefined ) {

				console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
				target = new Vector3();

			}

			// collinear or singular triangle
			if ( denom === 0 ) {

				// arbitrary location outside of triangle?
				// not sure if this is the best idea, maybe should be returning undefined
				return target.set( - 2, - 1, - 1 );

			}

			var invDenom = 1 / denom;
			var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
			var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;

			// barycentric coordinates must always sum to 1
			return target.set( 1 - u - v, v, u );

		},

		containsPoint: function ( point, a, b, c ) {

			Triangle.getBarycoord( point, a, b, c, _v3 );

			return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 );

		},

		getUV: function ( point, p1, p2, p3, uv1, uv2, uv3, target ) {

			this.getBarycoord( point, p1, p2, p3, _v3 );

			target.set( 0, 0 );
			target.addScaledVector( uv1, _v3.x );
			target.addScaledVector( uv2, _v3.y );
			target.addScaledVector( uv3, _v3.z );

			return target;

		},

		isFrontFacing: function ( a, b, c, direction ) {

			_v0$1.subVectors( c, b );
			_v1$3.subVectors( a, b );

			// strictly front facing
			return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;

		}

	} );

	Object.assign( Triangle.prototype, {

		set: function ( a, b, c ) {

			this.a.copy( a );
			this.b.copy( b );
			this.c.copy( c );

			return this;

		},

		setFromPointsAndIndices: function ( points, i0, i1, i2 ) {

			this.a.copy( points[ i0 ] );
			this.b.copy( points[ i1 ] );
			this.c.copy( points[ i2 ] );

			return this;

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		copy: function ( triangle ) {

			this.a.copy( triangle.a );
			this.b.copy( triangle.b );
			this.c.copy( triangle.c );

			return this;

		},

		getArea: function () {

			_v0$1.subVectors( this.c, this.b );
			_v1$3.subVectors( this.a, this.b );

			return _v0$1.cross( _v1$3 ).length() * 0.5;

		},

		getMidpoint: function ( target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
				target = new Vector3();

			}

			return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );

		},

		getNormal: function ( target ) {

			return Triangle.getNormal( this.a, this.b, this.c, target );

		},

		getPlane: function ( target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Triangle: .getPlane() target is now required' );
				target = new Plane();

			}

			return target.setFromCoplanarPoints( this.a, this.b, this.c );

		},

		getBarycoord: function ( point, target ) {

			return Triangle.getBarycoord( point, this.a, this.b, this.c, target );

		},

		getUV: function ( point, uv1, uv2, uv3, target ) {

			return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );

		},

		containsPoint: function ( point ) {

			return Triangle.containsPoint( point, this.a, this.b, this.c );

		},

		isFrontFacing: function ( direction ) {

			return Triangle.isFrontFacing( this.a, this.b, this.c, direction );

		},

		intersectsBox: function ( box ) {

			return box.intersectsTriangle( this );

		},

		closestPointToPoint: function ( p, target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
				target = new Vector3();

			}

			var a = this.a, b = this.b, c = this.c;
			var v, w;

			// algorithm thanks to Real-Time Collision Detection by Christer Ericson,
			// published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
			// under the accompanying license; see chapter 5.1.5 for detailed explanation.
			// basically, we're distinguishing which of the voronoi regions of the triangle
			// the point lies in with the minimum amount of redundant computation.

			_vab.subVectors( b, a );
			_vac.subVectors( c, a );
			_vap.subVectors( p, a );
			var d1 = _vab.dot( _vap );
			var d2 = _vac.dot( _vap );
			if ( d1 <= 0 && d2 <= 0 ) {

				// vertex region of A; barycentric coords (1, 0, 0)
				return target.copy( a );

			}

			_vbp.subVectors( p, b );
			var d3 = _vab.dot( _vbp );
			var d4 = _vac.dot( _vbp );
			if ( d3 >= 0 && d4 <= d3 ) {

				// vertex region of B; barycentric coords (0, 1, 0)
				return target.copy( b );

			}

			var vc = d1 * d4 - d3 * d2;
			if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {

				v = d1 / ( d1 - d3 );
				// edge region of AB; barycentric coords (1-v, v, 0)
				return target.copy( a ).addScaledVector( _vab, v );

			}

			_vcp.subVectors( p, c );
			var d5 = _vab.dot( _vcp );
			var d6 = _vac.dot( _vcp );
			if ( d6 >= 0 && d5 <= d6 ) {

				// vertex region of C; barycentric coords (0, 0, 1)
				return target.copy( c );

			}

			var vb = d5 * d2 - d1 * d6;
			if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {

				w = d2 / ( d2 - d6 );
				// edge region of AC; barycentric coords (1-w, 0, w)
				return target.copy( a ).addScaledVector( _vac, w );

			}

			var va = d3 * d6 - d5 * d4;
			if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {

				_vbc.subVectors( c, b );
				w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
				// edge region of BC; barycentric coords (0, 1-w, w)
				return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC

			}

			// face region
			var denom = 1 / ( va + vb + vc );
			// u = va * denom
			v = vb * denom;
			w = vc * denom;

			return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );

		},

		equals: function ( triangle ) {

			return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	var _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
		'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
		'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
		'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
		'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
		'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
		'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
		'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
		'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
		'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
		'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
		'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
		'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
		'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
		'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
		'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
		'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
		'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
		'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
		'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
		'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
		'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
		'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
		'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };

	var _hslA = { h: 0, s: 0, l: 0 };
	var _hslB = { h: 0, s: 0, l: 0 };

	function Color( r, g, b ) {

		if ( g === undefined && b === undefined ) {

			// r is THREE.Color, hex or string
			return this.set( r );

		}

		return this.setRGB( r, g, b );

	}

	function hue2rgb( p, q, t ) {

		if ( t < 0 ) { t += 1; }
		if ( t > 1 ) { t -= 1; }
		if ( t < 1 / 6 ) { return p + ( q - p ) * 6 * t; }
		if ( t < 1 / 2 ) { return q; }
		if ( t < 2 / 3 ) { return p + ( q - p ) * 6 * ( 2 / 3 - t ); }
		return p;

	}

	function SRGBToLinear( c ) {

		return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );

	}

	function LinearToSRGB( c ) {

		return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;

	}

	Object.assign( Color.prototype, {

		isColor: true,

		r: 1, g: 1, b: 1,

		set: function ( value ) {

			if ( value && value.isColor ) {

				this.copy( value );

			} else if ( typeof value === 'number' ) {

				this.setHex( value );

			} else if ( typeof value === 'string' ) {

				this.setStyle( value );

			}

			return this;

		},

		setScalar: function ( scalar ) {

			this.r = scalar;
			this.g = scalar;
			this.b = scalar;

			return this;

		},

		setHex: function ( hex ) {

			hex = Math.floor( hex );

			this.r = ( hex >> 16 & 255 ) / 255;
			this.g = ( hex >> 8 & 255 ) / 255;
			this.b = ( hex & 255 ) / 255;

			return this;

		},

		setRGB: function ( r, g, b ) {

			this.r = r;
			this.g = g;
			this.b = b;

			return this;

		},

		setHSL: function ( h, s, l ) {

			// h,s,l ranges are in 0.0 - 1.0
			h = MathUtils.euclideanModulo( h, 1 );
			s = MathUtils.clamp( s, 0, 1 );
			l = MathUtils.clamp( l, 0, 1 );

			if ( s === 0 ) {

				this.r = this.g = this.b = l;

			} else {

				var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
				var q = ( 2 * l ) - p;

				this.r = hue2rgb( q, p, h + 1 / 3 );
				this.g = hue2rgb( q, p, h );
				this.b = hue2rgb( q, p, h - 1 / 3 );

			}

			return this;

		},

		setStyle: function ( style ) {

			function handleAlpha( string ) {

				if ( string === undefined ) { return; }

				if ( parseFloat( string ) < 1 ) {

					console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );

				}

			}


			var m;

			if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {

				// rgb / hsl

				var color;
				var name = m[ 1 ];
				var components = m[ 2 ];

				switch ( name ) {

					case 'rgb':
					case 'rgba':

						if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {

							// rgb(255,0,0) rgba(255,0,0,0.5)
							this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
							this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
							this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;

							handleAlpha( color[ 5 ] );

							return this;

						}

						if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {

							// rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
							this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
							this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
							this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;

							handleAlpha( color[ 5 ] );

							return this;

						}

						break;

					case 'hsl':
					case 'hsla':

						if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {

							// hsl(120,50%,50%) hsla(120,50%,50%,0.5)
							var h = parseFloat( color[ 1 ] ) / 360;
							var s = parseInt( color[ 2 ], 10 ) / 100;
							var l = parseInt( color[ 3 ], 10 ) / 100;

							handleAlpha( color[ 5 ] );

							return this.setHSL( h, s, l );

						}

						break;

				}

			} else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {

				// hex color

				var hex = m[ 1 ];
				var size = hex.length;

				if ( size === 3 ) {

					// #ff0
					this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
					this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
					this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;

					return this;

				} else if ( size === 6 ) {

					// #ff0000
					this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
					this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
					this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;

					return this;

				}

			}

			if ( style && style.length > 0 ) {

				return this.setColorName( style );

			}

			return this;

		},

		setColorName: function ( style ) {

			// color keywords
			var hex = _colorKeywords[ style ];

			if ( hex !== undefined ) {

				// red
				this.setHex( hex );

			} else {

				// unknown color
				console.warn( 'THREE.Color: Unknown color ' + style );

			}

			return this;

		},

		clone: function () {

			return new this.constructor( this.r, this.g, this.b );

		},

		copy: function ( color ) {

			this.r = color.r;
			this.g = color.g;
			this.b = color.b;

			return this;

		},

		copyGammaToLinear: function ( color, gammaFactor ) {

			if ( gammaFactor === undefined ) { gammaFactor = 2.0; }

			this.r = Math.pow( color.r, gammaFactor );
			this.g = Math.pow( color.g, gammaFactor );
			this.b = Math.pow( color.b, gammaFactor );

			return this;

		},

		copyLinearToGamma: function ( color, gammaFactor ) {

			if ( gammaFactor === undefined ) { gammaFactor = 2.0; }

			var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;

			this.r = Math.pow( color.r, safeInverse );
			this.g = Math.pow( color.g, safeInverse );
			this.b = Math.pow( color.b, safeInverse );

			return this;

		},

		convertGammaToLinear: function ( gammaFactor ) {

			this.copyGammaToLinear( this, gammaFactor );

			return this;

		},

		convertLinearToGamma: function ( gammaFactor ) {

			this.copyLinearToGamma( this, gammaFactor );

			return this;

		},

		copySRGBToLinear: function ( color ) {

			this.r = SRGBToLinear( color.r );
			this.g = SRGBToLinear( color.g );
			this.b = SRGBToLinear( color.b );

			return this;

		},

		copyLinearToSRGB: function ( color ) {

			this.r = LinearToSRGB( color.r );
			this.g = LinearToSRGB( color.g );
			this.b = LinearToSRGB( color.b );

			return this;

		},

		convertSRGBToLinear: function () {

			this.copySRGBToLinear( this );

			return this;

		},

		convertLinearToSRGB: function () {

			this.copyLinearToSRGB( this );

			return this;

		},

		getHex: function () {

			return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;

		},

		getHexString: function () {

			return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );

		},

		getHSL: function ( target ) {

			// h,s,l ranges are in 0.0 - 1.0

			if ( target === undefined ) {

				console.warn( 'THREE.Color: .getHSL() target is now required' );
				target = { h: 0, s: 0, l: 0 };

			}

			var r = this.r, g = this.g, b = this.b;

			var max = Math.max( r, g, b );
			var min = Math.min( r, g, b );

			var hue, saturation;
			var lightness = ( min + max ) / 2.0;

			if ( min === max ) {

				hue = 0;
				saturation = 0;

			} else {

				var delta = max - min;

				saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );

				switch ( max ) {

					case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
					case g: hue = ( b - r ) / delta + 2; break;
					case b: hue = ( r - g ) / delta + 4; break;

				}

				hue /= 6;

			}

			target.h = hue;
			target.s = saturation;
			target.l = lightness;

			return target;

		},

		getStyle: function () {

			return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';

		},

		offsetHSL: function ( h, s, l ) {

			this.getHSL( _hslA );

			_hslA.h += h; _hslA.s += s; _hslA.l += l;

			this.setHSL( _hslA.h, _hslA.s, _hslA.l );

			return this;

		},

		add: function ( color ) {

			this.r += color.r;
			this.g += color.g;
			this.b += color.b;

			return this;

		},

		addColors: function ( color1, color2 ) {

			this.r = color1.r + color2.r;
			this.g = color1.g + color2.g;
			this.b = color1.b + color2.b;

			return this;

		},

		addScalar: function ( s ) {

			this.r += s;
			this.g += s;
			this.b += s;

			return this;

		},

		sub: function ( color ) {

			this.r = Math.max( 0, this.r - color.r );
			this.g = Math.max( 0, this.g - color.g );
			this.b = Math.max( 0, this.b - color.b );

			return this;

		},

		multiply: function ( color ) {

			this.r *= color.r;
			this.g *= color.g;
			this.b *= color.b;

			return this;

		},

		multiplyScalar: function ( s ) {

			this.r *= s;
			this.g *= s;
			this.b *= s;

			return this;

		},

		lerp: function ( color, alpha ) {

			this.r += ( color.r - this.r ) * alpha;
			this.g += ( color.g - this.g ) * alpha;
			this.b += ( color.b - this.b ) * alpha;

			return this;

		},

		lerpHSL: function ( color, alpha ) {

			this.getHSL( _hslA );
			color.getHSL( _hslB );

			var h = MathUtils.lerp( _hslA.h, _hslB.h, alpha );
			var s = MathUtils.lerp( _hslA.s, _hslB.s, alpha );
			var l = MathUtils.lerp( _hslA.l, _hslB.l, alpha );

			this.setHSL( h, s, l );

			return this;

		},

		equals: function ( c ) {

			return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );

		},

		fromArray: function ( array, offset ) {

			if ( offset === undefined ) { offset = 0; }

			this.r = array[ offset ];
			this.g = array[ offset + 1 ];
			this.b = array[ offset + 2 ];

			return this;

		},

		toArray: function ( array, offset ) {

			if ( array === undefined ) { array = []; }
			if ( offset === undefined ) { offset = 0; }

			array[ offset ] = this.r;
			array[ offset + 1 ] = this.g;
			array[ offset + 2 ] = this.b;

			return array;

		},

		toJSON: function () {

			return this.getHex();

		}

	} );

	Color.NAMES = _colorKeywords;

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author alteredq / http://alteredqualia.com/
	 */

	function Face3( a, b, c, normal, color, materialIndex ) {

		this.a = a;
		this.b = b;
		this.c = c;

		this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
		this.vertexNormals = Array.isArray( normal ) ? normal : [];

		this.color = ( color && color.isColor ) ? color : new Color();
		this.vertexColors = Array.isArray( color ) ? color : [];

		this.materialIndex = materialIndex !== undefined ? materialIndex : 0;

	}

	Object.assign( Face3.prototype, {

		clone: function () {

			return new this.constructor().copy( this );

		},

		copy: function ( source ) {

			this.a = source.a;
			this.b = source.b;
			this.c = source.c;

			this.normal.copy( source.normal );
			this.color.copy( source.color );

			this.materialIndex = source.materialIndex;

			for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {

				this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();

			}

			for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {

				this.vertexColors[ i ] = source.vertexColors[ i ].clone();

			}

			return this;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author alteredq / http://alteredqualia.com/
	 */

	var materialId = 0;

	function Material() {

		Object.defineProperty( this, 'id', { value: materialId ++ } );

		this.uuid = MathUtils.generateUUID();

		this.name = '';
		this.type = 'Material';

		this.fog = true;

		this.blending = NormalBlending;
		this.side = FrontSide;
		this.flatShading = false;
		this.vertexTangents = false;
		this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors

		this.opacity = 1;
		this.transparent = false;

		this.blendSrc = SrcAlphaFactor;
		this.blendDst = OneMinusSrcAlphaFactor;
		this.blendEquation = AddEquation;
		this.blendSrcAlpha = null;
		this.blendDstAlpha = null;
		this.blendEquationAlpha = null;

		this.depthFunc = LessEqualDepth;
		this.depthTest = true;
		this.depthWrite = true;

		this.stencilWriteMask = 0xff;
		this.stencilFunc = AlwaysStencilFunc;
		this.stencilRef = 0;
		this.stencilFuncMask = 0xff;
		this.stencilFail = KeepStencilOp;
		this.stencilZFail = KeepStencilOp;
		this.stencilZPass = KeepStencilOp;
		this.stencilWrite = false;

		this.clippingPlanes = null;
		this.clipIntersection = false;
		this.clipShadows = false;

		this.shadowSide = null;

		this.colorWrite = true;

		this.precision = null; // override the renderer's default precision for this material

		this.polygonOffset = false;
		this.polygonOffsetFactor = 0;
		this.polygonOffsetUnits = 0;

		this.dithering = false;

		this.alphaTest = 0;
		this.premultipliedAlpha = false;

		this.visible = true;

		this.toneMapped = true;

		this.userData = {};

		this.version = 0;

	}

	Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {

		constructor: Material,

		isMaterial: true,

		onBeforeCompile: function () {},

		setValues: function ( values ) {

			if ( values === undefined ) { return; }

			for ( var key in values ) {

				var newValue = values[ key ];

				if ( newValue === undefined ) {

					console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
					continue;

				}

				// for backward compatability if shading is set in the constructor
				if ( key === 'shading' ) {

					console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
					this.flatShading = ( newValue === FlatShading ) ? true : false;
					continue;

				}

				var currentValue = this[ key ];

				if ( currentValue === undefined ) {

					console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
					continue;

				}

				if ( currentValue && currentValue.isColor ) {

					currentValue.set( newValue );

				} else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {

					currentValue.copy( newValue );

				} else {

					this[ key ] = newValue;

				}

			}

		},

		toJSON: function ( meta ) {

			var isRoot = ( meta === undefined || typeof meta === 'string' );

			if ( isRoot ) {

				meta = {
					textures: {},
					images: {}
				};

			}

			var data = {
				metadata: {
					version: 4.5,
					type: 'Material',
					generator: 'Material.toJSON'
				}
			};

			// standard Material serialization
			data.uuid = this.uuid;
			data.type = this.type;

			if ( this.name !== '' ) { data.name = this.name; }

			if ( this.color && this.color.isColor ) { data.color = this.color.getHex(); }

			if ( this.roughness !== undefined ) { data.roughness = this.roughness; }
			if ( this.metalness !== undefined ) { data.metalness = this.metalness; }

			if ( this.sheen && this.sheen.isColor ) { data.sheen = this.sheen.getHex(); }
			if ( this.emissive && this.emissive.isColor ) { data.emissive = this.emissive.getHex(); }
			if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) { data.emissiveIntensity = this.emissiveIntensity; }

			if ( this.specular && this.specular.isColor ) { data.specular = this.specular.getHex(); }
			if ( this.shininess !== undefined ) { data.shininess = this.shininess; }
			if ( this.clearcoat !== undefined ) { data.clearcoat = this.clearcoat; }
			if ( this.clearcoatRoughness !== undefined ) { data.clearcoatRoughness = this.clearcoatRoughness; }

			if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {

				data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
				data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();

			}

			if ( this.map && this.map.isTexture ) { data.map = this.map.toJSON( meta ).uuid; }
			if ( this.matcap && this.matcap.isTexture ) { data.matcap = this.matcap.toJSON( meta ).uuid; }
			if ( this.alphaMap && this.alphaMap.isTexture ) { data.alphaMap = this.alphaMap.toJSON( meta ).uuid; }
			if ( this.lightMap && this.lightMap.isTexture ) { data.lightMap = this.lightMap.toJSON( meta ).uuid; }

			if ( this.aoMap && this.aoMap.isTexture ) {

				data.aoMap = this.aoMap.toJSON( meta ).uuid;
				data.aoMapIntensity = this.aoMapIntensity;

			}

			if ( this.bumpMap && this.bumpMap.isTexture ) {

				data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
				data.bumpScale = this.bumpScale;

			}

			if ( this.normalMap && this.normalMap.isTexture ) {

				data.normalMap = this.normalMap.toJSON( meta ).uuid;
				data.normalMapType = this.normalMapType;
				data.normalScale = this.normalScale.toArray();

			}

			if ( this.displacementMap && this.displacementMap.isTexture ) {

				data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
				data.displacementScale = this.displacementScale;
				data.displacementBias = this.displacementBias;

			}

			if ( this.roughnessMap && this.roughnessMap.isTexture ) { data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; }
			if ( this.metalnessMap && this.metalnessMap.isTexture ) { data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; }

			if ( this.emissiveMap && this.emissiveMap.isTexture ) { data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; }
			if ( this.specularMap && this.specularMap.isTexture ) { data.specularMap = this.specularMap.toJSON( meta ).uuid; }

			if ( this.envMap && this.envMap.isTexture ) {

				data.envMap = this.envMap.toJSON( meta ).uuid;
				data.reflectivity = this.reflectivity; // Scale behind envMap
				data.refractionRatio = this.refractionRatio;

				if ( this.combine !== undefined ) { data.combine = this.combine; }
				if ( this.envMapIntensity !== undefined ) { data.envMapIntensity = this.envMapIntensity; }

			}

			if ( this.gradientMap && this.gradientMap.isTexture ) {

				data.gradientMap = this.gradientMap.toJSON( meta ).uuid;

			}

			if ( this.size !== undefined ) { data.size = this.size; }
			if ( this.sizeAttenuation !== undefined ) { data.sizeAttenuation = this.sizeAttenuation; }

			if ( this.blending !== NormalBlending ) { data.blending = this.blending; }
			if ( this.flatShading === true ) { data.flatShading = this.flatShading; }
			if ( this.side !== FrontSide ) { data.side = this.side; }
			if ( this.vertexColors !== NoColors ) { data.vertexColors = this.vertexColors; }

			if ( this.opacity < 1 ) { data.opacity = this.opacity; }
			if ( this.transparent === true ) { data.transparent = this.transparent; }

			data.depthFunc = this.depthFunc;
			data.depthTest = this.depthTest;
			data.depthWrite = this.depthWrite;

			data.stencilWrite = this.stencilWrite;
			data.stencilWriteMask = this.stencilWriteMask;
			data.stencilFunc = this.stencilFunc;
			data.stencilRef = this.stencilRef;
			data.stencilFuncMask = this.stencilFuncMask;
			data.stencilFail = this.stencilFail;
			data.stencilZFail = this.stencilZFail;
			data.stencilZPass = this.stencilZPass;

			// rotation (SpriteMaterial)
			if ( this.rotation && this.rotation !== 0 ) { data.rotation = this.rotation; }

			if ( this.polygonOffset === true ) { data.polygonOffset = true; }
			if ( this.polygonOffsetFactor !== 0 ) { data.polygonOffsetFactor = this.polygonOffsetFactor; }
			if ( this.polygonOffsetUnits !== 0 ) { data.polygonOffsetUnits = this.polygonOffsetUnits; }

			if ( this.linewidth && this.linewidth !== 1 ) { data.linewidth = this.linewidth; }
			if ( this.dashSize !== undefined ) { data.dashSize = this.dashSize; }
			if ( this.gapSize !== undefined ) { data.gapSize = this.gapSize; }
			if ( this.scale !== undefined ) { data.scale = this.scale; }

			if ( this.dithering === true ) { data.dithering = true; }

			if ( this.alphaTest > 0 ) { data.alphaTest = this.alphaTest; }
			if ( this.premultipliedAlpha === true ) { data.premultipliedAlpha = this.premultipliedAlpha; }

			if ( this.wireframe === true ) { data.wireframe = this.wireframe; }
			if ( this.wireframeLinewidth > 1 ) { data.wireframeLinewidth = this.wireframeLinewidth; }
			if ( this.wireframeLinecap !== 'round' ) { data.wireframeLinecap = this.wireframeLinecap; }
			if ( this.wireframeLinejoin !== 'round' ) { data.wireframeLinejoin = this.wireframeLinejoin; }

			if ( this.morphTargets === true ) { data.morphTargets = true; }
			if ( this.morphNormals === true ) { data.morphNormals = true; }
			if ( this.skinning === true ) { data.skinning = true; }

			if ( this.visible === false ) { data.visible = false; }

			if ( this.toneMapped === false ) { data.toneMapped = false; }

			if ( JSON.stringify( this.userData ) !== '{}' ) { data.userData = this.userData; }

			// TODO: Copied from Object3D.toJSON

			function extractFromCache( cache ) {

				var values = [];

				for ( var key in cache ) {

					var data = cache[ key ];
					delete data.metadata;
					values.push( data );

				}

				return values;

			}

			if ( isRoot ) {

				var textures = extractFromCache( meta.textures );
				var images = extractFromCache( meta.images );

				if ( textures.length > 0 ) { data.textures = textures; }
				if ( images.length > 0 ) { data.images = images; }

			}

			return data;

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		copy: function ( source ) {

			this.name = source.name;

			this.fog = source.fog;

			this.blending = source.blending;
			this.side = source.side;
			this.flatShading = source.flatShading;
			this.vertexTangents = source.vertexTangents;
			this.vertexColors = source.vertexColors;

			this.opacity = source.opacity;
			this.transparent = source.transparent;

			this.blendSrc = source.blendSrc;
			this.blendDst = source.blendDst;
			this.blendEquation = source.blendEquation;
			this.blendSrcAlpha = source.blendSrcAlpha;
			this.blendDstAlpha = source.blendDstAlpha;
			this.blendEquationAlpha = source.blendEquationAlpha;

			this.depthFunc = source.depthFunc;
			this.depthTest = source.depthTest;
			this.depthWrite = source.depthWrite;

			this.stencilWriteMask = source.stencilWriteMask;
			this.stencilFunc = source.stencilFunc;
			this.stencilRef = source.stencilRef;
			this.stencilFuncMask = source.stencilFuncMask;
			this.stencilFail = source.stencilFail;
			this.stencilZFail = source.stencilZFail;
			this.stencilZPass = source.stencilZPass;
			this.stencilWrite = source.stencilWrite;

			var srcPlanes = source.clippingPlanes,
				dstPlanes = null;

			if ( srcPlanes !== null ) {

				var n = srcPlanes.length;
				dstPlanes = new Array( n );

				for ( var i = 0; i !== n; ++ i )
					{ dstPlanes[ i ] = srcPlanes[ i ].clone(); }

			}

			this.clippingPlanes = dstPlanes;
			this.clipIntersection = source.clipIntersection;
			this.clipShadows = source.clipShadows;

			this.shadowSide = source.shadowSide;

			this.colorWrite = source.colorWrite;

			this.precision = source.precision;

			this.polygonOffset = source.polygonOffset;
			this.polygonOffsetFactor = source.polygonOffsetFactor;
			this.polygonOffsetUnits = source.polygonOffsetUnits;

			this.dithering = source.dithering;

			this.alphaTest = source.alphaTest;
			this.premultipliedAlpha = source.premultipliedAlpha;

			this.visible = source.visible;

			this.toneMapped = source.toneMapped;

			this.userData = JSON.parse( JSON.stringify( source.userData ) );

			return this;

		},

		dispose: function () {

			this.dispatchEvent( { type: 'dispose' } );

		}

	} );

	Object.defineProperty( Material.prototype, 'needsUpdate', {

		set: function ( value ) {

			if ( value === true ) { this.version ++; }

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author alteredq / http://alteredqualia.com/
	 *
	 * parameters = {
	 *  color: <hex>,
	 *  opacity: <float>,
	 *  map: new THREE.Texture( <Image> ),
	 *
	 *  lightMap: new THREE.Texture( <Image> ),
	 *  lightMapIntensity: <float>
	 *
	 *  aoMap: new THREE.Texture( <Image> ),
	 *  aoMapIntensity: <float>
	 *
	 *  specularMap: new THREE.Texture( <Image> ),
	 *
	 *  alphaMap: new THREE.Texture( <Image> ),
	 *
	 *  envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
	 *  combine: THREE.Multiply,
	 *  reflectivity: <float>,
	 *  refractionRatio: <float>,
	 *
	 *  depthTest: <bool>,
	 *  depthWrite: <bool>,
	 *
	 *  wireframe: <boolean>,
	 *  wireframeLinewidth: <float>,
	 *
	 *  skinning: <bool>,
	 *  morphTargets: <bool>
	 * }
	 */

	function MeshBasicMaterial( parameters ) {

		Material.call( this );

		this.type = 'MeshBasicMaterial';

		this.color = new Color( 0xffffff ); // emissive

		this.map = null;

		this.lightMap = null;
		this.lightMapIntensity = 1.0;

		this.aoMap = null;
		this.aoMapIntensity = 1.0;

		this.specularMap = null;

		this.alphaMap = null;

		this.envMap = null;
		this.combine = MultiplyOperation;
		this.reflectivity = 1;
		this.refractionRatio = 0.98;

		this.wireframe = false;
		this.wireframeLinewidth = 1;
		this.wireframeLinecap = 'round';
		this.wireframeLinejoin = 'round';

		this.skinning = false;
		this.morphTargets = false;

		this.setValues( parameters );

	}

	MeshBasicMaterial.prototype = Object.create( Material.prototype );
	MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;

	MeshBasicMaterial.prototype.isMeshBasicMaterial = true;

	MeshBasicMaterial.prototype.copy = function ( source ) {

		Material.prototype.copy.call( this, source );

		this.color.copy( source.color );

		this.map = source.map;

		this.lightMap = source.lightMap;
		this.lightMapIntensity = source.lightMapIntensity;

		this.aoMap = source.aoMap;
		this.aoMapIntensity = source.aoMapIntensity;

		this.specularMap = source.specularMap;

		this.alphaMap = source.alphaMap;

		this.envMap = source.envMap;
		this.combine = source.combine;
		this.reflectivity = source.reflectivity;
		this.refractionRatio = source.refractionRatio;

		this.wireframe = source.wireframe;
		this.wireframeLinewidth = source.wireframeLinewidth;
		this.wireframeLinecap = source.wireframeLinecap;
		this.wireframeLinejoin = source.wireframeLinejoin;

		this.skinning = source.skinning;
		this.morphTargets = source.morphTargets;

		return this;

	};

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	var _vector$3 = new Vector3();

	function BufferAttribute( array, itemSize, normalized ) {

		if ( Array.isArray( array ) ) {

			throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );

		}

		this.name = '';

		this.array = array;
		this.itemSize = itemSize;
		this.count = array !== undefined ? array.length / itemSize : 0;
		this.normalized = normalized === true;

		this.usage = StaticDrawUsage;
		this.updateRange = { offset: 0, count: - 1 };

		this.version = 0;

	}

	Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {

		set: function ( value ) {

			if ( value === true ) { this.version ++; }

		}

	} );

	Object.assign( BufferAttribute.prototype, {

		isBufferAttribute: true,

		onUploadCallback: function () {},

		setUsage: function ( value ) {

			this.usage = value;

			return this;

		},

		copy: function ( source ) {

			this.name = source.name;
			this.array = new source.array.constructor( source.array );
			this.itemSize = source.itemSize;
			this.count = source.count;
			this.normalized = source.normalized;

			this.usage = source.usage;

			return this;

		},

		copyAt: function ( index1, attribute, index2 ) {

			index1 *= this.itemSize;
			index2 *= attribute.itemSize;

			for ( var i = 0, l = this.itemSize; i < l; i ++ ) {

				this.array[ index1 + i ] = attribute.array[ index2 + i ];

			}

			return this;

		},

		copyArray: function ( array ) {

			this.array.set( array );

			return this;

		},

		copyColorsArray: function ( colors ) {

			var array = this.array, offset = 0;

			for ( var i = 0, l = colors.length; i < l; i ++ ) {

				var color = colors[ i ];

				if ( color === undefined ) {

					console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
					color = new Color();

				}

				array[ offset ++ ] = color.r;
				array[ offset ++ ] = color.g;
				array[ offset ++ ] = color.b;

			}

			return this;

		},

		copyVector2sArray: function ( vectors ) {

			var array = this.array, offset = 0;

			for ( var i = 0, l = vectors.length; i < l; i ++ ) {

				var vector = vectors[ i ];

				if ( vector === undefined ) {

					console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
					vector = new Vector2();

				}

				array[ offset ++ ] = vector.x;
				array[ offset ++ ] = vector.y;

			}

			return this;

		},

		copyVector3sArray: function ( vectors ) {

			var array = this.array, offset = 0;

			for ( var i = 0, l = vectors.length; i < l; i ++ ) {

				var vector = vectors[ i ];

				if ( vector === undefined ) {

					console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
					vector = new Vector3();

				}

				array[ offset ++ ] = vector.x;
				array[ offset ++ ] = vector.y;
				array[ offset ++ ] = vector.z;

			}

			return this;

		},

		copyVector4sArray: function ( vectors ) {

			var array = this.array, offset = 0;

			for ( var i = 0, l = vectors.length; i < l; i ++ ) {

				var vector = vectors[ i ];

				if ( vector === undefined ) {

					console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
					vector = new Vector4();

				}

				array[ offset ++ ] = vector.x;
				array[ offset ++ ] = vector.y;
				array[ offset ++ ] = vector.z;
				array[ offset ++ ] = vector.w;

			}

			return this;

		},

		applyMatrix3: function ( m ) {

			for ( var i = 0, l = this.count; i < l; i ++ ) {

				_vector$3.x = this.getX( i );
				_vector$3.y = this.getY( i );
				_vector$3.z = this.getZ( i );

				_vector$3.applyMatrix3( m );

				this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );

			}

			return this;

		},

		applyMatrix4: function ( m ) {

			for ( var i = 0, l = this.count; i < l; i ++ ) {

				_vector$3.x = this.getX( i );
				_vector$3.y = this.getY( i );
				_vector$3.z = this.getZ( i );

				_vector$3.applyMatrix4( m );

				this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );

			}

			return this;

		},

		applyNormalMatrix: function ( m ) {

			for ( var i = 0, l = this.count; i < l; i ++ ) {

				_vector$3.x = this.getX( i );
				_vector$3.y = this.getY( i );
				_vector$3.z = this.getZ( i );

				_vector$3.applyNormalMatrix( m );

				this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );

			}

			return this;

		},

		transformDirection: function ( m ) {

			for ( var i = 0, l = this.count; i < l; i ++ ) {

				_vector$3.x = this.getX( i );
				_vector$3.y = this.getY( i );
				_vector$3.z = this.getZ( i );

				_vector$3.transformDirection( m );

				this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );

			}

			return this;

		},

		set: function ( value, offset ) {

			if ( offset === undefined ) { offset = 0; }

			this.array.set( value, offset );

			return this;

		},

		getX: function ( index ) {

			return this.array[ index * this.itemSize ];

		},

		setX: function ( index, x ) {

			this.array[ index * this.itemSize ] = x;

			return this;

		},

		getY: function ( index ) {

			return this.array[ index * this.itemSize + 1 ];

		},

		setY: function ( index, y ) {

			this.array[ index * this.itemSize + 1 ] = y;

			return this;

		},

		getZ: function ( index ) {

			return this.array[ index * this.itemSize + 2 ];

		},

		setZ: function ( index, z ) {

			this.array[ index * this.itemSize + 2 ] = z;

			return this;

		},

		getW: function ( index ) {

			return this.array[ index * this.itemSize + 3 ];

		},

		setW: function ( index, w ) {

			this.array[ index * this.itemSize + 3 ] = w;

			return this;

		},

		setXY: function ( index, x, y ) {

			index *= this.itemSize;

			this.array[ index + 0 ] = x;
			this.array[ index + 1 ] = y;

			return this;

		},

		setXYZ: function ( index, x, y, z ) {

			index *= this.itemSize;

			this.array[ index + 0 ] = x;
			this.array[ index + 1 ] = y;
			this.array[ index + 2 ] = z;

			return this;

		},

		setXYZW: function ( index, x, y, z, w ) {

			index *= this.itemSize;

			this.array[ index + 0 ] = x;
			this.array[ index + 1 ] = y;
			this.array[ index + 2 ] = z;
			this.array[ index + 3 ] = w;

			return this;

		},

		onUpload: function ( callback ) {

			this.onUploadCallback = callback;

			return this;

		},

		clone: function () {

			return new this.constructor( this.array, this.itemSize ).copy( this );

		},

		toJSON: function () {

			return {
				itemSize: this.itemSize,
				type: this.array.constructor.name,
				array: Array.prototype.slice.call( this.array ),
				normalized: this.normalized
			};

		}

	} );

	//

	function Int8BufferAttribute( array, itemSize, normalized ) {

		BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );

	}

	Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
	Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;


	function Uint8BufferAttribute( array, itemSize, normalized ) {

		BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );

	}

	Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
	Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;


	function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {

		BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );

	}

	Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
	Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;


	function Int16BufferAttribute( array, itemSize, normalized ) {

		BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );

	}

	Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
	Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;


	function Uint16BufferAttribute( array, itemSize, normalized ) {

		BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );

	}

	Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
	Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;


	function Int32BufferAttribute( array, itemSize, normalized ) {

		BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );

	}

	Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
	Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;


	function Uint32BufferAttribute( array, itemSize, normalized ) {

		BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );

	}

	Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
	Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;


	function Float32BufferAttribute( array, itemSize, normalized ) {

		BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );

	}

	Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
	Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;


	function Float64BufferAttribute( array, itemSize, normalized ) {

		BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );

	}

	Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
	Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function DirectGeometry() {

		this.vertices = [];
		this.normals = [];
		this.colors = [];
		this.uvs = [];
		this.uvs2 = [];

		this.groups = [];

		this.morphTargets = {};

		this.skinWeights = [];
		this.skinIndices = [];

		// this.lineDistances = [];

		this.boundingBox = null;
		this.boundingSphere = null;

		// update flags

		this.verticesNeedUpdate = false;
		this.normalsNeedUpdate = false;
		this.colorsNeedUpdate = false;
		this.uvsNeedUpdate = false;
		this.groupsNeedUpdate = false;

	}

	Object.assign( DirectGeometry.prototype, {

		computeGroups: function ( geometry ) {

			var group;
			var groups = [];
			var materialIndex = undefined;

			var faces = geometry.faces;

			for ( var i = 0; i < faces.length; i ++ ) {

				var face = faces[ i ];

				// materials

				if ( face.materialIndex !== materialIndex ) {

					materialIndex = face.materialIndex;

					if ( group !== undefined ) {

						group.count = ( i * 3 ) - group.start;
						groups.push( group );

					}

					group = {
						start: i * 3,
						materialIndex: materialIndex
					};

				}

			}

			if ( group !== undefined ) {

				group.count = ( i * 3 ) - group.start;
				groups.push( group );

			}

			this.groups = groups;

		},

		fromGeometry: function ( geometry ) {

			var faces = geometry.faces;
			var vertices = geometry.vertices;
			var faceVertexUvs = geometry.faceVertexUvs;

			var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
			var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;

			// morphs

			var morphTargets = geometry.morphTargets;
			var morphTargetsLength = morphTargets.length;

			var morphTargetsPosition;

			if ( morphTargetsLength > 0 ) {

				morphTargetsPosition = [];

				for ( var i = 0; i < morphTargetsLength; i ++ ) {

					morphTargetsPosition[ i ] = {
						name: morphTargets[ i ].name,
					 	data: []
					};

				}

				this.morphTargets.position = morphTargetsPosition;

			}

			var morphNormals = geometry.morphNormals;
			var morphNormalsLength = morphNormals.length;

			var morphTargetsNormal;

			if ( morphNormalsLength > 0 ) {

				morphTargetsNormal = [];

				for ( var i = 0; i < morphNormalsLength; i ++ ) {

					morphTargetsNormal[ i ] = {
						name: morphNormals[ i ].name,
					 	data: []
					};

				}

				this.morphTargets.normal = morphTargetsNormal;

			}

			// skins

			var skinIndices = geometry.skinIndices;
			var skinWeights = geometry.skinWeights;

			var hasSkinIndices = skinIndices.length === vertices.length;
			var hasSkinWeights = skinWeights.length === vertices.length;

			//

			if ( vertices.length > 0 && faces.length === 0 ) {

				console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' );

			}

			for ( var i = 0; i < faces.length; i ++ ) {

				var face = faces[ i ];

				this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );

				var vertexNormals = face.vertexNormals;

				if ( vertexNormals.length === 3 ) {

					this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );

				} else {

					var normal = face.normal;

					this.normals.push( normal, normal, normal );

				}

				var vertexColors = face.vertexColors;

				if ( vertexColors.length === 3 ) {

					this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );

				} else {

					var color = face.color;

					this.colors.push( color, color, color );

				}

				if ( hasFaceVertexUv === true ) {

					var vertexUvs = faceVertexUvs[ 0 ][ i ];

					if ( vertexUvs !== undefined ) {

						this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );

					} else {

						console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );

						this.uvs.push( new Vector2(), new Vector2(), new Vector2() );

					}

				}

				if ( hasFaceVertexUv2 === true ) {

					var vertexUvs = faceVertexUvs[ 1 ][ i ];

					if ( vertexUvs !== undefined ) {

						this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );

					} else {

						console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );

						this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );

					}

				}

				// morphs

				for ( var j = 0; j < morphTargetsLength; j ++ ) {

					var morphTarget = morphTargets[ j ].vertices;

					morphTargetsPosition[ j ].data.push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );

				}

				for ( var j = 0; j < morphNormalsLength; j ++ ) {

					var morphNormal = morphNormals[ j ].vertexNormals[ i ];

					morphTargetsNormal[ j ].data.push( morphNormal.a, morphNormal.b, morphNormal.c );

				}

				// skins

				if ( hasSkinIndices ) {

					this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );

				}

				if ( hasSkinWeights ) {

					this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );

				}

			}

			this.computeGroups( geometry );

			this.verticesNeedUpdate = geometry.verticesNeedUpdate;
			this.normalsNeedUpdate = geometry.normalsNeedUpdate;
			this.colorsNeedUpdate = geometry.colorsNeedUpdate;
			this.uvsNeedUpdate = geometry.uvsNeedUpdate;
			this.groupsNeedUpdate = geometry.groupsNeedUpdate;

			if ( geometry.boundingSphere !== null ) {

				this.boundingSphere = geometry.boundingSphere.clone();

			}

			if ( geometry.boundingBox !== null ) {

				this.boundingBox = geometry.boundingBox.clone();

			}

			return this;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function arrayMax( array ) {

		if ( array.length === 0 ) { return - Infinity; }

		var max = array[ 0 ];

		for ( var i = 1, l = array.length; i < l; ++ i ) {

			if ( array[ i ] > max ) { max = array[ i ]; }

		}

		return max;

	}

	/**
	 * @author alteredq / http://alteredqualia.com/
	 * @author mrdoob / http://mrdoob.com/
	 */

	var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id

	var _m1$2 = new Matrix4();
	var _obj = new Object3D();
	var _offset = new Vector3();
	var _box$2 = new Box3();
	var _boxMorphTargets = new Box3();
	var _vector$4 = new Vector3();

	function BufferGeometry() {

		Object.defineProperty( this, 'id', { value: _bufferGeometryId += 2 } );

		this.uuid = MathUtils.generateUUID();

		this.name = '';
		this.type = 'BufferGeometry';

		this.index = null;
		this.attributes = {};

		this.morphAttributes = {};
		this.morphTargetsRelative = false;

		this.groups = [];

		this.boundingBox = null;
		this.boundingSphere = null;

		this.drawRange = { start: 0, count: Infinity };

		this.userData = {};

	}

	BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {

		constructor: BufferGeometry,

		isBufferGeometry: true,

		getIndex: function () {

			return this.index;

		},

		setIndex: function ( index ) {

			if ( Array.isArray( index ) ) {

				this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );

			} else {

				this.index = index;

			}

		},

		getAttribute: function ( name ) {

			return this.attributes[ name ];

		},

		setAttribute: function ( name, attribute ) {

			this.attributes[ name ] = attribute;

			return this;

		},

		deleteAttribute: function ( name ) {

			delete this.attributes[ name ];

			return this;

		},

		addGroup: function ( start, count, materialIndex ) {

			this.groups.push( {

				start: start,
				count: count,
				materialIndex: materialIndex !== undefined ? materialIndex : 0

			} );

		},

		clearGroups: function () {

			this.groups = [];

		},

		setDrawRange: function ( start, count ) {

			this.drawRange.start = start;
			this.drawRange.count = count;

		},

		applyMatrix4: function ( matrix ) {

			var position = this.attributes.position;

			if ( position !== undefined ) {

				position.applyMatrix4( matrix );

				position.needsUpdate = true;

			}

			var normal = this.attributes.normal;

			if ( normal !== undefined ) {

				var normalMatrix = new Matrix3().getNormalMatrix( matrix );

				normal.applyNormalMatrix( normalMatrix );

				normal.needsUpdate = true;

			}

			var tangent = this.attributes.tangent;

			if ( tangent !== undefined ) {

				tangent.transformDirection( matrix );

				tangent.needsUpdate = true;

			}

			if ( this.boundingBox !== null ) {

				this.computeBoundingBox();

			}

			if ( this.boundingSphere !== null ) {

				this.computeBoundingSphere();

			}

			return this;

		},

		rotateX: function ( angle ) {

			// rotate geometry around world x-axis

			_m1$2.makeRotationX( angle );

			this.applyMatrix4( _m1$2 );

			return this;

		},

		rotateY: function ( angle ) {

			// rotate geometry around world y-axis

			_m1$2.makeRotationY( angle );

			this.applyMatrix4( _m1$2 );

			return this;

		},

		rotateZ: function ( angle ) {

			// rotate geometry around world z-axis

			_m1$2.makeRotationZ( angle );

			this.applyMatrix4( _m1$2 );

			return this;

		},

		translate: function ( x, y, z ) {

			// translate geometry

			_m1$2.makeTranslation( x, y, z );

			this.applyMatrix4( _m1$2 );

			return this;

		},

		scale: function ( x, y, z ) {

			// scale geometry

			_m1$2.makeScale( x, y, z );

			this.applyMatrix4( _m1$2 );

			return this;

		},

		lookAt: function ( vector ) {

			_obj.lookAt( vector );

			_obj.updateMatrix();

			this.applyMatrix4( _obj.matrix );

			return this;

		},

		center: function () {

			this.computeBoundingBox();

			this.boundingBox.getCenter( _offset ).negate();

			this.translate( _offset.x, _offset.y, _offset.z );

			return this;

		},

		setFromObject: function ( object ) {

			// console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );

			var geometry = object.geometry;

			if ( object.isPoints || object.isLine ) {

				var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
				var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );

				this.setAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
				this.setAttribute( 'color', colors.copyColorsArray( geometry.colors ) );

				if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {

					var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );

					this.setAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );

				}

				if ( geometry.boundingSphere !== null ) {

					this.boundingSphere = geometry.boundingSphere.clone();

				}

				if ( geometry.boundingBox !== null ) {

					this.boundingBox = geometry.boundingBox.clone();

				}

			} else if ( object.isMesh ) {

				if ( geometry && geometry.isGeometry ) {

					this.fromGeometry( geometry );

				}

			}

			return this;

		},

		setFromPoints: function ( points ) {

			var position = [];

			for ( var i = 0, l = points.length; i < l; i ++ ) {

				var point = points[ i ];
				position.push( point.x, point.y, point.z || 0 );

			}

			this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );

			return this;

		},

		updateFromObject: function ( object ) {

			var geometry = object.geometry;

			if ( object.isMesh ) {

				var direct = geometry.__directGeometry;

				if ( geometry.elementsNeedUpdate === true ) {

					direct = undefined;
					geometry.elementsNeedUpdate = false;

				}

				if ( direct === undefined ) {

					return this.fromGeometry( geometry );

				}

				direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
				direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
				direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
				direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
				direct.groupsNeedUpdate = geometry.groupsNeedUpdate;

				geometry.verticesNeedUpdate = false;
				geometry.normalsNeedUpdate = false;
				geometry.colorsNeedUpdate = false;
				geometry.uvsNeedUpdate = false;
				geometry.groupsNeedUpdate = false;

				geometry = direct;

			}

			var attribute;

			if ( geometry.verticesNeedUpdate === true ) {

				attribute = this.attributes.position;

				if ( attribute !== undefined ) {

					attribute.copyVector3sArray( geometry.vertices );
					attribute.needsUpdate = true;

				}

				geometry.verticesNeedUpdate = false;

			}

			if ( geometry.normalsNeedUpdate === true ) {

				attribute = this.attributes.normal;

				if ( attribute !== undefined ) {

					attribute.copyVector3sArray( geometry.normals );
					attribute.needsUpdate = true;

				}

				geometry.normalsNeedUpdate = false;

			}

			if ( geometry.colorsNeedUpdate === true ) {

				attribute = this.attributes.color;

				if ( attribute !== undefined ) {

					attribute.copyColorsArray( geometry.colors );
					attribute.needsUpdate = true;

				}

				geometry.colorsNeedUpdate = false;

			}

			if ( geometry.uvsNeedUpdate ) {

				attribute = this.attributes.uv;

				if ( attribute !== undefined ) {

					attribute.copyVector2sArray( geometry.uvs );
					attribute.needsUpdate = true;

				}

				geometry.uvsNeedUpdate = false;

			}

			if ( geometry.lineDistancesNeedUpdate ) {

				attribute = this.attributes.lineDistance;

				if ( attribute !== undefined ) {

					attribute.copyArray( geometry.lineDistances );
					attribute.needsUpdate = true;

				}

				geometry.lineDistancesNeedUpdate = false;

			}

			if ( geometry.groupsNeedUpdate ) {

				geometry.computeGroups( object.geometry );
				this.groups = geometry.groups;

				geometry.groupsNeedUpdate = false;

			}

			return this;

		},

		fromGeometry: function ( geometry ) {

			geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );

			return this.fromDirectGeometry( geometry.__directGeometry );

		},

		fromDirectGeometry: function ( geometry ) {

			var positions = new Float32Array( geometry.vertices.length * 3 );
			this.setAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );

			if ( geometry.normals.length > 0 ) {

				var normals = new Float32Array( geometry.normals.length * 3 );
				this.setAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );

			}

			if ( geometry.colors.length > 0 ) {

				var colors = new Float32Array( geometry.colors.length * 3 );
				this.setAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );

			}

			if ( geometry.uvs.length > 0 ) {

				var uvs = new Float32Array( geometry.uvs.length * 2 );
				this.setAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );

			}

			if ( geometry.uvs2.length > 0 ) {

				var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
				this.setAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );

			}

			// groups

			this.groups = geometry.groups;

			// morphs

			for ( var name in geometry.morphTargets ) {

				var array = [];
				var morphTargets = geometry.morphTargets[ name ];

				for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {

					var morphTarget = morphTargets[ i ];

					var attribute = new Float32BufferAttribute( morphTarget.data.length * 3, 3 );
					attribute.name = morphTarget.name;

					array.push( attribute.copyVector3sArray( morphTarget.data ) );

				}

				this.morphAttributes[ name ] = array;

			}

			// skinning

			if ( geometry.skinIndices.length > 0 ) {

				var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
				this.setAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );

			}

			if ( geometry.skinWeights.length > 0 ) {

				var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
				this.setAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );

			}

			//

			if ( geometry.boundingSphere !== null ) {

				this.boundingSphere = geometry.boundingSphere.clone();

			}

			if ( geometry.boundingBox !== null ) {

				this.boundingBox = geometry.boundingBox.clone();

			}

			return this;

		},

		computeBoundingBox: function () {

			if ( this.boundingBox === null ) {

				this.boundingBox = new Box3();

			}

			var position = this.attributes.position;
			var morphAttributesPosition = this.morphAttributes.position;

			if ( position !== undefined ) {

				this.boundingBox.setFromBufferAttribute( position );

				// process morph attributes if present

				if ( morphAttributesPosition ) {

					for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {

						var morphAttribute = morphAttributesPosition[ i ];
						_box$2.setFromBufferAttribute( morphAttribute );

						if ( this.morphTargetsRelative ) {

							_vector$4.addVectors( this.boundingBox.min, _box$2.min );
							this.boundingBox.expandByPoint( _vector$4 );

							_vector$4.addVectors( this.boundingBox.max, _box$2.max );
							this.boundingBox.expandByPoint( _vector$4 );

						} else {

							this.boundingBox.expandByPoint( _box$2.min );
							this.boundingBox.expandByPoint( _box$2.max );

						}

					}

				}

			} else {

				this.boundingBox.makeEmpty();

			}

			if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {

				console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );

			}

		},

		computeBoundingSphere: function () {

			if ( this.boundingSphere === null ) {

				this.boundingSphere = new Sphere();

			}

			var position = this.attributes.position;
			var morphAttributesPosition = this.morphAttributes.position;

			if ( position ) {

				// first, find the center of the bounding sphere

				var center = this.boundingSphere.center;

				_box$2.setFromBufferAttribute( position );

				// process morph attributes if present

				if ( morphAttributesPosition ) {

					for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {

						var morphAttribute = morphAttributesPosition[ i ];
						_boxMorphTargets.setFromBufferAttribute( morphAttribute );

						if ( this.morphTargetsRelative ) {

							_vector$4.addVectors( _box$2.min, _boxMorphTargets.min );
							_box$2.expandByPoint( _vector$4 );

							_vector$4.addVectors( _box$2.max, _boxMorphTargets.max );
							_box$2.expandByPoint( _vector$4 );

						} else {

							_box$2.expandByPoint( _boxMorphTargets.min );
							_box$2.expandByPoint( _boxMorphTargets.max );

						}

					}

				}

				_box$2.getCenter( center );

				// second, try to find a boundingSphere with a radius smaller than the
				// boundingSphere of the boundingBox: sqrt(3) smaller in the best case

				var maxRadiusSq = 0;

				for ( var i = 0, il = position.count; i < il; i ++ ) {

					_vector$4.fromBufferAttribute( position, i );

					maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );

				}

				// process morph attributes if present

				if ( morphAttributesPosition ) {

					for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {

						var morphAttribute = morphAttributesPosition[ i ];
						var morphTargetsRelative = this.morphTargetsRelative;

						for ( var j = 0, jl = morphAttribute.count; j < jl; j ++ ) {

							_vector$4.fromBufferAttribute( morphAttribute, j );

							if ( morphTargetsRelative ) {

								_offset.fromBufferAttribute( position, j );
								_vector$4.add( _offset );

							}

							maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );

						}

					}

				}

				this.boundingSphere.radius = Math.sqrt( maxRadiusSq );

				if ( isNaN( this.boundingSphere.radius ) ) {

					console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );

				}

			}

		},

		computeFaceNormals: function () {

			// backwards compatibility

		},

		computeVertexNormals: function () {

			var index = this.index;
			var attributes = this.attributes;

			if ( attributes.position ) {

				var positions = attributes.position.array;

				if ( attributes.normal === undefined ) {

					this.setAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );

				} else {

					// reset existing normals to zero

					var array = attributes.normal.array;

					for ( var i = 0, il = array.length; i < il; i ++ ) {

						array[ i ] = 0;

					}

				}

				var normals = attributes.normal.array;

				var vA, vB, vC;
				var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
				var cb = new Vector3(), ab = new Vector3();

				// indexed elements

				if ( index ) {

					var indices = index.array;

					for ( var i = 0, il = index.count; i < il; i += 3 ) {

						vA = indices[ i + 0 ] * 3;
						vB = indices[ i + 1 ] * 3;
						vC = indices[ i + 2 ] * 3;

						pA.fromArray( positions, vA );
						pB.fromArray( positions, vB );
						pC.fromArray( positions, vC );

						cb.subVectors( pC, pB );
						ab.subVectors( pA, pB );
						cb.cross( ab );

						normals[ vA ] += cb.x;
						normals[ vA + 1 ] += cb.y;
						normals[ vA + 2 ] += cb.z;

						normals[ vB ] += cb.x;
						normals[ vB + 1 ] += cb.y;
						normals[ vB + 2 ] += cb.z;

						normals[ vC ] += cb.x;
						normals[ vC + 1 ] += cb.y;
						normals[ vC + 2 ] += cb.z;

					}

				} else {

					// non-indexed elements (unconnected triangle soup)

					for ( var i = 0, il = positions.length; i < il; i += 9 ) {

						pA.fromArray( positions, i );
						pB.fromArray( positions, i + 3 );
						pC.fromArray( positions, i + 6 );

						cb.subVectors( pC, pB );
						ab.subVectors( pA, pB );
						cb.cross( ab );

						normals[ i ] = cb.x;
						normals[ i + 1 ] = cb.y;
						normals[ i + 2 ] = cb.z;

						normals[ i + 3 ] = cb.x;
						normals[ i + 4 ] = cb.y;
						normals[ i + 5 ] = cb.z;

						normals[ i + 6 ] = cb.x;
						normals[ i + 7 ] = cb.y;
						normals[ i + 8 ] = cb.z;

					}

				}

				this.normalizeNormals();

				attributes.normal.needsUpdate = true;

			}

		},

		merge: function ( geometry, offset ) {

			if ( ! ( geometry && geometry.isBufferGeometry ) ) {

				console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
				return;

			}

			if ( offset === undefined ) {

				offset = 0;

				console.warn(
					'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
					+ 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
				);

			}

			var attributes = this.attributes;

			for ( var key in attributes ) {

				if ( geometry.attributes[ key ] === undefined ) { continue; }

				var attribute1 = attributes[ key ];
				var attributeArray1 = attribute1.array;

				var attribute2 = geometry.attributes[ key ];
				var attributeArray2 = attribute2.array;

				var attributeOffset = attribute2.itemSize * offset;
				var length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );

				for ( var i = 0, j = attributeOffset; i < length; i ++, j ++ ) {

					attributeArray1[ j ] = attributeArray2[ i ];

				}

			}

			return this;

		},

		normalizeNormals: function () {

			var normals = this.attributes.normal;

			for ( var i = 0, il = normals.count; i < il; i ++ ) {

				_vector$4.x = normals.getX( i );
				_vector$4.y = normals.getY( i );
				_vector$4.z = normals.getZ( i );

				_vector$4.normalize();

				normals.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z );

			}

		},

		toNonIndexed: function () {

			function convertBufferAttribute( attribute, indices ) {

				var array = attribute.array;
				var itemSize = attribute.itemSize;

				var array2 = new array.constructor( indices.length * itemSize );

				var index = 0, index2 = 0;

				for ( var i = 0, l = indices.length; i < l; i ++ ) {

					index = indices[ i ] * itemSize;

					for ( var j = 0; j < itemSize; j ++ ) {

						array2[ index2 ++ ] = array[ index ++ ];

					}

				}

				return new BufferAttribute( array2, itemSize );

			}

			//

			if ( this.index === null ) {

				console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
				return this;

			}

			var geometry2 = new BufferGeometry();

			var indices = this.index.array;
			var attributes = this.attributes;

			// attributes

			for ( var name in attributes ) {

				var attribute = attributes[ name ];

				var newAttribute = convertBufferAttribute( attribute, indices );

				geometry2.setAttribute( name, newAttribute );

			}

			// morph attributes

			var morphAttributes = this.morphAttributes;

			for ( name in morphAttributes ) {

				var morphArray = [];
				var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes

				for ( var i = 0, il = morphAttribute.length; i < il; i ++ ) {

					var attribute = morphAttribute[ i ];

					var newAttribute = convertBufferAttribute( attribute, indices );

					morphArray.push( newAttribute );

				}

				geometry2.morphAttributes[ name ] = morphArray;

			}

			geometry2.morphTargetsRelative = this.morphTargetsRelative;

			// groups

			var groups = this.groups;

			for ( var i = 0, l = groups.length; i < l; i ++ ) {

				var group = groups[ i ];
				geometry2.addGroup( group.start, group.count, group.materialIndex );

			}

			return geometry2;

		},

		toJSON: function () {

			var data = {
				metadata: {
					version: 4.5,
					type: 'BufferGeometry',
					generator: 'BufferGeometry.toJSON'
				}
			};

			// standard BufferGeometry serialization

			data.uuid = this.uuid;
			data.type = this.type;
			if ( this.name !== '' ) { data.name = this.name; }
			if ( Object.keys( this.userData ).length > 0 ) { data.userData = this.userData; }

			if ( this.parameters !== undefined ) {

				var parameters = this.parameters;

				for ( var key in parameters ) {

					if ( parameters[ key ] !== undefined ) { data[ key ] = parameters[ key ]; }

				}

				return data;

			}

			data.data = { attributes: {} };

			var index = this.index;

			if ( index !== null ) {

				data.data.index = {
					type: index.array.constructor.name,
					array: Array.prototype.slice.call( index.array )
				};

			}

			var attributes = this.attributes;

			for ( var key in attributes ) {

				var attribute = attributes[ key ];

				var attributeData = attribute.toJSON();

				if ( attribute.name !== '' ) { attributeData.name = attribute.name; }

				data.data.attributes[ key ] = attributeData;

			}

			var morphAttributes = {};
			var hasMorphAttributes = false;

			for ( var key in this.morphAttributes ) {

				var attributeArray = this.morphAttributes[ key ];

				var array = [];

				for ( var i = 0, il = attributeArray.length; i < il; i ++ ) {

					var attribute = attributeArray[ i ];

					var attributeData = attribute.toJSON();

					if ( attribute.name !== '' ) { attributeData.name = attribute.name; }

					array.push( attributeData );

				}

				if ( array.length > 0 ) {

					morphAttributes[ key ] = array;

					hasMorphAttributes = true;

				}

			}

			if ( hasMorphAttributes ) {

				data.data.morphAttributes = morphAttributes;
				data.data.morphTargetsRelative = this.morphTargetsRelative;

			}

			var groups = this.groups;

			if ( groups.length > 0 ) {

				data.data.groups = JSON.parse( JSON.stringify( groups ) );

			}

			var boundingSphere = this.boundingSphere;

			if ( boundingSphere !== null ) {

				data.data.boundingSphere = {
					center: boundingSphere.center.toArray(),
					radius: boundingSphere.radius
				};

			}

			return data;

		},

		clone: function () {

			/*
			 // Handle primitives

			 var parameters = this.parameters;

			 if ( parameters !== undefined ) {

			 var values = [];

			 for ( var key in parameters ) {

			 values.push( parameters[ key ] );

			 }

			 var geometry = Object.create( this.constructor.prototype );
			 this.constructor.apply( geometry, values );
			 return geometry;

			 }

			 return new this.constructor().copy( this );
			 */

			return new BufferGeometry().copy( this );

		},

		copy: function ( source ) {

			var name, i, l;

			// reset

			this.index = null;
			this.attributes = {};
			this.morphAttributes = {};
			this.groups = [];
			this.boundingBox = null;
			this.boundingSphere = null;

			// name

			this.name = source.name;

			// index

			var index = source.index;

			if ( index !== null ) {

				this.setIndex( index.clone() );

			}

			// attributes

			var attributes = source.attributes;

			for ( name in attributes ) {

				var attribute = attributes[ name ];
				this.setAttribute( name, attribute.clone() );

			}

			// morph attributes

			var morphAttributes = source.morphAttributes;

			for ( name in morphAttributes ) {

				var array = [];
				var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes

				for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {

					array.push( morphAttribute[ i ].clone() );

				}

				this.morphAttributes[ name ] = array;

			}

			this.morphTargetsRelative = source.morphTargetsRelative;

			// groups

			var groups = source.groups;

			for ( i = 0, l = groups.length; i < l; i ++ ) {

				var group = groups[ i ];
				this.addGroup( group.start, group.count, group.materialIndex );

			}

			// bounding box

			var boundingBox = source.boundingBox;

			if ( boundingBox !== null ) {

				this.boundingBox = boundingBox.clone();

			}

			// bounding sphere

			var boundingSphere = source.boundingSphere;

			if ( boundingSphere !== null ) {

				this.boundingSphere = boundingSphere.clone();

			}

			// draw range

			this.drawRange.start = source.drawRange.start;
			this.drawRange.count = source.drawRange.count;

			// user data

			this.userData = source.userData;

			return this;

		},

		dispose: function () {

			this.dispatchEvent( { type: 'dispose' } );

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author alteredq / http://alteredqualia.com/
	 * @author mikael emtinger / http://gomo.se/
	 * @author jonobr1 / http://jonobr1.com/
	 */

	var _inverseMatrix = new Matrix4();
	var _ray = new Ray();
	var _sphere = new Sphere();

	var _vA = new Vector3();
	var _vB = new Vector3();
	var _vC = new Vector3();

	var _tempA = new Vector3();
	var _tempB = new Vector3();
	var _tempC = new Vector3();

	var _morphA = new Vector3();
	var _morphB = new Vector3();
	var _morphC = new Vector3();

	var _uvA = new Vector2();
	var _uvB = new Vector2();
	var _uvC = new Vector2();

	var _intersectionPoint = new Vector3();
	var _intersectionPointWorld = new Vector3();

	function Mesh( geometry, material ) {

		Object3D.call( this );

		this.type = 'Mesh';

		this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
		this.material = material !== undefined ? material : new MeshBasicMaterial();

		this.updateMorphTargets();

	}

	Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {

		constructor: Mesh,

		isMesh: true,

		copy: function ( source ) {

			Object3D.prototype.copy.call( this, source );

			if ( source.morphTargetInfluences !== undefined ) {

				this.morphTargetInfluences = source.morphTargetInfluences.slice();

			}

			if ( source.morphTargetDictionary !== undefined ) {

				this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );

			}

			return this;

		},

		updateMorphTargets: function () {

			var geometry = this.geometry;
			var m, ml, name;

			if ( geometry.isBufferGeometry ) {

				var morphAttributes = geometry.morphAttributes;
				var keys = Object.keys( morphAttributes );

				if ( keys.length > 0 ) {

					var morphAttribute = morphAttributes[ keys[ 0 ] ];

					if ( morphAttribute !== undefined ) {

						this.morphTargetInfluences = [];
						this.morphTargetDictionary = {};

						for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {

							name = morphAttribute[ m ].name || String( m );

							this.morphTargetInfluences.push( 0 );
							this.morphTargetDictionary[ name ] = m;

						}

					}

				}

			} else {

				var morphTargets = geometry.morphTargets;

				if ( morphTargets !== undefined && morphTargets.length > 0 ) {

					console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );

				}

			}

		},

		raycast: function ( raycaster, intersects ) {

			var geometry = this.geometry;
			var material = this.material;
			var matrixWorld = this.matrixWorld;

			if ( material === undefined ) { return; }

			// Checking boundingSphere distance to ray

			if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); }

			_sphere.copy( geometry.boundingSphere );
			_sphere.applyMatrix4( matrixWorld );

			if ( raycaster.ray.intersectsSphere( _sphere ) === false ) { return; }

			//

			_inverseMatrix.getInverse( matrixWorld );
			_ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );

			// Check boundingBox before continuing

			if ( geometry.boundingBox !== null ) {

				if ( _ray.intersectsBox( geometry.boundingBox ) === false ) { return; }

			}

			var intersection;

			if ( geometry.isBufferGeometry ) {

				var a, b, c;
				var index = geometry.index;
				var position = geometry.attributes.position;
				var morphPosition = geometry.morphAttributes.position;
				var morphTargetsRelative = geometry.morphTargetsRelative;
				var uv = geometry.attributes.uv;
				var uv2 = geometry.attributes.uv2;
				var groups = geometry.groups;
				var drawRange = geometry.drawRange;
				var i, j, il, jl;
				var group, groupMaterial;
				var start, end;

				if ( index !== null ) {

					// indexed buffer geometry

					if ( Array.isArray( material ) ) {

						for ( i = 0, il = groups.length; i < il; i ++ ) {

							group = groups[ i ];
							groupMaterial = material[ group.materialIndex ];

							start = Math.max( group.start, drawRange.start );
							end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );

							for ( j = start, jl = end; j < jl; j += 3 ) {

								a = index.getX( j );
								b = index.getX( j + 1 );
								c = index.getX( j + 2 );

								intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );

								if ( intersection ) {

									intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
									intersection.face.materialIndex = group.materialIndex;
									intersects.push( intersection );

								}

							}

						}

					} else {

						start = Math.max( 0, drawRange.start );
						end = Math.min( index.count, ( drawRange.start + drawRange.count ) );

						for ( i = start, il = end; i < il; i += 3 ) {

							a = index.getX( i );
							b = index.getX( i + 1 );
							c = index.getX( i + 2 );

							intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );

							if ( intersection ) {

								intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
								intersects.push( intersection );

							}

						}

					}

				} else if ( position !== undefined ) {

					// non-indexed buffer geometry

					if ( Array.isArray( material ) ) {

						for ( i = 0, il = groups.length; i < il; i ++ ) {

							group = groups[ i ];
							groupMaterial = material[ group.materialIndex ];

							start = Math.max( group.start, drawRange.start );
							end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );

							for ( j = start, jl = end; j < jl; j += 3 ) {

								a = j;
								b = j + 1;
								c = j + 2;

								intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );

								if ( intersection ) {

									intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
									intersection.face.materialIndex = group.materialIndex;
									intersects.push( intersection );

								}

							}

						}

					} else {

						start = Math.max( 0, drawRange.start );
						end = Math.min( position.count, ( drawRange.start + drawRange.count ) );

						for ( i = start, il = end; i < il; i += 3 ) {

							a = i;
							b = i + 1;
							c = i + 2;

							intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );

							if ( intersection ) {

								intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
								intersects.push( intersection );

							}

						}

					}

				}

			} else if ( geometry.isGeometry ) {

				var fvA, fvB, fvC;
				var isMultiMaterial = Array.isArray( material );

				var vertices = geometry.vertices;
				var faces = geometry.faces;
				var uvs;

				var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
				if ( faceVertexUvs.length > 0 ) { uvs = faceVertexUvs; }

				for ( var f = 0, fl = faces.length; f < fl; f ++ ) {

					var face = faces[ f ];
					var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;

					if ( faceMaterial === undefined ) { continue; }

					fvA = vertices[ face.a ];
					fvB = vertices[ face.b ];
					fvC = vertices[ face.c ];

					intersection = checkIntersection( this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint );

					if ( intersection ) {

						if ( uvs && uvs[ f ] ) {

							var uvs_f = uvs[ f ];
							_uvA.copy( uvs_f[ 0 ] );
							_uvB.copy( uvs_f[ 1 ] );
							_uvC.copy( uvs_f[ 2 ] );

							intersection.uv = Triangle.getUV( _intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2() );

						}

						intersection.face = face;
						intersection.faceIndex = f;
						intersects.push( intersection );

					}

				}

			}

		},

		clone: function () {

			return new this.constructor( this.geometry, this.material ).copy( this );

		}

	} );

	function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {

		var intersect;

		if ( material.side === BackSide ) {

			intersect = ray.intersectTriangle( pC, pB, pA, true, point );

		} else {

			intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );

		}

		if ( intersect === null ) { return null; }

		_intersectionPointWorld.copy( point );
		_intersectionPointWorld.applyMatrix4( object.matrixWorld );

		var distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );

		if ( distance < raycaster.near || distance > raycaster.far ) { return null; }

		return {
			distance: distance,
			point: _intersectionPointWorld.clone(),
			object: object
		};

	}

	function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {

		_vA.fromBufferAttribute( position, a );
		_vB.fromBufferAttribute( position, b );
		_vC.fromBufferAttribute( position, c );

		var morphInfluences = object.morphTargetInfluences;

		if ( material.morphTargets && morphPosition && morphInfluences ) {

			_morphA.set( 0, 0, 0 );
			_morphB.set( 0, 0, 0 );
			_morphC.set( 0, 0, 0 );

			for ( var i = 0, il = morphPosition.length; i < il; i ++ ) {

				var influence = morphInfluences[ i ];
				var morphAttribute = morphPosition[ i ];

				if ( influence === 0 ) { continue; }

				_tempA.fromBufferAttribute( morphAttribute, a );
				_tempB.fromBufferAttribute( morphAttribute, b );
				_tempC.fromBufferAttribute( morphAttribute, c );

				if ( morphTargetsRelative ) {

					_morphA.addScaledVector( _tempA, influence );
					_morphB.addScaledVector( _tempB, influence );
					_morphC.addScaledVector( _tempC, influence );

				} else {

					_morphA.addScaledVector( _tempA.sub( _vA ), influence );
					_morphB.addScaledVector( _tempB.sub( _vB ), influence );
					_morphC.addScaledVector( _tempC.sub( _vC ), influence );

				}

			}

			_vA.add( _morphA );
			_vB.add( _morphB );
			_vC.add( _morphC );

		}

		var intersection = checkIntersection( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );

		if ( intersection ) {

			if ( uv ) {

				_uvA.fromBufferAttribute( uv, a );
				_uvB.fromBufferAttribute( uv, b );
				_uvC.fromBufferAttribute( uv, c );

				intersection.uv = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );

			}

			if ( uv2 ) {

				_uvA.fromBufferAttribute( uv2, a );
				_uvB.fromBufferAttribute( uv2, b );
				_uvC.fromBufferAttribute( uv2, c );

				intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );

			}

			var face = new Face3( a, b, c );
			Triangle.getNormal( _vA, _vB, _vC, face.normal );

			intersection.face = face;

		}

		return intersection;

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author kile / http://kile.stravaganza.org/
	 * @author alteredq / http://alteredqualia.com/
	 * @author mikael emtinger / http://gomo.se/
	 * @author zz85 / http://www.lab4games.net/zz85/blog
	 * @author bhouston / http://clara.io
	 */

	var _geometryId = 0; // Geometry uses even numbers as Id
	var _m1$3 = new Matrix4();
	var _obj$1 = new Object3D();
	var _offset$1 = new Vector3();

	function Geometry() {

		Object.defineProperty( this, 'id', { value: _geometryId += 2 } );

		this.uuid = MathUtils.generateUUID();

		this.name = '';
		this.type = 'Geometry';

		this.vertices = [];
		this.colors = [];
		this.faces = [];
		this.faceVertexUvs = [[]];

		this.morphTargets = [];
		this.morphNormals = [];

		this.skinWeights = [];
		this.skinIndices = [];

		this.lineDistances = [];

		this.boundingBox = null;
		this.boundingSphere = null;

		// update flags

		this.elementsNeedUpdate = false;
		this.verticesNeedUpdate = false;
		this.uvsNeedUpdate = false;
		this.normalsNeedUpdate = false;
		this.colorsNeedUpdate = false;
		this.lineDistancesNeedUpdate = false;
		this.groupsNeedUpdate = false;

	}

	Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {

		constructor: Geometry,

		isGeometry: true,

		applyMatrix4: function ( matrix ) {

			var normalMatrix = new Matrix3().getNormalMatrix( matrix );

			for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {

				var vertex = this.vertices[ i ];
				vertex.applyMatrix4( matrix );

			}

			for ( var i = 0, il = this.faces.length; i < il; i ++ ) {

				var face = this.faces[ i ];
				face.normal.applyMatrix3( normalMatrix ).normalize();

				for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {

					face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();

				}

			}

			if ( this.boundingBox !== null ) {

				this.computeBoundingBox();

			}

			if ( this.boundingSphere !== null ) {

				this.computeBoundingSphere();

			}

			this.verticesNeedUpdate = true;
			this.normalsNeedUpdate = true;

			return this;

		},

		rotateX: function ( angle ) {

			// rotate geometry around world x-axis

			_m1$3.makeRotationX( angle );

			this.applyMatrix4( _m1$3 );

			return this;

		},

		rotateY: function ( angle ) {

			// rotate geometry around world y-axis

			_m1$3.makeRotationY( angle );

			this.applyMatrix4( _m1$3 );

			return this;

		},

		rotateZ: function ( angle ) {

			// rotate geometry around world z-axis

			_m1$3.makeRotationZ( angle );

			this.applyMatrix4( _m1$3 );

			return this;

		},

		translate: function ( x, y, z ) {

			// translate geometry

			_m1$3.makeTranslation( x, y, z );

			this.applyMatrix4( _m1$3 );

			return this;

		},

		scale: function ( x, y, z ) {

			// scale geometry

			_m1$3.makeScale( x, y, z );

			this.applyMatrix4( _m1$3 );

			return this;

		},

		lookAt: function ( vector ) {

			_obj$1.lookAt( vector );

			_obj$1.updateMatrix();

			this.applyMatrix4( _obj$1.matrix );

			return this;

		},

		fromBufferGeometry: function ( geometry ) {

			var scope = this;

			var indices = geometry.index !== null ? geometry.index.array : undefined;
			var attributes = geometry.attributes;

			if ( attributes.position === undefined ) {

				console.error( 'THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.' );
				return this;

			}

			var positions = attributes.position.array;
			var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
			var colors = attributes.color !== undefined ? attributes.color.array : undefined;
			var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
			var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;

			if ( uvs2 !== undefined ) { this.faceVertexUvs[ 1 ] = []; }

			for ( var i = 0; i < positions.length; i += 3 ) {

				scope.vertices.push( new Vector3().fromArray( positions, i ) );

				if ( colors !== undefined ) {

					scope.colors.push( new Color().fromArray( colors, i ) );

				}

			}

			function addFace( a, b, c, materialIndex ) {

				var vertexColors = ( colors === undefined ) ? [] : [
					scope.colors[ a ].clone(),
					scope.colors[ b ].clone(),
					scope.colors[ c ].clone() ];

				var vertexNormals = ( normals === undefined ) ? [] : [
					new Vector3().fromArray( normals, a * 3 ),
					new Vector3().fromArray( normals, b * 3 ),
					new Vector3().fromArray( normals, c * 3 )
				];

				var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );

				scope.faces.push( face );

				if ( uvs !== undefined ) {

					scope.faceVertexUvs[ 0 ].push( [
						new Vector2().fromArray( uvs, a * 2 ),
						new Vector2().fromArray( uvs, b * 2 ),
						new Vector2().fromArray( uvs, c * 2 )
					] );

				}

				if ( uvs2 !== undefined ) {

					scope.faceVertexUvs[ 1 ].push( [
						new Vector2().fromArray( uvs2, a * 2 ),
						new Vector2().fromArray( uvs2, b * 2 ),
						new Vector2().fromArray( uvs2, c * 2 )
					] );

				}

			}

			var groups = geometry.groups;

			if ( groups.length > 0 ) {

				for ( var i = 0; i < groups.length; i ++ ) {

					var group = groups[ i ];

					var start = group.start;
					var count = group.count;

					for ( var j = start, jl = start + count; j < jl; j += 3 ) {

						if ( indices !== undefined ) {

							addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );

						} else {

							addFace( j, j + 1, j + 2, group.materialIndex );

						}

					}

				}

			} else {

				if ( indices !== undefined ) {

					for ( var i = 0; i < indices.length; i += 3 ) {

						addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );

					}

				} else {

					for ( var i = 0; i < positions.length / 3; i += 3 ) {

						addFace( i, i + 1, i + 2 );

					}

				}

			}

			this.computeFaceNormals();

			if ( geometry.boundingBox !== null ) {

				this.boundingBox = geometry.boundingBox.clone();

			}

			if ( geometry.boundingSphere !== null ) {

				this.boundingSphere = geometry.boundingSphere.clone();

			}

			return this;

		},

		center: function () {

			this.computeBoundingBox();

			this.boundingBox.getCenter( _offset$1 ).negate();

			this.translate( _offset$1.x, _offset$1.y, _offset$1.z );

			return this;

		},

		normalize: function () {

			this.computeBoundingSphere();

			var center = this.boundingSphere.center;
			var radius = this.boundingSphere.radius;

			var s = radius === 0 ? 1 : 1.0 / radius;

			var matrix = new Matrix4();
			matrix.set(
				s, 0, 0, - s * center.x,
				0, s, 0, - s * center.y,
				0, 0, s, - s * center.z,
				0, 0, 0, 1
			);

			this.applyMatrix4( matrix );

			return this;

		},

		computeFaceNormals: function () {

			var cb = new Vector3(), ab = new Vector3();

			for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {

				var face = this.faces[ f ];

				var vA = this.vertices[ face.a ];
				var vB = this.vertices[ face.b ];
				var vC = this.vertices[ face.c ];

				cb.subVectors( vC, vB );
				ab.subVectors( vA, vB );
				cb.cross( ab );

				cb.normalize();

				face.normal.copy( cb );

			}

		},

		computeVertexNormals: function ( areaWeighted ) {

			if ( areaWeighted === undefined ) { areaWeighted = true; }

			var v, vl, f, fl, face, vertices;

			vertices = new Array( this.vertices.length );

			for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {

				vertices[ v ] = new Vector3();

			}

			if ( areaWeighted ) {

				// vertex normals weighted by triangle areas
				// http://www.iquilezles.org/www/articles/normals/normals.htm

				var vA, vB, vC;
				var cb = new Vector3(), ab = new Vector3();

				for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

					face = this.faces[ f ];

					vA = this.vertices[ face.a ];
					vB = this.vertices[ face.b ];
					vC = this.vertices[ face.c ];

					cb.subVectors( vC, vB );
					ab.subVectors( vA, vB );
					cb.cross( ab );

					vertices[ face.a ].add( cb );
					vertices[ face.b ].add( cb );
					vertices[ face.c ].add( cb );

				}

			} else {

				this.computeFaceNormals();

				for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

					face = this.faces[ f ];

					vertices[ face.a ].add( face.normal );
					vertices[ face.b ].add( face.normal );
					vertices[ face.c ].add( face.normal );

				}

			}

			for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {

				vertices[ v ].normalize();

			}

			for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

				face = this.faces[ f ];

				var vertexNormals = face.vertexNormals;

				if ( vertexNormals.length === 3 ) {

					vertexNormals[ 0 ].copy( vertices[ face.a ] );
					vertexNormals[ 1 ].copy( vertices[ face.b ] );
					vertexNormals[ 2 ].copy( vertices[ face.c ] );

				} else {

					vertexNormals[ 0 ] = vertices[ face.a ].clone();
					vertexNormals[ 1 ] = vertices[ face.b ].clone();
					vertexNormals[ 2 ] = vertices[ face.c ].clone();

				}

			}

			if ( this.faces.length > 0 ) {

				this.normalsNeedUpdate = true;

			}

		},

		computeFlatVertexNormals: function () {

			var f, fl, face;

			this.computeFaceNormals();

			for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

				face = this.faces[ f ];

				var vertexNormals = face.vertexNormals;

				if ( vertexNormals.length === 3 ) {

					vertexNormals[ 0 ].copy( face.normal );
					vertexNormals[ 1 ].copy( face.normal );
					vertexNormals[ 2 ].copy( face.normal );

				} else {

					vertexNormals[ 0 ] = face.normal.clone();
					vertexNormals[ 1 ] = face.normal.clone();
					vertexNormals[ 2 ] = face.normal.clone();

				}

			}

			if ( this.faces.length > 0 ) {

				this.normalsNeedUpdate = true;

			}

		},

		computeMorphNormals: function () {

			var i, il, f, fl, face;

			// save original normals
			// - create temp variables on first access
			//   otherwise just copy (for faster repeated calls)

			for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

				face = this.faces[ f ];

				if ( ! face.__originalFaceNormal ) {

					face.__originalFaceNormal = face.normal.clone();

				} else {

					face.__originalFaceNormal.copy( face.normal );

				}

				if ( ! face.__originalVertexNormals ) { face.__originalVertexNormals = []; }

				for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {

					if ( ! face.__originalVertexNormals[ i ] ) {

						face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();

					} else {

						face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );

					}

				}

			}

			// use temp geometry to compute face and vertex normals for each morph

			var tmpGeo = new Geometry();
			tmpGeo.faces = this.faces;

			for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {

				// create on first access

				if ( ! this.morphNormals[ i ] ) {

					this.morphNormals[ i ] = {};
					this.morphNormals[ i ].faceNormals = [];
					this.morphNormals[ i ].vertexNormals = [];

					var dstNormalsFace = this.morphNormals[ i ].faceNormals;
					var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;

					var faceNormal, vertexNormals;

					for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

						faceNormal = new Vector3();
						vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };

						dstNormalsFace.push( faceNormal );
						dstNormalsVertex.push( vertexNormals );

					}

				}

				var morphNormals = this.morphNormals[ i ];

				// set vertices to morph target

				tmpGeo.vertices = this.morphTargets[ i ].vertices;

				// compute morph normals

				tmpGeo.computeFaceNormals();
				tmpGeo.computeVertexNormals();

				// store morph normals

				var faceNormal, vertexNormals;

				for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

					face = this.faces[ f ];

					faceNormal = morphNormals.faceNormals[ f ];
					vertexNormals = morphNormals.vertexNormals[ f ];

					faceNormal.copy( face.normal );

					vertexNormals.a.copy( face.vertexNormals[ 0 ] );
					vertexNormals.b.copy( face.vertexNormals[ 1 ] );
					vertexNormals.c.copy( face.vertexNormals[ 2 ] );

				}

			}

			// restore original normals

			for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

				face = this.faces[ f ];

				face.normal = face.__originalFaceNormal;
				face.vertexNormals = face.__originalVertexNormals;

			}

		},

		computeBoundingBox: function () {

			if ( this.boundingBox === null ) {

				this.boundingBox = new Box3();

			}

			this.boundingBox.setFromPoints( this.vertices );

		},

		computeBoundingSphere: function () {

			if ( this.boundingSphere === null ) {

				this.boundingSphere = new Sphere();

			}

			this.boundingSphere.setFromPoints( this.vertices );

		},

		merge: function ( geometry, matrix, materialIndexOffset ) {

			if ( ! ( geometry && geometry.isGeometry ) ) {

				console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
				return;

			}

			var normalMatrix,
				vertexOffset = this.vertices.length,
				vertices1 = this.vertices,
				vertices2 = geometry.vertices,
				faces1 = this.faces,
				faces2 = geometry.faces,
				colors1 = this.colors,
				colors2 = geometry.colors;

			if ( materialIndexOffset === undefined ) { materialIndexOffset = 0; }

			if ( matrix !== undefined ) {

				normalMatrix = new Matrix3().getNormalMatrix( matrix );

			}

			// vertices

			for ( var i = 0, il = vertices2.length; i < il; i ++ ) {

				var vertex = vertices2[ i ];

				var vertexCopy = vertex.clone();

				if ( matrix !== undefined ) { vertexCopy.applyMatrix4( matrix ); }

				vertices1.push( vertexCopy );

			}

			// colors

			for ( var i = 0, il = colors2.length; i < il; i ++ ) {

				colors1.push( colors2[ i ].clone() );

			}

			// faces

			for ( i = 0, il = faces2.length; i < il; i ++ ) {

				var face = faces2[ i ], faceCopy, normal, color,
					faceVertexNormals = face.vertexNormals,
					faceVertexColors = face.vertexColors;

				faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
				faceCopy.normal.copy( face.normal );

				if ( normalMatrix !== undefined ) {

					faceCopy.normal.applyMatrix3( normalMatrix ).normalize();

				}

				for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {

					normal = faceVertexNormals[ j ].clone();

					if ( normalMatrix !== undefined ) {

						normal.applyMatrix3( normalMatrix ).normalize();

					}

					faceCopy.vertexNormals.push( normal );

				}

				faceCopy.color.copy( face.color );

				for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {

					color = faceVertexColors[ j ];
					faceCopy.vertexColors.push( color.clone() );

				}

				faceCopy.materialIndex = face.materialIndex + materialIndexOffset;

				faces1.push( faceCopy );

			}

			// uvs

			for ( var i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {

				var faceVertexUvs2 = geometry.faceVertexUvs[ i ];

				if ( this.faceVertexUvs[ i ] === undefined ) { this.faceVertexUvs[ i ] = []; }

				for ( var j = 0, jl = faceVertexUvs2.length; j < jl; j ++ ) {

					var uvs2 = faceVertexUvs2[ j ], uvsCopy = [];

					for ( var k = 0, kl = uvs2.length; k < kl; k ++ ) {

						uvsCopy.push( uvs2[ k ].clone() );

					}

					this.faceVertexUvs[ i ].push( uvsCopy );

				}

			}

		},

		mergeMesh: function ( mesh ) {

			if ( ! ( mesh && mesh.isMesh ) ) {

				console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
				return;

			}

			if ( mesh.matrixAutoUpdate ) { mesh.updateMatrix(); }

			this.merge( mesh.geometry, mesh.matrix );

		},

		/*
		 * Checks for duplicate vertices with hashmap.
		 * Duplicated vertices are removed
		 * and faces' vertices are updated.
		 */

		mergeVertices: function () {

			var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
			var unique = [], changes = [];

			var v, key;
			var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
			var precision = Math.pow( 10, precisionPoints );
			var i, il, face;
			var indices, j, jl;

			for ( i = 0, il = this.vertices.length; i < il; i ++ ) {

				v = this.vertices[ i ];
				key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );

				if ( verticesMap[ key ] === undefined ) {

					verticesMap[ key ] = i;
					unique.push( this.vertices[ i ] );
					changes[ i ] = unique.length - 1;

				} else {

					//console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
					changes[ i ] = changes[ verticesMap[ key ] ];

				}

			}


			// if faces are completely degenerate after merging vertices, we
			// have to remove them from the geometry.
			var faceIndicesToRemove = [];

			for ( i = 0, il = this.faces.length; i < il; i ++ ) {

				face = this.faces[ i ];

				face.a = changes[ face.a ];
				face.b = changes[ face.b ];
				face.c = changes[ face.c ];

				indices = [ face.a, face.b, face.c ];

				// if any duplicate vertices are found in a Face3
				// we have to remove the face as nothing can be saved
				for ( var n = 0; n < 3; n ++ ) {

					if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {

						faceIndicesToRemove.push( i );
						break;

					}

				}

			}

			for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {

				var idx = faceIndicesToRemove[ i ];

				this.faces.splice( idx, 1 );

				for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {

					this.faceVertexUvs[ j ].splice( idx, 1 );

				}

			}

			// Use unique set of vertices

			var diff = this.vertices.length - unique.length;
			this.vertices = unique;
			return diff;

		},

		setFromPoints: function ( points ) {

			this.vertices = [];

			for ( var i = 0, l = points.length; i < l; i ++ ) {

				var point = points[ i ];
				this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );

			}

			return this;

		},

		sortFacesByMaterialIndex: function () {

			var faces = this.faces;
			var length = faces.length;

			// tag faces

			for ( var i = 0; i < length; i ++ ) {

				faces[ i ]._id = i;

			}

			// sort faces

			function materialIndexSort( a, b ) {

				return a.materialIndex - b.materialIndex;

			}

			faces.sort( materialIndexSort );

			// sort uvs

			var uvs1 = this.faceVertexUvs[ 0 ];
			var uvs2 = this.faceVertexUvs[ 1 ];

			var newUvs1, newUvs2;

			if ( uvs1 && uvs1.length === length ) { newUvs1 = []; }
			if ( uvs2 && uvs2.length === length ) { newUvs2 = []; }

			for ( var i = 0; i < length; i ++ ) {

				var id = faces[ i ]._id;

				if ( newUvs1 ) { newUvs1.push( uvs1[ id ] ); }
				if ( newUvs2 ) { newUvs2.push( uvs2[ id ] ); }

			}

			if ( newUvs1 ) { this.faceVertexUvs[ 0 ] = newUvs1; }
			if ( newUvs2 ) { this.faceVertexUvs[ 1 ] = newUvs2; }

		},

		toJSON: function () {

			var data = {
				metadata: {
					version: 4.5,
					type: 'Geometry',
					generator: 'Geometry.toJSON'
				}
			};

			// standard Geometry serialization

			data.uuid = this.uuid;
			data.type = this.type;
			if ( this.name !== '' ) { data.name = this.name; }

			if ( this.parameters !== undefined ) {

				var parameters = this.parameters;

				for ( var key in parameters ) {

					if ( parameters[ key ] !== undefined ) { data[ key ] = parameters[ key ]; }

				}

				return data;

			}

			var vertices = [];

			for ( var i = 0; i < this.vertices.length; i ++ ) {

				var vertex = this.vertices[ i ];
				vertices.push( vertex.x, vertex.y, vertex.z );

			}

			var faces = [];
			var normals = [];
			var normalsHash = {};
			var colors = [];
			var colorsHash = {};
			var uvs = [];
			var uvsHash = {};

			for ( var i = 0; i < this.faces.length; i ++ ) {

				var face = this.faces[ i ];

				var hasMaterial = true;
				var hasFaceUv = false; // deprecated
				var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
				var hasFaceNormal = face.normal.length() > 0;
				var hasFaceVertexNormal = face.vertexNormals.length > 0;
				var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
				var hasFaceVertexColor = face.vertexColors.length > 0;

				var faceType = 0;

				faceType = setBit( faceType, 0, 0 ); // isQuad
				faceType = setBit( faceType, 1, hasMaterial );
				faceType = setBit( faceType, 2, hasFaceUv );
				faceType = setBit( faceType, 3, hasFaceVertexUv );
				faceType = setBit( faceType, 4, hasFaceNormal );
				faceType = setBit( faceType, 5, hasFaceVertexNormal );
				faceType = setBit( faceType, 6, hasFaceColor );
				faceType = setBit( faceType, 7, hasFaceVertexColor );

				faces.push( faceType );
				faces.push( face.a, face.b, face.c );
				faces.push( face.materialIndex );

				if ( hasFaceVertexUv ) {

					var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];

					faces.push(
						getUvIndex( faceVertexUvs[ 0 ] ),
						getUvIndex( faceVertexUvs[ 1 ] ),
						getUvIndex( faceVertexUvs[ 2 ] )
					);

				}

				if ( hasFaceNormal ) {

					faces.push( getNormalIndex( face.normal ) );

				}

				if ( hasFaceVertexNormal ) {

					var vertexNormals = face.vertexNormals;

					faces.push(
						getNormalIndex( vertexNormals[ 0 ] ),
						getNormalIndex( vertexNormals[ 1 ] ),
						getNormalIndex( vertexNormals[ 2 ] )
					);

				}

				if ( hasFaceColor ) {

					faces.push( getColorIndex( face.color ) );

				}

				if ( hasFaceVertexColor ) {

					var vertexColors = face.vertexColors;

					faces.push(
						getColorIndex( vertexColors[ 0 ] ),
						getColorIndex( vertexColors[ 1 ] ),
						getColorIndex( vertexColors[ 2 ] )
					);

				}

			}

			function setBit( value, position, enabled ) {

				return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );

			}

			function getNormalIndex( normal ) {

				var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();

				if ( normalsHash[ hash ] !== undefined ) {

					return normalsHash[ hash ];

				}

				normalsHash[ hash ] = normals.length / 3;
				normals.push( normal.x, normal.y, normal.z );

				return normalsHash[ hash ];

			}

			function getColorIndex( color ) {

				var hash = color.r.toString() + color.g.toString() + color.b.toString();

				if ( colorsHash[ hash ] !== undefined ) {

					return colorsHash[ hash ];

				}

				colorsHash[ hash ] = colors.length;
				colors.push( color.getHex() );

				return colorsHash[ hash ];

			}

			function getUvIndex( uv ) {

				var hash = uv.x.toString() + uv.y.toString();

				if ( uvsHash[ hash ] !== undefined ) {

					return uvsHash[ hash ];

				}

				uvsHash[ hash ] = uvs.length / 2;
				uvs.push( uv.x, uv.y );

				return uvsHash[ hash ];

			}

			data.data = {};

			data.data.vertices = vertices;
			data.data.normals = normals;
			if ( colors.length > 0 ) { data.data.colors = colors; }
			if ( uvs.length > 0 ) { data.data.uvs = [ uvs ]; } // temporal backward compatibility
			data.data.faces = faces;

			return data;

		},

		clone: function () {

			/*
			 // Handle primitives

			 var parameters = this.parameters;

			 if ( parameters !== undefined ) {

			 var values = [];

			 for ( var key in parameters ) {

			 values.push( parameters[ key ] );

			 }

			 var geometry = Object.create( this.constructor.prototype );
			 this.constructor.apply( geometry, values );
			 return geometry;

			 }

			 return new this.constructor().copy( this );
			 */

			return new Geometry().copy( this );

		},

		copy: function ( source ) {

			var i, il, j, jl, k, kl;

			// reset

			this.vertices = [];
			this.colors = [];
			this.faces = [];
			this.faceVertexUvs = [[]];
			this.morphTargets = [];
			this.morphNormals = [];
			this.skinWeights = [];
			this.skinIndices = [];
			this.lineDistances = [];
			this.boundingBox = null;
			this.boundingSphere = null;

			// name

			this.name = source.name;

			// vertices

			var vertices = source.vertices;

			for ( i = 0, il = vertices.length; i < il; i ++ ) {

				this.vertices.push( vertices[ i ].clone() );

			}

			// colors

			var colors = source.colors;

			for ( i = 0, il = colors.length; i < il; i ++ ) {

				this.colors.push( colors[ i ].clone() );

			}

			// faces

			var faces = source.faces;

			for ( i = 0, il = faces.length; i < il; i ++ ) {

				this.faces.push( faces[ i ].clone() );

			}

			// face vertex uvs

			for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {

				var faceVertexUvs = source.faceVertexUvs[ i ];

				if ( this.faceVertexUvs[ i ] === undefined ) {

					this.faceVertexUvs[ i ] = [];

				}

				for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {

					var uvs = faceVertexUvs[ j ], uvsCopy = [];

					for ( k = 0, kl = uvs.length; k < kl; k ++ ) {

						var uv = uvs[ k ];

						uvsCopy.push( uv.clone() );

					}

					this.faceVertexUvs[ i ].push( uvsCopy );

				}

			}

			// morph targets

			var morphTargets = source.morphTargets;

			for ( i = 0, il = morphTargets.length; i < il; i ++ ) {

				var morphTarget = {};
				morphTarget.name = morphTargets[ i ].name;

				// vertices

				if ( morphTargets[ i ].vertices !== undefined ) {

					morphTarget.vertices = [];

					for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {

						morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );

					}

				}

				// normals

				if ( morphTargets[ i ].normals !== undefined ) {

					morphTarget.normals = [];

					for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {

						morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );

					}

				}

				this.morphTargets.push( morphTarget );

			}

			// morph normals

			var morphNormals = source.morphNormals;

			for ( i = 0, il = morphNormals.length; i < il; i ++ ) {

				var morphNormal = {};

				// vertex normals

				if ( morphNormals[ i ].vertexNormals !== undefined ) {

					morphNormal.vertexNormals = [];

					for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {

						var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
						var destVertexNormal = {};

						destVertexNormal.a = srcVertexNormal.a.clone();
						destVertexNormal.b = srcVertexNormal.b.clone();
						destVertexNormal.c = srcVertexNormal.c.clone();

						morphNormal.vertexNormals.push( destVertexNormal );

					}

				}

				// face normals

				if ( morphNormals[ i ].faceNormals !== undefined ) {

					morphNormal.faceNormals = [];

					for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {

						morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );

					}

				}

				this.morphNormals.push( morphNormal );

			}

			// skin weights

			var skinWeights = source.skinWeights;

			for ( i = 0, il = skinWeights.length; i < il; i ++ ) {

				this.skinWeights.push( skinWeights[ i ].clone() );

			}

			// skin indices

			var skinIndices = source.skinIndices;

			for ( i = 0, il = skinIndices.length; i < il; i ++ ) {

				this.skinIndices.push( skinIndices[ i ].clone() );

			}

			// line distances

			var lineDistances = source.lineDistances;

			for ( i = 0, il = lineDistances.length; i < il; i ++ ) {

				this.lineDistances.push( lineDistances[ i ] );

			}

			// bounding box

			var boundingBox = source.boundingBox;

			if ( boundingBox !== null ) {

				this.boundingBox = boundingBox.clone();

			}

			// bounding sphere

			var boundingSphere = source.boundingSphere;

			if ( boundingSphere !== null ) {

				this.boundingSphere = boundingSphere.clone();

			}

			// update flags

			this.elementsNeedUpdate = source.elementsNeedUpdate;
			this.verticesNeedUpdate = source.verticesNeedUpdate;
			this.uvsNeedUpdate = source.uvsNeedUpdate;
			this.normalsNeedUpdate = source.normalsNeedUpdate;
			this.colorsNeedUpdate = source.colorsNeedUpdate;
			this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
			this.groupsNeedUpdate = source.groupsNeedUpdate;

			return this;

		},

		dispose: function () {

			this.dispatchEvent( { type: 'dispose' } );

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	// BoxGeometry

	var BoxGeometry = /*@__PURE__*/(function (Geometry) {
		function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {

			Geometry.call(this);

			this.type = 'BoxGeometry';

			this.parameters = {
				width: width,
				height: height,
				depth: depth,
				widthSegments: widthSegments,
				heightSegments: heightSegments,
				depthSegments: depthSegments
			};

			this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
			this.mergeVertices();

		}

		if ( Geometry ) BoxGeometry.__proto__ = Geometry;
		BoxGeometry.prototype = Object.create( Geometry && Geometry.prototype );
		BoxGeometry.prototype.constructor = BoxGeometry;

		return BoxGeometry;
	}(Geometry));

	// BoxBufferGeometry

	var BoxBufferGeometry = /*@__PURE__*/(function (BufferGeometry) {
		function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {

			BufferGeometry.call(this);

			this.type = 'BoxBufferGeometry';

			this.parameters = {
				width: width,
				height: height,
				depth: depth,
				widthSegments: widthSegments,
				heightSegments: heightSegments,
				depthSegments: depthSegments
			};

			var scope = this;

			width = width || 1;
			height = height || 1;
			depth = depth || 1;

			// segments

			widthSegments = Math.floor( widthSegments ) || 1;
			heightSegments = Math.floor( heightSegments ) || 1;
			depthSegments = Math.floor( depthSegments ) || 1;

			// buffers

			var indices = [];
			var vertices = [];
			var normals = [];
			var uvs = [];

			// helper variables

			var numberOfVertices = 0;
			var groupStart = 0;

			// build each side of the box geometry

			buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
			buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
			buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
			buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
			buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
			buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz

			// build geometry

			this.setIndex( indices );
			this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
			this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
			this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

			function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {

				var segmentWidth = width / gridX;
				var segmentHeight = height / gridY;

				var widthHalf = width / 2;
				var heightHalf = height / 2;
				var depthHalf = depth / 2;

				var gridX1 = gridX + 1;
				var gridY1 = gridY + 1;

				var vertexCounter = 0;
				var groupCount = 0;

				var ix, iy;

				var vector = new Vector3();

				// generate vertices, normals and uvs

				for ( iy = 0; iy < gridY1; iy ++ ) {

					var y = iy * segmentHeight - heightHalf;

					for ( ix = 0; ix < gridX1; ix ++ ) {

						var x = ix * segmentWidth - widthHalf;

						// set values to correct vector component

						vector[ u ] = x * udir;
						vector[ v ] = y * vdir;
						vector[ w ] = depthHalf;

						// now apply vector to vertex buffer

						vertices.push( vector.x, vector.y, vector.z );

						// set values to correct vector component

						vector[ u ] = 0;
						vector[ v ] = 0;
						vector[ w ] = depth > 0 ? 1 : - 1;

						// now apply vector to normal buffer

						normals.push( vector.x, vector.y, vector.z );

						// uvs

						uvs.push( ix / gridX );
						uvs.push( 1 - ( iy / gridY ) );

						// counters

						vertexCounter += 1;

					}

				}

				// indices

				// 1. you need three indices to draw a single face
				// 2. a single segment consists of two faces
				// 3. so we need to generate six (2*3) indices per segment

				for ( iy = 0; iy < gridY; iy ++ ) {

					for ( ix = 0; ix < gridX; ix ++ ) {

						var a = numberOfVertices + ix + gridX1 * iy;
						var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
						var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
						var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;

						// faces

						indices.push( a, b, d );
						indices.push( b, c, d );

						// increase counter

						groupCount += 6;

					}

				}

				// add a group to the geometry. this will ensure multi material support

				scope.addGroup( groupStart, groupCount, materialIndex );

				// calculate new start value for groups

				groupStart += groupCount;

				// update total number of vertices

				numberOfVertices += vertexCounter;

			}

		}

		if ( BufferGeometry ) BoxBufferGeometry.__proto__ = BufferGeometry;
		BoxBufferGeometry.prototype = Object.create( BufferGeometry && BufferGeometry.prototype );
		BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;

		return BoxBufferGeometry;
	}(BufferGeometry));

	/**
	 * Uniform Utilities
	 */

	function cloneUniforms( src ) {

		var dst = {};

		for ( var u in src ) {

			dst[ u ] = {};

			for ( var p in src[ u ] ) {

				var property = src[ u ][ p ];

				if ( property && ( property.isColor ||
					property.isMatrix3 || property.isMatrix4 ||
					property.isVector2 || property.isVector3 || property.isVector4 ||
					property.isTexture ) ) {

					dst[ u ][ p ] = property.clone();

				} else if ( Array.isArray( property ) ) {

					dst[ u ][ p ] = property.slice();

				} else {

					dst[ u ][ p ] = property;

				}

			}

		}

		return dst;

	}

	function mergeUniforms( uniforms ) {

		var merged = {};

		for ( var u = 0; u < uniforms.length; u ++ ) {

			var tmp = cloneUniforms( uniforms[ u ] );

			for ( var p in tmp ) {

				merged[ p ] = tmp[ p ];

			}

		}

		return merged;

	}

	// Legacy

	var UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };

	var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";

	var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";

	/**
	 * @author alteredq / http://alteredqualia.com/
	 *
	 * parameters = {
	 *  defines: { "label" : "value" },
	 *  uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
	 *
	 *  fragmentShader: <string>,
	 *  vertexShader: <string>,
	 *
	 *  wireframe: <boolean>,
	 *  wireframeLinewidth: <float>,
	 *
	 *  lights: <bool>,
	 *
	 *  skinning: <bool>,
	 *  morphTargets: <bool>,
	 *  morphNormals: <bool>
	 * }
	 */

	function ShaderMaterial( parameters ) {

		Material.call( this );

		this.type = 'ShaderMaterial';

		this.defines = {};
		this.uniforms = {};

		this.vertexShader = default_vertex;
		this.fragmentShader = default_fragment;

		this.linewidth = 1;

		this.wireframe = false;
		this.wireframeLinewidth = 1;

		this.fog = false; // set to use scene fog
		this.lights = false; // set to use scene lights
		this.clipping = false; // set to use user-defined clipping planes

		this.skinning = false; // set to use skinning attribute streams
		this.morphTargets = false; // set to use morph targets
		this.morphNormals = false; // set to use morph normals

		this.extensions = {
			derivatives: false, // set to use derivatives
			fragDepth: false, // set to use fragment depth values
			drawBuffers: false, // set to use draw buffers
			shaderTextureLOD: false // set to use shader texture LOD
		};

		// When rendered geometry doesn't include these attributes but the material does,
		// use these default values in WebGL. This avoids errors when buffer data is missing.
		this.defaultAttributeValues = {
			'color': [ 1, 1, 1 ],
			'uv': [ 0, 0 ],
			'uv2': [ 0, 0 ]
		};

		this.index0AttributeName = undefined;
		this.uniformsNeedUpdate = false;

		if ( parameters !== undefined ) {

			if ( parameters.attributes !== undefined ) {

				console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );

			}

			this.setValues( parameters );

		}

	}

	ShaderMaterial.prototype = Object.create( Material.prototype );
	ShaderMaterial.prototype.constructor = ShaderMaterial;

	ShaderMaterial.prototype.isShaderMaterial = true;

	ShaderMaterial.prototype.copy = function ( source ) {

		Material.prototype.copy.call( this, source );

		this.fragmentShader = source.fragmentShader;
		this.vertexShader = source.vertexShader;

		this.uniforms = cloneUniforms( source.uniforms );

		this.defines = Object.assign( {}, source.defines );

		this.wireframe = source.wireframe;
		this.wireframeLinewidth = source.wireframeLinewidth;

		this.lights = source.lights;
		this.clipping = source.clipping;

		this.skinning = source.skinning;

		this.morphTargets = source.morphTargets;
		this.morphNormals = source.morphNormals;

		this.extensions = source.extensions;

		return this;

	};

	ShaderMaterial.prototype.toJSON = function ( meta ) {

		var data = Material.prototype.toJSON.call( this, meta );

		data.uniforms = {};

		for ( var name in this.uniforms ) {

			var uniform = this.uniforms[ name ];
			var value = uniform.value;

			if ( value && value.isTexture ) {

				data.uniforms[ name ] = {
					type: 't',
					value: value.toJSON( meta ).uuid
				};

			} else if ( value && value.isColor ) {

				data.uniforms[ name ] = {
					type: 'c',
					value: value.getHex()
				};

			} else if ( value && value.isVector2 ) {

				data.uniforms[ name ] = {
					type: 'v2',
					value: value.toArray()
				};

			} else if ( value && value.isVector3 ) {

				data.uniforms[ name ] = {
					type: 'v3',
					value: value.toArray()
				};

			} else if ( value && value.isVector4 ) {

				data.uniforms[ name ] = {
					type: 'v4',
					value: value.toArray()
				};

			} else if ( value && value.isMatrix3 ) {

				data.uniforms[ name ] = {
					type: 'm3',
					value: value.toArray()
				};

			} else if ( value && value.isMatrix4 ) {

				data.uniforms[ name ] = {
					type: 'm4',
					value: value.toArray()
				};

			} else {

				data.uniforms[ name ] = {
					value: value
				};

				// note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far

			}

		}

		if ( Object.keys( this.defines ).length > 0 ) { data.defines = this.defines; }

		data.vertexShader = this.vertexShader;
		data.fragmentShader = this.fragmentShader;

		var extensions = {};

		for ( var key in this.extensions ) {

			if ( this.extensions[ key ] === true ) { extensions[ key ] = true; }

		}

		if ( Object.keys( extensions ).length > 0 ) { data.extensions = extensions; }

		return data;

	};

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author mikael emtinger / http://gomo.se/
	 * @author WestLangley / http://github.com/WestLangley
	*/

	function Camera() {

		Object3D.call( this );

		this.type = 'Camera';

		this.matrixWorldInverse = new Matrix4();

		this.projectionMatrix = new Matrix4();
		this.projectionMatrixInverse = new Matrix4();

	}

	Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {

		constructor: Camera,

		isCamera: true,

		copy: function ( source, recursive ) {

			Object3D.prototype.copy.call( this, source, recursive );

			this.matrixWorldInverse.copy( source.matrixWorldInverse );

			this.projectionMatrix.copy( source.projectionMatrix );
			this.projectionMatrixInverse.copy( source.projectionMatrixInverse );

			return this;

		},

		getWorldDirection: function ( target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
				target = new Vector3();

			}

			this.updateMatrixWorld( true );

			var e = this.matrixWorld.elements;

			return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();

		},

		updateMatrixWorld: function ( force ) {

			Object3D.prototype.updateMatrixWorld.call( this, force );

			this.matrixWorldInverse.getInverse( this.matrixWorld );

		},

		updateWorldMatrix: function ( updateParents, updateChildren ) {

			Object3D.prototype.updateWorldMatrix.call( this, updateParents, updateChildren );

			this.matrixWorldInverse.getInverse( this.matrixWorld );

		},

		clone: function () {

			return new this.constructor().copy( this );

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author greggman / http://games.greggman.com/
	 * @author zz85 / http://www.lab4games.net/zz85/blog
	 * @author tschw
	 */

	function PerspectiveCamera( fov, aspect, near, far ) {

		Camera.call( this );

		this.type = 'PerspectiveCamera';

		this.fov = fov !== undefined ? fov : 50;
		this.zoom = 1;

		this.near = near !== undefined ? near : 0.1;
		this.far = far !== undefined ? far : 2000;
		this.focus = 10;

		this.aspect = aspect !== undefined ? aspect : 1;
		this.view = null;

		this.filmGauge = 35;	// width of the film (default in millimeters)
		this.filmOffset = 0;	// horizontal film offset (same unit as gauge)

		this.updateProjectionMatrix();

	}

	PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {

		constructor: PerspectiveCamera,

		isPerspectiveCamera: true,

		copy: function ( source, recursive ) {

			Camera.prototype.copy.call( this, source, recursive );

			this.fov = source.fov;
			this.zoom = source.zoom;

			this.near = source.near;
			this.far = source.far;
			this.focus = source.focus;

			this.aspect = source.aspect;
			this.view = source.view === null ? null : Object.assign( {}, source.view );

			this.filmGauge = source.filmGauge;
			this.filmOffset = source.filmOffset;

			return this;

		},

		/**
		 * Sets the FOV by focal length in respect to the current .filmGauge.
		 *
		 * The default film gauge is 35, so that the focal length can be specified for
		 * a 35mm (full frame) camera.
		 *
		 * Values for focal length and film gauge must have the same unit.
		 */
		setFocalLength: function ( focalLength ) {

			// see http://www.bobatkins.com/photography/technical/field_of_view.html
			var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;

			this.fov = MathUtils.RAD2DEG * 2 * Math.atan( vExtentSlope );
			this.updateProjectionMatrix();

		},

		/**
		 * Calculates the focal length from the current .fov and .filmGauge.
		 */
		getFocalLength: function () {

			var vExtentSlope = Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov );

			return 0.5 * this.getFilmHeight() / vExtentSlope;

		},

		getEffectiveFOV: function () {

			return MathUtils.RAD2DEG * 2 * Math.atan(
				Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom );

		},

		getFilmWidth: function () {

			// film not completely covered in portrait format (aspect < 1)
			return this.filmGauge * Math.min( this.aspect, 1 );

		},

		getFilmHeight: function () {

			// film not completely covered in landscape format (aspect > 1)
			return this.filmGauge / Math.max( this.aspect, 1 );

		},

		/**
		 * Sets an offset in a larger frustum. This is useful for multi-window or
		 * multi-monitor/multi-machine setups.
		 *
		 * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
		 * the monitors are in grid like this
		 *
		 *   +---+---+---+
		 *   | A | B | C |
		 *   +---+---+---+
		 *   | D | E | F |
		 *   +---+---+---+
		 *
		 * then for each monitor you would call it like this
		 *
		 *   var w = 1920;
		 *   var h = 1080;
		 *   var fullWidth = w * 3;
		 *   var fullHeight = h * 2;
		 *
		 *   --A--
		 *   camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
		 *   --B--
		 *   camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
		 *   --C--
		 *   camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
		 *   --D--
		 *   camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
		 *   --E--
		 *   camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
		 *   --F--
		 *   camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
		 *
		 *   Note there is no reason monitors have to be the same size or in a grid.
		 */
		setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {

			this.aspect = fullWidth / fullHeight;

			if ( this.view === null ) {

				this.view = {
					enabled: true,
					fullWidth: 1,
					fullHeight: 1,
					offsetX: 0,
					offsetY: 0,
					width: 1,
					height: 1
				};

			}

			this.view.enabled = true;
			this.view.fullWidth = fullWidth;
			this.view.fullHeight = fullHeight;
			this.view.offsetX = x;
			this.view.offsetY = y;
			this.view.width = width;
			this.view.height = height;

			this.updateProjectionMatrix();

		},

		clearViewOffset: function () {

			if ( this.view !== null ) {

				this.view.enabled = false;

			}

			this.updateProjectionMatrix();

		},

		updateProjectionMatrix: function () {

			var near = this.near,
				top = near * Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom,
				height = 2 * top,
				width = this.aspect * height,
				left = - 0.5 * width,
				view = this.view;

			if ( this.view !== null && this.view.enabled ) {

				var fullWidth = view.fullWidth,
					fullHeight = view.fullHeight;

				left += view.offsetX * width / fullWidth;
				top -= view.offsetY * height / fullHeight;
				width *= view.width / fullWidth;
				height *= view.height / fullHeight;

			}

			var skew = this.filmOffset;
			if ( skew !== 0 ) { left += near * skew / this.getFilmWidth(); }

			this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );

			this.projectionMatrixInverse.getInverse( this.projectionMatrix );

		},

		toJSON: function ( meta ) {

			var data = Object3D.prototype.toJSON.call( this, meta );

			data.object.fov = this.fov;
			data.object.zoom = this.zoom;

			data.object.near = this.near;
			data.object.far = this.far;
			data.object.focus = this.focus;

			data.object.aspect = this.aspect;

			if ( this.view !== null ) { data.object.view = Object.assign( {}, this.view ); }

			data.object.filmGauge = this.filmGauge;
			data.object.filmOffset = this.filmOffset;

			return data;

		}

	} );

	/**
	 * Camera for rendering cube maps
	 *	- renders scene into axis-aligned cube
	 *
	 * @author alteredq / http://alteredqualia.com/
	 */

	var fov = 90, aspect = 1;

	function CubeCamera( near, far, cubeResolution, options ) {

		Object3D.call( this );

		this.type = 'CubeCamera';

		var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
		cameraPX.up.set( 0, - 1, 0 );
		cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
		this.add( cameraPX );

		var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
		cameraNX.up.set( 0, - 1, 0 );
		cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
		this.add( cameraNX );

		var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
		cameraPY.up.set( 0, 0, 1 );
		cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
		this.add( cameraPY );

		var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
		cameraNY.up.set( 0, 0, - 1 );
		cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
		this.add( cameraNY );

		var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
		cameraPZ.up.set( 0, - 1, 0 );
		cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
		this.add( cameraPZ );

		var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
		cameraNZ.up.set( 0, - 1, 0 );
		cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
		this.add( cameraNZ );

		options = options || { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };

		this.renderTarget = new WebGLCubeRenderTarget( cubeResolution, options );
		this.renderTarget.texture.name = "CubeCamera";

		this.update = function ( renderer, scene ) {

			if ( this.parent === null ) { this.updateMatrixWorld(); }

			var currentRenderTarget = renderer.getRenderTarget();

			var renderTarget = this.renderTarget;
			var generateMipmaps = renderTarget.texture.generateMipmaps;

			renderTarget.texture.generateMipmaps = false;

			renderer.setRenderTarget( renderTarget, 0 );
			renderer.render( scene, cameraPX );

			renderer.setRenderTarget( renderTarget, 1 );
			renderer.render( scene, cameraNX );

			renderer.setRenderTarget( renderTarget, 2 );
			renderer.render( scene, cameraPY );

			renderer.setRenderTarget( renderTarget, 3 );
			renderer.render( scene, cameraNY );

			renderer.setRenderTarget( renderTarget, 4 );
			renderer.render( scene, cameraPZ );

			renderTarget.texture.generateMipmaps = generateMipmaps;

			renderer.setRenderTarget( renderTarget, 5 );
			renderer.render( scene, cameraNZ );

			renderer.setRenderTarget( currentRenderTarget );

		};

		this.clear = function ( renderer, color, depth, stencil ) {

			var currentRenderTarget = renderer.getRenderTarget();

			var renderTarget = this.renderTarget;

			for ( var i = 0; i < 6; i ++ ) {

				renderer.setRenderTarget( renderTarget, i );

				renderer.clear( color, depth, stencil );

			}

			renderer.setRenderTarget( currentRenderTarget );

		};

	}

	CubeCamera.prototype = Object.create( Object3D.prototype );
	CubeCamera.prototype.constructor = CubeCamera;

	/**
	 * @author alteredq / http://alteredqualia.com
	 * @author WestLangley / http://github.com/WestLangley
	 */

	function WebGLCubeRenderTarget( size, options, dummy ) {

		if ( Number.isInteger( options ) ) {

			console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );

			options = dummy;

		}

		WebGLRenderTarget.call( this, size, size, options );

	}

	WebGLCubeRenderTarget.prototype = Object.create( WebGLRenderTarget.prototype );
	WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;

	WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;

	WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function ( renderer, texture ) {

		this.texture.type = texture.type;
		this.texture.format = texture.format;
		this.texture.encoding = texture.encoding;

		var scene = new Scene();

		var shader = {

			uniforms: {
				tEquirect: { value: null },
			},

			vertexShader: [

				"varying vec3 vWorldDirection;",

				"vec3 transformDirection( in vec3 dir, in mat4 matrix ) {",

				"	return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );",

				"}",

				"void main() {",

				"	vWorldDirection = transformDirection( position, modelMatrix );",

				"	#include <begin_vertex>",
				"	#include <project_vertex>",

				"}"

			].join( '\n' ),

			fragmentShader: [

				"uniform sampler2D tEquirect;",

				"varying vec3 vWorldDirection;",

				"#define RECIPROCAL_PI 0.31830988618",
				"#define RECIPROCAL_PI2 0.15915494",

				"void main() {",

				"	vec3 direction = normalize( vWorldDirection );",

				"	vec2 sampleUV;",

				"	sampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;",

				"	sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;",

				"	gl_FragColor = texture2D( tEquirect, sampleUV );",

				"}"

			].join( '\n' ),
		};

		var material = new ShaderMaterial( {

			type: 'CubemapFromEquirect',

			uniforms: cloneUniforms( shader.uniforms ),
			vertexShader: shader.vertexShader,
			fragmentShader: shader.fragmentShader,
			side: BackSide,
			blending: NoBlending

		} );

		material.uniforms.tEquirect.value = texture;

		var mesh = new Mesh( new BoxBufferGeometry( 5, 5, 5 ), material );

		scene.add( mesh );

		var camera = new CubeCamera( 1, 10, 1 );

		camera.renderTarget = this;
		camera.renderTarget.texture.name = 'CubeCameraTexture';

		camera.update( renderer, scene );

		mesh.geometry.dispose();
		mesh.material.dispose();

		return this;

	};

	/**
	 * @author alteredq / http://alteredqualia.com/
	 */

	function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {

		Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );

		this.image = { data: data || null, width: width || 1, height: height || 1 };

		this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
		this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;

		this.generateMipmaps = false;
		this.flipY = false;
		this.unpackAlignment = 1;

		this.needsUpdate = true;

	}

	DataTexture.prototype = Object.create( Texture.prototype );
	DataTexture.prototype.constructor = DataTexture;

	DataTexture.prototype.isDataTexture = true;

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author alteredq / http://alteredqualia.com/
	 * @author bhouston / http://clara.io
	 */

	var _sphere$1 = new Sphere();
	var _vector$5 = new Vector3();

	function Frustum( p0, p1, p2, p3, p4, p5 ) {

		this.planes = [

			( p0 !== undefined ) ? p0 : new Plane(),
			( p1 !== undefined ) ? p1 : new Plane(),
			( p2 !== undefined ) ? p2 : new Plane(),
			( p3 !== undefined ) ? p3 : new Plane(),
			( p4 !== undefined ) ? p4 : new Plane(),
			( p5 !== undefined ) ? p5 : new Plane()

		];

	}

	Object.assign( Frustum.prototype, {

		set: function ( p0, p1, p2, p3, p4, p5 ) {

			var planes = this.planes;

			planes[ 0 ].copy( p0 );
			planes[ 1 ].copy( p1 );
			planes[ 2 ].copy( p2 );
			planes[ 3 ].copy( p3 );
			planes[ 4 ].copy( p4 );
			planes[ 5 ].copy( p5 );

			return this;

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		copy: function ( frustum ) {

			var planes = this.planes;

			for ( var i = 0; i < 6; i ++ ) {

				planes[ i ].copy( frustum.planes[ i ] );

			}

			return this;

		},

		setFromProjectionMatrix: function ( m ) {

			var planes = this.planes;
			var me = m.elements;
			var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
			var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
			var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
			var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];

			planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
			planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
			planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
			planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
			planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
			planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();

			return this;

		},

		intersectsObject: function ( object ) {

			var geometry = object.geometry;

			if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); }

			_sphere$1.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );

			return this.intersectsSphere( _sphere$1 );

		},

		intersectsSprite: function ( sprite ) {

			_sphere$1.center.set( 0, 0, 0 );
			_sphere$1.radius = 0.7071067811865476;
			_sphere$1.applyMatrix4( sprite.matrixWorld );

			return this.intersectsSphere( _sphere$1 );

		},

		intersectsSphere: function ( sphere ) {

			var planes = this.planes;
			var center = sphere.center;
			var negRadius = - sphere.radius;

			for ( var i = 0; i < 6; i ++ ) {

				var distance = planes[ i ].distanceToPoint( center );

				if ( distance < negRadius ) {

					return false;

				}

			}

			return true;

		},

		intersectsBox: function ( box ) {

			var planes = this.planes;

			for ( var i = 0; i < 6; i ++ ) {

				var plane = planes[ i ];

				// corner at max distance

				_vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
				_vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
				_vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;

				if ( plane.distanceToPoint( _vector$5 ) < 0 ) {

					return false;

				}

			}

			return true;

		},

		containsPoint: function ( point ) {

			var planes = this.planes;

			for ( var i = 0; i < 6; i ++ ) {

				if ( planes[ i ].distanceToPoint( point ) < 0 ) {

					return false;

				}

			}

			return true;

		}

	} );

	/**
	 * Uniforms library for shared webgl shaders
	 */

	var UniformsLib = {

		common: {

			diffuse: { value: new Color( 0xeeeeee ) },
			opacity: { value: 1.0 },

			map: { value: null },
			uvTransform: { value: new Matrix3() },
			uv2Transform: { value: new Matrix3() },

			alphaMap: { value: null },

		},

		specularmap: {

			specularMap: { value: null },

		},

		envmap: {

			envMap: { value: null },
			flipEnvMap: { value: - 1 },
			reflectivity: { value: 1.0 },
			refractionRatio: { value: 0.98 },
			maxMipLevel: { value: 0 }

		},

		aomap: {

			aoMap: { value: null },
			aoMapIntensity: { value: 1 }

		},

		lightmap: {

			lightMap: { value: null },
			lightMapIntensity: { value: 1 }

		},

		emissivemap: {

			emissiveMap: { value: null }

		},

		bumpmap: {

			bumpMap: { value: null },
			bumpScale: { value: 1 }

		},

		normalmap: {

			normalMap: { value: null },
			normalScale: { value: new Vector2( 1, 1 ) }

		},

		displacementmap: {

			displacementMap: { value: null },
			displacementScale: { value: 1 },
			displacementBias: { value: 0 }

		},

		roughnessmap: {

			roughnessMap: { value: null }

		},

		metalnessmap: {

			metalnessMap: { value: null }

		},

		gradientmap: {

			gradientMap: { value: null }

		},

		fog: {

			fogDensity: { value: 0.00025 },
			fogNear: { value: 1 },
			fogFar: { value: 2000 },
			fogColor: { value: new Color( 0xffffff ) }

		},

		lights: {

			ambientLightColor: { value: [] },

			lightProbe: { value: [] },

			directionalLights: { value: [], properties: {
				direction: {},
				color: {},

				shadow: {},
				shadowBias: {},
				shadowRadius: {},
				shadowMapSize: {}
			} },

			directionalShadowMap: { value: [] },
			directionalShadowMatrix: { value: [] },

			spotLights: { value: [], properties: {
				color: {},
				position: {},
				direction: {},
				distance: {},
				coneCos: {},
				penumbraCos: {},
				decay: {},

				shadow: {},
				shadowBias: {},
				shadowRadius: {},
				shadowMapSize: {}
			} },

			spotShadowMap: { value: [] },
			spotShadowMatrix: { value: [] },

			pointLights: { value: [], properties: {
				color: {},
				position: {},
				decay: {},
				distance: {},

				shadow: {},
				shadowBias: {},
				shadowRadius: {},
				shadowMapSize: {},
				shadowCameraNear: {},
				shadowCameraFar: {}
			} },

			pointShadowMap: { value: [] },
			pointShadowMatrix: { value: [] },

			hemisphereLights: { value: [], properties: {
				direction: {},
				skyColor: {},
				groundColor: {}
			} },

			// TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
			rectAreaLights: { value: [], properties: {
				color: {},
				position: {},
				width: {},
				height: {}
			} }

		},

		points: {

			diffuse: { value: new Color( 0xeeeeee ) },
			opacity: { value: 1.0 },
			size: { value: 1.0 },
			scale: { value: 1.0 },
			map: { value: null },
			alphaMap: { value: null },
			uvTransform: { value: new Matrix3() }

		},

		sprite: {

			diffuse: { value: new Color( 0xeeeeee ) },
			opacity: { value: 1.0 },
			center: { value: new Vector2( 0.5, 0.5 ) },
			rotation: { value: 0.0 },
			map: { value: null },
			alphaMap: { value: null },
			uvTransform: { value: new Matrix3() }

		}

	};

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function WebGLAnimation() {

		var context = null;
		var isAnimating = false;
		var animationLoop = null;

		function onAnimationFrame( time, frame ) {

			if ( isAnimating === false ) { return; }

			animationLoop( time, frame );

			context.requestAnimationFrame( onAnimationFrame );

		}

		return {

			start: function () {

				if ( isAnimating === true ) { return; }
				if ( animationLoop === null ) { return; }

				context.requestAnimationFrame( onAnimationFrame );

				isAnimating = true;

			},

			stop: function () {

				isAnimating = false;

			},

			setAnimationLoop: function ( callback ) {

				animationLoop = callback;

			},

			setContext: function ( value ) {

				context = value;

			}

		};

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function WebGLAttributes( gl, capabilities ) {

		var isWebGL2 = capabilities.isWebGL2;

		var buffers = new WeakMap();

		function createBuffer( attribute, bufferType ) {

			var array = attribute.array;
			var usage = attribute.usage;

			var buffer = gl.createBuffer();

			gl.bindBuffer( bufferType, buffer );
			gl.bufferData( bufferType, array, usage );

			attribute.onUploadCallback();

			var type = 5126;

			if ( array instanceof Float32Array ) {

				type = 5126;

			} else if ( array instanceof Float64Array ) {

				console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );

			} else if ( array instanceof Uint16Array ) {

				type = 5123;

			} else if ( array instanceof Int16Array ) {

				type = 5122;

			} else if ( array instanceof Uint32Array ) {

				type = 5125;

			} else if ( array instanceof Int32Array ) {

				type = 5124;

			} else if ( array instanceof Int8Array ) {

				type = 5120;

			} else if ( array instanceof Uint8Array ) {

				type = 5121;

			}

			return {
				buffer: buffer,
				type: type,
				bytesPerElement: array.BYTES_PER_ELEMENT,
				version: attribute.version
			};

		}

		function updateBuffer( buffer, attribute, bufferType ) {

			var array = attribute.array;
			var updateRange = attribute.updateRange;

			gl.bindBuffer( bufferType, buffer );

			if ( updateRange.count === - 1 ) {

				// Not using update ranges

				gl.bufferSubData( bufferType, 0, array );

			} else {

				if ( isWebGL2 ) {

					gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
						array, updateRange.offset, updateRange.count );

				} else {

					gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
						array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );

				}

				updateRange.count = - 1; // reset range

			}

		}

		//

		function get( attribute ) {

			if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; }

			return buffers.get( attribute );

		}

		function remove( attribute ) {

			if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; }

			var data = buffers.get( attribute );

			if ( data ) {

				gl.deleteBuffer( data.buffer );

				buffers.delete( attribute );

			}

		}

		function update( attribute, bufferType ) {

			if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; }

			var data = buffers.get( attribute );

			if ( data === undefined ) {

				buffers.set( attribute, createBuffer( attribute, bufferType ) );

			} else if ( data.version < attribute.version ) {

				updateBuffer( data.buffer, attribute, bufferType );

				data.version = attribute.version;

			}

		}

		return {

			get: get,
			remove: remove,
			update: update

		};

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	// PlaneGeometry

	function PlaneGeometry( width, height, widthSegments, heightSegments ) {

		Geometry.call( this );

		this.type = 'PlaneGeometry';

		this.parameters = {
			width: width,
			height: height,
			widthSegments: widthSegments,
			heightSegments: heightSegments
		};

		this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
		this.mergeVertices();

	}

	PlaneGeometry.prototype = Object.create( Geometry.prototype );
	PlaneGeometry.prototype.constructor = PlaneGeometry;

	// PlaneBufferGeometry

	function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {

		BufferGeometry.call( this );

		this.type = 'PlaneBufferGeometry';

		this.parameters = {
			width: width,
			height: height,
			widthSegments: widthSegments,
			heightSegments: heightSegments
		};

		width = width || 1;
		height = height || 1;

		var width_half = width / 2;
		var height_half = height / 2;

		var gridX = Math.floor( widthSegments ) || 1;
		var gridY = Math.floor( heightSegments ) || 1;

		var gridX1 = gridX + 1;
		var gridY1 = gridY + 1;

		var segment_width = width / gridX;
		var segment_height = height / gridY;

		var ix, iy;

		// buffers

		var indices = [];
		var vertices = [];
		var normals = [];
		var uvs = [];

		// generate vertices, normals and uvs

		for ( iy = 0; iy < gridY1; iy ++ ) {

			var y = iy * segment_height - height_half;

			for ( ix = 0; ix < gridX1; ix ++ ) {

				var x = ix * segment_width - width_half;

				vertices.push( x, - y, 0 );

				normals.push( 0, 0, 1 );

				uvs.push( ix / gridX );
				uvs.push( 1 - ( iy / gridY ) );

			}

		}

		// indices

		for ( iy = 0; iy < gridY; iy ++ ) {

			for ( ix = 0; ix < gridX; ix ++ ) {

				var a = ix + gridX1 * iy;
				var b = ix + gridX1 * ( iy + 1 );
				var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
				var d = ( ix + 1 ) + gridX1 * iy;

				// faces

				indices.push( a, b, d );
				indices.push( b, c, d );

			}

		}

		// build geometry

		this.setIndex( indices );
		this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
		this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

	}

	PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
	PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;

	var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";

	var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";

	var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";

	var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";

	var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";

	var begin_vertex = "vec3 transformed = vec3( position );";

	var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";

	var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE  = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS  = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha  = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";

	var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";

	var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";

	var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";

	var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvarying vec3 vViewPosition;\n#endif";

	var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif";

	var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";

	var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";

	var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";

	var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";

	var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n  return m[ 2 ][ 3 ] == - 1.0;\n}";

	var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_maxMipLevel 8.0\n#define cubeUV_minMipLevel 4.0\n#define cubeUV_maxTileSize 256.0\n#define cubeUV_minTileSize 16.0\nfloat getFace(vec3 direction) {\n    vec3 absDirection = abs(direction);\n    float face = -1.0;\n    if (absDirection.x > absDirection.z) {\n      if (absDirection.x > absDirection.y)\n        face = direction.x > 0.0 ? 0.0 : 3.0;\n      else\n        face = direction.y > 0.0 ? 1.0 : 4.0;\n    } else {\n      if (absDirection.z > absDirection.y)\n        face = direction.z > 0.0 ? 2.0 : 5.0;\n      else\n        face = direction.y > 0.0 ? 1.0 : 4.0;\n    }\n    return face;\n}\nvec2 getUV(vec3 direction, float face) {\n    vec2 uv;\n    if (face == 0.0) {\n      uv = vec2(-direction.z, direction.y) / abs(direction.x);\n    } else if (face == 1.0) {\n      uv = vec2(direction.x, -direction.z) / abs(direction.y);\n    } else if (face == 2.0) {\n      uv = direction.xy / abs(direction.z);\n    } else if (face == 3.0) {\n      uv = vec2(direction.z, direction.y) / abs(direction.x);\n    } else if (face == 4.0) {\n      uv = direction.xz / abs(direction.y);\n    } else {\n      uv = vec2(-direction.x, direction.y) / abs(direction.z);\n    }\n    return 0.5 * (uv + 1.0);\n}\nvec3 bilinearCubeUV(sampler2D envMap, vec3 direction, float mipInt) {\n  float face = getFace(direction);\n  float filterInt = max(cubeUV_minMipLevel - mipInt, 0.0);\n  mipInt = max(mipInt, cubeUV_minMipLevel);\n  float faceSize = exp2(mipInt);\n  float texelSize = 1.0 / (3.0 * cubeUV_maxTileSize);\n  vec2 uv = getUV(direction, face) * (faceSize - 1.0);\n  vec2 f = fract(uv);\n  uv += 0.5 - f;\n  if (face > 2.0) {\n    uv.y += faceSize;\n    face -= 3.0;\n  }\n  uv.x += face * faceSize;\n  if(mipInt < cubeUV_maxMipLevel){\n    uv.y += 2.0 * cubeUV_maxTileSize;\n  }\n  uv.y += filterInt * 2.0 * cubeUV_minTileSize;\n  uv.x += 3.0 * max(0.0, cubeUV_maxTileSize - 2.0 * faceSize);\n  uv *= texelSize;\n  vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n  uv.x += texelSize;\n  vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n  uv.y += texelSize;\n  vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n  uv.x -= texelSize;\n  vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n  vec3 tm = mix(tl, tr, f.x);\n  vec3 bm = mix(bl, br, f.x);\n  return mix(tm, bm, f.y);\n}\n#define r0 1.0\n#define v0 0.339\n#define m0 -2.0\n#define r1 0.8\n#define v1 0.276\n#define m1 -1.0\n#define r4 0.4\n#define v4 0.046\n#define m4 2.0\n#define r5 0.305\n#define v5 0.016\n#define m5 3.0\n#define r6 0.21\n#define v6 0.0038\n#define m6 4.0\nfloat roughnessToMip(float roughness) {\n  float mip = 0.0;\n  if (roughness >= r1) {\n    mip = (r0 - roughness) * (m1 - m0) / (r0 - r1) + m0;\n  } else if (roughness >= r4) {\n    mip = (r1 - roughness) * (m4 - m1) / (r1 - r4) + m1;\n  } else if (roughness >= r5) {\n    mip = (r4 - roughness) * (m5 - m4) / (r4 - r5) + m4;\n  } else if (roughness >= r6) {\n    mip = (r5 - roughness) * (m6 - m5) / (r5 - r6) + m5;\n  } else {\n    mip = -2.0 * log2(1.16 * roughness);  }\n  return mip;\n}\nvec4 textureCubeUV(sampler2D envMap, vec3 sampleDir, float roughness) {\n  float mip = clamp(roughnessToMip(roughness), m0, cubeUV_maxMipLevel);\n  float mipF = fract(mip);\n  float mipInt = floor(mip);\n  vec3 color0 = bilinearCubeUV(envMap, sampleDir, mipInt);\n  if (mipF == 0.0) {\n    return vec4(color0, 1.0);\n  } else {\n    vec3 color1 = bilinearCubeUV(envMap, sampleDir, mipInt + 1.0);\n    return vec4(mix(color0, color1, mipF), 1.0);\n  }\n}\n#endif";

	var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\ttransformedNormal = mat3( instanceMatrix ) * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";

	var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";

	var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";

	var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";

	var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";

	var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";

	var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value )  {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";

	var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\t\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t}  else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";

	var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";

	var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";

	var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";

	var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) { \n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";

	var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";

	var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";

	var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";

	var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";

	var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";

	var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";

	var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";

	var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif";

	var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight  ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";

	var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t  vec3 reflectVec = reflect( -viewDir, normal );\n\t\t  reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t  vec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";

	var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";

	var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";

	var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";

	var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";

	var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = saturate( clearcoat );\tmaterial.clearcoatRoughness = max( clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";

	var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3(    0, 1,    0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";

	var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( pointLight.shadow, directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( spotLight.shadow, directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( directionalLight.shadow, directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";

	var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";

	var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";

	var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";

	var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";

	var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";

	var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";

	var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";

	var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";

	var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";

	var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";

	var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";

	var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";

	var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";

	var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";

	var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";

	var normal_fragment_begin = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";

	var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";

	var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tmat3 tsn = mat3( S, T, N );\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";

	var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";

	var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN );\n\t#endif\n#endif";

	var clearcoat_normalmap_pars_fragment = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";

	var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";

	var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";

	var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";

	var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";

	var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";

	var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";

	var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";

	var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t  f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t  texture2DCompare( shadowMap, uv + + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t  f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";

	var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";

	var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif";

	var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= all( bvec2( directionalLight.shadow, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= all( bvec2( spotLight.shadow, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= all( bvec2( pointLight.shadow, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}";

	var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";

	var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";

	var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";

	var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix  = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";

	var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";

	var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";

	var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";

	var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( ( color * ( 2.51 * color + 0.03 ) ) / ( color * ( 2.43 * color + 0.59 ) + 0.14 ) );\n}";

	var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";

	var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";

	var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";

	var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";

	var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";

	var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";

	var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";

	var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";

	var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";

	var cube_frag = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";

	var cube_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";

	var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}";

	var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}";

	var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";

	var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";

	var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";

	var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";

	var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";

	var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";

	var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";

	var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";

	var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";

	var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";

	var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";

	var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";

	var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";

	var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";

	var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";

	var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";

	var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSPARENCY\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSPARENCY\n\tuniform float transparency;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSPARENCY\n\t\tdiffuseColor.a *= saturate( 1. - transparency + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";

	var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";

	var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";

	var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";

	var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";

	var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";

	var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";

	var shadow_vert = "#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";

	var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";

	var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";

	var ShaderChunk = {
		alphamap_fragment: alphamap_fragment,
		alphamap_pars_fragment: alphamap_pars_fragment,
		alphatest_fragment: alphatest_fragment,
		aomap_fragment: aomap_fragment,
		aomap_pars_fragment: aomap_pars_fragment,
		begin_vertex: begin_vertex,
		beginnormal_vertex: beginnormal_vertex,
		bsdfs: bsdfs,
		bumpmap_pars_fragment: bumpmap_pars_fragment,
		clipping_planes_fragment: clipping_planes_fragment,
		clipping_planes_pars_fragment: clipping_planes_pars_fragment,
		clipping_planes_pars_vertex: clipping_planes_pars_vertex,
		clipping_planes_vertex: clipping_planes_vertex,
		color_fragment: color_fragment,
		color_pars_fragment: color_pars_fragment,
		color_pars_vertex: color_pars_vertex,
		color_vertex: color_vertex,
		common: common,
		cube_uv_reflection_fragment: cube_uv_reflection_fragment,
		defaultnormal_vertex: defaultnormal_vertex,
		displacementmap_pars_vertex: displacementmap_pars_vertex,
		displacementmap_vertex: displacementmap_vertex,
		emissivemap_fragment: emissivemap_fragment,
		emissivemap_pars_fragment: emissivemap_pars_fragment,
		encodings_fragment: encodings_fragment,
		encodings_pars_fragment: encodings_pars_fragment,
		envmap_fragment: envmap_fragment,
		envmap_common_pars_fragment: envmap_common_pars_fragment,
		envmap_pars_fragment: envmap_pars_fragment,
		envmap_pars_vertex: envmap_pars_vertex,
		envmap_physical_pars_fragment: envmap_physical_pars_fragment,
		envmap_vertex: envmap_vertex,
		fog_vertex: fog_vertex,
		fog_pars_vertex: fog_pars_vertex,
		fog_fragment: fog_fragment,
		fog_pars_fragment: fog_pars_fragment,
		gradientmap_pars_fragment: gradientmap_pars_fragment,
		lightmap_fragment: lightmap_fragment,
		lightmap_pars_fragment: lightmap_pars_fragment,
		lights_lambert_vertex: lights_lambert_vertex,
		lights_pars_begin: lights_pars_begin,
		lights_toon_fragment: lights_toon_fragment,
		lights_toon_pars_fragment: lights_toon_pars_fragment,
		lights_phong_fragment: lights_phong_fragment,
		lights_phong_pars_fragment: lights_phong_pars_fragment,
		lights_physical_fragment: lights_physical_fragment,
		lights_physical_pars_fragment: lights_physical_pars_fragment,
		lights_fragment_begin: lights_fragment_begin,
		lights_fragment_maps: lights_fragment_maps,
		lights_fragment_end: lights_fragment_end,
		logdepthbuf_fragment: logdepthbuf_fragment,
		logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
		logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
		logdepthbuf_vertex: logdepthbuf_vertex,
		map_fragment: map_fragment,
		map_pars_fragment: map_pars_fragment,
		map_particle_fragment: map_particle_fragment,
		map_particle_pars_fragment: map_particle_pars_fragment,
		metalnessmap_fragment: metalnessmap_fragment,
		metalnessmap_pars_fragment: metalnessmap_pars_fragment,
		morphnormal_vertex: morphnormal_vertex,
		morphtarget_pars_vertex: morphtarget_pars_vertex,
		morphtarget_vertex: morphtarget_vertex,
		normal_fragment_begin: normal_fragment_begin,
		normal_fragment_maps: normal_fragment_maps,
		normalmap_pars_fragment: normalmap_pars_fragment,
		clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
		clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
		clearcoat_normalmap_pars_fragment: clearcoat_normalmap_pars_fragment,
		packing: packing,
		premultiplied_alpha_fragment: premultiplied_alpha_fragment,
		project_vertex: project_vertex,
		dithering_fragment: dithering_fragment,
		dithering_pars_fragment: dithering_pars_fragment,
		roughnessmap_fragment: roughnessmap_fragment,
		roughnessmap_pars_fragment: roughnessmap_pars_fragment,
		shadowmap_pars_fragment: shadowmap_pars_fragment,
		shadowmap_pars_vertex: shadowmap_pars_vertex,
		shadowmap_vertex: shadowmap_vertex,
		shadowmask_pars_fragment: shadowmask_pars_fragment,
		skinbase_vertex: skinbase_vertex,
		skinning_pars_vertex: skinning_pars_vertex,
		skinning_vertex: skinning_vertex,
		skinnormal_vertex: skinnormal_vertex,
		specularmap_fragment: specularmap_fragment,
		specularmap_pars_fragment: specularmap_pars_fragment,
		tonemapping_fragment: tonemapping_fragment,
		tonemapping_pars_fragment: tonemapping_pars_fragment,
		uv_pars_fragment: uv_pars_fragment,
		uv_pars_vertex: uv_pars_vertex,
		uv_vertex: uv_vertex,
		uv2_pars_fragment: uv2_pars_fragment,
		uv2_pars_vertex: uv2_pars_vertex,
		uv2_vertex: uv2_vertex,
		worldpos_vertex: worldpos_vertex,

		background_frag: background_frag,
		background_vert: background_vert,
		cube_frag: cube_frag,
		cube_vert: cube_vert,
		depth_frag: depth_frag,
		depth_vert: depth_vert,
		distanceRGBA_frag: distanceRGBA_frag,
		distanceRGBA_vert: distanceRGBA_vert,
		equirect_frag: equirect_frag,
		equirect_vert: equirect_vert,
		linedashed_frag: linedashed_frag,
		linedashed_vert: linedashed_vert,
		meshbasic_frag: meshbasic_frag,
		meshbasic_vert: meshbasic_vert,
		meshlambert_frag: meshlambert_frag,
		meshlambert_vert: meshlambert_vert,
		meshmatcap_frag: meshmatcap_frag,
		meshmatcap_vert: meshmatcap_vert,
		meshtoon_frag: meshtoon_frag,
		meshtoon_vert: meshtoon_vert,
		meshphong_frag: meshphong_frag,
		meshphong_vert: meshphong_vert,
		meshphysical_frag: meshphysical_frag,
		meshphysical_vert: meshphysical_vert,
		normal_frag: normal_frag,
		normal_vert: normal_vert,
		points_frag: points_frag,
		points_vert: points_vert,
		shadow_frag: shadow_frag,
		shadow_vert: shadow_vert,
		sprite_frag: sprite_frag,
		sprite_vert: sprite_vert
	};

	/**
	 * @author alteredq / http://alteredqualia.com/
	 * @author mrdoob / http://mrdoob.com/
	 * @author mikael emtinger / http://gomo.se/
	 */

	var ShaderLib = {

		basic: {

			uniforms: mergeUniforms( [
				UniformsLib.common,
				UniformsLib.specularmap,
				UniformsLib.envmap,
				UniformsLib.aomap,
				UniformsLib.lightmap,
				UniformsLib.fog
			] ),

			vertexShader: ShaderChunk.meshbasic_vert,
			fragmentShader: ShaderChunk.meshbasic_frag

		},

		lambert: {

			uniforms: mergeUniforms( [
				UniformsLib.common,
				UniformsLib.specularmap,
				UniformsLib.envmap,
				UniformsLib.aomap,
				UniformsLib.lightmap,
				UniformsLib.emissivemap,
				UniformsLib.fog,
				UniformsLib.lights,
				{
					emissive: { value: new Color( 0x000000 ) }
				}
			] ),

			vertexShader: ShaderChunk.meshlambert_vert,
			fragmentShader: ShaderChunk.meshlambert_frag

		},

		phong: {

			uniforms: mergeUniforms( [
				UniformsLib.common,
				UniformsLib.specularmap,
				UniformsLib.envmap,
				UniformsLib.aomap,
				UniformsLib.lightmap,
				UniformsLib.emissivemap,
				UniformsLib.bumpmap,
				UniformsLib.normalmap,
				UniformsLib.displacementmap,
				UniformsLib.fog,
				UniformsLib.lights,
				{
					emissive: { value: new Color( 0x000000 ) },
					specular: { value: new Color( 0x111111 ) },
					shininess: { value: 30 }
				}
			] ),

			vertexShader: ShaderChunk.meshphong_vert,
			fragmentShader: ShaderChunk.meshphong_frag

		},

		standard: {

			uniforms: mergeUniforms( [
				UniformsLib.common,
				UniformsLib.envmap,
				UniformsLib.aomap,
				UniformsLib.lightmap,
				UniformsLib.emissivemap,
				UniformsLib.bumpmap,
				UniformsLib.normalmap,
				UniformsLib.displacementmap,
				UniformsLib.roughnessmap,
				UniformsLib.metalnessmap,
				UniformsLib.fog,
				UniformsLib.lights,
				{
					emissive: { value: new Color( 0x000000 ) },
					roughness: { value: 0.5 },
					metalness: { value: 0.5 },
					envMapIntensity: { value: 1 } // temporary
				}
			] ),

			vertexShader: ShaderChunk.meshphysical_vert,
			fragmentShader: ShaderChunk.meshphysical_frag

		},

		toon: {

			uniforms: mergeUniforms( [
				UniformsLib.common,
				UniformsLib.specularmap,
				UniformsLib.aomap,
				UniformsLib.lightmap,
				UniformsLib.emissivemap,
				UniformsLib.bumpmap,
				UniformsLib.normalmap,
				UniformsLib.displacementmap,
				UniformsLib.gradientmap,
				UniformsLib.fog,
				UniformsLib.lights,
				{
					emissive: { value: new Color( 0x000000 ) },
					specular: { value: new Color( 0x111111 ) },
					shininess: { value: 30 }
				}
			] ),

			vertexShader: ShaderChunk.meshtoon_vert,
			fragmentShader: ShaderChunk.meshtoon_frag

		},

		matcap: {

			uniforms: mergeUniforms( [
				UniformsLib.common,
				UniformsLib.bumpmap,
				UniformsLib.normalmap,
				UniformsLib.displacementmap,
				UniformsLib.fog,
				{
					matcap: { value: null }
				}
			] ),

			vertexShader: ShaderChunk.meshmatcap_vert,
			fragmentShader: ShaderChunk.meshmatcap_frag

		},

		points: {

			uniforms: mergeUniforms( [
				UniformsLib.points,
				UniformsLib.fog
			] ),

			vertexShader: ShaderChunk.points_vert,
			fragmentShader: ShaderChunk.points_frag

		},

		dashed: {

			uniforms: mergeUniforms( [
				UniformsLib.common,
				UniformsLib.fog,
				{
					scale: { value: 1 },
					dashSize: { value: 1 },
					totalSize: { value: 2 }
				}
			] ),

			vertexShader: ShaderChunk.linedashed_vert,
			fragmentShader: ShaderChunk.linedashed_frag

		},

		depth: {

			uniforms: mergeUniforms( [
				UniformsLib.common,
				UniformsLib.displacementmap
			] ),

			vertexShader: ShaderChunk.depth_vert,
			fragmentShader: ShaderChunk.depth_frag

		},

		normal: {

			uniforms: mergeUniforms( [
				UniformsLib.common,
				UniformsLib.bumpmap,
				UniformsLib.normalmap,
				UniformsLib.displacementmap,
				{
					opacity: { value: 1.0 }
				}
			] ),

			vertexShader: ShaderChunk.normal_vert,
			fragmentShader: ShaderChunk.normal_frag

		},

		sprite: {

			uniforms: mergeUniforms( [
				UniformsLib.sprite,
				UniformsLib.fog
			] ),

			vertexShader: ShaderChunk.sprite_vert,
			fragmentShader: ShaderChunk.sprite_frag

		},

		background: {

			uniforms: {
				uvTransform: { value: new Matrix3() },
				t2D: { value: null },
			},

			vertexShader: ShaderChunk.background_vert,
			fragmentShader: ShaderChunk.background_frag

		},
		/* -------------------------------------------------------------------------
		//	Cube map shader
		 ------------------------------------------------------------------------- */

		cube: {

			uniforms: mergeUniforms( [
				UniformsLib.envmap,
				{
					opacity: { value: 1.0 }
				}
			] ),

			vertexShader: ShaderChunk.cube_vert,
			fragmentShader: ShaderChunk.cube_frag

		},

		equirect: {

			uniforms: {
				tEquirect: { value: null },
			},

			vertexShader: ShaderChunk.equirect_vert,
			fragmentShader: ShaderChunk.equirect_frag

		},

		distanceRGBA: {

			uniforms: mergeUniforms( [
				UniformsLib.common,
				UniformsLib.displacementmap,
				{
					referencePosition: { value: new Vector3() },
					nearDistance: { value: 1 },
					farDistance: { value: 1000 }
				}
			] ),

			vertexShader: ShaderChunk.distanceRGBA_vert,
			fragmentShader: ShaderChunk.distanceRGBA_frag

		},

		shadow: {

			uniforms: mergeUniforms( [
				UniformsLib.lights,
				UniformsLib.fog,
				{
					color: { value: new Color( 0x00000 ) },
					opacity: { value: 1.0 }
				} ] ),

			vertexShader: ShaderChunk.shadow_vert,
			fragmentShader: ShaderChunk.shadow_frag

		}

	};

	ShaderLib.physical = {

		uniforms: mergeUniforms( [
			ShaderLib.standard.uniforms,
			{
				transparency: { value: 0 },
				clearcoat: { value: 0 },
				clearcoatRoughness: { value: 0 },
				sheen: { value: new Color( 0x000000 ) },
				clearcoatNormalScale: { value: new Vector2( 1, 1 ) },
				clearcoatNormalMap: { value: null },
			}
		] ),

		vertexShader: ShaderChunk.meshphysical_vert,
		fragmentShader: ShaderChunk.meshphysical_frag

	};

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function WebGLBackground( renderer, state, objects, premultipliedAlpha ) {

		var clearColor = new Color( 0x000000 );
		var clearAlpha = 0;

		var planeMesh;
		var boxMesh;

		var currentBackground = null;
		var currentBackgroundVersion = 0;
		var currentTonemapping = null;

		function render( renderList, scene, camera, forceClear ) {

			var background = scene.background;

			// Ignore background in AR
			// TODO: Reconsider this.

			var xr = renderer.xr;
			var session = xr.getSession && xr.getSession();

			if ( session && session.environmentBlendMode === 'additive' ) {

				background = null;

			}

			if ( background === null ) {

				setClear( clearColor, clearAlpha );

			} else if ( background && background.isColor ) {

				setClear( background, 1 );
				forceClear = true;

			}

			if ( renderer.autoClear || forceClear ) {

				renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );

			}

			if ( background && ( background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping ) ) {

				if ( boxMesh === undefined ) {

					boxMesh = new Mesh(
						new BoxBufferGeometry( 1, 1, 1 ),
						new ShaderMaterial( {
							type: 'BackgroundCubeMaterial',
							uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
							vertexShader: ShaderLib.cube.vertexShader,
							fragmentShader: ShaderLib.cube.fragmentShader,
							side: BackSide,
							depthTest: false,
							depthWrite: false,
							fog: false
						} )
					);

					boxMesh.geometry.deleteAttribute( 'normal' );
					boxMesh.geometry.deleteAttribute( 'uv' );

					boxMesh.onBeforeRender = function ( renderer, scene, camera ) {

						this.matrixWorld.copyPosition( camera.matrixWorld );

					};

					// enable code injection for non-built-in material
					Object.defineProperty( boxMesh.material, 'envMap', {

						get: function () {

							return this.uniforms.envMap.value;

						}

					} );

					objects.update( boxMesh );

				}

				var texture = background.isWebGLCubeRenderTarget ? background.texture : background;

				boxMesh.material.uniforms.envMap.value = texture;
				boxMesh.material.uniforms.flipEnvMap.value = texture.isCubeTexture ? - 1 : 1;

				if ( currentBackground !== background ||
					currentBackgroundVersion !== texture.version ||
					currentTonemapping !== renderer.toneMapping ) {

					boxMesh.material.needsUpdate = true;

					currentBackground = background;
					currentBackgroundVersion = texture.version;
					currentTonemapping = renderer.toneMapping;

				}

				// push to the pre-sorted opaque render list
				renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );

			} else if ( background && background.isTexture ) {

				if ( planeMesh === undefined ) {

					planeMesh = new Mesh(
						new PlaneBufferGeometry( 2, 2 ),
						new ShaderMaterial( {
							type: 'BackgroundMaterial',
							uniforms: cloneUniforms( ShaderLib.background.uniforms ),
							vertexShader: ShaderLib.background.vertexShader,
							fragmentShader: ShaderLib.background.fragmentShader,
							side: FrontSide,
							depthTest: false,
							depthWrite: false,
							fog: false
						} )
					);

					planeMesh.geometry.deleteAttribute( 'normal' );

					// enable code injection for non-built-in material
					Object.defineProperty( planeMesh.material, 'map', {

						get: function () {

							return this.uniforms.t2D.value;

						}

					} );

					objects.update( planeMesh );

				}

				planeMesh.material.uniforms.t2D.value = background;

				if ( background.matrixAutoUpdate === true ) {

					background.updateMatrix();

				}

				planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );

				if ( currentBackground !== background ||
					currentBackgroundVersion !== background.version ||
					currentTonemapping !== renderer.toneMapping ) {

					planeMesh.material.needsUpdate = true;

					currentBackground = background;
					currentBackgroundVersion = background.version;
					currentTonemapping = renderer.toneMapping;

				}


				// push to the pre-sorted opaque render list
				renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );

			}

		}

		function setClear( color, alpha ) {

			state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );

		}

		return {

			getClearColor: function () {

				return clearColor;

			},
			setClearColor: function ( color, alpha ) {

				clearColor.set( color );
				clearAlpha = alpha !== undefined ? alpha : 1;
				setClear( clearColor, clearAlpha );

			},
			getClearAlpha: function () {

				return clearAlpha;

			},
			setClearAlpha: function ( alpha ) {

				clearAlpha = alpha;
				setClear( clearColor, clearAlpha );

			},
			render: render

		};

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function WebGLBufferRenderer( gl, extensions, info, capabilities ) {

		var isWebGL2 = capabilities.isWebGL2;

		var mode;

		function setMode( value ) {

			mode = value;

		}

		function render( start, count ) {

			gl.drawArrays( mode, start, count );

			info.update( count, mode );

		}

		function renderInstances( geometry, start, count, primcount ) {

			if ( primcount === 0 ) { return; }

			var extension, methodName;

			if ( isWebGL2 ) {

				extension = gl;
				methodName = 'drawArraysInstanced';

			} else {

				extension = extensions.get( 'ANGLE_instanced_arrays' );
				methodName = 'drawArraysInstancedANGLE';

				if ( extension === null ) {

					console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
					return;

				}

			}

			extension[ methodName ]( mode, start, count, primcount );

			info.update( count, mode, primcount );

		}

		//

		this.setMode = setMode;
		this.render = render;
		this.renderInstances = renderInstances;

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function WebGLCapabilities( gl, extensions, parameters ) {

		var maxAnisotropy;

		function getMaxAnisotropy() {

			if ( maxAnisotropy !== undefined ) { return maxAnisotropy; }

			var extension = extensions.get( 'EXT_texture_filter_anisotropic' );

			if ( extension !== null ) {

				maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );

			} else {

				maxAnisotropy = 0;

			}

			return maxAnisotropy;

		}

		function getMaxPrecision( precision ) {

			if ( precision === 'highp' ) {

				if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
					gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {

					return 'highp';

				}

				precision = 'mediump';

			}

			if ( precision === 'mediump' ) {

				if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
					gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {

					return 'mediump';

				}

			}

			return 'lowp';

		}

		/* eslint-disable no-undef */
		var isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
			( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
		/* eslint-enable no-undef */

		var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
		var maxPrecision = getMaxPrecision( precision );

		if ( maxPrecision !== precision ) {

			console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
			precision = maxPrecision;

		}

		var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;

		var maxTextures = gl.getParameter( 34930 );
		var maxVertexTextures = gl.getParameter( 35660 );
		var maxTextureSize = gl.getParameter( 3379 );
		var maxCubemapSize = gl.getParameter( 34076 );

		var maxAttributes = gl.getParameter( 34921 );
		var maxVertexUniforms = gl.getParameter( 36347 );
		var maxVaryings = gl.getParameter( 36348 );
		var maxFragmentUniforms = gl.getParameter( 36349 );

		var vertexTextures = maxVertexTextures > 0;
		var floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' );
		var floatVertexTextures = vertexTextures && floatFragmentTextures;

		var maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;

		return {

			isWebGL2: isWebGL2,

			getMaxAnisotropy: getMaxAnisotropy,
			getMaxPrecision: getMaxPrecision,

			precision: precision,
			logarithmicDepthBuffer: logarithmicDepthBuffer,

			maxTextures: maxTextures,
			maxVertexTextures: maxVertexTextures,
			maxTextureSize: maxTextureSize,
			maxCubemapSize: maxCubemapSize,

			maxAttributes: maxAttributes,
			maxVertexUniforms: maxVertexUniforms,
			maxVaryings: maxVaryings,
			maxFragmentUniforms: maxFragmentUniforms,

			vertexTextures: vertexTextures,
			floatFragmentTextures: floatFragmentTextures,
			floatVertexTextures: floatVertexTextures,

			maxSamples: maxSamples

		};

	}

	/**
	 * @author tschw
	 */

	function WebGLClipping() {

		var scope = this,

			globalState = null,
			numGlobalPlanes = 0,
			localClippingEnabled = false,
			renderingShadows = false,

			plane = new Plane(),
			viewNormalMatrix = new Matrix3(),

			uniform = { value: null, needsUpdate: false };

		this.uniform = uniform;
		this.numPlanes = 0;
		this.numIntersection = 0;

		this.init = function ( planes, enableLocalClipping, camera ) {

			var enabled =
				planes.length !== 0 ||
				enableLocalClipping ||
				// enable state of previous frame - the clipping code has to
				// run another frame in order to reset the state:
				numGlobalPlanes !== 0 ||
				localClippingEnabled;

			localClippingEnabled = enableLocalClipping;

			globalState = projectPlanes( planes, camera, 0 );
			numGlobalPlanes = planes.length;

			return enabled;

		};

		this.beginShadows = function () {

			renderingShadows = true;
			projectPlanes( null );

		};

		this.endShadows = function () {

			renderingShadows = false;
			resetGlobalState();

		};

		this.setState = function ( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {

			if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {

				// there's no local clipping

				if ( renderingShadows ) {

					// there's no global clipping

					projectPlanes( null );

				} else {

					resetGlobalState();

				}

			} else {

				var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
					lGlobal = nGlobal * 4,

					dstArray = cache.clippingState || null;

				uniform.value = dstArray; // ensure unique state

				dstArray = projectPlanes( planes, camera, lGlobal, fromCache );

				for ( var i = 0; i !== lGlobal; ++ i ) {

					dstArray[ i ] = globalState[ i ];

				}

				cache.clippingState = dstArray;
				this.numIntersection = clipIntersection ? this.numPlanes : 0;
				this.numPlanes += nGlobal;

			}


		};

		function resetGlobalState() {

			if ( uniform.value !== globalState ) {

				uniform.value = globalState;
				uniform.needsUpdate = numGlobalPlanes > 0;

			}

			scope.numPlanes = numGlobalPlanes;
			scope.numIntersection = 0;

		}

		function projectPlanes( planes, camera, dstOffset, skipTransform ) {

			var nPlanes = planes !== null ? planes.length : 0,
				dstArray = null;

			if ( nPlanes !== 0 ) {

				dstArray = uniform.value;

				if ( skipTransform !== true || dstArray === null ) {

					var flatSize = dstOffset + nPlanes * 4,
						viewMatrix = camera.matrixWorldInverse;

					viewNormalMatrix.getNormalMatrix( viewMatrix );

					if ( dstArray === null || dstArray.length < flatSize ) {

						dstArray = new Float32Array( flatSize );

					}

					for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {

						plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );

						plane.normal.toArray( dstArray, i4 );
						dstArray[ i4 + 3 ] = plane.constant;

					}

				}

				uniform.value = dstArray;
				uniform.needsUpdate = true;

			}

			scope.numPlanes = nPlanes;

			return dstArray;

		}

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function WebGLExtensions( gl ) {

		var extensions = {};

		return {

			get: function ( name ) {

				if ( extensions[ name ] !== undefined ) {

					return extensions[ name ];

				}

				var extension;

				switch ( name ) {

					case 'WEBGL_depth_texture':
						extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
						break;

					case 'EXT_texture_filter_anisotropic':
						extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
						break;

					case 'WEBGL_compressed_texture_s3tc':
						extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
						break;

					case 'WEBGL_compressed_texture_pvrtc':
						extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
						break;

					default:
						extension = gl.getExtension( name );

				}

				if ( extension === null ) {

					console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );

				}

				extensions[ name ] = extension;

				return extension;

			}

		};

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function WebGLGeometries( gl, attributes, info ) {

		var geometries = new WeakMap();
		var wireframeAttributes = new WeakMap();

		function onGeometryDispose( event ) {

			var geometry = event.target;
			var buffergeometry = geometries.get( geometry );

			if ( buffergeometry.index !== null ) {

				attributes.remove( buffergeometry.index );

			}

			for ( var name in buffergeometry.attributes ) {

				attributes.remove( buffergeometry.attributes[ name ] );

			}

			geometry.removeEventListener( 'dispose', onGeometryDispose );

			geometries.delete( geometry );

			var attribute = wireframeAttributes.get( buffergeometry );

			if ( attribute ) {

				attributes.remove( attribute );
				wireframeAttributes.delete( buffergeometry );

			}

			//

			info.memory.geometries --;

		}

		function get( object, geometry ) {

			var buffergeometry = geometries.get( geometry );

			if ( buffergeometry ) { return buffergeometry; }

			geometry.addEventListener( 'dispose', onGeometryDispose );

			if ( geometry.isBufferGeometry ) {

				buffergeometry = geometry;

			} else if ( geometry.isGeometry ) {

				if ( geometry._bufferGeometry === undefined ) {

					geometry._bufferGeometry = new BufferGeometry().setFromObject( object );

				}

				buffergeometry = geometry._bufferGeometry;

			}

			geometries.set( geometry, buffergeometry );

			info.memory.geometries ++;

			return buffergeometry;

		}

		function update( geometry ) {

			var index = geometry.index;
			var geometryAttributes = geometry.attributes;

			if ( index !== null ) {

				attributes.update( index, 34963 );

			}

			for ( var name in geometryAttributes ) {

				attributes.update( geometryAttributes[ name ], 34962 );

			}

			// morph targets

			var morphAttributes = geometry.morphAttributes;

			for ( var name in morphAttributes ) {

				var array = morphAttributes[ name ];

				for ( var i = 0, l = array.length; i < l; i ++ ) {

					attributes.update( array[ i ], 34962 );

				}

			}

		}

		function updateWireframeAttribute( geometry ) {

			var indices = [];

			var geometryIndex = geometry.index;
			var geometryPosition = geometry.attributes.position;
			var version = 0;

			if ( geometryIndex !== null ) {

				var array = geometryIndex.array;
				version = geometryIndex.version;

				for ( var i = 0, l = array.length; i < l; i += 3 ) {

					var a = array[ i + 0 ];
					var b = array[ i + 1 ];
					var c = array[ i + 2 ];

					indices.push( a, b, b, c, c, a );

				}

			} else {

				var array = geometryPosition.array;
				version = geometryPosition.version;

				for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {

					var a = i + 0;
					var b = i + 1;
					var c = i + 2;

					indices.push( a, b, b, c, c, a );

				}

			}

			var attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
			attribute.version = version;

			attributes.update( attribute, 34963 );

			//

			var previousAttribute = wireframeAttributes.get( geometry );

			if ( previousAttribute ) { attributes.remove( previousAttribute ); }

			//

			wireframeAttributes.set( geometry, attribute );

		}

		function getWireframeAttribute( geometry ) {

			var currentAttribute = wireframeAttributes.get( geometry );

			if ( currentAttribute ) {

				var geometryIndex = geometry.index;

				if ( geometryIndex !== null ) {

					// if the attribute is obsolete, create a new one

					if ( currentAttribute.version < geometryIndex.version ) {

						updateWireframeAttribute( geometry );

					}

				}

			} else {

				updateWireframeAttribute( geometry );

			}

			return wireframeAttributes.get( geometry );

		}

		return {

			get: get,
			update: update,

			getWireframeAttribute: getWireframeAttribute

		};

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {

		var isWebGL2 = capabilities.isWebGL2;

		var mode;

		function setMode( value ) {

			mode = value;

		}

		var type, bytesPerElement;

		function setIndex( value ) {

			type = value.type;
			bytesPerElement = value.bytesPerElement;

		}

		function render( start, count ) {

			gl.drawElements( mode, count, type, start * bytesPerElement );

			info.update( count, mode );

		}

		function renderInstances( geometry, start, count, primcount ) {

			if ( primcount === 0 ) { return; }

			var extension, methodName;

			if ( isWebGL2 ) {

				extension = gl;
				methodName = 'drawElementsInstanced';

			} else {

				extension = extensions.get( 'ANGLE_instanced_arrays' );
				methodName = 'drawElementsInstancedANGLE';

				if ( extension === null ) {

					console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
					return;

				}

			}

			extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );

			info.update( count, mode, primcount );

		}

		//

		this.setMode = setMode;
		this.setIndex = setIndex;
		this.render = render;
		this.renderInstances = renderInstances;

	}

	/**
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	function WebGLInfo( gl ) {

		var memory = {
			geometries: 0,
			textures: 0
		};

		var render = {
			frame: 0,
			calls: 0,
			triangles: 0,
			points: 0,
			lines: 0
		};

		function update( count, mode, instanceCount ) {

			instanceCount = instanceCount || 1;

			render.calls ++;

			switch ( mode ) {

				case 4:
					render.triangles += instanceCount * ( count / 3 );
					break;

				case 1:
					render.lines += instanceCount * ( count / 2 );
					break;

				case 3:
					render.lines += instanceCount * ( count - 1 );
					break;

				case 2:
					render.lines += instanceCount * count;
					break;

				case 0:
					render.points += instanceCount * count;
					break;

				default:
					console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
					break;

			}

		}

		function reset() {

			render.frame ++;
			render.calls = 0;
			render.triangles = 0;
			render.points = 0;
			render.lines = 0;

		}

		return {
			memory: memory,
			render: render,
			programs: null,
			autoReset: true,
			reset: reset,
			update: update
		};

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function absNumericalSort( a, b ) {

		return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );

	}

	function WebGLMorphtargets( gl ) {

		var influencesList = {};
		var morphInfluences = new Float32Array( 8 );

		function update( object, geometry, material, program ) {

			var objectInfluences = object.morphTargetInfluences;

			// When object doesn't have morph target influences defined, we treat it as a 0-length array
			// This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences

			var length = objectInfluences === undefined ? 0 : objectInfluences.length;

			var influences = influencesList[ geometry.id ];

			if ( influences === undefined ) {

				// initialise list

				influences = [];

				for ( var i = 0; i < length; i ++ ) {

					influences[ i ] = [ i, 0 ];

				}

				influencesList[ geometry.id ] = influences;

			}

			var morphTargets = material.morphTargets && geometry.morphAttributes.position;
			var morphNormals = material.morphNormals && geometry.morphAttributes.normal;

			// Remove current morphAttributes

			for ( var i = 0; i < length; i ++ ) {

				var influence = influences[ i ];

				if ( influence[ 1 ] !== 0 ) {

					if ( morphTargets ) { geometry.deleteAttribute( 'morphTarget' + i ); }
					if ( morphNormals ) { geometry.deleteAttribute( 'morphNormal' + i ); }

				}

			}

			// Collect influences

			for ( var i = 0; i < length; i ++ ) {

				var influence = influences[ i ];

				influence[ 0 ] = i;
				influence[ 1 ] = objectInfluences[ i ];

			}

			influences.sort( absNumericalSort );

			// Add morphAttributes

			var morphInfluencesSum = 0;

			for ( var i = 0; i < 8; i ++ ) {

				var influence = influences[ i ];

				if ( influence ) {

					var index = influence[ 0 ];
					var value = influence[ 1 ];

					if ( value ) {

						if ( morphTargets ) { geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] ); }
						if ( morphNormals ) { geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] ); }

						morphInfluences[ i ] = value;
						morphInfluencesSum += value;
						continue;

					}

				}

				morphInfluences[ i ] = 0;

			}

			// GLSL shader uses formula baseinfluence * base + sum(target * influence)
			// This allows us to switch between absolute morphs and relative morphs without changing shader code
			// When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
			var morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;

			program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
			program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );

		}

		return {

			update: update

		};

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function WebGLObjects( gl, geometries, attributes, info ) {

		var updateList = {};

		function update( object ) {

			var frame = info.render.frame;

			var geometry = object.geometry;
			var buffergeometry = geometries.get( object, geometry );

			// Update once per frame

			if ( updateList[ buffergeometry.id ] !== frame ) {

				if ( geometry.isGeometry ) {

					buffergeometry.updateFromObject( object );

				}

				geometries.update( buffergeometry );

				updateList[ buffergeometry.id ] = frame;

			}

			if ( object.isInstancedMesh ) {

				attributes.update( object.instanceMatrix, 34962 );

			}

			return buffergeometry;

		}

		function dispose() {

			updateList = {};

		}

		return {

			update: update,
			dispose: dispose

		};

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {

		images = images !== undefined ? images : [];
		mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
		format = format !== undefined ? format : RGBFormat;

		Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );

		this.flipY = false;

	}

	CubeTexture.prototype = Object.create( Texture.prototype );
	CubeTexture.prototype.constructor = CubeTexture;

	CubeTexture.prototype.isCubeTexture = true;

	Object.defineProperty( CubeTexture.prototype, 'images', {

		get: function () {

			return this.image;

		},

		set: function ( value ) {

			this.image = value;

		}

	} );

	/**
	 * @author Takahiro https://github.com/takahirox
	 */

	function DataTexture2DArray( data, width, height, depth ) {

		Texture.call( this, null );

		this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 };

		this.magFilter = NearestFilter;
		this.minFilter = NearestFilter;

		this.wrapR = ClampToEdgeWrapping;

		this.generateMipmaps = false;
		this.flipY = false;

		this.needsUpdate = true;

	}

	DataTexture2DArray.prototype = Object.create( Texture.prototype );
	DataTexture2DArray.prototype.constructor = DataTexture2DArray;
	DataTexture2DArray.prototype.isDataTexture2DArray = true;

	/**
	 * @author Artur Trzesiok
	 */

	function DataTexture3D( data, width, height, depth ) {

		// We're going to add .setXXX() methods for setting properties later.
		// Users can still set in DataTexture3D directly.
		//
		//	var texture = new THREE.DataTexture3D( data, width, height, depth );
		// 	texture.anisotropy = 16;
		//
		// See #14839

		Texture.call( this, null );

		this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 };

		this.magFilter = NearestFilter;
		this.minFilter = NearestFilter;

		this.wrapR = ClampToEdgeWrapping;

		this.generateMipmaps = false;
		this.flipY = false;

		this.needsUpdate = true;


	}

	DataTexture3D.prototype = Object.create( Texture.prototype );
	DataTexture3D.prototype.constructor = DataTexture3D;
	DataTexture3D.prototype.isDataTexture3D = true;

	/**
	 * @author tschw
	 * @author Mugen87 / https://github.com/Mugen87
	 * @author mrdoob / http://mrdoob.com/
	 *
	 * Uniforms of a program.
	 * Those form a tree structure with a special top-level container for the root,
	 * which you get by calling 'new WebGLUniforms( gl, program )'.
	 *
	 *
	 * Properties of inner nodes including the top-level container:
	 *
	 * .seq - array of nested uniforms
	 * .map - nested uniforms by name
	 *
	 *
	 * Methods of all nodes except the top-level container:
	 *
	 * .setValue( gl, value, [textures] )
	 *
	 * 		uploads a uniform value(s)
	 *  	the 'textures' parameter is needed for sampler uniforms
	 *
	 *
	 * Static methods of the top-level container (textures factorizations):
	 *
	 * .upload( gl, seq, values, textures )
	 *
	 * 		sets uniforms in 'seq' to 'values[id].value'
	 *
	 * .seqWithValue( seq, values ) : filteredSeq
	 *
	 * 		filters 'seq' entries with corresponding entry in values
	 *
	 *
	 * Methods of the top-level container (textures factorizations):
	 *
	 * .setValue( gl, name, value, textures )
	 *
	 * 		sets uniform with  name 'name' to 'value'
	 *
	 * .setOptional( gl, obj, prop )
	 *
	 * 		like .set for an optional property of the object
	 *
	 */

	var emptyTexture = new Texture();
	var emptyTexture2dArray = new DataTexture2DArray();
	var emptyTexture3d = new DataTexture3D();
	var emptyCubeTexture = new CubeTexture();

	// --- Utilities ---

	// Array Caches (provide typed arrays for temporary by size)

	var arrayCacheF32 = [];
	var arrayCacheI32 = [];

	// Float32Array caches used for uploading Matrix uniforms

	var mat4array = new Float32Array( 16 );
	var mat3array = new Float32Array( 9 );
	var mat2array = new Float32Array( 4 );

	// Flattening for arrays of vectors and matrices

	function flatten( array, nBlocks, blockSize ) {

		var firstElem = array[ 0 ];

		if ( firstElem <= 0 || firstElem > 0 ) { return array; }
		// unoptimized: ! isNaN( firstElem )
		// see http://jacksondunstan.com/articles/983

		var n = nBlocks * blockSize,
			r = arrayCacheF32[ n ];

		if ( r === undefined ) {

			r = new Float32Array( n );
			arrayCacheF32[ n ] = r;

		}

		if ( nBlocks !== 0 ) {

			firstElem.toArray( r, 0 );

			for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {

				offset += blockSize;
				array[ i ].toArray( r, offset );

			}

		}

		return r;

	}

	function arraysEqual( a, b ) {

		if ( a.length !== b.length ) { return false; }

		for ( var i = 0, l = a.length; i < l; i ++ ) {

			if ( a[ i ] !== b[ i ] ) { return false; }

		}

		return true;

	}

	function copyArray( a, b ) {

		for ( var i = 0, l = b.length; i < l; i ++ ) {

			a[ i ] = b[ i ];

		}

	}

	// Texture unit allocation

	function allocTexUnits( textures, n ) {

		var r = arrayCacheI32[ n ];

		if ( r === undefined ) {

			r = new Int32Array( n );
			arrayCacheI32[ n ] = r;

		}

		for ( var i = 0; i !== n; ++ i )
			{ r[ i ] = textures.allocateTextureUnit(); }

		return r;

	}

	// --- Setters ---

	// Note: Defining these methods externally, because they come in a bunch
	// and this way their names minify.

	// Single scalar

	function setValueV1f( gl, v ) {

		var cache = this.cache;

		if ( cache[ 0 ] === v ) { return; }

		gl.uniform1f( this.addr, v );

		cache[ 0 ] = v;

	}

	// Single float vector (from flat array or THREE.VectorN)

	function setValueV2f( gl, v ) {

		var cache = this.cache;

		if ( v.x !== undefined ) {

			if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {

				gl.uniform2f( this.addr, v.x, v.y );

				cache[ 0 ] = v.x;
				cache[ 1 ] = v.y;

			}

		} else {

			if ( arraysEqual( cache, v ) ) { return; }

			gl.uniform2fv( this.addr, v );

			copyArray( cache, v );

		}

	}

	function setValueV3f( gl, v ) {

		var cache = this.cache;

		if ( v.x !== undefined ) {

			if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {

				gl.uniform3f( this.addr, v.x, v.y, v.z );

				cache[ 0 ] = v.x;
				cache[ 1 ] = v.y;
				cache[ 2 ] = v.z;

			}

		} else if ( v.r !== undefined ) {

			if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {

				gl.uniform3f( this.addr, v.r, v.g, v.b );

				cache[ 0 ] = v.r;
				cache[ 1 ] = v.g;
				cache[ 2 ] = v.b;

			}

		} else {

			if ( arraysEqual( cache, v ) ) { return; }

			gl.uniform3fv( this.addr, v );

			copyArray( cache, v );

		}

	}

	function setValueV4f( gl, v ) {

		var cache = this.cache;

		if ( v.x !== undefined ) {

			if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {

				gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );

				cache[ 0 ] = v.x;
				cache[ 1 ] = v.y;
				cache[ 2 ] = v.z;
				cache[ 3 ] = v.w;

			}

		} else {

			if ( arraysEqual( cache, v ) ) { return; }

			gl.uniform4fv( this.addr, v );

			copyArray( cache, v );

		}

	}

	// Single matrix (from flat array or MatrixN)

	function setValueM2( gl, v ) {

		var cache = this.cache;
		var elements = v.elements;

		if ( elements === undefined ) {

			if ( arraysEqual( cache, v ) ) { return; }

			gl.uniformMatrix2fv( this.addr, false, v );

			copyArray( cache, v );

		} else {

			if ( arraysEqual( cache, elements ) ) { return; }

			mat2array.set( elements );

			gl.uniformMatrix2fv( this.addr, false, mat2array );

			copyArray( cache, elements );

		}

	}

	function setValueM3( gl, v ) {

		var cache = this.cache;
		var elements = v.elements;

		if ( elements === undefined ) {

			if ( arraysEqual( cache, v ) ) { return; }

			gl.uniformMatrix3fv( this.addr, false, v );

			copyArray( cache, v );

		} else {

			if ( arraysEqual( cache, elements ) ) { return; }

			mat3array.set( elements );

			gl.uniformMatrix3fv( this.addr, false, mat3array );

			copyArray( cache, elements );

		}

	}

	function setValueM4( gl, v ) {

		var cache = this.cache;
		var elements = v.elements;

		if ( elements === undefined ) {

			if ( arraysEqual( cache, v ) ) { return; }

			gl.uniformMatrix4fv( this.addr, false, v );

			copyArray( cache, v );

		} else {

			if ( arraysEqual( cache, elements ) ) { return; }

			mat4array.set( elements );

			gl.uniformMatrix4fv( this.addr, false, mat4array );

			copyArray( cache, elements );

		}

	}

	// Single texture (2D / Cube)

	function setValueT1( gl, v, textures ) {

		var cache = this.cache;
		var unit = textures.allocateTextureUnit();

		if ( cache[ 0 ] !== unit ) {

			gl.uniform1i( this.addr, unit );
			cache[ 0 ] = unit;

		}

		textures.safeSetTexture2D( v || emptyTexture, unit );

	}

	function setValueT2DArray1( gl, v, textures ) {

		var cache = this.cache;
		var unit = textures.allocateTextureUnit();

		if ( cache[ 0 ] !== unit ) {

			gl.uniform1i( this.addr, unit );
			cache[ 0 ] = unit;

		}

		textures.setTexture2DArray( v || emptyTexture2dArray, unit );

	}

	function setValueT3D1( gl, v, textures ) {

		var cache = this.cache;
		var unit = textures.allocateTextureUnit();

		if ( cache[ 0 ] !== unit ) {

			gl.uniform1i( this.addr, unit );
			cache[ 0 ] = unit;

		}

		textures.setTexture3D( v || emptyTexture3d, unit );

	}

	function setValueT6( gl, v, textures ) {

		var cache = this.cache;
		var unit = textures.allocateTextureUnit();

		if ( cache[ 0 ] !== unit ) {

			gl.uniform1i( this.addr, unit );
			cache[ 0 ] = unit;

		}

		textures.safeSetTextureCube( v || emptyCubeTexture, unit );

	}

	// Integer / Boolean vectors or arrays thereof (always flat arrays)

	function setValueV1i( gl, v ) {

		var cache = this.cache;

		if ( cache[ 0 ] === v ) { return; }

		gl.uniform1i( this.addr, v );

		cache[ 0 ] = v;

	}

	function setValueV2i( gl, v ) {

		var cache = this.cache;

		if ( arraysEqual( cache, v ) ) { return; }

		gl.uniform2iv( this.addr, v );

		copyArray( cache, v );

	}

	function setValueV3i( gl, v ) {

		var cache = this.cache;

		if ( arraysEqual( cache, v ) ) { return; }

		gl.uniform3iv( this.addr, v );

		copyArray( cache, v );

	}

	function setValueV4i( gl, v ) {

		var cache = this.cache;

		if ( arraysEqual( cache, v ) ) { return; }

		gl.uniform4iv( this.addr, v );

		copyArray( cache, v );

	}

	// uint

	function setValueV1ui( gl, v ) {

		var cache = this.cache;

		if ( cache[ 0 ] === v ) { return; }

		gl.uniform1ui( this.addr, v );

		cache[ 0 ] = v;

	}

	// Helper to pick the right setter for the singular case

	function getSingularSetter( type ) {

		switch ( type ) {

			case 0x1406: return setValueV1f; // FLOAT
			case 0x8b50: return setValueV2f; // _VEC2
			case 0x8b51: return setValueV3f; // _VEC3
			case 0x8b52: return setValueV4f; // _VEC4

			case 0x8b5a: return setValueM2; // _MAT2
			case 0x8b5b: return setValueM3; // _MAT3
			case 0x8b5c: return setValueM4; // _MAT4

			case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
			case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
			case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
			case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4

			case 0x1405: return setValueV1ui; // UINT

			case 0x8b5e: // SAMPLER_2D
			case 0x8d66: // SAMPLER_EXTERNAL_OES
			case 0x8dca: // INT_SAMPLER_2D
			case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
			case 0x8b62: // SAMPLER_2D_SHADOW
				return setValueT1;

			case 0x8b5f: // SAMPLER_3D
			case 0x8dcb: // INT_SAMPLER_3D
			case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
				return setValueT3D1;

			case 0x8b60: // SAMPLER_CUBE
			case 0x8dcc: // INT_SAMPLER_CUBE
			case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
			case 0x8dc5: // SAMPLER_CUBE_SHADOW
				return setValueT6;

			case 0x8dc1: // SAMPLER_2D_ARRAY
			case 0x8dcf: // INT_SAMPLER_2D_ARRAY
			case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
			case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
				return setValueT2DArray1;

		}

	}

	// Array of scalars
	function setValueV1fArray( gl, v ) {

		gl.uniform1fv( this.addr, v );

	}

	// Integer / Boolean vectors or arrays thereof (always flat arrays)
	function setValueV1iArray( gl, v ) {

		gl.uniform1iv( this.addr, v );

	}

	function setValueV2iArray( gl, v ) {

		gl.uniform2iv( this.addr, v );

	}

	function setValueV3iArray( gl, v ) {

		gl.uniform3iv( this.addr, v );

	}

	function setValueV4iArray( gl, v ) {

		gl.uniform4iv( this.addr, v );

	}


	// Array of vectors (flat or from THREE classes)

	function setValueV2fArray( gl, v ) {

		var data = flatten( v, this.size, 2 );

		gl.uniform2fv( this.addr, data );

	}

	function setValueV3fArray( gl, v ) {

		var data = flatten( v, this.size, 3 );

		gl.uniform3fv( this.addr, data );

	}

	function setValueV4fArray( gl, v ) {

		var data = flatten( v, this.size, 4 );

		gl.uniform4fv( this.addr, data );

	}

	// Array of matrices (flat or from THREE clases)

	function setValueM2Array( gl, v ) {

		var data = flatten( v, this.size, 4 );

		gl.uniformMatrix2fv( this.addr, false, data );

	}

	function setValueM3Array( gl, v ) {

		var data = flatten( v, this.size, 9 );

		gl.uniformMatrix3fv( this.addr, false, data );

	}

	function setValueM4Array( gl, v ) {

		var data = flatten( v, this.size, 16 );

		gl.uniformMatrix4fv( this.addr, false, data );

	}

	// Array of textures (2D / Cube)

	function setValueT1Array( gl, v, textures ) {

		var n = v.length;

		var units = allocTexUnits( textures, n );

		gl.uniform1iv( this.addr, units );

		for ( var i = 0; i !== n; ++ i ) {

			textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );

		}

	}

	function setValueT6Array( gl, v, textures ) {

		var n = v.length;

		var units = allocTexUnits( textures, n );

		gl.uniform1iv( this.addr, units );

		for ( var i = 0; i !== n; ++ i ) {

			textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );

		}

	}

	// Helper to pick the right setter for a pure (bottom-level) array

	function getPureArraySetter( type ) {

		switch ( type ) {

			case 0x1406: return setValueV1fArray; // FLOAT
			case 0x8b50: return setValueV2fArray; // _VEC2
			case 0x8b51: return setValueV3fArray; // _VEC3
			case 0x8b52: return setValueV4fArray; // _VEC4

			case 0x8b5a: return setValueM2Array; // _MAT2
			case 0x8b5b: return setValueM3Array; // _MAT3
			case 0x8b5c: return setValueM4Array; // _MAT4

			case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
			case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
			case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
			case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4

			case 0x8b5e: // SAMPLER_2D
			case 0x8d66: // SAMPLER_EXTERNAL_OES
			case 0x8dca: // INT_SAMPLER_2D
			case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
			case 0x8b62: // SAMPLER_2D_SHADOW
				return setValueT1Array;

			case 0x8b60: // SAMPLER_CUBE
			case 0x8dcc: // INT_SAMPLER_CUBE
			case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
			case 0x8dc5: // SAMPLER_CUBE_SHADOW
				return setValueT6Array;

		}

	}

	// --- Uniform Classes ---

	function SingleUniform( id, activeInfo, addr ) {

		this.id = id;
		this.addr = addr;
		this.cache = [];
		this.setValue = getSingularSetter( activeInfo.type );

		// this.path = activeInfo.name; // DEBUG

	}

	function PureArrayUniform( id, activeInfo, addr ) {

		this.id = id;
		this.addr = addr;
		this.cache = [];
		this.size = activeInfo.size;
		this.setValue = getPureArraySetter( activeInfo.type );

		// this.path = activeInfo.name; // DEBUG

	}

	PureArrayUniform.prototype.updateCache = function ( data ) {

		var cache = this.cache;

		if ( data instanceof Float32Array && cache.length !== data.length ) {

			this.cache = new Float32Array( data.length );

		}

		copyArray( cache, data );

	};

	function StructuredUniform( id ) {

		this.id = id;

		this.seq = [];
		this.map = {};

	}

	StructuredUniform.prototype.setValue = function ( gl, value, textures ) {

		var seq = this.seq;

		for ( var i = 0, n = seq.length; i !== n; ++ i ) {

			var u = seq[ i ];
			u.setValue( gl, value[ u.id ], textures );

		}

	};

	// --- Top-level ---

	// Parser - builds up the property tree from the path strings

	var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;

	// extracts
	// 	- the identifier (member name or array index)
	//  - followed by an optional right bracket (found when array index)
	//  - followed by an optional left bracket or dot (type of subscript)
	//
	// Note: These portions can be read in a non-overlapping fashion and
	// allow straightforward parsing of the hierarchy that WebGL encodes
	// in the uniform names.

	function addUniform( container, uniformObject ) {

		container.seq.push( uniformObject );
		container.map[ uniformObject.id ] = uniformObject;

	}

	function parseUniform( activeInfo, addr, container ) {

		var path = activeInfo.name,
			pathLength = path.length;

		// reset RegExp object, because of the early exit of a previous run
		RePathPart.lastIndex = 0;

		while ( true ) {

			var match = RePathPart.exec( path ),
				matchEnd = RePathPart.lastIndex,

				id = match[ 1 ],
				idIsIndex = match[ 2 ] === ']',
				subscript = match[ 3 ];

			if ( idIsIndex ) { id = id | 0; } // convert to integer

			if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {

				// bare name or "pure" bottom-level array "[0]" suffix

				addUniform( container, subscript === undefined ?
					new SingleUniform( id, activeInfo, addr ) :
					new PureArrayUniform( id, activeInfo, addr ) );

				break;

			} else {

				// step into inner node / create it in case it doesn't exist

				var map = container.map, next = map[ id ];

				if ( next === undefined ) {

					next = new StructuredUniform( id );
					addUniform( container, next );

				}

				container = next;

			}

		}

	}

	// Root Container

	function WebGLUniforms( gl, program ) {

		this.seq = [];
		this.map = {};

		var n = gl.getProgramParameter( program, 35718 );

		for ( var i = 0; i < n; ++ i ) {

			var info = gl.getActiveUniform( program, i ),
				addr = gl.getUniformLocation( program, info.name );

			parseUniform( info, addr, this );

		}

	}

	WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {

		var u = this.map[ name ];

		if ( u !== undefined ) { u.setValue( gl, value, textures ); }

	};

	WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {

		var v = object[ name ];

		if ( v !== undefined ) { this.setValue( gl, name, v ); }

	};


	// Static interface

	WebGLUniforms.upload = function ( gl, seq, values, textures ) {

		for ( var i = 0, n = seq.length; i !== n; ++ i ) {

			var u = seq[ i ],
				v = values[ u.id ];

			if ( v.needsUpdate !== false ) {

				// note: always updating when .needsUpdate is undefined
				u.setValue( gl, v.value, textures );

			}

		}

	};

	WebGLUniforms.seqWithValue = function ( seq, values ) {

		var r = [];

		for ( var i = 0, n = seq.length; i !== n; ++ i ) {

			var u = seq[ i ];
			if ( u.id in values ) { r.push( u ); }

		}

		return r;

	};

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function WebGLShader( gl, type, string ) {

		var shader = gl.createShader( type );

		gl.shaderSource( shader, string );
		gl.compileShader( shader );

		return shader;

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	var programIdCount = 0;

	function addLineNumbers( string ) {

		var lines = string.split( '\n' );

		for ( var i = 0; i < lines.length; i ++ ) {

			lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];

		}

		return lines.join( '\n' );

	}

	function getEncodingComponents( encoding ) {

		switch ( encoding ) {

			case LinearEncoding:
				return [ 'Linear', '( value )' ];
			case sRGBEncoding:
				return [ 'sRGB', '( value )' ];
			case RGBEEncoding:
				return [ 'RGBE', '( value )' ];
			case RGBM7Encoding:
				return [ 'RGBM', '( value, 7.0 )' ];
			case RGBM16Encoding:
				return [ 'RGBM', '( value, 16.0 )' ];
			case RGBDEncoding:
				return [ 'RGBD', '( value, 256.0 )' ];
			case GammaEncoding:
				return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
			case LogLuvEncoding:
				return [ 'LogLuv', '( value )' ];
			default:
				throw new Error( 'unsupported encoding: ' + encoding );

		}

	}

	function getShaderErrors( gl, shader, type ) {

		var status = gl.getShaderParameter( shader, 35713 );
		var log = gl.getShaderInfoLog( shader ).trim();

		if ( status && log === '' ) { return ''; }

		// --enable-privileged-webgl-extension
		// console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );

		var source = gl.getShaderSource( shader );

		return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source );

	}

	function getTexelDecodingFunction( functionName, encoding ) {

		var components = getEncodingComponents( encoding );
		return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';

	}

	function getTexelEncodingFunction( functionName, encoding ) {

		var components = getEncodingComponents( encoding );
		return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';

	}

	function getToneMappingFunction( functionName, toneMapping ) {

		var toneMappingName;

		switch ( toneMapping ) {

			case LinearToneMapping:
				toneMappingName = 'Linear';
				break;

			case ReinhardToneMapping:
				toneMappingName = 'Reinhard';
				break;

			case Uncharted2ToneMapping:
				toneMappingName = 'Uncharted2';
				break;

			case CineonToneMapping:
				toneMappingName = 'OptimizedCineon';
				break;

			case ACESFilmicToneMapping:
				toneMappingName = 'ACESFilmic';
				break;

			default:
				throw new Error( 'unsupported toneMapping: ' + toneMapping );

		}

		return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';

	}

	function generateExtensions( parameters ) {

		var chunks = [
			( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
			( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
			( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
			( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
		];

		return chunks.filter( filterEmptyLine ).join( '\n' );

	}

	function generateDefines( defines ) {

		var chunks = [];

		for ( var name in defines ) {

			var value = defines[ name ];

			if ( value === false ) { continue; }

			chunks.push( '#define ' + name + ' ' + value );

		}

		return chunks.join( '\n' );

	}

	function fetchAttributeLocations( gl, program ) {

		var attributes = {};

		var n = gl.getProgramParameter( program, 35721 );

		for ( var i = 0; i < n; i ++ ) {

			var info = gl.getActiveAttrib( program, i );
			var name = info.name;

			// console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );

			attributes[ name ] = gl.getAttribLocation( program, name );

		}

		return attributes;

	}

	function filterEmptyLine( string ) {

		return string !== '';

	}

	function replaceLightNums( string, parameters ) {

		return string
			.replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
			.replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
			.replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
			.replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
			.replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
			.replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
			.replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
			.replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );

	}

	function replaceClippingPlaneNums( string, parameters ) {

		return string
			.replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
			.replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );

	}

	// Resolve Includes

	var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;

	function resolveIncludes( string ) {

		return string.replace( includePattern, includeReplacer );

	}

	function includeReplacer( match, include ) {

		var string = ShaderChunk[ include ];

		if ( string === undefined ) {

			throw new Error( 'Can not resolve #include <' + include + '>' );

		}

		return resolveIncludes( string );

	}

	// Unroll Loops

	var loopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;

	function unrollLoops( string ) {

		return string.replace( loopPattern, loopReplacer );

	}

	function loopReplacer( match, start, end, snippet ) {

		var string = '';

		for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {

			string += snippet
				.replace( /\[ i \]/g, '[ ' + i + ' ]' )
				.replace( /UNROLLED_LOOP_INDEX/g, i );

		}

		return string;

	}

	//

	function generatePrecision( parameters ) {

		var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";

		if ( parameters.precision === "highp" ) {

			precisionstring += "\n#define HIGH_PRECISION";

		} else if ( parameters.precision === "mediump" ) {

			precisionstring += "\n#define MEDIUM_PRECISION";

		} else if ( parameters.precision === "lowp" ) {

			precisionstring += "\n#define LOW_PRECISION";

		}

		return precisionstring;

	}

	function generateShadowMapTypeDefine( parameters ) {

		var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';

		if ( parameters.shadowMapType === PCFShadowMap ) {

			shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';

		} else if ( parameters.shadowMapType === PCFSoftShadowMap ) {

			shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';

		} else if ( parameters.shadowMapType === VSMShadowMap ) {

			shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';

		}

		return shadowMapTypeDefine;

	}

	function generateEnvMapTypeDefine( parameters ) {

		var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';

		if ( parameters.envMap ) {

			switch ( parameters.envMapMode ) {

				case CubeReflectionMapping:
				case CubeRefractionMapping:
					envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
					break;

				case CubeUVReflectionMapping:
				case CubeUVRefractionMapping:
					envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
					break;

				case EquirectangularReflectionMapping:
				case EquirectangularRefractionMapping:
					envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
					break;

				case SphericalReflectionMapping:
					envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
					break;

			}

		}

		return envMapTypeDefine;

	}

	function generateEnvMapModeDefine( parameters ) {

		var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';

		if ( parameters.envMap ) {

			switch ( parameters.envMapMode ) {

				case CubeRefractionMapping:
				case EquirectangularRefractionMapping:
					envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
					break;

			}

		}

		return envMapModeDefine;

	}

	function generateEnvMapBlendingDefine( parameters ) {

		var envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';

		if ( parameters.envMap ) {

			switch ( parameters.combine ) {

				case MultiplyOperation:
					envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
					break;

				case MixOperation:
					envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
					break;

				case AddOperation:
					envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
					break;

			}

		}

		return envMapBlendingDefine;

	}

	function WebGLProgram( renderer, cacheKey, parameters ) {

		var gl = renderer.getContext();

		var defines = parameters.defines;

		var vertexShader = parameters.vertexShader;
		var fragmentShader = parameters.fragmentShader;
		var shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
		var envMapTypeDefine = generateEnvMapTypeDefine( parameters );
		var envMapModeDefine = generateEnvMapModeDefine( parameters );
		var envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );


		var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;

		var customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );

		var customDefines = generateDefines( defines );

		var program = gl.createProgram();

		var prefixVertex, prefixFragment;

		var numMultiviewViews = parameters.numMultiviewViews;

		if ( parameters.isRawShaderMaterial ) {

			prefixVertex = [

				customDefines

			].filter( filterEmptyLine ).join( '\n' );

			if ( prefixVertex.length > 0 ) {

				prefixVertex += '\n';

			}

			prefixFragment = [

				customExtensions,
				customDefines

			].filter( filterEmptyLine ).join( '\n' );

			if ( prefixFragment.length > 0 ) {

				prefixFragment += '\n';

			}

		} else {

			prefixVertex = [

				generatePrecision( parameters ),

				'#define SHADER_NAME ' + parameters.shaderName,

				customDefines,

				parameters.instancing ? '#define USE_INSTANCING' : '',
				parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',

				'#define GAMMA_FACTOR ' + gammaFactorDefine,

				'#define MAX_BONES ' + parameters.maxBones,
				( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
				( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',

				parameters.map ? '#define USE_MAP' : '',
				parameters.envMap ? '#define USE_ENVMAP' : '',
				parameters.envMap ? '#define ' + envMapModeDefine : '',
				parameters.lightMap ? '#define USE_LIGHTMAP' : '',
				parameters.aoMap ? '#define USE_AOMAP' : '',
				parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
				parameters.bumpMap ? '#define USE_BUMPMAP' : '',
				parameters.normalMap ? '#define USE_NORMALMAP' : '',
				( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
				( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',

				parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
				parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
				parameters.specularMap ? '#define USE_SPECULARMAP' : '',
				parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
				parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
				parameters.alphaMap ? '#define USE_ALPHAMAP' : '',

				parameters.vertexTangents ? '#define USE_TANGENT' : '',
				parameters.vertexColors ? '#define USE_COLOR' : '',
				parameters.vertexUvs ? '#define USE_UV' : '',
				parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',

				parameters.flatShading ? '#define FLAT_SHADED' : '',

				parameters.skinning ? '#define USE_SKINNING' : '',
				parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',

				parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
				parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
				parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
				parameters.flipSided ? '#define FLIP_SIDED' : '',

				parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
				parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',

				parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',

				parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
				( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',

				'uniform mat4 modelMatrix;',
				'uniform mat4 modelViewMatrix;',
				'uniform mat4 projectionMatrix;',
				'uniform mat4 viewMatrix;',
				'uniform mat3 normalMatrix;',
				'uniform vec3 cameraPosition;',
				'uniform bool isOrthographic;',

				'#ifdef USE_INSTANCING',

				' attribute mat4 instanceMatrix;',

				'#endif',

				'attribute vec3 position;',
				'attribute vec3 normal;',
				'attribute vec2 uv;',

				'#ifdef USE_TANGENT',

				'	attribute vec4 tangent;',

				'#endif',

				'#ifdef USE_COLOR',

				'	attribute vec3 color;',

				'#endif',

				'#ifdef USE_MORPHTARGETS',

				'	attribute vec3 morphTarget0;',
				'	attribute vec3 morphTarget1;',
				'	attribute vec3 morphTarget2;',
				'	attribute vec3 morphTarget3;',

				'	#ifdef USE_MORPHNORMALS',

				'		attribute vec3 morphNormal0;',
				'		attribute vec3 morphNormal1;',
				'		attribute vec3 morphNormal2;',
				'		attribute vec3 morphNormal3;',

				'	#else',

				'		attribute vec3 morphTarget4;',
				'		attribute vec3 morphTarget5;',
				'		attribute vec3 morphTarget6;',
				'		attribute vec3 morphTarget7;',

				'	#endif',

				'#endif',

				'#ifdef USE_SKINNING',

				'	attribute vec4 skinIndex;',
				'	attribute vec4 skinWeight;',

				'#endif',

				'\n'

			].filter( filterEmptyLine ).join( '\n' );

			prefixFragment = [

				customExtensions,

				generatePrecision( parameters ),

				'#define SHADER_NAME ' + parameters.shaderName,

				customDefines,

				parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer

				'#define GAMMA_FACTOR ' + gammaFactorDefine,

				( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
				( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',

				parameters.map ? '#define USE_MAP' : '',
				parameters.matcap ? '#define USE_MATCAP' : '',
				parameters.envMap ? '#define USE_ENVMAP' : '',
				parameters.envMap ? '#define ' + envMapTypeDefine : '',
				parameters.envMap ? '#define ' + envMapModeDefine : '',
				parameters.envMap ? '#define ' + envMapBlendingDefine : '',
				parameters.lightMap ? '#define USE_LIGHTMAP' : '',
				parameters.aoMap ? '#define USE_AOMAP' : '',
				parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
				parameters.bumpMap ? '#define USE_BUMPMAP' : '',
				parameters.normalMap ? '#define USE_NORMALMAP' : '',
				( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
				( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
				parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
				parameters.specularMap ? '#define USE_SPECULARMAP' : '',
				parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
				parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
				parameters.alphaMap ? '#define USE_ALPHAMAP' : '',

				parameters.sheen ? '#define USE_SHEEN' : '',

				parameters.vertexTangents ? '#define USE_TANGENT' : '',
				parameters.vertexColors ? '#define USE_COLOR' : '',
				parameters.vertexUvs ? '#define USE_UV' : '',
				parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',

				parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',

				parameters.flatShading ? '#define FLAT_SHADED' : '',

				parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
				parameters.flipSided ? '#define FLIP_SIDED' : '',

				parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
				parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',

				parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',

				parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',

				parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
				( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',

				( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',

				'uniform mat4 viewMatrix;',
				'uniform vec3 cameraPosition;',
				'uniform bool isOrthographic;',

				( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
				( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
				( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',

				parameters.dithering ? '#define DITHERING' : '',

				( parameters.outputEncoding || parameters.mapEncoding || parameters.matcapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding || parameters.lightMapEncoding ) ?
					ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below
				parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
				parameters.matcapEncoding ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
				parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
				parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
				parameters.lightMapEncoding ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
				parameters.outputEncoding ? getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ) : '',

				parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',

				'\n'

			].filter( filterEmptyLine ).join( '\n' );

		}

		vertexShader = resolveIncludes( vertexShader );
		vertexShader = replaceLightNums( vertexShader, parameters );
		vertexShader = replaceClippingPlaneNums( vertexShader, parameters );

		fragmentShader = resolveIncludes( fragmentShader );
		fragmentShader = replaceLightNums( fragmentShader, parameters );
		fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );

		vertexShader = unrollLoops( vertexShader );
		fragmentShader = unrollLoops( fragmentShader );

		if ( parameters.isWebGL2 && ! parameters.isRawShaderMaterial ) {

			var isGLSL3ShaderMaterial = false;

			var versionRegex = /^\s*#version\s+300\s+es\s*\n/;

			if ( parameters.isShaderMaterial &&
				vertexShader.match( versionRegex ) !== null &&
				fragmentShader.match( versionRegex ) !== null ) {

				isGLSL3ShaderMaterial = true;

				vertexShader = vertexShader.replace( versionRegex, '' );
				fragmentShader = fragmentShader.replace( versionRegex, '' );

			}

			// GLSL 3.0 conversion

			prefixVertex = [
				'#version 300 es\n',
				'#define attribute in',
				'#define varying out',
				'#define texture2D texture'
			].join( '\n' ) + '\n' + prefixVertex;

			prefixFragment = [
				'#version 300 es\n',
				'#define varying in',
				isGLSL3ShaderMaterial ? '' : 'out highp vec4 pc_fragColor;',
				isGLSL3ShaderMaterial ? '' : '#define gl_FragColor pc_fragColor',
				'#define gl_FragDepthEXT gl_FragDepth',
				'#define texture2D texture',
				'#define textureCube texture',
				'#define texture2DProj textureProj',
				'#define texture2DLodEXT textureLod',
				'#define texture2DProjLodEXT textureProjLod',
				'#define textureCubeLodEXT textureLod',
				'#define texture2DGradEXT textureGrad',
				'#define texture2DProjGradEXT textureProjGrad',
				'#define textureCubeGradEXT textureGrad'
			].join( '\n' ) + '\n' + prefixFragment;

			// Multiview

			if ( numMultiviewViews > 0 ) {

				prefixVertex = prefixVertex.replace(
					'#version 300 es\n',
					[
						'#version 300 es\n',
						'#extension GL_OVR_multiview2 : require',
						'layout(num_views = ' + numMultiviewViews + ') in;',
						'#define VIEW_ID gl_ViewID_OVR'
					].join( '\n' )
				);

				prefixVertex = prefixVertex.replace(
					[
						'uniform mat4 modelViewMatrix;',
						'uniform mat4 projectionMatrix;',
						'uniform mat4 viewMatrix;',
						'uniform mat3 normalMatrix;'
					].join( '\n' ),
					[
						'uniform mat4 modelViewMatrices[' + numMultiviewViews + '];',
						'uniform mat4 projectionMatrices[' + numMultiviewViews + '];',
						'uniform mat4 viewMatrices[' + numMultiviewViews + '];',
						'uniform mat3 normalMatrices[' + numMultiviewViews + '];',

						'#define modelViewMatrix modelViewMatrices[VIEW_ID]',
						'#define projectionMatrix projectionMatrices[VIEW_ID]',
						'#define viewMatrix viewMatrices[VIEW_ID]',
						'#define normalMatrix normalMatrices[VIEW_ID]'
					].join( '\n' )
				);

				prefixFragment = prefixFragment.replace(
					'#version 300 es\n',
					[
						'#version 300 es\n',
						'#extension GL_OVR_multiview2 : require',
						'#define VIEW_ID gl_ViewID_OVR'
					].join( '\n' )
				);

				prefixFragment = prefixFragment.replace(
					'uniform mat4 viewMatrix;',
					[
						'uniform mat4 viewMatrices[' + numMultiviewViews + '];',
						'#define viewMatrix viewMatrices[VIEW_ID]'
					].join( '\n' )
				);

			}

		}

		var vertexGlsl = prefixVertex + vertexShader;
		var fragmentGlsl = prefixFragment + fragmentShader;

		// console.log( '*VERTEX*', vertexGlsl );
		// console.log( '*FRAGMENT*', fragmentGlsl );

		var glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
		var glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );

		gl.attachShader( program, glVertexShader );
		gl.attachShader( program, glFragmentShader );

		// Force a particular attribute to index 0.

		if ( parameters.index0AttributeName !== undefined ) {

			gl.bindAttribLocation( program, 0, parameters.index0AttributeName );

		} else if ( parameters.morphTargets === true ) {

			// programs with morphTargets displace position out of attribute 0
			gl.bindAttribLocation( program, 0, 'position' );

		}

		gl.linkProgram( program );

		// check for link errors
		if ( renderer.debug.checkShaderErrors ) {

			var programLog = gl.getProgramInfoLog( program ).trim();
			var vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
			var fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();

			var runnable = true;
			var haveDiagnostics = true;

			if ( gl.getProgramParameter( program, 35714 ) === false ) {

				runnable = false;

				var vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
				var fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );

				console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors );

			} else if ( programLog !== '' ) {

				console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );

			} else if ( vertexLog === '' || fragmentLog === '' ) {

				haveDiagnostics = false;

			}

			if ( haveDiagnostics ) {

				this.diagnostics = {

					runnable: runnable,

					programLog: programLog,

					vertexShader: {

						log: vertexLog,
						prefix: prefixVertex

					},

					fragmentShader: {

						log: fragmentLog,
						prefix: prefixFragment

					}

				};

			}

		}

		// clean up

		gl.deleteShader( glVertexShader );
		gl.deleteShader( glFragmentShader );

		// set up caching for uniform locations

		var cachedUniforms;

		this.getUniforms = function () {

			if ( cachedUniforms === undefined ) {

				cachedUniforms = new WebGLUniforms( gl, program );

			}

			return cachedUniforms;

		};

		// set up caching for attribute locations

		var cachedAttributes;

		this.getAttributes = function () {

			if ( cachedAttributes === undefined ) {

				cachedAttributes = fetchAttributeLocations( gl, program );

			}

			return cachedAttributes;

		};

		// free resource

		this.destroy = function () {

			gl.deleteProgram( program );
			this.program = undefined;

		};

		//

		this.name = parameters.shaderName;
		this.id = programIdCount ++;
		this.cacheKey = cacheKey;
		this.usedTimes = 1;
		this.program = program;
		this.vertexShader = glVertexShader;
		this.fragmentShader = glFragmentShader;
		this.numMultiviewViews = numMultiviewViews;

		return this;

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function WebGLPrograms( renderer, extensions, capabilities ) {

		var programs = [];

		var isWebGL2 = capabilities.isWebGL2;
		var logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
		var floatVertexTextures = capabilities.floatVertexTextures;
		var precision = capabilities.precision;
		var maxVertexUniforms = capabilities.maxVertexUniforms;
		var vertexTextures = capabilities.vertexTextures;

		var shaderIDs = {
			MeshDepthMaterial: 'depth',
			MeshDistanceMaterial: 'distanceRGBA',
			MeshNormalMaterial: 'normal',
			MeshBasicMaterial: 'basic',
			MeshLambertMaterial: 'lambert',
			MeshPhongMaterial: 'phong',
			MeshToonMaterial: 'toon',
			MeshStandardMaterial: 'physical',
			MeshPhysicalMaterial: 'physical',
			MeshMatcapMaterial: 'matcap',
			LineBasicMaterial: 'basic',
			LineDashedMaterial: 'dashed',
			PointsMaterial: 'points',
			ShadowMaterial: 'shadow',
			SpriteMaterial: 'sprite'
		};

		var parameterNames = [
			"precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing", "numMultiviewViews",
			"map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "envMapCubeUV",
			"lightMap", "lightMapEncoding", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatNormalMap", "displacementMap", "specularMap",
			"roughnessMap", "metalnessMap", "gradientMap",
			"alphaMap", "combine", "vertexColors", "vertexTangents", "vertexUvs", "uvsVertexOnly", "fog", "useFog", "fogExp2",
			"flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
			"maxBones", "useVertexTexture", "morphTargets", "morphNormals",
			"maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
			"numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
			"numDirLightShadows", "numPointLightShadows", "numSpotLightShadows",
			"shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
			"alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering",
			"sheen"
		];

		function getShaderObject( material, shaderID ) {

			var shaderobject;

			if ( shaderID ) {

				var shader = ShaderLib[ shaderID ];

				shaderobject = {
					name: material.type,
					uniforms: UniformsUtils.clone( shader.uniforms ),
					vertexShader: shader.vertexShader,
					fragmentShader: shader.fragmentShader
				};

			} else {

				shaderobject = {
					name: material.type,
					uniforms: material.uniforms,
					vertexShader: material.vertexShader,
					fragmentShader: material.fragmentShader
				};

			}

			return shaderobject;

		}

		function allocateBones( object ) {

			var skeleton = object.skeleton;
			var bones = skeleton.bones;

			if ( floatVertexTextures ) {

				return 1024;

			} else {

				// default for when object is not specified
				// ( for example when prebuilding shader to be used with multiple objects )
				//
				//  - leave some extra space for other uniforms
				//  - limit here is ANGLE's 254 max uniform vectors
				//    (up to 54 should be safe)

				var nVertexUniforms = maxVertexUniforms;
				var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );

				var maxBones = Math.min( nVertexMatrices, bones.length );

				if ( maxBones < bones.length ) {

					console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
					return 0;

				}

				return maxBones;

			}

		}

		function getTextureEncodingFromMap( map ) {

			var encoding;

			if ( ! map ) {

				encoding = LinearEncoding;

			} else if ( map.isTexture ) {

				encoding = map.encoding;

			} else if ( map.isWebGLRenderTarget ) {

				console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
				encoding = map.texture.encoding;

			}

			return encoding;

		}

		this.getParameters = function ( material, lights, shadows, scene, nClipPlanes, nClipIntersection, object ) {

			var fog = scene.fog;
			var environment = material.isMeshStandardMaterial ? scene.environment : null;

			var envMap = material.envMap || environment;

			var shaderID = shaderIDs[ material.type ];

			// heuristics to create shader parameters according to lights in the scene
			// (not to blow over maxLights budget)

			var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;

			if ( material.precision !== null ) {

				precision = capabilities.getMaxPrecision( material.precision );

				if ( precision !== material.precision ) {

					console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );

				}

			}

			var shaderobject = getShaderObject( material, shaderID );
			material.onBeforeCompile( shaderobject, renderer );

			var currentRenderTarget = renderer.getRenderTarget();
			var numMultiviewViews = currentRenderTarget && currentRenderTarget.isWebGLMultiviewRenderTarget ? currentRenderTarget.numViews : 0;

			var parameters = {

				isWebGL2: isWebGL2,

				shaderID: shaderID,
				shaderName: shaderobject.name,

				uniforms: shaderobject.uniforms,
				vertexShader: shaderobject.vertexShader,
				fragmentShader: shaderobject.fragmentShader,
				defines: material.defines,

				isRawShaderMaterial: material.isRawShaderMaterial,
				isShaderMaterial: material.isShaderMaterial,

				precision: precision,

				instancing: object.isInstancedMesh === true,

				supportsVertexTextures: vertexTextures,
				numMultiviewViews: numMultiviewViews,
				outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
				map: !! material.map,
				mapEncoding: getTextureEncodingFromMap( material.map ),
				matcap: !! material.matcap,
				matcapEncoding: getTextureEncodingFromMap( material.matcap ),
				envMap: !! envMap,
				envMapMode: envMap && envMap.mapping,
				envMapEncoding: getTextureEncodingFromMap( envMap ),
				envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
				lightMap: !! material.lightMap,
				lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
				aoMap: !! material.aoMap,
				emissiveMap: !! material.emissiveMap,
				emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
				bumpMap: !! material.bumpMap,
				normalMap: !! material.normalMap,
				objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
				tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
				clearcoatNormalMap: !! material.clearcoatNormalMap,
				displacementMap: !! material.displacementMap,
				roughnessMap: !! material.roughnessMap,
				metalnessMap: !! material.metalnessMap,
				specularMap: !! material.specularMap,
				alphaMap: !! material.alphaMap,

				gradientMap: !! material.gradientMap,

				sheen: !! material.sheen,

				combine: material.combine,

				vertexTangents: ( material.normalMap && material.vertexTangents ),
				vertexColors: material.vertexColors,
				vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.displacementMap,
				uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap ) && !! material.displacementMap,

				fog: !! fog,
				useFog: material.fog,
				fogExp2: ( fog && fog.isFogExp2 ),

				flatShading: material.flatShading,

				sizeAttenuation: material.sizeAttenuation,
				logarithmicDepthBuffer: logarithmicDepthBuffer,

				skinning: material.skinning && maxBones > 0,
				maxBones: maxBones,
				useVertexTexture: floatVertexTextures,

				morphTargets: material.morphTargets,
				morphNormals: material.morphNormals,
				maxMorphTargets: renderer.maxMorphTargets,
				maxMorphNormals: renderer.maxMorphNormals,

				numDirLights: lights.directional.length,
				numPointLights: lights.point.length,
				numSpotLights: lights.spot.length,
				numRectAreaLights: lights.rectArea.length,
				numHemiLights: lights.hemi.length,

				numDirLightShadows: lights.directionalShadowMap.length,
				numPointLightShadows: lights.pointShadowMap.length,
				numSpotLightShadows: lights.spotShadowMap.length,

				numClippingPlanes: nClipPlanes,
				numClipIntersection: nClipIntersection,

				dithering: material.dithering,

				shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
				shadowMapType: renderer.shadowMap.type,

				toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
				physicallyCorrectLights: renderer.physicallyCorrectLights,

				premultipliedAlpha: material.premultipliedAlpha,

				alphaTest: material.alphaTest,
				doubleSided: material.side === DoubleSide,
				flipSided: material.side === BackSide,

				depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,

				index0AttributeName: material.index0AttributeName,

				extensionDerivatives: material.extensions && material.extensions.derivatives,
				extensionFragDepth: material.extensions && material.extensions.frawbuffers,
				extensionDrawbuffers: material.extensions && material.extensions.drawbuffers,
				extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,

				rendererExtensionFragDepth: isWebGL2 || extensions.get( 'EXT_frag_depth' ) !== null,
				rendererExtensionDrawBuffers: isWebGL2 || extensions.get( 'WEBGL_draw_buffers' ) !== null,
				rendererExtensionShaderTextureLod: isWebGL2 || extensions.get( 'EXT_shader_texture_lod' ) !== null,

				onBeforeCompile: material.onBeforeCompile

			};

			return parameters;

		};

		this.getProgramCacheKey = function ( parameters ) {

			var array = [];

			if ( parameters.shaderID ) {

				array.push( parameters.shaderID );

			} else {

				array.push( parameters.fragmentShader );
				array.push( parameters.vertexShader );

			}

			if ( parameters.defines !== undefined ) {

				for ( var name in parameters.defines ) {

					array.push( name );
					array.push( parameters.defines[ name ] );

				}

			}

			if ( parameters.isRawShaderMaterial === undefined ) {

				for ( var i = 0; i < parameterNames.length; i ++ ) {

					array.push( parameters[ parameterNames[ i ] ] );

				}

				array.push( renderer.outputEncoding );
				array.push( renderer.gammaFactor );

			}

			array.push( parameters.onBeforeCompile.toString() );

			return array.join();

		};

		this.acquireProgram = function ( parameters, cacheKey ) {

			var program;

			// Check if code has been already compiled
			for ( var p = 0, pl = programs.length; p < pl; p ++ ) {

				var preexistingProgram = programs[ p ];

				if ( preexistingProgram.cacheKey === cacheKey ) {

					program = preexistingProgram;
					++ program.usedTimes;

					break;

				}

			}

			if ( program === undefined ) {

				program = new WebGLProgram( renderer, cacheKey, parameters );
				programs.push( program );

			}

			return program;

		};

		this.releaseProgram = function ( program ) {

			if ( -- program.usedTimes === 0 ) {

				// Remove from unordered set
				var i = programs.indexOf( program );
				programs[ i ] = programs[ programs.length - 1 ];
				programs.pop();

				// Free WebGL resources
				program.destroy();

			}

		};

		// Exposed for resource monitoring & error feedback via renderer.info:
		this.programs = programs;

	}

	/**
	 * @author fordacious / fordacious.github.io
	 */

	function WebGLProperties() {

		var properties = new WeakMap();

		function get( object ) {

			var map = properties.get( object );

			if ( map === undefined ) {

				map = {};
				properties.set( object, map );

			}

			return map;

		}

		function remove( object ) {

			properties.delete( object );

		}

		function update( object, key, value ) {

			properties.get( object )[ key ] = value;

		}

		function dispose() {

			properties = new WeakMap();

		}

		return {
			get: get,
			remove: remove,
			update: update,
			dispose: dispose
		};

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function painterSortStable( a, b ) {

		if ( a.groupOrder !== b.groupOrder ) {

			return a.groupOrder - b.groupOrder;

		} else if ( a.renderOrder !== b.renderOrder ) {

			return a.renderOrder - b.renderOrder;

		} else if ( a.program !== b.program ) {

			return a.program.id - b.program.id;

		} else if ( a.material.id !== b.material.id ) {

			return a.material.id - b.material.id;

		} else if ( a.z !== b.z ) {

			return a.z - b.z;

		} else {

			return a.id - b.id;

		}

	}

	function reversePainterSortStable( a, b ) {

		if ( a.groupOrder !== b.groupOrder ) {

			return a.groupOrder - b.groupOrder;

		} else if ( a.renderOrder !== b.renderOrder ) {

			return a.renderOrder - b.renderOrder;

		} else if ( a.z !== b.z ) {

			return b.z - a.z;

		} else {

			return a.id - b.id;

		}

	}


	function WebGLRenderList() {

		var renderItems = [];
		var renderItemsIndex = 0;

		var opaque = [];
		var transparent = [];

		var defaultProgram = { id: - 1 };

		function init() {

			renderItemsIndex = 0;

			opaque.length = 0;
			transparent.length = 0;

		}

		function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {

			var renderItem = renderItems[ renderItemsIndex ];

			if ( renderItem === undefined ) {

				renderItem = {
					id: object.id,
					object: object,
					geometry: geometry,
					material: material,
					program: material.program || defaultProgram,
					groupOrder: groupOrder,
					renderOrder: object.renderOrder,
					z: z,
					group: group
				};

				renderItems[ renderItemsIndex ] = renderItem;

			} else {

				renderItem.id = object.id;
				renderItem.object = object;
				renderItem.geometry = geometry;
				renderItem.material = material;
				renderItem.program = material.program || defaultProgram;
				renderItem.groupOrder = groupOrder;
				renderItem.renderOrder = object.renderOrder;
				renderItem.z = z;
				renderItem.group = group;

			}

			renderItemsIndex ++;

			return renderItem;

		}

		function push( object, geometry, material, groupOrder, z, group ) {

			var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );

			( material.transparent === true ? transparent : opaque ).push( renderItem );

		}

		function unshift( object, geometry, material, groupOrder, z, group ) {

			var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );

			( material.transparent === true ? transparent : opaque ).unshift( renderItem );

		}

		function sort( customOpaqueSort, customTransparentSort ) {

			if ( opaque.length > 1 ) { opaque.sort( customOpaqueSort || painterSortStable ); }
			if ( transparent.length > 1 ) { transparent.sort( customTransparentSort || reversePainterSortStable ); }

		}

		return {
			opaque: opaque,
			transparent: transparent,

			init: init,
			push: push,
			unshift: unshift,

			sort: sort
		};

	}

	function WebGLRenderLists() {

		var lists = new WeakMap();

		function onSceneDispose( event ) {

			var scene = event.target;

			scene.removeEventListener( 'dispose', onSceneDispose );

			lists.delete( scene );

		}

		function get( scene, camera ) {

			var cameras = lists.get( scene );
			var list;
			if ( cameras === undefined ) {

				list = new WebGLRenderList();
				lists.set( scene, new WeakMap() );
				lists.get( scene ).set( camera, list );

				scene.addEventListener( 'dispose', onSceneDispose );

			} else {

				list = cameras.get( camera );
				if ( list === undefined ) {

					list = new WebGLRenderList();
					cameras.set( camera, list );

				}

			}

			return list;

		}

		function dispose() {

			lists = new WeakMap();

		}

		return {
			get: get,
			dispose: dispose
		};

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function UniformsCache() {

		var lights = {};

		return {

			get: function ( light ) {

				if ( lights[ light.id ] !== undefined ) {

					return lights[ light.id ];

				}

				var uniforms;

				switch ( light.type ) {

					case 'DirectionalLight':
						uniforms = {
							direction: new Vector3(),
							color: new Color(),

							shadow: false,
							shadowBias: 0,
							shadowRadius: 1,
							shadowMapSize: new Vector2()
						};
						break;

					case 'SpotLight':
						uniforms = {
							position: new Vector3(),
							direction: new Vector3(),
							color: new Color(),
							distance: 0,
							coneCos: 0,
							penumbraCos: 0,
							decay: 0,

							shadow: false,
							shadowBias: 0,
							shadowRadius: 1,
							shadowMapSize: new Vector2()
						};
						break;

					case 'PointLight':
						uniforms = {
							position: new Vector3(),
							color: new Color(),
							distance: 0,
							decay: 0,

							shadow: false,
							shadowBias: 0,
							shadowRadius: 1,
							shadowMapSize: new Vector2(),
							shadowCameraNear: 1,
							shadowCameraFar: 1000
						};
						break;

					case 'HemisphereLight':
						uniforms = {
							direction: new Vector3(),
							skyColor: new Color(),
							groundColor: new Color()
						};
						break;

					case 'RectAreaLight':
						uniforms = {
							color: new Color(),
							position: new Vector3(),
							halfWidth: new Vector3(),
							halfHeight: new Vector3()
							// TODO (abelnation): set RectAreaLight shadow uniforms
						};
						break;

				}

				lights[ light.id ] = uniforms;

				return uniforms;

			}

		};

	}

	var nextVersion = 0;

	function shadowCastingLightsFirst( lightA, lightB ) {

		return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );

	}

	function WebGLLights() {

		var cache = new UniformsCache();

		var state = {

			version: 0,

			hash: {
				directionalLength: - 1,
				pointLength: - 1,
				spotLength: - 1,
				rectAreaLength: - 1,
				hemiLength: - 1,

				numDirectionalShadows: - 1,
				numPointShadows: - 1,
				numSpotShadows: - 1,
			},

			ambient: [ 0, 0, 0 ],
			probe: [],
			directional: [],
			directionalShadowMap: [],
			directionalShadowMatrix: [],
			spot: [],
			spotShadowMap: [],
			spotShadowMatrix: [],
			rectArea: [],
			point: [],
			pointShadowMap: [],
			pointShadowMatrix: [],
			hemi: [],

			numDirectionalShadows: - 1,
			numPointShadows: - 1,
			numSpotShadows: - 1

		};

		for ( var i = 0; i < 9; i ++ ) { state.probe.push( new Vector3() ); }

		var vector3 = new Vector3();
		var matrix4 = new Matrix4();
		var matrix42 = new Matrix4();

		function setup( lights, shadows, camera ) {

			var r = 0, g = 0, b = 0;

			for ( var i = 0; i < 9; i ++ ) { state.probe[ i ].set( 0, 0, 0 ); }

			var directionalLength = 0;
			var pointLength = 0;
			var spotLength = 0;
			var rectAreaLength = 0;
			var hemiLength = 0;

			var numDirectionalShadows = 0;
			var numPointShadows = 0;
			var numSpotShadows = 0;

			var viewMatrix = camera.matrixWorldInverse;

			lights.sort( shadowCastingLightsFirst );

			for ( var i = 0, l = lights.length; i < l; i ++ ) {

				var light = lights[ i ];

				var color = light.color;
				var intensity = light.intensity;
				var distance = light.distance;

				var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;

				if ( light.isAmbientLight ) {

					r += color.r * intensity;
					g += color.g * intensity;
					b += color.b * intensity;

				} else if ( light.isLightProbe ) {

					for ( var j = 0; j < 9; j ++ ) {

						state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );

					}

				} else if ( light.isDirectionalLight ) {

					var uniforms = cache.get( light );

					uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
					uniforms.direction.setFromMatrixPosition( light.matrixWorld );
					vector3.setFromMatrixPosition( light.target.matrixWorld );
					uniforms.direction.sub( vector3 );
					uniforms.direction.transformDirection( viewMatrix );

					uniforms.shadow = light.castShadow;

					if ( light.castShadow ) {

						var shadow = light.shadow;

						uniforms.shadowBias = shadow.bias;
						uniforms.shadowRadius = shadow.radius;
						uniforms.shadowMapSize = shadow.mapSize;

						state.directionalShadowMap[ directionalLength ] = shadowMap;
						state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;

						numDirectionalShadows ++;

					}

					state.directional[ directionalLength ] = uniforms;

					directionalLength ++;

				} else if ( light.isSpotLight ) {

					var uniforms = cache.get( light );

					uniforms.position.setFromMatrixPosition( light.matrixWorld );
					uniforms.position.applyMatrix4( viewMatrix );

					uniforms.color.copy( color ).multiplyScalar( intensity );
					uniforms.distance = distance;

					uniforms.direction.setFromMatrixPosition( light.matrixWorld );
					vector3.setFromMatrixPosition( light.target.matrixWorld );
					uniforms.direction.sub( vector3 );
					uniforms.direction.transformDirection( viewMatrix );

					uniforms.coneCos = Math.cos( light.angle );
					uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
					uniforms.decay = light.decay;

					uniforms.shadow = light.castShadow;

					if ( light.castShadow ) {

						var shadow = light.shadow;

						uniforms.shadowBias = shadow.bias;
						uniforms.shadowRadius = shadow.radius;
						uniforms.shadowMapSize = shadow.mapSize;

						state.spotShadowMap[ spotLength ] = shadowMap;
						state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;

						numSpotShadows ++;

					}

					state.spot[ spotLength ] = uniforms;

					spotLength ++;

				} else if ( light.isRectAreaLight ) {

					var uniforms = cache.get( light );

					// (a) intensity is the total visible light emitted
					//uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );

					// (b) intensity is the brightness of the light
					uniforms.color.copy( color ).multiplyScalar( intensity );

					uniforms.position.setFromMatrixPosition( light.matrixWorld );
					uniforms.position.applyMatrix4( viewMatrix );

					// extract local rotation of light to derive width/height half vectors
					matrix42.identity();
					matrix4.copy( light.matrixWorld );
					matrix4.premultiply( viewMatrix );
					matrix42.extractRotation( matrix4 );

					uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
					uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );

					uniforms.halfWidth.applyMatrix4( matrix42 );
					uniforms.halfHeight.applyMatrix4( matrix42 );

					// TODO (abelnation): RectAreaLight distance?
					// uniforms.distance = distance;

					state.rectArea[ rectAreaLength ] = uniforms;

					rectAreaLength ++;

				} else if ( light.isPointLight ) {

					var uniforms = cache.get( light );

					uniforms.position.setFromMatrixPosition( light.matrixWorld );
					uniforms.position.applyMatrix4( viewMatrix );

					uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
					uniforms.distance = light.distance;
					uniforms.decay = light.decay;

					uniforms.shadow = light.castShadow;

					if ( light.castShadow ) {

						var shadow = light.shadow;

						uniforms.shadowBias = shadow.bias;
						uniforms.shadowRadius = shadow.radius;
						uniforms.shadowMapSize = shadow.mapSize;
						uniforms.shadowCameraNear = shadow.camera.near;
						uniforms.shadowCameraFar = shadow.camera.far;

						state.pointShadowMap[ pointLength ] = shadowMap;
						state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;

						numPointShadows ++;

					}

					state.point[ pointLength ] = uniforms;

					pointLength ++;

				} else if ( light.isHemisphereLight ) {

					var uniforms = cache.get( light );

					uniforms.direction.setFromMatrixPosition( light.matrixWorld );
					uniforms.direction.transformDirection( viewMatrix );
					uniforms.direction.normalize();

					uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
					uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );

					state.hemi[ hemiLength ] = uniforms;

					hemiLength ++;

				}

			}

			state.ambient[ 0 ] = r;
			state.ambient[ 1 ] = g;
			state.ambient[ 2 ] = b;

			var hash = state.hash;

			if ( hash.directionalLength !== directionalLength ||
				hash.pointLength !== pointLength ||
				hash.spotLength !== spotLength ||
				hash.rectAreaLength !== rectAreaLength ||
				hash.hemiLength !== hemiLength ||
				hash.numDirectionalShadows !== numDirectionalShadows ||
				hash.numPointShadows !== numPointShadows ||
				hash.numSpotShadows !== numSpotShadows ) {

				state.directional.length = directionalLength;
				state.spot.length = spotLength;
				state.rectArea.length = rectAreaLength;
				state.point.length = pointLength;
				state.hemi.length = hemiLength;

				state.directionalShadowMap.length = numDirectionalShadows;
				state.pointShadowMap.length = numPointShadows;
				state.spotShadowMap.length = numSpotShadows;
				state.directionalShadowMatrix.length = numDirectionalShadows;
				state.pointShadowMatrix.length = numPointShadows;
				state.spotShadowMatrix.length = numSpotShadows;

				hash.directionalLength = directionalLength;
				hash.pointLength = pointLength;
				hash.spotLength = spotLength;
				hash.rectAreaLength = rectAreaLength;
				hash.hemiLength = hemiLength;

				hash.numDirectionalShadows = numDirectionalShadows;
				hash.numPointShadows = numPointShadows;
				hash.numSpotShadows = numSpotShadows;

				state.version = nextVersion ++;

			}

		}

		return {
			setup: setup,
			state: state
		};

	}

	/**
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	function WebGLRenderState() {

		var lights = new WebGLLights();

		var lightsArray = [];
		var shadowsArray = [];

		function init() {

			lightsArray.length = 0;
			shadowsArray.length = 0;

		}

		function pushLight( light ) {

			lightsArray.push( light );

		}

		function pushShadow( shadowLight ) {

			shadowsArray.push( shadowLight );

		}

		function setupLights( camera ) {

			lights.setup( lightsArray, shadowsArray, camera );

		}

		var state = {
			lightsArray: lightsArray,
			shadowsArray: shadowsArray,

			lights: lights
		};

		return {
			init: init,
			state: state,
			setupLights: setupLights,

			pushLight: pushLight,
			pushShadow: pushShadow
		};

	}

	function WebGLRenderStates() {

		var renderStates = new WeakMap();

		function onSceneDispose( event ) {

			var scene = event.target;

			scene.removeEventListener( 'dispose', onSceneDispose );

			renderStates.delete( scene );

		}

		function get( scene, camera ) {

			var renderState;

			if ( renderStates.has( scene ) === false ) {

				renderState = new WebGLRenderState();
				renderStates.set( scene, new WeakMap() );
				renderStates.get( scene ).set( camera, renderState );

				scene.addEventListener( 'dispose', onSceneDispose );

			} else {

				if ( renderStates.get( scene ).has( camera ) === false ) {

					renderState = new WebGLRenderState();
					renderStates.get( scene ).set( camera, renderState );

				} else {

					renderState = renderStates.get( scene ).get( camera );

				}

			}

			return renderState;

		}

		function dispose() {

			renderStates = new WeakMap();

		}

		return {
			get: get,
			dispose: dispose
		};

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author alteredq / http://alteredqualia.com/
	 * @author bhouston / https://clara.io
	 * @author WestLangley / http://github.com/WestLangley
	 *
	 * parameters = {
	 *
	 *  opacity: <float>,
	 *
	 *  map: new THREE.Texture( <Image> ),
	 *
	 *  alphaMap: new THREE.Texture( <Image> ),
	 *
	 *  displacementMap: new THREE.Texture( <Image> ),
	 *  displacementScale: <float>,
	 *  displacementBias: <float>,
	 *
	 *  wireframe: <boolean>,
	 *  wireframeLinewidth: <float>
	 * }
	 */

	function MeshDepthMaterial( parameters ) {

		Material.call( this );

		this.type = 'MeshDepthMaterial';

		this.depthPacking = BasicDepthPacking;

		this.skinning = false;
		this.morphTargets = false;

		this.map = null;

		this.alphaMap = null;

		this.displacementMap = null;
		this.displacementScale = 1;
		this.displacementBias = 0;

		this.wireframe = false;
		this.wireframeLinewidth = 1;

		this.fog = false;

		this.setValues( parameters );

	}

	MeshDepthMaterial.prototype = Object.create( Material.prototype );
	MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;

	MeshDepthMaterial.prototype.isMeshDepthMaterial = true;

	MeshDepthMaterial.prototype.copy = function ( source ) {

		Material.prototype.copy.call( this, source );

		this.depthPacking = source.depthPacking;

		this.skinning = source.skinning;
		this.morphTargets = source.morphTargets;

		this.map = source.map;

		this.alphaMap = source.alphaMap;

		this.displacementMap = source.displacementMap;
		this.displacementScale = source.displacementScale;
		this.displacementBias = source.displacementBias;

		this.wireframe = source.wireframe;
		this.wireframeLinewidth = source.wireframeLinewidth;

		return this;

	};

	/**
	 * @author WestLangley / http://github.com/WestLangley
	 *
	 * parameters = {
	 *
	 *  referencePosition: <float>,
	 *  nearDistance: <float>,
	 *  farDistance: <float>,
	 *
	 *  skinning: <bool>,
	 *  morphTargets: <bool>,
	 *
	 *  map: new THREE.Texture( <Image> ),
	 *
	 *  alphaMap: new THREE.Texture( <Image> ),
	 *
	 *  displacementMap: new THREE.Texture( <Image> ),
	 *  displacementScale: <float>,
	 *  displacementBias: <float>
	 *
	 * }
	 */

	function MeshDistanceMaterial( parameters ) {

		Material.call( this );

		this.type = 'MeshDistanceMaterial';

		this.referencePosition = new Vector3();
		this.nearDistance = 1;
		this.farDistance = 1000;

		this.skinning = false;
		this.morphTargets = false;

		this.map = null;

		this.alphaMap = null;

		this.displacementMap = null;
		this.displacementScale = 1;
		this.displacementBias = 0;

		this.fog = false;

		this.setValues( parameters );

	}

	MeshDistanceMaterial.prototype = Object.create( Material.prototype );
	MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;

	MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;

	MeshDistanceMaterial.prototype.copy = function ( source ) {

		Material.prototype.copy.call( this, source );

		this.referencePosition.copy( source.referencePosition );
		this.nearDistance = source.nearDistance;
		this.farDistance = source.farDistance;

		this.skinning = source.skinning;
		this.morphTargets = source.morphTargets;

		this.map = source.map;

		this.alphaMap = source.alphaMap;

		this.displacementMap = source.displacementMap;
		this.displacementScale = source.displacementScale;
		this.displacementBias = source.displacementBias;

		return this;

	};

	var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n  float mean = 0.0;\n  float squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy  ) / resolution ) );\n  for ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n    #ifdef HORIZONAL_PASS\n      vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n      mean += distribution.x;\n      squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n    #else\n      float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0,  i )  * radius ) / resolution ) );\n      mean += depth;\n      squared_mean += depth * depth;\n    #endif\n  }\n  mean = mean * HALF_SAMPLE_RATE;\n  squared_mean = squared_mean * HALF_SAMPLE_RATE;\n  float std_dev = sqrt( squared_mean - mean * mean );\n  gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";

	var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";

	/**
	 * @author alteredq / http://alteredqualia.com/
	 * @author mrdoob / http://mrdoob.com/
	 */

	function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {

		var _frustum = new Frustum(),

			_shadowMapSize = new Vector2(),
			_viewportSize = new Vector2(),

			_viewport = new Vector4(),

			_depthMaterials = [],
			_distanceMaterials = [],

			_materialCache = {};

		var shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };

		var shadowMaterialVertical = new ShaderMaterial( {

			defines: {
				SAMPLE_RATE: 2.0 / 8.0,
				HALF_SAMPLE_RATE: 1.0 / 8.0
			},

			uniforms: {
				shadow_pass: { value: null },
				resolution: { value: new Vector2() },
				radius: { value: 4.0 }
			},

			vertexShader: vsm_vert,

			fragmentShader: vsm_frag

		} );

		var shadowMaterialHorizonal = shadowMaterialVertical.clone();
		shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;

		var fullScreenTri = new BufferGeometry();
		fullScreenTri.setAttribute(
			"position",
			new BufferAttribute(
				new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
				3
			)
		);

		var fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );

		var scope = this;

		this.enabled = false;

		this.autoUpdate = true;
		this.needsUpdate = false;

		this.type = PCFShadowMap;

		this.render = function ( lights, scene, camera ) {

			if ( scope.enabled === false ) { return; }
			if ( scope.autoUpdate === false && scope.needsUpdate === false ) { return; }

			if ( lights.length === 0 ) { return; }

			var currentRenderTarget = _renderer.getRenderTarget();
			var activeCubeFace = _renderer.getActiveCubeFace();
			var activeMipmapLevel = _renderer.getActiveMipmapLevel();

			var _state = _renderer.state;

			// Set GL state for depth map.
			_state.setBlending( NoBlending );
			_state.buffers.color.setClear( 1, 1, 1, 1 );
			_state.buffers.depth.setTest( true );
			_state.setScissorTest( false );

			// render depth map

			for ( var i = 0, il = lights.length; i < il; i ++ ) {

				var light = lights[ i ];
				var shadow = light.shadow;

				if ( shadow === undefined ) {

					console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
					continue;

				}

				_shadowMapSize.copy( shadow.mapSize );

				var shadowFrameExtents = shadow.getFrameExtents();

				_shadowMapSize.multiply( shadowFrameExtents );

				_viewportSize.copy( shadow.mapSize );

				if ( _shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize ) {

					console.warn( 'THREE.WebGLShadowMap:', light, 'has shadow exceeding max texture size, reducing' );

					if ( _shadowMapSize.x > maxTextureSize ) {

						_viewportSize.x = Math.floor( maxTextureSize / shadowFrameExtents.x );
						_shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
						shadow.mapSize.x = _viewportSize.x;

					}

					if ( _shadowMapSize.y > maxTextureSize ) {

						_viewportSize.y = Math.floor( maxTextureSize / shadowFrameExtents.y );
						_shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
						shadow.mapSize.y = _viewportSize.y;

					}

				}

				if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {

					var pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };

					shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
					shadow.map.texture.name = light.name + ".shadowMap";

					shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );

					shadow.camera.updateProjectionMatrix();

				}

				if ( shadow.map === null ) {

					var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };

					shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
					shadow.map.texture.name = light.name + ".shadowMap";

					shadow.camera.updateProjectionMatrix();

				}

				_renderer.setRenderTarget( shadow.map );
				_renderer.clear();

				var viewportCount = shadow.getViewportCount();

				for ( var vp = 0; vp < viewportCount; vp ++ ) {

					var viewport = shadow.getViewport( vp );

					_viewport.set(
						_viewportSize.x * viewport.x,
						_viewportSize.y * viewport.y,
						_viewportSize.x * viewport.z,
						_viewportSize.y * viewport.w
					);

					_state.viewport( _viewport );

					shadow.updateMatrices( light, vp );

					_frustum = shadow.getFrustum();

					renderObject( scene, camera, shadow.camera, light, this.type );

				}

				// do blur pass for VSM

				if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {

					VSMPass( shadow, camera );

				}

			}

			scope.needsUpdate = false;

			_renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );

		};

		function VSMPass( shadow, camera ) {

			var geometry = _objects.update( fullScreenMesh );

			// vertical pass

			shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
			shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
			shadowMaterialVertical.uniforms.radius.value = shadow.radius;
			_renderer.setRenderTarget( shadow.mapPass );
			_renderer.clear();
			_renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );

			// horizonal pass

			shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
			shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
			shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
			_renderer.setRenderTarget( shadow.map );
			_renderer.clear();
			_renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null );

		}

		function getDepthMaterialVariant( useMorphing, useSkinning, useInstancing ) {

			var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;

			var material = _depthMaterials[ index ];

			if ( material === undefined ) {

				material = new MeshDepthMaterial( {

					depthPacking: RGBADepthPacking,

					morphTargets: useMorphing,
					skinning: useSkinning

				} );

				_depthMaterials[ index ] = material;

			}

			return material;

		}

		function getDistanceMaterialVariant( useMorphing, useSkinning, useInstancing ) {

			var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;

			var material = _distanceMaterials[ index ];

			if ( material === undefined ) {

				material = new MeshDistanceMaterial( {

					morphTargets: useMorphing,
					skinning: useSkinning

				} );

				_distanceMaterials[ index ] = material;

			}

			return material;

		}

		function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) {

			var geometry = object.geometry;

			var result = null;

			var getMaterialVariant = getDepthMaterialVariant;
			var customMaterial = object.customDepthMaterial;

			if ( light.isPointLight === true ) {

				getMaterialVariant = getDistanceMaterialVariant;
				customMaterial = object.customDistanceMaterial;

			}

			if ( customMaterial === undefined ) {

				var useMorphing = false;

				if ( material.morphTargets === true ) {

					if ( geometry.isBufferGeometry === true ) {

						useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;

					} else if ( geometry.isGeometry === true ) {

						useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;

					}

				}

				var useSkinning = false;

				if ( object.isSkinnedMesh === true ) {

					if ( material.skinning === true ) {

						useSkinning = true;

					} else {

						console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );

					}

				}

				var useInstancing = object.isInstancedMesh === true;

				result = getMaterialVariant( useMorphing, useSkinning, useInstancing );

			} else {

				result = customMaterial;

			}

			if ( _renderer.localClippingEnabled &&
					material.clipShadows === true &&
					material.clippingPlanes.length !== 0 ) {

				// in this case we need a unique material instance reflecting the
				// appropriate state

				var keyA = result.uuid, keyB = material.uuid;

				var materialsForVariant = _materialCache[ keyA ];

				if ( materialsForVariant === undefined ) {

					materialsForVariant = {};
					_materialCache[ keyA ] = materialsForVariant;

				}

				var cachedMaterial = materialsForVariant[ keyB ];

				if ( cachedMaterial === undefined ) {

					cachedMaterial = result.clone();
					materialsForVariant[ keyB ] = cachedMaterial;

				}

				result = cachedMaterial;

			}

			result.visible = material.visible;
			result.wireframe = material.wireframe;

			if ( type === VSMShadowMap ) {

				result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;

			} else {

				result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];

			}

			result.clipShadows = material.clipShadows;
			result.clippingPlanes = material.clippingPlanes;
			result.clipIntersection = material.clipIntersection;

			result.wireframeLinewidth = material.wireframeLinewidth;
			result.linewidth = material.linewidth;

			if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {

				result.referencePosition.setFromMatrixPosition( light.matrixWorld );
				result.nearDistance = shadowCameraNear;
				result.farDistance = shadowCameraFar;

			}

			return result;

		}

		function renderObject( object, camera, shadowCamera, light, type ) {

			if ( object.visible === false ) { return; }

			var visible = object.layers.test( camera.layers );

			if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {

				if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {

					object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );

					var geometry = _objects.update( object );
					var material = object.material;

					if ( Array.isArray( material ) ) {

						var groups = geometry.groups;

						for ( var k = 0, kl = groups.length; k < kl; k ++ ) {

							var group = groups[ k ];
							var groupMaterial = material[ group.materialIndex ];

							if ( groupMaterial && groupMaterial.visible ) {

								var depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );

								_renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );

							}

						}

					} else if ( material.visible ) {

						var depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type );

						_renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );

					}

				}

			}

			var children = object.children;

			for ( var i = 0, l = children.length; i < l; i ++ ) {

				renderObject( children[ i ], camera, shadowCamera, light, type );

			}

		}

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function WebGLState( gl, extensions, capabilities ) {

		var isWebGL2 = capabilities.isWebGL2;

		function ColorBuffer() {

			var locked = false;

			var color = new Vector4();
			var currentColorMask = null;
			var currentColorClear = new Vector4( 0, 0, 0, 0 );

			return {

				setMask: function ( colorMask ) {

					if ( currentColorMask !== colorMask && ! locked ) {

						gl.colorMask( colorMask, colorMask, colorMask, colorMask );
						currentColorMask = colorMask;

					}

				},

				setLocked: function ( lock ) {

					locked = lock;

				},

				setClear: function ( r, g, b, a, premultipliedAlpha ) {

					if ( premultipliedAlpha === true ) {

						r *= a; g *= a; b *= a;

					}

					color.set( r, g, b, a );

					if ( currentColorClear.equals( color ) === false ) {

						gl.clearColor( r, g, b, a );
						currentColorClear.copy( color );

					}

				},

				reset: function () {

					locked = false;

					currentColorMask = null;
					currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state

				}

			};

		}

		function DepthBuffer() {

			var locked = false;

			var currentDepthMask = null;
			var currentDepthFunc = null;
			var currentDepthClear = null;

			return {

				setTest: function ( depthTest ) {

					if ( depthTest ) {

						enable( 2929 );

					} else {

						disable( 2929 );

					}

				},

				setMask: function ( depthMask ) {

					if ( currentDepthMask !== depthMask && ! locked ) {

						gl.depthMask( depthMask );
						currentDepthMask = depthMask;

					}

				},

				setFunc: function ( depthFunc ) {

					if ( currentDepthFunc !== depthFunc ) {

						if ( depthFunc ) {

							switch ( depthFunc ) {

								case NeverDepth:

									gl.depthFunc( 512 );
									break;

								case AlwaysDepth:

									gl.depthFunc( 519 );
									break;

								case LessDepth:

									gl.depthFunc( 513 );
									break;

								case LessEqualDepth:

									gl.depthFunc( 515 );
									break;

								case EqualDepth:

									gl.depthFunc( 514 );
									break;

								case GreaterEqualDepth:

									gl.depthFunc( 518 );
									break;

								case GreaterDepth:

									gl.depthFunc( 516 );
									break;

								case NotEqualDepth:

									gl.depthFunc( 517 );
									break;

								default:

									gl.depthFunc( 515 );

							}

						} else {

							gl.depthFunc( 515 );

						}

						currentDepthFunc = depthFunc;

					}

				},

				setLocked: function ( lock ) {

					locked = lock;

				},

				setClear: function ( depth ) {

					if ( currentDepthClear !== depth ) {

						gl.clearDepth( depth );
						currentDepthClear = depth;

					}

				},

				reset: function () {

					locked = false;

					currentDepthMask = null;
					currentDepthFunc = null;
					currentDepthClear = null;

				}

			};

		}

		function StencilBuffer() {

			var locked = false;

			var currentStencilMask = null;
			var currentStencilFunc = null;
			var currentStencilRef = null;
			var currentStencilFuncMask = null;
			var currentStencilFail = null;
			var currentStencilZFail = null;
			var currentStencilZPass = null;
			var currentStencilClear = null;

			return {

				setTest: function ( stencilTest ) {

					if ( ! locked ) {

						if ( stencilTest ) {

							enable( 2960 );

						} else {

							disable( 2960 );

						}

					}

				},

				setMask: function ( stencilMask ) {

					if ( currentStencilMask !== stencilMask && ! locked ) {

						gl.stencilMask( stencilMask );
						currentStencilMask = stencilMask;

					}

				},

				setFunc: function ( stencilFunc, stencilRef, stencilMask ) {

					if ( currentStencilFunc !== stencilFunc ||
					     currentStencilRef 	!== stencilRef 	||
					     currentStencilFuncMask !== stencilMask ) {

						gl.stencilFunc( stencilFunc, stencilRef, stencilMask );

						currentStencilFunc = stencilFunc;
						currentStencilRef = stencilRef;
						currentStencilFuncMask = stencilMask;

					}

				},

				setOp: function ( stencilFail, stencilZFail, stencilZPass ) {

					if ( currentStencilFail	 !== stencilFail 	||
					     currentStencilZFail !== stencilZFail ||
					     currentStencilZPass !== stencilZPass ) {

						gl.stencilOp( stencilFail, stencilZFail, stencilZPass );

						currentStencilFail = stencilFail;
						currentStencilZFail = stencilZFail;
						currentStencilZPass = stencilZPass;

					}

				},

				setLocked: function ( lock ) {

					locked = lock;

				},

				setClear: function ( stencil ) {

					if ( currentStencilClear !== stencil ) {

						gl.clearStencil( stencil );
						currentStencilClear = stencil;

					}

				},

				reset: function () {

					locked = false;

					currentStencilMask = null;
					currentStencilFunc = null;
					currentStencilRef = null;
					currentStencilFuncMask = null;
					currentStencilFail = null;
					currentStencilZFail = null;
					currentStencilZPass = null;
					currentStencilClear = null;

				}

			};

		}

		//

		var colorBuffer = new ColorBuffer();
		var depthBuffer = new DepthBuffer();
		var stencilBuffer = new StencilBuffer();

		var maxVertexAttributes = gl.getParameter( 34921 );
		var newAttributes = new Uint8Array( maxVertexAttributes );
		var enabledAttributes = new Uint8Array( maxVertexAttributes );
		var attributeDivisors = new Uint8Array( maxVertexAttributes );

		var enabledCapabilities = {};

		var currentProgram = null;

		var currentBlendingEnabled = null;
		var currentBlending = null;
		var currentBlendEquation = null;
		var currentBlendSrc = null;
		var currentBlendDst = null;
		var currentBlendEquationAlpha = null;
		var currentBlendSrcAlpha = null;
		var currentBlendDstAlpha = null;
		var currentPremultipledAlpha = false;

		var currentFlipSided = null;
		var currentCullFace = null;

		var currentLineWidth = null;

		var currentPolygonOffsetFactor = null;
		var currentPolygonOffsetUnits = null;

		var maxTextures = gl.getParameter( 35661 );

		var lineWidthAvailable = false;
		var version = 0;
		var glVersion = gl.getParameter( 7938 );

		if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {

			version = parseFloat( /^WebGL\ ([0-9])/.exec( glVersion )[ 1 ] );
			lineWidthAvailable = ( version >= 1.0 );

		} else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {

			version = parseFloat( /^OpenGL\ ES\ ([0-9])/.exec( glVersion )[ 1 ] );
			lineWidthAvailable = ( version >= 2.0 );

		}

		var currentTextureSlot = null;
		var currentBoundTextures = {};

		var currentScissor = new Vector4();
		var currentViewport = new Vector4();

		function createTexture( type, target, count ) {

			var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
			var texture = gl.createTexture();

			gl.bindTexture( type, texture );
			gl.texParameteri( type, 10241, 9728 );
			gl.texParameteri( type, 10240, 9728 );

			for ( var i = 0; i < count; i ++ ) {

				gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );

			}

			return texture;

		}

		var emptyTextures = {};
		emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
		emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );

		// init

		colorBuffer.setClear( 0, 0, 0, 1 );
		depthBuffer.setClear( 1 );
		stencilBuffer.setClear( 0 );

		enable( 2929 );
		depthBuffer.setFunc( LessEqualDepth );

		setFlipSided( false );
		setCullFace( CullFaceBack );
		enable( 2884 );

		setBlending( NoBlending );

		//

		function initAttributes() {

			for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {

				newAttributes[ i ] = 0;

			}

		}

		function enableAttribute( attribute ) {

			enableAttributeAndDivisor( attribute, 0 );

		}

		function enableAttributeAndDivisor( attribute, meshPerAttribute ) {

			newAttributes[ attribute ] = 1;

			if ( enabledAttributes[ attribute ] === 0 ) {

				gl.enableVertexAttribArray( attribute );
				enabledAttributes[ attribute ] = 1;

			}

			if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {

				var extension = isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );

				extension[ isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
				attributeDivisors[ attribute ] = meshPerAttribute;

			}

		}

		function disableUnusedAttributes() {

			for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {

				if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {

					gl.disableVertexAttribArray( i );
					enabledAttributes[ i ] = 0;

				}

			}

		}

		function enable( id ) {

			if ( enabledCapabilities[ id ] !== true ) {

				gl.enable( id );
				enabledCapabilities[ id ] = true;

			}

		}

		function disable( id ) {

			if ( enabledCapabilities[ id ] !== false ) {

				gl.disable( id );
				enabledCapabilities[ id ] = false;

			}

		}

		function useProgram( program ) {

			if ( currentProgram !== program ) {

				gl.useProgram( program );

				currentProgram = program;

				return true;

			}

			return false;

		}

		var equationToGL = {};
		equationToGL[ AddEquation ] = 32774;
		equationToGL[ SubtractEquation ] = 32778;
		equationToGL[ ReverseSubtractEquation ] = 32779;

		if ( isWebGL2 ) {

			equationToGL[ MinEquation ] = 32775;
			equationToGL[ MaxEquation ] = 32776;

		} else {

			var extension = extensions.get( 'EXT_blend_minmax' );

			if ( extension !== null ) {

				equationToGL[ MinEquation ] = extension.MIN_EXT;
				equationToGL[ MaxEquation ] = extension.MAX_EXT;

			}

		}

		var factorToGL = {};
		factorToGL[ ZeroFactor ] = 0;
		factorToGL[ OneFactor ] = 1;
		factorToGL[ SrcColorFactor ] = 768;
		factorToGL[ SrcAlphaFactor ] = 770;
		factorToGL[ SrcAlphaSaturateFactor ] = 776;
		factorToGL[ DstColorFactor ] = 774;
		factorToGL[ DstAlphaFactor ] = 772;
		factorToGL[ OneMinusSrcColorFactor ] = 769;
		factorToGL[ OneMinusSrcAlphaFactor ] = 771;
		factorToGL[ OneMinusDstColorFactor ] = 775;
		factorToGL[ OneMinusDstAlphaFactor ] = 773;

		function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {

			if ( blending === NoBlending ) {

				if ( currentBlendingEnabled ) {

					disable( 3042 );
					currentBlendingEnabled = false;

				}

				return;

			}

			if ( ! currentBlendingEnabled ) {

				enable( 3042 );
				currentBlendingEnabled = true;

			}

			if ( blending !== CustomBlending ) {

				if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {

					if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {

						gl.blendEquation( 32774 );

						currentBlendEquation = AddEquation;
						currentBlendEquationAlpha = AddEquation;

					}

					if ( premultipliedAlpha ) {

						switch ( blending ) {

							case NormalBlending:
								gl.blendFuncSeparate( 1, 771, 1, 771 );
								break;

							case AdditiveBlending:
								gl.blendFunc( 1, 1 );
								break;

							case SubtractiveBlending:
								gl.blendFuncSeparate( 0, 0, 769, 771 );
								break;

							case MultiplyBlending:
								gl.blendFuncSeparate( 0, 768, 0, 770 );
								break;

							default:
								console.error( 'THREE.WebGLState: Invalid blending: ', blending );
								break;

						}

					} else {

						switch ( blending ) {

							case NormalBlending:
								gl.blendFuncSeparate( 770, 771, 1, 771 );
								break;

							case AdditiveBlending:
								gl.blendFunc( 770, 1 );
								break;

							case SubtractiveBlending:
								gl.blendFunc( 0, 769 );
								break;

							case MultiplyBlending:
								gl.blendFunc( 0, 768 );
								break;

							default:
								console.error( 'THREE.WebGLState: Invalid blending: ', blending );
								break;

						}

					}

					currentBlendSrc = null;
					currentBlendDst = null;
					currentBlendSrcAlpha = null;
					currentBlendDstAlpha = null;

					currentBlending = blending;
					currentPremultipledAlpha = premultipliedAlpha;

				}

				return;

			}

			// custom blending

			blendEquationAlpha = blendEquationAlpha || blendEquation;
			blendSrcAlpha = blendSrcAlpha || blendSrc;
			blendDstAlpha = blendDstAlpha || blendDst;

			if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {

				gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );

				currentBlendEquation = blendEquation;
				currentBlendEquationAlpha = blendEquationAlpha;

			}

			if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {

				gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );

				currentBlendSrc = blendSrc;
				currentBlendDst = blendDst;
				currentBlendSrcAlpha = blendSrcAlpha;
				currentBlendDstAlpha = blendDstAlpha;

			}

			currentBlending = blending;
			currentPremultipledAlpha = null;

		}

		function setMaterial( material, frontFaceCW ) {

			material.side === DoubleSide
				? disable( 2884 )
				: enable( 2884 );

			var flipSided = ( material.side === BackSide );
			if ( frontFaceCW ) { flipSided = ! flipSided; }

			setFlipSided( flipSided );

			( material.blending === NormalBlending && material.transparent === false )
				? setBlending( NoBlending )
				: setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );

			depthBuffer.setFunc( material.depthFunc );
			depthBuffer.setTest( material.depthTest );
			depthBuffer.setMask( material.depthWrite );
			colorBuffer.setMask( material.colorWrite );

			var stencilWrite = material.stencilWrite;
			stencilBuffer.setTest( stencilWrite );
			if ( stencilWrite ) {

				stencilBuffer.setMask( material.stencilWriteMask );
				stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
				stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );

			}

			setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );

		}

		//

		function setFlipSided( flipSided ) {

			if ( currentFlipSided !== flipSided ) {

				if ( flipSided ) {

					gl.frontFace( 2304 );

				} else {

					gl.frontFace( 2305 );

				}

				currentFlipSided = flipSided;

			}

		}

		function setCullFace( cullFace ) {

			if ( cullFace !== CullFaceNone ) {

				enable( 2884 );

				if ( cullFace !== currentCullFace ) {

					if ( cullFace === CullFaceBack ) {

						gl.cullFace( 1029 );

					} else if ( cullFace === CullFaceFront ) {

						gl.cullFace( 1028 );

					} else {

						gl.cullFace( 1032 );

					}

				}

			} else {

				disable( 2884 );

			}

			currentCullFace = cullFace;

		}

		function setLineWidth( width ) {

			if ( width !== currentLineWidth ) {

				if ( lineWidthAvailable ) { gl.lineWidth( width ); }

				currentLineWidth = width;

			}

		}

		function setPolygonOffset( polygonOffset, factor, units ) {

			if ( polygonOffset ) {

				enable( 32823 );

				if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {

					gl.polygonOffset( factor, units );

					currentPolygonOffsetFactor = factor;
					currentPolygonOffsetUnits = units;

				}

			} else {

				disable( 32823 );

			}

		}

		function setScissorTest( scissorTest ) {

			if ( scissorTest ) {

				enable( 3089 );

			} else {

				disable( 3089 );

			}

		}

		// texture

		function activeTexture( webglSlot ) {

			if ( webglSlot === undefined ) { webglSlot = 33984 + maxTextures - 1; }

			if ( currentTextureSlot !== webglSlot ) {

				gl.activeTexture( webglSlot );
				currentTextureSlot = webglSlot;

			}

		}

		function bindTexture( webglType, webglTexture ) {

			if ( currentTextureSlot === null ) {

				activeTexture();

			}

			var boundTexture = currentBoundTextures[ currentTextureSlot ];

			if ( boundTexture === undefined ) {

				boundTexture = { type: undefined, texture: undefined };
				currentBoundTextures[ currentTextureSlot ] = boundTexture;

			}

			if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {

				gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );

				boundTexture.type = webglType;
				boundTexture.texture = webglTexture;

			}

		}

		function unbindTexture() {

			var boundTexture = currentBoundTextures[ currentTextureSlot ];

			if ( boundTexture !== undefined && boundTexture.type !== undefined ) {

				gl.bindTexture( boundTexture.type, null );

				boundTexture.type = undefined;
				boundTexture.texture = undefined;

			}

		}

		function compressedTexImage2D() {

			try {

				gl.compressedTexImage2D.apply( gl, arguments );

			} catch ( error ) {

				console.error( 'THREE.WebGLState:', error );

			}

		}

		function texImage2D() {

			try {

				gl.texImage2D.apply( gl, arguments );

			} catch ( error ) {

				console.error( 'THREE.WebGLState:', error );

			}

		}

		function texImage3D() {

			try {

				gl.texImage3D.apply( gl, arguments );

			} catch ( error ) {

				console.error( 'THREE.WebGLState:', error );

			}

		}

		//

		function scissor( scissor ) {

			if ( currentScissor.equals( scissor ) === false ) {

				gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
				currentScissor.copy( scissor );

			}

		}

		function viewport( viewport ) {

			if ( currentViewport.equals( viewport ) === false ) {

				gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
				currentViewport.copy( viewport );

			}

		}

		//

		function reset() {

			for ( var i = 0; i < enabledAttributes.length; i ++ ) {

				if ( enabledAttributes[ i ] === 1 ) {

					gl.disableVertexAttribArray( i );
					enabledAttributes[ i ] = 0;

				}

			}

			enabledCapabilities = {};

			currentTextureSlot = null;
			currentBoundTextures = {};

			currentProgram = null;

			currentBlending = null;

			currentFlipSided = null;
			currentCullFace = null;

			colorBuffer.reset();
			depthBuffer.reset();
			stencilBuffer.reset();

		}

		return {

			buffers: {
				color: colorBuffer,
				depth: depthBuffer,
				stencil: stencilBuffer
			},

			initAttributes: initAttributes,
			enableAttribute: enableAttribute,
			enableAttributeAndDivisor: enableAttributeAndDivisor,
			disableUnusedAttributes: disableUnusedAttributes,
			enable: enable,
			disable: disable,

			useProgram: useProgram,

			setBlending: setBlending,
			setMaterial: setMaterial,

			setFlipSided: setFlipSided,
			setCullFace: setCullFace,

			setLineWidth: setLineWidth,
			setPolygonOffset: setPolygonOffset,

			setScissorTest: setScissorTest,

			activeTexture: activeTexture,
			bindTexture: bindTexture,
			unbindTexture: unbindTexture,
			compressedTexImage2D: compressedTexImage2D,
			texImage2D: texImage2D,
			texImage3D: texImage3D,

			scissor: scissor,
			viewport: viewport,

			reset: reset

		};

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {

		var isWebGL2 = capabilities.isWebGL2;
		var maxTextures = capabilities.maxTextures;
		var maxCubemapSize = capabilities.maxCubemapSize;
		var maxTextureSize = capabilities.maxTextureSize;
		var maxSamples = capabilities.maxSamples;

		var _videoTextures = new WeakMap();
		var _canvas;

		// cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
		// also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
		// Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).

		var useOffscreenCanvas = false;

		try {

			useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
				&& ( new OffscreenCanvas( 1, 1 ).getContext( "2d" ) ) !== null;

		} catch ( err ) {

			// Ignore any errors

		}

		function createCanvas( width, height ) {

			// Use OffscreenCanvas when available. Specially needed in web workers

			return useOffscreenCanvas ?
				new OffscreenCanvas( width, height ) :
				document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );

		}

		function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {

			var scale = 1;

			// handle case if texture exceeds max size

			if ( image.width > maxSize || image.height > maxSize ) {

				scale = maxSize / Math.max( image.width, image.height );

			}

			// only perform resize if necessary

			if ( scale < 1 || needsPowerOfTwo === true ) {

				// only perform resize for certain image types

				if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
					( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
					( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {

					var floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;

					var width = floor( scale * image.width );
					var height = floor( scale * image.height );

					if ( _canvas === undefined ) { _canvas = createCanvas( width, height ); }

					// cube textures can't reuse the same canvas

					var canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;

					canvas.width = width;
					canvas.height = height;

					var context = canvas.getContext( '2d' );
					context.drawImage( image, 0, 0, width, height );

					console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );

					return canvas;

				} else {

					if ( 'data' in image ) {

						console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );

					}

					return image;

				}

			}

			return image;

		}

		function isPowerOfTwo( image ) {

			return MathUtils.isPowerOfTwo( image.width ) && MathUtils.isPowerOfTwo( image.height );

		}

		function textureNeedsPowerOfTwo( texture ) {

			if ( isWebGL2 ) { return false; }

			return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
				( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );

		}

		function textureNeedsGenerateMipmaps( texture, supportsMips ) {

			return texture.generateMipmaps && supportsMips &&
				texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;

		}

		function generateMipmap( target, texture, width, height ) {

			_gl.generateMipmap( target );

			var textureProperties = properties.get( texture );

			// Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
			textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;

		}

		function getInternalFormat( internalFormatName, glFormat, glType ) {

			if ( isWebGL2 === false ) { return glFormat; }

			if ( internalFormatName !== null ) {

				if ( _gl[ internalFormatName ] !== undefined ) { return _gl[ internalFormatName ]; }

				console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );

			}

			var internalFormat = glFormat;

			if ( glFormat === 6403 ) {

				if ( glType === 5126 ) { internalFormat = 33326; }
				if ( glType === 5131 ) { internalFormat = 33325; }
				if ( glType === 5121 ) { internalFormat = 33321; }

			}

			if ( glFormat === 6407 ) {

				if ( glType === 5126 ) { internalFormat = 34837; }
				if ( glType === 5131 ) { internalFormat = 34843; }
				if ( glType === 5121 ) { internalFormat = 32849; }

			}

			if ( glFormat === 6408 ) {

				if ( glType === 5126 ) { internalFormat = 34836; }
				if ( glType === 5131 ) { internalFormat = 34842; }
				if ( glType === 5121 ) { internalFormat = 32856; }

			}

			if ( internalFormat === 33325 || internalFormat === 33326 ||
				internalFormat === 34842 || internalFormat === 34836 ) {

				extensions.get( 'EXT_color_buffer_float' );

			} else if ( internalFormat === 34843 || internalFormat === 34837 ) {

				console.warn( 'THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead.' );

			}

			return internalFormat;

		}

		// Fallback filters for non-power-of-2 textures

		function filterFallback( f ) {

			if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {

				return 9728;

			}

			return 9729;

		}

		//

		function onTextureDispose( event ) {

			var texture = event.target;

			texture.removeEventListener( 'dispose', onTextureDispose );

			deallocateTexture( texture );

			if ( texture.isVideoTexture ) {

				_videoTextures.delete( texture );

			}

			info.memory.textures --;

		}

		function onRenderTargetDispose( event ) {

			var renderTarget = event.target;

			renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );

			deallocateRenderTarget( renderTarget );

			info.memory.textures --;

		}

		//

		function deallocateTexture( texture ) {

			var textureProperties = properties.get( texture );

			if ( textureProperties.__webglInit === undefined ) { return; }

			_gl.deleteTexture( textureProperties.__webglTexture );

			properties.remove( texture );

		}

		function deallocateRenderTarget( renderTarget ) {

			var renderTargetProperties = properties.get( renderTarget );
			var textureProperties = properties.get( renderTarget.texture );

			if ( ! renderTarget ) { return; }

			if ( textureProperties.__webglTexture !== undefined ) {

				_gl.deleteTexture( textureProperties.__webglTexture );

			}

			if ( renderTarget.depthTexture ) {

				renderTarget.depthTexture.dispose();

			}

			if ( renderTarget.isWebGLCubeRenderTarget ) {

				for ( var i = 0; i < 6; i ++ ) {

					_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
					if ( renderTargetProperties.__webglDepthbuffer ) { _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); }

				}

			} else {

				_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
				if ( renderTargetProperties.__webglDepthbuffer ) { _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); }

			}

			if ( renderTarget.isWebGLMultiviewRenderTarget ) {

				_gl.deleteTexture( renderTargetProperties.__webglColorTexture );
				_gl.deleteTexture( renderTargetProperties.__webglDepthStencilTexture );

				info.memory.textures -= 2;

				for ( var i = 0, il = renderTargetProperties.__webglViewFramebuffers.length; i < il; i ++ ) {

					_gl.deleteFramebuffer( renderTargetProperties.__webglViewFramebuffers[ i ] );

				}

			}

			properties.remove( renderTarget.texture );
			properties.remove( renderTarget );

		}

		//

		var textureUnits = 0;

		function resetTextureUnits() {

			textureUnits = 0;

		}

		function allocateTextureUnit() {

			var textureUnit = textureUnits;

			if ( textureUnit >= maxTextures ) {

				console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );

			}

			textureUnits += 1;

			return textureUnit;

		}

		//

		function setTexture2D( texture, slot ) {

			var textureProperties = properties.get( texture );

			if ( texture.isVideoTexture ) { updateVideoTexture( texture ); }

			if ( texture.version > 0 && textureProperties.__version !== texture.version ) {

				var image = texture.image;

				if ( image === undefined ) {

					console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );

				} else if ( image.complete === false ) {

					console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );

				} else {

					uploadTexture( textureProperties, texture, slot );
					return;

				}

			}

			state.activeTexture( 33984 + slot );
			state.bindTexture( 3553, textureProperties.__webglTexture );

		}

		function setTexture2DArray( texture, slot ) {

			var textureProperties = properties.get( texture );

			if ( texture.version > 0 && textureProperties.__version !== texture.version ) {

				uploadTexture( textureProperties, texture, slot );
				return;

			}

			state.activeTexture( 33984 + slot );
			state.bindTexture( 35866, textureProperties.__webglTexture );

		}

		function setTexture3D( texture, slot ) {

			var textureProperties = properties.get( texture );

			if ( texture.version > 0 && textureProperties.__version !== texture.version ) {

				uploadTexture( textureProperties, texture, slot );
				return;

			}

			state.activeTexture( 33984 + slot );
			state.bindTexture( 32879, textureProperties.__webglTexture );

		}

		function setTextureCube( texture, slot ) {

			if ( texture.image.length !== 6 ) { return; }

			var textureProperties = properties.get( texture );

			if ( texture.version > 0 && textureProperties.__version !== texture.version ) {

				initTexture( textureProperties, texture );

				state.activeTexture( 33984 + slot );
				state.bindTexture( 34067, textureProperties.__webglTexture );

				_gl.pixelStorei( 37440, texture.flipY );

				var isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
				var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );

				var cubeImage = [];

				for ( var i = 0; i < 6; i ++ ) {

					if ( ! isCompressed && ! isDataTexture ) {

						cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );

					} else {

						cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];

					}

				}

				var image = cubeImage[ 0 ],
					supportsMips = isPowerOfTwo( image ) || isWebGL2,
					glFormat = utils.convert( texture.format ),
					glType = utils.convert( texture.type ),
					glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );

				setTextureParameters( 34067, texture, supportsMips );

				var mipmaps;

				if ( isCompressed ) {

					for ( var i = 0; i < 6; i ++ ) {

						mipmaps = cubeImage[ i ].mipmaps;

						for ( var j = 0; j < mipmaps.length; j ++ ) {

							var mipmap = mipmaps[ j ];

							if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {

								if ( glFormat !== null ) {

									state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );

								} else {

									console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );

								}

							} else {

								state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );

							}

						}

					}

					textureProperties.__maxMipLevel = mipmaps.length - 1;

				} else {

					mipmaps = texture.mipmaps;

					for ( var i = 0; i < 6; i ++ ) {

						if ( isDataTexture ) {

							state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );

							for ( var j = 0; j < mipmaps.length; j ++ ) {

								var mipmap = mipmaps[ j ];
								var mipmapImage = mipmap.image[ i ].image;

								state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );

							}

						} else {

							state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );

							for ( var j = 0; j < mipmaps.length; j ++ ) {

								var mipmap = mipmaps[ j ];

								state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );

							}

						}

					}

					textureProperties.__maxMipLevel = mipmaps.length;

				}

				if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {

					// We assume images for cube map have the same size.
					generateMipmap( 34067, texture, image.width, image.height );

				}

				textureProperties.__version = texture.version;

				if ( texture.onUpdate ) { texture.onUpdate( texture ); }

			} else {

				state.activeTexture( 33984 + slot );
				state.bindTexture( 34067, textureProperties.__webglTexture );

			}

		}

		function setTextureCubeDynamic( texture, slot ) {

			state.activeTexture( 33984 + slot );
			state.bindTexture( 34067, properties.get( texture ).__webglTexture );

		}

		var wrappingToGL = {};
		wrappingToGL[ RepeatWrapping ] = 10497;
		wrappingToGL[ ClampToEdgeWrapping ] = 33071;
		wrappingToGL[ MirroredRepeatWrapping ] = 33648;

		var filterToGL = {};
		filterToGL[ NearestFilter ] = 9728;
		filterToGL[ NearestMipmapNearestFilter ] = 9984;
		filterToGL[ NearestMipmapLinearFilter ] = 9986;
		filterToGL[ LinearFilter ] = 9729;
		filterToGL[ LinearMipmapNearestFilter ] = 9985;
		filterToGL[ LinearMipmapLinearFilter ] = 9987;

		function setTextureParameters( textureType, texture, supportsMips ) {

			if ( supportsMips ) {

				_gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
				_gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );

				if ( textureType === 32879 || textureType === 35866 ) {

					_gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );

				}

				_gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
				_gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );

			} else {

				_gl.texParameteri( textureType, 10242, 33071 );
				_gl.texParameteri( textureType, 10243, 33071 );

				if ( textureType === 32879 || textureType === 35866 ) {

					_gl.texParameteri( textureType, 32882, 33071 );

				}

				if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {

					console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );

				}

				_gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
				_gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );

				if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {

					console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );

				}

			}

			var extension = extensions.get( 'EXT_texture_filter_anisotropic' );

			if ( extension ) {

				if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) { return; }
				if ( texture.type === HalfFloatType && ( isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) { return; }

				if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {

					_gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
					properties.get( texture ).__currentAnisotropy = texture.anisotropy;

				}

			}

		}

		function initTexture( textureProperties, texture ) {

			if ( textureProperties.__webglInit === undefined ) {

				textureProperties.__webglInit = true;

				texture.addEventListener( 'dispose', onTextureDispose );

				textureProperties.__webglTexture = _gl.createTexture();

				info.memory.textures ++;

			}

		}

		function uploadTexture( textureProperties, texture, slot ) {

			var textureType = 3553;

			if ( texture.isDataTexture2DArray ) { textureType = 35866; }
			if ( texture.isDataTexture3D ) { textureType = 32879; }

			initTexture( textureProperties, texture );

			state.activeTexture( 33984 + slot );
			state.bindTexture( textureType, textureProperties.__webglTexture );

			_gl.pixelStorei( 37440, texture.flipY );
			_gl.pixelStorei( 37441, texture.premultiplyAlpha );
			_gl.pixelStorei( 3317, texture.unpackAlignment );

			var needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false;
			var image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );

			var supportsMips = isPowerOfTwo( image ) || isWebGL2,
				glFormat = utils.convert( texture.format ),
				glType = utils.convert( texture.type ),
				glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );

			setTextureParameters( textureType, texture, supportsMips );

			var mipmap, mipmaps = texture.mipmaps;

			if ( texture.isDepthTexture ) {

				// populate depth texture with dummy data

				glInternalFormat = 6402;

				if ( texture.type === FloatType ) {

					if ( isWebGL2 === false ) { throw new Error( 'Float Depth Texture only supported in WebGL2.0' ); }
					glInternalFormat = 36012;

				} else if ( isWebGL2 ) {

					// WebGL 2.0 requires signed internalformat for glTexImage2D
					glInternalFormat = 33189;

				}

				if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {

					// The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
					// DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
					// (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
					if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {

						console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );

						texture.type = UnsignedShortType;
						glType = utils.convert( texture.type );

					}

				}

				// Depth stencil textures need the DEPTH_STENCIL internal format
				// (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
				if ( texture.format === DepthStencilFormat ) {

					glInternalFormat = 34041;

					// The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
					// DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
					// (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
					if ( texture.type !== UnsignedInt248Type ) {

						console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );

						texture.type = UnsignedInt248Type;
						glType = utils.convert( texture.type );

					}

				}

				state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );

			} else if ( texture.isDataTexture ) {

				// use manually created mipmaps if available
				// if there are no manual mipmaps
				// set 0 level mipmap and then use GL to generate other mipmap levels

				if ( mipmaps.length > 0 && supportsMips ) {

					for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {

						mipmap = mipmaps[ i ];
						state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );

					}

					texture.generateMipmaps = false;
					textureProperties.__maxMipLevel = mipmaps.length - 1;

				} else {

					state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
					textureProperties.__maxMipLevel = 0;

				}

			} else if ( texture.isCompressedTexture ) {

				for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {

					mipmap = mipmaps[ i ];

					if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {

						if ( glFormat !== null ) {

							state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );

						} else {

							console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );

						}

					} else {

						state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );

					}

				}

				textureProperties.__maxMipLevel = mipmaps.length - 1;

			} else if ( texture.isDataTexture2DArray ) {

				state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
				textureProperties.__maxMipLevel = 0;

			} else if ( texture.isDataTexture3D ) {

				state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
				textureProperties.__maxMipLevel = 0;

			} else {

				// regular Texture (image, video, canvas)

				// use manually created mipmaps if available
				// if there are no manual mipmaps
				// set 0 level mipmap and then use GL to generate other mipmap levels

				if ( mipmaps.length > 0 && supportsMips ) {

					for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {

						mipmap = mipmaps[ i ];
						state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );

					}

					texture.generateMipmaps = false;
					textureProperties.__maxMipLevel = mipmaps.length - 1;

				} else {

					state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
					textureProperties.__maxMipLevel = 0;

				}

			}

			if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {

				generateMipmap( textureType, texture, image.width, image.height );

			}

			textureProperties.__version = texture.version;

			if ( texture.onUpdate ) { texture.onUpdate( texture ); }

		}

		// Render targets

		// Setup storage for target texture and bind it to correct framebuffer
		function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {

			var glFormat = utils.convert( renderTarget.texture.format );
			var glType = utils.convert( renderTarget.texture.type );
			var glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
			state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
			_gl.bindFramebuffer( 36160, framebuffer );
			_gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
			_gl.bindFramebuffer( 36160, null );

		}

		// Setup storage for internal depth/stencil buffers and bind to correct framebuffer
		function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {

			_gl.bindRenderbuffer( 36161, renderbuffer );

			if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {

				if ( isMultisample ) {

					var samples = getRenderTargetSamples( renderTarget );

					_gl.renderbufferStorageMultisample( 36161, samples, 33189, renderTarget.width, renderTarget.height );

				} else {

					_gl.renderbufferStorage( 36161, 33189, renderTarget.width, renderTarget.height );

				}

				_gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );

			} else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {

				if ( isMultisample ) {

					var samples = getRenderTargetSamples( renderTarget );

					_gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );

				} else {

					_gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );

				}


				_gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );

			} else {

				var glFormat = utils.convert( renderTarget.texture.format );
				var glType = utils.convert( renderTarget.texture.type );
				var glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );

				if ( isMultisample ) {

					var samples = getRenderTargetSamples( renderTarget );

					_gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );

				} else {

					_gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );

				}

			}

			_gl.bindRenderbuffer( 36161, null );

		}

		// Setup resources for a Depth Texture for a FBO (needs an extension)
		function setupDepthTexture( framebuffer, renderTarget ) {

			var isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
			if ( isCube ) { throw new Error( 'Depth Texture with cube render targets is not supported' ); }

			_gl.bindFramebuffer( 36160, framebuffer );

			if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {

				throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );

			}

			// upload an empty depth texture with framebuffer size
			if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
					renderTarget.depthTexture.image.width !== renderTarget.width ||
					renderTarget.depthTexture.image.height !== renderTarget.height ) {

				renderTarget.depthTexture.image.width = renderTarget.width;
				renderTarget.depthTexture.image.height = renderTarget.height;
				renderTarget.depthTexture.needsUpdate = true;

			}

			setTexture2D( renderTarget.depthTexture, 0 );

			var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;

			if ( renderTarget.depthTexture.format === DepthFormat ) {

				_gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );

			} else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {

				_gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );

			} else {

				throw new Error( 'Unknown depthTexture format' );

			}

		}

		// Setup GL resources for a non-texture depth buffer
		function setupDepthRenderbuffer( renderTarget ) {

			var renderTargetProperties = properties.get( renderTarget );

			var isCube = ( renderTarget.isWebGLCubeRenderTarget === true );

			if ( renderTarget.depthTexture ) {

				if ( isCube ) { throw new Error( 'target.depthTexture not supported in Cube render targets' ); }

				setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );

			} else {

				if ( isCube ) {

					renderTargetProperties.__webglDepthbuffer = [];

					for ( var i = 0; i < 6; i ++ ) {

						_gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
						renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
						setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );

					}

				} else {

					_gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
					renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
					setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );

				}

			}

			_gl.bindFramebuffer( 36160, null );

		}

		// Set up GL resources for the render target
		function setupRenderTarget( renderTarget ) {

			var renderTargetProperties = properties.get( renderTarget );
			var textureProperties = properties.get( renderTarget.texture );

			renderTarget.addEventListener( 'dispose', onRenderTargetDispose );

			textureProperties.__webglTexture = _gl.createTexture();

			info.memory.textures ++;

			var isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
			var isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
			var isMultiview = ( renderTarget.isWebGLMultiviewRenderTarget === true );
			var supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;

			// Setup framebuffer

			if ( isCube ) {

				renderTargetProperties.__webglFramebuffer = [];

				for ( var i = 0; i < 6; i ++ ) {

					renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();

				}

			} else {

				renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();

				if ( isMultisample ) {

					if ( isWebGL2 ) {

						renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
						renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();

						_gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );

						var glFormat = utils.convert( renderTarget.texture.format );
						var glType = utils.convert( renderTarget.texture.type );
						var glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
						var samples = getRenderTargetSamples( renderTarget );
						_gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );

						_gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
						_gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
						_gl.bindRenderbuffer( 36161, null );

						if ( renderTarget.depthBuffer ) {

							renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
							setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );

						}

						_gl.bindFramebuffer( 36160, null );


					} else {

						console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );

					}

				} else if ( isMultiview ) {

					var width = renderTarget.width;
					var height = renderTarget.height;
					var numViews = renderTarget.numViews;

					_gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );

					var ext = extensions.get( 'OVR_multiview2' );

					info.memory.textures += 2;

					var colorTexture = _gl.createTexture();
					_gl.bindTexture( 35866, colorTexture );
					_gl.texParameteri( 35866, 10240, 9728 );
					_gl.texParameteri( 35866, 10241, 9728 );
					_gl.texImage3D( 35866, 0, 32856, width, height, numViews, 0, 6408, 5121, null );
					ext.framebufferTextureMultiviewOVR( 36160, 36064, colorTexture, 0, 0, numViews );

					var depthStencilTexture = _gl.createTexture();
					_gl.bindTexture( 35866, depthStencilTexture );
					_gl.texParameteri( 35866, 10240, 9728 );
					_gl.texParameteri( 35866, 10241, 9728 );
					_gl.texImage3D( 35866, 0, 35056, width, height, numViews, 0, 34041, 34042, null );
					ext.framebufferTextureMultiviewOVR( 36160, 33306, depthStencilTexture, 0, 0, numViews );

					var viewFramebuffers = new Array( numViews );
					for ( var i = 0; i < numViews; ++ i ) {

						viewFramebuffers[ i ] = _gl.createFramebuffer();
						_gl.bindFramebuffer( 36160, viewFramebuffers[ i ] );
						_gl.framebufferTextureLayer( 36160, 36064, colorTexture, 0, i );

					}

					renderTargetProperties.__webglColorTexture = colorTexture;
					renderTargetProperties.__webglDepthStencilTexture = depthStencilTexture;
					renderTargetProperties.__webglViewFramebuffers = viewFramebuffers;

					_gl.bindFramebuffer( 36160, null );
					_gl.bindTexture( 35866, null );

				}

			}

			// Setup color buffer

			if ( isCube ) {

				state.bindTexture( 34067, textureProperties.__webglTexture );
				setTextureParameters( 34067, renderTarget.texture, supportsMips );

				for ( var i = 0; i < 6; i ++ ) {

					setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i );

				}

				if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {

					generateMipmap( 34067, renderTarget.texture, renderTarget.width, renderTarget.height );

				}

				state.bindTexture( 34067, null );

			} else if ( ! isMultiview ) {

				state.bindTexture( 3553, textureProperties.__webglTexture );
				setTextureParameters( 3553, renderTarget.texture, supportsMips );
				setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553 );

				if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {

					generateMipmap( 3553, renderTarget.texture, renderTarget.width, renderTarget.height );

				}

				state.bindTexture( 3553, null );

			}

			// Setup depth and stencil buffers

			if ( renderTarget.depthBuffer ) {

				setupDepthRenderbuffer( renderTarget );

			}

		}

		function updateRenderTargetMipmap( renderTarget ) {

			var texture = renderTarget.texture;
			var supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;

			if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {

				var target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
				var webglTexture = properties.get( texture ).__webglTexture;

				state.bindTexture( target, webglTexture );
				generateMipmap( target, texture, renderTarget.width, renderTarget.height );
				state.bindTexture( target, null );

			}

		}

		function updateMultisampleRenderTarget( renderTarget ) {

			if ( renderTarget.isWebGLMultisampleRenderTarget ) {

				if ( isWebGL2 ) {

					var renderTargetProperties = properties.get( renderTarget );

					_gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
					_gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );

					var width = renderTarget.width;
					var height = renderTarget.height;
					var mask = 16384;

					if ( renderTarget.depthBuffer ) { mask |= 256; }
					if ( renderTarget.stencilBuffer ) { mask |= 1024; }

					_gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );

				} else {

					console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );

				}

			}

		}

		function getRenderTargetSamples( renderTarget ) {

			return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
				Math.min( maxSamples, renderTarget.samples ) : 0;

		}

		function updateVideoTexture( texture ) {

			var frame = info.render.frame;

			// Check the last frame we updated the VideoTexture

			if ( _videoTextures.get( texture ) !== frame ) {

				_videoTextures.set( texture, frame );
				texture.update();

			}

		}

		// backwards compatibility

		var warnedTexture2D = false;
		var warnedTextureCube = false;

		function safeSetTexture2D( texture, slot ) {

			if ( texture && texture.isWebGLRenderTarget ) {

				if ( warnedTexture2D === false ) {

					console.warn( "THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead." );
					warnedTexture2D = true;

				}

				texture = texture.texture;

			}

			setTexture2D( texture, slot );

		}

		function safeSetTextureCube( texture, slot ) {

			if ( texture && texture.isWebGLCubeRenderTarget ) {

				if ( warnedTextureCube === false ) {

					console.warn( "THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
					warnedTextureCube = true;

				}

				texture = texture.texture;

			}

			// currently relying on the fact that WebGLCubeRenderTarget.texture is a Texture and NOT a CubeTexture
			// TODO: unify these code paths
			if ( ( texture && texture.isCubeTexture ) ||
				( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {

				// CompressedTexture can have Array in image :/

				// this function alone should take care of cube textures
				setTextureCube( texture, slot );

			} else {

				// assumed: texture property of THREE.WebGLCubeRenderTarget
				setTextureCubeDynamic( texture, slot );

			}

		}

		//

		this.allocateTextureUnit = allocateTextureUnit;
		this.resetTextureUnits = resetTextureUnits;

		this.setTexture2D = setTexture2D;
		this.setTexture2DArray = setTexture2DArray;
		this.setTexture3D = setTexture3D;
		this.setTextureCube = setTextureCube;
		this.setTextureCubeDynamic = setTextureCubeDynamic;
		this.setupRenderTarget = setupRenderTarget;
		this.updateRenderTargetMipmap = updateRenderTargetMipmap;
		this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;

		this.safeSetTexture2D = safeSetTexture2D;
		this.safeSetTextureCube = safeSetTextureCube;

	}

	/**
	 * @author thespite / http://www.twitter.com/thespite
	 */

	function WebGLUtils( gl, extensions, capabilities ) {

		var isWebGL2 = capabilities.isWebGL2;

		function convert( p ) {

			var extension;

			if ( p === UnsignedByteType ) { return 5121; }
			if ( p === UnsignedShort4444Type ) { return 32819; }
			if ( p === UnsignedShort5551Type ) { return 32820; }
			if ( p === UnsignedShort565Type ) { return 33635; }

			if ( p === ByteType ) { return 5120; }
			if ( p === ShortType ) { return 5122; }
			if ( p === UnsignedShortType ) { return 5123; }
			if ( p === IntType ) { return 5124; }
			if ( p === UnsignedIntType ) { return 5125; }
			if ( p === FloatType ) { return 5126; }

			if ( p === HalfFloatType ) {

				if ( isWebGL2 ) { return 5131; }

				extension = extensions.get( 'OES_texture_half_float' );

				if ( extension !== null ) {

					return extension.HALF_FLOAT_OES;

				} else {

					return null;

				}

			}

			if ( p === AlphaFormat ) { return 6406; }
			if ( p === RGBFormat ) { return 6407; }
			if ( p === RGBAFormat ) { return 6408; }
			if ( p === LuminanceFormat ) { return 6409; }
			if ( p === LuminanceAlphaFormat ) { return 6410; }
			if ( p === DepthFormat ) { return 6402; }
			if ( p === DepthStencilFormat ) { return 34041; }
			if ( p === RedFormat ) { return 6403; }

			// WebGL2 formats.

			if ( p === RedIntegerFormat ) { return 36244; }
			if ( p === RGFormat ) { return 33319; }
			if ( p === RGIntegerFormat ) { return 33320; }
			if ( p === RGBIntegerFormat ) { return 36248; }
			if ( p === RGBAIntegerFormat ) { return 36249; }

			if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
				p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {

				extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );

				if ( extension !== null ) {

					if ( p === RGB_S3TC_DXT1_Format ) { return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; }
					if ( p === RGBA_S3TC_DXT1_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; }
					if ( p === RGBA_S3TC_DXT3_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; }
					if ( p === RGBA_S3TC_DXT5_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; }

				} else {

					return null;

				}

			}

			if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
				p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {

				extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );

				if ( extension !== null ) {

					if ( p === RGB_PVRTC_4BPPV1_Format ) { return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; }
					if ( p === RGB_PVRTC_2BPPV1_Format ) { return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; }
					if ( p === RGBA_PVRTC_4BPPV1_Format ) { return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; }
					if ( p === RGBA_PVRTC_2BPPV1_Format ) { return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; }

				} else {

					return null;

				}

			}

			if ( p === RGB_ETC1_Format ) {

				extension = extensions.get( 'WEBGL_compressed_texture_etc1' );

				if ( extension !== null ) {

					return extension.COMPRESSED_RGB_ETC1_WEBGL;

				} else {

					return null;

				}

			}

			if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
				p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
				p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
				p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
				p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {

				extension = extensions.get( 'WEBGL_compressed_texture_astc' );

				if ( extension !== null ) {

					// TODO Complete?

					return p;

				} else {

					return null;

				}

			}

			if ( p === UnsignedInt248Type ) {

				if ( isWebGL2 ) { return 34042; }

				extension = extensions.get( 'WEBGL_depth_texture' );

				if ( extension !== null ) {

					return extension.UNSIGNED_INT_24_8_WEBGL;

				} else {

					return null;

				}

			}

		}

		return { convert: convert };

	}

	/**
	 * @author fernandojsg / http://fernandojsg.com
	 * @author Takahiro https://github.com/takahirox
	 */

	function WebGLMultiviewRenderTarget( width, height, numViews, options ) {

		WebGLRenderTarget.call( this, width, height, options );

		this.depthBuffer = false;
		this.stencilBuffer = false;

		this.numViews = numViews;

	}

	WebGLMultiviewRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), {

		constructor: WebGLMultiviewRenderTarget,

		isWebGLMultiviewRenderTarget: true,

		copy: function ( source ) {

			WebGLRenderTarget.prototype.copy.call( this, source );

			this.numViews = source.numViews;

			return this;

		},

		setNumViews: function ( numViews ) {

			if ( this.numViews !== numViews ) {

				this.numViews = numViews;
				this.dispose();

			}

			return this;

		}

	} );

	/**
	 * @author fernandojsg / http://fernandojsg.com
	 * @author Takahiro https://github.com/takahirox
	 */

	function WebGLMultiview( renderer, gl ) {

		var DEFAULT_NUMVIEWS = 2;

		var extensions = renderer.extensions;
		var properties = renderer.properties;

		var renderTarget, currentRenderTarget;
		var mat3, mat4, cameraArray, renderSize;

		var available;
		var maxNumViews = 0;

		//

		function isAvailable() {

			if ( available === undefined ) {

				var extension = extensions.get( 'OVR_multiview2' );

				available = extension !== null && gl.getContextAttributes().antialias === false;

				if ( available ) {

					maxNumViews = gl.getParameter( extension.MAX_VIEWS_OVR );
					renderTarget = new WebGLMultiviewRenderTarget( 0, 0, DEFAULT_NUMVIEWS );

					renderSize = new Vector2();
					mat4 = [];
					mat3 = [];
					cameraArray = [];

					for ( var i = 0; i < maxNumViews; i ++ ) {

						mat4[ i ] = new Matrix4();
						mat3[ i ] = new Matrix3();

					}

				}

			}

			return available;

		}

		function getCameraArray( camera ) {

			if ( camera.isArrayCamera ) { return camera.cameras; }

			cameraArray[ 0 ] = camera;

			return cameraArray;

		}

		function updateCameraProjectionMatricesUniform( camera, uniforms ) {

			var cameras = getCameraArray( camera );

			for ( var i = 0; i < cameras.length; i ++ ) {

				mat4[ i ].copy( cameras[ i ].projectionMatrix );

			}

			uniforms.setValue( gl, 'projectionMatrices', mat4 );

		}

		function updateCameraViewMatricesUniform( camera, uniforms ) {

			var cameras = getCameraArray( camera );

			for ( var i = 0; i < cameras.length; i ++ ) {

				mat4[ i ].copy( cameras[ i ].matrixWorldInverse );

			}

			uniforms.setValue( gl, 'viewMatrices', mat4 );

		}

		function updateObjectMatricesUniforms( object, camera, uniforms ) {

			var cameras = getCameraArray( camera );

			for ( var i = 0; i < cameras.length; i ++ ) {

				mat4[ i ].multiplyMatrices( cameras[ i ].matrixWorldInverse, object.matrixWorld );
				mat3[ i ].getNormalMatrix( mat4[ i ] );

			}

			uniforms.setValue( gl, 'modelViewMatrices', mat4 );
			uniforms.setValue( gl, 'normalMatrices', mat3 );

		}

		function isMultiviewCompatible( camera ) {

			if ( camera.isArrayCamera === undefined ) { return true; }

			var cameras = camera.cameras;

			if ( cameras.length > maxNumViews ) { return false; }

			for ( var i = 1, il = cameras.length; i < il; i ++ ) {

				if ( cameras[ 0 ].viewport.z !== cameras[ i ].viewport.z ||
					cameras[ 0 ].viewport.w !== cameras[ i ].viewport.w ) { return false; }

			}

			return true;

		}

		function resizeRenderTarget( camera ) {

			if ( currentRenderTarget ) {

				renderSize.set( currentRenderTarget.width, currentRenderTarget.height );

			} else {

				renderer.getDrawingBufferSize( renderSize );

			}

			if ( camera.isArrayCamera ) {

				var viewport = camera.cameras[ 0 ].viewport;

				renderTarget.setSize( viewport.z, viewport.w );
				renderTarget.setNumViews( camera.cameras.length );

			} else {

				renderTarget.setSize( renderSize.x, renderSize.y );
				renderTarget.setNumViews( DEFAULT_NUMVIEWS );

			}

		}

		function attachCamera( camera ) {

			if ( isMultiviewCompatible( camera ) === false ) { return; }

			currentRenderTarget = renderer.getRenderTarget();
			resizeRenderTarget( camera );
			renderer.setRenderTarget( renderTarget );

		}

		function detachCamera( camera ) {

			if ( renderTarget !== renderer.getRenderTarget() ) { return; }

			renderer.setRenderTarget( currentRenderTarget );

			flush( camera );

		}

		function flush( camera ) {

			var srcRenderTarget = renderTarget;
			var numViews = srcRenderTarget.numViews;

			var srcFramebuffers = properties.get( srcRenderTarget ).__webglViewFramebuffers;

			var viewWidth = srcRenderTarget.width;
			var viewHeight = srcRenderTarget.height;

			if ( camera.isArrayCamera ) {

				for ( var i = 0; i < numViews; i ++ ) {

					var viewport = camera.cameras[ i ].viewport;

					var x1 = viewport.x;
					var y1 = viewport.y;
					var x2 = x1 + viewport.z;
					var y2 = y1 + viewport.w;

					gl.bindFramebuffer( 36008, srcFramebuffers[ i ] );
					gl.blitFramebuffer( 0, 0, viewWidth, viewHeight, x1, y1, x2, y2, 16384, 9728 );

				}

			} else {

				gl.bindFramebuffer( 36008, srcFramebuffers[ 0 ] );
				gl.blitFramebuffer( 0, 0, viewWidth, viewHeight, 0, 0, renderSize.x, renderSize.y, 16384, 9728 );

			}

		}

		this.isAvailable = isAvailable;
		this.attachCamera = attachCamera;
		this.detachCamera = detachCamera;
		this.updateCameraProjectionMatricesUniform = updateCameraProjectionMatricesUniform;
		this.updateCameraViewMatricesUniform = updateCameraViewMatricesUniform;
		this.updateObjectMatricesUniforms = updateObjectMatricesUniforms;

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function ArrayCamera( array ) {

		PerspectiveCamera.call( this );

		this.cameras = array || [];

	}

	ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {

		constructor: ArrayCamera,

		isArrayCamera: true

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function Group() {

		Object3D.call( this );

		this.type = 'Group';

	}

	Group.prototype = Object.assign( Object.create( Object3D.prototype ), {

		constructor: Group,

		isGroup: true

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function WebXRManager( renderer, gl ) {

		var scope = this;

		var session = null;

		// var framebufferScaleFactor = 1.0;

		var referenceSpace = null;
		var referenceSpaceType = 'local-floor';

		var pose = null;

		var controllers = [];
		var inputSourcesMap = new Map();

		//

		var cameraL = new PerspectiveCamera();
		cameraL.layers.enable( 1 );
		cameraL.viewport = new Vector4();

		var cameraR = new PerspectiveCamera();
		cameraR.layers.enable( 2 );
		cameraR.viewport = new Vector4();

		var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
		cameraVR.layers.enable( 1 );
		cameraVR.layers.enable( 2 );

		var _currentDepthNear = null;
		var _currentDepthFar = null;

		//

		this.enabled = false;

		this.isPresenting = false;

		this.getController = function ( id ) {

			var controller = controllers[ id ];

			if ( controller === undefined ) {

				controller = {};
				controllers[ id ] = controller;

			}

			if ( controller.targetRay === undefined ) {

				controller.targetRay = new Group();
				controller.targetRay.matrixAutoUpdate = false;
				controller.targetRay.visible = false;

			}

			return controller.targetRay;

		};

		this.getControllerGrip = function ( id ) {

			var controller = controllers[ id ];

			if ( controller === undefined ) {

				controller = {};
				controllers[ id ] = controller;

			}

			if ( controller.grip === undefined ) {

				controller.grip = new Group();
				controller.grip.matrixAutoUpdate = false;
				controller.grip.visible = false;

			}

			return controller.grip;

		};

		//

		function onSessionEvent( event ) {

			var controller = inputSourcesMap.get( event.inputSource );

			if ( controller ) {

				if ( controller.targetRay ) {

					controller.targetRay.dispatchEvent( { type: event.type } );

				}

				if ( controller.grip ) {

					controller.grip.dispatchEvent( { type: event.type } );

				}

			}

		}

		function onSessionEnd() {

			inputSourcesMap.forEach( function ( controller, inputSource ) {

				if ( controller.targetRay ) {

					controller.targetRay.dispatchEvent( { type: 'disconnected', data: inputSource } );
					controller.targetRay.visible = false;

				}

				if ( controller.grip ) {

					controller.grip.dispatchEvent( { type: 'disconnected', data: inputSource } );
					controller.grip.visible = false;

				}

			} );

			inputSourcesMap.clear();

			//

			renderer.setFramebuffer( null );
			renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830
			animation.stop();

			scope.isPresenting = false;

			scope.dispatchEvent( { type: 'sessionend' } );

		}

		function onRequestReferenceSpace( value ) {

			referenceSpace = value;

			animation.setContext( session );
			animation.start();

			scope.isPresenting = true;

			scope.dispatchEvent( { type: 'sessionstart' } );

		}

		this.setFramebufferScaleFactor = function ( /* value */ ) {

			// framebufferScaleFactor = value;

		};

		this.setReferenceSpaceType = function ( value ) {

			referenceSpaceType = value;

		};

		this.getReferenceSpace = function () {

			return referenceSpace;

		};

		this.getSession = function () {

			return session;

		};

		this.setSession = function ( value ) {

			session = value;

			if ( session !== null ) {

				session.addEventListener( 'select', onSessionEvent );
				session.addEventListener( 'selectstart', onSessionEvent );
				session.addEventListener( 'selectend', onSessionEvent );
				session.addEventListener( 'squeeze', onSessionEvent );
				session.addEventListener( 'squeezestart', onSessionEvent );
				session.addEventListener( 'squeezeend', onSessionEvent );
				session.addEventListener( 'end', onSessionEnd );

				var attributes = gl.getContextAttributes();

				var layerInit = {
					antialias: attributes.antialias,
					alpha: attributes.alpha,
					depth: attributes.depth,
					stencil: attributes.stencil
				};

				// eslint-disable-next-line no-undef
				var baseLayer = new XRWebGLLayer( session, gl, layerInit );

				session.updateRenderState( { baseLayer: baseLayer } );

				session.requestReferenceSpace( referenceSpaceType ).then( onRequestReferenceSpace );

				//

				session.addEventListener( 'inputsourceschange', updateInputSources );

			}

		};

		function updateInputSources( event ) {

			var inputSources = session.inputSources;

			// Assign inputSources to available controllers

			for ( var i = 0; i < controllers.length; i ++ ) {

				inputSourcesMap.set( inputSources[ i ], controllers[ i ] );

			}

			// Notify disconnected

			for ( var i = 0; i < event.removed.length; i ++ ) {

				var inputSource = event.removed[ i ];
				var controller = inputSourcesMap.get( inputSource );

				if ( controller ) {

					if ( controller.targetRay ) {

						controller.targetRay.dispatchEvent( { type: 'disconnected', data: inputSource } );

					}

					if ( controller.grip ) {

						controller.grip.dispatchEvent( { type: 'disconnected', data: inputSource } );

					}

					inputSourcesMap.delete( inputSource );

				}

			}

			// Notify connected

			for ( var i = 0; i < event.added.length; i ++ ) {

				var inputSource = event.added[ i ];
				var controller = inputSourcesMap.get( inputSource );

				if ( controller ) {

					if ( controller.targetRay ) {

						controller.targetRay.dispatchEvent( { type: 'connected', data: inputSource } );

					}

					if ( controller.grip ) {

						controller.grip.dispatchEvent( { type: 'connected', data: inputSource } );

					}

				}

			}

		}

		//

		var cameraLPos = new Vector3();
		var cameraRPos = new Vector3();

		/**
		 * @author jsantell / https://www.jsantell.com/
		 *
		 * Assumes 2 cameras that are parallel and share an X-axis, and that
		 * the cameras' projection and world matrices have already been set.
		 * And that near and far planes are identical for both cameras.
		 * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
		 */
		function setProjectionFromUnion( camera, cameraL, cameraR ) {

			cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
			cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );

			var ipd = cameraLPos.distanceTo( cameraRPos );

			var projL = cameraL.projectionMatrix.elements;
			var projR = cameraR.projectionMatrix.elements;

			// VR systems will have identical far and near planes, and
			// most likely identical top and bottom frustum extents.
			// Use the left camera for these values.
			var near = projL[ 14 ] / ( projL[ 10 ] - 1 );
			var far = projL[ 14 ] / ( projL[ 10 ] + 1 );
			var topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
			var bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];

			var leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
			var rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
			var left = near * leftFov;
			var right = near * rightFov;

			// Calculate the new camera's position offset from the
			// left camera. xOffset should be roughly half `ipd`.
			var zOffset = ipd / ( - leftFov + rightFov );
			var xOffset = zOffset * - leftFov;

			// TODO: Better way to apply this offset?
			cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
			camera.translateX( xOffset );
			camera.translateZ( zOffset );
			camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
			camera.matrixWorldInverse.getInverse( camera.matrixWorld );

			// Find the union of the frustum values of the cameras and scale
			// the values so that the near plane's position does not change in world space,
			// although must now be relative to the new union camera.
			var near2 = near + zOffset;
			var far2 = far + zOffset;
			var left2 = left - xOffset;
			var right2 = right + ( ipd - xOffset );
			var top2 = topFov * far / far2 * near2;
			var bottom2 = bottomFov * far / far2 * near2;

			camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );

		}

		function updateCamera( camera, parent ) {

			if ( parent === null ) {

				camera.matrixWorld.copy( camera.matrix );

			} else {

				camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );

			}

			camera.matrixWorldInverse.getInverse( camera.matrixWorld );

		}

		this.getCamera = function ( camera ) {

			cameraVR.near = cameraR.near = cameraL.near = camera.near;
			cameraVR.far = cameraR.far = cameraL.far = camera.far;

			if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {

				// Note that the new renderState won't apply until the next frame. See #18320

				session.updateRenderState( {
					depthNear: cameraVR.near,
					depthFar: cameraVR.far
				} );

				_currentDepthNear = cameraVR.near;
				_currentDepthFar = cameraVR.far;

			}

			var parent = camera.parent;
			var cameras = cameraVR.cameras;

			updateCamera( cameraVR, parent );

			for ( var i = 0; i < cameras.length; i ++ ) {

				updateCamera( cameras[ i ], parent );

			}

			// update camera and its children

			camera.matrixWorld.copy( cameraVR.matrixWorld );

			var children = camera.children;

			for ( var i = 0, l = children.length; i < l; i ++ ) {

				children[ i ].updateMatrixWorld( true );

			}

			setProjectionFromUnion( cameraVR, cameraL, cameraR );

			return cameraVR;

		};

		// Animation Loop

		var onAnimationFrameCallback = null;

		function onAnimationFrame( time, frame ) {

			pose = frame.getViewerPose( referenceSpace );

			if ( pose !== null ) {

				var views = pose.views;
				var baseLayer = session.renderState.baseLayer;

				renderer.setFramebuffer( baseLayer.framebuffer );

				for ( var i = 0; i < views.length; i ++ ) {

					var view = views[ i ];
					var viewport = baseLayer.getViewport( view );

					var camera = cameraVR.cameras[ i ];
					camera.matrix.fromArray( view.transform.matrix );
					camera.projectionMatrix.fromArray( view.projectionMatrix );
					camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );

					if ( i === 0 ) {

						cameraVR.matrix.copy( camera.matrix );

					}

				}

			}

			//

			var inputSources = session.inputSources;

			for ( var i = 0; i < controllers.length; i ++ ) {

				var controller = controllers[ i ];

				var inputSource = inputSources[ i ];

				var inputPose = null;
				var gripPose = null;

				if ( inputSource ) {

					if ( controller.targetRay ) {

						inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );

						if ( inputPose !== null ) {

							controller.targetRay.matrix.fromArray( inputPose.transform.matrix );
							controller.targetRay.matrix.decompose( controller.targetRay.position, controller.targetRay.rotation, controller.targetRay.scale );

						}

					}

					if ( controller.grip && inputSource.gripSpace ) {

						gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );

						if ( gripPose !== null ) {

							controller.grip.matrix.fromArray( gripPose.transform.matrix );
							controller.grip.matrix.decompose( controller.grip.position, controller.grip.rotation, controller.grip.scale );

						}

					}

				}

				if ( controller.targetRay ) {

					controller.targetRay.visible = inputPose !== null;

				}

				if ( controller.grip ) {

					controller.grip.visible = gripPose !== null;

				}

			}

			if ( onAnimationFrameCallback ) { onAnimationFrameCallback( time, frame ); }

		}

		var animation = new WebGLAnimation();
		animation.setAnimationLoop( onAnimationFrame );

		this.setAnimationLoop = function ( callback ) {

			onAnimationFrameCallback = callback;

		};

		this.dispose = function () {};

	}

	Object.assign( WebXRManager.prototype, EventDispatcher.prototype );

	/**
	 * @author supereggbert / http://www.paulbrunt.co.uk/
	 * @author mrdoob / http://mrdoob.com/
	 * @author alteredq / http://alteredqualia.com/
	 * @author szimek / https://github.com/szimek/
	 * @author tschw
	 */

	function WebGLRenderer( parameters ) {

		parameters = parameters || {};

		var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
			_context = parameters.context !== undefined ? parameters.context : null,

			_alpha = parameters.alpha !== undefined ? parameters.alpha : false,
			_depth = parameters.depth !== undefined ? parameters.depth : true,
			_stencil = parameters.stencil !== undefined ? parameters.stencil : true,
			_antialias = parameters.antialias !== undefined ? parameters.antialias : false,
			_premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
			_preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
			_powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
			_failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;

		var currentRenderList = null;
		var currentRenderState = null;

		// public properties

		this.domElement = _canvas;

		// Debug configuration container
		this.debug = {

			/**
			 * Enables error checking and reporting when shader programs are being compiled
			 * @type {boolean}
			 */
			checkShaderErrors: true
		};

		// clearing

		this.autoClear = true;
		this.autoClearColor = true;
		this.autoClearDepth = true;
		this.autoClearStencil = true;

		// scene graph

		this.sortObjects = true;

		// user-defined clipping

		this.clippingPlanes = [];
		this.localClippingEnabled = false;

		// physically based shading

		this.gammaFactor = 2.0;	// for backwards compatibility
		this.outputEncoding = LinearEncoding;

		// physical lights

		this.physicallyCorrectLights = false;

		// tone mapping

		this.toneMapping = LinearToneMapping;
		this.toneMappingExposure = 1.0;
		this.toneMappingWhitePoint = 1.0;

		// morphs

		this.maxMorphTargets = 8;
		this.maxMorphNormals = 4;

		// internal properties

		var _this = this,

			_isContextLost = false,

			// internal state cache

			_framebuffer = null,

			_currentActiveCubeFace = 0,
			_currentActiveMipmapLevel = 0,
			_currentRenderTarget = null,
			_currentFramebuffer = null,
			_currentMaterialId = - 1,

			// geometry and program caching

			_currentGeometryProgram = {
				geometry: null,
				program: null,
				wireframe: false
			},

			_currentCamera = null,
			_currentArrayCamera = null,

			_currentViewport = new Vector4(),
			_currentScissor = new Vector4(),
			_currentScissorTest = null,

			//

			_width = _canvas.width,
			_height = _canvas.height,

			_pixelRatio = 1,
			_opaqueSort = null,
			_transparentSort = null,

			_viewport = new Vector4( 0, 0, _width, _height ),
			_scissor = new Vector4( 0, 0, _width, _height ),
			_scissorTest = false,

			// frustum

			_frustum = new Frustum(),

			// clipping

			_clipping = new WebGLClipping(),
			_clippingEnabled = false,
			_localClippingEnabled = false,

			// camera matrices cache

			_projScreenMatrix = new Matrix4(),

			_vector3 = new Vector3();

		function getTargetPixelRatio() {

			return _currentRenderTarget === null ? _pixelRatio : 1;

		}

		// initialize

		var _gl;

		try {

			var contextAttributes = {
				alpha: _alpha,
				depth: _depth,
				stencil: _stencil,
				antialias: _antialias,
				premultipliedAlpha: _premultipliedAlpha,
				preserveDrawingBuffer: _preserveDrawingBuffer,
				powerPreference: _powerPreference,
				failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,
				xrCompatible: true
			};

			// event listeners must be registered before WebGL context is created, see #12753

			_canvas.addEventListener( 'webglcontextlost', onContextLost, false );
			_canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );

			_gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );

			if ( _gl === null ) {

				if ( _canvas.getContext( 'webgl' ) !== null ) {

					throw new Error( 'Error creating WebGL context with your selected attributes.' );

				} else {

					throw new Error( 'Error creating WebGL context.' );

				}

			}

			// Some experimental-webgl implementations do not have getShaderPrecisionFormat

			if ( _gl.getShaderPrecisionFormat === undefined ) {

				_gl.getShaderPrecisionFormat = function () {

					return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };

				};

			}

		} catch ( error ) {

			console.error( 'THREE.WebGLRenderer: ' + error.message );
			throw error;

		}

		var extensions, capabilities, state, info;
		var properties, textures, attributes, geometries, objects;
		var programCache, renderLists, renderStates;

		var background, morphtargets, bufferRenderer, indexedBufferRenderer;

		var utils;

		function initGLContext() {

			extensions = new WebGLExtensions( _gl );

			capabilities = new WebGLCapabilities( _gl, extensions, parameters );

			if ( capabilities.isWebGL2 === false ) {

				extensions.get( 'WEBGL_depth_texture' );
				extensions.get( 'OES_texture_float' );
				extensions.get( 'OES_texture_half_float' );
				extensions.get( 'OES_texture_half_float_linear' );
				extensions.get( 'OES_standard_derivatives' );
				extensions.get( 'OES_element_index_uint' );
				extensions.get( 'ANGLE_instanced_arrays' );

			}

			extensions.get( 'OES_texture_float_linear' );

			utils = new WebGLUtils( _gl, extensions, capabilities );

			state = new WebGLState( _gl, extensions, capabilities );
			state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
			state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );

			info = new WebGLInfo( _gl );
			properties = new WebGLProperties();
			textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
			attributes = new WebGLAttributes( _gl, capabilities );
			geometries = new WebGLGeometries( _gl, attributes, info );
			objects = new WebGLObjects( _gl, geometries, attributes, info );
			morphtargets = new WebGLMorphtargets( _gl );
			programCache = new WebGLPrograms( _this, extensions, capabilities );
			renderLists = new WebGLRenderLists();
			renderStates = new WebGLRenderStates();

			background = new WebGLBackground( _this, state, objects, _premultipliedAlpha );

			bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
			indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );

			info.programs = programCache.programs;

			_this.capabilities = capabilities;
			_this.extensions = extensions;
			_this.properties = properties;
			_this.renderLists = renderLists;
			_this.state = state;
			_this.info = info;

		}

		initGLContext();

		// xr

		var xr = new WebXRManager( _this, _gl );

		this.xr = xr;

		// Multiview

		var multiview = new WebGLMultiview( _this, _gl );

		// shadow map

		var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );

		this.shadowMap = shadowMap;

		// API

		this.getContext = function () {

			return _gl;

		};

		this.getContextAttributes = function () {

			return _gl.getContextAttributes();

		};

		this.forceContextLoss = function () {

			var extension = extensions.get( 'WEBGL_lose_context' );
			if ( extension ) { extension.loseContext(); }

		};

		this.forceContextRestore = function () {

			var extension = extensions.get( 'WEBGL_lose_context' );
			if ( extension ) { extension.restoreContext(); }

		};

		this.getPixelRatio = function () {

			return _pixelRatio;

		};

		this.setPixelRatio = function ( value ) {

			if ( value === undefined ) { return; }

			_pixelRatio = value;

			this.setSize( _width, _height, false );

		};

		this.getSize = function ( target ) {

			if ( target === undefined ) {

				console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );

				target = new Vector2();

			}

			return target.set( _width, _height );

		};

		this.setSize = function ( width, height, updateStyle ) {

			if ( xr.isPresenting ) {

				console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
				return;

			}

			_width = width;
			_height = height;

			_canvas.width = Math.floor( width * _pixelRatio );
			_canvas.height = Math.floor( height * _pixelRatio );

			if ( updateStyle !== false ) {

				_canvas.style.width = width + 'px';
				_canvas.style.height = height + 'px';

			}

			this.setViewport( 0, 0, width, height );

		};

		this.getDrawingBufferSize = function ( target ) {

			if ( target === undefined ) {

				console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );

				target = new Vector2();

			}

			return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();

		};

		this.setDrawingBufferSize = function ( width, height, pixelRatio ) {

			_width = width;
			_height = height;

			_pixelRatio = pixelRatio;

			_canvas.width = Math.floor( width * pixelRatio );
			_canvas.height = Math.floor( height * pixelRatio );

			this.setViewport( 0, 0, width, height );

		};

		this.getCurrentViewport = function ( target ) {

			if ( target === undefined ) {

				console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );

				target = new Vector4();

			}

			return target.copy( _currentViewport );

		};

		this.getViewport = function ( target ) {

			return target.copy( _viewport );

		};

		this.setViewport = function ( x, y, width, height ) {

			if ( x.isVector4 ) {

				_viewport.set( x.x, x.y, x.z, x.w );

			} else {

				_viewport.set( x, y, width, height );

			}

			state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );

		};

		this.getScissor = function ( target ) {

			return target.copy( _scissor );

		};

		this.setScissor = function ( x, y, width, height ) {

			if ( x.isVector4 ) {

				_scissor.set( x.x, x.y, x.z, x.w );

			} else {

				_scissor.set( x, y, width, height );

			}

			state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );

		};

		this.getScissorTest = function () {

			return _scissorTest;

		};

		this.setScissorTest = function ( boolean ) {

			state.setScissorTest( _scissorTest = boolean );

		};

		this.setOpaqueSort = function ( method ) {

			_opaqueSort = method;

		};

		this.setTransparentSort = function ( method ) {

			_transparentSort = method;

		};

		// Clearing

		this.getClearColor = function () {

			return background.getClearColor();

		};

		this.setClearColor = function () {

			background.setClearColor.apply( background, arguments );

		};

		this.getClearAlpha = function () {

			return background.getClearAlpha();

		};

		this.setClearAlpha = function () {

			background.setClearAlpha.apply( background, arguments );

		};

		this.clear = function ( color, depth, stencil ) {

			var bits = 0;

			if ( color === undefined || color ) { bits |= 16384; }
			if ( depth === undefined || depth ) { bits |= 256; }
			if ( stencil === undefined || stencil ) { bits |= 1024; }

			_gl.clear( bits );

		};

		this.clearColor = function () {

			this.clear( true, false, false );

		};

		this.clearDepth = function () {

			this.clear( false, true, false );

		};

		this.clearStencil = function () {

			this.clear( false, false, true );

		};

		//

		this.dispose = function () {

			_canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
			_canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );

			renderLists.dispose();
			renderStates.dispose();
			properties.dispose();
			objects.dispose();

			xr.dispose();

			animation.stop();

		};

		// Events

		function onContextLost( event ) {

			event.preventDefault();

			console.log( 'THREE.WebGLRenderer: Context Lost.' );

			_isContextLost = true;

		}

		function onContextRestore( /* event */ ) {

			console.log( 'THREE.WebGLRenderer: Context Restored.' );

			_isContextLost = false;

			initGLContext();

		}

		function onMaterialDispose( event ) {

			var material = event.target;

			material.removeEventListener( 'dispose', onMaterialDispose );

			deallocateMaterial( material );

		}

		// Buffer deallocation

		function deallocateMaterial( material ) {

			releaseMaterialProgramReference( material );

			properties.remove( material );

		}


		function releaseMaterialProgramReference( material ) {

			var programInfo = properties.get( material ).program;

			material.program = undefined;

			if ( programInfo !== undefined ) {

				programCache.releaseProgram( programInfo );

			}

		}

		// Buffer rendering

		function renderObjectImmediate( object, program ) {

			object.render( function ( object ) {

				_this.renderBufferImmediate( object, program );

			} );

		}

		this.renderBufferImmediate = function ( object, program ) {

			state.initAttributes();

			var buffers = properties.get( object );

			if ( object.hasPositions && ! buffers.position ) { buffers.position = _gl.createBuffer(); }
			if ( object.hasNormals && ! buffers.normal ) { buffers.normal = _gl.createBuffer(); }
			if ( object.hasUvs && ! buffers.uv ) { buffers.uv = _gl.createBuffer(); }
			if ( object.hasColors && ! buffers.color ) { buffers.color = _gl.createBuffer(); }

			var programAttributes = program.getAttributes();

			if ( object.hasPositions ) {

				_gl.bindBuffer( 34962, buffers.position );
				_gl.bufferData( 34962, object.positionArray, 35048 );

				state.enableAttribute( programAttributes.position );
				_gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 );

			}

			if ( object.hasNormals ) {

				_gl.bindBuffer( 34962, buffers.normal );
				_gl.bufferData( 34962, object.normalArray, 35048 );

				state.enableAttribute( programAttributes.normal );
				_gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 );

			}

			if ( object.hasUvs ) {

				_gl.bindBuffer( 34962, buffers.uv );
				_gl.bufferData( 34962, object.uvArray, 35048 );

				state.enableAttribute( programAttributes.uv );
				_gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 );

			}

			if ( object.hasColors ) {

				_gl.bindBuffer( 34962, buffers.color );
				_gl.bufferData( 34962, object.colorArray, 35048 );

				state.enableAttribute( programAttributes.color );
				_gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 );

			}

			state.disableUnusedAttributes();

			_gl.drawArrays( 4, 0, object.count );

			object.count = 0;

		};

		var tempScene = new Scene();

		this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {

			if ( scene === null ) { scene = tempScene; } // renderBufferDirect second parameter used to be fog (could be null)

			var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );

			var program = setProgram( camera, scene, material, object );

			state.setMaterial( material, frontFaceCW );

			var updateBuffers = false;

			if ( _currentGeometryProgram.geometry !== geometry.id ||
				_currentGeometryProgram.program !== program.id ||
				_currentGeometryProgram.wireframe !== ( material.wireframe === true ) ) {

				_currentGeometryProgram.geometry = geometry.id;
				_currentGeometryProgram.program = program.id;
				_currentGeometryProgram.wireframe = material.wireframe === true;
				updateBuffers = true;

			}

			if ( material.morphTargets || material.morphNormals ) {

				morphtargets.update( object, geometry, material, program );

				updateBuffers = true;

			}

			//

			var index = geometry.index;
			var position = geometry.attributes.position;

			//

			if ( index === null ) {

				if ( position === undefined || position.count === 0 ) { return; }

			} else if ( index.count === 0 ) {

				return;

			}

			//

			var rangeFactor = 1;

			if ( material.wireframe === true ) {

				index = geometries.getWireframeAttribute( geometry );
				rangeFactor = 2;

			}

			var attribute;
			var renderer = bufferRenderer;

			if ( index !== null ) {

				attribute = attributes.get( index );

				renderer = indexedBufferRenderer;
				renderer.setIndex( attribute );

			}

			if ( updateBuffers ) {

				setupVertexAttributes( object, geometry, material, program );

				if ( index !== null ) {

					_gl.bindBuffer( 34963, attribute.buffer );

				}

			}

			//

			var dataCount = ( index !== null ) ? index.count : position.count;

			var rangeStart = geometry.drawRange.start * rangeFactor;
			var rangeCount = geometry.drawRange.count * rangeFactor;

			var groupStart = group !== null ? group.start * rangeFactor : 0;
			var groupCount = group !== null ? group.count * rangeFactor : Infinity;

			var drawStart = Math.max( rangeStart, groupStart );
			var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;

			var drawCount = Math.max( 0, drawEnd - drawStart + 1 );

			if ( drawCount === 0 ) { return; }

			//

			if ( object.isMesh ) {

				if ( material.wireframe === true ) {

					state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
					renderer.setMode( 1 );

				} else {

					renderer.setMode( 4 );

				}

			} else if ( object.isLine ) {

				var lineWidth = material.linewidth;

				if ( lineWidth === undefined ) { lineWidth = 1; } // Not using Line*Material

				state.setLineWidth( lineWidth * getTargetPixelRatio() );

				if ( object.isLineSegments ) {

					renderer.setMode( 1 );

				} else if ( object.isLineLoop ) {

					renderer.setMode( 2 );

				} else {

					renderer.setMode( 3 );

				}

			} else if ( object.isPoints ) {

				renderer.setMode( 0 );

			} else if ( object.isSprite ) {

				renderer.setMode( 4 );

			}

			if ( object.isInstancedMesh ) {

				renderer.renderInstances( geometry, drawStart, drawCount, object.count );

			} else if ( geometry.isInstancedBufferGeometry ) {

				renderer.renderInstances( geometry, drawStart, drawCount, geometry.maxInstancedCount );

			} else {

				renderer.render( drawStart, drawCount );

			}

		};

		function setupVertexAttributes( object, geometry, material, program ) {

			if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {

				if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) { return; }

			}

			state.initAttributes();

			var geometryAttributes = geometry.attributes;

			var programAttributes = program.getAttributes();

			var materialDefaultAttributeValues = material.defaultAttributeValues;

			for ( var name in programAttributes ) {

				var programAttribute = programAttributes[ name ];

				if ( programAttribute >= 0 ) {

					var geometryAttribute = geometryAttributes[ name ];

					if ( geometryAttribute !== undefined ) {

						var normalized = geometryAttribute.normalized;
						var size = geometryAttribute.itemSize;

						var attribute = attributes.get( geometryAttribute );

						// TODO Attribute may not be available on context restore

						if ( attribute === undefined ) { continue; }

						var buffer = attribute.buffer;
						var type = attribute.type;
						var bytesPerElement = attribute.bytesPerElement;

						if ( geometryAttribute.isInterleavedBufferAttribute ) {

							var data = geometryAttribute.data;
							var stride = data.stride;
							var offset = geometryAttribute.offset;

							if ( data && data.isInstancedInterleavedBuffer ) {

								state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );

								if ( geometry.maxInstancedCount === undefined ) {

									geometry.maxInstancedCount = data.meshPerAttribute * data.count;

								}

							} else {

								state.enableAttribute( programAttribute );

							}

							_gl.bindBuffer( 34962, buffer );
							_gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );

						} else {

							if ( geometryAttribute.isInstancedBufferAttribute ) {

								state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );

								if ( geometry.maxInstancedCount === undefined ) {

									geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;

								}

							} else {

								state.enableAttribute( programAttribute );

							}

							_gl.bindBuffer( 34962, buffer );
							_gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );

						}

					} else if ( name === 'instanceMatrix' ) {

						var attribute = attributes.get( object.instanceMatrix );

						// TODO Attribute may not be available on context restore

						if ( attribute === undefined ) { continue; }

						var buffer = attribute.buffer;
						var type = attribute.type;

						state.enableAttributeAndDivisor( programAttribute + 0, 1 );
						state.enableAttributeAndDivisor( programAttribute + 1, 1 );
						state.enableAttributeAndDivisor( programAttribute + 2, 1 );
						state.enableAttributeAndDivisor( programAttribute + 3, 1 );

						_gl.bindBuffer( 34962, buffer );

						_gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 );
						_gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 );
						_gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 );
						_gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 );

					} else if ( materialDefaultAttributeValues !== undefined ) {

						var value = materialDefaultAttributeValues[ name ];

						if ( value !== undefined ) {

							switch ( value.length ) {

								case 2:
									_gl.vertexAttrib2fv( programAttribute, value );
									break;

								case 3:
									_gl.vertexAttrib3fv( programAttribute, value );
									break;

								case 4:
									_gl.vertexAttrib4fv( programAttribute, value );
									break;

								default:
									_gl.vertexAttrib1fv( programAttribute, value );

							}

						}

					}

				}

			}

			state.disableUnusedAttributes();

		}

		// Compile

		this.compile = function ( scene, camera ) {

			currentRenderState = renderStates.get( scene, camera );
			currentRenderState.init();

			scene.traverse( function ( object ) {

				if ( object.isLight ) {

					currentRenderState.pushLight( object );

					if ( object.castShadow ) {

						currentRenderState.pushShadow( object );

					}

				}

			} );

			currentRenderState.setupLights( camera );

			var compiled = {};

			scene.traverse( function ( object ) {

				if ( object.material ) {

					if ( Array.isArray( object.material ) ) {

						for ( var i = 0; i < object.material.length; i ++ ) {

							if ( object.material[ i ].uuid in compiled === false ) {

								initMaterial( object.material[ i ], scene, object );
								compiled[ object.material[ i ].uuid ] = true;

							}

						}

					} else if ( object.material.uuid in compiled === false ) {

						initMaterial( object.material, scene, object );
						compiled[ object.material.uuid ] = true;

					}

				}

			} );

		};

		// Animation Loop

		var onAnimationFrameCallback = null;

		function onAnimationFrame( time ) {

			if ( xr.isPresenting ) { return; }
			if ( onAnimationFrameCallback ) { onAnimationFrameCallback( time ); }

		}

		var animation = new WebGLAnimation();
		animation.setAnimationLoop( onAnimationFrame );

		if ( typeof window !== 'undefined' ) { animation.setContext( window ); }

		this.setAnimationLoop = function ( callback ) {

			onAnimationFrameCallback = callback;
			xr.setAnimationLoop( callback );

			animation.start();

		};

		// Rendering

		this.render = function ( scene, camera ) {

			var renderTarget, forceClear;

			if ( arguments[ 2 ] !== undefined ) {

				console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
				renderTarget = arguments[ 2 ];

			}

			if ( arguments[ 3 ] !== undefined ) {

				console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
				forceClear = arguments[ 3 ];

			}

			if ( ! ( camera && camera.isCamera ) ) {

				console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
				return;

			}

			if ( _isContextLost ) { return; }

			// reset caching for this frame

			_currentGeometryProgram.geometry = null;
			_currentGeometryProgram.program = null;
			_currentGeometryProgram.wireframe = false;
			_currentMaterialId = - 1;
			_currentCamera = null;

			// update scene graph

			if ( scene.autoUpdate === true ) { scene.updateMatrixWorld(); }

			// update camera matrices and frustum

			if ( camera.parent === null ) { camera.updateMatrixWorld(); }

			if ( xr.enabled && xr.isPresenting ) {

				camera = xr.getCamera( camera );

			}

			//

			currentRenderState = renderStates.get( scene, camera );
			currentRenderState.init();

			scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget );

			_projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
			_frustum.setFromProjectionMatrix( _projScreenMatrix );

			_localClippingEnabled = this.localClippingEnabled;
			_clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );

			currentRenderList = renderLists.get( scene, camera );
			currentRenderList.init();

			projectObject( scene, camera, 0, _this.sortObjects );

			if ( _this.sortObjects === true ) {

				currentRenderList.sort( _opaqueSort, _transparentSort );

			}

			//

			if ( _clippingEnabled ) { _clipping.beginShadows(); }

			var shadowsArray = currentRenderState.state.shadowsArray;

			shadowMap.render( shadowsArray, scene, camera );

			currentRenderState.setupLights( camera );

			if ( _clippingEnabled ) { _clipping.endShadows(); }

			//

			if ( this.info.autoReset ) { this.info.reset(); }

			if ( renderTarget !== undefined ) {

				this.setRenderTarget( renderTarget );

			}

			if ( xr.enabled && multiview.isAvailable() ) {

				multiview.attachCamera( camera );

			}

			//

			background.render( currentRenderList, scene, camera, forceClear );

			// render scene

			var opaqueObjects = currentRenderList.opaque;
			var transparentObjects = currentRenderList.transparent;

			if ( scene.overrideMaterial ) {

				var overrideMaterial = scene.overrideMaterial;

				if ( opaqueObjects.length ) { renderObjects( opaqueObjects, scene, camera, overrideMaterial ); }
				if ( transparentObjects.length ) { renderObjects( transparentObjects, scene, camera, overrideMaterial ); }

			} else {

				// opaque pass (front-to-back order)

				if ( opaqueObjects.length ) { renderObjects( opaqueObjects, scene, camera ); }

				// transparent pass (back-to-front order)

				if ( transparentObjects.length ) { renderObjects( transparentObjects, scene, camera ); }

			}

			//

			scene.onAfterRender( _this, scene, camera );

			//

			if ( _currentRenderTarget !== null ) {

				// Generate mipmap if we're using any kind of mipmap filtering

				textures.updateRenderTargetMipmap( _currentRenderTarget );

				// resolve multisample renderbuffers to a single-sample texture if necessary

				textures.updateMultisampleRenderTarget( _currentRenderTarget );

			}

			// Ensure depth buffer writing is enabled so it can be cleared on next render

			state.buffers.depth.setTest( true );
			state.buffers.depth.setMask( true );
			state.buffers.color.setMask( true );

			state.setPolygonOffset( false );

			if ( xr.enabled ) {

				if ( multiview.isAvailable() ) {

					multiview.detachCamera( camera );

				}

			}

			// _gl.finish();

			currentRenderList = null;
			currentRenderState = null;

		};

		function projectObject( object, camera, groupOrder, sortObjects ) {

			if ( object.visible === false ) { return; }

			var visible = object.layers.test( camera.layers );

			if ( visible ) {

				if ( object.isGroup ) {

					groupOrder = object.renderOrder;

				} else if ( object.isLOD ) {

					if ( object.autoUpdate === true ) { object.update( camera ); }

				} else if ( object.isLight ) {

					currentRenderState.pushLight( object );

					if ( object.castShadow ) {

						currentRenderState.pushShadow( object );

					}

				} else if ( object.isSprite ) {

					if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {

						if ( sortObjects ) {

							_vector3.setFromMatrixPosition( object.matrixWorld )
								.applyMatrix4( _projScreenMatrix );

						}

						var geometry = objects.update( object );
						var material = object.material;

						if ( material.visible ) {

							currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );

						}

					}

				} else if ( object.isImmediateRenderObject ) {

					if ( sortObjects ) {

						_vector3.setFromMatrixPosition( object.matrixWorld )
							.applyMatrix4( _projScreenMatrix );

					}

					currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );

				} else if ( object.isMesh || object.isLine || object.isPoints ) {

					if ( object.isSkinnedMesh ) {

						// update skeleton only once in a frame

						if ( object.skeleton.frame !== info.render.frame ) {

							object.skeleton.update();
							object.skeleton.frame = info.render.frame;

						}

					}

					if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {

						if ( sortObjects ) {

							_vector3.setFromMatrixPosition( object.matrixWorld )
								.applyMatrix4( _projScreenMatrix );

						}

						var geometry = objects.update( object );
						var material = object.material;

						if ( Array.isArray( material ) ) {

							var groups = geometry.groups;

							for ( var i = 0, l = groups.length; i < l; i ++ ) {

								var group = groups[ i ];
								var groupMaterial = material[ group.materialIndex ];

								if ( groupMaterial && groupMaterial.visible ) {

									currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );

								}

							}

						} else if ( material.visible ) {

							currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );

						}

					}

				}

			}

			var children = object.children;

			for ( var i = 0, l = children.length; i < l; i ++ ) {

				projectObject( children[ i ], camera, groupOrder, sortObjects );

			}

		}

		function renderObjects( renderList, scene, camera, overrideMaterial ) {

			for ( var i = 0, l = renderList.length; i < l; i ++ ) {

				var renderItem = renderList[ i ];

				var object = renderItem.object;
				var geometry = renderItem.geometry;
				var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
				var group = renderItem.group;

				if ( camera.isArrayCamera ) {

					_currentArrayCamera = camera;

					if ( xr.enabled && multiview.isAvailable() ) {

						renderObject( object, scene, camera, geometry, material, group );

					} else {

						var cameras = camera.cameras;

						for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {

							var camera2 = cameras[ j ];

							if ( object.layers.test( camera2.layers ) ) {

								state.viewport( _currentViewport.copy( camera2.viewport ) );

								currentRenderState.setupLights( camera2 );

								renderObject( object, scene, camera2, geometry, material, group );

							}

						}

					}

				} else {

					_currentArrayCamera = null;

					renderObject( object, scene, camera, geometry, material, group );

				}

			}

		}

		function renderObject( object, scene, camera, geometry, material, group ) {

			object.onBeforeRender( _this, scene, camera, geometry, material, group );
			currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );

			object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
			object.normalMatrix.getNormalMatrix( object.modelViewMatrix );

			if ( object.isImmediateRenderObject ) {

				var program = setProgram( camera, scene, material, object );

				state.setMaterial( material );

				_currentGeometryProgram.geometry = null;
				_currentGeometryProgram.program = null;
				_currentGeometryProgram.wireframe = false;

				renderObjectImmediate( object, program );

			} else {

				_this.renderBufferDirect( camera, scene, geometry, material, object, group );

			}

			object.onAfterRender( _this, scene, camera, geometry, material, group );
			currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );

		}

		function initMaterial( material, scene, object ) {

			var materialProperties = properties.get( material );

			var lights = currentRenderState.state.lights;
			var shadowsArray = currentRenderState.state.shadowsArray;

			var lightsStateVersion = lights.state.version;

			var parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, _clipping.numPlanes, _clipping.numIntersection, object );
			var programCacheKey = programCache.getProgramCacheKey( parameters );

			var program = materialProperties.program;
			var programChange = true;

			if ( program === undefined ) {

				// new material
				material.addEventListener( 'dispose', onMaterialDispose );

			} else if ( program.cacheKey !== programCacheKey ) {

				// changed glsl or parameters
				releaseMaterialProgramReference( material );

			} else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) {

				materialProperties.lightsStateVersion = lightsStateVersion;

				programChange = false;

			} else if ( parameters.shaderID !== undefined ) {

				// same glsl and uniform list
				return;

			} else {

				// only rebuild uniform list
				programChange = false;

			}

			if ( programChange ) {

				program = programCache.acquireProgram( parameters, programCacheKey );

				materialProperties.program = program;
				materialProperties.uniforms = parameters.uniforms;
				materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
				materialProperties.outputEncoding = _this.outputEncoding;
				material.program = program;

			}

			var programAttributes = program.getAttributes();

			if ( material.morphTargets ) {

				material.numSupportedMorphTargets = 0;

				for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {

					if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {

						material.numSupportedMorphTargets ++;

					}

				}

			}

			if ( material.morphNormals ) {

				material.numSupportedMorphNormals = 0;

				for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {

					if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {

						material.numSupportedMorphNormals ++;

					}

				}

			}

			var uniforms = materialProperties.uniforms;

			if ( ! material.isShaderMaterial &&
				! material.isRawShaderMaterial ||
				material.clipping === true ) {

				materialProperties.numClippingPlanes = _clipping.numPlanes;
				materialProperties.numIntersection = _clipping.numIntersection;
				uniforms.clippingPlanes = _clipping.uniform;

			}

			materialProperties.fog = scene.fog;

			// store the light setup it was created for

			materialProperties.needsLights = materialNeedsLights( material );
			materialProperties.lightsStateVersion = lightsStateVersion;

			if ( materialProperties.needsLights ) {

				// wire up the material to this renderer's lighting state

				uniforms.ambientLightColor.value = lights.state.ambient;
				uniforms.lightProbe.value = lights.state.probe;
				uniforms.directionalLights.value = lights.state.directional;
				uniforms.spotLights.value = lights.state.spot;
				uniforms.rectAreaLights.value = lights.state.rectArea;
				uniforms.pointLights.value = lights.state.point;
				uniforms.hemisphereLights.value = lights.state.hemi;

				uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
				uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
				uniforms.spotShadowMap.value = lights.state.spotShadowMap;
				uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
				uniforms.pointShadowMap.value = lights.state.pointShadowMap;
				uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
				// TODO (abelnation): add area lights shadow info to uniforms

			}

			var progUniforms = materialProperties.program.getUniforms(),
				uniformsList =
					WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );

			materialProperties.uniformsList = uniformsList;

		}

		function setProgram( camera, scene, material, object ) {

			textures.resetTextureUnits();

			var fog = scene.fog;
			var environment = material.isMeshStandardMaterial ? scene.environment : null;

			var materialProperties = properties.get( material );
			var lights = currentRenderState.state.lights;

			if ( _clippingEnabled ) {

				if ( _localClippingEnabled || camera !== _currentCamera ) {

					var useCache =
						camera === _currentCamera &&
						material.id === _currentMaterialId;

					// we might want to call this function with some ClippingGroup
					// object instead of the material, once it becomes feasible
					// (#8465, #8379)
					_clipping.setState(
						material.clippingPlanes, material.clipIntersection, material.clipShadows,
						camera, materialProperties, useCache );

				}

			}

			if ( material.version === materialProperties.__version ) {

				if ( materialProperties.program === undefined ) {

					initMaterial( material, scene, object );

				} else if ( material.fog && materialProperties.fog !== fog ) {

					initMaterial( material, scene, object );

				} else if ( materialProperties.environment !== environment ) {

					initMaterial( material, scene, object );

				} else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {

					initMaterial( material, scene, object );

				} else if ( materialProperties.numClippingPlanes !== undefined &&
					( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
					materialProperties.numIntersection !== _clipping.numIntersection ) ) {

					initMaterial( material, scene, object );

				} else if ( materialProperties.outputEncoding !== _this.outputEncoding ) {

					initMaterial( material, scene, object );

				}

			} else {

				initMaterial( material, scene, object );
				materialProperties.__version = material.version;

			}

			var refreshProgram = false;
			var refreshMaterial = false;
			var refreshLights = false;

			var program = materialProperties.program,
				p_uniforms = program.getUniforms(),
				m_uniforms = materialProperties.uniforms;

			if ( state.useProgram( program.program ) ) {

				refreshProgram = true;
				refreshMaterial = true;
				refreshLights = true;

			}

			if ( material.id !== _currentMaterialId ) {

				_currentMaterialId = material.id;

				refreshMaterial = true;

			}

			if ( refreshProgram || _currentCamera !== camera ) {

				if ( program.numMultiviewViews > 0 ) {

					multiview.updateCameraProjectionMatricesUniform( camera, p_uniforms );

				} else {

					p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );

				}

				if ( capabilities.logarithmicDepthBuffer ) {

					p_uniforms.setValue( _gl, 'logDepthBufFC',
						2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );

				}

				if ( _currentCamera !== camera ) {

					_currentCamera = camera;

					// lighting uniforms depend on the camera so enforce an update
					// now, in case this material supports lights - or later, when
					// the next material that does gets activated:

					refreshMaterial = true;		// set to true on material change
					refreshLights = true;		// remains set until update done

				}

				// load material specific uniforms
				// (shader material also gets them for the sake of genericity)

				if ( material.isShaderMaterial ||
					material.isMeshPhongMaterial ||
					material.isMeshToonMaterial ||
					material.isMeshStandardMaterial ||
					material.envMap ) {

					var uCamPos = p_uniforms.map.cameraPosition;

					if ( uCamPos !== undefined ) {

						uCamPos.setValue( _gl,
							_vector3.setFromMatrixPosition( camera.matrixWorld ) );

					}

				}

				if ( material.isMeshPhongMaterial ||
					material.isMeshToonMaterial ||
					material.isMeshLambertMaterial ||
					material.isMeshBasicMaterial ||
					material.isMeshStandardMaterial ||
					material.isShaderMaterial ) {

					p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );

				}

				if ( material.isMeshPhongMaterial ||
					material.isMeshToonMaterial ||
					material.isMeshLambertMaterial ||
					material.isMeshBasicMaterial ||
					material.isMeshStandardMaterial ||
					material.isShaderMaterial ||
					material.skinning ) {

					if ( program.numMultiviewViews > 0 ) {

						multiview.updateCameraViewMatricesUniform( camera, p_uniforms );

					} else {

						p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );

					}

				}

			}

			// skinning uniforms must be set even if material didn't change
			// auto-setting of texture unit for bone texture must go before other textures
			// not sure why, but otherwise weird things happen

			if ( material.skinning ) {

				p_uniforms.setOptional( _gl, object, 'bindMatrix' );
				p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );

				var skeleton = object.skeleton;

				if ( skeleton ) {

					var bones = skeleton.bones;

					if ( capabilities.floatVertexTextures ) {

						if ( skeleton.boneTexture === undefined ) {

							// layout (1 matrix = 4 pixels)
							//      RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
							//  with  8x8  pixel texture max   16 bones * 4 pixels =  (8 * 8)
							//       16x16 pixel texture max   64 bones * 4 pixels = (16 * 16)
							//       32x32 pixel texture max  256 bones * 4 pixels = (32 * 32)
							//       64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)


							var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
							size = MathUtils.ceilPowerOfTwo( size );
							size = Math.max( size, 4 );

							var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
							boneMatrices.set( skeleton.boneMatrices ); // copy current values

							var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );

							skeleton.boneMatrices = boneMatrices;
							skeleton.boneTexture = boneTexture;
							skeleton.boneTextureSize = size;

						}

						p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
						p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );

					} else {

						p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );

					}

				}

			}

			if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {

				materialProperties.receiveShadow = object.receiveShadow;
				p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );

			}

			if ( refreshMaterial ) {

				p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
				p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );

				if ( materialProperties.needsLights ) {

					// the current material requires lighting info

					// note: all lighting uniforms are always set correctly
					// they simply reference the renderer's state for their
					// values
					//
					// use the current material's .needsUpdate flags to set
					// the GL state when required

					markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );

				}

				// refresh uniforms common to several materials

				if ( fog && material.fog ) {

					refreshUniformsFog( m_uniforms, fog );

				}

				if ( material.isMeshBasicMaterial ) {

					refreshUniformsCommon( m_uniforms, material );

				} else if ( material.isMeshLambertMaterial ) {

					refreshUniformsCommon( m_uniforms, material );
					refreshUniformsLambert( m_uniforms, material );

				} else if ( material.isMeshToonMaterial ) {

					refreshUniformsCommon( m_uniforms, material );
					refreshUniformsToon( m_uniforms, material );

				} else if ( material.isMeshPhongMaterial ) {

					refreshUniformsCommon( m_uniforms, material );
					refreshUniformsPhong( m_uniforms, material );

				} else if ( material.isMeshStandardMaterial ) {

					refreshUniformsCommon( m_uniforms, material, environment );

					if ( material.isMeshPhysicalMaterial ) {

						refreshUniformsPhysical( m_uniforms, material, environment );

					} else {

						refreshUniformsStandard( m_uniforms, material, environment );

					}

				} else if ( material.isMeshMatcapMaterial ) {

					refreshUniformsCommon( m_uniforms, material );
					refreshUniformsMatcap( m_uniforms, material );

				} else if ( material.isMeshDepthMaterial ) {

					refreshUniformsCommon( m_uniforms, material );
					refreshUniformsDepth( m_uniforms, material );

				} else if ( material.isMeshDistanceMaterial ) {

					refreshUniformsCommon( m_uniforms, material );
					refreshUniformsDistance( m_uniforms, material );

				} else if ( material.isMeshNormalMaterial ) {

					refreshUniformsCommon( m_uniforms, material );
					refreshUniformsNormal( m_uniforms, material );

				} else if ( material.isLineBasicMaterial ) {

					refreshUniformsLine( m_uniforms, material );

					if ( material.isLineDashedMaterial ) {

						refreshUniformsDash( m_uniforms, material );

					}

				} else if ( material.isPointsMaterial ) {

					refreshUniformsPoints( m_uniforms, material );

				} else if ( material.isSpriteMaterial ) {

					refreshUniformsSprites( m_uniforms, material );

				} else if ( material.isShadowMaterial ) {

					m_uniforms.color.value.copy( material.color );
					m_uniforms.opacity.value = material.opacity;

				}

				// RectAreaLight Texture
				// TODO (mrdoob): Find a nicer implementation

				if ( m_uniforms.ltc_1 !== undefined ) { m_uniforms.ltc_1.value = UniformsLib.LTC_1; }
				if ( m_uniforms.ltc_2 !== undefined ) { m_uniforms.ltc_2.value = UniformsLib.LTC_2; }

				WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );

				if ( material.isShaderMaterial ) {

					material.uniformsNeedUpdate = false; // #15581

				}

			}

			if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {

				WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
				material.uniformsNeedUpdate = false;

			}

			if ( material.isSpriteMaterial ) {

				p_uniforms.setValue( _gl, 'center', object.center );

			}

			// common matrices

			if ( program.numMultiviewViews > 0 ) {

				multiview.updateObjectMatricesUniforms( object, camera, p_uniforms );

			} else {

				p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
				p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );

			}

			p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );

			return program;

		}

		// Uniforms (refresh uniforms objects)

		function refreshUniformsCommon( uniforms, material, environment ) {

			uniforms.opacity.value = material.opacity;

			if ( material.color ) {

				uniforms.diffuse.value.copy( material.color );

			}

			if ( material.emissive ) {

				uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );

			}

			if ( material.map ) {

				uniforms.map.value = material.map;

			}

			if ( material.alphaMap ) {

				uniforms.alphaMap.value = material.alphaMap;

			}

			if ( material.specularMap ) {

				uniforms.specularMap.value = material.specularMap;

			}

			var envMap = material.envMap || environment;

			if ( envMap ) {

				uniforms.envMap.value = envMap;

				uniforms.flipEnvMap.value = envMap.isCubeTexture ? - 1 : 1;

				uniforms.reflectivity.value = material.reflectivity;
				uniforms.refractionRatio.value = material.refractionRatio;

				uniforms.maxMipLevel.value = properties.get( envMap ).__maxMipLevel;

			}

			if ( material.lightMap ) {

				uniforms.lightMap.value = material.lightMap;
				uniforms.lightMapIntensity.value = material.lightMapIntensity;

			}

			if ( material.aoMap ) {

				uniforms.aoMap.value = material.aoMap;
				uniforms.aoMapIntensity.value = material.aoMapIntensity;

			}

			// uv repeat and offset setting priorities
			// 1. color map
			// 2. specular map
			// 3. normal map
			// 4. bump map
			// 5. alpha map
			// 6. emissive map

			var uvScaleMap;

			if ( material.map ) {

				uvScaleMap = material.map;

			} else if ( material.specularMap ) {

				uvScaleMap = material.specularMap;

			} else if ( material.displacementMap ) {

				uvScaleMap = material.displacementMap;

			} else if ( material.normalMap ) {

				uvScaleMap = material.normalMap;

			} else if ( material.bumpMap ) {

				uvScaleMap = material.bumpMap;

			} else if ( material.roughnessMap ) {

				uvScaleMap = material.roughnessMap;

			} else if ( material.metalnessMap ) {

				uvScaleMap = material.metalnessMap;

			} else if ( material.alphaMap ) {

				uvScaleMap = material.alphaMap;

			} else if ( material.emissiveMap ) {

				uvScaleMap = material.emissiveMap;

			}

			if ( uvScaleMap !== undefined ) {

				// backwards compatibility
				if ( uvScaleMap.isWebGLRenderTarget ) {

					uvScaleMap = uvScaleMap.texture;

				}

				if ( uvScaleMap.matrixAutoUpdate === true ) {

					uvScaleMap.updateMatrix();

				}

				uniforms.uvTransform.value.copy( uvScaleMap.matrix );

			}

			// uv repeat and offset setting priorities for uv2
			// 1. ao map
			// 2. light map

			var uv2ScaleMap;

			if ( material.aoMap ) {

				uv2ScaleMap = material.aoMap;

			} else if ( material.lightMap ) {

				uv2ScaleMap = material.lightMap;

			}

			if ( uv2ScaleMap !== undefined ) {

				// backwards compatibility
				if ( uv2ScaleMap.isWebGLRenderTarget ) {

					uv2ScaleMap = uv2ScaleMap.texture;

				}

				if ( uv2ScaleMap.matrixAutoUpdate === true ) {

					uv2ScaleMap.updateMatrix();

				}

				uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );

			}

		}

		function refreshUniformsLine( uniforms, material ) {

			uniforms.diffuse.value.copy( material.color );
			uniforms.opacity.value = material.opacity;

		}

		function refreshUniformsDash( uniforms, material ) {

			uniforms.dashSize.value = material.dashSize;
			uniforms.totalSize.value = material.dashSize + material.gapSize;
			uniforms.scale.value = material.scale;

		}

		function refreshUniformsPoints( uniforms, material ) {

			uniforms.diffuse.value.copy( material.color );
			uniforms.opacity.value = material.opacity;
			uniforms.size.value = material.size * _pixelRatio;
			uniforms.scale.value = _height * 0.5;

			if ( material.map ) {

				uniforms.map.value = material.map;

			}

			if ( material.alphaMap ) {

				uniforms.alphaMap.value = material.alphaMap;

			}

			// uv repeat and offset setting priorities
			// 1. color map
			// 2. alpha map

			var uvScaleMap;

			if ( material.map ) {

				uvScaleMap = material.map;

			} else if ( material.alphaMap ) {

				uvScaleMap = material.alphaMap;

			}

			if ( uvScaleMap !== undefined ) {

				if ( uvScaleMap.matrixAutoUpdate === true ) {

					uvScaleMap.updateMatrix();

				}

				uniforms.uvTransform.value.copy( uvScaleMap.matrix );

			}

		}

		function refreshUniformsSprites( uniforms, material ) {

			uniforms.diffuse.value.copy( material.color );
			uniforms.opacity.value = material.opacity;
			uniforms.rotation.value = material.rotation;

			if ( material.map ) {

				uniforms.map.value = material.map;

			}

			if ( material.alphaMap ) {

				uniforms.alphaMap.value = material.alphaMap;

			}

			// uv repeat and offset setting priorities
			// 1. color map
			// 2. alpha map

			var uvScaleMap;

			if ( material.map ) {

				uvScaleMap = material.map;

			} else if ( material.alphaMap ) {

				uvScaleMap = material.alphaMap;

			}

			if ( uvScaleMap !== undefined ) {

				if ( uvScaleMap.matrixAutoUpdate === true ) {

					uvScaleMap.updateMatrix();

				}

				uniforms.uvTransform.value.copy( uvScaleMap.matrix );

			}

		}

		function refreshUniformsFog( uniforms, fog ) {

			uniforms.fogColor.value.copy( fog.color );

			if ( fog.isFog ) {

				uniforms.fogNear.value = fog.near;
				uniforms.fogFar.value = fog.far;

			} else if ( fog.isFogExp2 ) {

				uniforms.fogDensity.value = fog.density;

			}

		}

		function refreshUniformsLambert( uniforms, material ) {

			if ( material.emissiveMap ) {

				uniforms.emissiveMap.value = material.emissiveMap;

			}

		}

		function refreshUniformsPhong( uniforms, material ) {

			uniforms.specular.value.copy( material.specular );
			uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )

			if ( material.emissiveMap ) {

				uniforms.emissiveMap.value = material.emissiveMap;

			}

			if ( material.bumpMap ) {

				uniforms.bumpMap.value = material.bumpMap;
				uniforms.bumpScale.value = material.bumpScale;
				if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }

			}

			if ( material.normalMap ) {

				uniforms.normalMap.value = material.normalMap;
				uniforms.normalScale.value.copy( material.normalScale );
				if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }

			}

			if ( material.displacementMap ) {

				uniforms.displacementMap.value = material.displacementMap;
				uniforms.displacementScale.value = material.displacementScale;
				uniforms.displacementBias.value = material.displacementBias;

			}

		}

		function refreshUniformsToon( uniforms, material ) {

			uniforms.specular.value.copy( material.specular );
			uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )

			if ( material.gradientMap ) {

				uniforms.gradientMap.value = material.gradientMap;

			}

			if ( material.emissiveMap ) {

				uniforms.emissiveMap.value = material.emissiveMap;

			}

			if ( material.bumpMap ) {

				uniforms.bumpMap.value = material.bumpMap;
				uniforms.bumpScale.value = material.bumpScale;
				if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }

			}

			if ( material.normalMap ) {

				uniforms.normalMap.value = material.normalMap;
				uniforms.normalScale.value.copy( material.normalScale );
				if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }

			}

			if ( material.displacementMap ) {

				uniforms.displacementMap.value = material.displacementMap;
				uniforms.displacementScale.value = material.displacementScale;
				uniforms.displacementBias.value = material.displacementBias;

			}

		}

		function refreshUniformsStandard( uniforms, material, environment ) {

			uniforms.roughness.value = material.roughness;
			uniforms.metalness.value = material.metalness;

			if ( material.roughnessMap ) {

				uniforms.roughnessMap.value = material.roughnessMap;

			}

			if ( material.metalnessMap ) {

				uniforms.metalnessMap.value = material.metalnessMap;

			}

			if ( material.emissiveMap ) {

				uniforms.emissiveMap.value = material.emissiveMap;

			}

			if ( material.bumpMap ) {

				uniforms.bumpMap.value = material.bumpMap;
				uniforms.bumpScale.value = material.bumpScale;
				if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }

			}

			if ( material.normalMap ) {

				uniforms.normalMap.value = material.normalMap;
				uniforms.normalScale.value.copy( material.normalScale );
				if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }

			}

			if ( material.displacementMap ) {

				uniforms.displacementMap.value = material.displacementMap;
				uniforms.displacementScale.value = material.displacementScale;
				uniforms.displacementBias.value = material.displacementBias;

			}

			if ( material.envMap || environment ) {

				//uniforms.envMap.value = material.envMap; // part of uniforms common
				uniforms.envMapIntensity.value = material.envMapIntensity;

			}

		}

		function refreshUniformsPhysical( uniforms, material, environment ) {

			refreshUniformsStandard( uniforms, material, environment );

			uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common

			uniforms.clearcoat.value = material.clearcoat;
			uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
			if ( material.sheen ) { uniforms.sheen.value.copy( material.sheen ); }

			if ( material.clearcoatNormalMap ) {

				uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
				uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;

				if ( material.side === BackSide ) {

					uniforms.clearcoatNormalScale.value.negate();

				}

			}

			uniforms.transparency.value = material.transparency;

		}

		function refreshUniformsMatcap( uniforms, material ) {

			if ( material.matcap ) {

				uniforms.matcap.value = material.matcap;

			}

			if ( material.bumpMap ) {

				uniforms.bumpMap.value = material.bumpMap;
				uniforms.bumpScale.value = material.bumpScale;
				if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }

			}

			if ( material.normalMap ) {

				uniforms.normalMap.value = material.normalMap;
				uniforms.normalScale.value.copy( material.normalScale );
				if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }

			}

			if ( material.displacementMap ) {

				uniforms.displacementMap.value = material.displacementMap;
				uniforms.displacementScale.value = material.displacementScale;
				uniforms.displacementBias.value = material.displacementBias;

			}

		}

		function refreshUniformsDepth( uniforms, material ) {

			if ( material.displacementMap ) {

				uniforms.displacementMap.value = material.displacementMap;
				uniforms.displacementScale.value = material.displacementScale;
				uniforms.displacementBias.value = material.displacementBias;

			}

		}

		function refreshUniformsDistance( uniforms, material ) {

			if ( material.displacementMap ) {

				uniforms.displacementMap.value = material.displacementMap;
				uniforms.displacementScale.value = material.displacementScale;
				uniforms.displacementBias.value = material.displacementBias;

			}

			uniforms.referencePosition.value.copy( material.referencePosition );
			uniforms.nearDistance.value = material.nearDistance;
			uniforms.farDistance.value = material.farDistance;

		}

		function refreshUniformsNormal( uniforms, material ) {

			if ( material.bumpMap ) {

				uniforms.bumpMap.value = material.bumpMap;
				uniforms.bumpScale.value = material.bumpScale;
				if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; }

			}

			if ( material.normalMap ) {

				uniforms.normalMap.value = material.normalMap;
				uniforms.normalScale.value.copy( material.normalScale );
				if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); }

			}

			if ( material.displacementMap ) {

				uniforms.displacementMap.value = material.displacementMap;
				uniforms.displacementScale.value = material.displacementScale;
				uniforms.displacementBias.value = material.displacementBias;

			}

		}

		// If uniforms are marked as clean, they don't need to be loaded to the GPU.

		function markUniformsLightsNeedsUpdate( uniforms, value ) {

			uniforms.ambientLightColor.needsUpdate = value;
			uniforms.lightProbe.needsUpdate = value;

			uniforms.directionalLights.needsUpdate = value;
			uniforms.pointLights.needsUpdate = value;
			uniforms.spotLights.needsUpdate = value;
			uniforms.rectAreaLights.needsUpdate = value;
			uniforms.hemisphereLights.needsUpdate = value;

		}

		function materialNeedsLights( material ) {

			return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
				material.isMeshStandardMaterial || material.isShadowMaterial ||
				( material.isShaderMaterial && material.lights === true );

		}

		//
		this.setFramebuffer = function ( value ) {

			if ( _framebuffer !== value && _currentRenderTarget === null ) { _gl.bindFramebuffer( 36160, value ); }

			_framebuffer = value;

		};

		this.getActiveCubeFace = function () {

			return _currentActiveCubeFace;

		};

		this.getActiveMipmapLevel = function () {

			return _currentActiveMipmapLevel;

		};

		this.getRenderTarget = function () {

			return _currentRenderTarget;

		};

		this.setRenderTarget = function ( renderTarget, activeCubeFace, activeMipmapLevel ) {

			_currentRenderTarget = renderTarget;
			_currentActiveCubeFace = activeCubeFace;
			_currentActiveMipmapLevel = activeMipmapLevel;

			if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {

				textures.setupRenderTarget( renderTarget );

			}

			var framebuffer = _framebuffer;
			var isCube = false;

			if ( renderTarget ) {

				var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;

				if ( renderTarget.isWebGLCubeRenderTarget ) {

					framebuffer = __webglFramebuffer[ activeCubeFace || 0 ];
					isCube = true;

				} else if ( renderTarget.isWebGLMultisampleRenderTarget ) {

					framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;

				} else {

					framebuffer = __webglFramebuffer;

				}

				_currentViewport.copy( renderTarget.viewport );
				_currentScissor.copy( renderTarget.scissor );
				_currentScissorTest = renderTarget.scissorTest;

			} else {

				_currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
				_currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
				_currentScissorTest = _scissorTest;

			}

			if ( _currentFramebuffer !== framebuffer ) {

				_gl.bindFramebuffer( 36160, framebuffer );
				_currentFramebuffer = framebuffer;

			}

			state.viewport( _currentViewport );
			state.scissor( _currentScissor );
			state.setScissorTest( _currentScissorTest );

			if ( isCube ) {

				var textureProperties = properties.get( renderTarget.texture );
				_gl.framebufferTexture2D( 36160, 36064, 34069 + ( activeCubeFace || 0 ), textureProperties.__webglTexture, activeMipmapLevel || 0 );

			}

		};

		this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {

			if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {

				console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
				return;

			}

			var framebuffer = properties.get( renderTarget ).__webglFramebuffer;

			if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {

				framebuffer = framebuffer[ activeCubeFaceIndex ];

			}

			if ( framebuffer ) {

				var restore = false;

				if ( framebuffer !== _currentFramebuffer ) {

					_gl.bindFramebuffer( 36160, framebuffer );

					restore = true;

				}

				try {

					var texture = renderTarget.texture;
					var textureFormat = texture.format;
					var textureType = texture.type;

					if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {

						console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
						return;

					}

					if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // IE11, Edge and Chrome Mac < 52 (#9513)
						! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
						! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {

						console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
						return;

					}

					if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {

						// the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)

						if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {

							_gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );

						}

					} else {

						console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );

					}

				} finally {

					if ( restore ) {

						_gl.bindFramebuffer( 36160, _currentFramebuffer );

					}

				}

			}

		};

		this.copyFramebufferToTexture = function ( position, texture, level ) {

			if ( level === undefined ) { level = 0; }

			var levelScale = Math.pow( 2, - level );
			var width = Math.floor( texture.image.width * levelScale );
			var height = Math.floor( texture.image.height * levelScale );
			var glFormat = utils.convert( texture.format );

			textures.setTexture2D( texture, 0 );

			_gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );

			state.unbindTexture();

		};

		this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) {

			var width = srcTexture.image.width;
			var height = srcTexture.image.height;
			var glFormat = utils.convert( dstTexture.format );
			var glType = utils.convert( dstTexture.type );

			textures.setTexture2D( dstTexture, 0 );

			if ( srcTexture.isDataTexture ) {

				_gl.texSubImage2D( 3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );

			} else {

				_gl.texSubImage2D( 3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image );

			}

			state.unbindTexture();

		};

		this.initTexture = function ( texture ) {

			textures.setTexture2D( texture, 0 );

			state.unbindTexture();

		};

		if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {

			__THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef

		}

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author alteredq / http://alteredqualia.com/
	 */

	function FogExp2( color, density ) {

		this.name = '';

		this.color = new Color( color );
		this.density = ( density !== undefined ) ? density : 0.00025;

	}

	Object.assign( FogExp2.prototype, {

		isFogExp2: true,

		clone: function () {

			return new FogExp2( this.color, this.density );

		},

		toJSON: function ( /* meta */ ) {

			return {
				type: 'FogExp2',
				color: this.color.getHex(),
				density: this.density
			};

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author alteredq / http://alteredqualia.com/
	 */

	function Fog( color, near, far ) {

		this.name = '';

		this.color = new Color( color );

		this.near = ( near !== undefined ) ? near : 1;
		this.far = ( far !== undefined ) ? far : 1000;

	}

	Object.assign( Fog.prototype, {

		isFog: true,

		clone: function () {

			return new Fog( this.color, this.near, this.far );

		},

		toJSON: function ( /* meta */ ) {

			return {
				type: 'Fog',
				color: this.color.getHex(),
				near: this.near,
				far: this.far
			};

		}

	} );

	/**
	 * @author benaadams / https://twitter.com/ben_a_adams
	 */

	function InterleavedBuffer( array, stride ) {

		this.array = array;
		this.stride = stride;
		this.count = array !== undefined ? array.length / stride : 0;

		this.usage = StaticDrawUsage;
		this.updateRange = { offset: 0, count: - 1 };

		this.version = 0;

	}

	Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {

		set: function ( value ) {

			if ( value === true ) { this.version ++; }

		}

	} );

	Object.assign( InterleavedBuffer.prototype, {

		isInterleavedBuffer: true,

		onUploadCallback: function () {},

		setUsage: function ( value ) {

			this.usage = value;

			return this;

		},

		copy: function ( source ) {

			this.array = new source.array.constructor( source.array );
			this.count = source.count;
			this.stride = source.stride;
			this.usage = source.usage;

			return this;

		},

		copyAt: function ( index1, attribute, index2 ) {

			index1 *= this.stride;
			index2 *= attribute.stride;

			for ( var i = 0, l = this.stride; i < l; i ++ ) {

				this.array[ index1 + i ] = attribute.array[ index2 + i ];

			}

			return this;

		},

		set: function ( value, offset ) {

			if ( offset === undefined ) { offset = 0; }

			this.array.set( value, offset );

			return this;

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		onUpload: function ( callback ) {

			this.onUploadCallback = callback;

			return this;

		}

	} );

	/**
	 * @author benaadams / https://twitter.com/ben_a_adams
	 */

	var _vector$6 = new Vector3();

	function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {

		this.data = interleavedBuffer;
		this.itemSize = itemSize;
		this.offset = offset;

		this.normalized = normalized === true;

	}

	Object.defineProperties( InterleavedBufferAttribute.prototype, {

		count: {

			get: function () {

				return this.data.count;

			}

		},

		array: {

			get: function () {

				return this.data.array;

			}

		}

	} );

	Object.assign( InterleavedBufferAttribute.prototype, {

		isInterleavedBufferAttribute: true,

		applyMatrix4: function ( m ) {

			for ( var i = 0, l = this.data.count; i < l; i ++ ) {

				_vector$6.x = this.getX( i );
				_vector$6.y = this.getY( i );
				_vector$6.z = this.getZ( i );

				_vector$6.applyMatrix4( m );

				this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );

			}

			return this;

		},

		setX: function ( index, x ) {

			this.data.array[ index * this.data.stride + this.offset ] = x;

			return this;

		},

		setY: function ( index, y ) {

			this.data.array[ index * this.data.stride + this.offset + 1 ] = y;

			return this;

		},

		setZ: function ( index, z ) {

			this.data.array[ index * this.data.stride + this.offset + 2 ] = z;

			return this;

		},

		setW: function ( index, w ) {

			this.data.array[ index * this.data.stride + this.offset + 3 ] = w;

			return this;

		},

		getX: function ( index ) {

			return this.data.array[ index * this.data.stride + this.offset ];

		},

		getY: function ( index ) {

			return this.data.array[ index * this.data.stride + this.offset + 1 ];

		},

		getZ: function ( index ) {

			return this.data.array[ index * this.data.stride + this.offset + 2 ];

		},

		getW: function ( index ) {

			return this.data.array[ index * this.data.stride + this.offset + 3 ];

		},

		setXY: function ( index, x, y ) {

			index = index * this.data.stride + this.offset;

			this.data.array[ index + 0 ] = x;
			this.data.array[ index + 1 ] = y;

			return this;

		},

		setXYZ: function ( index, x, y, z ) {

			index = index * this.data.stride + this.offset;

			this.data.array[ index + 0 ] = x;
			this.data.array[ index + 1 ] = y;
			this.data.array[ index + 2 ] = z;

			return this;

		},

		setXYZW: function ( index, x, y, z, w ) {

			index = index * this.data.stride + this.offset;

			this.data.array[ index + 0 ] = x;
			this.data.array[ index + 1 ] = y;
			this.data.array[ index + 2 ] = z;
			this.data.array[ index + 3 ] = w;

			return this;

		}

	} );

	/**
	 * @author alteredq / http://alteredqualia.com/
	 *
	 * parameters = {
	 *  color: <hex>,
	 *  map: new THREE.Texture( <Image> ),
	 *  alphaMap: new THREE.Texture( <Image> ),
	 *  rotation: <float>,
	 *  sizeAttenuation: <bool>
	 * }
	 */

	function SpriteMaterial( parameters ) {

		Material.call( this );

		this.type = 'SpriteMaterial';

		this.color = new Color( 0xffffff );

		this.map = null;

		this.alphaMap = null;

		this.rotation = 0;

		this.sizeAttenuation = true;

		this.transparent = true;

		this.setValues( parameters );

	}

	SpriteMaterial.prototype = Object.create( Material.prototype );
	SpriteMaterial.prototype.constructor = SpriteMaterial;
	SpriteMaterial.prototype.isSpriteMaterial = true;

	SpriteMaterial.prototype.copy = function ( source ) {

		Material.prototype.copy.call( this, source );

		this.color.copy( source.color );

		this.map = source.map;

		this.alphaMap = source.alphaMap;

		this.rotation = source.rotation;

		this.sizeAttenuation = source.sizeAttenuation;

		return this;

	};

	/**
	 * @author mikael emtinger / http://gomo.se/
	 * @author alteredq / http://alteredqualia.com/
	 */

	var _geometry;

	var _intersectPoint = new Vector3();
	var _worldScale = new Vector3();
	var _mvPosition = new Vector3();

	var _alignedPosition = new Vector2();
	var _rotatedPosition = new Vector2();
	var _viewWorldMatrix = new Matrix4();

	var _vA$1 = new Vector3();
	var _vB$1 = new Vector3();
	var _vC$1 = new Vector3();

	var _uvA$1 = new Vector2();
	var _uvB$1 = new Vector2();
	var _uvC$1 = new Vector2();

	function Sprite( material ) {

		Object3D.call( this );

		this.type = 'Sprite';

		if ( _geometry === undefined ) {

			_geometry = new BufferGeometry();

			var float32Array = new Float32Array( [
				- 0.5, - 0.5, 0, 0, 0,
				0.5, - 0.5, 0, 1, 0,
				0.5, 0.5, 0, 1, 1,
				- 0.5, 0.5, 0, 0, 1
			] );

			var interleavedBuffer = new InterleavedBuffer( float32Array, 5 );

			_geometry.setIndex( [ 0, 1, 2,	0, 2, 3 ] );
			_geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
			_geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );

		}

		this.geometry = _geometry;
		this.material = ( material !== undefined ) ? material : new SpriteMaterial();

		this.center = new Vector2( 0.5, 0.5 );

	}

	Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {

		constructor: Sprite,

		isSprite: true,

		raycast: function ( raycaster, intersects ) {

			if ( raycaster.camera === null ) {

				console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );

			}

			_worldScale.setFromMatrixScale( this.matrixWorld );

			_viewWorldMatrix.copy( raycaster.camera.matrixWorld );
			this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );

			_mvPosition.setFromMatrixPosition( this.modelViewMatrix );

			if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {

				_worldScale.multiplyScalar( - _mvPosition.z );

			}

			var rotation = this.material.rotation;
			var sin, cos;
			if ( rotation !== 0 ) {

				cos = Math.cos( rotation );
				sin = Math.sin( rotation );

			}

			var center = this.center;

			transformVertex( _vA$1.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
			transformVertex( _vB$1.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
			transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );

			_uvA$1.set( 0, 0 );
			_uvB$1.set( 1, 0 );
			_uvC$1.set( 1, 1 );

			// check first triangle
			var intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );

			if ( intersect === null ) {

				// check second triangle
				transformVertex( _vB$1.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
				_uvB$1.set( 0, 1 );

				intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
				if ( intersect === null ) {

					return;

				}

			}

			var distance = raycaster.ray.origin.distanceTo( _intersectPoint );

			if ( distance < raycaster.near || distance > raycaster.far ) { return; }

			intersects.push( {

				distance: distance,
				point: _intersectPoint.clone(),
				uv: Triangle.getUV( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ),
				face: null,
				object: this

			} );

		},

		clone: function () {

			return new this.constructor( this.material ).copy( this );

		},

		copy: function ( source ) {

			Object3D.prototype.copy.call( this, source );

			if ( source.center !== undefined ) { this.center.copy( source.center ); }

			return this;

		}


	} );

	function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {

		// compute position in camera space
		_alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );

		// to check if rotation is not zero
		if ( sin !== undefined ) {

			_rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
			_rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );

		} else {

			_rotatedPosition.copy( _alignedPosition );

		}


		vertexPosition.copy( mvPosition );
		vertexPosition.x += _rotatedPosition.x;
		vertexPosition.y += _rotatedPosition.y;

		// transform to world space
		vertexPosition.applyMatrix4( _viewWorldMatrix );

	}

	/**
	 * @author mikael emtinger / http://gomo.se/
	 * @author alteredq / http://alteredqualia.com/
	 * @author mrdoob / http://mrdoob.com/
	 */

	var _v1$4 = new Vector3();
	var _v2$2 = new Vector3();

	function LOD() {

		Object3D.call( this );

		this.type = 'LOD';

		Object.defineProperties( this, {
			levels: {
				enumerable: true,
				value: []
			}
		} );

		this.autoUpdate = true;

	}

	LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {

		constructor: LOD,

		isLOD: true,

		copy: function ( source ) {

			Object3D.prototype.copy.call( this, source, false );

			var levels = source.levels;

			for ( var i = 0, l = levels.length; i < l; i ++ ) {

				var level = levels[ i ];

				this.addLevel( level.object.clone(), level.distance );

			}

			this.autoUpdate = source.autoUpdate;

			return this;

		},

		addLevel: function ( object, distance ) {

			if ( distance === undefined ) { distance = 0; }

			distance = Math.abs( distance );

			var levels = this.levels;

			for ( var l = 0; l < levels.length; l ++ ) {

				if ( distance < levels[ l ].distance ) {

					break;

				}

			}

			levels.splice( l, 0, { distance: distance, object: object } );

			this.add( object );

			return this;

		},

		getObjectForDistance: function ( distance ) {

			var levels = this.levels;

			if ( levels.length > 0 ) {

				for ( var i = 1, l = levels.length; i < l; i ++ ) {

					if ( distance < levels[ i ].distance ) {

						break;

					}

				}

				return levels[ i - 1 ].object;

			}

			return null;

		},

		raycast: function ( raycaster, intersects ) {

			var levels = this.levels;

			if ( levels.length > 0 ) {

				_v1$4.setFromMatrixPosition( this.matrixWorld );

				var distance = raycaster.ray.origin.distanceTo( _v1$4 );

				this.getObjectForDistance( distance ).raycast( raycaster, intersects );

			}

		},

		update: function ( camera ) {

			var levels = this.levels;

			if ( levels.length > 1 ) {

				_v1$4.setFromMatrixPosition( camera.matrixWorld );
				_v2$2.setFromMatrixPosition( this.matrixWorld );

				var distance = _v1$4.distanceTo( _v2$2 );

				levels[ 0 ].object.visible = true;

				for ( var i = 1, l = levels.length; i < l; i ++ ) {

					if ( distance >= levels[ i ].distance ) {

						levels[ i - 1 ].object.visible = false;
						levels[ i ].object.visible = true;

					} else {

						break;

					}

				}

				for ( ; i < l; i ++ ) {

					levels[ i ].object.visible = false;

				}

			}

		},

		toJSON: function ( meta ) {

			var data = Object3D.prototype.toJSON.call( this, meta );

			if ( this.autoUpdate === false ) { data.object.autoUpdate = false; }

			data.object.levels = [];

			var levels = this.levels;

			for ( var i = 0, l = levels.length; i < l; i ++ ) {

				var level = levels[ i ];

				data.object.levels.push( {
					object: level.object.uuid,
					distance: level.distance
				} );

			}

			return data;

		}

	} );

	/**
	 * @author mikael emtinger / http://gomo.se/
	 * @author alteredq / http://alteredqualia.com/
	 * @author ikerr / http://verold.com
	 */

	function SkinnedMesh( geometry, material ) {

		if ( geometry && geometry.isGeometry ) {

			console.error( 'THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );

		}

		Mesh.call( this, geometry, material );

		this.type = 'SkinnedMesh';

		this.bindMode = 'attached';
		this.bindMatrix = new Matrix4();
		this.bindMatrixInverse = new Matrix4();

	}

	SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {

		constructor: SkinnedMesh,

		isSkinnedMesh: true,

		bind: function ( skeleton, bindMatrix ) {

			this.skeleton = skeleton;

			if ( bindMatrix === undefined ) {

				this.updateMatrixWorld( true );

				this.skeleton.calculateInverses();

				bindMatrix = this.matrixWorld;

			}

			this.bindMatrix.copy( bindMatrix );
			this.bindMatrixInverse.getInverse( bindMatrix );

		},

		pose: function () {

			this.skeleton.pose();

		},

		normalizeSkinWeights: function () {

			var vector = new Vector4();

			var skinWeight = this.geometry.attributes.skinWeight;

			for ( var i = 0, l = skinWeight.count; i < l; i ++ ) {

				vector.x = skinWeight.getX( i );
				vector.y = skinWeight.getY( i );
				vector.z = skinWeight.getZ( i );
				vector.w = skinWeight.getW( i );

				var scale = 1.0 / vector.manhattanLength();

				if ( scale !== Infinity ) {

					vector.multiplyScalar( scale );

				} else {

					vector.set( 1, 0, 0, 0 ); // do something reasonable

				}

				skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );

			}

		},

		updateMatrixWorld: function ( force ) {

			Mesh.prototype.updateMatrixWorld.call( this, force );

			if ( this.bindMode === 'attached' ) {

				this.bindMatrixInverse.getInverse( this.matrixWorld );

			} else if ( this.bindMode === 'detached' ) {

				this.bindMatrixInverse.getInverse( this.bindMatrix );

			} else {

				console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );

			}

		},

		clone: function () {

			return new this.constructor( this.geometry, this.material ).copy( this );

		}

	} );

	/**
	 * @author mikael emtinger / http://gomo.se/
	 * @author alteredq / http://alteredqualia.com/
	 * @author michael guerrero / http://realitymeltdown.com
	 * @author ikerr / http://verold.com
	 */

	var _offsetMatrix = new Matrix4();
	var _identityMatrix = new Matrix4();

	function Skeleton( bones, boneInverses ) {

		// copy the bone array

		bones = bones || [];

		this.bones = bones.slice( 0 );
		this.boneMatrices = new Float32Array( this.bones.length * 16 );

		this.frame = - 1;

		// use the supplied bone inverses or calculate the inverses

		if ( boneInverses === undefined ) {

			this.calculateInverses();

		} else {

			if ( this.bones.length === boneInverses.length ) {

				this.boneInverses = boneInverses.slice( 0 );

			} else {

				console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );

				this.boneInverses = [];

				for ( var i = 0, il = this.bones.length; i < il; i ++ ) {

					this.boneInverses.push( new Matrix4() );

				}

			}

		}

	}

	Object.assign( Skeleton.prototype, {

		calculateInverses: function () {

			this.boneInverses = [];

			for ( var i = 0, il = this.bones.length; i < il; i ++ ) {

				var inverse = new Matrix4();

				if ( this.bones[ i ] ) {

					inverse.getInverse( this.bones[ i ].matrixWorld );

				}

				this.boneInverses.push( inverse );

			}

		},

		pose: function () {

			var bone, i, il;

			// recover the bind-time world matrices

			for ( i = 0, il = this.bones.length; i < il; i ++ ) {

				bone = this.bones[ i ];

				if ( bone ) {

					bone.matrixWorld.getInverse( this.boneInverses[ i ] );

				}

			}

			// compute the local matrices, positions, rotations and scales

			for ( i = 0, il = this.bones.length; i < il; i ++ ) {

				bone = this.bones[ i ];

				if ( bone ) {

					if ( bone.parent && bone.parent.isBone ) {

						bone.matrix.getInverse( bone.parent.matrixWorld );
						bone.matrix.multiply( bone.matrixWorld );

					} else {

						bone.matrix.copy( bone.matrixWorld );

					}

					bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );

				}

			}

		},

		update: function () {

			var bones = this.bones;
			var boneInverses = this.boneInverses;
			var boneMatrices = this.boneMatrices;
			var boneTexture = this.boneTexture;

			// flatten bone matrices to array

			for ( var i = 0, il = bones.length; i < il; i ++ ) {

				// compute the offset between the current and the original transform

				var matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;

				_offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
				_offsetMatrix.toArray( boneMatrices, i * 16 );

			}

			if ( boneTexture !== undefined ) {

				boneTexture.needsUpdate = true;

			}

		},

		clone: function () {

			return new Skeleton( this.bones, this.boneInverses );

		},

		getBoneByName: function ( name ) {

			for ( var i = 0, il = this.bones.length; i < il; i ++ ) {

				var bone = this.bones[ i ];

				if ( bone.name === name ) {

					return bone;

				}

			}

			return undefined;

		}

	} );

	/**
	 * @author mikael emtinger / http://gomo.se/
	 * @author alteredq / http://alteredqualia.com/
	 * @author ikerr / http://verold.com
	 */

	function Bone() {

		Object3D.call( this );

		this.type = 'Bone';

	}

	Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {

		constructor: Bone,

		isBone: true

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	var _instanceLocalMatrix = new Matrix4();
	var _instanceWorldMatrix = new Matrix4();

	var _instanceIntersects = [];

	var _mesh = new Mesh();

	function InstancedMesh( geometry, material, count ) {

		Mesh.call( this, geometry, material );

		this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 );

		this.count = count;

		this.frustumCulled = false;

	}

	InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {

		constructor: InstancedMesh,

		isInstancedMesh: true,

		getMatrixAt: function ( index, matrix ) {

			matrix.fromArray( this.instanceMatrix.array, index * 16 );

		},

		raycast: function ( raycaster, intersects ) {

			var matrixWorld = this.matrixWorld;
			var raycastTimes = this.count;

			_mesh.geometry = this.geometry;
			_mesh.material = this.material;

			if ( _mesh.material === undefined ) { return; }

			for ( var instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {

				// calculate the world matrix for each instance

				this.getMatrixAt( instanceId, _instanceLocalMatrix );

				_instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );

				// the mesh represents this single instance

				_mesh.matrixWorld = _instanceWorldMatrix;

				_mesh.raycast( raycaster, _instanceIntersects );

				// process the result of raycast

				if ( _instanceIntersects.length > 0 ) {

					_instanceIntersects[ 0 ].instanceId = instanceId;
					_instanceIntersects[ 0 ].object = this;

					intersects.push( _instanceIntersects[ 0 ] );

					_instanceIntersects.length = 0;

				}

			}

		},

		setMatrixAt: function ( index, matrix ) {

			matrix.toArray( this.instanceMatrix.array, index * 16 );

		},

		updateMorphTargets: function () {

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author alteredq / http://alteredqualia.com/
	 *
	 * parameters = {
	 *  color: <hex>,
	 *  opacity: <float>,
	 *
	 *  linewidth: <float>,
	 *  linecap: "round",
	 *  linejoin: "round"
	 * }
	 */

	function LineBasicMaterial( parameters ) {

		Material.call( this );

		this.type = 'LineBasicMaterial';

		this.color = new Color( 0xffffff );

		this.linewidth = 1;
		this.linecap = 'round';
		this.linejoin = 'round';

		this.setValues( parameters );

	}

	LineBasicMaterial.prototype = Object.create( Material.prototype );
	LineBasicMaterial.prototype.constructor = LineBasicMaterial;

	LineBasicMaterial.prototype.isLineBasicMaterial = true;

	LineBasicMaterial.prototype.copy = function ( source ) {

		Material.prototype.copy.call( this, source );

		this.color.copy( source.color );

		this.linewidth = source.linewidth;
		this.linecap = source.linecap;
		this.linejoin = source.linejoin;

		return this;

	};

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	var _start = new Vector3();
	var _end = new Vector3();
	var _inverseMatrix$1 = new Matrix4();
	var _ray$1 = new Ray();
	var _sphere$2 = new Sphere();

	function Line( geometry, material, mode ) {

		if ( mode === 1 ) {

			console.error( 'THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.' );

		}

		Object3D.call( this );

		this.type = 'Line';

		this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
		this.material = material !== undefined ? material : new LineBasicMaterial();

	}

	Line.prototype = Object.assign( Object.create( Object3D.prototype ), {

		constructor: Line,

		isLine: true,

		computeLineDistances: function () {

			var geometry = this.geometry;

			if ( geometry.isBufferGeometry ) {

				// we assume non-indexed geometry

				if ( geometry.index === null ) {

					var positionAttribute = geometry.attributes.position;
					var lineDistances = [ 0 ];

					for ( var i = 1, l = positionAttribute.count; i < l; i ++ ) {

						_start.fromBufferAttribute( positionAttribute, i - 1 );
						_end.fromBufferAttribute( positionAttribute, i );

						lineDistances[ i ] = lineDistances[ i - 1 ];
						lineDistances[ i ] += _start.distanceTo( _end );

					}

					geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );

				} else {

					console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );

				}

			} else if ( geometry.isGeometry ) {

				var vertices = geometry.vertices;
				var lineDistances = geometry.lineDistances;

				lineDistances[ 0 ] = 0;

				for ( var i = 1, l = vertices.length; i < l; i ++ ) {

					lineDistances[ i ] = lineDistances[ i - 1 ];
					lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] );

				}

			}

			return this;

		},

		raycast: function ( raycaster, intersects ) {

			var precision = raycaster.linePrecision;

			var geometry = this.geometry;
			var matrixWorld = this.matrixWorld;

			// Checking boundingSphere distance to ray

			if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); }

			_sphere$2.copy( geometry.boundingSphere );
			_sphere$2.applyMatrix4( matrixWorld );
			_sphere$2.radius += precision;

			if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) { return; }

			//

			_inverseMatrix$1.getInverse( matrixWorld );
			_ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );

			var localPrecision = precision / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
			var localPrecisionSq = localPrecision * localPrecision;

			var vStart = new Vector3();
			var vEnd = new Vector3();
			var interSegment = new Vector3();
			var interRay = new Vector3();
			var step = ( this && this.isLineSegments ) ? 2 : 1;

			if ( geometry.isBufferGeometry ) {

				var index = geometry.index;
				var attributes = geometry.attributes;
				var positions = attributes.position.array;

				if ( index !== null ) {

					var indices = index.array;

					for ( var i = 0, l = indices.length - 1; i < l; i += step ) {

						var a = indices[ i ];
						var b = indices[ i + 1 ];

						vStart.fromArray( positions, a * 3 );
						vEnd.fromArray( positions, b * 3 );

						var distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );

						if ( distSq > localPrecisionSq ) { continue; }

						interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation

						var distance = raycaster.ray.origin.distanceTo( interRay );

						if ( distance < raycaster.near || distance > raycaster.far ) { continue; }

						intersects.push( {

							distance: distance,
							// What do we want? intersection point on the ray or on the segment??
							// point: raycaster.ray.at( distance ),
							point: interSegment.clone().applyMatrix4( this.matrixWorld ),
							index: i,
							face: null,
							faceIndex: null,
							object: this

						} );

					}

				} else {

					for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {

						vStart.fromArray( positions, 3 * i );
						vEnd.fromArray( positions, 3 * i + 3 );

						var distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );

						if ( distSq > localPrecisionSq ) { continue; }

						interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation

						var distance = raycaster.ray.origin.distanceTo( interRay );

						if ( distance < raycaster.near || distance > raycaster.far ) { continue; }

						intersects.push( {

							distance: distance,
							// What do we want? intersection point on the ray or on the segment??
							// point: raycaster.ray.at( distance ),
							point: interSegment.clone().applyMatrix4( this.matrixWorld ),
							index: i,
							face: null,
							faceIndex: null,
							object: this

						} );

					}

				}

			} else if ( geometry.isGeometry ) {

				var vertices = geometry.vertices;
				var nbVertices = vertices.length;

				for ( var i = 0; i < nbVertices - 1; i += step ) {

					var distSq = _ray$1.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );

					if ( distSq > localPrecisionSq ) { continue; }

					interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation

					var distance = raycaster.ray.origin.distanceTo( interRay );

					if ( distance < raycaster.near || distance > raycaster.far ) { continue; }

					intersects.push( {

						distance: distance,
						// What do we want? intersection point on the ray or on the segment??
						// point: raycaster.ray.at( distance ),
						point: interSegment.clone().applyMatrix4( this.matrixWorld ),
						index: i,
						face: null,
						faceIndex: null,
						object: this

					} );

				}

			}

		},

		clone: function () {

			return new this.constructor( this.geometry, this.material ).copy( this );

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	var _start$1 = new Vector3();
	var _end$1 = new Vector3();

	function LineSegments( geometry, material ) {

		Line.call( this, geometry, material );

		this.type = 'LineSegments';

	}

	LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {

		constructor: LineSegments,

		isLineSegments: true,

		computeLineDistances: function () {

			var geometry = this.geometry;

			if ( geometry.isBufferGeometry ) {

				// we assume non-indexed geometry

				if ( geometry.index === null ) {

					var positionAttribute = geometry.attributes.position;
					var lineDistances = [];

					for ( var i = 0, l = positionAttribute.count; i < l; i += 2 ) {

						_start$1.fromBufferAttribute( positionAttribute, i );
						_end$1.fromBufferAttribute( positionAttribute, i + 1 );

						lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
						lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );

					}

					geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );

				} else {

					console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );

				}

			} else if ( geometry.isGeometry ) {

				var vertices = geometry.vertices;
				var lineDistances = geometry.lineDistances;

				for ( var i = 0, l = vertices.length; i < l; i += 2 ) {

					_start$1.copy( vertices[ i ] );
					_end$1.copy( vertices[ i + 1 ] );

					lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
					lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );

				}

			}

			return this;

		}

	} );

	/**
	 * @author mgreter / http://github.com/mgreter
	 */

	function LineLoop( geometry, material ) {

		Line.call( this, geometry, material );

		this.type = 'LineLoop';

	}

	LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {

		constructor: LineLoop,

		isLineLoop: true,

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author alteredq / http://alteredqualia.com/
	 *
	 * parameters = {
	 *  color: <hex>,
	 *  opacity: <float>,
	 *  map: new THREE.Texture( <Image> ),
	 *  alphaMap: new THREE.Texture( <Image> ),
	 *
	 *  size: <float>,
	 *  sizeAttenuation: <bool>
	 *
	 *  morphTargets: <bool>
	 * }
	 */

	function PointsMaterial( parameters ) {

		Material.call( this );

		this.type = 'PointsMaterial';

		this.color = new Color( 0xffffff );

		this.map = null;

		this.alphaMap = null;

		this.size = 1;
		this.sizeAttenuation = true;

		this.morphTargets = false;

		this.setValues( parameters );

	}

	PointsMaterial.prototype = Object.create( Material.prototype );
	PointsMaterial.prototype.constructor = PointsMaterial;

	PointsMaterial.prototype.isPointsMaterial = true;

	PointsMaterial.prototype.copy = function ( source ) {

		Material.prototype.copy.call( this, source );

		this.color.copy( source.color );

		this.map = source.map;

		this.alphaMap = source.alphaMap;

		this.size = source.size;
		this.sizeAttenuation = source.sizeAttenuation;

		this.morphTargets = source.morphTargets;

		return this;

	};

	/**
	 * @author alteredq / http://alteredqualia.com/
	 */

	var _inverseMatrix$2 = new Matrix4();
	var _ray$2 = new Ray();
	var _sphere$3 = new Sphere();
	var _position$1 = new Vector3();

	function Points( geometry, material ) {

		Object3D.call( this );

		this.type = 'Points';

		this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
		this.material = material !== undefined ? material : new PointsMaterial();

		this.updateMorphTargets();

	}

	Points.prototype = Object.assign( Object.create( Object3D.prototype ), {

		constructor: Points,

		isPoints: true,

		raycast: function ( raycaster, intersects ) {

			var geometry = this.geometry;
			var matrixWorld = this.matrixWorld;
			var threshold = raycaster.params.Points.threshold;

			// Checking boundingSphere distance to ray

			if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); }

			_sphere$3.copy( geometry.boundingSphere );
			_sphere$3.applyMatrix4( matrixWorld );
			_sphere$3.radius += threshold;

			if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) { return; }

			//

			_inverseMatrix$2.getInverse( matrixWorld );
			_ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );

			var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
			var localThresholdSq = localThreshold * localThreshold;

			if ( geometry.isBufferGeometry ) {

				var index = geometry.index;
				var attributes = geometry.attributes;
				var positions = attributes.position.array;

				if ( index !== null ) {

					var indices = index.array;

					for ( var i = 0, il = indices.length; i < il; i ++ ) {

						var a = indices[ i ];

						_position$1.fromArray( positions, a * 3 );

						testPoint( _position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this );

					}

				} else {

					for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {

						_position$1.fromArray( positions, i * 3 );

						testPoint( _position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this );

					}

				}

			} else {

				var vertices = geometry.vertices;

				for ( var i = 0, l = vertices.length; i < l; i ++ ) {

					testPoint( vertices[ i ], i, localThresholdSq, matrixWorld, raycaster, intersects, this );

				}

			}

		},

		updateMorphTargets: function () {

			var geometry = this.geometry;
			var m, ml, name;

			if ( geometry.isBufferGeometry ) {

				var morphAttributes = geometry.morphAttributes;
				var keys = Object.keys( morphAttributes );

				if ( keys.length > 0 ) {

					var morphAttribute = morphAttributes[ keys[ 0 ] ];

					if ( morphAttribute !== undefined ) {

						this.morphTargetInfluences = [];
						this.morphTargetDictionary = {};

						for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {

							name = morphAttribute[ m ].name || String( m );

							this.morphTargetInfluences.push( 0 );
							this.morphTargetDictionary[ name ] = m;

						}

					}

				}

			} else {

				var morphTargets = geometry.morphTargets;

				if ( morphTargets !== undefined && morphTargets.length > 0 ) {

					console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );

				}

			}

		},

		clone: function () {

			return new this.constructor( this.geometry, this.material ).copy( this );

		}

	} );

	function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {

		var rayPointDistanceSq = _ray$2.distanceSqToPoint( point );

		if ( rayPointDistanceSq < localThresholdSq ) {

			var intersectPoint = new Vector3();

			_ray$2.closestPointToPoint( point, intersectPoint );
			intersectPoint.applyMatrix4( matrixWorld );

			var distance = raycaster.ray.origin.distanceTo( intersectPoint );

			if ( distance < raycaster.near || distance > raycaster.far ) { return; }

			intersects.push( {

				distance: distance,
				distanceToRay: Math.sqrt( rayPointDistanceSq ),
				point: intersectPoint,
				index: index,
				face: null,
				object: object

			} );

		}

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {

		Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );

		this.format = format !== undefined ? format : RGBFormat;

		this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
		this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;

		this.generateMipmaps = false;

	}

	VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {

		constructor: VideoTexture,

		isVideoTexture: true,

		update: function () {

			var video = this.image;

			if ( video.readyState >= video.HAVE_CURRENT_DATA ) {

				this.needsUpdate = true;

			}

		}

	} );

	/**
	 * @author alteredq / http://alteredqualia.com/
	 */

	function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {

		Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );

		this.image = { width: width, height: height };
		this.mipmaps = mipmaps;

		// no flipping for cube textures
		// (also flipping doesn't work for compressed textures )

		this.flipY = false;

		// can't generate mipmaps for compressed textures
		// mips must be embedded in DDS files

		this.generateMipmaps = false;

	}

	CompressedTexture.prototype = Object.create( Texture.prototype );
	CompressedTexture.prototype.constructor = CompressedTexture;

	CompressedTexture.prototype.isCompressedTexture = true;

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {

		Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );

		this.needsUpdate = true;

	}

	CanvasTexture.prototype = Object.create( Texture.prototype );
	CanvasTexture.prototype.constructor = CanvasTexture;
	CanvasTexture.prototype.isCanvasTexture = true;

	/**
	 * @author Matt DesLauriers / @mattdesl
	 * @author atix / arthursilber.de
	 */

	function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {

		format = format !== undefined ? format : DepthFormat;

		if ( format !== DepthFormat && format !== DepthStencilFormat ) {

			throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );

		}

		if ( type === undefined && format === DepthFormat ) { type = UnsignedShortType; }
		if ( type === undefined && format === DepthStencilFormat ) { type = UnsignedInt248Type; }

		Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );

		this.image = { width: width, height: height };

		this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
		this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;

		this.flipY = false;
		this.generateMipmaps	= false;

	}

	DepthTexture.prototype = Object.create( Texture.prototype );
	DepthTexture.prototype.constructor = DepthTexture;
	DepthTexture.prototype.isDepthTexture = true;

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	function WireframeGeometry( geometry ) {

		BufferGeometry.call( this );

		this.type = 'WireframeGeometry';

		// buffer

		var vertices = [];

		// helper variables

		var i, j, l, o, ol;
		var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
		var key, keys = [ 'a', 'b', 'c' ];
		var vertex;

		// different logic for Geometry and BufferGeometry

		if ( geometry && geometry.isGeometry ) {

			// create a data structure that contains all edges without duplicates

			var faces = geometry.faces;

			for ( i = 0, l = faces.length; i < l; i ++ ) {

				var face = faces[ i ];

				for ( j = 0; j < 3; j ++ ) {

					edge1 = face[ keys[ j ] ];
					edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
					edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
					edge[ 1 ] = Math.max( edge1, edge2 );

					key = edge[ 0 ] + ',' + edge[ 1 ];

					if ( edges[ key ] === undefined ) {

						edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };

					}

				}

			}

			// generate vertices

			for ( key in edges ) {

				e = edges[ key ];

				vertex = geometry.vertices[ e.index1 ];
				vertices.push( vertex.x, vertex.y, vertex.z );

				vertex = geometry.vertices[ e.index2 ];
				vertices.push( vertex.x, vertex.y, vertex.z );

			}

		} else if ( geometry && geometry.isBufferGeometry ) {

			var position, indices, groups;
			var group, start, count;
			var index1, index2;

			vertex = new Vector3();

			if ( geometry.index !== null ) {

				// indexed BufferGeometry

				position = geometry.attributes.position;
				indices = geometry.index;
				groups = geometry.groups;

				if ( groups.length === 0 ) {

					groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];

				}

				// create a data structure that contains all eges without duplicates

				for ( o = 0, ol = groups.length; o < ol; ++ o ) {

					group = groups[ o ];

					start = group.start;
					count = group.count;

					for ( i = start, l = ( start + count ); i < l; i += 3 ) {

						for ( j = 0; j < 3; j ++ ) {

							edge1 = indices.getX( i + j );
							edge2 = indices.getX( i + ( j + 1 ) % 3 );
							edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
							edge[ 1 ] = Math.max( edge1, edge2 );

							key = edge[ 0 ] + ',' + edge[ 1 ];

							if ( edges[ key ] === undefined ) {

								edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };

							}

						}

					}

				}

				// generate vertices

				for ( key in edges ) {

					e = edges[ key ];

					vertex.fromBufferAttribute( position, e.index1 );
					vertices.push( vertex.x, vertex.y, vertex.z );

					vertex.fromBufferAttribute( position, e.index2 );
					vertices.push( vertex.x, vertex.y, vertex.z );

				}

			} else {

				// non-indexed BufferGeometry

				position = geometry.attributes.position;

				for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {

					for ( j = 0; j < 3; j ++ ) {

						// three edges per triangle, an edge is represented as (index1, index2)
						// e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)

						index1 = 3 * i + j;
						vertex.fromBufferAttribute( position, index1 );
						vertices.push( vertex.x, vertex.y, vertex.z );

						index2 = 3 * i + ( ( j + 1 ) % 3 );
						vertex.fromBufferAttribute( position, index2 );
						vertices.push( vertex.x, vertex.y, vertex.z );

					}

				}

			}

		}

		// build geometry

		this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );

	}

	WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
	WireframeGeometry.prototype.constructor = WireframeGeometry;

	/**
	 * @author zz85 / https://github.com/zz85
	 * @author Mugen87 / https://github.com/Mugen87
	 *
	 * Parametric Surfaces Geometry
	 * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
	 */

	// ParametricGeometry

	function ParametricGeometry( func, slices, stacks ) {

		Geometry.call( this );

		this.type = 'ParametricGeometry';

		this.parameters = {
			func: func,
			slices: slices,
			stacks: stacks
		};

		this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
		this.mergeVertices();

	}

	ParametricGeometry.prototype = Object.create( Geometry.prototype );
	ParametricGeometry.prototype.constructor = ParametricGeometry;

	// ParametricBufferGeometry

	function ParametricBufferGeometry( func, slices, stacks ) {

		BufferGeometry.call( this );

		this.type = 'ParametricBufferGeometry';

		this.parameters = {
			func: func,
			slices: slices,
			stacks: stacks
		};

		// buffers

		var indices = [];
		var vertices = [];
		var normals = [];
		var uvs = [];

		var EPS = 0.00001;

		var normal = new Vector3();

		var p0 = new Vector3(), p1 = new Vector3();
		var pu = new Vector3(), pv = new Vector3();

		var i, j;

		if ( func.length < 3 ) {

			console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );

		}

		// generate vertices, normals and uvs

		var sliceCount = slices + 1;

		for ( i = 0; i <= stacks; i ++ ) {

			var v = i / stacks;

			for ( j = 0; j <= slices; j ++ ) {

				var u = j / slices;

				// vertex

				func( u, v, p0 );
				vertices.push( p0.x, p0.y, p0.z );

				// normal

				// approximate tangent vectors via finite differences

				if ( u - EPS >= 0 ) {

					func( u - EPS, v, p1 );
					pu.subVectors( p0, p1 );

				} else {

					func( u + EPS, v, p1 );
					pu.subVectors( p1, p0 );

				}

				if ( v - EPS >= 0 ) {

					func( u, v - EPS, p1 );
					pv.subVectors( p0, p1 );

				} else {

					func( u, v + EPS, p1 );
					pv.subVectors( p1, p0 );

				}

				// cross product of tangent vectors returns surface normal

				normal.crossVectors( pu, pv ).normalize();
				normals.push( normal.x, normal.y, normal.z );

				// uv

				uvs.push( u, v );

			}

		}

		// generate indices

		for ( i = 0; i < stacks; i ++ ) {

			for ( j = 0; j < slices; j ++ ) {

				var a = i * sliceCount + j;
				var b = i * sliceCount + j + 1;
				var c = ( i + 1 ) * sliceCount + j + 1;
				var d = ( i + 1 ) * sliceCount + j;

				// faces one and two

				indices.push( a, b, d );
				indices.push( b, c, d );

			}

		}

		// build geometry

		this.setIndex( indices );
		this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
		this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

	}

	ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
	ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;

	/**
	 * @author clockworkgeek / https://github.com/clockworkgeek
	 * @author timothypratley / https://github.com/timothypratley
	 * @author WestLangley / http://github.com/WestLangley
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	// PolyhedronGeometry

	function PolyhedronGeometry( vertices, indices, radius, detail ) {

		Geometry.call( this );

		this.type = 'PolyhedronGeometry';

		this.parameters = {
			vertices: vertices,
			indices: indices,
			radius: radius,
			detail: detail
		};

		this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
		this.mergeVertices();

	}

	PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
	PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;

	// PolyhedronBufferGeometry

	function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {

		BufferGeometry.call( this );

		this.type = 'PolyhedronBufferGeometry';

		this.parameters = {
			vertices: vertices,
			indices: indices,
			radius: radius,
			detail: detail
		};

		radius = radius || 1;
		detail = detail || 0;

		// default buffer data

		var vertexBuffer = [];
		var uvBuffer = [];

		// the subdivision creates the vertex buffer data

		subdivide( detail );

		// all vertices should lie on a conceptual sphere with a given radius

		applyRadius( radius );

		// finally, create the uv data

		generateUVs();

		// build non-indexed geometry

		this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
		this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
		this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );

		if ( detail === 0 ) {

			this.computeVertexNormals(); // flat normals

		} else {

			this.normalizeNormals(); // smooth normals

		}

		// helper functions

		function subdivide( detail ) {

			var a = new Vector3();
			var b = new Vector3();
			var c = new Vector3();

			// iterate over all faces and apply a subdivison with the given detail value

			for ( var i = 0; i < indices.length; i += 3 ) {

				// get the vertices of the face

				getVertexByIndex( indices[ i + 0 ], a );
				getVertexByIndex( indices[ i + 1 ], b );
				getVertexByIndex( indices[ i + 2 ], c );

				// perform subdivision

				subdivideFace( a, b, c, detail );

			}

		}

		function subdivideFace( a, b, c, detail ) {

			var cols = Math.pow( 2, detail );

			// we use this multidimensional array as a data structure for creating the subdivision

			var v = [];

			var i, j;

			// construct all of the vertices for this subdivision

			for ( i = 0; i <= cols; i ++ ) {

				v[ i ] = [];

				var aj = a.clone().lerp( c, i / cols );
				var bj = b.clone().lerp( c, i / cols );

				var rows = cols - i;

				for ( j = 0; j <= rows; j ++ ) {

					if ( j === 0 && i === cols ) {

						v[ i ][ j ] = aj;

					} else {

						v[ i ][ j ] = aj.clone().lerp( bj, j / rows );

					}

				}

			}

			// construct all of the faces

			for ( i = 0; i < cols; i ++ ) {

				for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {

					var k = Math.floor( j / 2 );

					if ( j % 2 === 0 ) {

						pushVertex( v[ i ][ k + 1 ] );
						pushVertex( v[ i + 1 ][ k ] );
						pushVertex( v[ i ][ k ] );

					} else {

						pushVertex( v[ i ][ k + 1 ] );
						pushVertex( v[ i + 1 ][ k + 1 ] );
						pushVertex( v[ i + 1 ][ k ] );

					}

				}

			}

		}

		function applyRadius( radius ) {

			var vertex = new Vector3();

			// iterate over the entire buffer and apply the radius to each vertex

			for ( var i = 0; i < vertexBuffer.length; i += 3 ) {

				vertex.x = vertexBuffer[ i + 0 ];
				vertex.y = vertexBuffer[ i + 1 ];
				vertex.z = vertexBuffer[ i + 2 ];

				vertex.normalize().multiplyScalar( radius );

				vertexBuffer[ i + 0 ] = vertex.x;
				vertexBuffer[ i + 1 ] = vertex.y;
				vertexBuffer[ i + 2 ] = vertex.z;

			}

		}

		function generateUVs() {

			var vertex = new Vector3();

			for ( var i = 0; i < vertexBuffer.length; i += 3 ) {

				vertex.x = vertexBuffer[ i + 0 ];
				vertex.y = vertexBuffer[ i + 1 ];
				vertex.z = vertexBuffer[ i + 2 ];

				var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
				var v = inclination( vertex ) / Math.PI + 0.5;
				uvBuffer.push( u, 1 - v );

			}

			correctUVs();

			correctSeam();

		}

		function correctSeam() {

			// handle case when face straddles the seam, see #3269

			for ( var i = 0; i < uvBuffer.length; i += 6 ) {

				// uv data of a single face

				var x0 = uvBuffer[ i + 0 ];
				var x1 = uvBuffer[ i + 2 ];
				var x2 = uvBuffer[ i + 4 ];

				var max = Math.max( x0, x1, x2 );
				var min = Math.min( x0, x1, x2 );

				// 0.9 is somewhat arbitrary

				if ( max > 0.9 && min < 0.1 ) {

					if ( x0 < 0.2 ) { uvBuffer[ i + 0 ] += 1; }
					if ( x1 < 0.2 ) { uvBuffer[ i + 2 ] += 1; }
					if ( x2 < 0.2 ) { uvBuffer[ i + 4 ] += 1; }

				}

			}

		}

		function pushVertex( vertex ) {

			vertexBuffer.push( vertex.x, vertex.y, vertex.z );

		}

		function getVertexByIndex( index, vertex ) {

			var stride = index * 3;

			vertex.x = vertices[ stride + 0 ];
			vertex.y = vertices[ stride + 1 ];
			vertex.z = vertices[ stride + 2 ];

		}

		function correctUVs() {

			var a = new Vector3();
			var b = new Vector3();
			var c = new Vector3();

			var centroid = new Vector3();

			var uvA = new Vector2();
			var uvB = new Vector2();
			var uvC = new Vector2();

			for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {

				a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
				b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
				c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );

				uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
				uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
				uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );

				centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );

				var azi = azimuth( centroid );

				correctUV( uvA, j + 0, a, azi );
				correctUV( uvB, j + 2, b, azi );
				correctUV( uvC, j + 4, c, azi );

			}

		}

		function correctUV( uv, stride, vector, azimuth ) {

			if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {

				uvBuffer[ stride ] = uv.x - 1;

			}

			if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {

				uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;

			}

		}

		// Angle around the Y axis, counter-clockwise when looking from above.

		function azimuth( vector ) {

			return Math.atan2( vector.z, - vector.x );

		}


		// Angle above the XZ plane.

		function inclination( vector ) {

			return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );

		}

	}

	PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
	PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;

	/**
	 * @author timothypratley / https://github.com/timothypratley
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	// TetrahedronGeometry

	function TetrahedronGeometry( radius, detail ) {

		Geometry.call( this );

		this.type = 'TetrahedronGeometry';

		this.parameters = {
			radius: radius,
			detail: detail
		};

		this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
		this.mergeVertices();

	}

	TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
	TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;

	// TetrahedronBufferGeometry

	function TetrahedronBufferGeometry( radius, detail ) {

		var vertices = [
			1, 1, 1, 	- 1, - 1, 1, 	- 1, 1, - 1, 	1, - 1, - 1
		];

		var indices = [
			2, 1, 0, 	0, 3, 2,	1, 3, 0,	2, 3, 1
		];

		PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );

		this.type = 'TetrahedronBufferGeometry';

		this.parameters = {
			radius: radius,
			detail: detail
		};

	}

	TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
	TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;

	/**
	 * @author timothypratley / https://github.com/timothypratley
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	// OctahedronGeometry

	function OctahedronGeometry( radius, detail ) {

		Geometry.call( this );

		this.type = 'OctahedronGeometry';

		this.parameters = {
			radius: radius,
			detail: detail
		};

		this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
		this.mergeVertices();

	}

	OctahedronGeometry.prototype = Object.create( Geometry.prototype );
	OctahedronGeometry.prototype.constructor = OctahedronGeometry;

	// OctahedronBufferGeometry

	function OctahedronBufferGeometry( radius, detail ) {

		var vertices = [
			1, 0, 0, 	- 1, 0, 0,	0, 1, 0,
			0, - 1, 0, 	0, 0, 1,	0, 0, - 1
		];

		var indices = [
			0, 2, 4,	0, 4, 3,	0, 3, 5,
			0, 5, 2,	1, 2, 5,	1, 5, 3,
			1, 3, 4,	1, 4, 2
		];

		PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );

		this.type = 'OctahedronBufferGeometry';

		this.parameters = {
			radius: radius,
			detail: detail
		};

	}

	OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
	OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;

	/**
	 * @author timothypratley / https://github.com/timothypratley
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	// IcosahedronGeometry

	function IcosahedronGeometry( radius, detail ) {

		Geometry.call( this );

		this.type = 'IcosahedronGeometry';

		this.parameters = {
			radius: radius,
			detail: detail
		};

		this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
		this.mergeVertices();

	}

	IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
	IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;

	// IcosahedronBufferGeometry

	function IcosahedronBufferGeometry( radius, detail ) {

		var t = ( 1 + Math.sqrt( 5 ) ) / 2;

		var vertices = [
			- 1, t, 0, 	1, t, 0, 	- 1, - t, 0, 	1, - t, 0,
			 0, - 1, t, 	0, 1, t,	0, - 1, - t, 	0, 1, - t,
			 t, 0, - 1, 	t, 0, 1, 	- t, 0, - 1, 	- t, 0, 1
		];

		var indices = [
			 0, 11, 5, 	0, 5, 1, 	0, 1, 7, 	0, 7, 10, 	0, 10, 11,
			 1, 5, 9, 	5, 11, 4,	11, 10, 2,	10, 7, 6,	7, 1, 8,
			 3, 9, 4, 	3, 4, 2,	3, 2, 6,	3, 6, 8,	3, 8, 9,
			 4, 9, 5, 	2, 4, 11,	6, 2, 10,	8, 6, 7,	9, 8, 1
		];

		PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );

		this.type = 'IcosahedronBufferGeometry';

		this.parameters = {
			radius: radius,
			detail: detail
		};

	}

	IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
	IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;

	/**
	 * @author Abe Pazos / https://hamoid.com
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	// DodecahedronGeometry

	function DodecahedronGeometry( radius, detail ) {

		Geometry.call( this );

		this.type = 'DodecahedronGeometry';

		this.parameters = {
			radius: radius,
			detail: detail
		};

		this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
		this.mergeVertices();

	}

	DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
	DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;

	// DodecahedronBufferGeometry

	function DodecahedronBufferGeometry( radius, detail ) {

		var t = ( 1 + Math.sqrt( 5 ) ) / 2;
		var r = 1 / t;

		var vertices = [

			// (±1, ±1, ±1)
			- 1, - 1, - 1,	- 1, - 1, 1,
			- 1, 1, - 1, - 1, 1, 1,
			1, - 1, - 1, 1, - 1, 1,
			1, 1, - 1, 1, 1, 1,

			// (0, ±1/φ, ±φ)
			 0, - r, - t, 0, - r, t,
			 0, r, - t, 0, r, t,

			// (±1/φ, ±φ, 0)
			- r, - t, 0, - r, t, 0,
			 r, - t, 0, r, t, 0,

			// (±φ, 0, ±1/φ)
			- t, 0, - r, t, 0, - r,
			- t, 0, r, t, 0, r
		];

		var indices = [
			3, 11, 7, 	3, 7, 15, 	3, 15, 13,
			7, 19, 17, 	7, 17, 6, 	7, 6, 15,
			17, 4, 8, 	17, 8, 10, 	17, 10, 6,
			8, 0, 16, 	8, 16, 2, 	8, 2, 10,
			0, 12, 1, 	0, 1, 18, 	0, 18, 16,
			6, 10, 2, 	6, 2, 13, 	6, 13, 15,
			2, 16, 18, 	2, 18, 3, 	2, 3, 13,
			18, 1, 9, 	18, 9, 11, 	18, 11, 3,
			4, 14, 12, 	4, 12, 0, 	4, 0, 8,
			11, 9, 5, 	11, 5, 19, 	11, 19, 7,
			19, 5, 14, 	19, 14, 4, 	19, 4, 17,
			1, 12, 14, 	1, 14, 5, 	1, 5, 9
		];

		PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );

		this.type = 'DodecahedronBufferGeometry';

		this.parameters = {
			radius: radius,
			detail: detail
		};

	}

	DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
	DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;

	/**
	 * @author oosmoxiecode / https://github.com/oosmoxiecode
	 * @author WestLangley / https://github.com/WestLangley
	 * @author zz85 / https://github.com/zz85
	 * @author miningold / https://github.com/miningold
	 * @author jonobr1 / https://github.com/jonobr1
	 * @author Mugen87 / https://github.com/Mugen87
	 *
	 */

	// TubeGeometry

	function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {

		Geometry.call( this );

		this.type = 'TubeGeometry';

		this.parameters = {
			path: path,
			tubularSegments: tubularSegments,
			radius: radius,
			radialSegments: radialSegments,
			closed: closed
		};

		if ( taper !== undefined ) { console.warn( 'THREE.TubeGeometry: taper has been removed.' ); }

		var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );

		// expose internals

		this.tangents = bufferGeometry.tangents;
		this.normals = bufferGeometry.normals;
		this.binormals = bufferGeometry.binormals;

		// create geometry

		this.fromBufferGeometry( bufferGeometry );
		this.mergeVertices();

	}

	TubeGeometry.prototype = Object.create( Geometry.prototype );
	TubeGeometry.prototype.constructor = TubeGeometry;

	// TubeBufferGeometry

	function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {

		BufferGeometry.call( this );

		this.type = 'TubeBufferGeometry';

		this.parameters = {
			path: path,
			tubularSegments: tubularSegments,
			radius: radius,
			radialSegments: radialSegments,
			closed: closed
		};

		tubularSegments = tubularSegments || 64;
		radius = radius || 1;
		radialSegments = radialSegments || 8;
		closed = closed || false;

		var frames = path.computeFrenetFrames( tubularSegments, closed );

		// expose internals

		this.tangents = frames.tangents;
		this.normals = frames.normals;
		this.binormals = frames.binormals;

		// helper variables

		var vertex = new Vector3();
		var normal = new Vector3();
		var uv = new Vector2();
		var P = new Vector3();

		var i, j;

		// buffer

		var vertices = [];
		var normals = [];
		var uvs = [];
		var indices = [];

		// create buffer data

		generateBufferData();

		// build geometry

		this.setIndex( indices );
		this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
		this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

		// functions

		function generateBufferData() {

			for ( i = 0; i < tubularSegments; i ++ ) {

				generateSegment( i );

			}

			// if the geometry is not closed, generate the last row of vertices and normals
			// at the regular position on the given path
			//
			// if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)

			generateSegment( ( closed === false ) ? tubularSegments : 0 );

			// uvs are generated in a separate function.
			// this makes it easy compute correct values for closed geometries

			generateUVs();

			// finally create faces

			generateIndices();

		}

		function generateSegment( i ) {

			// we use getPointAt to sample evenly distributed points from the given path

			P = path.getPointAt( i / tubularSegments, P );

			// retrieve corresponding normal and binormal

			var N = frames.normals[ i ];
			var B = frames.binormals[ i ];

			// generate normals and vertices for the current segment

			for ( j = 0; j <= radialSegments; j ++ ) {

				var v = j / radialSegments * Math.PI * 2;

				var sin = Math.sin( v );
				var cos = - Math.cos( v );

				// normal

				normal.x = ( cos * N.x + sin * B.x );
				normal.y = ( cos * N.y + sin * B.y );
				normal.z = ( cos * N.z + sin * B.z );
				normal.normalize();

				normals.push( normal.x, normal.y, normal.z );

				// vertex

				vertex.x = P.x + radius * normal.x;
				vertex.y = P.y + radius * normal.y;
				vertex.z = P.z + radius * normal.z;

				vertices.push( vertex.x, vertex.y, vertex.z );

			}

		}

		function generateIndices() {

			for ( j = 1; j <= tubularSegments; j ++ ) {

				for ( i = 1; i <= radialSegments; i ++ ) {

					var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
					var b = ( radialSegments + 1 ) * j + ( i - 1 );
					var c = ( radialSegments + 1 ) * j + i;
					var d = ( radialSegments + 1 ) * ( j - 1 ) + i;

					// faces

					indices.push( a, b, d );
					indices.push( b, c, d );

				}

			}

		}

		function generateUVs() {

			for ( i = 0; i <= tubularSegments; i ++ ) {

				for ( j = 0; j <= radialSegments; j ++ ) {

					uv.x = i / tubularSegments;
					uv.y = j / radialSegments;

					uvs.push( uv.x, uv.y );

				}

			}

		}

	}

	TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
	TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;

	TubeBufferGeometry.prototype.toJSON = function () {

		var data = BufferGeometry.prototype.toJSON.call( this );

		data.path = this.parameters.path.toJSON();

		return data;

	};

	/**
	 * @author oosmoxiecode
	 * @author Mugen87 / https://github.com/Mugen87
	 *
	 * based on http://www.blackpawn.com/texts/pqtorus/
	 */

	// TorusKnotGeometry

	function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {

		Geometry.call( this );

		this.type = 'TorusKnotGeometry';

		this.parameters = {
			radius: radius,
			tube: tube,
			tubularSegments: tubularSegments,
			radialSegments: radialSegments,
			p: p,
			q: q
		};

		if ( heightScale !== undefined ) { console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' ); }

		this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
		this.mergeVertices();

	}

	TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
	TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;

	// TorusKnotBufferGeometry

	function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {

		BufferGeometry.call( this );

		this.type = 'TorusKnotBufferGeometry';

		this.parameters = {
			radius: radius,
			tube: tube,
			tubularSegments: tubularSegments,
			radialSegments: radialSegments,
			p: p,
			q: q
		};

		radius = radius || 1;
		tube = tube || 0.4;
		tubularSegments = Math.floor( tubularSegments ) || 64;
		radialSegments = Math.floor( radialSegments ) || 8;
		p = p || 2;
		q = q || 3;

		// buffers

		var indices = [];
		var vertices = [];
		var normals = [];
		var uvs = [];

		// helper variables

		var i, j;

		var vertex = new Vector3();
		var normal = new Vector3();

		var P1 = new Vector3();
		var P2 = new Vector3();

		var B = new Vector3();
		var T = new Vector3();
		var N = new Vector3();

		// generate vertices, normals and uvs

		for ( i = 0; i <= tubularSegments; ++ i ) {

			// the radian "u" is used to calculate the position on the torus curve of the current tubular segement

			var u = i / tubularSegments * p * Math.PI * 2;

			// now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
			// these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions

			calculatePositionOnCurve( u, p, q, radius, P1 );
			calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );

			// calculate orthonormal basis

			T.subVectors( P2, P1 );
			N.addVectors( P2, P1 );
			B.crossVectors( T, N );
			N.crossVectors( B, T );

			// normalize B, N. T can be ignored, we don't use it

			B.normalize();
			N.normalize();

			for ( j = 0; j <= radialSegments; ++ j ) {

				// now calculate the vertices. they are nothing more than an extrusion of the torus curve.
				// because we extrude a shape in the xy-plane, there is no need to calculate a z-value.

				var v = j / radialSegments * Math.PI * 2;
				var cx = - tube * Math.cos( v );
				var cy = tube * Math.sin( v );

				// now calculate the final vertex position.
				// first we orient the extrusion with our basis vectos, then we add it to the current position on the curve

				vertex.x = P1.x + ( cx * N.x + cy * B.x );
				vertex.y = P1.y + ( cx * N.y + cy * B.y );
				vertex.z = P1.z + ( cx * N.z + cy * B.z );

				vertices.push( vertex.x, vertex.y, vertex.z );

				// normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)

				normal.subVectors( vertex, P1 ).normalize();

				normals.push( normal.x, normal.y, normal.z );

				// uv

				uvs.push( i / tubularSegments );
				uvs.push( j / radialSegments );

			}

		}

		// generate indices

		for ( j = 1; j <= tubularSegments; j ++ ) {

			for ( i = 1; i <= radialSegments; i ++ ) {

				// indices

				var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
				var b = ( radialSegments + 1 ) * j + ( i - 1 );
				var c = ( radialSegments + 1 ) * j + i;
				var d = ( radialSegments + 1 ) * ( j - 1 ) + i;

				// faces

				indices.push( a, b, d );
				indices.push( b, c, d );

			}

		}

		// build geometry

		this.setIndex( indices );
		this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
		this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

		// this function calculates the current position on the torus curve

		function calculatePositionOnCurve( u, p, q, radius, position ) {

			var cu = Math.cos( u );
			var su = Math.sin( u );
			var quOverP = q / p * u;
			var cs = Math.cos( quOverP );

			position.x = radius * ( 2 + cs ) * 0.5 * cu;
			position.y = radius * ( 2 + cs ) * su * 0.5;
			position.z = radius * Math.sin( quOverP ) * 0.5;

		}

	}

	TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
	TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;

	/**
	 * @author oosmoxiecode
	 * @author mrdoob / http://mrdoob.com/
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	// TorusGeometry

	function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {

		Geometry.call( this );

		this.type = 'TorusGeometry';

		this.parameters = {
			radius: radius,
			tube: tube,
			radialSegments: radialSegments,
			tubularSegments: tubularSegments,
			arc: arc
		};

		this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
		this.mergeVertices();

	}

	TorusGeometry.prototype = Object.create( Geometry.prototype );
	TorusGeometry.prototype.constructor = TorusGeometry;

	// TorusBufferGeometry

	function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {

		BufferGeometry.call( this );

		this.type = 'TorusBufferGeometry';

		this.parameters = {
			radius: radius,
			tube: tube,
			radialSegments: radialSegments,
			tubularSegments: tubularSegments,
			arc: arc
		};

		radius = radius || 1;
		tube = tube || 0.4;
		radialSegments = Math.floor( radialSegments ) || 8;
		tubularSegments = Math.floor( tubularSegments ) || 6;
		arc = arc || Math.PI * 2;

		// buffers

		var indices = [];
		var vertices = [];
		var normals = [];
		var uvs = [];

		// helper variables

		var center = new Vector3();
		var vertex = new Vector3();
		var normal = new Vector3();

		var j, i;

		// generate vertices, normals and uvs

		for ( j = 0; j <= radialSegments; j ++ ) {

			for ( i = 0; i <= tubularSegments; i ++ ) {

				var u = i / tubularSegments * arc;
				var v = j / radialSegments * Math.PI * 2;

				// vertex

				vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
				vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
				vertex.z = tube * Math.sin( v );

				vertices.push( vertex.x, vertex.y, vertex.z );

				// normal

				center.x = radius * Math.cos( u );
				center.y = radius * Math.sin( u );
				normal.subVectors( vertex, center ).normalize();

				normals.push( normal.x, normal.y, normal.z );

				// uv

				uvs.push( i / tubularSegments );
				uvs.push( j / radialSegments );

			}

		}

		// generate indices

		for ( j = 1; j <= radialSegments; j ++ ) {

			for ( i = 1; i <= tubularSegments; i ++ ) {

				// indices

				var a = ( tubularSegments + 1 ) * j + i - 1;
				var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
				var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
				var d = ( tubularSegments + 1 ) * j + i;

				// faces

				indices.push( a, b, d );
				indices.push( b, c, d );

			}

		}

		// build geometry

		this.setIndex( indices );
		this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
		this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

	}

	TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
	TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;

	/**
	 * @author Mugen87 / https://github.com/Mugen87
	 * Port from https://github.com/mapbox/earcut (v2.1.5)
	 */

	var Earcut = {

		triangulate: function ( data, holeIndices, dim ) {

			dim = dim || 2;

			var hasHoles = holeIndices && holeIndices.length,
				outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length,
				outerNode = linkedList( data, 0, outerLen, dim, true ),
				triangles = [];

			if ( ! outerNode || outerNode.next === outerNode.prev ) { return triangles; }

			var minX, minY, maxX, maxY, x, y, invSize;

			if ( hasHoles ) { outerNode = eliminateHoles( data, holeIndices, outerNode, dim ); }

			// if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
			if ( data.length > 80 * dim ) {

				minX = maxX = data[ 0 ];
				minY = maxY = data[ 1 ];

				for ( var i = dim; i < outerLen; i += dim ) {

					x = data[ i ];
					y = data[ i + 1 ];
					if ( x < minX ) { minX = x; }
					if ( y < minY ) { minY = y; }
					if ( x > maxX ) { maxX = x; }
					if ( y > maxY ) { maxY = y; }

				}

				// minX, minY and invSize are later used to transform coords into integers for z-order calculation
				invSize = Math.max( maxX - minX, maxY - minY );
				invSize = invSize !== 0 ? 1 / invSize : 0;

			}

			earcutLinked( outerNode, triangles, dim, minX, minY, invSize );

			return triangles;

		}

	};

	// create a circular doubly linked list from polygon points in the specified winding order
	function linkedList( data, start, end, dim, clockwise ) {

		var i, last;

		if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {

			for ( i = start; i < end; i += dim ) { last = insertNode( i, data[ i ], data[ i + 1 ], last ); }

		} else {

			for ( i = end - dim; i >= start; i -= dim ) { last = insertNode( i, data[ i ], data[ i + 1 ], last ); }

		}

		if ( last && equals( last, last.next ) ) {

			removeNode( last );
			last = last.next;

		}

		return last;

	}

	// eliminate colinear or duplicate points
	function filterPoints( start, end ) {

		if ( ! start ) { return start; }
		if ( ! end ) { end = start; }

		var p = start,
			again;
		do {

			again = false;

			if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {

				removeNode( p );
				p = end = p.prev;
				if ( p === p.next ) { break; }
				again = true;

			} else {

				p = p.next;

			}

		} while ( again || p !== end );

		return end;

	}

	// main ear slicing loop which triangulates a polygon (given as a linked list)
	function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {

		if ( ! ear ) { return; }

		// interlink polygon nodes in z-order
		if ( ! pass && invSize ) { indexCurve( ear, minX, minY, invSize ); }

		var stop = ear,
			prev, next;

		// iterate through ears, slicing them one by one
		while ( ear.prev !== ear.next ) {

			prev = ear.prev;
			next = ear.next;

			if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {

				// cut off the triangle
				triangles.push( prev.i / dim );
				triangles.push( ear.i / dim );
				triangles.push( next.i / dim );

				removeNode( ear );

				// skipping the next vertex leads to less sliver triangles
				ear = next.next;
				stop = next.next;

				continue;

			}

			ear = next;

			// if we looped through the whole remaining polygon and can't find any more ears
			if ( ear === stop ) {

				// try filtering points and slicing again
				if ( ! pass ) {

					earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );

					// if this didn't work, try curing all small self-intersections locally

				} else if ( pass === 1 ) {

					ear = cureLocalIntersections( ear, triangles, dim );
					earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );

					// as a last resort, try splitting the remaining polygon into two

				} else if ( pass === 2 ) {

					splitEarcut( ear, triangles, dim, minX, minY, invSize );

				}

				break;

			}

		}

	}

	// check whether a polygon node forms a valid ear with adjacent nodes
	function isEar( ear ) {

		var a = ear.prev,
			b = ear,
			c = ear.next;

		if ( area( a, b, c ) >= 0 ) { return false; } // reflex, can't be an ear

		// now make sure we don't have other points inside the potential ear
		var p = ear.next.next;

		while ( p !== ear.prev ) {

			if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
				area( p.prev, p, p.next ) >= 0 ) { return false; }
			p = p.next;

		}

		return true;

	}

	function isEarHashed( ear, minX, minY, invSize ) {

		var a = ear.prev,
			b = ear,
			c = ear.next;

		if ( area( a, b, c ) >= 0 ) { return false; } // reflex, can't be an ear

		// triangle bbox; min & max are calculated like this for speed
		var minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
			minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
			maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
			maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );

		// z-order range for the current triangle bbox;
		var minZ = zOrder( minTX, minTY, minX, minY, invSize ),
			maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );

		var p = ear.prevZ,
			n = ear.nextZ;

		// look for points inside the triangle in both directions
		while ( p && p.z >= minZ && n && n.z <= maxZ ) {

			if ( p !== ear.prev && p !== ear.next &&
				pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
				area( p.prev, p, p.next ) >= 0 ) { return false; }
			p = p.prevZ;

			if ( n !== ear.prev && n !== ear.next &&
				pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
				area( n.prev, n, n.next ) >= 0 ) { return false; }
			n = n.nextZ;

		}

		// look for remaining points in decreasing z-order
		while ( p && p.z >= minZ ) {

			if ( p !== ear.prev && p !== ear.next &&
				pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
				area( p.prev, p, p.next ) >= 0 ) { return false; }
			p = p.prevZ;

		}

		// look for remaining points in increasing z-order
		while ( n && n.z <= maxZ ) {

			if ( n !== ear.prev && n !== ear.next &&
				pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
				area( n.prev, n, n.next ) >= 0 ) { return false; }
			n = n.nextZ;

		}

		return true;

	}

	// go through all polygon nodes and cure small local self-intersections
	function cureLocalIntersections( start, triangles, dim ) {

		var p = start;
		do {

			var a = p.prev,
				b = p.next.next;

			if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {

				triangles.push( a.i / dim );
				triangles.push( p.i / dim );
				triangles.push( b.i / dim );

				// remove two nodes involved
				removeNode( p );
				removeNode( p.next );

				p = start = b;

			}

			p = p.next;

		} while ( p !== start );

		return p;

	}

	// try splitting polygon into two and triangulate them independently
	function splitEarcut( start, triangles, dim, minX, minY, invSize ) {

		// look for a valid diagonal that divides the polygon into two
		var a = start;
		do {

			var b = a.next.next;
			while ( b !== a.prev ) {

				if ( a.i !== b.i && isValidDiagonal( a, b ) ) {

					// split the polygon in two by the diagonal
					var c = splitPolygon( a, b );

					// filter colinear points around the cuts
					a = filterPoints( a, a.next );
					c = filterPoints( c, c.next );

					// run earcut on each half
					earcutLinked( a, triangles, dim, minX, minY, invSize );
					earcutLinked( c, triangles, dim, minX, minY, invSize );
					return;

				}

				b = b.next;

			}

			a = a.next;

		} while ( a !== start );

	}

	// link every hole into the outer loop, producing a single-ring polygon without holes
	function eliminateHoles( data, holeIndices, outerNode, dim ) {

		var queue = [],
			i, len, start, end, list;

		for ( i = 0, len = holeIndices.length; i < len; i ++ ) {

			start = holeIndices[ i ] * dim;
			end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
			list = linkedList( data, start, end, dim, false );
			if ( list === list.next ) { list.steiner = true; }
			queue.push( getLeftmost( list ) );

		}

		queue.sort( compareX );

		// process holes from left to right
		for ( i = 0; i < queue.length; i ++ ) {

			eliminateHole( queue[ i ], outerNode );
			outerNode = filterPoints( outerNode, outerNode.next );

		}

		return outerNode;

	}

	function compareX( a, b ) {

		return a.x - b.x;

	}

	// find a bridge between vertices that connects hole with an outer ring and and link it
	function eliminateHole( hole, outerNode ) {

		outerNode = findHoleBridge( hole, outerNode );
		if ( outerNode ) {

			var b = splitPolygon( outerNode, hole );
			filterPoints( b, b.next );

		}

	}

	// David Eberly's algorithm for finding a bridge between hole and outer polygon
	function findHoleBridge( hole, outerNode ) {

		var p = outerNode,
			hx = hole.x,
			hy = hole.y,
			qx = - Infinity,
			m;

		// find a segment intersected by a ray from the hole's leftmost point to the left;
		// segment's endpoint with lesser x will be potential connection point
		do {

			if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {

				var x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
				if ( x <= hx && x > qx ) {

					qx = x;
					if ( x === hx ) {

						if ( hy === p.y ) { return p; }
						if ( hy === p.next.y ) { return p.next; }

					}

					m = p.x < p.next.x ? p : p.next;

				}

			}

			p = p.next;

		} while ( p !== outerNode );

		if ( ! m ) { return null; }

		if ( hx === qx ) { return m.prev; } // hole touches outer segment; pick lower endpoint

		// look for points inside the triangle of hole point, segment intersection and endpoint;
		// if there are no points found, we have a valid connection;
		// otherwise choose the point of the minimum angle with the ray as connection point

		var stop = m,
			mx = m.x,
			my = m.y,
			tanMin = Infinity,
			tan;

		p = m.next;

		while ( p !== stop ) {

			if ( hx >= p.x && p.x >= mx && hx !== p.x &&
					pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {

				tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential

				if ( ( tan < tanMin || ( tan === tanMin && p.x > m.x ) ) && locallyInside( p, hole ) ) {

					m = p;
					tanMin = tan;

				}

			}

			p = p.next;

		}

		return m;

	}

	// interlink polygon nodes in z-order
	function indexCurve( start, minX, minY, invSize ) {

		var p = start;
		do {

			if ( p.z === null ) { p.z = zOrder( p.x, p.y, minX, minY, invSize ); }
			p.prevZ = p.prev;
			p.nextZ = p.next;
			p = p.next;

		} while ( p !== start );

		p.prevZ.nextZ = null;
		p.prevZ = null;

		sortLinked( p );

	}

	// Simon Tatham's linked list merge sort algorithm
	// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
	function sortLinked( list ) {

		var i, p, q, e, tail, numMerges, pSize, qSize,
			inSize = 1;

		do {

			p = list;
			list = null;
			tail = null;
			numMerges = 0;

			while ( p ) {

				numMerges ++;
				q = p;
				pSize = 0;
				for ( i = 0; i < inSize; i ++ ) {

					pSize ++;
					q = q.nextZ;
					if ( ! q ) { break; }

				}

				qSize = inSize;

				while ( pSize > 0 || ( qSize > 0 && q ) ) {

					if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {

						e = p;
						p = p.nextZ;
						pSize --;

					} else {

						e = q;
						q = q.nextZ;
						qSize --;

					}

					if ( tail ) { tail.nextZ = e; }
					else { list = e; }

					e.prevZ = tail;
					tail = e;

				}

				p = q;

			}

			tail.nextZ = null;
			inSize *= 2;

		} while ( numMerges > 1 );

		return list;

	}

	// z-order of a point given coords and inverse of the longer side of data bbox
	function zOrder( x, y, minX, minY, invSize ) {

		// coords are transformed into non-negative 15-bit integer range
		x = 32767 * ( x - minX ) * invSize;
		y = 32767 * ( y - minY ) * invSize;

		x = ( x | ( x << 8 ) ) & 0x00FF00FF;
		x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
		x = ( x | ( x << 2 ) ) & 0x33333333;
		x = ( x | ( x << 1 ) ) & 0x55555555;

		y = ( y | ( y << 8 ) ) & 0x00FF00FF;
		y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
		y = ( y | ( y << 2 ) ) & 0x33333333;
		y = ( y | ( y << 1 ) ) & 0x55555555;

		return x | ( y << 1 );

	}

	// find the leftmost node of a polygon ring
	function getLeftmost( start ) {

		var p = start,
			leftmost = start;
		do {

			if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) { leftmost = p; }
			p = p.next;

		} while ( p !== start );

		return leftmost;

	}

	// check if a point lies within a convex triangle
	function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {

		return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
			   ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
			   ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;

	}

	// check if a diagonal between two polygon nodes is valid (lies in polygon interior)
	function isValidDiagonal( a, b ) {

		return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) &&
			   locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b );

	}

	// signed area of a triangle
	function area( p, q, r ) {

		return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );

	}

	// check if two points are equal
	function equals( p1, p2 ) {

		return p1.x === p2.x && p1.y === p2.y;

	}

	// check if two segments intersect
	function intersects( p1, q1, p2, q2 ) {

		if ( ( equals( p1, p2 ) && equals( q1, q2 ) ) ||
			( equals( p1, q2 ) && equals( p2, q1 ) ) ) { return true; }
		return area( p1, q1, p2 ) > 0 !== area( p1, q1, q2 ) > 0 &&
			   area( p2, q2, p1 ) > 0 !== area( p2, q2, q1 ) > 0;

	}

	// check if a polygon diagonal intersects any polygon segments
	function intersectsPolygon( a, b ) {

		var p = a;
		do {

			if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
					intersects( p, p.next, a, b ) ) { return true; }
			p = p.next;

		} while ( p !== a );

		return false;

	}

	// check if a polygon diagonal is locally inside the polygon
	function locallyInside( a, b ) {

		return area( a.prev, a, a.next ) < 0 ?
			area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
			area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;

	}

	// check if the middle point of a polygon diagonal is inside the polygon
	function middleInside( a, b ) {

		var p = a,
			inside = false,
			px = ( a.x + b.x ) / 2,
			py = ( a.y + b.y ) / 2;
		do {

			if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
					( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
				{ inside = ! inside; }
			p = p.next;

		} while ( p !== a );

		return inside;

	}

	// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
	// if one belongs to the outer ring and another to a hole, it merges it into a single ring
	function splitPolygon( a, b ) {

		var a2 = new Node( a.i, a.x, a.y ),
			b2 = new Node( b.i, b.x, b.y ),
			an = a.next,
			bp = b.prev;

		a.next = b;
		b.prev = a;

		a2.next = an;
		an.prev = a2;

		b2.next = a2;
		a2.prev = b2;

		bp.next = b2;
		b2.prev = bp;

		return b2;

	}

	// create a node and optionally link it with previous one (in a circular doubly linked list)
	function insertNode( i, x, y, last ) {

		var p = new Node( i, x, y );

		if ( ! last ) {

			p.prev = p;
			p.next = p;

		} else {

			p.next = last.next;
			p.prev = last;
			last.next.prev = p;
			last.next = p;

		}

		return p;

	}

	function removeNode( p ) {

		p.next.prev = p.prev;
		p.prev.next = p.next;

		if ( p.prevZ ) { p.prevZ.nextZ = p.nextZ; }
		if ( p.nextZ ) { p.nextZ.prevZ = p.prevZ; }

	}

	function Node( i, x, y ) {

		// vertex index in coordinates array
		this.i = i;

		// vertex coordinates
		this.x = x;
		this.y = y;

		// previous and next vertex nodes in a polygon ring
		this.prev = null;
		this.next = null;

		// z-order curve value
		this.z = null;

		// previous and next nodes in z-order
		this.prevZ = null;
		this.nextZ = null;

		// indicates whether this is a steiner point
		this.steiner = false;

	}

	function signedArea( data, start, end, dim ) {

		var sum = 0;
		for ( var i = start, j = end - dim; i < end; i += dim ) {

			sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
			j = i;

		}

		return sum;

	}

	/**
	 * @author zz85 / http://www.lab4games.net/zz85/blog
	 */

	var ShapeUtils = {

		// calculate area of the contour polygon

		area: function ( contour ) {

			var n = contour.length;
			var a = 0.0;

			for ( var p = n - 1, q = 0; q < n; p = q ++ ) {

				a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;

			}

			return a * 0.5;

		},

		isClockWise: function ( pts ) {

			return ShapeUtils.area( pts ) < 0;

		},

		triangulateShape: function ( contour, holes ) {

			var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
			var holeIndices = []; // array of hole indices
			var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]

			removeDupEndPts( contour );
			addContour( vertices, contour );

			//

			var holeIndex = contour.length;

			holes.forEach( removeDupEndPts );

			for ( var i = 0; i < holes.length; i ++ ) {

				holeIndices.push( holeIndex );
				holeIndex += holes[ i ].length;
				addContour( vertices, holes[ i ] );

			}

			//

			var triangles = Earcut.triangulate( vertices, holeIndices );

			//

			for ( var i = 0; i < triangles.length; i += 3 ) {

				faces.push( triangles.slice( i, i + 3 ) );

			}

			return faces;

		}

	};

	function removeDupEndPts( points ) {

		var l = points.length;

		if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {

			points.pop();

		}

	}

	function addContour( vertices, contour ) {

		for ( var i = 0; i < contour.length; i ++ ) {

			vertices.push( contour[ i ].x );
			vertices.push( contour[ i ].y );

		}

	}

	/**
	 * @author zz85 / http://www.lab4games.net/zz85/blog
	 *
	 * Creates extruded geometry from a path shape.
	 *
	 * parameters = {
	 *
	 *  curveSegments: <int>, // number of points on the curves
	 *  steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
	 *  depth: <float>, // Depth to extrude the shape
	 *
	 *  bevelEnabled: <bool>, // turn on bevel
	 *  bevelThickness: <float>, // how deep into the original shape bevel goes
	 *  bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
	 *  bevelOffset: <float>, // how far from shape outline does bevel start
	 *  bevelSegments: <int>, // number of bevel layers
	 *
	 *  extrudePath: <THREE.Curve> // curve to extrude shape along
	 *
	 *  UVGenerator: <Object> // object that provides UV generator functions
	 *
	 * }
	 */

	// ExtrudeGeometry

	function ExtrudeGeometry( shapes, options ) {

		Geometry.call( this );

		this.type = 'ExtrudeGeometry';

		this.parameters = {
			shapes: shapes,
			options: options
		};

		this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
		this.mergeVertices();

	}

	ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
	ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;

	ExtrudeGeometry.prototype.toJSON = function () {

		var data = Geometry.prototype.toJSON.call( this );

		var shapes = this.parameters.shapes;
		var options = this.parameters.options;

		return toJSON( shapes, options, data );

	};

	// ExtrudeBufferGeometry

	function ExtrudeBufferGeometry( shapes, options ) {

		BufferGeometry.call( this );

		this.type = 'ExtrudeBufferGeometry';

		this.parameters = {
			shapes: shapes,
			options: options
		};

		shapes = Array.isArray( shapes ) ? shapes : [ shapes ];

		var scope = this;

		var verticesArray = [];
		var uvArray = [];

		for ( var i = 0, l = shapes.length; i < l; i ++ ) {

			var shape = shapes[ i ];
			addShape( shape );

		}

		// build geometry

		this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
		this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );

		this.computeVertexNormals();

		// functions

		function addShape( shape ) {

			var placeholder = [];

			// options

			var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
			var steps = options.steps !== undefined ? options.steps : 1;
			var depth = options.depth !== undefined ? options.depth : 100;

			var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
			var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
			var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
			var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
			var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;

			var extrudePath = options.extrudePath;

			var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;

			// deprecated options

			if ( options.amount !== undefined ) {

				console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
				depth = options.amount;

			}

			//

			var extrudePts, extrudeByPath = false;
			var splineTube, binormal, normal, position2;

			if ( extrudePath ) {

				extrudePts = extrudePath.getSpacedPoints( steps );

				extrudeByPath = true;
				bevelEnabled = false; // bevels not supported for path extrusion

				// SETUP TNB variables

				// TODO1 - have a .isClosed in spline?

				splineTube = extrudePath.computeFrenetFrames( steps, false );

				// console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);

				binormal = new Vector3();
				normal = new Vector3();
				position2 = new Vector3();

			}

			// Safeguards if bevels are not enabled

			if ( ! bevelEnabled ) {

				bevelSegments = 0;
				bevelThickness = 0;
				bevelSize = 0;
				bevelOffset = 0;

			}

			// Variables initialization

			var ahole, h, hl; // looping of holes

			var shapePoints = shape.extractPoints( curveSegments );

			var vertices = shapePoints.shape;
			var holes = shapePoints.holes;

			var reverse = ! ShapeUtils.isClockWise( vertices );

			if ( reverse ) {

				vertices = vertices.reverse();

				// Maybe we should also check if holes are in the opposite direction, just to be safe ...

				for ( h = 0, hl = holes.length; h < hl; h ++ ) {

					ahole = holes[ h ];

					if ( ShapeUtils.isClockWise( ahole ) ) {

						holes[ h ] = ahole.reverse();

					}

				}

			}


			var faces = ShapeUtils.triangulateShape( vertices, holes );

			/* Vertices */

			var contour = vertices; // vertices has all points but contour has only points of circumference

			for ( h = 0, hl = holes.length; h < hl; h ++ ) {

				ahole = holes[ h ];

				vertices = vertices.concat( ahole );

			}


			function scalePt2( pt, vec, size ) {

				if ( ! vec ) { console.error( "THREE.ExtrudeGeometry: vec does not exist" ); }

				return vec.clone().multiplyScalar( size ).add( pt );

			}

			var b, bs, t, z,
				vert, vlen = vertices.length,
				face, flen = faces.length;


			// Find directions for point movement


			function getBevelVec( inPt, inPrev, inNext ) {

				// computes for inPt the corresponding point inPt' on a new contour
				//   shifted by 1 unit (length of normalized vector) to the left
				// if we walk along contour clockwise, this new contour is outside the old one
				//
				// inPt' is the intersection of the two lines parallel to the two
				//  adjacent edges of inPt at a distance of 1 unit on the left side.

				var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt

				// good reading for geometry algorithms (here: line-line intersection)
				// http://geomalgorithms.com/a05-_intersect-1.html

				var v_prev_x = inPt.x - inPrev.x,
					v_prev_y = inPt.y - inPrev.y;
				var v_next_x = inNext.x - inPt.x,
					v_next_y = inNext.y - inPt.y;

				var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );

				// check for collinear edges
				var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );

				if ( Math.abs( collinear0 ) > Number.EPSILON ) {

					// not collinear

					// length of vectors for normalizing

					var v_prev_len = Math.sqrt( v_prev_lensq );
					var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );

					// shift adjacent points by unit vectors to the left

					var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
					var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );

					var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
					var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );

					// scaling factor for v_prev to intersection point

					var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
							( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
						( v_prev_x * v_next_y - v_prev_y * v_next_x );

					// vector from inPt to intersection point

					v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
					v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );

					// Don't normalize!, otherwise sharp corners become ugly
					//  but prevent crazy spikes
					var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
					if ( v_trans_lensq <= 2 ) {

						return new Vector2( v_trans_x, v_trans_y );

					} else {

						shrink_by = Math.sqrt( v_trans_lensq / 2 );

					}

				} else {

					// handle special case of collinear edges

					var direction_eq = false; // assumes: opposite
					if ( v_prev_x > Number.EPSILON ) {

						if ( v_next_x > Number.EPSILON ) {

							direction_eq = true;

						}

					} else {

						if ( v_prev_x < - Number.EPSILON ) {

							if ( v_next_x < - Number.EPSILON ) {

								direction_eq = true;

							}

						} else {

							if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {

								direction_eq = true;

							}

						}

					}

					if ( direction_eq ) {

						// console.log("Warning: lines are a straight sequence");
						v_trans_x = - v_prev_y;
						v_trans_y = v_prev_x;
						shrink_by = Math.sqrt( v_prev_lensq );

					} else {

						// console.log("Warning: lines are a straight spike");
						v_trans_x = v_prev_x;
						v_trans_y = v_prev_y;
						shrink_by = Math.sqrt( v_prev_lensq / 2 );

					}

				}

				return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );

			}


			var contourMovements = [];

			for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {

				if ( j === il ) { j = 0; }
				if ( k === il ) { k = 0; }

				//  (j)---(i)---(k)
				// console.log('i,j,k', i, j , k)

				contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );

			}

			var holesMovements = [],
				oneHoleMovements, verticesMovements = contourMovements.concat();

			for ( h = 0, hl = holes.length; h < hl; h ++ ) {

				ahole = holes[ h ];

				oneHoleMovements = [];

				for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {

					if ( j === il ) { j = 0; }
					if ( k === il ) { k = 0; }

					//  (j)---(i)---(k)
					oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );

				}

				holesMovements.push( oneHoleMovements );
				verticesMovements = verticesMovements.concat( oneHoleMovements );

			}


			// Loop bevelSegments, 1 for the front, 1 for the back

			for ( b = 0; b < bevelSegments; b ++ ) {

				//for ( b = bevelSegments; b > 0; b -- ) {

				t = b / bevelSegments;
				z = bevelThickness * Math.cos( t * Math.PI / 2 );
				bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;

				// contract shape

				for ( i = 0, il = contour.length; i < il; i ++ ) {

					vert = scalePt2( contour[ i ], contourMovements[ i ], bs );

					v( vert.x, vert.y, - z );

				}

				// expand holes

				for ( h = 0, hl = holes.length; h < hl; h ++ ) {

					ahole = holes[ h ];
					oneHoleMovements = holesMovements[ h ];

					for ( i = 0, il = ahole.length; i < il; i ++ ) {

						vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );

						v( vert.x, vert.y, - z );

					}

				}

			}

			bs = bevelSize + bevelOffset;

			// Back facing vertices

			for ( i = 0; i < vlen; i ++ ) {

				vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];

				if ( ! extrudeByPath ) {

					v( vert.x, vert.y, 0 );

				} else {

					// v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );

					normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
					binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );

					position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );

					v( position2.x, position2.y, position2.z );

				}

			}

			// Add stepped vertices...
			// Including front facing vertices

			var s;

			for ( s = 1; s <= steps; s ++ ) {

				for ( i = 0; i < vlen; i ++ ) {

					vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];

					if ( ! extrudeByPath ) {

						v( vert.x, vert.y, depth / steps * s );

					} else {

						// v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );

						normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
						binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );

						position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );

						v( position2.x, position2.y, position2.z );

					}

				}

			}


			// Add bevel segments planes

			//for ( b = 1; b <= bevelSegments; b ++ ) {
			for ( b = bevelSegments - 1; b >= 0; b -- ) {

				t = b / bevelSegments;
				z = bevelThickness * Math.cos( t * Math.PI / 2 );
				bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;

				// contract shape

				for ( i = 0, il = contour.length; i < il; i ++ ) {

					vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
					v( vert.x, vert.y, depth + z );

				}

				// expand holes

				for ( h = 0, hl = holes.length; h < hl; h ++ ) {

					ahole = holes[ h ];
					oneHoleMovements = holesMovements[ h ];

					for ( i = 0, il = ahole.length; i < il; i ++ ) {

						vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );

						if ( ! extrudeByPath ) {

							v( vert.x, vert.y, depth + z );

						} else {

							v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );

						}

					}

				}

			}

			/* Faces */

			// Top and bottom faces

			buildLidFaces();

			// Sides faces

			buildSideFaces();


			/////  Internal functions

			function buildLidFaces() {

				var start = verticesArray.length / 3;

				if ( bevelEnabled ) {

					var layer = 0; // steps + 1
					var offset = vlen * layer;

					// Bottom faces

					for ( i = 0; i < flen; i ++ ) {

						face = faces[ i ];
						f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );

					}

					layer = steps + bevelSegments * 2;
					offset = vlen * layer;

					// Top faces

					for ( i = 0; i < flen; i ++ ) {

						face = faces[ i ];
						f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );

					}

				} else {

					// Bottom faces

					for ( i = 0; i < flen; i ++ ) {

						face = faces[ i ];
						f3( face[ 2 ], face[ 1 ], face[ 0 ] );

					}

					// Top faces

					for ( i = 0; i < flen; i ++ ) {

						face = faces[ i ];
						f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );

					}

				}

				scope.addGroup( start, verticesArray.length / 3 - start, 0 );

			}

			// Create faces for the z-sides of the shape

			function buildSideFaces() {

				var start = verticesArray.length / 3;
				var layeroffset = 0;
				sidewalls( contour, layeroffset );
				layeroffset += contour.length;

				for ( h = 0, hl = holes.length; h < hl; h ++ ) {

					ahole = holes[ h ];
					sidewalls( ahole, layeroffset );

					//, true
					layeroffset += ahole.length;

				}


				scope.addGroup( start, verticesArray.length / 3 - start, 1 );


			}

			function sidewalls( contour, layeroffset ) {

				var j, k;
				i = contour.length;

				while ( -- i >= 0 ) {

					j = i;
					k = i - 1;
					if ( k < 0 ) { k = contour.length - 1; }

					//console.log('b', i,j, i-1, k,vertices.length);

					var s = 0,
						sl = steps + bevelSegments * 2;

					for ( s = 0; s < sl; s ++ ) {

						var slen1 = vlen * s;
						var slen2 = vlen * ( s + 1 );

						var a = layeroffset + j + slen1,
							b = layeroffset + k + slen1,
							c = layeroffset + k + slen2,
							d = layeroffset + j + slen2;

						f4( a, b, c, d );

					}

				}

			}

			function v( x, y, z ) {

				placeholder.push( x );
				placeholder.push( y );
				placeholder.push( z );

			}


			function f3( a, b, c ) {

				addVertex( a );
				addVertex( b );
				addVertex( c );

				var nextIndex = verticesArray.length / 3;
				var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );

				addUV( uvs[ 0 ] );
				addUV( uvs[ 1 ] );
				addUV( uvs[ 2 ] );

			}

			function f4( a, b, c, d ) {

				addVertex( a );
				addVertex( b );
				addVertex( d );

				addVertex( b );
				addVertex( c );
				addVertex( d );


				var nextIndex = verticesArray.length / 3;
				var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );

				addUV( uvs[ 0 ] );
				addUV( uvs[ 1 ] );
				addUV( uvs[ 3 ] );

				addUV( uvs[ 1 ] );
				addUV( uvs[ 2 ] );
				addUV( uvs[ 3 ] );

			}

			function addVertex( index ) {

				verticesArray.push( placeholder[ index * 3 + 0 ] );
				verticesArray.push( placeholder[ index * 3 + 1 ] );
				verticesArray.push( placeholder[ index * 3 + 2 ] );

			}


			function addUV( vector2 ) {

				uvArray.push( vector2.x );
				uvArray.push( vector2.y );

			}

		}

	}

	ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
	ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;

	ExtrudeBufferGeometry.prototype.toJSON = function () {

		var data = BufferGeometry.prototype.toJSON.call( this );

		var shapes = this.parameters.shapes;
		var options = this.parameters.options;

		return toJSON( shapes, options, data );

	};

	//

	var WorldUVGenerator = {

		generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {

			var a_x = vertices[ indexA * 3 ];
			var a_y = vertices[ indexA * 3 + 1 ];
			var b_x = vertices[ indexB * 3 ];
			var b_y = vertices[ indexB * 3 + 1 ];
			var c_x = vertices[ indexC * 3 ];
			var c_y = vertices[ indexC * 3 + 1 ];

			return [
				new Vector2( a_x, a_y ),
				new Vector2( b_x, b_y ),
				new Vector2( c_x, c_y )
			];

		},

		generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {

			var a_x = vertices[ indexA * 3 ];
			var a_y = vertices[ indexA * 3 + 1 ];
			var a_z = vertices[ indexA * 3 + 2 ];
			var b_x = vertices[ indexB * 3 ];
			var b_y = vertices[ indexB * 3 + 1 ];
			var b_z = vertices[ indexB * 3 + 2 ];
			var c_x = vertices[ indexC * 3 ];
			var c_y = vertices[ indexC * 3 + 1 ];
			var c_z = vertices[ indexC * 3 + 2 ];
			var d_x = vertices[ indexD * 3 ];
			var d_y = vertices[ indexD * 3 + 1 ];
			var d_z = vertices[ indexD * 3 + 2 ];

			if ( Math.abs( a_y - b_y ) < 0.01 ) {

				return [
					new Vector2( a_x, 1 - a_z ),
					new Vector2( b_x, 1 - b_z ),
					new Vector2( c_x, 1 - c_z ),
					new Vector2( d_x, 1 - d_z )
				];

			} else {

				return [
					new Vector2( a_y, 1 - a_z ),
					new Vector2( b_y, 1 - b_z ),
					new Vector2( c_y, 1 - c_z ),
					new Vector2( d_y, 1 - d_z )
				];

			}

		}
	};

	function toJSON( shapes, options, data ) {

		//

		data.shapes = [];

		if ( Array.isArray( shapes ) ) {

			for ( var i = 0, l = shapes.length; i < l; i ++ ) {

				var shape = shapes[ i ];

				data.shapes.push( shape.uuid );

			}

		} else {

			data.shapes.push( shapes.uuid );

		}

		//

		if ( options.extrudePath !== undefined ) { data.options.extrudePath = options.extrudePath.toJSON(); }

		return data;

	}

	/**
	 * @author zz85 / http://www.lab4games.net/zz85/blog
	 * @author alteredq / http://alteredqualia.com/
	 *
	 * Text = 3D Text
	 *
	 * parameters = {
	 *  font: <THREE.Font>, // font
	 *
	 *  size: <float>, // size of the text
	 *  height: <float>, // thickness to extrude text
	 *  curveSegments: <int>, // number of points on the curves
	 *
	 *  bevelEnabled: <bool>, // turn on bevel
	 *  bevelThickness: <float>, // how deep into text bevel goes
	 *  bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
	 *  bevelOffset: <float> // how far from text outline does bevel start
	 * }
	 */

	// TextGeometry

	function TextGeometry( text, parameters ) {

		Geometry.call( this );

		this.type = 'TextGeometry';

		this.parameters = {
			text: text,
			parameters: parameters
		};

		this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
		this.mergeVertices();

	}

	TextGeometry.prototype = Object.create( Geometry.prototype );
	TextGeometry.prototype.constructor = TextGeometry;

	// TextBufferGeometry

	function TextBufferGeometry( text, parameters ) {

		parameters = parameters || {};

		var font = parameters.font;

		if ( ! ( font && font.isFont ) ) {

			console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
			return new Geometry();

		}

		var shapes = font.generateShapes( text, parameters.size );

		// translate parameters to ExtrudeGeometry API

		parameters.depth = parameters.height !== undefined ? parameters.height : 50;

		// defaults

		if ( parameters.bevelThickness === undefined ) { parameters.bevelThickness = 10; }
		if ( parameters.bevelSize === undefined ) { parameters.bevelSize = 8; }
		if ( parameters.bevelEnabled === undefined ) { parameters.bevelEnabled = false; }

		ExtrudeBufferGeometry.call( this, shapes, parameters );

		this.type = 'TextBufferGeometry';

	}

	TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
	TextBufferGeometry.prototype.constructor = TextBufferGeometry;

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author benaadams / https://twitter.com/ben_a_adams
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	// SphereGeometry

	function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {

		Geometry.call( this );

		this.type = 'SphereGeometry';

		this.parameters = {
			radius: radius,
			widthSegments: widthSegments,
			heightSegments: heightSegments,
			phiStart: phiStart,
			phiLength: phiLength,
			thetaStart: thetaStart,
			thetaLength: thetaLength
		};

		this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
		this.mergeVertices();

	}

	SphereGeometry.prototype = Object.create( Geometry.prototype );
	SphereGeometry.prototype.constructor = SphereGeometry;

	// SphereBufferGeometry

	function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {

		BufferGeometry.call( this );

		this.type = 'SphereBufferGeometry';

		this.parameters = {
			radius: radius,
			widthSegments: widthSegments,
			heightSegments: heightSegments,
			phiStart: phiStart,
			phiLength: phiLength,
			thetaStart: thetaStart,
			thetaLength: thetaLength
		};

		radius = radius || 1;

		widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
		heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );

		phiStart = phiStart !== undefined ? phiStart : 0;
		phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;

		thetaStart = thetaStart !== undefined ? thetaStart : 0;
		thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;

		var thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );

		var ix, iy;

		var index = 0;
		var grid = [];

		var vertex = new Vector3();
		var normal = new Vector3();

		// buffers

		var indices = [];
		var vertices = [];
		var normals = [];
		var uvs = [];

		// generate vertices, normals and uvs

		for ( iy = 0; iy <= heightSegments; iy ++ ) {

			var verticesRow = [];

			var v = iy / heightSegments;

			// special case for the poles

			var uOffset = 0;

			if ( iy == 0 && thetaStart == 0 ) {

				uOffset = 0.5 / widthSegments;

			} else if ( iy == heightSegments && thetaEnd == Math.PI ) {

				uOffset = - 0.5 / widthSegments;

			}

			for ( ix = 0; ix <= widthSegments; ix ++ ) {

				var u = ix / widthSegments;

				// vertex

				vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
				vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
				vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );

				vertices.push( vertex.x, vertex.y, vertex.z );

				// normal

				normal.copy( vertex ).normalize();
				normals.push( normal.x, normal.y, normal.z );

				// uv

				uvs.push( u + uOffset, 1 - v );

				verticesRow.push( index ++ );

			}

			grid.push( verticesRow );

		}

		// indices

		for ( iy = 0; iy < heightSegments; iy ++ ) {

			for ( ix = 0; ix < widthSegments; ix ++ ) {

				var a = grid[ iy ][ ix + 1 ];
				var b = grid[ iy ][ ix ];
				var c = grid[ iy + 1 ][ ix ];
				var d = grid[ iy + 1 ][ ix + 1 ];

				if ( iy !== 0 || thetaStart > 0 ) { indices.push( a, b, d ); }
				if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) { indices.push( b, c, d ); }

			}

		}

		// build geometry

		this.setIndex( indices );
		this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
		this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

	}

	SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
	SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;

	/**
	 * @author Kaleb Murphy
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	// RingGeometry

	function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {

		Geometry.call( this );

		this.type = 'RingGeometry';

		this.parameters = {
			innerRadius: innerRadius,
			outerRadius: outerRadius,
			thetaSegments: thetaSegments,
			phiSegments: phiSegments,
			thetaStart: thetaStart,
			thetaLength: thetaLength
		};

		this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
		this.mergeVertices();

	}

	RingGeometry.prototype = Object.create( Geometry.prototype );
	RingGeometry.prototype.constructor = RingGeometry;

	// RingBufferGeometry

	function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {

		BufferGeometry.call( this );

		this.type = 'RingBufferGeometry';

		this.parameters = {
			innerRadius: innerRadius,
			outerRadius: outerRadius,
			thetaSegments: thetaSegments,
			phiSegments: phiSegments,
			thetaStart: thetaStart,
			thetaLength: thetaLength
		};

		innerRadius = innerRadius || 0.5;
		outerRadius = outerRadius || 1;

		thetaStart = thetaStart !== undefined ? thetaStart : 0;
		thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;

		thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
		phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;

		// buffers

		var indices = [];
		var vertices = [];
		var normals = [];
		var uvs = [];

		// some helper variables

		var segment;
		var radius = innerRadius;
		var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
		var vertex = new Vector3();
		var uv = new Vector2();
		var j, i;

		// generate vertices, normals and uvs

		for ( j = 0; j <= phiSegments; j ++ ) {

			for ( i = 0; i <= thetaSegments; i ++ ) {

				// values are generate from the inside of the ring to the outside

				segment = thetaStart + i / thetaSegments * thetaLength;

				// vertex

				vertex.x = radius * Math.cos( segment );
				vertex.y = radius * Math.sin( segment );

				vertices.push( vertex.x, vertex.y, vertex.z );

				// normal

				normals.push( 0, 0, 1 );

				// uv

				uv.x = ( vertex.x / outerRadius + 1 ) / 2;
				uv.y = ( vertex.y / outerRadius + 1 ) / 2;

				uvs.push( uv.x, uv.y );

			}

			// increase the radius for next row of vertices

			radius += radiusStep;

		}

		// indices

		for ( j = 0; j < phiSegments; j ++ ) {

			var thetaSegmentLevel = j * ( thetaSegments + 1 );

			for ( i = 0; i < thetaSegments; i ++ ) {

				segment = i + thetaSegmentLevel;

				var a = segment;
				var b = segment + thetaSegments + 1;
				var c = segment + thetaSegments + 2;
				var d = segment + 1;

				// faces

				indices.push( a, b, d );
				indices.push( b, c, d );

			}

		}

		// build geometry

		this.setIndex( indices );
		this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
		this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

	}

	RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
	RingBufferGeometry.prototype.constructor = RingBufferGeometry;

	/**
	 * @author zz85 / https://github.com/zz85
	 * @author bhouston / http://clara.io
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	// LatheGeometry

	function LatheGeometry( points, segments, phiStart, phiLength ) {

		Geometry.call( this );

		this.type = 'LatheGeometry';

		this.parameters = {
			points: points,
			segments: segments,
			phiStart: phiStart,
			phiLength: phiLength
		};

		this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
		this.mergeVertices();

	}

	LatheGeometry.prototype = Object.create( Geometry.prototype );
	LatheGeometry.prototype.constructor = LatheGeometry;

	// LatheBufferGeometry

	function LatheBufferGeometry( points, segments, phiStart, phiLength ) {

		BufferGeometry.call( this );

		this.type = 'LatheBufferGeometry';

		this.parameters = {
			points: points,
			segments: segments,
			phiStart: phiStart,
			phiLength: phiLength
		};

		segments = Math.floor( segments ) || 12;
		phiStart = phiStart || 0;
		phiLength = phiLength || Math.PI * 2;

		// clamp phiLength so it's in range of [ 0, 2PI ]

		phiLength = MathUtils.clamp( phiLength, 0, Math.PI * 2 );


		// buffers

		var indices = [];
		var vertices = [];
		var uvs = [];

		// helper variables

		var base;
		var inverseSegments = 1.0 / segments;
		var vertex = new Vector3();
		var uv = new Vector2();
		var i, j;

		// generate vertices and uvs

		for ( i = 0; i <= segments; i ++ ) {

			var phi = phiStart + i * inverseSegments * phiLength;

			var sin = Math.sin( phi );
			var cos = Math.cos( phi );

			for ( j = 0; j <= ( points.length - 1 ); j ++ ) {

				// vertex

				vertex.x = points[ j ].x * sin;
				vertex.y = points[ j ].y;
				vertex.z = points[ j ].x * cos;

				vertices.push( vertex.x, vertex.y, vertex.z );

				// uv

				uv.x = i / segments;
				uv.y = j / ( points.length - 1 );

				uvs.push( uv.x, uv.y );


			}

		}

		// indices

		for ( i = 0; i < segments; i ++ ) {

			for ( j = 0; j < ( points.length - 1 ); j ++ ) {

				base = j + i * points.length;

				var a = base;
				var b = base + points.length;
				var c = base + points.length + 1;
				var d = base + 1;

				// faces

				indices.push( a, b, d );
				indices.push( b, c, d );

			}

		}

		// build geometry

		this.setIndex( indices );
		this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

		// generate normals

		this.computeVertexNormals();

		// if the geometry is closed, we need to average the normals along the seam.
		// because the corresponding vertices are identical (but still have different UVs).

		if ( phiLength === Math.PI * 2 ) {

			var normals = this.attributes.normal.array;
			var n1 = new Vector3();
			var n2 = new Vector3();
			var n = new Vector3();

			// this is the buffer offset for the last line of vertices

			base = segments * points.length * 3;

			for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {

				// select the normal of the vertex in the first line

				n1.x = normals[ j + 0 ];
				n1.y = normals[ j + 1 ];
				n1.z = normals[ j + 2 ];

				// select the normal of the vertex in the last line

				n2.x = normals[ base + j + 0 ];
				n2.y = normals[ base + j + 1 ];
				n2.z = normals[ base + j + 2 ];

				// average normals

				n.addVectors( n1, n2 ).normalize();

				// assign the new values to both normals

				normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
				normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
				normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;

			}

		}

	}

	LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
	LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;

	/**
	 * @author jonobr1 / http://jonobr1.com
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	// ShapeGeometry

	function ShapeGeometry( shapes, curveSegments ) {

		Geometry.call( this );

		this.type = 'ShapeGeometry';

		if ( typeof curveSegments === 'object' ) {

			console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );

			curveSegments = curveSegments.curveSegments;

		}

		this.parameters = {
			shapes: shapes,
			curveSegments: curveSegments
		};

		this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
		this.mergeVertices();

	}

	ShapeGeometry.prototype = Object.create( Geometry.prototype );
	ShapeGeometry.prototype.constructor = ShapeGeometry;

	ShapeGeometry.prototype.toJSON = function () {

		var data = Geometry.prototype.toJSON.call( this );

		var shapes = this.parameters.shapes;

		return toJSON$1( shapes, data );

	};

	// ShapeBufferGeometry

	function ShapeBufferGeometry( shapes, curveSegments ) {

		BufferGeometry.call( this );

		this.type = 'ShapeBufferGeometry';

		this.parameters = {
			shapes: shapes,
			curveSegments: curveSegments
		};

		curveSegments = curveSegments || 12;

		// buffers

		var indices = [];
		var vertices = [];
		var normals = [];
		var uvs = [];

		// helper variables

		var groupStart = 0;
		var groupCount = 0;

		// allow single and array values for "shapes" parameter

		if ( Array.isArray( shapes ) === false ) {

			addShape( shapes );

		} else {

			for ( var i = 0; i < shapes.length; i ++ ) {

				addShape( shapes[ i ] );

				this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support

				groupStart += groupCount;
				groupCount = 0;

			}

		}

		// build geometry

		this.setIndex( indices );
		this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
		this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );


		// helper functions

		function addShape( shape ) {

			var i, l, shapeHole;

			var indexOffset = vertices.length / 3;
			var points = shape.extractPoints( curveSegments );

			var shapeVertices = points.shape;
			var shapeHoles = points.holes;

			// check direction of vertices

			if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {

				shapeVertices = shapeVertices.reverse();

			}

			for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {

				shapeHole = shapeHoles[ i ];

				if ( ShapeUtils.isClockWise( shapeHole ) === true ) {

					shapeHoles[ i ] = shapeHole.reverse();

				}

			}

			var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );

			// join vertices of inner and outer paths to a single array

			for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {

				shapeHole = shapeHoles[ i ];
				shapeVertices = shapeVertices.concat( shapeHole );

			}

			// vertices, normals, uvs

			for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {

				var vertex = shapeVertices[ i ];

				vertices.push( vertex.x, vertex.y, 0 );
				normals.push( 0, 0, 1 );
				uvs.push( vertex.x, vertex.y ); // world uvs

			}

			// incides

			for ( i = 0, l = faces.length; i < l; i ++ ) {

				var face = faces[ i ];

				var a = face[ 0 ] + indexOffset;
				var b = face[ 1 ] + indexOffset;
				var c = face[ 2 ] + indexOffset;

				indices.push( a, b, c );
				groupCount += 3;

			}

		}

	}

	ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
	ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;

	ShapeBufferGeometry.prototype.toJSON = function () {

		var data = BufferGeometry.prototype.toJSON.call( this );

		var shapes = this.parameters.shapes;

		return toJSON$1( shapes, data );

	};

	//

	function toJSON$1( shapes, data ) {

		data.shapes = [];

		if ( Array.isArray( shapes ) ) {

			for ( var i = 0, l = shapes.length; i < l; i ++ ) {

				var shape = shapes[ i ];

				data.shapes.push( shape.uuid );

			}

		} else {

			data.shapes.push( shapes.uuid );

		}

		return data;

	}

	/**
	 * @author WestLangley / http://github.com/WestLangley
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	function EdgesGeometry( geometry, thresholdAngle ) {

		BufferGeometry.call( this );

		this.type = 'EdgesGeometry';

		this.parameters = {
			thresholdAngle: thresholdAngle
		};

		thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;

		// buffer

		var vertices = [];

		// helper variables

		var thresholdDot = Math.cos( MathUtils.DEG2RAD * thresholdAngle );
		var edge = [ 0, 0 ], edges = {}, edge1, edge2;
		var key, keys = [ 'a', 'b', 'c' ];

		// prepare source geometry

		var geometry2;

		if ( geometry.isBufferGeometry ) {

			geometry2 = new Geometry();
			geometry2.fromBufferGeometry( geometry );

		} else {

			geometry2 = geometry.clone();

		}

		geometry2.mergeVertices();
		geometry2.computeFaceNormals();

		var sourceVertices = geometry2.vertices;
		var faces = geometry2.faces;

		// now create a data structure where each entry represents an edge with its adjoining faces

		for ( var i = 0, l = faces.length; i < l; i ++ ) {

			var face = faces[ i ];

			for ( var j = 0; j < 3; j ++ ) {

				edge1 = face[ keys[ j ] ];
				edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
				edge[ 0 ] = Math.min( edge1, edge2 );
				edge[ 1 ] = Math.max( edge1, edge2 );

				key = edge[ 0 ] + ',' + edge[ 1 ];

				if ( edges[ key ] === undefined ) {

					edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };

				} else {

					edges[ key ].face2 = i;

				}

			}

		}

		// generate vertices

		for ( key in edges ) {

			var e = edges[ key ];

			// an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.

			if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {

				var vertex = sourceVertices[ e.index1 ];
				vertices.push( vertex.x, vertex.y, vertex.z );

				vertex = sourceVertices[ e.index2 ];
				vertices.push( vertex.x, vertex.y, vertex.z );

			}

		}

		// build geometry

		this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );

	}

	EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
	EdgesGeometry.prototype.constructor = EdgesGeometry;

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	// CylinderGeometry

	function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {

		Geometry.call( this );

		this.type = 'CylinderGeometry';

		this.parameters = {
			radiusTop: radiusTop,
			radiusBottom: radiusBottom,
			height: height,
			radialSegments: radialSegments,
			heightSegments: heightSegments,
			openEnded: openEnded,
			thetaStart: thetaStart,
			thetaLength: thetaLength
		};

		this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
		this.mergeVertices();

	}

	CylinderGeometry.prototype = Object.create( Geometry.prototype );
	CylinderGeometry.prototype.constructor = CylinderGeometry;

	// CylinderBufferGeometry

	function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {

		BufferGeometry.call( this );

		this.type = 'CylinderBufferGeometry';

		this.parameters = {
			radiusTop: radiusTop,
			radiusBottom: radiusBottom,
			height: height,
			radialSegments: radialSegments,
			heightSegments: heightSegments,
			openEnded: openEnded,
			thetaStart: thetaStart,
			thetaLength: thetaLength
		};

		var scope = this;

		radiusTop = radiusTop !== undefined ? radiusTop : 1;
		radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
		height = height || 1;

		radialSegments = Math.floor( radialSegments ) || 8;
		heightSegments = Math.floor( heightSegments ) || 1;

		openEnded = openEnded !== undefined ? openEnded : false;
		thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
		thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;

		// buffers

		var indices = [];
		var vertices = [];
		var normals = [];
		var uvs = [];

		// helper variables

		var index = 0;
		var indexArray = [];
		var halfHeight = height / 2;
		var groupStart = 0;

		// generate geometry

		generateTorso();

		if ( openEnded === false ) {

			if ( radiusTop > 0 ) { generateCap( true ); }
			if ( radiusBottom > 0 ) { generateCap( false ); }

		}

		// build geometry

		this.setIndex( indices );
		this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
		this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

		function generateTorso() {

			var x, y;
			var normal = new Vector3();
			var vertex = new Vector3();

			var groupCount = 0;

			// this will be used to calculate the normal
			var slope = ( radiusBottom - radiusTop ) / height;

			// generate vertices, normals and uvs

			for ( y = 0; y <= heightSegments; y ++ ) {

				var indexRow = [];

				var v = y / heightSegments;

				// calculate the radius of the current row

				var radius = v * ( radiusBottom - radiusTop ) + radiusTop;

				for ( x = 0; x <= radialSegments; x ++ ) {

					var u = x / radialSegments;

					var theta = u * thetaLength + thetaStart;

					var sinTheta = Math.sin( theta );
					var cosTheta = Math.cos( theta );

					// vertex

					vertex.x = radius * sinTheta;
					vertex.y = - v * height + halfHeight;
					vertex.z = radius * cosTheta;
					vertices.push( vertex.x, vertex.y, vertex.z );

					// normal

					normal.set( sinTheta, slope, cosTheta ).normalize();
					normals.push( normal.x, normal.y, normal.z );

					// uv

					uvs.push( u, 1 - v );

					// save index of vertex in respective row

					indexRow.push( index ++ );

				}

				// now save vertices of the row in our index array

				indexArray.push( indexRow );

			}

			// generate indices

			for ( x = 0; x < radialSegments; x ++ ) {

				for ( y = 0; y < heightSegments; y ++ ) {

					// we use the index array to access the correct indices

					var a = indexArray[ y ][ x ];
					var b = indexArray[ y + 1 ][ x ];
					var c = indexArray[ y + 1 ][ x + 1 ];
					var d = indexArray[ y ][ x + 1 ];

					// faces

					indices.push( a, b, d );
					indices.push( b, c, d );

					// update group counter

					groupCount += 6;

				}

			}

			// add a group to the geometry. this will ensure multi material support

			scope.addGroup( groupStart, groupCount, 0 );

			// calculate new start value for groups

			groupStart += groupCount;

		}

		function generateCap( top ) {

			var x, centerIndexStart, centerIndexEnd;

			var uv = new Vector2();
			var vertex = new Vector3();

			var groupCount = 0;

			var radius = ( top === true ) ? radiusTop : radiusBottom;
			var sign = ( top === true ) ? 1 : - 1;

			// save the index of the first center vertex
			centerIndexStart = index;

			// first we generate the center vertex data of the cap.
			// because the geometry needs one set of uvs per face,
			// we must generate a center vertex per face/segment

			for ( x = 1; x <= radialSegments; x ++ ) {

				// vertex

				vertices.push( 0, halfHeight * sign, 0 );

				// normal

				normals.push( 0, sign, 0 );

				// uv

				uvs.push( 0.5, 0.5 );

				// increase index

				index ++;

			}

			// save the index of the last center vertex

			centerIndexEnd = index;

			// now we generate the surrounding vertices, normals and uvs

			for ( x = 0; x <= radialSegments; x ++ ) {

				var u = x / radialSegments;
				var theta = u * thetaLength + thetaStart;

				var cosTheta = Math.cos( theta );
				var sinTheta = Math.sin( theta );

				// vertex

				vertex.x = radius * sinTheta;
				vertex.y = halfHeight * sign;
				vertex.z = radius * cosTheta;
				vertices.push( vertex.x, vertex.y, vertex.z );

				// normal

				normals.push( 0, sign, 0 );

				// uv

				uv.x = ( cosTheta * 0.5 ) + 0.5;
				uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
				uvs.push( uv.x, uv.y );

				// increase index

				index ++;

			}

			// generate indices

			for ( x = 0; x < radialSegments; x ++ ) {

				var c = centerIndexStart + x;
				var i = centerIndexEnd + x;

				if ( top === true ) {

					// face top

					indices.push( i, i + 1, c );

				} else {

					// face bottom

					indices.push( i + 1, i, c );

				}

				groupCount += 3;

			}

			// add a group to the geometry. this will ensure multi material support

			scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );

			// calculate new start value for groups

			groupStart += groupCount;

		}

	}

	CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
	CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;

	/**
	 * @author abelnation / http://github.com/abelnation
	 */

	// ConeGeometry

	function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {

		CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );

		this.type = 'ConeGeometry';

		this.parameters = {
			radius: radius,
			height: height,
			radialSegments: radialSegments,
			heightSegments: heightSegments,
			openEnded: openEnded,
			thetaStart: thetaStart,
			thetaLength: thetaLength
		};

	}

	ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
	ConeGeometry.prototype.constructor = ConeGeometry;

	// ConeBufferGeometry

	function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {

		CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );

		this.type = 'ConeBufferGeometry';

		this.parameters = {
			radius: radius,
			height: height,
			radialSegments: radialSegments,
			heightSegments: heightSegments,
			openEnded: openEnded,
			thetaStart: thetaStart,
			thetaLength: thetaLength
		};

	}

	ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
	ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;

	/**
	 * @author benaadams / https://twitter.com/ben_a_adams
	 * @author Mugen87 / https://github.com/Mugen87
	 * @author hughes
	 */

	// CircleGeometry

	function CircleGeometry( radius, segments, thetaStart, thetaLength ) {

		Geometry.call( this );

		this.type = 'CircleGeometry';

		this.parameters = {
			radius: radius,
			segments: segments,
			thetaStart: thetaStart,
			thetaLength: thetaLength
		};

		this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
		this.mergeVertices();

	}

	CircleGeometry.prototype = Object.create( Geometry.prototype );
	CircleGeometry.prototype.constructor = CircleGeometry;

	// CircleBufferGeometry

	function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {

		BufferGeometry.call( this );

		this.type = 'CircleBufferGeometry';

		this.parameters = {
			radius: radius,
			segments: segments,
			thetaStart: thetaStart,
			thetaLength: thetaLength
		};

		radius = radius || 1;
		segments = segments !== undefined ? Math.max( 3, segments ) : 8;

		thetaStart = thetaStart !== undefined ? thetaStart : 0;
		thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;

		// buffers

		var indices = [];
		var vertices = [];
		var normals = [];
		var uvs = [];

		// helper variables

		var i, s;
		var vertex = new Vector3();
		var uv = new Vector2();

		// center point

		vertices.push( 0, 0, 0 );
		normals.push( 0, 0, 1 );
		uvs.push( 0.5, 0.5 );

		for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {

			var segment = thetaStart + s / segments * thetaLength;

			// vertex

			vertex.x = radius * Math.cos( segment );
			vertex.y = radius * Math.sin( segment );

			vertices.push( vertex.x, vertex.y, vertex.z );

			// normal

			normals.push( 0, 0, 1 );

			// uvs

			uv.x = ( vertices[ i ] / radius + 1 ) / 2;
			uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;

			uvs.push( uv.x, uv.y );

		}

		// indices

		for ( i = 1; i <= segments; i ++ ) {

			indices.push( i, i + 1, 0 );

		}

		// build geometry

		this.setIndex( indices );
		this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
		this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

	}

	CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
	CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;



	var Geometries = /*#__PURE__*/Object.freeze({
		__proto__: null,
		WireframeGeometry: WireframeGeometry,
		ParametricGeometry: ParametricGeometry,
		ParametricBufferGeometry: ParametricBufferGeometry,
		TetrahedronGeometry: TetrahedronGeometry,
		TetrahedronBufferGeometry: TetrahedronBufferGeometry,
		OctahedronGeometry: OctahedronGeometry,
		OctahedronBufferGeometry: OctahedronBufferGeometry,
		IcosahedronGeometry: IcosahedronGeometry,
		IcosahedronBufferGeometry: IcosahedronBufferGeometry,
		DodecahedronGeometry: DodecahedronGeometry,
		DodecahedronBufferGeometry: DodecahedronBufferGeometry,
		PolyhedronGeometry: PolyhedronGeometry,
		PolyhedronBufferGeometry: PolyhedronBufferGeometry,
		TubeGeometry: TubeGeometry,
		TubeBufferGeometry: TubeBufferGeometry,
		TorusKnotGeometry: TorusKnotGeometry,
		TorusKnotBufferGeometry: TorusKnotBufferGeometry,
		TorusGeometry: TorusGeometry,
		TorusBufferGeometry: TorusBufferGeometry,
		TextGeometry: TextGeometry,
		TextBufferGeometry: TextBufferGeometry,
		SphereGeometry: SphereGeometry,
		SphereBufferGeometry: SphereBufferGeometry,
		RingGeometry: RingGeometry,
		RingBufferGeometry: RingBufferGeometry,
		PlaneGeometry: PlaneGeometry,
		PlaneBufferGeometry: PlaneBufferGeometry,
		LatheGeometry: LatheGeometry,
		LatheBufferGeometry: LatheBufferGeometry,
		ShapeGeometry: ShapeGeometry,
		ShapeBufferGeometry: ShapeBufferGeometry,
		ExtrudeGeometry: ExtrudeGeometry,
		ExtrudeBufferGeometry: ExtrudeBufferGeometry,
		EdgesGeometry: EdgesGeometry,
		ConeGeometry: ConeGeometry,
		ConeBufferGeometry: ConeBufferGeometry,
		CylinderGeometry: CylinderGeometry,
		CylinderBufferGeometry: CylinderBufferGeometry,
		CircleGeometry: CircleGeometry,
		CircleBufferGeometry: CircleBufferGeometry,
		BoxGeometry: BoxGeometry,
		BoxBufferGeometry: BoxBufferGeometry
	});

	/**
	 * @author mrdoob / http://mrdoob.com/
	 *
	 * parameters = {
	 *  color: <THREE.Color>
	 * }
	 */

	function ShadowMaterial( parameters ) {

		Material.call( this );

		this.type = 'ShadowMaterial';

		this.color = new Color( 0x000000 );
		this.transparent = true;

		this.setValues( parameters );

	}

	ShadowMaterial.prototype = Object.create( Material.prototype );
	ShadowMaterial.prototype.constructor = ShadowMaterial;

	ShadowMaterial.prototype.isShadowMaterial = true;

	ShadowMaterial.prototype.copy = function ( source ) {

		Material.prototype.copy.call( this, source );

		this.color.copy( source.color );

		return this;

	};

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function RawShaderMaterial( parameters ) {

		ShaderMaterial.call( this, parameters );

		this.type = 'RawShaderMaterial';

	}

	RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
	RawShaderMaterial.prototype.constructor = RawShaderMaterial;

	RawShaderMaterial.prototype.isRawShaderMaterial = true;

	/**
	 * @author WestLangley / http://github.com/WestLangley
	 *
	 * parameters = {
	 *  color: <hex>,
	 *  roughness: <float>,
	 *  metalness: <float>,
	 *  opacity: <float>,
	 *
	 *  map: new THREE.Texture( <Image> ),
	 *
	 *  lightMap: new THREE.Texture( <Image> ),
	 *  lightMapIntensity: <float>
	 *
	 *  aoMap: new THREE.Texture( <Image> ),
	 *  aoMapIntensity: <float>
	 *
	 *  emissive: <hex>,
	 *  emissiveIntensity: <float>
	 *  emissiveMap: new THREE.Texture( <Image> ),
	 *
	 *  bumpMap: new THREE.Texture( <Image> ),
	 *  bumpScale: <float>,
	 *
	 *  normalMap: new THREE.Texture( <Image> ),
	 *  normalMapType: THREE.TangentSpaceNormalMap,
	 *  normalScale: <Vector2>,
	 *
	 *  displacementMap: new THREE.Texture( <Image> ),
	 *  displacementScale: <float>,
	 *  displacementBias: <float>,
	 *
	 *  roughnessMap: new THREE.Texture( <Image> ),
	 *
	 *  metalnessMap: new THREE.Texture( <Image> ),
	 *
	 *  alphaMap: new THREE.Texture( <Image> ),
	 *
	 *  envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
	 *  envMapIntensity: <float>
	 *
	 *  refractionRatio: <float>,
	 *
	 *  wireframe: <boolean>,
	 *  wireframeLinewidth: <float>,
	 *
	 *  skinning: <bool>,
	 *  morphTargets: <bool>,
	 *  morphNormals: <bool>
	 * }
	 */

	function MeshStandardMaterial( parameters ) {

		Material.call( this );

		this.defines = { 'STANDARD': '' };

		this.type = 'MeshStandardMaterial';

		this.color = new Color( 0xffffff ); // diffuse
		this.roughness = 1.0;
		this.metalness = 0.0;

		this.map = null;

		this.lightMap = null;
		this.lightMapIntensity = 1.0;

		this.aoMap = null;
		this.aoMapIntensity = 1.0;

		this.emissive = new Color( 0x000000 );
		this.emissiveIntensity = 1.0;
		this.emissiveMap = null;

		this.bumpMap = null;
		this.bumpScale = 1;

		this.normalMap = null;
		this.normalMapType = TangentSpaceNormalMap;
		this.normalScale = new Vector2( 1, 1 );

		this.displacementMap = null;
		this.displacementScale = 1;
		this.displacementBias = 0;

		this.roughnessMap = null;

		this.metalnessMap = null;

		this.alphaMap = null;

		this.envMap = null;
		this.envMapIntensity = 1.0;

		this.refractionRatio = 0.98;

		this.wireframe = false;
		this.wireframeLinewidth = 1;
		this.wireframeLinecap = 'round';
		this.wireframeLinejoin = 'round';

		this.skinning = false;
		this.morphTargets = false;
		this.morphNormals = false;

		this.setValues( parameters );

	}

	MeshStandardMaterial.prototype = Object.create( Material.prototype );
	MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;

	MeshStandardMaterial.prototype.isMeshStandardMaterial = true;

	MeshStandardMaterial.prototype.copy = function ( source ) {

		Material.prototype.copy.call( this, source );

		this.defines = { 'STANDARD': '' };

		this.color.copy( source.color );
		this.roughness = source.roughness;
		this.metalness = source.metalness;

		this.map = source.map;

		this.lightMap = source.lightMap;
		this.lightMapIntensity = source.lightMapIntensity;

		this.aoMap = source.aoMap;
		this.aoMapIntensity = source.aoMapIntensity;

		this.emissive.copy( source.emissive );
		this.emissiveMap = source.emissiveMap;
		this.emissiveIntensity = source.emissiveIntensity;

		this.bumpMap = source.bumpMap;
		this.bumpScale = source.bumpScale;

		this.normalMap = source.normalMap;
		this.normalMapType = source.normalMapType;
		this.normalScale.copy( source.normalScale );

		this.displacementMap = source.displacementMap;
		this.displacementScale = source.displacementScale;
		this.displacementBias = source.displacementBias;

		this.roughnessMap = source.roughnessMap;

		this.metalnessMap = source.metalnessMap;

		this.alphaMap = source.alphaMap;

		this.envMap = source.envMap;
		this.envMapIntensity = source.envMapIntensity;

		this.refractionRatio = source.refractionRatio;

		this.wireframe = source.wireframe;
		this.wireframeLinewidth = source.wireframeLinewidth;
		this.wireframeLinecap = source.wireframeLinecap;
		this.wireframeLinejoin = source.wireframeLinejoin;

		this.skinning = source.skinning;
		this.morphTargets = source.morphTargets;
		this.morphNormals = source.morphNormals;

		return this;

	};

	/**
	 * @author WestLangley / http://github.com/WestLangley
	 *
	 * parameters = {
	 *  reflectivity: <float>
	 *  clearcoat: <float>
	 *  clearcoatRoughness: <float>
	 *
	 *  sheen: <Color>
	 *
	 *  clearcoatNormalScale: <Vector2>,
	 *  clearcoatNormalMap: new THREE.Texture( <Image> ),
	 * }
	 */

	function MeshPhysicalMaterial( parameters ) {

		MeshStandardMaterial.call( this );

		this.defines = {

			'STANDARD': '',
			'PHYSICAL': ''

		};

		this.type = 'MeshPhysicalMaterial';

		this.reflectivity = 0.5; // maps to F0 = 0.04

		this.clearcoat = 0.0;
		this.clearcoatRoughness = 0.0;

		this.sheen = null; // null will disable sheen bsdf

		this.clearcoatNormalScale = new Vector2( 1, 1 );
		this.clearcoatNormalMap = null;

		this.transparency = 0.0;

		this.setValues( parameters );

	}

	MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
	MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;

	MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;

	MeshPhysicalMaterial.prototype.copy = function ( source ) {

		MeshStandardMaterial.prototype.copy.call( this, source );

		this.defines = {

			'STANDARD': '',
			'PHYSICAL': ''

		};

		this.reflectivity = source.reflectivity;

		this.clearcoat = source.clearcoat;
		this.clearcoatRoughness = source.clearcoatRoughness;

		if ( source.sheen ) { this.sheen = ( this.sheen || new Color() ).copy( source.sheen ); }
		else { this.sheen = null; }

		this.clearcoatNormalMap = source.clearcoatNormalMap;
		this.clearcoatNormalScale.copy( source.clearcoatNormalScale );

		this.transparency = source.transparency;

		return this;

	};

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author alteredq / http://alteredqualia.com/
	 *
	 * parameters = {
	 *  color: <hex>,
	 *  specular: <hex>,
	 *  shininess: <float>,
	 *  opacity: <float>,
	 *
	 *  map: new THREE.Texture( <Image> ),
	 *
	 *  lightMap: new THREE.Texture( <Image> ),
	 *  lightMapIntensity: <float>
	 *
	 *  aoMap: new THREE.Texture( <Image> ),
	 *  aoMapIntensity: <float>
	 *
	 *  emissive: <hex>,
	 *  emissiveIntensity: <float>
	 *  emissiveMap: new THREE.Texture( <Image> ),
	 *
	 *  bumpMap: new THREE.Texture( <Image> ),
	 *  bumpScale: <float>,
	 *
	 *  normalMap: new THREE.Texture( <Image> ),
	 *  normalMapType: THREE.TangentSpaceNormalMap,
	 *  normalScale: <Vector2>,
	 *
	 *  displacementMap: new THREE.Texture( <Image> ),
	 *  displacementScale: <float>,
	 *  displacementBias: <float>,
	 *
	 *  specularMap: new THREE.Texture( <Image> ),
	 *
	 *  alphaMap: new THREE.Texture( <Image> ),
	 *
	 *  envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
	 *  combine: THREE.MultiplyOperation,
	 *  reflectivity: <float>,
	 *  refractionRatio: <float>,
	 *
	 *  wireframe: <boolean>,
	 *  wireframeLinewidth: <float>,
	 *
	 *  skinning: <bool>,
	 *  morphTargets: <bool>,
	 *  morphNormals: <bool>
	 * }
	 */

	function MeshPhongMaterial( parameters ) {

		Material.call( this );

		this.type = 'MeshPhongMaterial';

		this.color = new Color( 0xffffff ); // diffuse
		this.specular = new Color( 0x111111 );
		this.shininess = 30;

		this.map = null;

		this.lightMap = null;
		this.lightMapIntensity = 1.0;

		this.aoMap = null;
		this.aoMapIntensity = 1.0;

		this.emissive = new Color( 0x000000 );
		this.emissiveIntensity = 1.0;
		this.emissiveMap = null;

		this.bumpMap = null;
		this.bumpScale = 1;

		this.normalMap = null;
		this.normalMapType = TangentSpaceNormalMap;
		this.normalScale = new Vector2( 1, 1 );

		this.displacementMap = null;
		this.displacementScale = 1;
		this.displacementBias = 0;

		this.specularMap = null;

		this.alphaMap = null;

		this.envMap = null;
		this.combine = MultiplyOperation;
		this.reflectivity = 1;
		this.refractionRatio = 0.98;

		this.wireframe = false;
		this.wireframeLinewidth = 1;
		this.wireframeLinecap = 'round';
		this.wireframeLinejoin = 'round';

		this.skinning = false;
		this.morphTargets = false;
		this.morphNormals = false;

		this.setValues( parameters );

	}

	MeshPhongMaterial.prototype = Object.create( Material.prototype );
	MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;

	MeshPhongMaterial.prototype.isMeshPhongMaterial = true;

	MeshPhongMaterial.prototype.copy = function ( source ) {

		Material.prototype.copy.call( this, source );

		this.color.copy( source.color );
		this.specular.copy( source.specular );
		this.shininess = source.shininess;

		this.map = source.map;

		this.lightMap = source.lightMap;
		this.lightMapIntensity = source.lightMapIntensity;

		this.aoMap = source.aoMap;
		this.aoMapIntensity = source.aoMapIntensity;

		this.emissive.copy( source.emissive );
		this.emissiveMap = source.emissiveMap;
		this.emissiveIntensity = source.emissiveIntensity;

		this.bumpMap = source.bumpMap;
		this.bumpScale = source.bumpScale;

		this.normalMap = source.normalMap;
		this.normalMapType = source.normalMapType;
		this.normalScale.copy( source.normalScale );

		this.displacementMap = source.displacementMap;
		this.displacementScale = source.displacementScale;
		this.displacementBias = source.displacementBias;

		this.specularMap = source.specularMap;

		this.alphaMap = source.alphaMap;

		this.envMap = source.envMap;
		this.combine = source.combine;
		this.reflectivity = source.reflectivity;
		this.refractionRatio = source.refractionRatio;

		this.wireframe = source.wireframe;
		this.wireframeLinewidth = source.wireframeLinewidth;
		this.wireframeLinecap = source.wireframeLinecap;
		this.wireframeLinejoin = source.wireframeLinejoin;

		this.skinning = source.skinning;
		this.morphTargets = source.morphTargets;
		this.morphNormals = source.morphNormals;

		return this;

	};

	/**
	 * @author takahirox / http://github.com/takahirox
	 *
	 * parameters = {
	 *  color: <hex>,
	 *  specular: <hex>,
	 *  shininess: <float>,
	 *
	 *  map: new THREE.Texture( <Image> ),
	 *  gradientMap: new THREE.Texture( <Image> ),
	 *
	 *  lightMap: new THREE.Texture( <Image> ),
	 *  lightMapIntensity: <float>
	 *
	 *  aoMap: new THREE.Texture( <Image> ),
	 *  aoMapIntensity: <float>
	 *
	 *  emissive: <hex>,
	 *  emissiveIntensity: <float>
	 *  emissiveMap: new THREE.Texture( <Image> ),
	 *
	 *  bumpMap: new THREE.Texture( <Image> ),
	 *  bumpScale: <float>,
	 *
	 *  normalMap: new THREE.Texture( <Image> ),
	 *  normalMapType: THREE.TangentSpaceNormalMap,
	 *  normalScale: <Vector2>,
	 *
	 *  displacementMap: new THREE.Texture( <Image> ),
	 *  displacementScale: <float>,
	 *  displacementBias: <float>,
	 *
	 *  specularMap: new THREE.Texture( <Image> ),
	 *
	 *  alphaMap: new THREE.Texture( <Image> ),
	 *
	 *  wireframe: <boolean>,
	 *  wireframeLinewidth: <float>,
	 *
	 *  skinning: <bool>,
	 *  morphTargets: <bool>,
	 *  morphNormals: <bool>
	 * }
	 */

	function MeshToonMaterial( parameters ) {

		Material.call( this );

		this.defines = { 'TOON': '' };

		this.type = 'MeshToonMaterial';

		this.color = new Color( 0xffffff );
		this.specular = new Color( 0x111111 );
		this.shininess = 30;

		this.map = null;
		this.gradientMap = null;

		this.lightMap = null;
		this.lightMapIntensity = 1.0;

		this.aoMap = null;
		this.aoMapIntensity = 1.0;

		this.emissive = new Color( 0x000000 );
		this.emissiveIntensity = 1.0;
		this.emissiveMap = null;

		this.bumpMap = null;
		this.bumpScale = 1;

		this.normalMap = null;
		this.normalMapType = TangentSpaceNormalMap;
		this.normalScale = new Vector2( 1, 1 );

		this.displacementMap = null;
		this.displacementScale = 1;
		this.displacementBias = 0;

		this.specularMap = null;

		this.alphaMap = null;

		this.wireframe = false;
		this.wireframeLinewidth = 1;
		this.wireframeLinecap = 'round';
		this.wireframeLinejoin = 'round';

		this.skinning = false;
		this.morphTargets = false;
		this.morphNormals = false;

		this.setValues( parameters );

	}

	MeshToonMaterial.prototype = Object.create( Material.prototype );
	MeshToonMaterial.prototype.constructor = MeshToonMaterial;

	MeshToonMaterial.prototype.isMeshToonMaterial = true;

	MeshToonMaterial.prototype.copy = function ( source ) {

		Material.prototype.copy.call( this, source );

		this.color.copy( source.color );
		this.specular.copy( source.specular );
		this.shininess = source.shininess;

		this.map = source.map;
		this.gradientMap = source.gradientMap;

		this.lightMap = source.lightMap;
		this.lightMapIntensity = source.lightMapIntensity;

		this.aoMap = source.aoMap;
		this.aoMapIntensity = source.aoMapIntensity;

		this.emissive.copy( source.emissive );
		this.emissiveMap = source.emissiveMap;
		this.emissiveIntensity = source.emissiveIntensity;

		this.bumpMap = source.bumpMap;
		this.bumpScale = source.bumpScale;

		this.normalMap = source.normalMap;
		this.normalMapType = source.normalMapType;
		this.normalScale.copy( source.normalScale );

		this.displacementMap = source.displacementMap;
		this.displacementScale = source.displacementScale;
		this.displacementBias = source.displacementBias;

		this.specularMap = source.specularMap;

		this.alphaMap = source.alphaMap;

		this.wireframe = source.wireframe;
		this.wireframeLinewidth = source.wireframeLinewidth;
		this.wireframeLinecap = source.wireframeLinecap;
		this.wireframeLinejoin = source.wireframeLinejoin;

		this.skinning = source.skinning;
		this.morphTargets = source.morphTargets;
		this.morphNormals = source.morphNormals;

		return this;

	};

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author WestLangley / http://github.com/WestLangley
	 *
	 * parameters = {
	 *  opacity: <float>,
	 *
	 *  bumpMap: new THREE.Texture( <Image> ),
	 *  bumpScale: <float>,
	 *
	 *  normalMap: new THREE.Texture( <Image> ),
	 *  normalMapType: THREE.TangentSpaceNormalMap,
	 *  normalScale: <Vector2>,
	 *
	 *  displacementMap: new THREE.Texture( <Image> ),
	 *  displacementScale: <float>,
	 *  displacementBias: <float>,
	 *
	 *  wireframe: <boolean>,
	 *  wireframeLinewidth: <float>
	 *
	 *  skinning: <bool>,
	 *  morphTargets: <bool>,
	 *  morphNormals: <bool>
	 * }
	 */

	function MeshNormalMaterial( parameters ) {

		Material.call( this );

		this.type = 'MeshNormalMaterial';

		this.bumpMap = null;
		this.bumpScale = 1;

		this.normalMap = null;
		this.normalMapType = TangentSpaceNormalMap;
		this.normalScale = new Vector2( 1, 1 );

		this.displacementMap = null;
		this.displacementScale = 1;
		this.displacementBias = 0;

		this.wireframe = false;
		this.wireframeLinewidth = 1;

		this.fog = false;

		this.skinning = false;
		this.morphTargets = false;
		this.morphNormals = false;

		this.setValues( parameters );

	}

	MeshNormalMaterial.prototype = Object.create( Material.prototype );
	MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;

	MeshNormalMaterial.prototype.isMeshNormalMaterial = true;

	MeshNormalMaterial.prototype.copy = function ( source ) {

		Material.prototype.copy.call( this, source );

		this.bumpMap = source.bumpMap;
		this.bumpScale = source.bumpScale;

		this.normalMap = source.normalMap;
		this.normalMapType = source.normalMapType;
		this.normalScale.copy( source.normalScale );

		this.displacementMap = source.displacementMap;
		this.displacementScale = source.displacementScale;
		this.displacementBias = source.displacementBias;

		this.wireframe = source.wireframe;
		this.wireframeLinewidth = source.wireframeLinewidth;

		this.skinning = source.skinning;
		this.morphTargets = source.morphTargets;
		this.morphNormals = source.morphNormals;

		return this;

	};

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author alteredq / http://alteredqualia.com/
	 *
	 * parameters = {
	 *  color: <hex>,
	 *  opacity: <float>,
	 *
	 *  map: new THREE.Texture( <Image> ),
	 *
	 *  lightMap: new THREE.Texture( <Image> ),
	 *  lightMapIntensity: <float>
	 *
	 *  aoMap: new THREE.Texture( <Image> ),
	 *  aoMapIntensity: <float>
	 *
	 *  emissive: <hex>,
	 *  emissiveIntensity: <float>
	 *  emissiveMap: new THREE.Texture( <Image> ),
	 *
	 *  specularMap: new THREE.Texture( <Image> ),
	 *
	 *  alphaMap: new THREE.Texture( <Image> ),
	 *
	 *  envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
	 *  combine: THREE.Multiply,
	 *  reflectivity: <float>,
	 *  refractionRatio: <float>,
	 *
	 *  wireframe: <boolean>,
	 *  wireframeLinewidth: <float>,
	 *
	 *  skinning: <bool>,
	 *  morphTargets: <bool>,
	 *  morphNormals: <bool>
	 * }
	 */

	function MeshLambertMaterial( parameters ) {

		Material.call( this );

		this.type = 'MeshLambertMaterial';

		this.color = new Color( 0xffffff ); // diffuse

		this.map = null;

		this.lightMap = null;
		this.lightMapIntensity = 1.0;

		this.aoMap = null;
		this.aoMapIntensity = 1.0;

		this.emissive = new Color( 0x000000 );
		this.emissiveIntensity = 1.0;
		this.emissiveMap = null;

		this.specularMap = null;

		this.alphaMap = null;

		this.envMap = null;
		this.combine = MultiplyOperation;
		this.reflectivity = 1;
		this.refractionRatio = 0.98;

		this.wireframe = false;
		this.wireframeLinewidth = 1;
		this.wireframeLinecap = 'round';
		this.wireframeLinejoin = 'round';

		this.skinning = false;
		this.morphTargets = false;
		this.morphNormals = false;

		this.setValues( parameters );

	}

	MeshLambertMaterial.prototype = Object.create( Material.prototype );
	MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;

	MeshLambertMaterial.prototype.isMeshLambertMaterial = true;

	MeshLambertMaterial.prototype.copy = function ( source ) {

		Material.prototype.copy.call( this, source );

		this.color.copy( source.color );

		this.map = source.map;

		this.lightMap = source.lightMap;
		this.lightMapIntensity = source.lightMapIntensity;

		this.aoMap = source.aoMap;
		this.aoMapIntensity = source.aoMapIntensity;

		this.emissive.copy( source.emissive );
		this.emissiveMap = source.emissiveMap;
		this.emissiveIntensity = source.emissiveIntensity;

		this.specularMap = source.specularMap;

		this.alphaMap = source.alphaMap;

		this.envMap = source.envMap;
		this.combine = source.combine;
		this.reflectivity = source.reflectivity;
		this.refractionRatio = source.refractionRatio;

		this.wireframe = source.wireframe;
		this.wireframeLinewidth = source.wireframeLinewidth;
		this.wireframeLinecap = source.wireframeLinecap;
		this.wireframeLinejoin = source.wireframeLinejoin;

		this.skinning = source.skinning;
		this.morphTargets = source.morphTargets;
		this.morphNormals = source.morphNormals;

		return this;

	};

	/**
	 * @author WestLangley / http://github.com/WestLangley
	 *
	 * parameters = {
	 *  color: <hex>,
	 *  opacity: <float>,
	 *
	 *  matcap: new THREE.Texture( <Image> ),
	 *
	 *  map: new THREE.Texture( <Image> ),
	 *
	 *  bumpMap: new THREE.Texture( <Image> ),
	 *  bumpScale: <float>,
	 *
	 *  normalMap: new THREE.Texture( <Image> ),
	 *  normalMapType: THREE.TangentSpaceNormalMap,
	 *  normalScale: <Vector2>,
	 *
	 *  displacementMap: new THREE.Texture( <Image> ),
	 *  displacementScale: <float>,
	 *  displacementBias: <float>,
	 *
	 *  alphaMap: new THREE.Texture( <Image> ),
	 *
	 *  skinning: <bool>,
	 *  morphTargets: <bool>,
	 *  morphNormals: <bool>
	 * }
	 */

	function MeshMatcapMaterial( parameters ) {

		Material.call( this );

		this.defines = { 'MATCAP': '' };

		this.type = 'MeshMatcapMaterial';

		this.color = new Color( 0xffffff ); // diffuse

		this.matcap = null;

		this.map = null;

		this.bumpMap = null;
		this.bumpScale = 1;

		this.normalMap = null;
		this.normalMapType = TangentSpaceNormalMap;
		this.normalScale = new Vector2( 1, 1 );

		this.displacementMap = null;
		this.displacementScale = 1;
		this.displacementBias = 0;

		this.alphaMap = null;

		this.skinning = false;
		this.morphTargets = false;
		this.morphNormals = false;

		this.setValues( parameters );

	}

	MeshMatcapMaterial.prototype = Object.create( Material.prototype );
	MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;

	MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;

	MeshMatcapMaterial.prototype.copy = function ( source ) {

		Material.prototype.copy.call( this, source );

		this.defines = { 'MATCAP': '' };

		this.color.copy( source.color );

		this.matcap = source.matcap;

		this.map = source.map;

		this.bumpMap = source.bumpMap;
		this.bumpScale = source.bumpScale;

		this.normalMap = source.normalMap;
		this.normalMapType = source.normalMapType;
		this.normalScale.copy( source.normalScale );

		this.displacementMap = source.displacementMap;
		this.displacementScale = source.displacementScale;
		this.displacementBias = source.displacementBias;

		this.alphaMap = source.alphaMap;

		this.skinning = source.skinning;
		this.morphTargets = source.morphTargets;
		this.morphNormals = source.morphNormals;

		return this;

	};

	/**
	 * @author alteredq / http://alteredqualia.com/
	 *
	 * parameters = {
	 *  color: <hex>,
	 *  opacity: <float>,
	 *
	 *  linewidth: <float>,
	 *
	 *  scale: <float>,
	 *  dashSize: <float>,
	 *  gapSize: <float>
	 * }
	 */

	function LineDashedMaterial( parameters ) {

		LineBasicMaterial.call( this );

		this.type = 'LineDashedMaterial';

		this.scale = 1;
		this.dashSize = 3;
		this.gapSize = 1;

		this.setValues( parameters );

	}

	LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
	LineDashedMaterial.prototype.constructor = LineDashedMaterial;

	LineDashedMaterial.prototype.isLineDashedMaterial = true;

	LineDashedMaterial.prototype.copy = function ( source ) {

		LineBasicMaterial.prototype.copy.call( this, source );

		this.scale = source.scale;
		this.dashSize = source.dashSize;
		this.gapSize = source.gapSize;

		return this;

	};



	var Materials = /*#__PURE__*/Object.freeze({
		__proto__: null,
		ShadowMaterial: ShadowMaterial,
		SpriteMaterial: SpriteMaterial,
		RawShaderMaterial: RawShaderMaterial,
		ShaderMaterial: ShaderMaterial,
		PointsMaterial: PointsMaterial,
		MeshPhysicalMaterial: MeshPhysicalMaterial,
		MeshStandardMaterial: MeshStandardMaterial,
		MeshPhongMaterial: MeshPhongMaterial,
		MeshToonMaterial: MeshToonMaterial,
		MeshNormalMaterial: MeshNormalMaterial,
		MeshLambertMaterial: MeshLambertMaterial,
		MeshDepthMaterial: MeshDepthMaterial,
		MeshDistanceMaterial: MeshDistanceMaterial,
		MeshBasicMaterial: MeshBasicMaterial,
		MeshMatcapMaterial: MeshMatcapMaterial,
		LineDashedMaterial: LineDashedMaterial,
		LineBasicMaterial: LineBasicMaterial,
		Material: Material
	});

	/**
	 * @author tschw
	 * @author Ben Houston / http://clara.io/
	 * @author David Sarno / http://lighthaus.us/
	 */

	var AnimationUtils = {

		// same as Array.prototype.slice, but also works on typed arrays
		arraySlice: function ( array, from, to ) {

			if ( AnimationUtils.isTypedArray( array ) ) {

				// in ios9 array.subarray(from, undefined) will return empty array
				// but array.subarray(from) or array.subarray(from, len) is correct
				return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );

			}

			return array.slice( from, to );

		},

		// converts an array to a specific type
		convertArray: function ( array, type, forceClone ) {

			if ( ! array || // let 'undefined' and 'null' pass
				! forceClone && array.constructor === type ) { return array; }

			if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {

				return new type( array ); // create typed array

			}

			return Array.prototype.slice.call( array ); // create Array

		},

		isTypedArray: function ( object ) {

			return ArrayBuffer.isView( object ) &&
				! ( object instanceof DataView );

		},

		// returns an array by which times and values can be sorted
		getKeyframeOrder: function ( times ) {

			function compareTime( i, j ) {

				return times[ i ] - times[ j ];

			}

			var n = times.length;
			var result = new Array( n );
			for ( var i = 0; i !== n; ++ i ) { result[ i ] = i; }

			result.sort( compareTime );

			return result;

		},

		// uses the array previously returned by 'getKeyframeOrder' to sort data
		sortedArray: function ( values, stride, order ) {

			var nValues = values.length;
			var result = new values.constructor( nValues );

			for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {

				var srcOffset = order[ i ] * stride;

				for ( var j = 0; j !== stride; ++ j ) {

					result[ dstOffset ++ ] = values[ srcOffset + j ];

				}

			}

			return result;

		},

		// function for parsing AOS keyframe formats
		flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {

			var i = 1, key = jsonKeys[ 0 ];

			while ( key !== undefined && key[ valuePropertyName ] === undefined ) {

				key = jsonKeys[ i ++ ];

			}

			if ( key === undefined ) { return; } // no data

			var value = key[ valuePropertyName ];
			if ( value === undefined ) { return; } // no data

			if ( Array.isArray( value ) ) {

				do {

					value = key[ valuePropertyName ];

					if ( value !== undefined ) {

						times.push( key.time );
						values.push.apply( values, value ); // push all elements

					}

					key = jsonKeys[ i ++ ];

				} while ( key !== undefined );

			} else if ( value.toArray !== undefined ) {

				// ...assume THREE.Math-ish

				do {

					value = key[ valuePropertyName ];

					if ( value !== undefined ) {

						times.push( key.time );
						value.toArray( values, values.length );

					}

					key = jsonKeys[ i ++ ];

				} while ( key !== undefined );

			} else {

				// otherwise push as-is

				do {

					value = key[ valuePropertyName ];

					if ( value !== undefined ) {

						times.push( key.time );
						values.push( value );

					}

					key = jsonKeys[ i ++ ];

				} while ( key !== undefined );

			}

		},

		subclip: function ( sourceClip, name, startFrame, endFrame, fps ) {

			fps = fps || 30;

			var clip = sourceClip.clone();

			clip.name = name;

			var tracks = [];

			for ( var i = 0; i < clip.tracks.length; ++ i ) {

				var track = clip.tracks[ i ];
				var valueSize = track.getValueSize();

				var times = [];
				var values = [];

				for ( var j = 0; j < track.times.length; ++ j ) {

					var frame = track.times[ j ] * fps;

					if ( frame < startFrame || frame >= endFrame ) { continue; }

					times.push( track.times[ j ] );

					for ( var k = 0; k < valueSize; ++ k ) {

						values.push( track.values[ j * valueSize + k ] );

					}

				}

				if ( times.length === 0 ) { continue; }

				track.times = AnimationUtils.convertArray( times, track.times.constructor );
				track.values = AnimationUtils.convertArray( values, track.values.constructor );

				tracks.push( track );

			}

			clip.tracks = tracks;

			// find minimum .times value across all tracks in the trimmed clip

			var minStartTime = Infinity;

			for ( var i = 0; i < clip.tracks.length; ++ i ) {

				if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {

					minStartTime = clip.tracks[ i ].times[ 0 ];

				}

			}

			// shift all tracks such that clip begins at t=0

			for ( var i = 0; i < clip.tracks.length; ++ i ) {

				clip.tracks[ i ].shift( - 1 * minStartTime );

			}

			clip.resetDuration();

			return clip;

		}

	};

	/**
	 * Abstract base class of interpolants over parametric samples.
	 *
	 * The parameter domain is one dimensional, typically the time or a path
	 * along a curve defined by the data.
	 *
	 * The sample values can have any dimensionality and derived classes may
	 * apply special interpretations to the data.
	 *
	 * This class provides the interval seek in a Template Method, deferring
	 * the actual interpolation to derived classes.
	 *
	 * Time complexity is O(1) for linear access crossing at most two points
	 * and O(log N) for random access, where N is the number of positions.
	 *
	 * References:
	 *
	 * 		http://www.oodesign.com/template-method-pattern.html
	 *
	 * @author tschw
	 */

	function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {

		this.parameterPositions = parameterPositions;
		this._cachedIndex = 0;

		this.resultBuffer = resultBuffer !== undefined ?
			resultBuffer : new sampleValues.constructor( sampleSize );
		this.sampleValues = sampleValues;
		this.valueSize = sampleSize;

	}

	Object.assign( Interpolant.prototype, {

		evaluate: function ( t ) {

			var pp = this.parameterPositions,
				i1 = this._cachedIndex,

				t1 = pp[ i1 ],
				t0 = pp[ i1 - 1 ];

			validate_interval: {

				seek: {

					var right;

					linear_scan: {

						//- See http://jsperf.com/comparison-to-undefined/3
						//- slower code:
						//-
						//- 				if ( t >= t1 || t1 === undefined ) {
						forward_scan: if ( ! ( t < t1 ) ) {

							for ( var giveUpAt = i1 + 2; ; ) {

								if ( t1 === undefined ) {

									if ( t < t0 ) { break forward_scan; }

									// after end

									i1 = pp.length;
									this._cachedIndex = i1;
									return this.afterEnd_( i1 - 1, t, t0 );

								}

								if ( i1 === giveUpAt ) { break; } // this loop

								t0 = t1;
								t1 = pp[ ++ i1 ];

								if ( t < t1 ) {

									// we have arrived at the sought interval
									break seek;

								}

							}

							// prepare binary search on the right side of the index
							right = pp.length;
							break linear_scan;

						}

						//- slower code:
						//-					if ( t < t0 || t0 === undefined ) {
						if ( ! ( t >= t0 ) ) {

							// looping?

							var t1global = pp[ 1 ];

							if ( t < t1global ) {

								i1 = 2; // + 1, using the scan for the details
								t0 = t1global;

							}

							// linear reverse scan

							for ( var giveUpAt = i1 - 2; ; ) {

								if ( t0 === undefined ) {

									// before start

									this._cachedIndex = 0;
									return this.beforeStart_( 0, t, t1 );

								}

								if ( i1 === giveUpAt ) { break; } // this loop

								t1 = t0;
								t0 = pp[ -- i1 - 1 ];

								if ( t >= t0 ) {

									// we have arrived at the sought interval
									break seek;

								}

							}

							// prepare binary search on the left side of the index
							right = i1;
							i1 = 0;
							break linear_scan;

						}

						// the interval is valid

						break validate_interval;

					} // linear scan

					// binary search

					while ( i1 < right ) {

						var mid = ( i1 + right ) >>> 1;

						if ( t < pp[ mid ] ) {

							right = mid;

						} else {

							i1 = mid + 1;

						}

					}

					t1 = pp[ i1 ];
					t0 = pp[ i1 - 1 ];

					// check boundary cases, again

					if ( t0 === undefined ) {

						this._cachedIndex = 0;
						return this.beforeStart_( 0, t, t1 );

					}

					if ( t1 === undefined ) {

						i1 = pp.length;
						this._cachedIndex = i1;
						return this.afterEnd_( i1 - 1, t0, t );

					}

				} // seek

				this._cachedIndex = i1;

				this.intervalChanged_( i1, t0, t1 );

			} // validate_interval

			return this.interpolate_( i1, t0, t, t1 );

		},

		settings: null, // optional, subclass-specific settings structure
		// Note: The indirection allows central control of many interpolants.

		// --- Protected interface

		DefaultSettings_: {},

		getSettings_: function () {

			return this.settings || this.DefaultSettings_;

		},

		copySampleValue_: function ( index ) {

			// copies a sample value to the result buffer

			var result = this.resultBuffer,
				values = this.sampleValues,
				stride = this.valueSize,
				offset = index * stride;

			for ( var i = 0; i !== stride; ++ i ) {

				result[ i ] = values[ offset + i ];

			}

			return result;

		},

		// Template methods for derived classes:

		interpolate_: function ( /* i1, t0, t, t1 */ ) {

			throw new Error( 'call to abstract method' );
			// implementations shall return this.resultBuffer

		},

		intervalChanged_: function ( /* i1, t0, t1 */ ) {

			// empty

		}

	} );

	//!\ DECLARE ALIAS AFTER assign prototype !
	Object.assign( Interpolant.prototype, {

		//( 0, t, t0 ), returns this.resultBuffer
		beforeStart_: Interpolant.prototype.copySampleValue_,

		//( N-1, tN-1, t ), returns this.resultBuffer
		afterEnd_: Interpolant.prototype.copySampleValue_,

	} );

	/**
	 * Fast and simple cubic spline interpolant.
	 *
	 * It was derived from a Hermitian construction setting the first derivative
	 * at each sample position to the linear slope between neighboring positions
	 * over their parameter interval.
	 *
	 * @author tschw
	 */

	function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {

		Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );

		this._weightPrev = - 0;
		this._offsetPrev = - 0;
		this._weightNext = - 0;
		this._offsetNext = - 0;

	}

	CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {

		constructor: CubicInterpolant,

		DefaultSettings_: {

			endingStart: ZeroCurvatureEnding,
			endingEnd: ZeroCurvatureEnding

		},

		intervalChanged_: function ( i1, t0, t1 ) {

			var pp = this.parameterPositions,
				iPrev = i1 - 2,
				iNext = i1 + 1,

				tPrev = pp[ iPrev ],
				tNext = pp[ iNext ];

			if ( tPrev === undefined ) {

				switch ( this.getSettings_().endingStart ) {

					case ZeroSlopeEnding:

						// f'(t0) = 0
						iPrev = i1;
						tPrev = 2 * t0 - t1;

						break;

					case WrapAroundEnding:

						// use the other end of the curve
						iPrev = pp.length - 2;
						tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];

						break;

					default: // ZeroCurvatureEnding

						// f''(t0) = 0 a.k.a. Natural Spline
						iPrev = i1;
						tPrev = t1;

				}

			}

			if ( tNext === undefined ) {

				switch ( this.getSettings_().endingEnd ) {

					case ZeroSlopeEnding:

						// f'(tN) = 0
						iNext = i1;
						tNext = 2 * t1 - t0;

						break;

					case WrapAroundEnding:

						// use the other end of the curve
						iNext = 1;
						tNext = t1 + pp[ 1 ] - pp[ 0 ];

						break;

					default: // ZeroCurvatureEnding

						// f''(tN) = 0, a.k.a. Natural Spline
						iNext = i1 - 1;
						tNext = t0;

				}

			}

			var halfDt = ( t1 - t0 ) * 0.5,
				stride = this.valueSize;

			this._weightPrev = halfDt / ( t0 - tPrev );
			this._weightNext = halfDt / ( tNext - t1 );
			this._offsetPrev = iPrev * stride;
			this._offsetNext = iNext * stride;

		},

		interpolate_: function ( i1, t0, t, t1 ) {

			var result = this.resultBuffer,
				values = this.sampleValues,
				stride = this.valueSize,

				o1 = i1 * stride,		o0 = o1 - stride,
				oP = this._offsetPrev, 	oN = this._offsetNext,
				wP = this._weightPrev,	wN = this._weightNext,

				p = ( t - t0 ) / ( t1 - t0 ),
				pp = p * p,
				ppp = pp * p;

			// evaluate polynomials

			var sP = - wP * ppp + 2 * wP * pp - wP * p;
			var s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
			var s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
			var sN = wN * ppp - wN * pp;

			// combine data linearly

			for ( var i = 0; i !== stride; ++ i ) {

				result[ i ] =
						sP * values[ oP + i ] +
						s0 * values[ o0 + i ] +
						s1 * values[ o1 + i ] +
						sN * values[ oN + i ];

			}

			return result;

		}

	} );

	/**
	 * @author tschw
	 */

	function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {

		Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );

	}

	LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {

		constructor: LinearInterpolant,

		interpolate_: function ( i1, t0, t, t1 ) {

			var result = this.resultBuffer,
				values = this.sampleValues,
				stride = this.valueSize,

				offset1 = i1 * stride,
				offset0 = offset1 - stride,

				weight1 = ( t - t0 ) / ( t1 - t0 ),
				weight0 = 1 - weight1;

			for ( var i = 0; i !== stride; ++ i ) {

				result[ i ] =
						values[ offset0 + i ] * weight0 +
						values[ offset1 + i ] * weight1;

			}

			return result;

		}

	} );

	/**
	 *
	 * Interpolant that evaluates to the sample value at the position preceeding
	 * the parameter.
	 *
	 * @author tschw
	 */

	function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {

		Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );

	}

	DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {

		constructor: DiscreteInterpolant,

		interpolate_: function ( i1 /*, t0, t, t1 */ ) {

			return this.copySampleValue_( i1 - 1 );

		}

	} );

	/**
	 *
	 * A timed sequence of keyframes for a specific property.
	 *
	 *
	 * @author Ben Houston / http://clara.io/
	 * @author David Sarno / http://lighthaus.us/
	 * @author tschw
	 */

	function KeyframeTrack( name, times, values, interpolation ) {

		if ( name === undefined ) { throw new Error( 'THREE.KeyframeTrack: track name is undefined' ); }
		if ( times === undefined || times.length === 0 ) { throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name ); }

		this.name = name;

		this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
		this.values = AnimationUtils.convertArray( values, this.ValueBufferType );

		this.setInterpolation( interpolation || this.DefaultInterpolation );

	}

	// Static methods

	Object.assign( KeyframeTrack, {

		// Serialization (in static context, because of constructor invocation
		// and automatic invocation of .toJSON):

		toJSON: function ( track ) {

			var trackType = track.constructor;

			var json;

			// derived classes can define a static toJSON method
			if ( trackType.toJSON !== undefined ) {

				json = trackType.toJSON( track );

			} else {

				// by default, we assume the data can be serialized as-is
				json = {

					'name': track.name,
					'times': AnimationUtils.convertArray( track.times, Array ),
					'values': AnimationUtils.convertArray( track.values, Array )

				};

				var interpolation = track.getInterpolation();

				if ( interpolation !== track.DefaultInterpolation ) {

					json.interpolation = interpolation;

				}

			}

			json.type = track.ValueTypeName; // mandatory

			return json;

		}

	} );

	Object.assign( KeyframeTrack.prototype, {

		constructor: KeyframeTrack,

		TimeBufferType: Float32Array,

		ValueBufferType: Float32Array,

		DefaultInterpolation: InterpolateLinear,

		InterpolantFactoryMethodDiscrete: function ( result ) {

			return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );

		},

		InterpolantFactoryMethodLinear: function ( result ) {

			return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );

		},

		InterpolantFactoryMethodSmooth: function ( result ) {

			return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );

		},

		setInterpolation: function ( interpolation ) {

			var factoryMethod;

			switch ( interpolation ) {

				case InterpolateDiscrete:

					factoryMethod = this.InterpolantFactoryMethodDiscrete;

					break;

				case InterpolateLinear:

					factoryMethod = this.InterpolantFactoryMethodLinear;

					break;

				case InterpolateSmooth:

					factoryMethod = this.InterpolantFactoryMethodSmooth;

					break;

			}

			if ( factoryMethod === undefined ) {

				var message = "unsupported interpolation for " +
					this.ValueTypeName + " keyframe track named " + this.name;

				if ( this.createInterpolant === undefined ) {

					// fall back to default, unless the default itself is messed up
					if ( interpolation !== this.DefaultInterpolation ) {

						this.setInterpolation( this.DefaultInterpolation );

					} else {

						throw new Error( message ); // fatal, in this case

					}

				}

				console.warn( 'THREE.KeyframeTrack:', message );
				return this;

			}

			this.createInterpolant = factoryMethod;

			return this;

		},

		getInterpolation: function () {

			switch ( this.createInterpolant ) {

				case this.InterpolantFactoryMethodDiscrete:

					return InterpolateDiscrete;

				case this.InterpolantFactoryMethodLinear:

					return InterpolateLinear;

				case this.InterpolantFactoryMethodSmooth:

					return InterpolateSmooth;

			}

		},

		getValueSize: function () {

			return this.values.length / this.times.length;

		},

		// move all keyframes either forwards or backwards in time
		shift: function ( timeOffset ) {

			if ( timeOffset !== 0.0 ) {

				var times = this.times;

				for ( var i = 0, n = times.length; i !== n; ++ i ) {

					times[ i ] += timeOffset;

				}

			}

			return this;

		},

		// scale all keyframe times by a factor (useful for frame <-> seconds conversions)
		scale: function ( timeScale ) {

			if ( timeScale !== 1.0 ) {

				var times = this.times;

				for ( var i = 0, n = times.length; i !== n; ++ i ) {

					times[ i ] *= timeScale;

				}

			}

			return this;

		},

		// removes keyframes before and after animation without changing any values within the range [startTime, endTime].
		// IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
		trim: function ( startTime, endTime ) {

			var times = this.times,
				nKeys = times.length,
				from = 0,
				to = nKeys - 1;

			while ( from !== nKeys && times[ from ] < startTime ) {

				++ from;

			}

			while ( to !== - 1 && times[ to ] > endTime ) {

				-- to;

			}

			++ to; // inclusive -> exclusive bound

			if ( from !== 0 || to !== nKeys ) {

				// empty tracks are forbidden, so keep at least one keyframe
				if ( from >= to ) { to = Math.max( to, 1 ), from = to - 1; }

				var stride = this.getValueSize();
				this.times = AnimationUtils.arraySlice( times, from, to );
				this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );

			}

			return this;

		},

		// ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
		validate: function () {

			var valid = true;

			var valueSize = this.getValueSize();
			if ( valueSize - Math.floor( valueSize ) !== 0 ) {

				console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
				valid = false;

			}

			var times = this.times,
				values = this.values,

				nKeys = times.length;

			if ( nKeys === 0 ) {

				console.error( 'THREE.KeyframeTrack: Track is empty.', this );
				valid = false;

			}

			var prevTime = null;

			for ( var i = 0; i !== nKeys; i ++ ) {

				var currTime = times[ i ];

				if ( typeof currTime === 'number' && isNaN( currTime ) ) {

					console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
					valid = false;
					break;

				}

				if ( prevTime !== null && prevTime > currTime ) {

					console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
					valid = false;
					break;

				}

				prevTime = currTime;

			}

			if ( values !== undefined ) {

				if ( AnimationUtils.isTypedArray( values ) ) {

					for ( var i = 0, n = values.length; i !== n; ++ i ) {

						var value = values[ i ];

						if ( isNaN( value ) ) {

							console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
							valid = false;
							break;

						}

					}

				}

			}

			return valid;

		},

		// removes equivalent sequential keys as common in morph target sequences
		// (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
		optimize: function () {

			// times or values may be shared with other tracks, so overwriting is unsafe
			var times = AnimationUtils.arraySlice( this.times ),
				values = AnimationUtils.arraySlice( this.values ),
				stride = this.getValueSize(),

				smoothInterpolation = this.getInterpolation() === InterpolateSmooth,

				writeIndex = 1,
				lastIndex = times.length - 1;

			for ( var i = 1; i < lastIndex; ++ i ) {

				var keep = false;

				var time = times[ i ];
				var timeNext = times[ i + 1 ];

				// remove adjacent keyframes scheduled at the same time

				if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {

					if ( ! smoothInterpolation ) {

						// remove unnecessary keyframes same as their neighbors

						var offset = i * stride,
							offsetP = offset - stride,
							offsetN = offset + stride;

						for ( var j = 0; j !== stride; ++ j ) {

							var value = values[ offset + j ];

							if ( value !== values[ offsetP + j ] ||
								value !== values[ offsetN + j ] ) {

								keep = true;
								break;

							}

						}

					} else {

						keep = true;

					}

				}

				// in-place compaction

				if ( keep ) {

					if ( i !== writeIndex ) {

						times[ writeIndex ] = times[ i ];

						var readOffset = i * stride,
							writeOffset = writeIndex * stride;

						for ( var j = 0; j !== stride; ++ j ) {

							values[ writeOffset + j ] = values[ readOffset + j ];

						}

					}

					++ writeIndex;

				}

			}

			// flush last keyframe (compaction looks ahead)

			if ( lastIndex > 0 ) {

				times[ writeIndex ] = times[ lastIndex ];

				for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {

					values[ writeOffset + j ] = values[ readOffset + j ];

				}

				++ writeIndex;

			}

			if ( writeIndex !== times.length ) {

				this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
				this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );

			} else {

				this.times = times;
				this.values = values;

			}

			return this;

		},

		clone: function () {

			var times = AnimationUtils.arraySlice( this.times, 0 );
			var values = AnimationUtils.arraySlice( this.values, 0 );

			var TypedKeyframeTrack = this.constructor;
			var track = new TypedKeyframeTrack( this.name, times, values );

			// Interpolant argument to constructor is not saved, so copy the factory method directly.
			track.createInterpolant = this.createInterpolant;

			return track;

		}

	} );

	/**
	 *
	 * A Track of Boolean keyframe values.
	 *
	 *
	 * @author Ben Houston / http://clara.io/
	 * @author David Sarno / http://lighthaus.us/
	 * @author tschw
	 */

	function BooleanKeyframeTrack( name, times, values ) {

		KeyframeTrack.call( this, name, times, values );

	}

	BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {

		constructor: BooleanKeyframeTrack,

		ValueTypeName: 'bool',
		ValueBufferType: Array,

		DefaultInterpolation: InterpolateDiscrete,

		InterpolantFactoryMethodLinear: undefined,
		InterpolantFactoryMethodSmooth: undefined

		// Note: Actually this track could have a optimized / compressed
		// representation of a single value and a custom interpolant that
		// computes "firstValue ^ isOdd( index )".

	} );

	/**
	 *
	 * A Track of keyframe values that represent color.
	 *
	 *
	 * @author Ben Houston / http://clara.io/
	 * @author David Sarno / http://lighthaus.us/
	 * @author tschw
	 */

	function ColorKeyframeTrack( name, times, values, interpolation ) {

		KeyframeTrack.call( this, name, times, values, interpolation );

	}

	ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {

		constructor: ColorKeyframeTrack,

		ValueTypeName: 'color'

		// ValueBufferType is inherited

		// DefaultInterpolation is inherited

		// Note: Very basic implementation and nothing special yet.
		// However, this is the place for color space parameterization.

	} );

	/**
	 *
	 * A Track of numeric keyframe values.
	 *
	 * @author Ben Houston / http://clara.io/
	 * @author David Sarno / http://lighthaus.us/
	 * @author tschw
	 */

	function NumberKeyframeTrack( name, times, values, interpolation ) {

		KeyframeTrack.call( this, name, times, values, interpolation );

	}

	NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {

		constructor: NumberKeyframeTrack,

		ValueTypeName: 'number'

		// ValueBufferType is inherited

		// DefaultInterpolation is inherited

	} );

	/**
	 * Spherical linear unit quaternion interpolant.
	 *
	 * @author tschw
	 */

	function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {

		Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );

	}

	QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {

		constructor: QuaternionLinearInterpolant,

		interpolate_: function ( i1, t0, t, t1 ) {

			var result = this.resultBuffer,
				values = this.sampleValues,
				stride = this.valueSize,

				offset = i1 * stride,

				alpha = ( t - t0 ) / ( t1 - t0 );

			for ( var end = offset + stride; offset !== end; offset += 4 ) {

				Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );

			}

			return result;

		}

	} );

	/**
	 *
	 * A Track of quaternion keyframe values.
	 *
	 * @author Ben Houston / http://clara.io/
	 * @author David Sarno / http://lighthaus.us/
	 * @author tschw
	 */

	function QuaternionKeyframeTrack( name, times, values, interpolation ) {

		KeyframeTrack.call( this, name, times, values, interpolation );

	}

	QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {

		constructor: QuaternionKeyframeTrack,

		ValueTypeName: 'quaternion',

		// ValueBufferType is inherited

		DefaultInterpolation: InterpolateLinear,

		InterpolantFactoryMethodLinear: function ( result ) {

			return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );

		},

		InterpolantFactoryMethodSmooth: undefined // not yet implemented

	} );

	/**
	 *
	 * A Track that interpolates Strings
	 *
	 *
	 * @author Ben Houston / http://clara.io/
	 * @author David Sarno / http://lighthaus.us/
	 * @author tschw
	 */

	function StringKeyframeTrack( name, times, values, interpolation ) {

		KeyframeTrack.call( this, name, times, values, interpolation );

	}

	StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {

		constructor: StringKeyframeTrack,

		ValueTypeName: 'string',
		ValueBufferType: Array,

		DefaultInterpolation: InterpolateDiscrete,

		InterpolantFactoryMethodLinear: undefined,

		InterpolantFactoryMethodSmooth: undefined

	} );

	/**
	 *
	 * A Track of vectored keyframe values.
	 *
	 *
	 * @author Ben Houston / http://clara.io/
	 * @author David Sarno / http://lighthaus.us/
	 * @author tschw
	 */

	function VectorKeyframeTrack( name, times, values, interpolation ) {

		KeyframeTrack.call( this, name, times, values, interpolation );

	}

	VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {

		constructor: VectorKeyframeTrack,

		ValueTypeName: 'vector'

		// ValueBufferType is inherited

		// DefaultInterpolation is inherited

	} );

	/**
	 *
	 * Reusable set of Tracks that represent an animation.
	 *
	 * @author Ben Houston / http://clara.io/
	 * @author David Sarno / http://lighthaus.us/
	 */

	function AnimationClip( name, duration, tracks ) {

		this.name = name;
		this.tracks = tracks;
		this.duration = ( duration !== undefined ) ? duration : - 1;

		this.uuid = MathUtils.generateUUID();

		// this means it should figure out its duration by scanning the tracks
		if ( this.duration < 0 ) {

			this.resetDuration();

		}

	}

	function getTrackTypeForValueTypeName( typeName ) {

		switch ( typeName.toLowerCase() ) {

			case 'scalar':
			case 'double':
			case 'float':
			case 'number':
			case 'integer':

				return NumberKeyframeTrack;

			case 'vector':
			case 'vector2':
			case 'vector3':
			case 'vector4':

				return VectorKeyframeTrack;

			case 'color':

				return ColorKeyframeTrack;

			case 'quaternion':

				return QuaternionKeyframeTrack;

			case 'bool':
			case 'boolean':

				return BooleanKeyframeTrack;

			case 'string':

				return StringKeyframeTrack;

		}

		throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );

	}

	function parseKeyframeTrack( json ) {

		if ( json.type === undefined ) {

			throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );

		}

		var trackType = getTrackTypeForValueTypeName( json.type );

		if ( json.times === undefined ) {

			var times = [], values = [];

			AnimationUtils.flattenJSON( json.keys, times, values, 'value' );

			json.times = times;
			json.values = values;

		}

		// derived classes can define a static parse method
		if ( trackType.parse !== undefined ) {

			return trackType.parse( json );

		} else {

			// by default, we assume a constructor compatible with the base
			return new trackType( json.name, json.times, json.values, json.interpolation );

		}

	}

	Object.assign( AnimationClip, {

		parse: function ( json ) {

			var tracks = [],
				jsonTracks = json.tracks,
				frameTime = 1.0 / ( json.fps || 1.0 );

			for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {

				tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );

			}

			return new AnimationClip( json.name, json.duration, tracks );

		},

		toJSON: function ( clip ) {

			var tracks = [],
				clipTracks = clip.tracks;

			var json = {

				'name': clip.name,
				'duration': clip.duration,
				'tracks': tracks,
				'uuid': clip.uuid

			};

			for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {

				tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );

			}

			return json;

		},

		CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {

			var numMorphTargets = morphTargetSequence.length;
			var tracks = [];

			for ( var i = 0; i < numMorphTargets; i ++ ) {

				var times = [];
				var values = [];

				times.push(
					( i + numMorphTargets - 1 ) % numMorphTargets,
					i,
					( i + 1 ) % numMorphTargets );

				values.push( 0, 1, 0 );

				var order = AnimationUtils.getKeyframeOrder( times );
				times = AnimationUtils.sortedArray( times, 1, order );
				values = AnimationUtils.sortedArray( values, 1, order );

				// if there is a key at the first frame, duplicate it as the
				// last frame as well for perfect loop.
				if ( ! noLoop && times[ 0 ] === 0 ) {

					times.push( numMorphTargets );
					values.push( values[ 0 ] );

				}

				tracks.push(
					new NumberKeyframeTrack(
						'.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
						times, values
					).scale( 1.0 / fps ) );

			}

			return new AnimationClip( name, - 1, tracks );

		},

		findByName: function ( objectOrClipArray, name ) {

			var clipArray = objectOrClipArray;

			if ( ! Array.isArray( objectOrClipArray ) ) {

				var o = objectOrClipArray;
				clipArray = o.geometry && o.geometry.animations || o.animations;

			}

			for ( var i = 0; i < clipArray.length; i ++ ) {

				if ( clipArray[ i ].name === name ) {

					return clipArray[ i ];

				}

			}

			return null;

		},

		CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {

			var animationToMorphTargets = {};

			// tested with https://regex101.com/ on trick sequences
			// such flamingo_flyA_003, flamingo_run1_003, crdeath0059
			var pattern = /^([\w-]*?)([\d]+)$/;

			// sort morph target names into animation groups based
			// patterns like Walk_001, Walk_002, Run_001, Run_002
			for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {

				var morphTarget = morphTargets[ i ];
				var parts = morphTarget.name.match( pattern );

				if ( parts && parts.length > 1 ) {

					var name = parts[ 1 ];

					var animationMorphTargets = animationToMorphTargets[ name ];
					if ( ! animationMorphTargets ) {

						animationToMorphTargets[ name ] = animationMorphTargets = [];

					}

					animationMorphTargets.push( morphTarget );

				}

			}

			var clips = [];

			for ( var name in animationToMorphTargets ) {

				clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );

			}

			return clips;

		},

		// parse the animation.hierarchy format
		parseAnimation: function ( animation, bones ) {

			if ( ! animation ) {

				console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
				return null;

			}

			var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {

				// only return track if there are actually keys.
				if ( animationKeys.length !== 0 ) {

					var times = [];
					var values = [];

					AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );

					// empty keys are filtered out, so check again
					if ( times.length !== 0 ) {

						destTracks.push( new trackType( trackName, times, values ) );

					}

				}

			};

			var tracks = [];

			var clipName = animation.name || 'default';
			// automatic length determination in AnimationClip.
			var duration = animation.length || - 1;
			var fps = animation.fps || 30;

			var hierarchyTracks = animation.hierarchy || [];

			for ( var h = 0; h < hierarchyTracks.length; h ++ ) {

				var animationKeys = hierarchyTracks[ h ].keys;

				// skip empty tracks
				if ( ! animationKeys || animationKeys.length === 0 ) { continue; }

				// process morph targets
				if ( animationKeys[ 0 ].morphTargets ) {

					// figure out all morph targets used in this track
					var morphTargetNames = {};

					for ( var k = 0; k < animationKeys.length; k ++ ) {

						if ( animationKeys[ k ].morphTargets ) {

							for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {

								morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;

							}

						}

					}

					// create a track for each morph target with all zero
					// morphTargetInfluences except for the keys in which
					// the morphTarget is named.
					for ( var morphTargetName in morphTargetNames ) {

						var times = [];
						var values = [];

						for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {

							var animationKey = animationKeys[ k ];

							times.push( animationKey.time );
							values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );

						}

						tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );

					}

					duration = morphTargetNames.length * ( fps || 1.0 );

				} else {

					// ...assume skeletal animation

					var boneName = '.bones[' + bones[ h ].name + ']';

					addNonemptyTrack(
						VectorKeyframeTrack, boneName + '.position',
						animationKeys, 'pos', tracks );

					addNonemptyTrack(
						QuaternionKeyframeTrack, boneName + '.quaternion',
						animationKeys, 'rot', tracks );

					addNonemptyTrack(
						VectorKeyframeTrack, boneName + '.scale',
						animationKeys, 'scl', tracks );

				}

			}

			if ( tracks.length === 0 ) {

				return null;

			}

			var clip = new AnimationClip( clipName, duration, tracks );

			return clip;

		}

	} );

	Object.assign( AnimationClip.prototype, {

		resetDuration: function () {

			var tracks = this.tracks, duration = 0;

			for ( var i = 0, n = tracks.length; i !== n; ++ i ) {

				var track = this.tracks[ i ];

				duration = Math.max( duration, track.times[ track.times.length - 1 ] );

			}

			this.duration = duration;

			return this;

		},

		trim: function () {

			for ( var i = 0; i < this.tracks.length; i ++ ) {

				this.tracks[ i ].trim( 0, this.duration );

			}

			return this;

		},

		validate: function () {

			var valid = true;

			for ( var i = 0; i < this.tracks.length; i ++ ) {

				valid = valid && this.tracks[ i ].validate();

			}

			return valid;

		},

		optimize: function () {

			for ( var i = 0; i < this.tracks.length; i ++ ) {

				this.tracks[ i ].optimize();

			}

			return this;

		},

		clone: function () {

			var tracks = [];

			for ( var i = 0; i < this.tracks.length; i ++ ) {

				tracks.push( this.tracks[ i ].clone() );

			}

			return new AnimationClip( this.name, this.duration, tracks );

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	var Cache = {

		enabled: false,

		files: {},

		add: function ( key, file ) {

			if ( this.enabled === false ) { return; }

			// console.log( 'THREE.Cache', 'Adding key:', key );

			this.files[ key ] = file;

		},

		get: function ( key ) {

			if ( this.enabled === false ) { return; }

			// console.log( 'THREE.Cache', 'Checking key:', key );

			return this.files[ key ];

		},

		remove: function ( key ) {

			delete this.files[ key ];

		},

		clear: function () {

			this.files = {};

		}

	};

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function LoadingManager( onLoad, onProgress, onError ) {

		var scope = this;

		var isLoading = false;
		var itemsLoaded = 0;
		var itemsTotal = 0;
		var urlModifier = undefined;
		var handlers = [];

		// Refer to #5689 for the reason why we don't set .onStart
		// in the constructor

		this.onStart = undefined;
		this.onLoad = onLoad;
		this.onProgress = onProgress;
		this.onError = onError;

		this.itemStart = function ( url ) {

			itemsTotal ++;

			if ( isLoading === false ) {

				if ( scope.onStart !== undefined ) {

					scope.onStart( url, itemsLoaded, itemsTotal );

				}

			}

			isLoading = true;

		};

		this.itemEnd = function ( url ) {

			itemsLoaded ++;

			if ( scope.onProgress !== undefined ) {

				scope.onProgress( url, itemsLoaded, itemsTotal );

			}

			if ( itemsLoaded === itemsTotal ) {

				isLoading = false;

				if ( scope.onLoad !== undefined ) {

					scope.onLoad();

				}

			}

		};

		this.itemError = function ( url ) {

			if ( scope.onError !== undefined ) {

				scope.onError( url );

			}

		};

		this.resolveURL = function ( url ) {

			if ( urlModifier ) {

				return urlModifier( url );

			}

			return url;

		};

		this.setURLModifier = function ( transform ) {

			urlModifier = transform;

			return this;

		};

		this.addHandler = function ( regex, loader ) {

			handlers.push( regex, loader );

			return this;

		};

		this.removeHandler = function ( regex ) {

			var index = handlers.indexOf( regex );

			if ( index !== - 1 ) {

				handlers.splice( index, 2 );

			}

			return this;

		};

		this.getHandler = function ( file ) {

			for ( var i = 0, l = handlers.length; i < l; i += 2 ) {

				var regex = handlers[ i ];
				var loader = handlers[ i + 1 ];

				if ( regex.global ) { regex.lastIndex = 0; } // see #17920

				if ( regex.test( file ) ) {

					return loader;

				}

			}

			return null;

		};

	}

	var DefaultLoadingManager = new LoadingManager();

	/**
	 * @author alteredq / http://alteredqualia.com/
	 */

	function Loader( manager ) {

		this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;

		this.crossOrigin = 'anonymous';
		this.path = '';
		this.resourcePath = '';

	}

	Object.assign( Loader.prototype, {

		load: function ( /* url, onLoad, onProgress, onError */ ) {},

		parse: function ( /* data */ ) {},

		setCrossOrigin: function ( crossOrigin ) {

			this.crossOrigin = crossOrigin;
			return this;

		},

		setPath: function ( path ) {

			this.path = path;
			return this;

		},

		setResourcePath: function ( resourcePath ) {

			this.resourcePath = resourcePath;
			return this;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	var loading = {};

	function FileLoader( manager ) {

		Loader.call( this, manager );

	}

	FileLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

		constructor: FileLoader,

		load: function ( url, onLoad, onProgress, onError ) {

			if ( url === undefined ) { url = ''; }

			if ( this.path !== undefined ) { url = this.path + url; }

			url = this.manager.resolveURL( url );

			var scope = this;

			var cached = Cache.get( url );

			if ( cached !== undefined ) {

				scope.manager.itemStart( url );

				setTimeout( function () {

					if ( onLoad ) { onLoad( cached ); }

					scope.manager.itemEnd( url );

				}, 0 );

				return cached;

			}

			// Check if request is duplicate

			if ( loading[ url ] !== undefined ) {

				loading[ url ].push( {

					onLoad: onLoad,
					onProgress: onProgress,
					onError: onError

				} );

				return;

			}

			// Check for data: URI
			var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
			var dataUriRegexResult = url.match( dataUriRegex );

			// Safari can not handle Data URIs through XMLHttpRequest so process manually
			if ( dataUriRegexResult ) {

				var mimeType = dataUriRegexResult[ 1 ];
				var isBase64 = !! dataUriRegexResult[ 2 ];
				var data = dataUriRegexResult[ 3 ];

				data = decodeURIComponent( data );

				if ( isBase64 ) { data = atob( data ); }

				try {

					var response;
					var responseType = ( this.responseType || '' ).toLowerCase();

					switch ( responseType ) {

						case 'arraybuffer':
						case 'blob':

							var view = new Uint8Array( data.length );

							for ( var i = 0; i < data.length; i ++ ) {

								view[ i ] = data.charCodeAt( i );

							}

							if ( responseType === 'blob' ) {

								response = new Blob( [ view.buffer ], { type: mimeType } );

							} else {

								response = view.buffer;

							}

							break;

						case 'document':

							var parser = new DOMParser();
							response = parser.parseFromString( data, mimeType );

							break;

						case 'json':

							response = JSON.parse( data );

							break;

						default: // 'text' or other

							response = data;

							break;

					}

					// Wait for next browser tick like standard XMLHttpRequest event dispatching does
					setTimeout( function () {

						if ( onLoad ) { onLoad( response ); }

						scope.manager.itemEnd( url );

					}, 0 );

				} catch ( error ) {

					// Wait for next browser tick like standard XMLHttpRequest event dispatching does
					setTimeout( function () {

						if ( onError ) { onError( error ); }

						scope.manager.itemError( url );
						scope.manager.itemEnd( url );

					}, 0 );

				}

			} else {

				// Initialise array for duplicate requests

				loading[ url ] = [];

				loading[ url ].push( {

					onLoad: onLoad,
					onProgress: onProgress,
					onError: onError

				} );

				var request = new XMLHttpRequest();

				request.open( 'GET', url, true );

				request.addEventListener( 'load', function ( event ) {

					var response = this.response;

					var callbacks = loading[ url ];

					delete loading[ url ];

					if ( this.status === 200 || this.status === 0 ) {

						// Some browsers return HTTP Status 0 when using non-http protocol
						// e.g. 'file://' or 'data://'. Handle as success.

						if ( this.status === 0 ) { console.warn( 'THREE.FileLoader: HTTP Status 0 received.' ); }

						// Add to cache only on HTTP success, so that we do not cache
						// error response bodies as proper responses to requests.
						Cache.add( url, response );

						for ( var i = 0, il = callbacks.length; i < il; i ++ ) {

							var callback = callbacks[ i ];
							if ( callback.onLoad ) { callback.onLoad( response ); }

						}

						scope.manager.itemEnd( url );

					} else {

						for ( var i = 0, il = callbacks.length; i < il; i ++ ) {

							var callback = callbacks[ i ];
							if ( callback.onError ) { callback.onError( event ); }

						}

						scope.manager.itemError( url );
						scope.manager.itemEnd( url );

					}

				}, false );

				request.addEventListener( 'progress', function ( event ) {

					var callbacks = loading[ url ];

					for ( var i = 0, il = callbacks.length; i < il; i ++ ) {

						var callback = callbacks[ i ];
						if ( callback.onProgress ) { callback.onProgress( event ); }

					}

				}, false );

				request.addEventListener( 'error', function ( event ) {

					var callbacks = loading[ url ];

					delete loading[ url ];

					for ( var i = 0, il = callbacks.length; i < il; i ++ ) {

						var callback = callbacks[ i ];
						if ( callback.onError ) { callback.onError( event ); }

					}

					scope.manager.itemError( url );
					scope.manager.itemEnd( url );

				}, false );

				request.addEventListener( 'abort', function ( event ) {

					var callbacks = loading[ url ];

					delete loading[ url ];

					for ( var i = 0, il = callbacks.length; i < il; i ++ ) {

						var callback = callbacks[ i ];
						if ( callback.onError ) { callback.onError( event ); }

					}

					scope.manager.itemError( url );
					scope.manager.itemEnd( url );

				}, false );

				if ( this.responseType !== undefined ) { request.responseType = this.responseType; }
				if ( this.withCredentials !== undefined ) { request.withCredentials = this.withCredentials; }

				if ( request.overrideMimeType ) { request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' ); }

				for ( var header in this.requestHeader ) {

					request.setRequestHeader( header, this.requestHeader[ header ] );

				}

				request.send( null );

			}

			scope.manager.itemStart( url );

			return request;

		},

		setResponseType: function ( value ) {

			this.responseType = value;
			return this;

		},

		setWithCredentials: function ( value ) {

			this.withCredentials = value;
			return this;

		},

		setMimeType: function ( value ) {

			this.mimeType = value;
			return this;

		},

		setRequestHeader: function ( value ) {

			this.requestHeader = value;
			return this;

		}

	} );

	/**
	 * @author bhouston / http://clara.io/
	 */

	function AnimationLoader( manager ) {

		Loader.call( this, manager );

	}

	AnimationLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

		constructor: AnimationLoader,

		load: function ( url, onLoad, onProgress, onError ) {

			var scope = this;

			var loader = new FileLoader( scope.manager );
			loader.setPath( scope.path );
			loader.load( url, function ( text ) {

				onLoad( scope.parse( JSON.parse( text ) ) );

			}, onProgress, onError );

		},

		parse: function ( json ) {

			var animations = [];

			for ( var i = 0; i < json.length; i ++ ) {

				var clip = AnimationClip.parse( json[ i ] );

				animations.push( clip );

			}

			return animations;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 *
	 * Abstract Base class to block based textures loader (dds, pvr, ...)
	 *
	 * Sub classes have to implement the parse() method which will be used in load().
	 */

	function CompressedTextureLoader( manager ) {

		Loader.call( this, manager );

	}

	CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

		constructor: CompressedTextureLoader,

		load: function ( url, onLoad, onProgress, onError ) {

			var scope = this;

			var images = [];

			var texture = new CompressedTexture();
			texture.image = images;

			var loader = new FileLoader( this.manager );
			loader.setPath( this.path );
			loader.setResponseType( 'arraybuffer' );

			function loadTexture( i ) {

				loader.load( url[ i ], function ( buffer ) {

					var texDatas = scope.parse( buffer, true );

					images[ i ] = {
						width: texDatas.width,
						height: texDatas.height,
						format: texDatas.format,
						mipmaps: texDatas.mipmaps
					};

					loaded += 1;

					if ( loaded === 6 ) {

						if ( texDatas.mipmapCount === 1 )
							{ texture.minFilter = LinearFilter; }

						texture.format = texDatas.format;
						texture.needsUpdate = true;

						if ( onLoad ) { onLoad( texture ); }

					}

				}, onProgress, onError );

			}

			if ( Array.isArray( url ) ) {

				var loaded = 0;

				for ( var i = 0, il = url.length; i < il; ++ i ) {

					loadTexture( i );

				}

			} else {

				// compressed cubemap texture stored in a single DDS file

				loader.load( url, function ( buffer ) {

					var texDatas = scope.parse( buffer, true );

					if ( texDatas.isCubemap ) {

						var faces = texDatas.mipmaps.length / texDatas.mipmapCount;

						for ( var f = 0; f < faces; f ++ ) {

							images[ f ] = { mipmaps: [] };

							for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {

								images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
								images[ f ].format = texDatas.format;
								images[ f ].width = texDatas.width;
								images[ f ].height = texDatas.height;

							}

						}

					} else {

						texture.image.width = texDatas.width;
						texture.image.height = texDatas.height;
						texture.mipmaps = texDatas.mipmaps;

					}

					if ( texDatas.mipmapCount === 1 ) {

						texture.minFilter = LinearFilter;

					}

					texture.format = texDatas.format;
					texture.needsUpdate = true;

					if ( onLoad ) { onLoad( texture ); }

				}, onProgress, onError );

			}

			return texture;

		}

	} );

	/**
	 * @author Nikos M. / https://github.com/foo123/
	 *
	 * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
	 *
	 * Sub classes have to implement the parse() method which will be used in load().
	 */

	function DataTextureLoader( manager ) {

		Loader.call( this, manager );

	}

	DataTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

		constructor: DataTextureLoader,

		load: function ( url, onLoad, onProgress, onError ) {

			var scope = this;

			var texture = new DataTexture();

			var loader = new FileLoader( this.manager );
			loader.setResponseType( 'arraybuffer' );
			loader.setPath( this.path );
			loader.load( url, function ( buffer ) {

				var texData = scope.parse( buffer );

				if ( ! texData ) { return; }

				if ( texData.image !== undefined ) {

					texture.image = texData.image;

				} else if ( texData.data !== undefined ) {

					texture.image.width = texData.width;
					texture.image.height = texData.height;
					texture.image.data = texData.data;

				}

				texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
				texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;

				texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
				texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;

				texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;

				if ( texData.format !== undefined ) {

					texture.format = texData.format;

				}
				if ( texData.type !== undefined ) {

					texture.type = texData.type;

				}

				if ( texData.mipmaps !== undefined ) {

					texture.mipmaps = texData.mipmaps;
					texture.minFilter = LinearMipmapLinearFilter; // presumably...

				}

				if ( texData.mipmapCount === 1 ) {

					texture.minFilter = LinearFilter;

				}

				texture.needsUpdate = true;

				if ( onLoad ) { onLoad( texture, texData ); }

			}, onProgress, onError );


			return texture;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function ImageLoader( manager ) {

		Loader.call( this, manager );

	}

	ImageLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

		constructor: ImageLoader,

		load: function ( url, onLoad, onProgress, onError ) {

			if ( this.path !== undefined ) { url = this.path + url; }

			url = this.manager.resolveURL( url );

			var scope = this;

			var cached = Cache.get( url );

			if ( cached !== undefined ) {

				scope.manager.itemStart( url );

				setTimeout( function () {

					if ( onLoad ) { onLoad( cached ); }

					scope.manager.itemEnd( url );

				}, 0 );

				return cached;

			}

			var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );

			function onImageLoad() {

				image.removeEventListener( 'load', onImageLoad, false );
				image.removeEventListener( 'error', onImageError, false );

				Cache.add( url, this );

				if ( onLoad ) { onLoad( this ); }

				scope.manager.itemEnd( url );

			}

			function onImageError( event ) {

				image.removeEventListener( 'load', onImageLoad, false );
				image.removeEventListener( 'error', onImageError, false );

				if ( onError ) { onError( event ); }

				scope.manager.itemError( url );
				scope.manager.itemEnd( url );

			}

			image.addEventListener( 'load', onImageLoad, false );
			image.addEventListener( 'error', onImageError, false );

			if ( url.substr( 0, 5 ) !== 'data:' ) {

				if ( this.crossOrigin !== undefined ) { image.crossOrigin = this.crossOrigin; }

			}

			scope.manager.itemStart( url );

			image.src = url;

			return image;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */


	function CubeTextureLoader( manager ) {

		Loader.call( this, manager );

	}

	CubeTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

		constructor: CubeTextureLoader,

		load: function ( urls, onLoad, onProgress, onError ) {

			var texture = new CubeTexture();

			var loader = new ImageLoader( this.manager );
			loader.setCrossOrigin( this.crossOrigin );
			loader.setPath( this.path );

			var loaded = 0;

			function loadTexture( i ) {

				loader.load( urls[ i ], function ( image ) {

					texture.images[ i ] = image;

					loaded ++;

					if ( loaded === 6 ) {

						texture.needsUpdate = true;

						if ( onLoad ) { onLoad( texture ); }

					}

				}, undefined, onError );

			}

			for ( var i = 0; i < urls.length; ++ i ) {

				loadTexture( i );

			}

			return texture;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function TextureLoader( manager ) {

		Loader.call( this, manager );

	}

	TextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

		constructor: TextureLoader,

		load: function ( url, onLoad, onProgress, onError ) {

			var texture = new Texture();

			var loader = new ImageLoader( this.manager );
			loader.setCrossOrigin( this.crossOrigin );
			loader.setPath( this.path );

			loader.load( url, function ( image ) {

				texture.image = image;

				// JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
				var isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;

				texture.format = isJPEG ? RGBFormat : RGBAFormat;
				texture.needsUpdate = true;

				if ( onLoad !== undefined ) {

					onLoad( texture );

				}

			}, onProgress, onError );

			return texture;

		}

	} );

	/**
	 * @author zz85 / http://www.lab4games.net/zz85/blog
	 * Extensible curve object
	 *
	 * Some common of curve methods:
	 * .getPoint( t, optionalTarget ), .getTangent( t )
	 * .getPointAt( u, optionalTarget ), .getTangentAt( u )
	 * .getPoints(), .getSpacedPoints()
	 * .getLength()
	 * .updateArcLengths()
	 *
	 * This following curves inherit from THREE.Curve:
	 *
	 * -- 2D curves --
	 * THREE.ArcCurve
	 * THREE.CubicBezierCurve
	 * THREE.EllipseCurve
	 * THREE.LineCurve
	 * THREE.QuadraticBezierCurve
	 * THREE.SplineCurve
	 *
	 * -- 3D curves --
	 * THREE.CatmullRomCurve3
	 * THREE.CubicBezierCurve3
	 * THREE.LineCurve3
	 * THREE.QuadraticBezierCurve3
	 *
	 * A series of curves can be represented as a THREE.CurvePath.
	 *
	 **/

	/**************************************************************
	 *	Abstract Curve base class
	 **************************************************************/

	function Curve() {

		this.type = 'Curve';

		this.arcLengthDivisions = 200;

	}

	Object.assign( Curve.prototype, {

		// Virtual base class method to overwrite and implement in subclasses
		//	- t [0 .. 1]

		getPoint: function ( /* t, optionalTarget */ ) {

			console.warn( 'THREE.Curve: .getPoint() not implemented.' );
			return null;

		},

		// Get point at relative position in curve according to arc length
		// - u [0 .. 1]

		getPointAt: function ( u, optionalTarget ) {

			var t = this.getUtoTmapping( u );
			return this.getPoint( t, optionalTarget );

		},

		// Get sequence of points using getPoint( t )

		getPoints: function ( divisions ) {

			if ( divisions === undefined ) { divisions = 5; }

			var points = [];

			for ( var d = 0; d <= divisions; d ++ ) {

				points.push( this.getPoint( d / divisions ) );

			}

			return points;

		},

		// Get sequence of points using getPointAt( u )

		getSpacedPoints: function ( divisions ) {

			if ( divisions === undefined ) { divisions = 5; }

			var points = [];

			for ( var d = 0; d <= divisions; d ++ ) {

				points.push( this.getPointAt( d / divisions ) );

			}

			return points;

		},

		// Get total curve arc length

		getLength: function () {

			var lengths = this.getLengths();
			return lengths[ lengths.length - 1 ];

		},

		// Get list of cumulative segment lengths

		getLengths: function ( divisions ) {

			if ( divisions === undefined ) { divisions = this.arcLengthDivisions; }

			if ( this.cacheArcLengths &&
				( this.cacheArcLengths.length === divisions + 1 ) &&
				! this.needsUpdate ) {

				return this.cacheArcLengths;

			}

			this.needsUpdate = false;

			var cache = [];
			var current, last = this.getPoint( 0 );
			var p, sum = 0;

			cache.push( 0 );

			for ( p = 1; p <= divisions; p ++ ) {

				current = this.getPoint( p / divisions );
				sum += current.distanceTo( last );
				cache.push( sum );
				last = current;

			}

			this.cacheArcLengths = cache;

			return cache; // { sums: cache, sum: sum }; Sum is in the last element.

		},

		updateArcLengths: function () {

			this.needsUpdate = true;
			this.getLengths();

		},

		// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant

		getUtoTmapping: function ( u, distance ) {

			var arcLengths = this.getLengths();

			var i = 0, il = arcLengths.length;

			var targetArcLength; // The targeted u distance value to get

			if ( distance ) {

				targetArcLength = distance;

			} else {

				targetArcLength = u * arcLengths[ il - 1 ];

			}

			// binary search for the index with largest value smaller than target u distance

			var low = 0, high = il - 1, comparison;

			while ( low <= high ) {

				i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats

				comparison = arcLengths[ i ] - targetArcLength;

				if ( comparison < 0 ) {

					low = i + 1;

				} else if ( comparison > 0 ) {

					high = i - 1;

				} else {

					high = i;
					break;

					// DONE

				}

			}

			i = high;

			if ( arcLengths[ i ] === targetArcLength ) {

				return i / ( il - 1 );

			}

			// we could get finer grain at lengths, or use simple interpolation between two points

			var lengthBefore = arcLengths[ i ];
			var lengthAfter = arcLengths[ i + 1 ];

			var segmentLength = lengthAfter - lengthBefore;

			// determine where we are between the 'before' and 'after' points

			var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;

			// add that fractional amount to t

			var t = ( i + segmentFraction ) / ( il - 1 );

			return t;

		},

		// Returns a unit vector tangent at t
		// In case any sub curve does not implement its tangent derivation,
		// 2 points a small delta apart will be used to find its gradient
		// which seems to give a reasonable approximation

		getTangent: function ( t ) {

			var delta = 0.0001;
			var t1 = t - delta;
			var t2 = t + delta;

			// Capping in case of danger

			if ( t1 < 0 ) { t1 = 0; }
			if ( t2 > 1 ) { t2 = 1; }

			var pt1 = this.getPoint( t1 );
			var pt2 = this.getPoint( t2 );

			var vec = pt2.clone().sub( pt1 );
			return vec.normalize();

		},

		getTangentAt: function ( u ) {

			var t = this.getUtoTmapping( u );
			return this.getTangent( t );

		},

		computeFrenetFrames: function ( segments, closed ) {

			// see http://www.cs.indiana.edu/pub/techreports/TR425.pdf

			var normal = new Vector3();

			var tangents = [];
			var normals = [];
			var binormals = [];

			var vec = new Vector3();
			var mat = new Matrix4();

			var i, u, theta;

			// compute the tangent vectors for each segment on the curve

			for ( i = 0; i <= segments; i ++ ) {

				u = i / segments;

				tangents[ i ] = this.getTangentAt( u );
				tangents[ i ].normalize();

			}

			// select an initial normal vector perpendicular to the first tangent vector,
			// and in the direction of the minimum tangent xyz component

			normals[ 0 ] = new Vector3();
			binormals[ 0 ] = new Vector3();
			var min = Number.MAX_VALUE;
			var tx = Math.abs( tangents[ 0 ].x );
			var ty = Math.abs( tangents[ 0 ].y );
			var tz = Math.abs( tangents[ 0 ].z );

			if ( tx <= min ) {

				min = tx;
				normal.set( 1, 0, 0 );

			}

			if ( ty <= min ) {

				min = ty;
				normal.set( 0, 1, 0 );

			}

			if ( tz <= min ) {

				normal.set( 0, 0, 1 );

			}

			vec.crossVectors( tangents[ 0 ], normal ).normalize();

			normals[ 0 ].crossVectors( tangents[ 0 ], vec );
			binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );


			// compute the slowly-varying normal and binormal vectors for each segment on the curve

			for ( i = 1; i <= segments; i ++ ) {

				normals[ i ] = normals[ i - 1 ].clone();

				binormals[ i ] = binormals[ i - 1 ].clone();

				vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );

				if ( vec.length() > Number.EPSILON ) {

					vec.normalize();

					theta = Math.acos( MathUtils.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors

					normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );

				}

				binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );

			}

			// if the curve is closed, postprocess the vectors so the first and last normal vectors are the same

			if ( closed === true ) {

				theta = Math.acos( MathUtils.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
				theta /= segments;

				if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {

					theta = - theta;

				}

				for ( i = 1; i <= segments; i ++ ) {

					// twist a little...
					normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
					binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );

				}

			}

			return {
				tangents: tangents,
				normals: normals,
				binormals: binormals
			};

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		copy: function ( source ) {

			this.arcLengthDivisions = source.arcLengthDivisions;

			return this;

		},

		toJSON: function () {

			var data = {
				metadata: {
					version: 4.5,
					type: 'Curve',
					generator: 'Curve.toJSON'
				}
			};

			data.arcLengthDivisions = this.arcLengthDivisions;
			data.type = this.type;

			return data;

		},

		fromJSON: function ( json ) {

			this.arcLengthDivisions = json.arcLengthDivisions;

			return this;

		}

	} );

	function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {

		Curve.call( this );

		this.type = 'EllipseCurve';

		this.aX = aX || 0;
		this.aY = aY || 0;

		this.xRadius = xRadius || 1;
		this.yRadius = yRadius || 1;

		this.aStartAngle = aStartAngle || 0;
		this.aEndAngle = aEndAngle || 2 * Math.PI;

		this.aClockwise = aClockwise || false;

		this.aRotation = aRotation || 0;

	}

	EllipseCurve.prototype = Object.create( Curve.prototype );
	EllipseCurve.prototype.constructor = EllipseCurve;

	EllipseCurve.prototype.isEllipseCurve = true;

	EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) {

		var point = optionalTarget || new Vector2();

		var twoPi = Math.PI * 2;
		var deltaAngle = this.aEndAngle - this.aStartAngle;
		var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;

		// ensures that deltaAngle is 0 .. 2 PI
		while ( deltaAngle < 0 ) { deltaAngle += twoPi; }
		while ( deltaAngle > twoPi ) { deltaAngle -= twoPi; }

		if ( deltaAngle < Number.EPSILON ) {

			if ( samePoints ) {

				deltaAngle = 0;

			} else {

				deltaAngle = twoPi;

			}

		}

		if ( this.aClockwise === true && ! samePoints ) {

			if ( deltaAngle === twoPi ) {

				deltaAngle = - twoPi;

			} else {

				deltaAngle = deltaAngle - twoPi;

			}

		}

		var angle = this.aStartAngle + t * deltaAngle;
		var x = this.aX + this.xRadius * Math.cos( angle );
		var y = this.aY + this.yRadius * Math.sin( angle );

		if ( this.aRotation !== 0 ) {

			var cos = Math.cos( this.aRotation );
			var sin = Math.sin( this.aRotation );

			var tx = x - this.aX;
			var ty = y - this.aY;

			// Rotate the point about the center of the ellipse.
			x = tx * cos - ty * sin + this.aX;
			y = tx * sin + ty * cos + this.aY;

		}

		return point.set( x, y );

	};

	EllipseCurve.prototype.copy = function ( source ) {

		Curve.prototype.copy.call( this, source );

		this.aX = source.aX;
		this.aY = source.aY;

		this.xRadius = source.xRadius;
		this.yRadius = source.yRadius;

		this.aStartAngle = source.aStartAngle;
		this.aEndAngle = source.aEndAngle;

		this.aClockwise = source.aClockwise;

		this.aRotation = source.aRotation;

		return this;

	};


	EllipseCurve.prototype.toJSON = function () {

		var data = Curve.prototype.toJSON.call( this );

		data.aX = this.aX;
		data.aY = this.aY;

		data.xRadius = this.xRadius;
		data.yRadius = this.yRadius;

		data.aStartAngle = this.aStartAngle;
		data.aEndAngle = this.aEndAngle;

		data.aClockwise = this.aClockwise;

		data.aRotation = this.aRotation;

		return data;

	};

	EllipseCurve.prototype.fromJSON = function ( json ) {

		Curve.prototype.fromJSON.call( this, json );

		this.aX = json.aX;
		this.aY = json.aY;

		this.xRadius = json.xRadius;
		this.yRadius = json.yRadius;

		this.aStartAngle = json.aStartAngle;
		this.aEndAngle = json.aEndAngle;

		this.aClockwise = json.aClockwise;

		this.aRotation = json.aRotation;

		return this;

	};

	function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {

		EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );

		this.type = 'ArcCurve';

	}

	ArcCurve.prototype = Object.create( EllipseCurve.prototype );
	ArcCurve.prototype.constructor = ArcCurve;

	ArcCurve.prototype.isArcCurve = true;

	/**
	 * @author zz85 https://github.com/zz85
	 *
	 * Centripetal CatmullRom Curve - which is useful for avoiding
	 * cusps and self-intersections in non-uniform catmull rom curves.
	 * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
	 *
	 * curve.type accepts centripetal(default), chordal and catmullrom
	 * curve.tension is used for catmullrom which defaults to 0.5
	 */


	/*
	Based on an optimized c++ solution in
	 - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
	 - http://ideone.com/NoEbVM

	This CubicPoly class could be used for reusing some variables and calculations,
	but for three.js curve use, it could be possible inlined and flatten into a single function call
	which can be placed in CurveUtils.
	*/

	function CubicPoly() {

		var c0 = 0, c1 = 0, c2 = 0, c3 = 0;

		/*
		 * Compute coefficients for a cubic polynomial
		 *   p(s) = c0 + c1*s + c2*s^2 + c3*s^3
		 * such that
		 *   p(0) = x0, p(1) = x1
		 *  and
		 *   p'(0) = t0, p'(1) = t1.
		 */
		function init( x0, x1, t0, t1 ) {

			c0 = x0;
			c1 = t0;
			c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
			c3 = 2 * x0 - 2 * x1 + t0 + t1;

		}

		return {

			initCatmullRom: function ( x0, x1, x2, x3, tension ) {

				init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );

			},

			initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {

				// compute tangents when parameterized in [t1,t2]
				var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
				var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;

				// rescale tangents for parametrization in [0,1]
				t1 *= dt1;
				t2 *= dt1;

				init( x1, x2, t1, t2 );

			},

			calc: function ( t ) {

				var t2 = t * t;
				var t3 = t2 * t;
				return c0 + c1 * t + c2 * t2 + c3 * t3;

			}

		};

	}

	//

	var tmp = new Vector3();
	var px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();

	function CatmullRomCurve3( points, closed, curveType, tension ) {

		Curve.call( this );

		this.type = 'CatmullRomCurve3';

		this.points = points || [];
		this.closed = closed || false;
		this.curveType = curveType || 'centripetal';
		this.tension = tension || 0.5;

	}

	CatmullRomCurve3.prototype = Object.create( Curve.prototype );
	CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;

	CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;

	CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget ) {

		var point = optionalTarget || new Vector3();

		var points = this.points;
		var l = points.length;

		var p = ( l - ( this.closed ? 0 : 1 ) ) * t;
		var intPoint = Math.floor( p );
		var weight = p - intPoint;

		if ( this.closed ) {

			intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;

		} else if ( weight === 0 && intPoint === l - 1 ) {

			intPoint = l - 2;
			weight = 1;

		}

		var p0, p1, p2, p3; // 4 points

		if ( this.closed || intPoint > 0 ) {

			p0 = points[ ( intPoint - 1 ) % l ];

		} else {

			// extrapolate first point
			tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
			p0 = tmp;

		}

		p1 = points[ intPoint % l ];
		p2 = points[ ( intPoint + 1 ) % l ];

		if ( this.closed || intPoint + 2 < l ) {

			p3 = points[ ( intPoint + 2 ) % l ];

		} else {

			// extrapolate last point
			tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
			p3 = tmp;

		}

		if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {

			// init Centripetal / Chordal Catmull-Rom
			var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
			var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
			var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
			var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );

			// safety check for repeated points
			if ( dt1 < 1e-4 ) { dt1 = 1.0; }
			if ( dt0 < 1e-4 ) { dt0 = dt1; }
			if ( dt2 < 1e-4 ) { dt2 = dt1; }

			px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
			py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
			pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );

		} else if ( this.curveType === 'catmullrom' ) {

			px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
			py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
			pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );

		}

		point.set(
			px.calc( weight ),
			py.calc( weight ),
			pz.calc( weight )
		);

		return point;

	};

	CatmullRomCurve3.prototype.copy = function ( source ) {

		Curve.prototype.copy.call( this, source );

		this.points = [];

		for ( var i = 0, l = source.points.length; i < l; i ++ ) {

			var point = source.points[ i ];

			this.points.push( point.clone() );

		}

		this.closed = source.closed;
		this.curveType = source.curveType;
		this.tension = source.tension;

		return this;

	};

	CatmullRomCurve3.prototype.toJSON = function () {

		var data = Curve.prototype.toJSON.call( this );

		data.points = [];

		for ( var i = 0, l = this.points.length; i < l; i ++ ) {

			var point = this.points[ i ];
			data.points.push( point.toArray() );

		}

		data.closed = this.closed;
		data.curveType = this.curveType;
		data.tension = this.tension;

		return data;

	};

	CatmullRomCurve3.prototype.fromJSON = function ( json ) {

		Curve.prototype.fromJSON.call( this, json );

		this.points = [];

		for ( var i = 0, l = json.points.length; i < l; i ++ ) {

			var point = json.points[ i ];
			this.points.push( new Vector3().fromArray( point ) );

		}

		this.closed = json.closed;
		this.curveType = json.curveType;
		this.tension = json.tension;

		return this;

	};

	/**
	 * @author zz85 / http://www.lab4games.net/zz85/blog
	 *
	 * Bezier Curves formulas obtained from
	 * http://en.wikipedia.org/wiki/Bézier_curve
	 */

	function CatmullRom( t, p0, p1, p2, p3 ) {

		var v0 = ( p2 - p0 ) * 0.5;
		var v1 = ( p3 - p1 ) * 0.5;
		var t2 = t * t;
		var t3 = t * t2;
		return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;

	}

	//

	function QuadraticBezierP0( t, p ) {

		var k = 1 - t;
		return k * k * p;

	}

	function QuadraticBezierP1( t, p ) {

		return 2 * ( 1 - t ) * t * p;

	}

	function QuadraticBezierP2( t, p ) {

		return t * t * p;

	}

	function QuadraticBezier( t, p0, p1, p2 ) {

		return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
			QuadraticBezierP2( t, p2 );

	}

	//

	function CubicBezierP0( t, p ) {

		var k = 1 - t;
		return k * k * k * p;

	}

	function CubicBezierP1( t, p ) {

		var k = 1 - t;
		return 3 * k * k * t * p;

	}

	function CubicBezierP2( t, p ) {

		return 3 * ( 1 - t ) * t * t * p;

	}

	function CubicBezierP3( t, p ) {

		return t * t * t * p;

	}

	function CubicBezier( t, p0, p1, p2, p3 ) {

		return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
			CubicBezierP3( t, p3 );

	}

	function CubicBezierCurve( v0, v1, v2, v3 ) {

		Curve.call( this );

		this.type = 'CubicBezierCurve';

		this.v0 = v0 || new Vector2();
		this.v1 = v1 || new Vector2();
		this.v2 = v2 || new Vector2();
		this.v3 = v3 || new Vector2();

	}

	CubicBezierCurve.prototype = Object.create( Curve.prototype );
	CubicBezierCurve.prototype.constructor = CubicBezierCurve;

	CubicBezierCurve.prototype.isCubicBezierCurve = true;

	CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {

		var point = optionalTarget || new Vector2();

		var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;

		point.set(
			CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
			CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
		);

		return point;

	};

	CubicBezierCurve.prototype.copy = function ( source ) {

		Curve.prototype.copy.call( this, source );

		this.v0.copy( source.v0 );
		this.v1.copy( source.v1 );
		this.v2.copy( source.v2 );
		this.v3.copy( source.v3 );

		return this;

	};

	CubicBezierCurve.prototype.toJSON = function () {

		var data = Curve.prototype.toJSON.call( this );

		data.v0 = this.v0.toArray();
		data.v1 = this.v1.toArray();
		data.v2 = this.v2.toArray();
		data.v3 = this.v3.toArray();

		return data;

	};

	CubicBezierCurve.prototype.fromJSON = function ( json ) {

		Curve.prototype.fromJSON.call( this, json );

		this.v0.fromArray( json.v0 );
		this.v1.fromArray( json.v1 );
		this.v2.fromArray( json.v2 );
		this.v3.fromArray( json.v3 );

		return this;

	};

	function CubicBezierCurve3( v0, v1, v2, v3 ) {

		Curve.call( this );

		this.type = 'CubicBezierCurve3';

		this.v0 = v0 || new Vector3();
		this.v1 = v1 || new Vector3();
		this.v2 = v2 || new Vector3();
		this.v3 = v3 || new Vector3();

	}

	CubicBezierCurve3.prototype = Object.create( Curve.prototype );
	CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;

	CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;

	CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {

		var point = optionalTarget || new Vector3();

		var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;

		point.set(
			CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
			CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
			CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
		);

		return point;

	};

	CubicBezierCurve3.prototype.copy = function ( source ) {

		Curve.prototype.copy.call( this, source );

		this.v0.copy( source.v0 );
		this.v1.copy( source.v1 );
		this.v2.copy( source.v2 );
		this.v3.copy( source.v3 );

		return this;

	};

	CubicBezierCurve3.prototype.toJSON = function () {

		var data = Curve.prototype.toJSON.call( this );

		data.v0 = this.v0.toArray();
		data.v1 = this.v1.toArray();
		data.v2 = this.v2.toArray();
		data.v3 = this.v3.toArray();

		return data;

	};

	CubicBezierCurve3.prototype.fromJSON = function ( json ) {

		Curve.prototype.fromJSON.call( this, json );

		this.v0.fromArray( json.v0 );
		this.v1.fromArray( json.v1 );
		this.v2.fromArray( json.v2 );
		this.v3.fromArray( json.v3 );

		return this;

	};

	function LineCurve( v1, v2 ) {

		Curve.call( this );

		this.type = 'LineCurve';

		this.v1 = v1 || new Vector2();
		this.v2 = v2 || new Vector2();

	}

	LineCurve.prototype = Object.create( Curve.prototype );
	LineCurve.prototype.constructor = LineCurve;

	LineCurve.prototype.isLineCurve = true;

	LineCurve.prototype.getPoint = function ( t, optionalTarget ) {

		var point = optionalTarget || new Vector2();

		if ( t === 1 ) {

			point.copy( this.v2 );

		} else {

			point.copy( this.v2 ).sub( this.v1 );
			point.multiplyScalar( t ).add( this.v1 );

		}

		return point;

	};

	// Line curve is linear, so we can overwrite default getPointAt

	LineCurve.prototype.getPointAt = function ( u, optionalTarget ) {

		return this.getPoint( u, optionalTarget );

	};

	LineCurve.prototype.getTangent = function ( /* t */ ) {

		var tangent = this.v2.clone().sub( this.v1 );

		return tangent.normalize();

	};

	LineCurve.prototype.copy = function ( source ) {

		Curve.prototype.copy.call( this, source );

		this.v1.copy( source.v1 );
		this.v2.copy( source.v2 );

		return this;

	};

	LineCurve.prototype.toJSON = function () {

		var data = Curve.prototype.toJSON.call( this );

		data.v1 = this.v1.toArray();
		data.v2 = this.v2.toArray();

		return data;

	};

	LineCurve.prototype.fromJSON = function ( json ) {

		Curve.prototype.fromJSON.call( this, json );

		this.v1.fromArray( json.v1 );
		this.v2.fromArray( json.v2 );

		return this;

	};

	function LineCurve3( v1, v2 ) {

		Curve.call( this );

		this.type = 'LineCurve3';

		this.v1 = v1 || new Vector3();
		this.v2 = v2 || new Vector3();

	}

	LineCurve3.prototype = Object.create( Curve.prototype );
	LineCurve3.prototype.constructor = LineCurve3;

	LineCurve3.prototype.isLineCurve3 = true;

	LineCurve3.prototype.getPoint = function ( t, optionalTarget ) {

		var point = optionalTarget || new Vector3();

		if ( t === 1 ) {

			point.copy( this.v2 );

		} else {

			point.copy( this.v2 ).sub( this.v1 );
			point.multiplyScalar( t ).add( this.v1 );

		}

		return point;

	};

	// Line curve is linear, so we can overwrite default getPointAt

	LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) {

		return this.getPoint( u, optionalTarget );

	};

	LineCurve3.prototype.copy = function ( source ) {

		Curve.prototype.copy.call( this, source );

		this.v1.copy( source.v1 );
		this.v2.copy( source.v2 );

		return this;

	};

	LineCurve3.prototype.toJSON = function () {

		var data = Curve.prototype.toJSON.call( this );

		data.v1 = this.v1.toArray();
		data.v2 = this.v2.toArray();

		return data;

	};

	LineCurve3.prototype.fromJSON = function ( json ) {

		Curve.prototype.fromJSON.call( this, json );

		this.v1.fromArray( json.v1 );
		this.v2.fromArray( json.v2 );

		return this;

	};

	function QuadraticBezierCurve( v0, v1, v2 ) {

		Curve.call( this );

		this.type = 'QuadraticBezierCurve';

		this.v0 = v0 || new Vector2();
		this.v1 = v1 || new Vector2();
		this.v2 = v2 || new Vector2();

	}

	QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
	QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;

	QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;

	QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {

		var point = optionalTarget || new Vector2();

		var v0 = this.v0, v1 = this.v1, v2 = this.v2;

		point.set(
			QuadraticBezier( t, v0.x, v1.x, v2.x ),
			QuadraticBezier( t, v0.y, v1.y, v2.y )
		);

		return point;

	};

	QuadraticBezierCurve.prototype.copy = function ( source ) {

		Curve.prototype.copy.call( this, source );

		this.v0.copy( source.v0 );
		this.v1.copy( source.v1 );
		this.v2.copy( source.v2 );

		return this;

	};

	QuadraticBezierCurve.prototype.toJSON = function () {

		var data = Curve.prototype.toJSON.call( this );

		data.v0 = this.v0.toArray();
		data.v1 = this.v1.toArray();
		data.v2 = this.v2.toArray();

		return data;

	};

	QuadraticBezierCurve.prototype.fromJSON = function ( json ) {

		Curve.prototype.fromJSON.call( this, json );

		this.v0.fromArray( json.v0 );
		this.v1.fromArray( json.v1 );
		this.v2.fromArray( json.v2 );

		return this;

	};

	function QuadraticBezierCurve3( v0, v1, v2 ) {

		Curve.call( this );

		this.type = 'QuadraticBezierCurve3';

		this.v0 = v0 || new Vector3();
		this.v1 = v1 || new Vector3();
		this.v2 = v2 || new Vector3();

	}

	QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
	QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;

	QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;

	QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {

		var point = optionalTarget || new Vector3();

		var v0 = this.v0, v1 = this.v1, v2 = this.v2;

		point.set(
			QuadraticBezier( t, v0.x, v1.x, v2.x ),
			QuadraticBezier( t, v0.y, v1.y, v2.y ),
			QuadraticBezier( t, v0.z, v1.z, v2.z )
		);

		return point;

	};

	QuadraticBezierCurve3.prototype.copy = function ( source ) {

		Curve.prototype.copy.call( this, source );

		this.v0.copy( source.v0 );
		this.v1.copy( source.v1 );
		this.v2.copy( source.v2 );

		return this;

	};

	QuadraticBezierCurve3.prototype.toJSON = function () {

		var data = Curve.prototype.toJSON.call( this );

		data.v0 = this.v0.toArray();
		data.v1 = this.v1.toArray();
		data.v2 = this.v2.toArray();

		return data;

	};

	QuadraticBezierCurve3.prototype.fromJSON = function ( json ) {

		Curve.prototype.fromJSON.call( this, json );

		this.v0.fromArray( json.v0 );
		this.v1.fromArray( json.v1 );
		this.v2.fromArray( json.v2 );

		return this;

	};

	function SplineCurve( points /* array of Vector2 */ ) {

		Curve.call( this );

		this.type = 'SplineCurve';

		this.points = points || [];

	}

	SplineCurve.prototype = Object.create( Curve.prototype );
	SplineCurve.prototype.constructor = SplineCurve;

	SplineCurve.prototype.isSplineCurve = true;

	SplineCurve.prototype.getPoint = function ( t, optionalTarget ) {

		var point = optionalTarget || new Vector2();

		var points = this.points;
		var p = ( points.length - 1 ) * t;

		var intPoint = Math.floor( p );
		var weight = p - intPoint;

		var p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
		var p1 = points[ intPoint ];
		var p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
		var p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];

		point.set(
			CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
			CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
		);

		return point;

	};

	SplineCurve.prototype.copy = function ( source ) {

		Curve.prototype.copy.call( this, source );

		this.points = [];

		for ( var i = 0, l = source.points.length; i < l; i ++ ) {

			var point = source.points[ i ];

			this.points.push( point.clone() );

		}

		return this;

	};

	SplineCurve.prototype.toJSON = function () {

		var data = Curve.prototype.toJSON.call( this );

		data.points = [];

		for ( var i = 0, l = this.points.length; i < l; i ++ ) {

			var point = this.points[ i ];
			data.points.push( point.toArray() );

		}

		return data;

	};

	SplineCurve.prototype.fromJSON = function ( json ) {

		Curve.prototype.fromJSON.call( this, json );

		this.points = [];

		for ( var i = 0, l = json.points.length; i < l; i ++ ) {

			var point = json.points[ i ];
			this.points.push( new Vector2().fromArray( point ) );

		}

		return this;

	};



	var Curves = /*#__PURE__*/Object.freeze({
		__proto__: null,
		ArcCurve: ArcCurve,
		CatmullRomCurve3: CatmullRomCurve3,
		CubicBezierCurve: CubicBezierCurve,
		CubicBezierCurve3: CubicBezierCurve3,
		EllipseCurve: EllipseCurve,
		LineCurve: LineCurve,
		LineCurve3: LineCurve3,
		QuadraticBezierCurve: QuadraticBezierCurve,
		QuadraticBezierCurve3: QuadraticBezierCurve3,
		SplineCurve: SplineCurve
	});

	/**
	 * @author zz85 / http://www.lab4games.net/zz85/blog
	 *
	 **/

	/**************************************************************
	 *	Curved Path - a curve path is simply a array of connected
	 *  curves, but retains the api of a curve
	 **************************************************************/

	function CurvePath() {

		Curve.call( this );

		this.type = 'CurvePath';

		this.curves = [];
		this.autoClose = false; // Automatically closes the path

	}

	CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {

		constructor: CurvePath,

		add: function ( curve ) {

			this.curves.push( curve );

		},

		closePath: function () {

			// Add a line curve if start and end of lines are not connected
			var startPoint = this.curves[ 0 ].getPoint( 0 );
			var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );

			if ( ! startPoint.equals( endPoint ) ) {

				this.curves.push( new LineCurve( endPoint, startPoint ) );

			}

		},

		// To get accurate point with reference to
		// entire path distance at time t,
		// following has to be done:

		// 1. Length of each sub path have to be known
		// 2. Locate and identify type of curve
		// 3. Get t for the curve
		// 4. Return curve.getPointAt(t')

		getPoint: function ( t ) {

			var d = t * this.getLength();
			var curveLengths = this.getCurveLengths();
			var i = 0;

			// To think about boundaries points.

			while ( i < curveLengths.length ) {

				if ( curveLengths[ i ] >= d ) {

					var diff = curveLengths[ i ] - d;
					var curve = this.curves[ i ];

					var segmentLength = curve.getLength();
					var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;

					return curve.getPointAt( u );

				}

				i ++;

			}

			return null;

			// loop where sum != 0, sum > d , sum+1 <d

		},

		// We cannot use the default THREE.Curve getPoint() with getLength() because in
		// THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
		// getPoint() depends on getLength

		getLength: function () {

			var lens = this.getCurveLengths();
			return lens[ lens.length - 1 ];

		},

		// cacheLengths must be recalculated.
		updateArcLengths: function () {

			this.needsUpdate = true;
			this.cacheLengths = null;
			this.getCurveLengths();

		},

		// Compute lengths and cache them
		// We cannot overwrite getLengths() because UtoT mapping uses it.

		getCurveLengths: function () {

			// We use cache values if curves and cache array are same length

			if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {

				return this.cacheLengths;

			}

			// Get length of sub-curve
			// Push sums into cached array

			var lengths = [], sums = 0;

			for ( var i = 0, l = this.curves.length; i < l; i ++ ) {

				sums += this.curves[ i ].getLength();
				lengths.push( sums );

			}

			this.cacheLengths = lengths;

			return lengths;

		},

		getSpacedPoints: function ( divisions ) {

			if ( divisions === undefined ) { divisions = 40; }

			var points = [];

			for ( var i = 0; i <= divisions; i ++ ) {

				points.push( this.getPoint( i / divisions ) );

			}

			if ( this.autoClose ) {

				points.push( points[ 0 ] );

			}

			return points;

		},

		getPoints: function ( divisions ) {

			divisions = divisions || 12;

			var points = [], last;

			for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {

				var curve = curves[ i ];
				var resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
					: ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
						: ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
							: divisions;

				var pts = curve.getPoints( resolution );

				for ( var j = 0; j < pts.length; j ++ ) {

					var point = pts[ j ];

					if ( last && last.equals( point ) ) { continue; } // ensures no consecutive points are duplicates

					points.push( point );
					last = point;

				}

			}

			if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {

				points.push( points[ 0 ] );

			}

			return points;

		},

		copy: function ( source ) {

			Curve.prototype.copy.call( this, source );

			this.curves = [];

			for ( var i = 0, l = source.curves.length; i < l; i ++ ) {

				var curve = source.curves[ i ];

				this.curves.push( curve.clone() );

			}

			this.autoClose = source.autoClose;

			return this;

		},

		toJSON: function () {

			var data = Curve.prototype.toJSON.call( this );

			data.autoClose = this.autoClose;
			data.curves = [];

			for ( var i = 0, l = this.curves.length; i < l; i ++ ) {

				var curve = this.curves[ i ];
				data.curves.push( curve.toJSON() );

			}

			return data;

		},

		fromJSON: function ( json ) {

			Curve.prototype.fromJSON.call( this, json );

			this.autoClose = json.autoClose;
			this.curves = [];

			for ( var i = 0, l = json.curves.length; i < l; i ++ ) {

				var curve = json.curves[ i ];
				this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );

			}

			return this;

		}

	} );

	/**
	 * @author zz85 / http://www.lab4games.net/zz85/blog
	 * Creates free form 2d path using series of points, lines or curves.
	 **/

	function Path( points ) {

		CurvePath.call( this );

		this.type = 'Path';

		this.currentPoint = new Vector2();

		if ( points ) {

			this.setFromPoints( points );

		}

	}

	Path.prototype = Object.assign( Object.create( CurvePath.prototype ), {

		constructor: Path,

		setFromPoints: function ( points ) {

			this.moveTo( points[ 0 ].x, points[ 0 ].y );

			for ( var i = 1, l = points.length; i < l; i ++ ) {

				this.lineTo( points[ i ].x, points[ i ].y );

			}

			return this;

		},

		moveTo: function ( x, y ) {

			this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?

			return this;

		},

		lineTo: function ( x, y ) {

			var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
			this.curves.push( curve );

			this.currentPoint.set( x, y );

			return this;

		},

		quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {

			var curve = new QuadraticBezierCurve(
				this.currentPoint.clone(),
				new Vector2( aCPx, aCPy ),
				new Vector2( aX, aY )
			);

			this.curves.push( curve );

			this.currentPoint.set( aX, aY );

			return this;

		},

		bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {

			var curve = new CubicBezierCurve(
				this.currentPoint.clone(),
				new Vector2( aCP1x, aCP1y ),
				new Vector2( aCP2x, aCP2y ),
				new Vector2( aX, aY )
			);

			this.curves.push( curve );

			this.currentPoint.set( aX, aY );

			return this;

		},

		splineThru: function ( pts /*Array of Vector*/ ) {

			var npts = [ this.currentPoint.clone() ].concat( pts );

			var curve = new SplineCurve( npts );
			this.curves.push( curve );

			this.currentPoint.copy( pts[ pts.length - 1 ] );

			return this;

		},

		arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {

			var x0 = this.currentPoint.x;
			var y0 = this.currentPoint.y;

			this.absarc( aX + x0, aY + y0, aRadius,
				aStartAngle, aEndAngle, aClockwise );

			return this;

		},

		absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {

			this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );

			return this;

		},

		ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {

			var x0 = this.currentPoint.x;
			var y0 = this.currentPoint.y;

			this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );

			return this;

		},

		absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {

			var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );

			if ( this.curves.length > 0 ) {

				// if a previous curve is present, attempt to join
				var firstPoint = curve.getPoint( 0 );

				if ( ! firstPoint.equals( this.currentPoint ) ) {

					this.lineTo( firstPoint.x, firstPoint.y );

				}

			}

			this.curves.push( curve );

			var lastPoint = curve.getPoint( 1 );
			this.currentPoint.copy( lastPoint );

			return this;

		},

		copy: function ( source ) {

			CurvePath.prototype.copy.call( this, source );

			this.currentPoint.copy( source.currentPoint );

			return this;

		},

		toJSON: function () {

			var data = CurvePath.prototype.toJSON.call( this );

			data.currentPoint = this.currentPoint.toArray();

			return data;

		},

		fromJSON: function ( json ) {

			CurvePath.prototype.fromJSON.call( this, json );

			this.currentPoint.fromArray( json.currentPoint );

			return this;

		}

	} );

	/**
	 * @author zz85 / http://www.lab4games.net/zz85/blog
	 * Defines a 2d shape plane using paths.
	 **/

	// STEP 1 Create a path.
	// STEP 2 Turn path into shape.
	// STEP 3 ExtrudeGeometry takes in Shape/Shapes
	// STEP 3a - Extract points from each shape, turn to vertices
	// STEP 3b - Triangulate each shape, add faces.

	function Shape( points ) {

		Path.call( this, points );

		this.uuid = MathUtils.generateUUID();

		this.type = 'Shape';

		this.holes = [];

	}

	Shape.prototype = Object.assign( Object.create( Path.prototype ), {

		constructor: Shape,

		getPointsHoles: function ( divisions ) {

			var holesPts = [];

			for ( var i = 0, l = this.holes.length; i < l; i ++ ) {

				holesPts[ i ] = this.holes[ i ].getPoints( divisions );

			}

			return holesPts;

		},

		// get points of shape and holes (keypoints based on segments parameter)

		extractPoints: function ( divisions ) {

			return {

				shape: this.getPoints( divisions ),
				holes: this.getPointsHoles( divisions )

			};

		},

		copy: function ( source ) {

			Path.prototype.copy.call( this, source );

			this.holes = [];

			for ( var i = 0, l = source.holes.length; i < l; i ++ ) {

				var hole = source.holes[ i ];

				this.holes.push( hole.clone() );

			}

			return this;

		},

		toJSON: function () {

			var data = Path.prototype.toJSON.call( this );

			data.uuid = this.uuid;
			data.holes = [];

			for ( var i = 0, l = this.holes.length; i < l; i ++ ) {

				var hole = this.holes[ i ];
				data.holes.push( hole.toJSON() );

			}

			return data;

		},

		fromJSON: function ( json ) {

			Path.prototype.fromJSON.call( this, json );

			this.uuid = json.uuid;
			this.holes = [];

			for ( var i = 0, l = json.holes.length; i < l; i ++ ) {

				var hole = json.holes[ i ];
				this.holes.push( new Path().fromJSON( hole ) );

			}

			return this;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author alteredq / http://alteredqualia.com/
	 */

	function Light( color, intensity ) {

		Object3D.call( this );

		this.type = 'Light';

		this.color = new Color( color );
		this.intensity = intensity !== undefined ? intensity : 1;

		this.receiveShadow = undefined;

	}

	Light.prototype = Object.assign( Object.create( Object3D.prototype ), {

		constructor: Light,

		isLight: true,

		copy: function ( source ) {

			Object3D.prototype.copy.call( this, source );

			this.color.copy( source.color );
			this.intensity = source.intensity;

			return this;

		},

		toJSON: function ( meta ) {

			var data = Object3D.prototype.toJSON.call( this, meta );

			data.object.color = this.color.getHex();
			data.object.intensity = this.intensity;

			if ( this.groundColor !== undefined ) { data.object.groundColor = this.groundColor.getHex(); }

			if ( this.distance !== undefined ) { data.object.distance = this.distance; }
			if ( this.angle !== undefined ) { data.object.angle = this.angle; }
			if ( this.decay !== undefined ) { data.object.decay = this.decay; }
			if ( this.penumbra !== undefined ) { data.object.penumbra = this.penumbra; }

			if ( this.shadow !== undefined ) { data.object.shadow = this.shadow.toJSON(); }

			return data;

		}

	} );

	/**
	 * @author alteredq / http://alteredqualia.com/
	 */

	function HemisphereLight( skyColor, groundColor, intensity ) {

		Light.call( this, skyColor, intensity );

		this.type = 'HemisphereLight';

		this.castShadow = undefined;

		this.position.copy( Object3D.DefaultUp );
		this.updateMatrix();

		this.groundColor = new Color( groundColor );

	}

	HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {

		constructor: HemisphereLight,

		isHemisphereLight: true,

		copy: function ( source ) {

			Light.prototype.copy.call( this, source );

			this.groundColor.copy( source.groundColor );

			return this;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function LightShadow( camera ) {

		this.camera = camera;

		this.bias = 0;
		this.radius = 1;

		this.mapSize = new Vector2( 512, 512 );

		this.map = null;
		this.mapPass = null;
		this.matrix = new Matrix4();

		this._frustum = new Frustum();
		this._frameExtents = new Vector2( 1, 1 );

		this._viewportCount = 1;

		this._viewports = [

			new Vector4( 0, 0, 1, 1 )

		];

	}

	Object.assign( LightShadow.prototype, {

		_projScreenMatrix: new Matrix4(),

		_lightPositionWorld: new Vector3(),

		_lookTarget: new Vector3(),

		getViewportCount: function () {

			return this._viewportCount;

		},

		getFrustum: function () {

			return this._frustum;

		},

		updateMatrices: function ( light ) {

			var shadowCamera = this.camera,
				shadowMatrix = this.matrix,
				projScreenMatrix = this._projScreenMatrix,
				lookTarget = this._lookTarget,
				lightPositionWorld = this._lightPositionWorld;

			lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
			shadowCamera.position.copy( lightPositionWorld );

			lookTarget.setFromMatrixPosition( light.target.matrixWorld );
			shadowCamera.lookAt( lookTarget );
			shadowCamera.updateMatrixWorld();

			projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
			this._frustum.setFromProjectionMatrix( projScreenMatrix );

			shadowMatrix.set(
				0.5, 0.0, 0.0, 0.5,
				0.0, 0.5, 0.0, 0.5,
				0.0, 0.0, 0.5, 0.5,
				0.0, 0.0, 0.0, 1.0
			);

			shadowMatrix.multiply( shadowCamera.projectionMatrix );
			shadowMatrix.multiply( shadowCamera.matrixWorldInverse );

		},

		getViewport: function ( viewportIndex ) {

			return this._viewports[ viewportIndex ];

		},

		getFrameExtents: function () {

			return this._frameExtents;

		},

		copy: function ( source ) {

			this.camera = source.camera.clone();

			this.bias = source.bias;
			this.radius = source.radius;

			this.mapSize.copy( source.mapSize );

			return this;

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		toJSON: function () {

			var object = {};

			if ( this.bias !== 0 ) { object.bias = this.bias; }
			if ( this.radius !== 1 ) { object.radius = this.radius; }
			if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) { object.mapSize = this.mapSize.toArray(); }

			object.camera = this.camera.toJSON( false ).object;
			delete object.camera.matrix;

			return object;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function SpotLightShadow() {

		LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );

	}

	SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {

		constructor: SpotLightShadow,

		isSpotLightShadow: true,

		updateMatrices: function ( light ) {

			var camera = this.camera;

			var fov = MathUtils.RAD2DEG * 2 * light.angle;
			var aspect = this.mapSize.width / this.mapSize.height;
			var far = light.distance || camera.far;

			if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {

				camera.fov = fov;
				camera.aspect = aspect;
				camera.far = far;
				camera.updateProjectionMatrix();

			}

			LightShadow.prototype.updateMatrices.call( this, light );

		}

	} );

	/**
	 * @author alteredq / http://alteredqualia.com/
	 */

	function SpotLight( color, intensity, distance, angle, penumbra, decay ) {

		Light.call( this, color, intensity );

		this.type = 'SpotLight';

		this.position.copy( Object3D.DefaultUp );
		this.updateMatrix();

		this.target = new Object3D();

		Object.defineProperty( this, 'power', {
			get: function () {

				// intensity = power per solid angle.
				// ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
				return this.intensity * Math.PI;

			},
			set: function ( power ) {

				// intensity = power per solid angle.
				// ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
				this.intensity = power / Math.PI;

			}
		} );

		this.distance = ( distance !== undefined ) ? distance : 0;
		this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
		this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
		this.decay = ( decay !== undefined ) ? decay : 1;	// for physically correct lights, should be 2.

		this.shadow = new SpotLightShadow();

	}

	SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {

		constructor: SpotLight,

		isSpotLight: true,

		copy: function ( source ) {

			Light.prototype.copy.call( this, source );

			this.distance = source.distance;
			this.angle = source.angle;
			this.penumbra = source.penumbra;
			this.decay = source.decay;

			this.target = source.target.clone();

			this.shadow = source.shadow.clone();

			return this;

		}

	} );

	function PointLightShadow() {

		LightShadow.call( this, new PerspectiveCamera( 90, 1, 0.5, 500 ) );

		this._frameExtents = new Vector2( 4, 2 );

		this._viewportCount = 6;

		this._viewports = [
			// These viewports map a cube-map onto a 2D texture with the
			// following orientation:
			//
			//  xzXZ
			//   y Y
			//
			// X - Positive x direction
			// x - Negative x direction
			// Y - Positive y direction
			// y - Negative y direction
			// Z - Positive z direction
			// z - Negative z direction

			// positive X
			new Vector4( 2, 1, 1, 1 ),
			// negative X
			new Vector4( 0, 1, 1, 1 ),
			// positive Z
			new Vector4( 3, 1, 1, 1 ),
			// negative Z
			new Vector4( 1, 1, 1, 1 ),
			// positive Y
			new Vector4( 3, 0, 1, 1 ),
			// negative Y
			new Vector4( 1, 0, 1, 1 )
		];

		this._cubeDirections = [
			new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
			new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
		];

		this._cubeUps = [
			new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
			new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ),	new Vector3( 0, 0, - 1 )
		];

	}

	PointLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {

		constructor: PointLightShadow,

		isPointLightShadow: true,

		updateMatrices: function ( light, viewportIndex ) {

			if ( viewportIndex === undefined ) { viewportIndex = 0; }

			var camera = this.camera,
				shadowMatrix = this.matrix,
				lightPositionWorld = this._lightPositionWorld,
				lookTarget = this._lookTarget,
				projScreenMatrix = this._projScreenMatrix;

			lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
			camera.position.copy( lightPositionWorld );

			lookTarget.copy( camera.position );
			lookTarget.add( this._cubeDirections[ viewportIndex ] );
			camera.up.copy( this._cubeUps[ viewportIndex ] );
			camera.lookAt( lookTarget );
			camera.updateMatrixWorld();

			shadowMatrix.makeTranslation( - lightPositionWorld.x, - lightPositionWorld.y, - lightPositionWorld.z );

			projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
			this._frustum.setFromProjectionMatrix( projScreenMatrix );

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */


	function PointLight( color, intensity, distance, decay ) {

		Light.call( this, color, intensity );

		this.type = 'PointLight';

		Object.defineProperty( this, 'power', {
			get: function () {

				// intensity = power per solid angle.
				// ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
				return this.intensity * 4 * Math.PI;

			},
			set: function ( power ) {

				// intensity = power per solid angle.
				// ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
				this.intensity = power / ( 4 * Math.PI );

			}
		} );

		this.distance = ( distance !== undefined ) ? distance : 0;
		this.decay = ( decay !== undefined ) ? decay : 1;	// for physically correct lights, should be 2.

		this.shadow = new PointLightShadow();

	}

	PointLight.prototype = Object.assign( Object.create( Light.prototype ), {

		constructor: PointLight,

		isPointLight: true,

		copy: function ( source ) {

			Light.prototype.copy.call( this, source );

			this.distance = source.distance;
			this.decay = source.decay;

			this.shadow = source.shadow.clone();

			return this;

		}

	} );

	/**
	 * @author alteredq / http://alteredqualia.com/
	 * @author arose / http://github.com/arose
	 */

	function OrthographicCamera( left, right, top, bottom, near, far ) {

		Camera.call( this );

		this.type = 'OrthographicCamera';

		this.zoom = 1;
		this.view = null;

		this.left = ( left !== undefined ) ? left : - 1;
		this.right = ( right !== undefined ) ? right : 1;
		this.top = ( top !== undefined ) ? top : 1;
		this.bottom = ( bottom !== undefined ) ? bottom : - 1;

		this.near = ( near !== undefined ) ? near : 0.1;
		this.far = ( far !== undefined ) ? far : 2000;

		this.updateProjectionMatrix();

	}

	OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {

		constructor: OrthographicCamera,

		isOrthographicCamera: true,

		copy: function ( source, recursive ) {

			Camera.prototype.copy.call( this, source, recursive );

			this.left = source.left;
			this.right = source.right;
			this.top = source.top;
			this.bottom = source.bottom;
			this.near = source.near;
			this.far = source.far;

			this.zoom = source.zoom;
			this.view = source.view === null ? null : Object.assign( {}, source.view );

			return this;

		},

		setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {

			if ( this.view === null ) {

				this.view = {
					enabled: true,
					fullWidth: 1,
					fullHeight: 1,
					offsetX: 0,
					offsetY: 0,
					width: 1,
					height: 1
				};

			}

			this.view.enabled = true;
			this.view.fullWidth = fullWidth;
			this.view.fullHeight = fullHeight;
			this.view.offsetX = x;
			this.view.offsetY = y;
			this.view.width = width;
			this.view.height = height;

			this.updateProjectionMatrix();

		},

		clearViewOffset: function () {

			if ( this.view !== null ) {

				this.view.enabled = false;

			}

			this.updateProjectionMatrix();

		},

		updateProjectionMatrix: function () {

			var dx = ( this.right - this.left ) / ( 2 * this.zoom );
			var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
			var cx = ( this.right + this.left ) / 2;
			var cy = ( this.top + this.bottom ) / 2;

			var left = cx - dx;
			var right = cx + dx;
			var top = cy + dy;
			var bottom = cy - dy;

			if ( this.view !== null && this.view.enabled ) {

				var scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
				var scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;

				left += scaleW * this.view.offsetX;
				right = left + scaleW * this.view.width;
				top -= scaleH * this.view.offsetY;
				bottom = top - scaleH * this.view.height;

			}

			this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );

			this.projectionMatrixInverse.getInverse( this.projectionMatrix );

		},

		toJSON: function ( meta ) {

			var data = Object3D.prototype.toJSON.call( this, meta );

			data.object.zoom = this.zoom;
			data.object.left = this.left;
			data.object.right = this.right;
			data.object.top = this.top;
			data.object.bottom = this.bottom;
			data.object.near = this.near;
			data.object.far = this.far;

			if ( this.view !== null ) { data.object.view = Object.assign( {}, this.view ); }

			return data;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function DirectionalLightShadow() {

		LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );

	}

	DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {

		constructor: DirectionalLightShadow,

		isDirectionalLightShadow: true,

		updateMatrices: function ( light ) {

			LightShadow.prototype.updateMatrices.call( this, light );

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author alteredq / http://alteredqualia.com/
	 */

	function DirectionalLight( color, intensity ) {

		Light.call( this, color, intensity );

		this.type = 'DirectionalLight';

		this.position.copy( Object3D.DefaultUp );
		this.updateMatrix();

		this.target = new Object3D();

		this.shadow = new DirectionalLightShadow();

	}

	DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {

		constructor: DirectionalLight,

		isDirectionalLight: true,

		copy: function ( source ) {

			Light.prototype.copy.call( this, source );

			this.target = source.target.clone();

			this.shadow = source.shadow.clone();

			return this;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function AmbientLight( color, intensity ) {

		Light.call( this, color, intensity );

		this.type = 'AmbientLight';

		this.castShadow = undefined;

	}

	AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {

		constructor: AmbientLight,

		isAmbientLight: true

	} );

	/**
	 * @author abelnation / http://github.com/abelnation
	 */

	function RectAreaLight( color, intensity, width, height ) {

		Light.call( this, color, intensity );

		this.type = 'RectAreaLight';

		this.width = ( width !== undefined ) ? width : 10;
		this.height = ( height !== undefined ) ? height : 10;

	}

	RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {

		constructor: RectAreaLight,

		isRectAreaLight: true,

		copy: function ( source ) {

			Light.prototype.copy.call( this, source );

			this.width = source.width;
			this.height = source.height;

			return this;

		},

		toJSON: function ( meta ) {

			var data = Light.prototype.toJSON.call( this, meta );

			data.object.width = this.width;
			data.object.height = this.height;

			return data;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function MaterialLoader( manager ) {

		Loader.call( this, manager );

		this.textures = {};

	}

	MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

		constructor: MaterialLoader,

		load: function ( url, onLoad, onProgress, onError ) {

			var scope = this;

			var loader = new FileLoader( scope.manager );
			loader.setPath( scope.path );
			loader.load( url, function ( text ) {

				onLoad( scope.parse( JSON.parse( text ) ) );

			}, onProgress, onError );

		},

		parse: function ( json ) {

			var textures = this.textures;

			function getTexture( name ) {

				if ( textures[ name ] === undefined ) {

					console.warn( 'THREE.MaterialLoader: Undefined texture', name );

				}

				return textures[ name ];

			}

			var material = new Materials[ json.type ]();

			if ( json.uuid !== undefined ) { material.uuid = json.uuid; }
			if ( json.name !== undefined ) { material.name = json.name; }
			if ( json.color !== undefined ) { material.color.setHex( json.color ); }
			if ( json.roughness !== undefined ) { material.roughness = json.roughness; }
			if ( json.metalness !== undefined ) { material.metalness = json.metalness; }
			if ( json.sheen !== undefined ) { material.sheen = new Color().setHex( json.sheen ); }
			if ( json.emissive !== undefined ) { material.emissive.setHex( json.emissive ); }
			if ( json.specular !== undefined ) { material.specular.setHex( json.specular ); }
			if ( json.shininess !== undefined ) { material.shininess = json.shininess; }
			if ( json.clearcoat !== undefined ) { material.clearcoat = json.clearcoat; }
			if ( json.clearcoatRoughness !== undefined ) { material.clearcoatRoughness = json.clearcoatRoughness; }
			if ( json.vertexColors !== undefined ) { material.vertexColors = json.vertexColors; }
			if ( json.fog !== undefined ) { material.fog = json.fog; }
			if ( json.flatShading !== undefined ) { material.flatShading = json.flatShading; }
			if ( json.blending !== undefined ) { material.blending = json.blending; }
			if ( json.combine !== undefined ) { material.combine = json.combine; }
			if ( json.side !== undefined ) { material.side = json.side; }
			if ( json.opacity !== undefined ) { material.opacity = json.opacity; }
			if ( json.transparent !== undefined ) { material.transparent = json.transparent; }
			if ( json.alphaTest !== undefined ) { material.alphaTest = json.alphaTest; }
			if ( json.depthTest !== undefined ) { material.depthTest = json.depthTest; }
			if ( json.depthWrite !== undefined ) { material.depthWrite = json.depthWrite; }
			if ( json.colorWrite !== undefined ) { material.colorWrite = json.colorWrite; }

			if ( json.stencilWrite !== undefined ) { material.stencilWrite = json.stencilWrite; }
			if ( json.stencilWriteMask !== undefined ) { material.stencilWriteMask = json.stencilWriteMask; }
			if ( json.stencilFunc !== undefined ) { material.stencilFunc = json.stencilFunc; }
			if ( json.stencilRef !== undefined ) { material.stencilRef = json.stencilRef; }
			if ( json.stencilFuncMask !== undefined ) { material.stencilFuncMask = json.stencilFuncMask; }
			if ( json.stencilFail !== undefined ) { material.stencilFail = json.stencilFail; }
			if ( json.stencilZFail !== undefined ) { material.stencilZFail = json.stencilZFail; }
			if ( json.stencilZPass !== undefined ) { material.stencilZPass = json.stencilZPass; }

			if ( json.wireframe !== undefined ) { material.wireframe = json.wireframe; }
			if ( json.wireframeLinewidth !== undefined ) { material.wireframeLinewidth = json.wireframeLinewidth; }
			if ( json.wireframeLinecap !== undefined ) { material.wireframeLinecap = json.wireframeLinecap; }
			if ( json.wireframeLinejoin !== undefined ) { material.wireframeLinejoin = json.wireframeLinejoin; }

			if ( json.rotation !== undefined ) { material.rotation = json.rotation; }

			if ( json.linewidth !== 1 ) { material.linewidth = json.linewidth; }
			if ( json.dashSize !== undefined ) { material.dashSize = json.dashSize; }
			if ( json.gapSize !== undefined ) { material.gapSize = json.gapSize; }
			if ( json.scale !== undefined ) { material.scale = json.scale; }

			if ( json.polygonOffset !== undefined ) { material.polygonOffset = json.polygonOffset; }
			if ( json.polygonOffsetFactor !== undefined ) { material.polygonOffsetFactor = json.polygonOffsetFactor; }
			if ( json.polygonOffsetUnits !== undefined ) { material.polygonOffsetUnits = json.polygonOffsetUnits; }

			if ( json.skinning !== undefined ) { material.skinning = json.skinning; }
			if ( json.morphTargets !== undefined ) { material.morphTargets = json.morphTargets; }
			if ( json.morphNormals !== undefined ) { material.morphNormals = json.morphNormals; }
			if ( json.dithering !== undefined ) { material.dithering = json.dithering; }

			if ( json.visible !== undefined ) { material.visible = json.visible; }

			if ( json.toneMapped !== undefined ) { material.toneMapped = json.toneMapped; }

			if ( json.userData !== undefined ) { material.userData = json.userData; }

			// Shader Material

			if ( json.uniforms !== undefined ) {

				for ( var name in json.uniforms ) {

					var uniform = json.uniforms[ name ];

					material.uniforms[ name ] = {};

					switch ( uniform.type ) {

						case 't':
							material.uniforms[ name ].value = getTexture( uniform.value );
							break;

						case 'c':
							material.uniforms[ name ].value = new Color().setHex( uniform.value );
							break;

						case 'v2':
							material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
							break;

						case 'v3':
							material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
							break;

						case 'v4':
							material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
							break;

						case 'm3':
							material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );

						case 'm4':
							material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
							break;

						default:
							material.uniforms[ name ].value = uniform.value;

					}

				}

			}

			if ( json.defines !== undefined ) { material.defines = json.defines; }
			if ( json.vertexShader !== undefined ) { material.vertexShader = json.vertexShader; }
			if ( json.fragmentShader !== undefined ) { material.fragmentShader = json.fragmentShader; }

			if ( json.extensions !== undefined ) {

				for ( var key in json.extensions ) {

					material.extensions[ key ] = json.extensions[ key ];

				}

			}

			// Deprecated

			if ( json.shading !== undefined ) { material.flatShading = json.shading === 1; } // THREE.FlatShading

			// for PointsMaterial

			if ( json.size !== undefined ) { material.size = json.size; }
			if ( json.sizeAttenuation !== undefined ) { material.sizeAttenuation = json.sizeAttenuation; }

			// maps

			if ( json.map !== undefined ) { material.map = getTexture( json.map ); }
			if ( json.matcap !== undefined ) { material.matcap = getTexture( json.matcap ); }

			if ( json.alphaMap !== undefined ) {

				material.alphaMap = getTexture( json.alphaMap );
				material.transparent = true;

			}

			if ( json.bumpMap !== undefined ) { material.bumpMap = getTexture( json.bumpMap ); }
			if ( json.bumpScale !== undefined ) { material.bumpScale = json.bumpScale; }

			if ( json.normalMap !== undefined ) { material.normalMap = getTexture( json.normalMap ); }
			if ( json.normalMapType !== undefined ) { material.normalMapType = json.normalMapType; }
			if ( json.normalScale !== undefined ) {

				var normalScale = json.normalScale;

				if ( Array.isArray( normalScale ) === false ) {

					// Blender exporter used to export a scalar. See #7459

					normalScale = [ normalScale, normalScale ];

				}

				material.normalScale = new Vector2().fromArray( normalScale );

			}

			if ( json.displacementMap !== undefined ) { material.displacementMap = getTexture( json.displacementMap ); }
			if ( json.displacementScale !== undefined ) { material.displacementScale = json.displacementScale; }
			if ( json.displacementBias !== undefined ) { material.displacementBias = json.displacementBias; }

			if ( json.roughnessMap !== undefined ) { material.roughnessMap = getTexture( json.roughnessMap ); }
			if ( json.metalnessMap !== undefined ) { material.metalnessMap = getTexture( json.metalnessMap ); }

			if ( json.emissiveMap !== undefined ) { material.emissiveMap = getTexture( json.emissiveMap ); }
			if ( json.emissiveIntensity !== undefined ) { material.emissiveIntensity = json.emissiveIntensity; }

			if ( json.specularMap !== undefined ) { material.specularMap = getTexture( json.specularMap ); }

			if ( json.envMap !== undefined ) { material.envMap = getTexture( json.envMap ); }
			if ( json.envMapIntensity !== undefined ) { material.envMapIntensity = json.envMapIntensity; }

			if ( json.reflectivity !== undefined ) { material.reflectivity = json.reflectivity; }
			if ( json.refractionRatio !== undefined ) { material.refractionRatio = json.refractionRatio; }

			if ( json.lightMap !== undefined ) { material.lightMap = getTexture( json.lightMap ); }
			if ( json.lightMapIntensity !== undefined ) { material.lightMapIntensity = json.lightMapIntensity; }

			if ( json.aoMap !== undefined ) { material.aoMap = getTexture( json.aoMap ); }
			if ( json.aoMapIntensity !== undefined ) { material.aoMapIntensity = json.aoMapIntensity; }

			if ( json.gradientMap !== undefined ) { material.gradientMap = getTexture( json.gradientMap ); }

			if ( json.clearcoatNormalMap !== undefined ) { material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap ); }
			if ( json.clearcoatNormalScale !== undefined ) { material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale ); }

			return material;

		},

		setTextures: function ( value ) {

			this.textures = value;
			return this;

		}

	} );

	/**
	 * @author Don McCurdy / https://www.donmccurdy.com
	 */

	var LoaderUtils = {

		decodeText: function ( array ) {

			if ( typeof TextDecoder !== 'undefined' ) {

				return new TextDecoder().decode( array );

			}

			// Avoid the String.fromCharCode.apply(null, array) shortcut, which
			// throws a "maximum call stack size exceeded" error for large arrays.

			var s = '';

			for ( var i = 0, il = array.length; i < il; i ++ ) {

				// Implicitly assumes little-endian.
				s += String.fromCharCode( array[ i ] );

			}

			try {

				// merges multi-byte utf-8 characters.

				return decodeURIComponent( escape( s ) );

			} catch ( e ) { // see #16358

				return s;

			}

		},

		extractUrlBase: function ( url ) {

			var index = url.lastIndexOf( '/' );

			if ( index === - 1 ) { return './'; }

			return url.substr( 0, index + 1 );

		}

	};

	/**
	 * @author benaadams / https://twitter.com/ben_a_adams
	 */

	function InstancedBufferGeometry() {

		BufferGeometry.call( this );

		this.type = 'InstancedBufferGeometry';
		this.maxInstancedCount = undefined;

	}

	InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {

		constructor: InstancedBufferGeometry,

		isInstancedBufferGeometry: true,

		copy: function ( source ) {

			BufferGeometry.prototype.copy.call( this, source );

			this.maxInstancedCount = source.maxInstancedCount;

			return this;

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		toJSON: function () {

			var data = BufferGeometry.prototype.toJSON.call( this );

			data.maxInstancedCount = this.maxInstancedCount;

			data.isInstancedBufferGeometry = true;

			return data;

		}

	} );

	/**
	 * @author benaadams / https://twitter.com/ben_a_adams
	 */

	function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) {

		if ( typeof ( normalized ) === 'number' ) {

			meshPerAttribute = normalized;

			normalized = false;

			console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );

		}

		BufferAttribute.call( this, array, itemSize, normalized );

		this.meshPerAttribute = meshPerAttribute || 1;

	}

	InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {

		constructor: InstancedBufferAttribute,

		isInstancedBufferAttribute: true,

		copy: function ( source ) {

			BufferAttribute.prototype.copy.call( this, source );

			this.meshPerAttribute = source.meshPerAttribute;

			return this;

		},

		toJSON: function ()	{

			var data = BufferAttribute.prototype.toJSON.call( this );

			data.meshPerAttribute = this.meshPerAttribute;

			data.isInstancedBufferAttribute = true;

			return data;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function BufferGeometryLoader( manager ) {

		Loader.call( this, manager );

	}

	BufferGeometryLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

		constructor: BufferGeometryLoader,

		load: function ( url, onLoad, onProgress, onError ) {

			var scope = this;

			var loader = new FileLoader( scope.manager );
			loader.setPath( scope.path );
			loader.load( url, function ( text ) {

				onLoad( scope.parse( JSON.parse( text ) ) );

			}, onProgress, onError );

		},

		parse: function ( json ) {

			var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();

			var index = json.data.index;

			if ( index !== undefined ) {

				var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
				geometry.setIndex( new BufferAttribute( typedArray, 1 ) );

			}

			var attributes = json.data.attributes;

			for ( var key in attributes ) {

				var attribute = attributes[ key ];
				var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
				var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
				var bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
				if ( attribute.name !== undefined ) { bufferAttribute.name = attribute.name; }
				geometry.setAttribute( key, bufferAttribute );

			}

			var morphAttributes = json.data.morphAttributes;

			if ( morphAttributes ) {

				for ( var key in morphAttributes ) {

					var attributeArray = morphAttributes[ key ];

					var array = [];

					for ( var i = 0, il = attributeArray.length; i < il; i ++ ) {

						var attribute = attributeArray[ i ];
						var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );

						var bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
						if ( attribute.name !== undefined ) { bufferAttribute.name = attribute.name; }
						array.push( bufferAttribute );

					}

					geometry.morphAttributes[ key ] = array;

				}

			}

			var morphTargetsRelative = json.data.morphTargetsRelative;

			if ( morphTargetsRelative ) {

				geometry.morphTargetsRelative = true;

			}

			var groups = json.data.groups || json.data.drawcalls || json.data.offsets;

			if ( groups !== undefined ) {

				for ( var i = 0, n = groups.length; i !== n; ++ i ) {

					var group = groups[ i ];

					geometry.addGroup( group.start, group.count, group.materialIndex );

				}

			}

			var boundingSphere = json.data.boundingSphere;

			if ( boundingSphere !== undefined ) {

				var center = new Vector3();

				if ( boundingSphere.center !== undefined ) {

					center.fromArray( boundingSphere.center );

				}

				geometry.boundingSphere = new Sphere( center, boundingSphere.radius );

			}

			if ( json.name ) { geometry.name = json.name; }
			if ( json.userData ) { geometry.userData = json.userData; }

			return geometry;

		}

	} );

	var TYPED_ARRAYS = {
		Int8Array: Int8Array,
		Uint8Array: Uint8Array,
		// Workaround for IE11 pre KB2929437. See #11440
		Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
		Int16Array: Int16Array,
		Uint16Array: Uint16Array,
		Int32Array: Int32Array,
		Uint32Array: Uint32Array,
		Float32Array: Float32Array,
		Float64Array: Float64Array
	};

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function ObjectLoader( manager ) {

		Loader.call( this, manager );

	}

	ObjectLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

		constructor: ObjectLoader,

		load: function ( url, onLoad, onProgress, onError ) {

			var scope = this;

			var path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
			this.resourcePath = this.resourcePath || path;

			var loader = new FileLoader( scope.manager );
			loader.setPath( this.path );
			loader.load( url, function ( text ) {

				var json = null;

				try {

					json = JSON.parse( text );

				} catch ( error ) {

					if ( onError !== undefined ) { onError( error ); }

					console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );

					return;

				}

				var metadata = json.metadata;

				if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {

					console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
					return;

				}

				scope.parse( json, onLoad );

			}, onProgress, onError );

		},

		parse: function ( json, onLoad ) {

			var shapes = this.parseShape( json.shapes );
			var geometries = this.parseGeometries( json.geometries, shapes );

			var images = this.parseImages( json.images, function () {

				if ( onLoad !== undefined ) { onLoad( object ); }

			} );

			var textures = this.parseTextures( json.textures, images );
			var materials = this.parseMaterials( json.materials, textures );

			var object = this.parseObject( json.object, geometries, materials );

			if ( json.animations ) {

				object.animations = this.parseAnimations( json.animations );

			}

			if ( json.images === undefined || json.images.length === 0 ) {

				if ( onLoad !== undefined ) { onLoad( object ); }

			}

			return object;

		},

		parseShape: function ( json ) {

			var shapes = {};

			if ( json !== undefined ) {

				for ( var i = 0, l = json.length; i < l; i ++ ) {

					var shape = new Shape().fromJSON( json[ i ] );

					shapes[ shape.uuid ] = shape;

				}

			}

			return shapes;

		},

		parseGeometries: function ( json, shapes ) {

			var geometries = {};

			if ( json !== undefined ) {

				var bufferGeometryLoader = new BufferGeometryLoader();

				for ( var i = 0, l = json.length; i < l; i ++ ) {

					var geometry;
					var data = json[ i ];

					switch ( data.type ) {

						case 'PlaneGeometry':
						case 'PlaneBufferGeometry':

							geometry = new Geometries[ data.type ](
								data.width,
								data.height,
								data.widthSegments,
								data.heightSegments
							);

							break;

						case 'BoxGeometry':
						case 'BoxBufferGeometry':
						case 'CubeGeometry': // backwards compatible

							geometry = new Geometries[ data.type ](
								data.width,
								data.height,
								data.depth,
								data.widthSegments,
								data.heightSegments,
								data.depthSegments
							);

							break;

						case 'CircleGeometry':
						case 'CircleBufferGeometry':

							geometry = new Geometries[ data.type ](
								data.radius,
								data.segments,
								data.thetaStart,
								data.thetaLength
							);

							break;

						case 'CylinderGeometry':
						case 'CylinderBufferGeometry':

							geometry = new Geometries[ data.type ](
								data.radiusTop,
								data.radiusBottom,
								data.height,
								data.radialSegments,
								data.heightSegments,
								data.openEnded,
								data.thetaStart,
								data.thetaLength
							);

							break;

						case 'ConeGeometry':
						case 'ConeBufferGeometry':

							geometry = new Geometries[ data.type ](
								data.radius,
								data.height,
								data.radialSegments,
								data.heightSegments,
								data.openEnded,
								data.thetaStart,
								data.thetaLength
							);

							break;

						case 'SphereGeometry':
						case 'SphereBufferGeometry':

							geometry = new Geometries[ data.type ](
								data.radius,
								data.widthSegments,
								data.heightSegments,
								data.phiStart,
								data.phiLength,
								data.thetaStart,
								data.thetaLength
							);

							break;

						case 'DodecahedronGeometry':
						case 'DodecahedronBufferGeometry':
						case 'IcosahedronGeometry':
						case 'IcosahedronBufferGeometry':
						case 'OctahedronGeometry':
						case 'OctahedronBufferGeometry':
						case 'TetrahedronGeometry':
						case 'TetrahedronBufferGeometry':

							geometry = new Geometries[ data.type ](
								data.radius,
								data.detail
							);

							break;

						case 'RingGeometry':
						case 'RingBufferGeometry':

							geometry = new Geometries[ data.type ](
								data.innerRadius,
								data.outerRadius,
								data.thetaSegments,
								data.phiSegments,
								data.thetaStart,
								data.thetaLength
							);

							break;

						case 'TorusGeometry':
						case 'TorusBufferGeometry':

							geometry = new Geometries[ data.type ](
								data.radius,
								data.tube,
								data.radialSegments,
								data.tubularSegments,
								data.arc
							);

							break;

						case 'TorusKnotGeometry':
						case 'TorusKnotBufferGeometry':

							geometry = new Geometries[ data.type ](
								data.radius,
								data.tube,
								data.tubularSegments,
								data.radialSegments,
								data.p,
								data.q
							);

							break;

						case 'TubeGeometry':
						case 'TubeBufferGeometry':

							// This only works for built-in curves (e.g. CatmullRomCurve3).
							// User defined curves or instances of CurvePath will not be deserialized.
							geometry = new Geometries[ data.type ](
								new Curves[ data.path.type ]().fromJSON( data.path ),
								data.tubularSegments,
								data.radius,
								data.radialSegments,
								data.closed
							);

							break;

						case 'LatheGeometry':
						case 'LatheBufferGeometry':

							geometry = new Geometries[ data.type ](
								data.points,
								data.segments,
								data.phiStart,
								data.phiLength
							);

							break;

						case 'PolyhedronGeometry':
						case 'PolyhedronBufferGeometry':

							geometry = new Geometries[ data.type ](
								data.vertices,
								data.indices,
								data.radius,
								data.details
							);

							break;

						case 'ShapeGeometry':
						case 'ShapeBufferGeometry':

							var geometryShapes = [];

							for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {

								var shape = shapes[ data.shapes[ j ] ];

								geometryShapes.push( shape );

							}

							geometry = new Geometries[ data.type ](
								geometryShapes,
								data.curveSegments
							);

							break;


						case 'ExtrudeGeometry':
						case 'ExtrudeBufferGeometry':

							var geometryShapes = [];

							for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) {

								var shape = shapes[ data.shapes[ j ] ];

								geometryShapes.push( shape );

							}

							var extrudePath = data.options.extrudePath;

							if ( extrudePath !== undefined ) {

								data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );

							}

							geometry = new Geometries[ data.type ](
								geometryShapes,
								data.options
							);

							break;

						case 'BufferGeometry':
						case 'InstancedBufferGeometry':

							geometry = bufferGeometryLoader.parse( data );

							break;

						case 'Geometry':

							if ( 'THREE' in window && 'LegacyJSONLoader' in THREE ) {

								var geometryLoader = new THREE.LegacyJSONLoader();
								geometry = geometryLoader.parse( data, this.resourcePath ).geometry;


							} else {

								console.error( 'THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".' );

							}

							break;

						default:

							console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );

							continue;

					}

					geometry.uuid = data.uuid;

					if ( data.name !== undefined ) { geometry.name = data.name; }
					if ( geometry.isBufferGeometry === true && data.userData !== undefined ) { geometry.userData = data.userData; }

					geometries[ data.uuid ] = geometry;

				}

			}

			return geometries;

		},

		parseMaterials: function ( json, textures ) {

			var cache = {}; // MultiMaterial
			var materials = {};

			if ( json !== undefined ) {

				var loader = new MaterialLoader();
				loader.setTextures( textures );

				for ( var i = 0, l = json.length; i < l; i ++ ) {

					var data = json[ i ];

					if ( data.type === 'MultiMaterial' ) {

						// Deprecated

						var array = [];

						for ( var j = 0; j < data.materials.length; j ++ ) {

							var material = data.materials[ j ];

							if ( cache[ material.uuid ] === undefined ) {

								cache[ material.uuid ] = loader.parse( material );

							}

							array.push( cache[ material.uuid ] );

						}

						materials[ data.uuid ] = array;

					} else {

						if ( cache[ data.uuid ] === undefined ) {

							cache[ data.uuid ] = loader.parse( data );

						}

						materials[ data.uuid ] = cache[ data.uuid ];

					}

				}

			}

			return materials;

		},

		parseAnimations: function ( json ) {

			var animations = [];

			for ( var i = 0; i < json.length; i ++ ) {

				var data = json[ i ];

				var clip = AnimationClip.parse( data );

				if ( data.uuid !== undefined ) { clip.uuid = data.uuid; }

				animations.push( clip );

			}

			return animations;

		},

		parseImages: function ( json, onLoad ) {

			var scope = this;
			var images = {};

			function loadImage( url ) {

				scope.manager.itemStart( url );

				return loader.load( url, function () {

					scope.manager.itemEnd( url );

				}, undefined, function () {

					scope.manager.itemError( url );
					scope.manager.itemEnd( url );

				} );

			}

			if ( json !== undefined && json.length > 0 ) {

				var manager = new LoadingManager( onLoad );

				var loader = new ImageLoader( manager );
				loader.setCrossOrigin( this.crossOrigin );

				for ( var i = 0, il = json.length; i < il; i ++ ) {

					var image = json[ i ];
					var url = image.url;

					if ( Array.isArray( url ) ) {

						// load array of images e.g CubeTexture

						images[ image.uuid ] = [];

						for ( var j = 0, jl = url.length; j < jl; j ++ ) {

							var currentUrl = url[ j ];

							var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( currentUrl ) ? currentUrl : scope.resourcePath + currentUrl;

							images[ image.uuid ].push( loadImage( path ) );

						}

					} else {

						// load single image

						var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.resourcePath + image.url;

						images[ image.uuid ] = loadImage( path );

					}

				}

			}

			return images;

		},

		parseTextures: function ( json, images ) {

			function parseConstant( value, type ) {

				if ( typeof value === 'number' ) { return value; }

				console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );

				return type[ value ];

			}

			var textures = {};

			if ( json !== undefined ) {

				for ( var i = 0, l = json.length; i < l; i ++ ) {

					var data = json[ i ];

					if ( data.image === undefined ) {

						console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );

					}

					if ( images[ data.image ] === undefined ) {

						console.warn( 'THREE.ObjectLoader: Undefined image', data.image );

					}

					var texture;

					if ( Array.isArray( images[ data.image ] ) ) {

						texture = new CubeTexture( images[ data.image ] );

					} else {

						texture = new Texture( images[ data.image ] );

					}

					texture.needsUpdate = true;

					texture.uuid = data.uuid;

					if ( data.name !== undefined ) { texture.name = data.name; }

					if ( data.mapping !== undefined ) { texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING ); }

					if ( data.offset !== undefined ) { texture.offset.fromArray( data.offset ); }
					if ( data.repeat !== undefined ) { texture.repeat.fromArray( data.repeat ); }
					if ( data.center !== undefined ) { texture.center.fromArray( data.center ); }
					if ( data.rotation !== undefined ) { texture.rotation = data.rotation; }

					if ( data.wrap !== undefined ) {

						texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
						texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );

					}

					if ( data.format !== undefined ) { texture.format = data.format; }
					if ( data.type !== undefined ) { texture.type = data.type; }
					if ( data.encoding !== undefined ) { texture.encoding = data.encoding; }

					if ( data.minFilter !== undefined ) { texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); }
					if ( data.magFilter !== undefined ) { texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); }
					if ( data.anisotropy !== undefined ) { texture.anisotropy = data.anisotropy; }

					if ( data.flipY !== undefined ) { texture.flipY = data.flipY; }

					if ( data.premultiplyAlpha !== undefined ) { texture.premultiplyAlpha = data.premultiplyAlpha; }
					if ( data.unpackAlignment !== undefined ) { texture.unpackAlignment = data.unpackAlignment; }

					textures[ data.uuid ] = texture;

				}

			}

			return textures;

		},

		parseObject: function ( data, geometries, materials ) {

			var object;

			function getGeometry( name ) {

				if ( geometries[ name ] === undefined ) {

					console.warn( 'THREE.ObjectLoader: Undefined geometry', name );

				}

				return geometries[ name ];

			}

			function getMaterial( name ) {

				if ( name === undefined ) { return undefined; }

				if ( Array.isArray( name ) ) {

					var array = [];

					for ( var i = 0, l = name.length; i < l; i ++ ) {

						var uuid = name[ i ];

						if ( materials[ uuid ] === undefined ) {

							console.warn( 'THREE.ObjectLoader: Undefined material', uuid );

						}

						array.push( materials[ uuid ] );

					}

					return array;

				}

				if ( materials[ name ] === undefined ) {

					console.warn( 'THREE.ObjectLoader: Undefined material', name );

				}

				return materials[ name ];

			}

			switch ( data.type ) {

				case 'Scene':

					object = new Scene();

					if ( data.background !== undefined ) {

						if ( Number.isInteger( data.background ) ) {

							object.background = new Color( data.background );

						}

					}

					if ( data.fog !== undefined ) {

						if ( data.fog.type === 'Fog' ) {

							object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );

						} else if ( data.fog.type === 'FogExp2' ) {

							object.fog = new FogExp2( data.fog.color, data.fog.density );

						}

					}

					break;

				case 'PerspectiveCamera':

					object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );

					if ( data.focus !== undefined ) { object.focus = data.focus; }
					if ( data.zoom !== undefined ) { object.zoom = data.zoom; }
					if ( data.filmGauge !== undefined ) { object.filmGauge = data.filmGauge; }
					if ( data.filmOffset !== undefined ) { object.filmOffset = data.filmOffset; }
					if ( data.view !== undefined ) { object.view = Object.assign( {}, data.view ); }

					break;

				case 'OrthographicCamera':

					object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );

					if ( data.zoom !== undefined ) { object.zoom = data.zoom; }
					if ( data.view !== undefined ) { object.view = Object.assign( {}, data.view ); }

					break;

				case 'AmbientLight':

					object = new AmbientLight( data.color, data.intensity );

					break;

				case 'DirectionalLight':

					object = new DirectionalLight( data.color, data.intensity );

					break;

				case 'PointLight':

					object = new PointLight( data.color, data.intensity, data.distance, data.decay );

					break;

				case 'RectAreaLight':

					object = new RectAreaLight( data.color, data.intensity, data.width, data.height );

					break;

				case 'SpotLight':

					object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );

					break;

				case 'HemisphereLight':

					object = new HemisphereLight( data.color, data.groundColor, data.intensity );

					break;

				case 'SkinnedMesh':

					console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );

				case 'Mesh':

					var geometry = getGeometry( data.geometry );
					var material = getMaterial( data.material );

					if ( geometry.bones && geometry.bones.length > 0 ) {

						object = new SkinnedMesh( geometry, material );

					} else {

						object = new Mesh( geometry, material );

					}

					break;

				case 'InstancedMesh':

					var geometry = getGeometry( data.geometry );
					var material = getMaterial( data.material );
					var count = data.count;
					var instanceMatrix = data.instanceMatrix;

					object = new InstancedMesh( geometry, material, count );
					object.instanceMatrix = new BufferAttribute( new Float32Array( instanceMatrix.array ), 16 );

					break;

				case 'LOD':

					object = new LOD();

					break;

				case 'Line':

					object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );

					break;

				case 'LineLoop':

					object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );

					break;

				case 'LineSegments':

					object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );

					break;

				case 'PointCloud':
				case 'Points':

					object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );

					break;

				case 'Sprite':

					object = new Sprite( getMaterial( data.material ) );

					break;

				case 'Group':

					object = new Group();

					break;

				default:

					object = new Object3D();

			}

			object.uuid = data.uuid;

			if ( data.name !== undefined ) { object.name = data.name; }

			if ( data.matrix !== undefined ) {

				object.matrix.fromArray( data.matrix );

				if ( data.matrixAutoUpdate !== undefined ) { object.matrixAutoUpdate = data.matrixAutoUpdate; }
				if ( object.matrixAutoUpdate ) { object.matrix.decompose( object.position, object.quaternion, object.scale ); }

			} else {

				if ( data.position !== undefined ) { object.position.fromArray( data.position ); }
				if ( data.rotation !== undefined ) { object.rotation.fromArray( data.rotation ); }
				if ( data.quaternion !== undefined ) { object.quaternion.fromArray( data.quaternion ); }
				if ( data.scale !== undefined ) { object.scale.fromArray( data.scale ); }

			}

			if ( data.castShadow !== undefined ) { object.castShadow = data.castShadow; }
			if ( data.receiveShadow !== undefined ) { object.receiveShadow = data.receiveShadow; }

			if ( data.shadow ) {

				if ( data.shadow.bias !== undefined ) { object.shadow.bias = data.shadow.bias; }
				if ( data.shadow.radius !== undefined ) { object.shadow.radius = data.shadow.radius; }
				if ( data.shadow.mapSize !== undefined ) { object.shadow.mapSize.fromArray( data.shadow.mapSize ); }
				if ( data.shadow.camera !== undefined ) { object.shadow.camera = this.parseObject( data.shadow.camera ); }

			}

			if ( data.visible !== undefined ) { object.visible = data.visible; }
			if ( data.frustumCulled !== undefined ) { object.frustumCulled = data.frustumCulled; }
			if ( data.renderOrder !== undefined ) { object.renderOrder = data.renderOrder; }
			if ( data.userData !== undefined ) { object.userData = data.userData; }
			if ( data.layers !== undefined ) { object.layers.mask = data.layers; }

			if ( data.children !== undefined ) {

				var children = data.children;

				for ( var i = 0; i < children.length; i ++ ) {

					object.add( this.parseObject( children[ i ], geometries, materials ) );

				}

			}

			if ( data.type === 'LOD' ) {

				if ( data.autoUpdate !== undefined ) { object.autoUpdate = data.autoUpdate; }

				var levels = data.levels;

				for ( var l = 0; l < levels.length; l ++ ) {

					var level = levels[ l ];
					var child = object.getObjectByProperty( 'uuid', level.object );

					if ( child !== undefined ) {

						object.addLevel( child, level.distance );

					}

				}

			}

			return object;

		}

	} );

	var TEXTURE_MAPPING = {
		UVMapping: UVMapping,
		CubeReflectionMapping: CubeReflectionMapping,
		CubeRefractionMapping: CubeRefractionMapping,
		EquirectangularReflectionMapping: EquirectangularReflectionMapping,
		EquirectangularRefractionMapping: EquirectangularRefractionMapping,
		SphericalReflectionMapping: SphericalReflectionMapping,
		CubeUVReflectionMapping: CubeUVReflectionMapping,
		CubeUVRefractionMapping: CubeUVRefractionMapping
	};

	var TEXTURE_WRAPPING = {
		RepeatWrapping: RepeatWrapping,
		ClampToEdgeWrapping: ClampToEdgeWrapping,
		MirroredRepeatWrapping: MirroredRepeatWrapping
	};

	var TEXTURE_FILTER = {
		NearestFilter: NearestFilter,
		NearestMipmapNearestFilter: NearestMipmapNearestFilter,
		NearestMipmapLinearFilter: NearestMipmapLinearFilter,
		LinearFilter: LinearFilter,
		LinearMipmapNearestFilter: LinearMipmapNearestFilter,
		LinearMipmapLinearFilter: LinearMipmapLinearFilter
	};

	/**
	 * @author thespite / http://clicktorelease.com/
	 */


	function ImageBitmapLoader( manager ) {

		if ( typeof createImageBitmap === 'undefined' ) {

			console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );

		}

		if ( typeof fetch === 'undefined' ) {

			console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );

		}

		Loader.call( this, manager );

		this.options = undefined;

	}

	ImageBitmapLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

		constructor: ImageBitmapLoader,

		setOptions: function setOptions( options ) {

			this.options = options;

			return this;

		},

		load: function ( url, onLoad, onProgress, onError ) {

			if ( url === undefined ) { url = ''; }

			if ( this.path !== undefined ) { url = this.path + url; }

			url = this.manager.resolveURL( url );

			var scope = this;

			var cached = Cache.get( url );

			if ( cached !== undefined ) {

				scope.manager.itemStart( url );

				setTimeout( function () {

					if ( onLoad ) { onLoad( cached ); }

					scope.manager.itemEnd( url );

				}, 0 );

				return cached;

			}

			fetch( url ).then( function ( res ) {

				return res.blob();

			} ).then( function ( blob ) {

				if ( scope.options === undefined ) {

					// Workaround for FireFox. It causes an error if you pass options.
					return createImageBitmap( blob );

				} else {

					return createImageBitmap( blob, scope.options );

				}

			} ).then( function ( imageBitmap ) {

				Cache.add( url, imageBitmap );

				if ( onLoad ) { onLoad( imageBitmap ); }

				scope.manager.itemEnd( url );

			} ).catch( function ( e ) {

				if ( onError ) { onError( e ); }

				scope.manager.itemError( url );
				scope.manager.itemEnd( url );

			} );

			scope.manager.itemStart( url );

		}

	} );

	/**
	 * @author zz85 / http://www.lab4games.net/zz85/blog
	 * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
	 **/

	function ShapePath() {

		this.type = 'ShapePath';

		this.color = new Color();

		this.subPaths = [];
		this.currentPath = null;

	}

	Object.assign( ShapePath.prototype, {

		moveTo: function ( x, y ) {

			this.currentPath = new Path();
			this.subPaths.push( this.currentPath );
			this.currentPath.moveTo( x, y );

			return this;

		},

		lineTo: function ( x, y ) {

			this.currentPath.lineTo( x, y );

			return this;

		},

		quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {

			this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );

			return this;

		},

		bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {

			this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );

			return this;

		},

		splineThru: function ( pts ) {

			this.currentPath.splineThru( pts );

			return this;

		},

		toShapes: function ( isCCW, noHoles ) {

			function toShapesNoHoles( inSubpaths ) {

				var shapes = [];

				for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {

					var tmpPath = inSubpaths[ i ];

					var tmpShape = new Shape();
					tmpShape.curves = tmpPath.curves;

					shapes.push( tmpShape );

				}

				return shapes;

			}

			function isPointInsidePolygon( inPt, inPolygon ) {

				var polyLen = inPolygon.length;

				// inPt on polygon contour => immediate success    or
				// toggling of inside/outside at every single! intersection point of an edge
				//  with the horizontal line through inPt, left of inPt
				//  not counting lowerY endpoints of edges and whole edges on that line
				var inside = false;
				for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {

					var edgeLowPt = inPolygon[ p ];
					var edgeHighPt = inPolygon[ q ];

					var edgeDx = edgeHighPt.x - edgeLowPt.x;
					var edgeDy = edgeHighPt.y - edgeLowPt.y;

					if ( Math.abs( edgeDy ) > Number.EPSILON ) {

						// not parallel
						if ( edgeDy < 0 ) {

							edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
							edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;

						}
						if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) 		{ continue; }

						if ( inPt.y === edgeLowPt.y ) {

							if ( inPt.x === edgeLowPt.x )		{ return	true; }		// inPt is on contour ?
							// continue;				// no intersection or edgeLowPt => doesn't count !!!

						} else {

							var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
							if ( perpEdge === 0 )				{ return	true; }		// inPt is on contour ?
							if ( perpEdge < 0 ) 				{ continue; }
							inside = ! inside;		// true intersection left of inPt

						}

					} else {

						// parallel or collinear
						if ( inPt.y !== edgeLowPt.y ) 		{ continue; }			// parallel
						// edge lies on the same horizontal line as inPt
						if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
							 ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) )		{ return	true; }	// inPt: Point on contour !
						// continue;

					}

				}

				return	inside;

			}

			var isClockWise = ShapeUtils.isClockWise;

			var subPaths = this.subPaths;
			if ( subPaths.length === 0 ) { return []; }

			if ( noHoles === true )	{ return	toShapesNoHoles( subPaths ); }


			var solid, tmpPath, tmpShape, shapes = [];

			if ( subPaths.length === 1 ) {

				tmpPath = subPaths[ 0 ];
				tmpShape = new Shape();
				tmpShape.curves = tmpPath.curves;
				shapes.push( tmpShape );
				return shapes;

			}

			var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
			holesFirst = isCCW ? ! holesFirst : holesFirst;

			// console.log("Holes first", holesFirst);

			var betterShapeHoles = [];
			var newShapes = [];
			var newShapeHoles = [];
			var mainIdx = 0;
			var tmpPoints;

			newShapes[ mainIdx ] = undefined;
			newShapeHoles[ mainIdx ] = [];

			for ( var i = 0, l = subPaths.length; i < l; i ++ ) {

				tmpPath = subPaths[ i ];
				tmpPoints = tmpPath.getPoints();
				solid = isClockWise( tmpPoints );
				solid = isCCW ? ! solid : solid;

				if ( solid ) {

					if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) )	{ mainIdx ++; }

					newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
					newShapes[ mainIdx ].s.curves = tmpPath.curves;

					if ( holesFirst )	{ mainIdx ++; }
					newShapeHoles[ mainIdx ] = [];

					//console.log('cw', i);

				} else {

					newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );

					//console.log('ccw', i);

				}

			}

			// only Holes? -> probably all Shapes with wrong orientation
			if ( ! newShapes[ 0 ] )	{ return	toShapesNoHoles( subPaths ); }


			if ( newShapes.length > 1 ) {

				var ambiguous = false;
				var toChange = [];

				for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {

					betterShapeHoles[ sIdx ] = [];

				}

				for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {

					var sho = newShapeHoles[ sIdx ];

					for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {

						var ho = sho[ hIdx ];
						var hole_unassigned = true;

						for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {

							if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {

								if ( sIdx !== s2Idx )	{ toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); }
								if ( hole_unassigned ) {

									hole_unassigned = false;
									betterShapeHoles[ s2Idx ].push( ho );

								} else {

									ambiguous = true;

								}

							}

						}
						if ( hole_unassigned ) {

							betterShapeHoles[ sIdx ].push( ho );

						}

					}

				}
				// console.log("ambiguous: ", ambiguous);
				if ( toChange.length > 0 ) {

					// console.log("to change: ", toChange);
					if ( ! ambiguous )	{ newShapeHoles = betterShapeHoles; }

				}

			}

			var tmpHoles;

			for ( var i = 0, il = newShapes.length; i < il; i ++ ) {

				tmpShape = newShapes[ i ].s;
				shapes.push( tmpShape );
				tmpHoles = newShapeHoles[ i ];

				for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {

					tmpShape.holes.push( tmpHoles[ j ].h );

				}

			}

			//console.log("shape", shapes);

			return shapes;

		}

	} );

	/**
	 * @author zz85 / http://www.lab4games.net/zz85/blog
	 * @author mrdoob / http://mrdoob.com/
	 */


	function Font( data ) {

		this.type = 'Font';

		this.data = data;

	}

	Object.assign( Font.prototype, {

		isFont: true,

		generateShapes: function ( text, size ) {

			if ( size === undefined ) { size = 100; }

			var shapes = [];
			var paths = createPaths( text, size, this.data );

			for ( var p = 0, pl = paths.length; p < pl; p ++ ) {

				Array.prototype.push.apply( shapes, paths[ p ].toShapes() );

			}

			return shapes;

		}

	} );

	function createPaths( text, size, data ) {

		var chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // workaround for IE11, see #13988
		var scale = size / data.resolution;
		var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;

		var paths = [];

		var offsetX = 0, offsetY = 0;

		for ( var i = 0; i < chars.length; i ++ ) {

			var char = chars[ i ];

			if ( char === '\n' ) {

				offsetX = 0;
				offsetY -= line_height;

			} else {

				var ret = createPath( char, scale, offsetX, offsetY, data );
				offsetX += ret.offsetX;
				paths.push( ret.path );

			}

		}

		return paths;

	}

	function createPath( char, scale, offsetX, offsetY, data ) {

		var glyph = data.glyphs[ char ] || data.glyphs[ '?' ];

		if ( ! glyph ) {

			console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' );

			return;

		}

		var path = new ShapePath();

		var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;

		if ( glyph.o ) {

			var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );

			for ( var i = 0, l = outline.length; i < l; ) {

				var action = outline[ i ++ ];

				switch ( action ) {

					case 'm': // moveTo

						x = outline[ i ++ ] * scale + offsetX;
						y = outline[ i ++ ] * scale + offsetY;

						path.moveTo( x, y );

						break;

					case 'l': // lineTo

						x = outline[ i ++ ] * scale + offsetX;
						y = outline[ i ++ ] * scale + offsetY;

						path.lineTo( x, y );

						break;

					case 'q': // quadraticCurveTo

						cpx = outline[ i ++ ] * scale + offsetX;
						cpy = outline[ i ++ ] * scale + offsetY;
						cpx1 = outline[ i ++ ] * scale + offsetX;
						cpy1 = outline[ i ++ ] * scale + offsetY;

						path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );

						break;

					case 'b': // bezierCurveTo

						cpx = outline[ i ++ ] * scale + offsetX;
						cpy = outline[ i ++ ] * scale + offsetY;
						cpx1 = outline[ i ++ ] * scale + offsetX;
						cpy1 = outline[ i ++ ] * scale + offsetY;
						cpx2 = outline[ i ++ ] * scale + offsetX;
						cpy2 = outline[ i ++ ] * scale + offsetY;

						path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );

						break;

				}

			}

		}

		return { offsetX: glyph.ha * scale, path: path };

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function FontLoader( manager ) {

		Loader.call( this, manager );

	}

	FontLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

		constructor: FontLoader,

		load: function ( url, onLoad, onProgress, onError ) {

			var scope = this;

			var loader = new FileLoader( this.manager );
			loader.setPath( this.path );
			loader.load( url, function ( text ) {

				var json;

				try {

					json = JSON.parse( text );

				} catch ( e ) {

					console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
					json = JSON.parse( text.substring( 65, text.length - 2 ) );

				}

				var font = scope.parse( json );

				if ( onLoad ) { onLoad( font ); }

			}, onProgress, onError );

		},

		parse: function ( json ) {

			return new Font( json );

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	var _context;

	var AudioContext = {

		getContext: function () {

			if ( _context === undefined ) {

				_context = new ( window.AudioContext || window.webkitAudioContext )();

			}

			return _context;

		},

		setContext: function ( value ) {

			_context = value;

		}

	};

	/**
	 * @author Reece Aaron Lecrivain / http://reecenotes.com/
	 */

	function AudioLoader( manager ) {

		Loader.call( this, manager );

	}

	AudioLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

		constructor: AudioLoader,

		load: function ( url, onLoad, onProgress, onError ) {

			var loader = new FileLoader( this.manager );
			loader.setResponseType( 'arraybuffer' );
			loader.setPath( this.path );
			loader.load( url, function ( buffer ) {

				// Create a copy of the buffer. The `decodeAudioData` method
				// detaches the buffer when complete, preventing reuse.
				var bufferCopy = buffer.slice( 0 );

				var context = AudioContext.getContext();
				context.decodeAudioData( bufferCopy, function ( audioBuffer ) {

					onLoad( audioBuffer );

				} );

			}, onProgress, onError );

		}

	} );

	/**
	 * @author bhouston / http://clara.io
	 * @author WestLangley / http://github.com/WestLangley
	 *
	 * Primary reference:
	 *   https://graphics.stanford.edu/papers/envmap/envmap.pdf
	 *
	 * Secondary reference:
	 *   https://www.ppsloan.org/publications/StupidSH36.pdf
	 */

	// 3-band SH defined by 9 coefficients

	function SphericalHarmonics3() {

		this.coefficients = [];

		for ( var i = 0; i < 9; i ++ ) {

			this.coefficients.push( new Vector3() );

		}

	}

	Object.assign( SphericalHarmonics3.prototype, {

		isSphericalHarmonics3: true,

		set: function ( coefficients ) {

			for ( var i = 0; i < 9; i ++ ) {

				this.coefficients[ i ].copy( coefficients[ i ] );

			}

			return this;

		},

		zero: function () {

			for ( var i = 0; i < 9; i ++ ) {

				this.coefficients[ i ].set( 0, 0, 0 );

			}

			return this;

		},

		// get the radiance in the direction of the normal
		// target is a Vector3
		getAt: function ( normal, target ) {

			// normal is assumed to be unit length

			var x = normal.x, y = normal.y, z = normal.z;

			var coeff = this.coefficients;

			// band 0
			target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );

			// band 1
			target.addScale( coeff[ 1 ], 0.488603 * y );
			target.addScale( coeff[ 2 ], 0.488603 * z );
			target.addScale( coeff[ 3 ], 0.488603 * x );

			// band 2
			target.addScale( coeff[ 4 ], 1.092548 * ( x * y ) );
			target.addScale( coeff[ 5 ], 1.092548 * ( y * z ) );
			target.addScale( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
			target.addScale( coeff[ 7 ], 1.092548 * ( x * z ) );
			target.addScale( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );

			return target;

		},

		// get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
		// target is a Vector3
		// https://graphics.stanford.edu/papers/envmap/envmap.pdf
		getIrradianceAt: function ( normal, target ) {

			// normal is assumed to be unit length

			var x = normal.x, y = normal.y, z = normal.z;

			var coeff = this.coefficients;

			// band 0
			target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095

			// band 1
			target.addScale( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
			target.addScale( coeff[ 2 ], 2.0 * 0.511664 * z );
			target.addScale( coeff[ 3 ], 2.0 * 0.511664 * x );

			// band 2
			target.addScale( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
			target.addScale( coeff[ 5 ], 2.0 * 0.429043 * y * z );
			target.addScale( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
			target.addScale( coeff[ 7 ], 2.0 * 0.429043 * x * z );
			target.addScale( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274

			return target;

		},

		add: function ( sh ) {

			for ( var i = 0; i < 9; i ++ ) {

				this.coefficients[ i ].add( sh.coefficients[ i ] );

			}

			return this;

		},


		scale: function ( s ) {

			for ( var i = 0; i < 9; i ++ ) {

				this.coefficients[ i ].multiplyScalar( s );

			}

			return this;

		},

		lerp: function ( sh, alpha ) {

			for ( var i = 0; i < 9; i ++ ) {

				this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );

			}

			return this;

		},

		equals: function ( sh ) {

			for ( var i = 0; i < 9; i ++ ) {

				if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {

					return false;

				}

			}

			return true;

		},

		copy: function ( sh ) {

			return this.set( sh.coefficients );

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		fromArray: function ( array, offset ) {

			if ( offset === undefined ) { offset = 0; }

			var coefficients = this.coefficients;

			for ( var i = 0; i < 9; i ++ ) {

				coefficients[ i ].fromArray( array, offset + ( i * 3 ) );

			}

			return this;

		},

		toArray: function ( array, offset ) {

			if ( array === undefined ) { array = []; }
			if ( offset === undefined ) { offset = 0; }

			var coefficients = this.coefficients;

			for ( var i = 0; i < 9; i ++ ) {

				coefficients[ i ].toArray( array, offset + ( i * 3 ) );

			}

			return array;

		}

	} );

	Object.assign( SphericalHarmonics3, {

		// evaluate the basis functions
		// shBasis is an Array[ 9 ]
		getBasisAt: function ( normal, shBasis ) {

			// normal is assumed to be unit length

			var x = normal.x, y = normal.y, z = normal.z;

			// band 0
			shBasis[ 0 ] = 0.282095;

			// band 1
			shBasis[ 1 ] = 0.488603 * y;
			shBasis[ 2 ] = 0.488603 * z;
			shBasis[ 3 ] = 0.488603 * x;

			// band 2
			shBasis[ 4 ] = 1.092548 * x * y;
			shBasis[ 5 ] = 1.092548 * y * z;
			shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
			shBasis[ 7 ] = 1.092548 * x * z;
			shBasis[ 8 ] = 0.546274 * ( x * x - y * y );

		}

	} );

	/**
	 * @author WestLangley / http://github.com/WestLangley
	 *
	 * A LightProbe is a source of indirect-diffuse light
	 */

	function LightProbe( sh, intensity ) {

		Light.call( this, undefined, intensity );

		this.sh = ( sh !== undefined ) ? sh : new SphericalHarmonics3();

	}

	LightProbe.prototype = Object.assign( Object.create( Light.prototype ), {

		constructor: LightProbe,

		isLightProbe: true,

		copy: function ( source ) {

			Light.prototype.copy.call( this, source );

			this.sh.copy( source.sh );
			this.intensity = source.intensity;

			return this;

		},

		toJSON: function ( meta ) {

			var data = Light.prototype.toJSON.call( this, meta );

			// data.sh = this.sh.toArray(); // todo

			return data;

		}

	} );

	/**
	 * @author WestLangley / http://github.com/WestLangley
	 */

	function HemisphereLightProbe( skyColor, groundColor, intensity ) {

		LightProbe.call( this, undefined, intensity );

		var color1 = new Color().set( skyColor );
		var color2 = new Color().set( groundColor );

		var sky = new Vector3( color1.r, color1.g, color1.b );
		var ground = new Vector3( color2.r, color2.g, color2.b );

		// without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
		var c0 = Math.sqrt( Math.PI );
		var c1 = c0 * Math.sqrt( 0.75 );

		this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
		this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );

	}

	HemisphereLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {

		constructor: HemisphereLightProbe,

		isHemisphereLightProbe: true,

		copy: function ( source ) { // modifying colors not currently supported

			LightProbe.prototype.copy.call( this, source );

			return this;

		},

		toJSON: function ( meta ) {

			var data = LightProbe.prototype.toJSON.call( this, meta );

			// data.sh = this.sh.toArray(); // todo

			return data;

		}

	} );

	/**
	 * @author WestLangley / http://github.com/WestLangley
	 */

	function AmbientLightProbe( color, intensity ) {

		LightProbe.call( this, undefined, intensity );

		var color1 = new Color().set( color );

		// without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
		this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );

	}

	AmbientLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {

		constructor: AmbientLightProbe,

		isAmbientLightProbe: true,

		copy: function ( source ) { // modifying color not currently supported

			LightProbe.prototype.copy.call( this, source );

			return this;

		},

		toJSON: function ( meta ) {

			var data = LightProbe.prototype.toJSON.call( this, meta );

			// data.sh = this.sh.toArray(); // todo

			return data;

		}

	} );

	var _eyeRight = new Matrix4();
	var _eyeLeft = new Matrix4();

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function StereoCamera() {

		this.type = 'StereoCamera';

		this.aspect = 1;

		this.eyeSep = 0.064;

		this.cameraL = new PerspectiveCamera();
		this.cameraL.layers.enable( 1 );
		this.cameraL.matrixAutoUpdate = false;

		this.cameraR = new PerspectiveCamera();
		this.cameraR.layers.enable( 2 );
		this.cameraR.matrixAutoUpdate = false;

		this._cache = {
			focus: null,
			fov: null,
			aspect: null,
			near: null,
			far: null,
			zoom: null,
			eyeSep: null
		};

	}

	Object.assign( StereoCamera.prototype, {

		update: function ( camera ) {

			var cache = this._cache;

			var needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
				cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
				cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;

			if ( needsUpdate ) {

				cache.focus = camera.focus;
				cache.fov = camera.fov;
				cache.aspect = camera.aspect * this.aspect;
				cache.near = camera.near;
				cache.far = camera.far;
				cache.zoom = camera.zoom;
				cache.eyeSep = this.eyeSep;

				// Off-axis stereoscopic effect based on
				// http://paulbourke.net/stereographics/stereorender/

				var projectionMatrix = camera.projectionMatrix.clone();
				var eyeSepHalf = cache.eyeSep / 2;
				var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
				var ymax = ( cache.near * Math.tan( MathUtils.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
				var xmin, xmax;

				// translate xOffset

				_eyeLeft.elements[ 12 ] = - eyeSepHalf;
				_eyeRight.elements[ 12 ] = eyeSepHalf;

				// for left eye

				xmin = - ymax * cache.aspect + eyeSepOnProjection;
				xmax = ymax * cache.aspect + eyeSepOnProjection;

				projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
				projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );

				this.cameraL.projectionMatrix.copy( projectionMatrix );

				// for right eye

				xmin = - ymax * cache.aspect - eyeSepOnProjection;
				xmax = ymax * cache.aspect - eyeSepOnProjection;

				projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
				projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );

				this.cameraR.projectionMatrix.copy( projectionMatrix );

			}

			this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
			this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );

		}

	} );

	/**
	 * @author alteredq / http://alteredqualia.com/
	 */

	function Clock( autoStart ) {

		this.autoStart = ( autoStart !== undefined ) ? autoStart : true;

		this.startTime = 0;
		this.oldTime = 0;
		this.elapsedTime = 0;

		this.running = false;

	}

	Object.assign( Clock.prototype, {

		start: function () {

			this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732

			this.oldTime = this.startTime;
			this.elapsedTime = 0;
			this.running = true;

		},

		stop: function () {

			this.getElapsedTime();
			this.running = false;
			this.autoStart = false;

		},

		getElapsedTime: function () {

			this.getDelta();
			return this.elapsedTime;

		},

		getDelta: function () {

			var diff = 0;

			if ( this.autoStart && ! this.running ) {

				this.start();
				return 0;

			}

			if ( this.running ) {

				var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();

				diff = ( newTime - this.oldTime ) / 1000;
				this.oldTime = newTime;

				this.elapsedTime += diff;

			}

			return diff;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	var _position$2 = new Vector3();
	var _quaternion$3 = new Quaternion();
	var _scale$1 = new Vector3();
	var _orientation = new Vector3();

	function AudioListener() {

		Object3D.call( this );

		this.type = 'AudioListener';

		this.context = AudioContext.getContext();

		this.gain = this.context.createGain();
		this.gain.connect( this.context.destination );

		this.filter = null;

		this.timeDelta = 0;

		// private

		this._clock = new Clock();

	}

	AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {

		constructor: AudioListener,

		getInput: function () {

			return this.gain;

		},

		removeFilter: function ( ) {

			if ( this.filter !== null ) {

				this.gain.disconnect( this.filter );
				this.filter.disconnect( this.context.destination );
				this.gain.connect( this.context.destination );
				this.filter = null;

			}

			return this;

		},

		getFilter: function () {

			return this.filter;

		},

		setFilter: function ( value ) {

			if ( this.filter !== null ) {

				this.gain.disconnect( this.filter );
				this.filter.disconnect( this.context.destination );

			} else {

				this.gain.disconnect( this.context.destination );

			}

			this.filter = value;
			this.gain.connect( this.filter );
			this.filter.connect( this.context.destination );

			return this;

		},

		getMasterVolume: function () {

			return this.gain.gain.value;

		},

		setMasterVolume: function ( value ) {

			this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );

			return this;

		},

		updateMatrixWorld: function ( force ) {

			Object3D.prototype.updateMatrixWorld.call( this, force );

			var listener = this.context.listener;
			var up = this.up;

			this.timeDelta = this._clock.getDelta();

			this.matrixWorld.decompose( _position$2, _quaternion$3, _scale$1 );

			_orientation.set( 0, 0, - 1 ).applyQuaternion( _quaternion$3 );

			if ( listener.positionX ) {

				// code path for Chrome (see #14393)

				var endTime = this.context.currentTime + this.timeDelta;

				listener.positionX.linearRampToValueAtTime( _position$2.x, endTime );
				listener.positionY.linearRampToValueAtTime( _position$2.y, endTime );
				listener.positionZ.linearRampToValueAtTime( _position$2.z, endTime );
				listener.forwardX.linearRampToValueAtTime( _orientation.x, endTime );
				listener.forwardY.linearRampToValueAtTime( _orientation.y, endTime );
				listener.forwardZ.linearRampToValueAtTime( _orientation.z, endTime );
				listener.upX.linearRampToValueAtTime( up.x, endTime );
				listener.upY.linearRampToValueAtTime( up.y, endTime );
				listener.upZ.linearRampToValueAtTime( up.z, endTime );

			} else {

				listener.setPosition( _position$2.x, _position$2.y, _position$2.z );
				listener.setOrientation( _orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z );

			}

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author Reece Aaron Lecrivain / http://reecenotes.com/
	 */

	function Audio( listener ) {

		Object3D.call( this );

		this.type = 'Audio';

		this.listener = listener;
		this.context = listener.context;

		this.gain = this.context.createGain();
		this.gain.connect( listener.getInput() );

		this.autoplay = false;

		this.buffer = null;
		this.detune = 0;
		this.loop = false;
		this.loopStart = 0;
		this.loopEnd = 0;
		this.offset = 0;
		this.duration = undefined;
		this.playbackRate = 1;
		this.isPlaying = false;
		this.hasPlaybackControl = true;
		this.sourceType = 'empty';

		this._startedAt = 0;
		this._pausedAt = 0;

		this.filters = [];

	}

	Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {

		constructor: Audio,

		getOutput: function () {

			return this.gain;

		},

		setNodeSource: function ( audioNode ) {

			this.hasPlaybackControl = false;
			this.sourceType = 'audioNode';
			this.source = audioNode;
			this.connect();

			return this;

		},

		setMediaElementSource: function ( mediaElement ) {

			this.hasPlaybackControl = false;
			this.sourceType = 'mediaNode';
			this.source = this.context.createMediaElementSource( mediaElement );
			this.connect();

			return this;

		},

		setMediaStreamSource: function ( mediaStream ) {

			this.hasPlaybackControl = false;
			this.sourceType = 'mediaStreamNode';
			this.source = this.context.createMediaStreamSource( mediaStream );
			this.connect();

			return this;

		},

		setBuffer: function ( audioBuffer ) {

			this.buffer = audioBuffer;
			this.sourceType = 'buffer';

			if ( this.autoplay ) { this.play(); }

			return this;

		},

		play: function ( delay ) {

			if ( delay === undefined ) { delay = 0; }

			if ( this.isPlaying === true ) {

				console.warn( 'THREE.Audio: Audio is already playing.' );
				return;

			}

			if ( this.hasPlaybackControl === false ) {

				console.warn( 'THREE.Audio: this Audio has no playback control.' );
				return;

			}

			this._startedAt = this.context.currentTime + delay;

			var source = this.context.createBufferSource();
			source.buffer = this.buffer;
			source.loop = this.loop;
			source.loopStart = this.loopStart;
			source.loopEnd = this.loopEnd;
			source.onended = this.onEnded.bind( this );
			source.start( this._startedAt, this._pausedAt + this.offset, this.duration );

			this.isPlaying = true;

			this.source = source;

			this.setDetune( this.detune );
			this.setPlaybackRate( this.playbackRate );

			return this.connect();

		},

		pause: function () {

			if ( this.hasPlaybackControl === false ) {

				console.warn( 'THREE.Audio: this Audio has no playback control.' );
				return;

			}

			if ( this.isPlaying === true ) {

				this._pausedAt = ( this.context.currentTime - this._startedAt ) * this.playbackRate;

				this.source.stop();
				this.source.onended = null;

				this.isPlaying = false;

			}

			return this;

		},

		stop: function () {

			if ( this.hasPlaybackControl === false ) {

				console.warn( 'THREE.Audio: this Audio has no playback control.' );
				return;

			}

			this._pausedAt = 0;

			this.source.stop();
			this.source.onended = null;
			this.isPlaying = false;

			return this;

		},

		connect: function () {

			if ( this.filters.length > 0 ) {

				this.source.connect( this.filters[ 0 ] );

				for ( var i = 1, l = this.filters.length; i < l; i ++ ) {

					this.filters[ i - 1 ].connect( this.filters[ i ] );

				}

				this.filters[ this.filters.length - 1 ].connect( this.getOutput() );

			} else {

				this.source.connect( this.getOutput() );

			}

			return this;

		},

		disconnect: function () {

			if ( this.filters.length > 0 ) {

				this.source.disconnect( this.filters[ 0 ] );

				for ( var i = 1, l = this.filters.length; i < l; i ++ ) {

					this.filters[ i - 1 ].disconnect( this.filters[ i ] );

				}

				this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );

			} else {

				this.source.disconnect( this.getOutput() );

			}

			return this;

		},

		getFilters: function () {

			return this.filters;

		},

		setFilters: function ( value ) {

			if ( ! value ) { value = []; }

			if ( this.isPlaying === true ) {

				this.disconnect();
				this.filters = value;
				this.connect();

			} else {

				this.filters = value;

			}

			return this;

		},

		setDetune: function ( value ) {

			this.detune = value;

			if ( this.source.detune === undefined ) { return; } // only set detune when available

			if ( this.isPlaying === true ) {

				this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );

			}

			return this;

		},

		getDetune: function () {

			return this.detune;

		},

		getFilter: function () {

			return this.getFilters()[ 0 ];

		},

		setFilter: function ( filter ) {

			return this.setFilters( filter ? [ filter ] : [] );

		},

		setPlaybackRate: function ( value ) {

			if ( this.hasPlaybackControl === false ) {

				console.warn( 'THREE.Audio: this Audio has no playback control.' );
				return;

			}

			this.playbackRate = value;

			if ( this.isPlaying === true ) {

				this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );

			}

			return this;

		},

		getPlaybackRate: function () {

			return this.playbackRate;

		},

		onEnded: function () {

			this.isPlaying = false;

		},

		getLoop: function () {

			if ( this.hasPlaybackControl === false ) {

				console.warn( 'THREE.Audio: this Audio has no playback control.' );
				return false;

			}

			return this.loop;

		},

		setLoop: function ( value ) {

			if ( this.hasPlaybackControl === false ) {

				console.warn( 'THREE.Audio: this Audio has no playback control.' );
				return;

			}

			this.loop = value;

			if ( this.isPlaying === true ) {

				this.source.loop = this.loop;

			}

			return this;

		},

		setLoopStart: function ( value ) {

			this.loopStart = value;

			return this;

		},

		setLoopEnd: function ( value ) {

			this.loopEnd = value;

			return this;

		},

		getVolume: function () {

			return this.gain.gain.value;

		},

		setVolume: function ( value ) {

			this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );

			return this;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	var _position$3 = new Vector3();
	var _quaternion$4 = new Quaternion();
	var _scale$2 = new Vector3();
	var _orientation$1 = new Vector3();

	function PositionalAudio( listener ) {

		Audio.call( this, listener );

		this.panner = this.context.createPanner();
		this.panner.panningModel = 'HRTF';
		this.panner.connect( this.gain );

	}

	PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {

		constructor: PositionalAudio,

		getOutput: function () {

			return this.panner;

		},

		getRefDistance: function () {

			return this.panner.refDistance;

		},

		setRefDistance: function ( value ) {

			this.panner.refDistance = value;

			return this;

		},

		getRolloffFactor: function () {

			return this.panner.rolloffFactor;

		},

		setRolloffFactor: function ( value ) {

			this.panner.rolloffFactor = value;

			return this;

		},

		getDistanceModel: function () {

			return this.panner.distanceModel;

		},

		setDistanceModel: function ( value ) {

			this.panner.distanceModel = value;

			return this;

		},

		getMaxDistance: function () {

			return this.panner.maxDistance;

		},

		setMaxDistance: function ( value ) {

			this.panner.maxDistance = value;

			return this;

		},

		setDirectionalCone: function ( coneInnerAngle, coneOuterAngle, coneOuterGain ) {

			this.panner.coneInnerAngle = coneInnerAngle;
			this.panner.coneOuterAngle = coneOuterAngle;
			this.panner.coneOuterGain = coneOuterGain;

			return this;

		},

		updateMatrixWorld: function ( force ) {

			Object3D.prototype.updateMatrixWorld.call( this, force );

			if ( this.hasPlaybackControl === true && this.isPlaying === false ) { return; }

			this.matrixWorld.decompose( _position$3, _quaternion$4, _scale$2 );

			_orientation$1.set( 0, 0, 1 ).applyQuaternion( _quaternion$4 );

			var panner = this.panner;

			if ( panner.positionX ) {

				// code path for Chrome and Firefox (see #14393)

				var endTime = this.context.currentTime + this.listener.timeDelta;

				panner.positionX.linearRampToValueAtTime( _position$3.x, endTime );
				panner.positionY.linearRampToValueAtTime( _position$3.y, endTime );
				panner.positionZ.linearRampToValueAtTime( _position$3.z, endTime );
				panner.orientationX.linearRampToValueAtTime( _orientation$1.x, endTime );
				panner.orientationY.linearRampToValueAtTime( _orientation$1.y, endTime );
				panner.orientationZ.linearRampToValueAtTime( _orientation$1.z, endTime );

			} else {

				panner.setPosition( _position$3.x, _position$3.y, _position$3.z );
				panner.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z );

			}

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function AudioAnalyser( audio, fftSize ) {

		this.analyser = audio.context.createAnalyser();
		this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;

		this.data = new Uint8Array( this.analyser.frequencyBinCount );

		audio.getOutput().connect( this.analyser );

	}

	Object.assign( AudioAnalyser.prototype, {

		getFrequencyData: function () {

			this.analyser.getByteFrequencyData( this.data );

			return this.data;

		},

		getAverageFrequency: function () {

			var value = 0, data = this.getFrequencyData();

			for ( var i = 0; i < data.length; i ++ ) {

				value += data[ i ];

			}

			return value / data.length;

		}

	} );

	/**
	 *
	 * Buffered scene graph property that allows weighted accumulation.
	 *
	 *
	 * @author Ben Houston / http://clara.io/
	 * @author David Sarno / http://lighthaus.us/
	 * @author tschw
	 */

	function PropertyMixer( binding, typeName, valueSize ) {

		this.binding = binding;
		this.valueSize = valueSize;

		var bufferType = Float64Array,
			mixFunction;

		switch ( typeName ) {

			case 'quaternion':
				mixFunction = this._slerp;
				break;

			case 'string':
			case 'bool':
				bufferType = Array;
				mixFunction = this._select;
				break;

			default:
				mixFunction = this._lerp;

		}

		this.buffer = new bufferType( valueSize * 4 );
		// layout: [ incoming | accu0 | accu1 | orig ]
		//
		// interpolators can use .buffer as their .result
		// the data then goes to 'incoming'
		//
		// 'accu0' and 'accu1' are used frame-interleaved for
		// the cumulative result and are compared to detect
		// changes
		//
		// 'orig' stores the original state of the property

		this._mixBufferRegion = mixFunction;

		this.cumulativeWeight = 0;

		this.useCount = 0;
		this.referenceCount = 0;

	}

	Object.assign( PropertyMixer.prototype, {

		// accumulate data in the 'incoming' region into 'accu<i>'
		accumulate: function ( accuIndex, weight ) {

			// note: happily accumulating nothing when weight = 0, the caller knows
			// the weight and shouldn't have made the call in the first place

			var buffer = this.buffer,
				stride = this.valueSize,
				offset = accuIndex * stride + stride,

				currentWeight = this.cumulativeWeight;

			if ( currentWeight === 0 ) {

				// accuN := incoming * weight

				for ( var i = 0; i !== stride; ++ i ) {

					buffer[ offset + i ] = buffer[ i ];

				}

				currentWeight = weight;

			} else {

				// accuN := accuN + incoming * weight

				currentWeight += weight;
				var mix = weight / currentWeight;
				this._mixBufferRegion( buffer, offset, 0, mix, stride );

			}

			this.cumulativeWeight = currentWeight;

		},

		// apply the state of 'accu<i>' to the binding when accus differ
		apply: function ( accuIndex ) {

			var stride = this.valueSize,
				buffer = this.buffer,
				offset = accuIndex * stride + stride,

				weight = this.cumulativeWeight,

				binding = this.binding;

			this.cumulativeWeight = 0;

			if ( weight < 1 ) {

				// accuN := accuN + original * ( 1 - cumulativeWeight )

				var originalValueOffset = stride * 3;

				this._mixBufferRegion(
					buffer, offset, originalValueOffset, 1 - weight, stride );

			}

			for ( var i = stride, e = stride + stride; i !== e; ++ i ) {

				if ( buffer[ i ] !== buffer[ i + stride ] ) {

					// value has changed -> update scene graph

					binding.setValue( buffer, offset );
					break;

				}

			}

		},

		// remember the state of the bound property and copy it to both accus
		saveOriginalState: function () {

			var binding = this.binding;

			var buffer = this.buffer,
				stride = this.valueSize,

				originalValueOffset = stride * 3;

			binding.getValue( buffer, originalValueOffset );

			// accu[0..1] := orig -- initially detect changes against the original
			for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {

				buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];

			}

			this.cumulativeWeight = 0;

		},

		// apply the state previously taken via 'saveOriginalState' to the binding
		restoreOriginalState: function () {

			var originalValueOffset = this.valueSize * 3;
			this.binding.setValue( this.buffer, originalValueOffset );

		},


		// mix functions

		_select: function ( buffer, dstOffset, srcOffset, t, stride ) {

			if ( t >= 0.5 ) {

				for ( var i = 0; i !== stride; ++ i ) {

					buffer[ dstOffset + i ] = buffer[ srcOffset + i ];

				}

			}

		},

		_slerp: function ( buffer, dstOffset, srcOffset, t ) {

			Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );

		},

		_lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {

			var s = 1 - t;

			for ( var i = 0; i !== stride; ++ i ) {

				var j = dstOffset + i;

				buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;

			}

		}

	} );

	/**
	 *
	 * A reference to a real property in the scene graph.
	 *
	 *
	 * @author Ben Houston / http://clara.io/
	 * @author David Sarno / http://lighthaus.us/
	 * @author tschw
	 */

	// Characters [].:/ are reserved for track binding syntax.
	var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
	var _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );

	// Attempts to allow node names from any language. ES5's `\w` regexp matches
	// only latin characters, and the unicode \p{L} is not yet supported. So
	// instead, we exclude reserved characters and match everything else.
	var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
	var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';

	// Parent directories, delimited by '/' or ':'. Currently unused, but must
	// be matched to parse the rest of the track name.
	var _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );

	// Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
	var _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );

	// Object on target node, and accessor. May not contain reserved
	// characters. Accessor may contain any character except closing bracket.
	var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );

	// Property and accessor. May not contain reserved characters. Accessor may
	// contain any non-bracket characters.
	var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );

	var _trackRe = new RegExp( ''
		+ '^'
		+ _directoryRe
		+ _nodeRe
		+ _objectRe
		+ _propertyRe
		+ '$'
	);

	var _supportedObjectNames = [ 'material', 'materials', 'bones' ];

	function Composite( targetGroup, path, optionalParsedPath ) {

		var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );

		this._targetGroup = targetGroup;
		this._bindings = targetGroup.subscribe_( path, parsedPath );

	}

	Object.assign( Composite.prototype, {

		getValue: function ( array, offset ) {

			this.bind(); // bind all binding

			var firstValidIndex = this._targetGroup.nCachedObjects_,
				binding = this._bindings[ firstValidIndex ];

			// and only call .getValue on the first
			if ( binding !== undefined ) { binding.getValue( array, offset ); }

		},

		setValue: function ( array, offset ) {

			var bindings = this._bindings;

			for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {

				bindings[ i ].setValue( array, offset );

			}

		},

		bind: function () {

			var bindings = this._bindings;

			for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {

				bindings[ i ].bind();

			}

		},

		unbind: function () {

			var bindings = this._bindings;

			for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {

				bindings[ i ].unbind();

			}

		}

	} );


	function PropertyBinding( rootNode, path, parsedPath ) {

		this.path = path;
		this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );

		this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;

		this.rootNode = rootNode;

	}

	Object.assign( PropertyBinding, {

		Composite: Composite,

		create: function ( root, path, parsedPath ) {

			if ( ! ( root && root.isAnimationObjectGroup ) ) {

				return new PropertyBinding( root, path, parsedPath );

			} else {

				return new PropertyBinding.Composite( root, path, parsedPath );

			}

		},

		/**
		 * Replaces spaces with underscores and removes unsupported characters from
		 * node names, to ensure compatibility with parseTrackName().
		 *
		 * @param {string} name Node name to be sanitized.
		 * @return {string}
		 */
		sanitizeNodeName: function ( name ) {

			return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );

		},

		parseTrackName: function ( trackName ) {

			var matches = _trackRe.exec( trackName );

			if ( ! matches ) {

				throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );

			}

			var results = {
				// directoryName: matches[ 1 ], // (tschw) currently unused
				nodeName: matches[ 2 ],
				objectName: matches[ 3 ],
				objectIndex: matches[ 4 ],
				propertyName: matches[ 5 ], // required
				propertyIndex: matches[ 6 ]
			};

			var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );

			if ( lastDot !== undefined && lastDot !== - 1 ) {

				var objectName = results.nodeName.substring( lastDot + 1 );

				// Object names must be checked against a whitelist. Otherwise, there
				// is no way to parse 'foo.bar.baz': 'baz' must be a property, but
				// 'bar' could be the objectName, or part of a nodeName (which can
				// include '.' characters).
				if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {

					results.nodeName = results.nodeName.substring( 0, lastDot );
					results.objectName = objectName;

				}

			}

			if ( results.propertyName === null || results.propertyName.length === 0 ) {

				throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );

			}

			return results;

		},

		findNode: function ( root, nodeName ) {

			if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {

				return root;

			}

			// search into skeleton bones.
			if ( root.skeleton ) {

				var bone = root.skeleton.getBoneByName( nodeName );

				if ( bone !== undefined ) {

					return bone;

				}

			}

			// search into node subtree.
			if ( root.children ) {

				var searchNodeSubtree = function ( children ) {

					for ( var i = 0; i < children.length; i ++ ) {

						var childNode = children[ i ];

						if ( childNode.name === nodeName || childNode.uuid === nodeName ) {

							return childNode;

						}

						var result = searchNodeSubtree( childNode.children );

						if ( result ) { return result; }

					}

					return null;

				};

				var subTreeNode = searchNodeSubtree( root.children );

				if ( subTreeNode ) {

					return subTreeNode;

				}

			}

			return null;

		}

	} );

	Object.assign( PropertyBinding.prototype, { // prototype, continued

		// these are used to "bind" a nonexistent property
		_getValue_unavailable: function () {},
		_setValue_unavailable: function () {},

		BindingType: {
			Direct: 0,
			EntireArray: 1,
			ArrayElement: 2,
			HasFromToArray: 3
		},

		Versioning: {
			None: 0,
			NeedsUpdate: 1,
			MatrixWorldNeedsUpdate: 2
		},

		GetterByBindingType: [

			function getValue_direct( buffer, offset ) {

				buffer[ offset ] = this.node[ this.propertyName ];

			},

			function getValue_array( buffer, offset ) {

				var source = this.resolvedProperty;

				for ( var i = 0, n = source.length; i !== n; ++ i ) {

					buffer[ offset ++ ] = source[ i ];

				}

			},

			function getValue_arrayElement( buffer, offset ) {

				buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];

			},

			function getValue_toArray( buffer, offset ) {

				this.resolvedProperty.toArray( buffer, offset );

			}

		],

		SetterByBindingTypeAndVersioning: [

			[
				// Direct

				function setValue_direct( buffer, offset ) {

					this.targetObject[ this.propertyName ] = buffer[ offset ];

				},

				function setValue_direct_setNeedsUpdate( buffer, offset ) {

					this.targetObject[ this.propertyName ] = buffer[ offset ];
					this.targetObject.needsUpdate = true;

				},

				function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {

					this.targetObject[ this.propertyName ] = buffer[ offset ];
					this.targetObject.matrixWorldNeedsUpdate = true;

				}

			], [

				// EntireArray

				function setValue_array( buffer, offset ) {

					var dest = this.resolvedProperty;

					for ( var i = 0, n = dest.length; i !== n; ++ i ) {

						dest[ i ] = buffer[ offset ++ ];

					}

				},

				function setValue_array_setNeedsUpdate( buffer, offset ) {

					var dest = this.resolvedProperty;

					for ( var i = 0, n = dest.length; i !== n; ++ i ) {

						dest[ i ] = buffer[ offset ++ ];

					}

					this.targetObject.needsUpdate = true;

				},

				function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {

					var dest = this.resolvedProperty;

					for ( var i = 0, n = dest.length; i !== n; ++ i ) {

						dest[ i ] = buffer[ offset ++ ];

					}

					this.targetObject.matrixWorldNeedsUpdate = true;

				}

			], [

				// ArrayElement

				function setValue_arrayElement( buffer, offset ) {

					this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];

				},

				function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {

					this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
					this.targetObject.needsUpdate = true;

				},

				function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {

					this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
					this.targetObject.matrixWorldNeedsUpdate = true;

				}

			], [

				// HasToFromArray

				function setValue_fromArray( buffer, offset ) {

					this.resolvedProperty.fromArray( buffer, offset );

				},

				function setValue_fromArray_setNeedsUpdate( buffer, offset ) {

					this.resolvedProperty.fromArray( buffer, offset );
					this.targetObject.needsUpdate = true;

				},

				function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {

					this.resolvedProperty.fromArray( buffer, offset );
					this.targetObject.matrixWorldNeedsUpdate = true;

				}

			]

		],

		getValue: function getValue_unbound( targetArray, offset ) {

			this.bind();
			this.getValue( targetArray, offset );

			// Note: This class uses a State pattern on a per-method basis:
			// 'bind' sets 'this.getValue' / 'setValue' and shadows the
			// prototype version of these methods with one that represents
			// the bound state. When the property is not found, the methods
			// become no-ops.

		},

		setValue: function getValue_unbound( sourceArray, offset ) {

			this.bind();
			this.setValue( sourceArray, offset );

		},

		// create getter / setter pair for a property in the scene graph
		bind: function () {

			var targetObject = this.node,
				parsedPath = this.parsedPath,

				objectName = parsedPath.objectName,
				propertyName = parsedPath.propertyName,
				propertyIndex = parsedPath.propertyIndex;

			if ( ! targetObject ) {

				targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;

				this.node = targetObject;

			}

			// set fail state so we can just 'return' on error
			this.getValue = this._getValue_unavailable;
			this.setValue = this._setValue_unavailable;

			// ensure there is a value node
			if ( ! targetObject ) {

				console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
				return;

			}

			if ( objectName ) {

				var objectIndex = parsedPath.objectIndex;

				// special cases were we need to reach deeper into the hierarchy to get the face materials....
				switch ( objectName ) {

					case 'materials':

						if ( ! targetObject.material ) {

							console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
							return;

						}

						if ( ! targetObject.material.materials ) {

							console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
							return;

						}

						targetObject = targetObject.material.materials;

						break;

					case 'bones':

						if ( ! targetObject.skeleton ) {

							console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
							return;

						}

						// potential future optimization: skip this if propertyIndex is already an integer
						// and convert the integer string to a true integer.

						targetObject = targetObject.skeleton.bones;

						// support resolving morphTarget names into indices.
						for ( var i = 0; i < targetObject.length; i ++ ) {

							if ( targetObject[ i ].name === objectIndex ) {

								objectIndex = i;
								break;

							}

						}

						break;

					default:

						if ( targetObject[ objectName ] === undefined ) {

							console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
							return;

						}

						targetObject = targetObject[ objectName ];

				}


				if ( objectIndex !== undefined ) {

					if ( targetObject[ objectIndex ] === undefined ) {

						console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
						return;

					}

					targetObject = targetObject[ objectIndex ];

				}

			}

			// resolve property
			var nodeProperty = targetObject[ propertyName ];

			if ( nodeProperty === undefined ) {

				var nodeName = parsedPath.nodeName;

				console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
					'.' + propertyName + ' but it wasn\'t found.', targetObject );
				return;

			}

			// determine versioning scheme
			var versioning = this.Versioning.None;

			this.targetObject = targetObject;

			if ( targetObject.needsUpdate !== undefined ) { // material

				versioning = this.Versioning.NeedsUpdate;

			} else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform

				versioning = this.Versioning.MatrixWorldNeedsUpdate;

			}

			// determine how the property gets bound
			var bindingType = this.BindingType.Direct;

			if ( propertyIndex !== undefined ) {

				// access a sub element of the property array (only primitives are supported right now)

				if ( propertyName === "morphTargetInfluences" ) {

					// potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.

					// support resolving morphTarget names into indices.
					if ( ! targetObject.geometry ) {

						console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
						return;

					}

					if ( targetObject.geometry.isBufferGeometry ) {

						if ( ! targetObject.geometry.morphAttributes ) {

							console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
							return;

						}

						for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {

							if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {

								propertyIndex = i;
								break;

							}

						}


					} else {

						if ( ! targetObject.geometry.morphTargets ) {

							console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
							return;

						}

						for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {

							if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {

								propertyIndex = i;
								break;

							}

						}

					}

				}

				bindingType = this.BindingType.ArrayElement;

				this.resolvedProperty = nodeProperty;
				this.propertyIndex = propertyIndex;

			} else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {

				// must use copy for Object3D.Euler/Quaternion

				bindingType = this.BindingType.HasFromToArray;

				this.resolvedProperty = nodeProperty;

			} else if ( Array.isArray( nodeProperty ) ) {

				bindingType = this.BindingType.EntireArray;

				this.resolvedProperty = nodeProperty;

			} else {

				this.propertyName = propertyName;

			}

			// select getter / setter
			this.getValue = this.GetterByBindingType[ bindingType ];
			this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];

		},

		unbind: function () {

			this.node = null;

			// back to the prototype version of getValue / setValue
			// note: avoiding to mutate the shape of 'this' via 'delete'
			this.getValue = this._getValue_unbound;
			this.setValue = this._setValue_unbound;

		}

	} );

	//!\ DECLARE ALIAS AFTER assign prototype !
	Object.assign( PropertyBinding.prototype, {

		// initial state of these methods that calls 'bind'
		_getValue_unbound: PropertyBinding.prototype.getValue,
		_setValue_unbound: PropertyBinding.prototype.setValue,

	} );

	/**
	 *
	 * A group of objects that receives a shared animation state.
	 *
	 * Usage:
	 *
	 *  - Add objects you would otherwise pass as 'root' to the
	 *    constructor or the .clipAction method of AnimationMixer.
	 *
	 *  - Instead pass this object as 'root'.
	 *
	 *  - You can also add and remove objects later when the mixer
	 *    is running.
	 *
	 * Note:
	 *
	 *    Objects of this class appear as one object to the mixer,
	 *    so cache control of the individual objects must be done
	 *    on the group.
	 *
	 * Limitation:
	 *
	 *  - The animated properties must be compatible among the
	 *    all objects in the group.
	 *
	 *  - A single property can either be controlled through a
	 *    target group or directly, but not both.
	 *
	 * @author tschw
	 */

	function AnimationObjectGroup() {

		this.uuid = MathUtils.generateUUID();

		// cached objects followed by the active ones
		this._objects = Array.prototype.slice.call( arguments );

		this.nCachedObjects_ = 0; // threshold
		// note: read by PropertyBinding.Composite

		var indices = {};
		this._indicesByUUID = indices; // for bookkeeping

		for ( var i = 0, n = arguments.length; i !== n; ++ i ) {

			indices[ arguments[ i ].uuid ] = i;

		}

		this._paths = []; // inside: string
		this._parsedPaths = []; // inside: { we don't care, here }
		this._bindings = []; // inside: Array< PropertyBinding >
		this._bindingsIndicesByPath = {}; // inside: indices in these arrays

		var scope = this;

		this.stats = {

			objects: {
				get total() {

					return scope._objects.length;

				},
				get inUse() {

					return this.total - scope.nCachedObjects_;

				}
			},
			get bindingsPerObject() {

				return scope._bindings.length;

			}

		};

	}

	Object.assign( AnimationObjectGroup.prototype, {

		isAnimationObjectGroup: true,

		add: function () {

			var objects = this._objects,
				nObjects = objects.length,
				nCachedObjects = this.nCachedObjects_,
				indicesByUUID = this._indicesByUUID,
				paths = this._paths,
				parsedPaths = this._parsedPaths,
				bindings = this._bindings,
				nBindings = bindings.length,
				knownObject = undefined;

			for ( var i = 0, n = arguments.length; i !== n; ++ i ) {

				var object = arguments[ i ],
					uuid = object.uuid,
					index = indicesByUUID[ uuid ];

				if ( index === undefined ) {

					// unknown object -> add it to the ACTIVE region

					index = nObjects ++;
					indicesByUUID[ uuid ] = index;
					objects.push( object );

					// accounting is done, now do the same for all bindings

					for ( var j = 0, m = nBindings; j !== m; ++ j ) {

						bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );

					}

				} else if ( index < nCachedObjects ) {

					knownObject = objects[ index ];

					// move existing object to the ACTIVE region

					var firstActiveIndex = -- nCachedObjects,
						lastCachedObject = objects[ firstActiveIndex ];

					indicesByUUID[ lastCachedObject.uuid ] = index;
					objects[ index ] = lastCachedObject;

					indicesByUUID[ uuid ] = firstActiveIndex;
					objects[ firstActiveIndex ] = object;

					// accounting is done, now do the same for all bindings

					for ( var j = 0, m = nBindings; j !== m; ++ j ) {

						var bindingsForPath = bindings[ j ],
							lastCached = bindingsForPath[ firstActiveIndex ],
							binding = bindingsForPath[ index ];

						bindingsForPath[ index ] = lastCached;

						if ( binding === undefined ) {

							// since we do not bother to create new bindings
							// for objects that are cached, the binding may
							// or may not exist

							binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );

						}

						bindingsForPath[ firstActiveIndex ] = binding;

					}

				} else if ( objects[ index ] !== knownObject ) {

					console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
						'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );

				} // else the object is already where we want it to be

			} // for arguments

			this.nCachedObjects_ = nCachedObjects;

		},

		remove: function () {

			var objects = this._objects,
				nCachedObjects = this.nCachedObjects_,
				indicesByUUID = this._indicesByUUID,
				bindings = this._bindings,
				nBindings = bindings.length;

			for ( var i = 0, n = arguments.length; i !== n; ++ i ) {

				var object = arguments[ i ],
					uuid = object.uuid,
					index = indicesByUUID[ uuid ];

				if ( index !== undefined && index >= nCachedObjects ) {

					// move existing object into the CACHED region

					var lastCachedIndex = nCachedObjects ++,
						firstActiveObject = objects[ lastCachedIndex ];

					indicesByUUID[ firstActiveObject.uuid ] = index;
					objects[ index ] = firstActiveObject;

					indicesByUUID[ uuid ] = lastCachedIndex;
					objects[ lastCachedIndex ] = object;

					// accounting is done, now do the same for all bindings

					for ( var j = 0, m = nBindings; j !== m; ++ j ) {

						var bindingsForPath = bindings[ j ],
							firstActive = bindingsForPath[ lastCachedIndex ],
							binding = bindingsForPath[ index ];

						bindingsForPath[ index ] = firstActive;
						bindingsForPath[ lastCachedIndex ] = binding;

					}

				}

			} // for arguments

			this.nCachedObjects_ = nCachedObjects;

		},

		// remove & forget
		uncache: function () {

			var objects = this._objects,
				nObjects = objects.length,
				nCachedObjects = this.nCachedObjects_,
				indicesByUUID = this._indicesByUUID,
				bindings = this._bindings,
				nBindings = bindings.length;

			for ( var i = 0, n = arguments.length; i !== n; ++ i ) {

				var object = arguments[ i ],
					uuid = object.uuid,
					index = indicesByUUID[ uuid ];

				if ( index !== undefined ) {

					delete indicesByUUID[ uuid ];

					if ( index < nCachedObjects ) {

						// object is cached, shrink the CACHED region

						var firstActiveIndex = -- nCachedObjects,
							lastCachedObject = objects[ firstActiveIndex ],
							lastIndex = -- nObjects,
							lastObject = objects[ lastIndex ];

						// last cached object takes this object's place
						indicesByUUID[ lastCachedObject.uuid ] = index;
						objects[ index ] = lastCachedObject;

						// last object goes to the activated slot and pop
						indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
						objects[ firstActiveIndex ] = lastObject;
						objects.pop();

						// accounting is done, now do the same for all bindings

						for ( var j = 0, m = nBindings; j !== m; ++ j ) {

							var bindingsForPath = bindings[ j ],
								lastCached = bindingsForPath[ firstActiveIndex ],
								last = bindingsForPath[ lastIndex ];

							bindingsForPath[ index ] = lastCached;
							bindingsForPath[ firstActiveIndex ] = last;
							bindingsForPath.pop();

						}

					} else {

						// object is active, just swap with the last and pop

						var lastIndex = -- nObjects,
							lastObject = objects[ lastIndex ];

						indicesByUUID[ lastObject.uuid ] = index;
						objects[ index ] = lastObject;
						objects.pop();

						// accounting is done, now do the same for all bindings

						for ( var j = 0, m = nBindings; j !== m; ++ j ) {

							var bindingsForPath = bindings[ j ];

							bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
							bindingsForPath.pop();

						}

					} // cached or active

				} // if object is known

			} // for arguments

			this.nCachedObjects_ = nCachedObjects;

		},

		// Internal interface used by befriended PropertyBinding.Composite:

		subscribe_: function ( path, parsedPath ) {

			// returns an array of bindings for the given path that is changed
			// according to the contained objects in the group

			var indicesByPath = this._bindingsIndicesByPath,
				index = indicesByPath[ path ],
				bindings = this._bindings;

			if ( index !== undefined ) { return bindings[ index ]; }

			var paths = this._paths,
				parsedPaths = this._parsedPaths,
				objects = this._objects,
				nObjects = objects.length,
				nCachedObjects = this.nCachedObjects_,
				bindingsForPath = new Array( nObjects );

			index = bindings.length;

			indicesByPath[ path ] = index;

			paths.push( path );
			parsedPaths.push( parsedPath );
			bindings.push( bindingsForPath );

			for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {

				var object = objects[ i ];
				bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );

			}

			return bindingsForPath;

		},

		unsubscribe_: function ( path ) {

			// tells the group to forget about a property path and no longer
			// update the array previously obtained with 'subscribe_'

			var indicesByPath = this._bindingsIndicesByPath,
				index = indicesByPath[ path ];

			if ( index !== undefined ) {

				var paths = this._paths,
					parsedPaths = this._parsedPaths,
					bindings = this._bindings,
					lastBindingsIndex = bindings.length - 1,
					lastBindings = bindings[ lastBindingsIndex ],
					lastBindingsPath = path[ lastBindingsIndex ];

				indicesByPath[ lastBindingsPath ] = index;

				bindings[ index ] = lastBindings;
				bindings.pop();

				parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
				parsedPaths.pop();

				paths[ index ] = paths[ lastBindingsIndex ];
				paths.pop();

			}

		}

	} );

	/**
	 *
	 * Action provided by AnimationMixer for scheduling clip playback on specific
	 * objects.
	 *
	 * @author Ben Houston / http://clara.io/
	 * @author David Sarno / http://lighthaus.us/
	 * @author tschw
	 *
	 */

	function AnimationAction( mixer, clip, localRoot ) {

		this._mixer = mixer;
		this._clip = clip;
		this._localRoot = localRoot || null;

		var tracks = clip.tracks,
			nTracks = tracks.length,
			interpolants = new Array( nTracks );

		var interpolantSettings = {
			endingStart: ZeroCurvatureEnding,
			endingEnd: ZeroCurvatureEnding
		};

		for ( var i = 0; i !== nTracks; ++ i ) {

			var interpolant = tracks[ i ].createInterpolant( null );
			interpolants[ i ] = interpolant;
			interpolant.settings = interpolantSettings;

		}

		this._interpolantSettings = interpolantSettings;

		this._interpolants = interpolants; // bound by the mixer

		// inside: PropertyMixer (managed by the mixer)
		this._propertyBindings = new Array( nTracks );

		this._cacheIndex = null; // for the memory manager
		this._byClipCacheIndex = null; // for the memory manager

		this._timeScaleInterpolant = null;
		this._weightInterpolant = null;

		this.loop = LoopRepeat;
		this._loopCount = - 1;

		// global mixer time when the action is to be started
		// it's set back to 'null' upon start of the action
		this._startTime = null;

		// scaled local time of the action
		// gets clamped or wrapped to 0..clip.duration according to loop
		this.time = 0;

		this.timeScale = 1;
		this._effectiveTimeScale = 1;

		this.weight = 1;
		this._effectiveWeight = 1;

		this.repetitions = Infinity; // no. of repetitions when looping

		this.paused = false; // true -> zero effective time scale
		this.enabled = true; // false -> zero effective weight

		this.clampWhenFinished = false;// keep feeding the last frame?

		this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
		this.zeroSlopeAtEnd = true;// clips for start, loop and end

	}

	Object.assign( AnimationAction.prototype, {

		// State & Scheduling

		play: function () {

			this._mixer._activateAction( this );

			return this;

		},

		stop: function () {

			this._mixer._deactivateAction( this );

			return this.reset();

		},

		reset: function () {

			this.paused = false;
			this.enabled = true;

			this.time = 0; // restart clip
			this._loopCount = - 1;// forget previous loops
			this._startTime = null;// forget scheduling

			return this.stopFading().stopWarping();

		},

		isRunning: function () {

			return this.enabled && ! this.paused && this.timeScale !== 0 &&
				this._startTime === null && this._mixer._isActiveAction( this );

		},

		// return true when play has been called
		isScheduled: function () {

			return this._mixer._isActiveAction( this );

		},

		startAt: function ( time ) {

			this._startTime = time;

			return this;

		},

		setLoop: function ( mode, repetitions ) {

			this.loop = mode;
			this.repetitions = repetitions;

			return this;

		},

		// Weight

		// set the weight stopping any scheduled fading
		// although .enabled = false yields an effective weight of zero, this
		// method does *not* change .enabled, because it would be confusing
		setEffectiveWeight: function ( weight ) {

			this.weight = weight;

			// note: same logic as when updated at runtime
			this._effectiveWeight = this.enabled ? weight : 0;

			return this.stopFading();

		},

		// return the weight considering fading and .enabled
		getEffectiveWeight: function () {

			return this._effectiveWeight;

		},

		fadeIn: function ( duration ) {

			return this._scheduleFading( duration, 0, 1 );

		},

		fadeOut: function ( duration ) {

			return this._scheduleFading( duration, 1, 0 );

		},

		crossFadeFrom: function ( fadeOutAction, duration, warp ) {

			fadeOutAction.fadeOut( duration );
			this.fadeIn( duration );

			if ( warp ) {

				var fadeInDuration = this._clip.duration,
					fadeOutDuration = fadeOutAction._clip.duration,

					startEndRatio = fadeOutDuration / fadeInDuration,
					endStartRatio = fadeInDuration / fadeOutDuration;

				fadeOutAction.warp( 1.0, startEndRatio, duration );
				this.warp( endStartRatio, 1.0, duration );

			}

			return this;

		},

		crossFadeTo: function ( fadeInAction, duration, warp ) {

			return fadeInAction.crossFadeFrom( this, duration, warp );

		},

		stopFading: function () {

			var weightInterpolant = this._weightInterpolant;

			if ( weightInterpolant !== null ) {

				this._weightInterpolant = null;
				this._mixer._takeBackControlInterpolant( weightInterpolant );

			}

			return this;

		},

		// Time Scale Control

		// set the time scale stopping any scheduled warping
		// although .paused = true yields an effective time scale of zero, this
		// method does *not* change .paused, because it would be confusing
		setEffectiveTimeScale: function ( timeScale ) {

			this.timeScale = timeScale;
			this._effectiveTimeScale = this.paused ? 0 : timeScale;

			return this.stopWarping();

		},

		// return the time scale considering warping and .paused
		getEffectiveTimeScale: function () {

			return this._effectiveTimeScale;

		},

		setDuration: function ( duration ) {

			this.timeScale = this._clip.duration / duration;

			return this.stopWarping();

		},

		syncWith: function ( action ) {

			this.time = action.time;
			this.timeScale = action.timeScale;

			return this.stopWarping();

		},

		halt: function ( duration ) {

			return this.warp( this._effectiveTimeScale, 0, duration );

		},

		warp: function ( startTimeScale, endTimeScale, duration ) {

			var mixer = this._mixer, now = mixer.time,
				interpolant = this._timeScaleInterpolant,

				timeScale = this.timeScale;

			if ( interpolant === null ) {

				interpolant = mixer._lendControlInterpolant();
				this._timeScaleInterpolant = interpolant;

			}

			var times = interpolant.parameterPositions,
				values = interpolant.sampleValues;

			times[ 0 ] = now;
			times[ 1 ] = now + duration;

			values[ 0 ] = startTimeScale / timeScale;
			values[ 1 ] = endTimeScale / timeScale;

			return this;

		},

		stopWarping: function () {

			var timeScaleInterpolant = this._timeScaleInterpolant;

			if ( timeScaleInterpolant !== null ) {

				this._timeScaleInterpolant = null;
				this._mixer._takeBackControlInterpolant( timeScaleInterpolant );

			}

			return this;

		},

		// Object Accessors

		getMixer: function () {

			return this._mixer;

		},

		getClip: function () {

			return this._clip;

		},

		getRoot: function () {

			return this._localRoot || this._mixer._root;

		},

		// Interna

		_update: function ( time, deltaTime, timeDirection, accuIndex ) {

			// called by the mixer

			if ( ! this.enabled ) {

				// call ._updateWeight() to update ._effectiveWeight

				this._updateWeight( time );
				return;

			}

			var startTime = this._startTime;

			if ( startTime !== null ) {

				// check for scheduled start of action

				var timeRunning = ( time - startTime ) * timeDirection;
				if ( timeRunning < 0 || timeDirection === 0 ) {

					return; // yet to come / don't decide when delta = 0

				}

				// start

				this._startTime = null; // unschedule
				deltaTime = timeDirection * timeRunning;

			}

			// apply time scale and advance time

			deltaTime *= this._updateTimeScale( time );
			var clipTime = this._updateTime( deltaTime );

			// note: _updateTime may disable the action resulting in
			// an effective weight of 0

			var weight = this._updateWeight( time );

			if ( weight > 0 ) {

				var interpolants = this._interpolants;
				var propertyMixers = this._propertyBindings;

				for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {

					interpolants[ j ].evaluate( clipTime );
					propertyMixers[ j ].accumulate( accuIndex, weight );

				}

			}

		},

		_updateWeight: function ( time ) {

			var weight = 0;

			if ( this.enabled ) {

				weight = this.weight;
				var interpolant = this._weightInterpolant;

				if ( interpolant !== null ) {

					var interpolantValue = interpolant.evaluate( time )[ 0 ];

					weight *= interpolantValue;

					if ( time > interpolant.parameterPositions[ 1 ] ) {

						this.stopFading();

						if ( interpolantValue === 0 ) {

							// faded out, disable
							this.enabled = false;

						}

					}

				}

			}

			this._effectiveWeight = weight;
			return weight;

		},

		_updateTimeScale: function ( time ) {

			var timeScale = 0;

			if ( ! this.paused ) {

				timeScale = this.timeScale;

				var interpolant = this._timeScaleInterpolant;

				if ( interpolant !== null ) {

					var interpolantValue = interpolant.evaluate( time )[ 0 ];

					timeScale *= interpolantValue;

					if ( time > interpolant.parameterPositions[ 1 ] ) {

						this.stopWarping();

						if ( timeScale === 0 ) {

							// motion has halted, pause
							this.paused = true;

						} else {

							// warp done - apply final time scale
							this.timeScale = timeScale;

						}

					}

				}

			}

			this._effectiveTimeScale = timeScale;
			return timeScale;

		},

		_updateTime: function ( deltaTime ) {

			var time = this.time + deltaTime;
			var duration = this._clip.duration;
			var loop = this.loop;
			var loopCount = this._loopCount;

			var pingPong = ( loop === LoopPingPong );

			if ( deltaTime === 0 ) {

				if ( loopCount === - 1 ) { return time; }

				return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;

			}

			if ( loop === LoopOnce ) {

				if ( loopCount === - 1 ) {

					// just started

					this._loopCount = 0;
					this._setEndings( true, true, false );

				}

				handle_stop: {

					if ( time >= duration ) {

						time = duration;

					} else if ( time < 0 ) {

						time = 0;

					} else {

						this.time = time;

						break handle_stop;

					}

					if ( this.clampWhenFinished ) { this.paused = true; }
					else { this.enabled = false; }

					this.time = time;

					this._mixer.dispatchEvent( {
						type: 'finished', action: this,
						direction: deltaTime < 0 ? - 1 : 1
					} );

				}

			} else { // repetitive Repeat or PingPong

				if ( loopCount === - 1 ) {

					// just started

					if ( deltaTime >= 0 ) {

						loopCount = 0;

						this._setEndings( true, this.repetitions === 0, pingPong );

					} else {

						// when looping in reverse direction, the initial
						// transition through zero counts as a repetition,
						// so leave loopCount at -1

						this._setEndings( this.repetitions === 0, true, pingPong );

					}

				}

				if ( time >= duration || time < 0 ) {

					// wrap around

					var loopDelta = Math.floor( time / duration ); // signed
					time -= duration * loopDelta;

					loopCount += Math.abs( loopDelta );

					var pending = this.repetitions - loopCount;

					if ( pending <= 0 ) {

						// have to stop (switch state, clamp time, fire event)

						if ( this.clampWhenFinished ) { this.paused = true; }
						else { this.enabled = false; }

						time = deltaTime > 0 ? duration : 0;

						this.time = time;

						this._mixer.dispatchEvent( {
							type: 'finished', action: this,
							direction: deltaTime > 0 ? 1 : - 1
						} );

					} else {

						// keep running

						if ( pending === 1 ) {

							// entering the last round

							var atStart = deltaTime < 0;
							this._setEndings( atStart, ! atStart, pingPong );

						} else {

							this._setEndings( false, false, pingPong );

						}

						this._loopCount = loopCount;

						this.time = time;

						this._mixer.dispatchEvent( {
							type: 'loop', action: this, loopDelta: loopDelta
						} );

					}

				} else {

					this.time = time;

				}

				if ( pingPong && ( loopCount & 1 ) === 1 ) {

					// invert time for the "pong round"

					return duration - time;

				}

			}

			return time;

		},

		_setEndings: function ( atStart, atEnd, pingPong ) {

			var settings = this._interpolantSettings;

			if ( pingPong ) {

				settings.endingStart = ZeroSlopeEnding;
				settings.endingEnd = ZeroSlopeEnding;

			} else {

				// assuming for LoopOnce atStart == atEnd == true

				if ( atStart ) {

					settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;

				} else {

					settings.endingStart = WrapAroundEnding;

				}

				if ( atEnd ) {

					settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;

				} else {

					settings.endingEnd 	 = WrapAroundEnding;

				}

			}

		},

		_scheduleFading: function ( duration, weightNow, weightThen ) {

			var mixer = this._mixer, now = mixer.time,
				interpolant = this._weightInterpolant;

			if ( interpolant === null ) {

				interpolant = mixer._lendControlInterpolant();
				this._weightInterpolant = interpolant;

			}

			var times = interpolant.parameterPositions,
				values = interpolant.sampleValues;

			times[ 0 ] = now;
			values[ 0 ] = weightNow;
			times[ 1 ] = now + duration;
			values[ 1 ] = weightThen;

			return this;

		}

	} );

	/**
	 *
	 * Player for AnimationClips.
	 *
	 *
	 * @author Ben Houston / http://clara.io/
	 * @author David Sarno / http://lighthaus.us/
	 * @author tschw
	 */

	function AnimationMixer( root ) {

		this._root = root;
		this._initMemoryManager();
		this._accuIndex = 0;

		this.time = 0;

		this.timeScale = 1.0;

	}

	AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {

		constructor: AnimationMixer,

		_bindAction: function ( action, prototypeAction ) {

			var root = action._localRoot || this._root,
				tracks = action._clip.tracks,
				nTracks = tracks.length,
				bindings = action._propertyBindings,
				interpolants = action._interpolants,
				rootUuid = root.uuid,
				bindingsByRoot = this._bindingsByRootAndName,
				bindingsByName = bindingsByRoot[ rootUuid ];

			if ( bindingsByName === undefined ) {

				bindingsByName = {};
				bindingsByRoot[ rootUuid ] = bindingsByName;

			}

			for ( var i = 0; i !== nTracks; ++ i ) {

				var track = tracks[ i ],
					trackName = track.name,
					binding = bindingsByName[ trackName ];

				if ( binding !== undefined ) {

					bindings[ i ] = binding;

				} else {

					binding = bindings[ i ];

					if ( binding !== undefined ) {

						// existing binding, make sure the cache knows

						if ( binding._cacheIndex === null ) {

							++ binding.referenceCount;
							this._addInactiveBinding( binding, rootUuid, trackName );

						}

						continue;

					}

					var path = prototypeAction && prototypeAction.
						_propertyBindings[ i ].binding.parsedPath;

					binding = new PropertyMixer(
						PropertyBinding.create( root, trackName, path ),
						track.ValueTypeName, track.getValueSize() );

					++ binding.referenceCount;
					this._addInactiveBinding( binding, rootUuid, trackName );

					bindings[ i ] = binding;

				}

				interpolants[ i ].resultBuffer = binding.buffer;

			}

		},

		_activateAction: function ( action ) {

			if ( ! this._isActiveAction( action ) ) {

				if ( action._cacheIndex === null ) {

					// this action has been forgotten by the cache, but the user
					// appears to be still using it -> rebind

					var rootUuid = ( action._localRoot || this._root ).uuid,
						clipUuid = action._clip.uuid,
						actionsForClip = this._actionsByClip[ clipUuid ];

					this._bindAction( action,
						actionsForClip && actionsForClip.knownActions[ 0 ] );

					this._addInactiveAction( action, clipUuid, rootUuid );

				}

				var bindings = action._propertyBindings;

				// increment reference counts / sort out state
				for ( var i = 0, n = bindings.length; i !== n; ++ i ) {

					var binding = bindings[ i ];

					if ( binding.useCount ++ === 0 ) {

						this._lendBinding( binding );
						binding.saveOriginalState();

					}

				}

				this._lendAction( action );

			}

		},

		_deactivateAction: function ( action ) {

			if ( this._isActiveAction( action ) ) {

				var bindings = action._propertyBindings;

				// decrement reference counts / sort out state
				for ( var i = 0, n = bindings.length; i !== n; ++ i ) {

					var binding = bindings[ i ];

					if ( -- binding.useCount === 0 ) {

						binding.restoreOriginalState();
						this._takeBackBinding( binding );

					}

				}

				this._takeBackAction( action );

			}

		},

		// Memory manager

		_initMemoryManager: function () {

			this._actions = []; // 'nActiveActions' followed by inactive ones
			this._nActiveActions = 0;

			this._actionsByClip = {};
			// inside:
			// {
			// 	knownActions: Array< AnimationAction > - used as prototypes
			// 	actionByRoot: AnimationAction - lookup
			// }


			this._bindings = []; // 'nActiveBindings' followed by inactive ones
			this._nActiveBindings = 0;

			this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >


			this._controlInterpolants = []; // same game as above
			this._nActiveControlInterpolants = 0;

			var scope = this;

			this.stats = {

				actions: {
					get total() {

						return scope._actions.length;

					},
					get inUse() {

						return scope._nActiveActions;

					}
				},
				bindings: {
					get total() {

						return scope._bindings.length;

					},
					get inUse() {

						return scope._nActiveBindings;

					}
				},
				controlInterpolants: {
					get total() {

						return scope._controlInterpolants.length;

					},
					get inUse() {

						return scope._nActiveControlInterpolants;

					}
				}

			};

		},

		// Memory management for AnimationAction objects

		_isActiveAction: function ( action ) {

			var index = action._cacheIndex;
			return index !== null && index < this._nActiveActions;

		},

		_addInactiveAction: function ( action, clipUuid, rootUuid ) {

			var actions = this._actions,
				actionsByClip = this._actionsByClip,
				actionsForClip = actionsByClip[ clipUuid ];

			if ( actionsForClip === undefined ) {

				actionsForClip = {

					knownActions: [ action ],
					actionByRoot: {}

				};

				action._byClipCacheIndex = 0;

				actionsByClip[ clipUuid ] = actionsForClip;

			} else {

				var knownActions = actionsForClip.knownActions;

				action._byClipCacheIndex = knownActions.length;
				knownActions.push( action );

			}

			action._cacheIndex = actions.length;
			actions.push( action );

			actionsForClip.actionByRoot[ rootUuid ] = action;

		},

		_removeInactiveAction: function ( action ) {

			var actions = this._actions,
				lastInactiveAction = actions[ actions.length - 1 ],
				cacheIndex = action._cacheIndex;

			lastInactiveAction._cacheIndex = cacheIndex;
			actions[ cacheIndex ] = lastInactiveAction;
			actions.pop();

			action._cacheIndex = null;


			var clipUuid = action._clip.uuid,
				actionsByClip = this._actionsByClip,
				actionsForClip = actionsByClip[ clipUuid ],
				knownActionsForClip = actionsForClip.knownActions,

				lastKnownAction =
					knownActionsForClip[ knownActionsForClip.length - 1 ],

				byClipCacheIndex = action._byClipCacheIndex;

			lastKnownAction._byClipCacheIndex = byClipCacheIndex;
			knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
			knownActionsForClip.pop();

			action._byClipCacheIndex = null;


			var actionByRoot = actionsForClip.actionByRoot,
				rootUuid = ( action._localRoot || this._root ).uuid;

			delete actionByRoot[ rootUuid ];

			if ( knownActionsForClip.length === 0 ) {

				delete actionsByClip[ clipUuid ];

			}

			this._removeInactiveBindingsForAction( action );

		},

		_removeInactiveBindingsForAction: function ( action ) {

			var bindings = action._propertyBindings;
			for ( var i = 0, n = bindings.length; i !== n; ++ i ) {

				var binding = bindings[ i ];

				if ( -- binding.referenceCount === 0 ) {

					this._removeInactiveBinding( binding );

				}

			}

		},

		_lendAction: function ( action ) {

			// [ active actions |  inactive actions  ]
			// [  active actions >| inactive actions ]
			//                 s        a
			//                  <-swap->
			//                 a        s

			var actions = this._actions,
				prevIndex = action._cacheIndex,

				lastActiveIndex = this._nActiveActions ++,

				firstInactiveAction = actions[ lastActiveIndex ];

			action._cacheIndex = lastActiveIndex;
			actions[ lastActiveIndex ] = action;

			firstInactiveAction._cacheIndex = prevIndex;
			actions[ prevIndex ] = firstInactiveAction;

		},

		_takeBackAction: function ( action ) {

			// [  active actions  | inactive actions ]
			// [ active actions |< inactive actions  ]
			//        a        s
			//         <-swap->
			//        s        a

			var actions = this._actions,
				prevIndex = action._cacheIndex,

				firstInactiveIndex = -- this._nActiveActions,

				lastActiveAction = actions[ firstInactiveIndex ];

			action._cacheIndex = firstInactiveIndex;
			actions[ firstInactiveIndex ] = action;

			lastActiveAction._cacheIndex = prevIndex;
			actions[ prevIndex ] = lastActiveAction;

		},

		// Memory management for PropertyMixer objects

		_addInactiveBinding: function ( binding, rootUuid, trackName ) {

			var bindingsByRoot = this._bindingsByRootAndName,
				bindingByName = bindingsByRoot[ rootUuid ],

				bindings = this._bindings;

			if ( bindingByName === undefined ) {

				bindingByName = {};
				bindingsByRoot[ rootUuid ] = bindingByName;

			}

			bindingByName[ trackName ] = binding;

			binding._cacheIndex = bindings.length;
			bindings.push( binding );

		},

		_removeInactiveBinding: function ( binding ) {

			var bindings = this._bindings,
				propBinding = binding.binding,
				rootUuid = propBinding.rootNode.uuid,
				trackName = propBinding.path,
				bindingsByRoot = this._bindingsByRootAndName,
				bindingByName = bindingsByRoot[ rootUuid ],

				lastInactiveBinding = bindings[ bindings.length - 1 ],
				cacheIndex = binding._cacheIndex;

			lastInactiveBinding._cacheIndex = cacheIndex;
			bindings[ cacheIndex ] = lastInactiveBinding;
			bindings.pop();

			delete bindingByName[ trackName ];

			if ( Object.keys( bindingByName ).length === 0 ) {

				delete bindingsByRoot[ rootUuid ];

			}

		},

		_lendBinding: function ( binding ) {

			var bindings = this._bindings,
				prevIndex = binding._cacheIndex,

				lastActiveIndex = this._nActiveBindings ++,

				firstInactiveBinding = bindings[ lastActiveIndex ];

			binding._cacheIndex = lastActiveIndex;
			bindings[ lastActiveIndex ] = binding;

			firstInactiveBinding._cacheIndex = prevIndex;
			bindings[ prevIndex ] = firstInactiveBinding;

		},

		_takeBackBinding: function ( binding ) {

			var bindings = this._bindings,
				prevIndex = binding._cacheIndex,

				firstInactiveIndex = -- this._nActiveBindings,

				lastActiveBinding = bindings[ firstInactiveIndex ];

			binding._cacheIndex = firstInactiveIndex;
			bindings[ firstInactiveIndex ] = binding;

			lastActiveBinding._cacheIndex = prevIndex;
			bindings[ prevIndex ] = lastActiveBinding;

		},


		// Memory management of Interpolants for weight and time scale

		_lendControlInterpolant: function () {

			var interpolants = this._controlInterpolants,
				lastActiveIndex = this._nActiveControlInterpolants ++,
				interpolant = interpolants[ lastActiveIndex ];

			if ( interpolant === undefined ) {

				interpolant = new LinearInterpolant(
					new Float32Array( 2 ), new Float32Array( 2 ),
					1, this._controlInterpolantsResultBuffer );

				interpolant.__cacheIndex = lastActiveIndex;
				interpolants[ lastActiveIndex ] = interpolant;

			}

			return interpolant;

		},

		_takeBackControlInterpolant: function ( interpolant ) {

			var interpolants = this._controlInterpolants,
				prevIndex = interpolant.__cacheIndex,

				firstInactiveIndex = -- this._nActiveControlInterpolants,

				lastActiveInterpolant = interpolants[ firstInactiveIndex ];

			interpolant.__cacheIndex = firstInactiveIndex;
			interpolants[ firstInactiveIndex ] = interpolant;

			lastActiveInterpolant.__cacheIndex = prevIndex;
			interpolants[ prevIndex ] = lastActiveInterpolant;

		},

		_controlInterpolantsResultBuffer: new Float32Array( 1 ),

		// return an action for a clip optionally using a custom root target
		// object (this method allocates a lot of dynamic memory in case a
		// previously unknown clip/root combination is specified)
		clipAction: function ( clip, optionalRoot ) {

			var root = optionalRoot || this._root,
				rootUuid = root.uuid,

				clipObject = typeof clip === 'string' ?
					AnimationClip.findByName( root, clip ) : clip,

				clipUuid = clipObject !== null ? clipObject.uuid : clip,

				actionsForClip = this._actionsByClip[ clipUuid ],
				prototypeAction = null;

			if ( actionsForClip !== undefined ) {

				var existingAction =
						actionsForClip.actionByRoot[ rootUuid ];

				if ( existingAction !== undefined ) {

					return existingAction;

				}

				// we know the clip, so we don't have to parse all
				// the bindings again but can just copy
				prototypeAction = actionsForClip.knownActions[ 0 ];

				// also, take the clip from the prototype action
				if ( clipObject === null )
					{ clipObject = prototypeAction._clip; }

			}

			// clip must be known when specified via string
			if ( clipObject === null ) { return null; }

			// allocate all resources required to run it
			var newAction = new AnimationAction( this, clipObject, optionalRoot );

			this._bindAction( newAction, prototypeAction );

			// and make the action known to the memory manager
			this._addInactiveAction( newAction, clipUuid, rootUuid );

			return newAction;

		},

		// get an existing action
		existingAction: function ( clip, optionalRoot ) {

			var root = optionalRoot || this._root,
				rootUuid = root.uuid,

				clipObject = typeof clip === 'string' ?
					AnimationClip.findByName( root, clip ) : clip,

				clipUuid = clipObject ? clipObject.uuid : clip,

				actionsForClip = this._actionsByClip[ clipUuid ];

			if ( actionsForClip !== undefined ) {

				return actionsForClip.actionByRoot[ rootUuid ] || null;

			}

			return null;

		},

		// deactivates all previously scheduled actions
		stopAllAction: function () {

			var actions = this._actions,
				nActions = this._nActiveActions,
				bindings = this._bindings,
				nBindings = this._nActiveBindings;

			this._nActiveActions = 0;
			this._nActiveBindings = 0;

			for ( var i = 0; i !== nActions; ++ i ) {

				actions[ i ].reset();

			}

			for ( var i = 0; i !== nBindings; ++ i ) {

				bindings[ i ].useCount = 0;

			}

			return this;

		},

		// advance the time and update apply the animation
		update: function ( deltaTime ) {

			deltaTime *= this.timeScale;

			var actions = this._actions,
				nActions = this._nActiveActions,

				time = this.time += deltaTime,
				timeDirection = Math.sign( deltaTime ),

				accuIndex = this._accuIndex ^= 1;

			// run active actions

			for ( var i = 0; i !== nActions; ++ i ) {

				var action = actions[ i ];

				action._update( time, deltaTime, timeDirection, accuIndex );

			}

			// update scene graph

			var bindings = this._bindings,
				nBindings = this._nActiveBindings;

			for ( var i = 0; i !== nBindings; ++ i ) {

				bindings[ i ].apply( accuIndex );

			}

			return this;

		},

		// Allows you to seek to a specific time in an animation.
		setTime: function ( timeInSeconds ) {

			this.time = 0; // Zero out time attribute for AnimationMixer object;
			for ( var i = 0; i < this._actions.length; i ++ ) {

				this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.

			}

			return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.

		},

		// return this mixer's root target object
		getRoot: function () {

			return this._root;

		},

		// free all resources specific to a particular clip
		uncacheClip: function ( clip ) {

			var actions = this._actions,
				clipUuid = clip.uuid,
				actionsByClip = this._actionsByClip,
				actionsForClip = actionsByClip[ clipUuid ];

			if ( actionsForClip !== undefined ) {

				// note: just calling _removeInactiveAction would mess up the
				// iteration state and also require updating the state we can
				// just throw away

				var actionsToRemove = actionsForClip.knownActions;

				for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {

					var action = actionsToRemove[ i ];

					this._deactivateAction( action );

					var cacheIndex = action._cacheIndex,
						lastInactiveAction = actions[ actions.length - 1 ];

					action._cacheIndex = null;
					action._byClipCacheIndex = null;

					lastInactiveAction._cacheIndex = cacheIndex;
					actions[ cacheIndex ] = lastInactiveAction;
					actions.pop();

					this._removeInactiveBindingsForAction( action );

				}

				delete actionsByClip[ clipUuid ];

			}

		},

		// free all resources specific to a particular root target object
		uncacheRoot: function ( root ) {

			var rootUuid = root.uuid,
				actionsByClip = this._actionsByClip;

			for ( var clipUuid in actionsByClip ) {

				var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
					action = actionByRoot[ rootUuid ];

				if ( action !== undefined ) {

					this._deactivateAction( action );
					this._removeInactiveAction( action );

				}

			}

			var bindingsByRoot = this._bindingsByRootAndName,
				bindingByName = bindingsByRoot[ rootUuid ];

			if ( bindingByName !== undefined ) {

				for ( var trackName in bindingByName ) {

					var binding = bindingByName[ trackName ];
					binding.restoreOriginalState();
					this._removeInactiveBinding( binding );

				}

			}

		},

		// remove a targeted clip from the cache
		uncacheAction: function ( clip, optionalRoot ) {

			var action = this.existingAction( clip, optionalRoot );

			if ( action !== null ) {

				this._deactivateAction( action );
				this._removeInactiveAction( action );

			}

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function Uniform( value ) {

		if ( typeof value === 'string' ) {

			console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
			value = arguments[ 1 ];

		}

		this.value = value;

	}

	Uniform.prototype.clone = function () {

		return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );

	};

	/**
	 * @author benaadams / https://twitter.com/ben_a_adams
	 */

	function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {

		InterleavedBuffer.call( this, array, stride );

		this.meshPerAttribute = meshPerAttribute || 1;

	}

	InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {

		constructor: InstancedInterleavedBuffer,

		isInstancedInterleavedBuffer: true,

		copy: function ( source ) {

			InterleavedBuffer.prototype.copy.call( this, source );

			this.meshPerAttribute = source.meshPerAttribute;

			return this;

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author bhouston / http://clara.io/
	 * @author stephomi / http://stephaneginier.com/
	 */

	function Raycaster( origin, direction, near, far ) {

		this.ray = new Ray( origin, direction );
		// direction is assumed to be normalized (for accurate distance calculations)

		this.near = near || 0;
		this.far = far || Infinity;
		this.camera = null;

		this.params = {
			Mesh: {},
			Line: {},
			LOD: {},
			Points: { threshold: 1 },
			Sprite: {}
		};

		Object.defineProperties( this.params, {
			PointCloud: {
				get: function () {

					console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
					return this.Points;

				}
			}
		} );

	}

	function ascSort( a, b ) {

		return a.distance - b.distance;

	}

	function intersectObject( object, raycaster, intersects, recursive ) {

		if ( object.visible === false ) { return; }

		object.raycast( raycaster, intersects );

		if ( recursive === true ) {

			var children = object.children;

			for ( var i = 0, l = children.length; i < l; i ++ ) {

				intersectObject( children[ i ], raycaster, intersects, true );

			}

		}

	}

	Object.assign( Raycaster.prototype, {

		linePrecision: 1,

		set: function ( origin, direction ) {

			// direction is assumed to be normalized (for accurate distance calculations)

			this.ray.set( origin, direction );

		},

		setFromCamera: function ( coords, camera ) {

			if ( ( camera && camera.isPerspectiveCamera ) ) {

				this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
				this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
				this.camera = camera;

			} else if ( ( camera && camera.isOrthographicCamera ) ) {

				this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
				this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
				this.camera = camera;

			} else {

				console.error( 'THREE.Raycaster: Unsupported camera type.' );

			}

		},

		intersectObject: function ( object, recursive, optionalTarget ) {

			var intersects = optionalTarget || [];

			intersectObject( object, this, intersects, recursive );

			intersects.sort( ascSort );

			return intersects;

		},

		intersectObjects: function ( objects, recursive, optionalTarget ) {

			var intersects = optionalTarget || [];

			if ( Array.isArray( objects ) === false ) {

				console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
				return intersects;

			}

			for ( var i = 0, l = objects.length; i < l; i ++ ) {

				intersectObject( objects[ i ], this, intersects, recursive );

			}

			intersects.sort( ascSort );

			return intersects;

		}

	} );

	/**
	 * @author bhouston / http://clara.io
	 * @author WestLangley / http://github.com/WestLangley
	 *
	 * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
	 *
	 * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
	 * The azimuthal angle (theta) is measured from the positive z-axis.
	 */

	function Spherical( radius, phi, theta ) {

		this.radius = ( radius !== undefined ) ? radius : 1.0;
		this.phi = ( phi !== undefined ) ? phi : 0; // polar angle
		this.theta = ( theta !== undefined ) ? theta : 0; // azimuthal angle

		return this;

	}

	Object.assign( Spherical.prototype, {

		set: function ( radius, phi, theta ) {

			this.radius = radius;
			this.phi = phi;
			this.theta = theta;

			return this;

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		copy: function ( other ) {

			this.radius = other.radius;
			this.phi = other.phi;
			this.theta = other.theta;

			return this;

		},

		// restrict phi to be betwee EPS and PI-EPS
		makeSafe: function () {

			var EPS = 0.000001;
			this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );

			return this;

		},

		setFromVector3: function ( v ) {

			return this.setFromCartesianCoords( v.x, v.y, v.z );

		},

		setFromCartesianCoords: function ( x, y, z ) {

			this.radius = Math.sqrt( x * x + y * y + z * z );

			if ( this.radius === 0 ) {

				this.theta = 0;
				this.phi = 0;

			} else {

				this.theta = Math.atan2( x, z );
				this.phi = Math.acos( MathUtils.clamp( y / this.radius, - 1, 1 ) );

			}

			return this;

		}

	} );

	/**
	 * @author Mugen87 / https://github.com/Mugen87
	 *
	 * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
	 *
	 */

	function Cylindrical( radius, theta, y ) {

		this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
		this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
		this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane

		return this;

	}

	Object.assign( Cylindrical.prototype, {

		set: function ( radius, theta, y ) {

			this.radius = radius;
			this.theta = theta;
			this.y = y;

			return this;

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		copy: function ( other ) {

			this.radius = other.radius;
			this.theta = other.theta;
			this.y = other.y;

			return this;

		},

		setFromVector3: function ( v ) {

			return this.setFromCartesianCoords( v.x, v.y, v.z );

		},

		setFromCartesianCoords: function ( x, y, z ) {

			this.radius = Math.sqrt( x * x + z * z );
			this.theta = Math.atan2( x, z );
			this.y = y;

			return this;

		}

	} );

	/**
	 * @author bhouston / http://clara.io
	 */

	var _vector$7 = new Vector2();

	function Box2( min, max ) {

		this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
		this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );

	}

	Object.assign( Box2.prototype, {

		set: function ( min, max ) {

			this.min.copy( min );
			this.max.copy( max );

			return this;

		},

		setFromPoints: function ( points ) {

			this.makeEmpty();

			for ( var i = 0, il = points.length; i < il; i ++ ) {

				this.expandByPoint( points[ i ] );

			}

			return this;

		},

		setFromCenterAndSize: function ( center, size ) {

			var halfSize = _vector$7.copy( size ).multiplyScalar( 0.5 );
			this.min.copy( center ).sub( halfSize );
			this.max.copy( center ).add( halfSize );

			return this;

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		copy: function ( box ) {

			this.min.copy( box.min );
			this.max.copy( box.max );

			return this;

		},

		makeEmpty: function () {

			this.min.x = this.min.y = + Infinity;
			this.max.x = this.max.y = - Infinity;

			return this;

		},

		isEmpty: function () {

			// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes

			return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );

		},

		getCenter: function ( target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Box2: .getCenter() target is now required' );
				target = new Vector2();

			}

			return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );

		},

		getSize: function ( target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Box2: .getSize() target is now required' );
				target = new Vector2();

			}

			return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );

		},

		expandByPoint: function ( point ) {

			this.min.min( point );
			this.max.max( point );

			return this;

		},

		expandByVector: function ( vector ) {

			this.min.sub( vector );
			this.max.add( vector );

			return this;

		},

		expandByScalar: function ( scalar ) {

			this.min.addScalar( - scalar );
			this.max.addScalar( scalar );

			return this;

		},

		containsPoint: function ( point ) {

			return point.x < this.min.x || point.x > this.max.x ||
				point.y < this.min.y || point.y > this.max.y ? false : true;

		},

		containsBox: function ( box ) {

			return this.min.x <= box.min.x && box.max.x <= this.max.x &&
				this.min.y <= box.min.y && box.max.y <= this.max.y;

		},

		getParameter: function ( point, target ) {

			// This can potentially have a divide by zero if the box
			// has a size dimension of 0.

			if ( target === undefined ) {

				console.warn( 'THREE.Box2: .getParameter() target is now required' );
				target = new Vector2();

			}

			return target.set(
				( point.x - this.min.x ) / ( this.max.x - this.min.x ),
				( point.y - this.min.y ) / ( this.max.y - this.min.y )
			);

		},

		intersectsBox: function ( box ) {

			// using 4 splitting planes to rule out intersections

			return box.max.x < this.min.x || box.min.x > this.max.x ||
				box.max.y < this.min.y || box.min.y > this.max.y ? false : true;

		},

		clampPoint: function ( point, target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Box2: .clampPoint() target is now required' );
				target = new Vector2();

			}

			return target.copy( point ).clamp( this.min, this.max );

		},

		distanceToPoint: function ( point ) {

			var clampedPoint = _vector$7.copy( point ).clamp( this.min, this.max );
			return clampedPoint.sub( point ).length();

		},

		intersect: function ( box ) {

			this.min.max( box.min );
			this.max.min( box.max );

			return this;

		},

		union: function ( box ) {

			this.min.min( box.min );
			this.max.max( box.max );

			return this;

		},

		translate: function ( offset ) {

			this.min.add( offset );
			this.max.add( offset );

			return this;

		},

		equals: function ( box ) {

			return box.min.equals( this.min ) && box.max.equals( this.max );

		}

	} );

	/**
	 * @author bhouston / http://clara.io
	 */

	var _startP = new Vector3();
	var _startEnd = new Vector3();

	function Line3( start, end ) {

		this.start = ( start !== undefined ) ? start : new Vector3();
		this.end = ( end !== undefined ) ? end : new Vector3();

	}

	Object.assign( Line3.prototype, {

		set: function ( start, end ) {

			this.start.copy( start );
			this.end.copy( end );

			return this;

		},

		clone: function () {

			return new this.constructor().copy( this );

		},

		copy: function ( line ) {

			this.start.copy( line.start );
			this.end.copy( line.end );

			return this;

		},

		getCenter: function ( target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Line3: .getCenter() target is now required' );
				target = new Vector3();

			}

			return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );

		},

		delta: function ( target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Line3: .delta() target is now required' );
				target = new Vector3();

			}

			return target.subVectors( this.end, this.start );

		},

		distanceSq: function () {

			return this.start.distanceToSquared( this.end );

		},

		distance: function () {

			return this.start.distanceTo( this.end );

		},

		at: function ( t, target ) {

			if ( target === undefined ) {

				console.warn( 'THREE.Line3: .at() target is now required' );
				target = new Vector3();

			}

			return this.delta( target ).multiplyScalar( t ).add( this.start );

		},

		closestPointToPointParameter: function ( point, clampToLine ) {

			_startP.subVectors( point, this.start );
			_startEnd.subVectors( this.end, this.start );

			var startEnd2 = _startEnd.dot( _startEnd );
			var startEnd_startP = _startEnd.dot( _startP );

			var t = startEnd_startP / startEnd2;

			if ( clampToLine ) {

				t = MathUtils.clamp( t, 0, 1 );

			}

			return t;

		},

		closestPointToPoint: function ( point, clampToLine, target ) {

			var t = this.closestPointToPointParameter( point, clampToLine );

			if ( target === undefined ) {

				console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
				target = new Vector3();

			}

			return this.delta( target ).multiplyScalar( t ).add( this.start );

		},

		applyMatrix4: function ( matrix ) {

			this.start.applyMatrix4( matrix );
			this.end.applyMatrix4( matrix );

			return this;

		},

		equals: function ( line ) {

			return line.start.equals( this.start ) && line.end.equals( this.end );

		}

	} );

	/**
	 * @author alteredq / http://alteredqualia.com/
	 */

	function ImmediateRenderObject( material ) {

		Object3D.call( this );

		this.material = material;
		this.render = function ( /* renderCallback */ ) {};

	}

	ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
	ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;

	ImmediateRenderObject.prototype.isImmediateRenderObject = true;

	/**
	 * @author alteredq / http://alteredqualia.com/
	 * @author mrdoob / http://mrdoob.com/
	 * @author WestLangley / http://github.com/WestLangley
	 */

	var _vector$8 = new Vector3();

	function SpotLightHelper( light, color ) {

		Object3D.call( this );

		this.light = light;
		this.light.updateMatrixWorld();

		this.matrix = light.matrixWorld;
		this.matrixAutoUpdate = false;

		this.color = color;

		var geometry = new BufferGeometry();

		var positions = [
			0, 0, 0, 	0, 0, 1,
			0, 0, 0, 	1, 0, 1,
			0, 0, 0,	- 1, 0, 1,
			0, 0, 0, 	0, 1, 1,
			0, 0, 0, 	0, - 1, 1
		];

		for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {

			var p1 = ( i / l ) * Math.PI * 2;
			var p2 = ( j / l ) * Math.PI * 2;

			positions.push(
				Math.cos( p1 ), Math.sin( p1 ), 1,
				Math.cos( p2 ), Math.sin( p2 ), 1
			);

		}

		geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );

		var material = new LineBasicMaterial( { fog: false } );

		this.cone = new LineSegments( geometry, material );
		this.add( this.cone );

		this.update();

	}

	SpotLightHelper.prototype = Object.create( Object3D.prototype );
	SpotLightHelper.prototype.constructor = SpotLightHelper;

	SpotLightHelper.prototype.dispose = function () {

		this.cone.geometry.dispose();
		this.cone.material.dispose();

	};

	SpotLightHelper.prototype.update = function () {

		this.light.updateMatrixWorld();

		var coneLength = this.light.distance ? this.light.distance : 1000;
		var coneWidth = coneLength * Math.tan( this.light.angle );

		this.cone.scale.set( coneWidth, coneWidth, coneLength );

		_vector$8.setFromMatrixPosition( this.light.target.matrixWorld );

		this.cone.lookAt( _vector$8 );

		if ( this.color !== undefined ) {

			this.cone.material.color.set( this.color );

		} else {

			this.cone.material.color.copy( this.light.color );

		}

	};

	/**
	 * @author Sean Griffin / http://twitter.com/sgrif
	 * @author Michael Guerrero / http://realitymeltdown.com
	 * @author mrdoob / http://mrdoob.com/
	 * @author ikerr / http://verold.com
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	var _vector$9 = new Vector3();
	var _boneMatrix = new Matrix4();
	var _matrixWorldInv = new Matrix4();

	function getBoneList( object ) {

		var boneList = [];

		if ( object && object.isBone ) {

			boneList.push( object );

		}

		for ( var i = 0; i < object.children.length; i ++ ) {

			boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );

		}

		return boneList;

	}

	function SkeletonHelper( object ) {

		var bones = getBoneList( object );

		var geometry = new BufferGeometry();

		var vertices = [];
		var colors = [];

		var color1 = new Color( 0, 0, 1 );
		var color2 = new Color( 0, 1, 0 );

		for ( var i = 0; i < bones.length; i ++ ) {

			var bone = bones[ i ];

			if ( bone.parent && bone.parent.isBone ) {

				vertices.push( 0, 0, 0 );
				vertices.push( 0, 0, 0 );
				colors.push( color1.r, color1.g, color1.b );
				colors.push( color2.r, color2.g, color2.b );

			}

		}

		geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );

		var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );

		LineSegments.call( this, geometry, material );

		this.root = object;
		this.bones = bones;

		this.matrix = object.matrixWorld;
		this.matrixAutoUpdate = false;

	}

	SkeletonHelper.prototype = Object.create( LineSegments.prototype );
	SkeletonHelper.prototype.constructor = SkeletonHelper;

	SkeletonHelper.prototype.updateMatrixWorld = function ( force ) {

		var bones = this.bones;

		var geometry = this.geometry;
		var position = geometry.getAttribute( 'position' );

		_matrixWorldInv.getInverse( this.root.matrixWorld );

		for ( var i = 0, j = 0; i < bones.length; i ++ ) {

			var bone = bones[ i ];

			if ( bone.parent && bone.parent.isBone ) {

				_boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
				_vector$9.setFromMatrixPosition( _boneMatrix );
				position.setXYZ( j, _vector$9.x, _vector$9.y, _vector$9.z );

				_boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
				_vector$9.setFromMatrixPosition( _boneMatrix );
				position.setXYZ( j + 1, _vector$9.x, _vector$9.y, _vector$9.z );

				j += 2;

			}

		}

		geometry.getAttribute( 'position' ).needsUpdate = true;

		Object3D.prototype.updateMatrixWorld.call( this, force );

	};

	/**
	 * @author alteredq / http://alteredqualia.com/
	 * @author mrdoob / http://mrdoob.com/
	 */

	function PointLightHelper( light, sphereSize, color ) {

		this.light = light;
		this.light.updateMatrixWorld();

		this.color = color;

		var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
		var material = new MeshBasicMaterial( { wireframe: true, fog: false } );

		Mesh.call( this, geometry, material );

		this.matrix = this.light.matrixWorld;
		this.matrixAutoUpdate = false;

		this.update();


		/*
		var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
		var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );

		this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
		this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );

		var d = light.distance;

		if ( d === 0.0 ) {

			this.lightDistance.visible = false;

		} else {

			this.lightDistance.scale.set( d, d, d );

		}

		this.add( this.lightDistance );
		*/

	}

	PointLightHelper.prototype = Object.create( Mesh.prototype );
	PointLightHelper.prototype.constructor = PointLightHelper;

	PointLightHelper.prototype.dispose = function () {

		this.geometry.dispose();
		this.material.dispose();

	};

	PointLightHelper.prototype.update = function () {

		if ( this.color !== undefined ) {

			this.material.color.set( this.color );

		} else {

			this.material.color.copy( this.light.color );

		}

		/*
		var d = this.light.distance;

		if ( d === 0.0 ) {

			this.lightDistance.visible = false;

		} else {

			this.lightDistance.visible = true;
			this.lightDistance.scale.set( d, d, d );

		}
		*/

	};

	/**
	 * @author alteredq / http://alteredqualia.com/
	 * @author mrdoob / http://mrdoob.com/
	 * @author Mugen87 / https://github.com/Mugen87
	 */

	var _vector$a = new Vector3();
	var _color1 = new Color();
	var _color2 = new Color();

	function HemisphereLightHelper( light, size, color ) {

		Object3D.call( this );

		this.light = light;
		this.light.updateMatrixWorld();

		this.matrix = light.matrixWorld;
		this.matrixAutoUpdate = false;

		this.color = color;

		var geometry = new OctahedronBufferGeometry( size );
		geometry.rotateY( Math.PI * 0.5 );

		this.material = new MeshBasicMaterial( { wireframe: true, fog: false } );
		if ( this.color === undefined ) { this.material.vertexColors = VertexColors; }

		var position = geometry.getAttribute( 'position' );
		var colors = new Float32Array( position.count * 3 );

		geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );

		this.add( new Mesh( geometry, this.material ) );

		this.update();

	}

	HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
	HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;

	HemisphereLightHelper.prototype.dispose = function () {

		this.children[ 0 ].geometry.dispose();
		this.children[ 0 ].material.dispose();

	};

	HemisphereLightHelper.prototype.update = function () {

		var mesh = this.children[ 0 ];

		if ( this.color !== undefined ) {

			this.material.color.set( this.color );

		} else {

			var colors = mesh.geometry.getAttribute( 'color' );

			_color1.copy( this.light.color );
			_color2.copy( this.light.groundColor );

			for ( var i = 0, l = colors.count; i < l; i ++ ) {

				var color = ( i < ( l / 2 ) ) ? _color1 : _color2;

				colors.setXYZ( i, color.r, color.g, color.b );

			}

			colors.needsUpdate = true;

		}

		mesh.lookAt( _vector$a.setFromMatrixPosition( this.light.matrixWorld ).negate() );

	};

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function GridHelper( size, divisions, color1, color2 ) {

		size = size || 10;
		divisions = divisions || 10;
		color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
		color2 = new Color( color2 !== undefined ? color2 : 0x888888 );

		var center = divisions / 2;
		var step = size / divisions;
		var halfSize = size / 2;

		var vertices = [], colors = [];

		for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {

			vertices.push( - halfSize, 0, k, halfSize, 0, k );
			vertices.push( k, 0, - halfSize, k, 0, halfSize );

			var color = i === center ? color1 : color2;

			color.toArray( colors, j ); j += 3;
			color.toArray( colors, j ); j += 3;
			color.toArray( colors, j ); j += 3;
			color.toArray( colors, j ); j += 3;

		}

		var geometry = new BufferGeometry();
		geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );

		var material = new LineBasicMaterial( { vertexColors: VertexColors } );

		LineSegments.call( this, geometry, material );

	}

	GridHelper.prototype = Object.assign( Object.create( LineSegments.prototype ), {

		constructor: GridHelper,

		copy: function ( source ) {

			LineSegments.prototype.copy.call( this, source );

			this.geometry.copy( source.geometry );
			this.material.copy( source.material );

			return this;

		},

		clone: function () {

			return new this.constructor().copy( this );

		}

	} );

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author Mugen87 / http://github.com/Mugen87
	 * @author Hectate / http://www.github.com/Hectate
	 */

	function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {

		radius = radius || 10;
		radials = radials || 16;
		circles = circles || 8;
		divisions = divisions || 64;
		color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
		color2 = new Color( color2 !== undefined ? color2 : 0x888888 );

		var vertices = [];
		var colors = [];

		var x, z;
		var v, i, j, r, color;

		// create the radials

		for ( i = 0; i <= radials; i ++ ) {

			v = ( i / radials ) * ( Math.PI * 2 );

			x = Math.sin( v ) * radius;
			z = Math.cos( v ) * radius;

			vertices.push( 0, 0, 0 );
			vertices.push( x, 0, z );

			color = ( i & 1 ) ? color1 : color2;

			colors.push( color.r, color.g, color.b );
			colors.push( color.r, color.g, color.b );

		}

		// create the circles

		for ( i = 0; i <= circles; i ++ ) {

			color = ( i & 1 ) ? color1 : color2;

			r = radius - ( radius / circles * i );

			for ( j = 0; j < divisions; j ++ ) {

				// first vertex

				v = ( j / divisions ) * ( Math.PI * 2 );

				x = Math.sin( v ) * r;
				z = Math.cos( v ) * r;

				vertices.push( x, 0, z );
				colors.push( color.r, color.g, color.b );

				// second vertex

				v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );

				x = Math.sin( v ) * r;
				z = Math.cos( v ) * r;

				vertices.push( x, 0, z );
				colors.push( color.r, color.g, color.b );

			}

		}

		var geometry = new BufferGeometry();
		geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );

		var material = new LineBasicMaterial( { vertexColors: VertexColors } );

		LineSegments.call( this, geometry, material );

	}

	PolarGridHelper.prototype = Object.create( LineSegments.prototype );
	PolarGridHelper.prototype.constructor = PolarGridHelper;

	/**
	 * @author alteredq / http://alteredqualia.com/
	 * @author mrdoob / http://mrdoob.com/
	 * @author WestLangley / http://github.com/WestLangley
	 */

	var _v1$5 = new Vector3();
	var _v2$3 = new Vector3();
	var _v3$1 = new Vector3();

	function DirectionalLightHelper( light, size, color ) {

		Object3D.call( this );

		this.light = light;
		this.light.updateMatrixWorld();

		this.matrix = light.matrixWorld;
		this.matrixAutoUpdate = false;

		this.color = color;

		if ( size === undefined ) { size = 1; }

		var geometry = new BufferGeometry();
		geometry.setAttribute( 'position', new Float32BufferAttribute( [
			- size, size, 0,
			size, size, 0,
			size, - size, 0,
			- size, - size, 0,
			- size, size, 0
		], 3 ) );

		var material = new LineBasicMaterial( { fog: false } );

		this.lightPlane = new Line( geometry, material );
		this.add( this.lightPlane );

		geometry = new BufferGeometry();
		geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );

		this.targetLine = new Line( geometry, material );
		this.add( this.targetLine );

		this.update();

	}

	DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
	DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;

	DirectionalLightHelper.prototype.dispose = function () {

		this.lightPlane.geometry.dispose();
		this.lightPlane.material.dispose();
		this.targetLine.geometry.dispose();
		this.targetLine.material.dispose();

	};

	DirectionalLightHelper.prototype.update = function () {

		_v1$5.setFromMatrixPosition( this.light.matrixWorld );
		_v2$3.setFromMatrixPosition( this.light.target.matrixWorld );
		_v3$1.subVectors( _v2$3, _v1$5 );

		this.lightPlane.lookAt( _v2$3 );

		if ( this.color !== undefined ) {

			this.lightPlane.material.color.set( this.color );
			this.targetLine.material.color.set( this.color );

		} else {

			this.lightPlane.material.color.copy( this.light.color );
			this.targetLine.material.color.copy( this.light.color );

		}

		this.targetLine.lookAt( _v2$3 );
		this.targetLine.scale.z = _v3$1.length();

	};

	/**
	 * @author alteredq / http://alteredqualia.com/
	 * @author Mugen87 / https://github.com/Mugen87
	 *
	 *	- shows frustum, line of sight and up of the camera
	 *	- suitable for fast updates
	 * 	- based on frustum visualization in lightgl.js shadowmap example
	 *		http://evanw.github.com/lightgl.js/tests/shadowmap.html
	 */

	var _vector$b = new Vector3();
	var _camera = new Camera();

	function CameraHelper( camera ) {

		var geometry = new BufferGeometry();
		var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );

		var vertices = [];
		var colors = [];

		var pointMap = {};

		// colors

		var colorFrustum = new Color( 0xffaa00 );
		var colorCone = new Color( 0xff0000 );
		var colorUp = new Color( 0x00aaff );
		var colorTarget = new Color( 0xffffff );
		var colorCross = new Color( 0x333333 );

		// near

		addLine( 'n1', 'n2', colorFrustum );
		addLine( 'n2', 'n4', colorFrustum );
		addLine( 'n4', 'n3', colorFrustum );
		addLine( 'n3', 'n1', colorFrustum );

		// far

		addLine( 'f1', 'f2', colorFrustum );
		addLine( 'f2', 'f4', colorFrustum );
		addLine( 'f4', 'f3', colorFrustum );
		addLine( 'f3', 'f1', colorFrustum );

		// sides

		addLine( 'n1', 'f1', colorFrustum );
		addLine( 'n2', 'f2', colorFrustum );
		addLine( 'n3', 'f3', colorFrustum );
		addLine( 'n4', 'f4', colorFrustum );

		// cone

		addLine( 'p', 'n1', colorCone );
		addLine( 'p', 'n2', colorCone );
		addLine( 'p', 'n3', colorCone );
		addLine( 'p', 'n4', colorCone );

		// up

		addLine( 'u1', 'u2', colorUp );
		addLine( 'u2', 'u3', colorUp );
		addLine( 'u3', 'u1', colorUp );

		// target

		addLine( 'c', 't', colorTarget );
		addLine( 'p', 'c', colorCross );

		// cross

		addLine( 'cn1', 'cn2', colorCross );
		addLine( 'cn3', 'cn4', colorCross );

		addLine( 'cf1', 'cf2', colorCross );
		addLine( 'cf3', 'cf4', colorCross );

		function addLine( a, b, color ) {

			addPoint( a, color );
			addPoint( b, color );

		}

		function addPoint( id, color ) {

			vertices.push( 0, 0, 0 );
			colors.push( color.r, color.g, color.b );

			if ( pointMap[ id ] === undefined ) {

				pointMap[ id ] = [];

			}

			pointMap[ id ].push( ( vertices.length / 3 ) - 1 );

		}

		geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );

		LineSegments.call( this, geometry, material );

		this.camera = camera;
		if ( this.camera.updateProjectionMatrix ) { this.camera.updateProjectionMatrix(); }

		this.matrix = camera.matrixWorld;
		this.matrixAutoUpdate = false;

		this.pointMap = pointMap;

		this.update();

	}

	CameraHelper.prototype = Object.create( LineSegments.prototype );
	CameraHelper.prototype.constructor = CameraHelper;

	CameraHelper.prototype.update = function () {

		var geometry = this.geometry;
		var pointMap = this.pointMap;

		var w = 1, h = 1;

		// we need just camera projection matrix inverse
		// world matrix must be identity

		_camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );

		// center / target

		setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
		setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );

		// near

		setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
		setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
		setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
		setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );

		// far

		setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
		setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
		setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
		setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );

		// up

		setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
		setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
		setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );

		// cross

		setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
		setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
		setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
		setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );

		setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
		setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
		setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
		setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );

		geometry.getAttribute( 'position' ).needsUpdate = true;

	};

	function setPoint( point, pointMap, geometry, camera, x, y, z ) {

		_vector$b.set( x, y, z ).unproject( camera );

		var points = pointMap[ point ];

		if ( points !== undefined ) {

			var position = geometry.getAttribute( 'position' );

			for ( var i = 0, l = points.length; i < l; i ++ ) {

				position.setXYZ( points[ i ], _vector$b.x, _vector$b.y, _vector$b.z );

			}

		}

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 * @author Mugen87 / http://github.com/Mugen87
	 */

	var _box$3 = new Box3();

	function BoxHelper( object, color ) {

		this.object = object;

		if ( color === undefined ) { color = 0xffff00; }

		var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
		var positions = new Float32Array( 8 * 3 );

		var geometry = new BufferGeometry();
		geometry.setIndex( new BufferAttribute( indices, 1 ) );
		geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );

		LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );

		this.matrixAutoUpdate = false;

		this.update();

	}

	BoxHelper.prototype = Object.create( LineSegments.prototype );
	BoxHelper.prototype.constructor = BoxHelper;

	BoxHelper.prototype.update = function ( object ) {

		if ( object !== undefined ) {

			console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );

		}

		if ( this.object !== undefined ) {

			_box$3.setFromObject( this.object );

		}

		if ( _box$3.isEmpty() ) { return; }

		var min = _box$3.min;
		var max = _box$3.max;

		/*
		  5____4
		1/___0/|
		| 6__|_7
		2/___3/

		0: max.x, max.y, max.z
		1: min.x, max.y, max.z
		2: min.x, min.y, max.z
		3: max.x, min.y, max.z
		4: max.x, max.y, min.z
		5: min.x, max.y, min.z
		6: min.x, min.y, min.z
		7: max.x, min.y, min.z
		*/

		var position = this.geometry.attributes.position;
		var array = position.array;

		array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
		array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
		array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
		array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
		array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
		array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
		array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
		array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;

		position.needsUpdate = true;

		this.geometry.computeBoundingSphere();


	};

	BoxHelper.prototype.setFromObject = function ( object ) {

		this.object = object;
		this.update();

		return this;

	};

	BoxHelper.prototype.copy = function ( source ) {

		LineSegments.prototype.copy.call( this, source );

		this.object = source.object;

		return this;

	};

	BoxHelper.prototype.clone = function () {

		return new this.constructor().copy( this );

	};

	/**
	 * @author WestLangley / http://github.com/WestLangley
	 */

	function Box3Helper( box, color ) {

		this.type = 'Box3Helper';

		this.box = box;

		color = color || 0xffff00;

		var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );

		var positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];

		var geometry = new BufferGeometry();

		geometry.setIndex( new BufferAttribute( indices, 1 ) );

		geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );

		LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );

		this.geometry.computeBoundingSphere();

	}

	Box3Helper.prototype = Object.create( LineSegments.prototype );
	Box3Helper.prototype.constructor = Box3Helper;

	Box3Helper.prototype.updateMatrixWorld = function ( force ) {

		var box = this.box;

		if ( box.isEmpty() ) { return; }

		box.getCenter( this.position );

		box.getSize( this.scale );

		this.scale.multiplyScalar( 0.5 );

		Object3D.prototype.updateMatrixWorld.call( this, force );

	};

	/**
	 * @author WestLangley / http://github.com/WestLangley
	 */

	function PlaneHelper( plane, size, hex ) {

		this.type = 'PlaneHelper';

		this.plane = plane;

		this.size = ( size === undefined ) ? 1 : size;

		var color = ( hex !== undefined ) ? hex : 0xffff00;

		var positions = [ 1, - 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 ];

		var geometry = new BufferGeometry();
		geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
		geometry.computeBoundingSphere();

		Line.call( this, geometry, new LineBasicMaterial( { color: color } ) );

		//

		var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];

		var geometry2 = new BufferGeometry();
		geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
		geometry2.computeBoundingSphere();

		this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false } ) ) );

	}

	PlaneHelper.prototype = Object.create( Line.prototype );
	PlaneHelper.prototype.constructor = PlaneHelper;

	PlaneHelper.prototype.updateMatrixWorld = function ( force ) {

		var scale = - this.plane.constant;

		if ( Math.abs( scale ) < 1e-8 ) { scale = 1e-8; } // sign does not matter

		this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );

		this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here

		this.lookAt( this.plane.normal );

		Object3D.prototype.updateMatrixWorld.call( this, force );

	};

	/**
	 * @author WestLangley / http://github.com/WestLangley
	 * @author zz85 / http://github.com/zz85
	 * @author bhouston / http://clara.io
	 *
	 * Creates an arrow for visualizing directions
	 *
	 * Parameters:
	 *  dir - Vector3
	 *  origin - Vector3
	 *  length - Number
	 *  color - color in hex value
	 *  headLength - Number
	 *  headWidth - Number
	 */

	var _axis = new Vector3();
	var _lineGeometry, _coneGeometry;

	function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {

		// dir is assumed to be normalized

		Object3D.call( this );

		if ( dir === undefined ) { dir = new Vector3( 0, 0, 1 ); }
		if ( origin === undefined ) { origin = new Vector3( 0, 0, 0 ); }
		if ( length === undefined ) { length = 1; }
		if ( color === undefined ) { color = 0xffff00; }
		if ( headLength === undefined ) { headLength = 0.2 * length; }
		if ( headWidth === undefined ) { headWidth = 0.2 * headLength; }

		if ( _lineGeometry === undefined ) {

			_lineGeometry = new BufferGeometry();
			_lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );

			_coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
			_coneGeometry.translate( 0, - 0.5, 0 );

		}

		this.position.copy( origin );

		this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color } ) );
		this.line.matrixAutoUpdate = false;
		this.add( this.line );

		this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color } ) );
		this.cone.matrixAutoUpdate = false;
		this.add( this.cone );

		this.setDirection( dir );
		this.setLength( length, headLength, headWidth );

	}

	ArrowHelper.prototype = Object.create( Object3D.prototype );
	ArrowHelper.prototype.constructor = ArrowHelper;

	ArrowHelper.prototype.setDirection = function ( dir ) {

		// dir is assumed to be normalized

		if ( dir.y > 0.99999 ) {

			this.quaternion.set( 0, 0, 0, 1 );

		} else if ( dir.y < - 0.99999 ) {

			this.quaternion.set( 1, 0, 0, 0 );

		} else {

			_axis.set( dir.z, 0, - dir.x ).normalize();

			var radians = Math.acos( dir.y );

			this.quaternion.setFromAxisAngle( _axis, radians );

		}

	};

	ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {

		if ( headLength === undefined ) { headLength = 0.2 * length; }
		if ( headWidth === undefined ) { headWidth = 0.2 * headLength; }

		this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
		this.line.updateMatrix();

		this.cone.scale.set( headWidth, headLength, headWidth );
		this.cone.position.y = length;
		this.cone.updateMatrix();

	};

	ArrowHelper.prototype.setColor = function ( color ) {

		this.line.material.color.set( color );
		this.cone.material.color.set( color );

	};

	ArrowHelper.prototype.copy = function ( source ) {

		Object3D.prototype.copy.call( this, source, false );

		this.line.copy( source.line );
		this.cone.copy( source.cone );

		return this;

	};

	ArrowHelper.prototype.clone = function () {

		return new this.constructor().copy( this );

	};

	/**
	 * @author sroucheray / http://sroucheray.org/
	 * @author mrdoob / http://mrdoob.com/
	 */

	function AxesHelper( size ) {

		size = size || 1;

		var vertices = [
			0, 0, 0,	size, 0, 0,
			0, 0, 0,	0, size, 0,
			0, 0, 0,	0, 0, size
		];

		var colors = [
			1, 0, 0,	1, 0.6, 0,
			0, 1, 0,	0.6, 1, 0,
			0, 0, 1,	0, 0.6, 1
		];

		var geometry = new BufferGeometry();
		geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );

		var material = new LineBasicMaterial( { vertexColors: VertexColors } );

		LineSegments.call( this, geometry, material );

	}

	AxesHelper.prototype = Object.create( LineSegments.prototype );
	AxesHelper.prototype.constructor = AxesHelper;

	/**
	 * @author Emmett Lalish / elalish
	 *
	 * This class generates a Prefiltered, Mipmapped Radiance Environment Map
	 * (PMREM) from a cubeMap environment texture. This allows different levels of
	 * blur to be quickly accessed based on material roughness. It is packed into a
	 * special CubeUV format that allows us to perform custom interpolation so that
	 * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
	 * chain, it only goes down to the LOD_MIN level (above), and then creates extra
	 * even more filtered 'mips' at the same LOD_MIN resolution, associated with
	 * higher roughness levels. In this way we maintain resolution to smoothly
	 * interpolate diffuse lighting while limiting sampling computation.
	 */

	var LOD_MIN = 4;
	var LOD_MAX = 8;
	var SIZE_MAX = Math.pow( 2, LOD_MAX );
	// The standard deviations (radians) associated with the extra mips. These are
	// chosen to approximate a Trowbridge-Reitz distribution function times the
	// geometric shadowing function. These sigma values squared must match the
	// variance #defines in cube_uv_reflection_fragment.glsl.js.
	var EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
	var TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
	// The maximum length of the blur for loop. Smaller sigmas will use fewer
	// samples and exit early, but not recompile the shader.
	var MAX_SAMPLES = 20;
	var ENCODINGS = {};
	ENCODINGS[ LinearEncoding ] = 0;
	ENCODINGS[ sRGBEncoding ] = 1;
	ENCODINGS[ RGBEEncoding ] = 2;
	ENCODINGS[ RGBM7Encoding ] = 3;
	ENCODINGS[ RGBM16Encoding ] = 4;
	ENCODINGS[ RGBDEncoding ] = 5;
	ENCODINGS[ GammaEncoding ] = 6;

	var _flatCamera = new OrthographicCamera();
	var _blurMaterial = _getBlurShader( MAX_SAMPLES );
	var _equirectShader = null;
	var _cubemapShader = null;

	var ref = _createPlanes();
	var _lodPlanes = ref._lodPlanes;
	var _sizeLods = ref._sizeLods;
	var _sigmas = ref._sigmas;
	var _pingPongRenderTarget = null;
	var _renderer = null;

	var _oldTarget = null;

	// Golden Ratio
	var PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
	var INV_PHI = 1 / PHI;
	// Vertices of a dodecahedron (except the opposites, which represent the
	// same axis), used as axis directions evenly spread on a sphere.
	var _axisDirections = [
		new Vector3( 1, 1, 1 ),
		new Vector3( - 1, 1, 1 ),
		new Vector3( 1, 1, - 1 ),
		new Vector3( - 1, 1, - 1 ),
		new Vector3( 0, PHI, INV_PHI ),
		new Vector3( 0, PHI, - INV_PHI ),
		new Vector3( INV_PHI, 0, PHI ),
		new Vector3( - INV_PHI, 0, PHI ),
		new Vector3( PHI, INV_PHI, 0 ),
		new Vector3( - PHI, INV_PHI, 0 ) ];

	function PMREMGenerator( renderer ) {

		_renderer = renderer;
		_compileMaterial( _blurMaterial );

	}

	PMREMGenerator.prototype = {

		constructor: PMREMGenerator,

		/**
		 * Generates a PMREM from a supplied Scene, which can be faster than using an
		 * image if networking bandwidth is low. Optional sigma specifies a blur radius
		 * in radians to be applied to the scene before PMREM generation. Optional near
		 * and far planes ensure the scene is rendered in its entirety (the cubeCamera
		 * is placed at the origin).
		 */
		fromScene: function ( scene, sigma, near, far ) {
			if ( sigma === void 0 ) sigma = 0;
			if ( near === void 0 ) near = 0.1;
			if ( far === void 0 ) far = 100;


			_oldTarget = _renderer.getRenderTarget();
			var cubeUVRenderTarget = _allocateTargets();
			_sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
			if ( sigma > 0 ) {

				_blur( cubeUVRenderTarget, 0, 0, sigma );

			}
			_applyPMREM( cubeUVRenderTarget );
			_cleanup( cubeUVRenderTarget );

			return cubeUVRenderTarget;

		},

		/**
		 * Generates a PMREM from an equirectangular texture, which can be either LDR
		 * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
		 * as this matches best with the 256 x 256 cubemap output.
		 */
		fromEquirectangular: function ( equirectangular ) {

			equirectangular.magFilter = NearestFilter;
			equirectangular.minFilter = NearestFilter;
			equirectangular.generateMipmaps = false;

			return this.fromCubemap( equirectangular );

		},

		/**
		 * Generates a PMREM from an cubemap texture, which can be either LDR
		 * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
		 * as this matches best with the 256 x 256 cubemap output.
		 */
		fromCubemap: function ( cubemap ) {

			_oldTarget = _renderer.getRenderTarget();
			var cubeUVRenderTarget = _allocateTargets( cubemap );
			_textureToCubeUV( cubemap, cubeUVRenderTarget );
			_applyPMREM( cubeUVRenderTarget );
			_cleanup( cubeUVRenderTarget );

			return cubeUVRenderTarget;

		},

		/**
		 * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
		 * your texture's network fetch for increased concurrency.
		 */
		compileCubemapShader: function () {

			if ( _cubemapShader == null ) {

				_cubemapShader = _getCubemapShader();
				_compileMaterial( _cubemapShader );

			}

		},

		/**
		 * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
		 * your texture's network fetch for increased concurrency.
		 */
		compileEquirectangularShader: function () {

			if ( _equirectShader == null ) {

				_equirectShader = _getEquirectShader();
				_compileMaterial( _equirectShader );

			}

		},

		/**
		 * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
		 * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
		 * one of them will cause any others to also become unusable.
		 */
		dispose: function () {

			_blurMaterial.dispose();

			if ( _cubemapShader != null ) { _cubemapShader.dispose(); }
			if ( _equirectShader != null ) { _equirectShader.dispose(); }

			for ( var i = 0; i < _lodPlanes.length; i ++ ) {

				_lodPlanes[ i ].dispose();

			}

		},

	};

	function _createPlanes() {

		var _lodPlanes = [];
		var _sizeLods = [];
		var _sigmas = [];

		var lod = LOD_MAX;
		for ( var i = 0; i < TOTAL_LODS; i ++ ) {

			var sizeLod = Math.pow( 2, lod );
			_sizeLods.push( sizeLod );
			var sigma = 1.0 / sizeLod;
			if ( i > LOD_MAX - LOD_MIN ) {

				sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];

			} else if ( i == 0 ) {

				sigma = 0;

			}
			_sigmas.push( sigma );

			var texelSize = 1.0 / ( sizeLod - 1 );
			var min = - texelSize / 2;
			var max = 1 + texelSize / 2;
			var uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];

			var cubeFaces = 6;
			var vertices = 6;
			var positionSize = 3;
			var uvSize = 2;
			var faceIndexSize = 1;

			var position = new Float32Array( positionSize * vertices * cubeFaces );
			var uv = new Float32Array( uvSize * vertices * cubeFaces );
			var faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );

			for ( var face = 0; face < cubeFaces; face ++ ) {

				var x = ( face % 3 ) * 2 / 3 - 1;
				var y = face > 2 ? 0 : - 1;
				var coordinates = [
					x, y, 0,
					x + 2 / 3, y, 0,
					x + 2 / 3, y + 1, 0,
					x, y, 0,
					x + 2 / 3, y + 1, 0,
					x, y + 1, 0
				];
				position.set( coordinates, positionSize * vertices * face );
				uv.set( uv1, uvSize * vertices * face );
				var fill = [ face, face, face, face, face, face ];
				faceIndex.set( fill, faceIndexSize * vertices * face );

			}
			var planes = new BufferGeometry();
			planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
			planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
			planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
			_lodPlanes.push( planes );

			if ( lod > LOD_MIN ) {

				lod --;

			}

		}
		return { _lodPlanes: _lodPlanes, _sizeLods: _sizeLods, _sigmas: _sigmas };

	}

	function _allocateTargets( equirectangular ) {

		var params = {
			magFilter: NearestFilter,
			minFilter: NearestFilter,
			generateMipmaps: false,
			type: equirectangular ? equirectangular.type : UnsignedByteType,
			format: equirectangular ? equirectangular.format : RGBEFormat,
			encoding: equirectangular ? equirectangular.encoding : RGBEEncoding,
			depthBuffer: false,
			stencilBuffer: false
		};
		var cubeUVRenderTarget = _createRenderTarget( params );
		cubeUVRenderTarget.depthBuffer = equirectangular ? false : true;
		_pingPongRenderTarget = _createRenderTarget( params );
		return cubeUVRenderTarget;

	}

	function _cleanup( outputTarget ) {

		_pingPongRenderTarget.dispose();
		_renderer.setRenderTarget( _oldTarget );
		outputTarget.scissorTest = false;
		// reset viewport and scissor
		outputTarget.setSize( outputTarget.width, outputTarget.height );

	}

	function _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {

		var fov = 90;
		var aspect = 1;
		var cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
		var upSign = [ 1, 1, 1, 1, - 1, 1 ];
		var forwardSign = [ 1, 1, - 1, - 1, - 1, 1 ];

		var outputEncoding = _renderer.outputEncoding;
		var toneMapping = _renderer.toneMapping;
		var toneMappingExposure = _renderer.toneMappingExposure;
		var clearColor = _renderer.getClearColor();
		var clearAlpha = _renderer.getClearAlpha();

		_renderer.toneMapping = LinearToneMapping;
		_renderer.toneMappingExposure = 1.0;
		_renderer.outputEncoding = LinearEncoding;
		scene.scale.z *= - 1;

		var background = scene.background;
		if ( background && background.isColor ) {

			background.convertSRGBToLinear();
			// Convert linear to RGBE
			var maxComponent = Math.max( background.r, background.g, background.b );
			var fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 );
			background = background.multiplyScalar( Math.pow( 2.0, - fExp ) );
			var alpha = ( fExp + 128.0 ) / 255.0;
			_renderer.setClearColor( background, alpha );
			scene.background = null;

		}

		for ( var i = 0; i < 6; i ++ ) {

			var col = i % 3;
			if ( col == 0 ) {

				cubeCamera.up.set( 0, upSign[ i ], 0 );
				cubeCamera.lookAt( forwardSign[ i ], 0, 0 );

			} else if ( col == 1 ) {

				cubeCamera.up.set( 0, 0, upSign[ i ] );
				cubeCamera.lookAt( 0, forwardSign[ i ], 0 );

			} else {

				cubeCamera.up.set( 0, upSign[ i ], 0 );
				cubeCamera.lookAt( 0, 0, forwardSign[ i ] );

			}
			_setViewport( cubeUVRenderTarget,
				col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
			_renderer.setRenderTarget( cubeUVRenderTarget );
			_renderer.render( scene, cubeCamera );

		}

		_renderer.toneMapping = toneMapping;
		_renderer.toneMappingExposure = toneMappingExposure;
		_renderer.outputEncoding = outputEncoding;
		_renderer.setClearColor( clearColor, clearAlpha );
		scene.scale.z *= - 1;

	}

	function _textureToCubeUV( texture, cubeUVRenderTarget ) {

		var scene = new Scene();
		if ( texture.isCubeTexture ) {

			if ( _cubemapShader == null ) {

				_cubemapShader = _getCubemapShader();

			}

		} else {

			if ( _equirectShader == null ) {

				_equirectShader = _getEquirectShader();

			}

		}
		var material = texture.isCubeTexture ? _cubemapShader : _equirectShader;
		scene.add( new Mesh( _lodPlanes[ 0 ], material ) );
		var uniforms = material.uniforms;

		uniforms[ 'envMap' ].value = texture;
		if ( ! texture.isCubeTexture ) {

			uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );

		}
		uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
		uniforms[ 'outputEncoding' ].value = ENCODINGS[ texture.encoding ];

		_setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
		_renderer.setRenderTarget( cubeUVRenderTarget );
		_renderer.render( scene, _flatCamera );

	}

	function _compileMaterial( material ) {

		var tmpScene = new Scene();
		tmpScene.add( new Mesh( _lodPlanes[ 0 ], material ) );
		_renderer.compile( tmpScene, _flatCamera );

	}

	function _createRenderTarget( params ) {

		var cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
		cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
		cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
		cubeUVRenderTarget.scissorTest = true;
		return cubeUVRenderTarget;

	}

	function _setViewport( target, x, y, width, height ) {

		target.viewport.set( x, y, width, height );
		target.scissor.set( x, y, width, height );

	}

	function _applyPMREM( cubeUVRenderTarget ) {

		var autoClear = _renderer.autoClear;
		_renderer.autoClear = false;

		for ( var i = 1; i < TOTAL_LODS; i ++ ) {

			var sigma = Math.sqrt(
				_sigmas[ i ] * _sigmas[ i ] -
			_sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
			var poleAxis =
			_axisDirections[ ( i - 1 ) % _axisDirections.length ];
			_blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );

		}

		_renderer.autoClear = autoClear;

	}

	/**
	 * This is a two-pass Gaussian blur for a cubemap. Normally this is done
	 * vertically and horizontally, but this breaks down on a cube. Here we apply
	 * the blur latitudinally (around the poles), and then longitudinally (towards
	 * the poles) to approximate the orthogonally-separable blur. It is least
	 * accurate at the poles, but still does a decent job.
	 */
	function _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {

		_halfBlur(
			cubeUVRenderTarget,
			_pingPongRenderTarget,
			lodIn,
			lodOut,
			sigma,
			'latitudinal',
			poleAxis );

		_halfBlur(
			_pingPongRenderTarget,
			cubeUVRenderTarget,
			lodOut,
			lodOut,
			sigma,
			'longitudinal',
			poleAxis );

	}

	function _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {

		if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {

			console.error(
				'blur direction must be either latitudinal or longitudinal!' );

		}

		// Number of standard deviations at which to cut off the discrete approximation.
		var STANDARD_DEVIATIONS = 3;

		var blurScene = new Scene();
		blurScene.add( new Mesh( _lodPlanes[ lodOut ], _blurMaterial ) );
		var blurUniforms = _blurMaterial.uniforms;

		var pixels = _sizeLods[ lodIn ] - 1;
		var radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
		var sigmaPixels = sigmaRadians / radiansPerPixel;
		var samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;

		if ( samples > MAX_SAMPLES ) {

			console.warn( ("sigmaRadians, " + sigmaRadians + ", is too large and will clip, as it requested " + samples + " samples when the maximum is set to " + MAX_SAMPLES) );

		}

		var weights = [];
		var sum = 0;

		for ( var i = 0; i < MAX_SAMPLES; ++ i ) {

			var x = i / sigmaPixels;
			var weight = Math.exp( - x * x / 2 );
			weights.push( weight );

			if ( i == 0 ) {

				sum += weight;

			} else if ( i < samples ) {

				sum += 2 * weight;

			}

		}

		for ( var i = 0; i < weights.length; i ++ ) {

			weights[ i ] = weights[ i ] / sum;

		}

		blurUniforms[ 'envMap' ].value = targetIn.texture;
		blurUniforms[ 'samples' ].value = samples;
		blurUniforms[ 'weights' ].value = weights;
		blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
		if ( poleAxis ) {

			blurUniforms[ 'poleAxis' ].value = poleAxis;

		}
		blurUniforms[ 'dTheta' ].value = radiansPerPixel;
		blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
		blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
		blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];

		var outputSize = _sizeLods[ lodOut ];
		var x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
		var y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) +
		2 * outputSize *
			( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );

		_setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
		_renderer.setRenderTarget( targetOut );
		_renderer.render( blurScene, _flatCamera );

	}

	function _getBlurShader( maxSamples ) {

		var weights = new Float32Array( maxSamples );
		var poleAxis = new Vector3( 0, 1, 0 );
		var shaderMaterial = new RawShaderMaterial( {

			defines: { 'n': maxSamples },

			uniforms: {
				'envMap': { value: null },
				'samples': { value: 1 },
				'weights': { value: weights },
				'latitudinal': { value: false },
				'dTheta': { value: 0 },
				'mipInt': { value: 0 },
				'poleAxis': { value: poleAxis },
				'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
				'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
			},

			vertexShader: _getCommonVertexShader(),

			fragmentShader: ("\nprecision mediump float;\nprecision mediump int;\nvarying vec3 vOutputDirection;\nuniform sampler2D envMap;\nuniform int samples;\nuniform float weights[n];\nuniform bool latitudinal;\nuniform float dTheta;\nuniform float mipInt;\nuniform vec3 poleAxis;\n\n" + (_getEncodings()) + "\n\n#define ENVMAP_TYPE_CUBE_UV\n#include <cube_uv_reflection_fragment>\n\nvoid main() {\n\tgl_FragColor = vec4(0.0);\n\tfor (int i = 0; i < n; i++) {\n\t\tif (i >= samples)\n\t\t\tbreak;\n\t\tfor (int dir = -1; dir < 2; dir += 2) {\n\t\t\tif (i == 0 && dir == 1)\n\t\t\t\tcontinue;\n\t\t\tvec3 axis = latitudinal ? poleAxis : cross(poleAxis, vOutputDirection);\n\t\t\tif (all(equal(axis, vec3(0.0))))\n\t\t\t\taxis = cross(vec3(0.0, 1.0, 0.0), vOutputDirection);\n\t\t\taxis = normalize(axis);\n\t\t\tfloat theta = dTheta * float(dir * i);\n\t\t\tfloat cosTheta = cos(theta);\n\t\t\t// Rodrigues' axis-angle rotation\n\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross(axis, vOutputDirection) * sin(theta)\n\t\t\t\t\t+ axis * dot(axis, vOutputDirection) * (1.0 - cosTheta);\n\t\t\tgl_FragColor.rgb +=\n\t\t\t\t\tweights[i] * bilinearCubeUV(envMap, sampleDirection, mipInt);\n\t\t}\n\t}\n\tgl_FragColor = linearToOutputTexel(gl_FragColor);\n}\n\t\t"),

			blending: NoBlending,
			depthTest: false,
			depthWrite: false

		} );

		shaderMaterial.type = 'SphericalGaussianBlur';

		return shaderMaterial;

	}

	function _getEquirectShader() {

		var texelSize = new Vector2( 1, 1 );
		var shaderMaterial = new RawShaderMaterial( {

			uniforms: {
				'envMap': { value: null },
				'texelSize': { value: texelSize },
				'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
				'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
			},

			vertexShader: _getCommonVertexShader(),

			fragmentShader: ("\nprecision mediump float;\nprecision mediump int;\nvarying vec3 vOutputDirection;\nuniform sampler2D envMap;\nuniform vec2 texelSize;\n\n" + (_getEncodings()) + "\n\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n\nvoid main() {\n\tgl_FragColor = vec4(0.0);\n\tvec3 outputDirection = normalize(vOutputDirection);\n\tvec2 uv;\n\tuv.y = asin(clamp(outputDirection.y, -1.0, 1.0)) * RECIPROCAL_PI + 0.5;\n\tuv.x = atan(outputDirection.z, outputDirection.x) * RECIPROCAL_PI2 + 0.5;\n\tvec2 f = fract(uv / texelSize - 0.5);\n\tuv -= f * texelSize;\n\tvec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n\tuv.x += texelSize.x;\n\tvec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n\tuv.y += texelSize.y;\n\tvec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n\tuv.x -= texelSize.x;\n\tvec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n\tvec3 tm = mix(tl, tr, f.x);\n\tvec3 bm = mix(bl, br, f.x);\n\tgl_FragColor.rgb = mix(tm, bm, f.y);\n\tgl_FragColor = linearToOutputTexel(gl_FragColor);\n}\n\t\t"),

			blending: NoBlending,
			depthTest: false,
			depthWrite: false

		} );

		shaderMaterial.type = 'EquirectangularToCubeUV';

		return shaderMaterial;

	}

	function _getCubemapShader() {

		var shaderMaterial = new RawShaderMaterial( {

			uniforms: {
				'envMap': { value: null },
				'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
				'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
			},

			vertexShader: _getCommonVertexShader(),

			fragmentShader: ("\nprecision mediump float;\nprecision mediump int;\nvarying vec3 vOutputDirection;\nuniform samplerCube envMap;\n\n" + (_getEncodings()) + "\n\nvoid main() {\n\tgl_FragColor = vec4(0.0);\n\tgl_FragColor.rgb = envMapTexelToLinear(textureCube(envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ))).rgb;\n\tgl_FragColor = linearToOutputTexel(gl_FragColor);\n}\n\t\t"),

			blending: NoBlending,
			depthTest: false,
			depthWrite: false

		} );

		shaderMaterial.type = 'CubemapToCubeUV';

		return shaderMaterial;

	}

	function _getCommonVertexShader() {

		return "\nprecision mediump float;\nprecision mediump int;\nattribute vec3 position;\nattribute vec2 uv;\nattribute float faceIndex;\nvarying vec3 vOutputDirection;\nvec3 getDirection(vec2 uv, float face) {\n\tuv = 2.0 * uv - 1.0;\n\tvec3 direction = vec3(uv, 1.0);\n\tif (face == 0.0) {\n\t\tdirection = direction.zyx;\n\t\tdirection.z *= -1.0;\n\t} else if (face == 1.0) {\n\t\tdirection = direction.xzy;\n\t\tdirection.z *= -1.0;\n\t} else if (face == 3.0) {\n\t\tdirection = direction.zyx;\n\t\tdirection.x *= -1.0;\n\t} else if (face == 4.0) {\n\t\tdirection = direction.xzy;\n\t\tdirection.y *= -1.0;\n\t} else if (face == 5.0) {\n\t\tdirection.xz *= -1.0;\n\t}\n\treturn direction;\n}\nvoid main() {\n\tvOutputDirection = getDirection(uv, faceIndex);\n\tgl_Position = vec4( position, 1.0 );\n}\n\t";

	}

	function _getEncodings() {

		return "\nuniform int inputEncoding;\nuniform int outputEncoding;\n\n#include <encodings_pars_fragment>\n\nvec4 inputTexelToLinear(vec4 value){\n\tif(inputEncoding == 0){\n\t\treturn value;\n\t}else if(inputEncoding == 1){\n\t\treturn sRGBToLinear(value);\n\t}else if(inputEncoding == 2){\n\t\treturn RGBEToLinear(value);\n\t}else if(inputEncoding == 3){\n\t\treturn RGBMToLinear(value, 7.0);\n\t}else if(inputEncoding == 4){\n\t\treturn RGBMToLinear(value, 16.0);\n\t}else if(inputEncoding == 5){\n\t\treturn RGBDToLinear(value, 256.0);\n\t}else{\n\t\treturn GammaToLinear(value, 2.2);\n\t}\n}\n\nvec4 linearToOutputTexel(vec4 value){\n\tif(outputEncoding == 0){\n\t\treturn value;\n\t}else if(outputEncoding == 1){\n\t\treturn LinearTosRGB(value);\n\t}else if(outputEncoding == 2){\n\t\treturn LinearToRGBE(value);\n\t}else if(outputEncoding == 3){\n\t\treturn LinearToRGBM(value, 7.0);\n\t}else if(outputEncoding == 4){\n\t\treturn LinearToRGBM(value, 16.0);\n\t}else if(outputEncoding == 5){\n\t\treturn LinearToRGBD(value, 256.0);\n\t}else{\n\t\treturn LinearToGamma(value, 2.2);\n\t}\n}\n\nvec4 envMapTexelToLinear(vec4 color) {\n\treturn inputTexelToLinear(color);\n}\n\t";

	}

	/**
	 * @author mrdoob / http://mrdoob.com/
	 */

	function Face4( a, b, c, d, normal, color, materialIndex ) {

		console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
		return new Face3( a, b, c, normal, color, materialIndex );

	}

	var LineStrip = 0;

	var LinePieces = 1;

	function MeshFaceMaterial( materials ) {

		console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
		return materials;

	}

	function MultiMaterial( materials ) {

		if ( materials === undefined ) { materials = []; }

		console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
		materials.isMultiMaterial = true;
		materials.materials = materials;
		materials.clone = function () {

			return materials.slice();

		};
		return materials;

	}

	function PointCloud( geometry, material ) {

		console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
		return new Points( geometry, material );

	}

	function Particle( material ) {

		console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
		return new Sprite( material );

	}

	function ParticleSystem( geometry, material ) {

		console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
		return new Points( geometry, material );

	}

	function PointCloudMaterial( parameters ) {

		console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
		return new PointsMaterial( parameters );

	}

	function ParticleBasicMaterial( parameters ) {

		console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
		return new PointsMaterial( parameters );

	}

	function ParticleSystemMaterial( parameters ) {

		console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
		return new PointsMaterial( parameters );

	}

	function Vertex( x, y, z ) {

		console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
		return new Vector3( x, y, z );

	}

	//

	function DynamicBufferAttribute( array, itemSize ) {

		console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
		return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );

	}

	function Int8Attribute( array, itemSize ) {

		console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
		return new Int8BufferAttribute( array, itemSize );

	}

	function Uint8Attribute( array, itemSize ) {

		console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
		return new Uint8BufferAttribute( array, itemSize );

	}

	function Uint8ClampedAttribute( array, itemSize ) {

		console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
		return new Uint8ClampedBufferAttribute( array, itemSize );

	}

	function Int16Attribute( array, itemSize ) {

		console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
		return new Int16BufferAttribute( array, itemSize );

	}

	function Uint16Attribute( array, itemSize ) {

		console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
		return new Uint16BufferAttribute( array, itemSize );

	}

	function Int32Attribute( array, itemSize ) {

		console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
		return new Int32BufferAttribute( array, itemSize );

	}

	function Uint32Attribute( array, itemSize ) {

		console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
		return new Uint32BufferAttribute( array, itemSize );

	}

	function Float32Attribute( array, itemSize ) {

		console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
		return new Float32BufferAttribute( array, itemSize );

	}

	function Float64Attribute( array, itemSize ) {

		console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
		return new Float64BufferAttribute( array, itemSize );

	}

	//

	Curve.create = function ( construct, getPoint ) {

		console.log( 'THREE.Curve.create() has been deprecated' );

		construct.prototype = Object.create( Curve.prototype );
		construct.prototype.constructor = construct;
		construct.prototype.getPoint = getPoint;

		return construct;

	};

	//

	Object.assign( CurvePath.prototype, {

		createPointsGeometry: function ( divisions ) {

			console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );

			// generate geometry from path points (for Line or Points objects)

			var pts = this.getPoints( divisions );
			return this.createGeometry( pts );

		},

		createSpacedPointsGeometry: function ( divisions ) {

			console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );

			// generate geometry from equidistant sampling along the path

			var pts = this.getSpacedPoints( divisions );
			return this.createGeometry( pts );

		},

		createGeometry: function ( points ) {

			console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );

			var geometry = new Geometry();

			for ( var i = 0, l = points.length; i < l; i ++ ) {

				var point = points[ i ];
				geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );

			}

			return geometry;

		}

	} );

	//

	Object.assign( Path.prototype, {

		fromPoints: function ( points ) {

			console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
			return this.setFromPoints( points );

		}

	} );

	//

	function ClosedSplineCurve3( points ) {

		console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );

		CatmullRomCurve3.call( this, points );
		this.type = 'catmullrom';
		this.closed = true;

	}

	ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );

	//

	function SplineCurve3( points ) {

		console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );

		CatmullRomCurve3.call( this, points );
		this.type = 'catmullrom';

	}

	SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );

	//

	function Spline( points ) {

		console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );

		CatmullRomCurve3.call( this, points );
		this.type = 'catmullrom';

	}

	Spline.prototype = Object.create( CatmullRomCurve3.prototype );

	Object.assign( Spline.prototype, {

		initFromArray: function ( /* a */ ) {

			console.error( 'THREE.Spline: .initFromArray() has been removed.' );

		},
		getControlPointsArray: function ( /* optionalTarget */ ) {

			console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );

		},
		reparametrizeByArcLength: function ( /* samplingCoef */ ) {

			console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );

		}

	} );

	//

	function AxisHelper( size ) {

		console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
		return new AxesHelper( size );

	}

	function BoundingBoxHelper( object, color ) {

		console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
		return new BoxHelper( object, color );

	}

	function EdgesHelper( object, hex ) {

		console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
		return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );

	}

	GridHelper.prototype.setColors = function () {

		console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );

	};

	SkeletonHelper.prototype.update = function () {

		console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );

	};

	function WireframeHelper( object, hex ) {

		console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
		return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );

	}

	//

	Object.assign( Loader.prototype, {

		extractUrlBase: function ( url ) {

			console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
			return LoaderUtils.extractUrlBase( url );

		}

	} );

	Loader.Handlers = {

		add: function ( /* regex, loader */ ) {

			console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );

		},

		get: function ( /* file */ ) {

			console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );

		}

	};

	function XHRLoader( manager ) {

		console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
		return new FileLoader( manager );

	}

	function BinaryTextureLoader( manager ) {

		console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
		return new DataTextureLoader( manager );

	}

	Object.assign( ObjectLoader.prototype, {

		setTexturePath: function ( value ) {

			console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
			return this.setResourcePath( value );

		}

	} );

	//

	Object.assign( Box2.prototype, {

		center: function ( optionalTarget ) {

			console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
			return this.getCenter( optionalTarget );

		},
		empty: function () {

			console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
			return this.isEmpty();

		},
		isIntersectionBox: function ( box ) {

			console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
			return this.intersectsBox( box );

		},
		size: function ( optionalTarget ) {

			console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
			return this.getSize( optionalTarget );

		}
	} );

	Object.assign( Box3.prototype, {

		center: function ( optionalTarget ) {

			console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
			return this.getCenter( optionalTarget );

		},
		empty: function () {

			console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
			return this.isEmpty();

		},
		isIntersectionBox: function ( box ) {

			console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
			return this.intersectsBox( box );

		},
		isIntersectionSphere: function ( sphere ) {

			console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
			return this.intersectsSphere( sphere );

		},
		size: function ( optionalTarget ) {

			console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
			return this.getSize( optionalTarget );

		}
	} );

	Frustum.prototype.setFromMatrix = function ( m ) {

		console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
		return this.setFromProjectionMatrix( m );

	};

	Line3.prototype.center = function ( optionalTarget ) {

		console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
		return this.getCenter( optionalTarget );

	};

	Object.assign( MathUtils, {

		random16: function () {

			console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
			return Math.random();

		},

		nearestPowerOfTwo: function ( value ) {

			console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
			return MathUtils.floorPowerOfTwo( value );

		},

		nextPowerOfTwo: function ( value ) {

			console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
			return MathUtils.ceilPowerOfTwo( value );

		}

	} );

	Object.assign( Matrix3.prototype, {

		flattenToArrayOffset: function ( array, offset ) {

			console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
			return this.toArray( array, offset );

		},
		multiplyVector3: function ( vector ) {

			console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
			return vector.applyMatrix3( this );

		},
		multiplyVector3Array: function ( /* a */ ) {

			console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );

		},
		applyToBufferAttribute: function ( attribute ) {

			console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
			return attribute.applyMatrix3( this );

		},
		applyToVector3Array: function ( /* array, offset, length */ ) {

			console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );

		}

	} );

	Object.assign( Matrix4.prototype, {

		extractPosition: function ( m ) {

			console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
			return this.copyPosition( m );

		},
		flattenToArrayOffset: function ( array, offset ) {

			console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
			return this.toArray( array, offset );

		},
		getPosition: function () {

			console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
			return new Vector3().setFromMatrixColumn( this, 3 );

		},
		setRotationFromQuaternion: function ( q ) {

			console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
			return this.makeRotationFromQuaternion( q );

		},
		multiplyToArray: function () {

			console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );

		},
		multiplyVector3: function ( vector ) {

			console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
			return vector.applyMatrix4( this );

		},
		multiplyVector4: function ( vector ) {

			console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
			return vector.applyMatrix4( this );

		},
		multiplyVector3Array: function ( /* a */ ) {

			console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );

		},
		rotateAxis: function ( v ) {

			console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
			v.transformDirection( this );

		},
		crossVector: function ( vector ) {

			console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
			return vector.applyMatrix4( this );

		},
		translate: function () {

			console.error( 'THREE.Matrix4: .translate() has been removed.' );

		},
		rotateX: function () {

			console.error( 'THREE.Matrix4: .rotateX() has been removed.' );

		},
		rotateY: function () {

			console.error( 'THREE.Matrix4: .rotateY() has been removed.' );

		},
		rotateZ: function () {

			console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );

		},
		rotateByAxis: function () {

			console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );

		},
		applyToBufferAttribute: function ( attribute ) {

			console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
			return attribute.applyMatrix4( this );

		},
		applyToVector3Array: function ( /* array, offset, length */ ) {

			console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );

		},
		makeFrustum: function ( left, right, bottom, top, near, far ) {

			console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
			return this.makePerspective( left, right, top, bottom, near, far );

		}

	} );

	Plane.prototype.isIntersectionLine = function ( line ) {

		console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
		return this.intersectsLine( line );

	};

	Quaternion.prototype.multiplyVector3 = function ( vector ) {

		console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
		return vector.applyQuaternion( this );

	};

	Object.assign( Ray.prototype, {

		isIntersectionBox: function ( box ) {

			console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
			return this.intersectsBox( box );

		},
		isIntersectionPlane: function ( plane ) {

			console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
			return this.intersectsPlane( plane );

		},
		isIntersectionSphere: function ( sphere ) {

			console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
			return this.intersectsSphere( sphere );

		}

	} );

	Object.assign( Triangle.prototype, {

		area: function () {

			console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
			return this.getArea();

		},
		barycoordFromPoint: function ( point, target ) {

			console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
			return this.getBarycoord( point, target );

		},
		midpoint: function ( target ) {

			console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
			return this.getMidpoint( target );

		},
		normal: function ( target ) {

			console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
			return this.getNormal( target );

		},
		plane: function ( target ) {

			console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
			return this.getPlane( target );

		}

	} );

	Object.assign( Triangle, {

		barycoordFromPoint: function ( point, a, b, c, target ) {

			console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
			return Triangle.getBarycoord( point, a, b, c, target );

		},
		normal: function ( a, b, c, target ) {

			console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
			return Triangle.getNormal( a, b, c, target );

		}

	} );

	Object.assign( Shape.prototype, {

		extractAllPoints: function ( divisions ) {

			console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
			return this.extractPoints( divisions );

		},
		extrude: function ( options ) {

			console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
			return new ExtrudeGeometry( this, options );

		},
		makeGeometry: function ( options ) {

			console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
			return new ShapeGeometry( this, options );

		}

	} );

	Object.assign( Vector2.prototype, {

		fromAttribute: function ( attribute, index, offset ) {

			console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
			return this.fromBufferAttribute( attribute, index, offset );

		},
		distanceToManhattan: function ( v ) {

			console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
			return this.manhattanDistanceTo( v );

		},
		lengthManhattan: function () {

			console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
			return this.manhattanLength();

		}

	} );

	Object.assign( Vector3.prototype, {

		setEulerFromRotationMatrix: function () {

			console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );

		},
		setEulerFromQuaternion: function () {

			console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );

		},
		getPositionFromMatrix: function ( m ) {

			console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
			return this.setFromMatrixPosition( m );

		},
		getScaleFromMatrix: function ( m ) {

			console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
			return this.setFromMatrixScale( m );

		},
		getColumnFromMatrix: function ( index, matrix ) {

			console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
			return this.setFromMatrixColumn( matrix, index );

		},
		applyProjection: function ( m ) {

			console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
			return this.applyMatrix4( m );

		},
		fromAttribute: function ( attribute, index, offset ) {

			console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
			return this.fromBufferAttribute( attribute, index, offset );

		},
		distanceToManhattan: function ( v ) {

			console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
			return this.manhattanDistanceTo( v );

		},
		lengthManhattan: function () {

			console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
			return this.manhattanLength();

		}

	} );

	Object.assign( Vector4.prototype, {

		fromAttribute: function ( attribute, index, offset ) {

			console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
			return this.fromBufferAttribute( attribute, index, offset );

		},
		lengthManhattan: function () {

			console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
			return this.manhattanLength();

		}

	} );

	//

	Object.assign( Geometry.prototype, {

		computeTangents: function () {

			console.error( 'THREE.Geometry: .computeTangents() has been removed.' );

		},
		computeLineDistances: function () {

			console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' );

		},
		applyMatrix: function ( matrix ) {

			console.warn( 'THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().' );
			return this.applyMatrix4( matrix );

		}

	} );

	Object.assign( Object3D.prototype, {

		getChildByName: function ( name ) {

			console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
			return this.getObjectByName( name );

		},
		renderDepth: function () {

			console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );

		},
		translate: function ( distance, axis ) {

			console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
			return this.translateOnAxis( axis, distance );

		},
		getWorldRotation: function () {

			console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );

		},
		applyMatrix: function ( matrix ) {

			console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
			return this.applyMatrix4( matrix );

		}

	} );

	Object.defineProperties( Object3D.prototype, {

		eulerOrder: {
			get: function () {

				console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
				return this.rotation.order;

			},
			set: function ( value ) {

				console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
				this.rotation.order = value;

			}
		},
		useQuaternion: {
			get: function () {

				console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );

			},
			set: function () {

				console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );

			}
		}

	} );

	Object.assign( Mesh.prototype, {

		setDrawMode: function () {

			console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );

		},

	} );

	Object.defineProperties( Mesh.prototype, {

		drawMode: {
			get: function () {

				console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
				return TrianglesDrawMode;

			},
			set: function () {

				console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );

			}
		}

	} );

	Object.defineProperties( LOD.prototype, {

		objects: {
			get: function () {

				console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
				return this.levels;

			}
		}

	} );

	Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {

		get: function () {

			console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );

		},
		set: function () {

			console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );

		}

	} );

	SkinnedMesh.prototype.initBones = function () {

		console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );

	};

	Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {

		get: function () {

			console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
			return this.arcLengthDivisions;

		},
		set: function ( value ) {

			console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
			this.arcLengthDivisions = value;

		}

	} );

	//

	PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {

		console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
				"Use .setFocalLength and .filmGauge for a photographic setup." );

		if ( filmGauge !== undefined ) { this.filmGauge = filmGauge; }
		this.setFocalLength( focalLength );

	};

	//

	Object.defineProperties( Light.prototype, {
		onlyShadow: {
			set: function () {

				console.warn( 'THREE.Light: .onlyShadow has been removed.' );

			}
		},
		shadowCameraFov: {
			set: function ( value ) {

				console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
				this.shadow.camera.fov = value;

			}
		},
		shadowCameraLeft: {
			set: function ( value ) {

				console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
				this.shadow.camera.left = value;

			}
		},
		shadowCameraRight: {
			set: function ( value ) {

				console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
				this.shadow.camera.right = value;

			}
		},
		shadowCameraTop: {
			set: function ( value ) {

				console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
				this.shadow.camera.top = value;

			}
		},
		shadowCameraBottom: {
			set: function ( value ) {

				console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
				this.shadow.camera.bottom = value;

			}
		},
		shadowCameraNear: {
			set: function ( value ) {

				console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
				this.shadow.camera.near = value;

			}
		},
		shadowCameraFar: {
			set: function ( value ) {

				console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
				this.shadow.camera.far = value;

			}
		},
		shadowCameraVisible: {
			set: function () {

				console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );

			}
		},
		shadowBias: {
			set: function ( value ) {

				console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
				this.shadow.bias = value;

			}
		},
		shadowDarkness: {
			set: function () {

				console.warn( 'THREE.Light: .shadowDarkness has been removed.' );

			}
		},
		shadowMapWidth: {
			set: function ( value ) {

				console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
				this.shadow.mapSize.width = value;

			}
		},
		shadowMapHeight: {
			set: function ( value ) {

				console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
				this.shadow.mapSize.height = value;

			}
		}
	} );

	//

	Object.defineProperties( BufferAttribute.prototype, {

		length: {
			get: function () {

				console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
				return this.array.length;

			}
		},
		dynamic: {
			get: function () {

				console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
				return this.usage === DynamicDrawUsage;

			},
			set: function ( /* value */ ) {

				console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
				this.setUsage( DynamicDrawUsage );

			}
		}

	} );

	Object.assign( BufferAttribute.prototype, {
		setDynamic: function ( value ) {

			console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
			this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
			return this;

		},
		copyIndicesArray: function ( /* indices */ ) {

			console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );

		},
		setArray: function ( /* array */ ) {

			console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );

		}
	} );

	Object.assign( BufferGeometry.prototype, {

		addIndex: function ( index ) {

			console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
			this.setIndex( index );

		},
		addAttribute: function ( name, attribute ) {

			console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );

			if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {

				console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );

				return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );

			}

			if ( name === 'index' ) {

				console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
				this.setIndex( attribute );

				return this;

			}

			return this.setAttribute( name, attribute );

		},
		addDrawCall: function ( start, count, indexOffset ) {

			if ( indexOffset !== undefined ) {

				console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );

			}
			console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
			this.addGroup( start, count );

		},
		clearDrawCalls: function () {

			console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
			this.clearGroups();

		},
		computeTangents: function () {

			console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );

		},
		computeOffsets: function () {

			console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );

		},
		removeAttribute: function ( name ) {

			console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );

			return this.deleteAttribute( name );

		},
		applyMatrix: function ( matrix ) {

			console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
			return this.applyMatrix4( matrix );

		}

	} );

	Object.defineProperties( BufferGeometry.prototype, {

		drawcalls: {
			get: function () {

				console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
				return this.groups;

			}
		},
		offsets: {
			get: function () {

				console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
				return this.groups;

			}
		}

	} );

	Object.defineProperties( InterleavedBuffer.prototype, {

		dynamic: {
			get: function () {

				console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
				return this.usage === DynamicDrawUsage;

			},
			set: function ( value ) {

				console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
				this.setUsage( value );

			}
		}

	} );

	Object.assign( InterleavedBuffer.prototype, {
		setDynamic: function ( value ) {

			console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
			this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
			return this;

		},
		setArray: function ( /* array */ ) {

			console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );

		}
	} );

	//

	Object.assign( ExtrudeBufferGeometry.prototype, {

		getArrays: function () {

			console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' );

		},

		addShapeList: function () {

			console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' );

		},

		addShape: function () {

			console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' );

		}

	} );

	//

	Object.defineProperties( Uniform.prototype, {

		dynamic: {
			set: function () {

				console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );

			}
		},
		onUpdate: {
			value: function () {

				console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
				return this;

			}
		}

	} );

	//

	Object.defineProperties( Material.prototype, {

		wrapAround: {
			get: function () {

				console.warn( 'THREE.Material: .wrapAround has been removed.' );

			},
			set: function () {

				console.warn( 'THREE.Material: .wrapAround has been removed.' );

			}
		},

		overdraw: {
			get: function () {

				console.warn( 'THREE.Material: .overdraw has been removed.' );

			},
			set: function () {

				console.warn( 'THREE.Material: .overdraw has been removed.' );

			}
		},

		wrapRGB: {
			get: function () {

				console.warn( 'THREE.Material: .wrapRGB has been removed.' );
				return new Color();

			}
		},

		shading: {
			get: function () {

				console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );

			},
			set: function ( value ) {

				console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
				this.flatShading = ( value === FlatShading );

			}
		},

		stencilMask: {
			get: function () {

				console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
				return this.stencilFuncMask;

			},
			set: function ( value ) {

				console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
				this.stencilFuncMask = value;

			}
		}

	} );

	Object.defineProperties( MeshPhongMaterial.prototype, {

		metal: {
			get: function () {

				console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
				return false;

			},
			set: function () {

				console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );

			}
		}

	} );

	Object.defineProperties( ShaderMaterial.prototype, {

		derivatives: {
			get: function () {

				console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
				return this.extensions.derivatives;

			},
			set: function ( value ) {

				console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
				this.extensions.derivatives = value;

			}
		}

	} );

	//

	Object.assign( WebGLRenderer.prototype, {

		clearTarget: function ( renderTarget, color, depth, stencil ) {

			console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
			this.setRenderTarget( renderTarget );
			this.clear( color, depth, stencil );

		},
		animate: function ( callback ) {

			console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
			this.setAnimationLoop( callback );

		},
		getCurrentRenderTarget: function () {

			console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
			return this.getRenderTarget();

		},
		getMaxAnisotropy: function () {

			console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
			return this.capabilities.getMaxAnisotropy();

		},
		getPrecision: function () {

			console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
			return this.capabilities.precision;

		},
		resetGLState: function () {

			console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
			return this.state.reset();

		},
		supportsFloatTextures: function () {

			console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
			return this.extensions.get( 'OES_texture_float' );

		},
		supportsHalfFloatTextures: function () {

			console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
			return this.extensions.get( 'OES_texture_half_float' );

		},
		supportsStandardDerivatives: function () {

			console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
			return this.extensions.get( 'OES_standard_derivatives' );

		},
		supportsCompressedTextureS3TC: function () {

			console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
			return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );

		},
		supportsCompressedTexturePVRTC: function () {

			console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
			return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );

		},
		supportsBlendMinMax: function () {

			console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
			return this.extensions.get( 'EXT_blend_minmax' );

		},
		supportsVertexTextures: function () {

			console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
			return this.capabilities.vertexTextures;

		},
		supportsInstancedArrays: function () {

			console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
			return this.extensions.get( 'ANGLE_instanced_arrays' );

		},
		enableScissorTest: function ( boolean ) {

			console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
			this.setScissorTest( boolean );

		},
		initMaterial: function () {

			console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );

		},
		addPrePlugin: function () {

			console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );

		},
		addPostPlugin: function () {

			console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );

		},
		updateShadowMap: function () {

			console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );

		},
		setFaceCulling: function () {

			console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );

		},
		allocTextureUnit: function () {

			console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );

		},
		setTexture: function () {

			console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );

		},
		setTexture2D: function () {

			console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );

		},
		setTextureCube: function () {

			console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );

		},
		getActiveMipMapLevel: function () {

			console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
			return this.getActiveMipmapLevel();

		}

	} );

	Object.defineProperties( WebGLRenderer.prototype, {

		shadowMapEnabled: {
			get: function () {

				return this.shadowMap.enabled;

			},
			set: function ( value ) {

				console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
				this.shadowMap.enabled = value;

			}
		},
		shadowMapType: {
			get: function () {

				return this.shadowMap.type;

			},
			set: function ( value ) {

				console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
				this.shadowMap.type = value;

			}
		},
		shadowMapCullFace: {
			get: function () {

				console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
				return undefined;

			},
			set: function ( /* value */ ) {

				console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );

			}
		},
		context: {
			get: function () {

				console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
				return this.getContext();

			}
		},
		vr: {
			get: function () {

				console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
				return this.xr;

			}
		},
		gammaInput: {
			get: function () {

				console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
				return false;

			},
			set: function () {

				console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );

			}
		},
		gammaOutput: {
			get: function () {

				console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
				return false;

			},
			set: function ( value ) {

				console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
				this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;

			}
		}

	} );

	Object.defineProperties( WebGLShadowMap.prototype, {

		cullFace: {
			get: function () {

				console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
				return undefined;

			},
			set: function ( /* cullFace */ ) {

				console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );

			}
		},
		renderReverseSided: {
			get: function () {

				console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
				return undefined;

			},
			set: function () {

				console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );

			}
		},
		renderSingleSided: {
			get: function () {

				console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
				return undefined;

			},
			set: function () {

				console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );

			}
		}

	} );

	function WebGLRenderTargetCube( width, height, options ) {

		console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
		return new WebGLCubeRenderTarget( width, options );

	}

	//

	Object.defineProperties( WebGLRenderTarget.prototype, {

		wrapS: {
			get: function () {

				console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
				return this.texture.wrapS;

			},
			set: function ( value ) {

				console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
				this.texture.wrapS = value;

			}
		},
		wrapT: {
			get: function () {

				console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
				return this.texture.wrapT;

			},
			set: function ( value ) {

				console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
				this.texture.wrapT = value;

			}
		},
		magFilter: {
			get: function () {

				console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
				return this.texture.magFilter;

			},
			set: function ( value ) {

				console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
				this.texture.magFilter = value;

			}
		},
		minFilter: {
			get: function () {

				console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
				return this.texture.minFilter;

			},
			set: function ( value ) {

				console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
				this.texture.minFilter = value;

			}
		},
		anisotropy: {
			get: function () {

				console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
				return this.texture.anisotropy;

			},
			set: function ( value ) {

				console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
				this.texture.anisotropy = value;

			}
		},
		offset: {
			get: function () {

				console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
				return this.texture.offset;

			},
			set: function ( value ) {

				console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
				this.texture.offset = value;

			}
		},
		repeat: {
			get: function () {

				console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
				return this.texture.repeat;

			},
			set: function ( value ) {

				console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
				this.texture.repeat = value;

			}
		},
		format: {
			get: function () {

				console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
				return this.texture.format;

			},
			set: function ( value ) {

				console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
				this.texture.format = value;

			}
		},
		type: {
			get: function () {

				console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
				return this.texture.type;

			},
			set: function ( value ) {

				console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
				this.texture.type = value;

			}
		},
		generateMipmaps: {
			get: function () {

				console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
				return this.texture.generateMipmaps;

			},
			set: function ( value ) {

				console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
				this.texture.generateMipmaps = value;

			}
		}

	} );

	//

	Object.defineProperties( Audio.prototype, {

		load: {
			value: function ( file ) {

				console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
				var scope = this;
				var audioLoader = new AudioLoader();
				audioLoader.load( file, function ( buffer ) {

					scope.setBuffer( buffer );

				} );
				return this;

			}
		},
		startTime: {
			set: function () {

				console.warn( 'THREE.Audio: .startTime is now .play( delay ).' );

			}
		}

	} );

	AudioAnalyser.prototype.getData = function () {

		console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
		return this.getFrequencyData();

	};

	//

	CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {

		console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
		return this.update( renderer, scene );

	};

	//

	var GeometryUtils = {

		merge: function ( geometry1, geometry2, materialIndexOffset ) {

			console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
			var matrix;

			if ( geometry2.isMesh ) {

				geometry2.matrixAutoUpdate && geometry2.updateMatrix();

				matrix = geometry2.matrix;
				geometry2 = geometry2.geometry;

			}

			geometry1.merge( geometry2, matrix, materialIndexOffset );

		},

		center: function ( geometry ) {

			console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
			return geometry.center();

		}

	};

	ImageUtils.crossOrigin = undefined;

	ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {

		console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );

		var loader = new TextureLoader();
		loader.setCrossOrigin( this.crossOrigin );

		var texture = loader.load( url, onLoad, undefined, onError );

		if ( mapping ) { texture.mapping = mapping; }

		return texture;

	};

	ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {

		console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );

		var loader = new CubeTextureLoader();
		loader.setCrossOrigin( this.crossOrigin );

		var texture = loader.load( urls, onLoad, undefined, onError );

		if ( mapping ) { texture.mapping = mapping; }

		return texture;

	};

	ImageUtils.loadCompressedTexture = function () {

		console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );

	};

	ImageUtils.loadCompressedTextureCube = function () {

		console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );

	};

	//

	function CanvasRenderer() {

		console.error( 'THREE.CanvasRenderer has been removed' );

	}

	//

	function JSONLoader() {

		console.error( 'THREE.JSONLoader has been removed.' );

	}

	//

	var SceneUtils = {

		createMultiMaterialObject: function ( /* geometry, materials */ ) {

			console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );

		},

		detach: function ( /* child, parent, scene */ ) {

			console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );

		},

		attach: function ( /* child, scene, parent */ ) {

			console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' );

		}

	};

	//

	function LensFlare() {

		console.error( 'THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js' );

	}

	if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {

		/* eslint-disable no-undef */
		__THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
			revision: REVISION,
		} } ) );
		/* eslint-enable no-undef */

	}

	exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
	exports.AddEquation = AddEquation;
	exports.AddOperation = AddOperation;
	exports.AdditiveBlending = AdditiveBlending;
	exports.AlphaFormat = AlphaFormat;
	exports.AlwaysDepth = AlwaysDepth;
	exports.AlwaysStencilFunc = AlwaysStencilFunc;
	exports.AmbientLight = AmbientLight;
	exports.AmbientLightProbe = AmbientLightProbe;
	exports.AnimationClip = AnimationClip;
	exports.AnimationLoader = AnimationLoader;
	exports.AnimationMixer = AnimationMixer;
	exports.AnimationObjectGroup = AnimationObjectGroup;
	exports.AnimationUtils = AnimationUtils;
	exports.ArcCurve = ArcCurve;
	exports.ArrayCamera = ArrayCamera;
	exports.ArrowHelper = ArrowHelper;
	exports.Audio = Audio;
	exports.AudioAnalyser = AudioAnalyser;
	exports.AudioContext = AudioContext;
	exports.AudioListener = AudioListener;
	exports.AudioLoader = AudioLoader;
	exports.AxesHelper = AxesHelper;
	exports.AxisHelper = AxisHelper;
	exports.BackSide = BackSide;
	exports.BasicDepthPacking = BasicDepthPacking;
	exports.BasicShadowMap = BasicShadowMap;
	exports.BinaryTextureLoader = BinaryTextureLoader;
	exports.Bone = Bone;
	exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
	exports.BoundingBoxHelper = BoundingBoxHelper;
	exports.Box2 = Box2;
	exports.Box3 = Box3;
	exports.Box3Helper = Box3Helper;
	exports.BoxBufferGeometry = BoxBufferGeometry;
	exports.BoxGeometry = BoxGeometry;
	exports.BoxHelper = BoxHelper;
	exports.BufferAttribute = BufferAttribute;
	exports.BufferGeometry = BufferGeometry;
	exports.BufferGeometryLoader = BufferGeometryLoader;
	exports.ByteType = ByteType;
	exports.Cache = Cache;
	exports.Camera = Camera;
	exports.CameraHelper = CameraHelper;
	exports.CanvasRenderer = CanvasRenderer;
	exports.CanvasTexture = CanvasTexture;
	exports.CatmullRomCurve3 = CatmullRomCurve3;
	exports.CineonToneMapping = CineonToneMapping;
	exports.CircleBufferGeometry = CircleBufferGeometry;
	exports.CircleGeometry = CircleGeometry;
	exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
	exports.Clock = Clock;
	exports.ClosedSplineCurve3 = ClosedSplineCurve3;
	exports.Color = Color;
	exports.ColorKeyframeTrack = ColorKeyframeTrack;
	exports.CompressedTexture = CompressedTexture;
	exports.CompressedTextureLoader = CompressedTextureLoader;
	exports.ConeBufferGeometry = ConeBufferGeometry;
	exports.ConeGeometry = ConeGeometry;
	exports.CubeCamera = CubeCamera;
	exports.CubeGeometry = BoxGeometry;
	exports.CubeReflectionMapping = CubeReflectionMapping;
	exports.CubeRefractionMapping = CubeRefractionMapping;
	exports.CubeTexture = CubeTexture;
	exports.CubeTextureLoader = CubeTextureLoader;
	exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
	exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
	exports.CubicBezierCurve = CubicBezierCurve;
	exports.CubicBezierCurve3 = CubicBezierCurve3;
	exports.CubicInterpolant = CubicInterpolant;
	exports.CullFaceBack = CullFaceBack;
	exports.CullFaceFront = CullFaceFront;
	exports.CullFaceFrontBack = CullFaceFrontBack;
	exports.CullFaceNone = CullFaceNone;
	exports.Curve = Curve;
	exports.CurvePath = CurvePath;
	exports.CustomBlending = CustomBlending;
	exports.CylinderBufferGeometry = CylinderBufferGeometry;
	exports.CylinderGeometry = CylinderGeometry;
	exports.Cylindrical = Cylindrical;
	exports.DataTexture = DataTexture;
	exports.DataTexture2DArray = DataTexture2DArray;
	exports.DataTexture3D = DataTexture3D;
	exports.DataTextureLoader = DataTextureLoader;
	exports.DecrementStencilOp = DecrementStencilOp;
	exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
	exports.DefaultLoadingManager = DefaultLoadingManager;
	exports.DepthFormat = DepthFormat;
	exports.DepthStencilFormat = DepthStencilFormat;
	exports.DepthTexture = DepthTexture;
	exports.DirectionalLight = DirectionalLight;
	exports.DirectionalLightHelper = DirectionalLightHelper;
	exports.DirectionalLightShadow = DirectionalLightShadow;
	exports.DiscreteInterpolant = DiscreteInterpolant;
	exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
	exports.DodecahedronGeometry = DodecahedronGeometry;
	exports.DoubleSide = DoubleSide;
	exports.DstAlphaFactor = DstAlphaFactor;
	exports.DstColorFactor = DstColorFactor;
	exports.DynamicBufferAttribute = DynamicBufferAttribute;
	exports.DynamicCopyUsage = DynamicCopyUsage;
	exports.DynamicDrawUsage = DynamicDrawUsage;
	exports.DynamicReadUsage = DynamicReadUsage;
	exports.EdgesGeometry = EdgesGeometry;
	exports.EdgesHelper = EdgesHelper;
	exports.EllipseCurve = EllipseCurve;
	exports.EqualDepth = EqualDepth;
	exports.EqualStencilFunc = EqualStencilFunc;
	exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
	exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
	exports.Euler = Euler;
	exports.EventDispatcher = EventDispatcher;
	exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
	exports.ExtrudeGeometry = ExtrudeGeometry;
	exports.Face3 = Face3;
	exports.Face4 = Face4;
	exports.FaceColors = FaceColors;
	exports.FileLoader = FileLoader;
	exports.FlatShading = FlatShading;
	exports.Float32Attribute = Float32Attribute;
	exports.Float32BufferAttribute = Float32BufferAttribute;
	exports.Float64Attribute = Float64Attribute;
	exports.Float64BufferAttribute = Float64BufferAttribute;
	exports.FloatType = FloatType;
	exports.Fog = Fog;
	exports.FogExp2 = FogExp2;
	exports.Font = Font;
	exports.FontLoader = FontLoader;
	exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
	exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
	exports.FrontSide = FrontSide;
	exports.Frustum = Frustum;
	exports.GammaEncoding = GammaEncoding;
	exports.Geometry = Geometry;
	exports.GeometryUtils = GeometryUtils;
	exports.GreaterDepth = GreaterDepth;
	exports.GreaterEqualDepth = GreaterEqualDepth;
	exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
	exports.GreaterStencilFunc = GreaterStencilFunc;
	exports.GridHelper = GridHelper;
	exports.Group = Group;
	exports.HalfFloatType = HalfFloatType;
	exports.HemisphereLight = HemisphereLight;
	exports.HemisphereLightHelper = HemisphereLightHelper;
	exports.HemisphereLightProbe = HemisphereLightProbe;
	exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
	exports.IcosahedronGeometry = IcosahedronGeometry;
	exports.ImageBitmapLoader = ImageBitmapLoader;
	exports.ImageLoader = ImageLoader;
	exports.ImageUtils = ImageUtils;
	exports.ImmediateRenderObject = ImmediateRenderObject;
	exports.IncrementStencilOp = IncrementStencilOp;
	exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
	exports.InstancedBufferAttribute = InstancedBufferAttribute;
	exports.InstancedBufferGeometry = InstancedBufferGeometry;
	exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
	exports.InstancedMesh = InstancedMesh;
	exports.Int16Attribute = Int16Attribute;
	exports.Int16BufferAttribute = Int16BufferAttribute;
	exports.Int32Attribute = Int32Attribute;
	exports.Int32BufferAttribute = Int32BufferAttribute;
	exports.Int8Attribute = Int8Attribute;
	exports.Int8BufferAttribute = Int8BufferAttribute;
	exports.IntType = IntType;
	exports.InterleavedBuffer = InterleavedBuffer;
	exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
	exports.Interpolant = Interpolant;
	exports.InterpolateDiscrete = InterpolateDiscrete;
	exports.InterpolateLinear = InterpolateLinear;
	exports.InterpolateSmooth = InterpolateSmooth;
	exports.InvertStencilOp = InvertStencilOp;
	exports.JSONLoader = JSONLoader;
	exports.KeepStencilOp = KeepStencilOp;
	exports.KeyframeTrack = KeyframeTrack;
	exports.LOD = LOD;
	exports.LatheBufferGeometry = LatheBufferGeometry;
	exports.LatheGeometry = LatheGeometry;
	exports.Layers = Layers;
	exports.LensFlare = LensFlare;
	exports.LessDepth = LessDepth;
	exports.LessEqualDepth = LessEqualDepth;
	exports.LessEqualStencilFunc = LessEqualStencilFunc;
	exports.LessStencilFunc = LessStencilFunc;
	exports.Light = Light;
	exports.LightProbe = LightProbe;
	exports.LightShadow = LightShadow;
	exports.Line = Line;
	exports.Line3 = Line3;
	exports.LineBasicMaterial = LineBasicMaterial;
	exports.LineCurve = LineCurve;
	exports.LineCurve3 = LineCurve3;
	exports.LineDashedMaterial = LineDashedMaterial;
	exports.LineLoop = LineLoop;
	exports.LinePieces = LinePieces;
	exports.LineSegments = LineSegments;
	exports.LineStrip = LineStrip;
	exports.LinearEncoding = LinearEncoding;
	exports.LinearFilter = LinearFilter;
	exports.LinearInterpolant = LinearInterpolant;
	exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
	exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
	exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
	exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
	exports.LinearToneMapping = LinearToneMapping;
	exports.Loader = Loader;
	exports.LoaderUtils = LoaderUtils;
	exports.LoadingManager = LoadingManager;
	exports.LogLuvEncoding = LogLuvEncoding;
	exports.LoopOnce = LoopOnce;
	exports.LoopPingPong = LoopPingPong;
	exports.LoopRepeat = LoopRepeat;
	exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
	exports.LuminanceFormat = LuminanceFormat;
	exports.MOUSE = MOUSE;
	exports.Material = Material;
	exports.MaterialLoader = MaterialLoader;
	exports.Math = MathUtils;
	exports.MathUtils = MathUtils;
	exports.Matrix3 = Matrix3;
	exports.Matrix4 = Matrix4;
	exports.MaxEquation = MaxEquation;
	exports.Mesh = Mesh;
	exports.MeshBasicMaterial = MeshBasicMaterial;
	exports.MeshDepthMaterial = MeshDepthMaterial;
	exports.MeshDistanceMaterial = MeshDistanceMaterial;
	exports.MeshFaceMaterial = MeshFaceMaterial;
	exports.MeshLambertMaterial = MeshLambertMaterial;
	exports.MeshMatcapMaterial = MeshMatcapMaterial;
	exports.MeshNormalMaterial = MeshNormalMaterial;
	exports.MeshPhongMaterial = MeshPhongMaterial;
	exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
	exports.MeshStandardMaterial = MeshStandardMaterial;
	exports.MeshToonMaterial = MeshToonMaterial;
	exports.MinEquation = MinEquation;
	exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
	exports.MixOperation = MixOperation;
	exports.MultiMaterial = MultiMaterial;
	exports.MultiplyBlending = MultiplyBlending;
	exports.MultiplyOperation = MultiplyOperation;
	exports.NearestFilter = NearestFilter;
	exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
	exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
	exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
	exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
	exports.NeverDepth = NeverDepth;
	exports.NeverStencilFunc = NeverStencilFunc;
	exports.NoBlending = NoBlending;
	exports.NoColors = NoColors;
	exports.NoToneMapping = NoToneMapping;
	exports.NormalBlending = NormalBlending;
	exports.NotEqualDepth = NotEqualDepth;
	exports.NotEqualStencilFunc = NotEqualStencilFunc;
	exports.NumberKeyframeTrack = NumberKeyframeTrack;
	exports.Object3D = Object3D;
	exports.ObjectLoader = ObjectLoader;
	exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
	exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
	exports.OctahedronGeometry = OctahedronGeometry;
	exports.OneFactor = OneFactor;
	exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
	exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
	exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
	exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
	exports.OrthographicCamera = OrthographicCamera;
	exports.PCFShadowMap = PCFShadowMap;
	exports.PCFSoftShadowMap = PCFSoftShadowMap;
	exports.PMREMGenerator = PMREMGenerator;
	exports.ParametricBufferGeometry = ParametricBufferGeometry;
	exports.ParametricGeometry = ParametricGeometry;
	exports.Particle = Particle;
	exports.ParticleBasicMaterial = ParticleBasicMaterial;
	exports.ParticleSystem = ParticleSystem;
	exports.ParticleSystemMaterial = ParticleSystemMaterial;
	exports.Path = Path;
	exports.PerspectiveCamera = PerspectiveCamera;
	exports.Plane = Plane;
	exports.PlaneBufferGeometry = PlaneBufferGeometry;
	exports.PlaneGeometry = PlaneGeometry;
	exports.PlaneHelper = PlaneHelper;
	exports.PointCloud = PointCloud;
	exports.PointCloudMaterial = PointCloudMaterial;
	exports.PointLight = PointLight;
	exports.PointLightHelper = PointLightHelper;
	exports.Points = Points;
	exports.PointsMaterial = PointsMaterial;
	exports.PolarGridHelper = PolarGridHelper;
	exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
	exports.PolyhedronGeometry = PolyhedronGeometry;
	exports.PositionalAudio = PositionalAudio;
	exports.PropertyBinding = PropertyBinding;
	exports.PropertyMixer = PropertyMixer;
	exports.QuadraticBezierCurve = QuadraticBezierCurve;
	exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
	exports.Quaternion = Quaternion;
	exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
	exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
	exports.REVISION = REVISION;
	exports.RGBADepthPacking = RGBADepthPacking;
	exports.RGBAFormat = RGBAFormat;
	exports.RGBAIntegerFormat = RGBAIntegerFormat;
	exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
	exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
	exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
	exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
	exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
	exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
	exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
	exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
	exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
	exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
	exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
	exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
	exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
	exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
	exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
	exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
	exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
	exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
	exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
	exports.RGBDEncoding = RGBDEncoding;
	exports.RGBEEncoding = RGBEEncoding;
	exports.RGBEFormat = RGBEFormat;
	exports.RGBFormat = RGBFormat;
	exports.RGBIntegerFormat = RGBIntegerFormat;
	exports.RGBM16Encoding = RGBM16Encoding;
	exports.RGBM7Encoding = RGBM7Encoding;
	exports.RGB_ETC1_Format = RGB_ETC1_Format;
	exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
	exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
	exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
	exports.RGFormat = RGFormat;
	exports.RGIntegerFormat = RGIntegerFormat;
	exports.RawShaderMaterial = RawShaderMaterial;
	exports.Ray = Ray;
	exports.Raycaster = Raycaster;
	exports.RectAreaLight = RectAreaLight;
	exports.RedFormat = RedFormat;
	exports.RedIntegerFormat = RedIntegerFormat;
	exports.ReinhardToneMapping = ReinhardToneMapping;
	exports.RepeatWrapping = RepeatWrapping;
	exports.ReplaceStencilOp = ReplaceStencilOp;
	exports.ReverseSubtractEquation = ReverseSubtractEquation;
	exports.RingBufferGeometry = RingBufferGeometry;
	exports.RingGeometry = RingGeometry;
	exports.Scene = Scene;
	exports.SceneUtils = SceneUtils;
	exports.ShaderChunk = ShaderChunk;
	exports.ShaderLib = ShaderLib;
	exports.ShaderMaterial = ShaderMaterial;
	exports.ShadowMaterial = ShadowMaterial;
	exports.Shape = Shape;
	exports.ShapeBufferGeometry = ShapeBufferGeometry;
	exports.ShapeGeometry = ShapeGeometry;
	exports.ShapePath = ShapePath;
	exports.ShapeUtils = ShapeUtils;
	exports.ShortType = ShortType;
	exports.Skeleton = Skeleton;
	exports.SkeletonHelper = SkeletonHelper;
	exports.SkinnedMesh = SkinnedMesh;
	exports.SmoothShading = SmoothShading;
	exports.Sphere = Sphere;
	exports.SphereBufferGeometry = SphereBufferGeometry;
	exports.SphereGeometry = SphereGeometry;
	exports.Spherical = Spherical;
	exports.SphericalHarmonics3 = SphericalHarmonics3;
	exports.SphericalReflectionMapping = SphericalReflectionMapping;
	exports.Spline = Spline;
	exports.SplineCurve = SplineCurve;
	exports.SplineCurve3 = SplineCurve3;
	exports.SpotLight = SpotLight;
	exports.SpotLightHelper = SpotLightHelper;
	exports.SpotLightShadow = SpotLightShadow;
	exports.Sprite = Sprite;
	exports.SpriteMaterial = SpriteMaterial;
	exports.SrcAlphaFactor = SrcAlphaFactor;
	exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
	exports.SrcColorFactor = SrcColorFactor;
	exports.StaticCopyUsage = StaticCopyUsage;
	exports.StaticDrawUsage = StaticDrawUsage;
	exports.StaticReadUsage = StaticReadUsage;
	exports.StereoCamera = StereoCamera;
	exports.StreamCopyUsage = StreamCopyUsage;
	exports.StreamDrawUsage = StreamDrawUsage;
	exports.StreamReadUsage = StreamReadUsage;
	exports.StringKeyframeTrack = StringKeyframeTrack;
	exports.SubtractEquation = SubtractEquation;
	exports.SubtractiveBlending = SubtractiveBlending;
	exports.TOUCH = TOUCH;
	exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
	exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
	exports.TetrahedronGeometry = TetrahedronGeometry;
	exports.TextBufferGeometry = TextBufferGeometry;
	exports.TextGeometry = TextGeometry;
	exports.Texture = Texture;
	exports.TextureLoader = TextureLoader;
	exports.TorusBufferGeometry = TorusBufferGeometry;
	exports.TorusGeometry = TorusGeometry;
	exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
	exports.TorusKnotGeometry = TorusKnotGeometry;
	exports.Triangle = Triangle;
	exports.TriangleFanDrawMode = TriangleFanDrawMode;
	exports.TriangleStripDrawMode = TriangleStripDrawMode;
	exports.TrianglesDrawMode = TrianglesDrawMode;
	exports.TubeBufferGeometry = TubeBufferGeometry;
	exports.TubeGeometry = TubeGeometry;
	exports.UVMapping = UVMapping;
	exports.Uint16Attribute = Uint16Attribute;
	exports.Uint16BufferAttribute = Uint16BufferAttribute;
	exports.Uint32Attribute = Uint32Attribute;
	exports.Uint32BufferAttribute = Uint32BufferAttribute;
	exports.Uint8Attribute = Uint8Attribute;
	exports.Uint8BufferAttribute = Uint8BufferAttribute;
	exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
	exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
	exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
	exports.Uniform = Uniform;
	exports.UniformsLib = UniformsLib;
	exports.UniformsUtils = UniformsUtils;
	exports.UnsignedByteType = UnsignedByteType;
	exports.UnsignedInt248Type = UnsignedInt248Type;
	exports.UnsignedIntType = UnsignedIntType;
	exports.UnsignedShort4444Type = UnsignedShort4444Type;
	exports.UnsignedShort5551Type = UnsignedShort5551Type;
	exports.UnsignedShort565Type = UnsignedShort565Type;
	exports.UnsignedShortType = UnsignedShortType;
	exports.VSMShadowMap = VSMShadowMap;
	exports.Vector2 = Vector2;
	exports.Vector3 = Vector3;
	exports.Vector4 = Vector4;
	exports.VectorKeyframeTrack = VectorKeyframeTrack;
	exports.Vertex = Vertex;
	exports.VertexColors = VertexColors;
	exports.VideoTexture = VideoTexture;
	exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
	exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
	exports.WebGLRenderTarget = WebGLRenderTarget;
	exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
	exports.WebGLRenderer = WebGLRenderer;
	exports.WebGLUtils = WebGLUtils;
	exports.WireframeGeometry = WireframeGeometry;
	exports.WireframeHelper = WireframeHelper;
	exports.WrapAroundEnding = WrapAroundEnding;
	exports.XHRLoader = XHRLoader;
	exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
	exports.ZeroFactor = ZeroFactor;
	exports.ZeroSlopeEnding = ZeroSlopeEnding;
	exports.ZeroStencilOp = ZeroStencilOp;
	exports.sRGBEncoding = sRGBEncoding;

	Object.defineProperty(exports, '__esModule', { value: true });

})));


/***/ }),
/* 13 */
/***/ (function(module, exports) {

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  try {
    var info = gen[key](arg);
    var value = info.value;
  } catch (error) {
    reject(error);
    return;
  }

  if (info.done) {
    resolve(value);
  } else {
    Promise.resolve(value).then(_next, _throw);
  }
}

function _asyncToGenerator(fn) {
  return function () {
    var self = this,
        args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);

      function _next(value) {
        asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }

      function _throw(err) {
        asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }

      _next(undefined);
    });
  };
}

module.exports = _asyncToGenerator;

/***/ }),
/* 14 */,
/* 15 */
/***/ (function(module, exports, __webpack_require__) {

var arrayWithHoles = __webpack_require__(93);

var iterableToArrayLimit = __webpack_require__(94);

var nonIterableRest = __webpack_require__(95);

function _slicedToArray(arr, i) {
  return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest();
}

module.exports = _slicedToArray;

/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {

var arrayWithoutHoles = __webpack_require__(122);

var iterableToArray = __webpack_require__(123);

var nonIterableSpread = __webpack_require__(124);

function _toConsumableArray(arr) {
  return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread();
}

module.exports = _toConsumableArray;

/***/ }),
/* 17 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _extends; });
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);
}

/***/ }),
/* 18 */
/***/ (function(module, exports) {

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

module.exports = _defineProperty;

/***/ }),
/* 19 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(Hammer) {/* harmony import */ var utils_merge__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3);


var rangePan = function rangePan() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$properties = _ref.properties,
      propertiesProp = _ref$properties === void 0 ? {} : _ref$properties,
      _ref$scale = _ref.scale,
      scale = _ref$scale === void 0 ? 'x' : _ref$scale;

  var defaultProperties = {
    type: 'hammer',
    gestures: [{
      type: 'Pan',
      options: {
        event: 'range',
        direction: Hammer.DIRECTION_HORIZONTAL
      },
      events: {
        rangestart: function rangestart(e) {
          this.chart.component("".concat(scale, "-range")).emit('rangeStart', e);
        },
        rangemove: function rangemove(e) {
          this.chart.component("".concat(scale, "-range")).emit('rangeMove', e);
        },
        rangeend: function rangeend(e) {
          this.chart.component("".concat(scale, "-range")).emit('rangeEnd', e);
        }
      }
    }]
  };

  if (scale === 'y') {
    defaultProperties.gestures[0].options.direction = Hammer.DIRECTION_VERTICAL;
  }

  var properties = Object(utils_merge__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(defaultProperties, propertiesProp);
  return properties;
};

/* harmony default export */ __webpack_exports__["a"] = (rangePan);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(64)))

/***/ }),
/* 20 */,
/* 21 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _interopRequireDefault = __webpack_require__(34);

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _react = _interopRequireDefault(__webpack_require__(0));

var _createSvgIcon = _interopRequireDefault(__webpack_require__(44));

var _default = (0, _createSvgIcon.default)(_react.default.createElement("path", {
  d: "M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"
}), 'Check');

exports.default = _default;

/***/ }),
/* 22 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _defineProperty; });
function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


if (true) {
  module.exports = __webpack_require__(89);
} else {}


/***/ }),
/* 24 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// CONCATENATED MODULE: ./node_modules/@material-ui/styles/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js
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;
}
// CONCATENATED MODULE: ./node_modules/@material-ui/styles/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _objectWithoutProperties; });

function _objectWithoutProperties(source, excluded) {
  if (source == null) return {};
  var target = _objectWithoutPropertiesLoose(source, excluded);
  var key, i;

  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);

    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key = sourceSymbolKeys[i];
      if (excluded.indexOf(key) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
      target[key] = source[key];
    }
  }

  return target;
}

/***/ }),
/* 25 */,
/* 26 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _createMuiTheme__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(76);

var defaultTheme = Object(_createMuiTheme__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])();
/* harmony default export */ __webpack_exports__["a"] = (defaultTheme);

/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {

var rng = __webpack_require__(119);
var bytesToUuid = __webpack_require__(120);

function v4(options, buf, offset) {
  var i = buf && offset || 0;

  if (typeof(options) == 'string') {
    buf = options === 'binary' ? new Array(16) : null;
    options = null;
  }
  options = options || {};

  var rnds = options.random || (options.rng || rng)();

  // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  rnds[6] = (rnds[6] & 0x0f) | 0x40;
  rnds[8] = (rnds[8] & 0x3f) | 0x80;

  // Copy bytes to buffer, if provided
  if (buf) {
    for (var ii = 0; ii < 16; ++ii) {
      buf[i + ii] = rnds[ii];
    }
  }

  return buf || bytesToUuid(rnds);
}

module.exports = v4;


/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _interopRequireDefault = __webpack_require__(34);

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _react = _interopRequireDefault(__webpack_require__(0));

var _createSvgIcon = _interopRequireDefault(__webpack_require__(44));

var _default = (0, _createSvgIcon.default)(_react.default.createElement("path", {
  d: "M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"
}), 'Search');

exports.default = _default;

/***/ }),
/* 29 */,
/* 30 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* globals
	Atomics,
	SharedArrayBuffer,
*/

var undefined;

var $TypeError = TypeError;

var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
	try {
		$gOPD({}, '');
	} catch (e) {
		$gOPD = null; // this is IE 8, which has a broken gOPD
	}
}

var throwTypeError = function () { throw new $TypeError(); };
var ThrowTypeError = $gOPD
	? (function () {
		try {
			// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
			arguments.callee; // IE 8 does not throw here
			return throwTypeError;
		} catch (calleeThrows) {
			try {
				// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
				return $gOPD(arguments, 'callee').get;
			} catch (gOPDthrows) {
				return throwTypeError;
			}
		}
	}())
	: throwTypeError;

var hasSymbols = __webpack_require__(42)();

var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto

var generator; // = function * () {};
var generatorFunction = generator ? getProto(generator) : undefined;
var asyncFn; // async function() {};
var asyncFunction = asyncFn ? asyncFn.constructor : undefined;
var asyncGen; // async function * () {};
var asyncGenFunction = asyncGen ? getProto(asyncGen) : undefined;
var asyncGenIterator = asyncGen ? asyncGen() : undefined;

var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);

var INTRINSICS = {
	'%Array%': Array,
	'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
	'%ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer.prototype,
	'%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,
	'%ArrayPrototype%': Array.prototype,
	'%ArrayProto_entries%': Array.prototype.entries,
	'%ArrayProto_forEach%': Array.prototype.forEach,
	'%ArrayProto_keys%': Array.prototype.keys,
	'%ArrayProto_values%': Array.prototype.values,
	'%AsyncFromSyncIteratorPrototype%': undefined,
	'%AsyncFunction%': asyncFunction,
	'%AsyncFunctionPrototype%': asyncFunction ? asyncFunction.prototype : undefined,
	'%AsyncGenerator%': asyncGen ? getProto(asyncGenIterator) : undefined,
	'%AsyncGeneratorFunction%': asyncGenFunction,
	'%AsyncGeneratorPrototype%': asyncGenFunction ? asyncGenFunction.prototype : undefined,
	'%AsyncIteratorPrototype%': asyncGenIterator && hasSymbols && Symbol.asyncIterator ? asyncGenIterator[Symbol.asyncIterator]() : undefined,
	'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
	'%Boolean%': Boolean,
	'%BooleanPrototype%': Boolean.prototype,
	'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
	'%DataViewPrototype%': typeof DataView === 'undefined' ? undefined : DataView.prototype,
	'%Date%': Date,
	'%DatePrototype%': Date.prototype,
	'%decodeURI%': decodeURI,
	'%decodeURIComponent%': decodeURIComponent,
	'%encodeURI%': encodeURI,
	'%encodeURIComponent%': encodeURIComponent,
	'%Error%': Error,
	'%ErrorPrototype%': Error.prototype,
	'%eval%': eval, // eslint-disable-line no-eval
	'%EvalError%': EvalError,
	'%EvalErrorPrototype%': EvalError.prototype,
	'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
	'%Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined : Float32Array.prototype,
	'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
	'%Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined : Float64Array.prototype,
	'%Function%': Function,
	'%FunctionPrototype%': Function.prototype,
	'%Generator%': generator ? getProto(generator()) : undefined,
	'%GeneratorFunction%': generatorFunction,
	'%GeneratorPrototype%': generatorFunction ? generatorFunction.prototype : undefined,
	'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
	'%Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined : Int8Array.prototype,
	'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
	'%Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined : Int8Array.prototype,
	'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
	'%Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined : Int32Array.prototype,
	'%isFinite%': isFinite,
	'%isNaN%': isNaN,
	'%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,
	'%JSON%': typeof JSON === 'object' ? JSON : undefined,
	'%JSONParse%': typeof JSON === 'object' ? JSON.parse : undefined,
	'%Map%': typeof Map === 'undefined' ? undefined : Map,
	'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),
	'%MapPrototype%': typeof Map === 'undefined' ? undefined : Map.prototype,
	'%Math%': Math,
	'%Number%': Number,
	'%NumberPrototype%': Number.prototype,
	'%Object%': Object,
	'%ObjectPrototype%': Object.prototype,
	'%ObjProto_toString%': Object.prototype.toString,
	'%ObjProto_valueOf%': Object.prototype.valueOf,
	'%parseFloat%': parseFloat,
	'%parseInt%': parseInt,
	'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
	'%PromisePrototype%': typeof Promise === 'undefined' ? undefined : Promise.prototype,
	'%PromiseProto_then%': typeof Promise === 'undefined' ? undefined : Promise.prototype.then,
	'%Promise_all%': typeof Promise === 'undefined' ? undefined : Promise.all,
	'%Promise_reject%': typeof Promise === 'undefined' ? undefined : Promise.reject,
	'%Promise_resolve%': typeof Promise === 'undefined' ? undefined : Promise.resolve,
	'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
	'%RangeError%': RangeError,
	'%RangeErrorPrototype%': RangeError.prototype,
	'%ReferenceError%': ReferenceError,
	'%ReferenceErrorPrototype%': ReferenceError.prototype,
	'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
	'%RegExp%': RegExp,
	'%RegExpPrototype%': RegExp.prototype,
	'%Set%': typeof Set === 'undefined' ? undefined : Set,
	'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),
	'%SetPrototype%': typeof Set === 'undefined' ? undefined : Set.prototype,
	'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
	'%SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer.prototype,
	'%String%': String,
	'%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,
	'%StringPrototype%': String.prototype,
	'%Symbol%': hasSymbols ? Symbol : undefined,
	'%SymbolPrototype%': hasSymbols ? Symbol.prototype : undefined,
	'%SyntaxError%': SyntaxError,
	'%SyntaxErrorPrototype%': SyntaxError.prototype,
	'%ThrowTypeError%': ThrowTypeError,
	'%TypedArray%': TypedArray,
	'%TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined,
	'%TypeError%': $TypeError,
	'%TypeErrorPrototype%': $TypeError.prototype,
	'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
	'%Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array.prototype,
	'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
	'%Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray.prototype,
	'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
	'%Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array.prototype,
	'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
	'%Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array.prototype,
	'%URIError%': URIError,
	'%URIErrorPrototype%': URIError.prototype,
	'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
	'%WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined : WeakMap.prototype,
	'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet,
	'%WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined : WeakSet.prototype
};

var bind = __webpack_require__(40);
var $replace = bind.call(Function.call, String.prototype.replace);

/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
	var result = [];
	$replace(string, rePropName, function (match, number, quote, subString) {
		result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : (number || match);
	});
	return result;
};
/* end adaptation */

var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
	if (!(name in INTRINSICS)) {
		throw new SyntaxError('intrinsic ' + name + ' does not exist!');
	}

	// istanbul ignore if // hopefully this is impossible to test :-)
	if (typeof INTRINSICS[name] === 'undefined' && !allowMissing) {
		throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
	}

	return INTRINSICS[name];
};

module.exports = function GetIntrinsic(name, allowMissing) {
	if (typeof name !== 'string' || name.length === 0) {
		throw new TypeError('intrinsic name must be a non-empty string');
	}
	if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
		throw new TypeError('"allowMissing" argument must be a boolean');
	}

	var parts = stringToPath(name);

	var value = getBaseIntrinsic('%' + (parts.length > 0 ? parts[0] : '') + '%', allowMissing);
	for (var i = 1; i < parts.length; i += 1) {
		if (value != null) {
			if ($gOPD && (i + 1) >= parts.length) {
				var desc = $gOPD(value, parts[i]);
				if (!allowMissing && !(parts[i] in value)) {
					throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
				}
				value = desc ? (desc.get || desc.value) : value[parts[i]];
			} else {
				value = value[parts[i]];
			}
		}
	}
	return value;
};


/***/ }),
/* 31 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export easing */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return duration; });
/* harmony import */ var _babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4);

// Follow https://material.google.com/motion/duration-easing.html#duration-easing-natural-easing-curves
// to learn the context in which each easing should be used.
var easing = {
  // This is the most common easing curve.
  easeInOut: 'cubic-bezier(0.4, 0, 0.2, 1)',
  // Objects enter the screen at full velocity from off-screen and
  // slowly decelerate to a resting point.
  easeOut: 'cubic-bezier(0.0, 0, 0.2, 1)',
  // Objects leave the screen at full velocity. They do not decelerate when off-screen.
  easeIn: 'cubic-bezier(0.4, 0, 1, 1)',
  // The sharp curve is used by objects that may return to the screen at any time.
  sharp: 'cubic-bezier(0.4, 0, 0.6, 1)'
}; // Follow https://material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations
// to learn when use what timing

var duration = {
  shortest: 150,
  shorter: 200,
  short: 250,
  // most basic recommended timing
  standard: 300,
  // this is to be used in complex animations
  complex: 375,
  // recommended when something is entering screen
  enteringScreen: 225,
  // recommended when something is leaving screen
  leavingScreen: 195
};

function formatMs(milliseconds) {
  return "".concat(Math.round(milliseconds), "ms");
}
/**
 * @param {string|Array} props
 * @param {object} param
 * @param {string} param.prop
 * @param {number} param.duration
 * @param {string} param.easing
 * @param {number} param.delay
 */


/* harmony default export */ __webpack_exports__["a"] = ({
  easing: easing,
  duration: duration,
  create: function create() {
    var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['all'];
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    var _options$duration = options.duration,
        durationOption = _options$duration === void 0 ? duration.standard : _options$duration,
        _options$easing = options.easing,
        easingOption = _options$easing === void 0 ? easing.easeInOut : _options$easing,
        _options$delay = options.delay,
        delay = _options$delay === void 0 ? 0 : _options$delay,
        other = Object(_babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(options, ["duration", "easing", "delay"]);

    if (false) { var isNumber, isString; }

    return (Array.isArray(props) ? props : [props]).map(function (animatedProp) {
      return "".concat(animatedProp, " ").concat(typeof durationOption === 'string' ? durationOption : formatMs(durationOption), " ").concat(easingOption, " ").concat(typeof delay === 'string' ? delay : formatMs(delay));
    }).join(',');
  },
  getAutoHeightDuration: function getAutoHeightDuration(height) {
    if (!height) {
      return 0;
    }

    var constant = height / 36; // https://www.wolframalpha.com/input/?i=(4+%2B+15+*+(x+%2F+36+)+**+0.25+%2B+(x+%2F+36)+%2F+5)+*+10

    return Math.round((4 + 15 * Math.pow(constant, 0.25) + constant / 5) * 10);
  }
});

/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {

/* Mapbox GL JS is licensed under the 3-Clause BSD License. Full text of license: https://github.com/mapbox/mapbox-gl-js/blob/v1.10.1/LICENSE.txt */
(function (global, factory) {
 true ? module.exports = factory() :
undefined;
}(this, (function () { 'use strict';

/* eslint-disable */

var shared, worker, mapboxgl;
// define gets called three times: one for each chunk. we rely on the order
// they're imported to know which is which
function define(_, chunk) {
if (!shared) {
    shared = chunk;
} else if (!worker) {
    worker = chunk;
} else {
    var workerBundleString = 'var sharedChunk = {}; (' + shared + ')(sharedChunk); (' + worker + ')(sharedChunk);'

    var sharedChunk = {};
    shared(sharedChunk);
    mapboxgl = chunk(sharedChunk);
    mapboxgl.workerUrl = window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }));
}
}


define(["exports"],(function(t){"use strict";function e(t,e){return t(e={exports:{}},e.exports),e.exports}var r=n;function n(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=n,this.p2x=r,this.p2y=n;}n.prototype.sampleCurveX=function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},n.prototype.sampleCurveY=function(t){return ((this.ay*t+this.by)*t+this.cy)*t},n.prototype.sampleCurveDerivativeX=function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},n.prototype.solveCurveX=function(t,e){var r,n,i,a,o;for(void 0===e&&(e=1e-6),i=t,o=0;o<8;o++){if(a=this.sampleCurveX(i)-t,Math.abs(a)<e)return i;var s=this.sampleCurveDerivativeX(i);if(Math.abs(s)<1e-6)break;i-=a/s;}if((i=t)<(r=0))return r;if(i>(n=1))return n;for(;r<n;){if(a=this.sampleCurveX(i),Math.abs(a-t)<e)return i;t>a?r=i:n=i,i=.5*(n-r)+r;}return i},n.prototype.solve=function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))};var i=a;function a(t,e){this.x=t,this.y=e;}function o(t,e,n,i){var a=new r(t,e,n,i);return function(t){return a.solve(t)}}a.prototype={clone:function(){return new a(this.x,this.y)},add:function(t){return this.clone()._add(t)},sub:function(t){return this.clone()._sub(t)},multByPoint:function(t){return this.clone()._multByPoint(t)},divByPoint:function(t){return this.clone()._divByPoint(t)},mult:function(t){return this.clone()._mult(t)},div:function(t){return this.clone()._div(t)},rotate:function(t){return this.clone()._rotate(t)},rotateAround:function(t,e){return this.clone()._rotateAround(t,e)},matMult:function(t){return this.clone()._matMult(t)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(t){return this.x===t.x&&this.y===t.y},dist:function(t){return Math.sqrt(this.distSqr(t))},distSqr:function(t){var e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith:function(t){return this.angleWithSep(t.x,t.y)},angleWithSep:function(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult:function(t){var e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add:function(t){return this.x+=t.x,this.y+=t.y,this},_sub:function(t){return this.x-=t.x,this.y-=t.y,this},_mult:function(t){return this.x*=t,this.y*=t,this},_div:function(t){return this.x/=t,this.y/=t,this},_multByPoint:function(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint:function(t){return this.x/=t.x,this.y/=t.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var t=this.y;return this.y=this.x,this.x=-t,this},_rotate:function(t){var e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround:function(t,e){var r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},a.convert=function(t){return t instanceof a?t:Array.isArray(t)?new a(t[0],t[1]):t};var s=o(.25,.1,.25,1);function u(t,e,r){return Math.min(r,Math.max(e,t))}function l(t,e,r){var n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function p(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];for(var n=0,i=e;n<i.length;n+=1){var a=i[n];for(var o in a)t[o]=a[o];}return t}var c=1;function h(){return c++}function f(){return function t(e){return e?(e^16*Math.random()>>e/4).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,t)}()}function y(t){return !!t&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t)}function d(t,e){t.forEach((function(t){e[t]&&(e[t]=e[t].bind(e));}));}function m(t,e){return -1!==t.indexOf(e,t.length-e.length)}function v(t,e,r){var n={};for(var i in t)n[i]=e.call(r||this,t[i],i,t);return n}function g(t,e,r){var n={};for(var i in t)e.call(r||this,t[i],i,t)&&(n[i]=t[i]);return n}function x(t){return Array.isArray(t)?t.map(x):"object"==typeof t&&t?v(t,x):t}var b={};function w(t){b[t]||("undefined"!=typeof console&&console.warn(t),b[t]=!0);}function _(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function A(t){for(var e=0,r=0,n=t.length,i=n-1,a=void 0,o=void 0;r<n;i=r++)e+=((o=t[i]).x-(a=t[r]).x)*(a.y+o.y);return e}function S(){return "undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope}function k(t){var e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(function(t,r,n,i){var a=n||i;return e[r]=!a||a.toLowerCase(),""})),e["max-age"]){var r=parseInt(e["max-age"],10);isNaN(r)?delete e["max-age"]:e["max-age"]=r;}return e}var I=null;function z(t){if(null==I){var e=t.navigator?t.navigator.userAgent:null;I=!!t.safari||!(!e||!(/\b(iPad|iPhone|iPod)\b/.test(e)||e.match("Safari")&&!e.match("Chrome")));}return I}function C(t){try{var e=self[t];return e.setItem("_mapbox_test_",1),e.removeItem("_mapbox_test_"),!0}catch(t){return !1}}var M,E,T,P,B=self.performance&&self.performance.now?self.performance.now.bind(self.performance):Date.now.bind(Date),V=self.requestAnimationFrame||self.mozRequestAnimationFrame||self.webkitRequestAnimationFrame||self.msRequestAnimationFrame,F=self.cancelAnimationFrame||self.mozCancelAnimationFrame||self.webkitCancelAnimationFrame||self.msCancelAnimationFrame,D={now:B,frame:function(t){var e=V(t);return {cancel:function(){return F(e)}}},getImageData:function(t,e){void 0===e&&(e=0);var r=self.document.createElement("canvas"),n=r.getContext("2d");if(!n)throw new Error("failed to create canvas 2d context");return r.width=t.width,r.height=t.height,n.drawImage(t,0,0,t.width,t.height),n.getImageData(-e,-e,t.width+2*e,t.height+2*e)},resolveURL:function(t){return M||(M=self.document.createElement("a")),M.href=t,M.href},hardwareConcurrency:self.navigator.hardwareConcurrency||4,get devicePixelRatio(){return self.devicePixelRatio},get prefersReducedMotion(){return !!self.matchMedia&&(null==E&&(E=self.matchMedia("(prefers-reduced-motion: reduce)")),E.matches)}},L={API_URL:"https://api.mapbox.com",get EVENTS_URL(){return this.API_URL?0===this.API_URL.indexOf("https://api.mapbox.cn")?"https://events.mapbox.cn/events/v2":0===this.API_URL.indexOf("https://api.mapbox.com")?"https://events.mapbox.com/events/v2":null:null},FEEDBACK_URL:"https://apps.mapbox.com/feedback",REQUIRE_ACCESS_TOKEN:!0,ACCESS_TOKEN:null,MAX_PARALLEL_IMAGE_REQUESTS:16},R={supported:!1,testSupport:function(t){!O&&P&&(U?j(t):T=t);}},O=!1,U=!1;function j(t){var e=t.createTexture();t.bindTexture(t.TEXTURE_2D,e);try{if(t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,P),t.isContextLost())return;R.supported=!0;}catch(t){}t.deleteTexture(e),O=!0;}self.document&&((P=self.document.createElement("img")).onload=function(){T&&j(T),T=null,U=!0;},P.onerror=function(){O=!0,T=null;},P.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");var q="01",N=function(t,e){this._transformRequestFn=t,this._customAccessToken=e,this._createSkuToken();};function K(t){return 0===t.indexOf("mapbox:")}N.prototype._createSkuToken=function(){var t=function(){for(var t="",e=0;e<10;e++)t+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(62*Math.random())];return {token:["1",q,t].join(""),tokenExpiresAt:Date.now()+432e5}}();this._skuToken=t.token,this._skuTokenExpiresAt=t.tokenExpiresAt;},N.prototype._isSkuTokenExpired=function(){return Date.now()>this._skuTokenExpiresAt},N.prototype.transformRequest=function(t,e){return this._transformRequestFn&&this._transformRequestFn(t,e)||{url:t}},N.prototype.normalizeStyleURL=function(t,e){if(!K(t))return t;var r=J(t);return r.path="/styles/v1"+r.path,this._makeAPIURL(r,this._customAccessToken||e)},N.prototype.normalizeGlyphsURL=function(t,e){if(!K(t))return t;var r=J(t);return r.path="/fonts/v1"+r.path,this._makeAPIURL(r,this._customAccessToken||e)},N.prototype.normalizeSourceURL=function(t,e){if(!K(t))return t;var r=J(t);return r.path="/v4/"+r.authority+".json",r.params.push("secure"),this._makeAPIURL(r,this._customAccessToken||e)},N.prototype.normalizeSpriteURL=function(t,e,r,n){var i=J(t);return K(t)?(i.path="/styles/v1"+i.path+"/sprite"+e+r,this._makeAPIURL(i,this._customAccessToken||n)):(i.path+=""+e+r,H(i))},N.prototype.normalizeTileURL=function(t,e){if(this._isSkuTokenExpired()&&this._createSkuToken(),t&&!K(t))return t;var r=J(t);r.path=r.path.replace(/(\.(png|jpg)\d*)(?=$)/,(D.devicePixelRatio>=2||512===e?"@2x":"")+(R.supported?".webp":"$1")),r.path=r.path.replace(/^.+\/v4\//,"/"),r.path="/v4"+r.path;var n=this._customAccessToken||function(t){for(var e=0,r=t;e<r.length;e+=1){var n=r[e].match(/^access_token=(.*)$/);if(n)return n[1]}return null}(r.params)||L.ACCESS_TOKEN;return L.REQUIRE_ACCESS_TOKEN&&n&&this._skuToken&&r.params.push("sku="+this._skuToken),this._makeAPIURL(r,n)},N.prototype.canonicalizeTileURL=function(t,e){var r=J(t);if(!r.path.match(/(^\/v4\/)/)||!r.path.match(/\.[\w]+$/))return t;var n="mapbox://tiles/";n+=r.path.replace("/v4/","");var i=r.params;return e&&(i=i.filter((function(t){return !t.match(/^access_token=/)}))),i.length&&(n+="?"+i.join("&")),n},N.prototype.canonicalizeTileset=function(t,e){for(var r=!!e&&K(e),n=[],i=0,a=t.tiles||[];i<a.length;i+=1){var o=a[i];Z(o)?n.push(this.canonicalizeTileURL(o,r)):n.push(o);}return n},N.prototype._makeAPIURL=function(t,e){var r="See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes",n=J(L.API_URL);if(t.protocol=n.protocol,t.authority=n.authority,"/"!==n.path&&(t.path=""+n.path+t.path),!L.REQUIRE_ACCESS_TOKEN)return H(t);if(!(e=e||L.ACCESS_TOKEN))throw new Error("An API access token is required to use Mapbox GL. "+r);if("s"===e[0])throw new Error("Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). "+r);return t.params=t.params.filter((function(t){return -1===t.indexOf("access_token")})),t.params.push("access_token="+e),H(t)};var G=/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/|\?|$)/i;function Z(t){return G.test(t)}var X=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function J(t){var e=t.match(X);if(!e)throw new Error("Unable to parse URL object");return {protocol:e[1],authority:e[2],path:e[3]||"/",params:e[4]?e[4].split("&"):[]}}function H(t){var e=t.params.length?"?"+t.params.join("&"):"";return t.protocol+"://"+t.authority+t.path+e}function Y(t){if(!t)return null;var e=t.split(".");if(!e||3!==e.length)return null;try{return JSON.parse(decodeURIComponent(self.atob(e[1]).split("").map((function(t){return "%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)})).join("")))}catch(t){return null}}var $=function(t){this.type=t,this.anonId=null,this.eventData={},this.queue=[],this.pendingRequest=null;};$.prototype.getStorageKey=function(t){var e,r=Y(L.ACCESS_TOKEN);return e=r&&r.u?self.btoa(encodeURIComponent(r.u).replace(/%([0-9A-F]{2})/g,(function(t,e){return String.fromCharCode(Number("0x"+e))}))):L.ACCESS_TOKEN||"",t?"mapbox.eventData."+t+":"+e:"mapbox.eventData:"+e},$.prototype.fetchEventData=function(){var t=C("localStorage"),e=this.getStorageKey(),r=this.getStorageKey("uuid");if(t)try{var n=self.localStorage.getItem(e);n&&(this.eventData=JSON.parse(n));var i=self.localStorage.getItem(r);i&&(this.anonId=i);}catch(t){w("Unable to read from LocalStorage");}},$.prototype.saveEventData=function(){var t=C("localStorage"),e=this.getStorageKey(),r=this.getStorageKey("uuid");if(t)try{self.localStorage.setItem(r,this.anonId),Object.keys(this.eventData).length>=1&&self.localStorage.setItem(e,JSON.stringify(this.eventData));}catch(t){w("Unable to write to LocalStorage");}},$.prototype.processRequests=function(t){},$.prototype.postEvent=function(t,e,r,n){var i=this;if(L.EVENTS_URL){var a=J(L.EVENTS_URL);a.params.push("access_token="+(n||L.ACCESS_TOKEN||""));var o={event:this.type,created:new Date(t).toISOString(),sdkIdentifier:"mapbox-gl-js",sdkVersion:"1.10.1",skuId:q,userId:this.anonId},s=e?p(o,e):o,u={url:H(a),headers:{"Content-Type":"text/plain"},body:JSON.stringify([s])};this.pendingRequest=xt(u,(function(t){i.pendingRequest=null,r(t),i.saveEventData(),i.processRequests(n);}));}},$.prototype.queueRequest=function(t,e){this.queue.push(t),this.processRequests(e);};var W,Q,tt=function(t){function e(){t.call(this,"map.load"),this.success={},this.skuToken="";}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.postMapLoadEvent=function(t,e,r,n){this.skuToken=r,(L.EVENTS_URL&&n||L.ACCESS_TOKEN&&Array.isArray(t)&&t.some((function(t){return K(t)||Z(t)})))&&this.queueRequest({id:e,timestamp:Date.now()},n);},e.prototype.processRequests=function(t){var e=this;if(!this.pendingRequest&&0!==this.queue.length){var r=this.queue.shift(),n=r.id,i=r.timestamp;n&&this.success[n]||(this.anonId||this.fetchEventData(),y(this.anonId)||(this.anonId=f()),this.postEvent(i,{skuToken:this.skuToken},(function(t){t||n&&(e.success[n]=!0);}),t));}},e}($),et=new(function(t){function e(e){t.call(this,"appUserTurnstile"),this._customAccessToken=e;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.postTurnstileEvent=function(t,e){L.EVENTS_URL&&L.ACCESS_TOKEN&&Array.isArray(t)&&t.some((function(t){return K(t)||Z(t)}))&&this.queueRequest(Date.now(),e);},e.prototype.processRequests=function(t){var e=this;if(!this.pendingRequest&&0!==this.queue.length){this.anonId&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();var r=Y(L.ACCESS_TOKEN),n=r?r.u:L.ACCESS_TOKEN,i=n!==this.eventData.tokenU;y(this.anonId)||(this.anonId=f(),i=!0);var a=this.queue.shift();if(this.eventData.lastSuccess){var o=new Date(this.eventData.lastSuccess),s=new Date(a),u=(a-this.eventData.lastSuccess)/864e5;i=i||u>=1||u<-1||o.getDate()!==s.getDate();}else i=!0;if(!i)return this.processRequests();this.postEvent(a,{"enabled.telemetry":!1},(function(t){t||(e.eventData.lastSuccess=a,e.eventData.tokenU=n);}),t);}},e}($)),rt=et.postTurnstileEvent.bind(et),nt=new tt,it=nt.postMapLoadEvent.bind(nt),at=500,ot=50;function st(){self.caches&&!W&&(W=self.caches.open("mapbox-tiles"));}function ut(t){var e=t.indexOf("?");return e<0?t:t.slice(0,e)}var lt,pt=1/0;function ct(){return null==lt&&(lt=self.OffscreenCanvas&&new self.OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof self.createImageBitmap),lt}var ht={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Image:"Image"};"function"==typeof Object.freeze&&Object.freeze(ht);var ft=function(t){function e(e,r,n){401===r&&Z(n)&&(e+=": you may have provided an invalid Mapbox access token. See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes"),t.call(this,e),this.status=r,this.url=n,this.name=this.constructor.name,this.message=e;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.toString=function(){return this.name+": "+this.message+" ("+this.status+"): "+this.url},e}(Error),yt=S()?function(){return self.worker&&self.worker.referrer}:function(){return ("blob:"===self.location.protocol?self.parent:self).location.href};var dt,mt,vt=function(t,e){if(!(/^file:/.test(r=t.url)||/^file:/.test(yt())&&!/^\w+:/.test(r))){if(self.fetch&&self.Request&&self.AbortController&&self.Request.prototype.hasOwnProperty("signal"))return function(t,e){var r,n=new self.AbortController,i=new self.Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,referrer:yt(),signal:n.signal}),a=!1,o=!1,s=(r=i.url).indexOf("sku=")>0&&Z(r);"json"===t.type&&i.headers.set("Accept","application/json");var u=function(r,n,a){if(!o){if(r&&"SecurityError"!==r.message&&w(r),n&&a)return l(n);var u=Date.now();self.fetch(i).then((function(r){if(r.ok){var n=s?r.clone():null;return l(r,n,u)}return e(new ft(r.statusText,r.status,t.url))})).catch((function(t){20!==t.code&&e(new Error(t.message));}));}},l=function(r,n,s){("arrayBuffer"===t.type?r.arrayBuffer():"json"===t.type?r.json():r.text()).then((function(t){o||(n&&s&&function(t,e,r){if(st(),W){var n={status:e.status,statusText:e.statusText,headers:new self.Headers};e.headers.forEach((function(t,e){return n.headers.set(e,t)}));var i=k(e.headers.get("Cache-Control")||"");i["no-store"]||(i["max-age"]&&n.headers.set("Expires",new Date(r+1e3*i["max-age"]).toUTCString()),new Date(n.headers.get("Expires")).getTime()-r<42e4||function(t,e){if(void 0===Q)try{new Response(new ReadableStream),Q=!0;}catch(t){Q=!1;}Q?e(t.body):t.blob().then(e);}(e,(function(e){var r=new self.Response(e,n);st(),W&&W.then((function(e){return e.put(ut(t.url),r)})).catch((function(t){return w(t.message)}));})));}}(i,n,s),a=!0,e(null,t,r.headers.get("Cache-Control"),r.headers.get("Expires")));})).catch((function(t){o||e(new Error(t.message));}));};return s?function(t,e){if(st(),!W)return e(null);var r=ut(t.url);W.then((function(t){t.match(r).then((function(n){var i=function(t){if(!t)return !1;var e=new Date(t.headers.get("Expires")||0),r=k(t.headers.get("Cache-Control")||"");return e>Date.now()&&!r["no-cache"]}(n);t.delete(r),i&&t.put(r,n.clone()),e(null,n,i);})).catch(e);})).catch(e);}(i,u):u(null,null),{cancel:function(){o=!0,a||n.abort();}}}(t,e);if(S()&&self.worker&&self.worker.actor)return self.worker.actor.send("getResource",t,e,void 0,!0)}var r;return function(t,e){var r=new self.XMLHttpRequest;for(var n in r.open(t.method||"GET",t.url,!0),"arrayBuffer"===t.type&&(r.responseType="arraybuffer"),t.headers)r.setRequestHeader(n,t.headers[n]);return "json"===t.type&&(r.responseType="text",r.setRequestHeader("Accept","application/json")),r.withCredentials="include"===t.credentials,r.onerror=function(){e(new Error(r.statusText));},r.onload=function(){if((r.status>=200&&r.status<300||0===r.status)&&null!==r.response){var n=r.response;if("json"===t.type)try{n=JSON.parse(r.response);}catch(t){return e(t)}e(null,n,r.getResponseHeader("Cache-Control"),r.getResponseHeader("Expires"));}else e(new ft(r.statusText,r.status,t.url));},r.send(t.body),{cancel:function(){return r.abort()}}}(t,e)},gt=function(t,e){return vt(p(t,{type:"arrayBuffer"}),e)},xt=function(t,e){return vt(p(t,{method:"POST"}),e)};dt=[],mt=0;var bt=function(t,e){if(R.supported&&(t.headers||(t.headers={}),t.headers.accept="image/webp,*/*"),mt>=L.MAX_PARALLEL_IMAGE_REQUESTS){var r={requestParameters:t,callback:e,cancelled:!1,cancel:function(){this.cancelled=!0;}};return dt.push(r),r}mt++;var n=!1,i=function(){if(!n)for(n=!0,mt--;dt.length&&mt<L.MAX_PARALLEL_IMAGE_REQUESTS;){var t=dt.shift();t.cancelled||(t.cancel=bt(t.requestParameters,t.callback).cancel);}},a=gt(t,(function(t,r,n,a){i(),t?e(t):r&&(ct()?function(t,e){var r=new self.Blob([new Uint8Array(t)],{type:"image/png"});self.createImageBitmap(r).then((function(t){e(null,t);})).catch((function(t){e(new Error("Could not load image because of "+t.message+". Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));}));}(r,e):function(t,e,r,n){var i=new self.Image,a=self.URL;i.onload=function(){e(null,i),a.revokeObjectURL(i.src);},i.onerror=function(){return e(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."))};var o=new self.Blob([new Uint8Array(t)],{type:"image/png"});i.cacheControl=r,i.expires=n,i.src=t.byteLength?a.createObjectURL(o):"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";}(r,e,n,a));}));return {cancel:function(){a.cancel(),i();}}};function wt(t,e,r){r[t]&&-1!==r[t].indexOf(e)||(r[t]=r[t]||[],r[t].push(e));}function _t(t,e,r){if(r&&r[t]){var n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1);}}var At=function(t,e){void 0===e&&(e={}),p(this,e),this.type=t;},St=function(t){function e(e,r){void 0===r&&(r={}),t.call(this,"error",p({error:e},r));}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e}(At),kt=function(){};kt.prototype.on=function(t,e){return this._listeners=this._listeners||{},wt(t,e,this._listeners),this},kt.prototype.off=function(t,e){return _t(t,e,this._listeners),_t(t,e,this._oneTimeListeners),this},kt.prototype.once=function(t,e){return this._oneTimeListeners=this._oneTimeListeners||{},wt(t,e,this._oneTimeListeners),this},kt.prototype.fire=function(t,e){"string"==typeof t&&(t=new At(t,e||{}));var r=t.type;if(this.listens(r)){t.target=this;for(var n=0,i=this._listeners&&this._listeners[r]?this._listeners[r].slice():[];n<i.length;n+=1)i[n].call(this,t);for(var a=0,o=this._oneTimeListeners&&this._oneTimeListeners[r]?this._oneTimeListeners[r].slice():[];a<o.length;a+=1){var s=o[a];_t(r,s,this._oneTimeListeners),s.call(this,t);}var u=this._eventedParent;u&&(p(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),u.fire(t));}else t instanceof St&&console.error(t.error);return this},kt.prototype.listens=function(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)},kt.prototype.setEventedParent=function(t,e){return this._eventedParent=t,this._eventedParentData=e,this};var It={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},light:{type:"light"},sources:{required:!0,type:"sources"},sprite:{type:"string"},glyphs:{type:"string"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{}},default:"mapbox"},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{},within:{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},expression_name:{type:"enum",values:{let:{group:"Variable binding"},var:{group:"Variable binding"},literal:{group:"Types"},array:{group:"Types"},at:{group:"Lookup"},in:{group:"Lookup"},"index-of":{group:"Lookup"},slice:{group:"Lookup"},case:{group:"Decision"},match:{group:"Decision"},coalesce:{group:"Decision"},step:{group:"Ramps, scales, curves"},interpolate:{group:"Ramps, scales, curves"},"interpolate-hcl":{group:"Ramps, scales, curves"},"interpolate-lab":{group:"Ramps, scales, curves"},ln2:{group:"Math"},pi:{group:"Math"},e:{group:"Math"},typeof:{group:"Types"},string:{group:"Types"},number:{group:"Types"},boolean:{group:"Types"},object:{group:"Types"},collator:{group:"Types"},format:{group:"Types"},image:{group:"Types"},"number-format":{group:"Types"},"to-string":{group:"Types"},"to-number":{group:"Types"},"to-boolean":{group:"Types"},"to-rgba":{group:"Color"},"to-color":{group:"Types"},rgb:{group:"Color"},rgba:{group:"Color"},get:{group:"Lookup"},has:{group:"Lookup"},length:{group:"Lookup"},properties:{group:"Feature data"},"feature-state":{group:"Feature data"},"geometry-type":{group:"Feature data"},id:{group:"Feature data"},zoom:{group:"Zoom"},"heatmap-density":{group:"Heatmap"},"line-progress":{group:"Feature data"},accumulated:{group:"Feature data"},"+":{group:"Math"},"*":{group:"Math"},"-":{group:"Math"},"/":{group:"Math"},"%":{group:"Math"},"^":{group:"Math"},sqrt:{group:"Math"},log10:{group:"Math"},ln:{group:"Math"},log2:{group:"Math"},sin:{group:"Math"},cos:{group:"Math"},tan:{group:"Math"},asin:{group:"Math"},acos:{group:"Math"},atan:{group:"Math"},min:{group:"Math"},max:{group:"Math"},round:{group:"Math"},abs:{group:"Math"},ceil:{group:"Math"},floor:{group:"Math"},distance:{group:"Math"},"==":{group:"Decision"},"!=":{group:"Decision"},">":{group:"Decision"},"<":{group:"Decision"},">=":{group:"Decision"},"<=":{group:"Decision"},all:{group:"Decision"},any:{group:"Decision"},"!":{group:"Decision"},within:{group:"Decision"},"is-supported-script":{group:"String"},upcase:{group:"String"},downcase:{group:"String"},concat:{group:"String"},"resolved-locale":{group:"String"}}},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}},zt=function(t,e,r,n){this.message=(t?t+": ":"")+r,n&&(this.identifier=n),null!=e&&e.__line__&&(this.line=e.__line__);};function Ct(t){var e=t.value;return e?[new zt(t.key,e,"constants have been deprecated as of v8")]:[]}function Mt(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];for(var n=0,i=e;n<i.length;n+=1){var a=i[n];for(var o in a)t[o]=a[o];}return t}function Et(t){return t instanceof Number||t instanceof String||t instanceof Boolean?t.valueOf():t}function Tt(t){if(Array.isArray(t))return t.map(Tt);if(t instanceof Object&&!(t instanceof Number||t instanceof String||t instanceof Boolean)){var e={};for(var r in t)e[r]=Tt(t[r]);return e}return Et(t)}var Pt=function(t){function e(e,r){t.call(this,r),this.message=r,this.key=e;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e}(Error),Bt=function(t,e){void 0===e&&(e=[]),this.parent=t,this.bindings={};for(var r=0,n=e;r<n.length;r+=1){var i=n[r];this.bindings[i[0]]=i[1];}};Bt.prototype.concat=function(t){return new Bt(this,t)},Bt.prototype.get=function(t){if(this.bindings[t])return this.bindings[t];if(this.parent)return this.parent.get(t);throw new Error(t+" not found in scope.")},Bt.prototype.has=function(t){return !!this.bindings[t]||!!this.parent&&this.parent.has(t)};var Vt={kind:"null"},Ft={kind:"number"},Dt={kind:"string"},Lt={kind:"boolean"},Rt={kind:"color"},Ot={kind:"object"},Ut={kind:"value"},jt={kind:"collator"},qt={kind:"formatted"},Nt={kind:"resolvedImage"};function Kt(t,e){return {kind:"array",itemType:t,N:e}}function Gt(t){if("array"===t.kind){var e=Gt(t.itemType);return "number"==typeof t.N?"array<"+e+", "+t.N+">":"value"===t.itemType.kind?"array":"array<"+e+">"}return t.kind}var Zt=[Vt,Ft,Dt,Lt,Rt,qt,Ot,Kt(Ut),Nt];function Xt(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!Xt(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else {if(t.kind===e.kind)return null;if("value"===t.kind)for(var r=0,n=Zt;r<n.length;r+=1)if(!Xt(n[r],e))return null}return "Expected "+Gt(t)+" but found "+Gt(e)+" instead."}function Jt(t,e){return e.some((function(e){return e.kind===t.kind}))}function Ht(t,e){return e.some((function(e){return "null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t}))}var Yt=e((function(t,e){var r={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function n(t){return (t=Math.round(t))<0?0:t>255?255:t}function i(t){return n("%"===t[t.length-1]?parseFloat(t)/100*255:parseInt(t))}function a(t){return (e="%"===t[t.length-1]?parseFloat(t)/100:parseFloat(t))<0?0:e>1?1:e;var e;}function o(t,e,r){return r<0?r+=1:r>1&&(r-=1),6*r<1?t+(e-t)*r*6:2*r<1?e:3*r<2?t+(e-t)*(2/3-r)*6:t}try{e.parseCSSColor=function(t){var e,s=t.replace(/ /g,"").toLowerCase();if(s in r)return r[s].slice();if("#"===s[0])return 4===s.length?(e=parseInt(s.substr(1),16))>=0&&e<=4095?[(3840&e)>>4|(3840&e)>>8,240&e|(240&e)>>4,15&e|(15&e)<<4,1]:null:7===s.length&&(e=parseInt(s.substr(1),16))>=0&&e<=16777215?[(16711680&e)>>16,(65280&e)>>8,255&e,1]:null;var u=s.indexOf("("),l=s.indexOf(")");if(-1!==u&&l+1===s.length){var p=s.substr(0,u),c=s.substr(u+1,l-(u+1)).split(","),h=1;switch(p){case"rgba":if(4!==c.length)return null;h=a(c.pop());case"rgb":return 3!==c.length?null:[i(c[0]),i(c[1]),i(c[2]),h];case"hsla":if(4!==c.length)return null;h=a(c.pop());case"hsl":if(3!==c.length)return null;var f=(parseFloat(c[0])%360+360)%360/360,y=a(c[1]),d=a(c[2]),m=d<=.5?d*(y+1):d+y-d*y,v=2*d-m;return [n(255*o(v,m,f+1/3)),n(255*o(v,m,f)),n(255*o(v,m,f-1/3)),h];default:return null}}return null};}catch(t){}})).parseCSSColor,$t=function(t,e,r,n){void 0===n&&(n=1),this.r=t,this.g=e,this.b=r,this.a=n;};$t.parse=function(t){if(t){if(t instanceof $t)return t;if("string"==typeof t){var e=Yt(t);if(e)return new $t(e[0]/255*e[3],e[1]/255*e[3],e[2]/255*e[3],e[3])}}},$t.prototype.toString=function(){var t=this.toArray(),e=t[1],r=t[2],n=t[3];return "rgba("+Math.round(t[0])+","+Math.round(e)+","+Math.round(r)+","+n+")"},$t.prototype.toArray=function(){var t=this.a;return 0===t?[0,0,0,0]:[255*this.r/t,255*this.g/t,255*this.b/t,t]},$t.black=new $t(0,0,0,1),$t.white=new $t(1,1,1,1),$t.transparent=new $t(0,0,0,0),$t.red=new $t(1,0,0,1);var Wt=function(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});};Wt.prototype.compare=function(t,e){return this.collator.compare(t,e)},Wt.prototype.resolvedLocale=function(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale};var Qt=function(t,e,r,n,i){this.text=t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i;},te=function(t){this.sections=t;};te.fromString=function(t){return new te([new Qt(t,null,null,null,null)])},te.prototype.isEmpty=function(){return 0===this.sections.length||!this.sections.some((function(t){return 0!==t.text.length||t.image&&0!==t.image.name.length}))},te.factory=function(t){return t instanceof te?t:te.fromString(t)},te.prototype.toString=function(){return 0===this.sections.length?"":this.sections.map((function(t){return t.text})).join("")},te.prototype.serialize=function(){for(var t=["format"],e=0,r=this.sections;e<r.length;e+=1){var n=r[e];if(n.image)t.push(["image",n.image.name]);else {t.push(n.text);var i={};n.fontStack&&(i["text-font"]=["literal",n.fontStack.split(",")]),n.scale&&(i["font-scale"]=n.scale),n.textColor&&(i["text-color"]=["rgba"].concat(n.textColor.toArray())),t.push(i);}}return t};var ee=function(t){this.name=t.name,this.available=t.available;};function re(t,e,r,n){return "number"==typeof t&&t>=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:"Invalid rgba value ["+[t,e,r,n].join(", ")+"]: 'a' must be between 0 and 1.":"Invalid rgba value ["+("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")+"]: 'r', 'g', and 'b' must be between 0 and 255."}function ne(t){if(null===t)return !0;if("string"==typeof t)return !0;if("boolean"==typeof t)return !0;if("number"==typeof t)return !0;if(t instanceof $t)return !0;if(t instanceof Wt)return !0;if(t instanceof te)return !0;if(t instanceof ee)return !0;if(Array.isArray(t)){for(var e=0,r=t;e<r.length;e+=1)if(!ne(r[e]))return !1;return !0}if("object"==typeof t){for(var n in t)if(!ne(t[n]))return !1;return !0}return !1}function ie(t){if(null===t)return Vt;if("string"==typeof t)return Dt;if("boolean"==typeof t)return Lt;if("number"==typeof t)return Ft;if(t instanceof $t)return Rt;if(t instanceof Wt)return jt;if(t instanceof te)return qt;if(t instanceof ee)return Nt;if(Array.isArray(t)){for(var e,r=t.length,n=0,i=t;n<i.length;n+=1){var a=ie(i[n]);if(e){if(e===a)continue;e=Ut;break}e=a;}return Kt(e||Ut,r)}return Ot}function ae(t){var e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof $t||t instanceof te||t instanceof ee?t.toString():JSON.stringify(t)}ee.prototype.toString=function(){return this.name},ee.fromString=function(t){return t?new ee({name:t,available:!1}):null},ee.prototype.serialize=function(){return ["image",this.name]};var oe=function(t,e){this.type=t,this.value=e;};oe.parse=function(t,e){if(2!==t.length)return e.error("'literal' expression requires exactly one argument, but found "+(t.length-1)+" instead.");if(!ne(t[1]))return e.error("invalid value");var r=t[1],n=ie(r),i=e.expectedType;return "array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new oe(n,r)},oe.prototype.evaluate=function(){return this.value},oe.prototype.eachChild=function(){},oe.prototype.outputDefined=function(){return !0},oe.prototype.serialize=function(){return "array"===this.type.kind||"object"===this.type.kind?["literal",this.value]:this.value instanceof $t?["rgba"].concat(this.value.toArray()):this.value instanceof te?this.value.serialize():this.value};var se=function(t){this.name="ExpressionEvaluationError",this.message=t;};se.prototype.toJSON=function(){return this.message};var ue={string:Dt,number:Ft,boolean:Lt,object:Ot},le=function(t,e){this.type=t,this.args=e;};le.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");var r,n=1,i=t[0];if("array"===i){var a,o;if(t.length>2){var s=t[1];if("string"!=typeof s||!(s in ue)||"object"===s)return e.error('The item type argument of "array" must be one of string, number, boolean',1);a=ue[s],n++;}else a=Ut;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);o=t[2],n++;}r=Kt(a,o);}else r=ue[i];for(var u=[];n<t.length;n++){var l=e.parse(t[n],n,Ut);if(!l)return null;u.push(l);}return new le(r,u)},le.prototype.evaluate=function(t){for(var e=0;e<this.args.length;e++){var r=this.args[e].evaluate(t);if(!Xt(this.type,ie(r)))return r;if(e===this.args.length-1)throw new se("Expected value to be of type "+Gt(this.type)+", but found "+Gt(ie(r))+" instead.")}return null},le.prototype.eachChild=function(t){this.args.forEach(t);},le.prototype.outputDefined=function(){return this.args.every((function(t){return t.outputDefined()}))},le.prototype.serialize=function(){var t=this.type,e=[t.kind];if("array"===t.kind){var r=t.itemType;if("string"===r.kind||"number"===r.kind||"boolean"===r.kind){e.push(r.kind);var n=t.N;("number"==typeof n||this.args.length>1)&&e.push(n);}}return e.concat(this.args.map((function(t){return t.serialize()})))};var pe=function(t){this.type=qt,this.sections=t;};pe.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");var r=t[1];if(!Array.isArray(r)&&"object"==typeof r)return e.error("First argument must be an image or text section.");for(var n=[],i=!1,a=1;a<=t.length-1;++a){var o=t[a];if(i&&"object"==typeof o&&!Array.isArray(o)){i=!1;var s=null;if(o["font-scale"]&&!(s=e.parse(o["font-scale"],1,Ft)))return null;var u=null;if(o["text-font"]&&!(u=e.parse(o["text-font"],1,Kt(Dt))))return null;var l=null;if(o["text-color"]&&!(l=e.parse(o["text-color"],1,Rt)))return null;var p=n[n.length-1];p.scale=s,p.font=u,p.textColor=l;}else {var c=e.parse(t[a],1,Ut);if(!c)return null;var h=c.type.kind;if("string"!==h&&"value"!==h&&"null"!==h&&"resolvedImage"!==h)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,n.push({content:c,scale:null,font:null,textColor:null});}}return new pe(n)},pe.prototype.evaluate=function(t){return new te(this.sections.map((function(e){var r=e.content.evaluate(t);return ie(r)===Nt?new Qt("",r,null,null,null):new Qt(ae(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null)})))},pe.prototype.eachChild=function(t){for(var e=0,r=this.sections;e<r.length;e+=1){var n=r[e];t(n.content),n.scale&&t(n.scale),n.font&&t(n.font),n.textColor&&t(n.textColor);}},pe.prototype.outputDefined=function(){return !1},pe.prototype.serialize=function(){for(var t=["format"],e=0,r=this.sections;e<r.length;e+=1){var n=r[e];t.push(n.content.serialize());var i={};n.scale&&(i["font-scale"]=n.scale.serialize()),n.font&&(i["text-font"]=n.font.serialize()),n.textColor&&(i["text-color"]=n.textColor.serialize()),t.push(i);}return t};var ce=function(t){this.type=Nt,this.input=t;};ce.parse=function(t,e){if(2!==t.length)return e.error("Expected two arguments.");var r=e.parse(t[1],1,Dt);return r?new ce(r):e.error("No image name provided.")},ce.prototype.evaluate=function(t){var e=this.input.evaluate(t),r=ee.fromString(e);return r&&t.availableImages&&(r.available=t.availableImages.indexOf(e)>-1),r},ce.prototype.eachChild=function(t){t(this.input);},ce.prototype.outputDefined=function(){return !1},ce.prototype.serialize=function(){return ["image",this.input.serialize()]};var he={"to-boolean":Lt,"to-color":Rt,"to-number":Ft,"to-string":Dt},fe=function(t,e){this.type=t,this.args=e;};fe.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");var r=t[0];if(("to-boolean"===r||"to-string"===r)&&2!==t.length)return e.error("Expected one argument.");for(var n=he[r],i=[],a=1;a<t.length;a++){var o=e.parse(t[a],a,Ut);if(!o)return null;i.push(o);}return new fe(n,i)},fe.prototype.evaluate=function(t){if("boolean"===this.type.kind)return Boolean(this.args[0].evaluate(t));if("color"===this.type.kind){for(var e,r,n=0,i=this.args;n<i.length;n+=1){if(r=null,(e=i[n].evaluate(t))instanceof $t)return e;if("string"==typeof e){var a=t.parseColor(e);if(a)return a}else if(Array.isArray(e)&&!(r=e.length<3||e.length>4?"Invalid rbga value "+JSON.stringify(e)+": expected an array containing either three or four numeric values.":re(e[0],e[1],e[2],e[3])))return new $t(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new se(r||"Could not parse color from value '"+("string"==typeof e?e:String(JSON.stringify(e)))+"'")}if("number"===this.type.kind){for(var o=null,s=0,u=this.args;s<u.length;s+=1){if(null===(o=u[s].evaluate(t)))return 0;var l=Number(o);if(!isNaN(l))return l}throw new se("Could not convert "+JSON.stringify(o)+" to number.")}return "formatted"===this.type.kind?te.fromString(ae(this.args[0].evaluate(t))):"resolvedImage"===this.type.kind?ee.fromString(ae(this.args[0].evaluate(t))):ae(this.args[0].evaluate(t))},fe.prototype.eachChild=function(t){this.args.forEach(t);},fe.prototype.outputDefined=function(){return this.args.every((function(t){return t.outputDefined()}))},fe.prototype.serialize=function(){if("formatted"===this.type.kind)return new pe([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if("resolvedImage"===this.type.kind)return new ce(this.args[0]).serialize();var t=["to-"+this.type.kind];return this.eachChild((function(e){t.push(e.serialize());})),t};var ye=["Unknown","Point","LineString","Polygon"],de=function(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache={},this.availableImages=null,this.canonical=null;};de.prototype.id=function(){return this.feature&&"id"in this.feature?this.feature.id:null},de.prototype.geometryType=function(){return this.feature?"number"==typeof this.feature.type?ye[this.feature.type]:this.feature.type:null},de.prototype.geometry=function(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null},de.prototype.canonicalID=function(){return this.canonical},de.prototype.properties=function(){return this.feature&&this.feature.properties||{}},de.prototype.parseColor=function(t){var e=this._parseColorCache[t];return e||(e=this._parseColorCache[t]=$t.parse(t)),e};var me=function(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n;};me.prototype.evaluate=function(t){return this._evaluate(t,this.args)},me.prototype.eachChild=function(t){this.args.forEach(t);},me.prototype.outputDefined=function(){return !1},me.prototype.serialize=function(){return [this.name].concat(this.args.map((function(t){return t.serialize()})))},me.parse=function(t,e){var r,n=t[0],i=me.definitions[n];if(!i)return e.error('Unknown expression "'+n+'". If you wanted a literal array, use ["literal", [...]].',0);for(var a=Array.isArray(i)?i[0]:i.type,o=Array.isArray(i)?[[i[1],i[2]]]:i.overloads,s=o.filter((function(e){var r=e[0];return !Array.isArray(r)||r.length===t.length-1})),u=null,l=0,p=s;l<p.length;l+=1){var c=p[l],h=c[0],f=c[1];u=new Re(e.registry,e.path,null,e.scope);for(var y=[],d=!1,m=1;m<t.length;m++){var v=t[m],g=Array.isArray(h)?h[m-1]:h.type,x=u.parse(v,1+y.length,g);if(!x){d=!0;break}y.push(x);}if(!d)if(Array.isArray(h)&&h.length!==y.length)u.error("Expected "+h.length+" arguments, but found "+y.length+" instead.");else {for(var b=0;b<y.length;b++){var w=Array.isArray(h)?h[b]:h.type,_=y[b];u.concat(b+1).checkSubtype(w,_.type);}if(0===u.errors.length)return new me(n,a,f,y)}}if(1===s.length)(r=e.errors).push.apply(r,u.errors);else {for(var A=(s.length?s:o).map((function(t){var e;return e=t[0],Array.isArray(e)?"("+e.map(Gt).join(", ")+")":"("+Gt(e.type)+"...)"})).join(" | "),S=[],k=1;k<t.length;k++){var I=e.parse(t[k],1+S.length);if(!I)return null;S.push(Gt(I.type));}e.error("Expected arguments of type "+A+", but found ("+S.join(", ")+") instead.");}return null},me.register=function(t,e){for(var r in me.definitions=e,e)t[r]=me;};var ve=function(t,e,r){this.type=jt,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e;};function ge(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1]);}function xe(t,e){return !(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function be(t,e){var r=(180+t[0])/360,n=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return [Math.round(r*i*8192),Math.round(n*i*8192)]}function we(t,e,r){return e[1]>t[1]!=r[1]>t[1]&&t[0]<(r[0]-e[0])*(t[1]-e[1])/(r[1]-e[1])+e[0]}function _e(t,e){for(var r,n,i,a,o,s,u,l=!1,p=0,c=e.length;p<c;p++)for(var h=e[p],f=0,y=h.length;f<y-1;f++){if((a=(r=t)[0]-(n=h[f])[0])*(u=r[1]-(i=h[f+1])[1])-(s=r[0]-i[0])*(o=r[1]-n[1])==0&&a*s<=0&&o*u<=0)return !1;we(t,h[f],h[f+1])&&(l=!l);}return l}function Ae(t,e){for(var r=0;r<e.length;r++)if(_e(t,e[r]))return !0;return !1}function Se(t,e,r,n){var i=n[0]-r[0],a=n[1]-r[1],o=(t[0]-r[0])*a-i*(t[1]-r[1]),s=(e[0]-r[0])*a-i*(e[1]-r[1]);return o>0&&s<0||o<0&&s>0}function ke(t,e,r){for(var n=0,i=r;n<i.length;n+=1)for(var a=i[n],o=0;o<a.length-1;++o)if(0!=(c=[(p=a[o+1])[0]-(l=a[o])[0],p[1]-l[1]])[0]*(h=[(u=e)[0]-(s=t)[0],u[1]-s[1]])[1]-c[1]*h[0]&&Se(s,u,l,p)&&Se(l,p,s,u))return !0;var s,u,l,p,c,h;return !1}function Ie(t,e){for(var r=0;r<t.length;++r)if(!_e(t[r],e))return !1;for(var n=0;n<t.length-1;++n)if(ke(t[n],t[n+1],e))return !1;return !0}function ze(t,e){for(var r=0;r<e.length;r++)if(Ie(t,e[r]))return !0;return !1}function Ce(t,e,r){for(var n=[],i=0;i<t.length;i++){for(var a=[],o=0;o<t[i].length;o++){var s=be(t[i][o],r);ge(e,s),a.push(s);}n.push(a);}return n}function Me(t,e,r){for(var n=[],i=0;i<t.length;i++){var a=Ce(t[i],e,r);n.push(a);}return n}function Ee(t,e,r,n){if(t[0]<r[0]||t[0]>r[2]){var i=.5*n,a=t[0]-r[0]>i?-n:r[0]-t[0]>i?n:0;0===a&&(a=t[0]-r[2]>i?-n:r[2]-t[0]>i?n:0),t[0]+=a;}ge(e,t);}function Te(t,e,r,n){for(var i=8192*Math.pow(2,n.z),a=[8192*n.x,8192*n.y],o=[],s=0,u=t;s<u.length;s+=1)for(var l=0,p=u[s];l<p.length;l+=1){var c=p[l],h=[c.x+a[0],c.y+a[1]];Ee(h,e,r,i),o.push(h);}return o}function Pe(t,e,r,n){for(var i,a=8192*Math.pow(2,n.z),o=[8192*n.x,8192*n.y],s=[],u=0,l=t;u<l.length;u+=1){for(var p=[],c=0,h=l[u];c<h.length;c+=1){var f=h[c],y=[f.x+o[0],f.y+o[1]];ge(e,y),p.push(y);}s.push(p);}if(e[2]-e[0]<=a/2){(i=e)[0]=i[1]=1/0,i[2]=i[3]=-1/0;for(var d=0,m=s;d<m.length;d+=1)for(var v=0,g=m[d];v<g.length;v+=1)Ee(g[v],e,r,a);}return s}ve.parse=function(t,e){if(2!==t.length)return e.error("Expected one argument.");var r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");var n=e.parse(void 0!==r["case-sensitive"]&&r["case-sensitive"],1,Lt);if(!n)return null;var i=e.parse(void 0!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,Lt);if(!i)return null;var a=null;return r.locale&&!(a=e.parse(r.locale,1,Dt))?null:new ve(n,i,a)},ve.prototype.evaluate=function(t){return new Wt(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)},ve.prototype.eachChild=function(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale);},ve.prototype.outputDefined=function(){return !1},ve.prototype.serialize=function(){var t={};return t["case-sensitive"]=this.caseSensitive.serialize(),t["diacritic-sensitive"]=this.diacriticSensitive.serialize(),this.locale&&(t.locale=this.locale.serialize()),["collator",t]};var Be=function(t,e){this.type=Lt,this.geojson=t,this.geometries=e;};function Ve(t){if(t instanceof me){if("get"===t.name&&1===t.args.length)return !1;if("feature-state"===t.name)return !1;if("has"===t.name&&1===t.args.length)return !1;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return !1;if(/^filter-/.test(t.name))return !1}if(t instanceof Be)return !1;var e=!0;return t.eachChild((function(t){e&&!Ve(t)&&(e=!1);})),e}function Fe(t){if(t instanceof me&&"feature-state"===t.name)return !1;var e=!0;return t.eachChild((function(t){e&&!Fe(t)&&(e=!1);})),e}function De(t,e){if(t instanceof me&&e.indexOf(t.name)>=0)return !1;var r=!0;return t.eachChild((function(t){r&&!De(t,e)&&(r=!1);})),r}Be.parse=function(t,e){if(2!==t.length)return e.error("'within' expression requires exactly one argument, but found "+(t.length-1)+" instead.");if(ne(t[1])){var r=t[1];if("FeatureCollection"===r.type)for(var n=0;n<r.features.length;++n){var i=r.features[n].geometry.type;if("Polygon"===i||"MultiPolygon"===i)return new Be(r,r.features[n].geometry)}else if("Feature"===r.type){var a=r.geometry.type;if("Polygon"===a||"MultiPolygon"===a)return new Be(r,r.geometry)}else if("Polygon"===r.type||"MultiPolygon"===r.type)return new Be(r,r)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")},Be.prototype.evaluate=function(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){var r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){var a=Ce(e.coordinates,n,i),o=Te(t.geometry(),r,n,i);if(!xe(r,n))return !1;for(var s=0,u=o;s<u.length;s+=1)if(!_e(u[s],a))return !1}if("MultiPolygon"===e.type){var l=Me(e.coordinates,n,i),p=Te(t.geometry(),r,n,i);if(!xe(r,n))return !1;for(var c=0,h=p;c<h.length;c+=1)if(!Ae(h[c],l))return !1}return !0}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){var r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){var a=Ce(e.coordinates,n,i),o=Pe(t.geometry(),r,n,i);if(!xe(r,n))return !1;for(var s=0,u=o;s<u.length;s+=1)if(!Ie(u[s],a))return !1}if("MultiPolygon"===e.type){var l=Me(e.coordinates,n,i),p=Pe(t.geometry(),r,n,i);if(!xe(r,n))return !1;for(var c=0,h=p;c<h.length;c+=1)if(!ze(h[c],l))return !1}return !0}(t,this.geometries)}return !1},Be.prototype.eachChild=function(){},Be.prototype.outputDefined=function(){return !0},Be.prototype.serialize=function(){return ["within",this.geojson]};var Le=function(t,e){this.type=e.type,this.name=t,this.boundExpression=e;};Le.parse=function(t,e){if(2!==t.length||"string"!=typeof t[1])return e.error("'var' expression requires exactly one string literal argument.");var r=t[1];return e.scope.has(r)?new Le(r,e.scope.get(r)):e.error('Unknown variable "'+r+'". Make sure "'+r+'" has been bound in an enclosing "let" expression before using it.',1)},Le.prototype.evaluate=function(t){return this.boundExpression.evaluate(t)},Le.prototype.eachChild=function(){},Le.prototype.outputDefined=function(){return !1},Le.prototype.serialize=function(){return ["var",this.name]};var Re=function(t,e,r,n,i){void 0===e&&(e=[]),void 0===n&&(n=new Bt),void 0===i&&(i=[]),this.registry=t,this.path=e,this.key=e.map((function(t){return "["+t+"]"})).join(""),this.scope=n,this.errors=i,this.expectedType=r;};function Oe(t,e){for(var r,n=t.length-1,i=0,a=n,o=0;i<=a;)if((r=t[o=Math.floor((i+a)/2)])<=e){if(o===n||e<t[o+1])return o;i=o+1;}else {if(!(r>e))throw new se("Input is not a number.");a=o-1;}return 0}Re.prototype.parse=function(t,e,r,n,i){return void 0===i&&(i={}),e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)},Re.prototype._parse=function(t,e){function r(t,e,r){return "assert"===r?new le(e,[t]):"coerce"===r?new fe(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');var n=t[0];if("string"!=typeof n)return this.error("Expression name must be a string, but found "+typeof n+' instead. If you wanted a literal array, use ["literal", [...]].',0),null;var i=this.registry[n];if(i){var a=i.parse(t,this);if(!a)return null;if(this.expectedType){var o=this.expectedType,s=a.type;if("string"!==o.kind&&"number"!==o.kind&&"boolean"!==o.kind&&"object"!==o.kind&&"array"!==o.kind||"value"!==s.kind)if("color"!==o.kind&&"formatted"!==o.kind&&"resolvedImage"!==o.kind||"value"!==s.kind&&"string"!==s.kind){if(this.checkSubtype(o,s))return null}else a=r(a,o,e.typeAnnotation||"coerce");else a=r(a,o,e.typeAnnotation||"assert");}if(!(a instanceof oe)&&"resolvedImage"!==a.type.kind&&function t(e){if(e instanceof Le)return t(e.boundExpression);if(e instanceof me&&"error"===e.name)return !1;if(e instanceof ve)return !1;if(e instanceof Be)return !1;var r=e instanceof fe||e instanceof le,n=!0;return e.eachChild((function(e){n=r?n&&t(e):n&&e instanceof oe;})),!!n&&Ve(e)&&De(e,["zoom","heatmap-density","line-progress","accumulated","is-supported-script"])}(a)){var u=new de;try{a=new oe(a.type,a.evaluate(u));}catch(t){return this.error(t.message),null}}return a}return this.error('Unknown expression "'+n+'". If you wanted a literal array, use ["literal", [...]].',0)}return this.error(void 0===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':"Expected an array, but found "+typeof t+" instead.")},Re.prototype.concat=function(t,e,r){var n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new Re(this.registry,n,e||null,i,this.errors)},Re.prototype.error=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];var n=""+this.key+e.map((function(t){return "["+t+"]"})).join("");this.errors.push(new Pt(n,t));},Re.prototype.checkSubtype=function(t,e){var r=Xt(t,e);return r&&this.error(r),r};var Ue=function(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(var n=0,i=r;n<i.length;n+=1){var a=i[n],o=a[1];this.labels.push(a[0]),this.outputs.push(o);}};function je(t,e,r){return t*(1-r)+e*r}Ue.parse=function(t,e){if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");var r=e.parse(t[1],1,Ft);if(!r)return null;var n=[],i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(var a=1;a<t.length;a+=2){var o=1===a?-1/0:t[a],s=t[a+1],u=a,l=a+1;if("number"!=typeof o)return e.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.',u);if(n.length&&n[n.length-1][0]>=o)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',u);var p=e.parse(s,l,i);if(!p)return null;i=i||p.type,n.push([o,p]);}return new Ue(i,r,n)},Ue.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[Oe(e,n)].evaluate(t)},Ue.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e<r.length;e+=1)t(r[e]);},Ue.prototype.outputDefined=function(){return this.outputs.every((function(t){return t.outputDefined()}))},Ue.prototype.serialize=function(){for(var t=["step",this.input.serialize()],e=0;e<this.labels.length;e++)e>0&&t.push(this.labels[e]),t.push(this.outputs[e].serialize());return t};var qe=Object.freeze({__proto__:null,number:je,color:function(t,e,r){return new $t(je(t.r,e.r,r),je(t.g,e.g,r),je(t.b,e.b,r),je(t.a,e.a,r))},array:function(t,e,r){return t.map((function(t,n){return je(t,e[n],r)}))}}),Ne=6/29*3*(6/29),Ke=Math.PI/180,Ge=180/Math.PI;function Ze(t){return t>.008856451679035631?Math.pow(t,1/3):t/Ne+4/29}function Xe(t){return t>6/29?t*t*t:Ne*(t-4/29)}function Je(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function He(t){return (t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Ye(t){var e=He(t.r),r=He(t.g),n=He(t.b),i=Ze((.4124564*e+.3575761*r+.1804375*n)/.95047),a=Ze((.2126729*e+.7151522*r+.072175*n)/1);return {l:116*a-16,a:500*(i-a),b:200*(a-Ze((.0193339*e+.119192*r+.9503041*n)/1.08883)),alpha:t.a}}function $e(t){var e=(t.l+16)/116,r=isNaN(t.a)?e:e+t.a/500,n=isNaN(t.b)?e:e-t.b/200;return e=1*Xe(e),r=.95047*Xe(r),n=1.08883*Xe(n),new $t(Je(3.2404542*r-1.5371385*e-.4985314*n),Je(-.969266*r+1.8760108*e+.041556*n),Je(.0556434*r-.2040259*e+1.0572252*n),t.alpha)}function We(t,e,r){var n=e-t;return t+r*(n>180||n<-180?n-360*Math.round(n/360):n)}var Qe={forward:Ye,reverse:$e,interpolate:function(t,e,r){return {l:je(t.l,e.l,r),a:je(t.a,e.a,r),b:je(t.b,e.b,r),alpha:je(t.alpha,e.alpha,r)}}},tr={forward:function(t){var e=Ye(t),r=e.l,n=e.a,i=e.b,a=Math.atan2(i,n)*Ge;return {h:a<0?a+360:a,c:Math.sqrt(n*n+i*i),l:r,alpha:t.a}},reverse:function(t){var e=t.h*Ke,r=t.c;return $e({l:t.l,a:Math.cos(e)*r,b:Math.sin(e)*r,alpha:t.alpha})},interpolate:function(t,e,r){return {h:We(t.h,e.h,r),c:je(t.c,e.c,r),l:je(t.l,e.l,r),alpha:je(t.alpha,e.alpha,r)}}},er=Object.freeze({__proto__:null,lab:Qe,hcl:tr}),rr=function(t,e,r,n,i){this.type=t,this.operator=e,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(var a=0,o=i;a<o.length;a+=1){var s=o[a],u=s[1];this.labels.push(s[0]),this.outputs.push(u);}};function nr(t,e,r,n){var i=n-r,a=t-r;return 0===i?0:1===e?a/i:(Math.pow(e,a)-1)/(Math.pow(e,i)-1)}rr.interpolationFactor=function(t,e,n,i){var a=0;if("exponential"===t.name)a=nr(e,t.base,n,i);else if("linear"===t.name)a=nr(e,1,n,i);else if("cubic-bezier"===t.name){var o=t.controlPoints;a=new r(o[0],o[1],o[2],o[3]).solve(nr(e,1,n,i));}return a},rr.parse=function(t,e){var r=t[0],n=t[1],i=t[2],a=t.slice(3);if(!Array.isArray(n)||0===n.length)return e.error("Expected an interpolation type expression.",1);if("linear"===n[0])n={name:"linear"};else if("exponential"===n[0]){var o=n[1];if("number"!=typeof o)return e.error("Exponential interpolation requires a numeric base.",1,1);n={name:"exponential",base:o};}else {if("cubic-bezier"!==n[0])return e.error("Unknown interpolation type "+String(n[0]),1,0);var s=n.slice(1);if(4!==s.length||s.some((function(t){return "number"!=typeof t||t<0||t>1})))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:s};}if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(!(i=e.parse(i,2,Ft)))return null;var u=[],l=null;"interpolate-hcl"===r||"interpolate-lab"===r?l=Rt:e.expectedType&&"value"!==e.expectedType.kind&&(l=e.expectedType);for(var p=0;p<a.length;p+=2){var c=a[p],h=a[p+1],f=p+3,y=p+4;if("number"!=typeof c)return e.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.',f);if(u.length&&u[u.length-1][0]>=c)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',f);var d=e.parse(h,y,l);if(!d)return null;l=l||d.type,u.push([c,d]);}return "number"===l.kind||"color"===l.kind||"array"===l.kind&&"number"===l.itemType.kind&&"number"==typeof l.N?new rr(l,r,n,i,u):e.error("Type "+Gt(l)+" is not interpolatable.")},rr.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);var a=Oe(e,n),o=rr.interpolationFactor(this.interpolation,n,e[a],e[a+1]),s=r[a].evaluate(t),u=r[a+1].evaluate(t);return "interpolate"===this.operator?qe[this.type.kind.toLowerCase()](s,u,o):"interpolate-hcl"===this.operator?tr.reverse(tr.interpolate(tr.forward(s),tr.forward(u),o)):Qe.reverse(Qe.interpolate(Qe.forward(s),Qe.forward(u),o))},rr.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e<r.length;e+=1)t(r[e]);},rr.prototype.outputDefined=function(){return this.outputs.every((function(t){return t.outputDefined()}))},rr.prototype.serialize=function(){var t;t="linear"===this.interpolation.name?["linear"]:"exponential"===this.interpolation.name?1===this.interpolation.base?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier"].concat(this.interpolation.controlPoints);for(var e=[this.operator,t,this.input.serialize()],r=0;r<this.labels.length;r++)e.push(this.labels[r],this.outputs[r].serialize());return e};var ir=function(t,e){this.type=t,this.args=e;};ir.parse=function(t,e){if(t.length<2)return e.error("Expectected at least one argument.");var r=null,n=e.expectedType;n&&"value"!==n.kind&&(r=n);for(var i=[],a=0,o=t.slice(1);a<o.length;a+=1){var s=e.parse(o[a],1+i.length,r,void 0,{typeAnnotation:"omit"});if(!s)return null;r=r||s.type,i.push(s);}var u=n&&i.some((function(t){return Xt(n,t.type)}));return new ir(u?Ut:r,i)},ir.prototype.evaluate=function(t){for(var e,r=null,n=0,i=0,a=this.args;i<a.length&&(n++,(r=a[i].evaluate(t))&&r instanceof ee&&!r.available&&(e||(e=r.name),r=null,n===this.args.length&&(r=e)),null===r);i+=1);return r},ir.prototype.eachChild=function(t){this.args.forEach(t);},ir.prototype.outputDefined=function(){return this.args.every((function(t){return t.outputDefined()}))},ir.prototype.serialize=function(){var t=["coalesce"];return this.eachChild((function(e){t.push(e.serialize());})),t};var ar=function(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;};ar.prototype.evaluate=function(t){return this.result.evaluate(t)},ar.prototype.eachChild=function(t){for(var e=0,r=this.bindings;e<r.length;e+=1)t(r[e][1]);t(this.result);},ar.parse=function(t,e){if(t.length<4)return e.error("Expected at least 3 arguments, but found "+(t.length-1)+" instead.");for(var r=[],n=1;n<t.length-1;n+=2){var i=t[n];if("string"!=typeof i)return e.error("Expected string, but found "+typeof i+" instead.",n);if(/[^a-zA-Z0-9_]/.test(i))return e.error("Variable names must contain only alphanumeric characters or '_'.",n);var a=e.parse(t[n+1],n+1);if(!a)return null;r.push([i,a]);}var o=e.parse(t[t.length-1],t.length-1,e.expectedType,r);return o?new ar(r,o):null},ar.prototype.outputDefined=function(){return this.result.outputDefined()},ar.prototype.serialize=function(){for(var t=["let"],e=0,r=this.bindings;e<r.length;e+=1){var n=r[e];t.push(n[0],n[1].serialize());}return t.push(this.result.serialize()),t};var or=function(t,e,r){this.type=t,this.index=e,this.input=r;};or.parse=function(t,e){if(3!==t.length)return e.error("Expected 2 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,Ft),n=e.parse(t[2],2,Kt(e.expectedType||Ut));return r&&n?new or(n.type.itemType,r,n):null},or.prototype.evaluate=function(t){var e=this.index.evaluate(t),r=this.input.evaluate(t);if(e<0)throw new se("Array index out of bounds: "+e+" < 0.");if(e>=r.length)throw new se("Array index out of bounds: "+e+" > "+(r.length-1)+".");if(e!==Math.floor(e))throw new se("Array index must be an integer, but found "+e+" instead.");return r[e]},or.prototype.eachChild=function(t){t(this.index),t(this.input);},or.prototype.outputDefined=function(){return !1},or.prototype.serialize=function(){return ["at",this.index.serialize(),this.input.serialize()]};var sr=function(t,e){this.type=Lt,this.needle=t,this.haystack=e;};sr.parse=function(t,e){if(3!==t.length)return e.error("Expected 2 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);return r&&n?Jt(r.type,[Lt,Dt,Ft,Vt,Ut])?new sr(r,n):e.error("Expected first argument to be of type boolean, string, number or null, but found "+Gt(r.type)+" instead"):null},sr.prototype.evaluate=function(t){var e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!r)return !1;if(!Ht(e,["boolean","string","number","null"]))throw new se("Expected first argument to be of type boolean, string, number or null, but found "+Gt(ie(e))+" instead.");if(!Ht(r,["string","array"]))throw new se("Expected second argument to be of type array or string, but found "+Gt(ie(r))+" instead.");return r.indexOf(e)>=0},sr.prototype.eachChild=function(t){t(this.needle),t(this.haystack);},sr.prototype.outputDefined=function(){return !0},sr.prototype.serialize=function(){return ["in",this.needle.serialize(),this.haystack.serialize()]};var ur=function(t,e,r){this.type=Ft,this.needle=t,this.haystack=e,this.fromIndex=r;};ur.parse=function(t,e){if(t.length<=2||t.length>=5)return e.error("Expected 3 or 4 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);if(!r||!n)return null;if(!Jt(r.type,[Lt,Dt,Ft,Vt,Ut]))return e.error("Expected first argument to be of type boolean, string, number or null, but found "+Gt(r.type)+" instead");if(4===t.length){var i=e.parse(t[3],3,Ft);return i?new ur(r,n,i):null}return new ur(r,n)},ur.prototype.evaluate=function(t){var e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!Ht(e,["boolean","string","number","null"]))throw new se("Expected first argument to be of type boolean, string, number or null, but found "+Gt(ie(e))+" instead.");if(!Ht(r,["string","array"]))throw new se("Expected second argument to be of type array or string, but found "+Gt(ie(r))+" instead.");if(this.fromIndex){var n=this.fromIndex.evaluate(t);return r.indexOf(e,n)}return r.indexOf(e)},ur.prototype.eachChild=function(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex);},ur.prototype.outputDefined=function(){return !1},ur.prototype.serialize=function(){if(null!=this.fromIndex&&void 0!==this.fromIndex){var t=this.fromIndex.serialize();return ["index-of",this.needle.serialize(),this.haystack.serialize(),t]}return ["index-of",this.needle.serialize(),this.haystack.serialize()]};var lr=function(t,e,r,n,i,a){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=a;};lr.parse=function(t,e){if(t.length<5)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if(t.length%2!=1)return e.error("Expected an even number of arguments.");var r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);for(var i={},a=[],o=2;o<t.length-1;o+=2){var s=t[o],u=t[o+1];Array.isArray(s)||(s=[s]);var l=e.concat(o);if(0===s.length)return l.error("Expected at least one branch label.");for(var p=0,c=s;p<c.length;p+=1){var h=c[p];if("number"!=typeof h&&"string"!=typeof h)return l.error("Branch labels must be numbers or strings.");if("number"==typeof h&&Math.abs(h)>Number.MAX_SAFE_INTEGER)return l.error("Branch labels must be integers no larger than "+Number.MAX_SAFE_INTEGER+".");if("number"==typeof h&&Math.floor(h)!==h)return l.error("Numeric branch labels must be integer values.");if(r){if(l.checkSubtype(r,ie(h)))return null}else r=ie(h);if(void 0!==i[String(h)])return l.error("Branch labels must be unique.");i[String(h)]=a.length;}var f=e.parse(u,o,n);if(!f)return null;n=n||f.type,a.push(f);}var y=e.parse(t[1],1,Ut);if(!y)return null;var d=e.parse(t[t.length-1],t.length-1,n);return d?"value"!==y.type.kind&&e.concat(1).checkSubtype(r,y.type)?null:new lr(r,n,y,i,a,d):null},lr.prototype.evaluate=function(t){var e=this.input.evaluate(t);return (ie(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)},lr.prototype.eachChild=function(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);},lr.prototype.outputDefined=function(){return this.outputs.every((function(t){return t.outputDefined()}))&&this.otherwise.outputDefined()},lr.prototype.serialize=function(){for(var t=this,e=["match",this.input.serialize()],r=[],n={},i=0,a=Object.keys(this.cases).sort();i<a.length;i+=1){var o=a[i];void 0===(c=n[this.cases[o]])?(n[this.cases[o]]=r.length,r.push([this.cases[o],[o]])):r[c][1].push(o);}for(var s=function(e){return "number"===t.inputType.kind?Number(e):e},u=0,l=r;u<l.length;u+=1){var p=l[u],c=p[0],h=p[1];e.push(1===h.length?s(h[0]):h.map(s)),e.push(this.outputs[outputIndex$1].serialize());}return e.push(this.otherwise.serialize()),e};var pr=function(t,e,r){this.type=t,this.branches=e,this.otherwise=r;};pr.parse=function(t,e){if(t.length<4)return e.error("Expected at least 3 arguments, but found only "+(t.length-1)+".");if(t.length%2!=0)return e.error("Expected an odd number of arguments.");var r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);for(var n=[],i=1;i<t.length-1;i+=2){var a=e.parse(t[i],i,Lt);if(!a)return null;var o=e.parse(t[i+1],i+1,r);if(!o)return null;n.push([a,o]),r=r||o.type;}var s=e.parse(t[t.length-1],t.length-1,r);return s?new pr(r,n,s):null},pr.prototype.evaluate=function(t){for(var e=0,r=this.branches;e<r.length;e+=1){var n=r[e],i=n[1];if(n[0].evaluate(t))return i.evaluate(t)}return this.otherwise.evaluate(t)},pr.prototype.eachChild=function(t){for(var e=0,r=this.branches;e<r.length;e+=1){var n=r[e],i=n[1];t(n[0]),t(i);}t(this.otherwise);},pr.prototype.outputDefined=function(){return this.branches.every((function(t){return t[1].outputDefined()}))&&this.otherwise.outputDefined()},pr.prototype.serialize=function(){var t=["case"];return this.eachChild((function(e){t.push(e.serialize());})),t};var cr=function(t,e,r,n){this.type=t,this.input=e,this.beginIndex=r,this.endIndex=n;};function hr(t,e){return "=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function fr(t,e,r,n){return 0===n.compare(e,r)}function yr(t,e,r){var n="=="!==t&&"!="!==t;return function(){function i(t,e,r){this.type=Lt,this.lhs=t,this.rhs=e,this.collator=r,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind;}return i.parse=function(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");var r=t[0],a=e.parse(t[1],1,Ut);if(!a)return null;if(!hr(r,a.type))return e.concat(1).error('"'+r+"\" comparisons are not supported for type '"+Gt(a.type)+"'.");var o=e.parse(t[2],2,Ut);if(!o)return null;if(!hr(r,o.type))return e.concat(2).error('"'+r+"\" comparisons are not supported for type '"+Gt(o.type)+"'.");if(a.type.kind!==o.type.kind&&"value"!==a.type.kind&&"value"!==o.type.kind)return e.error("Cannot compare types '"+Gt(a.type)+"' and '"+Gt(o.type)+"'.");n&&("value"===a.type.kind&&"value"!==o.type.kind?a=new le(o.type,[a]):"value"!==a.type.kind&&"value"===o.type.kind&&(o=new le(a.type,[o])));var s=null;if(4===t.length){if("string"!==a.type.kind&&"string"!==o.type.kind&&"value"!==a.type.kind&&"value"!==o.type.kind)return e.error("Cannot use collator to compare non-string types.");if(!(s=e.parse(t[3],3,jt)))return null}return new i(a,o,s)},i.prototype.evaluate=function(i){var a=this.lhs.evaluate(i),o=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){var s=ie(a),u=ie(o);if(s.kind!==u.kind||"string"!==s.kind&&"number"!==s.kind)throw new se('Expected arguments for "'+t+'" to be (string, string) or (number, number), but found ('+s.kind+", "+u.kind+") instead.")}if(this.collator&&!n&&this.hasUntypedArgument){var l=ie(a),p=ie(o);if("string"!==l.kind||"string"!==p.kind)return e(i,a,o)}return this.collator?r(i,a,o,this.collator.evaluate(i)):e(i,a,o)},i.prototype.eachChild=function(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);},i.prototype.outputDefined=function(){return !0},i.prototype.serialize=function(){var e=[t];return this.eachChild((function(t){e.push(t.serialize());})),e},i}()}cr.parse=function(t,e){if(t.length<=2||t.length>=5)return e.error("Expected 3 or 4 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ft);if(!r||!n)return null;if(!Jt(r.type,[Kt(Ut),Dt,Ut]))return e.error("Expected first argument to be of type array or string, but found "+Gt(r.type)+" instead");if(4===t.length){var i=e.parse(t[3],3,Ft);return i?new cr(r.type,r,n,i):null}return new cr(r.type,r,n)},cr.prototype.evaluate=function(t){var e=this.input.evaluate(t),r=this.beginIndex.evaluate(t);if(!Ht(e,["string","array"]))throw new se("Expected first argument to be of type array or string, but found "+Gt(ie(e))+" instead.");if(this.endIndex){var n=this.endIndex.evaluate(t);return e.slice(r,n)}return e.slice(r)},cr.prototype.eachChild=function(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex);},cr.prototype.outputDefined=function(){return !1},cr.prototype.serialize=function(){if(null!=this.endIndex&&void 0!==this.endIndex){var t=this.endIndex.serialize();return ["slice",this.input.serialize(),this.beginIndex.serialize(),t]}return ["slice",this.input.serialize(),this.beginIndex.serialize()]};var dr=yr("==",(function(t,e,r){return e===r}),fr),mr=yr("!=",(function(t,e,r){return e!==r}),(function(t,e,r,n){return !fr(0,e,r,n)})),vr=yr("<",(function(t,e,r){return e<r}),(function(t,e,r,n){return n.compare(e,r)<0})),gr=yr(">",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),xr=yr("<=",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),br=yr(">=",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0})),wr=function(t,e,r,n,i){this.type=Dt,this.number=t,this.locale=e,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i;};wr.parse=function(t,e){if(3!==t.length)return e.error("Expected two arguments.");var r=e.parse(t[1],1,Ft);if(!r)return null;var n=t[2];if("object"!=typeof n||Array.isArray(n))return e.error("NumberFormat options argument must be an object.");var i=null;if(n.locale&&!(i=e.parse(n.locale,1,Dt)))return null;var a=null;if(n.currency&&!(a=e.parse(n.currency,1,Dt)))return null;var o=null;if(n["min-fraction-digits"]&&!(o=e.parse(n["min-fraction-digits"],1,Ft)))return null;var s=null;return n["max-fraction-digits"]&&!(s=e.parse(n["max-fraction-digits"],1,Ft))?null:new wr(r,i,a,o,s)},wr.prototype.evaluate=function(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))},wr.prototype.eachChild=function(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);},wr.prototype.outputDefined=function(){return !1},wr.prototype.serialize=function(){var t={};return this.locale&&(t.locale=this.locale.serialize()),this.currency&&(t.currency=this.currency.serialize()),this.minFractionDigits&&(t["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(t["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),t]};var _r=function(t){this.type=Ft,this.input=t;};_r.parse=function(t,e){if(2!==t.length)return e.error("Expected 1 argument, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error("Expected argument of type string or array, but found "+Gt(r.type)+" instead."):new _r(r):null},_r.prototype.evaluate=function(t){var e=this.input.evaluate(t);if("string"==typeof e)return e.length;if(Array.isArray(e))return e.length;throw new se("Expected value to be of type string or array, but found "+Gt(ie(e))+" instead.")},_r.prototype.eachChild=function(t){t(this.input);},_r.prototype.outputDefined=function(){return !1},_r.prototype.serialize=function(){var t=["length"];return this.eachChild((function(e){t.push(e.serialize());})),t};var Ar={"==":dr,"!=":mr,">":gr,"<":vr,">=":br,"<=":xr,array:le,at:or,boolean:le,case:pr,coalesce:ir,collator:ve,format:pe,image:ce,in:sr,"index-of":ur,interpolate:rr,"interpolate-hcl":rr,"interpolate-lab":rr,length:_r,let:ar,literal:oe,match:lr,number:le,"number-format":wr,object:le,slice:cr,step:Ue,string:le,"to-boolean":fe,"to-color":fe,"to-number":fe,"to-string":fe,var:Le,within:Be};function Sr(t,e){var r=e[0],n=e[1],i=e[2],a=e[3];r=r.evaluate(t),n=n.evaluate(t),i=i.evaluate(t);var o=a?a.evaluate(t):1,s=re(r,n,i,o);if(s)throw new se(s);return new $t(r/255*o,n/255*o,i/255*o,o)}function kr(t,e){return t in e}function Ir(t,e){var r=e[t];return void 0===r?null:r}function zr(t){return {type:t}}function Cr(t){return {result:"success",value:t}}function Mr(t){return {result:"error",value:t}}function Er(t){return "data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function Tr(t){return !!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function Pr(t){return !!t.expression&&t.expression.interpolated}function Br(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function Vr(t){return "object"==typeof t&&null!==t&&!Array.isArray(t)}function Fr(t){return t}function Dr(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function Lr(t,e,r,n,i){return Dr(typeof r===i?n[r]:void 0,t.default,e.default)}function Rr(t,e,r){if("number"!==Br(r))return Dr(t.default,e.default);var n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];var i=Oe(t.stops.map((function(t){return t[0]})),r);return t.stops[i][1]}function Or(t,e,r){var n=void 0!==t.base?t.base:1;if("number"!==Br(r))return Dr(t.default,e.default);var i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];var a=Oe(t.stops.map((function(t){return t[0]})),r),o=function(t,e,r,n){var i=n-r,a=t-r;return 0===i?0:1===e?a/i:(Math.pow(e,a)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[a][0],t.stops[a+1][0]),s=t.stops[a][1],u=t.stops[a+1][1],l=qe[e.type]||Fr;if(t.colorSpace&&"rgb"!==t.colorSpace){var p=er[t.colorSpace];l=function(t,e){return p.reverse(p.interpolate(p.forward(t),p.forward(e),o))};}return "function"==typeof s.evaluate?{evaluate:function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];var r=s.evaluate.apply(void 0,t),n=u.evaluate.apply(void 0,t);if(void 0!==r&&void 0!==n)return l(r,n,o)}}:l(s,u,o)}function Ur(t,e,r){return "color"===e.type?r=$t.parse(r):"formatted"===e.type?r=te.fromString(r.toString()):"resolvedImage"===e.type?r=ee.fromString(r.toString()):Br(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0),Dr(r,t.default,e.default)}me.register(Ar,{error:[{kind:"error"},[Dt],function(t,e){throw new se(e[0].evaluate(t))}],typeof:[Dt,[Ut],function(t,e){return Gt(ie(e[0].evaluate(t)))}],"to-rgba":[Kt(Ft,4),[Rt],function(t,e){return e[0].evaluate(t).toArray()}],rgb:[Rt,[Ft,Ft,Ft],Sr],rgba:[Rt,[Ft,Ft,Ft,Ft],Sr],has:{type:Lt,overloads:[[[Dt],function(t,e){return kr(e[0].evaluate(t),t.properties())}],[[Dt,Ot],function(t,e){var r=e[1];return kr(e[0].evaluate(t),r.evaluate(t))}]]},get:{type:Ut,overloads:[[[Dt],function(t,e){return Ir(e[0].evaluate(t),t.properties())}],[[Dt,Ot],function(t,e){var r=e[1];return Ir(e[0].evaluate(t),r.evaluate(t))}]]},"feature-state":[Ut,[Dt],function(t,e){return Ir(e[0].evaluate(t),t.featureState||{})}],properties:[Ot,[],function(t){return t.properties()}],"geometry-type":[Dt,[],function(t){return t.geometryType()}],id:[Ut,[],function(t){return t.id()}],zoom:[Ft,[],function(t){return t.globals.zoom}],"heatmap-density":[Ft,[],function(t){return t.globals.heatmapDensity||0}],"line-progress":[Ft,[],function(t){return t.globals.lineProgress||0}],accumulated:[Ut,[],function(t){return void 0===t.globals.accumulated?null:t.globals.accumulated}],"+":[Ft,zr(Ft),function(t,e){for(var r=0,n=0,i=e;n<i.length;n+=1)r+=i[n].evaluate(t);return r}],"*":[Ft,zr(Ft),function(t,e){for(var r=1,n=0,i=e;n<i.length;n+=1)r*=i[n].evaluate(t);return r}],"-":{type:Ft,overloads:[[[Ft,Ft],function(t,e){var r=e[1];return e[0].evaluate(t)-r.evaluate(t)}],[[Ft],function(t,e){return -e[0].evaluate(t)}]]},"/":[Ft,[Ft,Ft],function(t,e){var r=e[1];return e[0].evaluate(t)/r.evaluate(t)}],"%":[Ft,[Ft,Ft],function(t,e){var r=e[1];return e[0].evaluate(t)%r.evaluate(t)}],ln2:[Ft,[],function(){return Math.LN2}],pi:[Ft,[],function(){return Math.PI}],e:[Ft,[],function(){return Math.E}],"^":[Ft,[Ft,Ft],function(t,e){var r=e[1];return Math.pow(e[0].evaluate(t),r.evaluate(t))}],sqrt:[Ft,[Ft],function(t,e){return Math.sqrt(e[0].evaluate(t))}],log10:[Ft,[Ft],function(t,e){return Math.log(e[0].evaluate(t))/Math.LN10}],ln:[Ft,[Ft],function(t,e){return Math.log(e[0].evaluate(t))}],log2:[Ft,[Ft],function(t,e){return Math.log(e[0].evaluate(t))/Math.LN2}],sin:[Ft,[Ft],function(t,e){return Math.sin(e[0].evaluate(t))}],cos:[Ft,[Ft],function(t,e){return Math.cos(e[0].evaluate(t))}],tan:[Ft,[Ft],function(t,e){return Math.tan(e[0].evaluate(t))}],asin:[Ft,[Ft],function(t,e){return Math.asin(e[0].evaluate(t))}],acos:[Ft,[Ft],function(t,e){return Math.acos(e[0].evaluate(t))}],atan:[Ft,[Ft],function(t,e){return Math.atan(e[0].evaluate(t))}],min:[Ft,zr(Ft),function(t,e){return Math.min.apply(Math,e.map((function(e){return e.evaluate(t)})))}],max:[Ft,zr(Ft),function(t,e){return Math.max.apply(Math,e.map((function(e){return e.evaluate(t)})))}],abs:[Ft,[Ft],function(t,e){return Math.abs(e[0].evaluate(t))}],round:[Ft,[Ft],function(t,e){var r=e[0].evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[Ft,[Ft],function(t,e){return Math.floor(e[0].evaluate(t))}],ceil:[Ft,[Ft],function(t,e){return Math.ceil(e[0].evaluate(t))}],"filter-==":[Lt,[Dt,Ut],function(t,e){var r=e[0],n=e[1];return t.properties()[r.value]===n.value}],"filter-id-==":[Lt,[Ut],function(t,e){var r=e[0];return t.id()===r.value}],"filter-type-==":[Lt,[Dt],function(t,e){var r=e[0];return t.geometryType()===r.value}],"filter-<":[Lt,[Dt,Ut],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i<a}],"filter-id-<":[Lt,[Ut],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<i}],"filter->":[Lt,[Dt,Ut],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>a}],"filter-id->":[Lt,[Ut],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>i}],"filter-<=":[Lt,[Dt,Ut],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i<=a}],"filter-id-<=":[Lt,[Ut],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<=i}],"filter->=":[Lt,[Dt,Ut],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>=a}],"filter-id->=":[Lt,[Ut],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>=i}],"filter-has":[Lt,[Ut],function(t,e){return e[0].value in t.properties()}],"filter-has-id":[Lt,[],function(t){return null!==t.id()&&void 0!==t.id()}],"filter-type-in":[Lt,[Kt(Dt)],function(t,e){return e[0].value.indexOf(t.geometryType())>=0}],"filter-id-in":[Lt,[Kt(Ut)],function(t,e){return e[0].value.indexOf(t.id())>=0}],"filter-in-small":[Lt,[Dt,Kt(Ut)],function(t,e){var r=e[0];return e[1].value.indexOf(t.properties()[r.value])>=0}],"filter-in-large":[Lt,[Dt,Kt(Ut)],function(t,e){var r=e[0],n=e[1];return function(t,e,r,n){for(;r<=n;){var i=r+n>>1;if(e[i]===t)return !0;e[i]>t?n=i-1:r=i+1;}return !1}(t.properties()[r.value],n.value,0,n.value.length-1)}],all:{type:Lt,overloads:[[[Lt,Lt],function(t,e){var r=e[1];return e[0].evaluate(t)&&r.evaluate(t)}],[zr(Lt),function(t,e){for(var r=0,n=e;r<n.length;r+=1)if(!n[r].evaluate(t))return !1;return !0}]]},any:{type:Lt,overloads:[[[Lt,Lt],function(t,e){var r=e[1];return e[0].evaluate(t)||r.evaluate(t)}],[zr(Lt),function(t,e){for(var r=0,n=e;r<n.length;r+=1)if(n[r].evaluate(t))return !0;return !1}]]},"!":[Lt,[Lt],function(t,e){return !e[0].evaluate(t)}],"is-supported-script":[Lt,[Dt],function(t,e){var r=t.globals&&t.globals.isSupportedScript;return !r||r(e[0].evaluate(t))}],upcase:[Dt,[Dt],function(t,e){return e[0].evaluate(t).toUpperCase()}],downcase:[Dt,[Dt],function(t,e){return e[0].evaluate(t).toLowerCase()}],concat:[Dt,zr(Ut),function(t,e){return e.map((function(e){return ae(e.evaluate(t))})).join("")}],"resolved-locale":[Dt,[jt],function(t,e){return e[0].evaluate(t).resolvedLocale()}]});var jr=function(t,e){this.expression=t,this._warningHistory={},this._evaluator=new de,this._defaultValue=e?function(t){return "color"===t.type&&Vr(t.default)?new $t(0,0,0,0):"color"===t.type?$t.parse(t.default)||null:void 0===t.default?null:t.default}(e):null,this._enumValues=e&&"enum"===e.type?e.values:null;};function qr(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in Ar}function Nr(t,e){var r=new Re(Ar,[],e?function(t){var e={color:Rt,string:Dt,number:Ft,enum:Dt,boolean:Lt,formatted:qt,resolvedImage:Nt};return "array"===t.type?Kt(e[t.value]||Ut,t.length):e[t.type]}(e):void 0),n=r.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return n?Cr(new jr(n,e)):Mr(r.errors)}jr.prototype.evaluateWithoutErrorHandling=function(t,e,r,n,i,a){return this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=a,this.expression.evaluate(this._evaluator)},jr.prototype.evaluate=function(t,e,r,n,i,a){this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=a||null;try{var o=this.expression.evaluate(this._evaluator);if(null==o||"number"==typeof o&&o!=o)return this._defaultValue;if(this._enumValues&&!(o in this._enumValues))throw new se("Expected value to be one of "+Object.keys(this._enumValues).map((function(t){return JSON.stringify(t)})).join(", ")+", but found "+JSON.stringify(o)+" instead.");return o}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}};var Kr=function(t,e){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!Fe(e.expression);};Kr.prototype.evaluateWithoutErrorHandling=function(t,e,r,n,i,a){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,a)},Kr.prototype.evaluate=function(t,e,r,n,i,a){return this._styleExpression.evaluate(t,e,r,n,i,a)};var Gr=function(t,e,r,n){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent="camera"!==t&&!Fe(e.expression),this.interpolationType=n;};function Zr(t,e){if("error"===(t=Nr(t,e)).result)return t;var r=t.value.expression,n=Ve(r);if(!n&&!Er(e))return Mr([new Pt("","data expressions not supported")]);var i=De(r,["zoom"]);if(!i&&!Tr(e))return Mr([new Pt("","zoom expressions not supported")]);var a=function t(e){var r=null;if(e instanceof ar)r=t(e.result);else if(e instanceof ir)for(var n=0,i=e.args;n<i.length&&!(r=t(i[n]));n+=1);else (e instanceof Ue||e instanceof rr)&&e.input instanceof me&&"zoom"===e.input.name&&(r=e);return r instanceof Pt||e.eachChild((function(e){var n=t(e);n instanceof Pt?r=n:!r&&n?r=new Pt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):r&&n&&r!==n&&(r=new Pt("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));})),r}(r);return a||i?a instanceof Pt?Mr([a]):a instanceof rr&&!Pr(e)?Mr([new Pt("",'"interpolate" expressions cannot be used with this property')]):Cr(a?new Gr(n?"camera":"composite",t.value,a.labels,a instanceof rr?a.interpolation:void 0):new Kr(n?"constant":"source",t.value)):Mr([new Pt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}Gr.prototype.evaluateWithoutErrorHandling=function(t,e,r,n,i,a){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,a)},Gr.prototype.evaluate=function(t,e,r,n,i,a){return this._styleExpression.evaluate(t,e,r,n,i,a)},Gr.prototype.interpolationFactor=function(t,e,r){return this.interpolationType?rr.interpolationFactor(this.interpolationType,t,e,r):0};var Xr=function(t,e){this._parameters=t,this._specification=e,Mt(this,function t(e,r){var n,i,a,o="color"===r.type,s=e.stops&&"object"==typeof e.stops[0][0],u=s||!(s||void 0!==e.property),l=e.type||(Pr(r)?"exponential":"interval");if(o&&((e=Mt({},e)).stops&&(e.stops=e.stops.map((function(t){return [t[0],$t.parse(t[1])]}))),e.default=$t.parse(e.default?e.default:r.default)),e.colorSpace&&"rgb"!==e.colorSpace&&!er[e.colorSpace])throw new Error("Unknown color space: "+e.colorSpace);if("exponential"===l)n=Or;else if("interval"===l)n=Rr;else if("categorical"===l){n=Lr,i=Object.create(null);for(var p=0,c=e.stops;p<c.length;p+=1){var h=c[p];i[h[0]]=h[1];}a=typeof e.stops[0][0];}else {if("identity"!==l)throw new Error('Unknown function type "'+l+'"');n=Ur;}if(s){for(var f={},y=[],d=0;d<e.stops.length;d++){var m=e.stops[d],v=m[0].zoom;void 0===f[v]&&(f[v]={zoom:v,type:e.type,property:e.property,default:e.default,stops:[]},y.push(v)),f[v].stops.push([m[0].value,m[1]]);}for(var g=[],x=0,b=y;x<b.length;x+=1){var w=b[x];g.push([f[w].zoom,t(f[w],r)]);}var _={name:"linear"};return {kind:"composite",interpolationType:_,interpolationFactor:rr.interpolationFactor.bind(void 0,_),zoomStops:g.map((function(t){return t[0]})),evaluate:function(t,n){var i=t.zoom;return Or({stops:g,base:e.base},r,i).evaluate(i,n)}}}if(u){var A="exponential"===l?{name:"exponential",base:void 0!==e.base?e.base:1}:null;return {kind:"camera",interpolationType:A,interpolationFactor:rr.interpolationFactor.bind(void 0,A),zoomStops:e.stops.map((function(t){return t[0]})),evaluate:function(t){return n(e,r,t.zoom,i,a)}}}return {kind:"source",evaluate:function(t,o){var s=o&&o.properties?o.properties[e.property]:void 0;return void 0===s?Dr(e.default,r.default):n(e,r,s,i,a)}}}(this._parameters,this._specification));};function Jr(t){var e=t.key,r=t.value,n=t.valueSpec||{},i=t.objectElementValidators||{},a=t.style,o=t.styleSpec,s=[],u=Br(r);if("object"!==u)return [new zt(e,r,"object expected, "+u+" found")];for(var l in r){var p=l.split(".")[0],c=n[p]||n["*"],h=void 0;if(i[p])h=i[p];else if(n[p])h=bn;else if(i["*"])h=i["*"];else {if(!n["*"]){s.push(new zt(e,r[l],'unknown property "'+l+'"'));continue}h=bn;}s=s.concat(h({key:(e?e+".":e)+l,value:r[l],valueSpec:c,style:a,styleSpec:o,object:r,objectKey:l},r));}for(var f in n)i[f]||n[f].required&&void 0===n[f].default&&void 0===r[f]&&s.push(new zt(e,r,'missing required property "'+f+'"'));return s}function Hr(t){var e=t.value,r=t.valueSpec,n=t.style,i=t.styleSpec,a=t.key,o=t.arrayElementValidator||bn;if("array"!==Br(e))return [new zt(a,e,"array expected, "+Br(e)+" found")];if(r.length&&e.length!==r.length)return [new zt(a,e,"array length "+r.length+" expected, length "+e.length+" found")];if(r["min-length"]&&e.length<r["min-length"])return [new zt(a,e,"array length at least "+r["min-length"]+" expected, length "+e.length+" found")];var s={type:r.value,values:r.values};i.$version<7&&(s.function=r.function),"object"===Br(r.value)&&(s=r.value);for(var u=[],l=0;l<e.length;l++)u=u.concat(o({array:e,arrayIndex:l,value:e[l],valueSpec:s,style:n,styleSpec:i,key:a+"["+l+"]"}));return u}function Yr(t){var e=t.key,r=t.value,n=t.valueSpec,i=Br(r);return "number"===i&&r!=r&&(i="NaN"),"number"!==i?[new zt(e,r,"number expected, "+i+" found")]:"minimum"in n&&r<n.minimum?[new zt(e,r,r+" is less than the minimum value "+n.minimum)]:"maximum"in n&&r>n.maximum?[new zt(e,r,r+" is greater than the maximum value "+n.maximum)]:[]}function $r(t){var e,r,n,i=t.valueSpec,a=Et(t.value.type),o={},s="categorical"!==a&&void 0===t.value.property,u=!s,l="array"===Br(t.value.stops)&&"array"===Br(t.value.stops[0])&&"object"===Br(t.value.stops[0][0]),p=Jr({key:t.key,value:t.value,valueSpec:t.styleSpec.function,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===a)return [new zt(t.key,t.value,'identity function may not have a "stops" property')];var e=[],r=t.value;return e=e.concat(Hr({key:t.key,value:r,valueSpec:t.valueSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:c})),"array"===Br(r)&&0===r.length&&e.push(new zt(t.key,r,"array must have at least one stop")),e},default:function(t){return bn({key:t.key,value:t.value,valueSpec:i,style:t.style,styleSpec:t.styleSpec})}}});return "identity"===a&&s&&p.push(new zt(t.key,t.value,'missing required property "property"')),"identity"===a||t.value.stops||p.push(new zt(t.key,t.value,'missing required property "stops"')),"exponential"===a&&t.valueSpec.expression&&!Pr(t.valueSpec)&&p.push(new zt(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(u&&!Er(t.valueSpec)?p.push(new zt(t.key,t.value,"property functions not supported")):s&&!Tr(t.valueSpec)&&p.push(new zt(t.key,t.value,"zoom functions not supported"))),"categorical"!==a&&!l||void 0!==t.value.property||p.push(new zt(t.key,t.value,'"property" property is required')),p;function c(t){var e=[],a=t.value,s=t.key;if("array"!==Br(a))return [new zt(s,a,"array expected, "+Br(a)+" found")];if(2!==a.length)return [new zt(s,a,"array length 2 expected, length "+a.length+" found")];if(l){if("object"!==Br(a[0]))return [new zt(s,a,"object expected, "+Br(a[0])+" found")];if(void 0===a[0].zoom)return [new zt(s,a,"object stop key must have zoom")];if(void 0===a[0].value)return [new zt(s,a,"object stop key must have value")];if(n&&n>Et(a[0].zoom))return [new zt(s,a[0].zoom,"stop zoom values must appear in ascending order")];Et(a[0].zoom)!==n&&(n=Et(a[0].zoom),r=void 0,o={}),e=e.concat(Jr({key:s+"[0]",value:a[0],valueSpec:{zoom:{}},style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:Yr,value:h}}));}else e=e.concat(h({key:s+"[0]",value:a[0],valueSpec:{},style:t.style,styleSpec:t.styleSpec},a));return qr(Tt(a[1]))?e.concat([new zt(s+"[1]",a[1],"expressions are not allowed in function stops.")]):e.concat(bn({key:s+"[1]",value:a[1],valueSpec:i,style:t.style,styleSpec:t.styleSpec}))}function h(t,n){var s=Br(t.value),u=Et(t.value),l=null!==t.value?t.value:n;if(e){if(s!==e)return [new zt(t.key,l,s+" stop domain type must match previous stop domain type "+e)]}else e=s;if("number"!==s&&"string"!==s&&"boolean"!==s)return [new zt(t.key,l,"stop domain value must be a number, string, or boolean")];if("number"!==s&&"categorical"!==a){var p="number expected, "+s+" found";return Er(i)&&void 0===a&&(p+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new zt(t.key,l,p)]}return "categorical"!==a||"number"!==s||isFinite(u)&&Math.floor(u)===u?"categorical"!==a&&"number"===s&&void 0!==r&&u<r?[new zt(t.key,l,"stop domain values must appear in ascending order")]:(r=u,"categorical"===a&&u in o?[new zt(t.key,l,"stop domain values must be unique")]:(o[u]=!0,[])):[new zt(t.key,l,"integer expected, found "+u)]}}function Wr(t){var e=("property"===t.expressionContext?Zr:Nr)(Tt(t.value),t.valueSpec);if("error"===e.result)return e.value.map((function(e){return new zt(""+t.key+e.key,t.value,e.message)}));var r=e.value.expression||e.value._styleExpression.expression;if("property"===t.expressionContext&&"text-font"===t.propertyKey&&!r.outputDefined())return [new zt(t.key,t.value,'Invalid data expression for "'+t.propertyKey+'". Output values must be contained as literals within the expression.')];if("property"===t.expressionContext&&"layout"===t.propertyType&&!Fe(r))return [new zt(t.key,t.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===t.expressionContext&&!Fe(r))return [new zt(t.key,t.value,'"feature-state" data expressions are not supported with filters.')];if(t.expressionContext&&0===t.expressionContext.indexOf("cluster")){if(!De(r,["zoom","feature-state"]))return [new zt(t.key,t.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===t.expressionContext&&!Ve(r))return [new zt(t.key,t.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return []}function Qr(t){var e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(Et(r))&&i.push(new zt(e,r,"expected one of ["+n.values.join(", ")+"], "+JSON.stringify(r)+" found")):-1===Object.keys(n.values).indexOf(Et(r))&&i.push(new zt(e,r,"expected one of ["+Object.keys(n.values).join(", ")+"], "+JSON.stringify(r)+" found")),i}function tn(t){if(!0===t||!1===t)return !0;if(!Array.isArray(t)||0===t.length)return !1;switch(t[0]){case"has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case"!in":case"!has":case"none":return !1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case"any":case"all":for(var e=0,r=t.slice(1);e<r.length;e+=1){var n=r[e];if(!tn(n)&&"boolean"!=typeof n)return !1}return !0;default:return !0}}Xr.deserialize=function(t){return new Xr(t._parameters,t._specification)},Xr.serialize=function(t){return {_parameters:t._parameters,_specification:t._specification}};var en={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function rn(t){if(null==t)return {filter:function(){return !0},needGeometry:!1};tn(t)||(t=an(t));var e=Nr(t,en);if("error"===e.result)throw new Error(e.value.map((function(t){return t.key+": "+t.message})).join(", "));return {filter:function(t,r,n){return e.value.evaluate(t,r,{},n)},needGeometry:function t(e){if(!Array.isArray(e))return !1;if("within"===e[0])return !0;for(var r=1;r<e.length;r++)if(t(e[r]))return !0;return !1}(t)}}function nn(t,e){return t<e?-1:t>e?1:0}function an(t){if(!t)return !0;var e,r=t[0];return t.length<=1?"any"!==r:"=="===r?on(t[1],t[2],"=="):"!="===r?ln(on(t[1],t[2],"==")):"<"===r||">"===r||"<="===r||">="===r?on(t[1],t[2],r):"any"===r?(e=t.slice(1),["any"].concat(e.map(an))):"all"===r?["all"].concat(t.slice(1).map(an)):"none"===r?["all"].concat(t.slice(1).map(an).map(ln)):"in"===r?sn(t[1],t.slice(2)):"!in"===r?ln(sn(t[1],t.slice(2))):"has"===r?un(t[1]):"!has"===r?ln(un(t[1])):"within"!==r||t}function on(t,e,r){switch(t){case"$type":return ["filter-type-"+r,e];case"$id":return ["filter-id-"+r,e];default:return ["filter-"+r,t,e]}}function sn(t,e){if(0===e.length)return !1;switch(t){case"$type":return ["filter-type-in",["literal",e]];case"$id":return ["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((function(t){return typeof t!=typeof e[0]}))?["filter-in-large",t,["literal",e.sort(nn)]]:["filter-in-small",t,["literal",e]]}}function un(t){switch(t){case"$type":return !0;case"$id":return ["filter-has-id"];default:return ["filter-has",t]}}function ln(t){return ["!",t]}function pn(t){return tn(Tt(t.value))?Wr(Mt({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):function t(e){var r=e.value,n=e.key;if("array"!==Br(r))return [new zt(n,r,"array expected, "+Br(r)+" found")];var i,a=e.styleSpec,o=[];if(r.length<1)return [new zt(n,r,"filter array must have at least 1 element")];switch(o=o.concat(Qr({key:n+"[0]",value:r[0],valueSpec:a.filter_operator,style:e.style,styleSpec:e.styleSpec})),Et(r[0])){case"<":case"<=":case">":case">=":r.length>=2&&"$type"===Et(r[1])&&o.push(new zt(n,r,'"$type" cannot be use with operator "'+r[0]+'"'));case"==":case"!=":3!==r.length&&o.push(new zt(n,r,'filter array for operator "'+r[0]+'" must have 3 elements'));case"in":case"!in":r.length>=2&&"string"!==(i=Br(r[1]))&&o.push(new zt(n+"[1]",r[1],"string expected, "+i+" found"));for(var s=2;s<r.length;s++)i=Br(r[s]),"$type"===Et(r[1])?o=o.concat(Qr({key:n+"["+s+"]",value:r[s],valueSpec:a.geometry_type,style:e.style,styleSpec:e.styleSpec})):"string"!==i&&"number"!==i&&"boolean"!==i&&o.push(new zt(n+"["+s+"]",r[s],"string, number, or boolean expected, "+i+" found"));break;case"any":case"all":case"none":for(var u=1;u<r.length;u++)o=o.concat(t({key:n+"["+u+"]",value:r[u],style:e.style,styleSpec:e.styleSpec}));break;case"has":case"!has":i=Br(r[1]),2!==r.length?o.push(new zt(n,r,'filter array for "'+r[0]+'" operator must have 2 elements')):"string"!==i&&o.push(new zt(n+"[1]",r[1],"string expected, "+i+" found"));break;case"within":i=Br(r[1]),2!==r.length?o.push(new zt(n,r,'filter array for "'+r[0]+'" operator must have 2 elements')):"object"!==i&&o.push(new zt(n+"[1]",r[1],"object expected, "+i+" found"));}return o}(t)}function cn(t,e){var r=t.key,n=t.style,i=t.styleSpec,a=t.value,o=t.objectKey,s=i[e+"_"+t.layerType];if(!s)return [];var u=o.match(/^(.*)-transition$/);if("paint"===e&&u&&s[u[1]]&&s[u[1]].transition)return bn({key:r,value:a,valueSpec:i.transition,style:n,styleSpec:i});var l,p=t.valueSpec||s[o];if(!p)return [new zt(r,a,'unknown property "'+o+'"')];if("string"===Br(a)&&Er(p)&&!p.tokens&&(l=/^{([^}]+)}$/.exec(a)))return [new zt(r,a,'"'+o+'" does not support interpolation syntax\nUse an identity property function instead: `{ "type": "identity", "property": '+JSON.stringify(l[1])+" }`.")];var c=[];return "symbol"===t.layerType&&("text-field"===o&&n&&!n.glyphs&&c.push(new zt(r,a,'use of "text-field" requires a style "glyphs" property')),"text-font"===o&&Vr(Tt(a))&&"identity"===Et(a.type)&&c.push(new zt(r,a,'"text-font" does not support identity functions'))),c.concat(bn({key:t.key,value:a,valueSpec:p,style:n,styleSpec:i,expressionContext:"property",propertyType:e,propertyKey:o}))}function hn(t){return cn(t,"paint")}function fn(t){return cn(t,"layout")}function yn(t){var e=[],r=t.value,n=t.key,i=t.style,a=t.styleSpec;r.type||r.ref||e.push(new zt(n,r,'either "type" or "ref" is required'));var o,s=Et(r.type),u=Et(r.ref);if(r.id)for(var l=Et(r.id),p=0;p<t.arrayIndex;p++){var c=i.layers[p];Et(c.id)===l&&e.push(new zt(n,r.id,'duplicate layer id "'+r.id+'", previously used at line '+c.id.__line__));}if("ref"in r)["type","source","source-layer","filter","layout"].forEach((function(t){t in r&&e.push(new zt(n,r[t],'"'+t+'" is prohibited for ref layers'));})),i.layers.forEach((function(t){Et(t.id)===u&&(o=t);})),o?o.ref?e.push(new zt(n,r.ref,"ref cannot reference another ref layer")):s=Et(o.type):e.push(new zt(n,r.ref,'ref layer "'+u+'" not found'));else if("background"!==s)if(r.source){var h=i.sources&&i.sources[r.source],f=h&&Et(h.type);h?"vector"===f&&"raster"===s?e.push(new zt(n,r.source,'layer "'+r.id+'" requires a raster source')):"raster"===f&&"raster"!==s?e.push(new zt(n,r.source,'layer "'+r.id+'" requires a vector source')):"vector"!==f||r["source-layer"]?"raster-dem"===f&&"hillshade"!==s?e.push(new zt(n,r.source,"raster-dem source can only be used with layer type 'hillshade'.")):"line"!==s||!r.paint||!r.paint["line-gradient"]||"geojson"===f&&h.lineMetrics||e.push(new zt(n,r,'layer "'+r.id+'" specifies a line-gradient, which requires a GeoJSON source with `lineMetrics` enabled.')):e.push(new zt(n,r,'layer "'+r.id+'" must specify a "source-layer"')):e.push(new zt(n,r.source,'source "'+r.source+'" not found'));}else e.push(new zt(n,r,'missing required property "source"'));return e=e.concat(Jr({key:n,value:r,valueSpec:a.layer,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(){return []},type:function(){return bn({key:n+".type",value:r.type,valueSpec:a.layer.type,style:t.style,styleSpec:t.styleSpec,object:r,objectKey:"type"})},filter:pn,layout:function(t){return Jr({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(t){return fn(Mt({layerType:s},t))}}})},paint:function(t){return Jr({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{"*":function(t){return hn(Mt({layerType:s},t))}}})}}}))}function dn(t){var e=t.value,r=t.key,n=Br(e);return "string"!==n?[new zt(r,e,"string expected, "+n+" found")]:[]}var mn={promoteId:function(t){var e=t.key,r=t.value;if("string"===Br(r))return dn({key:e,value:r});var n=[];for(var i in r)n.push.apply(n,dn({key:e+"."+i,value:r[i]}));return n}};function vn(t){var e=t.value,r=t.key,n=t.styleSpec,i=t.style;if(!e.type)return [new zt(r,e,'"type" is required')];var a,o=Et(e.type);switch(o){case"vector":case"raster":case"raster-dem":return Jr({key:r,value:e,valueSpec:n["source_"+o.replace("-","_")],style:t.style,styleSpec:n,objectElementValidators:mn});case"geojson":if(a=Jr({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n,objectElementValidators:mn}),e.cluster)for(var s in e.clusterProperties){var u=e.clusterProperties[s],l=u[0],p="string"==typeof l?[l,["accumulated"],["get",s]]:l;a.push.apply(a,Wr({key:r+"."+s+".map",value:u[1],expressionContext:"cluster-map"})),a.push.apply(a,Wr({key:r+"."+s+".reduce",value:p,expressionContext:"cluster-reduce"}));}return a;case"video":return Jr({key:r,value:e,valueSpec:n.source_video,style:i,styleSpec:n});case"image":return Jr({key:r,value:e,valueSpec:n.source_image,style:i,styleSpec:n});case"canvas":return [new zt(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Qr({key:r+".type",value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]},style:i,styleSpec:n})}}function gn(t){var e=t.value,r=t.styleSpec,n=r.light,i=t.style,a=[],o=Br(e);if(void 0===e)return a;if("object"!==o)return a.concat([new zt("light",e,"object expected, "+o+" found")]);for(var s in e){var u=s.match(/^(.*)-transition$/);a=a.concat(u&&n[u[1]]&&n[u[1]].transition?bn({key:s,value:e[s],valueSpec:r.transition,style:i,styleSpec:r}):n[s]?bn({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new zt(s,e[s],'unknown property "'+s+'"')]);}return a}var xn={"*":function(){return []},array:Hr,boolean:function(t){var e=t.value,r=t.key,n=Br(e);return "boolean"!==n?[new zt(r,e,"boolean expected, "+n+" found")]:[]},number:Yr,color:function(t){var e=t.key,r=t.value,n=Br(r);return "string"!==n?[new zt(e,r,"color expected, "+n+" found")]:null===Yt(r)?[new zt(e,r,'color expected, "'+r+'" found')]:[]},constants:Ct,enum:Qr,filter:pn,function:$r,layer:yn,object:Jr,source:vn,light:gn,string:dn,formatted:function(t){return 0===dn(t).length?[]:Wr(t)},resolvedImage:function(t){return 0===dn(t).length?[]:Wr(t)}};function bn(t){var e=t.value,r=t.valueSpec,n=t.styleSpec;return r.expression&&Vr(Et(e))?$r(t):r.expression&&qr(Tt(e))?Wr(t):r.type&&xn[r.type]?xn[r.type](t):Jr(Mt({},t,{valueSpec:r.type?n[r.type]:r}))}function wn(t){var e=t.value,r=t.key,n=dn(t);return n.length||(-1===e.indexOf("{fontstack}")&&n.push(new zt(r,e,'"glyphs" url must include a "{fontstack}" token')),-1===e.indexOf("{range}")&&n.push(new zt(r,e,'"glyphs" url must include a "{range}" token'))),n}function _n(t,e){void 0===e&&(e=It);var r=[];return r=r.concat(bn({key:"",value:t,valueSpec:e.$root,styleSpec:e,style:t,objectElementValidators:{glyphs:wn,"*":function(){return []}}})),t.constants&&(r=r.concat(Ct({key:"constants",value:t.constants,style:t,styleSpec:e}))),An(r)}function An(t){return [].concat(t).sort((function(t,e){return t.line-e.line}))}function Sn(t){return function(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];return An(t.apply(this,e))}}_n.source=Sn(vn),_n.light=Sn(gn),_n.layer=Sn(yn),_n.filter=Sn(pn),_n.paintProperty=Sn(hn),_n.layoutProperty=Sn(fn);var kn=_n,In=kn.light,zn=kn.paintProperty,Cn=kn.layoutProperty;function Mn(t,e){var r=!1;if(e&&e.length)for(var n=0,i=e;n<i.length;n+=1)t.fire(new St(new Error(i[n].message))),r=!0;return r}var En=Tn;function Tn(t,e,r){var n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;var i=new Int32Array(this.arrayBuffer);t=i[0],this.d=(e=i[1])+2*(r=i[2]);for(var a=0;a<this.d*this.d;a++){var o=i[3+a],s=i[3+a+1];n.push(o===s?null:i.subarray(o,s));}var u=i[3+n.length+1];this.keys=i.subarray(i[3+n.length],u),this.bboxes=i.subarray(u),this.insert=this._insertReadonly;}else {this.d=e+2*r;for(var l=0;l<this.d*this.d;l++)n.push([]);this.keys=[],this.bboxes=[];}this.n=e,this.extent=t,this.padding=r,this.scale=e/t,this.uid=0;var p=r/e*t;this.min=-p,this.max=t+p;}Tn.prototype.insert=function(t,e,r,n,i){this._forEachCell(e,r,n,i,this._insertCell,this.uid++),this.keys.push(t),this.bboxes.push(e),this.bboxes.push(r),this.bboxes.push(n),this.bboxes.push(i);},Tn.prototype._insertReadonly=function(){throw "Cannot insert into a GridIndex created from an ArrayBuffer."},Tn.prototype._insertCell=function(t,e,r,n,i,a){this.cells[i].push(a);},Tn.prototype.query=function(t,e,r,n,i){var a=this.min,o=this.max;if(t<=a&&e<=a&&o<=r&&o<=n&&!i)return Array.prototype.slice.call(this.keys);var s=[];return this._forEachCell(t,e,r,n,this._queryCell,s,{},i),s},Tn.prototype._queryCell=function(t,e,r,n,i,a,o,s){var u=this.cells[i];if(null!==u)for(var l=this.keys,p=this.bboxes,c=0;c<u.length;c++){var h=u[c];if(void 0===o[h]){var f=4*h;(s?s(p[f+0],p[f+1],p[f+2],p[f+3]):t<=p[f+2]&&e<=p[f+3]&&r>=p[f+0]&&n>=p[f+1])?(o[h]=!0,a.push(l[h])):o[h]=!1;}}},Tn.prototype._forEachCell=function(t,e,r,n,i,a,o,s){for(var u=this._convertToCellCoord(t),l=this._convertToCellCoord(e),p=this._convertToCellCoord(r),c=this._convertToCellCoord(n),h=u;h<=p;h++)for(var f=l;f<=c;f++){var y=this.d*f+h;if((!s||s(this._convertFromCellCoord(h),this._convertFromCellCoord(f),this._convertFromCellCoord(h+1),this._convertFromCellCoord(f+1)))&&i.call(this,t,e,r,n,y,a,o,s))return}},Tn.prototype._convertFromCellCoord=function(t){return (t-this.padding)/this.scale},Tn.prototype._convertToCellCoord=function(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))},Tn.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var t=this.cells,e=3+this.cells.length+1+1,r=0,n=0;n<this.cells.length;n++)r+=this.cells[n].length;var i=new Int32Array(e+r+this.keys.length+this.bboxes.length);i[0]=this.extent,i[1]=this.n,i[2]=this.padding;for(var a=e,o=0;o<t.length;o++){var s=t[o];i[3+o]=a,i.set(s,a),a+=s.length;}return i[3+t.length]=a,i.set(this.keys,a),i[3+t.length+1]=a+=this.keys.length,i.set(this.bboxes,a),a+=this.bboxes.length,i.buffer};var Pn=self.ImageData,Bn=self.ImageBitmap,Vn={};function Fn(t,e,r){void 0===r&&(r={}),Object.defineProperty(e,"_classRegistryKey",{value:t,writeable:!1}),Vn[t]={klass:e,omit:r.omit||[],shallow:r.shallow||[]};}for(var Dn in Fn("Object",Object),En.serialize=function(t,e){var r=t.toArrayBuffer();return e&&e.push(r),{buffer:r}},En.deserialize=function(t){return new En(t.buffer)},Fn("Grid",En),Fn("Color",$t),Fn("Error",Error),Fn("ResolvedImage",ee),Fn("StylePropertyFunction",Xr),Fn("StyleExpression",jr,{omit:["_evaluator"]}),Fn("ZoomDependentExpression",Gr),Fn("ZoomConstantExpression",Kr),Fn("CompoundExpression",me,{omit:["_evaluate"]}),Ar)Ar[Dn]._classRegistryKey||Fn("Expression_"+Dn,Ar[Dn]);function Ln(t){return t&&"undefined"!=typeof ArrayBuffer&&(t instanceof ArrayBuffer||t.constructor&&"ArrayBuffer"===t.constructor.name)}function Rn(t){return Bn&&t instanceof Bn}function On(t,e){if(null==t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||t instanceof Boolean||t instanceof Number||t instanceof String||t instanceof Date||t instanceof RegExp)return t;if(Ln(t)||Rn(t))return e&&e.push(t),t;if(ArrayBuffer.isView(t)){var r=t;return e&&e.push(r.buffer),r}if(t instanceof Pn)return e&&e.push(t.data.buffer),t;if(Array.isArray(t)){for(var n=[],i=0,a=t;i<a.length;i+=1)n.push(On(a[i],e));return n}if("object"==typeof t){var o=t.constructor,s=o._classRegistryKey;if(!s)throw new Error("can't serialize object of unregistered class");var u=o.serialize?o.serialize(t,e):{};if(!o.serialize){for(var l in t)if(t.hasOwnProperty(l)&&!(Vn[s].omit.indexOf(l)>=0)){var p=t[l];u[l]=Vn[s].shallow.indexOf(l)>=0?p:On(p,e);}t instanceof Error&&(u.message=t.message);}if(u.$name)throw new Error("$name property is reserved for worker serialization logic.");return "Object"!==s&&(u.$name=s),u}throw new Error("can't serialize object of type "+typeof t)}function Un(t){if(null==t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||t instanceof Boolean||t instanceof Number||t instanceof String||t instanceof Date||t instanceof RegExp||Ln(t)||Rn(t)||ArrayBuffer.isView(t)||t instanceof Pn)return t;if(Array.isArray(t))return t.map(Un);if("object"==typeof t){var e=t.$name||"Object",r=Vn[e].klass;if(!r)throw new Error("can't deserialize unregistered class "+e);if(r.deserialize)return r.deserialize(t);for(var n=Object.create(r.prototype),i=0,a=Object.keys(t);i<a.length;i+=1){var o=a[i];if("$name"!==o){var s=t[o];n[o]=Vn[e].shallow.indexOf(o)>=0?s:Un(s);}}return n}throw new Error("can't deserialize object of type "+typeof t)}var jn=function(){this.first=!0;};jn.prototype.update=function(t,e){var r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoom<r&&(this.lastIntegerZoom=r,this.lastIntegerZoomTime=e),t!==this.lastZoom&&(this.lastZoom=t,this.lastFloorZoom=r,!0))};var qn={"Latin-1 Supplement":function(t){return t>=128&&t<=255},Arabic:function(t){return t>=1536&&t<=1791},"Arabic Supplement":function(t){return t>=1872&&t<=1919},"Arabic Extended-A":function(t){return t>=2208&&t<=2303},"Hangul Jamo":function(t){return t>=4352&&t<=4607},"Unified Canadian Aboriginal Syllabics":function(t){return t>=5120&&t<=5759},Khmer:function(t){return t>=6016&&t<=6143},"Unified Canadian Aboriginal Syllabics Extended":function(t){return t>=6320&&t<=6399},"General Punctuation":function(t){return t>=8192&&t<=8303},"Letterlike Symbols":function(t){return t>=8448&&t<=8527},"Number Forms":function(t){return t>=8528&&t<=8591},"Miscellaneous Technical":function(t){return t>=8960&&t<=9215},"Control Pictures":function(t){return t>=9216&&t<=9279},"Optical Character Recognition":function(t){return t>=9280&&t<=9311},"Enclosed Alphanumerics":function(t){return t>=9312&&t<=9471},"Geometric Shapes":function(t){return t>=9632&&t<=9727},"Miscellaneous Symbols":function(t){return t>=9728&&t<=9983},"Miscellaneous Symbols and Arrows":function(t){return t>=11008&&t<=11263},"CJK Radicals Supplement":function(t){return t>=11904&&t<=12031},"Kangxi Radicals":function(t){return t>=12032&&t<=12255},"Ideographic Description Characters":function(t){return t>=12272&&t<=12287},"CJK Symbols and Punctuation":function(t){return t>=12288&&t<=12351},Hiragana:function(t){return t>=12352&&t<=12447},Katakana:function(t){return t>=12448&&t<=12543},Bopomofo:function(t){return t>=12544&&t<=12591},"Hangul Compatibility Jamo":function(t){return t>=12592&&t<=12687},Kanbun:function(t){return t>=12688&&t<=12703},"Bopomofo Extended":function(t){return t>=12704&&t<=12735},"CJK Strokes":function(t){return t>=12736&&t<=12783},"Katakana Phonetic Extensions":function(t){return t>=12784&&t<=12799},"Enclosed CJK Letters and Months":function(t){return t>=12800&&t<=13055},"CJK Compatibility":function(t){return t>=13056&&t<=13311},"CJK Unified Ideographs Extension A":function(t){return t>=13312&&t<=19903},"Yijing Hexagram Symbols":function(t){return t>=19904&&t<=19967},"CJK Unified Ideographs":function(t){return t>=19968&&t<=40959},"Yi Syllables":function(t){return t>=40960&&t<=42127},"Yi Radicals":function(t){return t>=42128&&t<=42191},"Hangul Jamo Extended-A":function(t){return t>=43360&&t<=43391},"Hangul Syllables":function(t){return t>=44032&&t<=55215},"Hangul Jamo Extended-B":function(t){return t>=55216&&t<=55295},"Private Use Area":function(t){return t>=57344&&t<=63743},"CJK Compatibility Ideographs":function(t){return t>=63744&&t<=64255},"Arabic Presentation Forms-A":function(t){return t>=64336&&t<=65023},"Vertical Forms":function(t){return t>=65040&&t<=65055},"CJK Compatibility Forms":function(t){return t>=65072&&t<=65103},"Small Form Variants":function(t){return t>=65104&&t<=65135},"Arabic Presentation Forms-B":function(t){return t>=65136&&t<=65279},"Halfwidth and Fullwidth Forms":function(t){return t>=65280&&t<=65519}};function Nn(t){for(var e=0,r=t;e<r.length;e+=1)if(Kn(r[e].charCodeAt(0)))return !0;return !1}function Kn(t){return !(746!==t&&747!==t&&(t<4352||!(qn["Bopomofo Extended"](t)||qn.Bopomofo(t)||qn["CJK Compatibility Forms"](t)&&!(t>=65097&&t<=65103)||qn["CJK Compatibility Ideographs"](t)||qn["CJK Compatibility"](t)||qn["CJK Radicals Supplement"](t)||qn["CJK Strokes"](t)||!(!qn["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||qn["CJK Unified Ideographs Extension A"](t)||qn["CJK Unified Ideographs"](t)||qn["Enclosed CJK Letters and Months"](t)||qn["Hangul Compatibility Jamo"](t)||qn["Hangul Jamo Extended-A"](t)||qn["Hangul Jamo Extended-B"](t)||qn["Hangul Jamo"](t)||qn["Hangul Syllables"](t)||qn.Hiragana(t)||qn["Ideographic Description Characters"](t)||qn.Kanbun(t)||qn["Kangxi Radicals"](t)||qn["Katakana Phonetic Extensions"](t)||qn.Katakana(t)&&12540!==t||!(!qn["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!qn["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||qn["Unified Canadian Aboriginal Syllabics"](t)||qn["Unified Canadian Aboriginal Syllabics Extended"](t)||qn["Vertical Forms"](t)||qn["Yijing Hexagram Symbols"](t)||qn["Yi Syllables"](t)||qn["Yi Radicals"](t))))}function Gn(t){return !(Kn(t)||function(t){return !!(qn["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||qn["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||qn["Letterlike Symbols"](t)||qn["Number Forms"](t)||qn["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||qn["Control Pictures"](t)&&9251!==t||qn["Optical Character Recognition"](t)||qn["Enclosed Alphanumerics"](t)||qn["Geometric Shapes"](t)||qn["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||qn["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||qn["CJK Symbols and Punctuation"](t)||qn.Katakana(t)||qn["Private Use Area"](t)||qn["CJK Compatibility Forms"](t)||qn["Small Form Variants"](t)||qn["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}function Zn(t){return t>=1424&&t<=2303||qn["Arabic Presentation Forms-A"](t)||qn["Arabic Presentation Forms-B"](t)}function Xn(t,e){return !(!e&&Zn(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||qn.Khmer(t))}function Jn(t){for(var e=0,r=t;e<r.length;e+=1)if(Zn(r[e].charCodeAt(0)))return !0;return !1}var Hn=null,Yn="unavailable",$n=null,Wn=function(t){t&&"string"==typeof t&&t.indexOf("NetworkError")>-1&&(Yn="error"),Hn&&Hn(t);};function Qn(){ti.fire(new At("pluginStateChange",{pluginStatus:Yn,pluginURL:$n}));}var ti=new kt,ei=function(){return Yn},ri=function(){if("deferred"!==Yn||!$n)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Yn="loading",Qn(),$n&&gt({url:$n},(function(t){t?Wn(t):(Yn="loaded",Qn());}));},ni={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:function(){return "loaded"===Yn||null!=ni.applyArabicShaping},isLoading:function(){return "loading"===Yn},setState:function(t){Yn=t.pluginStatus,$n=t.pluginURL;},isParsed:function(){return null!=ni.applyArabicShaping&&null!=ni.processBidirectionalText&&null!=ni.processStyledBidirectionalText},getPluginURL:function(){return $n}},ii=function(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.zoomHistory=e.zoomHistory,this.transition=e.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new jn,this.transition={});};ii.prototype.isSupportedScript=function(t){return function(t,e){for(var r=0,n=t;r<n.length;r+=1)if(!Xn(n[r].charCodeAt(0),e))return !1;return !0}(t,ni.isLoaded())},ii.prototype.crossFadingFactor=function(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)},ii.prototype.getCrossfadeParameters=function(){var t=this.zoom,e=t-Math.floor(t),r=this.crossFadingFactor();return t>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*r}:{fromScale:.5,toScale:1,t:1-(1-r)*e}};var ai=function(t,e){this.property=t,this.value=e,this.expression=function(t,e){if(Vr(t))return new Xr(t,e);if(qr(t)){var r=Zr(t,e);if("error"===r.result)throw new Error(r.value.map((function(t){return t.key+": "+t.message})).join(", "));return r.value}var n=t;return "string"==typeof t&&"color"===e.type&&(n=$t.parse(t)),{kind:"constant",evaluate:function(){return n}}}(void 0===e?t.specification.default:e,t.specification);};ai.prototype.isDataDriven=function(){return "source"===this.expression.kind||"composite"===this.expression.kind},ai.prototype.possiblyEvaluate=function(t,e,r){return this.property.possiblyEvaluate(this,t,e,r)};var oi=function(t){this.property=t,this.value=new ai(t,void 0);};oi.prototype.transitioned=function(t,e){return new ui(this.property,this.value,e,p({},t.transition,this.transition),t.now)},oi.prototype.untransitioned=function(){return new ui(this.property,this.value,null,{},0)};var si=function(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues);};si.prototype.getValue=function(t){return x(this._values[t].value.value)},si.prototype.setValue=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new oi(this._values[t].property)),this._values[t].value=new ai(this._values[t].property,null===e?void 0:x(e));},si.prototype.getTransition=function(t){return x(this._values[t].transition)},si.prototype.setTransition=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new oi(this._values[t].property)),this._values[t].transition=x(e)||void 0;},si.prototype.serialize=function(){for(var t={},e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e],i=this.getValue(n);void 0!==i&&(t[n]=i);var a=this.getTransition(n);void 0!==a&&(t[n+"-transition"]=a);}return t},si.prototype.transitioned=function(t,e){for(var r=new li(this._properties),n=0,i=Object.keys(this._values);n<i.length;n+=1){var a=i[n];r._values[a]=this._values[a].transitioned(t,e._values[a]);}return r},si.prototype.untransitioned=function(){for(var t=new li(this._properties),e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e];t._values[n]=this._values[n].untransitioned();}return t};var ui=function(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r);};ui.prototype.possiblyEvaluate=function(t,e,r){var n=t.now||0,i=this.value.possiblyEvaluate(t,e,r),a=this.prior;if(a){if(n>this.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(n<this.begin)return a.possiblyEvaluate(t,e,r);var o=(n-this.begin)/(this.end-this.begin);return this.property.interpolate(a.possiblyEvaluate(t,e,r),i,function(t){if(t<=0)return 0;if(t>=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}(o))}return i};var li=function(t){this._properties=t,this._values=Object.create(t.defaultTransitioningPropertyValues);};li.prototype.possiblyEvaluate=function(t,e,r){for(var n=new hi(this._properties),i=0,a=Object.keys(this._values);i<a.length;i+=1){var o=a[i];n._values[o]=this._values[o].possiblyEvaluate(t,e,r);}return n},li.prototype.hasTransition=function(){for(var t=0,e=Object.keys(this._values);t<e.length;t+=1)if(this._values[e[t]].prior)return !0;return !1};var pi=function(t){this._properties=t,this._values=Object.create(t.defaultPropertyValues);};pi.prototype.getValue=function(t){return x(this._values[t].value)},pi.prototype.setValue=function(t,e){this._values[t]=new ai(this._values[t].property,null===e?void 0:x(e));},pi.prototype.serialize=function(){for(var t={},e=0,r=Object.keys(this._values);e<r.length;e+=1){var n=r[e],i=this.getValue(n);void 0!==i&&(t[n]=i);}return t},pi.prototype.possiblyEvaluate=function(t,e,r){for(var n=new hi(this._properties),i=0,a=Object.keys(this._values);i<a.length;i+=1){var o=a[i];n._values[o]=this._values[o].possiblyEvaluate(t,e,r);}return n};var ci=function(t,e,r){this.property=t,this.value=e,this.parameters=r;};ci.prototype.isConstant=function(){return "constant"===this.value.kind},ci.prototype.constantOr=function(t){return "constant"===this.value.kind?this.value.value:t},ci.prototype.evaluate=function(t,e,r,n){return this.property.evaluate(this.value,this.parameters,t,e,r,n)};var hi=function(t){this._properties=t,this._values=Object.create(t.defaultPossiblyEvaluatedValues);};hi.prototype.get=function(t){return this._values[t]};var fi=function(t){this.specification=t;};fi.prototype.possiblyEvaluate=function(t,e){return t.expression.evaluate(e)},fi.prototype.interpolate=function(t,e,r){var n=qe[this.specification.type];return n?n(t,e,r):t};var yi=function(t,e){this.specification=t,this.overrides=e;};yi.prototype.possiblyEvaluate=function(t,e,r,n){return new ci(this,"constant"===t.expression.kind||"camera"===t.expression.kind?{kind:"constant",value:t.expression.evaluate(e,null,{},r,n)}:t.expression,e)},yi.prototype.interpolate=function(t,e,r){if("constant"!==t.value.kind||"constant"!==e.value.kind)return t;if(void 0===t.value.value||void 0===e.value.value)return new ci(this,{kind:"constant",value:void 0},t.parameters);var n=qe[this.specification.type];return n?new ci(this,{kind:"constant",value:n(t.value.value,e.value.value,r)},t.parameters):t},yi.prototype.evaluate=function(t,e,r,n,i,a){return "constant"===t.kind?t.value:t.evaluate(e,r,n,i,a)};var di=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.possiblyEvaluate=function(t,e,r,n){if(void 0===t.value)return new ci(this,{kind:"constant",value:void 0},e);if("constant"===t.expression.kind){var i=t.expression.evaluate(e,null,{},r,n),a="resolvedImage"===t.property.specification.type&&"string"!=typeof i?i.name:i,o=this._calculate(a,a,a,e);return new ci(this,{kind:"constant",value:o},e)}if("camera"===t.expression.kind){var s=this._calculate(t.expression.evaluate({zoom:e.zoom-1}),t.expression.evaluate({zoom:e.zoom}),t.expression.evaluate({zoom:e.zoom+1}),e);return new ci(this,{kind:"constant",value:s},e)}return new ci(this,t.expression,e)},e.prototype.evaluate=function(t,e,r,n,i,a){if("source"===t.kind){var o=t.evaluate(e,r,n,i,a);return this._calculate(o,o,o,e)}return "composite"===t.kind?this._calculate(t.evaluate({zoom:Math.floor(e.zoom)-1},r,n),t.evaluate({zoom:Math.floor(e.zoom)},r,n),t.evaluate({zoom:Math.floor(e.zoom)+1},r,n),e):t.value},e.prototype._calculate=function(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}},e.prototype.interpolate=function(t){return t},e}(yi),mi=function(t){this.specification=t;};mi.prototype.possiblyEvaluate=function(t,e,r,n){if(void 0!==t.value){if("constant"===t.expression.kind){var i=t.expression.evaluate(e,null,{},r,n);return this._calculate(i,i,i,e)}return this._calculate(t.expression.evaluate(new ii(Math.floor(e.zoom-1),e)),t.expression.evaluate(new ii(Math.floor(e.zoom),e)),t.expression.evaluate(new ii(Math.floor(e.zoom+1),e)),e)}},mi.prototype._calculate=function(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}},mi.prototype.interpolate=function(t){return t};var vi=function(t){this.specification=t;};vi.prototype.possiblyEvaluate=function(t,e,r,n){return !!t.expression.evaluate(e,null,{},r,n)},vi.prototype.interpolate=function(){return !1};var gi=function(t){for(var e in this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[],t){var r=t[e];r.specification.overridable&&this.overridableProperties.push(e);var n=this.defaultPropertyValues[e]=new ai(r,void 0),i=this.defaultTransitionablePropertyValues[e]=new oi(r);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}};Fn("DataDrivenProperty",yi),Fn("DataConstantProperty",fi),Fn("CrossFadedDataDrivenProperty",di),Fn("CrossFadedProperty",mi),Fn("ColorRampProperty",vi);var xi=function(t){function e(e,r){if(t.call(this),this.id=e.id,this.type=e.type,this._featureFilter={filter:function(){return !0},needGeometry:!1},"custom"!==e.type&&(this.metadata=(e=e).metadata,this.minzoom=e.minzoom,this.maxzoom=e.maxzoom,"background"!==e.type&&(this.source=e.source,this.sourceLayer=e["source-layer"],this.filter=e.filter),r.layout&&(this._unevaluatedLayout=new pi(r.layout)),r.paint)){for(var n in this._transitionablePaint=new si(r.paint),e.paint)this.setPaintProperty(n,e.paint[n],{validate:!1});for(var i in e.layout)this.setLayoutProperty(i,e.layout[i],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new hi(r.paint);}}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getCrossfadeParameters=function(){return this._crossfadeParameters},e.prototype.getLayoutProperty=function(t){return "visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)},e.prototype.setLayoutProperty=function(t,e,r){void 0===r&&(r={}),null!=e&&this._validate(Cn,"layers."+this.id+".layout."+t,t,e,r)||("visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e);},e.prototype.getPaintProperty=function(t){return m(t,"-transition")?this._transitionablePaint.getTransition(t.slice(0,-"-transition".length)):this._transitionablePaint.getValue(t)},e.prototype.setPaintProperty=function(t,e,r){if(void 0===r&&(r={}),null!=e&&this._validate(zn,"layers."+this.id+".paint."+t,t,e,r))return !1;if(m(t,"-transition"))return this._transitionablePaint.setTransition(t.slice(0,-"-transition".length),e||void 0),!1;var n=this._transitionablePaint._values[t],i="cross-faded-data-driven"===n.property.specification["property-type"],a=n.value.isDataDriven(),o=n.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);var s=this._transitionablePaint._values[t].value;return s.isDataDriven()||a||i||this._handleOverridablePaintPropertyUpdate(t,o,s)},e.prototype._handleSpecialPaintPropertyUpdate=function(t){},e.prototype._handleOverridablePaintPropertyUpdate=function(t,e,r){return !1},e.prototype.isHidden=function(t){return !!(this.minzoom&&t<this.minzoom)||!!(this.maxzoom&&t>=this.maxzoom)||"none"===this.visibility},e.prototype.updateTransitions=function(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);},e.prototype.hasTransition=function(){return this._transitioningPaint.hasTransition()},e.prototype.recalculate=function(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,void 0,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,void 0,e);},e.prototype.serialize=function(){var t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),g(t,(function(t,e){return !(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)}))},e.prototype._validate=function(t,e,r,n,i){return void 0===i&&(i={}),(!i||!1!==i.validate)&&Mn(this,t.call(kn,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:It,style:{glyphs:!0,sprite:!0}}))},e.prototype.is3D=function(){return !1},e.prototype.isTileClipped=function(){return !1},e.prototype.hasOffscreenPass=function(){return !1},e.prototype.resize=function(){},e.prototype.isStateDependent=function(){for(var t in this.paint._values){var e=this.paint.get(t);if(e instanceof ci&&Er(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return !0}return !1},e}(kt),bi={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array},wi=function(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;},_i=function(){this.isTransferred=!1,this.capacity=-1,this.resize(0);};function Ai(t,e){void 0===e&&(e=1);var r=0,n=0;return {members:t.map((function(t){var i=bi[t.type].BYTES_PER_ELEMENT,a=r=Si(r,Math.max(e,i)),o=t.components||1;return n=Math.max(n,i),r+=i*o,{name:t.name,type:t.type,components:o,offset:a}})),size:Si(r,Math.max(n,e)),alignment:e}}function Si(t,e){return Math.ceil(t/e)*e}_i.serialize=function(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}},_i.deserialize=function(t){var e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e},_i.prototype._trim=function(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());},_i.prototype.clear=function(){this.length=0;},_i.prototype.resize=function(t){this.reserve(t),this.length=t;},_i.prototype.reserve=function(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);var e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}},_i.prototype._refreshViews=function(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")};var ki=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;return this.resize(r+1),this.emplace(r,t,e)},e.prototype.emplace=function(t,e,r){var n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t},e}(_i);ki.prototype.bytesPerElement=4,Fn("StructArrayLayout2i4",ki);var Ii=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)},e.prototype.emplace=function(t,e,r,n,i){var a=4*t;return this.int16[a+0]=e,this.int16[a+1]=r,this.int16[a+2]=n,this.int16[a+3]=i,t},e}(_i);Ii.prototype.bytesPerElement=8,Fn("StructArrayLayout4i8",Ii);var zi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a){var o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,a)},e.prototype.emplace=function(t,e,r,n,i,a,o){var s=6*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,this.int16[s+4]=a,this.int16[s+5]=o,t},e}(_i);zi.prototype.bytesPerElement=12,Fn("StructArrayLayout2i4i12",zi);var Ci=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a){var o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,a)},e.prototype.emplace=function(t,e,r,n,i,a,o){var s=4*t,u=8*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.uint8[u+4]=n,this.uint8[u+5]=i,this.uint8[u+6]=a,this.uint8[u+7]=o,t},e}(_i);Ci.prototype.bytesPerElement=8,Fn("StructArrayLayout2i4ub8",Ci);var Mi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l){var p=this.length;return this.resize(p+1),this.emplace(p,t,e,r,n,i,a,o,s,u,l)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p){var c=9*t,h=18*t;return this.uint16[c+0]=e,this.uint16[c+1]=r,this.uint16[c+2]=n,this.uint16[c+3]=i,this.uint16[c+4]=a,this.uint16[c+5]=o,this.uint16[c+6]=s,this.uint16[c+7]=u,this.uint8[h+16]=l,this.uint8[h+17]=p,t},e}(_i);Mi.prototype.bytesPerElement=18,Fn("StructArrayLayout8ui2ub18",Mi);var Ei=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l,p,c){var h=this.length;return this.resize(h+1),this.emplace(h,t,e,r,n,i,a,o,s,u,l,p,c)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p,c,h){var f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=a,this.uint16[f+5]=o,this.uint16[f+6]=s,this.uint16[f+7]=u,this.int16[f+8]=l,this.int16[f+9]=p,this.int16[f+10]=c,this.int16[f+11]=h,t},e}(_i);Ei.prototype.bytesPerElement=24,Fn("StructArrayLayout4i4ui4i24",Ei);var Ti=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t},e}(_i);Ti.prototype.bytesPerElement=12,Fn("StructArrayLayout3f12",Ti);var Pi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;return this.resize(e+1),this.emplace(e,t)},e.prototype.emplace=function(t,e){return this.uint32[1*t+0]=e,t},e}(_i);Pi.prototype.bytesPerElement=4,Fn("StructArrayLayout1ul4",Pi);var Bi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u){var l=this.length;return this.resize(l+1),this.emplace(l,t,e,r,n,i,a,o,s,u)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l){var p=10*t,c=5*t;return this.int16[p+0]=e,this.int16[p+1]=r,this.int16[p+2]=n,this.int16[p+3]=i,this.int16[p+4]=a,this.int16[p+5]=o,this.uint32[c+3]=s,this.uint16[p+8]=u,this.uint16[p+9]=l,t},e}(_i);Bi.prototype.bytesPerElement=20,Fn("StructArrayLayout6i1ul2ui20",Bi);var Vi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a){var o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,a)},e.prototype.emplace=function(t,e,r,n,i,a,o){var s=6*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,this.int16[s+4]=a,this.int16[s+5]=o,t},e}(_i);Vi.prototype.bytesPerElement=12,Fn("StructArrayLayout2i2i2i12",Vi);var Fi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i){var a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i)},e.prototype.emplace=function(t,e,r,n,i,a){var o=4*t,s=8*t;return this.float32[o+0]=e,this.float32[o+1]=r,this.float32[o+2]=n,this.int16[s+6]=i,this.int16[s+7]=a,t},e}(_i);Fi.prototype.bytesPerElement=16,Fn("StructArrayLayout2f1f2i16",Fi);var Di=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)},e.prototype.emplace=function(t,e,r,n,i){var a=12*t,o=3*t;return this.uint8[a+0]=e,this.uint8[a+1]=r,this.float32[o+1]=n,this.float32[o+2]=i,t},e}(_i);Di.prototype.bytesPerElement=12,Fn("StructArrayLayout2ub2f12",Di);var Li=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t},e}(_i);Li.prototype.bytesPerElement=6,Fn("StructArrayLayout3ui6",Li);var Ri=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m){var v=this.length;return this.resize(v+1),this.emplace(v,t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v){var g=24*t,x=12*t,b=48*t;return this.int16[g+0]=e,this.int16[g+1]=r,this.uint16[g+2]=n,this.uint16[g+3]=i,this.uint32[x+2]=a,this.uint32[x+3]=o,this.uint32[x+4]=s,this.uint16[g+10]=u,this.uint16[g+11]=l,this.uint16[g+12]=p,this.float32[x+7]=c,this.float32[x+8]=h,this.uint8[b+36]=f,this.uint8[b+37]=y,this.uint8[b+38]=d,this.uint32[x+10]=m,this.int16[g+22]=v,t},e}(_i);Ri.prototype.bytesPerElement=48,Fn("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",Ri);var Oi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,w,_,A,S,k,I,z){var C=this.length;return this.resize(C+1),this.emplace(C,t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,w,_,A,S,k,I,z)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,w,_,A,S,k,I,z,C){var M=34*t,E=17*t;return this.int16[M+0]=e,this.int16[M+1]=r,this.int16[M+2]=n,this.int16[M+3]=i,this.int16[M+4]=a,this.int16[M+5]=o,this.int16[M+6]=s,this.int16[M+7]=u,this.uint16[M+8]=l,this.uint16[M+9]=p,this.uint16[M+10]=c,this.uint16[M+11]=h,this.uint16[M+12]=f,this.uint16[M+13]=y,this.uint16[M+14]=d,this.uint16[M+15]=m,this.uint16[M+16]=v,this.uint16[M+17]=g,this.uint16[M+18]=x,this.uint16[M+19]=b,this.uint16[M+20]=w,this.uint16[M+21]=_,this.uint16[M+22]=A,this.uint32[E+12]=S,this.float32[E+13]=k,this.float32[E+14]=I,this.float32[E+15]=z,this.float32[E+16]=C,t},e}(_i);Oi.prototype.bytesPerElement=68,Fn("StructArrayLayout8i15ui1ul4f68",Oi);var Ui=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;return this.resize(e+1),this.emplace(e,t)},e.prototype.emplace=function(t,e){return this.float32[1*t+0]=e,t},e}(_i);Ui.prototype.bytesPerElement=4,Fn("StructArrayLayout1f4",Ui);var ji=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t},e}(_i);ji.prototype.bytesPerElement=6,Fn("StructArrayLayout3i6",ji);var qi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=4*t;return this.uint32[2*t+0]=e,this.uint16[i+2]=r,this.uint16[i+3]=n,t},e}(_i);qi.prototype.bytesPerElement=8,Fn("StructArrayLayout1ul2ui8",qi);var Ni=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;return this.resize(r+1),this.emplace(r,t,e)},e.prototype.emplace=function(t,e,r){var n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t},e}(_i);Ni.prototype.bytesPerElement=4,Fn("StructArrayLayout2ui4",Ni);var Ki=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;return this.resize(e+1),this.emplace(e,t)},e.prototype.emplace=function(t,e){return this.uint16[1*t+0]=e,t},e}(_i);Ki.prototype.bytesPerElement=2,Fn("StructArrayLayout1ui2",Ki);var Gi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;return this.resize(r+1),this.emplace(r,t,e)},e.prototype.emplace=function(t,e,r){var n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t},e}(_i);Gi.prototype.bytesPerElement=8,Fn("StructArrayLayout2f8",Gi);var Zi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)},e.prototype.emplace=function(t,e,r,n,i){var a=4*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.float32[a+3]=i,t},e}(_i);Zi.prototype.bytesPerElement=16,Fn("StructArrayLayout4f16",Zi);var Xi=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={anchorPointX:{configurable:!0},anchorPointY:{configurable:!0},x1:{configurable:!0},y1:{configurable:!0},x2:{configurable:!0},y2:{configurable:!0},featureIndex:{configurable:!0},sourceLayerIndex:{configurable:!0},bucketIndex:{configurable:!0},anchorPoint:{configurable:!0}};return r.anchorPointX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorPointY.get=function(){return this._structArray.int16[this._pos2+1]},r.x1.get=function(){return this._structArray.int16[this._pos2+2]},r.y1.get=function(){return this._structArray.int16[this._pos2+3]},r.x2.get=function(){return this._structArray.int16[this._pos2+4]},r.y2.get=function(){return this._structArray.int16[this._pos2+5]},r.featureIndex.get=function(){return this._structArray.uint32[this._pos4+3]},r.sourceLayerIndex.get=function(){return this._structArray.uint16[this._pos2+8]},r.bucketIndex.get=function(){return this._structArray.uint16[this._pos2+9]},r.anchorPoint.get=function(){return new i(this.anchorPointX,this.anchorPointY)},Object.defineProperties(e.prototype,r),e}(wi);Xi.prototype.size=20;var Ji=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.get=function(t){return new Xi(this,t)},e}(Bi);Fn("CollisionBoxArray",Ji);var Hi=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={anchorX:{configurable:!0},anchorY:{configurable:!0},glyphStartIndex:{configurable:!0},numGlyphs:{configurable:!0},vertexStartIndex:{configurable:!0},lineStartIndex:{configurable:!0},lineLength:{configurable:!0},segment:{configurable:!0},lowerSize:{configurable:!0},upperSize:{configurable:!0},lineOffsetX:{configurable:!0},lineOffsetY:{configurable:!0},writingMode:{configurable:!0},placedOrientation:{configurable:!0},hidden:{configurable:!0},crossTileID:{configurable:!0},associatedIconIndex:{configurable:!0}};return r.anchorX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorY.get=function(){return this._structArray.int16[this._pos2+1]},r.glyphStartIndex.get=function(){return this._structArray.uint16[this._pos2+2]},r.numGlyphs.get=function(){return this._structArray.uint16[this._pos2+3]},r.vertexStartIndex.get=function(){return this._structArray.uint32[this._pos4+2]},r.lineStartIndex.get=function(){return this._structArray.uint32[this._pos4+3]},r.lineLength.get=function(){return this._structArray.uint32[this._pos4+4]},r.segment.get=function(){return this._structArray.uint16[this._pos2+10]},r.lowerSize.get=function(){return this._structArray.uint16[this._pos2+11]},r.upperSize.get=function(){return this._structArray.uint16[this._pos2+12]},r.lineOffsetX.get=function(){return this._structArray.float32[this._pos4+7]},r.lineOffsetY.get=function(){return this._structArray.float32[this._pos4+8]},r.writingMode.get=function(){return this._structArray.uint8[this._pos1+36]},r.placedOrientation.get=function(){return this._structArray.uint8[this._pos1+37]},r.placedOrientation.set=function(t){this._structArray.uint8[this._pos1+37]=t;},r.hidden.get=function(){return this._structArray.uint8[this._pos1+38]},r.hidden.set=function(t){this._structArray.uint8[this._pos1+38]=t;},r.crossTileID.get=function(){return this._structArray.uint32[this._pos4+10]},r.crossTileID.set=function(t){this._structArray.uint32[this._pos4+10]=t;},r.associatedIconIndex.get=function(){return this._structArray.int16[this._pos2+22]},Object.defineProperties(e.prototype,r),e}(wi);Hi.prototype.size=48;var Yi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.get=function(t){return new Hi(this,t)},e}(Ri);Fn("PlacedSymbolArray",Yi);var $i=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={anchorX:{configurable:!0},anchorY:{configurable:!0},rightJustifiedTextSymbolIndex:{configurable:!0},centerJustifiedTextSymbolIndex:{configurable:!0},leftJustifiedTextSymbolIndex:{configurable:!0},verticalPlacedTextSymbolIndex:{configurable:!0},placedIconSymbolIndex:{configurable:!0},verticalPlacedIconSymbolIndex:{configurable:!0},key:{configurable:!0},textBoxStartIndex:{configurable:!0},textBoxEndIndex:{configurable:!0},verticalTextBoxStartIndex:{configurable:!0},verticalTextBoxEndIndex:{configurable:!0},iconBoxStartIndex:{configurable:!0},iconBoxEndIndex:{configurable:!0},verticalIconBoxStartIndex:{configurable:!0},verticalIconBoxEndIndex:{configurable:!0},featureIndex:{configurable:!0},numHorizontalGlyphVertices:{configurable:!0},numVerticalGlyphVertices:{configurable:!0},numIconVertices:{configurable:!0},numVerticalIconVertices:{configurable:!0},useRuntimeCollisionCircles:{configurable:!0},crossTileID:{configurable:!0},textBoxScale:{configurable:!0},textOffset0:{configurable:!0},textOffset1:{configurable:!0},collisionCircleDiameter:{configurable:!0}};return r.anchorX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorY.get=function(){return this._structArray.int16[this._pos2+1]},r.rightJustifiedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+2]},r.centerJustifiedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+3]},r.leftJustifiedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+4]},r.verticalPlacedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+5]},r.placedIconSymbolIndex.get=function(){return this._structArray.int16[this._pos2+6]},r.verticalPlacedIconSymbolIndex.get=function(){return this._structArray.int16[this._pos2+7]},r.key.get=function(){return this._structArray.uint16[this._pos2+8]},r.textBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+9]},r.textBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+10]},r.verticalTextBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+11]},r.verticalTextBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+12]},r.iconBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+13]},r.iconBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+14]},r.verticalIconBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+15]},r.verticalIconBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+16]},r.featureIndex.get=function(){return this._structArray.uint16[this._pos2+17]},r.numHorizontalGlyphVertices.get=function(){return this._structArray.uint16[this._pos2+18]},r.numVerticalGlyphVertices.get=function(){return this._structArray.uint16[this._pos2+19]},r.numIconVertices.get=function(){return this._structArray.uint16[this._pos2+20]},r.numVerticalIconVertices.get=function(){return this._structArray.uint16[this._pos2+21]},r.useRuntimeCollisionCircles.get=function(){return this._structArray.uint16[this._pos2+22]},r.crossTileID.get=function(){return this._structArray.uint32[this._pos4+12]},r.crossTileID.set=function(t){this._structArray.uint32[this._pos4+12]=t;},r.textBoxScale.get=function(){return this._structArray.float32[this._pos4+13]},r.textOffset0.get=function(){return this._structArray.float32[this._pos4+14]},r.textOffset1.get=function(){return this._structArray.float32[this._pos4+15]},r.collisionCircleDiameter.get=function(){return this._structArray.float32[this._pos4+16]},Object.defineProperties(e.prototype,r),e}(wi);$i.prototype.size=68;var Wi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.get=function(t){return new $i(this,t)},e}(Oi);Fn("SymbolInstanceArray",Wi);var Qi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getoffsetX=function(t){return this.float32[1*t+0]},e}(Ui);Fn("GlyphOffsetArray",Qi);var ta=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getx=function(t){return this.int16[3*t+0]},e.prototype.gety=function(t){return this.int16[3*t+1]},e.prototype.gettileUnitDistanceFromAnchor=function(t){return this.int16[3*t+2]},e}(ji);Fn("SymbolLineVertexArray",ta);var ea=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={featureIndex:{configurable:!0},sourceLayerIndex:{configurable:!0},bucketIndex:{configurable:!0}};return r.featureIndex.get=function(){return this._structArray.uint32[this._pos4+0]},r.sourceLayerIndex.get=function(){return this._structArray.uint16[this._pos2+2]},r.bucketIndex.get=function(){return this._structArray.uint16[this._pos2+3]},Object.defineProperties(e.prototype,r),e}(wi);ea.prototype.size=8;var ra=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.get=function(t){return new ea(this,t)},e}(qi);Fn("FeatureIndexArray",ra);var na=Ai([{name:"a_pos",components:2,type:"Int16"}],4).members,ia=function(t){void 0===t&&(t=[]),this.segments=t;};function aa(t,e){return 256*(t=u(Math.floor(t),0,255))+u(Math.floor(e),0,255)}ia.prototype.prepareSegment=function(t,e,r,n){var i=this.segments[this.segments.length-1];return t>ia.MAX_VERTEX_ARRAY_LENGTH&&w("Max vertices per segment is "+ia.MAX_VERTEX_ARRAY_LENGTH+": bucket requested "+t),(!i||i.vertexLength+t>ia.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n)&&(i={vertexOffset:e.length,primitiveOffset:r.length,vertexLength:0,primitiveLength:0},void 0!==n&&(i.sortKey=n),this.segments.push(i)),i},ia.prototype.get=function(){return this.segments},ia.prototype.destroy=function(){for(var t=0,e=this.segments;t<e.length;t+=1){var r=e[t];for(var n in r.vaos)r.vaos[n].destroy();}},ia.simpleSegment=function(t,e,r,n){return new ia([{vertexOffset:t,primitiveOffset:e,vertexLength:r,primitiveLength:n,vaos:{},sortKey:0}])},ia.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Fn("SegmentVector",ia);var oa=Ai([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint8"},{name:"a_pixel_ratio_to",components:1,type:"Uint8"}]),sa=e((function(t){t.exports=function(t,e){var r,n,i,a,o,s,u,l;for(n=t.length-(r=3&t.length),i=e,o=3432918353,s=461845907,l=0;l<n;)u=255&t.charCodeAt(l)|(255&t.charCodeAt(++l))<<8|(255&t.charCodeAt(++l))<<16|(255&t.charCodeAt(++l))<<24,++l,i=27492+(65535&(a=5*(65535&(i=(i^=u=(65535&(u=(u=(65535&u)*o+(((u>>>16)*o&65535)<<16)&4294967295)<<15|u>>>17))*s+(((u>>>16)*s&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(a>>>16)&65535)<<16);switch(u=0,r){case 3:u^=(255&t.charCodeAt(l+2))<<16;case 2:u^=(255&t.charCodeAt(l+1))<<8;case 1:i^=u=(65535&(u=(u=(65535&(u^=255&t.charCodeAt(l)))*o+(((u>>>16)*o&65535)<<16)&4294967295)<<15|u>>>17))*s+(((u>>>16)*s&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0};})),ua=e((function(t){t.exports=function(t,e){for(var r,n=t.length,i=e^n,a=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(a)|(255&t.charCodeAt(++a))<<8|(255&t.charCodeAt(++a))<<16|(255&t.charCodeAt(++a))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++a;switch(n){case 3:i^=(255&t.charCodeAt(a+2))<<16;case 2:i^=(255&t.charCodeAt(a+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(a)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0};})),la=sa,pa=ua;la.murmur3=sa,la.murmur2=pa;var ca=function(){this.ids=[],this.positions=[],this.indexed=!1;};ca.prototype.add=function(t,e,r,n){this.ids.push(fa(t)),this.positions.push(e,r,n);},ca.prototype.getPositions=function(t){for(var e=fa(t),r=0,n=this.ids.length-1;r<n;){var i=r+n>>1;this.ids[i]>=e?n=i:r=i+1;}for(var a=[];this.ids[r]===e;)a.push({index:this.positions[3*r],start:this.positions[3*r+1],end:this.positions[3*r+2]}),r++;return a},ca.serialize=function(t,e){var r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return function t(e,r,n,i){for(;n<i;){for(var a=e[n+i>>1],o=n-1,s=i+1;;){do{o++;}while(e[o]<a);do{s--;}while(e[s]>a);if(o>=s)break;ya(e,o,s),ya(r,3*o,3*s),ya(r,3*o+1,3*s+1),ya(r,3*o+2,3*s+2);}s-n<i-s?(t(e,r,n,s),n=s+1):(t(e,r,s+1,i),i=s);}}(r,n,0,r.length-1),e&&e.push(r.buffer,n.buffer),{ids:r,positions:n}},ca.deserialize=function(t){var e=new ca;return e.ids=t.ids,e.positions=t.positions,e.indexed=!0,e};var ha=Math.pow(2,53)-1;function fa(t){var e=+t;return !isNaN(e)&&e<=ha?e:la(String(t))}function ya(t,e,r){var n=t[e];t[e]=t[r],t[r]=n;}Fn("FeaturePositionMap",ca);var da=function(t,e){this.gl=t.gl,this.location=e;},ma=function(t){function e(e,r){t.call(this,e,r),this.current=0;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.set=function(t){this.current!==t&&(this.current=t,this.gl.uniform1i(this.location,t));},e}(da),va=function(t){function e(e,r){t.call(this,e,r),this.current=0;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.set=function(t){this.current!==t&&(this.current=t,this.gl.uniform1f(this.location,t));},e}(da),ga=function(t){function e(e,r){t.call(this,e,r),this.current=[0,0];}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.set=function(t){t[0]===this.current[0]&&t[1]===this.current[1]||(this.current=t,this.gl.uniform2f(this.location,t[0],t[1]));},e}(da),xa=function(t){function e(e,r){t.call(this,e,r),this.current=[0,0,0];}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.set=function(t){t[0]===this.current[0]&&t[1]===this.current[1]&&t[2]===this.current[2]||(this.current=t,this.gl.uniform3f(this.location,t[0],t[1],t[2]));},e}(da),ba=function(t){function e(e,r){t.call(this,e,r),this.current=[0,0,0,0];}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.set=function(t){t[0]===this.current[0]&&t[1]===this.current[1]&&t[2]===this.current[2]&&t[3]===this.current[3]||(this.current=t,this.gl.uniform4f(this.location,t[0],t[1],t[2],t[3]));},e}(da),wa=function(t){function e(e,r){t.call(this,e,r),this.current=$t.transparent;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.set=function(t){t.r===this.current.r&&t.g===this.current.g&&t.b===this.current.b&&t.a===this.current.a||(this.current=t,this.gl.uniform4f(this.location,t.r,t.g,t.b,t.a));},e}(da),_a=new Float32Array(16),Aa=function(t){function e(e,r){t.call(this,e,r),this.current=_a;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.set=function(t){if(t[12]!==this.current[12]||t[0]!==this.current[0])return this.current=t,void this.gl.uniformMatrix4fv(this.location,!1,t);for(var e=1;e<16;e++)if(t[e]!==this.current[e]){this.current=t,this.gl.uniformMatrix4fv(this.location,!1,t);break}},e}(da);function Sa(t){return [aa(255*t.r,255*t.g),aa(255*t.b,255*t.a)]}var ka=function(t,e,r){this.value=t,this.uniformNames=e.map((function(t){return "u_"+t})),this.type=r;};ka.prototype.setUniform=function(t,e,r){t.set(r.constantOr(this.value));},ka.prototype.getBinding=function(t,e,r){return "color"===this.type?new wa(t,e):new va(t,e)};var Ia=function(t,e){this.uniformNames=e.map((function(t){return "u_"+t})),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1;};Ia.prototype.setConstantPatternPositions=function(t,e){this.pixelRatioFrom=e.pixelRatio,this.pixelRatioTo=t.pixelRatio,this.patternFrom=e.tlbr,this.patternTo=t.tlbr;},Ia.prototype.setUniform=function(t,e,r,n){var i="u_pattern_to"===n?this.patternTo:"u_pattern_from"===n?this.patternFrom:"u_pixel_ratio_to"===n?this.pixelRatioTo:"u_pixel_ratio_from"===n?this.pixelRatioFrom:null;i&&t.set(i);},Ia.prototype.getBinding=function(t,e,r){return "u_pattern"===r.substr(0,9)?new ba(t,e):new va(t,e)};var za=function(t,e,r,n){this.expression=t,this.type=r,this.maxValue=0,this.paintVertexAttributes=e.map((function(t){return {name:"a_"+t,type:"Float32",components:"color"===r?2:1,offset:0}})),this.paintVertexArray=new n;};za.prototype.populatePaintArray=function(t,e,r,n,i){var a=this.paintVertexArray.length,o=this.expression.evaluate(new ii(0),e,{},n,[],i);this.paintVertexArray.resize(t),this._setPaintValue(a,t,o);},za.prototype.updatePaintArray=function(t,e,r,n){var i=this.expression.evaluate({zoom:0},r,n);this._setPaintValue(t,e,i);},za.prototype._setPaintValue=function(t,e,r){if("color"===this.type)for(var n=Sa(r),i=t;i<e;i++)this.paintVertexArray.emplace(i,n[0],n[1]);else {for(var a=t;a<e;a++)this.paintVertexArray.emplace(a,r);this.maxValue=Math.max(this.maxValue,Math.abs(r));}},za.prototype.upload=function(t){this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer&&this.paintVertexBuffer.buffer?this.paintVertexBuffer.updateData(this.paintVertexArray):this.paintVertexBuffer=t.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes,this.expression.isStateDependent));},za.prototype.destroy=function(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy();};var Ca=function(t,e,r,n,i,a){this.expression=t,this.uniformNames=e.map((function(t){return "u_"+t+"_t"})),this.type=r,this.useIntegerZoom=n,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=e.map((function(t){return {name:"a_"+t,type:"Float32",components:"color"===r?4:2,offset:0}})),this.paintVertexArray=new a;};Ca.prototype.populatePaintArray=function(t,e,r,n,i){var a=this.expression.evaluate(new ii(this.zoom),e,{},n,[],i),o=this.expression.evaluate(new ii(this.zoom+1),e,{},n,[],i),s=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(s,t,a,o);},Ca.prototype.updatePaintArray=function(t,e,r,n){var i=this.expression.evaluate({zoom:this.zoom},r,n),a=this.expression.evaluate({zoom:this.zoom+1},r,n);this._setPaintValue(t,e,i,a);},Ca.prototype._setPaintValue=function(t,e,r,n){if("color"===this.type)for(var i=Sa(r),a=Sa(n),o=t;o<e;o++)this.paintVertexArray.emplace(o,i[0],i[1],a[0],a[1]);else {for(var s=t;s<e;s++)this.paintVertexArray.emplace(s,r,n);this.maxValue=Math.max(this.maxValue,Math.abs(r),Math.abs(n));}},Ca.prototype.upload=function(t){this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer&&this.paintVertexBuffer.buffer?this.paintVertexBuffer.updateData(this.paintVertexArray):this.paintVertexBuffer=t.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes,this.expression.isStateDependent));},Ca.prototype.destroy=function(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy();},Ca.prototype.setUniform=function(t,e){var r=this.useIntegerZoom?Math.floor(e.zoom):e.zoom,n=u(this.expression.interpolationFactor(r,this.zoom,this.zoom+1),0,1);t.set(n);},Ca.prototype.getBinding=function(t,e,r){return new va(t,e)};var Ma=function(t,e,r,n,i,a){this.expression=t,this.type=e,this.useIntegerZoom=r,this.zoom=n,this.layerId=a,this.zoomInPaintVertexArray=new i,this.zoomOutPaintVertexArray=new i;};Ma.prototype.populatePaintArray=function(t,e,r){var n=this.zoomInPaintVertexArray.length;this.zoomInPaintVertexArray.resize(t),this.zoomOutPaintVertexArray.resize(t),this._setPaintValues(n,t,e.patterns&&e.patterns[this.layerId],r);},Ma.prototype.updatePaintArray=function(t,e,r,n,i){this._setPaintValues(t,e,r.patterns&&r.patterns[this.layerId],i);},Ma.prototype._setPaintValues=function(t,e,r,n){if(n&&r){var i=n[r.min],a=n[r.mid],o=n[r.max];if(i&&a&&o)for(var s=t;s<e;s++)this.zoomInPaintVertexArray.emplace(s,a.tl[0],a.tl[1],a.br[0],a.br[1],i.tl[0],i.tl[1],i.br[0],i.br[1],a.pixelRatio,i.pixelRatio),this.zoomOutPaintVertexArray.emplace(s,a.tl[0],a.tl[1],a.br[0],a.br[1],o.tl[0],o.tl[1],o.br[0],o.br[1],a.pixelRatio,o.pixelRatio);}},Ma.prototype.upload=function(t){this.zoomInPaintVertexArray&&this.zoomInPaintVertexArray.arrayBuffer&&this.zoomOutPaintVertexArray&&this.zoomOutPaintVertexArray.arrayBuffer&&(this.zoomInPaintVertexBuffer=t.createVertexBuffer(this.zoomInPaintVertexArray,oa.members,this.expression.isStateDependent),this.zoomOutPaintVertexBuffer=t.createVertexBuffer(this.zoomOutPaintVertexArray,oa.members,this.expression.isStateDependent));},Ma.prototype.destroy=function(){this.zoomOutPaintVertexBuffer&&this.zoomOutPaintVertexBuffer.destroy(),this.zoomInPaintVertexBuffer&&this.zoomInPaintVertexBuffer.destroy();};var Ea=function(t,e,r,n){this.binders={},this.layoutAttributes=n,this._buffers=[];var i=[];for(var a in t.paint._values)if(r(a)){var o=t.paint.get(a);if(o instanceof ci&&Er(o.property.specification)){var s=Pa(a,t.type),u=o.value,l=o.property.specification.type,p=o.property.useIntegerZoom,c=o.property.specification["property-type"],h="cross-faded"===c||"cross-faded-data-driven"===c;if("constant"===u.kind)this.binders[a]=h?new Ia(u.value,s):new ka(u.value,s,l),i.push("/u_"+a);else if("source"===u.kind||h){var f=Ba(a,l,"source");this.binders[a]=h?new Ma(u,l,p,e,f,t.id):new za(u,s,l,f),i.push("/a_"+a);}else {var y=Ba(a,l,"composite");this.binders[a]=new Ca(u,s,l,p,e,y),i.push("/z_"+a);}}}this.cacheKey=i.sort().join("");};Ea.prototype.getMaxValue=function(t){var e=this.binders[t];return e instanceof za||e instanceof Ca?e.maxValue:0},Ea.prototype.populatePaintArrays=function(t,e,r,n,i){for(var a in this.binders){var o=this.binders[a];(o instanceof za||o instanceof Ca||o instanceof Ma)&&o.populatePaintArray(t,e,r,n,i);}},Ea.prototype.setConstantPatternPositions=function(t,e){for(var r in this.binders){var n=this.binders[r];n instanceof Ia&&n.setConstantPatternPositions(t,e);}},Ea.prototype.updatePaintArrays=function(t,e,r,n,i){var a=!1;for(var o in t)for(var s=0,u=e.getPositions(o);s<u.length;s+=1){var l=u[s],p=r.feature(l.index);for(var c in this.binders){var h=this.binders[c];if((h instanceof za||h instanceof Ca||h instanceof Ma)&&!0===h.expression.isStateDependent){var f=n.paint.get(c);h.expression=f.value,h.updatePaintArray(l.start,l.end,p,t[o],i),a=!0;}}}return a},Ea.prototype.defines=function(){var t=[];for(var e in this.binders){var r=this.binders[e];(r instanceof ka||r instanceof Ia)&&t.push.apply(t,r.uniformNames.map((function(t){return "#define HAS_UNIFORM_"+t})));}return t},Ea.prototype.getPaintVertexBuffers=function(){return this._buffers},Ea.prototype.getUniforms=function(t,e){var r=[];for(var n in this.binders){var i=this.binders[n];if(i instanceof ka||i instanceof Ia||i instanceof Ca)for(var a=0,o=i.uniformNames;a<o.length;a+=1){var s=o[a];if(e[s]){var u=i.getBinding(t,e[s],s);r.push({name:s,property:n,binding:u});}}}return r},Ea.prototype.setUniforms=function(t,e,r,n){for(var i=0,a=e;i<a.length;i+=1){var o=a[i],s=o.name,u=o.property;this.binders[u].setUniform(o.binding,n,r.get(u),s);}},Ea.prototype.updatePaintBuffers=function(t){for(var e in this._buffers=[],this.binders){var r=this.binders[e];if(t&&r instanceof Ma){var n=2===t.fromScale?r.zoomInPaintVertexBuffer:r.zoomOutPaintVertexBuffer;n&&this._buffers.push(n);}else (r instanceof za||r instanceof Ca)&&r.paintVertexBuffer&&this._buffers.push(r.paintVertexBuffer);}},Ea.prototype.upload=function(t){for(var e in this.binders){var r=this.binders[e];(r instanceof za||r instanceof Ca||r instanceof Ma)&&r.upload(t);}this.updatePaintBuffers();},Ea.prototype.destroy=function(){for(var t in this.binders){var e=this.binders[t];(e instanceof za||e instanceof Ca||e instanceof Ma)&&e.destroy();}};var Ta=function(t,e,r,n){void 0===n&&(n=function(){return !0}),this.programConfigurations={};for(var i=0,a=e;i<a.length;i+=1){var o=a[i];this.programConfigurations[o.id]=new Ea(o,r,n,t);}this.needsUpload=!1,this._featureMap=new ca,this._bufferOffset=0;};function Pa(t,e){return {"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[t]||[t.replace(e+"-","").replace(/-/g,"_")]}function Ba(t,e,r){var n={color:{source:Gi,composite:Zi},number:{source:Ui,composite:Gi}},i=function(t){return {"line-pattern":{source:Mi,composite:Mi},"fill-pattern":{source:Mi,composite:Mi},"fill-extrusion-pattern":{source:Mi,composite:Mi}}[t]}(t);return i&&i[r]||n[e][r]}Ta.prototype.populatePaintArrays=function(t,e,r,n,i,a){for(var o in this.programConfigurations)this.programConfigurations[o].populatePaintArrays(t,e,n,i,a);void 0!==e.id&&this._featureMap.add(e.id,r,this._bufferOffset,t),this._bufferOffset=t,this.needsUpload=!0;},Ta.prototype.updatePaintArrays=function(t,e,r,n){for(var i=0,a=r;i<a.length;i+=1){var o=a[i];this.needsUpload=this.programConfigurations[o.id].updatePaintArrays(t,this._featureMap,e,o,n)||this.needsUpload;}},Ta.prototype.get=function(t){return this.programConfigurations[t]},Ta.prototype.upload=function(t){if(this.needsUpload){for(var e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=!1;}},Ta.prototype.destroy=function(){for(var t in this.programConfigurations)this.programConfigurations[t].destroy();},Fn("ConstantBinder",ka),Fn("CrossFadedConstantBinder",Ia),Fn("SourceExpressionBinder",za),Fn("CrossFadedCompositeBinder",Ma),Fn("CompositeExpressionBinder",Ca),Fn("ProgramConfiguration",Ea,{omit:["_buffers"]}),Fn("ProgramConfigurationSet",Ta);var Va={min:-1*Math.pow(2,14),max:Math.pow(2,14)-1};function Fa(t){for(var e=8192/t.extent,r=t.loadGeometry(),n=0;n<r.length;n++)for(var i=r[n],a=0;a<i.length;a++){var o=i[a];o.x=Math.round(o.x*e),o.y=Math.round(o.y*e),(o.x<Va.min||o.x>Va.max||o.y<Va.min||o.y>Va.max)&&(w("Geometry exceeds allowed extent, reduce your vector tile buffer size"),o.x=u(o.x,Va.min,Va.max),o.y=u(o.y,Va.min,Va.max));}return r}function Da(t,e,r,n,i){t.emplaceBack(2*e+(n+1)/2,2*r+(i+1)/2);}var La=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new ki,this.indexArray=new Li,this.segments=new ia,this.programConfigurations=new Ta(na,t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};function Ra(t,e){for(var r=0;r<t.length;r++)if(Xa(e,t[r]))return !0;for(var n=0;n<e.length;n++)if(Xa(t,e[n]))return !0;return !!qa(t,e)}function Oa(t,e,r){return !!Xa(t,e)||!!Ka(e,t,r)}function Ua(t,e){if(1===t.length)return Za(e,t[0]);for(var r=0;r<e.length;r++)for(var n=e[r],i=0;i<n.length;i++)if(Xa(t,n[i]))return !0;for(var a=0;a<t.length;a++)if(Za(e,t[a]))return !0;for(var o=0;o<e.length;o++)if(qa(t,e[o]))return !0;return !1}function ja(t,e,r){if(t.length>1){if(qa(t,e))return !0;for(var n=0;n<e.length;n++)if(Ka(e[n],t,r))return !0}for(var i=0;i<t.length;i++)if(Ka(t[i],e,r))return !0;return !1}function qa(t,e){if(0===t.length||0===e.length)return !1;for(var r=0;r<t.length-1;r++)for(var n=t[r],i=t[r+1],a=0;a<e.length-1;a++)if(Na(n,i,e[a],e[a+1]))return !0;return !1}function Na(t,e,r,n){return _(t,r,n)!==_(e,r,n)&&_(t,e,r)!==_(t,e,n)}function Ka(t,e,r){var n=r*r;if(1===e.length)return t.distSqr(e[0])<n;for(var i=1;i<e.length;i++)if(Ga(t,e[i-1],e[i])<n)return !0;return !1}function Ga(t,e,r){var n=e.distSqr(r);if(0===n)return t.distSqr(e);var i=((t.x-e.x)*(r.x-e.x)+(t.y-e.y)*(r.y-e.y))/n;return t.distSqr(i<0?e:i>1?r:r.sub(e)._mult(i)._add(e))}function Za(t,e){for(var r,n,i,a=!1,o=0;o<t.length;o++)for(var s=0,u=(r=t[o]).length-1;s<r.length;u=s++)(n=r[s]).y>e.y!=(i=r[u]).y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(a=!a);return a}function Xa(t,e){for(var r=!1,n=0,i=t.length-1;n<t.length;i=n++){var a=t[n],o=t[i];a.y>e.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(r=!r);}return r}function Ja(t,e,r){var n=r[0],i=r[2];if(t.x<n.x&&e.x<n.x||t.x>i.x&&e.x>i.x||t.y<n.y&&e.y<n.y||t.y>i.y&&e.y>i.y)return !1;var a=_(t,e,r[0]);return a!==_(t,e,r[1])||a!==_(t,e,r[2])||a!==_(t,e,r[3])}function Ha(t,e,r){var n=e.paint.get(t).value;return "constant"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function Ya(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function $a(t,e,r,n,a){if(!e[0]&&!e[1])return t;var o=i.convert(e)._mult(a);"viewport"===r&&o._rotate(-n);for(var s=[],u=0;u<t.length;u++)s.push(t[u].sub(o));return s}La.prototype.populate=function(t,e,r){var n=this.layers[0],i=[],a=null;"circle"===n.type&&(a=n.layout.get("circle-sort-key"));for(var o=0,s=t;o<s.length;o+=1){var u=s[o],l=u.feature,p=u.id,c=u.index,h=u.sourceLayerIndex,f=this.layers[0]._featureFilter.needGeometry,y={type:l.type,id:p,properties:l.properties,geometry:f?Fa(l):[]};if(this.layers[0]._featureFilter.filter(new ii(this.zoom),y,r)){f||(y.geometry=Fa(l));var d=a?a.evaluate(y,{},r):void 0;i.push({id:p,properties:l.properties,type:l.type,sourceLayerIndex:h,index:c,geometry:y.geometry,patterns:{},sortKey:d});}}a&&i.sort((function(t,e){return t.sortKey-e.sortKey}));for(var m=0,v=i;m<v.length;m+=1){var g=v[m],x=g.geometry,b=g.index,w=g.sourceLayerIndex,_=t[b].feature;this.addFeature(g,x,b,r),e.featureIndex.insert(_,x,b,w,this.index);}},La.prototype.update=function(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);},La.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},La.prototype.uploadPending=function(){return !this.uploaded||this.programConfigurations.needsUpload},La.prototype.upload=function(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,na),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;},La.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());},La.prototype.addFeature=function(t,e,r,n){for(var i=0,a=e;i<a.length;i+=1)for(var o=0,s=a[i];o<s.length;o+=1){var u=s[o],l=u.x,p=u.y;if(!(l<0||l>=8192||p<0||p>=8192)){var c=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,t.sortKey),h=c.vertexLength;Da(this.layoutVertexArray,l,p,-1,-1),Da(this.layoutVertexArray,l,p,1,-1),Da(this.layoutVertexArray,l,p,1,1),Da(this.layoutVertexArray,l,p,-1,1),this.indexArray.emplaceBack(h,h+1,h+2),this.indexArray.emplaceBack(h,h+3,h+2),c.vertexLength+=4,c.primitiveLength+=2;}}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{},n);},Fn("CircleBucket",La,{omit:["layers"]});var Wa=new gi({"circle-sort-key":new yi(It.layout_circle["circle-sort-key"])}),Qa={paint:new gi({"circle-radius":new yi(It.paint_circle["circle-radius"]),"circle-color":new yi(It.paint_circle["circle-color"]),"circle-blur":new yi(It.paint_circle["circle-blur"]),"circle-opacity":new yi(It.paint_circle["circle-opacity"]),"circle-translate":new fi(It.paint_circle["circle-translate"]),"circle-translate-anchor":new fi(It.paint_circle["circle-translate-anchor"]),"circle-pitch-scale":new fi(It.paint_circle["circle-pitch-scale"]),"circle-pitch-alignment":new fi(It.paint_circle["circle-pitch-alignment"]),"circle-stroke-width":new yi(It.paint_circle["circle-stroke-width"]),"circle-stroke-color":new yi(It.paint_circle["circle-stroke-color"]),"circle-stroke-opacity":new yi(It.paint_circle["circle-stroke-opacity"])}),layout:Wa},to="undefined"!=typeof Float32Array?Float32Array:Array;function eo(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function ro(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],u=e[5],l=e[6],p=e[7],c=e[8],h=e[9],f=e[10],y=e[11],d=e[12],m=e[13],v=e[14],g=e[15],x=r[0],b=r[1],w=r[2],_=r[3];return t[0]=x*n+b*s+w*c+_*d,t[1]=x*i+b*u+w*h+_*m,t[2]=x*a+b*l+w*f+_*v,t[3]=x*o+b*p+w*y+_*g,t[4]=(x=r[4])*n+(b=r[5])*s+(w=r[6])*c+(_=r[7])*d,t[5]=x*i+b*u+w*h+_*m,t[6]=x*a+b*l+w*f+_*v,t[7]=x*o+b*p+w*y+_*g,t[8]=(x=r[8])*n+(b=r[9])*s+(w=r[10])*c+(_=r[11])*d,t[9]=x*i+b*u+w*h+_*m,t[10]=x*a+b*l+w*f+_*v,t[11]=x*o+b*p+w*y+_*g,t[12]=(x=r[12])*n+(b=r[13])*s+(w=r[14])*c+(_=r[15])*d,t[13]=x*i+b*u+w*h+_*m,t[14]=x*a+b*l+w*f+_*v,t[15]=x*o+b*p+w*y+_*g,t}Math.hypot||(Math.hypot=function(){for(var t=arguments,e=0,r=arguments.length;r--;)e+=t[r]*t[r];return Math.sqrt(e)});var no,io=ro;function ao(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t}no=new to(3),to!=Float32Array&&(no[0]=0,no[1]=0,no[2]=0),function(){var t=new to(4);to!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0);}();var oo=(function(){var t=new to(2);to!=Float32Array&&(t[0]=0,t[1]=0);}(),function(t){function e(e){t.call(this,e,Qa);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.createBucket=function(t){return new La(t)},e.prototype.queryRadius=function(t){var e=t;return Ha("circle-radius",this,e)+Ha("circle-stroke-width",this,e)+Ya(this.paint.get("circle-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,a,o,s){for(var u=$a(t,this.paint.get("circle-translate"),this.paint.get("circle-translate-anchor"),a.angle,o),l=this.paint.get("circle-radius").evaluate(e,r)+this.paint.get("circle-stroke-width").evaluate(e,r),p="map"===this.paint.get("circle-pitch-alignment"),c=p?u:function(t,e){return t.map((function(t){return so(t,e)}))}(u,s),h=p?l*o:l,f=0,y=n;f<y.length;f+=1)for(var d=0,m=y[f];d<m.length;d+=1){var v=m[d],g=p?v:so(v,s),x=h,b=ao([],[v.x,v.y,0,1],s);if("viewport"===this.paint.get("circle-pitch-scale")&&"map"===this.paint.get("circle-pitch-alignment")?x*=b[3]/a.cameraToCenterDistance:"map"===this.paint.get("circle-pitch-scale")&&"viewport"===this.paint.get("circle-pitch-alignment")&&(x*=a.cameraToCenterDistance/b[3]),Oa(c,g,x))return !0}return !1},e}(xi));function so(t,e){var r=ao([],[t.x,t.y,0,1],e);return new i(r[0]/r[3],r[1]/r[3])}var uo=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e}(La);function lo(t,e,r,n){var i=e.width,a=e.height;if(n){if(n instanceof Uint8ClampedArray)n=new Uint8Array(n.buffer);else if(n.length!==i*a*r)throw new RangeError("mismatched image size")}else n=new Uint8Array(i*a*r);return t.width=i,t.height=a,t.data=n,t}function po(t,e,r){var n=e.width,i=e.height;if(n!==t.width||i!==t.height){var a=lo({},{width:n,height:i},r);co(t,a,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,n),height:Math.min(t.height,i)},r),t.width=n,t.height=i,t.data=a.data;}}function co(t,e,r,n,i,a){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");for(var o=t.data,s=e.data,u=0;u<i.height;u++)for(var l=((r.y+u)*t.width+r.x)*a,p=((n.y+u)*e.width+n.x)*a,c=0;c<i.width*a;c++)s[p+c]=o[l+c];return e}Fn("HeatmapBucket",uo,{omit:["layers"]});var ho=function(t,e){lo(this,t,1,e);};ho.prototype.resize=function(t){po(this,t,1);},ho.prototype.clone=function(){return new ho({width:this.width,height:this.height},new Uint8Array(this.data))},ho.copy=function(t,e,r,n,i){co(t,e,r,n,i,1);};var fo=function(t,e){lo(this,t,4,e);};fo.prototype.resize=function(t){po(this,t,4);},fo.prototype.replace=function(t,e){e?this.data.set(t):this.data=t instanceof Uint8ClampedArray?new Uint8Array(t.buffer):t;},fo.prototype.clone=function(){return new fo({width:this.width,height:this.height},new Uint8Array(this.data))},fo.copy=function(t,e,r,n,i){co(t,e,r,n,i,4);},Fn("AlphaImage",ho),Fn("RGBAImage",fo);var yo={paint:new gi({"heatmap-radius":new yi(It.paint_heatmap["heatmap-radius"]),"heatmap-weight":new yi(It.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new fi(It.paint_heatmap["heatmap-intensity"]),"heatmap-color":new vi(It.paint_heatmap["heatmap-color"]),"heatmap-opacity":new fi(It.paint_heatmap["heatmap-opacity"])})};function mo(t,e){for(var r=new Uint8Array(1024),n={},i=0,a=0;i<256;i++,a+=4){n[e]=i/255;var o=t.evaluate(n);r[a+0]=Math.floor(255*o.r/o.a),r[a+1]=Math.floor(255*o.g/o.a),r[a+2]=Math.floor(255*o.b/o.a),r[a+3]=Math.floor(255*o.a);}return new fo({width:256,height:1},r)}var vo=function(t){function e(e){t.call(this,e,yo),this._updateColorRamp();}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.createBucket=function(t){return new uo(t)},e.prototype._handleSpecialPaintPropertyUpdate=function(t){"heatmap-color"===t&&this._updateColorRamp();},e.prototype._updateColorRamp=function(){this.colorRamp=mo(this._transitionablePaint._values["heatmap-color"].value.expression,"heatmapDensity"),this.colorRampTexture=null;},e.prototype.resize=function(){this.heatmapFbo&&(this.heatmapFbo.destroy(),this.heatmapFbo=null);},e.prototype.queryRadius=function(){return 0},e.prototype.queryIntersectsFeature=function(){return !1},e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("heatmap-opacity")&&"none"!==this.visibility},e}(xi),go={paint:new gi({"hillshade-illumination-direction":new fi(It.paint_hillshade["hillshade-illumination-direction"]),"hillshade-illumination-anchor":new fi(It.paint_hillshade["hillshade-illumination-anchor"]),"hillshade-exaggeration":new fi(It.paint_hillshade["hillshade-exaggeration"]),"hillshade-shadow-color":new fi(It.paint_hillshade["hillshade-shadow-color"]),"hillshade-highlight-color":new fi(It.paint_hillshade["hillshade-highlight-color"]),"hillshade-accent-color":new fi(It.paint_hillshade["hillshade-accent-color"])})},xo=function(t){function e(e){t.call(this,e,go);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("hillshade-exaggeration")&&"none"!==this.visibility},e}(xi),bo=Ai([{name:"a_pos",components:2,type:"Int16"}],4).members,wo=Ao,_o=Ao;function Ao(t,e,r){r=r||2;var n,i,a,o,s,u,l,p=e&&e.length,c=p?e[0]*r:t.length,h=So(t,0,c,r,!0),f=[];if(!h||h.next===h.prev)return f;if(p&&(h=function(t,e,r,n){var i,a,o,s=[];for(i=0,a=e.length;i<a;i++)(o=So(t,e[i]*n,i<a-1?e[i+1]*n:t.length,n,!1))===o.next&&(o.steiner=!0),s.push(Fo(o));for(s.sort(To),i=0;i<s.length;i++)Po(s[i],r),r=ko(r,r.next);return r}(t,e,h,r)),t.length>80*r){n=a=t[0],i=o=t[1];for(var y=r;y<c;y+=r)(s=t[y])<n&&(n=s),(u=t[y+1])<i&&(i=u),s>a&&(a=s),u>o&&(o=u);l=0!==(l=Math.max(a-n,o-i))?1/l:0;}return Io(h,f,r,n,i,l),f}function So(t,e,r,n,i){var a,o;if(i===Jo(t,e,r,n)>0)for(a=e;a<r;a+=n)o=Go(a,t[a],t[a+1],o);else for(a=r-n;a>=e;a-=n)o=Go(a,t[a],t[a+1],o);return o&&Oo(o,o.next)&&(Zo(o),o=o.next),o}function ko(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!Oo(n,n.next)&&0!==Ro(n.prev,n,n.next))n=n.next;else {if(Zo(n),(n=e=n.prev)===n.next)break;r=!0;}}while(r||n!==e);return e}function Io(t,e,r,n,i,a,o){if(t){!o&&a&&function(t,e,r,n){var i=t;do{null===i.z&&(i.z=Vo(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,a,o,s,u,l=1;do{for(r=t,t=null,a=null,o=0;r;){for(o++,n=r,s=0,e=0;e<l&&(s++,n=n.nextZ);e++);for(u=l;s>0||u>0&&n;)0!==s&&(0===u||!n||r.z<=n.z)?(i=r,r=r.nextZ,s--):(i=n,n=n.nextZ,u--),a?a.nextZ=i:t=i,i.prevZ=a,a=i;r=n;}a.nextZ=null,l*=2;}while(o>1)}(i);}(t,n,i,a);for(var s,u,l=t;t.prev!==t.next;)if(s=t.prev,u=t.next,a?Co(t,n,i,a):zo(t))e.push(s.i/r),e.push(t.i/r),e.push(u.i/r),Zo(t),t=u.next,l=u.next;else if((t=u)===l){o?1===o?Io(t=Mo(ko(t),e,r),e,r,n,i,a,2):2===o&&Eo(t,e,r,n,i,a):Io(ko(t),e,r,n,i,a,1);break}}}function zo(t){var e=t.prev,r=t,n=t.next;if(Ro(e,r,n)>=0)return !1;for(var i=t.next.next;i!==t.prev;){if(Do(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&Ro(i.prev,i,i.next)>=0)return !1;i=i.next;}return !0}function Co(t,e,r,n){var i=t.prev,a=t,o=t.next;if(Ro(i,a,o)>=0)return !1;for(var s=i.x>a.x?i.x>o.x?i.x:o.x:a.x>o.x?a.x:o.x,u=i.y>a.y?i.y>o.y?i.y:o.y:a.y>o.y?a.y:o.y,l=Vo(i.x<a.x?i.x<o.x?i.x:o.x:a.x<o.x?a.x:o.x,i.y<a.y?i.y<o.y?i.y:o.y:a.y<o.y?a.y:o.y,e,r,n),p=Vo(s,u,e,r,n),c=t.prevZ,h=t.nextZ;c&&c.z>=l&&h&&h.z<=p;){if(c!==t.prev&&c!==t.next&&Do(i.x,i.y,a.x,a.y,o.x,o.y,c.x,c.y)&&Ro(c.prev,c,c.next)>=0)return !1;if(c=c.prevZ,h!==t.prev&&h!==t.next&&Do(i.x,i.y,a.x,a.y,o.x,o.y,h.x,h.y)&&Ro(h.prev,h,h.next)>=0)return !1;h=h.nextZ;}for(;c&&c.z>=l;){if(c!==t.prev&&c!==t.next&&Do(i.x,i.y,a.x,a.y,o.x,o.y,c.x,c.y)&&Ro(c.prev,c,c.next)>=0)return !1;c=c.prevZ;}for(;h&&h.z<=p;){if(h!==t.prev&&h!==t.next&&Do(i.x,i.y,a.x,a.y,o.x,o.y,h.x,h.y)&&Ro(h.prev,h,h.next)>=0)return !1;h=h.nextZ;}return !0}function Mo(t,e,r){var n=t;do{var i=n.prev,a=n.next.next;!Oo(i,a)&&Uo(i,n,n.next,a)&&No(i,a)&&No(a,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(a.i/r),Zo(n),Zo(n.next),n=t=a),n=n.next;}while(n!==t);return ko(n)}function Eo(t,e,r,n,i,a){var o=t;do{for(var s=o.next.next;s!==o.prev;){if(o.i!==s.i&&Lo(o,s)){var u=Ko(o,s);return o=ko(o,o.next),u=ko(u,u.next),Io(o,e,r,n,i,a),void Io(u,e,r,n,i,a)}s=s.next;}o=o.next;}while(o!==t)}function To(t,e){return t.x-e.x}function Po(t,e){if(e=function(t,e){var r,n=e,i=t.x,a=t.y,o=-1/0;do{if(a<=n.y&&a>=n.next.y&&n.next.y!==n.y){var s=n.x+(a-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(s<=i&&s>o){if(o=s,s===i){if(a===n.y)return n;if(a===n.next.y)return n.next}r=n.x<n.next.x?n:n.next;}}n=n.next;}while(n!==e);if(!r)return null;if(i===o)return r;var u,l=r,p=r.x,c=r.y,h=1/0;n=r;do{i>=n.x&&n.x>=p&&i!==n.x&&Do(a<c?i:o,a,p,c,a<c?o:i,a,n.x,n.y)&&(u=Math.abs(a-n.y)/(i-n.x),No(n,t)&&(u<h||u===h&&(n.x>r.x||n.x===r.x&&Bo(r,n)))&&(r=n,h=u)),n=n.next;}while(n!==l);return r}(t,e)){var r=Ko(e,t);ko(e,e.next),ko(r,r.next);}}function Bo(t,e){return Ro(t.prev,t,e.prev)<0&&Ro(e.next,t,t.next)<0}function Vo(t,e,r,n,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function Fo(t){var e=t,r=t;do{(e.x<r.x||e.x===r.x&&e.y<r.y)&&(r=e),e=e.next;}while(e!==t);return r}function Do(t,e,r,n,i,a,o,s){return (i-o)*(e-s)-(t-o)*(a-s)>=0&&(t-o)*(n-s)-(r-o)*(e-s)>=0&&(r-o)*(a-s)-(i-o)*(n-s)>=0}function Lo(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&Uo(r,r.next,t,e))return !0;r=r.next;}while(r!==t);return !1}(t,e)&&(No(t,e)&&No(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)&&(Ro(t.prev,t,e.prev)||Ro(t,e.prev,e))||Oo(t,e)&&Ro(t.prev,t,t.next)>0&&Ro(e.prev,e,e.next)>0)}function Ro(t,e,r){return (e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Oo(t,e){return t.x===e.x&&t.y===e.y}function Uo(t,e,r,n){var i=qo(Ro(t,e,r)),a=qo(Ro(t,e,n)),o=qo(Ro(r,n,t)),s=qo(Ro(r,n,e));return i!==a&&o!==s||!(0!==i||!jo(t,r,e))||!(0!==a||!jo(t,n,e))||!(0!==o||!jo(r,t,n))||!(0!==s||!jo(r,e,n))}function jo(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function qo(t){return t>0?1:t<0?-1:0}function No(t,e){return Ro(t.prev,t,t.next)<0?Ro(t,e,t.next)>=0&&Ro(t,t.prev,e)>=0:Ro(t,e,t.prev)<0||Ro(t,t.next,e)<0}function Ko(t,e){var r=new Xo(t.i,t.x,t.y),n=new Xo(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function Go(t,e,r,n){var i=new Xo(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Zo(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ);}function Xo(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1;}function Jo(t,e,r,n){for(var i=0,a=e,o=r-n;a<r;a+=n)i+=(t[o]-t[a])*(t[a+1]+t[o+1]),o=a;return i}function Ho(t,e,r,n,i){!function t(e,r,n,i,a){for(;i>n;){if(i-n>600){var o=i-n+1,s=r-n+1,u=Math.log(o),l=.5*Math.exp(2*u/3),p=.5*Math.sqrt(u*l*(o-l)/o)*(s-o/2<0?-1:1);t(e,r,Math.max(n,Math.floor(r-s*l/o+p)),Math.min(i,Math.floor(r+(o-s)*l/o+p)),a);}var c=e[r],h=n,f=i;for(Yo(e,n,r),a(e[i],c)>0&&Yo(e,n,i);h<f;){for(Yo(e,h,f),h++,f--;a(e[h],c)<0;)h++;for(;a(e[f],c)>0;)f--;}0===a(e[n],c)?Yo(e,n,f):Yo(e,++f,i),f<=r&&(n=f+1),r<=f&&(i=f-1);}}(t,e,r||0,n||t.length-1,i||$o);}function Yo(t,e,r){var n=t[e];t[e]=t[r],t[r]=n;}function $o(t,e){return t<e?-1:t>e?1:0}function Wo(t,e){var r=t.length;if(r<=1)return [t];for(var n,i,a=[],o=0;o<r;o++){var s=A(t[o]);0!==s&&(t[o].area=Math.abs(s),void 0===i&&(i=s<0),i===s<0?(n&&a.push(n),n=[t[o]]):n.push(t[o]));}if(n&&a.push(n),e>1)for(var u=0;u<a.length;u++)a[u].length<=e||(Ho(a[u],e,1,a[u].length-1,Qo),a[u]=a[u].slice(0,e));return a}function Qo(t,e){return e.area-t.area}function ts(t,e,r){for(var n=r.patternDependencies,i=!1,a=0,o=e;a<o.length;a+=1){var s=o[a].paint.get(t+"-pattern");s.isConstant()||(i=!0);var u=s.constantOr(null);u&&(i=!0,n[u.to]=!0,n[u.from]=!0);}return i}function es(t,e,r,n,i){for(var a=i.patternDependencies,o=0,s=e;o<s.length;o+=1){var u=s[o],l=u.paint.get(t+"-pattern").value;if("constant"!==l.kind){var p=l.evaluate({zoom:n-1},r,{},i.availableImages),c=l.evaluate({zoom:n},r,{},i.availableImages),h=l.evaluate({zoom:n+1},r,{},i.availableImages);c=c&&c.name?c.name:c,h=h&&h.name?h.name:h,a[p=p&&p.name?p.name:p]=!0,a[c]=!0,a[h]=!0,r.patterns[u.id]={min:p,mid:c,max:h};}}return r}Ao.deviation=function(t,e,r,n){var i=e&&e.length,a=Math.abs(Jo(t,0,i?e[0]*r:t.length,r));if(i)for(var o=0,s=e.length;o<s;o++)a-=Math.abs(Jo(t,e[o]*r,o<s-1?e[o+1]*r:t.length,r));var u=0;for(o=0;o<n.length;o+=3){var l=n[o]*r,p=n[o+1]*r,c=n[o+2]*r;u+=Math.abs((t[l]-t[c])*(t[p+1]-t[l+1])-(t[l]-t[p])*(t[c+1]-t[l+1]));}return 0===a&&0===u?0:Math.abs((u-a)/a)},Ao.flatten=function(t){for(var e=t[0][0].length,r={vertices:[],holes:[],dimensions:e},n=0,i=0;i<t.length;i++){for(var a=0;a<t[i].length;a++)for(var o=0;o<e;o++)r.vertices.push(t[i][a][o]);i>0&&r.holes.push(n+=t[i-1].length);}return r},wo.default=_o;var rs=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new ki,this.indexArray=new Li,this.indexArray2=new Ni,this.programConfigurations=new Ta(bo,t.layers,t.zoom),this.segments=new ia,this.segments2=new ia,this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};rs.prototype.populate=function(t,e,r){this.hasPattern=ts("fill",this.layers,e);for(var n=this.layers[0].layout.get("fill-sort-key"),i=[],a=0,o=t;a<o.length;a+=1){var s=o[a],u=s.feature,l=s.id,p=s.index,c=s.sourceLayerIndex,h=this.layers[0]._featureFilter.needGeometry,f={type:u.type,id:l,properties:u.properties,geometry:h?Fa(u):[]};if(this.layers[0]._featureFilter.filter(new ii(this.zoom),f,r)){h||(f.geometry=Fa(u));var y=n?n.evaluate(f,{},r,e.availableImages):void 0;i.push({id:l,properties:u.properties,type:u.type,sourceLayerIndex:c,index:p,geometry:f.geometry,patterns:{},sortKey:y});}}n&&i.sort((function(t,e){return t.sortKey-e.sortKey}));for(var d=0,m=i;d<m.length;d+=1){var v=m[d],g=v.geometry,x=v.index,b=v.sourceLayerIndex;if(this.hasPattern){var w=es("fill",this.layers,v,this.zoom,e);this.patternFeatures.push(w);}else this.addFeature(v,g,x,r,{});e.featureIndex.insert(t[x].feature,g,x,b,this.index);}},rs.prototype.update=function(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);},rs.prototype.addFeatures=function(t,e,r){for(var n=0,i=this.patternFeatures;n<i.length;n+=1){var a=i[n];this.addFeature(a,a.geometry,a.index,e,r);}},rs.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},rs.prototype.uploadPending=function(){return !this.uploaded||this.programConfigurations.needsUpload},rs.prototype.upload=function(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,bo),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=!0;},rs.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());},rs.prototype.addFeature=function(t,e,r,n,i){for(var a=0,o=Wo(e,500);a<o.length;a+=1){for(var s=o[a],u=0,l=0,p=s;l<p.length;l+=1)u+=p[l].length;for(var c=this.segments.prepareSegment(u,this.layoutVertexArray,this.indexArray),h=c.vertexLength,f=[],y=[],d=0,m=s;d<m.length;d+=1){var v=m[d];if(0!==v.length){v!==s[0]&&y.push(f.length/2);var g=this.segments2.prepareSegment(v.length,this.layoutVertexArray,this.indexArray2),x=g.vertexLength;this.layoutVertexArray.emplaceBack(v[0].x,v[0].y),this.indexArray2.emplaceBack(x+v.length-1,x),f.push(v[0].x),f.push(v[0].y);for(var b=1;b<v.length;b++)this.layoutVertexArray.emplaceBack(v[b].x,v[b].y),this.indexArray2.emplaceBack(x+b-1,x+b),f.push(v[b].x),f.push(v[b].y);g.vertexLength+=v.length,g.primitiveLength+=v.length;}}for(var w=wo(f,y),_=0;_<w.length;_+=3)this.indexArray.emplaceBack(h+w[_],h+w[_+1],h+w[_+2]);c.vertexLength+=u,c.primitiveLength+=w.length/3;}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,i,n);},Fn("FillBucket",rs,{omit:["layers","patternFeatures"]});var ns=new gi({"fill-sort-key":new yi(It.layout_fill["fill-sort-key"])}),is={paint:new gi({"fill-antialias":new fi(It.paint_fill["fill-antialias"]),"fill-opacity":new yi(It.paint_fill["fill-opacity"]),"fill-color":new yi(It.paint_fill["fill-color"]),"fill-outline-color":new yi(It.paint_fill["fill-outline-color"]),"fill-translate":new fi(It.paint_fill["fill-translate"]),"fill-translate-anchor":new fi(It.paint_fill["fill-translate-anchor"]),"fill-pattern":new di(It.paint_fill["fill-pattern"])}),layout:ns},as=function(t){function e(e){t.call(this,e,is);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.recalculate=function(e,r){t.prototype.recalculate.call(this,e,r);var n=this.paint._values["fill-outline-color"];"constant"===n.value.kind&&void 0===n.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"]);},e.prototype.createBucket=function(t){return new rs(t)},e.prototype.queryRadius=function(){return Ya(this.paint.get("fill-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,a,o){return Ua($a(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),a.angle,o),n)},e.prototype.isTileClipped=function(){return !0},e}(xi),os=Ai([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4).members,ss=us;function us(t,e,r,n,i){this.properties={},this.extent=r,this.type=0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=i,t.readFields(ls,this,e);}function ls(t,e,r){1==t?e.id=r.readVarint():2==t?function(t,e){for(var r=t.readVarint()+t.pos;t.pos<r;){var n=e._keys[t.readVarint()],i=e._values[t.readVarint()];e.properties[n]=i;}}(r,e):3==t?e.type=r.readVarint():4==t&&(e._geometry=r.pos);}function ps(t){for(var e,r,n=0,i=0,a=t.length,o=a-1;i<a;o=i++)n+=((r=t[o]).x-(e=t[i]).x)*(e.y+r.y);return n}us.types=["Unknown","Point","LineString","Polygon"],us.prototype.loadGeometry=function(){var t=this._pbf;t.pos=this._geometry;for(var e,r=t.readVarint()+t.pos,n=1,a=0,o=0,s=0,u=[];t.pos<r;){if(a<=0){var l=t.readVarint();n=7&l,a=l>>3;}if(a--,1===n||2===n)o+=t.readSVarint(),s+=t.readSVarint(),1===n&&(e&&u.push(e),e=[]),e.push(new i(o,s));else {if(7!==n)throw new Error("unknown command "+n);e&&e.push(e[0].clone());}}return e&&u.push(e),u},us.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,a=0,o=1/0,s=-1/0,u=1/0,l=-1/0;t.pos<e;){if(n<=0){var p=t.readVarint();r=7&p,n=p>>3;}if(n--,1===r||2===r)(i+=t.readSVarint())<o&&(o=i),i>s&&(s=i),(a+=t.readSVarint())<u&&(u=a),a>l&&(l=a);else if(7!==r)throw new Error("unknown command "+r)}return [o,u,s,l]},us.prototype.toGeoJSON=function(t,e,r){var n,i,a=this.extent*Math.pow(2,r),o=this.extent*t,s=this.extent*e,u=this.loadGeometry(),l=us.types[this.type];function p(t){for(var e=0;e<t.length;e++){var r=t[e];t[e]=[360*(r.x+o)/a-180,360/Math.PI*Math.atan(Math.exp((180-360*(r.y+s)/a)*Math.PI/180))-90];}}switch(this.type){case 1:var c=[];for(n=0;n<u.length;n++)c[n]=u[n][0];p(u=c);break;case 2:for(n=0;n<u.length;n++)p(u[n]);break;case 3:for(u=function(t){var e=t.length;if(e<=1)return [t];for(var r,n,i=[],a=0;a<e;a++){var o=ps(t[a]);0!==o&&(void 0===n&&(n=o<0),n===o<0?(r&&i.push(r),r=[t[a]]):r.push(t[a]));}return r&&i.push(r),i}(u),n=0;n<u.length;n++)for(i=0;i<u[n].length;i++)p(u[n][i]);}1===u.length?u=u[0]:l="Multi"+l;var h={type:"Feature",geometry:{type:l,coordinates:u},properties:this.properties};return "id"in this&&(h.id=this.id),h};var cs=hs;function hs(t,e){this.version=1,this.name=null,this.extent=4096,this.length=0,this._pbf=t,this._keys=[],this._values=[],this._features=[],t.readFields(fs,this,e),this.length=this._features.length;}function fs(t,e,r){15===t?e.version=r.readVarint():1===t?e.name=r.readString():5===t?e.extent=r.readVarint():2===t?e._features.push(r.pos):3===t?e._keys.push(r.readString()):4===t&&e._values.push(function(t){for(var e=null,r=t.readVarint()+t.pos;t.pos<r;){var n=t.readVarint()>>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null;}return e}(r));}function ys(t,e,r){if(3===t){var n=new cs(r,r.readVarint()+r.pos);n.length&&(e[n.name]=n);}}hs.prototype.feature=function(t){if(t<0||t>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];var e=this._pbf.readVarint()+this._pbf.pos;return new ss(this._pbf,e,this.extent,this._keys,this._values)};var ds={VectorTile:function(t,e){this.layers=t.readFields(ys,{},e);},VectorTileFeature:ss,VectorTileLayer:cs},ms=ds.VectorTileFeature.types,vs=Math.pow(2,13);function gs(t,e,r,n,i,a,o,s){t.emplaceBack(e,r,2*Math.floor(n*vs)+o,i*vs*2,a*vs*2,Math.round(s));}var xs=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new zi,this.indexArray=new Li,this.programConfigurations=new Ta(os,t.layers,t.zoom),this.segments=new ia,this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};function bs(t,e){return t.x===e.x&&(t.x<0||t.x>8192)||t.y===e.y&&(t.y<0||t.y>8192)}xs.prototype.populate=function(t,e,r){this.features=[],this.hasPattern=ts("fill-extrusion",this.layers,e);for(var n=0,i=t;n<i.length;n+=1){var a=i[n],o=a.feature,s=a.id,u=a.index,l=a.sourceLayerIndex,p=this.layers[0]._featureFilter.needGeometry,c={type:o.type,id:s,properties:o.properties,geometry:p?Fa(o):[]};if(this.layers[0]._featureFilter.filter(new ii(this.zoom),c,r)){var h={id:s,sourceLayerIndex:l,index:u,geometry:p?c.geometry:Fa(o),properties:o.properties,type:o.type,patterns:{}};void 0!==o.id&&(h.id=o.id),this.hasPattern?this.features.push(es("fill-extrusion",this.layers,h,this.zoom,e)):this.addFeature(h,h.geometry,u,r,{}),e.featureIndex.insert(o,h.geometry,u,l,this.index,!0);}}},xs.prototype.addFeatures=function(t,e,r){for(var n=0,i=this.features;n<i.length;n+=1){var a=i[n];this.addFeature(a,a.geometry,a.index,e,r);}},xs.prototype.update=function(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);},xs.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},xs.prototype.uploadPending=function(){return !this.uploaded||this.programConfigurations.needsUpload},xs.prototype.upload=function(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,os),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;},xs.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());},xs.prototype.addFeature=function(t,e,r,n,i){for(var a=0,o=Wo(e,500);a<o.length;a+=1){for(var s=o[a],u=0,l=0,p=s;l<p.length;l+=1)u+=p[l].length;for(var c=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray),h=0,f=s;h<f.length;h+=1){var y=f[h];if(0!==y.length&&!((P=y).every((function(t){return t.x<0}))||P.every((function(t){return t.x>8192}))||P.every((function(t){return t.y<0}))||P.every((function(t){return t.y>8192}))))for(var d=0,m=0;m<y.length;m++){var v=y[m];if(m>=1){var g=y[m-1];if(!bs(v,g)){c.vertexLength+4>ia.MAX_VERTEX_ARRAY_LENGTH&&(c=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));var x=v.sub(g)._perp()._unit(),b=g.dist(v);d+b>32768&&(d=0),gs(this.layoutVertexArray,v.x,v.y,x.x,x.y,0,0,d),gs(this.layoutVertexArray,v.x,v.y,x.x,x.y,0,1,d),gs(this.layoutVertexArray,g.x,g.y,x.x,x.y,0,0,d+=b),gs(this.layoutVertexArray,g.x,g.y,x.x,x.y,0,1,d);var w=c.vertexLength;this.indexArray.emplaceBack(w,w+2,w+1),this.indexArray.emplaceBack(w+1,w+2,w+3),c.vertexLength+=4,c.primitiveLength+=2;}}}}if(c.vertexLength+u>ia.MAX_VERTEX_ARRAY_LENGTH&&(c=this.segments.prepareSegment(u,this.layoutVertexArray,this.indexArray)),"Polygon"===ms[t.type]){for(var _=[],A=[],S=c.vertexLength,k=0,I=s;k<I.length;k+=1){var z=I[k];if(0!==z.length){z!==s[0]&&A.push(_.length/2);for(var C=0;C<z.length;C++){var M=z[C];gs(this.layoutVertexArray,M.x,M.y,0,0,1,1,0),_.push(M.x),_.push(M.y);}}}for(var E=wo(_,A),T=0;T<E.length;T+=3)this.indexArray.emplaceBack(S+E[T],S+E[T+2],S+E[T+1]);c.primitiveLength+=E.length/3,c.vertexLength+=u;}}var P;this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,i,n);},Fn("FillExtrusionBucket",xs,{omit:["layers","features"]});var ws={paint:new gi({"fill-extrusion-opacity":new fi(It["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new yi(It["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new fi(It["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new fi(It["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new di(It["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new yi(It["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new yi(It["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new fi(It["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})},_s=function(t){function e(e){t.call(this,e,ws);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.createBucket=function(t){return new xs(t)},e.prototype.queryRadius=function(){return Ya(this.paint.get("fill-extrusion-translate"))},e.prototype.is3D=function(){return !0},e.prototype.queryIntersectsFeature=function(t,e,r,n,a,o,s,u){var l=$a(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),o.angle,s),p=this.paint.get("fill-extrusion-height").evaluate(e,r),c=this.paint.get("fill-extrusion-base").evaluate(e,r),h=function(t,e,r,n){for(var a=[],o=0,s=t;o<s.length;o+=1){var u=s[o],l=[u.x,u.y,0,1];ao(l,l,e),a.push(new i(l[0]/l[3],l[1]/l[3]));}return a}(l,u),f=function(t,e,r,n){for(var a=[],o=[],s=n[8]*e,u=n[9]*e,l=n[10]*e,p=n[11]*e,c=n[8]*r,h=n[9]*r,f=n[10]*r,y=n[11]*r,d=0,m=t;d<m.length;d+=1){for(var v=[],g=[],x=0,b=m[d];x<b.length;x+=1){var w=b[x],_=w.x,A=w.y,S=n[0]*_+n[4]*A+n[12],k=n[1]*_+n[5]*A+n[13],I=n[2]*_+n[6]*A+n[14],z=n[3]*_+n[7]*A+n[15],C=I+l,M=z+p,E=S+c,T=k+h,P=I+f,B=z+y,V=new i((S+s)/M,(k+u)/M);V.z=C/M,v.push(V);var F=new i(E/B,T/B);F.z=P/B,g.push(F);}a.push(v),o.push(g);}return [a,o]}(n,c,p,u);return function(t,e,r){var n=1/0;Ua(r,e)&&(n=Ss(r,e[0]));for(var i=0;i<e.length;i++)for(var a=e[i],o=t[i],s=0;s<a.length-1;s++){var u=a[s],l=[u,a[s+1],o[s+1],o[s],u];Ra(r,l)&&(n=Math.min(n,Ss(r,l)));}return n!==1/0&&n}(f[0],f[1],h)},e}(xi);function As(t,e){return t.x*e.x+t.y*e.y}function Ss(t,e){if(1===t.length){for(var r,n=0,i=e[n++];!r||i.equals(r);)if(!(r=e[n++]))return 1/0;for(;n<e.length;n++){var a=e[n],o=t[0],s=r.sub(i),u=a.sub(i),l=o.sub(i),p=As(s,s),c=As(s,u),h=As(u,u),f=As(l,s),y=As(l,u),d=p*h-c*c,m=(h*f-c*y)/d,v=(p*y-c*f)/d,g=i.z*(1-m-v)+r.z*m+a.z*v;if(isFinite(g))return g}return 1/0}for(var x=1/0,b=0,w=e;b<w.length;b+=1)x=Math.min(x,w[b].z);return x}var ks=Ai([{name:"a_pos_normal",components:2,type:"Int16"},{name:"a_data",components:4,type:"Uint8"}],4).members,Is=ds.VectorTileFeature.types,zs=Math.cos(Math.PI/180*37.5),Cs=Math.pow(2,14)/.5,Ms=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new Ci,this.indexArray=new Li,this.programConfigurations=new Ta(ks,t.layers,t.zoom),this.segments=new ia,this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};Ms.prototype.populate=function(t,e,r){this.hasPattern=ts("line",this.layers,e);for(var n=this.layers[0].layout.get("line-sort-key"),i=[],a=0,o=t;a<o.length;a+=1){var s=o[a],u=s.feature,l=s.id,p=s.index,c=s.sourceLayerIndex,h=this.layers[0]._featureFilter.needGeometry,f={type:u.type,id:l,properties:u.properties,geometry:h?Fa(u):[]};if(this.layers[0]._featureFilter.filter(new ii(this.zoom),f,r)){h||(f.geometry=Fa(u));var y=n?n.evaluate(f,{},r):void 0;i.push({id:l,properties:u.properties,type:u.type,sourceLayerIndex:c,index:p,geometry:f.geometry,patterns:{},sortKey:y});}}n&&i.sort((function(t,e){return t.sortKey-e.sortKey}));for(var d=0,m=i;d<m.length;d+=1){var v=m[d],g=v.geometry,x=v.index,b=v.sourceLayerIndex;if(this.hasPattern){var w=es("line",this.layers,v,this.zoom,e);this.patternFeatures.push(w);}else this.addFeature(v,g,x,r,{});e.featureIndex.insert(t[x].feature,g,x,b,this.index);}},Ms.prototype.update=function(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);},Ms.prototype.addFeatures=function(t,e,r){for(var n=0,i=this.patternFeatures;n<i.length;n+=1){var a=i[n];this.addFeature(a,a.geometry,a.index,e,r);}},Ms.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length},Ms.prototype.uploadPending=function(){return !this.uploaded||this.programConfigurations.needsUpload},Ms.prototype.upload=function(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,ks),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=!0;},Ms.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());},Ms.prototype.addFeature=function(t,e,r,n,i){for(var a=this.layers[0].layout,o=a.get("line-join").evaluate(t,{}),s=a.get("line-cap"),u=a.get("line-miter-limit"),l=a.get("line-round-limit"),p=0,c=e;p<c.length;p+=1)this.addLine(c[p],t,o,s,u,l);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,i,n);},Ms.prototype.addLine=function(t,e,r,n,i,a){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,e.properties&&e.properties.hasOwnProperty("mapbox_clip_start")&&e.properties.hasOwnProperty("mapbox_clip_end")){this.clipStart=+e.properties.mapbox_clip_start,this.clipEnd=+e.properties.mapbox_clip_end;for(var o=0;o<t.length-1;o++)this.totalDistance+=t[o].dist(t[o+1]);this.updateScaledDistance();}for(var s="Polygon"===Is[e.type],u=t.length;u>=2&&t[u-1].equals(t[u-2]);)u--;for(var l=0;l<u-1&&t[l].equals(t[l+1]);)l++;if(!(u<(s?3:2))){"bevel"===r&&(i=1.05);var p,c=this.overscaling<=16?122880/(512*this.overscaling):0,h=this.segments.prepareSegment(10*u,this.layoutVertexArray,this.indexArray),f=void 0,y=void 0,d=void 0,m=void 0;this.e1=this.e2=-1,s&&(m=t[l].sub(p=t[u-2])._unit()._perp());for(var v=l;v<u;v++)if(!(y=v===u-1?s?t[l+1]:void 0:t[v+1])||!t[v].equals(y)){m&&(d=m),p&&(f=p),p=t[v],m=y?y.sub(p)._unit()._perp():d;var g=(d=d||m).add(m);0===g.x&&0===g.y||g._unit();var x=d.x*m.x+d.y*m.y,b=g.x*m.x+g.y*m.y,w=0!==b?1/b:1/0,_=2*Math.sqrt(2-2*b),A=b<zs&&f&&y,S=d.x*m.y-d.y*m.x>0;if(A&&v>l){var k=p.dist(f);if(k>2*c){var I=p.sub(p.sub(f)._mult(c/k)._round());this.updateDistance(f,I),this.addCurrentVertex(I,d,0,0,h),f=I;}}var z=f&&y,C=z?r:s?"butt":n;if(z&&"round"===C&&(w<a?C="miter":w<=2&&(C="fakeround")),"miter"===C&&w>i&&(C="bevel"),"bevel"===C&&(w>2&&(C="flipbevel"),w<i&&(C="miter")),f&&this.updateDistance(f,p),"miter"===C)g._mult(w),this.addCurrentVertex(p,g,0,0,h);else if("flipbevel"===C){if(w>100)g=m.mult(-1);else {var M=w*d.add(m).mag()/d.sub(m).mag();g._perp()._mult(M*(S?-1:1));}this.addCurrentVertex(p,g,0,0,h),this.addCurrentVertex(p,g.mult(-1),0,0,h);}else if("bevel"===C||"fakeround"===C){var E=-Math.sqrt(w*w-1),T=S?E:0,P=S?0:E;if(f&&this.addCurrentVertex(p,d,T,P,h),"fakeround"===C)for(var B=Math.round(180*_/Math.PI/20),V=1;V<B;V++){var F=V/B;if(.5!==F){var D=F-.5;F+=F*D*(F-1)*((1.0904+x*(x*(3.55645-1.43519*x)-3.2452))*D*D+(.848013+x*(.215638*x-1.06021)));}var L=m.sub(d)._mult(F)._add(d)._unit()._mult(S?-1:1);this.addHalfVertex(p,L.x,L.y,!1,S,0,h);}y&&this.addCurrentVertex(p,m,-T,-P,h);}else if("butt"===C)this.addCurrentVertex(p,g,0,0,h);else if("square"===C){var R=f?1:-1;this.addCurrentVertex(p,g,R,R,h);}else "round"===C&&(f&&(this.addCurrentVertex(p,d,0,0,h),this.addCurrentVertex(p,d,1,1,h,!0)),y&&(this.addCurrentVertex(p,m,-1,-1,h,!0),this.addCurrentVertex(p,m,0,0,h)));if(A&&v<u-1){var O=p.dist(y);if(O>2*c){var U=p.add(y.sub(p)._mult(c/O)._round());this.updateDistance(p,U),this.addCurrentVertex(U,m,0,0,h),p=U;}}}}},Ms.prototype.addCurrentVertex=function(t,e,r,n,i,a){void 0===a&&(a=!1);var o=e.y*n-e.x,s=-e.y-e.x*n;this.addHalfVertex(t,e.x+e.y*r,e.y-e.x*r,a,!1,r,i),this.addHalfVertex(t,o,s,a,!0,-n,i),this.distance>Cs/2&&0===this.totalDistance&&(this.distance=0,this.addCurrentVertex(t,e,r,n,i,a));},Ms.prototype.addHalfVertex=function(t,e,r,n,i,a,o){var s=.5*this.scaledDistance;this.layoutVertexArray.emplaceBack((t.x<<1)+(n?1:0),(t.y<<1)+(i?1:0),Math.round(63*e)+128,Math.round(63*r)+128,1+(0===a?0:a<0?-1:1)|(63&s)<<2,s>>6);var u=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,u),o.primitiveLength++),i?this.e2=u:this.e1=u;},Ms.prototype.updateScaledDistance=function(){this.scaledDistance=this.totalDistance>0?(this.clipStart+(this.clipEnd-this.clipStart)*this.distance/this.totalDistance)*(Cs-1):this.distance;},Ms.prototype.updateDistance=function(t,e){this.distance+=t.dist(e),this.updateScaledDistance();},Fn("LineBucket",Ms,{omit:["layers","patternFeatures"]});var Es=new gi({"line-cap":new fi(It.layout_line["line-cap"]),"line-join":new yi(It.layout_line["line-join"]),"line-miter-limit":new fi(It.layout_line["line-miter-limit"]),"line-round-limit":new fi(It.layout_line["line-round-limit"]),"line-sort-key":new yi(It.layout_line["line-sort-key"])}),Ts={paint:new gi({"line-opacity":new yi(It.paint_line["line-opacity"]),"line-color":new yi(It.paint_line["line-color"]),"line-translate":new fi(It.paint_line["line-translate"]),"line-translate-anchor":new fi(It.paint_line["line-translate-anchor"]),"line-width":new yi(It.paint_line["line-width"]),"line-gap-width":new yi(It.paint_line["line-gap-width"]),"line-offset":new yi(It.paint_line["line-offset"]),"line-blur":new yi(It.paint_line["line-blur"]),"line-dasharray":new mi(It.paint_line["line-dasharray"]),"line-pattern":new di(It.paint_line["line-pattern"]),"line-gradient":new vi(It.paint_line["line-gradient"])}),layout:Es},Ps=new(function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.possiblyEvaluate=function(e,r){return r=new ii(Math.floor(r.zoom),{now:r.now,fadeDuration:r.fadeDuration,zoomHistory:r.zoomHistory,transition:r.transition}),t.prototype.possiblyEvaluate.call(this,e,r)},e.prototype.evaluate=function(e,r,n,i){return r=p({},r,{zoom:Math.floor(r.zoom)}),t.prototype.evaluate.call(this,e,r,n,i)},e}(yi))(Ts.paint.properties["line-width"].specification);Ps.useIntegerZoom=!0;var Bs=function(t){function e(e){t.call(this,e,Ts);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._handleSpecialPaintPropertyUpdate=function(t){"line-gradient"===t&&this._updateGradient();},e.prototype._updateGradient=function(){this.gradient=mo(this._transitionablePaint._values["line-gradient"].value.expression,"lineProgress"),this.gradientTexture=null;},e.prototype.recalculate=function(e,r){t.prototype.recalculate.call(this,e,r),this.paint._values["line-floorwidth"]=Ps.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,e);},e.prototype.createBucket=function(t){return new Ms(t)},e.prototype.queryRadius=function(t){var e=t,r=Vs(Ha("line-width",this,e),Ha("line-gap-width",this,e)),n=Ha("line-offset",this,e);return r/2+Math.abs(n)+Ya(this.paint.get("line-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,a,o,s){var u=$a(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),o.angle,s),l=s/2*Vs(this.paint.get("line-width").evaluate(e,r),this.paint.get("line-gap-width").evaluate(e,r)),p=this.paint.get("line-offset").evaluate(e,r);return p&&(n=function(t,e){for(var r=[],n=new i(0,0),a=0;a<t.length;a++){for(var o=t[a],s=[],u=0;u<o.length;u++){var l=o[u],p=o[u+1],c=0===u?n:l.sub(o[u-1])._unit()._perp(),h=u===o.length-1?n:p.sub(l)._unit()._perp(),f=c._add(h)._unit();f._mult(1/(f.x*h.x+f.y*h.y)),s.push(f._mult(e)._add(l));}r.push(s);}return r}(n,p*s)),function(t,e,r){for(var n=0;n<e.length;n++){var i=e[n];if(t.length>=3)for(var a=0;a<i.length;a++)if(Xa(t,i[a]))return !0;if(ja(t,i,r))return !0}return !1}(u,n,l)},e.prototype.isTileClipped=function(){return !0},e}(xi);function Vs(t,e){return e>0?e+2*t:t}var Fs=Ai([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Ds=Ai([{name:"a_projected_pos",components:3,type:"Float32"}],4),Ls=(Ai([{name:"a_fade_opacity",components:1,type:"Uint32"}],4),Ai([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"}])),Rs=(Ai([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]),Ai([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4)),Os=Ai([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function Us(t,e,r){return t.sections.forEach((function(t){t.text=function(t,e,r){var n=e.layout.get("text-transform").evaluate(r,{});return "uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),ni.applyArabicShaping&&(t=ni.applyArabicShaping(t)),t}(t.text,e,r);})),t}Ai([{name:"triangle",components:3,type:"Uint16"}]),Ai([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),Ai([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",components:2,name:"textOffset"},{type:"Float32",name:"collisionCircleDiameter"}]),Ai([{type:"Float32",name:"offsetX"}]),Ai([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]);var js={"!":"︕","#":"＃",$:"＄","%":"％","&":"＆","(":"︵",")":"︶","*":"＊","+":"＋",",":"︐","-":"︲",".":"・","/":"／",":":"︓",";":"︔","<":"︿","=":"＝",">":"﹀","?":"︖","@":"＠","[":"﹇","\\":"＼","]":"﹈","^":"＾",_:"︳","`":"｀","{":"︷","|":"―","}":"︸","~":"～","¢":"￠","£":"￡","¥":"￥","¦":"￤","¬":"￢","¯":"￣","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"￦","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","！":"︕","（":"︵","）":"︶","，":"︐","－":"︲","．":"・","：":"︓","；":"︔","＜":"︿","＞":"﹀","？":"︖","［":"﹇","］":"﹈","＿":"︳","｛":"︷","｜":"―","｝":"︸","｟":"︵","｠":"︶","｡":"︒","｢":"﹁","｣":"﹂"},qs=function(t,e,r,n,i){var a,o,s=8*i-n-1,u=(1<<s)-1,l=u>>1,p=-7,c=r?i-1:0,h=r?-1:1,f=t[e+c];for(c+=h,a=f&(1<<-p)-1,f>>=-p,p+=s;p>0;a=256*a+t[e+c],c+=h,p-=8);for(o=a&(1<<-p)-1,a>>=-p,p+=n;p>0;o=256*o+t[e+c],c+=h,p-=8);if(0===a)a=1-l;else {if(a===u)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,n),a-=l;}return (f?-1:1)*o*Math.pow(2,a-n)},Ns=function(t,e,r,n,i,a){var o,s,u,l=8*a-i-1,p=(1<<l)-1,c=p>>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:a-1,y=n?1:-1,d=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=p):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),(e+=o+c>=1?h/u:h*Math.pow(2,1-c))*u>=2&&(o++,u/=2),o+c>=p?(s=0,o=p):o+c>=1?(s=(e*u-1)*Math.pow(2,i),o+=c):(s=e*Math.pow(2,c-1)*Math.pow(2,i),o=0));i>=8;t[r+f]=255&s,f+=y,s/=256,i-=8);for(o=o<<i|s,l+=i;l>0;t[r+f]=255&o,f+=y,o/=256,l-=8);t[r+f-y]|=128*d;},Ks=Gs;function Gs(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length;}Gs.Varint=0,Gs.Fixed64=1,Gs.Bytes=2,Gs.Fixed32=5;var Zs="undefined"==typeof TextDecoder?null:new TextDecoder("utf8");function Xs(t){return t.type===Gs.Bytes?t.readVarint()+t.pos:t.pos+1}function Js(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function Hs(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i];}function Ys(t,e){for(var r=0;r<t.length;r++)e.writeVarint(t[r]);}function $s(t,e){for(var r=0;r<t.length;r++)e.writeSVarint(t[r]);}function Ws(t,e){for(var r=0;r<t.length;r++)e.writeFloat(t[r]);}function Qs(t,e){for(var r=0;r<t.length;r++)e.writeDouble(t[r]);}function tu(t,e){for(var r=0;r<t.length;r++)e.writeBoolean(t[r]);}function eu(t,e){for(var r=0;r<t.length;r++)e.writeFixed32(t[r]);}function ru(t,e){for(var r=0;r<t.length;r++)e.writeSFixed32(t[r]);}function nu(t,e){for(var r=0;r<t.length;r++)e.writeFixed64(t[r]);}function iu(t,e){for(var r=0;r<t.length;r++)e.writeSFixed64(t[r]);}function au(t,e){return (t[e]|t[e+1]<<8|t[e+2]<<16)+16777216*t[e+3]}function ou(t,e,r){t[r]=e,t[r+1]=e>>>8,t[r+2]=e>>>16,t[r+3]=e>>>24;}function su(t,e){return (t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}function uu(t,e,r){1===t&&r.readMessage(lu,e);}function lu(t,e,r){if(3===t){var n=r.readMessage(pu,{}),i=n.width,a=n.height,o=n.left,s=n.top,u=n.advance;e.push({id:n.id,bitmap:new ho({width:i+6,height:a+6},n.bitmap),metrics:{width:i,height:a,left:o,top:s,advance:u}});}}function pu(t,e,r){1===t?e.id=r.readVarint():2===t?e.bitmap=r.readBytes():3===t?e.width=r.readVarint():4===t?e.height=r.readVarint():5===t?e.left=r.readSVarint():6===t?e.top=r.readSVarint():7===t&&(e.advance=r.readVarint());}function cu(t){for(var e=0,r=0,n=0,i=t;n<i.length;n+=1){var a=i[n];e+=a.w*a.h,r=Math.max(r,a.w);}t.sort((function(t,e){return e.h-t.h}));for(var o=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),r),h:1/0}],s=0,u=0,l=0,p=t;l<p.length;l+=1)for(var c=p[l],h=o.length-1;h>=0;h--){var f=o[h];if(!(c.w>f.w||c.h>f.h)){if(c.x=f.x,c.y=f.y,u=Math.max(u,c.y+c.h),s=Math.max(s,c.x+c.w),c.w===f.w&&c.h===f.h){var y=o.pop();h<o.length&&(o[h]=y);}else c.h===f.h?(f.x+=c.w,f.w-=c.w):c.w===f.w?(f.y+=c.h,f.h-=c.h):(o.push({x:f.x+c.w,y:f.y,w:f.w-c.w,h:c.h}),f.y+=c.h,f.h-=c.h);break}}return {w:s,h:u,fill:e/(s*u)||0}}Gs.prototype={destroy:function(){this.buf=null;},readFields:function(t,e,r){for(r=r||this.length;this.pos<r;){var n=this.readVarint(),i=n>>3,a=this.pos;this.type=7&n,t(i,e,this),this.pos===a&&this.skip(n);}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=au(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=su(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=au(this.buf,this.pos)+4294967296*au(this.buf,this.pos+4);return this.pos+=8,t},readSFixed64:function(){var t=au(this.buf,this.pos)+4294967296*su(this.buf,this.pos+4);return this.pos+=8,t},readFloat:function(){var t=qs(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=qs(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,a=r.buf;if(n=(112&(i=a[r.pos++]))>>4,i<128)return Js(t,n,e);if(n|=(127&(i=a[r.pos++]))<<3,i<128)return Js(t,n,e);if(n|=(127&(i=a[r.pos++]))<<10,i<128)return Js(t,n,e);if(n|=(127&(i=a[r.pos++]))<<17,i<128)return Js(t,n,e);if(n|=(127&(i=a[r.pos++]))<<24,i<128)return Js(t,n,e);if(n|=(1&(i=a[r.pos++]))<<31,i<128)return Js(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&Zs?function(t,e,r){return Zs.decode(t.subarray(e,r))}(this.buf,e,t):function(t,e,r){for(var n="",i=e;i<r;){var a,o,s,u=t[i],l=null,p=u>239?4:u>223?3:u>191?2:1;if(i+p>r)break;1===p?u<128&&(l=u):2===p?128==(192&(a=t[i+1]))&&(l=(31&u)<<6|63&a)<=127&&(l=null):3===p?(o=t[i+2],128==(192&(a=t[i+1]))&&128==(192&o)&&((l=(15&u)<<12|(63&a)<<6|63&o)<=2047||l>=55296&&l<=57343)&&(l=null)):4===p&&(o=t[i+2],s=t[i+3],128==(192&(a=t[i+1]))&&128==(192&o)&&128==(192&s)&&((l=(15&u)<<18|(63&a)<<12|(63&o)<<6|63&s)<=65535||l>=1114112)&&(l=null)),null===l?(l=65533,p=1):l>65535&&(l-=65536,n+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),n+=String.fromCharCode(l),i+=p;}return n}(this.buf,e,t)},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,e){if(this.type!==Gs.Bytes)return t.push(this.readVarint(e));var r=Xs(this);for(t=t||[];this.pos<r;)t.push(this.readVarint(e));return t},readPackedSVarint:function(t){if(this.type!==Gs.Bytes)return t.push(this.readSVarint());var e=Xs(this);for(t=t||[];this.pos<e;)t.push(this.readSVarint());return t},readPackedBoolean:function(t){if(this.type!==Gs.Bytes)return t.push(this.readBoolean());var e=Xs(this);for(t=t||[];this.pos<e;)t.push(this.readBoolean());return t},readPackedFloat:function(t){if(this.type!==Gs.Bytes)return t.push(this.readFloat());var e=Xs(this);for(t=t||[];this.pos<e;)t.push(this.readFloat());return t},readPackedDouble:function(t){if(this.type!==Gs.Bytes)return t.push(this.readDouble());var e=Xs(this);for(t=t||[];this.pos<e;)t.push(this.readDouble());return t},readPackedFixed32:function(t){if(this.type!==Gs.Bytes)return t.push(this.readFixed32());var e=Xs(this);for(t=t||[];this.pos<e;)t.push(this.readFixed32());return t},readPackedSFixed32:function(t){if(this.type!==Gs.Bytes)return t.push(this.readSFixed32());var e=Xs(this);for(t=t||[];this.pos<e;)t.push(this.readSFixed32());return t},readPackedFixed64:function(t){if(this.type!==Gs.Bytes)return t.push(this.readFixed64());var e=Xs(this);for(t=t||[];this.pos<e;)t.push(this.readFixed64());return t},readPackedSFixed64:function(t){if(this.type!==Gs.Bytes)return t.push(this.readSFixed64());var e=Xs(this);for(t=t||[];this.pos<e;)t.push(this.readSFixed64());return t},skip:function(t){var e=7&t;if(e===Gs.Varint)for(;this.buf[this.pos++]>127;);else if(e===Gs.Bytes)this.pos=this.readVarint()+this.pos;else if(e===Gs.Fixed32)this.pos+=4;else {if(e!==Gs.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8;}},writeTag:function(t,e){this.writeVarint(t<<3|e);},realloc:function(t){for(var e=this.length||16;e<this.pos+t;)e*=2;if(e!==this.length){var r=new Uint8Array(e);r.set(this.buf),this.buf=r,this.length=e;}},finish:function(){return this.length=this.pos,this.pos=0,this.buf.subarray(0,this.length)},writeFixed32:function(t){this.realloc(4),ou(this.buf,t,this.pos),this.pos+=4;},writeSFixed32:function(t){this.realloc(4),ou(this.buf,t,this.pos),this.pos+=4;},writeFixed64:function(t){this.realloc(8),ou(this.buf,-1&t,this.pos),ou(this.buf,Math.floor(t*(1/4294967296)),this.pos+4),this.pos+=8;},writeSFixed64:function(t){this.realloc(8),ou(this.buf,-1&t,this.pos),ou(this.buf,Math.floor(t*(1/4294967296)),this.pos+4),this.pos+=8;},writeVarint:function(t){(t=+t||0)>268435455||t<0?function(t,e){var r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,r.buf[r.pos]=127&(t>>>=7);}(r,0,e),function(t,e){var r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))));}(n,e);}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))));},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t);},writeBoolean:function(t){this.writeVarint(Boolean(t));},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,r){for(var n,i,a=0;a<e.length;a++){if((n=e.charCodeAt(a))>55295&&n<57344){if(!i){n>56319||a+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&Hs(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;},writeFloat:function(t){this.realloc(4),Ns(this.buf,t,this.pos,!0,23,4),this.pos+=4;},writeDouble:function(t){this.realloc(8),Ns(this.buf,t,this.pos,!0,52,8),this.pos+=8;},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r<e;r++)this.buf[this.pos++]=t[r];},writeRawMessage:function(t,e){this.pos++;var r=this.pos;t(e,this);var n=this.pos-r;n>=128&&Hs(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;},writeMessage:function(t,e,r){this.writeTag(t,Gs.Bytes),this.writeRawMessage(e,r);},writePackedVarint:function(t,e){e.length&&this.writeMessage(t,Ys,e);},writePackedSVarint:function(t,e){e.length&&this.writeMessage(t,$s,e);},writePackedBoolean:function(t,e){e.length&&this.writeMessage(t,tu,e);},writePackedFloat:function(t,e){e.length&&this.writeMessage(t,Ws,e);},writePackedDouble:function(t,e){e.length&&this.writeMessage(t,Qs,e);},writePackedFixed32:function(t,e){e.length&&this.writeMessage(t,eu,e);},writePackedSFixed32:function(t,e){e.length&&this.writeMessage(t,ru,e);},writePackedFixed64:function(t,e){e.length&&this.writeMessage(t,nu,e);},writePackedSFixed64:function(t,e){e.length&&this.writeMessage(t,iu,e);},writeBytesField:function(t,e){this.writeTag(t,Gs.Bytes),this.writeBytes(e);},writeFixed32Field:function(t,e){this.writeTag(t,Gs.Fixed32),this.writeFixed32(e);},writeSFixed32Field:function(t,e){this.writeTag(t,Gs.Fixed32),this.writeSFixed32(e);},writeFixed64Field:function(t,e){this.writeTag(t,Gs.Fixed64),this.writeFixed64(e);},writeSFixed64Field:function(t,e){this.writeTag(t,Gs.Fixed64),this.writeSFixed64(e);},writeVarintField:function(t,e){this.writeTag(t,Gs.Varint),this.writeVarint(e);},writeSVarintField:function(t,e){this.writeTag(t,Gs.Varint),this.writeSVarint(e);},writeStringField:function(t,e){this.writeTag(t,Gs.Bytes),this.writeString(e);},writeFloatField:function(t,e){this.writeTag(t,Gs.Fixed32),this.writeFloat(e);},writeDoubleField:function(t,e){this.writeTag(t,Gs.Fixed64),this.writeDouble(e);},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e));}};var hu=function(t,e){var r=e.pixelRatio,n=e.version,i=e.stretchX,a=e.stretchY,o=e.content;this.paddedRect=t,this.pixelRatio=r,this.stretchX=i,this.stretchY=a,this.content=o,this.version=n;},fu={tl:{configurable:!0},br:{configurable:!0},tlbr:{configurable:!0},displaySize:{configurable:!0}};fu.tl.get=function(){return [this.paddedRect.x+1,this.paddedRect.y+1]},fu.br.get=function(){return [this.paddedRect.x+this.paddedRect.w-1,this.paddedRect.y+this.paddedRect.h-1]},fu.tlbr.get=function(){return this.tl.concat(this.br)},fu.displaySize.get=function(){return [(this.paddedRect.w-2)/this.pixelRatio,(this.paddedRect.h-2)/this.pixelRatio]},Object.defineProperties(hu.prototype,fu);var yu=function(t,e){var r={},n={};this.haveRenderCallbacks=[];var i=[];this.addImages(t,r,i),this.addImages(e,n,i);var a=cu(i),o=new fo({width:a.w||1,height:a.h||1});for(var s in t){var u=t[s],l=r[s].paddedRect;fo.copy(u.data,o,{x:0,y:0},{x:l.x+1,y:l.y+1},u.data);}for(var p in e){var c=e[p],h=n[p].paddedRect,f=h.x+1,y=h.y+1,d=c.data.width,m=c.data.height;fo.copy(c.data,o,{x:0,y:0},{x:f,y:y},c.data),fo.copy(c.data,o,{x:0,y:m-1},{x:f,y:y-1},{width:d,height:1}),fo.copy(c.data,o,{x:0,y:0},{x:f,y:y+m},{width:d,height:1}),fo.copy(c.data,o,{x:d-1,y:0},{x:f-1,y:y},{width:1,height:m}),fo.copy(c.data,o,{x:0,y:0},{x:f+d,y:y},{width:1,height:m});}this.image=o,this.iconPositions=r,this.patternPositions=n;};yu.prototype.addImages=function(t,e,r){for(var n in t){var i=t[n],a={x:0,y:0,w:i.data.width+2,h:i.data.height+2};r.push(a),e[n]=new hu(a,i),i.hasRenderCallback&&this.haveRenderCallbacks.push(n);}},yu.prototype.patchUpdatedImages=function(t,e){for(var r in t.dispatchRenderCallbacks(this.haveRenderCallbacks),t.updatedImages)this.patchUpdatedImage(this.iconPositions[r],t.getImage(r),e),this.patchUpdatedImage(this.patternPositions[r],t.getImage(r),e);},yu.prototype.patchUpdatedImage=function(t,e,r){if(t&&e&&t.version!==e.version){t.version=e.version;var n=t.tl;r.update(e.data,void 0,{x:n[0],y:n[1]});}},Fn("ImagePosition",hu),Fn("ImageAtlas",yu);var du={horizontal:1,vertical:2,horizontalOnly:3},mu=function(){this.scale=1,this.fontStack="",this.imageName=null;};mu.forText=function(t,e){var r=new mu;return r.scale=t||1,r.fontStack=e,r},mu.forImage=function(t){var e=new mu;return e.imageName=t,e};var vu=function(){this.text="",this.sectionIndex=[],this.sections=[],this.imageSectionID=null;};function gu(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d){var m,v=vu.fromFeature(t,i);c===du.vertical&&v.verticalizePunctuation();var g=ni.processBidirectionalText,x=ni.processStyledBidirectionalText;if(g&&1===v.sections.length){m=[];for(var b=0,w=g(v.toString(),ku(v,l,a,e,n,f,y));b<w.length;b+=1){var _=w[b],A=new vu;A.text=_,A.sections=v.sections;for(var S=0;S<_.length;S++)A.sectionIndex.push(0);m.push(A);}}else if(x){m=[];for(var k=0,I=x(v.text,v.sectionIndex,ku(v,l,a,e,n,f,y));k<I.length;k+=1){var z=I[k],C=new vu;C.text=z[0],C.sectionIndex=z[1],C.sections=v.sections,m.push(C);}}else m=function(t,e){for(var r=[],n=t.text,i=0,a=0,o=e;a<o.length;a+=1){var s=o[a];r.push(t.substring(i,s)),i=s;}return i<n.length&&r.push(t.substring(i,n.length)),r}(v,ku(v,l,a,e,n,f,y));var M=[],E={positionedLines:M,text:v.toString(),top:p[1],bottom:p[1],left:p[0],right:p[0],writingMode:c,iconsInText:!1,verticalizable:!1};return function(t,e,r,n,i,a,o,s,u,l,p,c){for(var h=0,f=-17,y=0,d=0,m="right"===s?1:"left"===s?0:.5,v=0,g=0,x=i;g<x.length;g+=1){var b=x[g];b.trim();var w=b.getMaxScale(),_=24*(w-1),A={positionedGlyphs:[],lineOffset:0};t.positionedLines[v]=A;var S=A.positionedGlyphs,k=0;if(b.length()){for(var I=0;I<b.length();I++){var z=b.getSection(I),C=b.getSectionIndex(I),M=b.getCharCode(I),E=0,T=null,P=null,B=null,V=24,F=!(u===du.horizontal||!p&&!Kn(M)||p&&(xu[M]||(K=M,qn.Arabic(K)||qn["Arabic Supplement"](K)||qn["Arabic Extended-A"](K)||qn["Arabic Presentation Forms-A"](K)||qn["Arabic Presentation Forms-B"](K))));if(z.imageName){var D=n[z.imageName];if(!D)continue;B=z.imageName,t.iconsInText=t.iconsInText||!0,P=D.paddedRect;var L=D.displaySize;z.scale=24*z.scale/c,E=_+(24-L[1]*z.scale),V=(T={width:L[0],height:L[1],left:1,top:-3,advance:F?L[1]:L[0]}).advance;var R=F?L[0]*z.scale-24*w:L[1]*z.scale-24*w;R>0&&R>k&&(k=R);}else {var O=r[z.fontStack],U=O&&O[M];if(U&&U.rect)P=U.rect,T=U.metrics;else {var j=e[z.fontStack],q=j&&j[M];if(!q)continue;T=q.metrics;}E=24*(w-z.scale);}F?(t.verticalizable=!0,S.push({glyph:M,imageName:B,x:h,y:f+E,vertical:F,scale:z.scale,fontStack:z.fontStack,sectionIndex:C,metrics:T,rect:P}),h+=V*z.scale+l):(S.push({glyph:M,imageName:B,x:h,y:f+E,vertical:F,scale:z.scale,fontStack:z.fontStack,sectionIndex:C,metrics:T,rect:P}),h+=T.advance*z.scale+l);}0!==S.length&&(y=Math.max(h-l,y),zu(S,0,S.length-1,m,k)),h=0;var N=a*w+k;A.lineOffset=Math.max(k,_),f+=N,d=Math.max(N,d),++v;}else f+=a,++v;}var K,G=f- -17,Z=Iu(o),X=Z.horizontalAlign,J=Z.verticalAlign;(function(t,e,r,n,i,a,o,s,u){var l,p=(e-r)*i;l=a!==o?-s*n- -17:(-n*u+.5)*o;for(var c=0,h=t;c<h.length;c+=1)for(var f=0,y=h[c].positionedGlyphs;f<y.length;f+=1){var d=y[f];d.x+=p,d.y+=l;}})(t.positionedLines,m,X,J,y,d,a,G,i.length),t.top+=-J*G,t.bottom=t.top+G,t.left+=-X*y,t.right=t.left+y;}(E,e,r,n,m,o,s,u,c,l,h,d),!function(t){for(var e=0,r=t;e<r.length;e+=1)if(0!==r[e].positionedGlyphs.length)return !1;return !0}(M)&&E}vu.fromFeature=function(t,e){for(var r=new vu,n=0;n<t.sections.length;n++){var i=t.sections[n];i.image?r.addImageSection(i):r.addTextSection(i,e);}return r},vu.prototype.length=function(){return this.text.length},vu.prototype.getSection=function(t){return this.sections[this.sectionIndex[t]]},vu.prototype.getSectionIndex=function(t){return this.sectionIndex[t]},vu.prototype.getCharCode=function(t){return this.text.charCodeAt(t)},vu.prototype.verticalizePunctuation=function(){this.text=function(t){for(var e="",r=0;r<t.length;r++){var n=t.charCodeAt(r+1)||null,i=t.charCodeAt(r-1)||null;e+=n&&Gn(n)&&!js[t[r+1]]||i&&Gn(i)&&!js[t[r-1]]||!js[t[r]]?t[r]:js[t[r]];}return e}(this.text);},vu.prototype.trim=function(){for(var t=0,e=0;e<this.text.length&&xu[this.text.charCodeAt(e)];e++)t++;for(var r=this.text.length,n=this.text.length-1;n>=0&&n>=t&&xu[this.text.charCodeAt(n)];n--)r--;this.text=this.text.substring(t,r),this.sectionIndex=this.sectionIndex.slice(t,r);},vu.prototype.substring=function(t,e){var r=new vu;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r},vu.prototype.toString=function(){return this.text},vu.prototype.getMaxScale=function(){var t=this;return this.sectionIndex.reduce((function(e,r){return Math.max(e,t.sections[r].scale)}),0)},vu.prototype.addTextSection=function(t,e){this.text+=t.text,this.sections.push(mu.forText(t.scale,t.fontStack||e));for(var r=this.sections.length-1,n=0;n<t.text.length;++n)this.sectionIndex.push(r);},vu.prototype.addImageSection=function(t){var e=t.image?t.image.name:"";if(0!==e.length){var r=this.getNextImageSectionCharCode();r?(this.text+=String.fromCharCode(r),this.sections.push(mu.forImage(e)),this.sectionIndex.push(this.sections.length-1)):w("Reached maximum number of images 6401");}else w("Can't add FormattedSection with an empty image.");},vu.prototype.getNextImageSectionCharCode=function(){return this.imageSectionID?this.imageSectionID>=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)};var xu={9:!0,10:!0,11:!0,12:!0,13:!0,32:!0},bu={};function wu(t,e,r,n,i,a){if(e.imageName){var o=n[e.imageName];return o?o.displaySize[0]*e.scale*24/a+i:0}var s=r[e.fontStack],u=s&&s[t];return u?u.metrics.advance*e.scale+i:0}function _u(t,e,r,n){var i=Math.pow(t-e,2);return n?t<e?i/2:2*i:i+Math.abs(r)*r}function Au(t,e,r){var n=0;return 10===t&&(n-=1e4),r&&(n+=150),40!==t&&65288!==t||(n+=50),41!==e&&65289!==e||(n+=50),n}function Su(t,e,r,n,i,a){for(var o=null,s=_u(e,r,i,a),u=0,l=n;u<l.length;u+=1){var p=l[u],c=_u(e-p.x,r,i,a)+p.badness;c<=s&&(o=p,s=c);}return {index:t,x:e,priorBreak:o,badness:s}}function ku(t,e,r,n,i,a,o){if("point"!==a)return [];if(!t)return [];for(var s,u=[],l=function(t,e,r,n,i,a){for(var o=0,s=0;s<t.length();s++){var u=t.getSection(s);o+=wu(t.getCharCode(s),u,n,i,e,a);}return o/Math.max(1,Math.ceil(o/r))}(t,e,r,n,i,o),p=t.text.indexOf("​")>=0,c=0,h=0;h<t.length();h++){var f=t.getSection(h),y=t.getCharCode(h);if(xu[y]||(c+=wu(y,f,n,i,e,o)),h<t.length()-1){var d=!((s=y)<11904||!(qn["Bopomofo Extended"](s)||qn.Bopomofo(s)||qn["CJK Compatibility Forms"](s)||qn["CJK Compatibility Ideographs"](s)||qn["CJK Compatibility"](s)||qn["CJK Radicals Supplement"](s)||qn["CJK Strokes"](s)||qn["CJK Symbols and Punctuation"](s)||qn["CJK Unified Ideographs Extension A"](s)||qn["CJK Unified Ideographs"](s)||qn["Enclosed CJK Letters and Months"](s)||qn["Halfwidth and Fullwidth Forms"](s)||qn.Hiragana(s)||qn["Ideographic Description Characters"](s)||qn["Kangxi Radicals"](s)||qn["Katakana Phonetic Extensions"](s)||qn.Katakana(s)||qn["Vertical Forms"](s)||qn["Yi Radicals"](s)||qn["Yi Syllables"](s)));(bu[y]||d||f.imageName)&&u.push(Su(h+1,c,l,u,Au(y,t.getCharCode(h+1),d&&p),!1));}}return function t(e){return e?t(e.priorBreak).concat(e.index):[]}(Su(t.length(),c,l,u,0,!0))}function Iu(t){var e=.5,r=.5;switch(t){case"right":case"top-right":case"bottom-right":e=1;break;case"left":case"top-left":case"bottom-left":e=0;}switch(t){case"bottom":case"bottom-right":case"bottom-left":r=1;break;case"top":case"top-right":case"top-left":r=0;}return {horizontalAlign:e,verticalAlign:r}}function zu(t,e,r,n,i){if(n||i)for(var a=t[r],o=(t[r].x+a.metrics.advance*a.scale)*n,s=e;s<=r;s++)t[s].x-=o,t[s].y+=i;}function Cu(t,e,r,n,i,a){var o,s=t.image;if(s.content){var u=s.content,l=s.pixelRatio||1;o=[u[0]/l,u[1]/l,s.displaySize[0]-u[2]/l,s.displaySize[1]-u[3]/l];}var p,c,h,f,y=e.left*a,d=e.right*a;"width"===r||"both"===r?(f=i[0]+y-n[3],c=i[0]+d+n[1]):c=(f=i[0]+(y+d-s.displaySize[0])/2)+s.displaySize[0];var m=e.top*a,v=e.bottom*a;return "height"===r||"both"===r?(p=i[1]+m-n[0],h=i[1]+v+n[2]):h=(p=i[1]+(m+v-s.displaySize[1])/2)+s.displaySize[1],{image:s,top:p,right:c,bottom:h,left:f,collisionPadding:o}}bu[10]=!0,bu[32]=!0,bu[38]=!0,bu[40]=!0,bu[41]=!0,bu[43]=!0,bu[45]=!0,bu[47]=!0,bu[173]=!0,bu[183]=!0,bu[8203]=!0,bu[8208]=!0,bu[8211]=!0,bu[8231]=!0;var Mu=function(t){function e(e,r,n,i){t.call(this,e,r),this.angle=n,void 0!==i&&(this.segment=i);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.clone=function(){return new e(this.x,this.y,this.angle,this.segment)},e}(i);function Eu(t,e){var r=e.expression;if("constant"===r.kind)return {kind:"constant",layoutSize:r.evaluate(new ii(t+1))};if("source"===r.kind)return {kind:"source"};for(var n=r.zoomStops,i=r.interpolationType,a=0;a<n.length&&n[a]<=t;)a++;for(var o=a=Math.max(0,a-1);o<n.length&&n[o]<t+1;)o++;o=Math.min(n.length-1,o);var s=n[a],u=n[o];return "composite"===r.kind?{kind:"composite",minZoom:s,maxZoom:u,interpolationType:i}:{kind:"camera",minZoom:s,maxZoom:u,minSize:r.evaluate(new ii(s)),maxSize:r.evaluate(new ii(u)),interpolationType:i}}function Tu(t,e,r){var n=e.uSize,i=r.lowerSize;return "source"===t.kind?i/128:"composite"===t.kind?je(i/128,r.upperSize/128,e.uSizeT):n}function Pu(t,e){var r=0,n=0;if("constant"===t.kind)n=t.layoutSize;else if("source"!==t.kind){var i=t.interpolationType,a=i?u(rr.interpolationFactor(i,e,t.minZoom,t.maxZoom),0,1):0;"camera"===t.kind?n=je(t.minSize,t.maxSize,a):r=a;}return {uSizeT:r,uSize:n}}Fn("Anchor",Mu);var Bu=Object.freeze({__proto__:null,getSizeData:Eu,evaluateSizeForFeature:Tu,evaluateSizeForZoom:Pu,SIZE_PACK_FACTOR:128});function Vu(t,e,r,n,i){if(void 0===e.segment)return !0;for(var a=e,o=e.segment+1,s=0;s>-r/2;){if(--o<0)return !1;s-=t[o].dist(a),a=t[o];}s+=t[o].dist(t[o+1]),o++;for(var u=[],l=0;s<r/2;){var p=t[o],c=t[o+1];if(!c)return !1;var h=t[o-1].angleTo(p)-p.angleTo(c);for(h=Math.abs((h+3*Math.PI)%(2*Math.PI)-Math.PI),u.push({distance:s,angleDelta:h}),l+=h;s-u[0].distance>n;)l-=u.shift().angleDelta;if(l>i)return !1;o++,s+=p.dist(c);}return !0}function Fu(t){for(var e=0,r=0;r<t.length-1;r++)e+=t[r].dist(t[r+1]);return e}function Du(t,e,r){return t?.6*e*r:0}function Lu(t,e){return Math.max(t?t.right-t.left:0,e?e.right-e.left:0)}function Ru(t,e,r,n,i,a){for(var o=Du(r,i,a),s=Lu(r,n)*a,u=0,l=Fu(t)/2,p=0;p<t.length-1;p++){var c=t[p],h=t[p+1],f=c.dist(h);if(u+f>l){var y=(l-u)/f,d=je(c.x,h.x,y),m=je(c.y,h.y,y),v=new Mu(d,m,h.angleTo(c),p);return v._round(),!o||Vu(t,v,s,o,e)?v:void 0}u+=f;}}function Ou(t,e,r,n,i,a,o,s,u){var l=Du(n,a,o),p=Lu(n,i),c=p*o,h=0===t[0].x||t[0].x===u||0===t[0].y||t[0].y===u;return e-c<e/4&&(e=c+e/4),function t(e,r,n,i,a,o,s,u,l){for(var p=o/2,c=Fu(e),h=0,f=r-n,y=[],d=0;d<e.length-1;d++){for(var m=e[d],v=e[d+1],g=m.dist(v),x=v.angleTo(m);f+n<h+g;){var b=((f+=n)-h)/g,w=je(m.x,v.x,b),_=je(m.y,v.y,b);if(w>=0&&w<l&&_>=0&&_<l&&f-p>=0&&f+p<=c){var A=new Mu(w,_,x,d);A._round(),i&&!Vu(e,A,o,i,a)||y.push(A);}}h+=g;}return u||y.length||s||(y=t(e,h/2,n,i,a,o,s,!0,l)),y}(t,h?e/2*s%e:(p/2+2*a)*o*s%e,e,l,r,c,h,!1,u)}function Uu(t,e,r,n,a){for(var o=[],s=0;s<t.length;s++)for(var u=t[s],l=void 0,p=0;p<u.length-1;p++){var c=u[p],h=u[p+1];c.x<e&&h.x<e||(c.x<e?c=new i(e,c.y+(e-c.x)/(h.x-c.x)*(h.y-c.y))._round():h.x<e&&(h=new i(e,c.y+(e-c.x)/(h.x-c.x)*(h.y-c.y))._round()),c.y<r&&h.y<r||(c.y<r?c=new i(c.x+(r-c.y)/(h.y-c.y)*(h.x-c.x),r)._round():h.y<r&&(h=new i(c.x+(r-c.y)/(h.y-c.y)*(h.x-c.x),r)._round()),c.x>=n&&h.x>=n||(c.x>=n?c=new i(n,c.y+(n-c.x)/(h.x-c.x)*(h.y-c.y))._round():h.x>=n&&(h=new i(n,c.y+(n-c.x)/(h.x-c.x)*(h.y-c.y))._round()),c.y>=a&&h.y>=a||(c.y>=a?c=new i(c.x+(a-c.y)/(h.y-c.y)*(h.x-c.x),a)._round():h.y>=a&&(h=new i(c.x+(a-c.y)/(h.y-c.y)*(h.x-c.x),a)._round()),l&&c.equals(l[l.length-1])||o.push(l=[c]),l.push(h)))));}return o}function ju(t,e,r,n){var a=[],o=t.image,s=o.pixelRatio,u=o.paddedRect.w-2,l=o.paddedRect.h-2,p=t.right-t.left,c=t.bottom-t.top,h=o.stretchX||[[0,u]],f=o.stretchY||[[0,l]],y=function(t,e){return t+e[1]-e[0]},d=h.reduce(y,0),m=f.reduce(y,0),v=u-d,g=l-m,x=0,b=d,w=0,_=m,A=0,S=v,k=0,I=g;if(o.content&&n){var z=o.content;x=qu(h,0,z[0]),w=qu(f,0,z[1]),b=qu(h,z[0],z[2]),_=qu(f,z[1],z[3]),A=z[0]-x,k=z[1]-w,S=z[2]-z[0]-b,I=z[3]-z[1]-_;}var C=function(n,a,u,l){var h=Ku(n.stretch-x,b,p,t.left),f=Gu(n.fixed-A,S,n.stretch,d),y=Ku(a.stretch-w,_,c,t.top),v=Gu(a.fixed-k,I,a.stretch,m),g=Ku(u.stretch-x,b,p,t.left),z=Gu(u.fixed-A,S,u.stretch,d),C=Ku(l.stretch-w,_,c,t.top),M=Gu(l.fixed-k,I,l.stretch,m),E=new i(h,y),T=new i(g,y),P=new i(g,C),B=new i(h,C),V=new i(f/s,v/s),F=new i(z/s,M/s),D=e*Math.PI/180;if(D){var L=Math.sin(D),R=Math.cos(D),O=[R,-L,L,R];E._matMult(O),T._matMult(O),B._matMult(O),P._matMult(O);}var U=n.stretch+n.fixed,j=a.stretch+a.fixed;return {tl:E,tr:T,bl:B,br:P,tex:{x:o.paddedRect.x+1+U,y:o.paddedRect.y+1+j,w:u.stretch+u.fixed-U,h:l.stretch+l.fixed-j},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:V,pixelOffsetBR:F,minFontScaleX:S/s/p,minFontScaleY:I/s/c,isSDF:r}};if(n&&(o.stretchX||o.stretchY))for(var M=Nu(h,v,d),E=Nu(f,g,m),T=0;T<M.length-1;T++)for(var P=M[T],B=M[T+1],V=0;V<E.length-1;V++)a.push(C(P,E[V],B,E[V+1]));else a.push(C({fixed:0,stretch:-1},{fixed:0,stretch:-1},{fixed:0,stretch:u+1},{fixed:0,stretch:l+1}));return a}function qu(t,e,r){for(var n=0,i=0,a=t;i<a.length;i+=1){var o=a[i];n+=Math.max(e,Math.min(r,o[1]))-Math.max(e,Math.min(r,o[0]));}return n}function Nu(t,e,r){for(var n=[{fixed:-1,stretch:0}],i=0,a=t;i<a.length;i+=1){var o=a[i],s=o[0],u=o[1],l=n[n.length-1];n.push({fixed:s-l.stretch,stretch:l.stretch}),n.push({fixed:s-l.stretch,stretch:l.stretch+(u-s)});}return n.push({fixed:e+1,stretch:r}),n}function Ku(t,e,r,n){return t/e*r+n}function Gu(t,e,r,n){return t-e*r/n}var Zu=function(t,e,r,n,a,o,s,u,l,p){if(this.boxStartIndex=t.length,l){var c=o.top,h=o.bottom,f=o.collisionPadding;f&&(c-=f[1],h+=f[3]);var y=h-c;y>0&&(y=Math.max(10,y),this.circleDiameter=y);}else {var d=o.top*s-u,m=o.bottom*s+u,v=o.left*s-u,g=o.right*s+u,x=o.collisionPadding;if(x&&(v-=x[0]*s,d-=x[1]*s,g+=x[2]*s,m+=x[3]*s),p){var b=new i(v,d),w=new i(g,d),_=new i(v,m),A=new i(g,m),S=p*Math.PI/180;b._rotate(S),w._rotate(S),_._rotate(S),A._rotate(S),v=Math.min(b.x,w.x,_.x,A.x),g=Math.max(b.x,w.x,_.x,A.x),d=Math.min(b.y,w.y,_.y,A.y),m=Math.max(b.y,w.y,_.y,A.y);}t.emplaceBack(e.x,e.y,v,d,g,m,r,n,a);}this.boxEndIndex=t.length;},Xu=function(t,e){if(void 0===t&&(t=[]),void 0===e&&(e=Ju),this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r);};function Ju(t,e){return t<e?-1:t>e?1:0}function Hu(t,e,r){void 0===e&&(e=1),void 0===r&&(r=!1);for(var n=1/0,a=1/0,o=-1/0,s=-1/0,u=t[0],l=0;l<u.length;l++){var p=u[l];(!l||p.x<n)&&(n=p.x),(!l||p.y<a)&&(a=p.y),(!l||p.x>o)&&(o=p.x),(!l||p.y>s)&&(s=p.y);}var c=Math.min(o-n,s-a),h=c/2,f=new Xu([],Yu);if(0===c)return new i(n,a);for(var y=n;y<o;y+=c)for(var d=a;d<s;d+=c)f.push(new $u(y+h,d+h,h,t));for(var m=function(t){for(var e=0,r=0,n=0,i=t[0],a=0,o=i.length,s=o-1;a<o;s=a++){var u=i[a],l=i[s],p=u.x*l.y-l.x*u.y;r+=(u.x+l.x)*p,n+=(u.y+l.y)*p,e+=3*p;}return new $u(r/e,n/e,0,t)}(t),v=f.length;f.length;){var g=f.pop();(g.d>m.d||!m.d)&&(m=g,r&&console.log("found best %d after %d probes",Math.round(1e4*g.d)/1e4,v)),g.max-m.d<=e||(f.push(new $u(g.p.x-(h=g.h/2),g.p.y-h,h,t)),f.push(new $u(g.p.x+h,g.p.y-h,h,t)),f.push(new $u(g.p.x-h,g.p.y+h,h,t)),f.push(new $u(g.p.x+h,g.p.y+h,h,t)),v+=4);}return r&&(console.log("num probes: "+v),console.log("best distance: "+m.d)),m.p}function Yu(t,e){return e.max-t.max}function $u(t,e,r,n){this.p=new i(t,e),this.h=r,this.d=function(t,e){for(var r=!1,n=1/0,i=0;i<e.length;i++)for(var a=e[i],o=0,s=a.length,u=s-1;o<s;u=o++){var l=a[o],p=a[u];l.y>t.y!=p.y>t.y&&t.x<(p.x-l.x)*(t.y-l.y)/(p.y-l.y)+l.x&&(r=!r),n=Math.min(n,Ga(t,l,p));}return (r?1:-1)*Math.sqrt(n)}(this.p,n),this.max=this.d+this.h*Math.SQRT2;}Xu.prototype.push=function(t){this.data.push(t),this.length++,this._up(this.length-1);},Xu.prototype.pop=function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}},Xu.prototype.peek=function(){return this.data[0]},Xu.prototype._up=function(t){for(var e=this.data,r=this.compare,n=e[t];t>0;){var i=t-1>>1,a=e[i];if(r(n,a)>=0)break;e[t]=a,t=i;}e[t]=n;},Xu.prototype._down=function(t){for(var e=this.data,r=this.compare,n=this.length>>1,i=e[t];t<n;){var a=1+(t<<1),o=e[a],s=a+1;if(s<this.length&&r(e[s],o)<0&&(a=s,o=e[s]),r(o,i)>=0)break;e[t]=o,t=a;}e[t]=i;};var Wu=Number.POSITIVE_INFINITY;function Qu(t,e){return e[1]!==Wu?function(t,e,r){var n=0,i=0;switch(e=Math.abs(e),r=Math.abs(r),t){case"top-right":case"top-left":case"top":i=r-7;break;case"bottom-right":case"bottom-left":case"bottom":i=7-r;}switch(t){case"top-right":case"bottom-right":case"right":n=-e;break;case"top-left":case"bottom-left":case"left":n=e;}return [n,i]}(t,e[0],e[1]):function(t,e){var r=0,n=0;e<0&&(e=0);var i=e/Math.sqrt(2);switch(t){case"top-right":case"top-left":n=i-7;break;case"bottom-right":case"bottom-left":n=7-i;break;case"bottom":n=7-e;break;case"top":n=e-7;}switch(t){case"top-right":case"bottom-right":r=-i;break;case"top-left":case"bottom-left":r=i;break;case"left":r=e;break;case"right":r=-e;}return [r,n]}(t,e[0])}function tl(t){switch(t){case"right":case"top-right":case"bottom-right":return "right";case"left":case"top-left":case"bottom-left":return "left"}return "center"}function el(t,e,r,n,a,o,s,u,l,p,c,h,f,y,d){var m=function(t,e,r,n,a,o,s,u){for(var l=n.layout.get("text-rotate").evaluate(o,{})*Math.PI/180,p=[],c=0,h=e.positionedLines;c<h.length;c+=1)for(var f=h[c],y=0,d=f.positionedGlyphs;y<d.length;y+=1){var m=d[y];if(m.rect){var v=m.rect||{},g=4,x=!0,b=1,w=0,_=(a||u)&&m.vertical,A=m.metrics.advance*m.scale/2;if(u&&e.verticalizable&&(w=f.lineOffset/2-(m.imageName?-(24-m.metrics.width*m.scale)/2:24*(m.scale-1))),m.imageName){var S=s[m.imageName];x=S.sdf,g=1/(b=S.pixelRatio);}var k=a?[m.x+A,m.y]:[0,0],I=a?[0,0]:[m.x+A+r[0],m.y+r[1]-w],z=[0,0];_&&(z=I,I=[0,0]);var C=(m.metrics.left-g)*m.scale-A+I[0],M=(-m.metrics.top-g)*m.scale+I[1],E=C+v.w*m.scale/b,T=M+v.h*m.scale/b,P=new i(C,M),B=new i(E,M),V=new i(C,T),F=new i(E,T);if(_){var D=new i(-A,A- -17),L=-Math.PI/2,R=12-A,O=new i(22-R,-(m.imageName?R:0)),U=new(Function.prototype.bind.apply(i,[null].concat(z)));P._rotateAround(L,D)._add(O)._add(U),B._rotateAround(L,D)._add(O)._add(U),V._rotateAround(L,D)._add(O)._add(U),F._rotateAround(L,D)._add(O)._add(U);}if(l){var j=Math.sin(l),q=Math.cos(l),N=[q,-j,j,q];P._matMult(N),B._matMult(N),V._matMult(N),F._matMult(N);}var K=new i(0,0),G=new i(0,0);p.push({tl:P,tr:B,bl:V,br:F,tex:v,writingMode:e.writingMode,glyphOffset:k,sectionIndex:m.sectionIndex,isSDF:x,pixelOffsetTL:K,pixelOffsetBR:G,minFontScaleX:0,minFontScaleY:0});}}return p}(0,r,u,a,o,s,n,t.allowVerticalPlacement),v=t.textSizeData,g=null;"source"===v.kind?(g=[128*a.layout.get("text-size").evaluate(s,{})])[0]>32640&&w(t.layerIds[0]+': Value for "text-size" is >= 255. Reduce your "text-size".'):"composite"===v.kind&&((g=[128*y.compositeTextSizes[0].evaluate(s,{},d),128*y.compositeTextSizes[1].evaluate(s,{},d)])[0]>32640||g[1]>32640)&&w(t.layerIds[0]+': Value for "text-size" is >= 255. Reduce your "text-size".'),t.addSymbols(t.text,m,g,u,o,s,p,e,l.lineStartIndex,l.lineLength,f,d);for(var x=0,b=c;x<b.length;x+=1)h[b[x]]=t.text.placedSymbolArray.length-1;return 4*m.length}function rl(t){for(var e in t)return t[e];return null}function nl(t,e,r,n){var i=t.compareText;if(e in i){for(var a=i[e],o=a.length-1;o>=0;o--)if(n.dist(a[o])<r)return !0}else i[e]=[];return i[e].push(n),!1}var il=ds.VectorTileFeature.types,al=[{name:"a_fade_opacity",components:1,type:"Uint8",offset:0}];function ol(t,e,r,n,i,a,o,s,u,l,p,c,h){var f=s?Math.min(32640,Math.round(s[0])):0,y=s?Math.min(32640,Math.round(s[1])):0;t.emplaceBack(e,r,Math.round(32*n),Math.round(32*i),a,o,(f<<1)+(u?1:0),y,16*l,16*p,256*c,256*h);}function sl(t,e,r){t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r);}function ul(t){for(var e=0,r=t.sections;e<r.length;e+=1)if(Jn(r[e].text))return !0;return !1}var ll=function(t){this.layoutVertexArray=new Ei,this.indexArray=new Li,this.programConfigurations=t,this.segments=new ia,this.dynamicLayoutVertexArray=new Ti,this.opacityVertexArray=new Pi,this.placedSymbolArray=new Yi;};ll.prototype.isEmpty=function(){return 0===this.layoutVertexArray.length&&0===this.indexArray.length&&0===this.dynamicLayoutVertexArray.length&&0===this.opacityVertexArray.length},ll.prototype.upload=function(t,e,r,n){this.isEmpty()||(r&&(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Fs.members),this.indexBuffer=t.createIndexBuffer(this.indexArray,e),this.dynamicLayoutVertexBuffer=t.createVertexBuffer(this.dynamicLayoutVertexArray,Ds.members,!0),this.opacityVertexBuffer=t.createVertexBuffer(this.opacityVertexArray,al,!0),this.opacityVertexBuffer.itemSize=1),(r||n)&&this.programConfigurations.upload(t));},ll.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy());},Fn("SymbolBuffers",ll);var pl=function(t,e,r){this.layoutVertexArray=new t,this.layoutAttributes=e,this.indexArray=new r,this.segments=new ia,this.collisionVertexArray=new Di;};pl.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=t.createVertexBuffer(this.collisionVertexArray,Ls.members,!0);},pl.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy());},Fn("CollisionBuffers",pl);var cl=function(t){this.collisionBoxArray=t.collisionBoxArray,this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.pixelRatio=t.pixelRatio,this.sourceLayerIndex=t.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=eo([]),this.placementViewportMatrix=eo([]);var e=this.layers[0]._unevaluatedLayout._values;this.textSizeData=Eu(this.zoom,e["text-size"]),this.iconSizeData=Eu(this.zoom,e["icon-size"]);var r=this.layers[0].layout,n=r.get("symbol-sort-key"),i=r.get("symbol-z-order");this.sortFeaturesByKey="viewport-y"!==i&&void 0!==n.constantOr(1),this.sortFeaturesByY=("viewport-y"===i||"auto"===i&&!this.sortFeaturesByKey)&&(r.get("text-allow-overlap")||r.get("icon-allow-overlap")||r.get("text-ignore-placement")||r.get("icon-ignore-placement")),"point"===r.get("symbol-placement")&&(this.writingModes=r.get("text-writing-mode").map((function(t){return du[t]}))),this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id})),this.sourceID=t.sourceID;};cl.prototype.createArrays=function(){this.text=new ll(new Ta(Fs.members,this.layers,this.zoom,(function(t){return /^text/.test(t)}))),this.icon=new ll(new Ta(Fs.members,this.layers,this.zoom,(function(t){return /^icon/.test(t)}))),this.glyphOffsetArray=new Qi,this.lineVertexArray=new ta,this.symbolInstances=new Wi;},cl.prototype.calculateGlyphDependencies=function(t,e,r,n,i){for(var a=0;a<t.length;a++)if(e[t.charCodeAt(a)]=!0,(r||n)&&i){var o=js[t.charAt(a)];o&&(e[o.charCodeAt(0)]=!0);}},cl.prototype.populate=function(t,e,r){var n=this.layers[0],i=n.layout,a=i.get("text-font"),o=i.get("text-field"),s=i.get("icon-image"),u=("constant"!==o.value.kind||o.value.value instanceof te&&!o.value.value.isEmpty()||o.value.value.toString().length>0)&&("constant"!==a.value.kind||a.value.value.length>0),l="constant"!==s.value.kind||!!s.value.value||Object.keys(s.parameters).length>0,p=i.get("symbol-sort-key");if(this.features=[],u||l){for(var c=e.iconDependencies,h=e.glyphDependencies,f=e.availableImages,y=new ii(this.zoom),d=0,m=t;d<m.length;d+=1){var v=m[d],g=v.feature,x=v.id,b=v.index,w=v.sourceLayerIndex,_=n._featureFilter.needGeometry,A={type:g.type,id:x,properties:g.properties,geometry:_?Fa(g):[]};if(n._featureFilter.filter(y,A,r)){_||(A.geometry=Fa(g));var S=void 0;if(u){var k=n.getValueAndResolveTokens("text-field",A,r,f),I=te.factory(k);ul(I)&&(this.hasRTLText=!0),(!this.hasRTLText||"unavailable"===ei()||this.hasRTLText&&ni.isParsed())&&(S=Us(I,n,A));}var z=void 0;if(l){var C=n.getValueAndResolveTokens("icon-image",A,r,f);z=C instanceof ee?C:ee.fromString(C);}if(S||z){var M=this.sortFeaturesByKey?p.evaluate(A,{},r):void 0,E={id:x,text:S,icon:z,index:b,sourceLayerIndex:w,geometry:Fa(g),properties:g.properties,type:il[g.type],sortKey:M};if(this.features.push(E),z&&(c[z.name]=!0),S){var T=a.evaluate(A,{},r).join(","),P="map"===i.get("text-rotation-alignment")&&"point"!==i.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(du.vertical)>=0;for(var B=0,V=S.sections;B<V.length;B+=1){var F=V[B];if(F.image)c[F.image.name]=!0;else {var D=Nn(S.toString()),L=F.fontStack||T,R=h[L]=h[L]||{};this.calculateGlyphDependencies(F.text,R,P,this.allowVerticalPlacement,D);}}}}}}"line"===i.get("symbol-placement")&&(this.features=function(t){var e={},r={},n=[],i=0;function a(e){n.push(t[e]),i++;}function o(t,e,i){var a=r[t];return delete r[t],r[e]=a,n[a].geometry[0].pop(),n[a].geometry[0]=n[a].geometry[0].concat(i[0]),a}function s(t,r,i){var a=e[r];return delete e[r],e[t]=a,n[a].geometry[0].shift(),n[a].geometry[0]=i[0].concat(n[a].geometry[0]),a}function u(t,e,r){var n=r?e[0][e[0].length-1]:e[0][0];return t+":"+n.x+":"+n.y}for(var l=0;l<t.length;l++){var p=t[l],c=p.geometry,h=p.text?p.text.toString():null;if(h){var f=u(h,c),y=u(h,c,!0);if(f in r&&y in e&&r[f]!==e[y]){var d=s(f,y,c),m=o(f,y,n[d].geometry);delete e[f],delete r[y],r[u(h,n[m].geometry,!0)]=m,n[d].geometry=null;}else f in r?o(f,y,c):y in e?s(f,y,c):(a(l),e[f]=i-1,r[y]=i-1);}else a(l);}return n.filter((function(t){return t.geometry}))}(this.features)),this.sortFeaturesByKey&&this.features.sort((function(t,e){return t.sortKey-e.sortKey}));}},cl.prototype.update=function(t,e,r){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(t,e,this.layers,r),this.icon.programConfigurations.updatePaintArrays(t,e,this.layers,r));},cl.prototype.isEmpty=function(){return 0===this.symbolInstances.length&&!this.hasRTLText},cl.prototype.uploadPending=function(){return !this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload},cl.prototype.upload=function(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0;},cl.prototype.destroyDebugData=function(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy();},cl.prototype.destroy=function(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData();},cl.prototype.addToLineVertexArray=function(t,e){var r=this.lineVertexArray.length;if(void 0!==t.segment){for(var n=t.dist(e[t.segment+1]),i=t.dist(e[t.segment]),a={},o=t.segment+1;o<e.length;o++)a[o]={x:e[o].x,y:e[o].y,tileUnitDistanceFromAnchor:n},o<e.length-1&&(n+=e[o+1].dist(e[o]));for(var s=t.segment||0;s>=0;s--)a[s]={x:e[s].x,y:e[s].y,tileUnitDistanceFromAnchor:i},s>0&&(i+=e[s-1].dist(e[s]));for(var u=0;u<e.length;u++){var l=a[u];this.lineVertexArray.emplaceBack(l.x,l.y,l.tileUnitDistanceFromAnchor);}}return {lineStartIndex:r,lineLength:this.lineVertexArray.length-r}},cl.prototype.addSymbols=function(t,e,r,n,i,a,o,s,u,l,p,c){for(var h=t.indexArray,f=t.layoutVertexArray,y=t.segments.prepareSegment(4*e.length,f,h,a.sortKey),d=this.glyphOffsetArray.length,m=y.vertexLength,v=this.allowVerticalPlacement&&o===du.vertical?Math.PI/2:0,g=a.text&&a.text.sections,x=0;x<e.length;x++){var b=e[x],w=b.tl,_=b.tr,A=b.bl,S=b.br,k=b.tex,I=b.pixelOffsetTL,z=b.pixelOffsetBR,C=b.minFontScaleX,M=b.minFontScaleY,E=b.glyphOffset,T=b.isSDF,P=b.sectionIndex,B=y.vertexLength,V=E[1];ol(f,s.x,s.y,w.x,V+w.y,k.x,k.y,r,T,I.x,I.y,C,M),ol(f,s.x,s.y,_.x,V+_.y,k.x+k.w,k.y,r,T,z.x,I.y,C,M),ol(f,s.x,s.y,A.x,V+A.y,k.x,k.y+k.h,r,T,I.x,z.y,C,M),ol(f,s.x,s.y,S.x,V+S.y,k.x+k.w,k.y+k.h,r,T,z.x,z.y,C,M),sl(t.dynamicLayoutVertexArray,s,v),h.emplaceBack(B,B+1,B+2),h.emplaceBack(B+1,B+2,B+3),y.vertexLength+=4,y.primitiveLength+=2,this.glyphOffsetArray.emplaceBack(E[0]),x!==e.length-1&&P===e[x+1].sectionIndex||t.programConfigurations.populatePaintArrays(f.length,a,a.index,{},c,g&&g[P]);}t.placedSymbolArray.emplaceBack(s.x,s.y,d,this.glyphOffsetArray.length-d,m,u,l,s.segment,r?r[0]:0,r?r[1]:0,n[0],n[1],o,0,!1,0,p);},cl.prototype._addCollisionDebugVertex=function(t,e,r,n,i,a){return e.emplaceBack(0,0),t.emplaceBack(r.x,r.y,n,i,Math.round(a.x),Math.round(a.y))},cl.prototype.addCollisionDebugVertices=function(t,e,r,n,a,o,s){var u=a.segments.prepareSegment(4,a.layoutVertexArray,a.indexArray),l=u.vertexLength,p=a.layoutVertexArray,c=a.collisionVertexArray,h=s.anchorX,f=s.anchorY;this._addCollisionDebugVertex(p,c,o,h,f,new i(t,e)),this._addCollisionDebugVertex(p,c,o,h,f,new i(r,e)),this._addCollisionDebugVertex(p,c,o,h,f,new i(r,n)),this._addCollisionDebugVertex(p,c,o,h,f,new i(t,n)),u.vertexLength+=4;var y=a.indexArray;y.emplaceBack(l,l+1),y.emplaceBack(l+1,l+2),y.emplaceBack(l+2,l+3),y.emplaceBack(l+3,l),u.primitiveLength+=4;},cl.prototype.addDebugCollisionBoxes=function(t,e,r,n){for(var i=t;i<e;i++){var a=this.collisionBoxArray.get(i);this.addCollisionDebugVertices(a.x1,a.y1,a.x2,a.y2,n?this.textCollisionBox:this.iconCollisionBox,a.anchorPoint,r);}},cl.prototype.generateCollisionDebugBuffers=function(){this.hasDebugData()&&this.destroyDebugData(),this.textCollisionBox=new pl(Vi,Rs.members,Ni),this.iconCollisionBox=new pl(Vi,Rs.members,Ni);for(var t=0;t<this.symbolInstances.length;t++){var e=this.symbolInstances.get(t);this.addDebugCollisionBoxes(e.textBoxStartIndex,e.textBoxEndIndex,e,!0),this.addDebugCollisionBoxes(e.verticalTextBoxStartIndex,e.verticalTextBoxEndIndex,e,!0),this.addDebugCollisionBoxes(e.iconBoxStartIndex,e.iconBoxEndIndex,e,!1),this.addDebugCollisionBoxes(e.verticalIconBoxStartIndex,e.verticalIconBoxEndIndex,e,!1);}},cl.prototype._deserializeCollisionBoxesForSymbol=function(t,e,r,n,i,a,o,s,u){for(var l={},p=e;p<r;p++){var c=t.get(p);l.textBox={x1:c.x1,y1:c.y1,x2:c.x2,y2:c.y2,anchorPointX:c.anchorPointX,anchorPointY:c.anchorPointY},l.textFeatureIndex=c.featureIndex;break}for(var h=n;h<i;h++){var f=t.get(h);l.verticalTextBox={x1:f.x1,y1:f.y1,x2:f.x2,y2:f.y2,anchorPointX:f.anchorPointX,anchorPointY:f.anchorPointY},l.verticalTextFeatureIndex=f.featureIndex;break}for(var y=a;y<o;y++){var d=t.get(y);l.iconBox={x1:d.x1,y1:d.y1,x2:d.x2,y2:d.y2,anchorPointX:d.anchorPointX,anchorPointY:d.anchorPointY},l.iconFeatureIndex=d.featureIndex;break}for(var m=s;m<u;m++){var v=t.get(m);l.verticalIconBox={x1:v.x1,y1:v.y1,x2:v.x2,y2:v.y2,anchorPointX:v.anchorPointX,anchorPointY:v.anchorPointY},l.verticalIconFeatureIndex=v.featureIndex;break}return l},cl.prototype.deserializeCollisionBoxes=function(t){this.collisionArrays=[];for(var e=0;e<this.symbolInstances.length;e++){var r=this.symbolInstances.get(e);this.collisionArrays.push(this._deserializeCollisionBoxesForSymbol(t,r.textBoxStartIndex,r.textBoxEndIndex,r.verticalTextBoxStartIndex,r.verticalTextBoxEndIndex,r.iconBoxStartIndex,r.iconBoxEndIndex,r.verticalIconBoxStartIndex,r.verticalIconBoxEndIndex));}},cl.prototype.hasTextData=function(){return this.text.segments.get().length>0},cl.prototype.hasIconData=function(){return this.icon.segments.get().length>0},cl.prototype.hasDebugData=function(){return this.textCollisionBox&&this.iconCollisionBox},cl.prototype.hasTextCollisionBoxData=function(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0},cl.prototype.hasIconCollisionBoxData=function(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0},cl.prototype.addIndicesForPlacedSymbol=function(t,e){for(var r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs,i=r.vertexStartIndex;i<n;i+=4)t.indexArray.emplaceBack(i,i+1,i+2),t.indexArray.emplaceBack(i+1,i+2,i+3);},cl.prototype.getSortedSymbolIndexes=function(t){if(this.sortedAngle===t&&void 0!==this.symbolInstanceIndexes)return this.symbolInstanceIndexes;for(var e=Math.sin(t),r=Math.cos(t),n=[],i=[],a=[],o=0;o<this.symbolInstances.length;++o){a.push(o);var s=this.symbolInstances.get(o);n.push(0|Math.round(e*s.anchorX+r*s.anchorY)),i.push(s.featureIndex);}return a.sort((function(t,e){return n[t]-n[e]||i[e]-i[t]})),a},cl.prototype.addToSortKeyRanges=function(t,e){var r=this.sortKeyRanges[this.sortKeyRanges.length-1];r&&r.sortKey===e?r.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1});},cl.prototype.sortFeatures=function(t){var e=this;if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(var r=0,n=this.symbolInstanceIndexes;r<n.length;r+=1){var i=this.symbolInstances.get(n[r]);this.featureSortOrder.push(i.featureIndex),[i.rightJustifiedTextSymbolIndex,i.centerJustifiedTextSymbolIndex,i.leftJustifiedTextSymbolIndex].forEach((function(t,r,n){t>=0&&n.indexOf(t)===r&&e.addIndicesForPlacedSymbol(e.text,t);})),i.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,i.verticalPlacedTextSymbolIndex),i.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,i.placedIconSymbolIndex),i.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,i.verticalPlacedIconSymbolIndex);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}},Fn("SymbolBucket",cl,{omit:["layers","collisionBoxArray","features","compareText"]}),cl.MAX_GLYPHS=65535,cl.addDynamicAttributes=sl;var hl=new gi({"symbol-placement":new fi(It.layout_symbol["symbol-placement"]),"symbol-spacing":new fi(It.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new fi(It.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new yi(It.layout_symbol["symbol-sort-key"]),"symbol-z-order":new fi(It.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new fi(It.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new fi(It.layout_symbol["icon-ignore-placement"]),"icon-optional":new fi(It.layout_symbol["icon-optional"]),"icon-rotation-alignment":new fi(It.layout_symbol["icon-rotation-alignment"]),"icon-size":new yi(It.layout_symbol["icon-size"]),"icon-text-fit":new fi(It.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new fi(It.layout_symbol["icon-text-fit-padding"]),"icon-image":new yi(It.layout_symbol["icon-image"]),"icon-rotate":new yi(It.layout_symbol["icon-rotate"]),"icon-padding":new fi(It.layout_symbol["icon-padding"]),"icon-keep-upright":new fi(It.layout_symbol["icon-keep-upright"]),"icon-offset":new yi(It.layout_symbol["icon-offset"]),"icon-anchor":new yi(It.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new fi(It.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new fi(It.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new fi(It.layout_symbol["text-rotation-alignment"]),"text-field":new yi(It.layout_symbol["text-field"]),"text-font":new yi(It.layout_symbol["text-font"]),"text-size":new yi(It.layout_symbol["text-size"]),"text-max-width":new yi(It.layout_symbol["text-max-width"]),"text-line-height":new fi(It.layout_symbol["text-line-height"]),"text-letter-spacing":new yi(It.layout_symbol["text-letter-spacing"]),"text-justify":new yi(It.layout_symbol["text-justify"]),"text-radial-offset":new yi(It.layout_symbol["text-radial-offset"]),"text-variable-anchor":new fi(It.layout_symbol["text-variable-anchor"]),"text-anchor":new yi(It.layout_symbol["text-anchor"]),"text-max-angle":new fi(It.layout_symbol["text-max-angle"]),"text-writing-mode":new fi(It.layout_symbol["text-writing-mode"]),"text-rotate":new yi(It.layout_symbol["text-rotate"]),"text-padding":new fi(It.layout_symbol["text-padding"]),"text-keep-upright":new fi(It.layout_symbol["text-keep-upright"]),"text-transform":new yi(It.layout_symbol["text-transform"]),"text-offset":new yi(It.layout_symbol["text-offset"]),"text-allow-overlap":new fi(It.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new fi(It.layout_symbol["text-ignore-placement"]),"text-optional":new fi(It.layout_symbol["text-optional"])}),fl={paint:new gi({"icon-opacity":new yi(It.paint_symbol["icon-opacity"]),"icon-color":new yi(It.paint_symbol["icon-color"]),"icon-halo-color":new yi(It.paint_symbol["icon-halo-color"]),"icon-halo-width":new yi(It.paint_symbol["icon-halo-width"]),"icon-halo-blur":new yi(It.paint_symbol["icon-halo-blur"]),"icon-translate":new fi(It.paint_symbol["icon-translate"]),"icon-translate-anchor":new fi(It.paint_symbol["icon-translate-anchor"]),"text-opacity":new yi(It.paint_symbol["text-opacity"]),"text-color":new yi(It.paint_symbol["text-color"],{runtimeType:Rt,getOverride:function(t){return t.textColor},hasOverride:function(t){return !!t.textColor}}),"text-halo-color":new yi(It.paint_symbol["text-halo-color"]),"text-halo-width":new yi(It.paint_symbol["text-halo-width"]),"text-halo-blur":new yi(It.paint_symbol["text-halo-blur"]),"text-translate":new fi(It.paint_symbol["text-translate"]),"text-translate-anchor":new fi(It.paint_symbol["text-translate-anchor"])}),layout:hl},yl=function(t){this.type=t.property.overrides?t.property.overrides.runtimeType:Vt,this.defaultValue=t;};yl.prototype.evaluate=function(t){if(t.formattedSection){var e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default},yl.prototype.eachChild=function(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);},yl.prototype.outputDefined=function(){return !1},yl.prototype.serialize=function(){return null},Fn("FormatSectionOverride",yl,{omit:["defaultValue"]});var dl=function(t){function e(e){t.call(this,e,fl);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.recalculate=function(e,r){if(t.prototype.recalculate.call(this,e,r),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){var n=this.layout.get("text-writing-mode");if(n){for(var i=[],a=0,o=n;a<o.length;a+=1){var s=o[a];i.indexOf(s)<0&&i.push(s);}this.layout._values["text-writing-mode"]=i;}else this.layout._values["text-writing-mode"]=["horizontal"];}this._setPaintOverrides();},e.prototype.getValueAndResolveTokens=function(t,e,r,n){var i=this.layout.get(t).evaluate(e,{},r,n),a=this._unevaluatedLayout._values[t];return a.isDataDriven()||qr(a.value)||!i?i:function(t,e){return e.replace(/{([^{}]+)}/g,(function(e,r){return r in t?String(t[r]):""}))}(e.properties,i)},e.prototype.createBucket=function(t){return new cl(t)},e.prototype.queryRadius=function(){return 0},e.prototype.queryIntersectsFeature=function(){return !1},e.prototype._setPaintOverrides=function(){for(var t=0,r=fl.paint.overridableProperties;t<r.length;t+=1){var n=r[t];if(e.hasPaintOverride(this.layout,n)){var i,a=this.paint.get(n),o=new yl(a),s=new jr(o,a.property.specification);i="constant"===a.value.kind||"source"===a.value.kind?new Kr("source",s):new Gr("composite",s,a.value.zoomStops,a.value._interpolationType),this.paint._values[n]=new ci(a.property,i,a.parameters);}}},e.prototype._handleOverridablePaintPropertyUpdate=function(t,r,n){return !(!this.layout||r.isDataDriven()||n.isDataDriven())&&e.hasPaintOverride(this.layout,t)},e.hasPaintOverride=function(t,e){var r=t.get("text-field"),n=fl.paint.properties[e],i=!1,a=function(t){for(var e=0,r=t;e<r.length;e+=1)if(n.overrides&&n.overrides.hasOverride(r[e]))return void(i=!0)};if("constant"===r.value.kind&&r.value.value instanceof te)a(r.value.value.sections);else if("source"===r.value.kind){var o=function(t){i||(t instanceof oe&&ie(t.value)===qt?a(t.value.sections):t instanceof pe?a(t.sections):t.eachChild(o));},s=r.value;s._styleExpression&&o(s._styleExpression.expression);}return i},e}(xi),ml={paint:new gi({"background-color":new fi(It.paint_background["background-color"]),"background-pattern":new mi(It.paint_background["background-pattern"]),"background-opacity":new fi(It.paint_background["background-opacity"])})},vl=function(t){function e(e){t.call(this,e,ml);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e}(xi),gl={paint:new gi({"raster-opacity":new fi(It.paint_raster["raster-opacity"]),"raster-hue-rotate":new fi(It.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new fi(It.paint_raster["raster-brightness-min"]),"raster-brightness-max":new fi(It.paint_raster["raster-brightness-max"]),"raster-saturation":new fi(It.paint_raster["raster-saturation"]),"raster-contrast":new fi(It.paint_raster["raster-contrast"]),"raster-resampling":new fi(It.paint_raster["raster-resampling"]),"raster-fade-duration":new fi(It.paint_raster["raster-fade-duration"])})},xl=function(t){function e(e){t.call(this,e,gl);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e}(xi),bl=function(t){function e(e){t.call(this,e,{}),this.implementation=e;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.is3D=function(){return "3d"===this.implementation.renderingMode},e.prototype.hasOffscreenPass=function(){return void 0!==this.implementation.prerender},e.prototype.recalculate=function(){},e.prototype.updateTransitions=function(){},e.prototype.hasTransition=function(){},e.prototype.serialize=function(){},e.prototype.onAdd=function(t){this.implementation.onAdd&&this.implementation.onAdd(t,t.painter.context.gl);},e.prototype.onRemove=function(t){this.implementation.onRemove&&this.implementation.onRemove(t,t.painter.context.gl);},e}(xi),wl={circle:oo,heatmap:vo,hillshade:xo,fill:as,"fill-extrusion":_s,line:Bs,symbol:dl,background:vl,raster:xl},_l=self.HTMLImageElement,Al=self.HTMLCanvasElement,Sl=self.HTMLVideoElement,kl=self.ImageData,Il=self.ImageBitmap,zl=function(t,e,r,n){this.context=t,this.format=r,this.texture=t.gl.createTexture(),this.update(e,n);};zl.prototype.update=function(t,e,r){var n=t.width,i=t.height,a=!(this.size&&this.size[0]===n&&this.size[1]===i||r),o=this.context,s=o.gl;if(this.useMipmap=Boolean(e&&e.useMipmap),s.bindTexture(s.TEXTURE_2D,this.texture),o.pixelStoreUnpackFlipY.set(!1),o.pixelStoreUnpack.set(1),o.pixelStoreUnpackPremultiplyAlpha.set(this.format===s.RGBA&&(!e||!1!==e.premultiply)),a)this.size=[n,i],t instanceof _l||t instanceof Al||t instanceof Sl||t instanceof kl||Il&&t instanceof Il?s.texImage2D(s.TEXTURE_2D,0,this.format,this.format,s.UNSIGNED_BYTE,t):s.texImage2D(s.TEXTURE_2D,0,this.format,n,i,0,this.format,s.UNSIGNED_BYTE,t.data);else {var u=r||{x:0,y:0},l=u.x,p=u.y;t instanceof _l||t instanceof Al||t instanceof Sl||t instanceof kl||Il&&t instanceof Il?s.texSubImage2D(s.TEXTURE_2D,0,l,p,s.RGBA,s.UNSIGNED_BYTE,t):s.texSubImage2D(s.TEXTURE_2D,0,l,p,n,i,s.RGBA,s.UNSIGNED_BYTE,t.data);}this.useMipmap&&this.isSizePowerOfTwo()&&s.generateMipmap(s.TEXTURE_2D);},zl.prototype.bind=function(t,e,r){var n=this.context.gl;n.bindTexture(n.TEXTURE_2D,this.texture),r!==n.LINEAR_MIPMAP_NEAREST||this.isSizePowerOfTwo()||(r=n.LINEAR),t!==this.filter&&(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,t),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,r||t),this.filter=t),e!==this.wrap&&(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,e),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,e),this.wrap=e);},zl.prototype.isSizePowerOfTwo=function(){return this.size[0]===this.size[1]&&Math.log(this.size[0])/Math.LN2%1==0},zl.prototype.destroy=function(){this.context.gl.deleteTexture(this.texture),this.texture=null;};var Cl=function(t){var e=this;this._callback=t,this._triggered=!1,"undefined"!=typeof MessageChannel&&(this._channel=new MessageChannel,this._channel.port2.onmessage=function(){e._triggered=!1,e._callback();});};Cl.prototype.trigger=function(){var t=this;this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout((function(){t._triggered=!1,t._callback();}),0));},Cl.prototype.remove=function(){delete this._channel,this._callback=function(){};};var Ml=function(t,e,r){this.target=t,this.parent=e,this.mapId=r,this.callbacks={},this.tasks={},this.taskQueue=[],this.cancelCallbacks={},d(["receive","process"],this),this.invoker=new Cl(this.process),this.target.addEventListener("message",this.receive,!1),this.globalScope=S()?t:self;};function El(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return [t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}Ml.prototype.send=function(t,e,r,n,i){var a=this;void 0===i&&(i=!1);var o=Math.round(1e18*Math.random()).toString(36).substring(0,10);r&&(this.callbacks[o]=r);var s=z(this.globalScope)?void 0:[];return this.target.postMessage({id:o,type:t,hasCallback:!!r,targetMapId:n,mustQueue:i,sourceMapId:this.mapId,data:On(e,s)},s),{cancel:function(){r&&delete a.callbacks[o],a.target.postMessage({id:o,type:"<cancel>",targetMapId:n,sourceMapId:a.mapId});}}},Ml.prototype.receive=function(t){var e=t.data,r=e.id;if(r&&(!e.targetMapId||this.mapId===e.targetMapId))if("<cancel>"===e.type){delete this.tasks[r];var n=this.cancelCallbacks[r];delete this.cancelCallbacks[r],n&&n();}else S()||e.mustQueue?(this.tasks[r]=e,this.taskQueue.push(r),this.invoker.trigger()):this.processTask(r,e);},Ml.prototype.process=function(){if(this.taskQueue.length){var t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length&&this.invoker.trigger(),e&&this.processTask(t,e);}},Ml.prototype.processTask=function(t,e){var r=this;if("<response>"===e.type){var n=this.callbacks[t];delete this.callbacks[t],n&&(e.error?n(Un(e.error)):n(null,Un(e.data)));}else {var i=!1,a=z(this.globalScope)?void 0:[],o=e.hasCallback?function(e,n){i=!0,delete r.cancelCallbacks[t],r.target.postMessage({id:t,type:"<response>",sourceMapId:r.mapId,error:e?On(e):null,data:On(n,a)},a);}:function(t){i=!0;},s=null,u=Un(e.data);if(this.parent[e.type])s=this.parent[e.type](e.sourceMapId,u,o);else if(this.parent.getWorkerSource){var l=e.type.split(".");s=this.parent.getWorkerSource(e.sourceMapId,l[0],u.source)[l[1]](u,o);}else o(new Error("Could not find function "+e.type));!i&&s&&s.cancel&&(this.cancelCallbacks[t]=s.cancel);}},Ml.prototype.remove=function(){this.invoker.remove(),this.target.removeEventListener("message",this.receive,!1);};var Tl=function(t,e){t&&(e?this.setSouthWest(t).setNorthEast(e):4===t.length?this.setSouthWest([t[0],t[1]]).setNorthEast([t[2],t[3]]):this.setSouthWest(t[0]).setNorthEast(t[1]));};Tl.prototype.setNorthEast=function(t){return this._ne=t instanceof Pl?new Pl(t.lng,t.lat):Pl.convert(t),this},Tl.prototype.setSouthWest=function(t){return this._sw=t instanceof Pl?new Pl(t.lng,t.lat):Pl.convert(t),this},Tl.prototype.extend=function(t){var e,r,n=this._sw,i=this._ne;if(t instanceof Pl)e=t,r=t;else {if(!(t instanceof Tl))return Array.isArray(t)?4===t.length||t.every(Array.isArray)?this.extend(Tl.convert(t)):this.extend(Pl.convert(t)):this;if(r=t._ne,!(e=t._sw)||!r)return this}return n||i?(n.lng=Math.min(e.lng,n.lng),n.lat=Math.min(e.lat,n.lat),i.lng=Math.max(r.lng,i.lng),i.lat=Math.max(r.lat,i.lat)):(this._sw=new Pl(e.lng,e.lat),this._ne=new Pl(r.lng,r.lat)),this},Tl.prototype.getCenter=function(){return new Pl((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)},Tl.prototype.getSouthWest=function(){return this._sw},Tl.prototype.getNorthEast=function(){return this._ne},Tl.prototype.getNorthWest=function(){return new Pl(this.getWest(),this.getNorth())},Tl.prototype.getSouthEast=function(){return new Pl(this.getEast(),this.getSouth())},Tl.prototype.getWest=function(){return this._sw.lng},Tl.prototype.getSouth=function(){return this._sw.lat},Tl.prototype.getEast=function(){return this._ne.lng},Tl.prototype.getNorth=function(){return this._ne.lat},Tl.prototype.toArray=function(){return [this._sw.toArray(),this._ne.toArray()]},Tl.prototype.toString=function(){return "LngLatBounds("+this._sw.toString()+", "+this._ne.toString()+")"},Tl.prototype.isEmpty=function(){return !(this._sw&&this._ne)},Tl.prototype.contains=function(t){var e=Pl.convert(t),r=e.lng,n=e.lat,i=this._sw.lng<=r&&r<=this._ne.lng;return this._sw.lng>this._ne.lng&&(i=this._sw.lng>=r&&r>=this._ne.lng),this._sw.lat<=n&&n<=this._ne.lat&&i},Tl.convert=function(t){return !t||t instanceof Tl?t:new Tl(t)};var Pl=function(t,e){if(isNaN(t)||isNaN(e))throw new Error("Invalid LngLat object: ("+t+", "+e+")");if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")};Pl.prototype.wrap=function(){return new Pl(l(this.lng,-180,180),this.lat)},Pl.prototype.toArray=function(){return [this.lng,this.lat]},Pl.prototype.toString=function(){return "LngLat("+this.lng+", "+this.lat+")"},Pl.prototype.distanceTo=function(t){var e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return 6371008.8*Math.acos(Math.min(i,1))},Pl.prototype.toBounds=function(t){void 0===t&&(t=0);var e=360*t/40075017,r=e/Math.cos(Math.PI/180*this.lat);return new Tl(new Pl(this.lng-r,this.lat-e),new Pl(this.lng+r,this.lat+e))},Pl.convert=function(t){if(t instanceof Pl)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new Pl(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new Pl(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, an object {lon: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]")};var Bl=2*Math.PI*6371008.8;function Vl(t){return Bl*Math.cos(t*Math.PI/180)}function Fl(t){return (180+t)/360}function Dl(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function Ll(t,e){return t/Vl(e)}function Rl(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}var Ol=function(t,e,r){void 0===r&&(r=0),this.x=+t,this.y=+e,this.z=+r;};Ol.fromLngLat=function(t,e){void 0===e&&(e=0);var r=Pl.convert(t);return new Ol(Fl(r.lng),Dl(r.lat),Ll(e,r.lat))},Ol.prototype.toLngLat=function(){return new Pl(360*this.x-180,Rl(this.y))},Ol.prototype.toAltitude=function(){return this.z*Vl(Rl(this.y))},Ol.prototype.meterInMercatorCoordinateUnits=function(){return 1/Bl*(t=Rl(this.y),1/Math.cos(t*Math.PI/180));var t;};var Ul=function(t,e,r){this.z=t,this.x=e,this.y=r,this.key=Nl(0,t,t,e,r);};Ul.prototype.equals=function(t){return this.z===t.z&&this.x===t.x&&this.y===t.y},Ul.prototype.url=function(t,e){var r,n,i,a,o,s=(n=this.y,i=this.z,a=El(256*(r=this.x),256*(n=Math.pow(2,i)-n-1),i),o=El(256*(r+1),256*(n+1),i),a[0]+","+a[1]+","+o[0]+","+o[1]),u=function(t,e,r){for(var n,i="",a=t;a>0;a--)i+=(e&(n=1<<a-1)?1:0)+(r&n?2:0);return i}(this.z,this.x,this.y);return t[(this.x+this.y)%t.length].replace("{prefix}",(this.x%16).toString(16)+(this.y%16).toString(16)).replace("{z}",String(this.z)).replace("{x}",String(this.x)).replace("{y}",String("tms"===e?Math.pow(2,this.z)-this.y-1:this.y)).replace("{quadkey}",u).replace("{bbox-epsg-3857}",s)},Ul.prototype.getTilePoint=function(t){var e=Math.pow(2,this.z);return new i(8192*(t.x*e-this.x),8192*(t.y*e-this.y))},Ul.prototype.toString=function(){return this.z+"/"+this.x+"/"+this.y};var jl=function(t,e){this.wrap=t,this.canonical=e,this.key=Nl(t,e.z,e.z,e.x,e.y);},ql=function(t,e,r,n,i){this.overscaledZ=t,this.wrap=e,this.canonical=new Ul(r,+n,+i),this.key=Nl(e,t,r,n,i);};function Nl(t,e,r,n,i){(t*=2)<0&&(t=-1*t-1);var a=1<<r;return (a*a*t+a*i+n).toString(36)+r.toString(36)+e.toString(36)}ql.prototype.equals=function(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)},ql.prototype.scaledTo=function(t){var e=this.canonical.z-t;return t>this.canonical.z?new ql(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new ql(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)},ql.prototype.calculateScaledKey=function(t,e){var r=this.canonical.z-t;return t>this.canonical.z?Nl(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Nl(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)},ql.prototype.isChildOf=function(t){if(t.wrap!==this.wrap)return !1;var e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ<this.overscaledZ&&t.canonical.x===this.canonical.x>>e&&t.canonical.y===this.canonical.y>>e},ql.prototype.children=function(t){if(this.overscaledZ>=t)return [new ql(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];var e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return [new ql(e,this.wrap,e,r,n),new ql(e,this.wrap,e,r+1,n),new ql(e,this.wrap,e,r,n+1),new ql(e,this.wrap,e,r+1,n+1)]},ql.prototype.isLessThan=function(t){return this.wrap<t.wrap||!(this.wrap>t.wrap)&&(this.overscaledZ<t.overscaledZ||!(this.overscaledZ>t.overscaledZ)&&(this.canonical.x<t.canonical.x||!(this.canonical.x>t.canonical.x)&&this.canonical.y<t.canonical.y))},ql.prototype.wrapped=function(){return new ql(this.overscaledZ,0,this.canonical.z,this.canonical.x,this.canonical.y)},ql.prototype.unwrapTo=function(t){return new ql(this.overscaledZ,t,this.canonical.z,this.canonical.x,this.canonical.y)},ql.prototype.overscaleFactor=function(){return Math.pow(2,this.overscaledZ-this.canonical.z)},ql.prototype.toUnwrapped=function(){return new jl(this.wrap,this.canonical)},ql.prototype.toString=function(){return this.overscaledZ+"/"+this.canonical.x+"/"+this.canonical.y},ql.prototype.getTilePoint=function(t){return this.canonical.getTilePoint(new Ol(t.x-this.wrap,t.y))},Fn("CanonicalTileID",Ul),Fn("OverscaledTileID",ql,{omit:["posMatrix"]});var Kl=function(t,e,r){if(this.uid=t,e.height!==e.width)throw new RangeError("DEM tiles must be square");if(r&&"mapbox"!==r&&"terrarium"!==r)return w('"'+r+'" is not a valid encoding type. Valid types include "mapbox" and "terrarium".');this.stride=e.height;var n=this.dim=e.height-2;this.data=new Uint32Array(e.data.buffer),this.encoding=r||"mapbox";for(var i=0;i<n;i++)this.data[this._idx(-1,i)]=this.data[this._idx(0,i)],this.data[this._idx(n,i)]=this.data[this._idx(n-1,i)],this.data[this._idx(i,-1)]=this.data[this._idx(i,0)],this.data[this._idx(i,n)]=this.data[this._idx(i,n-1)];this.data[this._idx(-1,-1)]=this.data[this._idx(0,0)],this.data[this._idx(n,-1)]=this.data[this._idx(n-1,0)],this.data[this._idx(-1,n)]=this.data[this._idx(0,n-1)],this.data[this._idx(n,n)]=this.data[this._idx(n-1,n-1)];};Kl.prototype.get=function(t,e){var r=new Uint8Array(this.data.buffer),n=4*this._idx(t,e);return ("terrarium"===this.encoding?this._unpackTerrarium:this._unpackMapbox)(r[n],r[n+1],r[n+2])},Kl.prototype.getUnpackVector=function(){return "terrarium"===this.encoding?[256,1,1/256,32768]:[6553.6,25.6,.1,1e4]},Kl.prototype._idx=function(t,e){if(t<-1||t>=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return (e+1)*this.stride+(t+1)},Kl.prototype._unpackMapbox=function(t,e,r){return (256*t*256+256*e+r)/10-1e4},Kl.prototype._unpackTerrarium=function(t,e,r){return 256*t+e+r/256-32768},Kl.prototype.getPixels=function(){return new fo({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))},Kl.prototype.backfillBorder=function(t,e,r){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");var n=e*this.dim,i=e*this.dim+this.dim,a=r*this.dim,o=r*this.dim+this.dim;switch(e){case-1:n=i-1;break;case 1:i=n+1;}switch(r){case-1:a=o-1;break;case 1:o=a+1;}for(var s=-e*this.dim,u=-r*this.dim,l=a;l<o;l++)for(var p=n;p<i;p++)this.data[this._idx(p,l)]=t.data[this._idx(p+s,l+u)];},Fn("DEMData",Kl);var Gl=function(t){this._stringToNumber={},this._numberToString=[];for(var e=0;e<t.length;e++){var r=t[e];this._stringToNumber[r]=e,this._numberToString[e]=r;}};Gl.prototype.encode=function(t){return this._stringToNumber[t]},Gl.prototype.decode=function(t){return this._numberToString[t]};var Zl=function(t,e,r,n,i){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,this.id=i;},Xl={geometry:{configurable:!0}};Xl.geometry.get=function(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry},Xl.geometry.set=function(t){this._geometry=t;},Zl.prototype.toJSON=function(){var t={geometry:this.geometry};for(var e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t},Object.defineProperties(Zl.prototype,Xl);var Jl=function(){this.state={},this.stateChanges={},this.deletedStates={};};Jl.prototype.updateState=function(t,e,r){var n=String(e);if(this.stateChanges[t]=this.stateChanges[t]||{},this.stateChanges[t][n]=this.stateChanges[t][n]||{},p(this.stateChanges[t][n],r),null===this.deletedStates[t])for(var i in this.deletedStates[t]={},this.state[t])i!==n&&(this.deletedStates[t][i]=null);else if(this.deletedStates[t]&&null===this.deletedStates[t][n])for(var a in this.deletedStates[t][n]={},this.state[t][n])r[a]||(this.deletedStates[t][n][a]=null);else for(var o in r)this.deletedStates[t]&&this.deletedStates[t][n]&&null===this.deletedStates[t][n][o]&&delete this.deletedStates[t][n][o];},Jl.prototype.removeFeatureState=function(t,e,r){if(null!==this.deletedStates[t]){var n=String(e);if(this.deletedStates[t]=this.deletedStates[t]||{},r&&void 0!==e)null!==this.deletedStates[t][n]&&(this.deletedStates[t][n]=this.deletedStates[t][n]||{},this.deletedStates[t][n][r]=null);else if(void 0!==e)if(this.stateChanges[t]&&this.stateChanges[t][n])for(r in this.deletedStates[t][n]={},this.stateChanges[t][n])this.deletedStates[t][n][r]=null;else this.deletedStates[t][n]=null;else this.deletedStates[t]=null;}},Jl.prototype.getState=function(t,e){var r=String(e),n=p({},(this.state[t]||{})[r],(this.stateChanges[t]||{})[r]);if(null===this.deletedStates[t])return {};if(this.deletedStates[t]){var i=this.deletedStates[t][e];if(null===i)return {};for(var a in i)delete n[a];}return n},Jl.prototype.initializeTileState=function(t,e){t.setFeatureState(this.state,e);},Jl.prototype.coalesceChanges=function(t,e){var r={};for(var n in this.stateChanges){this.state[n]=this.state[n]||{};var i={};for(var a in this.stateChanges[n])this.state[n][a]||(this.state[n][a]={}),p(this.state[n][a],this.stateChanges[n][a]),i[a]=this.state[n][a];r[n]=i;}for(var o in this.deletedStates){this.state[o]=this.state[o]||{};var s={};if(null===this.deletedStates[o])for(var u in this.state[o])s[u]={},this.state[o][u]={};else for(var l in this.deletedStates[o]){if(null===this.deletedStates[o][l])this.state[o][l]={};else for(var c=0,h=Object.keys(this.deletedStates[o][l]);c<h.length;c+=1)delete this.state[o][l][h[c]];s[l]=this.state[o][l];}r[o]=r[o]||{},p(r[o],s);}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(r).length)for(var f in t)t[f].setFeatureState(r,e);};var Hl=function(t,e){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=new En(8192,16,0),this.grid3D=new En(8192,16,0),this.featureIndexArray=new ra,this.promoteId=e;};function Yl(t,e,r,n,i){return v(t,(function(t,a){var o=e instanceof hi?e.get(a):null;return o&&o.evaluate?o.evaluate(r,n,i):o}))}function $l(t){for(var e=1/0,r=1/0,n=-1/0,i=-1/0,a=0,o=t;a<o.length;a+=1){var s=o[a];e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);}return {minX:e,minY:r,maxX:n,maxY:i}}function Wl(t,e){return e-t}Hl.prototype.insert=function(t,e,r,n,i,a){var o=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);for(var s=a?this.grid3D:this.grid,u=0;u<e.length;u++){for(var l=e[u],p=[1/0,1/0,-1/0,-1/0],c=0;c<l.length;c++){var h=l[c];p[0]=Math.min(p[0],h.x),p[1]=Math.min(p[1],h.y),p[2]=Math.max(p[2],h.x),p[3]=Math.max(p[3],h.y);}p[0]<8192&&p[1]<8192&&p[2]>=0&&p[3]>=0&&s.insert(o,p[0],p[1],p[2],p[3]);}},Hl.prototype.loadVTLayers=function(){return this.vtLayers||(this.vtLayers=new ds.VectorTile(new Ks(this.rawTileData)).layers,this.sourceLayerCoder=new Gl(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers},Hl.prototype.query=function(t,e,r,n){var a=this;this.loadVTLayers();for(var o=t.params||{},s=8192/t.tileSize/t.scale,u=rn(o.filter),l=t.queryGeometry,p=t.queryPadding*s,c=$l(l),h=this.grid.query(c.minX-p,c.minY-p,c.maxX+p,c.maxY+p),f=$l(t.cameraQueryGeometry),y=this.grid3D.query(f.minX-p,f.minY-p,f.maxX+p,f.maxY+p,(function(e,r,n,a){return function(t,e,r,n,a){for(var o=0,s=t;o<s.length;o+=1){var u=s[o];if(e<=u.x&&r<=u.y&&n>=u.x&&a>=u.y)return !0}var l=[new i(e,r),new i(e,a),new i(n,a),new i(n,r)];if(t.length>2)for(var p=0,c=l;p<c.length;p+=1)if(Xa(t,c[p]))return !0;for(var h=0;h<t.length-1;h++)if(Ja(t[h],t[h+1],l))return !0;return !1}(t.cameraQueryGeometry,e-p,r-p,n+p,a+p)})),d=0,m=y;d<m.length;d+=1)h.push(m[d]);h.sort(Wl);for(var v,g={},x=function(i){var p=h[i];if(p!==v){v=p;var c=a.featureIndexArray.get(p),f=null;a.loadMatchingFeature(g,c.bucketIndex,c.sourceLayerIndex,c.featureIndex,u,o.layers,o.availableImages,e,r,n,(function(e,r,n){return f||(f=Fa(e)),r.queryIntersectsFeature(l,e,n,f,a.z,t.transform,s,t.pixelPosMatrix)}));}},b=0;b<h.length;b++)x(b);return g},Hl.prototype.loadMatchingFeature=function(t,e,r,n,i,a,o,s,u,l,p){var c=this.bucketLayerIDs[e];if(!a||function(t,e){for(var r=0;r<t.length;r++)if(e.indexOf(t[r])>=0)return !0;return !1}(a,c)){var h=this.sourceLayerCoder.decode(r),f=this.vtLayers[h].feature(n);if(i.filter(new ii(this.tileID.overscaledZ),f))for(var y=this.getId(f,h),d=0;d<c.length;d++){var m=c[d];if(!(a&&a.indexOf(m)<0)){var v=s[m];if(v){var g={};void 0!==y&&l&&(g=l.getState(v.sourceLayer||"_geojsonTileLayer",y));var x=u[m];x.paint=Yl(x.paint,v.paint,f,g,o),x.layout=Yl(x.layout,v.layout,f,g,o);var b=!p||p(f,v,g);if(b){var w=new Zl(f,this.z,this.x,this.y,y);w.layer=x;var _=t[m];void 0===_&&(_=t[m]=[]),_.push({featureIndex:n,feature:w,intersectionZ:b});}}}}}},Hl.prototype.lookupSymbolFeatures=function(t,e,r,n,i,a,o,s){var u={};this.loadVTLayers();for(var l=rn(i),p=0,c=t;p<c.length;p+=1)this.loadMatchingFeature(u,r,n,c[p],l,a,o,s,e);return u},Hl.prototype.hasLayer=function(t){for(var e=0,r=this.bucketLayerIDs;e<r.length;e+=1)for(var n=0,i=r[e];n<i.length;n+=1)if(t===i[n])return !0;return !1},Hl.prototype.getId=function(t,e){var r=t.id;return this.promoteId&&"boolean"==typeof(r=t.properties["string"==typeof this.promoteId?this.promoteId:this.promoteId[e]])&&(r=Number(r)),r},Fn("FeatureIndex",Hl,{omit:["rawTileData","sourceLayerCoder"]});var Ql=function(t,e){this.tileID=t,this.uid=h(),this.uses=0,this.tileSize=e,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.expiredRequestCount=0,this.state="loading";};Ql.prototype.registerFadeDuration=function(t){var e=t+this.timeAdded;e<D.now()||this.fadeEndTime&&e<this.fadeEndTime||(this.fadeEndTime=e);},Ql.prototype.wasRequested=function(){return "errored"===this.state||"loaded"===this.state||"reloading"===this.state},Ql.prototype.loadVectorData=function(t,e,r){if(this.hasData()&&this.unloadVectorData(),this.state="loaded",t){for(var n in t.featureIndex&&(this.latestFeatureIndex=t.featureIndex,t.rawTileData?(this.latestRawTileData=t.rawTileData,this.latestFeatureIndex.rawTileData=t.rawTileData):this.latestRawTileData&&(this.latestFeatureIndex.rawTileData=this.latestRawTileData)),this.collisionBoxArray=t.collisionBoxArray,this.buckets=function(t,e){var r={};if(!e)return r;for(var n=function(){var t=a[i],n=t.layerIds.map((function(t){return e.getLayer(t)})).filter(Boolean);if(0!==n.length){t.layers=n,t.stateDependentLayerIds&&(t.stateDependentLayers=t.stateDependentLayerIds.map((function(t){return n.filter((function(e){return e.id===t}))[0]})));for(var o=0,s=n;o<s.length;o+=1)r[s[o].id]=t;}},i=0,a=t;i<a.length;i+=1)n();return r}(t.buckets,e.style),this.hasSymbolBuckets=!1,this.buckets){var i=this.buckets[n];if(i instanceof cl){if(this.hasSymbolBuckets=!0,!r)break;i.justReloaded=!0;}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(var a in this.buckets){var o=this.buckets[a];if(o instanceof cl&&o.hasRTLText){this.hasRTLText=!0,ni.isLoading()||ni.isLoaded()||"deferred"!==ei()||ri();break}}for(var s in this.queryPadding=0,this.buckets){var u=this.buckets[s];this.queryPadding=Math.max(this.queryPadding,e.style.getLayer(s).queryRadius(u));}t.imageAtlas&&(this.imageAtlas=t.imageAtlas),t.glyphAtlasImage&&(this.glyphAtlasImage=t.glyphAtlasImage);}else this.collisionBoxArray=new Ji;},Ql.prototype.unloadVectorData=function(){for(var t in this.buckets)this.buckets[t].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";},Ql.prototype.getBucket=function(t){return this.buckets[t.id]},Ql.prototype.upload=function(t){for(var e in this.buckets){var r=this.buckets[e];r.uploadPending()&&r.upload(t);}var n=t.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new zl(t,this.imageAtlas.image,n.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new zl(t,this.glyphAtlasImage,n.ALPHA),this.glyphAtlasImage=null);},Ql.prototype.prepare=function(t){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(t,this.imageAtlasTexture);},Ql.prototype.queryRenderedFeatures=function(t,e,r,n,i,a,o,s,u,l){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:n,cameraQueryGeometry:i,scale:a,tileSize:this.tileSize,pixelPosMatrix:l,transform:s,params:o,queryPadding:this.queryPadding*u},t,e,r):{}},Ql.prototype.querySourceFeatures=function(t,e){var r=this.latestFeatureIndex;if(r&&r.rawTileData){var n=r.loadVTLayers(),i=e?e.sourceLayer:"",a=n._geojsonTileLayer||n[i];if(a)for(var o=rn(e&&e.filter),s=this.tileID.canonical,u=s.z,l=s.x,p=s.y,c={z:u,x:l,y:p},h=0;h<a.length;h++){var f=a.feature(h);if(o.filter(new ii(this.tileID.overscaledZ),f)){var y=r.getId(f,i),d=new Zl(f,u,l,p,y);d.tile=c,t.push(d);}}}},Ql.prototype.hasData=function(){return "loaded"===this.state||"reloading"===this.state||"expired"===this.state},Ql.prototype.patternsLoaded=function(){return this.imageAtlas&&!!Object.keys(this.imageAtlas.patternPositions).length},Ql.prototype.setExpiryData=function(t){var e=this.expirationTime;if(t.cacheControl){var r=k(t.cacheControl);r["max-age"]&&(this.expirationTime=Date.now()+1e3*r["max-age"]);}else t.expires&&(this.expirationTime=new Date(t.expires).getTime());if(this.expirationTime){var n=Date.now(),i=!1;if(this.expirationTime>n)i=!1;else if(e)if(this.expirationTime<e)i=!0;else {var a=this.expirationTime-e;a?this.expirationTime=n+Math.max(a,3e4):i=!0;}else i=!0;i?(this.expiredRequestCount++,this.state="expired"):this.expiredRequestCount=0;}},Ql.prototype.getExpiryTimeout=function(){if(this.expirationTime)return this.expiredRequestCount?1e3*(1<<Math.min(this.expiredRequestCount-1,31)):Math.min(this.expirationTime-(new Date).getTime(),Math.pow(2,31)-1)},Ql.prototype.setFeatureState=function(t,e){if(this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData&&0!==Object.keys(t).length){var r=this.latestFeatureIndex.loadVTLayers();for(var n in this.buckets)if(e.style.hasLayer(n)){var i=this.buckets[n],a=i.layers[0].sourceLayer||"_geojsonTileLayer",o=r[a],s=t[a];if(o&&s&&0!==Object.keys(s).length){i.update(s,o,this.imageAtlas&&this.imageAtlas.patternPositions||{});var u=e&&e.style&&e.style.getLayer(n);u&&(this.queryPadding=Math.max(this.queryPadding,u.queryRadius(i)));}}}},Ql.prototype.holdingForFade=function(){return void 0!==this.symbolFadeHoldUntil},Ql.prototype.symbolFadeFinished=function(){return !this.symbolFadeHoldUntil||this.symbolFadeHoldUntil<D.now()},Ql.prototype.clearFadeHold=function(){this.symbolFadeHoldUntil=void 0;},Ql.prototype.setHoldDuration=function(t){this.symbolFadeHoldUntil=D.now()+t;},Ql.prototype.setDependencies=function(t,e){for(var r={},n=0,i=e;n<i.length;n+=1)r[i[n]]=!0;this.dependencies[t]=r;},Ql.prototype.hasDependency=function(t,e){for(var r=0,n=t;r<n.length;r+=1){var i=this.dependencies[n[r]];if(i)for(var a=0,o=e;a<o.length;a+=1)if(i[o[a]])return !0}return !1};var tp=self.performance,ep=function(t){this._marks={start:[t.url,"start"].join("#"),end:[t.url,"end"].join("#"),measure:t.url.toString()},tp.mark(this._marks.start);};ep.prototype.finish=function(){tp.mark(this._marks.end);var t=tp.getEntriesByName(this._marks.measure);return 0===t.length&&(tp.measure(this._marks.measure,this._marks.start,this._marks.end),t=tp.getEntriesByName(this._marks.measure),tp.clearMarks(this._marks.start),tp.clearMarks(this._marks.end),tp.clearMeasures(this._marks.measure)),t},t.Actor=Ml,t.AlphaImage=ho,t.CanonicalTileID=Ul,t.CollisionBoxArray=Ji,t.Color=$t,t.DEMData=Kl,t.DataConstantProperty=fi,t.DictionaryCoder=Gl,t.EXTENT=8192,t.ErrorEvent=St,t.EvaluationParameters=ii,t.Event=At,t.Evented=kt,t.FeatureIndex=Hl,t.FillBucket=rs,t.FillExtrusionBucket=xs,t.ImageAtlas=yu,t.ImagePosition=hu,t.LineBucket=Ms,t.LngLat=Pl,t.LngLatBounds=Tl,t.MercatorCoordinate=Ol,t.ONE_EM=24,t.OverscaledTileID=ql,t.Point=i,t.Point$1=i,t.Properties=gi,t.Protobuf=Ks,t.RGBAImage=fo,t.RequestManager=N,t.RequestPerformance=ep,t.ResourceType=ht,t.SegmentVector=ia,t.SourceFeatureState=Jl,t.StructArrayLayout1ui2=Ki,t.StructArrayLayout2f1f2i16=Fi,t.StructArrayLayout2i4=ki,t.StructArrayLayout3ui6=Li,t.StructArrayLayout4i8=Ii,t.SymbolBucket=cl,t.Texture=zl,t.Tile=Ql,t.Transitionable=si,t.Uniform1f=va,t.Uniform1i=ma,t.Uniform2f=ga,t.Uniform3f=xa,t.Uniform4f=ba,t.UniformColor=wa,t.UniformMatrix4f=Aa,t.UnwrappedTileID=jl,t.ValidationError=zt,t.WritingMode=du,t.ZoomHistory=jn,t.add=function(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t},t.addDynamicAttributes=sl,t.asyncAll=function(t,e,r){if(!t.length)return r(null,[]);var n=t.length,i=new Array(t.length),a=null;t.forEach((function(t,o){e(t,(function(t,e){t&&(a=t),i[o]=e,0==--n&&r(a,i);}));}));},t.bezier=o,t.bindAll=d,t.browser=D,t.cacheEntryPossiblyAdded=function(t){++pt>ot&&(t.getActor().send("enforceCacheSizeLimit",at),pt=0);},t.clamp=u,t.clearTileCache=function(t){var e=self.caches.delete("mapbox-tiles");t&&e.catch(t).then((function(){return t()}));},t.clipLine=Uu,t.clone=function(t){var e=new to(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},t.clone$1=x,t.clone$2=function(t){var e=new to(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e},t.collisionCircleLayout=Os,t.config=L,t.create=function(){var t=new to(16);return to!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},t.create$1=function(){var t=new to(9);return to!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[5]=0,t[6]=0,t[7]=0),t[0]=1,t[4]=1,t[8]=1,t},t.create$2=function(){var t=new to(4);return to!=Float32Array&&(t[1]=0,t[2]=0),t[0]=1,t[3]=1,t},t.createCommonjsModule=e,t.createExpression=Nr,t.createLayout=Ai,t.createStyleLayer=function(t){return "custom"===t.type?new bl(t):new wl[t.type](t)},t.cross=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],u=r[2];return t[0]=i*u-a*s,t[1]=a*o-n*u,t[2]=n*s-i*o,t},t.deepEqual=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return !1;for(var n=0;n<e.length;n++)if(!t(e[n],r[n]))return !1;return !0}if("object"==typeof e&&null!==e&&null!==r){if("object"!=typeof r)return !1;if(Object.keys(e).length!==Object.keys(r).length)return !1;for(var i in e)if(!t(e[i],r[i]))return !1;return !0}return e===r},t.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]},t.dot$1=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]},t.ease=s,t.emitValidationErrors=Mn,t.endsWith=m,t.enforceCacheSizeLimit=function(t){st(),W&&W.then((function(e){e.keys().then((function(r){for(var n=0;n<r.length-t;n++)e.delete(r[n]);}));}));},t.evaluateSizeForFeature=Tu,t.evaluateSizeForZoom=Pu,t.evaluateVariableOffset=Qu,t.evented=ti,t.extend=p,t.featureFilter=rn,t.filterObject=g,t.fromRotation=function(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=r,t[2]=0,t[3]=-r,t[4]=n,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t},t.getAnchorAlignment=Iu,t.getAnchorJustification=tl,t.getArrayBuffer=gt,t.getImage=bt,t.getJSON=function(t,e){return vt(p(t,{type:"json"}),e)},t.getRTLTextPluginStatus=ei,t.getReferrer=yt,t.getVideo=function(t,e){var r,n,i=self.document.createElement("video");i.muted=!0,i.onloadstart=function(){e(null,i);};for(var a=0;a<t.length;a++){var o=self.document.createElement("source");r=t[a],n=void 0,(n=self.document.createElement("a")).href=r,(n.protocol!==self.document.location.protocol||n.host!==self.document.location.host)&&(i.crossOrigin="Anonymous"),o.src=t[a],i.appendChild(o);}return {cancel:function(){}}},t.identity=eo,t.invert=function(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],u=e[6],l=e[7],p=e[8],c=e[9],h=e[10],f=e[11],y=e[12],d=e[13],m=e[14],v=e[15],g=r*s-n*o,x=r*u-i*o,b=r*l-a*o,w=n*u-i*s,_=n*l-a*s,A=i*l-a*u,S=p*d-c*y,k=p*m-h*y,I=p*v-f*y,z=c*m-h*d,C=c*v-f*d,M=h*v-f*m,E=g*M-x*C+b*z+w*I-_*k+A*S;return E?(t[0]=(s*M-u*C+l*z)*(E=1/E),t[1]=(i*C-n*M-a*z)*E,t[2]=(d*A-m*_+v*w)*E,t[3]=(h*_-c*A-f*w)*E,t[4]=(u*I-o*M-l*k)*E,t[5]=(r*M-i*I+a*k)*E,t[6]=(m*b-y*A-v*x)*E,t[7]=(p*A-h*b+f*x)*E,t[8]=(o*C-s*I+l*S)*E,t[9]=(n*I-r*C-a*S)*E,t[10]=(y*_-d*b+v*g)*E,t[11]=(c*b-p*_-f*g)*E,t[12]=(s*k-o*z-u*S)*E,t[13]=(r*z-n*k+i*S)*E,t[14]=(d*x-y*w-m*g)*E,t[15]=(p*w-c*x+h*g)*E,t):null},t.isChar=qn,t.isMapboxURL=K,t.keysDifference=function(t,e){var r=[];for(var n in t)n in e||r.push(n);return r},t.makeRequest=vt,t.mapObject=v,t.mercatorXfromLng=Fl,t.mercatorYfromLat=Dl,t.mercatorZfromAltitude=Ll,t.mul=io,t.multiply=ro,t.mvt=ds,t.normalize=function(t,e){var r=e[0],n=e[1],i=e[2],a=r*r+n*n+i*i;return a>0&&(a=1/Math.sqrt(a)),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a,t},t.number=je,t.offscreenCanvasSupported=ct,t.ortho=function(t,e,r,n,i,a,o){var s=1/(e-r),u=1/(n-i),l=1/(a-o);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*u,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*l,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*u,t[14]=(o+a)*l,t[15]=1,t},t.parseGlyphPBF=function(t){return new Ks(t).readFields(uu,[])},t.pbf=Ks,t.performSymbolLayout=function(t,e,r,n,i,a,o){t.createArrays(),t.tilePixelRatio=8192/(512*t.overscaling),t.compareText={},t.iconsNeedLinear=!1;var s=t.layers[0].layout,u=t.layers[0]._unevaluatedLayout._values,l={};if("composite"===t.textSizeData.kind){var p=t.textSizeData,c=p.maxZoom;l.compositeTextSizes=[u["text-size"].possiblyEvaluate(new ii(p.minZoom),o),u["text-size"].possiblyEvaluate(new ii(c),o)];}if("composite"===t.iconSizeData.kind){var h=t.iconSizeData,f=h.maxZoom;l.compositeIconSizes=[u["icon-size"].possiblyEvaluate(new ii(h.minZoom),o),u["icon-size"].possiblyEvaluate(new ii(f),o)];}l.layoutTextSize=u["text-size"].possiblyEvaluate(new ii(t.zoom+1),o),l.layoutIconSize=u["icon-size"].possiblyEvaluate(new ii(t.zoom+1),o),l.textMaxSize=u["text-size"].possiblyEvaluate(new ii(18));for(var y=24*s.get("text-line-height"),d="map"===s.get("text-rotation-alignment")&&"point"!==s.get("symbol-placement"),m=s.get("text-keep-upright"),v=s.get("text-size"),g=function(){var a=b[x],u=s.get("text-font").evaluate(a,{},o).join(","),p=v.evaluate(a,{},o),c=l.layoutTextSize.evaluate(a,{},o),h=l.layoutIconSize.evaluate(a,{},o),f={horizontal:{},vertical:void 0},g=a.text,_=[0,0];if(g){var A=g.toString(),S=24*s.get("text-letter-spacing").evaluate(a,{},o),k=function(t){for(var e=0,r=t;e<r.length;e+=1)if(n=r[e].charCodeAt(0),qn.Arabic(n)||qn["Arabic Supplement"](n)||qn["Arabic Extended-A"](n)||qn["Arabic Presentation Forms-A"](n)||qn["Arabic Presentation Forms-B"](n))return !1;var n;return !0}(A)?S:0,I=s.get("text-anchor").evaluate(a,{},o),z=s.get("text-variable-anchor");if(!z){var C=s.get("text-radial-offset").evaluate(a,{},o);_=C?Qu(I,[24*C,Wu]):s.get("text-offset").evaluate(a,{},o).map((function(t){return 24*t}));}var M=d?"center":s.get("text-justify").evaluate(a,{},o),E=s.get("symbol-placement"),T="point"===E?24*s.get("text-max-width").evaluate(a,{},o):0,P=function(){t.allowVerticalPlacement&&Nn(A)&&(f.vertical=gu(g,e,r,i,u,T,y,I,"left",k,_,du.vertical,!0,E,c,p));};if(!d&&z){for(var B="auto"===M?z.map((function(t){return tl(t)})):[M],V=!1,F=0;F<B.length;F++){var D=B[F];if(!f.horizontal[D])if(V)f.horizontal[D]=f.horizontal[0];else {var L=gu(g,e,r,i,u,T,y,"center",D,k,_,du.horizontal,!1,E,c,p);L&&(f.horizontal[D]=L,V=1===L.positionedLines.length);}}P();}else {"auto"===M&&(M=tl(I));var R=gu(g,e,r,i,u,T,y,I,M,k,_,du.horizontal,!1,E,c,p);R&&(f.horizontal[M]=R),P(),Nn(A)&&d&&m&&(f.vertical=gu(g,e,r,i,u,T,y,I,M,k,_,du.vertical,!1,E,c,p));}}var O=void 0,U=!1;if(a.icon&&a.icon.name){var j=n[a.icon.name];j&&(O=function(t,e,r){var n=Iu(r),i=e[0]-t.displaySize[0]*n.horizontalAlign,a=e[1]-t.displaySize[1]*n.verticalAlign;return {image:t,top:a,bottom:a+t.displaySize[1],left:i,right:i+t.displaySize[0]}}(i[a.icon.name],s.get("icon-offset").evaluate(a,{},o),s.get("icon-anchor").evaluate(a,{},o)),U=j.sdf,void 0===t.sdfIcons?t.sdfIcons=j.sdf:t.sdfIcons!==j.sdf&&w("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(j.pixelRatio!==t.pixelRatio||0!==s.get("icon-rotate").constantOr(1))&&(t.iconsNeedLinear=!0));}var q=rl(f.horizontal)||f.vertical;t.iconsInText=!!q&&q.iconsInText,(q||O)&&function(t,e,r,n,i,a,o,s,u,l,p){var c=a.textMaxSize.evaluate(e,{});void 0===c&&(c=o);var h,f=t.layers[0].layout,y=f.get("icon-offset").evaluate(e,{},p),d=rl(r.horizontal),m=o/24,v=t.tilePixelRatio*m,g=t.tilePixelRatio*c/24,x=t.tilePixelRatio*s,b=t.tilePixelRatio*f.get("symbol-spacing"),_=f.get("text-padding")*t.tilePixelRatio,A=f.get("icon-padding")*t.tilePixelRatio,S=f.get("text-max-angle")/180*Math.PI,k="map"===f.get("text-rotation-alignment")&&"point"!==f.get("symbol-placement"),I="map"===f.get("icon-rotation-alignment")&&"point"!==f.get("symbol-placement"),z=f.get("symbol-placement"),C=b/2,M=f.get("icon-text-fit");n&&"none"!==M&&(t.allowVerticalPlacement&&r.vertical&&(h=Cu(n,r.vertical,M,f.get("icon-text-fit-padding"),y,m)),d&&(n=Cu(n,d,M,f.get("icon-text-fit-padding"),y,m)));var E=function(s,c){c.x<0||c.x>=8192||c.y<0||c.y>=8192||function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,_,A,S,k){var I,z,C,M,E,T=t.addToLineVertexArray(e,r),P=0,B=0,V=0,F=0,D=-1,L=-1,R={},O=la(""),U=0,j=0;if(void 0===s._unevaluatedLayout.getValue("text-radial-offset")?(U=(I=s.layout.get("text-offset").evaluate(b,{},S).map((function(t){return 24*t})))[0],j=I[1]):(U=24*s.layout.get("text-radial-offset").evaluate(b,{},S),j=Wu),t.allowVerticalPlacement&&n.vertical){var q=s.layout.get("text-rotate").evaluate(b,{},S)+90;M=new Zu(u,e,l,p,c,n.vertical,h,f,y,q),o&&(E=new Zu(u,e,l,p,c,o,m,v,y,q));}if(i){var N=s.layout.get("icon-rotate").evaluate(b,{}),K="none"!==s.layout.get("icon-text-fit"),G=ju(i,N,A,K),Z=o?ju(o,N,A,K):void 0;C=new Zu(u,e,l,p,c,i,m,v,!1,N),P=4*G.length;var X=t.iconSizeData,J=null;"source"===X.kind?(J=[128*s.layout.get("icon-size").evaluate(b,{})])[0]>32640&&w(t.layerIds[0]+': Value for "icon-size" is >= 255. Reduce your "icon-size".'):"composite"===X.kind&&((J=[128*_.compositeIconSizes[0].evaluate(b,{},S),128*_.compositeIconSizes[1].evaluate(b,{},S)])[0]>32640||J[1]>32640)&&w(t.layerIds[0]+': Value for "icon-size" is >= 255. Reduce your "icon-size".'),t.addSymbols(t.icon,G,J,x,g,b,!1,e,T.lineStartIndex,T.lineLength,-1,S),D=t.icon.placedSymbolArray.length-1,Z&&(B=4*Z.length,t.addSymbols(t.icon,Z,J,x,g,b,du.vertical,e,T.lineStartIndex,T.lineLength,-1,S),L=t.icon.placedSymbolArray.length-1);}for(var H in n.horizontal){var Y=n.horizontal[H];if(!z){O=la(Y.text);var $=s.layout.get("text-rotate").evaluate(b,{},S);z=new Zu(u,e,l,p,c,Y,h,f,y,$);}var W=1===Y.positionedLines.length;if(V+=el(t,e,Y,a,s,y,b,d,T,n.vertical?du.horizontal:du.horizontalOnly,W?Object.keys(n.horizontal):[H],R,D,_,S),W)break}n.vertical&&(F+=el(t,e,n.vertical,a,s,y,b,d,T,du.vertical,["vertical"],R,L,_,S));var Q=z?z.boxStartIndex:t.collisionBoxArray.length,tt=z?z.boxEndIndex:t.collisionBoxArray.length,et=M?M.boxStartIndex:t.collisionBoxArray.length,rt=M?M.boxEndIndex:t.collisionBoxArray.length,nt=C?C.boxStartIndex:t.collisionBoxArray.length,it=C?C.boxEndIndex:t.collisionBoxArray.length,at=E?E.boxStartIndex:t.collisionBoxArray.length,ot=E?E.boxEndIndex:t.collisionBoxArray.length,st=-1,ut=function(t,e){return t&&t.circleDiameter?Math.max(t.circleDiameter,e):e};st=ut(z,st),st=ut(M,st),st=ut(C,st);var lt=(st=ut(E,st))>-1?1:0;lt&&(st*=k/24),t.glyphOffsetArray.length>=cl.MAX_GLYPHS&&w("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),void 0!==b.sortKey&&t.addToSortKeyRanges(t.symbolInstances.length,b.sortKey),t.symbolInstances.emplaceBack(e.x,e.y,R.right>=0?R.right:-1,R.center>=0?R.center:-1,R.left>=0?R.left:-1,R.vertical||-1,D,L,O,Q,tt,et,rt,nt,it,at,ot,l,V,F,P,B,lt,0,h,U,j,st);}(t,c,s,r,n,i,h,t.layers[0],t.collisionBoxArray,e.index,e.sourceLayerIndex,t.index,v,_,k,u,x,A,I,y,e,a,l,p,o);};if("line"===z)for(var T=0,P=Uu(e.geometry,0,0,8192,8192);T<P.length;T+=1)for(var B=P[T],V=0,F=Ou(B,b,S,r.vertical||d,n,24,g,t.overscaling,8192);V<F.length;V+=1){var D=F[V];d&&nl(t,d.text,C,D)||E(B,D);}else if("line-center"===z)for(var L=0,R=e.geometry;L<R.length;L+=1){var O=R[L];if(O.length>1){var U=Ru(O,S,r.vertical||d,n,24,g);U&&E(O,U);}}else if("Polygon"===e.type)for(var j=0,q=Wo(e.geometry,0);j<q.length;j+=1){var N=q[j],K=Hu(N,16);E(N[0],new Mu(K.x,K.y,0));}else if("LineString"===e.type)for(var G=0,Z=e.geometry;G<Z.length;G+=1){var X=Z[G];E(X,new Mu(X[0].x,X[0].y,0));}else if("Point"===e.type)for(var J=0,H=e.geometry;J<H.length;J+=1)for(var Y=0,$=H[J];Y<$.length;Y+=1){var W=$[Y];E([W],new Mu(W.x,W.y,0));}}(t,a,f,O,n,l,c,h,_,U,o);},x=0,b=t.features;x<b.length;x+=1)g();a&&t.generateCollisionDebugBuffers();},t.perspective=function(t,e,r,n,i){var a,o=1/Math.tan(e/2);return t[0]=o/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=i&&i!==1/0?(t[10]=(i+n)*(a=1/(n-i)),t[14]=2*i*n*a):(t[10]=-1,t[14]=-2*n),t},t.pick=function(t,e){for(var r={},n=0;n<e.length;n++){var i=e[n];i in t&&(r[i]=t[i]);}return r},t.plugin=ni,t.polygonIntersectsPolygon=Ra,t.postMapLoadEvent=it,t.postTurnstileEvent=rt,t.potpack=cu,t.refProperties=["type","source","source-layer","minzoom","maxzoom","filter","layout"],t.register=Fn,t.registerForPluginStateChange=function(t){return t({pluginStatus:Yn,pluginURL:$n}),ti.on("pluginStateChange",t),t},t.rotate=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=Math.sin(r),u=Math.cos(r);return t[0]=n*u+a*s,t[1]=i*u+o*s,t[2]=n*-s+a*u,t[3]=i*-s+o*u,t},t.rotateX=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[4],o=e[5],s=e[6],u=e[7],l=e[8],p=e[9],c=e[10],h=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=a*i+l*n,t[5]=o*i+p*n,t[6]=s*i+c*n,t[7]=u*i+h*n,t[8]=l*i-a*n,t[9]=p*i-o*n,t[10]=c*i-s*n,t[11]=h*i-u*n,t},t.rotateZ=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],u=e[3],l=e[4],p=e[5],c=e[6],h=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i+l*n,t[1]=o*i+p*n,t[2]=s*i+c*n,t[3]=u*i+h*n,t[4]=l*i-a*n,t[5]=p*i-o*n,t[6]=c*i-s*n,t[7]=h*i-u*n,t},t.scale=function(t,e,r){var n=r[0],i=r[1],a=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*a,t[9]=e[9]*a,t[10]=e[10]*a,t[11]=e[11]*a,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.scale$1=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t[3]=e[3]*r,t},t.scale$2=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t},t.setCacheLimits=function(t,e){at=t,ot=e;},t.setRTLTextPlugin=function(t,e,r){if(void 0===r&&(r=!1),"deferred"===Yn||"loading"===Yn||"loaded"===Yn)throw new Error("setRTLTextPlugin cannot be called multiple times.");$n=D.resolveURL(t),Yn="deferred",Hn=e,Qn(),r||ri();},t.sphericalToCartesian=function(t){var e=t[0],r=t[1],n=t[2];return r+=90,r*=Math.PI/180,n*=Math.PI/180,{x:e*Math.cos(r)*Math.sin(n),y:e*Math.sin(r)*Math.sin(n),z:e*Math.cos(n)}},t.sqrLen=function(t){var e=t[0],r=t[1];return e*e+r*r},t.styleSpec=It,t.sub=function(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t},t.symbolSize=Bu,t.transformMat3=function(t,e,r){var n=e[0],i=e[1],a=e[2];return t[0]=n*r[0]+i*r[3]+a*r[6],t[1]=n*r[1]+i*r[4]+a*r[7],t[2]=n*r[2]+i*r[5]+a*r[8],t},t.transformMat4=ao,t.translate=function(t,e,r){var n,i,a,o,s,u,l,p,c,h,f,y,d=r[0],m=r[1],v=r[2];return e===t?(t[12]=e[0]*d+e[4]*m+e[8]*v+e[12],t[13]=e[1]*d+e[5]*m+e[9]*v+e[13],t[14]=e[2]*d+e[6]*m+e[10]*v+e[14],t[15]=e[3]*d+e[7]*m+e[11]*v+e[15]):(i=e[1],a=e[2],o=e[3],s=e[4],u=e[5],l=e[6],p=e[7],c=e[8],h=e[9],f=e[10],y=e[11],t[0]=n=e[0],t[1]=i,t[2]=a,t[3]=o,t[4]=s,t[5]=u,t[6]=l,t[7]=p,t[8]=c,t[9]=h,t[10]=f,t[11]=y,t[12]=n*d+s*m+c*v+e[12],t[13]=i*d+u*m+h*v+e[13],t[14]=a*d+l*m+f*v+e[14],t[15]=o*d+p*m+y*v+e[15]),t},t.triggerPluginCompletionEvent=Wn,t.uniqueId=h,t.validateCustomStyleLayer=function(t){var e=[],r=t.id;return void 0===r&&e.push({message:"layers."+r+': missing required property "id"'}),void 0===t.render&&e.push({message:"layers."+r+': missing required method "render"'}),t.renderingMode&&"2d"!==t.renderingMode&&"3d"!==t.renderingMode&&e.push({message:"layers."+r+': property "renderingMode" must be either "2d" or "3d"'}),e},t.validateLight=In,t.validateStyle=kn,t.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},t.vectorTile=ds,t.version="1.10.1",t.warnOnce=w,t.webpSupported=R,t.window=self,t.wrap=l;}));

define(["./shared"],(function(e){"use strict";function t(e){var r=typeof e;if("number"===r||"boolean"===r||"string"===r||null==e)return JSON.stringify(e);if(Array.isArray(e)){for(var i="[",o=0,n=e;o<n.length;o+=1)i+=t(n[o])+",";return i+"]"}for(var s=Object.keys(e).sort(),a="{",l=0;l<s.length;l++)a+=JSON.stringify(s[l])+":"+t(e[s[l]])+",";return a+"}"}function r(r){for(var i="",o=0,n=e.refProperties;o<n.length;o+=1)i+="/"+t(r[n[o]]);return i}var i=function(e){this.keyCache={},e&&this.replace(e);};i.prototype.replace=function(e){this._layerConfigs={},this._layers={},this.update(e,[]);},i.prototype.update=function(t,i){for(var o=this,n=0,s=t;n<s.length;n+=1){var a=s[n];this._layerConfigs[a.id]=a;var l=this._layers[a.id]=e.createStyleLayer(a);l._featureFilter=e.featureFilter(l.filter),this.keyCache[a.id]&&delete this.keyCache[a.id];}for(var u=0,h=i;u<h.length;u+=1){var c=h[u];delete this.keyCache[c],delete this._layerConfigs[c],delete this._layers[c];}this.familiesBySource={};for(var p=0,f=function(e,t){for(var i={},o=0;o<e.length;o++){var n=t&&t[e[o].id]||r(e[o]);t&&(t[e[o].id]=n);var s=i[n];s||(s=i[n]=[]),s.push(e[o]);}var a=[];for(var l in i)a.push(i[l]);return a}(e.values(this._layerConfigs),this.keyCache);p<f.length;p+=1){var d=f[p].map((function(e){return o._layers[e.id]})),g=d[0];if("none"!==g.visibility){var v=g.source||"",m=this.familiesBySource[v];m||(m=this.familiesBySource[v]={});var y=g.sourceLayer||"_geojsonTileLayer",x=m[y];x||(x=m[y]=[]),x.push(d);}}};var o=function(t){var r={},i=[];for(var o in t){var n=t[o],s=r[o]={};for(var a in n){var l=n[+a];if(l&&0!==l.bitmap.width&&0!==l.bitmap.height){var u={x:0,y:0,w:l.bitmap.width+2,h:l.bitmap.height+2};i.push(u),s[a]={rect:u,metrics:l.metrics};}}}var h=e.potpack(i),c=new e.AlphaImage({width:h.w||1,height:h.h||1});for(var p in t){var f=t[p];for(var d in f){var g=f[+d];if(g&&0!==g.bitmap.width&&0!==g.bitmap.height){var v=r[p][d].rect;e.AlphaImage.copy(g.bitmap,c,{x:0,y:0},{x:v.x+1,y:v.y+1},g.bitmap);}}}this.image=c,this.positions=r;};e.register("GlyphAtlas",o);var n=function(t){this.tileID=new e.OverscaledTileID(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming,this.returnDependencies=!!t.returnDependencies,this.promoteId=t.promoteId;};function s(t,r,i){for(var o=new e.EvaluationParameters(r),n=0,s=t;n<s.length;n+=1)s[n].recalculate(o,i);}function a(t,r){var i=e.getArrayBuffer(t.request,(function(t,i,o,n){t?r(t):i&&r(null,{vectorTile:new e.vectorTile.VectorTile(new e.pbf(i)),rawData:i,cacheControl:o,expires:n});}));return function(){i.cancel(),r();}}n.prototype.parse=function(t,r,i,n,a){var l=this;this.status="parsing",this.data=t,this.collisionBoxArray=new e.CollisionBoxArray;var u=new e.DictionaryCoder(Object.keys(t.layers).sort()),h=new e.FeatureIndex(this.tileID,this.promoteId);h.bucketLayerIDs=[];var c,p,f,d,g={},v={featureIndex:h,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:i},m=r.familiesBySource[this.source];for(var y in m){var x=t.layers[y];if(x){1===x.version&&e.warnOnce('Vector tile source "'+this.source+'" layer "'+y+'" does not use vector tile spec v2 and therefore may have some rendering errors.');for(var w=u.encode(y),S=[],I=0;I<x.length;I++){var M=x.feature(I),b=h.getId(M,y);S.push({feature:M,id:b,index:I,sourceLayerIndex:w});}for(var _=0,k=m[y];_<k.length;_+=1){var P=k[_],T=P[0];T.minzoom&&this.zoom<Math.floor(T.minzoom)||T.maxzoom&&this.zoom>=T.maxzoom||"none"!==T.visibility&&(s(P,this.zoom,i),(g[T.id]=T.createBucket({index:h.bucketLayerIDs.length,layers:P,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:w,sourceID:this.source})).populate(S,v,this.tileID.canonical),h.bucketLayerIDs.push(P.map((function(e){return e.id}))));}}}var C=e.mapObject(v.glyphDependencies,(function(e){return Object.keys(e).map(Number)}));Object.keys(C).length?n.send("getGlyphs",{uid:this.uid,stacks:C},(function(e,t){c||(c=e,p=t,O.call(l));})):p={};var D=Object.keys(v.iconDependencies);D.length?n.send("getImages",{icons:D,source:this.source,tileID:this.tileID,type:"icons"},(function(e,t){c||(c=e,f=t,O.call(l));})):f={};var L=Object.keys(v.patternDependencies);function O(){if(c)return a(c);if(p&&f&&d){var t=new o(p),r=new e.ImageAtlas(f,d);for(var n in g){var l=g[n];l instanceof e.SymbolBucket?(s(l.layers,this.zoom,i),e.performSymbolLayout(l,p,t.positions,f,r.iconPositions,this.showCollisionBoxes,this.tileID.canonical)):l.hasPattern&&(l instanceof e.LineBucket||l instanceof e.FillBucket||l instanceof e.FillExtrusionBucket)&&(s(l.layers,this.zoom,i),l.addFeatures(v,this.tileID.canonical,r.patternPositions));}this.status="done",a(null,{buckets:e.values(g).filter((function(e){return !e.isEmpty()})),featureIndex:h,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:t.image,imageAtlas:r,glyphMap:this.returnDependencies?p:null,iconMap:this.returnDependencies?f:null,glyphPositions:this.returnDependencies?t.positions:null});}}L.length?n.send("getImages",{icons:L,source:this.source,tileID:this.tileID,type:"patterns"},(function(e,t){c||(c=e,d=t,O.call(l));})):d={},O.call(this);};var l=function(e,t,r,i){this.actor=e,this.layerIndex=t,this.availableImages=r,this.loadVectorData=i||a,this.loading={},this.loaded={};};l.prototype.loadTile=function(t,r){var i=this,o=t.uid;this.loading||(this.loading={});var s=!!(t&&t.request&&t.request.collectResourceTiming)&&new e.RequestPerformance(t.request),a=this.loading[o]=new n(t);a.abort=this.loadVectorData(t,(function(t,n){if(delete i.loading[o],t||!n)return a.status="done",i.loaded[o]=a,r(t);var l=n.rawData,u={};n.expires&&(u.expires=n.expires),n.cacheControl&&(u.cacheControl=n.cacheControl);var h={};if(s){var c=s.finish();c&&(h.resourceTiming=JSON.parse(JSON.stringify(c)));}a.vectorTile=n.vectorTile,a.parse(n.vectorTile,i.layerIndex,i.availableImages,i.actor,(function(t,i){if(t||!i)return r(t);r(null,e.extend({rawTileData:l.slice(0)},i,u,h));})),i.loaded=i.loaded||{},i.loaded[o]=a;}));},l.prototype.reloadTile=function(e,t){var r=this,i=this.loaded,o=e.uid,n=this;if(i&&i[o]){var s=i[o];s.showCollisionBoxes=e.showCollisionBoxes;var a=function(e,i){var o=s.reloadCallback;o&&(delete s.reloadCallback,s.parse(s.vectorTile,n.layerIndex,r.availableImages,n.actor,o)),t(e,i);};"parsing"===s.status?s.reloadCallback=a:"done"===s.status&&(s.vectorTile?s.parse(s.vectorTile,this.layerIndex,this.availableImages,this.actor,a):a());}},l.prototype.abortTile=function(e,t){var r=this.loading,i=e.uid;r&&r[i]&&r[i].abort&&(r[i].abort(),delete r[i]),t();},l.prototype.removeTile=function(e,t){var r=this.loaded,i=e.uid;r&&r[i]&&delete r[i],t();};var u=e.window.ImageBitmap,h=function(){this.loaded={};};function c(e,t){if(0!==e.length){p(e[0],t);for(var r=1;r<e.length;r++)p(e[r],!t);}}function p(e,t){for(var r=0,i=0,o=e.length,n=o-1;i<o;n=i++)r+=(e[i][0]-e[n][0])*(e[n][1]+e[i][1]);r>=0!=!!t&&e.reverse();}h.prototype.loadTile=function(t,r){var i=t.uid,o=t.encoding,n=t.rawImageData,s=u&&n instanceof u?this.getImageData(n):n,a=new e.DEMData(i,s,o);this.loaded=this.loaded||{},this.loaded[i]=a,r(null,a);},h.prototype.getImageData=function(t){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(t.width,t.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d")),this.offscreenCanvas.width=t.width,this.offscreenCanvas.height=t.height,this.offscreenCanvasContext.drawImage(t,0,0,t.width,t.height);var r=this.offscreenCanvasContext.getImageData(-1,-1,t.width+2,t.height+2);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),new e.RGBAImage({width:r.width,height:r.height},r.data)},h.prototype.removeTile=function(e){var t=this.loaded,r=e.uid;t&&t[r]&&delete t[r];};var f=e.vectorTile.VectorTileFeature.prototype.toGeoJSON,d=function(t){this._feature=t,this.extent=e.EXTENT,this.type=t.type,this.properties=t.tags,"id"in t&&!isNaN(t.id)&&(this.id=parseInt(t.id,10));};d.prototype.loadGeometry=function(){if(1===this._feature.type){for(var t=[],r=0,i=this._feature.geometry;r<i.length;r+=1){var o=i[r];t.push([new e.Point$1(o[0],o[1])]);}return t}for(var n=[],s=0,a=this._feature.geometry;s<a.length;s+=1){for(var l=[],u=0,h=a[s];u<h.length;u+=1){var c=h[u];l.push(new e.Point$1(c[0],c[1]));}n.push(l);}return n},d.prototype.toGeoJSON=function(e,t,r){return f.call(this,e,t,r)};var g=function(t){this.layers={_geojsonTileLayer:this},this.name="_geojsonTileLayer",this.extent=e.EXTENT,this.length=t.length,this._features=t;};g.prototype.feature=function(e){return new d(this._features[e])};var v=e.vectorTile.VectorTileFeature,m=y;function y(e,t){this.options=t||{},this.features=e,this.length=e.length;}function x(e,t){this.id="number"==typeof e.id?e.id:void 0,this.type=e.type,this.rawGeometry=1===e.type?[e.geometry]:e.geometry,this.properties=e.tags,this.extent=t||4096;}y.prototype.feature=function(e){return new x(this.features[e],this.options.extent)},x.prototype.loadGeometry=function(){var t=this.rawGeometry;this.geometry=[];for(var r=0;r<t.length;r++){for(var i=t[r],o=[],n=0;n<i.length;n++)o.push(new e.Point$1(i[n][0],i[n][1]));this.geometry.push(o);}return this.geometry},x.prototype.bbox=function(){this.geometry||this.loadGeometry();for(var e=this.geometry,t=1/0,r=-1/0,i=1/0,o=-1/0,n=0;n<e.length;n++)for(var s=e[n],a=0;a<s.length;a++){var l=s[a];t=Math.min(t,l.x),r=Math.max(r,l.x),i=Math.min(i,l.y),o=Math.max(o,l.y);}return [t,i,r,o]},x.prototype.toGeoJSON=v.prototype.toGeoJSON;var w=I,S=m;function I(t){var r=new e.pbf;return function(e,t){for(var r in e.layers)t.writeMessage(3,M,e.layers[r]);}(t,r),r.finish()}function M(e,t){var r;t.writeVarintField(15,e.version||1),t.writeStringField(1,e.name||""),t.writeVarintField(5,e.extent||4096);var i={keys:[],values:[],keycache:{},valuecache:{}};for(r=0;r<e.length;r++)i.feature=e.feature(r),t.writeMessage(2,b,i);var o=i.keys;for(r=0;r<o.length;r++)t.writeStringField(3,o[r]);var n=i.values;for(r=0;r<n.length;r++)t.writeMessage(4,C,n[r]);}function b(e,t){var r=e.feature;void 0!==r.id&&t.writeVarintField(1,r.id),t.writeMessage(2,_,e),t.writeVarintField(3,r.type),t.writeMessage(4,T,r);}function _(e,t){var r=e.feature,i=e.keys,o=e.values,n=e.keycache,s=e.valuecache;for(var a in r.properties){var l=n[a];void 0===l&&(i.push(a),n[a]=l=i.length-1),t.writeVarint(l);var u=r.properties[a],h=typeof u;"string"!==h&&"boolean"!==h&&"number"!==h&&(u=JSON.stringify(u));var c=h+":"+u,p=s[c];void 0===p&&(o.push(u),s[c]=p=o.length-1),t.writeVarint(p);}}function k(e,t){return (t<<3)+(7&e)}function P(e){return e<<1^e>>31}function T(e,t){for(var r=e.loadGeometry(),i=e.type,o=0,n=0,s=r.length,a=0;a<s;a++){var l=r[a],u=1;1===i&&(u=l.length),t.writeVarint(k(1,u));for(var h=3===i?l.length-1:l.length,c=0;c<h;c++){1===c&&1!==i&&t.writeVarint(k(2,h-1));var p=l[c].x-o,f=l[c].y-n;t.writeVarint(P(p)),t.writeVarint(P(f)),o+=p,n+=f;}3===i&&t.writeVarint(k(7,1));}}function C(e,t){var r=typeof e;"string"===r?t.writeStringField(1,e):"boolean"===r?t.writeBooleanField(7,e):"number"===r&&(e%1!=0?t.writeDoubleField(3,e):e<0?t.writeSVarintField(6,e):t.writeVarintField(5,e));}function D(e,t,r,i){L(e,r,i),L(t,2*r,2*i),L(t,2*r+1,2*i+1);}function L(e,t,r){var i=e[t];e[t]=e[r],e[r]=i;}function O(e,t,r,i){var o=e-r,n=t-i;return o*o+n*n}w.fromVectorTileJs=I,w.fromGeojsonVt=function(e,t){t=t||{};var r={};for(var i in e)r[i]=new m(e[i].features,t),r[i].name=i,r[i].version=t.version,r[i].extent=t.extent;return I({layers:r})},w.GeoJSONWrapper=S;var z=function(e){return e[0]},E=function(e){return e[1]},F=function(e,t,r,i,o){void 0===t&&(t=z),void 0===r&&(r=E),void 0===i&&(i=64),void 0===o&&(o=Float64Array),this.nodeSize=i,this.points=e;for(var n=e.length<65536?Uint16Array:Uint32Array,s=this.ids=new n(e.length),a=this.coords=new o(2*e.length),l=0;l<e.length;l++)s[l]=l,a[2*l]=t(e[l]),a[2*l+1]=r(e[l]);!function e(t,r,i,o,n,s){if(!(n-o<=i)){var a=o+n>>1;!function e(t,r,i,o,n,s){for(;n>o;){if(n-o>600){var a=n-o+1,l=i-o+1,u=Math.log(a),h=.5*Math.exp(2*u/3),c=.5*Math.sqrt(u*h*(a-h)/a)*(l-a/2<0?-1:1);e(t,r,i,Math.max(o,Math.floor(i-l*h/a+c)),Math.min(n,Math.floor(i+(a-l)*h/a+c)),s);}var p=r[2*i+s],f=o,d=n;for(D(t,r,o,i),r[2*n+s]>p&&D(t,r,o,n);f<d;){for(D(t,r,f,d),f++,d--;r[2*f+s]<p;)f++;for(;r[2*d+s]>p;)d--;}r[2*o+s]===p?D(t,r,o,d):D(t,r,++d,n),d<=i&&(o=d+1),i<=d&&(n=d-1);}}(t,r,a,o,n,s%2),e(t,r,i,o,a-1,s+1),e(t,r,i,a+1,n,s+1);}}(s,a,i,0,s.length-1,0);};F.prototype.range=function(e,t,r,i){return function(e,t,r,i,o,n,s){for(var a,l,u=[0,e.length-1,0],h=[];u.length;){var c=u.pop(),p=u.pop(),f=u.pop();if(p-f<=s)for(var d=f;d<=p;d++)l=t[2*d+1],(a=t[2*d])>=r&&a<=o&&l>=i&&l<=n&&h.push(e[d]);else {var g=Math.floor((f+p)/2);l=t[2*g+1],(a=t[2*g])>=r&&a<=o&&l>=i&&l<=n&&h.push(e[g]);var v=(c+1)%2;(0===c?r<=a:i<=l)&&(u.push(f),u.push(g-1),u.push(v)),(0===c?o>=a:n>=l)&&(u.push(g+1),u.push(p),u.push(v));}}return h}(this.ids,this.coords,e,t,r,i,this.nodeSize)},F.prototype.within=function(e,t,r){return function(e,t,r,i,o,n){for(var s=[0,e.length-1,0],a=[],l=o*o;s.length;){var u=s.pop(),h=s.pop(),c=s.pop();if(h-c<=n)for(var p=c;p<=h;p++)O(t[2*p],t[2*p+1],r,i)<=l&&a.push(e[p]);else {var f=Math.floor((c+h)/2),d=t[2*f],g=t[2*f+1];O(d,g,r,i)<=l&&a.push(e[f]);var v=(u+1)%2;(0===u?r-o<=d:i-o<=g)&&(s.push(c),s.push(f-1),s.push(v)),(0===u?r+o>=d:i+o>=g)&&(s.push(f+1),s.push(h),s.push(v));}}return a}(this.ids,this.coords,e,t,r,this.nodeSize)};var N={minZoom:0,maxZoom:16,radius:40,extent:512,nodeSize:64,log:!1,generateId:!1,reduce:null,map:function(e){return e}},J=function(e){this.options=V(Object.create(N),e),this.trees=new Array(this.options.maxZoom+1);};function Z(e,t,r,i,o){return {x:e,y:t,zoom:1/0,id:r,parentId:-1,numPoints:i,properties:o}}function A(e,t){var r=e.geometry.coordinates,i=r[1];return {x:Y(r[0]),y:j(i),zoom:1/0,index:t,parentId:-1}}function B(e){return {type:"Feature",id:e.id,properties:G(e),geometry:{type:"Point",coordinates:[(i=e.x,360*(i-.5)),(t=e.y,r=(180-360*t)*Math.PI/180,360*Math.atan(Math.exp(r))/Math.PI-90)]}};var t,r,i;}function G(e){var t=e.numPoints,r=t>=1e4?Math.round(t/1e3)+"k":t>=1e3?Math.round(t/100)/10+"k":t;return V(V({},e.properties),{cluster:!0,cluster_id:e.id,point_count:t,point_count_abbreviated:r})}function Y(e){return e/360+.5}function j(e){var t=Math.sin(e*Math.PI/180),r=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return r<0?0:r>1?1:r}function V(e,t){for(var r in t)e[r]=t[r];return e}function X(e){return e.x}function W(e){return e.y}function R(e,t,r,i,o,n){var s=o-r,a=n-i;if(0!==s||0!==a){var l=((e-r)*s+(t-i)*a)/(s*s+a*a);l>1?(r=o,i=n):l>0&&(r+=s*l,i+=a*l);}return (s=e-r)*s+(a=t-i)*a}function q(e,t,r,i){var o={id:void 0===e?null:e,type:t,geometry:r,tags:i,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};return function(e){var t=e.geometry,r=e.type;if("Point"===r||"MultiPoint"===r||"LineString"===r)U(e,t);else if("Polygon"===r||"MultiLineString"===r)for(var i=0;i<t.length;i++)U(e,t[i]);else if("MultiPolygon"===r)for(i=0;i<t.length;i++)for(var o=0;o<t[i].length;o++)U(e,t[i][o]);}(o),o}function U(e,t){for(var r=0;r<t.length;r+=3)e.minX=Math.min(e.minX,t[r]),e.minY=Math.min(e.minY,t[r+1]),e.maxX=Math.max(e.maxX,t[r]),e.maxY=Math.max(e.maxY,t[r+1]);}function $(e,t,r,i){if(t.geometry){var o=t.geometry.coordinates,n=t.geometry.type,s=Math.pow(r.tolerance/((1<<r.maxZoom)*r.extent),2),a=[],l=t.id;if(r.promoteId?l=t.properties[r.promoteId]:r.generateId&&(l=i||0),"Point"===n)H(o,a);else if("MultiPoint"===n)for(var u=0;u<o.length;u++)H(o[u],a);else if("LineString"===n)K(o,a,s,!1);else if("MultiLineString"===n){if(r.lineMetrics){for(u=0;u<o.length;u++)K(o[u],a=[],s,!1),e.push(q(l,"LineString",a,t.properties));return}Q(o,a,s,!1);}else if("Polygon"===n)Q(o,a,s,!0);else {if("MultiPolygon"!==n){if("GeometryCollection"===n){for(u=0;u<t.geometry.geometries.length;u++)$(e,{id:l,geometry:t.geometry.geometries[u],properties:t.properties},r,i);return}throw new Error("Input data is not a valid GeoJSON object.")}for(u=0;u<o.length;u++){var h=[];Q(o[u],h,s,!0),a.push(h);}}e.push(q(l,n,a,t.properties));}}function H(e,t){t.push(ee(e[0])),t.push(te(e[1])),t.push(0);}function K(e,t,r,i){for(var o,n,s=0,a=0;a<e.length;a++){var l=ee(e[a][0]),u=te(e[a][1]);t.push(l),t.push(u),t.push(0),a>0&&(s+=i?(o*u-l*n)/2:Math.sqrt(Math.pow(l-o,2)+Math.pow(u-n,2))),o=l,n=u;}var h=t.length-3;t[2]=1,function e(t,r,i,o){for(var n,s=o,a=i-r>>1,l=i-r,u=t[r],h=t[r+1],c=t[i],p=t[i+1],f=r+3;f<i;f+=3){var d=R(t[f],t[f+1],u,h,c,p);if(d>s)n=f,s=d;else if(d===s){var g=Math.abs(f-a);g<l&&(n=f,l=g);}}s>o&&(n-r>3&&e(t,r,n,o),t[n+2]=s,i-n>3&&e(t,n,i,o));}(t,0,h,r),t[h+2]=1,t.size=Math.abs(s),t.start=0,t.end=t.size;}function Q(e,t,r,i){for(var o=0;o<e.length;o++){var n=[];K(e[o],n,r,i),t.push(n);}}function ee(e){return e/360+.5}function te(e){var t=Math.sin(e*Math.PI/180),r=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return r<0?0:r>1?1:r}function re(e,t,r,i,o,n,s,a){if(i/=t,n>=(r/=t)&&s<i)return e;if(s<r||n>=i)return null;for(var l=[],u=0;u<e.length;u++){var h=e[u],c=h.geometry,p=h.type,f=0===o?h.minX:h.minY,d=0===o?h.maxX:h.maxY;if(f>=r&&d<i)l.push(h);else if(!(d<r||f>=i)){var g=[];if("Point"===p||"MultiPoint"===p)ie(c,g,r,i,o);else if("LineString"===p)oe(c,g,r,i,o,!1,a.lineMetrics);else if("MultiLineString"===p)se(c,g,r,i,o,!1);else if("Polygon"===p)se(c,g,r,i,o,!0);else if("MultiPolygon"===p)for(var v=0;v<c.length;v++){var m=[];se(c[v],m,r,i,o,!0),m.length&&g.push(m);}if(g.length){if(a.lineMetrics&&"LineString"===p){for(v=0;v<g.length;v++)l.push(q(h.id,p,g[v],h.tags));continue}"LineString"!==p&&"MultiLineString"!==p||(1===g.length?(p="LineString",g=g[0]):p="MultiLineString"),"Point"!==p&&"MultiPoint"!==p||(p=3===g.length?"Point":"MultiPoint"),l.push(q(h.id,p,g,h.tags));}}}return l.length?l:null}function ie(e,t,r,i,o){for(var n=0;n<e.length;n+=3){var s=e[n+o];s>=r&&s<=i&&(t.push(e[n]),t.push(e[n+1]),t.push(e[n+2]));}}function oe(e,t,r,i,o,n,s){for(var a,l,u=ne(e),h=0===o?le:ue,c=e.start,p=0;p<e.length-3;p+=3){var f=e[p],d=e[p+1],g=e[p+2],v=e[p+3],m=e[p+4],y=0===o?f:d,x=0===o?v:m,w=!1;s&&(a=Math.sqrt(Math.pow(f-v,2)+Math.pow(d-m,2))),y<r?x>r&&(l=h(u,f,d,v,m,r),s&&(u.start=c+a*l)):y>i?x<i&&(l=h(u,f,d,v,m,i),s&&(u.start=c+a*l)):ae(u,f,d,g),x<r&&y>=r&&(l=h(u,f,d,v,m,r),w=!0),x>i&&y<=i&&(l=h(u,f,d,v,m,i),w=!0),!n&&w&&(s&&(u.end=c+a*l),t.push(u),u=ne(e)),s&&(c+=a);}var S=e.length-3;f=e[S],d=e[S+1],g=e[S+2],(y=0===o?f:d)>=r&&y<=i&&ae(u,f,d,g),S=u.length-3,n&&S>=3&&(u[S]!==u[0]||u[S+1]!==u[1])&&ae(u,u[0],u[1],u[2]),u.length&&t.push(u);}function ne(e){var t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function se(e,t,r,i,o,n){for(var s=0;s<e.length;s++)oe(e[s],t,r,i,o,n,!1);}function ae(e,t,r,i){e.push(t),e.push(r),e.push(i);}function le(e,t,r,i,o,n){var s=(n-t)/(i-t);return e.push(n),e.push(r+(o-r)*s),e.push(1),s}function ue(e,t,r,i,o,n){var s=(n-r)/(o-r);return e.push(t+(i-t)*s),e.push(n),e.push(1),s}function he(e,t){for(var r=[],i=0;i<e.length;i++){var o,n=e[i],s=n.type;if("Point"===s||"MultiPoint"===s||"LineString"===s)o=ce(n.geometry,t);else if("MultiLineString"===s||"Polygon"===s){o=[];for(var a=0;a<n.geometry.length;a++)o.push(ce(n.geometry[a],t));}else if("MultiPolygon"===s)for(o=[],a=0;a<n.geometry.length;a++){for(var l=[],u=0;u<n.geometry[a].length;u++)l.push(ce(n.geometry[a][u],t));o.push(l);}r.push(q(n.id,s,o,n.tags));}return r}function ce(e,t){var r=[];r.size=e.size,void 0!==e.start&&(r.start=e.start,r.end=e.end);for(var i=0;i<e.length;i+=3)r.push(e[i]+t,e[i+1],e[i+2]);return r}function pe(e,t){if(e.transformed)return e;var r,i,o,n=1<<e.z,s=e.x,a=e.y;for(r=0;r<e.features.length;r++){var l=e.features[r],u=l.geometry,h=l.type;if(l.geometry=[],1===h)for(i=0;i<u.length;i+=2)l.geometry.push(fe(u[i],u[i+1],t,n,s,a));else for(i=0;i<u.length;i++){var c=[];for(o=0;o<u[i].length;o+=2)c.push(fe(u[i][o],u[i][o+1],t,n,s,a));l.geometry.push(c);}}return e.transformed=!0,e}function fe(e,t,r,i,o,n){return [Math.round(r*(e*i-o)),Math.round(r*(t*i-n))]}function de(e,t,r,i,o){for(var n=t===o.maxZoom?0:o.tolerance/((1<<t)*o.extent),s={features:[],numPoints:0,numSimplified:0,numFeatures:0,source:null,x:r,y:i,z:t,transformed:!1,minX:2,minY:1,maxX:-1,maxY:0},a=0;a<e.length;a++){s.numFeatures++,ge(s,e[a],n,o);var l=e[a].minX,u=e[a].minY,h=e[a].maxX,c=e[a].maxY;l<s.minX&&(s.minX=l),u<s.minY&&(s.minY=u),h>s.maxX&&(s.maxX=h),c>s.maxY&&(s.maxY=c);}return s}function ge(e,t,r,i){var o=t.geometry,n=t.type,s=[];if("Point"===n||"MultiPoint"===n)for(var a=0;a<o.length;a+=3)s.push(o[a]),s.push(o[a+1]),e.numPoints++,e.numSimplified++;else if("LineString"===n)ve(s,o,e,r,!1,!1);else if("MultiLineString"===n||"Polygon"===n)for(a=0;a<o.length;a++)ve(s,o[a],e,r,"Polygon"===n,0===a);else if("MultiPolygon"===n)for(var l=0;l<o.length;l++){var u=o[l];for(a=0;a<u.length;a++)ve(s,u[a],e,r,!0,0===a);}if(s.length){var h=t.tags||null;if("LineString"===n&&i.lineMetrics){for(var c in h={},t.tags)h[c]=t.tags[c];h.mapbox_clip_start=o.start/o.size,h.mapbox_clip_end=o.end/o.size;}var p={geometry:s,type:"Polygon"===n||"MultiPolygon"===n?3:"LineString"===n||"MultiLineString"===n?2:1,tags:h};null!==t.id&&(p.id=t.id),e.features.push(p);}}function ve(e,t,r,i,o,n){var s=i*i;if(i>0&&t.size<(o?s:i))r.numPoints+=t.length/3;else {for(var a=[],l=0;l<t.length;l+=3)(0===i||t[l+2]>s)&&(r.numSimplified++,a.push(t[l]),a.push(t[l+1])),r.numPoints++;o&&function(e,t){for(var r=0,i=0,o=e.length,n=o-2;i<o;n=i,i+=2)r+=(e[i]-e[n])*(e[i+1]+e[n+1]);if(r>0===t)for(i=0,o=e.length;i<o/2;i+=2){var s=e[i],a=e[i+1];e[i]=e[o-2-i],e[i+1]=e[o-1-i],e[o-2-i]=s,e[o-1-i]=a;}}(a,n),e.push(a);}}function me(e,t){var r=(t=this.options=function(e,t){for(var r in t)e[r]=t[r];return e}(Object.create(this.options),t)).debug;if(r&&console.time("preprocess data"),t.maxZoom<0||t.maxZoom>24)throw new Error("maxZoom should be in the 0-24 range");if(t.promoteId&&t.generateId)throw new Error("promoteId and generateId cannot be used together.");var i=function(e,t){var r=[];if("FeatureCollection"===e.type)for(var i=0;i<e.features.length;i++)$(r,e.features[i],t,i);else $(r,"Feature"===e.type?e:{geometry:e},t);return r}(e,t);this.tiles={},this.tileCoords=[],r&&(console.timeEnd("preprocess data"),console.log("index: maxZoom: %d, maxPoints: %d",t.indexMaxZoom,t.indexMaxPoints),console.time("generate tiles"),this.stats={},this.total=0),(i=function(e,t){var r=t.buffer/t.extent,i=e,o=re(e,1,-1-r,r,0,-1,2,t),n=re(e,1,1-r,2+r,0,-1,2,t);return (o||n)&&(i=re(e,1,-r,1+r,0,-1,2,t)||[],o&&(i=he(o,1).concat(i)),n&&(i=i.concat(he(n,-1)))),i}(i,t)).length&&this.splitTile(i,0,0,0),r&&(i.length&&console.log("features: %d, points: %d",this.tiles[0].numFeatures,this.tiles[0].numPoints),console.timeEnd("generate tiles"),console.log("tiles generated:",this.total,JSON.stringify(this.stats)));}function ye(e,t,r){return 32*((1<<e)*r+t)+e}function xe(e,t){var r=e.tileID.canonical;if(!this._geoJSONIndex)return t(null,null);var i=this._geoJSONIndex.getTile(r.z,r.x,r.y);if(!i)return t(null,null);var o=new g(i.features),n=w(o);0===n.byteOffset&&n.byteLength===n.buffer.byteLength||(n=new Uint8Array(n)),t(null,{vectorTile:o,rawData:n.buffer});}J.prototype.load=function(e){var t=this.options,r=t.log,i=t.minZoom,o=t.maxZoom,n=t.nodeSize;r&&console.time("total time");var s="prepare "+e.length+" points";r&&console.time(s),this.points=e;for(var a=[],l=0;l<e.length;l++)e[l].geometry&&a.push(A(e[l],l));this.trees[o+1]=new F(a,X,W,n,Float32Array),r&&console.timeEnd(s);for(var u=o;u>=i;u--){var h=+Date.now();a=this._cluster(a,u),this.trees[u]=new F(a,X,W,n,Float32Array),r&&console.log("z%d: %d clusters in %dms",u,a.length,+Date.now()-h);}return r&&console.timeEnd("total time"),this},J.prototype.getClusters=function(e,t){var r=((e[0]+180)%360+360)%360-180,i=Math.max(-90,Math.min(90,e[1])),o=180===e[2]?180:((e[2]+180)%360+360)%360-180,n=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)r=-180,o=180;else if(r>o){var s=this.getClusters([r,i,180,n],t),a=this.getClusters([-180,i,o,n],t);return s.concat(a)}for(var l=this.trees[this._limitZoom(t)],u=[],h=0,c=l.range(Y(r),j(n),Y(o),j(i));h<c.length;h+=1){var p=l.points[c[h]];u.push(p.numPoints?B(p):this.points[p.index]);}return u},J.prototype.getChildren=function(e){var t=this._getOriginId(e),r=this._getOriginZoom(e),i="No cluster with the specified id.",o=this.trees[r];if(!o)throw new Error(i);var n=o.points[t];if(!n)throw new Error(i);for(var s=this.options.radius/(this.options.extent*Math.pow(2,r-1)),a=[],l=0,u=o.within(n.x,n.y,s);l<u.length;l+=1){var h=o.points[u[l]];h.parentId===e&&a.push(h.numPoints?B(h):this.points[h.index]);}if(0===a.length)throw new Error(i);return a},J.prototype.getLeaves=function(e,t,r){var i=[];return this._appendLeaves(i,e,t=t||10,r=r||0,0),i},J.prototype.getTile=function(e,t,r){var i=this.trees[this._limitZoom(e)],o=Math.pow(2,e),n=this.options,s=n.radius/n.extent,a=(r-s)/o,l=(r+1+s)/o,u={features:[]};return this._addTileFeatures(i.range((t-s)/o,a,(t+1+s)/o,l),i.points,t,r,o,u),0===t&&this._addTileFeatures(i.range(1-s/o,a,1,l),i.points,o,r,o,u),t===o-1&&this._addTileFeatures(i.range(0,a,s/o,l),i.points,-1,r,o,u),u.features.length?u:null},J.prototype.getClusterExpansionZoom=function(e){for(var t=this._getOriginZoom(e)-1;t<=this.options.maxZoom;){var r=this.getChildren(e);if(t++,1!==r.length)break;e=r[0].properties.cluster_id;}return t},J.prototype._appendLeaves=function(e,t,r,i,o){for(var n=0,s=this.getChildren(t);n<s.length;n+=1){var a=s[n],l=a.properties;if(l&&l.cluster?o+l.point_count<=i?o+=l.point_count:o=this._appendLeaves(e,l.cluster_id,r,i,o):o<i?o++:e.push(a),e.length===r)break}return o},J.prototype._addTileFeatures=function(e,t,r,i,o,n){for(var s=0,a=e;s<a.length;s+=1){var l=t[a[s]],u=l.numPoints,h={type:1,geometry:[[Math.round(this.options.extent*(l.x*o-r)),Math.round(this.options.extent*(l.y*o-i))]],tags:u?G(l):this.points[l.index].properties},c=void 0;u?c=l.id:this.options.generateId?c=l.index:this.points[l.index].id&&(c=this.points[l.index].id),void 0!==c&&(h.id=c),n.features.push(h);}},J.prototype._limitZoom=function(e){return Math.max(this.options.minZoom,Math.min(e,this.options.maxZoom+1))},J.prototype._cluster=function(e,t){for(var r=[],i=this.options,o=i.reduce,n=i.radius/(i.extent*Math.pow(2,t)),s=0;s<e.length;s++){var a=e[s];if(!(a.zoom<=t)){a.zoom=t;for(var l=this.trees[t+1],u=l.within(a.x,a.y,n),h=a.numPoints||1,c=a.x*h,p=a.y*h,f=o&&h>1?this._map(a,!0):null,d=(s<<5)+(t+1)+this.points.length,g=0,v=u;g<v.length;g+=1){var m=l.points[v[g]];if(!(m.zoom<=t)){m.zoom=t;var y=m.numPoints||1;c+=m.x*y,p+=m.y*y,h+=y,m.parentId=d,o&&(f||(f=this._map(a,!0)),o(f,this._map(m)));}}1===h?r.push(a):(a.parentId=d,r.push(Z(c/h,p/h,d,h,f)));}}return r},J.prototype._getOriginId=function(e){return e-this.points.length>>5},J.prototype._getOriginZoom=function(e){return (e-this.points.length)%32},J.prototype._map=function(e,t){if(e.numPoints)return t?V({},e.properties):e.properties;var r=this.points[e.index].properties,i=this.options.map(r);return t&&i===r?V({},i):i},me.prototype.options={maxZoom:14,indexMaxZoom:5,indexMaxPoints:1e5,tolerance:3,extent:4096,buffer:64,lineMetrics:!1,promoteId:null,generateId:!1,debug:0},me.prototype.splitTile=function(e,t,r,i,o,n,s){for(var a=[e,t,r,i],l=this.options,u=l.debug;a.length;){i=a.pop(),r=a.pop(),t=a.pop(),e=a.pop();var h=1<<t,c=ye(t,r,i),p=this.tiles[c];if(!p&&(u>1&&console.time("creation"),p=this.tiles[c]=de(e,t,r,i,l),this.tileCoords.push({z:t,x:r,y:i}),u)){u>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,r,i,p.numFeatures,p.numPoints,p.numSimplified),console.timeEnd("creation"));var f="z"+t;this.stats[f]=(this.stats[f]||0)+1,this.total++;}if(p.source=e,o){if(t===l.maxZoom||t===o)continue;var d=1<<o-t;if(r!==Math.floor(n/d)||i!==Math.floor(s/d))continue}else if(t===l.indexMaxZoom||p.numPoints<=l.indexMaxPoints)continue;if(p.source=null,0!==e.length){u>1&&console.time("clipping");var g,v,m,y,x,w,S=.5*l.buffer/l.extent,I=.5-S,M=.5+S,b=1+S;g=v=m=y=null,x=re(e,h,r-S,r+M,0,p.minX,p.maxX,l),w=re(e,h,r+I,r+b,0,p.minX,p.maxX,l),e=null,x&&(g=re(x,h,i-S,i+M,1,p.minY,p.maxY,l),v=re(x,h,i+I,i+b,1,p.minY,p.maxY,l),x=null),w&&(m=re(w,h,i-S,i+M,1,p.minY,p.maxY,l),y=re(w,h,i+I,i+b,1,p.minY,p.maxY,l),w=null),u>1&&console.timeEnd("clipping"),a.push(g||[],t+1,2*r,2*i),a.push(v||[],t+1,2*r,2*i+1),a.push(m||[],t+1,2*r+1,2*i),a.push(y||[],t+1,2*r+1,2*i+1);}}},me.prototype.getTile=function(e,t,r){var i=this.options,o=i.extent,n=i.debug;if(e<0||e>24)return null;var s=1<<e,a=ye(e,t=(t%s+s)%s,r);if(this.tiles[a])return pe(this.tiles[a],o);n>1&&console.log("drilling down to z%d-%d-%d",e,t,r);for(var l,u=e,h=t,c=r;!l&&u>0;)u--,h=Math.floor(h/2),c=Math.floor(c/2),l=this.tiles[ye(u,h,c)];return l&&l.source?(n>1&&console.log("found parent tile z%d-%d-%d",u,h,c),n>1&&console.time("drilling down"),this.splitTile(l.source,u,h,c,e,t,r),n>1&&console.timeEnd("drilling down"),this.tiles[a]?pe(this.tiles[a],o):null):null};var we=function(t){function r(e,r,i,o){t.call(this,e,r,i,xe),o&&(this.loadGeoJSON=o);}return t&&(r.__proto__=t),(r.prototype=Object.create(t&&t.prototype)).constructor=r,r.prototype.loadData=function(e,t){this._pendingCallback&&this._pendingCallback(null,{abandoned:!0}),this._pendingCallback=t,this._pendingLoadDataParams=e,this._state&&"Idle"!==this._state?this._state="NeedsLoadData":(this._state="Coalescing",this._loadData());},r.prototype._loadData=function(){var t=this;if(this._pendingCallback&&this._pendingLoadDataParams){var r=this._pendingCallback,i=this._pendingLoadDataParams;delete this._pendingCallback,delete this._pendingLoadDataParams;var o=!!(i&&i.request&&i.request.collectResourceTiming)&&new e.RequestPerformance(i.request);this.loadGeoJSON(i,(function(n,s){if(n||!s)return r(n);if("object"!=typeof s)return r(new Error("Input data given to '"+i.source+"' is not a valid GeoJSON object."));!function e(t,r){var i,o=t&&t.type;if("FeatureCollection"===o)for(i=0;i<t.features.length;i++)e(t.features[i],r);else if("GeometryCollection"===o)for(i=0;i<t.geometries.length;i++)e(t.geometries[i],r);else if("Feature"===o)e(t.geometry,r);else if("Polygon"===o)c(t.coordinates,r);else if("MultiPolygon"===o)for(i=0;i<t.coordinates.length;i++)c(t.coordinates[i],r);return t}(s,!0);try{t._geoJSONIndex=i.cluster?new J(function(t){var r=t.superclusterOptions,i=t.clusterProperties;if(!i||!r)return r;for(var o={},n={},s={accumulated:null,zoom:0},a={properties:null},l=Object.keys(i),u=0,h=l;u<h.length;u+=1){var c=h[u],p=i[c],f=p[0],d=e.createExpression(p[1]),g=e.createExpression("string"==typeof f?[f,["accumulated"],["get",c]]:f);o[c]=d.value,n[c]=g.value;}return r.map=function(e){a.properties=e;for(var t={},r=0,i=l;r<i.length;r+=1){var n=i[r];t[n]=o[n].evaluate(s,a);}return t},r.reduce=function(e,t){a.properties=t;for(var r=0,i=l;r<i.length;r+=1){var o=i[r];s.accumulated=e[o],e[o]=n[o].evaluate(s,a);}},r}(i)).load(s.features):function(e,t){return new me(e,t)}(s,i.geojsonVtOptions);}catch(n){return r(n)}t.loaded={};var a={};if(o){var l=o.finish();l&&(a.resourceTiming={},a.resourceTiming[i.source]=JSON.parse(JSON.stringify(l)));}r(null,a);}));}},r.prototype.coalesce=function(){"Coalescing"===this._state?this._state="Idle":"NeedsLoadData"===this._state&&(this._state="Coalescing",this._loadData());},r.prototype.reloadTile=function(e,r){var i=this.loaded;return i&&i[e.uid]?t.prototype.reloadTile.call(this,e,r):this.loadTile(e,r)},r.prototype.loadGeoJSON=function(t,r){if(t.request)e.getJSON(t.request,r);else {if("string"!=typeof t.data)return r(new Error("Input data given to '"+t.source+"' is not a valid GeoJSON object."));try{return r(null,JSON.parse(t.data))}catch(e){return r(new Error("Input data given to '"+t.source+"' is not a valid GeoJSON object."))}}},r.prototype.removeSource=function(e,t){this._pendingCallback&&this._pendingCallback(null,{abandoned:!0}),t();},r.prototype.getClusterExpansionZoom=function(e,t){try{t(null,this._geoJSONIndex.getClusterExpansionZoom(e.clusterId));}catch(e){t(e);}},r.prototype.getClusterChildren=function(e,t){try{t(null,this._geoJSONIndex.getChildren(e.clusterId));}catch(e){t(e);}},r.prototype.getClusterLeaves=function(e,t){try{t(null,this._geoJSONIndex.getLeaves(e.clusterId,e.limit,e.offset));}catch(e){t(e);}},r}(l),Se=function(t){var r=this;this.self=t,this.actor=new e.Actor(t,this),this.layerIndexes={},this.availableImages={},this.workerSourceTypes={vector:l,geojson:we},this.workerSources={},this.demWorkerSources={},this.self.registerWorkerSource=function(e,t){if(r.workerSourceTypes[e])throw new Error('Worker source with name "'+e+'" already registered.');r.workerSourceTypes[e]=t;},this.self.registerRTLTextPlugin=function(t){if(e.plugin.isParsed())throw new Error("RTL text plugin already registered.");e.plugin.applyArabicShaping=t.applyArabicShaping,e.plugin.processBidirectionalText=t.processBidirectionalText,e.plugin.processStyledBidirectionalText=t.processStyledBidirectionalText;};};return Se.prototype.setReferrer=function(e,t){this.referrer=t;},Se.prototype.setImages=function(e,t,r){for(var i in this.availableImages[e]=t,this.workerSources[e]){var o=this.workerSources[e][i];for(var n in o)o[n].availableImages=t;}r();},Se.prototype.setLayers=function(e,t,r){this.getLayerIndex(e).replace(t),r();},Se.prototype.updateLayers=function(e,t,r){this.getLayerIndex(e).update(t.layers,t.removedIds),r();},Se.prototype.loadTile=function(e,t,r){this.getWorkerSource(e,t.type,t.source).loadTile(t,r);},Se.prototype.loadDEMTile=function(e,t,r){this.getDEMWorkerSource(e,t.source).loadTile(t,r);},Se.prototype.reloadTile=function(e,t,r){this.getWorkerSource(e,t.type,t.source).reloadTile(t,r);},Se.prototype.abortTile=function(e,t,r){this.getWorkerSource(e,t.type,t.source).abortTile(t,r);},Se.prototype.removeTile=function(e,t,r){this.getWorkerSource(e,t.type,t.source).removeTile(t,r);},Se.prototype.removeDEMTile=function(e,t){this.getDEMWorkerSource(e,t.source).removeTile(t);},Se.prototype.removeSource=function(e,t,r){if(this.workerSources[e]&&this.workerSources[e][t.type]&&this.workerSources[e][t.type][t.source]){var i=this.workerSources[e][t.type][t.source];delete this.workerSources[e][t.type][t.source],void 0!==i.removeSource?i.removeSource(t,r):r();}},Se.prototype.loadWorkerSource=function(e,t,r){try{this.self.importScripts(t.url),r();}catch(e){r(e.toString());}},Se.prototype.syncRTLPluginState=function(t,r,i){try{e.plugin.setState(r);var o=e.plugin.getPluginURL();if(e.plugin.isLoaded()&&!e.plugin.isParsed()&&null!=o){this.self.importScripts(o);var n=e.plugin.isParsed();i(n?void 0:new Error("RTL Text Plugin failed to import scripts from "+o),n);}}catch(e){i(e.toString());}},Se.prototype.getAvailableImages=function(e){var t=this.availableImages[e];return t||(t=[]),t},Se.prototype.getLayerIndex=function(e){var t=this.layerIndexes[e];return t||(t=this.layerIndexes[e]=new i),t},Se.prototype.getWorkerSource=function(e,t,r){var i=this;return this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][t]||(this.workerSources[e][t]={}),this.workerSources[e][t][r]||(this.workerSources[e][t][r]=new this.workerSourceTypes[t]({send:function(t,r,o){i.actor.send(t,r,o,e);}},this.getLayerIndex(e),this.getAvailableImages(e))),this.workerSources[e][t][r]},Se.prototype.getDEMWorkerSource=function(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new h),this.demWorkerSources[e][t]},Se.prototype.enforceCacheSizeLimit=function(t,r){e.enforceCacheSizeLimit(r);},"undefined"!=typeof WorkerGlobalScope&&void 0!==e.window&&e.window instanceof WorkerGlobalScope&&(e.window.worker=new Se(e.window)),Se}));

define(["./shared"],(function(t){"use strict";var e=t.createCommonjsModule((function(t){function e(t){return !i(t)}function i(t){return "undefined"==typeof window||"undefined"==typeof document?"not a browser":Array.prototype&&Array.prototype.every&&Array.prototype.filter&&Array.prototype.forEach&&Array.prototype.indexOf&&Array.prototype.lastIndexOf&&Array.prototype.map&&Array.prototype.some&&Array.prototype.reduce&&Array.prototype.reduceRight&&Array.isArray?Function.prototype&&Function.prototype.bind?Object.keys&&Object.create&&Object.getPrototypeOf&&Object.getOwnPropertyNames&&Object.isSealed&&Object.isFrozen&&Object.isExtensible&&Object.getOwnPropertyDescriptor&&Object.defineProperty&&Object.defineProperties&&Object.seal&&Object.freeze&&Object.preventExtensions?"JSON"in window&&"parse"in JSON&&"stringify"in JSON?function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return !1;var t,e,i=new Blob([""],{type:"text/javascript"}),o=URL.createObjectURL(i);try{e=new Worker(o),t=!0;}catch(e){t=!1;}return e&&e.terminate(),URL.revokeObjectURL(o),t}()?"Uint8ClampedArray"in window?ArrayBuffer.isView?function(){var t=document.createElement("canvas");t.width=t.height=1;var e=t.getContext("2d");if(!e)return !1;var i=e.getImageData(0,0,1,1);return i&&i.width===t.width}()?(void 0===o[i=t&&t.failIfMajorPerformanceCaveat]&&(o[i]=function(t){var i=function(t){var i=document.createElement("canvas"),o=Object.create(e.webGLContextAttributes);return o.failIfMajorPerformanceCaveat=t,i.probablySupportsContext?i.probablySupportsContext("webgl",o)||i.probablySupportsContext("experimental-webgl",o):i.supportsContext?i.supportsContext("webgl",o)||i.supportsContext("experimental-webgl",o):i.getContext("webgl",o)||i.getContext("experimental-webgl",o)}(t);if(!i)return !1;var o=i.createShader(i.VERTEX_SHADER);return !(!o||i.isContextLost())&&(i.shaderSource(o,"void main() {}"),i.compileShader(o),!0===i.getShaderParameter(o,i.COMPILE_STATUS))}(i)),o[i]?void 0:"insufficient WebGL support"):"insufficient Canvas/getImageData support":"insufficient ArrayBuffer support":"insufficient Uint8ClampedArray support":"insufficient worker support":"insufficient JSON support":"insufficient Object support":"insufficient Function support":"insufficent Array support";var i;}t.exports?t.exports=e:window&&(window.mapboxgl=window.mapboxgl||{},window.mapboxgl.supported=e,window.mapboxgl.notSupportedReason=i);var o={};e.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0};})),i={create:function(e,i,o){var r=t.window.document.createElement(e);return void 0!==i&&(r.className=i),o&&o.appendChild(r),r},createNS:function(e,i){return t.window.document.createElementNS(e,i)}},o=t.window.document.documentElement.style;function r(t){if(!o)return t[0];for(var e=0;e<t.length;e++)if(t[e]in o)return t[e];return t[0]}var a,n=r(["userSelect","MozUserSelect","WebkitUserSelect","msUserSelect"]);i.disableDrag=function(){o&&n&&(a=o[n],o[n]="none");},i.enableDrag=function(){o&&n&&(o[n]=a);};var s=r(["transform","WebkitTransform"]);i.setTransform=function(t,e){t.style[s]=e;};var l=!1;try{var c=Object.defineProperty({},"passive",{get:function(){l=!0;}});t.window.addEventListener("test",c,c),t.window.removeEventListener("test",c,c);}catch(t){l=!1;}i.addEventListener=function(t,e,i,o){void 0===o&&(o={}),t.addEventListener(e,i,"passive"in o&&l?o:o.capture);},i.removeEventListener=function(t,e,i,o){void 0===o&&(o={}),t.removeEventListener(e,i,"passive"in o&&l?o:o.capture);};var u=function(e){e.preventDefault(),e.stopPropagation(),t.window.removeEventListener("click",u,!0);};function h(t){var e=t.userImage;return !!(e&&e.render&&e.render())&&(t.data.replace(new Uint8Array(e.data.buffer)),!0)}i.suppressClick=function(){t.window.addEventListener("click",u,!0),t.window.setTimeout((function(){t.window.removeEventListener("click",u,!0);}),0);},i.mousePos=function(e,i){var o=e.getBoundingClientRect();return new t.Point(i.clientX-o.left-e.clientLeft,i.clientY-o.top-e.clientTop)},i.touchPos=function(e,i){for(var o=e.getBoundingClientRect(),r=[],a=0;a<i.length;a++)r.push(new t.Point(i[a].clientX-o.left-e.clientLeft,i[a].clientY-o.top-e.clientTop));return r},i.mouseButton=function(e){return void 0!==t.window.InstallTrigger&&2===e.button&&e.ctrlKey&&t.window.navigator.platform.toUpperCase().indexOf("MAC")>=0?0:e.button},i.remove=function(t){t.parentNode&&t.parentNode.removeChild(t);};var p=function(e){function i(){e.call(this),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new t.RGBAImage({width:1,height:1}),this.dirty=!0;}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.isLoaded=function(){return this.loaded},i.prototype.setLoaded=function(t){if(this.loaded!==t&&(this.loaded=t,t)){for(var e=0,i=this.requestors;e<i.length;e+=1){var o=i[e];this._notify(o.ids,o.callback);}this.requestors=[];}},i.prototype.getImage=function(t){return this.images[t]},i.prototype.addImage=function(t,e){this._validate(t,e)&&(this.images[t]=e);},i.prototype._validate=function(e,i){var o=!0;return this._validateStretch(i.stretchX,i.data&&i.data.width)||(this.fire(new t.ErrorEvent(new Error('Image "'+e+'" has invalid "stretchX" value'))),o=!1),this._validateStretch(i.stretchY,i.data&&i.data.height)||(this.fire(new t.ErrorEvent(new Error('Image "'+e+'" has invalid "stretchY" value'))),o=!1),this._validateContent(i.content,i)||(this.fire(new t.ErrorEvent(new Error('Image "'+e+'" has invalid "content" value'))),o=!1),o},i.prototype._validateStretch=function(t,e){if(!t)return !0;for(var i=0,o=0,r=t;o<r.length;o+=1){var a=r[o];if(a[0]<i||a[1]<a[0]||e<a[1])return !1;i=a[1];}return !0},i.prototype._validateContent=function(t,e){return !(t&&(4!==t.length||t[0]<0||e.data.width<t[0]||t[1]<0||e.data.height<t[1]||t[2]<0||e.data.width<t[2]||t[3]<0||e.data.height<t[3]||t[2]<t[0]||t[3]<t[1]))},i.prototype.updateImage=function(t,e){e.version=this.images[t].version+1,this.images[t]=e,this.updatedImages[t]=!0;},i.prototype.removeImage=function(t){var e=this.images[t];delete this.images[t],delete this.patterns[t],e.userImage&&e.userImage.onRemove&&e.userImage.onRemove();},i.prototype.listImages=function(){return Object.keys(this.images)},i.prototype.getImages=function(t,e){var i=!0;if(!this.isLoaded())for(var o=0,r=t;o<r.length;o+=1)this.images[r[o]]||(i=!1);this.isLoaded()||i?this._notify(t,e):this.requestors.push({ids:t,callback:e});},i.prototype._notify=function(e,i){for(var o={},r=0,a=e;r<a.length;r+=1){var n=a[r];this.images[n]||this.fire(new t.Event("styleimagemissing",{id:n}));var s=this.images[n];s?o[n]={data:s.data.clone(),pixelRatio:s.pixelRatio,sdf:s.sdf,version:s.version,stretchX:s.stretchX,stretchY:s.stretchY,content:s.content,hasRenderCallback:Boolean(s.userImage&&s.userImage.render)}:t.warnOnce('Image "'+n+'" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.');}i(null,o);},i.prototype.getPixelSize=function(){var t=this.atlasImage;return {width:t.width,height:t.height}},i.prototype.getPattern=function(e){var i=this.patterns[e],o=this.getImage(e);if(!o)return null;if(i&&i.position.version===o.version)return i.position;if(i)i.position.version=o.version;else {var r={w:o.data.width+2,h:o.data.height+2,x:0,y:0},a=new t.ImagePosition(r,o);this.patterns[e]={bin:r,position:a};}return this._updatePatternAtlas(),this.patterns[e].position},i.prototype.bind=function(e){var i=e.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new t.Texture(e,this.atlasImage,i.RGBA),this.atlasTexture.bind(i.LINEAR,i.CLAMP_TO_EDGE);},i.prototype._updatePatternAtlas=function(){var e=[];for(var i in this.patterns)e.push(this.patterns[i].bin);var o=t.potpack(e),r=o.w,a=o.h,n=this.atlasImage;for(var s in n.resize({width:r||1,height:a||1}),this.patterns){var l=this.patterns[s].bin,c=l.x+1,u=l.y+1,h=this.images[s].data,p=h.width,d=h.height;t.RGBAImage.copy(h,n,{x:0,y:0},{x:c,y:u},{width:p,height:d}),t.RGBAImage.copy(h,n,{x:0,y:d-1},{x:c,y:u-1},{width:p,height:1}),t.RGBAImage.copy(h,n,{x:0,y:0},{x:c,y:u+d},{width:p,height:1}),t.RGBAImage.copy(h,n,{x:p-1,y:0},{x:c-1,y:u},{width:1,height:d}),t.RGBAImage.copy(h,n,{x:0,y:0},{x:c+p,y:u},{width:1,height:d});}this.dirty=!0;},i.prototype.beginFrame=function(){this.callbackDispatchedThisFrame={};},i.prototype.dispatchRenderCallbacks=function(t){for(var e=0,i=t;e<i.length;e+=1){var o=i[e];if(!this.callbackDispatchedThisFrame[o]){this.callbackDispatchedThisFrame[o]=!0;var r=this.images[o];h(r)&&this.updateImage(o,r);}}},i}(t.Evented),d=m,_=m,f=1e20;function m(t,e,i,o,r,a){this.fontSize=t||24,this.buffer=void 0===e?3:e,this.cutoff=o||.25,this.fontFamily=r||"sans-serif",this.fontWeight=a||"normal",this.radius=i||8;var n=this.size=this.fontSize+2*this.buffer;this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=n,this.ctx=this.canvas.getContext("2d"),this.ctx.font=this.fontWeight+" "+this.fontSize+"px "+this.fontFamily,this.ctx.textBaseline="middle",this.ctx.fillStyle="black",this.gridOuter=new Float64Array(n*n),this.gridInner=new Float64Array(n*n),this.f=new Float64Array(n),this.d=new Float64Array(n),this.z=new Float64Array(n+1),this.v=new Int16Array(n),this.middle=Math.round(n/2*(navigator.userAgent.indexOf("Gecko/")>=0?1.2:1));}function g(t,e,i,o,r,a,n){for(var s=0;s<e;s++){for(var l=0;l<i;l++)o[l]=t[l*e+s];for(v(o,r,a,n,i),l=0;l<i;l++)t[l*e+s]=r[l];}for(l=0;l<i;l++){for(s=0;s<e;s++)o[s]=t[l*e+s];for(v(o,r,a,n,e),s=0;s<e;s++)t[l*e+s]=Math.sqrt(r[s]);}}function v(t,e,i,o,r){i[0]=0,o[0]=-f,o[1]=+f;for(var a=1,n=0;a<r;a++){for(var s=(t[a]+a*a-(t[i[n]]+i[n]*i[n]))/(2*a-2*i[n]);s<=o[n];)n--,s=(t[a]+a*a-(t[i[n]]+i[n]*i[n]))/(2*a-2*i[n]);i[++n]=a,o[n]=s,o[n+1]=+f;}for(a=0,n=0;a<r;a++){for(;o[n+1]<a;)n++;e[a]=(a-i[n])*(a-i[n])+t[i[n]];}}m.prototype.draw=function(t){this.ctx.clearRect(0,0,this.size,this.size),this.ctx.fillText(t,this.buffer,this.middle);for(var e=this.ctx.getImageData(0,0,this.size,this.size),i=new Uint8ClampedArray(this.size*this.size),o=0;o<this.size*this.size;o++){var r=e.data[4*o+3]/255;this.gridOuter[o]=1===r?0:0===r?f:Math.pow(Math.max(0,.5-r),2),this.gridInner[o]=1===r?f:0===r?0:Math.pow(Math.max(0,r-.5),2);}for(g(this.gridOuter,this.size,this.size,this.f,this.d,this.v,this.z),g(this.gridInner,this.size,this.size,this.f,this.d,this.v,this.z),o=0;o<this.size*this.size;o++)i[o]=Math.max(0,Math.min(255,Math.round(255-255*((this.gridOuter[o]-this.gridInner[o])/this.radius+this.cutoff))));return i},d.default=_;var y=function(t,e){this.requestManager=t,this.localIdeographFontFamily=e,this.entries={};};y.prototype.setURL=function(t){this.url=t;},y.prototype.getGlyphs=function(e,i){var o=this,r=[];for(var a in e)for(var n=0,s=e[a];n<s.length;n+=1)r.push({stack:a,id:s[n]});t.asyncAll(r,(function(t,e){var i=t.stack,r=t.id,a=o.entries[i];a||(a=o.entries[i]={glyphs:{},requests:{},ranges:{}});var n=a.glyphs[r];if(void 0===n){if(n=o._tinySDF(a,i,r))return a.glyphs[r]=n,void e(null,{stack:i,id:r,glyph:n});var s=Math.floor(r/256);if(256*s>65535)e(new Error("glyphs > 65535 not supported"));else if(a.ranges[s])e(null,{stack:i,id:r,glyph:n});else {var l=a.requests[s];l||(l=a.requests[s]=[],y.loadGlyphRange(i,s,o.url,o.requestManager,(function(t,e){if(e){for(var i in e)o._doesCharSupportLocalGlyph(+i)||(a.glyphs[+i]=e[+i]);a.ranges[s]=!0;}for(var r=0,n=l;r<n.length;r+=1)(0,n[r])(t,e);delete a.requests[s];}))),l.push((function(t,o){t?e(t):o&&e(null,{stack:i,id:r,glyph:o[r]||null});}));}}else e(null,{stack:i,id:r,glyph:n});}),(function(t,e){if(t)i(t);else if(e){for(var o={},r=0,a=e;r<a.length;r+=1){var n=a[r],s=n.stack,l=n.id,c=n.glyph;(o[s]||(o[s]={}))[l]=c&&{id:c.id,bitmap:c.bitmap.clone(),metrics:c.metrics};}i(null,o);}}));},y.prototype._doesCharSupportLocalGlyph=function(e){return !!this.localIdeographFontFamily&&(t.isChar["CJK Unified Ideographs"](e)||t.isChar["Hangul Syllables"](e)||t.isChar.Hiragana(e)||t.isChar.Katakana(e))},y.prototype._tinySDF=function(e,i,o){var r=this.localIdeographFontFamily;if(r&&this._doesCharSupportLocalGlyph(o)){var a=e.tinySDF;if(!a){var n="400";/bold/i.test(i)?n="900":/medium/i.test(i)?n="500":/light/i.test(i)&&(n="200"),a=e.tinySDF=new y.TinySDF(24,3,8,.25,r,n);}return {id:o,bitmap:new t.AlphaImage({width:30,height:30},a.draw(String.fromCharCode(o))),metrics:{width:24,height:24,left:0,top:-8,advance:24}}}},y.loadGlyphRange=function(e,i,o,r,a){var n=256*i,s=n+255,l=r.transformRequest(r.normalizeGlyphsURL(o).replace("{fontstack}",e).replace("{range}",n+"-"+s),t.ResourceType.Glyphs);t.getArrayBuffer(l,(function(e,i){if(e)a(e);else if(i){for(var o={},r=0,n=t.parseGlyphPBF(i);r<n.length;r+=1){var s=n[r];o[s.id]=s;}a(null,o);}}));},y.TinySDF=d;var x=function(){this.specification=t.styleSpec.light.position;};x.prototype.possiblyEvaluate=function(e,i){return t.sphericalToCartesian(e.expression.evaluate(i))},x.prototype.interpolate=function(e,i,o){return {x:t.number(e.x,i.x,o),y:t.number(e.y,i.y,o),z:t.number(e.z,i.z,o)}};var b=new t.Properties({anchor:new t.DataConstantProperty(t.styleSpec.light.anchor),position:new x,color:new t.DataConstantProperty(t.styleSpec.light.color),intensity:new t.DataConstantProperty(t.styleSpec.light.intensity)}),w=function(e){function i(i){e.call(this),this._transitionable=new t.Transitionable(b),this.setLight(i),this._transitioning=this._transitionable.untransitioned();}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.getLight=function(){return this._transitionable.serialize()},i.prototype.setLight=function(e,i){if(void 0===i&&(i={}),!this._validate(t.validateLight,e,i))for(var o in e){var r=e[o];t.endsWith(o,"-transition")?this._transitionable.setTransition(o.slice(0,-"-transition".length),r):this._transitionable.setValue(o,r);}},i.prototype.updateTransitions=function(t){this._transitioning=this._transitionable.transitioned(t,this._transitioning);},i.prototype.hasTransition=function(){return this._transitioning.hasTransition()},i.prototype.recalculate=function(t){this.properties=this._transitioning.possiblyEvaluate(t);},i.prototype._validate=function(e,i,o){return (!o||!1!==o.validate)&&t.emitValidationErrors(this,e.call(t.validateStyle,t.extend({value:i,style:{glyphs:!0,sprite:!0},styleSpec:t.styleSpec})))},i}(t.Evented),T=function(t,e){this.width=t,this.height=e,this.nextRow=0,this.data=new Uint8Array(this.width*this.height),this.dashEntry={};};T.prototype.getDash=function(t,e){var i=t.join(",")+String(e);return this.dashEntry[i]||(this.dashEntry[i]=this.addDash(t,e)),this.dashEntry[i]},T.prototype.getDashRanges=function(t,e,i){var o=[],r=t.length%2==1?-t[t.length-1]*i:0,a=t[0]*i,n=!0;o.push({left:r,right:a,isDash:n,zeroLength:0===t[0]});for(var s=t[0],l=1;l<t.length;l++){var c=t[l];o.push({left:r=s*i,right:a=(s+=c)*i,isDash:n=!n,zeroLength:0===c});}return o},T.prototype.addRoundDash=function(t,e,i){for(var o=e/2,r=-i;r<=i;r++)for(var a=this.width*(this.nextRow+i+r),n=0,s=t[n],l=0;l<this.width;l++){l/s.right>1&&(s=t[++n]);var c=Math.abs(l-s.left),u=Math.abs(l-s.right),h=Math.min(c,u),p=void 0,d=r/i*(o+1);if(s.isDash){var _=o-Math.abs(d);p=Math.sqrt(h*h+_*_);}else p=o-Math.sqrt(h*h+d*d);this.data[a+l]=Math.max(0,Math.min(255,p+128));}},T.prototype.addRegularDash=function(t){for(var e=t.length-1;e>=0;--e){var i=t[e],o=t[e+1];i.zeroLength?t.splice(e,1):o&&o.isDash===i.isDash&&(o.left=i.left,t.splice(e,1));}var r=t[0],a=t[t.length-1];r.isDash===a.isDash&&(r.left=a.left-this.width,a.right=r.right+this.width);for(var n=this.width*this.nextRow,s=0,l=t[s],c=0;c<this.width;c++){c/l.right>1&&(l=t[++s]);var u=Math.abs(c-l.left),h=Math.abs(c-l.right),p=Math.min(u,h);this.data[n+c]=Math.max(0,Math.min(255,(l.isDash?p:-p)+128));}},T.prototype.addDash=function(e,i){var o=i?7:0,r=2*o+1;if(this.nextRow+r>this.height)return t.warnOnce("LineAtlas out of space"),null;for(var a=0,n=0;n<e.length;n++)a+=e[n];if(0!==a){var s=this.width/a,l=this.getDashRanges(e,this.width,s);i?this.addRoundDash(l,s,o):this.addRegularDash(l);}var c={y:(this.nextRow+o+.5)/this.height,height:2*o/this.height,width:a};return this.nextRow+=r,this.dirty=!0,c},T.prototype.bind=function(t){var e=t.gl;this.texture?(e.bindTexture(e.TEXTURE_2D,this.texture),this.dirty&&(this.dirty=!1,e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.width,this.height,e.ALPHA,e.UNSIGNED_BYTE,this.data))):(this.texture=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texImage2D(e.TEXTURE_2D,0,e.ALPHA,this.width,this.height,0,e.ALPHA,e.UNSIGNED_BYTE,this.data));};var E=function e(i,o){this.workerPool=i,this.actors=[],this.currentActor=0,this.id=t.uniqueId();for(var r=this.workerPool.acquire(this.id),a=0;a<r.length;a++){var n=new e.Actor(r[a],o,this.id);n.name="Worker "+a,this.actors.push(n);}};function I(e,i,o){var r=function(r,a){if(r)return o(r);if(a){var n=t.pick(t.extend(a,e),["tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","scheme","tileSize","encoding"]);a.vector_layers&&(n.vectorLayers=a.vector_layers,n.vectorLayerIds=n.vectorLayers.map((function(t){return t.id}))),n.tiles=i.canonicalizeTileset(n,e.url),o(null,n);}};return e.url?t.getJSON(i.transformRequest(i.normalizeSourceURL(e.url),t.ResourceType.Source),r):t.browser.frame((function(){return r(null,e)}))}E.prototype.broadcast=function(e,i,o){t.asyncAll(this.actors,(function(t,o){t.send(e,i,o);}),o=o||function(){});},E.prototype.getActor=function(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]},E.prototype.remove=function(){this.actors.forEach((function(t){t.remove();})),this.actors=[],this.workerPool.release(this.id);},E.Actor=t.Actor;var P=function(e,i,o){this.bounds=t.LngLatBounds.convert(this.validateBounds(e)),this.minzoom=i||0,this.maxzoom=o||24;};P.prototype.validateBounds=function(t){return Array.isArray(t)&&4===t.length?[Math.max(-180,t[0]),Math.max(-90,t[1]),Math.min(180,t[2]),Math.min(90,t[3])]:[-180,-90,180,90]},P.prototype.contains=function(e){var i=Math.pow(2,e.z),o=Math.floor(t.mercatorXfromLng(this.bounds.getWest())*i),r=Math.floor(t.mercatorYfromLat(this.bounds.getNorth())*i),a=Math.ceil(t.mercatorXfromLng(this.bounds.getEast())*i),n=Math.ceil(t.mercatorYfromLat(this.bounds.getSouth())*i);return e.x>=o&&e.x<a&&e.y>=r&&e.y<n};var S=function(e){function i(i,o,r,a){if(e.call(this),this.id=i,this.dispatcher=r,this.type="vector",this.minzoom=0,this.maxzoom=22,this.scheme="xyz",this.tileSize=512,this.reparseOverscaled=!0,this.isTileClipped=!0,this._loaded=!1,t.extend(this,t.pick(o,["url","scheme","tileSize","promoteId"])),this._options=t.extend({type:"vector"},o),this._collectResourceTiming=o.collectResourceTiming,512!==this.tileSize)throw new Error("vector tile sources must have a tileSize of 512");this.setEventedParent(a);}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.load=function(){var e=this;this._loaded=!1,this.fire(new t.Event("dataloading",{dataType:"source"})),this._tileJSONRequest=I(this._options,this.map._requestManager,(function(i,o){e._tileJSONRequest=null,e._loaded=!0,i?e.fire(new t.ErrorEvent(i)):o&&(t.extend(e,o),o.bounds&&(e.tileBounds=new P(o.bounds,e.minzoom,e.maxzoom)),t.postTurnstileEvent(o.tiles,e.map._requestManager._customAccessToken),t.postMapLoadEvent(o.tiles,e.map._getMapId(),e.map._requestManager._skuToken,e.map._requestManager._customAccessToken),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})));}));},i.prototype.loaded=function(){return this._loaded},i.prototype.hasTile=function(t){return !this.tileBounds||this.tileBounds.contains(t.canonical)},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.onRemove=function(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null);},i.prototype.serialize=function(){return t.extend({},this._options)},i.prototype.loadTile=function(e,i){var o=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme)),r={request:this.map._requestManager.transformRequest(o,t.ResourceType.Tile),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:t.browser.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId};function a(o,r){return delete e.request,e.aborted?i(null):o&&404!==o.status?i(o):(r&&r.resourceTiming&&(e.resourceTiming=r.resourceTiming),this.map._refreshExpiredTiles&&r&&e.setExpiryData(r),e.loadVectorData(r,this.map.painter),t.cacheEntryPossiblyAdded(this.dispatcher),i(null),void(e.reloadCallback&&(this.loadTile(e,e.reloadCallback),e.reloadCallback=null)))}r.request.collectResourceTiming=this._collectResourceTiming,e.actor&&"expired"!==e.state?"loading"===e.state?e.reloadCallback=i:e.request=e.actor.send("reloadTile",r,a.bind(this)):(e.actor=this.dispatcher.getActor(),e.request=e.actor.send("loadTile",r,a.bind(this)));},i.prototype.abortTile=function(t){t.request&&(t.request.cancel(),delete t.request),t.actor&&t.actor.send("abortTile",{uid:t.uid,type:this.type,source:this.id},void 0);},i.prototype.unloadTile=function(t){t.unloadVectorData(),t.actor&&t.actor.send("removeTile",{uid:t.uid,type:this.type,source:this.id},void 0);},i.prototype.hasTransition=function(){return !1},i}(t.Evented),C=function(e){function i(i,o,r,a){e.call(this),this.id=i,this.dispatcher=r,this.setEventedParent(a),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=t.extend({type:"raster"},o),t.extend(this,t.pick(o,["url","scheme","tileSize"]));}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.load=function(){var e=this;this._loaded=!1,this.fire(new t.Event("dataloading",{dataType:"source"})),this._tileJSONRequest=I(this._options,this.map._requestManager,(function(i,o){e._tileJSONRequest=null,e._loaded=!0,i?e.fire(new t.ErrorEvent(i)):o&&(t.extend(e,o),o.bounds&&(e.tileBounds=new P(o.bounds,e.minzoom,e.maxzoom)),t.postTurnstileEvent(o.tiles),t.postMapLoadEvent(o.tiles,e.map._getMapId(),e.map._requestManager._skuToken),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})),e.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})));}));},i.prototype.loaded=function(){return this._loaded},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.onRemove=function(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null);},i.prototype.serialize=function(){return t.extend({},this._options)},i.prototype.hasTile=function(t){return !this.tileBounds||this.tileBounds.contains(t.canonical)},i.prototype.loadTile=function(e,i){var o=this,r=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme),this.tileSize);e.request=t.getImage(this.map._requestManager.transformRequest(r,t.ResourceType.Tile),(function(r,a){if(delete e.request,e.aborted)e.state="unloaded",i(null);else if(r)e.state="errored",i(r);else if(a){o.map._refreshExpiredTiles&&e.setExpiryData(a),delete a.cacheControl,delete a.expires;var n=o.map.painter.context,s=n.gl;e.texture=o.map.painter.getTileTexture(a.width),e.texture?e.texture.update(a,{useMipmap:!0}):(e.texture=new t.Texture(n,a,s.RGBA,{useMipmap:!0}),e.texture.bind(s.LINEAR,s.CLAMP_TO_EDGE,s.LINEAR_MIPMAP_NEAREST),n.extTextureFilterAnisotropic&&s.texParameterf(s.TEXTURE_2D,n.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,n.extTextureFilterAnisotropicMax)),e.state="loaded",t.cacheEntryPossiblyAdded(o.dispatcher),i(null);}}));},i.prototype.abortTile=function(t,e){t.request&&(t.request.cancel(),delete t.request),e();},i.prototype.unloadTile=function(t,e){t.texture&&this.map.painter.saveTileTexture(t.texture),e();},i.prototype.hasTransition=function(){return !1},i}(t.Evented),z=function(e){function i(i,o,r,a){e.call(this,i,o,r,a),this.type="raster-dem",this.maxzoom=22,this._options=t.extend({type:"raster-dem"},o),this.encoding=o.encoding||"mapbox";}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.serialize=function(){return {type:"raster-dem",url:this.url,tileSize:this.tileSize,tiles:this.tiles,bounds:this.bounds,encoding:this.encoding}},i.prototype.loadTile=function(e,i){var o=this.map._requestManager.normalizeTileURL(e.tileID.canonical.url(this.tiles,this.scheme),this.tileSize);function r(t,o){t&&(e.state="errored",i(t)),o&&(e.dem=o,e.needsHillshadePrepare=!0,e.state="loaded",i(null));}e.request=t.getImage(this.map._requestManager.transformRequest(o,t.ResourceType.Tile),function(o,a){if(delete e.request,e.aborted)e.state="unloaded",i(null);else if(o)e.state="errored",i(o);else if(a){this.map._refreshExpiredTiles&&e.setExpiryData(a),delete a.cacheControl,delete a.expires;var n=t.window.ImageBitmap&&a instanceof t.window.ImageBitmap&&t.offscreenCanvasSupported()?a:t.browser.getImageData(a,1),s={uid:e.uid,coord:e.tileID,source:this.id,rawImageData:n,encoding:this.encoding};e.actor&&"expired"!==e.state||(e.actor=this.dispatcher.getActor(),e.actor.send("loadDEMTile",s,r.bind(this)));}}.bind(this)),e.neighboringTiles=this._getNeighboringTiles(e.tileID);},i.prototype._getNeighboringTiles=function(e){var i=e.canonical,o=Math.pow(2,i.z),r=(i.x-1+o)%o,a=0===i.x?e.wrap-1:e.wrap,n=(i.x+1+o)%o,s=i.x+1===o?e.wrap+1:e.wrap,l={};return l[new t.OverscaledTileID(e.overscaledZ,a,i.z,r,i.y).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,i.z,n,i.y).key]={backfilled:!1},i.y>0&&(l[new t.OverscaledTileID(e.overscaledZ,a,i.z,r,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,i.z,n,i.y-1).key]={backfilled:!1}),i.y+1<o&&(l[new t.OverscaledTileID(e.overscaledZ,a,i.z,r,i.y+1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,e.wrap,i.z,i.x,i.y+1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,i.z,n,i.y+1).key]={backfilled:!1}),l},i.prototype.unloadTile=function(t){t.demTexture&&this.map.painter.saveTileTexture(t.demTexture),t.fbo&&(t.fbo.destroy(),delete t.fbo),t.dem&&delete t.dem,delete t.neighboringTiles,t.state="unloaded",t.actor&&t.actor.send("removeDEMTile",{uid:t.uid,source:this.id});},i}(C),D=function(e){function i(i,o,r,a){e.call(this),this.id=i,this.type="geojson",this.minzoom=0,this.maxzoom=18,this.tileSize=512,this.isTileClipped=!0,this.reparseOverscaled=!0,this._removed=!1,this._loaded=!1,this.actor=r.getActor(),this.setEventedParent(a),this._data=o.data,this._options=t.extend({},o),this._collectResourceTiming=o.collectResourceTiming,this._resourceTiming=[],void 0!==o.maxzoom&&(this.maxzoom=o.maxzoom),o.type&&(this.type=o.type),o.attribution&&(this.attribution=o.attribution),this.promoteId=o.promoteId;var n=t.EXTENT/this.tileSize;this.workerOptions=t.extend({source:this.id,cluster:o.cluster||!1,geojsonVtOptions:{buffer:(void 0!==o.buffer?o.buffer:128)*n,tolerance:(void 0!==o.tolerance?o.tolerance:.375)*n,extent:t.EXTENT,maxZoom:this.maxzoom,lineMetrics:o.lineMetrics||!1,generateId:o.generateId||!1},superclusterOptions:{maxZoom:void 0!==o.clusterMaxZoom?Math.min(o.clusterMaxZoom,this.maxzoom-1):this.maxzoom-1,extent:t.EXTENT,radius:(o.clusterRadius||50)*n,log:!1,generateId:o.generateId||!1},clusterProperties:o.clusterProperties},o.workerOptions);}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.load=function(){var e=this;this.fire(new t.Event("dataloading",{dataType:"source"})),this._updateWorkerData((function(i){if(i)e.fire(new t.ErrorEvent(i));else {var o={dataType:"source",sourceDataType:"metadata"};e._collectResourceTiming&&e._resourceTiming&&e._resourceTiming.length>0&&(o.resourceTiming=e._resourceTiming,e._resourceTiming=[]),e.fire(new t.Event("data",o));}}));},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.setData=function(e){var i=this;return this._data=e,this.fire(new t.Event("dataloading",{dataType:"source"})),this._updateWorkerData((function(e){if(e)i.fire(new t.ErrorEvent(e));else {var o={dataType:"source",sourceDataType:"content"};i._collectResourceTiming&&i._resourceTiming&&i._resourceTiming.length>0&&(o.resourceTiming=i._resourceTiming,i._resourceTiming=[]),i.fire(new t.Event("data",o));}})),this},i.prototype.getClusterExpansionZoom=function(t,e){return this.actor.send("geojson.getClusterExpansionZoom",{clusterId:t,source:this.id},e),this},i.prototype.getClusterChildren=function(t,e){return this.actor.send("geojson.getClusterChildren",{clusterId:t,source:this.id},e),this},i.prototype.getClusterLeaves=function(t,e,i,o){return this.actor.send("geojson.getClusterLeaves",{source:this.id,clusterId:t,limit:e,offset:i},o),this},i.prototype._updateWorkerData=function(e){var i=this;this._loaded=!1;var o=t.extend({},this.workerOptions),r=this._data;"string"==typeof r?(o.request=this.map._requestManager.transformRequest(t.browser.resolveURL(r),t.ResourceType.Source),o.request.collectResourceTiming=this._collectResourceTiming):o.data=JSON.stringify(r),this.actor.send(this.type+".loadData",o,(function(t,r){i._removed||r&&r.abandoned||(i._loaded=!0,r&&r.resourceTiming&&r.resourceTiming[i.id]&&(i._resourceTiming=r.resourceTiming[i.id].slice(0)),i.actor.send(i.type+".coalesce",{source:o.source},null),e(t));}));},i.prototype.loaded=function(){return this._loaded},i.prototype.loadTile=function(e,i){var o=this,r=e.actor?"reloadTile":"loadTile";e.actor=this.actor,e.request=this.actor.send(r,{type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:t.browser.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId},(function(t,a){return delete e.request,e.unloadVectorData(),e.aborted?i(null):t?i(t):(e.loadVectorData(a,o.map.painter,"reloadTile"===r),i(null))}));},i.prototype.abortTile=function(t){t.request&&(t.request.cancel(),delete t.request),t.aborted=!0;},i.prototype.unloadTile=function(t){t.unloadVectorData(),this.actor.send("removeTile",{uid:t.uid,type:this.type,source:this.id});},i.prototype.onRemove=function(){this._removed=!0,this.actor.send("removeSource",{type:this.type,source:this.id});},i.prototype.serialize=function(){return t.extend({},this._options,{type:this.type,data:this._data})},i.prototype.hasTransition=function(){return !1},i}(t.Evented),M=t.createLayout([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]),L=function(e){function i(t,i,o,r){e.call(this),this.id=t,this.dispatcher=o,this.coordinates=i.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(r),this.options=i;}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.load=function(e,i){var o=this;this._loaded=!1,this.fire(new t.Event("dataloading",{dataType:"source"})),this.url=this.options.url,t.getImage(this.map._requestManager.transformRequest(this.url,t.ResourceType.Image),(function(r,a){o._loaded=!0,r?o.fire(new t.ErrorEvent(r)):a&&(o.image=a,e&&(o.coordinates=e),i&&i(),o._finishLoading());}));},i.prototype.loaded=function(){return this._loaded},i.prototype.updateImage=function(t){var e=this;return this.image&&t.url?(this.options.url=t.url,this.load(t.coordinates,(function(){e.texture=null;})),this):this},i.prototype._finishLoading=function(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})));},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.setCoordinates=function(e){var i=this;this.coordinates=e;var o=e.map(t.MercatorCoordinate.fromLngLat);this.tileID=function(e){for(var i=1/0,o=1/0,r=-1/0,a=-1/0,n=0,s=e;n<s.length;n+=1){var l=s[n];i=Math.min(i,l.x),o=Math.min(o,l.y),r=Math.max(r,l.x),a=Math.max(a,l.y);}var c=Math.max(r-i,a-o),u=Math.max(0,Math.floor(-Math.log(c)/Math.LN2)),h=Math.pow(2,u);return new t.CanonicalTileID(u,Math.floor((i+r)/2*h),Math.floor((o+a)/2*h))}(o),this.minzoom=this.maxzoom=this.tileID.z;var r=o.map((function(t){return i.tileID.getTilePoint(t)._round()}));return this._boundsArray=new t.StructArrayLayout4i8,this._boundsArray.emplaceBack(r[0].x,r[0].y,0,0),this._boundsArray.emplaceBack(r[1].x,r[1].y,t.EXTENT,0),this._boundsArray.emplaceBack(r[3].x,r[3].y,0,t.EXTENT),this._boundsArray.emplaceBack(r[2].x,r[2].y,t.EXTENT,t.EXTENT),this.boundsBuffer&&(this.boundsBuffer.destroy(),delete this.boundsBuffer),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"content"})),this},i.prototype.prepare=function(){if(0!==Object.keys(this.tiles).length&&this.image){var e=this.map.painter.context,i=e.gl;for(var o in this.boundsBuffer||(this.boundsBuffer=e.createVertexBuffer(this._boundsArray,M.members)),this.boundsSegments||(this.boundsSegments=t.SegmentVector.simpleSegment(0,0,4,2)),this.texture||(this.texture=new t.Texture(e,this.image,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE)),this.tiles){var r=this.tiles[o];"loaded"!==r.state&&(r.state="loaded",r.texture=this.texture);}}},i.prototype.loadTile=function(t,e){this.tileID&&this.tileID.equals(t.tileID.canonical)?(this.tiles[String(t.tileID.wrap)]=t,t.buckets={},e(null)):(t.state="errored",e(null));},i.prototype.serialize=function(){return {type:"image",url:this.options.url,coordinates:this.coordinates}},i.prototype.hasTransition=function(){return !1},i}(t.Evented),A=function(e){function i(t,i,o,r){e.call(this,t,i,o,r),this.roundZoom=!0,this.type="video",this.options=i;}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.load=function(){var e=this;this._loaded=!1;var i=this.options;this.urls=[];for(var o=0,r=i.urls;o<r.length;o+=1)this.urls.push(this.map._requestManager.transformRequest(r[o],t.ResourceType.Source).url);t.getVideo(this.urls,(function(i,o){e._loaded=!0,i?e.fire(new t.ErrorEvent(i)):o&&(e.video=o,e.video.loop=!0,e.video.addEventListener("playing",(function(){e.map.triggerRepaint();})),e.map&&e.video.play(),e._finishLoading());}));},i.prototype.pause=function(){this.video&&this.video.pause();},i.prototype.play=function(){this.video&&this.video.play();},i.prototype.seek=function(e){if(this.video){var i=this.video.seekable;e<i.start(0)||e>i.end(0)?this.fire(new t.ErrorEvent(new t.ValidationError("sources."+this.id,null,"Playback for this video can be set only between the "+i.start(0)+" and "+i.end(0)+"-second mark."))):this.video.currentTime=e;}},i.prototype.getVideo=function(){return this.video},i.prototype.onAdd=function(t){this.map||(this.map=t,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));},i.prototype.prepare=function(){if(!(0===Object.keys(this.tiles).length||this.video.readyState<2)){var e=this.map.painter.context,i=e.gl;for(var o in this.boundsBuffer||(this.boundsBuffer=e.createVertexBuffer(this._boundsArray,M.members)),this.boundsSegments||(this.boundsSegments=t.SegmentVector.simpleSegment(0,0,4,2)),this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new t.Texture(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE)),this.tiles){var r=this.tiles[o];"loaded"!==r.state&&(r.state="loaded",r.texture=this.texture);}}},i.prototype.serialize=function(){return {type:"video",urls:this.urls,coordinates:this.coordinates}},i.prototype.hasTransition=function(){return this.video&&!this.video.paused},i}(L),R=function(e){function i(i,o,r,a){e.call(this,i,o,r,a),o.coordinates?Array.isArray(o.coordinates)&&4===o.coordinates.length&&!o.coordinates.some((function(t){return !Array.isArray(t)||2!==t.length||t.some((function(t){return "number"!=typeof t}))}))||this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'missing required property "coordinates"'))),o.animate&&"boolean"!=typeof o.animate&&this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'optional "animate" property must be a boolean value'))),o.canvas?"string"==typeof o.canvas||o.canvas instanceof t.window.HTMLCanvasElement||this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'missing required property "canvas"'))),this.options=o,this.animate=void 0===o.animate||o.animate;}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.load=function(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof t.window.HTMLCanvasElement?this.options.canvas:t.window.document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.ErrorEvent(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());},i.prototype.getCanvas=function(){return this.canvas},i.prototype.onAdd=function(t){this.map=t,this.load(),this.canvas&&this.animate&&this.play();},i.prototype.onRemove=function(){this.pause();},i.prototype.prepare=function(){var e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),!this._hasInvalidDimensions()&&0!==Object.keys(this.tiles).length){var i=this.map.painter.context,o=i.gl;for(var r in this.boundsBuffer||(this.boundsBuffer=i.createVertexBuffer(this._boundsArray,M.members)),this.boundsSegments||(this.boundsSegments=t.SegmentVector.simpleSegment(0,0,4,2)),this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new t.Texture(i,this.canvas,o.RGBA,{premultiply:!0}),this.tiles){var a=this.tiles[r];"loaded"!==a.state&&(a.state="loaded",a.texture=this.texture);}}},i.prototype.serialize=function(){return {type:"canvas",coordinates:this.coordinates}},i.prototype.hasTransition=function(){return this._playing},i.prototype._hasInvalidDimensions=function(){for(var t=0,e=[this.canvas.width,this.canvas.height];t<e.length;t+=1){var i=e[t];if(isNaN(i)||i<=0)return !0}return !1},i}(L),k={vector:S,raster:C,"raster-dem":z,geojson:D,video:A,image:L,canvas:R};function B(e,i){var o=t.identity([]);return t.translate(o,o,[1,1,0]),t.scale(o,o,[.5*e.width,.5*e.height,1]),t.multiply(o,o,e.calculatePosMatrix(i.toUnwrapped()))}function O(t,e,i,o,r,a){var n=function(t,e,i){if(t)for(var o=0,r=t;o<r.length;o+=1){var a=e[r[o]];if(a&&a.source===i&&"fill-extrusion"===a.type)return !0}else for(var n in e){var s=e[n];if(s.source===i&&"fill-extrusion"===s.type)return !0}return !1}(r&&r.layers,e,t.id),s=a.maxPitchScaleFactor(),l=t.tilesIn(o,s,n);l.sort(F);for(var c=[],u=0,h=l;u<h.length;u+=1){var p=h[u];c.push({wrappedTileID:p.tileID.wrapped().key,queryResults:p.tile.queryRenderedFeatures(e,i,t._state,p.queryGeometry,p.cameraQueryGeometry,p.scale,r,a,s,B(t.transform,p.tileID))});}var d=function(t){for(var e={},i={},o=0,r=t;o<r.length;o+=1){var a=r[o],n=a.queryResults,s=a.wrappedTileID,l=i[s]=i[s]||{};for(var c in n)for(var u=n[c],h=l[c]=l[c]||{},p=e[c]=e[c]||[],d=0,_=u;d<_.length;d+=1){var f=_[d];h[f.featureIndex]||(h[f.featureIndex]=!0,p.push(f));}}return e}(c);for(var _ in d)d[_].forEach((function(e){var i=e.feature,o=t.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=o;}));return d}function F(t,e){var i=t.tileID,o=e.tileID;return i.overscaledZ-o.overscaledZ||i.canonical.y-o.canonical.y||i.wrap-o.wrap||i.canonical.x-o.canonical.x}var U=function(t,e){this.max=t,this.onRemove=e,this.reset();};U.prototype.reset=function(){for(var t in this.data)for(var e=0,i=this.data[t];e<i.length;e+=1){var o=i[e];o.timeout&&clearTimeout(o.timeout),this.onRemove(o.value);}return this.data={},this.order=[],this},U.prototype.add=function(t,e,i){var o=this,r=t.wrapped().key;void 0===this.data[r]&&(this.data[r]=[]);var a={value:e,timeout:void 0};if(void 0!==i&&(a.timeout=setTimeout((function(){o.remove(t,a);}),i)),this.data[r].push(a),this.order.push(r),this.order.length>this.max){var n=this._getAndRemoveByKey(this.order[0]);n&&this.onRemove(n);}return this},U.prototype.has=function(t){return t.wrapped().key in this.data},U.prototype.getAndRemove=function(t){return this.has(t)?this._getAndRemoveByKey(t.wrapped().key):null},U.prototype._getAndRemoveByKey=function(t){var e=this.data[t].shift();return e.timeout&&clearTimeout(e.timeout),0===this.data[t].length&&delete this.data[t],this.order.splice(this.order.indexOf(t),1),e.value},U.prototype.getByKey=function(t){var e=this.data[t];return e?e[0].value:null},U.prototype.get=function(t){return this.has(t)?this.data[t.wrapped().key][0].value:null},U.prototype.remove=function(t,e){if(!this.has(t))return this;var i=t.wrapped().key,o=void 0===e?0:this.data[i].indexOf(e),r=this.data[i][o];return this.data[i].splice(o,1),r.timeout&&clearTimeout(r.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(r.value),this.order.splice(this.order.indexOf(i),1),this},U.prototype.setMaxSize=function(t){for(this.max=t;this.order.length>this.max;){var e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this},U.prototype.filter=function(t){var e=[];for(var i in this.data)for(var o=0,r=this.data[i];o<r.length;o+=1){var a=r[o];t(a.value)||e.push(a);}for(var n=0,s=e;n<s.length;n+=1){var l=s[n];this.remove(l.value.tileID,l);}};var N=function(t,e,i){this.context=t;var o=t.gl;this.buffer=o.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),t.bindElementBuffer.set(this.buffer),o.bufferData(o.ELEMENT_ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer;};N.prototype.bind=function(){this.context.bindElementBuffer.set(this.buffer);},N.prototype.updateData=function(t){var e=this.context.gl;this.context.unbindVAO(),this.bind(),e.bufferSubData(e.ELEMENT_ARRAY_BUFFER,0,t.arrayBuffer);},N.prototype.destroy=function(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);};var Z={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"},j=function(t,e,i,o){this.length=e.length,this.attributes=i,this.itemSize=e.bytesPerElement,this.dynamicDraw=o,this.context=t;var r=t.gl;this.buffer=r.createBuffer(),t.bindVertexBuffer.set(this.buffer),r.bufferData(r.ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer;};j.prototype.bind=function(){this.context.bindVertexBuffer.set(this.buffer);},j.prototype.updateData=function(t){var e=this.context.gl;this.bind(),e.bufferSubData(e.ARRAY_BUFFER,0,t.arrayBuffer);},j.prototype.enableAttributes=function(t,e){for(var i=0;i<this.attributes.length;i++){var o=e.attributes[this.attributes[i].name];void 0!==o&&t.enableVertexAttribArray(o);}},j.prototype.setVertexAttribPointers=function(t,e,i){for(var o=0;o<this.attributes.length;o++){var r=this.attributes[o],a=e.attributes[r.name];void 0!==a&&t.vertexAttribPointer(a,r.components,t[Z[r.type]],!1,this.itemSize,r.offset+this.itemSize*(i||0));}},j.prototype.destroy=function(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);};var q=function(t){this.gl=t.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1;};q.prototype.get=function(){return this.current},q.prototype.set=function(t){},q.prototype.getDefault=function(){return this.default},q.prototype.setDefault=function(){this.set(this.default);};var V=function(e){function i(){e.apply(this,arguments);}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.getDefault=function(){return t.Color.transparent},i.prototype.set=function(t){var e=this.current;(t.r!==e.r||t.g!==e.g||t.b!==e.b||t.a!==e.a||this.dirty)&&(this.gl.clearColor(t.r,t.g,t.b,t.a),this.current=t,this.dirty=!1);},i}(q),G=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return 1},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.clearDepth(t),this.current=t,this.dirty=!1);},e}(q),W=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return 0},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.clearStencil(t),this.current=t,this.dirty=!1);},e}(q),X=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return [!0,!0,!0,!0]},e.prototype.set=function(t){var e=this.current;(t[0]!==e[0]||t[1]!==e[1]||t[2]!==e[2]||t[3]!==e[3]||this.dirty)&&(this.gl.colorMask(t[0],t[1],t[2],t[3]),this.current=t,this.dirty=!1);},e}(q),H=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return !0},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.depthMask(t),this.current=t,this.dirty=!1);},e}(q),K=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return 255},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.stencilMask(t),this.current=t,this.dirty=!1);},e}(q),Y=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return {func:this.gl.ALWAYS,ref:0,mask:255}},e.prototype.set=function(t){var e=this.current;(t.func!==e.func||t.ref!==e.ref||t.mask!==e.mask||this.dirty)&&(this.gl.stencilFunc(t.func,t.ref,t.mask),this.current=t,this.dirty=!1);},e}(q),J=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){var t=this.gl;return [t.KEEP,t.KEEP,t.KEEP]},e.prototype.set=function(t){var e=this.current;(t[0]!==e[0]||t[1]!==e[1]||t[2]!==e[2]||this.dirty)&&(this.gl.stencilOp(t[0],t[1],t[2]),this.current=t,this.dirty=!1);},e}(q),Q=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;t?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this.current=t,this.dirty=!1;}},e}(q),$=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return [0,1]},e.prototype.set=function(t){var e=this.current;(t[0]!==e[0]||t[1]!==e[1]||this.dirty)&&(this.gl.depthRange(t[0],t[1]),this.current=t,this.dirty=!1);},e}(q),tt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;t?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this.current=t,this.dirty=!1;}},e}(q),et=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return this.gl.LESS},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.depthFunc(t),this.current=t,this.dirty=!1);},e}(q),it=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;t?e.enable(e.BLEND):e.disable(e.BLEND),this.current=t,this.dirty=!1;}},e}(q),ot=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){var t=this.gl;return [t.ONE,t.ZERO]},e.prototype.set=function(t){var e=this.current;(t[0]!==e[0]||t[1]!==e[1]||this.dirty)&&(this.gl.blendFunc(t[0],t[1]),this.current=t,this.dirty=!1);},e}(q),rt=function(e){function i(){e.apply(this,arguments);}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.getDefault=function(){return t.Color.transparent},i.prototype.set=function(t){var e=this.current;(t.r!==e.r||t.g!==e.g||t.b!==e.b||t.a!==e.a||this.dirty)&&(this.gl.blendColor(t.r,t.g,t.b,t.a),this.current=t,this.dirty=!1);},i}(q),at=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return this.gl.FUNC_ADD},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.blendEquation(t),this.current=t,this.dirty=!1);},e}(q),nt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;t?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this.current=t,this.dirty=!1;}},e}(q),st=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return this.gl.BACK},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.cullFace(t),this.current=t,this.dirty=!1);},e}(q),lt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return this.gl.CCW},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.frontFace(t),this.current=t,this.dirty=!1);},e}(q),ct=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.useProgram(t),this.current=t,this.dirty=!1);},e}(q),ut=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return this.gl.TEXTURE0},e.prototype.set=function(t){(t!==this.current||this.dirty)&&(this.gl.activeTexture(t),this.current=t,this.dirty=!1);},e}(q),ht=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){var t=this.gl;return [0,0,t.drawingBufferWidth,t.drawingBufferHeight]},e.prototype.set=function(t){var e=this.current;(t[0]!==e[0]||t[1]!==e[1]||t[2]!==e[2]||t[3]!==e[3]||this.dirty)&&(this.gl.viewport(t[0],t[1],t[2],t[3]),this.current=t,this.dirty=!1);},e}(q),pt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,t),this.current=t,this.dirty=!1;}},e}(q),dt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.bindRenderbuffer(e.RENDERBUFFER,t),this.current=t,this.dirty=!1;}},e}(q),_t=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.bindTexture(e.TEXTURE_2D,t),this.current=t,this.dirty=!1;}},e}(q),ft=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.bindBuffer(e.ARRAY_BUFFER,t),this.current=t,this.dirty=!1;}},e}(q),mt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){var e=this.gl;e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t),this.current=t,this.dirty=!1;},e}(q),gt=function(t){function e(e){t.call(this,e),this.vao=e.extVertexArrayObject;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return null},e.prototype.set=function(t){this.vao&&(t!==this.current||this.dirty)&&(this.vao.bindVertexArrayOES(t),this.current=t,this.dirty=!1);},e}(q),vt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return 4},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.pixelStorei(e.UNPACK_ALIGNMENT,t),this.current=t,this.dirty=!1;}},e}(q),yt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t),this.current=t,this.dirty=!1;}},e}(q),xt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return !1},e.prototype.set=function(t){if(t!==this.current||this.dirty){var e=this.gl;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,t),this.current=t,this.dirty=!1;}},e}(q),bt=function(t){function e(e,i){t.call(this,e),this.context=e,this.parent=i;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getDefault=function(){return null},e}(q),wt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.setDirty=function(){this.dirty=!0;},e.prototype.set=function(t){if(t!==this.current||this.dirty){this.context.bindFramebuffer.set(this.parent);var e=this.gl;e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.current=t,this.dirty=!1;}},e}(bt),Tt=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.set=function(t){if(t!==this.current||this.dirty){this.context.bindFramebuffer.set(this.parent);var e=this.gl;e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t),this.current=t,this.dirty=!1;}},e}(bt),Et=function(t,e,i,o){this.context=t,this.width=e,this.height=i;var r=this.framebuffer=t.gl.createFramebuffer();this.colorAttachment=new wt(t,r),o&&(this.depthAttachment=new Tt(t,r));};Et.prototype.destroy=function(){var t=this.context.gl,e=this.colorAttachment.get();if(e&&t.deleteTexture(e),this.depthAttachment){var i=this.depthAttachment.get();i&&t.deleteRenderbuffer(i);}t.deleteFramebuffer(this.framebuffer);};var It=function(t,e,i){this.func=t,this.mask=e,this.range=i;};It.ReadOnly=!1,It.ReadWrite=!0,It.disabled=new It(519,It.ReadOnly,[0,1]);var Pt=function(t,e,i,o,r,a){this.test=t,this.ref=e,this.mask=i,this.fail=o,this.depthFail=r,this.pass=a;};Pt.disabled=new Pt({func:519,mask:0},0,0,7680,7680,7680);var St=function(t,e,i){this.blendFunction=t,this.blendColor=e,this.mask=i;};St.disabled=new St(St.Replace=[1,0],t.Color.transparent,[!1,!1,!1,!1]),St.unblended=new St(St.Replace,t.Color.transparent,[!0,!0,!0,!0]),St.alphaBlended=new St([1,771],t.Color.transparent,[!0,!0,!0,!0]);var Ct=function(t,e,i){this.enable=t,this.mode=e,this.frontFace=i;};Ct.disabled=new Ct(!1,1029,2305),Ct.backCCW=new Ct(!0,1029,2305);var zt=function(t){this.gl=t,this.extVertexArrayObject=this.gl.getExtension("OES_vertex_array_object"),this.clearColor=new V(this),this.clearDepth=new G(this),this.clearStencil=new W(this),this.colorMask=new X(this),this.depthMask=new H(this),this.stencilMask=new K(this),this.stencilFunc=new Y(this),this.stencilOp=new J(this),this.stencilTest=new Q(this),this.depthRange=new $(this),this.depthTest=new tt(this),this.depthFunc=new et(this),this.blend=new it(this),this.blendFunc=new ot(this),this.blendColor=new rt(this),this.blendEquation=new at(this),this.cullFace=new nt(this),this.cullFaceSide=new st(this),this.frontFace=new lt(this),this.program=new ct(this),this.activeTexture=new ut(this),this.viewport=new ht(this),this.bindFramebuffer=new pt(this),this.bindRenderbuffer=new dt(this),this.bindTexture=new _t(this),this.bindVertexBuffer=new ft(this),this.bindElementBuffer=new mt(this),this.bindVertexArrayOES=this.extVertexArrayObject&&new gt(this),this.pixelStoreUnpack=new vt(this),this.pixelStoreUnpackPremultiplyAlpha=new yt(this),this.pixelStoreUnpackFlipY=new xt(this),this.extTextureFilterAnisotropic=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=t.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)),this.extTextureHalfFloat=t.getExtension("OES_texture_half_float"),this.extTextureHalfFloat&&(t.getExtension("OES_texture_half_float_linear"),this.extRenderToTextureHalfFloat=t.getExtension("EXT_color_buffer_half_float")),this.extTimerQuery=t.getExtension("EXT_disjoint_timer_query");};zt.prototype.setDefault=function(){this.unbindVAO(),this.clearColor.setDefault(),this.clearDepth.setDefault(),this.clearStencil.setDefault(),this.colorMask.setDefault(),this.depthMask.setDefault(),this.stencilMask.setDefault(),this.stencilFunc.setDefault(),this.stencilOp.setDefault(),this.stencilTest.setDefault(),this.depthRange.setDefault(),this.depthTest.setDefault(),this.depthFunc.setDefault(),this.blend.setDefault(),this.blendFunc.setDefault(),this.blendColor.setDefault(),this.blendEquation.setDefault(),this.cullFace.setDefault(),this.cullFaceSide.setDefault(),this.frontFace.setDefault(),this.program.setDefault(),this.activeTexture.setDefault(),this.bindFramebuffer.setDefault(),this.pixelStoreUnpack.setDefault(),this.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.pixelStoreUnpackFlipY.setDefault();},zt.prototype.setDirty=function(){this.clearColor.dirty=!0,this.clearDepth.dirty=!0,this.clearStencil.dirty=!0,this.colorMask.dirty=!0,this.depthMask.dirty=!0,this.stencilMask.dirty=!0,this.stencilFunc.dirty=!0,this.stencilOp.dirty=!0,this.stencilTest.dirty=!0,this.depthRange.dirty=!0,this.depthTest.dirty=!0,this.depthFunc.dirty=!0,this.blend.dirty=!0,this.blendFunc.dirty=!0,this.blendColor.dirty=!0,this.blendEquation.dirty=!0,this.cullFace.dirty=!0,this.cullFaceSide.dirty=!0,this.frontFace.dirty=!0,this.program.dirty=!0,this.activeTexture.dirty=!0,this.viewport.dirty=!0,this.bindFramebuffer.dirty=!0,this.bindRenderbuffer.dirty=!0,this.bindTexture.dirty=!0,this.bindVertexBuffer.dirty=!0,this.bindElementBuffer.dirty=!0,this.extVertexArrayObject&&(this.bindVertexArrayOES.dirty=!0),this.pixelStoreUnpack.dirty=!0,this.pixelStoreUnpackPremultiplyAlpha.dirty=!0,this.pixelStoreUnpackFlipY.dirty=!0;},zt.prototype.createIndexBuffer=function(t,e){return new N(this,t,e)},zt.prototype.createVertexBuffer=function(t,e,i){return new j(this,t,e,i)},zt.prototype.createRenderbuffer=function(t,e,i){var o=this.gl,r=o.createRenderbuffer();return this.bindRenderbuffer.set(r),o.renderbufferStorage(o.RENDERBUFFER,t,e,i),this.bindRenderbuffer.set(null),r},zt.prototype.createFramebuffer=function(t,e,i){return new Et(this,t,e,i)},zt.prototype.clear=function(t){var e=t.color,i=t.depth,o=this.gl,r=0;e&&(r|=o.COLOR_BUFFER_BIT,this.clearColor.set(e),this.colorMask.set([!0,!0,!0,!0])),void 0!==i&&(r|=o.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(i),this.depthMask.set(!0)),o.clear(r);},zt.prototype.setCullFace=function(t){!1===t.enable?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(t.mode),this.frontFace.set(t.frontFace));},zt.prototype.setDepthMode=function(t){t.func!==this.gl.ALWAYS||t.mask?(this.depthTest.set(!0),this.depthFunc.set(t.func),this.depthMask.set(t.mask),this.depthRange.set(t.range)):this.depthTest.set(!1);},zt.prototype.setStencilMode=function(t){t.test.func!==this.gl.ALWAYS||t.mask?(this.stencilTest.set(!0),this.stencilMask.set(t.mask),this.stencilOp.set([t.fail,t.depthFail,t.pass]),this.stencilFunc.set({func:t.test.func,ref:t.ref,mask:t.test.mask})):this.stencilTest.set(!1);},zt.prototype.setColorMode=function(e){t.deepEqual(e.blendFunction,St.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(e.blendFunction),this.blendColor.set(e.blendColor)),this.colorMask.set(e.mask);},zt.prototype.unbindVAO=function(){this.extVertexArrayObject&&this.bindVertexArrayOES.set(null);};var Dt=function(e){function i(i,o,r){var a=this;e.call(this),this.id=i,this.dispatcher=r,this.on("data",(function(t){"source"===t.dataType&&"metadata"===t.sourceDataType&&(a._sourceLoaded=!0),a._sourceLoaded&&!a._paused&&"source"===t.dataType&&"content"===t.sourceDataType&&(a.reload(),a.transform&&a.update(a.transform));})),this.on("error",(function(){a._sourceErrored=!0;})),this._source=function(e,i,o,r){var a=new k[i.type](e,i,o,r);if(a.id!==e)throw new Error("Expected Source id to be "+e+" instead of "+a.id);return t.bindAll(["load","abort","unload","serialize","prepare"],a),a}(i,o,r,this),this._tiles={},this._cache=new U(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new t.SourceFeatureState;}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.onAdd=function(t){this.map=t,this._maxTileCacheSize=t?t._maxTileCacheSize:null,this._source&&this._source.onAdd&&this._source.onAdd(t);},i.prototype.onRemove=function(t){this._source&&this._source.onRemove&&this._source.onRemove(t);},i.prototype.loaded=function(){if(this._sourceErrored)return !0;if(!this._sourceLoaded)return !1;if(!this._source.loaded())return !1;for(var t in this._tiles){var e=this._tiles[t];if("loaded"!==e.state&&"errored"!==e.state)return !1}return !0},i.prototype.getSource=function(){return this._source},i.prototype.pause=function(){this._paused=!0;},i.prototype.resume=function(){if(this._paused){var t=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,t&&this.reload(),this.transform&&this.update(this.transform);}},i.prototype._loadTile=function(t,e){return this._source.loadTile(t,e)},i.prototype._unloadTile=function(t){if(this._source.unloadTile)return this._source.unloadTile(t,(function(){}))},i.prototype._abortTile=function(t){if(this._source.abortTile)return this._source.abortTile(t,(function(){}))},i.prototype.serialize=function(){return this._source.serialize()},i.prototype.prepare=function(t){for(var e in this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null),this._tiles){var i=this._tiles[e];i.upload(t),i.prepare(this.map.style.imageManager);}},i.prototype.getIds=function(){return t.values(this._tiles).map((function(t){return t.tileID})).sort(Mt).map((function(t){return t.key}))},i.prototype.getRenderableIds=function(e){var i=this,o=[];for(var r in this._tiles)this._isIdRenderable(r,e)&&o.push(this._tiles[r]);return e?o.sort((function(e,o){var r=e.tileID,a=o.tileID,n=new t.Point(r.canonical.x,r.canonical.y)._rotate(i.transform.angle),s=new t.Point(a.canonical.x,a.canonical.y)._rotate(i.transform.angle);return r.overscaledZ-a.overscaledZ||s.y-n.y||s.x-n.x})).map((function(t){return t.tileID.key})):o.map((function(t){return t.tileID})).sort(Mt).map((function(t){return t.key}))},i.prototype.hasRenderableParent=function(t){var e=this.findLoadedParent(t,0);return !!e&&this._isIdRenderable(e.tileID.key)},i.prototype._isIdRenderable=function(t,e){return this._tiles[t]&&this._tiles[t].hasData()&&!this._coveredTiles[t]&&(e||!this._tiles[t].holdingForFade())},i.prototype.reload=function(){if(this._paused)this._shouldReloadOnResume=!0;else for(var t in this._cache.reset(),this._tiles)"errored"!==this._tiles[t].state&&this._reloadTile(t,"reloading");},i.prototype._reloadTile=function(t,e){var i=this._tiles[t];i&&("loading"!==i.state&&(i.state=e),this._loadTile(i,this._tileLoaded.bind(this,i,t,e)));},i.prototype._tileLoaded=function(e,i,o,r){if(r)return e.state="errored",void(404!==r.status?this._source.fire(new t.ErrorEvent(r,{tile:e})):this.update(this.transform));e.timeAdded=t.browser.now(),"expired"===o&&(e.refreshedUponExpiration=!0),this._setTileReloadTimer(i,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._state.initializeTileState(e,this.map?this.map.painter:null),this._source.fire(new t.Event("data",{dataType:"source",tile:e,coord:e.tileID}));},i.prototype._backfillDEM=function(t){for(var e=this.getRenderableIds(),i=0;i<e.length;i++){var o=e[i];if(t.neighboringTiles&&t.neighboringTiles[o]){var r=this.getTileByID(o);a(t,r),a(r,t);}}function a(t,e){t.needsHillshadePrepare=!0;var i=e.tileID.canonical.x-t.tileID.canonical.x,o=e.tileID.canonical.y-t.tileID.canonical.y,r=Math.pow(2,t.tileID.canonical.z),a=e.tileID.key;0===i&&0===o||Math.abs(o)>1||(Math.abs(i)>1&&(1===Math.abs(i+r)?i+=r:1===Math.abs(i-r)&&(i-=r)),e.dem&&t.dem&&(t.dem.backfillBorder(e.dem,i,o),t.neighboringTiles&&t.neighboringTiles[a]&&(t.neighboringTiles[a].backfilled=!0)));}},i.prototype.getTile=function(t){return this.getTileByID(t.key)},i.prototype.getTileByID=function(t){return this._tiles[t]},i.prototype._retainLoadedChildren=function(t,e,i,o){for(var r in this._tiles){var a=this._tiles[r];if(!(o[r]||!a.hasData()||a.tileID.overscaledZ<=e||a.tileID.overscaledZ>i)){for(var n=a.tileID;a&&a.tileID.overscaledZ>e+1;){var s=a.tileID.scaledTo(a.tileID.overscaledZ-1);(a=this._tiles[s.key])&&a.hasData()&&(n=s);}for(var l=n;l.overscaledZ>e;)if(t[(l=l.scaledTo(l.overscaledZ-1)).key]){o[n.key]=n;break}}}},i.prototype.findLoadedParent=function(t,e){if(t.key in this._loadedParentTiles){var i=this._loadedParentTiles[t.key];return i&&i.tileID.overscaledZ>=e?i:null}for(var o=t.overscaledZ-1;o>=e;o--){var r=t.scaledTo(o),a=this._getLoadedTile(r);if(a)return a}},i.prototype._getLoadedTile=function(t){var e=this._tiles[t.key];return e&&e.hasData()?e:this._cache.getByKey(t.wrapped().key)},i.prototype.updateCacheSize=function(t){var e=Math.ceil(t.width/this._source.tileSize)+1,i=Math.ceil(t.height/this._source.tileSize)+1,o=Math.floor(e*i*5),r="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,o):o;this._cache.setMaxSize(r);},i.prototype.handleWrapJump=function(t){var e=Math.round((t-(void 0===this._prevLng?t:this._prevLng))/360);if(this._prevLng=t,e){var i={};for(var o in this._tiles){var r=this._tiles[o];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+e),i[r.tileID.key]=r;}for(var a in this._tiles=i,this._timers)clearTimeout(this._timers[a]),delete this._timers[a];for(var n in this._tiles)this._setTileReloadTimer(n,this._tiles[n]);}},i.prototype.update=function(e){var o=this;if(this.transform=e,this._sourceLoaded&&!this._paused){var r;this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used?this._source.tileID?r=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((function(e){return new t.OverscaledTileID(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y)})):(r=e.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}),this._source.hasTile&&(r=r.filter((function(t){return o._source.hasTile(t)})))):r=[];var a=e.coveringZoomLevel(this._source),n=Math.max(a-i.maxOverzooming,this._source.minzoom),s=Math.max(a+i.maxUnderzooming,this._source.minzoom),l=this._updateRetainedTiles(r,a);if(Lt(this._source.type)){for(var c={},u={},h=0,p=Object.keys(l);h<p.length;h+=1){var d=p[h],_=l[d],f=this._tiles[d];if(f&&!(f.fadeEndTime&&f.fadeEndTime<=t.browser.now())){var m=this.findLoadedParent(_,n);m&&(this._addTile(m.tileID),c[m.tileID.key]=m.tileID),u[d]=_;}}for(var g in this._retainLoadedChildren(u,a,s,l),c)l[g]||(this._coveredTiles[g]=!0,l[g]=c[g]);}for(var v in l)this._tiles[v].clearFadeHold();for(var y=0,x=t.keysDifference(this._tiles,l);y<x.length;y+=1){var b=x[y],w=this._tiles[b];w.hasSymbolBuckets&&!w.holdingForFade()?w.setHoldDuration(this.map._fadeDuration):w.hasSymbolBuckets&&!w.symbolFadeFinished()||this._removeTile(b);}this._updateLoadedParentTileCache();}},i.prototype.releaseSymbolFadeTiles=function(){for(var t in this._tiles)this._tiles[t].holdingForFade()&&this._removeTile(t);},i.prototype._updateRetainedTiles=function(t,e){for(var o={},r={},a=Math.max(e-i.maxOverzooming,this._source.minzoom),n=Math.max(e+i.maxUnderzooming,this._source.minzoom),s={},l=0,c=t;l<c.length;l+=1){var u=c[l],h=this._addTile(u);o[u.key]=u,h.hasData()||e<this._source.maxzoom&&(s[u.key]=u);}this._retainLoadedChildren(s,e,n,o);for(var p=0,d=t;p<d.length;p+=1){var _=d[p],f=this._tiles[_.key];if(!f.hasData()){if(e+1>this._source.maxzoom){var m=_.children(this._source.maxzoom)[0],g=this.getTile(m);if(g&&g.hasData()){o[m.key]=m;continue}}else {var v=_.children(this._source.maxzoom);if(o[v[0].key]&&o[v[1].key]&&o[v[2].key]&&o[v[3].key])continue}for(var y=f.wasRequested(),x=_.overscaledZ-1;x>=a;--x){var b=_.scaledTo(x);if(r[b.key])break;if(r[b.key]=!0,!(f=this.getTile(b))&&y&&(f=this._addTile(b)),f&&(o[b.key]=b,y=f.wasRequested(),f.hasData()))break}}}return o},i.prototype._updateLoadedParentTileCache=function(){for(var t in this._loadedParentTiles={},this._tiles){for(var e=[],i=void 0,o=this._tiles[t].tileID;o.overscaledZ>0;){if(o.key in this._loadedParentTiles){i=this._loadedParentTiles[o.key];break}e.push(o.key);var r=o.scaledTo(o.overscaledZ-1);if(i=this._getLoadedTile(r))break;o=r;}for(var a=0,n=e;a<n.length;a+=1)this._loadedParentTiles[n[a]]=i;}},i.prototype._addTile=function(e){var i=this._tiles[e.key];if(i)return i;(i=this._cache.getAndRemove(e))&&(this._setTileReloadTimer(e.key,i),i.tileID=e,this._state.initializeTileState(i,this.map?this.map.painter:null),this._cacheTimers[e.key]&&(clearTimeout(this._cacheTimers[e.key]),delete this._cacheTimers[e.key],this._setTileReloadTimer(e.key,i)));var o=Boolean(i);return o||(i=new t.Tile(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,this._tileLoaded.bind(this,i,e.key,i.state))),i?(i.uses++,this._tiles[e.key]=i,o||this._source.fire(new t.Event("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i):null},i.prototype._setTileReloadTimer=function(t,e){var i=this;t in this._timers&&(clearTimeout(this._timers[t]),delete this._timers[t]);var o=e.getExpiryTimeout();o&&(this._timers[t]=setTimeout((function(){i._reloadTile(t,"expired"),delete i._timers[t];}),o));},i.prototype._removeTile=function(t){var e=this._tiles[t];e&&(e.uses--,delete this._tiles[t],this._timers[t]&&(clearTimeout(this._timers[t]),delete this._timers[t]),e.uses>0||(e.hasData()&&"reloading"!==e.state?this._cache.add(e.tileID,e,e.getExpiryTimeout()):(e.aborted=!0,this._abortTile(e),this._unloadTile(e))));},i.prototype.clearTiles=function(){for(var t in this._shouldReloadOnResume=!1,this._paused=!1,this._tiles)this._removeTile(t);this._cache.reset();},i.prototype.tilesIn=function(e,i,o){var r=this,a=[],n=this.transform;if(!n)return a;for(var s=o?n.getCameraQueryGeometry(e):e,l=e.map((function(t){return n.pointCoordinate(t)})),c=s.map((function(t){return n.pointCoordinate(t)})),u=this.getIds(),h=1/0,p=1/0,d=-1/0,_=-1/0,f=0,m=c;f<m.length;f+=1){var g=m[f];h=Math.min(h,g.x),p=Math.min(p,g.y),d=Math.max(d,g.x),_=Math.max(_,g.y);}for(var v=function(e){var o=r._tiles[u[e]];if(!o.holdingForFade()){var s=o.tileID,f=Math.pow(2,n.zoom-o.tileID.overscaledZ),m=i*o.queryPadding*t.EXTENT/o.tileSize/f,g=[s.getTilePoint(new t.MercatorCoordinate(h,p)),s.getTilePoint(new t.MercatorCoordinate(d,_))];if(g[0].x-m<t.EXTENT&&g[0].y-m<t.EXTENT&&g[1].x+m>=0&&g[1].y+m>=0){var v=l.map((function(t){return s.getTilePoint(t)})),y=c.map((function(t){return s.getTilePoint(t)}));a.push({tile:o,tileID:s,queryGeometry:v,cameraQueryGeometry:y,scale:f});}}},y=0;y<u.length;y++)v(y);return a},i.prototype.getVisibleCoordinates=function(t){for(var e=this,i=this.getRenderableIds(t).map((function(t){return e._tiles[t].tileID})),o=0,r=i;o<r.length;o+=1){var a=r[o];a.posMatrix=this.transform.calculatePosMatrix(a.toUnwrapped());}return i},i.prototype.hasTransition=function(){if(this._source.hasTransition())return !0;if(Lt(this._source.type))for(var e in this._tiles){var i=this._tiles[e];if(void 0!==i.fadeEndTime&&i.fadeEndTime>=t.browser.now())return !0}return !1},i.prototype.setFeatureState=function(t,e,i){this._state.updateState(t=t||"_geojsonTileLayer",e,i);},i.prototype.removeFeatureState=function(t,e,i){this._state.removeFeatureState(t=t||"_geojsonTileLayer",e,i);},i.prototype.getFeatureState=function(t,e){return this._state.getState(t=t||"_geojsonTileLayer",e)},i.prototype.setDependencies=function(t,e,i){var o=this._tiles[t];o&&o.setDependencies(e,i);},i.prototype.reloadTilesForDependencies=function(t,e){for(var i in this._tiles)this._tiles[i].hasDependency(t,e)&&this._reloadTile(i,"reloading");this._cache.filter((function(i){return !i.hasDependency(t,e)}));},i}(t.Evented);function Mt(t,e){var i=Math.abs(2*t.wrap)-+(t.wrap<0),o=Math.abs(2*e.wrap)-+(e.wrap<0);return t.overscaledZ-e.overscaledZ||o-i||e.canonical.y-t.canonical.y||e.canonical.x-t.canonical.x}function Lt(t){return "raster"===t||"image"===t||"video"===t}function At(){return new t.window.Worker(Wr.workerUrl)}Dt.maxOverzooming=10,Dt.maxUnderzooming=3;var Rt="mapboxgl_preloaded_worker_pool",kt=function(){this.active={};};kt.prototype.acquire=function(t){if(!this.workers)for(this.workers=[];this.workers.length<kt.workerCount;)this.workers.push(new At);return this.active[t]=!0,this.workers.slice()},kt.prototype.release=function(t){delete this.active[t],0===this.numActive()&&(this.workers.forEach((function(t){t.terminate();})),this.workers=null);},kt.prototype.isPreloaded=function(){return !!this.active[Rt]},kt.prototype.numActive=function(){return Object.keys(this.active).length};var Bt,Ot=Math.floor(t.browser.hardwareConcurrency/2);function Ft(){return Bt||(Bt=new kt),Bt}function Ut(e,i){var o={};for(var r in e)"ref"!==r&&(o[r]=e[r]);return t.refProperties.forEach((function(t){t in i&&(o[t]=i[t]);})),o}function Nt(t){t=t.slice();for(var e=Object.create(null),i=0;i<t.length;i++)e[t[i].id]=t[i];for(var o=0;o<t.length;o++)"ref"in t[o]&&(t[o]=Ut(t[o],e[t[o].ref]));return t}kt.workerCount=Math.max(Math.min(Ot,6),1);var Zt={setStyle:"setStyle",addLayer:"addLayer",removeLayer:"removeLayer",setPaintProperty:"setPaintProperty",setLayoutProperty:"setLayoutProperty",setFilter:"setFilter",addSource:"addSource",removeSource:"removeSource",setGeoJSONSourceData:"setGeoJSONSourceData",setLayerZoomRange:"setLayerZoomRange",setLayerProperty:"setLayerProperty",setCenter:"setCenter",setZoom:"setZoom",setBearing:"setBearing",setPitch:"setPitch",setSprite:"setSprite",setGlyphs:"setGlyphs",setTransition:"setTransition",setLight:"setLight"};function jt(t,e,i){i.push({command:Zt.addSource,args:[t,e[t]]});}function qt(t,e,i){e.push({command:Zt.removeSource,args:[t]}),i[t]=!0;}function Vt(t,e,i,o){qt(t,i,o),jt(t,e,i);}function Gt(e,i,o){var r;for(r in e[o])if(e[o].hasOwnProperty(r)&&"data"!==r&&!t.deepEqual(e[o][r],i[o][r]))return !1;for(r in i[o])if(i[o].hasOwnProperty(r)&&"data"!==r&&!t.deepEqual(e[o][r],i[o][r]))return !1;return !0}function Wt(e,i,o,r,a,n){var s;for(s in i=i||{},e=e||{})e.hasOwnProperty(s)&&(t.deepEqual(e[s],i[s])||o.push({command:n,args:[r,s,i[s],a]}));for(s in i)i.hasOwnProperty(s)&&!e.hasOwnProperty(s)&&(t.deepEqual(e[s],i[s])||o.push({command:n,args:[r,s,i[s],a]}));}function Xt(t){return t.id}function Ht(t,e){return t[e.id]=e,t}var Kt=function(t,e){this.reset(t,e);};Kt.prototype.reset=function(t,e){this.points=t||[],this._distances=[0];for(var i=1;i<this.points.length;i++)this._distances[i]=this._distances[i-1]+this.points[i].dist(this.points[i-1]);this.length=this._distances[this._distances.length-1],this.padding=Math.min(e||0,.5*this.length),this.paddedLength=this.length-2*this.padding;},Kt.prototype.lerp=function(e){if(1===this.points.length)return this.points[0];e=t.clamp(e,0,1);for(var i=1,o=this._distances[i],r=e*this.paddedLength+this.padding;o<r&&i<this._distances.length;)o=this._distances[++i];var a=i-1,n=this._distances[a],s=o-n,l=s>0?(r-n)/s:0;return this.points[a].mult(1-l).add(this.points[i].mult(l))};var Yt=function(t,e,i){var o=this.boxCells=[],r=this.circleCells=[];this.xCellCount=Math.ceil(t/i),this.yCellCount=Math.ceil(e/i);for(var a=0;a<this.xCellCount*this.yCellCount;a++)o.push([]),r.push([]);this.circleKeys=[],this.boxKeys=[],this.bboxes=[],this.circles=[],this.width=t,this.height=e,this.xScale=this.xCellCount/t,this.yScale=this.yCellCount/e,this.boxUid=0,this.circleUid=0;};function Jt(e,i,o,r,a){var n=t.create();return i?(t.scale(n,n,[1/a,1/a,1]),o||t.rotateZ(n,n,r.angle)):t.multiply(n,r.labelPlaneMatrix,e),n}function Qt(e,i,o,r,a){if(i){var n=t.clone(e);return t.scale(n,n,[a,a,1]),o||t.rotateZ(n,n,-r.angle),n}return r.glCoordMatrix}function $t(e,i){var o=[e.x,e.y,0,1];ue(o,o,i);var r=o[3];return {point:new t.Point(o[0]/r,o[1]/r),signedDistanceFromCamera:r}}function te(t,e){return .5+t/e*.5}function ee(t,e){var i=t[0]/t[3],o=t[1]/t[3];return i>=-e[0]&&i<=e[0]&&o>=-e[1]&&o<=e[1]}function ie(e,i,o,r,a,n,s,l){var c=r?e.textSizeData:e.iconSizeData,u=t.evaluateSizeForZoom(c,o.transform.zoom),h=[256/o.width*2+1,256/o.height*2+1],p=r?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;p.clear();for(var d=e.lineVertexArray,_=r?e.text.placedSymbolArray:e.icon.placedSymbolArray,f=o.transform.width/o.transform.height,m=!1,g=0;g<_.length;g++){var v=_.get(g);if(v.hidden||v.writingMode===t.WritingMode.vertical&&!m)ce(v.numGlyphs,p);else {m=!1;var y=[v.anchorX,v.anchorY,0,1];if(t.transformMat4(y,y,i),ee(y,h)){var x=te(o.transform.cameraToCenterDistance,y[3]),b=t.evaluateSizeForFeature(c,u,v),w=s?b/x:b*x,T=new t.Point(v.anchorX,v.anchorY),E=$t(T,a).point,I={},P=ae(v,w,!1,l,i,a,n,e.glyphOffsetArray,d,p,E,T,I,f);m=P.useVertical,(P.notEnoughRoom||m||P.needsFlipping&&ae(v,w,!0,l,i,a,n,e.glyphOffsetArray,d,p,E,T,I,f).notEnoughRoom)&&ce(v.numGlyphs,p);}else ce(v.numGlyphs,p);}}r?e.text.dynamicLayoutVertexBuffer.updateData(p):e.icon.dynamicLayoutVertexBuffer.updateData(p);}function oe(t,e,i,o,r,a,n,s,l,c,u){var h=s.glyphStartIndex+s.numGlyphs,p=s.lineStartIndex,d=s.lineStartIndex+s.lineLength,_=e.getoffsetX(s.glyphStartIndex),f=e.getoffsetX(h-1),m=se(t*_,i,o,r,a,n,s.segment,p,d,l,c,u);if(!m)return null;var g=se(t*f,i,o,r,a,n,s.segment,p,d,l,c,u);return g?{first:m,last:g}:null}function re(e,i,o,r){return e===t.WritingMode.horizontal&&Math.abs(o.y-i.y)>Math.abs(o.x-i.x)*r?{useVertical:!0}:(e===t.WritingMode.vertical?i.y<o.y:i.x>o.x)?{needsFlipping:!0}:null}function ae(e,i,o,r,a,n,s,l,c,u,h,p,d,_){var f,m=i/24,g=e.lineOffsetX*m,v=e.lineOffsetY*m;if(e.numGlyphs>1){var y=e.glyphStartIndex+e.numGlyphs,x=e.lineStartIndex,b=e.lineStartIndex+e.lineLength,w=oe(m,l,g,v,o,h,p,e,c,n,d);if(!w)return {notEnoughRoom:!0};var T=$t(w.first.point,s).point,E=$t(w.last.point,s).point;if(r&&!o){var I=re(e.writingMode,T,E,_);if(I)return I}f=[w.first];for(var P=e.glyphStartIndex+1;P<y-1;P++)f.push(se(m*l.getoffsetX(P),g,v,o,h,p,e.segment,x,b,c,n,d));f.push(w.last);}else {if(r&&!o){var S=$t(p,a).point,C=e.lineStartIndex+e.segment+1,z=new t.Point(c.getx(C),c.gety(C)),D=$t(z,a),M=D.signedDistanceFromCamera>0?D.point:ne(p,z,S,1,a),L=re(e.writingMode,S,M,_);if(L)return L}var A=se(m*l.getoffsetX(e.glyphStartIndex),g,v,o,h,p,e.segment,e.lineStartIndex,e.lineStartIndex+e.lineLength,c,n,d);if(!A)return {notEnoughRoom:!0};f=[A];}for(var R=0,k=f;R<k.length;R+=1){var B=k[R];t.addDynamicAttributes(u,B.point,B.angle);}return {}}function ne(t,e,i,o,r){var a=$t(t.add(t.sub(e)._unit()),r).point,n=i.sub(a);return i.add(n._mult(o/n.mag()))}function se(e,i,o,r,a,n,s,l,c,u,h,p){var d=r?e-i:e+i,_=d>0?1:-1,f=0;r&&(_*=-1,f=Math.PI),_<0&&(f+=Math.PI);for(var m=_>0?l+s:l+s+1,g=a,v=a,y=0,x=0,b=Math.abs(d),w=[];y+x<=b;){if((m+=_)<l||m>=c)return null;if(v=g,w.push(g),void 0===(g=p[m])){var T=new t.Point(u.getx(m),u.gety(m)),E=$t(T,h);if(E.signedDistanceFromCamera>0)g=p[m]=E.point;else {var I=m-_;g=ne(0===y?n:new t.Point(u.getx(I),u.gety(I)),T,v,b-y+1,h);}}y+=x,x=v.dist(g);}var P=(b-y)/x,S=g.sub(v),C=S.mult(P)._add(v);C._add(S._unit()._perp()._mult(o*_));var z=f+Math.atan2(g.y-v.y,g.x-v.x);return w.push(C),{point:C,angle:z,path:w}}Yt.prototype.keysLength=function(){return this.boxKeys.length+this.circleKeys.length},Yt.prototype.insert=function(t,e,i,o,r){this._forEachCell(e,i,o,r,this._insertBoxCell,this.boxUid++),this.boxKeys.push(t),this.bboxes.push(e),this.bboxes.push(i),this.bboxes.push(o),this.bboxes.push(r);},Yt.prototype.insertCircle=function(t,e,i,o){this._forEachCell(e-o,i-o,e+o,i+o,this._insertCircleCell,this.circleUid++),this.circleKeys.push(t),this.circles.push(e),this.circles.push(i),this.circles.push(o);},Yt.prototype._insertBoxCell=function(t,e,i,o,r,a){this.boxCells[r].push(a);},Yt.prototype._insertCircleCell=function(t,e,i,o,r,a){this.circleCells[r].push(a);},Yt.prototype._query=function(t,e,i,o,r,a){if(i<0||t>this.width||o<0||e>this.height)return !r&&[];var n=[];if(t<=0&&e<=0&&this.width<=i&&this.height<=o){if(r)return !0;for(var s=0;s<this.boxKeys.length;s++)n.push({key:this.boxKeys[s],x1:this.bboxes[4*s],y1:this.bboxes[4*s+1],x2:this.bboxes[4*s+2],y2:this.bboxes[4*s+3]});for(var l=0;l<this.circleKeys.length;l++){var c=this.circles[3*l],u=this.circles[3*l+1],h=this.circles[3*l+2];n.push({key:this.circleKeys[l],x1:c-h,y1:u-h,x2:c+h,y2:u+h});}return a?n.filter(a):n}return this._forEachCell(t,e,i,o,this._queryCell,n,{hitTest:r,seenUids:{box:{},circle:{}}},a),r?n.length>0:n},Yt.prototype._queryCircle=function(t,e,i,o,r){var a=t-i,n=t+i,s=e-i,l=e+i;if(n<0||a>this.width||l<0||s>this.height)return !o&&[];var c=[];return this._forEachCell(a,s,n,l,this._queryCellCircle,c,{hitTest:o,circle:{x:t,y:e,radius:i},seenUids:{box:{},circle:{}}},r),o?c.length>0:c},Yt.prototype.query=function(t,e,i,o,r){return this._query(t,e,i,o,!1,r)},Yt.prototype.hitTest=function(t,e,i,o,r){return this._query(t,e,i,o,!0,r)},Yt.prototype.hitTestCircle=function(t,e,i,o){return this._queryCircle(t,e,i,!0,o)},Yt.prototype._queryCell=function(t,e,i,o,r,a,n,s){var l=n.seenUids,c=this.boxCells[r];if(null!==c)for(var u=this.bboxes,h=0,p=c;h<p.length;h+=1){var d=p[h];if(!l.box[d]){l.box[d]=!0;var _=4*d;if(t<=u[_+2]&&e<=u[_+3]&&i>=u[_+0]&&o>=u[_+1]&&(!s||s(this.boxKeys[d]))){if(n.hitTest)return a.push(!0),!0;a.push({key:this.boxKeys[d],x1:u[_],y1:u[_+1],x2:u[_+2],y2:u[_+3]});}}}var f=this.circleCells[r];if(null!==f)for(var m=this.circles,g=0,v=f;g<v.length;g+=1){var y=v[g];if(!l.circle[y]){l.circle[y]=!0;var x=3*y;if(this._circleAndRectCollide(m[x],m[x+1],m[x+2],t,e,i,o)&&(!s||s(this.circleKeys[y]))){if(n.hitTest)return a.push(!0),!0;var b=m[x],w=m[x+1],T=m[x+2];a.push({key:this.circleKeys[y],x1:b-T,y1:w-T,x2:b+T,y2:w+T});}}}},Yt.prototype._queryCellCircle=function(t,e,i,o,r,a,n,s){var l=n.circle,c=n.seenUids,u=this.boxCells[r];if(null!==u)for(var h=this.bboxes,p=0,d=u;p<d.length;p+=1){var _=d[p];if(!c.box[_]){c.box[_]=!0;var f=4*_;if(this._circleAndRectCollide(l.x,l.y,l.radius,h[f+0],h[f+1],h[f+2],h[f+3])&&(!s||s(this.boxKeys[_])))return a.push(!0),!0}}var m=this.circleCells[r];if(null!==m)for(var g=this.circles,v=0,y=m;v<y.length;v+=1){var x=y[v];if(!c.circle[x]){c.circle[x]=!0;var b=3*x;if(this._circlesCollide(g[b],g[b+1],g[b+2],l.x,l.y,l.radius)&&(!s||s(this.circleKeys[x])))return a.push(!0),!0}}},Yt.prototype._forEachCell=function(t,e,i,o,r,a,n,s){for(var l=this._convertToXCellCoord(t),c=this._convertToYCellCoord(e),u=this._convertToXCellCoord(i),h=this._convertToYCellCoord(o),p=l;p<=u;p++)for(var d=c;d<=h;d++)if(r.call(this,t,e,i,o,this.xCellCount*d+p,a,n,s))return},Yt.prototype._convertToXCellCoord=function(t){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(t*this.xScale)))},Yt.prototype._convertToYCellCoord=function(t){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(t*this.yScale)))},Yt.prototype._circlesCollide=function(t,e,i,o,r,a){var n=o-t,s=r-e,l=i+a;return l*l>n*n+s*s},Yt.prototype._circleAndRectCollide=function(t,e,i,o,r,a,n){var s=(a-o)/2,l=Math.abs(t-(o+s));if(l>s+i)return !1;var c=(n-r)/2,u=Math.abs(e-(r+c));if(u>c+i)return !1;if(l<=s||u<=c)return !0;var h=l-s,p=u-c;return h*h+p*p<=i*i};var le=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function ce(t,e){for(var i=0;i<t;i++){var o=e.length;e.resize(o+4),e.float32.set(le,3*o);}}function ue(t,e,i){var o=e[0],r=e[1];return t[0]=i[0]*o+i[4]*r+i[12],t[1]=i[1]*o+i[5]*r+i[13],t[3]=i[3]*o+i[7]*r+i[15],t}var he=function(t,e,i){void 0===e&&(e=new Yt(t.width+200,t.height+200,25)),void 0===i&&(i=new Yt(t.width+200,t.height+200,25)),this.transform=t,this.grid=e,this.ignoredGrid=i,this.pitchfactor=Math.cos(t._pitch)*t.cameraToCenterDistance,this.screenRightBoundary=t.width+100,this.screenBottomBoundary=t.height+100,this.gridRightBoundary=t.width+200,this.gridBottomBoundary=t.height+200;};function pe(e,i,o){return i*(t.EXTENT/(e.tileSize*Math.pow(2,o-e.tileID.overscaledZ)))}he.prototype.placeCollisionBox=function(t,e,i,o,r){var a=this.projectAndGetPerspectiveRatio(o,t.anchorPointX,t.anchorPointY),n=i*a.perspectiveRatio,s=t.x1*n+a.point.x,l=t.y1*n+a.point.y,c=t.x2*n+a.point.x,u=t.y2*n+a.point.y;return !this.isInsideGrid(s,l,c,u)||!e&&this.grid.hitTest(s,l,c,u,r)?{box:[],offscreen:!1}:{box:[s,l,c,u],offscreen:this.isOffscreen(s,l,c,u)}},he.prototype.placeCollisionCircles=function(e,i,o,r,a,n,s,l,c,u,h,p,d){var _=[],f=new t.Point(i.anchorX,i.anchorY),m=$t(f,n),g=te(this.transform.cameraToCenterDistance,m.signedDistanceFromCamera),v=(u?a/g:a*g)/t.ONE_EM,y=$t(f,s).point,x=oe(v,r,i.lineOffsetX*v,i.lineOffsetY*v,!1,y,f,i,o,s,{}),b=!1,w=!1,T=!0;if(x){for(var E=.5*p*g+d,I=new t.Point(-100,-100),P=new t.Point(this.screenRightBoundary,this.screenBottomBoundary),S=new Kt,C=x.first,z=x.last,D=[],M=C.path.length-1;M>=1;M--)D.push(C.path[M]);for(var L=1;L<z.path.length;L++)D.push(z.path[L]);var A=2.5*E;if(l){var R=D.map((function(t){return $t(t,l)}));D=R.some((function(t){return t.signedDistanceFromCamera<=0}))?[]:R.map((function(t){return t.point}));}var k=[];if(D.length>0){for(var B=D[0].clone(),O=D[0].clone(),F=1;F<D.length;F++)B.x=Math.min(B.x,D[F].x),B.y=Math.min(B.y,D[F].y),O.x=Math.max(O.x,D[F].x),O.y=Math.max(O.y,D[F].y);k=B.x>=I.x&&O.x<=P.x&&B.y>=I.y&&O.y<=P.y?[D]:O.x<I.x||B.x>P.x||O.y<I.y||B.y>P.y?[]:t.clipLine([D],I.x,I.y,P.x,P.y);}for(var U=0,N=k;U<N.length;U+=1){var Z;S.reset(N[U],.25*E),Z=S.length<=.5*E?1:Math.ceil(S.paddedLength/A)+1;for(var j=0;j<Z;j++){var q=j/Math.max(Z-1,1),V=S.lerp(q),G=V.x+100,W=V.y+100;_.push(G,W,E,0);var X=G-E,H=W-E,K=G+E,Y=W+E;if(T=T&&this.isOffscreen(X,H,K,Y),w=w||this.isInsideGrid(X,H,K,Y),!e&&this.grid.hitTestCircle(G,W,E,h)&&(b=!0,!c))return {circles:[],offscreen:!1,collisionDetected:b}}}}return {circles:!c&&b||!w?[]:_,offscreen:T,collisionDetected:b}},he.prototype.queryRenderedSymbols=function(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return {};for(var i=[],o=1/0,r=1/0,a=-1/0,n=-1/0,s=0,l=e;s<l.length;s+=1){var c=l[s],u=new t.Point(c.x+100,c.y+100);o=Math.min(o,u.x),r=Math.min(r,u.y),a=Math.max(a,u.x),n=Math.max(n,u.y),i.push(u);}for(var h={},p={},d=0,_=this.grid.query(o,r,a,n).concat(this.ignoredGrid.query(o,r,a,n));d<_.length;d+=1){var f=_[d],m=f.key;if(void 0===h[m.bucketInstanceId]&&(h[m.bucketInstanceId]={}),!h[m.bucketInstanceId][m.featureIndex]){var g=[new t.Point(f.x1,f.y1),new t.Point(f.x2,f.y1),new t.Point(f.x2,f.y2),new t.Point(f.x1,f.y2)];t.polygonIntersectsPolygon(i,g)&&(h[m.bucketInstanceId][m.featureIndex]=!0,void 0===p[m.bucketInstanceId]&&(p[m.bucketInstanceId]=[]),p[m.bucketInstanceId].push(m.featureIndex));}}return p},he.prototype.insertCollisionBox=function(t,e,i,o,r){(e?this.ignoredGrid:this.grid).insert({bucketInstanceId:i,featureIndex:o,collisionGroupID:r},t[0],t[1],t[2],t[3]);},he.prototype.insertCollisionCircles=function(t,e,i,o,r){for(var a=e?this.ignoredGrid:this.grid,n={bucketInstanceId:i,featureIndex:o,collisionGroupID:r},s=0;s<t.length;s+=4)a.insertCircle(n,t[s],t[s+1],t[s+2]);},he.prototype.projectAndGetPerspectiveRatio=function(e,i,o){var r=[i,o,0,1];return ue(r,r,e),{point:new t.Point((r[0]/r[3]+1)/2*this.transform.width+100,(-r[1]/r[3]+1)/2*this.transform.height+100),perspectiveRatio:.5+this.transform.cameraToCenterDistance/r[3]*.5}},he.prototype.isOffscreen=function(t,e,i,o){return i<100||t>=this.screenRightBoundary||o<100||e>this.screenBottomBoundary},he.prototype.isInsideGrid=function(t,e,i,o){return i>=0&&t<this.gridRightBoundary&&o>=0&&e<this.gridBottomBoundary},he.prototype.getViewportMatrix=function(){var e=t.identity([]);return t.translate(e,e,[-100,-100,0]),e};var de=function(t,e,i,o){this.opacity=t?Math.max(0,Math.min(1,t.opacity+(t.placed?e:-e))):o&&i?1:0,this.placed=i;};de.prototype.isHidden=function(){return 0===this.opacity&&!this.placed};var _e=function(t,e,i,o,r){this.text=new de(t?t.text:null,e,i,r),this.icon=new de(t?t.icon:null,e,o,r);};_e.prototype.isHidden=function(){return this.text.isHidden()&&this.icon.isHidden()};var fe=function(t,e,i){this.text=t,this.icon=e,this.skipFade=i;},me=function(){this.invProjMatrix=t.create(),this.viewportMatrix=t.create(),this.circles=[];},ge=function(t,e,i,o,r){this.bucketInstanceId=t,this.featureIndex=e,this.sourceLayerIndex=i,this.bucketIndex=o,this.tileID=r;},ve=function(t){this.crossSourceCollisions=t,this.maxGroupID=0,this.collisionGroups={};};function ye(e,i,o,r,a){var n=t.getAnchorAlignment(e),s=-(n.horizontalAlign-.5)*i,l=-(n.verticalAlign-.5)*o,c=t.evaluateVariableOffset(e,r);return new t.Point(s+c[0]*a,l+c[1]*a)}function xe(e,i,o,r,a,n){var s=e.x1,l=e.x2,c=e.y1,u=e.y2,h=e.anchorPointX,p=e.anchorPointY,d=new t.Point(i,o);return r&&d._rotate(a?n:-n),{x1:s+d.x,y1:c+d.y,x2:l+d.x,y2:u+d.y,anchorPointX:h,anchorPointY:p}}ve.prototype.get=function(t){if(this.crossSourceCollisions)return {ID:0,predicate:null};if(!this.collisionGroups[t]){var e=++this.maxGroupID;this.collisionGroups[t]={ID:e,predicate:function(t){return t.collisionGroupID===e}};}return this.collisionGroups[t]};var be=function(t,e,i,o){this.transform=t.clone(),this.collisionIndex=new he(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=e,this.retainedQueryData={},this.collisionGroups=new ve(i),this.collisionCircleArrays={},this.prevPlacement=o,o&&(o.prevPlacement=void 0),this.placedOrientations={};};function we(t,e,i,o,r){t.emplaceBack(e?1:0,i?1:0,o||0,r||0),t.emplaceBack(e?1:0,i?1:0,o||0,r||0),t.emplaceBack(e?1:0,i?1:0,o||0,r||0),t.emplaceBack(e?1:0,i?1:0,o||0,r||0);}be.prototype.getBucketParts=function(e,i,o,r){var a=o.getBucket(i),n=o.latestFeatureIndex;if(a&&n&&i.id===a.layerIds[0]){var s=o.collisionBoxArray,l=a.layers[0].layout,c=Math.pow(2,this.transform.zoom-o.tileID.overscaledZ),u=o.tileSize/t.EXTENT,h=this.transform.calculatePosMatrix(o.tileID.toUnwrapped()),p="map"===l.get("text-pitch-alignment"),d="map"===l.get("text-rotation-alignment"),_=pe(o,1,this.transform.zoom),f=Jt(h,p,d,this.transform,_),m=null;if(p){var g=Qt(h,p,d,this.transform,_);m=t.multiply([],this.transform.labelPlaneMatrix,g);}this.retainedQueryData[a.bucketInstanceId]=new ge(a.bucketInstanceId,n,a.sourceLayerIndex,a.index,o.tileID);var v={bucket:a,layout:l,posMatrix:h,textLabelPlaneMatrix:f,labelToScreenMatrix:m,scale:c,textPixelRatio:u,holdingForFade:o.holdingForFade(),collisionBoxArray:s,partiallyEvaluatedTextSize:t.evaluateSizeForZoom(a.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(a.sourceID)};if(r)for(var y=0,x=a.sortKeyRanges;y<x.length;y+=1){var b=x[y];e.push({sortKey:b.sortKey,symbolInstanceStart:b.symbolInstanceStart,symbolInstanceEnd:b.symbolInstanceEnd,parameters:v});}else e.push({symbolInstanceStart:0,symbolInstanceEnd:a.symbolInstances.length,parameters:v});}},be.prototype.attemptAnchorPlacement=function(t,e,i,o,r,a,n,s,l,c,u,h,p,d,_){var f,m=[h.textOffset0,h.textOffset1],g=ye(t,i,o,m,r),v=this.collisionIndex.placeCollisionBox(xe(e,g.x,g.y,a,n,this.transform.angle),u,s,l,c.predicate);if(!_||0!==this.collisionIndex.placeCollisionBox(xe(_,g.x,g.y,a,n,this.transform.angle),u,s,l,c.predicate).box.length)return v.box.length>0?(this.prevPlacement&&this.prevPlacement.variableOffsets[h.crossTileID]&&this.prevPlacement.placements[h.crossTileID]&&this.prevPlacement.placements[h.crossTileID].text&&(f=this.prevPlacement.variableOffsets[h.crossTileID].anchor),this.variableOffsets[h.crossTileID]={textOffset:m,width:i,height:o,anchor:t,textBoxScale:r,prevAnchor:f},this.markUsedJustification(p,t,h,d),p.allowVerticalPlacement&&(this.markUsedOrientation(p,d,h),this.placedOrientations[h.crossTileID]=d),{shift:g,placedGlyphBoxes:v}):void 0},be.prototype.placeLayerBucketPart=function(e,i,o){var r=this,a=e.parameters,n=a.bucket,s=a.layout,l=a.posMatrix,c=a.textLabelPlaneMatrix,u=a.labelToScreenMatrix,h=a.textPixelRatio,p=a.holdingForFade,d=a.collisionBoxArray,_=a.partiallyEvaluatedTextSize,f=a.collisionGroup,m=s.get("text-optional"),g=s.get("icon-optional"),v=s.get("text-allow-overlap"),y=s.get("icon-allow-overlap"),x="map"===s.get("text-rotation-alignment"),b="map"===s.get("text-pitch-alignment"),w="none"!==s.get("icon-text-fit"),T="viewport-y"===s.get("symbol-z-order"),E=v&&(y||!n.hasIconData()||g),I=y&&(v||!n.hasTextData()||m);!n.collisionArrays&&d&&n.deserializeCollisionBoxes(d);var P=function(e,a){if(!i[e.crossTileID])if(p)r.placements[e.crossTileID]=new fe(!1,!1,!1);else {var d,T=!1,P=!1,S=!0,C=null,z={box:null,offscreen:null},D={box:null,offscreen:null},M=null,L=null,A=0,R=0,k=0;a.textFeatureIndex?A=a.textFeatureIndex:e.useRuntimeCollisionCircles&&(A=e.featureIndex),a.verticalTextFeatureIndex&&(R=a.verticalTextFeatureIndex);var B=a.textBox;if(B){var O=function(i){var o=t.WritingMode.horizontal;if(n.allowVerticalPlacement&&!i&&r.prevPlacement){var a=r.prevPlacement.placedOrientations[e.crossTileID];a&&(r.placedOrientations[e.crossTileID]=a,r.markUsedOrientation(n,o=a,e));}return o},F=function(i,o){if(n.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&a.verticalTextBox)for(var r=0,s=n.writingModes;r<s.length&&(s[r]===t.WritingMode.vertical?(z=o(),D=z):z=i(),!(z&&z.box&&z.box.length));r+=1);else z=i();};if(s.get("text-variable-anchor")){var U=s.get("text-variable-anchor");if(r.prevPlacement&&r.prevPlacement.variableOffsets[e.crossTileID]){var N=r.prevPlacement.variableOffsets[e.crossTileID];U.indexOf(N.anchor)>0&&(U=U.filter((function(t){return t!==N.anchor}))).unshift(N.anchor);}var Z=function(t,i,o){for(var a=t.x2-t.x1,s=t.y2-t.y1,c=e.textBoxScale,u=w&&!y?i:null,p={box:[],offscreen:!1},d=v?2*U.length:U.length,_=0;_<d;++_){var m=r.attemptAnchorPlacement(U[_%U.length],t,a,s,c,x,b,h,l,f,_>=U.length,e,n,o,u);if(m&&(p=m.placedGlyphBoxes)&&p.box&&p.box.length){T=!0,C=m.shift;break}}return p};F((function(){return Z(B,a.iconBox,t.WritingMode.horizontal)}),(function(){var i=a.verticalTextBox;return n.allowVerticalPlacement&&!(z&&z.box&&z.box.length)&&e.numVerticalGlyphVertices>0&&i?Z(i,a.verticalIconBox,t.WritingMode.vertical):{box:null,offscreen:null}})),z&&(T=z.box,S=z.offscreen);var j=O(z&&z.box);if(!T&&r.prevPlacement){var q=r.prevPlacement.variableOffsets[e.crossTileID];q&&(r.variableOffsets[e.crossTileID]=q,r.markUsedJustification(n,q.anchor,e,j));}}else {var V=function(t,i){var o=r.collisionIndex.placeCollisionBox(t,v,h,l,f.predicate);return o&&o.box&&o.box.length&&(r.markUsedOrientation(n,i,e),r.placedOrientations[e.crossTileID]=i),o};F((function(){return V(B,t.WritingMode.horizontal)}),(function(){var i=a.verticalTextBox;return n.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?V(i,t.WritingMode.vertical):{box:null,offscreen:null}})),O(z&&z.box&&z.box.length);}}if(T=(d=z)&&d.box&&d.box.length>0,S=d&&d.offscreen,e.useRuntimeCollisionCircles){var G=n.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),W=t.evaluateSizeForFeature(n.textSizeData,_,G),X=s.get("text-padding");M=r.collisionIndex.placeCollisionCircles(v,G,n.lineVertexArray,n.glyphOffsetArray,W,l,c,u,o,b,f.predicate,e.collisionCircleDiameter,X),T=v||M.circles.length>0&&!M.collisionDetected,S=S&&M.offscreen;}if(a.iconFeatureIndex&&(k=a.iconFeatureIndex),a.iconBox){var H=function(t){var e=w&&C?xe(t,C.x,C.y,x,b,r.transform.angle):t;return r.collisionIndex.placeCollisionBox(e,y,h,l,f.predicate)};P=D&&D.box&&D.box.length&&a.verticalIconBox?(L=H(a.verticalIconBox)).box.length>0:(L=H(a.iconBox)).box.length>0,S=S&&L.offscreen;}var K=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,Y=g||0===e.numIconVertices;if(K||Y?Y?K||(P=P&&T):T=P&&T:P=T=P&&T,T&&d&&d.box&&r.collisionIndex.insertCollisionBox(d.box,s.get("text-ignore-placement"),n.bucketInstanceId,D&&D.box&&R?R:A,f.ID),P&&L&&r.collisionIndex.insertCollisionBox(L.box,s.get("icon-ignore-placement"),n.bucketInstanceId,k,f.ID),M&&(T&&r.collisionIndex.insertCollisionCircles(M.circles,s.get("text-ignore-placement"),n.bucketInstanceId,A,f.ID),o)){var J=n.bucketInstanceId,Q=r.collisionCircleArrays[J];void 0===Q&&(Q=r.collisionCircleArrays[J]=new me);for(var $=0;$<M.circles.length;$+=4)Q.circles.push(M.circles[$+0]),Q.circles.push(M.circles[$+1]),Q.circles.push(M.circles[$+2]),Q.circles.push(M.collisionDetected?1:0);}r.placements[e.crossTileID]=new fe(T||E,P||I,S||n.justReloaded),i[e.crossTileID]=!0;}};if(T)for(var S=n.getSortedSymbolIndexes(this.transform.angle),C=S.length-1;C>=0;--C){var z=S[C];P(n.symbolInstances.get(z),n.collisionArrays[z]);}else for(var D=e.symbolInstanceStart;D<e.symbolInstanceEnd;D++)P(n.symbolInstances.get(D),n.collisionArrays[D]);if(o&&n.bucketInstanceId in this.collisionCircleArrays){var M=this.collisionCircleArrays[n.bucketInstanceId];t.invert(M.invProjMatrix,l),M.viewportMatrix=this.collisionIndex.getViewportMatrix();}n.justReloaded=!1;},be.prototype.markUsedJustification=function(e,i,o,r){var a;a=r===t.WritingMode.vertical?o.verticalPlacedTextSymbolIndex:{left:o.leftJustifiedTextSymbolIndex,center:o.centerJustifiedTextSymbolIndex,right:o.rightJustifiedTextSymbolIndex}[t.getAnchorJustification(i)];for(var n=0,s=[o.leftJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.rightJustifiedTextSymbolIndex,o.verticalPlacedTextSymbolIndex];n<s.length;n+=1){var l=s[n];l>=0&&(e.text.placedSymbolArray.get(l).crossTileID=a>=0&&l!==a?0:o.crossTileID);}},be.prototype.markUsedOrientation=function(e,i,o){for(var r=i===t.WritingMode.horizontal||i===t.WritingMode.horizontalOnly?i:0,a=i===t.WritingMode.vertical?i:0,n=0,s=[o.leftJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.rightJustifiedTextSymbolIndex];n<s.length;n+=1)e.text.placedSymbolArray.get(s[n]).placedOrientation=r;o.verticalPlacedTextSymbolIndex&&(e.text.placedSymbolArray.get(o.verticalPlacedTextSymbolIndex).placedOrientation=a);},be.prototype.commit=function(t){this.commitTime=t,this.zoomAtLastRecencyCheck=this.transform.zoom;var e=this.prevPlacement,i=!1;this.prevZoomAdjustment=e?e.zoomAdjustment(this.transform.zoom):0;var o=e?e.symbolFadeChange(t):1,r=e?e.opacities:{},a=e?e.variableOffsets:{},n=e?e.placedOrientations:{};for(var s in this.placements){var l=this.placements[s],c=r[s];c?(this.opacities[s]=new _e(c,o,l.text,l.icon),i=i||l.text!==c.text.placed||l.icon!==c.icon.placed):(this.opacities[s]=new _e(null,o,l.text,l.icon,l.skipFade),i=i||l.text||l.icon);}for(var u in r){var h=r[u];if(!this.opacities[u]){var p=new _e(h,o,!1,!1);p.isHidden()||(this.opacities[u]=p,i=i||h.text.placed||h.icon.placed);}}for(var d in a)this.variableOffsets[d]||!this.opacities[d]||this.opacities[d].isHidden()||(this.variableOffsets[d]=a[d]);for(var _ in n)this.placedOrientations[_]||!this.opacities[_]||this.opacities[_].isHidden()||(this.placedOrientations[_]=n[_]);i?this.lastPlacementChangeTime=t:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=e?e.lastPlacementChangeTime:t);},be.prototype.updateLayerOpacities=function(t,e){for(var i={},o=0,r=e;o<r.length;o+=1){var a=r[o],n=a.getBucket(t);n&&a.latestFeatureIndex&&t.id===n.layerIds[0]&&this.updateBucketOpacities(n,i,a.collisionBoxArray);}},be.prototype.updateBucketOpacities=function(e,i,o){var r=this;e.hasTextData()&&e.text.opacityVertexArray.clear(),e.hasIconData()&&e.icon.opacityVertexArray.clear(),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear();var a=e.layers[0].layout,n=new _e(null,0,!1,!1,!0),s=a.get("text-allow-overlap"),l=a.get("icon-allow-overlap"),c=a.get("text-variable-anchor"),u="map"===a.get("text-rotation-alignment"),h="map"===a.get("text-pitch-alignment"),p="none"!==a.get("icon-text-fit"),d=new _e(null,0,s&&(l||!e.hasIconData()||a.get("icon-optional")),l&&(s||!e.hasTextData()||a.get("text-optional")),!0);!e.collisionArrays&&o&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData())&&e.deserializeCollisionBoxes(o);for(var _=function(t,e,i){for(var o=0;o<e/4;o++)t.opacityVertexArray.emplaceBack(i);},f=function(o){var a=e.symbolInstances.get(o),s=a.numHorizontalGlyphVertices,l=a.numVerticalGlyphVertices,f=a.crossTileID,m=r.opacities[f];i[f]?m=n:m||(r.opacities[f]=m=d),i[f]=!0;var g=a.numIconVertices>0,v=r.placedOrientations[a.crossTileID],y=v===t.WritingMode.vertical,x=v===t.WritingMode.horizontal||v===t.WritingMode.horizontalOnly;if(s>0||l>0){var b=De(m.text);_(e.text,s,y?Me:b),_(e.text,l,x?Me:b);var w=m.text.isHidden();[a.rightJustifiedTextSymbolIndex,a.centerJustifiedTextSymbolIndex,a.leftJustifiedTextSymbolIndex].forEach((function(t){t>=0&&(e.text.placedSymbolArray.get(t).hidden=w||y?1:0);})),a.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(a.verticalPlacedTextSymbolIndex).hidden=w||x?1:0);var T=r.variableOffsets[a.crossTileID];T&&r.markUsedJustification(e,T.anchor,a,v);var E=r.placedOrientations[a.crossTileID];E&&(r.markUsedJustification(e,"left",a,E),r.markUsedOrientation(e,E,a));}if(g){var I=De(m.icon),P=!(p&&a.verticalPlacedIconSymbolIndex&&y);a.placedIconSymbolIndex>=0&&(_(e.icon,a.numIconVertices,P?I:Me),e.icon.placedSymbolArray.get(a.placedIconSymbolIndex).hidden=m.icon.isHidden()),a.verticalPlacedIconSymbolIndex>=0&&(_(e.icon,a.numVerticalIconVertices,P?Me:I),e.icon.placedSymbolArray.get(a.verticalPlacedIconSymbolIndex).hidden=m.icon.isHidden());}if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){var S=e.collisionArrays[o];if(S){var C=new t.Point(0,0);if(S.textBox||S.verticalTextBox){var z=!0;if(c){var D=r.variableOffsets[f];D?(C=ye(D.anchor,D.width,D.height,D.textOffset,D.textBoxScale),u&&C._rotate(h?r.transform.angle:-r.transform.angle)):z=!1;}S.textBox&&we(e.textCollisionBox.collisionVertexArray,m.text.placed,!z||y,C.x,C.y),S.verticalTextBox&&we(e.textCollisionBox.collisionVertexArray,m.text.placed,!z||x,C.x,C.y);}var M=Boolean(!x&&S.verticalIconBox);S.iconBox&&we(e.iconCollisionBox.collisionVertexArray,m.icon.placed,M,p?C.x:0,p?C.y:0),S.verticalIconBox&&we(e.iconCollisionBox.collisionVertexArray,m.icon.placed,!M,p?C.x:0,p?C.y:0);}}},m=0;m<e.symbolInstances.length;m++)f(m);if(e.sortFeatures(this.transform.angle),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),e.hasIconData()&&e.icon.opacityVertexBuffer&&e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexBuffer&&e.iconCollisionBox.collisionVertexBuffer.updateData(e.iconCollisionBox.collisionVertexArray),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexBuffer&&e.textCollisionBox.collisionVertexBuffer.updateData(e.textCollisionBox.collisionVertexArray),e.bucketInstanceId in this.collisionCircleArrays){var g=this.collisionCircleArrays[e.bucketInstanceId];e.placementInvProjMatrix=g.invProjMatrix,e.placementViewportMatrix=g.viewportMatrix,e.collisionCircleArray=g.circles,delete this.collisionCircleArrays[e.bucketInstanceId];}},be.prototype.symbolFadeChange=function(t){return 0===this.fadeDuration?1:(t-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment},be.prototype.zoomAdjustment=function(t){return Math.max(0,(this.transform.zoom-t)/1.5)},be.prototype.hasTransitions=function(t){return this.stale||t-this.lastPlacementChangeTime<this.fadeDuration},be.prototype.stillRecent=function(t,e){var i=this.zoomAtLastRecencyCheck===e?1-this.zoomAdjustment(e):1;return this.zoomAtLastRecencyCheck=e,this.commitTime+this.fadeDuration*i>t},be.prototype.setStale=function(){this.stale=!0;};var Te=Math.pow(2,25),Ee=Math.pow(2,24),Ie=Math.pow(2,17),Pe=Math.pow(2,16),Se=Math.pow(2,9),Ce=Math.pow(2,8),ze=Math.pow(2,1);function De(t){if(0===t.opacity&&!t.placed)return 0;if(1===t.opacity&&t.placed)return 4294967295;var e=t.placed?1:0,i=Math.floor(127*t.opacity);return i*Te+e*Ee+i*Ie+e*Pe+i*Se+e*Ce+i*ze+e}var Me=0,Le=function(t){this._sortAcrossTiles="viewport-y"!==t.layout.get("symbol-z-order")&&void 0!==t.layout.get("symbol-sort-key").constantOr(1),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];};Le.prototype.continuePlacement=function(t,e,i,o,r){for(var a=this._bucketParts;this._currentTileIndex<t.length;)if(e.getBucketParts(a,o,t[this._currentTileIndex],this._sortAcrossTiles),this._currentTileIndex++,r())return !0;for(this._sortAcrossTiles&&(this._sortAcrossTiles=!1,a.sort((function(t,e){return t.sortKey-e.sortKey})));this._currentPartIndex<a.length;)if(e.placeLayerBucketPart(a[this._currentPartIndex],this._seenCrossTileIDs,i),this._currentPartIndex++,r())return !0;return !1};var Ae=function(t,e,i,o,r,a,n){this.placement=new be(t,r,a,n),this._currentPlacementIndex=e.length-1,this._forceFullPlacement=i,this._showCollisionBoxes=o,this._done=!1;};Ae.prototype.isDone=function(){return this._done},Ae.prototype.continuePlacement=function(e,i,o){for(var r=this,a=t.browser.now(),n=function(){var e=t.browser.now()-a;return !r._forceFullPlacement&&e>2};this._currentPlacementIndex>=0;){var s=i[e[this._currentPlacementIndex]],l=this.placement.collisionIndex.transform.zoom;if("symbol"===s.type&&(!s.minzoom||s.minzoom<=l)&&(!s.maxzoom||s.maxzoom>l)){if(this._inProgressLayer||(this._inProgressLayer=new Le(s)),this._inProgressLayer.continuePlacement(o[s.source],this.placement,this._showCollisionBoxes,s,n))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;},Ae.prototype.commit=function(t){return this.placement.commit(t),this.placement};var Re=512/t.EXTENT/2,ke=function(t,e,i){this.tileID=t,this.indexedSymbolInstances={},this.bucketInstanceId=i;for(var o=0;o<e.length;o++){var r=e.get(o),a=r.key;this.indexedSymbolInstances[a]||(this.indexedSymbolInstances[a]=[]),this.indexedSymbolInstances[a].push({crossTileID:r.crossTileID,coord:this.getScaledCoordinates(r,t)});}};ke.prototype.getScaledCoordinates=function(e,i){var o=Re/Math.pow(2,i.canonical.z-this.tileID.canonical.z);return {x:Math.floor((i.canonical.x*t.EXTENT+e.anchorX)*o),y:Math.floor((i.canonical.y*t.EXTENT+e.anchorY)*o)}},ke.prototype.findMatches=function(t,e,i){for(var o=this.tileID.canonical.z<e.canonical.z?1:Math.pow(2,this.tileID.canonical.z-e.canonical.z),r=0;r<t.length;r++){var a=t.get(r);if(!a.crossTileID){var n=this.indexedSymbolInstances[a.key];if(n)for(var s=this.getScaledCoordinates(a,e),l=0,c=n;l<c.length;l+=1){var u=c[l];if(Math.abs(u.coord.x-s.x)<=o&&Math.abs(u.coord.y-s.y)<=o&&!i[u.crossTileID]){i[u.crossTileID]=!0,a.crossTileID=u.crossTileID;break}}}}};var Be=function(){this.maxCrossTileID=0;};Be.prototype.generate=function(){return ++this.maxCrossTileID};var Oe=function(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;};Oe.prototype.handleWrapJump=function(t){var e=Math.round((t-this.lng)/360);if(0!==e)for(var i in this.indexes){var o=this.indexes[i],r={};for(var a in o){var n=o[a];n.tileID=n.tileID.unwrapTo(n.tileID.wrap+e),r[n.tileID.key]=n;}this.indexes[i]=r;}this.lng=t;},Oe.prototype.addBucket=function(t,e,i){if(this.indexes[t.overscaledZ]&&this.indexes[t.overscaledZ][t.key]){if(this.indexes[t.overscaledZ][t.key].bucketInstanceId===e.bucketInstanceId)return !1;this.removeBucketCrossTileIDs(t.overscaledZ,this.indexes[t.overscaledZ][t.key]);}for(var o=0;o<e.symbolInstances.length;o++)e.symbolInstances.get(o).crossTileID=0;this.usedCrossTileIDs[t.overscaledZ]||(this.usedCrossTileIDs[t.overscaledZ]={});var r=this.usedCrossTileIDs[t.overscaledZ];for(var a in this.indexes){var n=this.indexes[a];if(Number(a)>t.overscaledZ)for(var s in n){var l=n[s];l.tileID.isChildOf(t)&&l.findMatches(e.symbolInstances,t,r);}else {var c=n[t.scaledTo(Number(a)).key];c&&c.findMatches(e.symbolInstances,t,r);}}for(var u=0;u<e.symbolInstances.length;u++){var h=e.symbolInstances.get(u);h.crossTileID||(h.crossTileID=i.generate(),r[h.crossTileID]=!0);}return void 0===this.indexes[t.overscaledZ]&&(this.indexes[t.overscaledZ]={}),this.indexes[t.overscaledZ][t.key]=new ke(t,e.symbolInstances,e.bucketInstanceId),!0},Oe.prototype.removeBucketCrossTileIDs=function(t,e){for(var i in e.indexedSymbolInstances)for(var o=0,r=e.indexedSymbolInstances[i];o<r.length;o+=1)delete this.usedCrossTileIDs[t][r[o].crossTileID];},Oe.prototype.removeStaleBuckets=function(t){var e=!1;for(var i in this.indexes){var o=this.indexes[i];for(var r in o)t[o[r].bucketInstanceId]||(this.removeBucketCrossTileIDs(i,o[r]),delete o[r],e=!0);}return e};var Fe=function(){this.layerIndexes={},this.crossTileIDs=new Be,this.maxBucketInstanceId=0,this.bucketsInCurrentPlacement={};};Fe.prototype.addLayer=function(t,e,i){var o=this.layerIndexes[t.id];void 0===o&&(o=this.layerIndexes[t.id]=new Oe);var r=!1,a={};o.handleWrapJump(i);for(var n=0,s=e;n<s.length;n+=1){var l=s[n],c=l.getBucket(t);c&&t.id===c.layerIds[0]&&(c.bucketInstanceId||(c.bucketInstanceId=++this.maxBucketInstanceId),o.addBucket(l.tileID,c,this.crossTileIDs)&&(r=!0),a[c.bucketInstanceId]=!0);}return o.removeStaleBuckets(a)&&(r=!0),r},Fe.prototype.pruneUnusedLayers=function(t){var e={};for(var i in t.forEach((function(t){e[t]=!0;})),this.layerIndexes)e[i]||delete this.layerIndexes[i];};var Ue=function(e,i){return t.emitValidationErrors(e,i&&i.filter((function(t){return "source.canvas"!==t.identifier})))},Ne=t.pick(Zt,["addLayer","removeLayer","setPaintProperty","setLayoutProperty","setFilter","addSource","removeSource","setLayerZoomRange","setLight","setTransition","setGeoJSONSourceData"]),Ze=t.pick(Zt,["setCenter","setZoom","setBearing","setPitch"]),je=function(){var e={},i=t.styleSpec.$version;for(var o in t.styleSpec.$root){var r,a=t.styleSpec.$root[o];if(a.required)null!=(r="version"===o?i:"array"===a.type?[]:{})&&(e[o]=r);}return e}(),qe=function(e){function i(o,r){var a=this;void 0===r&&(r={}),e.call(this),this.map=o,this.dispatcher=new E(Ft(),this),this.imageManager=new p,this.imageManager.setEventedParent(this),this.glyphManager=new y(o._requestManager,r.localIdeographFontFamily),this.lineAtlas=new T(256,512),this.crossTileSymbolIndex=new Fe,this._layers={},this._serializedLayers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.ZoomHistory,this._loaded=!1,this._availableImages=[],this._resetUpdates(),this.dispatcher.broadcast("setReferrer",t.getReferrer());var n=this;this._rtlTextPluginCallback=i.registerForPluginStateChange((function(e){n.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:e.pluginStatus,pluginURL:e.pluginURL},(function(e,i){if(t.triggerPluginCompletionEvent(e),i&&i.every((function(t){return t})))for(var o in n.sourceCaches)n.sourceCaches[o].reload();}));})),this.on("data",(function(t){if("source"===t.dataType&&"metadata"===t.sourceDataType){var e=a.sourceCaches[t.sourceId];if(e){var i=e.getSource();if(i&&i.vectorLayerIds)for(var o in a._layers){var r=a._layers[o];r.source===i.id&&a._validateLayer(r);}}}}));}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.loadURL=function(e,i){var o=this;void 0===i&&(i={}),this.fire(new t.Event("dataloading",{dataType:"style"}));var r="boolean"==typeof i.validate?i.validate:!t.isMapboxURL(e);e=this.map._requestManager.normalizeStyleURL(e,i.accessToken);var a=this.map._requestManager.transformRequest(e,t.ResourceType.Style);this._request=t.getJSON(a,(function(e,i){o._request=null,e?o.fire(new t.ErrorEvent(e)):i&&o._load(i,r);}));},i.prototype.loadJSON=function(e,i){var o=this;void 0===i&&(i={}),this.fire(new t.Event("dataloading",{dataType:"style"})),this._request=t.browser.frame((function(){o._request=null,o._load(e,!1!==i.validate);}));},i.prototype.loadEmpty=function(){this.fire(new t.Event("dataloading",{dataType:"style"})),this._load(je,!1);},i.prototype._load=function(e,i){if(!i||!Ue(this,t.validateStyle(e))){for(var o in this._loaded=!0,this.stylesheet=e,e.sources)this.addSource(o,e.sources[o],{validate:!1});e.sprite?this._loadSprite(e.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(e.glyphs);var r=Nt(this.stylesheet.layers);this._order=r.map((function(t){return t.id})),this._layers={},this._serializedLayers={};for(var a=0,n=r;a<n.length;a+=1){var s=n[a];(s=t.createStyleLayer(s)).setEventedParent(this,{layer:{id:s.id}}),this._layers[s.id]=s,this._serializedLayers[s.id]=s.serialize();}this.dispatcher.broadcast("setLayers",this._serializeLayers(this._order)),this.light=new w(this.stylesheet.light),this.fire(new t.Event("data",{dataType:"style"})),this.fire(new t.Event("style.load"));}},i.prototype._loadSprite=function(e){var i=this;this._spriteRequest=function(e,i,o){var r,a,n,s=t.browser.devicePixelRatio>1?"@2x":"",l=t.getJSON(i.transformRequest(i.normalizeSpriteURL(e,s,".json"),t.ResourceType.SpriteJSON),(function(t,e){l=null,n||(n=t,r=e,u());})),c=t.getImage(i.transformRequest(i.normalizeSpriteURL(e,s,".png"),t.ResourceType.SpriteImage),(function(t,e){c=null,n||(n=t,a=e,u());}));function u(){if(n)o(n);else if(r&&a){var e=t.browser.getImageData(a),i={};for(var s in r){var l=r[s],c=l.width,u=l.height,h=l.x,p=l.y,d=l.sdf,_=l.pixelRatio,f=l.stretchX,m=l.stretchY,g=l.content,v=new t.RGBAImage({width:c,height:u});t.RGBAImage.copy(e,v,{x:h,y:p},{x:0,y:0},{width:c,height:u}),i[s]={data:v,pixelRatio:_,sdf:d,stretchX:f,stretchY:m,content:g};}o(null,i);}}return {cancel:function(){l&&(l.cancel(),l=null),c&&(c.cancel(),c=null);}}}(e,this.map._requestManager,(function(e,o){if(i._spriteRequest=null,e)i.fire(new t.ErrorEvent(e));else if(o)for(var r in o)i.imageManager.addImage(r,o[r]);i.imageManager.setLoaded(!0),i._availableImages=i.imageManager.listImages(),i.dispatcher.broadcast("setImages",i._availableImages),i.fire(new t.Event("data",{dataType:"style"}));}));},i.prototype._validateLayer=function(e){var i=this.sourceCaches[e.source];if(i){var o=e.sourceLayer;if(o){var r=i.getSource();("geojson"===r.type||r.vectorLayerIds&&-1===r.vectorLayerIds.indexOf(o))&&this.fire(new t.ErrorEvent(new Error('Source layer "'+o+'" does not exist on source "'+r.id+'" as specified by style layer "'+e.id+'"')));}}},i.prototype.loaded=function(){if(!this._loaded)return !1;if(Object.keys(this._updatedSources).length)return !1;for(var t in this.sourceCaches)if(!this.sourceCaches[t].loaded())return !1;return !!this.imageManager.isLoaded()},i.prototype._serializeLayers=function(t){for(var e=[],i=0,o=t;i<o.length;i+=1){var r=this._layers[o[i]];"custom"!==r.type&&e.push(r.serialize());}return e},i.prototype.hasTransitions=function(){if(this.light&&this.light.hasTransition())return !0;for(var t in this.sourceCaches)if(this.sourceCaches[t].hasTransition())return !0;for(var e in this._layers)if(this._layers[e].hasTransition())return !0;return !1},i.prototype._checkLoaded=function(){if(!this._loaded)throw new Error("Style is not done loading")},i.prototype.update=function(e){if(this._loaded){var i=this._changed;if(this._changed){var o=Object.keys(this._updatedLayers),r=Object.keys(this._removedLayers);for(var a in (o.length||r.length)&&this._updateWorkerLayers(o,r),this._updatedSources){var n=this._updatedSources[a];"reload"===n?this._reloadSource(a):"clear"===n&&this._clearSource(a);}for(var s in this._updateTilesForChangedImages(),this._updatedPaintProps)this._layers[s].updateTransitions(e);this.light.updateTransitions(e),this._resetUpdates();}for(var l in this.sourceCaches)this.sourceCaches[l].used=!1;for(var c=0,u=this._order;c<u.length;c+=1){var h=this._layers[u[c]];h.recalculate(e,this._availableImages),!h.isHidden(e.zoom)&&h.source&&(this.sourceCaches[h.source].used=!0);}this.light.recalculate(e),this.z=e.zoom,i&&this.fire(new t.Event("data",{dataType:"style"}));}},i.prototype._updateTilesForChangedImages=function(){var t=Object.keys(this._changedImages);if(t.length){for(var e in this.sourceCaches)this.sourceCaches[e].reloadTilesForDependencies(["icons","patterns"],t);this._changedImages={};}},i.prototype._updateWorkerLayers=function(t,e){this.dispatcher.broadcast("updateLayers",{layers:this._serializeLayers(t),removedIds:e});},i.prototype._resetUpdates=function(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={};},i.prototype.setState=function(e){var i=this;if(this._checkLoaded(),Ue(this,t.validateStyle(e)))return !1;(e=t.clone$1(e)).layers=Nt(e.layers);var o=function(e,i){if(!e)return [{command:Zt.setStyle,args:[i]}];var o=[];try{if(!t.deepEqual(e.version,i.version))return [{command:Zt.setStyle,args:[i]}];t.deepEqual(e.center,i.center)||o.push({command:Zt.setCenter,args:[i.center]}),t.deepEqual(e.zoom,i.zoom)||o.push({command:Zt.setZoom,args:[i.zoom]}),t.deepEqual(e.bearing,i.bearing)||o.push({command:Zt.setBearing,args:[i.bearing]}),t.deepEqual(e.pitch,i.pitch)||o.push({command:Zt.setPitch,args:[i.pitch]}),t.deepEqual(e.sprite,i.sprite)||o.push({command:Zt.setSprite,args:[i.sprite]}),t.deepEqual(e.glyphs,i.glyphs)||o.push({command:Zt.setGlyphs,args:[i.glyphs]}),t.deepEqual(e.transition,i.transition)||o.push({command:Zt.setTransition,args:[i.transition]}),t.deepEqual(e.light,i.light)||o.push({command:Zt.setLight,args:[i.light]});var r={},a=[];!function(e,i,o,r){var a;for(a in i=i||{},e=e||{})e.hasOwnProperty(a)&&(i.hasOwnProperty(a)||qt(a,o,r));for(a in i)i.hasOwnProperty(a)&&(e.hasOwnProperty(a)?t.deepEqual(e[a],i[a])||("geojson"===e[a].type&&"geojson"===i[a].type&&Gt(e,i,a)?o.push({command:Zt.setGeoJSONSourceData,args:[a,i[a].data]}):Vt(a,i,o,r)):jt(a,i,o));}(e.sources,i.sources,a,r);var n=[];e.layers&&e.layers.forEach((function(t){r[t.source]?o.push({command:Zt.removeLayer,args:[t.id]}):n.push(t);})),o=o.concat(a),function(e,i,o){i=i||[];var r,a,n,s,l,c,u,h=(e=e||[]).map(Xt),p=i.map(Xt),d=e.reduce(Ht,{}),_=i.reduce(Ht,{}),f=h.slice(),m=Object.create(null);for(r=0,a=0;r<h.length;r++)_.hasOwnProperty(n=h[r])?a++:(o.push({command:Zt.removeLayer,args:[n]}),f.splice(f.indexOf(n,a),1));for(r=0,a=0;r<p.length;r++)f[f.length-1-r]!==(n=p[p.length-1-r])&&(d.hasOwnProperty(n)?(o.push({command:Zt.removeLayer,args:[n]}),f.splice(f.lastIndexOf(n,f.length-a),1)):a++,o.push({command:Zt.addLayer,args:[_[n],c=f[f.length-r]]}),f.splice(f.length-r,0,n),m[n]=!0);for(r=0;r<p.length;r++)if(s=d[n=p[r]],l=_[n],!m[n]&&!t.deepEqual(s,l))if(t.deepEqual(s.source,l.source)&&t.deepEqual(s["source-layer"],l["source-layer"])&&t.deepEqual(s.type,l.type)){for(u in Wt(s.layout,l.layout,o,n,null,Zt.setLayoutProperty),Wt(s.paint,l.paint,o,n,null,Zt.setPaintProperty),t.deepEqual(s.filter,l.filter)||o.push({command:Zt.setFilter,args:[n,l.filter]}),t.deepEqual(s.minzoom,l.minzoom)&&t.deepEqual(s.maxzoom,l.maxzoom)||o.push({command:Zt.setLayerZoomRange,args:[n,l.minzoom,l.maxzoom]}),s)s.hasOwnProperty(u)&&"layout"!==u&&"paint"!==u&&"filter"!==u&&"metadata"!==u&&"minzoom"!==u&&"maxzoom"!==u&&(0===u.indexOf("paint.")?Wt(s[u],l[u],o,n,u.slice(6),Zt.setPaintProperty):t.deepEqual(s[u],l[u])||o.push({command:Zt.setLayerProperty,args:[n,u,l[u]]}));for(u in l)l.hasOwnProperty(u)&&!s.hasOwnProperty(u)&&"layout"!==u&&"paint"!==u&&"filter"!==u&&"metadata"!==u&&"minzoom"!==u&&"maxzoom"!==u&&(0===u.indexOf("paint.")?Wt(s[u],l[u],o,n,u.slice(6),Zt.setPaintProperty):t.deepEqual(s[u],l[u])||o.push({command:Zt.setLayerProperty,args:[n,u,l[u]]}));}else o.push({command:Zt.removeLayer,args:[n]}),c=f[f.lastIndexOf(n)+1],o.push({command:Zt.addLayer,args:[l,c]});}(n,i.layers,o);}catch(t){console.warn("Unable to compute style diff:",t),o=[{command:Zt.setStyle,args:[i]}];}return o}(this.serialize(),e).filter((function(t){return !(t.command in Ze)}));if(0===o.length)return !1;var r=o.filter((function(t){return !(t.command in Ne)}));if(r.length>0)throw new Error("Unimplemented: "+r.map((function(t){return t.command})).join(", ")+".");return o.forEach((function(t){"setTransition"!==t.command&&i[t.command].apply(i,t.args);})),this.stylesheet=e,!0},i.prototype.addImage=function(e,i){if(this.getImage(e))return this.fire(new t.ErrorEvent(new Error("An image with this name already exists.")));this.imageManager.addImage(e,i),this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.fire(new t.Event("data",{dataType:"style"}));},i.prototype.updateImage=function(t,e){this.imageManager.updateImage(t,e);},i.prototype.getImage=function(t){return this.imageManager.getImage(t)},i.prototype.removeImage=function(e){if(!this.getImage(e))return this.fire(new t.ErrorEvent(new Error("No image with this name exists.")));this.imageManager.removeImage(e),this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.fire(new t.Event("data",{dataType:"style"}));},i.prototype.listImages=function(){return this._checkLoaded(),this.imageManager.listImages()},i.prototype.addSource=function(e,i,o){var r=this;if(void 0===o&&(o={}),this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error("There is already a source with this ID");if(!i.type)throw new Error("The type property must be defined, but the only the following properties were given: "+Object.keys(i).join(", ")+".");if(!(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(t.validateStyle.source,"sources."+e,i,null,o))){this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);var a=this.sourceCaches[e]=new Dt(e,i,this.dispatcher);a.style=this,a.setEventedParent(this,(function(){return {isSourceLoaded:r.loaded(),source:a.serialize(),sourceId:e}})),a.onAdd(this.map),this._changed=!0;}},i.prototype.removeSource=function(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(var i in this._layers)if(this._layers[i].source===e)return this.fire(new t.ErrorEvent(new Error('Source "'+e+'" cannot be removed while layer "'+i+'" is using it.')));var o=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],o.fire(new t.Event("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),o.setEventedParent(null),o.clearTiles(),o.onRemove&&o.onRemove(this.map),this._changed=!0;},i.prototype.setGeoJSONSourceData=function(t,e){this._checkLoaded(),this.sourceCaches[t].getSource().setData(e),this._changed=!0;},i.prototype.getSource=function(t){return this.sourceCaches[t]&&this.sourceCaches[t].getSource()},i.prototype.addLayer=function(e,i,o){void 0===o&&(o={}),this._checkLoaded();var r=e.id;if(this.getLayer(r))this.fire(new t.ErrorEvent(new Error('Layer with id "'+r+'" already exists on this map')));else {var a;if("custom"===e.type){if(Ue(this,t.validateCustomStyleLayer(e)))return;a=t.createStyleLayer(e);}else {if("object"==typeof e.source&&(this.addSource(r,e.source),e=t.clone$1(e),e=t.extend(e,{source:r})),this._validate(t.validateStyle.layer,"layers."+r,e,{arrayIndex:-1},o))return;a=t.createStyleLayer(e),this._validateLayer(a),a.setEventedParent(this,{layer:{id:r}}),this._serializedLayers[a.id]=a.serialize();}var n=i?this._order.indexOf(i):this._order.length;if(i&&-1===n)this.fire(new t.ErrorEvent(new Error('Layer with id "'+i+'" does not exist on this map.')));else {if(this._order.splice(n,0,r),this._layerOrderChanged=!0,this._layers[r]=a,this._removedLayers[r]&&a.source&&"custom"!==a.type){var s=this._removedLayers[r];delete this._removedLayers[r],s.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause());}this._updateLayer(a),a.onAdd&&a.onAdd(this.map);}}},i.prototype.moveLayer=function(e,i){if(this._checkLoaded(),this._changed=!0,this._layers[e]){if(e!==i){var o=this._order.indexOf(e);this._order.splice(o,1);var r=i?this._order.indexOf(i):this._order.length;i&&-1===r?this.fire(new t.ErrorEvent(new Error('Layer with id "'+i+'" does not exist on this map.'))):(this._order.splice(r,0,e),this._layerOrderChanged=!0);}}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be moved.")));},i.prototype.removeLayer=function(e){this._checkLoaded();var i=this._layers[e];if(i){i.setEventedParent(null);var o=this._order.indexOf(e);this._order.splice(o,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be removed.")));},i.prototype.getLayer=function(t){return this._layers[t]},i.prototype.hasLayer=function(t){return t in this._layers},i.prototype.setLayerZoomRange=function(e,i,o){this._checkLoaded();var r=this.getLayer(e);r?r.minzoom===i&&r.maxzoom===o||(null!=i&&(r.minzoom=i),null!=o&&(r.maxzoom=o),this._updateLayer(r)):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot have zoom extent.")));},i.prototype.setFilter=function(e,i,o){void 0===o&&(o={}),this._checkLoaded();var r=this.getLayer(e);if(r){if(!t.deepEqual(r.filter,i))return null==i?(r.filter=void 0,void this._updateLayer(r)):void(this._validate(t.validateStyle.filter,"layers."+r.id+".filter",i,null,o)||(r.filter=t.clone$1(i),this._updateLayer(r)))}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be filtered.")));},i.prototype.getFilter=function(e){return t.clone$1(this.getLayer(e).filter)},i.prototype.setLayoutProperty=function(e,i,o,r){void 0===r&&(r={}),this._checkLoaded();var a=this.getLayer(e);a?t.deepEqual(a.getLayoutProperty(i),o)||(a.setLayoutProperty(i,o,r),this._updateLayer(a)):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be styled.")));},i.prototype.getLayoutProperty=function(e,i){var o=this.getLayer(e);if(o)return o.getLayoutProperty(i);this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style.")));},i.prototype.setPaintProperty=function(e,i,o,r){void 0===r&&(r={}),this._checkLoaded();var a=this.getLayer(e);a?t.deepEqual(a.getPaintProperty(i),o)||(a.setPaintProperty(i,o,r)&&this._updateLayer(a),this._changed=!0,this._updatedPaintProps[e]=!0):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be styled.")));},i.prototype.getPaintProperty=function(t,e){return this.getLayer(t).getPaintProperty(e)},i.prototype.setFeatureState=function(e,i){this._checkLoaded();var o=e.source,r=e.sourceLayer,a=this.sourceCaches[o];if(void 0!==a){var n=a.getSource().type;"geojson"===n&&r?this.fire(new t.ErrorEvent(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==n||r?(void 0===e.id&&this.fire(new t.ErrorEvent(new Error("The feature id parameter must be provided."))),a.setFeatureState(r,e.id,i)):this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}else this.fire(new t.ErrorEvent(new Error("The source '"+o+"' does not exist in the map's style.")));},i.prototype.removeFeatureState=function(e,i){this._checkLoaded();var o=e.source,r=this.sourceCaches[o];if(void 0!==r){var a=r.getSource().type,n="vector"===a?e.sourceLayer:void 0;"vector"!==a||n?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.ErrorEvent(new Error("A feature id is requred to remove its specific state property."))):r.removeFeatureState(n,e.id,i):this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}else this.fire(new t.ErrorEvent(new Error("The source '"+o+"' does not exist in the map's style.")));},i.prototype.getFeatureState=function(e){this._checkLoaded();var i=e.source,o=e.sourceLayer,r=this.sourceCaches[i];if(void 0!==r){if("vector"!==r.getSource().type||o)return void 0===e.id&&this.fire(new t.ErrorEvent(new Error("The feature id parameter must be provided."))),r.getFeatureState(o,e.id);this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}else this.fire(new t.ErrorEvent(new Error("The source '"+i+"' does not exist in the map's style.")));},i.prototype.getTransition=function(){return t.extend({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)},i.prototype.serialize=function(){return t.filterObject({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,light:this.stylesheet.light,center:this.stylesheet.center,zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,sources:t.mapObject(this.sourceCaches,(function(t){return t.serialize()})),layers:this._serializeLayers(this._order)},(function(t){return void 0!==t}))},i.prototype._updateLayer=function(t){this._updatedLayers[t.id]=!0,t.source&&!this._updatedSources[t.source]&&"raster"!==this.sourceCaches[t.source].getSource().type&&(this._updatedSources[t.source]="reload",this.sourceCaches[t.source].pause()),this._changed=!0;},i.prototype._flattenAndSortRenderedFeatures=function(t){for(var e=this,i=function(t){return "fill-extrusion"===e._layers[t].type},o={},r=[],a=this._order.length-1;a>=0;a--){var n=this._order[a];if(i(n)){o[n]=a;for(var s=0,l=t;s<l.length;s+=1){var c=l[s][n];if(c)for(var u=0,h=c;u<h.length;u+=1)r.push(h[u]);}}}r.sort((function(t,e){return e.intersectionZ-t.intersectionZ}));for(var p=[],d=this._order.length-1;d>=0;d--){var _=this._order[d];if(i(_))for(var f=r.length-1;f>=0;f--){var m=r[f].feature;if(o[m.layer.id]<d)break;p.push(m),r.pop();}else for(var g=0,v=t;g<v.length;g+=1){var y=v[g][_];if(y)for(var x=0,b=y;x<b.length;x+=1)p.push(b[x].feature);}}return p},i.prototype.queryRenderedFeatures=function(e,i,o){i&&i.filter&&this._validate(t.validateStyle.filter,"queryRenderedFeatures.filter",i.filter,null,i);var r={};if(i&&i.layers){if(!Array.isArray(i.layers))return this.fire(new t.ErrorEvent(new Error("parameters.layers must be an Array."))),[];for(var a=0,n=i.layers;a<n.length;a+=1){var s=n[a],l=this._layers[s];if(!l)return this.fire(new t.ErrorEvent(new Error("The layer '"+s+"' does not exist in the map's style and cannot be queried for features."))),[];r[l.source]=!0;}}var c=[];for(var u in i.availableImages=this._availableImages,this.sourceCaches)i.layers&&!r[u]||c.push(O(this.sourceCaches[u],this._layers,this._serializedLayers,e,i,o));return this.placement&&c.push(function(t,e,i,o,r,a,n){for(var s={},l=a.queryRenderedSymbols(o),c=[],u=0,h=Object.keys(l).map(Number);u<h.length;u+=1)c.push(n[h[u]]);c.sort(F);for(var p=function(){var i=_[d],o=i.featureIndex.lookupSymbolFeatures(l[i.bucketInstanceId],e,i.bucketIndex,i.sourceLayerIndex,r.filter,r.layers,r.availableImages,t);for(var a in o){var n=s[a]=s[a]||[],c=o[a];c.sort((function(t,e){var o=i.featureSortOrder;if(o){var r=o.indexOf(t.featureIndex);return o.indexOf(e.featureIndex)-r}return e.featureIndex-t.featureIndex}));for(var u=0,h=c;u<h.length;u+=1)n.push(h[u]);}},d=0,_=c;d<_.length;d+=1)p();var f=function(e){s[e].forEach((function(o){var r=o.feature,a=i[t[e].source].getFeatureState(r.layer["source-layer"],r.id);r.source=r.layer.source,r.layer["source-layer"]&&(r.sourceLayer=r.layer["source-layer"]),r.state=a;}));};for(var m in s)f(m);return s}(this._layers,this._serializedLayers,this.sourceCaches,e,i,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(c)},i.prototype.querySourceFeatures=function(e,i){i&&i.filter&&this._validate(t.validateStyle.filter,"querySourceFeatures.filter",i.filter,null,i);var o=this.sourceCaches[e];return o?function(t,e){for(var i=t.getRenderableIds().map((function(e){return t.getTileByID(e)})),o=[],r={},a=0;a<i.length;a++){var n=i[a],s=n.tileID.canonical.key;r[s]||(r[s]=!0,n.querySourceFeatures(o,e));}return o}(o,i):[]},i.prototype.addSourceType=function(t,e,o){return i.getSourceType(t)?o(new Error('A source type called "'+t+'" already exists.')):(i.setSourceType(t,e),e.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:t,url:e.workerSourceURL},o):o(null,null))},i.prototype.getLight=function(){return this.light.getLight()},i.prototype.setLight=function(e,i){void 0===i&&(i={}),this._checkLoaded();var o=this.light.getLight(),r=!1;for(var a in e)if(!t.deepEqual(e[a],o[a])){r=!0;break}if(r){var n={now:t.browser.now(),transition:t.extend({duration:300,delay:0},this.stylesheet.transition)};this.light.setLight(e,i),this.light.updateTransitions(n);}},i.prototype._validate=function(e,i,o,r,a){return void 0===a&&(a={}),(!a||!1!==a.validate)&&Ue(this,e.call(t.validateStyle,t.extend({key:i,style:this.serialize(),value:o,styleSpec:t.styleSpec},r)))},i.prototype._remove=function(){for(var e in this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.cancel(),this._spriteRequest=null),t.evented.off("pluginStateChange",this._rtlTextPluginCallback),this._layers)this._layers[e].setEventedParent(null);for(var i in this.sourceCaches)this.sourceCaches[i].clearTiles(),this.sourceCaches[i].setEventedParent(null);this.imageManager.setEventedParent(null),this.setEventedParent(null),this.dispatcher.remove();},i.prototype._clearSource=function(t){this.sourceCaches[t].clearTiles();},i.prototype._reloadSource=function(t){this.sourceCaches[t].resume(),this.sourceCaches[t].reload();},i.prototype._updateSources=function(t){for(var e in this.sourceCaches)this.sourceCaches[e].update(t);},i.prototype._generateCollisionBoxes=function(){for(var t in this.sourceCaches)this._reloadSource(t);},i.prototype._updatePlacement=function(e,i,o,r,a){void 0===a&&(a=!1);for(var n=!1,s=!1,l={},c=0,u=this._order;c<u.length;c+=1){var h=this._layers[u[c]];if("symbol"===h.type){if(!l[h.source]){var p=this.sourceCaches[h.source];l[h.source]=p.getRenderableIds(!0).map((function(t){return p.getTileByID(t)})).sort((function(t,e){return e.tileID.overscaledZ-t.tileID.overscaledZ||(t.tileID.isLessThan(e.tileID)?-1:1)}));}var d=this.crossTileSymbolIndex.addLayer(h,l[h.source],e.center.lng);n=n||d;}}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((a=a||this._layerOrderChanged||0===o)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(t.browser.now(),e.zoom))&&(this.pauseablePlacement=new Ae(e,this._order,a,i,o,r,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,l),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(t.browser.now()),s=!0),n&&this.pauseablePlacement.placement.setStale()),s||n)for(var _=0,f=this._order;_<f.length;_+=1){var m=this._layers[f[_]];"symbol"===m.type&&this.placement.updateLayerOpacities(m,l[m.source]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(t.browser.now())},i.prototype._releaseSymbolFadeTiles=function(){for(var t in this.sourceCaches)this.sourceCaches[t].releaseSymbolFadeTiles();},i.prototype.getImages=function(t,e,i){this.imageManager.getImages(e.icons,i),this._updateTilesForChangedImages();var o=this.sourceCaches[e.source];o&&o.setDependencies(e.tileID.key,e.type,e.icons);},i.prototype.getGlyphs=function(t,e,i){this.glyphManager.getGlyphs(e.stacks,i);},i.prototype.getResource=function(e,i,o){return t.makeRequest(i,o)},i}(t.Evented);qe.getSourceType=function(t){return k[t]},qe.setSourceType=function(t,e){k[t]=e;},qe.registerForPluginStateChange=t.registerForPluginStateChange;var Ve=t.createLayout([{name:"a_pos",type:"Int16",components:2}]),Ge=gi("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif","#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}"),We=gi("uniform vec4 u_color;uniform float u_opacity;void main() {gl_FragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),Xe=gi("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"),He=gi("varying vec3 v_data;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);lowp float antialiasblur=v_data.z;float antialiased_blur=-max(blur,antialiasblur);float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));gl_FragColor=opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;attribute vec2 a_pos;varying vec3 v_data;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=vec2(mod(a_pos,2.0)*2.0-1.0);vec2 circle_center=floor(a_pos*0.5);if (u_pitch_with_map) {vec2 corner_position=circle_center;if (u_scale_with_map) {corner_position+=extrude*(radius+stroke_width)*u_extrude_scale;} else {vec4 projected_center=u_matrix*vec4(circle_center,0,1);corner_position+=extrude*(radius+stroke_width)*u_extrude_scale*(projected_center.w/u_camera_to_center_distance);}gl_Position=u_matrix*vec4(corner_position,0,1);} else {gl_Position=u_matrix*vec4(circle_center,0,1);if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),Ke=gi("void main() {gl_FragColor=vec4(1.0);}","attribute vec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),Ye=gi("uniform highp float u_intensity;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);gl_FragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;attribute vec2 a_pos;varying vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 unscaled_extrude=vec2(mod(a_pos,2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec4 pos=vec4(floor(a_pos*0.5)+extrude,0,1);gl_Position=u_matrix*pos;}"),Je=gi("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;varying vec2 v_pos;void main() {float t=texture2D(u_image,v_pos).r;vec4 color=texture2D(u_color_ramp,vec2(t,0.5));gl_FragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(0.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;attribute vec2 a_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),Qe=gi("varying float v_placed;varying float v_notUsed;void main() {float alpha=0.5;gl_FragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {gl_FragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {gl_FragColor*=.1;}}","attribute vec2 a_pos;attribute vec2 a_anchor_pos;attribute vec2 a_extrude;attribute vec2 a_placed;attribute vec2 a_shift;uniform mat4 u_matrix;uniform vec2 u_extrude_scale;uniform float u_camera_to_center_distance;varying float v_placed;varying float v_notUsed;void main() {vec4 projectedPoint=u_matrix*vec4(a_anchor_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);gl_Position=u_matrix*vec4(a_pos,0.0,1.0);gl_Position.xy+=(a_extrude+a_shift)*u_extrude_scale*gl_Position.w*collision_perspective_ratio;v_placed=a_placed.x;v_notUsed=a_placed.y;}"),$e=gi("varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);gl_FragColor=color*alpha*opacity_t;}","attribute vec2 a_pos;attribute float a_radius;attribute vec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd  =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz  /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 quadCenterPos=a_pos;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=collision;gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),ti=gi("uniform highp vec4 u_color;uniform sampler2D u_overlay;varying vec2 v_uv;void main() {vec4 overlay_color=texture2D(u_overlay,v_uv);gl_FragColor=mix(u_color,overlay_color,overlay_color.a);}","attribute vec2 a_pos;varying vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=u_matrix*vec4(a_pos*u_overlay_scale,0,1);}"),ei=gi("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_FragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);}"),ii=gi("varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=outline_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;uniform vec2 u_world;varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}"),oi=gi("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=u_matrix*vec4(a_pos,0,1);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}"),ri=gi("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),ai=gi("varying vec4 v_color;void main() {gl_FragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;attribute vec2 a_pos;attribute vec4 a_normal_ed;varying vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;base=max(0.0,base);height=max(0.0,height);float t=mod(normal.x,2.0);gl_Position=u_matrix*vec4(a_pos,t > 0.0 ? height : base,1);float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;float directional=clamp(dot(normal/16384.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),ni=gi("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);gl_FragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;attribute vec2 a_pos;attribute vec4 a_normal_ed;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;base=max(0.0,base);height=max(0.0,height);float t=mod(normal.x,2.0);float z=t > 0.0 ? height : base;gl_Position=u_matrix*vec4(a_pos,z,1);vec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,z*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),si=gi("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform float u_maxzoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture2D(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggeration=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/ pow(2.0,(u_zoom-u_maxzoom)*exaggeration+19.2562-u_zoom);gl_FragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),li=gi("uniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture2D(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);gl_FragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;}"),ci=gi("uniform lowp float u_device_pixel_ratio;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_linesofar;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_width2=vec2(outset,inset);}"),ui=gi("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;varying highp float v_lineprogress;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture2D(u_image,vec2(v_lineprogress,0.5));gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define MAX_LINE_DISTANCE 32767.0\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_lineprogress;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_lineprogress=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0/MAX_LINE_DISTANCE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_width2=vec2(outset,inset);}"),hi=gi("uniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture2D(u_image,pos_a),texture2D(u_image,pos_b),u_fade);gl_FragColor=color*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),pi=gi("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture2D(u_image,v_tex_a).a;float sdfdist_b=texture2D(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),di=gi("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;varying vec2 v_pos0;varying vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture2D(u_image0,v_pos0);vec4 color1=texture2D(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);gl_FragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos0;varying vec2 v_pos1;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos0=(((a_texture_pos/8192.0)-0.5)/u_buffer_scale )+0.5;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),_i=gi("uniform sampler2D u_texture;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;gl_FragColor=texture2D(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0),0.0,1.0);v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;v_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));}"),fi=gi("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset),0.0,1.0);float gamma_scale=gl_Position.w;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),mi=gi("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;gl_FragColor=texture2D(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale),0.0,1.0);float gamma_scale=gl_Position.w;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}");function gi(t,e){var i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,o={};return {fragmentSource:t=t.replace(i,(function(t,e,i,r,a){return o[a]=!0,"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nvarying "+i+" "+r+" "+a+";\n#else\nuniform "+i+" "+r+" u_"+a+";\n#endif\n":"\n#ifdef HAS_UNIFORM_u_"+a+"\n    "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n"})),vertexSource:e=e.replace(i,(function(t,e,i,r,a){var n="float"===r?"vec2":"vec4",s=a.match(/color/)?"color":n;return o[a]?"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nuniform lowp float u_"+a+"_t;\nattribute "+i+" "+n+" a_"+a+";\nvarying "+i+" "+r+" "+a+";\n#else\nuniform "+i+" "+r+" u_"+a+";\n#endif\n":"vec4"===s?"\n#ifndef HAS_UNIFORM_u_"+a+"\n    "+a+" = a_"+a+";\n#else\n    "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+a+"\n    "+a+" = unpack_mix_"+s+"(a_"+a+", u_"+a+"_t);\n#else\n    "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n":"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nuniform lowp float u_"+a+"_t;\nattribute "+i+" "+n+" a_"+a+";\n#else\nuniform "+i+" "+r+" u_"+a+";\n#endif\n":"vec4"===s?"\n#ifndef HAS_UNIFORM_u_"+a+"\n    "+i+" "+r+" "+a+" = a_"+a+";\n#else\n    "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+a+"\n    "+i+" "+r+" "+a+" = unpack_mix_"+s+"(a_"+a+", u_"+a+"_t);\n#else\n    "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n"}))}}var vi=Object.freeze({__proto__:null,prelude:Ge,background:We,backgroundPattern:Xe,circle:He,clippingMask:Ke,heatmap:Ye,heatmapTexture:Je,collisionBox:Qe,collisionCircle:$e,debug:ti,fill:ei,fillOutline:ii,fillOutlinePattern:oi,fillPattern:ri,fillExtrusion:ai,fillExtrusionPattern:ni,hillshadePrepare:si,hillshade:li,line:ci,lineGradient:ui,linePattern:hi,lineSDF:pi,raster:di,symbolIcon:_i,symbolSDF:fi,symbolTextAndIcon:mi}),yi=function(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;};yi.prototype.bind=function(t,e,i,o,r,a,n,s){this.context=t;for(var l=this.boundPaintVertexBuffers.length!==o.length,c=0;!l&&c<o.length;c++)this.boundPaintVertexBuffers[c]!==o[c]&&(l=!0);t.extVertexArrayObject&&this.vao&&this.boundProgram===e&&this.boundLayoutVertexBuffer===i&&!l&&this.boundIndexBuffer===r&&this.boundVertexOffset===a&&this.boundDynamicVertexBuffer===n&&this.boundDynamicVertexBuffer2===s?(t.bindVertexArrayOES.set(this.vao),n&&n.bind(),r&&r.dynamicDraw&&r.bind(),s&&s.bind()):this.freshBind(e,i,o,r,a,n,s);},yi.prototype.freshBind=function(t,e,i,o,r,a,n){var s,l=t.numAttributes,c=this.context,u=c.gl;if(c.extVertexArrayObject)this.vao&&this.destroy(),this.vao=c.extVertexArrayObject.createVertexArrayOES(),c.bindVertexArrayOES.set(this.vao),s=0,this.boundProgram=t,this.boundLayoutVertexBuffer=e,this.boundPaintVertexBuffers=i,this.boundIndexBuffer=o,this.boundVertexOffset=r,this.boundDynamicVertexBuffer=a,this.boundDynamicVertexBuffer2=n;else {s=c.currentNumAttributes||0;for(var h=l;h<s;h++)u.disableVertexAttribArray(h);}e.enableAttributes(u,t);for(var p=0,d=i;p<d.length;p+=1)d[p].enableAttributes(u,t);a&&a.enableAttributes(u,t),n&&n.enableAttributes(u,t),e.bind(),e.setVertexAttribPointers(u,t,r);for(var _=0,f=i;_<f.length;_+=1){var m=f[_];m.bind(),m.setVertexAttribPointers(u,t,r);}a&&(a.bind(),a.setVertexAttribPointers(u,t,r)),o&&o.bind(),n&&(n.bind(),n.setVertexAttribPointers(u,t,r)),c.currentNumAttributes=l;},yi.prototype.destroy=function(){this.vao&&(this.context.extVertexArrayObject.deleteVertexArrayOES(this.vao),this.vao=null);};var xi=function(t,e,i,o,r){var a=t.gl;this.program=a.createProgram();var n=i?i.defines():[];r&&n.push("#define OVERDRAW_INSPECTOR;");var s=n.concat(Ge.fragmentSource,e.fragmentSource).join("\n"),l=n.concat(Ge.vertexSource,e.vertexSource).join("\n"),c=a.createShader(a.FRAGMENT_SHADER);if(a.isContextLost())this.failedToCreate=!0;else {a.shaderSource(c,s),a.compileShader(c),a.attachShader(this.program,c);var u=a.createShader(a.VERTEX_SHADER);if(a.isContextLost())this.failedToCreate=!0;else {a.shaderSource(u,l),a.compileShader(u),a.attachShader(this.program,u);for(var h=i?i.layoutAttributes:[],p=0;p<h.length;p++)a.bindAttribLocation(this.program,p,h[p].name);a.linkProgram(this.program),a.deleteShader(u),a.deleteShader(c),this.numAttributes=a.getProgramParameter(this.program,a.ACTIVE_ATTRIBUTES),this.attributes={};for(var d={},_=0;_<this.numAttributes;_++){var f=a.getActiveAttrib(this.program,_);f&&(this.attributes[f.name]=a.getAttribLocation(this.program,f.name));}for(var m=a.getProgramParameter(this.program,a.ACTIVE_UNIFORMS),g=0;g<m;g++){var v=a.getActiveUniform(this.program,g);v&&(d[v.name]=a.getUniformLocation(this.program,v.name));}this.fixedUniforms=o(t,d),this.binderUniforms=i?i.getUniforms(t,d):[];}}};function bi(t,e,i){var o=1/pe(i,1,e.transform.tileZoom),r=Math.pow(2,i.tileID.overscaledZ),a=i.tileSize*Math.pow(2,e.transform.tileZoom)/r,n=a*(i.tileID.canonical.x+i.tileID.wrap*r),s=a*i.tileID.canonical.y;return {u_image:0,u_texsize:i.imageAtlasTexture.size,u_scale:[o,t.fromScale,t.toScale],u_fade:t.t,u_pixel_coord_upper:[n>>16,s>>16],u_pixel_coord_lower:[65535&n,65535&s]}}xi.prototype.draw=function(t,e,i,o,r,a,n,s,l,c,u,h,p,d,_,f){var m,g=t.gl;if(!this.failedToCreate){for(var v in t.program.set(this.program),t.setDepthMode(i),t.setStencilMode(o),t.setColorMode(r),t.setCullFace(a),this.fixedUniforms)this.fixedUniforms[v].set(n[v]);d&&d.setUniforms(t,this.binderUniforms,h,{zoom:p});for(var y=(m={},m[g.LINES]=2,m[g.TRIANGLES]=3,m[g.LINE_STRIP]=1,m)[e],x=0,b=u.get();x<b.length;x+=1){var w=b[x],T=w.vaos||(w.vaos={});(T[s]||(T[s]=new yi)).bind(t,this,l,d?d.getPaintVertexBuffers():[],c,w.vertexOffset,_,f),g.drawElements(e,w.primitiveLength*y,g.UNSIGNED_SHORT,w.primitiveOffset*y*2);}}};var wi=function(e,i,o,r){var a=i.style.light,n=a.properties.get("position"),s=[n.x,n.y,n.z],l=t.create$1();"viewport"===a.properties.get("anchor")&&t.fromRotation(l,-i.transform.angle),t.transformMat3(s,s,l);var c=a.properties.get("color");return {u_matrix:e,u_lightpos:s,u_lightintensity:a.properties.get("intensity"),u_lightcolor:[c.r,c.g,c.b],u_vertical_gradient:+o,u_opacity:r}},Ti=function(e,i,o,r,a,n,s){return t.extend(wi(e,i,o,r),bi(n,i,s),{u_height_factor:-Math.pow(2,a.overscaledZ)/s.tileSize/8})},Ei=function(t){return {u_matrix:t}},Ii=function(e,i,o,r){return t.extend(Ei(e),bi(o,i,r))},Pi=function(t,e){return {u_matrix:t,u_world:e}},Si=function(e,i,o,r,a){return t.extend(Ii(e,i,o,r),{u_world:a})},Ci=function(e,i,o,r){var a,n,s=e.transform;if("map"===r.paint.get("circle-pitch-alignment")){var l=pe(o,1,s.zoom);a=!0,n=[l,l];}else a=!1,n=s.pixelsToGLUnits;return {u_camera_to_center_distance:s.cameraToCenterDistance,u_scale_with_map:+("map"===r.paint.get("circle-pitch-scale")),u_matrix:e.translatePosMatrix(i.posMatrix,o,r.paint.get("circle-translate"),r.paint.get("circle-translate-anchor")),u_pitch_with_map:+a,u_device_pixel_ratio:t.browser.devicePixelRatio,u_extrude_scale:n}},zi=function(t,e,i){var o=pe(i,1,e.zoom),r=Math.pow(2,e.zoom-i.tileID.overscaledZ),a=i.tileID.overscaleFactor();return {u_matrix:t,u_camera_to_center_distance:e.cameraToCenterDistance,u_pixels_to_tile_units:o,u_extrude_scale:[e.pixelsToGLUnits[0]/(o*r),e.pixelsToGLUnits[1]/(o*r)],u_overscale_factor:a}},Di=function(t,e,i){return {u_matrix:t,u_inv_matrix:e,u_camera_to_center_distance:i.cameraToCenterDistance,u_viewport_size:[i.width,i.height]}},Mi=function(t,e,i){return void 0===i&&(i=1),{u_matrix:t,u_color:e,u_overlay:0,u_overlay_scale:i}},Li=function(t){return {u_matrix:t}},Ai=function(t,e,i,o){return {u_matrix:t,u_extrude_scale:pe(e,1,i),u_intensity:o}},Ri=function(e,i,o){var r=e.transform;return {u_matrix:Ui(e,i,o),u_ratio:1/pe(i,1,r.zoom),u_device_pixel_ratio:t.browser.devicePixelRatio,u_units_to_pixels:[1/r.pixelsToGLUnits[0],1/r.pixelsToGLUnits[1]]}},ki=function(e,i,o){return t.extend(Ri(e,i,o),{u_image:0})},Bi=function(e,i,o,r){var a=e.transform,n=Fi(i,a);return {u_matrix:Ui(e,i,o),u_texsize:i.imageAtlasTexture.size,u_ratio:1/pe(i,1,a.zoom),u_device_pixel_ratio:t.browser.devicePixelRatio,u_image:0,u_scale:[n,r.fromScale,r.toScale],u_fade:r.t,u_units_to_pixels:[1/a.pixelsToGLUnits[0],1/a.pixelsToGLUnits[1]]}},Oi=function(e,i,o,r,a){var n=e.lineAtlas,s=Fi(i,e.transform),l="round"===o.layout.get("line-cap"),c=n.getDash(r.from,l),u=n.getDash(r.to,l),h=c.width*a.fromScale,p=u.width*a.toScale;return t.extend(Ri(e,i,o),{u_patternscale_a:[s/h,-c.height/2],u_patternscale_b:[s/p,-u.height/2],u_sdfgamma:n.width/(256*Math.min(h,p)*t.browser.devicePixelRatio)/2,u_image:0,u_tex_y_a:c.y,u_tex_y_b:u.y,u_mix:a.t})};function Fi(t,e){return 1/pe(t,1,e.tileZoom)}function Ui(t,e,i){return t.translatePosMatrix(e.tileID.posMatrix,e,i.paint.get("line-translate"),i.paint.get("line-translate-anchor"))}var Ni=function(t,e,i,o,r){return {u_matrix:t,u_tl_parent:e,u_scale_parent:i,u_buffer_scale:1,u_fade_t:o.mix,u_opacity:o.opacity*r.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:r.paint.get("raster-brightness-min"),u_brightness_high:r.paint.get("raster-brightness-max"),u_saturation_factor:(n=r.paint.get("raster-saturation"),n>0?1-1/(1.001-n):-n),u_contrast_factor:(a=r.paint.get("raster-contrast"),a>0?1/(1-a):1+a),u_spin_weights:Zi(r.paint.get("raster-hue-rotate"))};var a,n;};function Zi(t){t*=Math.PI/180;var e=Math.sin(t),i=Math.cos(t);return [(2*i+1)/3,(-Math.sqrt(3)*e-i+1)/3,(Math.sqrt(3)*e-i+1)/3]}var ji,qi=function(t,e,i,o,r,a,n,s,l,c){var u=r.transform;return {u_is_size_zoom_constant:+("constant"===t||"source"===t),u_is_size_feature_constant:+("constant"===t||"camera"===t),u_size_t:e?e.uSizeT:0,u_size:e?e.uSize:0,u_camera_to_center_distance:u.cameraToCenterDistance,u_pitch:u.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:u.width/u.height,u_fade_change:r.options.fadeDuration?r.symbolFadeChange:1,u_matrix:a,u_label_plane_matrix:n,u_coord_matrix:s,u_is_text:+l,u_pitch_with_map:+o,u_texsize:c,u_texture:0}},Vi=function(e,i,o,r,a,n,s,l,c,u,h){var p=a.transform;return t.extend(qi(e,i,o,r,a,n,s,l,c,u),{u_gamma_scale:r?Math.cos(p._pitch)*p.cameraToCenterDistance:1,u_device_pixel_ratio:t.browser.devicePixelRatio,u_is_halo:+h})},Gi=function(e,i,o,r,a,n,s,l,c,u){return t.extend(Vi(e,i,o,r,a,n,s,l,!0,c,!0),{u_texsize_icon:u,u_texture_icon:1})},Wi=function(t,e,i){return {u_matrix:t,u_opacity:e,u_color:i}},Xi=function(e,i,o,r,a,n){return t.extend(function(t,e,i,o){var r=i.imageManager.getPattern(t.from.toString()),a=i.imageManager.getPattern(t.to.toString()),n=i.imageManager.getPixelSize(),s=n.width,l=n.height,c=Math.pow(2,o.tileID.overscaledZ),u=o.tileSize*Math.pow(2,i.transform.tileZoom)/c,h=u*(o.tileID.canonical.x+o.tileID.wrap*c),p=u*o.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:r.tl,u_pattern_br_a:r.br,u_pattern_tl_b:a.tl,u_pattern_br_b:a.br,u_texsize:[s,l],u_mix:e.t,u_pattern_size_a:r.displaySize,u_pattern_size_b:a.displaySize,u_scale_a:e.fromScale,u_scale_b:e.toScale,u_tile_units_to_pixels:1/pe(o,1,i.transform.tileZoom),u_pixel_coord_upper:[h>>16,p>>16],u_pixel_coord_lower:[65535&h,65535&p]}}(r,n,o,a),{u_matrix:e,u_opacity:i})},Hi={fillExtrusion:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_lightpos:new t.Uniform3f(e,i.u_lightpos),u_lightintensity:new t.Uniform1f(e,i.u_lightintensity),u_lightcolor:new t.Uniform3f(e,i.u_lightcolor),u_vertical_gradient:new t.Uniform1f(e,i.u_vertical_gradient),u_opacity:new t.Uniform1f(e,i.u_opacity)}},fillExtrusionPattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_lightpos:new t.Uniform3f(e,i.u_lightpos),u_lightintensity:new t.Uniform1f(e,i.u_lightintensity),u_lightcolor:new t.Uniform3f(e,i.u_lightcolor),u_vertical_gradient:new t.Uniform1f(e,i.u_vertical_gradient),u_height_factor:new t.Uniform1f(e,i.u_height_factor),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade),u_opacity:new t.Uniform1f(e,i.u_opacity)}},fill:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},fillPattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}},fillOutline:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_world:new t.Uniform2f(e,i.u_world)}},fillOutlinePattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_world:new t.Uniform2f(e,i.u_world),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}},circle:function(e,i){return {u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_scale_with_map:new t.Uniform1i(e,i.u_scale_with_map),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_extrude_scale:new t.Uniform2f(e,i.u_extrude_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},collisionBox:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pixels_to_tile_units:new t.Uniform1f(e,i.u_pixels_to_tile_units),u_extrude_scale:new t.Uniform2f(e,i.u_extrude_scale),u_overscale_factor:new t.Uniform1f(e,i.u_overscale_factor)}},collisionCircle:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_inv_matrix:new t.UniformMatrix4f(e,i.u_inv_matrix),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_viewport_size:new t.Uniform2f(e,i.u_viewport_size)}},debug:function(e,i){return {u_color:new t.UniformColor(e,i.u_color),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_overlay:new t.Uniform1i(e,i.u_overlay),u_overlay_scale:new t.Uniform1f(e,i.u_overlay_scale)}},clippingMask:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},heatmap:function(e,i){return {u_extrude_scale:new t.Uniform1f(e,i.u_extrude_scale),u_intensity:new t.Uniform1f(e,i.u_intensity),u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},heatmapTexture:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_world:new t.Uniform2f(e,i.u_world),u_image:new t.Uniform1i(e,i.u_image),u_color_ramp:new t.Uniform1i(e,i.u_color_ramp),u_opacity:new t.Uniform1f(e,i.u_opacity)}},hillshade:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_image:new t.Uniform1i(e,i.u_image),u_latrange:new t.Uniform2f(e,i.u_latrange),u_light:new t.Uniform2f(e,i.u_light),u_shadow:new t.UniformColor(e,i.u_shadow),u_highlight:new t.UniformColor(e,i.u_highlight),u_accent:new t.UniformColor(e,i.u_accent)}},hillshadePrepare:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_image:new t.Uniform1i(e,i.u_image),u_dimension:new t.Uniform2f(e,i.u_dimension),u_zoom:new t.Uniform1f(e,i.u_zoom),u_maxzoom:new t.Uniform1f(e,i.u_maxzoom),u_unpack:new t.Uniform4f(e,i.u_unpack)}},line:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels)}},lineGradient:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_image:new t.Uniform1i(e,i.u_image)}},linePattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_texsize:new t.Uniform2f(e,i.u_texsize),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_image:new t.Uniform1i(e,i.u_image),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}},lineSDF:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_patternscale_a:new t.Uniform2f(e,i.u_patternscale_a),u_patternscale_b:new t.Uniform2f(e,i.u_patternscale_b),u_sdfgamma:new t.Uniform1f(e,i.u_sdfgamma),u_image:new t.Uniform1i(e,i.u_image),u_tex_y_a:new t.Uniform1f(e,i.u_tex_y_a),u_tex_y_b:new t.Uniform1f(e,i.u_tex_y_b),u_mix:new t.Uniform1f(e,i.u_mix)}},raster:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_tl_parent:new t.Uniform2f(e,i.u_tl_parent),u_scale_parent:new t.Uniform1f(e,i.u_scale_parent),u_buffer_scale:new t.Uniform1f(e,i.u_buffer_scale),u_fade_t:new t.Uniform1f(e,i.u_fade_t),u_opacity:new t.Uniform1f(e,i.u_opacity),u_image0:new t.Uniform1i(e,i.u_image0),u_image1:new t.Uniform1i(e,i.u_image1),u_brightness_low:new t.Uniform1f(e,i.u_brightness_low),u_brightness_high:new t.Uniform1f(e,i.u_brightness_high),u_saturation_factor:new t.Uniform1f(e,i.u_saturation_factor),u_contrast_factor:new t.Uniform1f(e,i.u_contrast_factor),u_spin_weights:new t.Uniform3f(e,i.u_spin_weights)}},symbolIcon:function(e,i){return {u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texture:new t.Uniform1i(e,i.u_texture)}},symbolSDF:function(e,i){return {u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texture:new t.Uniform1i(e,i.u_texture),u_gamma_scale:new t.Uniform1f(e,i.u_gamma_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_is_halo:new t.Uniform1i(e,i.u_is_halo)}},symbolTextAndIcon:function(e,i){return {u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texsize_icon:new t.Uniform2f(e,i.u_texsize_icon),u_texture:new t.Uniform1i(e,i.u_texture),u_texture_icon:new t.Uniform1i(e,i.u_texture_icon),u_gamma_scale:new t.Uniform1f(e,i.u_gamma_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_is_halo:new t.Uniform1i(e,i.u_is_halo)}},background:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_opacity:new t.Uniform1f(e,i.u_opacity),u_color:new t.UniformColor(e,i.u_color)}},backgroundPattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_opacity:new t.Uniform1f(e,i.u_opacity),u_image:new t.Uniform1i(e,i.u_image),u_pattern_tl_a:new t.Uniform2f(e,i.u_pattern_tl_a),u_pattern_br_a:new t.Uniform2f(e,i.u_pattern_br_a),u_pattern_tl_b:new t.Uniform2f(e,i.u_pattern_tl_b),u_pattern_br_b:new t.Uniform2f(e,i.u_pattern_br_b),u_texsize:new t.Uniform2f(e,i.u_texsize),u_mix:new t.Uniform1f(e,i.u_mix),u_pattern_size_a:new t.Uniform2f(e,i.u_pattern_size_a),u_pattern_size_b:new t.Uniform2f(e,i.u_pattern_size_b),u_scale_a:new t.Uniform1f(e,i.u_scale_a),u_scale_b:new t.Uniform1f(e,i.u_scale_b),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.Uniform1f(e,i.u_tile_units_to_pixels)}}};function Ki(e,i,o,r,a,n,s){for(var l=e.context,c=l.gl,u=e.useProgram("collisionBox"),h=[],p=0,d=0,_=0;_<r.length;_++){var f=r[_],m=i.getTile(f),g=m.getBucket(o);if(g){var v=f.posMatrix;0===a[0]&&0===a[1]||(v=e.translatePosMatrix(f.posMatrix,m,a,n));var y=s?g.textCollisionBox:g.iconCollisionBox,x=g.collisionCircleArray;if(x.length>0){var b=t.create(),w=v;t.mul(b,g.placementInvProjMatrix,e.transform.glCoordMatrix),t.mul(b,b,g.placementViewportMatrix),h.push({circleArray:x,circleOffset:d,transform:w,invTransform:b}),d=p+=x.length/4;}y&&u.draw(l,c.LINES,It.disabled,Pt.disabled,e.colorModeForRenderPass(),Ct.disabled,zi(v,e.transform,m),o.id,y.layoutVertexBuffer,y.indexBuffer,y.segments,null,e.transform.zoom,null,null,y.collisionVertexBuffer);}}if(s&&h.length){var T=e.useProgram("collisionCircle"),E=new t.StructArrayLayout2f1f2i16;E.resize(4*p),E._trim();for(var I=0,P=0,S=h;P<S.length;P+=1)for(var C=S[P],z=0;z<C.circleArray.length/4;z++){var D=4*z,M=C.circleArray[D+0],L=C.circleArray[D+1],A=C.circleArray[D+2],R=C.circleArray[D+3];E.emplace(I++,M,L,A,R,0),E.emplace(I++,M,L,A,R,1),E.emplace(I++,M,L,A,R,2),E.emplace(I++,M,L,A,R,3);}(!ji||ji.length<2*p)&&(ji=function(e){var i=2*e,o=new t.StructArrayLayout3ui6;o.resize(i),o._trim();for(var r=0;r<i;r++){var a=6*r;o.uint16[a+0]=4*r+0,o.uint16[a+1]=4*r+1,o.uint16[a+2]=4*r+2,o.uint16[a+3]=4*r+2,o.uint16[a+4]=4*r+3,o.uint16[a+5]=4*r+0;}return o}(p));for(var k=l.createIndexBuffer(ji,!0),B=l.createVertexBuffer(E,t.collisionCircleLayout.members,!0),O=0,F=h;O<F.length;O+=1){var U=F[O],N=Di(U.transform,U.invTransform,e.transform);T.draw(l,c.TRIANGLES,It.disabled,Pt.disabled,e.colorModeForRenderPass(),Ct.disabled,N,o.id,B,k,t.SegmentVector.simpleSegment(0,2*U.circleOffset,U.circleArray.length,U.circleArray.length/2),null,e.transform.zoom,null,null,null);}B.destroy(),k.destroy();}}var Yi=t.identity(new Float32Array(16));function Ji(e,i,o,r,a,n){var s=t.getAnchorAlignment(e),l=-(s.horizontalAlign-.5)*i,c=-(s.verticalAlign-.5)*o,u=t.evaluateVariableOffset(e,r);return new t.Point((l/a+u[0])*n,(c/a+u[1])*n)}function Qi(e,i,o,r,a,n,s,l,c,u,h){var p=e.text.placedSymbolArray,d=e.text.dynamicLayoutVertexArray,_=e.icon.dynamicLayoutVertexArray,f={};d.clear();for(var m=0;m<p.length;m++){var g=p.get(m),v=g.hidden||!g.crossTileID||e.allowVerticalPlacement&&!g.placedOrientation?null:r[g.crossTileID];if(v){var y=new t.Point(g.anchorX,g.anchorY),x=$t(y,o?l:s),b=te(n.cameraToCenterDistance,x.signedDistanceFromCamera),w=a.evaluateSizeForFeature(e.textSizeData,u,g)*b/t.ONE_EM;o&&(w*=e.tilePixelRatio/c);for(var T=Ji(v.anchor,v.width,v.height,v.textOffset,v.textBoxScale,w),E=o?$t(y.add(T),s).point:x.point.add(i?T.rotate(-n.angle):T),I=e.allowVerticalPlacement&&g.placedOrientation===t.WritingMode.vertical?Math.PI/2:0,P=0;P<g.numGlyphs;P++)t.addDynamicAttributes(d,E,I);h&&g.associatedIconIndex>=0&&(f[g.associatedIconIndex]={shiftedAnchor:E,angle:I});}else ce(g.numGlyphs,d);}if(h){_.clear();for(var S=e.icon.placedSymbolArray,C=0;C<S.length;C++){var z=S.get(C);if(z.hidden)ce(z.numGlyphs,_);else {var D=f[C];if(D)for(var M=0;M<z.numGlyphs;M++)t.addDynamicAttributes(_,D.shiftedAnchor,D.angle);else ce(z.numGlyphs,_);}}e.icon.dynamicLayoutVertexBuffer.updateData(_);}e.text.dynamicLayoutVertexBuffer.updateData(d);}function $i(t,e,i){return i.iconsInText&&e?"symbolTextAndIcon":t?"symbolSDF":"symbolIcon"}function to(e,i,o,r,a,n,s,l,c,u,h,p){for(var d=e.context,_=d.gl,f=e.transform,m="map"===l,g="map"===c,v=m&&"point"!==o.layout.get("symbol-placement"),y=m&&!g&&!v,x=void 0!==o.layout.get("symbol-sort-key").constantOr(1),b=e.depthModeForSublayer(0,It.ReadOnly),w=o.layout.get("text-variable-anchor"),T=[],E=0,I=r;E<I.length;E+=1){var P=I[E],S=i.getTile(P),C=S.getBucket(o);if(C){var z=a?C.text:C.icon;if(z&&z.segments.get().length){var D=z.programConfigurations.get(o.id),M=a||C.sdfIcons,L=a?C.textSizeData:C.iconSizeData,A=g||0!==f.pitch,R=e.useProgram($i(M,a,C),D),k=t.evaluateSizeForZoom(L,f.zoom),B=void 0,O=[0,0],F=void 0,U=void 0,N=null,Z=void 0;if(a)F=S.glyphAtlasTexture,U=_.LINEAR,B=S.glyphAtlasTexture.size,C.iconsInText&&(O=S.imageAtlasTexture.size,N=S.imageAtlasTexture,Z=A||e.options.rotating||e.options.zooming||"composite"===L.kind||"camera"===L.kind?_.LINEAR:_.NEAREST);else {var j=1!==o.layout.get("icon-size").constantOr(0)||C.iconsNeedLinear;F=S.imageAtlasTexture,U=M||e.options.rotating||e.options.zooming||j||A?_.LINEAR:_.NEAREST,B=S.imageAtlasTexture.size;}var q=pe(S,1,e.transform.zoom),V=Jt(P.posMatrix,g,m,e.transform,q),G=Qt(P.posMatrix,g,m,e.transform,q),W=w&&C.hasTextData(),X="none"!==o.layout.get("icon-text-fit")&&W&&C.hasIconData();v&&ie(C,P.posMatrix,e,a,V,G,g,u);var H=e.translatePosMatrix(P.posMatrix,S,n,s),K=v||a&&w||X?Yi:V,Y=e.translatePosMatrix(G,S,n,s,!0),J=M&&0!==o.paint.get(a?"text-halo-width":"icon-halo-width").constantOr(1),Q={program:R,buffers:z,uniformValues:M?C.iconsInText?Gi(L.kind,k,y,g,e,H,K,Y,B,O):Vi(L.kind,k,y,g,e,H,K,Y,a,B,!0):qi(L.kind,k,y,g,e,H,K,Y,a,B),atlasTexture:F,atlasTextureIcon:N,atlasInterpolation:U,atlasInterpolationIcon:Z,isSDF:M,hasHalo:J};if(x)for(var $=0,tt=z.segments.get();$<tt.length;$+=1){var et=tt[$];T.push({segments:new t.SegmentVector([et]),sortKey:et.sortKey,state:Q});}else T.push({segments:z.segments,sortKey:0,state:Q});}}}x&&T.sort((function(t,e){return t.sortKey-e.sortKey}));for(var it=0,ot=T;it<ot.length;it+=1){var rt=ot[it],at=rt.state;if(d.activeTexture.set(_.TEXTURE0),at.atlasTexture.bind(at.atlasInterpolation,_.CLAMP_TO_EDGE),at.atlasTextureIcon&&(d.activeTexture.set(_.TEXTURE1),at.atlasTextureIcon&&at.atlasTextureIcon.bind(at.atlasInterpolationIcon,_.CLAMP_TO_EDGE)),at.isSDF){var nt=at.uniformValues;at.hasHalo&&(nt.u_is_halo=1,eo(at.buffers,rt.segments,o,e,at.program,b,h,p,nt)),nt.u_is_halo=0;}eo(at.buffers,rt.segments,o,e,at.program,b,h,p,at.uniformValues);}}function eo(t,e,i,o,r,a,n,s,l){var c=o.context;r.draw(c,c.gl.TRIANGLES,a,n,s,Ct.disabled,l,i.id,t.layoutVertexBuffer,t.indexBuffer,e,i.paint,o.transform.zoom,t.programConfigurations.get(i.id),t.dynamicLayoutVertexBuffer,t.opacityVertexBuffer);}function io(t,e,i,o,r,a,n){var s,l,c,u,h,p=t.context.gl,d=i.paint.get("fill-pattern"),_=d&&d.constantOr(1),f=i.getCrossfadeParameters();n?(l=_&&!i.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",s=p.LINES):(l=_?"fillPattern":"fill",s=p.TRIANGLES);for(var m=0,g=o;m<g.length;m+=1){var v=g[m],y=e.getTile(v);if(!_||y.patternsLoaded()){var x=y.getBucket(i);if(x){var b=x.programConfigurations.get(i.id),w=t.useProgram(l,b);_&&(t.context.activeTexture.set(p.TEXTURE0),y.imageAtlasTexture.bind(p.LINEAR,p.CLAMP_TO_EDGE),b.updatePaintBuffers(f));var T=d.constantOr(null);if(T&&y.imageAtlas){var E=y.imageAtlas,I=E.patternPositions[T.to.toString()],P=E.patternPositions[T.from.toString()];I&&P&&b.setConstantPatternPositions(I,P);}var S=t.translatePosMatrix(v.posMatrix,y,i.paint.get("fill-translate"),i.paint.get("fill-translate-anchor"));if(n){u=x.indexBuffer2,h=x.segments2;var C=[p.drawingBufferWidth,p.drawingBufferHeight];c="fillOutlinePattern"===l&&_?Si(S,t,f,y,C):Pi(S,C);}else u=x.indexBuffer,h=x.segments,c=_?Ii(S,t,f,y):Ei(S);w.draw(t.context,s,r,t.stencilModeForClipping(v),a,Ct.disabled,c,i.id,x.layoutVertexBuffer,u,h,i.paint,t.transform.zoom,b);}}}}function oo(t,e,i,o,r,a,n){for(var s=t.context,l=s.gl,c=i.paint.get("fill-extrusion-pattern"),u=c.constantOr(1),h=i.getCrossfadeParameters(),p=i.paint.get("fill-extrusion-opacity"),d=0,_=o;d<_.length;d+=1){var f=_[d],m=e.getTile(f),g=m.getBucket(i);if(g){var v=g.programConfigurations.get(i.id),y=t.useProgram(u?"fillExtrusionPattern":"fillExtrusion",v);u&&(t.context.activeTexture.set(l.TEXTURE0),m.imageAtlasTexture.bind(l.LINEAR,l.CLAMP_TO_EDGE),v.updatePaintBuffers(h));var x=c.constantOr(null);if(x&&m.imageAtlas){var b=m.imageAtlas,w=b.patternPositions[x.to.toString()],T=b.patternPositions[x.from.toString()];w&&T&&v.setConstantPatternPositions(w,T);}var E=t.translatePosMatrix(f.posMatrix,m,i.paint.get("fill-extrusion-translate"),i.paint.get("fill-extrusion-translate-anchor")),I=i.paint.get("fill-extrusion-vertical-gradient"),P=u?Ti(E,t,I,p,f,h,m):wi(E,t,I,p);y.draw(s,s.gl.TRIANGLES,r,a,n,Ct.backCCW,P,i.id,g.layoutVertexBuffer,g.indexBuffer,g.segments,i.paint,t.transform.zoom,v);}}}function ro(e,i,o,r,a,n){var s=e.context,l=s.gl,c=i.fbo;if(c){var u=e.useProgram("hillshade");s.activeTexture.set(l.TEXTURE0),l.bindTexture(l.TEXTURE_2D,c.colorAttachment.get());var h=function(e,i,o){var r=o.paint.get("hillshade-shadow-color"),a=o.paint.get("hillshade-highlight-color"),n=o.paint.get("hillshade-accent-color"),s=o.paint.get("hillshade-illumination-direction")*(Math.PI/180);"viewport"===o.paint.get("hillshade-illumination-anchor")&&(s-=e.transform.angle);var l,c,u,h=!e.options.moving;return {u_matrix:e.transform.calculatePosMatrix(i.tileID.toUnwrapped(),h),u_image:0,u_latrange:(l=i.tileID,c=Math.pow(2,l.canonical.z),u=l.canonical.y,[new t.MercatorCoordinate(0,u/c).toLngLat().lat,new t.MercatorCoordinate(0,(u+1)/c).toLngLat().lat]),u_light:[o.paint.get("hillshade-exaggeration"),s],u_shadow:r,u_highlight:a,u_accent:n}}(e,i,o);u.draw(s,l.TRIANGLES,r,a,n,Ct.disabled,h,o.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments);}}function ao(e,i,o,r,a,n,s){var l=e.context,c=l.gl,u=i.dem;if(u&&u.data){var h=u.dim,p=u.stride,d=u.getPixels();if(l.activeTexture.set(c.TEXTURE1),l.pixelStoreUnpackPremultiplyAlpha.set(!1),i.demTexture=i.demTexture||e.getTileTexture(p),i.demTexture){var _=i.demTexture;_.update(d,{premultiply:!1}),_.bind(c.NEAREST,c.CLAMP_TO_EDGE);}else i.demTexture=new t.Texture(l,d,c.RGBA,{premultiply:!1}),i.demTexture.bind(c.NEAREST,c.CLAMP_TO_EDGE);l.activeTexture.set(c.TEXTURE0);var f=i.fbo;if(!f){var m=new t.Texture(l,{width:h,height:h,data:null},c.RGBA);m.bind(c.LINEAR,c.CLAMP_TO_EDGE),(f=i.fbo=l.createFramebuffer(h,h,!0)).colorAttachment.set(m.texture);}l.bindFramebuffer.set(f.framebuffer),l.viewport.set([0,0,h,h]),e.useProgram("hillshadePrepare").draw(l,c.TRIANGLES,a,n,s,Ct.disabled,function(e,i,o){var r=i.stride,a=t.create();return t.ortho(a,0,t.EXTENT,-t.EXTENT,0,0,1),t.translate(a,a,[0,-t.EXTENT,0]),{u_matrix:a,u_image:1,u_dimension:[r,r],u_zoom:e.overscaledZ,u_maxzoom:o,u_unpack:i.getUnpackVector()}}(i.tileID,u,r),o.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments),i.needsHillshadePrepare=!1;}}function no(e,i,o,r,a){var n=r.paint.get("raster-fade-duration");if(n>0){var s=t.browser.now(),l=(s-e.timeAdded)/n,c=i?(s-i.timeAdded)/n:-1,u=o.getSource(),h=a.coveringZoomLevel({tileSize:u.tileSize,roundZoom:u.roundZoom}),p=!i||Math.abs(i.tileID.overscaledZ-h)>Math.abs(e.tileID.overscaledZ-h),d=p&&e.refreshedUponExpiration?1:t.clamp(p?l:1-c,0,1);return e.refreshedUponExpiration&&l>=1&&(e.refreshedUponExpiration=!1),i?{opacity:1,mix:1-d}:{opacity:d,mix:0}}return {opacity:1,mix:0}}var so=new t.Color(1,0,0,1),lo=new t.Color(0,1,0,1),co=new t.Color(0,0,1,1),uo=new t.Color(1,0,1,1),ho=new t.Color(0,1,1,1);function po(t,e,i,o){fo(t,0,e+i/2,t.transform.width,i,o);}function _o(t,e,i,o){fo(t,e-i/2,0,i,t.transform.height,o);}function fo(e,i,o,r,a,n){var s=e.context,l=s.gl;l.enable(l.SCISSOR_TEST),l.scissor(i*t.browser.devicePixelRatio,o*t.browser.devicePixelRatio,r*t.browser.devicePixelRatio,a*t.browser.devicePixelRatio),s.clear({color:n}),l.disable(l.SCISSOR_TEST);}function mo(e,i,o){var r=e.context,a=r.gl,n=o.posMatrix,s=e.useProgram("debug"),l=It.disabled,c=Pt.disabled,u=e.colorModeForRenderPass();r.activeTexture.set(a.TEXTURE0),e.emptyTexture.bind(a.LINEAR,a.CLAMP_TO_EDGE),s.draw(r,a.LINE_STRIP,l,c,u,Ct.disabled,Mi(n,t.Color.red),"$debug",e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);var h=i.getTileByID(o.key).latestRawTileData,p=Math.floor((h&&h.byteLength||0)/1024),d=i.getTile(o).tileSize,_=512/Math.min(d,512)*(o.overscaledZ/e.transform.zoom)*.5,f=o.canonical.toString();o.overscaledZ!==o.canonical.z&&(f+=" => "+o.overscaledZ),function(t,e){t.initDebugOverlayCanvas();var i=t.debugOverlayCanvas,o=t.context.gl,r=t.debugOverlayCanvas.getContext("2d");r.clearRect(0,0,i.width,i.height),r.shadowColor="white",r.shadowBlur=2,r.lineWidth=1.5,r.strokeStyle="white",r.textBaseline="top",r.font="bold 36px Open Sans, sans-serif",r.fillText(e,5,5),r.strokeText(e,5,5),t.debugOverlayTexture.update(i),t.debugOverlayTexture.bind(o.LINEAR,o.CLAMP_TO_EDGE);}(e,f+" "+p+"kb"),s.draw(r,a.TRIANGLES,l,c,St.alphaBlended,Ct.disabled,Mi(n,t.Color.transparent,_),"$debug",e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments);}var go={symbol:function(e,i,o,r,a){if("translucent"===e.renderPass){var n=Pt.disabled,s=e.colorModeForRenderPass();o.layout.get("text-variable-anchor")&&function(e,i,o,r,a,n,s){for(var l=i.transform,c="map"===a,u="map"===n,h=0,p=e;h<p.length;h+=1){var d=p[h],_=r.getTile(d),f=_.getBucket(o);if(f&&f.text&&f.text.segments.get().length){var m=t.evaluateSizeForZoom(f.textSizeData,l.zoom),g=pe(_,1,i.transform.zoom),v=Jt(d.posMatrix,u,c,i.transform,g),y="none"!==o.layout.get("icon-text-fit")&&f.hasIconData();if(m){var x=Math.pow(2,l.zoom-_.tileID.overscaledZ);Qi(f,c,u,s,t.symbolSize,l,v,d.posMatrix,x,m,y);}}}}(r,e,o,i,o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),a),0!==o.paint.get("icon-opacity").constantOr(1)&&to(e,i,o,r,!1,o.paint.get("icon-translate"),o.paint.get("icon-translate-anchor"),o.layout.get("icon-rotation-alignment"),o.layout.get("icon-pitch-alignment"),o.layout.get("icon-keep-upright"),n,s),0!==o.paint.get("text-opacity").constantOr(1)&&to(e,i,o,r,!0,o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),o.layout.get("text-rotation-alignment"),o.layout.get("text-pitch-alignment"),o.layout.get("text-keep-upright"),n,s),i.map.showCollisionBoxes&&(Ki(e,i,o,r,o.paint.get("text-translate"),o.paint.get("text-translate-anchor"),!0),Ki(e,i,o,r,o.paint.get("icon-translate"),o.paint.get("icon-translate-anchor"),!1));}},circle:function(e,i,o,r){if("translucent"===e.renderPass){var a=o.paint.get("circle-opacity"),n=o.paint.get("circle-stroke-width"),s=o.paint.get("circle-stroke-opacity"),l=void 0!==o.layout.get("circle-sort-key").constantOr(1);if(0!==a.constantOr(1)||0!==n.constantOr(1)&&0!==s.constantOr(1)){for(var c=e.context,u=c.gl,h=e.depthModeForSublayer(0,It.ReadOnly),p=Pt.disabled,d=e.colorModeForRenderPass(),_=[],f=0;f<r.length;f++){var m=r[f],g=i.getTile(m),v=g.getBucket(o);if(v){var y=v.programConfigurations.get(o.id),x={programConfiguration:y,program:e.useProgram("circle",y),layoutVertexBuffer:v.layoutVertexBuffer,indexBuffer:v.indexBuffer,uniformValues:Ci(e,m,g,o)};if(l)for(var b=0,w=v.segments.get();b<w.length;b+=1){var T=w[b];_.push({segments:new t.SegmentVector([T]),sortKey:T.sortKey,state:x});}else _.push({segments:v.segments,sortKey:0,state:x});}}l&&_.sort((function(t,e){return t.sortKey-e.sortKey}));for(var E=0,I=_;E<I.length;E+=1){var P=I[E],S=P.state;S.program.draw(c,u.TRIANGLES,h,p,d,Ct.disabled,S.uniformValues,o.id,S.layoutVertexBuffer,S.indexBuffer,P.segments,o.paint,e.transform.zoom,S.programConfiguration);}}}},heatmap:function(e,i,o,r){if(0!==o.paint.get("heatmap-opacity"))if("offscreen"===e.renderPass){var a=e.context,n=a.gl,s=Pt.disabled,l=new St([n.ONE,n.ONE],t.Color.transparent,[!0,!0,!0,!0]);!function(t,e,i){var o=t.gl;t.activeTexture.set(o.TEXTURE1),t.viewport.set([0,0,e.width/4,e.height/4]);var r=i.heatmapFbo;if(r)o.bindTexture(o.TEXTURE_2D,r.colorAttachment.get()),t.bindFramebuffer.set(r.framebuffer);else {var a=o.createTexture();o.bindTexture(o.TEXTURE_2D,a),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),r=i.heatmapFbo=t.createFramebuffer(e.width/4,e.height/4,!1),function(t,e,i,o){var r=t.gl;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e.width/4,e.height/4,0,r.RGBA,t.extRenderToTextureHalfFloat?t.extTextureHalfFloat.HALF_FLOAT_OES:r.UNSIGNED_BYTE,null),o.colorAttachment.set(i);}(t,e,a,r);}}(a,e,o),a.clear({color:t.Color.transparent});for(var c=0;c<r.length;c++){var u=r[c];if(!i.hasRenderableParent(u)){var h=i.getTile(u),p=h.getBucket(o);if(p){var d=p.programConfigurations.get(o.id);e.useProgram("heatmap",d).draw(a,n.TRIANGLES,It.disabled,s,l,Ct.disabled,Ai(u.posMatrix,h,e.transform.zoom,o.paint.get("heatmap-intensity")),o.id,p.layoutVertexBuffer,p.indexBuffer,p.segments,o.paint,e.transform.zoom,d);}}}a.viewport.set([0,0,e.width,e.height]);}else "translucent"===e.renderPass&&(e.context.setColorMode(e.colorModeForRenderPass()),function(e,i){var o=e.context,r=o.gl,a=i.heatmapFbo;if(a){o.activeTexture.set(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,a.colorAttachment.get()),o.activeTexture.set(r.TEXTURE1);var n=i.colorRampTexture;n||(n=i.colorRampTexture=new t.Texture(o,i.colorRamp,r.RGBA)),n.bind(r.LINEAR,r.CLAMP_TO_EDGE),e.useProgram("heatmapTexture").draw(o,r.TRIANGLES,It.disabled,Pt.disabled,e.colorModeForRenderPass(),Ct.disabled,function(e,i,o,r){var a=t.create();t.ortho(a,0,e.width,e.height,0,0,1);var n=e.context.gl;return {u_matrix:a,u_world:[n.drawingBufferWidth,n.drawingBufferHeight],u_image:0,u_color_ramp:1,u_opacity:i.paint.get("heatmap-opacity")}}(e,i),i.id,e.viewportBuffer,e.quadTriangleIndexBuffer,e.viewportSegments,i.paint,e.transform.zoom);}}(e,o));},line:function(e,i,o,r){if("translucent"===e.renderPass){var a=o.paint.get("line-opacity"),n=o.paint.get("line-width");if(0!==a.constantOr(1)&&0!==n.constantOr(1)){var s=e.depthModeForSublayer(0,It.ReadOnly),l=e.colorModeForRenderPass(),c=o.paint.get("line-dasharray"),u=o.paint.get("line-pattern"),h=u.constantOr(1),p=o.paint.get("line-gradient"),d=o.getCrossfadeParameters(),_=h?"linePattern":c?"lineSDF":p?"lineGradient":"line",f=e.context,m=f.gl,g=!0;if(p){f.activeTexture.set(m.TEXTURE0);var v=o.gradientTexture;if(!o.gradient)return;v||(v=o.gradientTexture=new t.Texture(f,o.gradient,m.RGBA)),v.bind(m.LINEAR,m.CLAMP_TO_EDGE);}for(var y=0,x=r;y<x.length;y+=1){var b=x[y],w=i.getTile(b);if(!h||w.patternsLoaded()){var T=w.getBucket(o);if(T){var E=T.programConfigurations.get(o.id),I=e.context.program.get(),P=e.useProgram(_,E),S=g||P.program!==I,C=u.constantOr(null);if(C&&w.imageAtlas){var z=w.imageAtlas,D=z.patternPositions[C.to.toString()],M=z.patternPositions[C.from.toString()];D&&M&&E.setConstantPatternPositions(D,M);}var L=h?Bi(e,w,o,d):c?Oi(e,w,o,c,d):p?ki(e,w,o):Ri(e,w,o);h?(f.activeTexture.set(m.TEXTURE0),w.imageAtlasTexture.bind(m.LINEAR,m.CLAMP_TO_EDGE),E.updatePaintBuffers(d)):c&&(S||e.lineAtlas.dirty)&&(f.activeTexture.set(m.TEXTURE0),e.lineAtlas.bind(f)),P.draw(f,m.TRIANGLES,s,e.stencilModeForClipping(b),l,Ct.disabled,L,o.id,T.layoutVertexBuffer,T.indexBuffer,T.segments,o.paint,e.transform.zoom,E),g=!1;}}}}}},fill:function(e,i,o,r){var a=o.paint.get("fill-color"),n=o.paint.get("fill-opacity");if(0!==n.constantOr(1)){var s=e.colorModeForRenderPass(),l=o.paint.get("fill-pattern"),c=e.opaquePassEnabledForLayer()&&!l.constantOr(1)&&1===a.constantOr(t.Color.transparent).a&&1===n.constantOr(0)?"opaque":"translucent";if(e.renderPass===c){var u=e.depthModeForSublayer(1,"opaque"===e.renderPass?It.ReadWrite:It.ReadOnly);io(e,i,o,r,u,s,!1);}if("translucent"===e.renderPass&&o.paint.get("fill-antialias")){var h=e.depthModeForSublayer(o.getPaintProperty("fill-outline-color")?2:0,It.ReadOnly);io(e,i,o,r,h,s,!0);}}},"fill-extrusion":function(t,e,i,o){var r=i.paint.get("fill-extrusion-opacity");if(0!==r&&"translucent"===t.renderPass){var a=new It(t.context.gl.LEQUAL,It.ReadWrite,t.depthRangeFor3D);if(1!==r||i.paint.get("fill-extrusion-pattern").constantOr(1))oo(t,e,i,o,a,Pt.disabled,St.disabled),oo(t,e,i,o,a,t.stencilModeFor3D(),t.colorModeForRenderPass());else {var n=t.colorModeForRenderPass();oo(t,e,i,o,a,Pt.disabled,n);}}},hillshade:function(t,e,i,o){if("offscreen"===t.renderPass||"translucent"===t.renderPass){for(var r=t.context,a=e.getSource().maxzoom,n=t.depthModeForSublayer(0,It.ReadOnly),s=t.colorModeForRenderPass(),l="translucent"===t.renderPass?t.stencilConfigForOverlap(o):[{},o],c=l[0],u=0,h=l[1];u<h.length;u+=1){var p=h[u],d=e.getTile(p);d.needsHillshadePrepare&&"offscreen"===t.renderPass?ao(t,d,i,a,n,Pt.disabled,s):"translucent"===t.renderPass&&ro(t,d,i,n,c[p.overscaledZ],s);}r.viewport.set([0,0,t.width,t.height]);}},raster:function(t,e,i,o){if("translucent"===t.renderPass&&0!==i.paint.get("raster-opacity")&&o.length)for(var r=t.context,a=r.gl,n=e.getSource(),s=t.useProgram("raster"),l=t.colorModeForRenderPass(),c=n instanceof L?[{},o]:t.stencilConfigForOverlap(o),u=c[0],h=c[1],p=h[h.length-1].overscaledZ,d=!t.options.moving,_=0,f=h;_<f.length;_+=1){var m=f[_],g=t.depthModeForSublayer(m.overscaledZ-p,1===i.paint.get("raster-opacity")?It.ReadWrite:It.ReadOnly,a.LESS),v=e.getTile(m),y=t.transform.calculatePosMatrix(m.toUnwrapped(),d);v.registerFadeDuration(i.paint.get("raster-fade-duration"));var x=e.findLoadedParent(m,0),b=no(v,x,e,i,t.transform),w=void 0,T=void 0,E="nearest"===i.paint.get("raster-resampling")?a.NEAREST:a.LINEAR;r.activeTexture.set(a.TEXTURE0),v.texture.bind(E,a.CLAMP_TO_EDGE,a.LINEAR_MIPMAP_NEAREST),r.activeTexture.set(a.TEXTURE1),x?(x.texture.bind(E,a.CLAMP_TO_EDGE,a.LINEAR_MIPMAP_NEAREST),w=Math.pow(2,x.tileID.overscaledZ-v.tileID.overscaledZ),T=[v.tileID.canonical.x*w%1,v.tileID.canonical.y*w%1]):v.texture.bind(E,a.CLAMP_TO_EDGE,a.LINEAR_MIPMAP_NEAREST);var I=Ni(y,T||[0,0],w||1,b,i);n instanceof L?s.draw(r,a.TRIANGLES,g,Pt.disabled,l,Ct.disabled,I,i.id,n.boundsBuffer,t.quadTriangleIndexBuffer,n.boundsSegments):s.draw(r,a.TRIANGLES,g,u[m.overscaledZ],l,Ct.disabled,I,i.id,t.rasterBoundsBuffer,t.quadTriangleIndexBuffer,t.rasterBoundsSegments);}},background:function(t,e,i){var o=i.paint.get("background-color"),r=i.paint.get("background-opacity");if(0!==r){var a=t.context,n=a.gl,s=t.transform,l=s.tileSize,c=i.paint.get("background-pattern");if(!t.isPatternMissing(c)){var u=!c&&1===o.a&&1===r&&t.opaquePassEnabledForLayer()?"opaque":"translucent";if(t.renderPass===u){var h=Pt.disabled,p=t.depthModeForSublayer(0,"opaque"===u?It.ReadWrite:It.ReadOnly),d=t.colorModeForRenderPass(),_=t.useProgram(c?"backgroundPattern":"background"),f=s.coveringTiles({tileSize:l});c&&(a.activeTexture.set(n.TEXTURE0),t.imageManager.bind(t.context));for(var m=i.getCrossfadeParameters(),g=0,v=f;g<v.length;g+=1){var y=v[g],x=t.transform.calculatePosMatrix(y.toUnwrapped()),b=c?Xi(x,r,t,c,{tileID:y,tileSize:l},m):Wi(x,r,o);_.draw(a,n.TRIANGLES,p,h,d,Ct.disabled,b,i.id,t.tileExtentBuffer,t.quadTriangleIndexBuffer,t.tileExtentSegments);}}}}},debug:function(t,e,i){for(var o=0;o<i.length;o++)mo(t,e,i[o]);},custom:function(t,e,i){var o=t.context,r=i.implementation;if("offscreen"===t.renderPass){var a=r.prerender;a&&(t.setCustomLayerDefaults(),o.setColorMode(t.colorModeForRenderPass()),a.call(r,o.gl,t.transform.customLayerMatrix()),o.setDirty(),t.setBaseState());}else if("translucent"===t.renderPass){t.setCustomLayerDefaults(),o.setColorMode(t.colorModeForRenderPass()),o.setStencilMode(Pt.disabled);var n="3d"===r.renderingMode?new It(t.context.gl.LEQUAL,It.ReadWrite,t.depthRangeFor3D):t.depthModeForSublayer(0,It.ReadOnly);o.setDepthMode(n),r.render(o.gl,t.transform.customLayerMatrix()),o.setDirty(),t.setBaseState(),o.bindFramebuffer.set(null);}}},vo=function(t,e){this.context=new zt(t),this.transform=e,this._tileTextures={},this.setup(),this.numSublayers=Dt.maxUnderzooming+Dt.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new Fe,this.gpuTimers={};};vo.prototype.resize=function(e,i){if(this.width=e*t.browser.devicePixelRatio,this.height=i*t.browser.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(var o=0,r=this.style._order;o<r.length;o+=1)this.style._layers[r[o]].resize();},vo.prototype.setup=function(){var e=this.context,i=new t.StructArrayLayout2i4;i.emplaceBack(0,0),i.emplaceBack(t.EXTENT,0),i.emplaceBack(0,t.EXTENT),i.emplaceBack(t.EXTENT,t.EXTENT),this.tileExtentBuffer=e.createVertexBuffer(i,Ve.members),this.tileExtentSegments=t.SegmentVector.simpleSegment(0,0,4,2);var o=new t.StructArrayLayout2i4;o.emplaceBack(0,0),o.emplaceBack(t.EXTENT,0),o.emplaceBack(0,t.EXTENT),o.emplaceBack(t.EXTENT,t.EXTENT),this.debugBuffer=e.createVertexBuffer(o,Ve.members),this.debugSegments=t.SegmentVector.simpleSegment(0,0,4,5);var r=new t.StructArrayLayout4i8;r.emplaceBack(0,0,0,0),r.emplaceBack(t.EXTENT,0,t.EXTENT,0),r.emplaceBack(0,t.EXTENT,0,t.EXTENT),r.emplaceBack(t.EXTENT,t.EXTENT,t.EXTENT,t.EXTENT),this.rasterBoundsBuffer=e.createVertexBuffer(r,M.members),this.rasterBoundsSegments=t.SegmentVector.simpleSegment(0,0,4,2);var a=new t.StructArrayLayout2i4;a.emplaceBack(0,0),a.emplaceBack(1,0),a.emplaceBack(0,1),a.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(a,Ve.members),this.viewportSegments=t.SegmentVector.simpleSegment(0,0,4,2);var n=new t.StructArrayLayout1ui2;n.emplaceBack(0),n.emplaceBack(1),n.emplaceBack(3),n.emplaceBack(2),n.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(n);var s=new t.StructArrayLayout3ui6;s.emplaceBack(0,1,2),s.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(s),this.emptyTexture=new t.Texture(e,{width:1,height:1,data:new Uint8Array([0,0,0,0])},e.gl.RGBA);var l=this.context.gl;this.stencilClearMode=new Pt({func:l.ALWAYS,mask:0},0,255,l.ZERO,l.ZERO,l.ZERO);},vo.prototype.clearStencil=function(){var e=this.context,i=e.gl;this.nextStencilID=1,this.currentStencilSource=void 0;var o=t.create();t.ortho(o,0,this.width,this.height,0,0,1),t.scale(o,o,[i.drawingBufferWidth,i.drawingBufferHeight,0]),this.useProgram("clippingMask").draw(e,i.TRIANGLES,It.disabled,this.stencilClearMode,St.disabled,Ct.disabled,Li(o),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);},vo.prototype._renderTileClippingMasks=function(t,e){if(this.currentStencilSource!==t.source&&t.isTileClipped()&&e&&e.length){this.currentStencilSource=t.source;var i=this.context,o=i.gl;this.nextStencilID+e.length>256&&this.clearStencil(),i.setColorMode(St.disabled),i.setDepthMode(It.disabled);var r=this.useProgram("clippingMask");this._tileClippingMaskIDs={};for(var a=0,n=e;a<n.length;a+=1){var s=n[a],l=this._tileClippingMaskIDs[s.key]=this.nextStencilID++;r.draw(i,o.TRIANGLES,It.disabled,new Pt({func:o.ALWAYS,mask:0},l,255,o.KEEP,o.KEEP,o.REPLACE),St.disabled,Ct.disabled,Li(s.posMatrix),"$clipping",this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments);}}},vo.prototype.stencilModeFor3D=function(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();var t=this.nextStencilID++,e=this.context.gl;return new Pt({func:e.NOTEQUAL,mask:255},t,255,e.KEEP,e.KEEP,e.REPLACE)},vo.prototype.stencilModeForClipping=function(t){var e=this.context.gl;return new Pt({func:e.EQUAL,mask:255},this._tileClippingMaskIDs[t.key],0,e.KEEP,e.KEEP,e.REPLACE)},vo.prototype.stencilConfigForOverlap=function(t){var e,i=this.context.gl,o=t.sort((function(t,e){return e.overscaledZ-t.overscaledZ})),r=o[o.length-1].overscaledZ,a=o[0].overscaledZ-r+1;if(a>1){this.currentStencilSource=void 0,this.nextStencilID+a>256&&this.clearStencil();for(var n={},s=0;s<a;s++)n[s+r]=new Pt({func:i.GEQUAL,mask:255},s+this.nextStencilID,255,i.KEEP,i.KEEP,i.REPLACE);return this.nextStencilID+=a,[n,o]}return [(e={},e[r]=Pt.disabled,e),o]},vo.prototype.colorModeForRenderPass=function(){var e=this.context.gl;return this._showOverdrawInspector?new St([e.CONSTANT_COLOR,e.ONE],new t.Color(1/8,1/8,1/8,0),[!0,!0,!0,!0]):"opaque"===this.renderPass?St.unblended:St.alphaBlended},vo.prototype.depthModeForSublayer=function(t,e,i){if(!this.opaquePassEnabledForLayer())return It.disabled;var o=1-((1+this.currentLayer)*this.numSublayers+t)*this.depthEpsilon;return new It(i||this.context.gl.LEQUAL,e,[o,o])},vo.prototype.opaquePassEnabledForLayer=function(){return this.currentLayer<this.opaquePassCutoff},vo.prototype.render=function(e,i){var o=this;this.style=e,this.options=i,this.lineAtlas=e.lineAtlas,this.imageManager=e.imageManager,this.glyphManager=e.glyphManager,this.symbolFadeChange=e.placement.symbolFadeChange(t.browser.now()),this.imageManager.beginFrame();var r=this.style._order,a=this.style.sourceCaches;for(var n in a){var s=a[n];s.used&&s.prepare(this.context);}var l,c,u={},h={},p={};for(var d in a){var _=a[d];u[d]=_.getVisibleCoordinates(),h[d]=u[d].slice().reverse(),p[d]=_.getVisibleCoordinates(!0).reverse();}this.opaquePassCutoff=1/0;for(var f=0;f<r.length;f++)if(this.style._layers[r[f]].is3D()){this.opaquePassCutoff=f;break}this.renderPass="offscreen";for(var m=0,g=r;m<g.length;m+=1){var v=this.style._layers[g[m]];if(v.hasOffscreenPass()&&!v.isHidden(this.transform.zoom)){var y=h[v.source];("custom"===v.type||y.length)&&this.renderLayer(this,a[v.source],v,y);}}for(this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.Color.black:t.Color.transparent,depth:1}),this.clearStencil(),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],this.renderPass="opaque",this.currentLayer=r.length-1;this.currentLayer>=0;this.currentLayer--){var x=this.style._layers[r[this.currentLayer]],b=a[x.source],w=u[x.source];this._renderTileClippingMasks(x,w),this.renderLayer(this,b,x,w);}for(this.renderPass="translucent",this.currentLayer=0;this.currentLayer<r.length;this.currentLayer++){var T=this.style._layers[r[this.currentLayer]],E=a[T.source],I=("symbol"===T.type?p:h)[T.source];this._renderTileClippingMasks(T,u[T.source]),this.renderLayer(this,E,T,I);}this.options.showTileBoundaries&&(t.values(this.style._layers).forEach((function(t){t.source&&!t.isHidden(o.transform.zoom)&&(t.source!==(c&&c.id)&&(c=o.style.sourceCaches[t.source]),(!l||l.getSource().maxzoom<c.getSource().maxzoom)&&(l=c));})),l&&go.debug(this,l,l.getVisibleCoordinates())),this.options.showPadding&&function(t){var e=t.transform.padding;po(t,t.transform.height-(e.top||0),3,so),po(t,e.bottom||0,3,lo),_o(t,e.left||0,3,co),_o(t,t.transform.width-(e.right||0),3,uo);var i=t.transform.centerPoint;!function(t,e,i,o){fo(t,e-1,i-10,2,20,o),fo(t,e-10,i-1,20,2,o);}(t,i.x,t.transform.height-i.y,ho);}(this),this.context.setDefault();},vo.prototype.renderLayer=function(t,e,i,o){i.isHidden(this.transform.zoom)||("background"===i.type||"custom"===i.type||o.length)&&(this.id=i.id,this.gpuTimingStart(i),go[i.type](t,e,i,o,this.style.placement.variableOffsets),this.gpuTimingEnd());},vo.prototype.gpuTimingStart=function(t){if(this.options.gpuTiming){var e=this.context.extTimerQuery,i=this.gpuTimers[t.id];i||(i=this.gpuTimers[t.id]={calls:0,cpuTime:0,query:e.createQueryEXT()}),i.calls++,e.beginQueryEXT(e.TIME_ELAPSED_EXT,i.query);}},vo.prototype.gpuTimingEnd=function(){if(this.options.gpuTiming){var t=this.context.extTimerQuery;t.endQueryEXT(t.TIME_ELAPSED_EXT);}},vo.prototype.collectGpuTimers=function(){var t=this.gpuTimers;return this.gpuTimers={},t},vo.prototype.queryGpuTimers=function(t){var e={};for(var i in t){var o=t[i],r=this.context.extTimerQuery,a=r.getQueryObjectEXT(o.query,r.QUERY_RESULT_EXT)/1e6;r.deleteQueryEXT(o.query),e[i]=a;}return e},vo.prototype.translatePosMatrix=function(e,i,o,r,a){if(!o[0]&&!o[1])return e;var n=a?"map"===r?this.transform.angle:0:"viewport"===r?-this.transform.angle:0;if(n){var s=Math.sin(n),l=Math.cos(n);o=[o[0]*l-o[1]*s,o[0]*s+o[1]*l];}var c=[a?o[0]:pe(i,o[0],this.transform.zoom),a?o[1]:pe(i,o[1],this.transform.zoom),0],u=new Float32Array(16);return t.translate(u,e,c),u},vo.prototype.saveTileTexture=function(t){var e=this._tileTextures[t.size[0]];e?e.push(t):this._tileTextures[t.size[0]]=[t];},vo.prototype.getTileTexture=function(t){var e=this._tileTextures[t];return e&&e.length>0?e.pop():null},vo.prototype.isPatternMissing=function(t){if(!t)return !1;if(!t.from||!t.to)return !0;var e=this.imageManager.getPattern(t.from.toString()),i=this.imageManager.getPattern(t.to.toString());return !e||!i},vo.prototype.useProgram=function(t,e){this.cache=this.cache||{};var i=""+t+(e?e.cacheKey:"")+(this._showOverdrawInspector?"/overdraw":"");return this.cache[i]||(this.cache[i]=new xi(this.context,vi[t],e,Hi[t],this._showOverdrawInspector)),this.cache[i]},vo.prototype.setCustomLayerDefaults=function(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();},vo.prototype.setBaseState=function(){var t=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(t.FUNC_ADD);},vo.prototype.initDebugOverlayCanvas=function(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=t.window.document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new t.Texture(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));},vo.prototype.destroy=function(){this.emptyTexture.destroy(),this.debugOverlayTexture&&this.debugOverlayTexture.destroy();};var yo=function(t,e){this.points=t,this.planes=e;};yo.fromInvProjectionMatrix=function(e,i,o){var r=Math.pow(2,o),a=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((function(i){return t.transformMat4([],i,e)})).map((function(e){return t.scale$1([],e,1/e[3]/i*r)})),n=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map((function(e){var i=t.sub([],a[e[0]],a[e[1]]),o=t.sub([],a[e[2]],a[e[1]]),r=t.normalize([],t.cross([],i,o)),n=-t.dot(r,a[e[1]]);return r.concat(n)}));return new yo(a,n)};var xo=function(e,i){this.min=e,this.max=i,this.center=t.scale$2([],t.add([],this.min,this.max),.5);};xo.prototype.quadrant=function(e){for(var i=[e%2==0,e<2],o=t.clone$2(this.min),r=t.clone$2(this.max),a=0;a<i.length;a++)o[a]=i[a]?this.min[a]:this.center[a],r[a]=i[a]?this.center[a]:this.max[a];return r[2]=this.max[2],new xo(o,r)},xo.prototype.distanceX=function(t){return Math.max(Math.min(this.max[0],t[0]),this.min[0])-t[0]},xo.prototype.distanceY=function(t){return Math.max(Math.min(this.max[1],t[1]),this.min[1])-t[1]},xo.prototype.intersects=function(e){for(var i=[[this.min[0],this.min[1],0,1],[this.max[0],this.min[1],0,1],[this.max[0],this.max[1],0,1],[this.min[0],this.max[1],0,1]],o=!0,r=0;r<e.planes.length;r++){for(var a=e.planes[r],n=0,s=0;s<i.length;s++)n+=t.dot$1(a,i[s])>=0;if(0===n)return 0;n!==i.length&&(o=!1);}if(o)return 2;for(var l=0;l<3;l++){for(var c=Number.MAX_VALUE,u=-Number.MAX_VALUE,h=0;h<e.points.length;h++){var p=e.points[h][l]-this.min[l];c=Math.min(c,p),u=Math.max(u,p);}if(u<0||c>this.max[l]-this.min[l])return 0}return 1};var bo=function(t,e,i,o){if(void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===o&&(o=0),isNaN(t)||t<0||isNaN(e)||e<0||isNaN(i)||i<0||isNaN(o)||o<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=t,this.bottom=e,this.left=i,this.right=o;};bo.prototype.interpolate=function(e,i,o){return null!=i.top&&null!=e.top&&(this.top=t.number(e.top,i.top,o)),null!=i.bottom&&null!=e.bottom&&(this.bottom=t.number(e.bottom,i.bottom,o)),null!=i.left&&null!=e.left&&(this.left=t.number(e.left,i.left,o)),null!=i.right&&null!=e.right&&(this.right=t.number(e.right,i.right,o)),this},bo.prototype.getCenter=function(e,i){var o=t.clamp((this.left+e-this.right)/2,0,e),r=t.clamp((this.top+i-this.bottom)/2,0,i);return new t.Point(o,r)},bo.prototype.equals=function(t){return this.top===t.top&&this.bottom===t.bottom&&this.left===t.left&&this.right===t.right},bo.prototype.clone=function(){return new bo(this.top,this.bottom,this.left,this.right)},bo.prototype.toJSON=function(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}};var wo=function(e,i,o,r,a){this.tileSize=512,this.maxValidLatitude=85.051129,this._renderWorldCopies=void 0===a||a,this._minZoom=e||0,this._maxZoom=i||22,this._minPitch=null==o?0:o,this._maxPitch=null==r?60:r,this.setMaxBounds(),this.width=0,this.height=0,this._center=new t.LngLat(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._unmodified=!0,this._edgeInsets=new bo,this._posMatrixCache={},this._alignedPosMatrixCache={};},To={minZoom:{configurable:!0},maxZoom:{configurable:!0},minPitch:{configurable:!0},maxPitch:{configurable:!0},renderWorldCopies:{configurable:!0},worldSize:{configurable:!0},centerOffset:{configurable:!0},size:{configurable:!0},bearing:{configurable:!0},pitch:{configurable:!0},fov:{configurable:!0},zoom:{configurable:!0},center:{configurable:!0},padding:{configurable:!0},centerPoint:{configurable:!0},unmodified:{configurable:!0},point:{configurable:!0}};wo.prototype.clone=function(){var t=new wo(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies);return t.tileSize=this.tileSize,t.latRange=this.latRange,t.width=this.width,t.height=this.height,t._center=this._center,t.zoom=this.zoom,t.angle=this.angle,t._fov=this._fov,t._pitch=this._pitch,t._unmodified=this._unmodified,t._edgeInsets=this._edgeInsets.clone(),t._calcMatrices(),t},To.minZoom.get=function(){return this._minZoom},To.minZoom.set=function(t){this._minZoom!==t&&(this._minZoom=t,this.zoom=Math.max(this.zoom,t));},To.maxZoom.get=function(){return this._maxZoom},To.maxZoom.set=function(t){this._maxZoom!==t&&(this._maxZoom=t,this.zoom=Math.min(this.zoom,t));},To.minPitch.get=function(){return this._minPitch},To.minPitch.set=function(t){this._minPitch!==t&&(this._minPitch=t,this.pitch=Math.max(this.pitch,t));},To.maxPitch.get=function(){return this._maxPitch},To.maxPitch.set=function(t){this._maxPitch!==t&&(this._maxPitch=t,this.pitch=Math.min(this.pitch,t));},To.renderWorldCopies.get=function(){return this._renderWorldCopies},To.renderWorldCopies.set=function(t){void 0===t?t=!0:null===t&&(t=!1),this._renderWorldCopies=t;},To.worldSize.get=function(){return this.tileSize*this.scale},To.centerOffset.get=function(){return this.centerPoint._sub(this.size._div(2))},To.size.get=function(){return new t.Point(this.width,this.height)},To.bearing.get=function(){return -this.angle/Math.PI*180},To.bearing.set=function(e){var i=-t.wrap(e,-180,180)*Math.PI/180;this.angle!==i&&(this._unmodified=!1,this.angle=i,this._calcMatrices(),this.rotationMatrix=t.create$2(),t.rotate(this.rotationMatrix,this.rotationMatrix,this.angle));},To.pitch.get=function(){return this._pitch/Math.PI*180},To.pitch.set=function(e){var i=t.clamp(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitch!==i&&(this._unmodified=!1,this._pitch=i,this._calcMatrices());},To.fov.get=function(){return this._fov/Math.PI*180},To.fov.set=function(t){t=Math.max(.01,Math.min(60,t)),this._fov!==t&&(this._unmodified=!1,this._fov=t/180*Math.PI,this._calcMatrices());},To.zoom.get=function(){return this._zoom},To.zoom.set=function(t){var e=Math.min(Math.max(t,this.minZoom),this.maxZoom);this._zoom!==e&&(this._unmodified=!1,this._zoom=e,this.scale=this.zoomScale(e),this.tileZoom=Math.floor(e),this.zoomFraction=e-this.tileZoom,this._constrain(),this._calcMatrices());},To.center.get=function(){return this._center},To.center.set=function(t){t.lat===this._center.lat&&t.lng===this._center.lng||(this._unmodified=!1,this._center=t,this._constrain(),this._calcMatrices());},To.padding.get=function(){return this._edgeInsets.toJSON()},To.padding.set=function(t){this._edgeInsets.equals(t)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,t,1),this._calcMatrices());},To.centerPoint.get=function(){return this._edgeInsets.getCenter(this.width,this.height)},wo.prototype.isPaddingEqual=function(t){return this._edgeInsets.equals(t)},wo.prototype.interpolatePadding=function(t,e,i){this._unmodified=!1,this._edgeInsets.interpolate(t,e,i),this._constrain(),this._calcMatrices();},wo.prototype.coveringZoomLevel=function(t){var e=(t.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/t.tileSize));return Math.max(0,e)},wo.prototype.getVisibleUnwrappedCoordinates=function(e){var i=[new t.UnwrappedTileID(0,e)];if(this._renderWorldCopies)for(var o=this.pointCoordinate(new t.Point(0,0)),r=this.pointCoordinate(new t.Point(this.width,0)),a=this.pointCoordinate(new t.Point(this.width,this.height)),n=this.pointCoordinate(new t.Point(0,this.height)),s=Math.floor(Math.min(o.x,r.x,a.x,n.x)),l=Math.floor(Math.max(o.x,r.x,a.x,n.x)),c=s-1;c<=l+1;c++)0!==c&&i.push(new t.UnwrappedTileID(c,e));return i},wo.prototype.coveringTiles=function(e){var i=this.coveringZoomLevel(e),o=i;if(void 0!==e.minzoom&&i<e.minzoom)return [];void 0!==e.maxzoom&&i>e.maxzoom&&(i=e.maxzoom);var r=t.MercatorCoordinate.fromLngLat(this.center),a=Math.pow(2,i),n=[a*r.x,a*r.y,0],s=yo.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,i),l=e.minzoom||0;this.pitch<=60&&this._edgeInsets.top<.1&&(l=i);var c=function(t){return {aabb:new xo([t*a,0,0],[(t+1)*a,a,0]),zoom:0,x:0,y:0,wrap:t,fullyVisible:!1}},u=[],h=[],p=i,d=e.reparseOverscaled?o:i;if(this._renderWorldCopies)for(var _=1;_<=3;_++)u.push(c(-_)),u.push(c(_));for(u.push(c(0));u.length>0;){var f=u.pop(),m=f.x,g=f.y,v=f.fullyVisible;if(!v){var y=f.aabb.intersects(s);if(0===y)continue;v=2===y;}var x=f.aabb.distanceX(n),b=f.aabb.distanceY(n),w=Math.max(Math.abs(x),Math.abs(b));if(f.zoom===p||w>3+(1<<p-f.zoom)-2&&f.zoom>=l)h.push({tileID:new t.OverscaledTileID(f.zoom===p?d:f.zoom,f.wrap,f.zoom,m,g),distanceSq:t.sqrLen([n[0]-.5-m,n[1]-.5-g])});else for(var T=0;T<4;T++){var E=(m<<1)+T%2,I=(g<<1)+(T>>1);u.push({aabb:f.aabb.quadrant(T),zoom:f.zoom+1,x:E,y:I,wrap:f.wrap,fullyVisible:v});}}return h.sort((function(t,e){return t.distanceSq-e.distanceSq})).map((function(t){return t.tileID}))},wo.prototype.resize=function(t,e){this.width=t,this.height=e,this.pixelsToGLUnits=[2/t,-2/e],this._constrain(),this._calcMatrices();},To.unmodified.get=function(){return this._unmodified},wo.prototype.zoomScale=function(t){return Math.pow(2,t)},wo.prototype.scaleZoom=function(t){return Math.log(t)/Math.LN2},wo.prototype.project=function(e){var i=t.clamp(e.lat,-this.maxValidLatitude,this.maxValidLatitude);return new t.Point(t.mercatorXfromLng(e.lng)*this.worldSize,t.mercatorYfromLat(i)*this.worldSize)},wo.prototype.unproject=function(e){return new t.MercatorCoordinate(e.x/this.worldSize,e.y/this.worldSize).toLngLat()},To.point.get=function(){return this.project(this.center)},wo.prototype.setLocationAtPoint=function(e,i){var o=this.pointCoordinate(i),r=this.pointCoordinate(this.centerPoint),a=this.locationCoordinate(e),n=new t.MercatorCoordinate(a.x-(o.x-r.x),a.y-(o.y-r.y));this.center=this.coordinateLocation(n),this._renderWorldCopies&&(this.center=this.center.wrap());},wo.prototype.locationPoint=function(t){return this.coordinatePoint(this.locationCoordinate(t))},wo.prototype.pointLocation=function(t){return this.coordinateLocation(this.pointCoordinate(t))},wo.prototype.locationCoordinate=function(e){return t.MercatorCoordinate.fromLngLat(e)},wo.prototype.coordinateLocation=function(t){return t.toLngLat()},wo.prototype.pointCoordinate=function(e){var i=[e.x,e.y,0,1],o=[e.x,e.y,1,1];t.transformMat4(i,i,this.pixelMatrixInverse),t.transformMat4(o,o,this.pixelMatrixInverse);var r=i[3],a=o[3],n=i[1]/r,s=o[1]/a,l=i[2]/r,c=o[2]/a,u=l===c?0:(0-l)/(c-l);return new t.MercatorCoordinate(t.number(i[0]/r,o[0]/a,u)/this.worldSize,t.number(n,s,u)/this.worldSize)},wo.prototype.coordinatePoint=function(e){var i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.transformMat4(i,i,this.pixelMatrix),new t.Point(i[0]/i[3],i[1]/i[3])},wo.prototype.getBounds=function(){return (new t.LngLatBounds).extend(this.pointLocation(new t.Point(0,0))).extend(this.pointLocation(new t.Point(this.width,0))).extend(this.pointLocation(new t.Point(this.width,this.height))).extend(this.pointLocation(new t.Point(0,this.height)))},wo.prototype.getMaxBounds=function(){return this.latRange&&2===this.latRange.length&&this.lngRange&&2===this.lngRange.length?new t.LngLatBounds([this.lngRange[0],this.latRange[0]],[this.lngRange[1],this.latRange[1]]):null},wo.prototype.setMaxBounds=function(t){t?(this.lngRange=[t.getWest(),t.getEast()],this.latRange=[t.getSouth(),t.getNorth()],this._constrain()):(this.lngRange=null,this.latRange=[-this.maxValidLatitude,this.maxValidLatitude]);},wo.prototype.calculatePosMatrix=function(e,i){void 0===i&&(i=!1);var o=e.key,r=i?this._alignedPosMatrixCache:this._posMatrixCache;if(r[o])return r[o];var a=e.canonical,n=this.worldSize/this.zoomScale(a.z),s=a.x+Math.pow(2,a.z)*e.wrap,l=t.identity(new Float64Array(16));return t.translate(l,l,[s*n,a.y*n,0]),t.scale(l,l,[n/t.EXTENT,n/t.EXTENT,1]),t.multiply(l,i?this.alignedProjMatrix:this.projMatrix,l),r[o]=new Float32Array(l),r[o]},wo.prototype.customLayerMatrix=function(){return this.mercatorMatrix.slice()},wo.prototype._constrain=function(){if(this.center&&this.width&&this.height&&!this._constraining){this._constraining=!0;var e,i,o,r,a=-90,n=90,s=-180,l=180,c=this.size,u=this._unmodified;if(this.latRange){var h=this.latRange;a=t.mercatorYfromLat(h[1])*this.worldSize,e=(n=t.mercatorYfromLat(h[0])*this.worldSize)-a<c.y?c.y/(n-a):0;}if(this.lngRange){var p=this.lngRange;s=t.mercatorXfromLng(p[0])*this.worldSize,i=(l=t.mercatorXfromLng(p[1])*this.worldSize)-s<c.x?c.x/(l-s):0;}var d=this.point,_=Math.max(i||0,e||0);if(_)return this.center=this.unproject(new t.Point(i?(l+s)/2:d.x,e?(n+a)/2:d.y)),this.zoom+=this.scaleZoom(_),this._unmodified=u,void(this._constraining=!1);if(this.latRange){var f=d.y,m=c.y/2;f-m<a&&(r=a+m),f+m>n&&(r=n-m);}if(this.lngRange){var g=d.x,v=c.x/2;g-v<s&&(o=s+v),g+v>l&&(o=l-v);}void 0===o&&void 0===r||(this.center=this.unproject(new t.Point(void 0!==o?o:d.x,void 0!==r?r:d.y))),this._unmodified=u,this._constraining=!1;}},wo.prototype._calcMatrices=function(){if(this.height){var e=this.centerOffset;this.cameraToCenterDistance=.5/Math.tan(this._fov/2)*this.height;var i=Math.PI/2+this._pitch,o=this._fov*(.5+e.y/this.height),r=Math.sin(o)*this.cameraToCenterDistance/Math.sin(t.clamp(Math.PI-i-o,.01,Math.PI-.01)),a=this.point,n=a.x,s=a.y,l=1.01*(Math.cos(Math.PI/2-this._pitch)*r+this.cameraToCenterDistance),c=this.height/50,u=new Float64Array(16);t.perspective(u,this._fov,this.width/this.height,c,l),u[8]=2*-e.x/this.width,u[9]=2*e.y/this.height,t.scale(u,u,[1,-1,1]),t.translate(u,u,[0,0,-this.cameraToCenterDistance]),t.rotateX(u,u,this._pitch),t.rotateZ(u,u,this.angle),t.translate(u,u,[-n,-s,0]),this.mercatorMatrix=t.scale([],u,[this.worldSize,this.worldSize,this.worldSize]),t.scale(u,u,[1,1,t.mercatorZfromAltitude(1,this.center.lat)*this.worldSize,1]),this.projMatrix=u,this.invProjMatrix=t.invert([],this.projMatrix);var h=this.width%2/2,p=this.height%2/2,d=Math.cos(this.angle),_=Math.sin(this.angle),f=n-Math.round(n)+d*h+_*p,m=s-Math.round(s)+d*p+_*h,g=new Float64Array(u);if(t.translate(g,g,[f>.5?f-1:f,m>.5?m-1:m,0]),this.alignedProjMatrix=g,u=t.create(),t.scale(u,u,[this.width/2,-this.height/2,1]),t.translate(u,u,[1,-1,0]),this.labelPlaneMatrix=u,u=t.create(),t.scale(u,u,[1,-1,1]),t.translate(u,u,[-1,-1,0]),t.scale(u,u,[2/this.width,2/this.height,1]),this.glCoordMatrix=u,this.pixelMatrix=t.multiply(new Float64Array(16),this.labelPlaneMatrix,this.projMatrix),!(u=t.invert(new Float64Array(16),this.pixelMatrix)))throw new Error("failed to invert matrix");this.pixelMatrixInverse=u,this._posMatrixCache={},this._alignedPosMatrixCache={};}},wo.prototype.maxPitchScaleFactor=function(){if(!this.pixelMatrixInverse)return 1;var e=this.pointCoordinate(new t.Point(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.transformMat4(i,i,this.pixelMatrix)[3]/this.cameraToCenterDistance},wo.prototype.getCameraPoint=function(){var e=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new t.Point(0,e))},wo.prototype.getCameraQueryGeometry=function(e){var i=this.getCameraPoint();if(1===e.length)return [e[0],i];for(var o=i.x,r=i.y,a=i.x,n=i.y,s=0,l=e;s<l.length;s+=1){var c=l[s];o=Math.min(o,c.x),r=Math.min(r,c.y),a=Math.max(a,c.x),n=Math.max(n,c.y);}return [new t.Point(o,r),new t.Point(a,r),new t.Point(a,n),new t.Point(o,n),new t.Point(o,r)]},Object.defineProperties(wo.prototype,To);var Eo=function(e){var i,o,r,a;this._hashName=e&&encodeURIComponent(e),t.bindAll(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=(i=this._updateHashUnthrottled.bind(this),o=!1,r=null,a=function(){r=null,o&&(i(),r=setTimeout(a,300),o=!1);},function(){return o=!0,r||a(),r});};Eo.prototype.addTo=function(e){return this._map=e,t.window.addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this},Eo.prototype.remove=function(){return t.window.removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),delete this._map,this},Eo.prototype.getHashString=function(e){var i=this._map.getCenter(),o=Math.round(100*this._map.getZoom())/100,r=Math.ceil((o*Math.LN2+Math.log(512/360/.5))/Math.LN10),a=Math.pow(10,r),n=Math.round(i.lng*a)/a,s=Math.round(i.lat*a)/a,l=this._map.getBearing(),c=this._map.getPitch(),u="";if(u+=e?"/"+n+"/"+s+"/"+o:o+"/"+s+"/"+n,(l||c)&&(u+="/"+Math.round(10*l)/10),c&&(u+="/"+Math.round(c)),this._hashName){var h=this._hashName,p=!1,d=t.window.location.hash.slice(1).split("&").map((function(t){var e=t.split("=")[0];return e===h?(p=!0,e+"="+u):t})).filter((function(t){return t}));return p||d.push(h+"="+u),"#"+d.join("&")}return "#"+u},Eo.prototype._getCurrentHash=function(){var e,i=this,o=t.window.location.hash.replace("#","");return this._hashName?(o.split("&").map((function(t){return t.split("=")})).forEach((function(t){t[0]===i._hashName&&(e=t);})),(e&&e[1]||"").split("/")):o.split("/")},Eo.prototype._onHashChange=function(){var t=this._getCurrentHash();if(t.length>=3&&!t.some((function(t){return isNaN(t)}))){var e=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(t[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+t[2],+t[1]],zoom:+t[0],bearing:e,pitch:+(t[4]||0)}),!0}return !1},Eo.prototype._updateHashUnthrottled=function(){var e=this.getHashString();try{t.window.history.replaceState(t.window.history.state,"",e);}catch(t){}};var Io={linearity:.3,easing:t.bezier(0,0,.3,1)},Po=t.extend({deceleration:2500,maxSpeed:1400},Io),So=t.extend({deceleration:20,maxSpeed:1400},Io),Co=t.extend({deceleration:1e3,maxSpeed:360},Io),zo=t.extend({deceleration:1e3,maxSpeed:90},Io),Do=function(t){this._map=t,this.clear();};function Mo(t,e){(!t.duration||t.duration<e.duration)&&(t.duration=e.duration,t.easing=e.easing);}function Lo(e,i,o){var r=o.maxSpeed,a=o.linearity,n=o.deceleration,s=t.clamp(e*a/(i/1e3),-r,r),l=Math.abs(s)/(n*a);return {easing:o.easing,duration:1e3*l,amount:s*(l/2)}}Do.prototype.clear=function(){this._inertiaBuffer=[];},Do.prototype.record=function(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:t.browser.now(),settings:e});},Do.prototype._drainInertiaBuffer=function(){for(var e=this._inertiaBuffer,i=t.browser.now();e.length>0&&i-e[0].time>160;)e.shift();},Do.prototype._onMoveEnd=function(e){if(this._drainInertiaBuffer(),!(this._inertiaBuffer.length<2)){for(var i={zoom:0,bearing:0,pitch:0,pan:new t.Point(0,0),pinchAround:void 0,around:void 0},o=0,r=this._inertiaBuffer;o<r.length;o+=1){var a=r[o].settings;i.zoom+=a.zoomDelta||0,i.bearing+=a.bearingDelta||0,i.pitch+=a.pitchDelta||0,a.panDelta&&i.pan._add(a.panDelta),a.around&&(i.around=a.around),a.pinchAround&&(i.pinchAround=a.pinchAround);}var n=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,s={};if(i.pan.mag()){var l=Lo(i.pan.mag(),n,t.extend({},Po,e||{}));s.offset=i.pan.mult(l.amount/i.pan.mag()),s.center=this._map.transform.center,Mo(s,l);}if(i.zoom){var c=Lo(i.zoom,n,So);s.zoom=this._map.transform.zoom+c.amount,Mo(s,c);}if(i.bearing){var u=Lo(i.bearing,n,Co);s.bearing=this._map.transform.bearing+t.clamp(u.amount,-179,179),Mo(s,u);}if(i.pitch){var h=Lo(i.pitch,n,zo);s.pitch=this._map.transform.pitch+h.amount,Mo(s,h);}if(s.zoom||s.bearing){var p=void 0===i.pinchAround?i.around:i.pinchAround;s.around=p?this._map.unproject(p):this._map.getCenter();}return this.clear(),t.extend(s,{noMoveStart:!0})}};var Ao=function(e){function o(o,r,a,n){void 0===n&&(n={});var s=i.mousePos(r.getCanvasContainer(),a),l=r.unproject(s);e.call(this,o,t.extend({point:s,lngLat:l,originalEvent:a},n)),this._defaultPrevented=!1,this.target=r;}e&&(o.__proto__=e),(o.prototype=Object.create(e&&e.prototype)).constructor=o;var r={defaultPrevented:{configurable:!0}};return o.prototype.preventDefault=function(){this._defaultPrevented=!0;},r.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(o.prototype,r),o}(t.Event),Ro=function(e){function o(o,r,a){var n="touchend"===o?a.changedTouches:a.touches,s=i.touchPos(r.getCanvasContainer(),n),l=s.map((function(t){return r.unproject(t)})),c=s.reduce((function(t,e,i,o){return t.add(e.div(o.length))}),new t.Point(0,0)),u=r.unproject(c);e.call(this,o,{points:s,point:c,lngLats:l,lngLat:u,originalEvent:a}),this._defaultPrevented=!1;}e&&(o.__proto__=e),(o.prototype=Object.create(e&&e.prototype)).constructor=o;var r={defaultPrevented:{configurable:!0}};return o.prototype.preventDefault=function(){this._defaultPrevented=!0;},r.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(o.prototype,r),o}(t.Event),ko=function(t){function e(e,i,o){t.call(this,e,{originalEvent:o}),this._defaultPrevented=!1;}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var i={defaultPrevented:{configurable:!0}};return e.prototype.preventDefault=function(){this._defaultPrevented=!0;},i.defaultPrevented.get=function(){return this._defaultPrevented},Object.defineProperties(e.prototype,i),e}(t.Event),Bo=function(t,e){this._map=t,this._clickTolerance=e.clickTolerance;};Bo.prototype.reset=function(){delete this._mousedownPos;},Bo.prototype.wheel=function(t){return this._firePreventable(new ko(t.type,this._map,t))},Bo.prototype.mousedown=function(t,e){return this._mousedownPos=e,this._firePreventable(new Ao(t.type,this._map,t))},Bo.prototype.mouseup=function(t){this._map.fire(new Ao(t.type,this._map,t));},Bo.prototype.click=function(t,e){this._mousedownPos&&this._mousedownPos.dist(e)>=this._clickTolerance||this._map.fire(new Ao(t.type,this._map,t));},Bo.prototype.dblclick=function(t){return this._firePreventable(new Ao(t.type,this._map,t))},Bo.prototype.mouseover=function(t){this._map.fire(new Ao(t.type,this._map,t));},Bo.prototype.mouseout=function(t){this._map.fire(new Ao(t.type,this._map,t));},Bo.prototype.touchstart=function(t){return this._firePreventable(new Ro(t.type,this._map,t))},Bo.prototype.touchmove=function(t){this._map.fire(new Ro(t.type,this._map,t));},Bo.prototype.touchend=function(t){this._map.fire(new Ro(t.type,this._map,t));},Bo.prototype.touchcancel=function(t){this._map.fire(new Ro(t.type,this._map,t));},Bo.prototype._firePreventable=function(t){if(this._map.fire(t),t.defaultPrevented)return {}},Bo.prototype.isEnabled=function(){return !0},Bo.prototype.isActive=function(){return !1},Bo.prototype.enable=function(){},Bo.prototype.disable=function(){};var Oo=function(t){this._map=t;};Oo.prototype.reset=function(){this._delayContextMenu=!1,delete this._contextMenuEvent;},Oo.prototype.mousemove=function(t){this._map.fire(new Ao(t.type,this._map,t));},Oo.prototype.mousedown=function(){this._delayContextMenu=!0;},Oo.prototype.mouseup=function(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new Ao("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);},Oo.prototype.contextmenu=function(t){this._delayContextMenu?this._contextMenuEvent=t:this._map.fire(new Ao(t.type,this._map,t)),this._map.listens("contextmenu")&&t.preventDefault();},Oo.prototype.isEnabled=function(){return !0},Oo.prototype.isActive=function(){return !1},Oo.prototype.enable=function(){},Oo.prototype.disable=function(){};var Fo=function(t,e){this._map=t,this._el=t.getCanvasContainer(),this._container=t.getContainer(),this._clickTolerance=e.clickTolerance||1;};function Uo(t,e){for(var i={},o=0;o<t.length;o++)i[t[o].identifier]=e[o];return i}Fo.prototype.isEnabled=function(){return !!this._enabled},Fo.prototype.isActive=function(){return !!this._active},Fo.prototype.enable=function(){this.isEnabled()||(this._enabled=!0);},Fo.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1);},Fo.prototype.mousedown=function(t,e){this.isEnabled()&&t.shiftKey&&0===t.button&&(i.disableDrag(),this._startPos=this._lastPos=e,this._active=!0);},Fo.prototype.mousemoveWindow=function(t,e){if(this._active){var o=e;if(!(this._lastPos.equals(o)||!this._box&&o.dist(this._startPos)<this._clickTolerance)){var r=this._startPos;this._lastPos=o,this._box||(this._box=i.create("div","mapboxgl-boxzoom",this._container),this._container.classList.add("mapboxgl-crosshair"),this._fireEvent("boxzoomstart",t));var a=Math.min(r.x,o.x),n=Math.max(r.x,o.x),s=Math.min(r.y,o.y),l=Math.max(r.y,o.y);i.setTransform(this._box,"translate("+a+"px,"+s+"px)"),this._box.style.width=n-a+"px",this._box.style.height=l-s+"px";}}},Fo.prototype.mouseupWindow=function(e,o){var r=this;if(this._active&&0===e.button){var a=this._startPos,n=o;if(this.reset(),i.suppressClick(),a.x!==n.x||a.y!==n.y)return this._map.fire(new t.Event("boxzoomend",{originalEvent:e})),{cameraAnimation:function(t){return t.fitScreenCoordinates(a,n,r._map.getBearing(),{linear:!0})}};this._fireEvent("boxzoomcancel",e);}},Fo.prototype.keydown=function(t){this._active&&27===t.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",t));},Fo.prototype.reset=function(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(i.remove(this._box),this._box=null),i.enableDrag(),delete this._startPos,delete this._lastPos;},Fo.prototype._fireEvent=function(e,i){return this._map.fire(new t.Event(e,{originalEvent:i}))};var No=function(t){this.reset(),this.numTouches=t.numTouches;};No.prototype.reset=function(){delete this.centroid,delete this.startTime,delete this.touches,this.aborted=!1;},No.prototype.touchstart=function(e,i,o){(this.centroid||o.length>this.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=e.timeStamp),o.length===this.numTouches&&(this.centroid=function(e){for(var i=new t.Point(0,0),o=0,r=e;o<r.length;o+=1)i._add(r[o]);return i.div(e.length)}(i),this.touches=Uo(o,i)));},No.prototype.touchmove=function(t,e,i){if(!this.aborted&&this.centroid){var o=Uo(i,e);for(var r in this.touches){var a=o[r];(!a||a.dist(this.touches[r])>30)&&(this.aborted=!0);}}},No.prototype.touchend=function(t,e,i){if((!this.centroid||t.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){var o=!this.aborted&&this.centroid;if(this.reset(),o)return o}};var Zo=function(t){this.singleTap=new No(t),this.numTaps=t.numTaps,this.reset();};Zo.prototype.reset=function(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();},Zo.prototype.touchstart=function(t,e,i){this.singleTap.touchstart(t,e,i);},Zo.prototype.touchmove=function(t,e,i){this.singleTap.touchmove(t,e,i);},Zo.prototype.touchend=function(t,e,i){var o=this.singleTap.touchend(t,e,i);if(o){var r=t.timeStamp-this.lastTime<500,a=!this.lastTap||this.lastTap.dist(o)<30;if(r&&a||this.reset(),this.count++,this.lastTime=t.timeStamp,this.lastTap=o,this.count===this.numTaps)return this.reset(),o}};var jo=function(){this._zoomIn=new Zo({numTouches:1,numTaps:2}),this._zoomOut=new Zo({numTouches:2,numTaps:1}),this.reset();};jo.prototype.reset=function(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset();},jo.prototype.touchstart=function(t,e,i){this._zoomIn.touchstart(t,e,i),this._zoomOut.touchstart(t,e,i);},jo.prototype.touchmove=function(t,e,i){this._zoomIn.touchmove(t,e,i),this._zoomOut.touchmove(t,e,i);},jo.prototype.touchend=function(t,e,i){var o=this,r=this._zoomIn.touchend(t,e,i),a=this._zoomOut.touchend(t,e,i);return r?(this._active=!0,t.preventDefault(),setTimeout((function(){return o.reset()}),0),{cameraAnimation:function(e){return e.easeTo({duration:300,zoom:e.getZoom()+1,around:e.unproject(r)},{originalEvent:t})}}):a?(this._active=!0,t.preventDefault(),setTimeout((function(){return o.reset()}),0),{cameraAnimation:function(e){return e.easeTo({duration:300,zoom:e.getZoom()-1,around:e.unproject(a)},{originalEvent:t})}}):void 0},jo.prototype.touchcancel=function(){this.reset();},jo.prototype.enable=function(){this._enabled=!0;},jo.prototype.disable=function(){this._enabled=!1,this.reset();},jo.prototype.isEnabled=function(){return this._enabled},jo.prototype.isActive=function(){return this._active};var qo=function(t){this.reset(),this._clickTolerance=t.clickTolerance||1;};qo.prototype.reset=function(){this._active=!1,this._moved=!1,delete this._lastPoint,delete this._eventButton;},qo.prototype._correctButton=function(t,e){return !1},qo.prototype._move=function(t,e){return {}},qo.prototype.mousedown=function(t,e){if(!this._lastPoint){var o=i.mouseButton(t);this._correctButton(t,o)&&(this._lastPoint=e,this._eventButton=o);}},qo.prototype.mousemoveWindow=function(t,e){var i=this._lastPoint;if(i&&(t.preventDefault(),this._moved||!(e.dist(i)<this._clickTolerance)))return this._moved=!0,this._lastPoint=e,this._move(i,e)},qo.prototype.mouseupWindow=function(t){i.mouseButton(t)===this._eventButton&&(this._moved&&i.suppressClick(),this.reset());},qo.prototype.enable=function(){this._enabled=!0;},qo.prototype.disable=function(){this._enabled=!1,this.reset();},qo.prototype.isEnabled=function(){return this._enabled},qo.prototype.isActive=function(){return this._active};var Vo=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.mousedown=function(e,i){t.prototype.mousedown.call(this,e,i),this._lastPoint&&(this._active=!0);},e.prototype._correctButton=function(t,e){return 0===e&&!t.ctrlKey},e.prototype._move=function(t,e){return {around:e,panDelta:e.sub(t)}},e}(qo),Go=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._correctButton=function(t,e){return 0===e&&t.ctrlKey||2===e},e.prototype._move=function(t,e){var i=.8*(e.x-t.x);if(i)return this._active=!0,{bearingDelta:i}},e.prototype.contextmenu=function(t){t.preventDefault();},e}(qo),Wo=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._correctButton=function(t,e){return 0===e&&t.ctrlKey||2===e},e.prototype._move=function(t,e){var i=-.5*(e.y-t.y);if(i)return this._active=!0,{pitchDelta:i}},e.prototype.contextmenu=function(t){t.preventDefault();},e}(qo),Xo=function(t){this._minTouches=1,this._clickTolerance=t.clickTolerance||1,this.reset();};Xo.prototype.reset=function(){this._active=!1,this._touches={},this._sum=new t.Point(0,0);},Xo.prototype.touchstart=function(t,e,i){return this._calculateTransform(t,e,i)},Xo.prototype.touchmove=function(t,e,i){if(this._active)return t.preventDefault(),this._calculateTransform(t,e,i)},Xo.prototype.touchend=function(t,e,i){this._calculateTransform(t,e,i),this._active&&i.length<this._minTouches&&this.reset();},Xo.prototype.touchcancel=function(){this.reset();},Xo.prototype._calculateTransform=function(e,i,o){o.length>0&&(this._active=!0);var r=Uo(o,i),a=new t.Point(0,0),n=new t.Point(0,0),s=0;for(var l in r){var c=r[l],u=this._touches[l];u&&(a._add(c),n._add(c.sub(u)),s++,r[l]=c);}if(this._touches=r,!(s<this._minTouches)&&n.mag()){var h=n.div(s);if(this._sum._add(h),!(this._sum.mag()<this._clickTolerance))return {around:a.div(s),panDelta:h}}},Xo.prototype.enable=function(){this._enabled=!0;},Xo.prototype.disable=function(){this._enabled=!1,this.reset();},Xo.prototype.isEnabled=function(){return this._enabled},Xo.prototype.isActive=function(){return this._active};var Ho=function(){this.reset();};function Ko(t,e,i){for(var o=0;o<t.length;o++)if(t[o].identifier===i)return e[o]}function Yo(t,e){return Math.log(t/e)/Math.LN2}Ho.prototype.reset=function(){this._active=!1,delete this._firstTwoTouches;},Ho.prototype._start=function(t){},Ho.prototype._move=function(t,e,i){return {}},Ho.prototype.touchstart=function(t,e,i){this._firstTwoTouches||i.length<2||(this._firstTwoTouches=[i[0].identifier,i[1].identifier],this._start([e[0],e[1]]));},Ho.prototype.touchmove=function(t,e,i){if(this._firstTwoTouches){t.preventDefault();var o=this._firstTwoTouches,r=o[1],a=Ko(i,e,o[0]),n=Ko(i,e,r);if(a&&n){var s=this._aroundCenter?null:a.add(n).div(2);return this._move([a,n],s,t)}}},Ho.prototype.touchend=function(t,e,o){if(this._firstTwoTouches){var r=this._firstTwoTouches,a=r[1],n=Ko(o,e,r[0]),s=Ko(o,e,a);n&&s||(this._active&&i.suppressClick(),this.reset());}},Ho.prototype.touchcancel=function(){this.reset();},Ho.prototype.enable=function(t){this._enabled=!0,this._aroundCenter=!!t&&"center"===t.around;},Ho.prototype.disable=function(){this._enabled=!1,this.reset();},Ho.prototype.isEnabled=function(){return this._enabled},Ho.prototype.isActive=function(){return this._active};var Jo=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.reset=function(){t.prototype.reset.call(this),delete this._distance,delete this._startDistance;},e.prototype._start=function(t){this._startDistance=this._distance=t[0].dist(t[1]);},e.prototype._move=function(t,e){var i=this._distance;if(this._distance=t[0].dist(t[1]),this._active||!(Math.abs(Yo(this._distance,this._startDistance))<.1))return this._active=!0,{zoomDelta:Yo(this._distance,i),pinchAround:e}},e}(Ho);function Qo(t,e){return 180*t.angleWith(e)/Math.PI}var $o=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.reset=function(){t.prototype.reset.call(this),delete this._minDiameter,delete this._startVector,delete this._vector;},e.prototype._start=function(t){this._startVector=this._vector=t[0].sub(t[1]),this._minDiameter=t[0].dist(t[1]);},e.prototype._move=function(t,e){var i=this._vector;if(this._vector=t[0].sub(t[1]),this._active||!this._isBelowThreshold(this._vector))return this._active=!0,{bearingDelta:Qo(this._vector,i),pinchAround:e}},e.prototype._isBelowThreshold=function(t){this._minDiameter=Math.min(this._minDiameter,t.mag());var e=25/(Math.PI*this._minDiameter)*360,i=Qo(t,this._startVector);return Math.abs(i)<e},e}(Ho);function tr(t){return Math.abs(t.y)>Math.abs(t.x)}var er=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.reset=function(){t.prototype.reset.call(this),this._valid=void 0,delete this._firstMove,delete this._lastPoints;},e.prototype._start=function(t){this._lastPoints=t,tr(t[0].sub(t[1]))&&(this._valid=!1);},e.prototype._move=function(t,e,i){var o=t[0].sub(this._lastPoints[0]),r=t[1].sub(this._lastPoints[1]);if(this._valid=this.gestureBeginsVertically(o,r,i.timeStamp),this._valid)return this._lastPoints=t,this._active=!0,{pitchDelta:(o.y+r.y)/2*-.5}},e.prototype.gestureBeginsVertically=function(t,e,i){if(void 0!==this._valid)return this._valid;var o=t.mag()>=2,r=e.mag()>=2;if(o||r){if(!o||!r)return void 0===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;var a=t.y>0==e.y>0;return tr(t)&&tr(e)&&a}},e}(Ho),ir={panStep:100,bearingStep:15,pitchStep:10},or=function(){var t=ir;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep;};function rr(t){return t*(2-t)}or.prototype.reset=function(){this._active=!1;},or.prototype.keydown=function(t){var e=this;if(!(t.altKey||t.ctrlKey||t.metaKey)){var i=0,o=0,r=0,a=0,n=0;switch(t.keyCode){case 61:case 107:case 171:case 187:i=1;break;case 189:case 109:case 173:i=-1;break;case 37:t.shiftKey?o=-1:(t.preventDefault(),a=-1);break;case 39:t.shiftKey?o=1:(t.preventDefault(),a=1);break;case 38:t.shiftKey?r=1:(t.preventDefault(),n=-1);break;case 40:t.shiftKey?r=-1:(t.preventDefault(),n=1);break;default:return}return {cameraAnimation:function(s){var l=s.getZoom();s.easeTo({duration:300,easeId:"keyboardHandler",easing:rr,zoom:i?Math.round(l)+i*(t.shiftKey?2:1):l,bearing:s.getBearing()+o*e._bearingStep,pitch:s.getPitch()+r*e._pitchStep,offset:[-a*e._panStep,-n*e._panStep],center:s.getCenter()},{originalEvent:t});}}}},or.prototype.enable=function(){this._enabled=!0;},or.prototype.disable=function(){this._enabled=!1,this.reset();},or.prototype.isEnabled=function(){return this._enabled},or.prototype.isActive=function(){return this._active};var ar=function(e,i){this._map=e,this._el=e.getCanvasContainer(),this._handler=i,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=1/450,t.bindAll(["_onWheel","_onTimeout","_onScrollFrame","_onScrollFinished"],this);};ar.prototype.setZoomRate=function(t){this._defaultZoomRate=t;},ar.prototype.setWheelZoomRate=function(t){this._wheelZoomRate=t;},ar.prototype.isEnabled=function(){return !!this._enabled},ar.prototype.isActive=function(){return !!this._active||void 0!==this._finishTimeout},ar.prototype.isZooming=function(){return !!this._zooming},ar.prototype.enable=function(t){this.isEnabled()||(this._enabled=!0,this._aroundCenter=t&&"center"===t.around);},ar.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1);},ar.prototype.wheel=function(e){if(this.isEnabled()){var i=e.deltaMode===t.window.WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY,o=t.browser.now(),r=o-(this._lastWheelEventTime||0);this._lastWheelEventTime=o,0!==i&&i%4.000244140625==0?this._type="wheel":0!==i&&Math.abs(i)<4?this._type="trackpad":r>400?(this._type=null,this._lastValue=i,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(r*i)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,i+=this._lastValue)),e.shiftKey&&i&&(i/=4),this._type&&(this._lastWheelEvent=e,this._delta-=i,this._active||this._start(e)),e.preventDefault();}},ar.prototype._onTimeout=function(t){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(t);},ar.prototype._start=function(e){if(this._delta){this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);var o=i.mousePos(this._el,e);this._around=t.LngLat.convert(this._aroundCenter?this._map.getCenter():this._map.unproject(o)),this._aroundPoint=this._map.transform.locationPoint(this._around),this._frameId||(this._frameId=!0,this._handler._triggerRenderFrame());}},ar.prototype.renderFrame=function(){return this._onScrollFrame()},ar.prototype._onScrollFrame=function(){var e=this;if(this._frameId&&(this._frameId=null,this.isActive())){var i=this._map.transform;if(0!==this._delta){var o="wheel"===this._type&&Math.abs(this._delta)>4.000244140625?this._wheelZoomRate:this._defaultZoomRate,r=2/(1+Math.exp(-Math.abs(this._delta*o)));this._delta<0&&0!==r&&(r=1/r);var a="number"==typeof this._targetZoom?i.zoomScale(this._targetZoom):i.scale;this._targetZoom=Math.min(i.maxZoom,Math.max(i.minZoom,i.scaleZoom(a*r))),"wheel"===this._type&&(this._startZoom=i.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}var n,s="number"==typeof this._targetZoom?this._targetZoom:i.zoom,l=this._startZoom,c=this._easing,u=!1;if("wheel"===this._type&&l&&c){var h=Math.min((t.browser.now()-this._lastWheelEventTime)/200,1),p=c(h);n=t.number(l,s,p),h<1?this._frameId||(this._frameId=!0):u=!0;}else n=s,u=!0;return this._active=!0,u&&(this._active=!1,this._finishTimeout=setTimeout((function(){e._zooming=!1,e._handler._triggerRenderFrame(),delete e._targetZoom,delete e._finishTimeout;}),200)),{noInertia:!0,needsRenderFrame:!u,zoomDelta:n-i.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}},ar.prototype._smoothOutEasing=function(e){var i=t.ease;if(this._prevEase){var o=this._prevEase,r=(t.browser.now()-o.start)/o.duration,a=o.easing(r+.01)-o.easing(r),n=.27/Math.sqrt(a*a+1e-4)*.01,s=Math.sqrt(.0729-n*n);i=t.bezier(n,s,.25,1);}return this._prevEase={start:t.browser.now(),duration:e,easing:i},i},ar.prototype.reset=function(){this._active=!1;};var nr=function(t,e){this._clickZoom=t,this._tapZoom=e;};nr.prototype.enable=function(){this._clickZoom.enable(),this._tapZoom.enable();},nr.prototype.disable=function(){this._clickZoom.disable(),this._tapZoom.disable();},nr.prototype.isEnabled=function(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()},nr.prototype.isActive=function(){return this._clickZoom.isActive()||this._tapZoom.isActive()};var sr=function(){this.reset();};sr.prototype.reset=function(){this._active=!1;},sr.prototype.dblclick=function(t,e){return t.preventDefault(),{cameraAnimation:function(i){i.easeTo({duration:300,zoom:i.getZoom()+(t.shiftKey?-1:1),around:i.unproject(e)},{originalEvent:t});}}},sr.prototype.enable=function(){this._enabled=!0;},sr.prototype.disable=function(){this._enabled=!1,this.reset();},sr.prototype.isEnabled=function(){return this._enabled},sr.prototype.isActive=function(){return this._active};var lr=function(){this._tap=new Zo({numTouches:1,numTaps:1}),this.reset();};lr.prototype.reset=function(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,this._tap.reset();},lr.prototype.touchstart=function(t,e,i){this._swipePoint||(this._tapTime&&t.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?i.length>0&&(this._swipePoint=e[0],this._swipeTouch=i[0].identifier):this._tap.touchstart(t,e,i));},lr.prototype.touchmove=function(t,e,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;var o=e[0],r=o.y-this._swipePoint.y;return this._swipePoint=o,t.preventDefault(),this._active=!0,{zoomDelta:r/128}}}else this._tap.touchmove(t,e,i);},lr.prototype.touchend=function(t,e,i){this._tapTime?this._swipePoint&&0===i.length&&this.reset():this._tap.touchend(t,e,i)&&(this._tapTime=t.timeStamp);},lr.prototype.touchcancel=function(){this.reset();},lr.prototype.enable=function(){this._enabled=!0;},lr.prototype.disable=function(){this._enabled=!1,this.reset();},lr.prototype.isEnabled=function(){return this._enabled},lr.prototype.isActive=function(){return this._active};var cr=function(t,e,i){this._el=t,this._mousePan=e,this._touchPan=i;};cr.prototype.enable=function(t){this._inertiaOptions=t||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("mapboxgl-touch-drag-pan");},cr.prototype.disable=function(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("mapboxgl-touch-drag-pan");},cr.prototype.isEnabled=function(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()},cr.prototype.isActive=function(){return this._mousePan.isActive()||this._touchPan.isActive()};var ur=function(t,e,i){this._pitchWithRotate=t.pitchWithRotate,this._mouseRotate=e,this._mousePitch=i;};ur.prototype.enable=function(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable();},ur.prototype.disable=function(){this._mouseRotate.disable(),this._mousePitch.disable();},ur.prototype.isEnabled=function(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())},ur.prototype.isActive=function(){return this._mouseRotate.isActive()||this._mousePitch.isActive()};var hr=function(t,e,i,o){this._el=t,this._touchZoom=e,this._touchRotate=i,this._tapDragZoom=o,this._rotationDisabled=!1,this._enabled=!0;};hr.prototype.enable=function(t){this._touchZoom.enable(t),this._rotationDisabled||this._touchRotate.enable(t),this._tapDragZoom.enable(),this._el.classList.add("mapboxgl-touch-zoom-rotate");},hr.prototype.disable=function(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("mapboxgl-touch-zoom-rotate");},hr.prototype.isEnabled=function(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()},hr.prototype.isActive=function(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()},hr.prototype.disableRotation=function(){this._rotationDisabled=!0,this._touchRotate.disable();},hr.prototype.enableRotation=function(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable();};var pr=function(t){return t.zoom||t.drag||t.pitch||t.rotate},dr=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e}(t.Event);function _r(t){return t.panDelta&&t.panDelta.mag()||t.zoomDelta||t.bearingDelta||t.pitchDelta}var fr=function(e,o){this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Do(e),this._bearingSnap=o.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(o),t.bindAll(["handleEvent","handleWindowEvent"],this);var r=this._el;this._listeners=[[r,"touchstart",{passive:!1}],[r,"touchmove",{passive:!1}],[r,"touchend",void 0],[r,"touchcancel",void 0],[r,"mousedown",void 0],[r,"mousemove",void 0],[r,"mouseup",void 0],[t.window.document,"mousemove",{capture:!0}],[t.window.document,"mouseup",void 0],[r,"mouseover",void 0],[r,"mouseout",void 0],[r,"dblclick",void 0],[r,"click",void 0],[r,"keydown",{capture:!1}],[r,"keyup",void 0],[r,"wheel",{passive:!1}],[r,"contextmenu",void 0],[t.window,"blur",void 0]];for(var a=0,n=this._listeners;a<n.length;a+=1){var s=n[a],l=s[0];i.addEventListener(l,s[1],l===t.window.document?this.handleWindowEvent:this.handleEvent,s[2]);}};fr.prototype.destroy=function(){for(var e=0,o=this._listeners;e<o.length;e+=1){var r=o[e],a=r[0];i.removeEventListener(a,r[1],a===t.window.document?this.handleWindowEvent:this.handleEvent,r[2]);}},fr.prototype._addDefaultHandlers=function(t){var e=this._map,i=e.getCanvasContainer();this._add("mapEvent",new Bo(e,t));var o=e.boxZoom=new Fo(e,t);this._add("boxZoom",o);var r=new jo,a=new sr;e.doubleClickZoom=new nr(a,r),this._add("tapZoom",r),this._add("clickZoom",a);var n=new lr;this._add("tapDragZoom",n);var s=e.touchPitch=new er;this._add("touchPitch",s);var l=new Go(t),c=new Wo(t);e.dragRotate=new ur(t,l,c),this._add("mouseRotate",l,["mousePitch"]),this._add("mousePitch",c,["mouseRotate"]);var u=new Vo(t),h=new Xo(t);e.dragPan=new cr(i,u,h),this._add("mousePan",u),this._add("touchPan",h,["touchZoom","touchRotate"]);var p=new $o,d=new Jo;e.touchZoomRotate=new hr(i,d,p,n),this._add("touchRotate",p,["touchPan","touchZoom"]),this._add("touchZoom",d,["touchPan","touchRotate"]);var _=e.scrollZoom=new ar(e,this);this._add("scrollZoom",_,["mousePan"]);var f=e.keyboard=new or;this._add("keyboard",f),this._add("blockableMapEvent",new Oo(e));for(var m=0,g=["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"];m<g.length;m+=1){var v=g[m];t.interactive&&t[v]&&e[v].enable(t[v]);}},fr.prototype._add=function(t,e,i){this._handlers.push({handlerName:t,handler:e,allowed:i}),this._handlersById[t]=e;},fr.prototype.stop=function(){if(!this._updatingCamera){for(var t=0,e=this._handlers;t<e.length;t+=1)e[t].handler.reset();this._inertia.clear(),this._fireEvents({},{}),this._changes=[];}},fr.prototype.isActive=function(){for(var t=0,e=this._handlers;t<e.length;t+=1)if(e[t].handler.isActive())return !0;return !1},fr.prototype.isZooming=function(){return !!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()},fr.prototype.isRotating=function(){return !!this._eventsInProgress.rotate},fr.prototype.isMoving=function(){return Boolean(pr(this._eventsInProgress))||this.isZooming()},fr.prototype._blockedByActive=function(t,e,i){for(var o in t)if(o!==i&&(!e||e.indexOf(o)<0))return !0;return !1},fr.prototype.handleWindowEvent=function(t){this.handleEvent(t,t.type+"Window");},fr.prototype._getMapTouches=function(t){for(var e=[],i=0,o=t;i<o.length;i+=1){var r=o[i];this._el.contains(r.target)&&e.push(r);}return e},fr.prototype.handleEvent=function(t,e){if("blur"!==t.type){this._updatingCamera=!0;for(var o="renderFrame"===t.type?void 0:t,r={needsRenderFrame:!1},a={},n={},s=t.touches?this._getMapTouches(t.touches):void 0,l=s?i.touchPos(this._el,s):i.mousePos(this._el,t),c=0,u=this._handlers;c<u.length;c+=1){var h=u[c],p=h.handlerName,d=h.handler,_=h.allowed;if(d.isEnabled()){var f=void 0;this._blockedByActive(n,_,p)?d.reset():d[e||t.type]&&(f=d[e||t.type](t,l,s),this.mergeHandlerResult(r,a,f,p,o),f&&f.needsRenderFrame&&this._triggerRenderFrame()),(f||d.isActive())&&(n[p]=d);}}var m={};for(var g in this._previousActiveHandlers)n[g]||(m[g]=o);this._previousActiveHandlers=n,(Object.keys(m).length||_r(r))&&(this._changes.push([r,a,m]),this._triggerRenderFrame()),(Object.keys(n).length||_r(r))&&this._map._stop(!0),this._updatingCamera=!1;var v=r.cameraAnimation;v&&(this._inertia.clear(),this._fireEvents({},{}),this._changes=[],v(this._map));}else this.stop();},fr.prototype.mergeHandlerResult=function(e,i,o,r,a){if(o){t.extend(e,o);var n={handlerName:r,originalEvent:o.originalEvent||a};void 0!==o.zoomDelta&&(i.zoom=n),void 0!==o.panDelta&&(i.drag=n),void 0!==o.pitchDelta&&(i.pitch=n),void 0!==o.bearingDelta&&(i.rotate=n);}},fr.prototype._applyChanges=function(){for(var e={},i={},o={},r=0,a=this._changes;r<a.length;r+=1){var n=a[r],s=n[0],l=n[1],c=n[2];s.panDelta&&(e.panDelta=(e.panDelta||new t.Point(0,0))._add(s.panDelta)),s.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+s.zoomDelta),s.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+s.bearingDelta),s.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+s.pitchDelta),void 0!==s.around&&(e.around=s.around),void 0!==s.pinchAround&&(e.pinchAround=s.pinchAround),s.noInertia&&(e.noInertia=s.noInertia),t.extend(i,l),t.extend(o,c);}this._updateMapTransform(e,i,o),this._changes=[];},fr.prototype._updateMapTransform=function(t,e,i){var o=this._map,r=o.transform;if(!_r(t))return this._fireEvents(e,i);var a=t.panDelta,n=t.zoomDelta,s=t.bearingDelta,l=t.pitchDelta,c=t.around,u=t.pinchAround;void 0!==u&&(c=u),o._stop(!0),c=c||o.transform.centerPoint;var h=r.pointLocation(a?c.sub(a):c);s&&(r.bearing+=s),l&&(r.pitch+=l),n&&(r.zoom+=n),r.setLocationAtPoint(h,c),this._map._update(),t.noInertia||this._inertia.record(t),this._fireEvents(e,i);},fr.prototype._fireEvents=function(e,i){var o=this,r=pr(this._eventsInProgress),a=pr(e),n={};for(var s in e)this._eventsInProgress[s]||(n[s+"start"]=e[s].originalEvent),this._eventsInProgress[s]=e[s];for(var l in !r&&a&&this._fireEvent("movestart",a.originalEvent),n)this._fireEvent(l,n[l]);for(var c in e.rotate&&(this._bearingChanged=!0),a&&this._fireEvent("move",a.originalEvent),e)this._fireEvent(c,e[c].originalEvent);var u,h={};for(var p in this._eventsInProgress){var d=this._eventsInProgress[p],_=d.handlerName,f=d.originalEvent;this._handlersById[_].isActive()||(delete this._eventsInProgress[p],h[p+"end"]=u=i[_]||f);}for(var m in h)this._fireEvent(m,h[m]);var g=pr(this._eventsInProgress);if((r||a)&&!g){this._updatingCamera=!0;var v=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),y=function(t){return 0!==t&&-o._bearingSnap<t&&t<o._bearingSnap};v?(y(v.bearing||this._map.getBearing())&&(v.bearing=0),this._map.easeTo(v,{originalEvent:u})):(this._map.fire(new t.Event("moveend",{originalEvent:u})),y(this._map.getBearing())&&this._map.resetNorth()),this._bearingChanged=!1,this._updatingCamera=!1;}},fr.prototype._fireEvent=function(e,i){this._map.fire(new t.Event(e,i?{originalEvent:i}:{}));},fr.prototype._triggerRenderFrame=function(){var t=this;void 0===this._frameId&&(this._frameId=this._map._requestRenderFrame((function(e){delete t._frameId,t.handleEvent(new dr("renderFrame",{timeStamp:e})),t._applyChanges();})));};var mr=function(e){function i(i,o){e.call(this),this._moving=!1,this._zooming=!1,this.transform=i,this._bearingSnap=o.bearingSnap,t.bindAll(["_renderFrameCallback"],this);}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.getCenter=function(){return new t.LngLat(this.transform.center.lng,this.transform.center.lat)},i.prototype.setCenter=function(t,e){return this.jumpTo({center:t},e)},i.prototype.panBy=function(e,i,o){return e=t.Point.convert(e).mult(-1),this.panTo(this.transform.center,t.extend({offset:e},i),o)},i.prototype.panTo=function(e,i,o){return this.easeTo(t.extend({center:e},i),o)},i.prototype.getZoom=function(){return this.transform.zoom},i.prototype.setZoom=function(t,e){return this.jumpTo({zoom:t},e),this},i.prototype.zoomTo=function(e,i,o){return this.easeTo(t.extend({zoom:e},i),o)},i.prototype.zoomIn=function(t,e){return this.zoomTo(this.getZoom()+1,t,e),this},i.prototype.zoomOut=function(t,e){return this.zoomTo(this.getZoom()-1,t,e),this},i.prototype.getBearing=function(){return this.transform.bearing},i.prototype.setBearing=function(t,e){return this.jumpTo({bearing:t},e),this},i.prototype.getPadding=function(){return this.transform.padding},i.prototype.setPadding=function(t,e){return this.jumpTo({padding:t},e),this},i.prototype.rotateTo=function(e,i,o){return this.easeTo(t.extend({bearing:e},i),o)},i.prototype.resetNorth=function(e,i){return this.rotateTo(0,t.extend({duration:1e3},e),i),this},i.prototype.resetNorthPitch=function(e,i){return this.easeTo(t.extend({bearing:0,pitch:0,duration:1e3},e),i),this},i.prototype.snapToNorth=function(t,e){return Math.abs(this.getBearing())<this._bearingSnap?this.resetNorth(t,e):this},i.prototype.getPitch=function(){return this.transform.pitch},i.prototype.setPitch=function(t,e){return this.jumpTo({pitch:t},e),this},i.prototype.cameraForBounds=function(e,i){return e=t.LngLatBounds.convert(e),this._cameraForBoxAndBearing(e.getNorthWest(),e.getSouthEast(),0,i)},i.prototype._cameraForBoxAndBearing=function(e,i,o,r){var a={top:0,bottom:0,right:0,left:0};if("number"==typeof(r=t.extend({padding:a,offset:[0,0],maxZoom:this.transform.maxZoom},r)).padding){var n=r.padding;r.padding={top:n,bottom:n,right:n,left:n};}r.padding=t.extend(a,r.padding);var s=this.transform,l=s.padding,c=s.project(t.LngLat.convert(e)),u=s.project(t.LngLat.convert(i)),h=c.rotate(-o*Math.PI/180),p=u.rotate(-o*Math.PI/180),d=new t.Point(Math.max(h.x,p.x),Math.max(h.y,p.y)),_=new t.Point(Math.min(h.x,p.x),Math.min(h.y,p.y)),f=d.sub(_),m=(s.width-(l.left+l.right+r.padding.left+r.padding.right))/f.x,g=(s.height-(l.top+l.bottom+r.padding.top+r.padding.bottom))/f.y;if(!(g<0||m<0)){var v=Math.min(s.scaleZoom(s.scale*Math.min(m,g)),r.maxZoom),y=t.Point.convert(r.offset),x=new t.Point(y.x+(r.padding.left-r.padding.right)/2,y.y+(r.padding.top-r.padding.bottom)/2).mult(s.scale/s.zoomScale(v));return {center:s.unproject(c.add(u).div(2).sub(x)),zoom:v,bearing:o}}t.warnOnce("Map cannot fit within canvas with the given bounds, padding, and/or offset.");},i.prototype.fitBounds=function(t,e,i){return this._fitInternal(this.cameraForBounds(t,e),e,i)},i.prototype.fitScreenCoordinates=function(e,i,o,r,a){return this._fitInternal(this._cameraForBoxAndBearing(this.transform.pointLocation(t.Point.convert(e)),this.transform.pointLocation(t.Point.convert(i)),o,r),r,a)},i.prototype._fitInternal=function(e,i,o){return e?(delete(i=t.extend(e,i)).padding,i.linear?this.easeTo(i,o):this.flyTo(i,o)):this},i.prototype.jumpTo=function(e,i){this.stop();var o=this.transform,r=!1,a=!1,n=!1;return "zoom"in e&&o.zoom!==+e.zoom&&(r=!0,o.zoom=+e.zoom),void 0!==e.center&&(o.center=t.LngLat.convert(e.center)),"bearing"in e&&o.bearing!==+e.bearing&&(a=!0,o.bearing=+e.bearing),"pitch"in e&&o.pitch!==+e.pitch&&(n=!0,o.pitch=+e.pitch),null==e.padding||o.isPaddingEqual(e.padding)||(o.padding=e.padding),this.fire(new t.Event("movestart",i)).fire(new t.Event("move",i)),r&&this.fire(new t.Event("zoomstart",i)).fire(new t.Event("zoom",i)).fire(new t.Event("zoomend",i)),a&&this.fire(new t.Event("rotatestart",i)).fire(new t.Event("rotate",i)).fire(new t.Event("rotateend",i)),n&&this.fire(new t.Event("pitchstart",i)).fire(new t.Event("pitch",i)).fire(new t.Event("pitchend",i)),this.fire(new t.Event("moveend",i))},i.prototype.easeTo=function(e,i){var o=this;this._stop(!1,e.easeId),(!1===(e=t.extend({offset:[0,0],duration:500,easing:t.ease},e)).animate||!e.essential&&t.browser.prefersReducedMotion)&&(e.duration=0);var r=this.transform,a=this.getZoom(),n=this.getBearing(),s=this.getPitch(),l=this.getPadding(),c="zoom"in e?+e.zoom:a,u="bearing"in e?this._normalizeBearing(e.bearing,n):n,h="pitch"in e?+e.pitch:s,p="padding"in e?e.padding:r.padding,d=t.Point.convert(e.offset),_=r.centerPoint.add(d),f=r.pointLocation(_),m=t.LngLat.convert(e.center||f);this._normalizeCenter(m);var g,v,y=r.project(f),x=r.project(m).sub(y),b=r.zoomScale(c-a);e.around&&(g=t.LngLat.convert(e.around),v=r.locationPoint(g));var w={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=this._zooming||c!==a,this._rotating=this._rotating||n!==u,this._pitching=this._pitching||h!==s,this._padding=!r.isPaddingEqual(p),this._easeId=e.easeId,this._prepareEase(i,e.noMoveStart,w),clearTimeout(this._easeEndTimeoutID),this._ease((function(e){if(o._zooming&&(r.zoom=t.number(a,c,e)),o._rotating&&(r.bearing=t.number(n,u,e)),o._pitching&&(r.pitch=t.number(s,h,e)),o._padding&&(r.interpolatePadding(l,p,e),_=r.centerPoint.add(d)),g)r.setLocationAtPoint(g,v);else {var f=r.zoomScale(r.zoom-a),m=c>a?Math.min(2,b):Math.max(.5,b),w=Math.pow(m,1-e),T=r.unproject(y.add(x.mult(e*w)).mult(f));r.setLocationAtPoint(r.renderWorldCopies?T.wrap():T,_);}o._fireMoveEvents(i);}),(function(t){o._afterEase(i,t);}),e),this},i.prototype._prepareEase=function(e,i,o){void 0===o&&(o={}),this._moving=!0,i||o.moving||this.fire(new t.Event("movestart",e)),this._zooming&&!o.zooming&&this.fire(new t.Event("zoomstart",e)),this._rotating&&!o.rotating&&this.fire(new t.Event("rotatestart",e)),this._pitching&&!o.pitching&&this.fire(new t.Event("pitchstart",e));},i.prototype._fireMoveEvents=function(e){this.fire(new t.Event("move",e)),this._zooming&&this.fire(new t.Event("zoom",e)),this._rotating&&this.fire(new t.Event("rotate",e)),this._pitching&&this.fire(new t.Event("pitch",e));},i.prototype._afterEase=function(e,i){if(!this._easeId||!i||this._easeId!==i){delete this._easeId;var o=this._zooming,r=this._rotating,a=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,o&&this.fire(new t.Event("zoomend",e)),r&&this.fire(new t.Event("rotateend",e)),a&&this.fire(new t.Event("pitchend",e)),this.fire(new t.Event("moveend",e));}},i.prototype.flyTo=function(e,i){var o=this;if(!e.essential&&t.browser.prefersReducedMotion){var r=t.pick(e,["center","zoom","bearing","pitch","around"]);return this.jumpTo(r,i)}this.stop(),e=t.extend({offset:[0,0],speed:1.2,curve:1.42,easing:t.ease},e);var a=this.transform,n=this.getZoom(),s=this.getBearing(),l=this.getPitch(),c=this.getPadding(),u="zoom"in e?t.clamp(+e.zoom,a.minZoom,a.maxZoom):n,h="bearing"in e?this._normalizeBearing(e.bearing,s):s,p="pitch"in e?+e.pitch:l,d="padding"in e?e.padding:a.padding,_=a.zoomScale(u-n),f=t.Point.convert(e.offset),m=a.centerPoint.add(f),g=a.pointLocation(m),v=t.LngLat.convert(e.center||g);this._normalizeCenter(v);var y=a.project(g),x=a.project(v).sub(y),b=e.curve,w=Math.max(a.width,a.height),T=w/_,E=x.mag();if("minZoom"in e){var I=t.clamp(Math.min(e.minZoom,n,u),a.minZoom,a.maxZoom),P=w/a.zoomScale(I-n);b=Math.sqrt(P/E*2);}var S=b*b;function C(t){var e=(T*T-w*w+(t?-1:1)*S*S*E*E)/(2*(t?T:w)*S*E);return Math.log(Math.sqrt(e*e+1)-e)}function z(t){return (Math.exp(t)-Math.exp(-t))/2}function D(t){return (Math.exp(t)+Math.exp(-t))/2}var M=C(0),L=function(t){return D(M)/D(M+b*t)},A=function(t){return w*((D(M)*(z(e=M+b*t)/D(e))-z(M))/S)/E;var e;},R=(C(1)-M)/b;if(Math.abs(E)<1e-6||!isFinite(R)){if(Math.abs(w-T)<1e-6)return this.easeTo(e,i);var k=T<w?-1:1;R=Math.abs(Math.log(T/w))/b,A=function(){return 0},L=function(t){return Math.exp(k*b*t)};}return e.duration="duration"in e?+e.duration:1e3*R/("screenSpeed"in e?+e.screenSpeed/b:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=s!==h,this._pitching=p!==l,this._padding=!a.isPaddingEqual(d),this._prepareEase(i,!1),this._ease((function(e){var r=e*R,_=1/L(r);a.zoom=1===e?u:n+a.scaleZoom(_),o._rotating&&(a.bearing=t.number(s,h,e)),o._pitching&&(a.pitch=t.number(l,p,e)),o._padding&&(a.interpolatePadding(c,d,e),m=a.centerPoint.add(f));var g=1===e?v:a.unproject(y.add(x.mult(A(r))).mult(_));a.setLocationAtPoint(a.renderWorldCopies?g.wrap():g,m),o._fireMoveEvents(i);}),(function(){return o._afterEase(i)}),e),this},i.prototype.isEasing=function(){return !!this._easeFrameId},i.prototype.stop=function(){return this._stop()},i.prototype._stop=function(t,e){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){var i=this._onEaseEnd;delete this._onEaseEnd,i.call(this,e);}if(!t){var o=this.handlers;o&&o.stop();}return this},i.prototype._ease=function(e,i,o){!1===o.animate||0===o.duration?(e(1),i()):(this._easeStart=t.browser.now(),this._easeOptions=o,this._onEaseFrame=e,this._onEaseEnd=i,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));},i.prototype._renderFrameCallback=function(){var e=Math.min((t.browser.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},i.prototype._normalizeBearing=function(e,i){e=t.wrap(e,-180,180);var o=Math.abs(e-i);return Math.abs(e-360-i)<o&&(e-=360),Math.abs(e+360-i)<o&&(e+=360),e},i.prototype._normalizeCenter=function(t){var e=this.transform;if(e.renderWorldCopies&&!e.lngRange){var i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}},i}(t.Evented),gr=function(e){void 0===e&&(e={}),this.options=e,t.bindAll(["_updateEditLink","_updateData","_updateCompact"],this);};gr.prototype.getDefaultPosition=function(){return "bottom-right"},gr.prototype.onAdd=function(t){var e=this.options&&this.options.compact;return this._map=t,this._container=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._innerContainer=i.create("div","mapboxgl-ctrl-attrib-inner",this._container),e&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),void 0===e&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container},gr.prototype.onRemove=function(){i.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0,this._attribHTML=void 0;},gr.prototype._updateEditLink=function(){var e=this._editLink;e||(e=this._editLink=this._container.querySelector(".mapbox-improve-map"));var i=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||t.config.ACCESS_TOKEN}];if(e){var o=i.reduce((function(t,e,o){return e.value&&(t+=e.key+"="+e.value+(o<i.length-1?"&":"")),t}),"?");e.href=t.config.FEEDBACK_URL+"/"+o+(this._map._hash?this._map._hash.getHashString(!0):""),e.rel="noopener nofollow";}},gr.prototype._updateData=function(t){!t||"metadata"!==t.sourceDataType&&"style"!==t.dataType||(this._updateAttributions(),this._updateEditLink());},gr.prototype._updateAttributions=function(){if(this._map.style){var t=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?t=t.concat(this.options.customAttribution.map((function(t){return "string"!=typeof t?"":t}))):"string"==typeof this.options.customAttribution&&t.push(this.options.customAttribution)),this._map.style.stylesheet){var e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}var i=this._map.style.sourceCaches;for(var o in i){var r=i[o];if(r.used){var a=r.getSource();a.attribution&&t.indexOf(a.attribution)<0&&t.push(a.attribution);}}t.sort((function(t,e){return t.length-e.length}));var n=(t=t.filter((function(e,i){for(var o=i+1;o<t.length;o++)if(t[o].indexOf(e)>=0)return !1;return !0}))).join(" | ");n!==this._attribHTML&&(this._attribHTML=n,t.length?(this._innerContainer.innerHTML=n,this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null);}},gr.prototype._updateCompact=function(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact");};var vr=function(){t.bindAll(["_updateLogo"],this),t.bindAll(["_updateCompact"],this);};vr.prototype.onAdd=function(t){this._map=t,this._container=i.create("div","mapboxgl-ctrl");var e=i.create("a","mapboxgl-ctrl-logo");return e.target="_blank",e.rel="noopener nofollow",e.href="https://www.mapbox.com/",e.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),e.setAttribute("rel","noopener nofollow"),this._container.appendChild(e),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._map.on("resize",this._updateCompact),this._updateCompact(),this._container},vr.prototype.onRemove=function(){i.remove(this._container),this._map.off("sourcedata",this._updateLogo),this._map.off("resize",this._updateCompact);},vr.prototype.getDefaultPosition=function(){return "bottom-left"},vr.prototype._updateLogo=function(t){t&&"metadata"!==t.sourceDataType||(this._container.style.display=this._logoRequired()?"block":"none");},vr.prototype._logoRequired=function(){if(this._map.style){var t=this._map.style.sourceCaches;for(var e in t)if(t[e].getSource().mapbox_logo)return !0;return !1}},vr.prototype._updateCompact=function(){var t=this._container.children;if(t.length){var e=t[0];this._map.getCanvasContainer().offsetWidth<250?e.classList.add("mapboxgl-compact"):e.classList.remove("mapboxgl-compact");}};var yr=function(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;};yr.prototype.add=function(t){var e=++this._id;return this._queue.push({callback:t,id:e,cancelled:!1}),e},yr.prototype.remove=function(t){for(var e=this._currentlyRunning,i=0,o=e?this._queue.concat(e):this._queue;i<o.length;i+=1){var r=o[i];if(r.id===t)return void(r.cancelled=!0)}},yr.prototype.run=function(t){void 0===t&&(t=0);var e=this._currentlyRunning=this._queue;this._queue=[];for(var i=0,o=e;i<o.length;i+=1){var r=o[i];if(!r.cancelled&&(r.callback(t),this._cleared))break}this._cleared=!1,this._currentlyRunning=!1;},yr.prototype.clear=function(){this._currentlyRunning&&(this._cleared=!0),this._queue=[];};var xr={"FullscreenControl.Enter":"Enter fullscreen","FullscreenControl.Exit":"Exit fullscreen","GeolocateControl.FindMyLocation":"Find my location","GeolocateControl.LocationNotAvailable":"Location not available","LogoControl.Title":"Mapbox logo","NavigationControl.ResetBearing":"Reset bearing to north","NavigationControl.ZoomIn":"Zoom in","NavigationControl.ZoomOut":"Zoom out","ScaleControl.Feet":"ft","ScaleControl.Meters":"m","ScaleControl.Kilometers":"km","ScaleControl.Miles":"mi","ScaleControl.NauticalMiles":"nm"},br=t.window.HTMLImageElement,wr=t.window.HTMLElement,Tr=t.window.ImageBitmap,Er={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:-2,maxZoom:22,minPitch:0,maxPitch:60,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,touchPitch:!0,bearingSnap:7,clickTolerance:3,pitchWithRotate:!0,hash:!1,attributionControl:!0,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,renderWorldCopies:!0,refreshExpiredTiles:!0,maxTileCacheSize:null,localIdeographFontFamily:"sans-serif",transformRequest:null,accessToken:null,fadeDuration:300,crossSourceCollisions:!0},Ir=function(o){function r(e){var i=this;if(null!=(e=t.extend({},Er,e)).minZoom&&null!=e.maxZoom&&e.minZoom>e.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=e.minPitch&&null!=e.maxPitch&&e.minPitch>e.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=e.minPitch&&e.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=e.maxPitch&&e.maxPitch>60)throw new Error("maxPitch must be less than or equal to 60");var r=new wo(e.minZoom,e.maxZoom,e.minPitch,e.maxPitch,e.renderWorldCopies);if(o.call(this,r,e),this._interactive=e.interactive,this._maxTileCacheSize=e.maxTileCacheSize,this._failIfMajorPerformanceCaveat=e.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=e.preserveDrawingBuffer,this._antialias=e.antialias,this._trackResize=e.trackResize,this._bearingSnap=e.bearingSnap,this._refreshExpiredTiles=e.refreshExpiredTiles,this._fadeDuration=e.fadeDuration,this._crossSourceCollisions=e.crossSourceCollisions,this._crossFadingFactor=1,this._collectResourceTiming=e.collectResourceTiming,this._renderTaskQueue=new yr,this._controls=[],this._mapId=t.uniqueId(),this._locale=t.extend({},xr,e.locale),this._requestManager=new t.RequestManager(e.transformRequest,e.accessToken),"string"==typeof e.container){if(this._container=t.window.document.getElementById(e.container),!this._container)throw new Error("Container '"+e.container+"' not found.")}else {if(!(e.container instanceof wr))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=e.container;}if(e.maxBounds&&this.setMaxBounds(e.maxBounds),t.bindAll(["_onWindowOnline","_onWindowResize","_contextLost","_contextRestored"],this),this._setupContainer(),this._setupPainter(),void 0===this.painter)throw new Error("Failed to initialize WebGL.");this.on("move",(function(){return i._update(!1)})),this.on("moveend",(function(){return i._update(!1)})),this.on("zoom",(function(){return i._update(!0)})),void 0!==t.window&&(t.window.addEventListener("online",this._onWindowOnline,!1),t.window.addEventListener("resize",this._onWindowResize,!1)),this.handlers=new fr(this,e),this._hash=e.hash&&new Eo("string"==typeof e.hash&&e.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:e.center,zoom:e.zoom,bearing:e.bearing,pitch:e.pitch}),e.bounds&&(this.resize(),this.fitBounds(e.bounds,t.extend({},e.fitBoundsOptions,{duration:0})))),this.resize(),this._localIdeographFontFamily=e.localIdeographFontFamily,e.style&&this.setStyle(e.style,{localIdeographFontFamily:e.localIdeographFontFamily}),e.attributionControl&&this.addControl(new gr({customAttribution:e.customAttribution})),this.addControl(new vr,e.logoPosition),this.on("style.load",(function(){i.transform.unmodified&&i.jumpTo(i.style.stylesheet);})),this.on("data",(function(e){i._update("style"===e.dataType),i.fire(new t.Event(e.dataType+"data",e));})),this.on("dataloading",(function(e){i.fire(new t.Event(e.dataType+"dataloading",e));}));}o&&(r.__proto__=o),(r.prototype=Object.create(o&&o.prototype)).constructor=r;var a={showTileBoundaries:{configurable:!0},showPadding:{configurable:!0},showCollisionBoxes:{configurable:!0},showOverdrawInspector:{configurable:!0},repaint:{configurable:!0},vertices:{configurable:!0},version:{configurable:!0}};return r.prototype._getMapId=function(){return this._mapId},r.prototype.addControl=function(e,i){if(void 0===i&&e.getDefaultPosition&&(i=e.getDefaultPosition()),void 0===i&&(i="top-right"),!e||!e.onAdd)return this.fire(new t.ErrorEvent(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));var o=e.onAdd(this);this._controls.push(e);var r=this._controlPositions[i];return -1!==i.indexOf("bottom")?r.insertBefore(o,r.firstChild):r.appendChild(o),this},r.prototype.removeControl=function(e){if(!e||!e.onRemove)return this.fire(new t.ErrorEvent(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));var i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this},r.prototype.resize=function(e){var i=this._containerDimensions(),o=i[0],r=i[1];this._resizeCanvas(o,r),this.transform.resize(o,r),this.painter.resize(o,r);var a=!this._moving;return a&&(this.stop(),this.fire(new t.Event("movestart",e)).fire(new t.Event("move",e))),this.fire(new t.Event("resize",e)),a&&this.fire(new t.Event("moveend",e)),this},r.prototype.getBounds=function(){return this.transform.getBounds()},r.prototype.getMaxBounds=function(){return this.transform.getMaxBounds()},r.prototype.setMaxBounds=function(e){return this.transform.setMaxBounds(t.LngLatBounds.convert(e)),this._update()},r.prototype.setMinZoom=function(t){if((t=null==t?-2:t)>=-2&&t<=this.transform.maxZoom)return this.transform.minZoom=t,this._update(),this.getZoom()<t&&this.setZoom(t),this;throw new Error("minZoom must be between -2 and the current maxZoom, inclusive")},r.prototype.getMinZoom=function(){return this.transform.minZoom},r.prototype.setMaxZoom=function(t){if((t=null==t?22:t)>=this.transform.minZoom)return this.transform.maxZoom=t,this._update(),this.getZoom()>t&&this.setZoom(t),this;throw new Error("maxZoom must be greater than the current minZoom")},r.prototype.getMaxZoom=function(){return this.transform.maxZoom},r.prototype.setMinPitch=function(t){if((t=null==t?0:t)<0)throw new Error("minPitch must be greater than or equal to 0");if(t>=0&&t<=this.transform.maxPitch)return this.transform.minPitch=t,this._update(),this.getPitch()<t&&this.setPitch(t),this;throw new Error("minPitch must be between 0 and the current maxPitch, inclusive")},r.prototype.getMinPitch=function(){return this.transform.minPitch},r.prototype.setMaxPitch=function(t){if((t=null==t?60:t)>60)throw new Error("maxPitch must be less than or equal to 60");if(t>=this.transform.minPitch)return this.transform.maxPitch=t,this._update(),this.getPitch()>t&&this.setPitch(t),this;throw new Error("maxPitch must be greater than the current minPitch")},r.prototype.getMaxPitch=function(){return this.transform.maxPitch},r.prototype.getRenderWorldCopies=function(){return this.transform.renderWorldCopies},r.prototype.setRenderWorldCopies=function(t){return this.transform.renderWorldCopies=t,this._update()},r.prototype.project=function(e){return this.transform.locationPoint(t.LngLat.convert(e))},r.prototype.unproject=function(e){return this.transform.pointLocation(t.Point.convert(e))},r.prototype.isMoving=function(){return this._moving||this.handlers.isMoving()},r.prototype.isZooming=function(){return this._zooming||this.handlers.isZooming()},r.prototype.isRotating=function(){return this._rotating||this.handlers.isRotating()},r.prototype._createDelegatedListener=function(t,e,i){var o,r=this;if("mouseenter"===t||"mouseover"===t){var a=!1;return {layer:e,listener:i,delegates:{mousemove:function(o){var n=r.getLayer(e)?r.queryRenderedFeatures(o.point,{layers:[e]}):[];n.length?a||(a=!0,i.call(r,new Ao(t,r,o.originalEvent,{features:n}))):a=!1;},mouseout:function(){a=!1;}}}}if("mouseleave"===t||"mouseout"===t){var n=!1;return {layer:e,listener:i,delegates:{mousemove:function(o){(r.getLayer(e)?r.queryRenderedFeatures(o.point,{layers:[e]}):[]).length?n=!0:n&&(n=!1,i.call(r,new Ao(t,r,o.originalEvent)));},mouseout:function(e){n&&(n=!1,i.call(r,new Ao(t,r,e.originalEvent)));}}}}return {layer:e,listener:i,delegates:(o={},o[t]=function(t){var o=r.getLayer(e)?r.queryRenderedFeatures(t.point,{layers:[e]}):[];o.length&&(t.features=o,i.call(r,t),delete t.features);},o)}},r.prototype.on=function(t,e,i){if(void 0===i)return o.prototype.on.call(this,t,e);var r=this._createDelegatedListener(t,e,i);for(var a in this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[t]=this._delegatedListeners[t]||[],this._delegatedListeners[t].push(r),r.delegates)this.on(a,r.delegates[a]);return this},r.prototype.once=function(t,e,i){if(void 0===i)return o.prototype.once.call(this,t,e);var r=this._createDelegatedListener(t,e,i);for(var a in r.delegates)this.once(a,r.delegates[a]);return this},r.prototype.off=function(t,e,i){var r=this;return void 0===i?o.prototype.off.call(this,t,e):(this._delegatedListeners&&this._delegatedListeners[t]&&function(o){for(var a=o[t],n=0;n<a.length;n++){var s=a[n];if(s.layer===e&&s.listener===i){for(var l in s.delegates)r.off(l,s.delegates[l]);return a.splice(n,1),r}}}(this._delegatedListeners),this)},r.prototype.queryRenderedFeatures=function(e,i){if(!this.style)return [];var o;if(void 0!==i||void 0===e||e instanceof t.Point||Array.isArray(e)||(i=e,e=void 0),i=i||{},(e=e||[[0,0],[this.transform.width,this.transform.height]])instanceof t.Point||"number"==typeof e[0])o=[t.Point.convert(e)];else {var r=t.Point.convert(e[0]),a=t.Point.convert(e[1]);o=[r,new t.Point(a.x,r.y),a,new t.Point(r.x,a.y),r];}return this.style.queryRenderedFeatures(o,i,this.transform)},r.prototype.querySourceFeatures=function(t,e){return this.style.querySourceFeatures(t,e)},r.prototype.setStyle=function(e,i){return !1!==(i=t.extend({},{localIdeographFontFamily:this._localIdeographFontFamily},i)).diff&&i.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,i),this):(this._localIdeographFontFamily=i.localIdeographFontFamily,this._updateStyle(e,i))},r.prototype._getUIString=function(t){var e=this._locale[t];if(null==e)throw new Error("Missing UI string '"+t+"'");return e},r.prototype._updateStyle=function(t,e){return this.style&&(this.style.setEventedParent(null),this.style._remove()),t?(this.style=new qe(this,e||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof t?this.style.loadURL(t):this.style.loadJSON(t),this):(delete this.style,this)},r.prototype._lazyInitEmptyStyle=function(){this.style||(this.style=new qe(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty());},r.prototype._diffStyle=function(e,i){var o=this;if("string"==typeof e){var r=this._requestManager.normalizeStyleURL(e),a=this._requestManager.transformRequest(r,t.ResourceType.Style);t.getJSON(a,(function(e,r){e?o.fire(new t.ErrorEvent(e)):r&&o._updateDiff(r,i);}));}else "object"==typeof e&&this._updateDiff(e,i);},r.prototype._updateDiff=function(e,i){try{this.style.setState(e)&&this._update(!0);}catch(o){t.warnOnce("Unable to perform style diff: "+(o.message||o.error||o)+".  Rebuilding the style from scratch."),this._updateStyle(e,i);}},r.prototype.getStyle=function(){if(this.style)return this.style.serialize()},r.prototype.isStyleLoaded=function(){return this.style?this.style.loaded():t.warnOnce("There is no style added to the map.")},r.prototype.addSource=function(t,e){return this._lazyInitEmptyStyle(),this.style.addSource(t,e),this._update(!0)},r.prototype.isSourceLoaded=function(e){var i=this.style&&this.style.sourceCaches[e];if(void 0!==i)return i.loaded();this.fire(new t.ErrorEvent(new Error("There is no source with ID '"+e+"'")));},r.prototype.areTilesLoaded=function(){var t=this.style&&this.style.sourceCaches;for(var e in t){var i=t[e]._tiles;for(var o in i){var r=i[o];if("loaded"!==r.state&&"errored"!==r.state)return !1}}return !0},r.prototype.addSourceType=function(t,e,i){return this._lazyInitEmptyStyle(),this.style.addSourceType(t,e,i)},r.prototype.removeSource=function(t){return this.style.removeSource(t),this._update(!0)},r.prototype.getSource=function(t){return this.style.getSource(t)},r.prototype.addImage=function(e,i,o){void 0===o&&(o={});var r=o.pixelRatio;void 0===r&&(r=1);var a=o.sdf;void 0===a&&(a=!1);var n=o.stretchX,s=o.stretchY,l=o.content;if(this._lazyInitEmptyStyle(),i instanceof br||Tr&&i instanceof Tr){var c=t.browser.getImageData(i);this.style.addImage(e,{data:new t.RGBAImage({width:c.width,height:c.height},c.data),pixelRatio:r,stretchX:n,stretchY:s,content:l,sdf:a,version:0});}else {if(void 0===i.width||void 0===i.height)return this.fire(new t.ErrorEvent(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));var u=i;this.style.addImage(e,{data:new t.RGBAImage({width:i.width,height:i.height},new Uint8Array(i.data)),pixelRatio:r,stretchX:n,stretchY:s,content:l,sdf:a,version:0,userImage:u}),u.onAdd&&u.onAdd(this,e);}},r.prototype.updateImage=function(e,i){var o=this.style.getImage(e);if(!o)return this.fire(new t.ErrorEvent(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));var r=i instanceof br||Tr&&i instanceof Tr?t.browser.getImageData(i):i,a=r.width,n=r.height,s=r.data;return void 0===a||void 0===n?this.fire(new t.ErrorEvent(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`"))):a!==o.data.width||n!==o.data.height?this.fire(new t.ErrorEvent(new Error("The width and height of the updated image must be that same as the previous version of the image"))):(o.data.replace(s,!(i instanceof br||Tr&&i instanceof Tr)),void this.style.updateImage(e,o))},r.prototype.hasImage=function(e){return e?!!this.style.getImage(e):(this.fire(new t.ErrorEvent(new Error("Missing required image id"))),!1)},r.prototype.removeImage=function(t){this.style.removeImage(t);},r.prototype.loadImage=function(e,i){t.getImage(this._requestManager.transformRequest(e,t.ResourceType.Image),i);},r.prototype.listImages=function(){return this.style.listImages()},r.prototype.addLayer=function(t,e){return this._lazyInitEmptyStyle(),this.style.addLayer(t,e),this._update(!0)},r.prototype.moveLayer=function(t,e){return this.style.moveLayer(t,e),this._update(!0)},r.prototype.removeLayer=function(t){return this.style.removeLayer(t),this._update(!0)},r.prototype.getLayer=function(t){return this.style.getLayer(t)},r.prototype.setLayerZoomRange=function(t,e,i){return this.style.setLayerZoomRange(t,e,i),this._update(!0)},r.prototype.setFilter=function(t,e,i){return void 0===i&&(i={}),this.style.setFilter(t,e,i),this._update(!0)},r.prototype.getFilter=function(t){return this.style.getFilter(t)},r.prototype.setPaintProperty=function(t,e,i,o){return void 0===o&&(o={}),this.style.setPaintProperty(t,e,i,o),this._update(!0)},r.prototype.getPaintProperty=function(t,e){return this.style.getPaintProperty(t,e)},r.prototype.setLayoutProperty=function(t,e,i,o){return void 0===o&&(o={}),this.style.setLayoutProperty(t,e,i,o),this._update(!0)},r.prototype.getLayoutProperty=function(t,e){return this.style.getLayoutProperty(t,e)},r.prototype.setLight=function(t,e){return void 0===e&&(e={}),this._lazyInitEmptyStyle(),this.style.setLight(t,e),this._update(!0)},r.prototype.getLight=function(){return this.style.getLight()},r.prototype.setFeatureState=function(t,e){return this.style.setFeatureState(t,e),this._update()},r.prototype.removeFeatureState=function(t,e){return this.style.removeFeatureState(t,e),this._update()},r.prototype.getFeatureState=function(t){return this.style.getFeatureState(t)},r.prototype.getContainer=function(){return this._container},r.prototype.getCanvasContainer=function(){return this._canvasContainer},r.prototype.getCanvas=function(){return this._canvas},r.prototype._containerDimensions=function(){var t=0,e=0;return this._container&&(t=this._container.clientWidth||400,e=this._container.clientHeight||300),[t,e]},r.prototype._detectMissingCSS=function(){"rgb(250, 128, 114)"!==t.window.getComputedStyle(this._missingCSSCanary).getPropertyValue("background-color")&&t.warnOnce("This page appears to be missing CSS declarations for Mapbox GL JS, which may cause the map to display incorrectly. Please ensure your page includes mapbox-gl.css, as described in https://www.mapbox.com/mapbox-gl-js/api/.");},r.prototype._setupContainer=function(){var t=this._container;t.classList.add("mapboxgl-map"),(this._missingCSSCanary=i.create("div","mapboxgl-canary",t)).style.visibility="hidden",this._detectMissingCSS();var e=this._canvasContainer=i.create("div","mapboxgl-canvas-container",t);this._interactive&&e.classList.add("mapboxgl-interactive"),this._canvas=i.create("canvas","mapboxgl-canvas",e),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex","0"),this._canvas.setAttribute("aria-label","Map");var o=this._containerDimensions();this._resizeCanvas(o[0],o[1]);var r=this._controlContainer=i.create("div","mapboxgl-control-container",t),a=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((function(t){a[t]=i.create("div","mapboxgl-ctrl-"+t,r);}));},r.prototype._resizeCanvas=function(e,i){var o=t.browser.devicePixelRatio||1;this._canvas.width=o*e,this._canvas.height=o*i,this._canvas.style.width=e+"px",this._canvas.style.height=i+"px";},r.prototype._setupPainter=function(){var i=t.extend({},e.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),o=this._canvas.getContext("webgl",i)||this._canvas.getContext("experimental-webgl",i);o?(this.painter=new vo(o,this.transform),t.webpSupported.testSupport(o)):this.fire(new t.ErrorEvent(new Error("Failed to initialize WebGL")));},r.prototype._contextLost=function(e){e.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new t.Event("webglcontextlost",{originalEvent:e}));},r.prototype._contextRestored=function(e){this._setupPainter(),this.resize(),this._update(),this.fire(new t.Event("webglcontextrestored",{originalEvent:e}));},r.prototype.loaded=function(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()},r.prototype._update=function(t){return this.style?(this._styleDirty=this._styleDirty||t,this._sourcesDirty=!0,this.triggerRepaint(),this):this},r.prototype._requestRenderFrame=function(t){return this._update(),this._renderTaskQueue.add(t)},r.prototype._cancelRenderFrame=function(t){this._renderTaskQueue.remove(t);},r.prototype._render=function(e){var i,o=this,r=0,a=this.painter.context.extTimerQuery;if(this.listens("gpu-timing-frame")&&(i=a.createQueryEXT(),a.beginQueryEXT(a.TIME_ELAPSED_EXT,i),r=t.browser.now()),this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(e),!this._removed){var n=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;var s=this.transform.zoom,l=t.browser.now();this.style.zoomHistory.update(s,l);var c=new t.EvaluationParameters(s,{now:l,fadeDuration:this._fadeDuration,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),u=c.crossFadingFactor();1===u&&u===this._crossFadingFactor||(n=!0,this._crossFadingFactor=u),this.style.update(c);}if(this.style&&this._sourcesDirty&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this._placementDirty=this.style&&this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,this._fadeDuration,this._crossSourceCollisions),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:this._fadeDuration,showPadding:this.showPadding,gpuTiming:!!this.listens("gpu-timing-layer")}),this.fire(new t.Event("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,this.fire(new t.Event("load"))),this.style&&(this.style.hasTransitions()||n)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles(),this.listens("gpu-timing-frame")){var h=t.browser.now()-r;a.endQueryEXT(a.TIME_ELAPSED_EXT,i),setTimeout((function(){var e=a.getQueryObjectEXT(i,a.QUERY_RESULT_EXT)/1e6;a.deleteQueryEXT(i),o.fire(new t.Event("gpu-timing-frame",{cpuTime:h,gpuTime:e}));}),50);}if(this.listens("gpu-timing-layer")){var p=this.painter.collectGpuTimers();setTimeout((function(){var e=o.painter.queryGpuTimers(p);o.fire(new t.Event("gpu-timing-layer",{layerTimes:e}));}),50);}return this._sourcesDirty||this._styleDirty||this._placementDirty||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&(this._fullyLoaded||(this._fullyLoaded=!0),this.fire(new t.Event("idle"))),this}},r.prototype.remove=function(){this._hash&&this._hash.remove();for(var e=0,i=this._controls;e<i.length;e+=1)i[e].onRemove(this);this._controls=[],this._frame&&(this._frame.cancel(),this._frame=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),void 0!==t.window&&(t.window.removeEventListener("resize",this._onWindowResize,!1),t.window.removeEventListener("online",this._onWindowOnline,!1));var o=this.painter.context.gl.getExtension("WEBGL_lose_context");o&&o.loseContext(),Pr(this._canvasContainer),Pr(this._controlContainer),Pr(this._missingCSSCanary),this._container.classList.remove("mapboxgl-map"),this._removed=!0,this.fire(new t.Event("remove"));},r.prototype.triggerRepaint=function(){var e=this;this.style&&!this._frame&&(this._frame=t.browser.frame((function(t){e._frame=null,e._render(t);})));},r.prototype._onWindowOnline=function(){this._update();},r.prototype._onWindowResize=function(t){this._trackResize&&this.resize({originalEvent:t})._update();},a.showTileBoundaries.get=function(){return !!this._showTileBoundaries},a.showTileBoundaries.set=function(t){this._showTileBoundaries!==t&&(this._showTileBoundaries=t,this._update());},a.showPadding.get=function(){return !!this._showPadding},a.showPadding.set=function(t){this._showPadding!==t&&(this._showPadding=t,this._update());},a.showCollisionBoxes.get=function(){return !!this._showCollisionBoxes},a.showCollisionBoxes.set=function(t){this._showCollisionBoxes!==t&&(this._showCollisionBoxes=t,t?this.style._generateCollisionBoxes():this._update());},a.showOverdrawInspector.get=function(){return !!this._showOverdrawInspector},a.showOverdrawInspector.set=function(t){this._showOverdrawInspector!==t&&(this._showOverdrawInspector=t,this._update());},a.repaint.get=function(){return !!this._repaint},a.repaint.set=function(t){this._repaint!==t&&(this._repaint=t,this.triggerRepaint());},a.vertices.get=function(){return !!this._vertices},a.vertices.set=function(t){this._vertices=t,this._update();},r.prototype._setCacheLimits=function(e,i){t.setCacheLimits(e,i);},a.version.get=function(){return t.version},Object.defineProperties(r.prototype,a),r}(mr);function Pr(t){t.parentNode&&t.parentNode.removeChild(t);}var Sr={showCompass:!0,showZoom:!0,visualizePitch:!1},Cr=function(e){var o=this;this.options=t.extend({},Sr,e),this._container=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",(function(t){return t.preventDefault()})),this.options.showZoom&&(t.bindAll(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",(function(t){return o._map.zoomIn({},{originalEvent:t})})),i.create("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden",!0),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",(function(t){return o._map.zoomOut({},{originalEvent:t})})),i.create("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden",!0)),this.options.showCompass&&(t.bindAll(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",(function(t){o.options.visualizePitch?o._map.resetNorthPitch({},{originalEvent:t}):o._map.resetNorth({},{originalEvent:t});})),this._compassIcon=i.create("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden",!0));};Cr.prototype._updateZoomButtons=function(){var t=this._map.getZoom();this._zoomInButton.disabled=t===this._map.getMaxZoom(),this._zoomOutButton.disabled=t===this._map.getMinZoom();},Cr.prototype._rotateCompassArrow=function(){var t=this.options.visualizePitch?"scale("+1/Math.pow(Math.cos(this._map.transform.pitch*(Math.PI/180)),.5)+") rotateX("+this._map.transform.pitch+"deg) rotateZ("+this._map.transform.angle*(180/Math.PI)+"deg)":"rotate("+this._map.transform.angle*(180/Math.PI)+"deg)";this._compassIcon.style.transform=t;},Cr.prototype.onAdd=function(t){return this._map=t,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new zr(this._map,this._compass,this.options.visualizePitch)),this._container},Cr.prototype.onRemove=function(){i.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map;},Cr.prototype._createButton=function(t,e){var o=i.create("button",t,this._container);return o.type="button",o.addEventListener("click",e),o},Cr.prototype._setButtonTitle=function(t,e){var i=this._map._getUIString("NavigationControl."+e);t.title=i,t.setAttribute("aria-label",i);};var zr=function(e,o,r){void 0===r&&(r=!1),this._clickTolerance=10,this.element=o,this.mouseRotate=new Go({clickTolerance:e.dragRotate._mouseRotate._clickTolerance}),this.map=e,r&&(this.mousePitch=new Wo({clickTolerance:e.dragRotate._mousePitch._clickTolerance})),t.bindAll(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),i.addEventListener(o,"mousedown",this.mousedown),i.addEventListener(o,"touchstart",this.touchstart,{passive:!1}),i.addEventListener(o,"touchmove",this.touchmove),i.addEventListener(o,"touchend",this.touchend),i.addEventListener(o,"touchcancel",this.reset);};function Dr(e,i,o){if(e=new t.LngLat(e.lng,e.lat),i){var r=new t.LngLat(e.lng-360,e.lat),a=new t.LngLat(e.lng+360,e.lat),n=o.locationPoint(e).distSqr(i);o.locationPoint(r).distSqr(i)<n?e=r:o.locationPoint(a).distSqr(i)<n&&(e=a);}for(;Math.abs(e.lng-o.center.lng)>180;){var s=o.locationPoint(e);if(s.x>=0&&s.y>=0&&s.x<=o.width&&s.y<=o.height)break;e.lng>o.center.lng?e.lng-=360:e.lng+=360;}return e}zr.prototype.down=function(t,e){this.mouseRotate.mousedown(t,e),this.mousePitch&&this.mousePitch.mousedown(t,e),i.disableDrag();},zr.prototype.move=function(t,e){var i=this.map,o=this.mouseRotate.mousemoveWindow(t,e);if(o&&o.bearingDelta&&i.setBearing(i.getBearing()+o.bearingDelta),this.mousePitch){var r=this.mousePitch.mousemoveWindow(t,e);r&&r.pitchDelta&&i.setPitch(i.getPitch()+r.pitchDelta);}},zr.prototype.off=function(){var t=this.element;i.removeEventListener(t,"mousedown",this.mousedown),i.removeEventListener(t,"touchstart",this.touchstart,{passive:!1}),i.removeEventListener(t,"touchmove",this.touchmove),i.removeEventListener(t,"touchend",this.touchend),i.removeEventListener(t,"touchcancel",this.reset),this.offTemp();},zr.prototype.offTemp=function(){i.enableDrag(),i.removeEventListener(t.window,"mousemove",this.mousemove),i.removeEventListener(t.window,"mouseup",this.mouseup);},zr.prototype.mousedown=function(e){this.down(t.extend({},e,{ctrlKey:!0,preventDefault:function(){return e.preventDefault()}}),i.mousePos(this.element,e)),i.addEventListener(t.window,"mousemove",this.mousemove),i.addEventListener(t.window,"mouseup",this.mouseup);},zr.prototype.mousemove=function(t){this.move(t,i.mousePos(this.element,t));},zr.prototype.mouseup=function(t){this.mouseRotate.mouseupWindow(t),this.mousePitch&&this.mousePitch.mouseupWindow(t),this.offTemp();},zr.prototype.touchstart=function(t){1!==t.targetTouches.length?this.reset():(this._startPos=this._lastPos=i.touchPos(this.element,t.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:function(){return t.preventDefault()}},this._startPos));},zr.prototype.touchmove=function(t){1!==t.targetTouches.length?this.reset():(this._lastPos=i.touchPos(this.element,t.targetTouches)[0],this.move({preventDefault:function(){return t.preventDefault()}},this._lastPos));},zr.prototype.touchend=function(t){0===t.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)<this._clickTolerance&&this.element.click(),this.reset();},zr.prototype.reset=function(){this.mouseRotate.reset(),this.mousePitch&&this.mousePitch.reset(),delete this._startPos,delete this._lastPos,this.offTemp();};var Mr={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function Lr(t,e,i){var o=t.classList;for(var r in Mr)o.remove("mapboxgl-"+i+"-anchor-"+r);o.add("mapboxgl-"+i+"-anchor-"+e);}var Ar,Rr=function(e){function o(o,r){var a=this;if(e.call(this),(o instanceof t.window.HTMLElement||r)&&(o=t.extend({element:o},r)),t.bindAll(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress"],this),this._anchor=o&&o.anchor||"center",this._color=o&&o.color||"#3FB1CE",this._draggable=o&&o.draggable||!1,this._state="inactive",this._rotation=o&&o.rotation||0,this._rotationAlignment=o&&o.rotationAlignment||"auto",this._pitchAlignment=o&&o.pitchAlignment&&"auto"!==o.pitchAlignment?o.pitchAlignment:this._rotationAlignment,o&&o.element)this._element=o.element,this._offset=t.Point.convert(o&&o.offset||[0,0]);else {this._defaultMarker=!0,this._element=i.create("div"),this._element.setAttribute("aria-label","Map marker");var n=i.createNS("http://www.w3.org/2000/svg","svg");n.setAttributeNS(null,"display","block"),n.setAttributeNS(null,"height","41px"),n.setAttributeNS(null,"width","27px"),n.setAttributeNS(null,"viewBox","0 0 27 41");var s=i.createNS("http://www.w3.org/2000/svg","g");s.setAttributeNS(null,"stroke","none"),s.setAttributeNS(null,"stroke-width","1"),s.setAttributeNS(null,"fill","none"),s.setAttributeNS(null,"fill-rule","evenodd");var l=i.createNS("http://www.w3.org/2000/svg","g");l.setAttributeNS(null,"fill-rule","nonzero");var c=i.createNS("http://www.w3.org/2000/svg","g");c.setAttributeNS(null,"transform","translate(3.0, 29.0)"),c.setAttributeNS(null,"fill","#000000");for(var u=0,h=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];u<h.length;u+=1){var p=h[u],d=i.createNS("http://www.w3.org/2000/svg","ellipse");d.setAttributeNS(null,"opacity","0.04"),d.setAttributeNS(null,"cx","10.5"),d.setAttributeNS(null,"cy","5.80029008"),d.setAttributeNS(null,"rx",p.rx),d.setAttributeNS(null,"ry",p.ry),c.appendChild(d);}var _=i.createNS("http://www.w3.org/2000/svg","g");_.setAttributeNS(null,"fill",this._color);var f=i.createNS("http://www.w3.org/2000/svg","path");f.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),_.appendChild(f);var m=i.createNS("http://www.w3.org/2000/svg","g");m.setAttributeNS(null,"opacity","0.25"),m.setAttributeNS(null,"fill","#000000");var g=i.createNS("http://www.w3.org/2000/svg","path");g.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),m.appendChild(g);var v=i.createNS("http://www.w3.org/2000/svg","g");v.setAttributeNS(null,"transform","translate(6.0, 7.0)"),v.setAttributeNS(null,"fill","#FFFFFF");var y=i.createNS("http://www.w3.org/2000/svg","g");y.setAttributeNS(null,"transform","translate(8.0, 8.0)");var x=i.createNS("http://www.w3.org/2000/svg","circle");x.setAttributeNS(null,"fill","#000000"),x.setAttributeNS(null,"opacity","0.25"),x.setAttributeNS(null,"cx","5.5"),x.setAttributeNS(null,"cy","5.5"),x.setAttributeNS(null,"r","5.4999962");var b=i.createNS("http://www.w3.org/2000/svg","circle");b.setAttributeNS(null,"fill","#FFFFFF"),b.setAttributeNS(null,"cx","5.5"),b.setAttributeNS(null,"cy","5.5"),b.setAttributeNS(null,"r","5.4999962"),y.appendChild(x),y.appendChild(b),l.appendChild(c),l.appendChild(_),l.appendChild(m),l.appendChild(v),l.appendChild(y),n.appendChild(l),this._element.appendChild(n),this._offset=t.Point.convert(o&&o.offset||[0,-14]);}this._element.classList.add("mapboxgl-marker"),this._element.addEventListener("dragstart",(function(t){t.preventDefault();})),this._element.addEventListener("mousedown",(function(t){t.preventDefault();})),this._element.addEventListener("focus",(function(){var t=a._map.getContainer();t.scrollTop=0,t.scrollLeft=0;})),Lr(this._element,this._anchor,"marker"),this._popup=null;}return e&&(o.__proto__=e),(o.prototype=Object.create(e&&e.prototype)).constructor=o,o.prototype.addTo=function(t){return this.remove(),this._map=t,t.getCanvasContainer().appendChild(this._element),t.on("move",this._update),t.on("moveend",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this},o.prototype.remove=function(){return this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),i.remove(this._element),this._popup&&this._popup.remove(),this},o.prototype.getLngLat=function(){return this._lngLat},o.prototype.setLngLat=function(e){return this._lngLat=t.LngLat.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this},o.prototype.getElement=function(){return this._element},o.prototype.setPopup=function(t){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),t){if(!("offset"in t.options)){var e=Math.sqrt(Math.pow(13.5,2)/2);t.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[e,-1*(24.6+e)],"bottom-right":[-e,-1*(24.6+e)],left:[13.5,-24.6],right:[-13.5,-24.6]}:this._offset;}this._popup=t,this._lngLat&&this._popup.setLngLat(this._lngLat),this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress);}return this},o.prototype._onKeyPress=function(t){var e=t.code,i=t.charCode||t.keyCode;"Space"!==e&&"Enter"!==e&&32!==i&&13!==i||this.togglePopup();},o.prototype._onMapClick=function(t){var e=t.originalEvent.target,i=this._element;this._popup&&(e===i||i.contains(e))&&this.togglePopup();},o.prototype.getPopup=function(){return this._popup},o.prototype.togglePopup=function(){var t=this._popup;return t?(t.isOpen()?t.remove():t.addTo(this._map),this):this},o.prototype._update=function(t){if(this._map){this._map.transform.renderWorldCopies&&(this._lngLat=Dr(this._lngLat,this._pos,this._map.transform)),this._pos=this._map.project(this._lngLat)._add(this._offset);var e="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?e="rotateZ("+this._rotation+"deg)":"map"===this._rotationAlignment&&(e="rotateZ("+(this._rotation-this._map.getBearing())+"deg)");var o="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?o="rotateX(0deg)":"map"===this._pitchAlignment&&(o="rotateX("+this._map.getPitch()+"deg)"),t&&"moveend"!==t.type||(this._pos=this._pos.round()),i.setTransform(this._element,Mr[this._anchor]+" translate("+this._pos.x+"px, "+this._pos.y+"px) "+o+" "+e);}},o.prototype.getOffset=function(){return this._offset},o.prototype.setOffset=function(e){return this._offset=t.Point.convert(e),this._update(),this},o.prototype._onMove=function(e){this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new t.Event("dragstart"))),this.fire(new t.Event("drag"));},o.prototype._onUp=function(){this._element.style.pointerEvents="auto",this._positionDelta=null,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new t.Event("dragend")),this._state="inactive";},o.prototype._addDragHandler=function(t){this._element.contains(t.originalEvent.target)&&(t.preventDefault(),this._positionDelta=t.point.sub(this._pos).add(this._offset),this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp));},o.prototype.setDraggable=function(t){return this._draggable=!!t,this._map&&(t?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this},o.prototype.isDraggable=function(){return this._draggable},o.prototype.setRotation=function(t){return this._rotation=t||0,this._update(),this},o.prototype.getRotation=function(){return this._rotation},o.prototype.setRotationAlignment=function(t){return this._rotationAlignment=t||"auto",this._update(),this},o.prototype.getRotationAlignment=function(){return this._rotationAlignment},o.prototype.setPitchAlignment=function(t){return this._pitchAlignment=t&&"auto"!==t?t:this._rotationAlignment,this._update(),this},o.prototype.getPitchAlignment=function(){return this._pitchAlignment},o}(t.Evented),kr={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0},Br=0,Or=!1,Fr=function(e){function o(i){e.call(this),this.options=t.extend({},kr,i),t.bindAll(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker"],this);}return e&&(o.__proto__=e),(o.prototype=Object.create(e&&e.prototype)).constructor=o,o.prototype.onAdd=function(e){var o;return this._map=e,this._container=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),o=this._setupUI,void 0!==Ar?o(Ar):void 0!==t.window.navigator.permissions?t.window.navigator.permissions.query({name:"geolocation"}).then((function(t){o(Ar="denied"!==t.state);})):o(Ar=!!t.window.navigator.geolocation),this._container},o.prototype.onRemove=function(){void 0!==this._geolocationWatchID&&(t.window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),i.remove(this._container),this._map.off("zoom",this._onZoom),this._map=void 0,Br=0,Or=!1;},o.prototype._isOutOfMapMaxBounds=function(t){var e=this._map.getMaxBounds(),i=t.coords;return e&&(i.longitude<e.getWest()||i.longitude>e.getEast()||i.latitude<e.getSouth()||i.latitude>e.getNorth())},o.prototype._setErrorState=function(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");}},o.prototype._onSuccess=function(e){if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.Event("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("mapboxgl-user-location-dot-stale"),this.fire(new t.Event("geolocate",e)),this._finish();}},o.prototype._updateCamera=function(e){var i=new t.LngLat(e.coords.longitude,e.coords.latitude),o=e.coords.accuracy,r=this._map.getBearing(),a=t.extend({bearing:r},this.options.fitBoundsOptions);this._map.fitBounds(i.toBounds(o),a,{geolocateSource:!0});},o.prototype._updateMarker=function(e){if(e){var i=new t.LngLat(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},o.prototype._updateCircleRadius=function(){var t=this._map._container.clientHeight/2,e=this._map.unproject([0,t]),i=this._map.unproject([1,t]),o=e.distanceTo(i),r=Math.ceil(2*this._accuracy/o);this._circleElement.style.width=r+"px",this._circleElement.style.height=r+"px";},o.prototype._onZoom=function(){this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();},o.prototype._onError=function(e){if(this._map){if(this.options.trackUserLocation)if(1===e.code){this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;var i=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=i,this._geolocateButton.setAttribute("aria-label",i),void 0!==this._geolocationWatchID&&this._clearWatch();}else {if(3===e.code&&Or)return;this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("mapboxgl-user-location-dot-stale"),this.fire(new t.Event("error",e)),this._finish();}},o.prototype._finish=function(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},o.prototype._setupUI=function(e){var o=this;if(this._container.addEventListener("contextmenu",(function(t){return t.preventDefault()})),this._geolocateButton=i.create("button","mapboxgl-ctrl-geolocate",this._container),i.create("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden",!0),this._geolocateButton.type="button",!1===e){t.warnOnce("Geolocation support is not available so the GeolocateControl will be disabled.");var r=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=r,this._geolocateButton.setAttribute("aria-label",r);}else {var a=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.title=a,this._geolocateButton.setAttribute("aria-label",a);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=i.create("div","mapboxgl-user-location-dot"),this._userLocationDotMarker=new Rr(this._dotElement),this._circleElement=i.create("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Rr({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",this.trigger.bind(this)),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(function(e){e.geolocateSource||"ACTIVE_LOCK"!==o._watchState||e.originalEvent&&"resize"===e.originalEvent.type||(o._watchState="BACKGROUND",o._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),o._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),o.fire(new t.Event("trackuserlocationend")));}));},o.prototype.trigger=function(){if(!this._setup)return t.warnOnce("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.Event("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":Br--,Or=!1,this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire(new t.Event("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.Event("trackuserlocationstart"));}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error");}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){var e;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),++Br>1?(e={maximumAge:6e5,timeout:0},Or=!0):(e=this.options.positionOptions,Or=!1),this._geolocationWatchID=t.window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else t.window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0},o.prototype._clearWatch=function(){t.window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);},o}(t.Evented),Ur={maxWidth:100,unit:"metric"},Nr=function(e){this.options=t.extend({},Ur,e),t.bindAll(["_onMove","setUnit"],this);};function Zr(t,e,i){var o=i&&i.maxWidth||100,r=t._container.clientHeight/2,a=t.unproject([0,r]),n=t.unproject([o,r]),s=a.distanceTo(n);if(i&&"imperial"===i.unit){var l=3.2808*s;l>5280?jr(e,o,l/5280,t._getUIString("ScaleControl.Miles")):jr(e,o,l,t._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?jr(e,o,s/1852,t._getUIString("ScaleControl.NauticalMiles")):s>=1e3?jr(e,o,s/1e3,t._getUIString("ScaleControl.Kilometers")):jr(e,o,s,t._getUIString("ScaleControl.Meters"));}function jr(t,e,i,o){var r,a,n,s=(r=i,(a=Math.pow(10,(""+Math.floor(r)).length-1))*(n=(n=r/a)>=10?10:n>=5?5:n>=3?3:n>=2?2:n>=1?1:function(t){var e=Math.pow(10,Math.ceil(-Math.log(t)/Math.LN10));return Math.round(t*e)/e}(n)));t.style.width=e*(s/i)+"px",t.innerHTML=s+"&nbsp;"+o;}Nr.prototype.getDefaultPosition=function(){return "bottom-left"},Nr.prototype._onMove=function(){Zr(this._map,this._container,this.options);},Nr.prototype.onAdd=function(t){return this._map=t,this._container=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-scale",t.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container},Nr.prototype.onRemove=function(){i.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;},Nr.prototype.setUnit=function(t){this.options.unit=t,Zr(this._map,this._container,this.options);};var qr=function(e){this._fullscreen=!1,e&&e.container&&(e.container instanceof t.window.HTMLElement?this._container=e.container:t.warnOnce("Full screen control 'container' must be a DOM element.")),t.bindAll(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in t.window.document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in t.window.document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in t.window.document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in t.window.document&&(this._fullscreenchange="MSFullscreenChange");};qr.prototype.onAdd=function(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display="none",t.warnOnce("This device does not support fullscreen mode.")),this._controlContainer},qr.prototype.onRemove=function(){i.remove(this._controlContainer),this._map=null,t.window.document.removeEventListener(this._fullscreenchange,this._changeIcon);},qr.prototype._checkFullscreenSupport=function(){return !!(t.window.document.fullscreenEnabled||t.window.document.mozFullScreenEnabled||t.window.document.msFullscreenEnabled||t.window.document.webkitFullscreenEnabled)},qr.prototype._setupUI=function(){var e=this._fullscreenButton=i.create("button","mapboxgl-ctrl-fullscreen",this._controlContainer);i.create("span","mapboxgl-ctrl-icon",e).setAttribute("aria-hidden",!0),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),t.window.document.addEventListener(this._fullscreenchange,this._changeIcon);},qr.prototype._updateTitle=function(){var t=this._getTitle();this._fullscreenButton.setAttribute("aria-label",t),this._fullscreenButton.title=t;},qr.prototype._getTitle=function(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")},qr.prototype._isFullscreen=function(){return this._fullscreen},qr.prototype._changeIcon=function(){(t.window.document.fullscreenElement||t.window.document.mozFullScreenElement||t.window.document.webkitFullscreenElement||t.window.document.msFullscreenElement)===this._container!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("mapboxgl-ctrl-shrink"),this._fullscreenButton.classList.toggle("mapboxgl-ctrl-fullscreen"),this._updateTitle());},qr.prototype._onClickFullscreen=function(){this._isFullscreen()?t.window.document.exitFullscreen?t.window.document.exitFullscreen():t.window.document.mozCancelFullScreen?t.window.document.mozCancelFullScreen():t.window.document.msExitFullscreen?t.window.document.msExitFullscreen():t.window.document.webkitCancelFullScreen&&t.window.document.webkitCancelFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen&&this._container.webkitRequestFullscreen();};var Vr={closeButton:!0,closeOnClick:!0,className:"",maxWidth:"240px"},Gr=function(e){function o(i){e.call(this),this.options=t.extend(Object.create(Vr),i),t.bindAll(["_update","_onClose","remove","_onMouseMove","_onMouseUp","_onDrag"],this);}return e&&(o.__proto__=e),(o.prototype=Object.create(e&&e.prototype)).constructor=o,o.prototype.addTo=function(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("mapboxgl-popup-track-pointer"),this._map._canvasContainer.classList.add("mapboxgl-track-pointer")):this._map.on("move",this._update),this.fire(new t.Event("open")),this},o.prototype.isOpen=function(){return !!this._map},o.prototype.remove=function(){return this._content&&i.remove(this._content),this._container&&(i.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),delete this._map),this.fire(new t.Event("close")),this},o.prototype.getLngLat=function(){return this._lngLat},o.prototype.setLngLat=function(e){return this._lngLat=t.LngLat.convert(e),this._pos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("mapboxgl-popup-track-pointer"),this._map._canvasContainer.classList.remove("mapboxgl-track-pointer")),this},o.prototype.trackPointer=function(){return this._trackPointer=!0,this._pos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("mapboxgl-popup-track-pointer"),this._map._canvasContainer.classList.add("mapboxgl-track-pointer")),this},o.prototype.getElement=function(){return this._container},o.prototype.setText=function(e){return this.setDOMContent(t.window.document.createTextNode(e))},o.prototype.setHTML=function(e){var i,o=t.window.document.createDocumentFragment(),r=t.window.document.createElement("body");for(r.innerHTML=e;i=r.firstChild;)o.appendChild(i);return this.setDOMContent(o)},o.prototype.getMaxWidth=function(){return this._container&&this._container.style.maxWidth},o.prototype.setMaxWidth=function(t){return this.options.maxWidth=t,this._update(),this},o.prototype.setDOMContent=function(t){return this._createContent(),this._content.appendChild(t),this._update(),this},o.prototype.addClassName=function(t){this._container&&this._container.classList.add(t);},o.prototype.removeClassName=function(t){this._container&&this._container.classList.remove(t);},o.prototype.toggleClassName=function(t){if(this._container)return this._container.classList.toggle(t)},o.prototype._createContent=function(){this._content&&i.remove(this._content),this._content=i.create("div","mapboxgl-popup-content",this._container),this.options.closeButton&&(this._closeButton=i.create("button","mapboxgl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.setAttribute("aria-label","Close popup"),this._closeButton.innerHTML="&#215;",this._closeButton.addEventListener("click",this._onClose));},o.prototype._onMouseUp=function(t){this._update(t.point);},o.prototype._onMouseMove=function(t){this._update(t.point);},o.prototype._onDrag=function(t){this._update(t.point);},o.prototype._update=function(e){var o=this;if(this._map&&(this._lngLat||this._trackPointer)&&this._content&&(this._container||(this._container=i.create("div","mapboxgl-popup",this._map.getContainer()),this._tip=i.create("div","mapboxgl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className&&this.options.className.split(" ").forEach((function(t){return o._container.classList.add(t)})),this._trackPointer&&this._container.classList.add("mapboxgl-popup-track-pointer")),this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._map.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=Dr(this._lngLat,this._pos,this._map.transform)),!this._trackPointer||e)){var r=this._pos=this._trackPointer&&e?e:this._map.project(this._lngLat),a=this.options.anchor,n=function e(i){if(i){if("number"==typeof i){var o=Math.round(Math.sqrt(.5*Math.pow(i,2)));return {center:new t.Point(0,0),top:new t.Point(0,i),"top-left":new t.Point(o,o),"top-right":new t.Point(-o,o),bottom:new t.Point(0,-i),"bottom-left":new t.Point(o,-o),"bottom-right":new t.Point(-o,-o),left:new t.Point(i,0),right:new t.Point(-i,0)}}if(i instanceof t.Point||Array.isArray(i)){var r=t.Point.convert(i);return {center:r,top:r,"top-left":r,"top-right":r,bottom:r,"bottom-left":r,"bottom-right":r,left:r,right:r}}return {center:t.Point.convert(i.center||[0,0]),top:t.Point.convert(i.top||[0,0]),"top-left":t.Point.convert(i["top-left"]||[0,0]),"top-right":t.Point.convert(i["top-right"]||[0,0]),bottom:t.Point.convert(i.bottom||[0,0]),"bottom-left":t.Point.convert(i["bottom-left"]||[0,0]),"bottom-right":t.Point.convert(i["bottom-right"]||[0,0]),left:t.Point.convert(i.left||[0,0]),right:t.Point.convert(i.right||[0,0])}}return e(new t.Point(0,0))}(this.options.offset);if(!a){var s,l=this._container.offsetWidth,c=this._container.offsetHeight;s=r.y+n.bottom.y<c?["top"]:r.y>this._map.transform.height-c?["bottom"]:[],r.x<l/2?s.push("left"):r.x>this._map.transform.width-l/2&&s.push("right"),a=0===s.length?"bottom":s.join("-");}var u=r.add(n[a]).round();i.setTransform(this._container,Mr[a]+" translate("+u.x+"px,"+u.y+"px)"),Lr(this._container,a,"popup");}},o.prototype._onClose=function(){this.remove();},o}(t.Evented),Wr={version:t.version,supported:e,setRTLTextPlugin:t.setRTLTextPlugin,getRTLTextPluginStatus:t.getRTLTextPluginStatus,Map:Ir,NavigationControl:Cr,GeolocateControl:Fr,AttributionControl:gr,ScaleControl:Nr,FullscreenControl:qr,Popup:Gr,Marker:Rr,Style:qe,LngLat:t.LngLat,LngLatBounds:t.LngLatBounds,Point:t.Point,MercatorCoordinate:t.MercatorCoordinate,Evented:t.Evented,config:t.config,prewarm:function(){Ft().acquire(Rt);},clearPrewarmedResources:function(){var t=Bt;t&&(t.isPreloaded()&&1===t.numActive()?(t.release(Rt),Bt=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"));},get accessToken(){return t.config.ACCESS_TOKEN},set accessToken(e){t.config.ACCESS_TOKEN=e;},get baseApiUrl(){return t.config.API_URL},set baseApiUrl(e){t.config.API_URL=e;},get workerCount(){return kt.workerCount},set workerCount(t){kt.workerCount=t;},get maxParallelImageRequests(){return t.config.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(e){t.config.MAX_PARALLEL_IMAGE_REQUESTS=e;},clearStorage:function(e){t.clearTileCache(e);},workerUrl:""};return Wr}));

//

return mapboxgl;

})));
//# sourceMappingURL=mapbox-gl.js.map


/***/ }),
/* 33 */
/***/ (function(module, exports) {

var g;

// This works in non-strict mode
g = (function() {
	return this;
})();

try {
	// This works if eval is allowed (see CSP)
	g = g || new Function("return this")();
} catch (e) {
	// This works if the window reference is available
	if (typeof window === "object") g = window;
}

// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}

module.exports = g;


/***/ }),
/* 34 */
/***/ (function(module, exports) {

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {
    "default": obj
  };
}

module.exports = _interopRequireDefault;

/***/ }),
/* 35 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// We need to centralize the zIndex definitions as they work
// like global values in the browser.
var zIndex = {
  mobileStepper: 1000,
  speedDial: 1050,
  appBar: 1100,
  drawer: 1200,
  modal: 1300,
  snackbar: 1400,
  tooltip: 1500
};
/* harmony default export */ __webpack_exports__["a"] = (zIndex);

/***/ }),
/* 36 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

var ThemeContext = react__WEBPACK_IMPORTED_MODULE_0___default.a.createContext(null);

if (false) {}

/* harmony default export */ __webpack_exports__["a"] = (ThemeContext);

/***/ }),
/* 37 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
var hasSymbol = typeof Symbol === 'function' && Symbol.for;
/* harmony default export */ __webpack_exports__["a"] = (hasSymbol ? Symbol.for('mui.nested') : '__THEME_NESTED__');

/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {

var objectKeys = __webpack_require__(53);
var isArguments = __webpack_require__(55);
var is = __webpack_require__(97);
var isRegex = __webpack_require__(98);
var flags = __webpack_require__(101);
var isArray = __webpack_require__(103);
var isDate = __webpack_require__(104);
var whichBoxedPrimitive = __webpack_require__(105);
var GetIntrinsic = __webpack_require__(30);
var callBound = __webpack_require__(43);
var whichCollection = __webpack_require__(110);
var getIterator = __webpack_require__(113);
var getSideChannel = __webpack_require__(116);

var $getTime = callBound('Date.prototype.getTime');
var gPO = Object.getPrototypeOf;
var $objToString = callBound('Object.prototype.toString');

var $Set = GetIntrinsic('%Set%', true);
var $mapHas = callBound('Map.prototype.has', true);
var $mapGet = callBound('Map.prototype.get', true);
var $mapSize = callBound('Map.prototype.size', true);
var $setAdd = callBound('Set.prototype.add', true);
var $setDelete = callBound('Set.prototype.delete', true);
var $setHas = callBound('Set.prototype.has', true);
var $setSize = callBound('Set.prototype.size', true);

// taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L401-L414
function setHasEqualElement(set, val1, strict, channel) {
  var i = getIterator(set);
  var result;
  while ((result = i.next()) && !result.done) {
    if (internalDeepEqual(val1, result.value, strict, channel)) { // eslint-disable-line no-use-before-define
      // Remove the matching element to make sure we do not check that again.
      $setDelete(set, result.value);
      return true;
    }
  }

  return false;
}

// taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L416-L439
function findLooseMatchingPrimitives(prim) {
  if (typeof prim === 'undefined') {
    return null;
  }
  if (typeof prim === 'object') { // Only pass in null as object!
    return void 0;
  }
  if (typeof prim === 'symbol') {
    return false;
  }
  if (typeof prim === 'string' || typeof prim === 'number') {
    // Loose equal entries exist only if the string is possible to convert to a regular number and not NaN.
    return +prim === +prim; // eslint-disable-line no-implicit-coercion
  }
  return true;
}

// taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L449-L460
function mapMightHaveLoosePrim(a, b, prim, item, channel) {
  var altValue = findLooseMatchingPrimitives(prim);
  if (altValue != null) {
    return altValue;
  }
  var curB = $mapGet(b, altValue);
  // eslint-disable-next-line no-use-before-define
  if ((typeof curB === 'undefined' && !$mapHas(b, altValue)) || !internalDeepEqual(item, curB, false, channel)) {
    return false;
  }
  // eslint-disable-next-line no-use-before-define
  return !$mapHas(a, altValue) && internalDeepEqual(item, curB, false, channel);
}

// taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L441-L447
function setMightHaveLoosePrim(a, b, prim) {
  var altValue = findLooseMatchingPrimitives(prim);
  if (altValue != null) {
    return altValue;
  }

  return $setHas(b, altValue) && !$setHas(a, altValue);
}

// taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L518-L533
function mapHasEqualEntry(set, map, key1, item1, strict, channel) {
  var i = getIterator(set);
  var result;
  var key2;
  while ((result = i.next()) && !result.done) {
    key2 = result.value;
    if (
      // eslint-disable-next-line no-use-before-define
      internalDeepEqual(key1, key2, strict, channel)
      // eslint-disable-next-line no-use-before-define
      && internalDeepEqual(item1, $mapGet(map, key2), strict, channel)
    ) {
      $setDelete(set, key2);
      return true;
    }
  }

  return false;
}

function internalDeepEqual(actual, expected, options, channel) {
  var opts = options || {};

  // 7.1. All identical values are equivalent, as determined by ===.
  if (opts.strict ? is(actual, expected) : actual === expected) {
    return true;
  }

  var actualBoxed = whichBoxedPrimitive(actual);
  var expectedBoxed = whichBoxedPrimitive(expected);
  if (actualBoxed !== expectedBoxed) {
    return false;
  }

  // 7.3. Other pairs that do not both pass typeof value == 'object', equivalence is determined by ==.
  if (!actual || !expected || (typeof actual !== 'object' && typeof expected !== 'object')) {
    if ((actual === false && expected) || (actual && expected === false)) { return false; }
    return opts.strict ? is(actual, expected) : actual == expected; // eslint-disable-line eqeqeq
  }

  /*
   * 7.4. For all other Object pairs, including Array objects, equivalence is
   * determined by having the same number of owned properties (as verified
   * with Object.prototype.hasOwnProperty.call), the same set of keys
   * (although not necessarily the same order), equivalent values for every
   * corresponding key, and an identical 'prototype' property. Note: this
   * accounts for both named and indexed properties on Arrays.
   */
  // see https://github.com/nodejs/node/commit/d3aafd02efd3a403d646a3044adcf14e63a88d32 for memos/channel inspiration

  var hasActual = channel.has(actual);
  var hasExpected = channel.has(expected);
  var sentinel;
  if (hasActual && hasExpected) {
    if (channel.get(actual) === channel.get(expected)) {
      return true;
    }
  } else {
    sentinel = {};
  }
  if (!hasActual) { channel.set(actual, sentinel); }
  if (!hasExpected) { channel.set(expected, sentinel); }

  // eslint-disable-next-line no-use-before-define
  return objEquiv(actual, expected, opts, channel);
}

function isBuffer(x) {
  if (!x || typeof x !== 'object' || typeof x.length !== 'number') {
    return false;
  }
  if (typeof x.copy !== 'function' || typeof x.slice !== 'function') {
    return false;
  }
  if (x.length > 0 && typeof x[0] !== 'number') {
    return false;
  }
  return true;
}

function setEquiv(a, b, opts, channel) {
  if ($setSize(a) !== $setSize(b)) {
    return false;
  }
  var iA = getIterator(a);
  var iB = getIterator(b);
  var resultA;
  var resultB;
  var set;
  while ((resultA = iA.next()) && !resultA.done) {
    if (resultA.value && typeof resultA.value === 'object') {
      if (!set) { set = new $Set(); }
      $setAdd(set, resultA.value);
    } else if (!$setHas(b, resultA.value)) {
      if (opts.strict) { return false; }
      if (!setMightHaveLoosePrim(a, b, resultA.value)) {
        return false;
      }
      if (!set) { set = new $Set(); }
      $setAdd(set, resultA.value);
    }
  }
  if (set) {
    while ((resultB = iB.next()) && !resultB.done) {
      // We have to check if a primitive value is already matching and only if it's not, go hunting for it.
      if (resultB.value && typeof resultB.value === 'object') {
        if (!setHasEqualElement(set, resultB.value, opts.strict, channel)) {
          return false;
        }
      } else if (
        !opts.strict
        && !$setHas(a, resultB.value)
        && !setHasEqualElement(set, resultB.value, opts.strict, channel)
      ) {
        return false;
      }
    }
    return $setSize(set) === 0;
  }
  return true;
}

function mapEquiv(a, b, opts, channel) {
  if ($mapSize(a) !== $mapSize(b)) {
    return false;
  }
  var iA = getIterator(a);
  var iB = getIterator(b);
  var resultA;
  var resultB;
  var set;
  var key;
  var item1;
  var item2;
  while ((resultA = iA.next()) && !resultA.done) {
    key = resultA.value[0];
    item1 = resultA.value[1];
    if (key && typeof key === 'object') {
      if (!set) { set = new $Set(); }
      $setAdd(set, key);
    } else {
      item2 = $mapGet(b, key);
      // if (typeof curB === 'undefined' && !$mapHas(b, altValue) || !internalDeepEqual(item, curB, false, channel)) {
      if ((typeof item2 === 'undefined' && !$mapHas(b, key)) || !internalDeepEqual(item1, item2, opts.strict, channel)) {
        if (opts.strict) {
          return false;
        }
        if (!mapMightHaveLoosePrim(a, b, key, item1, channel)) {
          return false;
        }
        if (!set) { set = new $Set(); }
        $setAdd(set, key);
      }
    }
  }

  if (set) {
    while ((resultB = iB.next()) && !resultB.done) {
      key = resultB.value[0];
      item1 = resultB.value[1];
      if (key && typeof key === 'object') {
        if (!mapHasEqualEntry(set, a, key, item1, opts.strict, channel)) {
          return false;
        }
      } else if (
        !opts.strict
        && (!a.has(key) || !internalDeepEqual($mapGet(a, key), item1, false, channel))
        && !mapHasEqualEntry(set, a, key, item1, false, channel)
      ) {
        return false;
      }
    }
    return $setSize(set) === 0;
  }
  return true;
}

function objEquiv(a, b, opts, channel) {
  /* eslint max-statements: [2, 100], max-lines-per-function: [2, 120], max-depth: [2, 5] */
  var i, key;

  if (typeof a !== typeof b) { return false; }
  if (a == null || b == null) { return false; }

  // an identical 'prototype' property.
  if (a.prototype !== b.prototype) { return false; }

  if ($objToString(a) !== $objToString(b)) { return false; }

  if (isArguments(a) !== isArguments(b)) { return false; }

  var aIsArray = isArray(a);
  var bIsArray = isArray(b);
  if (aIsArray !== bIsArray) { return false; }

  // TODO: replace when a cross-realm brand check is available
  var aIsError = a instanceof Error;
  var bIsError = b instanceof Error;
  if (aIsError !== bIsError) { return false; }
  if (aIsError || bIsError) {
    if (a.name !== b.name || a.message !== b.message) { return false; }
  }

  var aIsRegex = isRegex(a);
  var bIsRegex = isRegex(b);
  if (aIsRegex !== bIsRegex) { return false; }
  if ((aIsRegex || bIsRegex) && (a.source !== b.source || flags(a) !== flags(b))) {
    return false;
  }

  var aIsDate = isDate(a);
  var bIsDate = isDate(b);
  if (aIsDate !== bIsDate) { return false; }
  if (aIsDate || bIsDate) { // && would work too, because both are true or both false here
    if ($getTime(a) !== $getTime(b)) { return false; }
  }
  if (opts.strict && gPO && gPO(a) !== gPO(b)) { return false; }

  var aIsBuffer = isBuffer(a);
  var bIsBuffer = isBuffer(b);
  if (aIsBuffer !== bIsBuffer) { return false; }
  if (aIsBuffer || bIsBuffer) { // && would work too, because both are true or both false here
    if (a.length !== b.length) { return false; }
    for (i = 0; i < a.length; i++) {
      if (a[i] !== b[i]) { return false; }
    }
    return true;
  }

  if (typeof a !== typeof b) { return false; }

  try {
    var ka = objectKeys(a);
    var kb = objectKeys(b);
  } catch (e) { // happens when one is a string literal and the other isn't
    return false;
  }
  // having the same number of owned properties (keys incorporates hasOwnProperty)
  if (ka.length !== kb.length) { return false; }

  // the same set of keys (although not necessarily the same order),
  ka.sort();
  kb.sort();
  // ~~~cheap key test
  for (i = ka.length - 1; i >= 0; i--) {
    if (ka[i] != kb[i]) { return false; } // eslint-disable-line eqeqeq
  }

  // equivalent values for every corresponding key, and ~~~possibly expensive deep test
  for (i = ka.length - 1; i >= 0; i--) {
    key = ka[i];
    if (!internalDeepEqual(a[key], b[key], opts, channel)) { return false; }
  }

  var aCollection = whichCollection(a);
  var bCollection = whichCollection(b);
  if (aCollection !== bCollection) {
    return false;
  }
  if (aCollection === 'Set' || bCollection === 'Set') { // aCollection === bCollection
    return setEquiv(a, b, opts, channel);
  }
  if (aCollection === 'Map') { // aCollection === bCollection
    return mapEquiv(a, b, opts, channel);
  }

  return true;
}

module.exports = function deepEqual(a, b, opts) {
  return internalDeepEqual(a, b, opts, getSideChannel());
};


/***/ }),
/* 39 */,
/* 40 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var implementation = __webpack_require__(100);

module.exports = Function.prototype.bind || implementation;


/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var keys = __webpack_require__(53);
var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';

var toStr = Object.prototype.toString;
var concat = Array.prototype.concat;
var origDefineProperty = Object.defineProperty;

var isFunction = function (fn) {
	return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
};

var arePropertyDescriptorsSupported = function () {
	var obj = {};
	try {
		origDefineProperty(obj, 'x', { enumerable: false, value: obj });
		// eslint-disable-next-line no-unused-vars, no-restricted-syntax
		for (var _ in obj) { // jscs:ignore disallowUnusedVariables
			return false;
		}
		return obj.x === obj;
	} catch (e) { /* this is IE 8. */
		return false;
	}
};
var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported();

var defineProperty = function (object, name, value, predicate) {
	if (name in object && (!isFunction(predicate) || !predicate())) {
		return;
	}
	if (supportsDescriptors) {
		origDefineProperty(object, name, {
			configurable: true,
			enumerable: false,
			value: value,
			writable: true
		});
	} else {
		object[name] = value;
	}
};

var defineProperties = function (object, map) {
	var predicates = arguments.length > 2 ? arguments[2] : {};
	var props = keys(map);
	if (hasSymbols) {
		props = concat.call(props, Object.getOwnPropertySymbols(map));
	}
	for (var i = 0; i < props.length; i += 1) {
		defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
	}
};

defineProperties.supportsDescriptors = !!supportsDescriptors;

module.exports = defineProperties;


/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {

var origSymbol = global.Symbol;
var hasSymbolSham = __webpack_require__(57);

module.exports = function hasNativeSymbols() {
	if (typeof origSymbol !== 'function') { return false; }
	if (typeof Symbol !== 'function') { return false; }
	if (typeof origSymbol('foo') !== 'symbol') { return false; }
	if (typeof Symbol('bar') !== 'symbol') { return false; }

	return hasSymbolSham();
};

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(33)))

/***/ }),
/* 43 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var GetIntrinsic = __webpack_require__(30);

var callBind = __webpack_require__(56);

var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));

module.exports = function callBoundIntrinsic(name, allowMissing) {
	var intrinsic = GetIntrinsic(name, !!allowMissing);
	if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.')) {
		return callBind(intrinsic);
	}
	return intrinsic;
};


/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _interopRequireDefault = __webpack_require__(34);

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = createSvgIcon;

var _extends2 = _interopRequireDefault(__webpack_require__(121));

var _react = _interopRequireDefault(__webpack_require__(0));

var _SvgIcon = _interopRequireDefault(__webpack_require__(45));

function createSvgIcon(path, displayName) {
  var Component = _react.default.memo(_react.default.forwardRef(function (props, ref) {
    return _react.default.createElement(_SvgIcon.default, (0, _extends2.default)({
      ref: ref
    }, props), path);
  }));

  if (false) {}

  Component.muiName = _SvgIcon.default.muiName;
  return Component;
}

/***/ }),
/* 45 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _SvgIcon__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(63);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _SvgIcon__WEBPACK_IMPORTED_MODULE_0__["a"]; });



/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var isMergeableObject = function isMergeableObject(value) {
	return isNonNullObject(value)
		&& !isSpecial(value)
};

function isNonNullObject(value) {
	return !!value && typeof value === 'object'
}

function isSpecial(value) {
	var stringValue = Object.prototype.toString.call(value);

	return stringValue === '[object RegExp]'
		|| stringValue === '[object Date]'
		|| isReactElement(value)
}

// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;

function isReactElement(value) {
	return value.$$typeof === REACT_ELEMENT_TYPE
}

function emptyTarget(val) {
	return Array.isArray(val) ? [] : {}
}

function cloneUnlessOtherwiseSpecified(value, options) {
	return (options.clone !== false && options.isMergeableObject(value))
		? deepmerge(emptyTarget(value), value, options)
		: value
}

function defaultArrayMerge(target, source, options) {
	return target.concat(source).map(function(element) {
		return cloneUnlessOtherwiseSpecified(element, options)
	})
}

function getMergeFunction(key, options) {
	if (!options.customMerge) {
		return deepmerge
	}
	var customMerge = options.customMerge(key);
	return typeof customMerge === 'function' ? customMerge : deepmerge
}

function getEnumerableOwnPropertySymbols(target) {
	return Object.getOwnPropertySymbols
		? Object.getOwnPropertySymbols(target).filter(function(symbol) {
			return target.propertyIsEnumerable(symbol)
		})
		: []
}

function getKeys(target) {
	return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target))
}

function propertyIsOnObject(object, property) {
	try {
		return property in object
	} catch(_) {
		return false
	}
}

// Protects from prototype poisoning and unexpected merging up the prototype chain.
function propertyIsUnsafe(target, key) {
	return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,
		&& !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,
			&& Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.
}

function mergeObject(target, source, options) {
	var destination = {};
	if (options.isMergeableObject(target)) {
		getKeys(target).forEach(function(key) {
			destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
		});
	}
	getKeys(source).forEach(function(key) {
		if (propertyIsUnsafe(target, key)) {
			return
		}

		if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
			destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
		} else {
			destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
		}
	});
	return destination
}

function deepmerge(target, source, options) {
	options = options || {};
	options.arrayMerge = options.arrayMerge || defaultArrayMerge;
	options.isMergeableObject = options.isMergeableObject || isMergeableObject;
	// cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge()
	// implementations can use it. The caller may not replace it.
	options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;

	var sourceIsArray = Array.isArray(source);
	var targetIsArray = Array.isArray(target);
	var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;

	if (!sourceAndTargetTypesMatch) {
		return cloneUnlessOtherwiseSpecified(source, options)
	} else if (sourceIsArray) {
		return options.arrayMerge(target, source, options)
	} else {
		return mergeObject(target, source, options)
	}
}

deepmerge.all = function deepmergeAll(array, options) {
	if (!Array.isArray(array)) {
		throw new Error('first argument should be an array')
	}

	return array.reduce(function(prev, next) {
		return deepmerge(prev, next, options)
	}, {})
};

var deepmerge_1 = deepmerge;

module.exports = deepmerge_1;


/***/ }),
/* 47 */,
/* 48 */,
/* 49 */,
/* 50 */,
/* 51 */,
/* 52 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/


/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;

function toObject(val) {
	if (val === null || val === undefined) {
		throw new TypeError('Object.assign cannot be called with null or undefined');
	}

	return Object(val);
}

function shouldUseNative() {
	try {
		if (!Object.assign) {
			return false;
		}

		// Detect buggy property enumeration order in older V8 versions.

		// https://bugs.chromium.org/p/v8/issues/detail?id=4118
		var test1 = new String('abc');  // eslint-disable-line no-new-wrappers
		test1[5] = 'de';
		if (Object.getOwnPropertyNames(test1)[0] === '5') {
			return false;
		}

		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
		var test2 = {};
		for (var i = 0; i < 10; i++) {
			test2['_' + String.fromCharCode(i)] = i;
		}
		var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
			return test2[n];
		});
		if (order2.join('') !== '0123456789') {
			return false;
		}

		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
		var test3 = {};
		'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
			test3[letter] = letter;
		});
		if (Object.keys(Object.assign({}, test3)).join('') !==
				'abcdefghijklmnopqrst') {
			return false;
		}

		return true;
	} catch (err) {
		// We don't expect any of the above to throw, but better to be safe.
		return false;
	}
}

module.exports = shouldUseNative() ? Object.assign : function (target, source) {
	var from;
	var to = toObject(target);
	var symbols;

	for (var s = 1; s < arguments.length; s++) {
		from = Object(arguments[s]);

		for (var key in from) {
			if (hasOwnProperty.call(from, key)) {
				to[key] = from[key];
			}
		}

		if (getOwnPropertySymbols) {
			symbols = getOwnPropertySymbols(from);
			for (var i = 0; i < symbols.length; i++) {
				if (propIsEnumerable.call(from, symbols[i])) {
					to[symbols[i]] = from[symbols[i]];
				}
			}
		}
	}

	return to;
};


/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var slice = Array.prototype.slice;
var isArgs = __webpack_require__(54);

var origKeys = Object.keys;
var keysShim = origKeys ? function keys(o) { return origKeys(o); } : __webpack_require__(96);

var originalKeys = Object.keys;

keysShim.shim = function shimObjectKeys() {
	if (Object.keys) {
		var keysWorksWithArguments = (function () {
			// Safari 5.0 bug
			var args = Object.keys(arguments);
			return args && args.length === arguments.length;
		}(1, 2));
		if (!keysWorksWithArguments) {
			Object.keys = function keys(object) { // eslint-disable-line func-name-matching
				if (isArgs(object)) {
					return originalKeys(slice.call(object));
				}
				return originalKeys(object);
			};
		}
	} else {
		Object.keys = keysShim;
	}
	return Object.keys || keysShim;
};

module.exports = keysShim;


/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var toStr = Object.prototype.toString;

module.exports = function isArguments(value) {
	var str = toStr.call(value);
	var isArgs = str === '[object Arguments]';
	if (!isArgs) {
		isArgs = str !== '[object Array]' &&
			value !== null &&
			typeof value === 'object' &&
			typeof value.length === 'number' &&
			value.length >= 0 &&
			toStr.call(value.callee) === '[object Function]';
	}
	return isArgs;
};


/***/ }),
/* 55 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
var toStr = Object.prototype.toString;

var isStandardArguments = function isArguments(value) {
	if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) {
		return false;
	}
	return toStr.call(value) === '[object Arguments]';
};

var isLegacyArguments = function isArguments(value) {
	if (isStandardArguments(value)) {
		return true;
	}
	return value !== null &&
		typeof value === 'object' &&
		typeof value.length === 'number' &&
		value.length >= 0 &&
		toStr.call(value) !== '[object Array]' &&
		toStr.call(value.callee) === '[object Function]';
};

var supportsStandardArguments = (function () {
	return isStandardArguments(arguments);
}());

isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests

module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments;


/***/ }),
/* 56 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var bind = __webpack_require__(40);

var GetIntrinsic = __webpack_require__(30);

var $Function = GetIntrinsic('%Function%');
var $apply = $Function.apply;
var $call = $Function.call;

module.exports = function callBind() {
	return bind.apply($call, arguments);
};

module.exports.apply = function applyBind() {
	return bind.apply($apply, arguments);
};


/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
	if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
	if (typeof Symbol.iterator === 'symbol') { return true; }

	var obj = {};
	var sym = Symbol('test');
	var symObj = Object(sym);
	if (typeof sym === 'string') { return false; }

	if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
	if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }

	// temp disabled per https://github.com/ljharb/object.assign/issues/17
	// if (sym instanceof Symbol) { return false; }
	// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
	// if (!(symObj instanceof Symbol)) { return false; }

	// if (typeof Symbol.prototype.toString !== 'function') { return false; }
	// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }

	var symVal = 42;
	obj[sym] = symVal;
	for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax
	if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }

	if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }

	var syms = Object.getOwnPropertySymbols(obj);
	if (syms.length !== 1 || syms[0] !== sym) { return false; }

	if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }

	if (typeof Object.getOwnPropertyDescriptor === 'function') {
		var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
		if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
	}

	return true;
};


/***/ }),
/* 58 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var $Object = Object;
var $TypeError = TypeError;

module.exports = function flags() {
	if (this != null && this !== $Object(this)) {
		throw new $TypeError('RegExp.prototype.flags getter called on non-object');
	}
	var result = '';
	if (this.global) {
		result += 'g';
	}
	if (this.ignoreCase) {
		result += 'i';
	}
	if (this.multiline) {
		result += 'm';
	}
	if (this.dotAll) {
		result += 's';
	}
	if (this.unicode) {
		result += 'u';
	}
	if (this.sticky) {
		result += 'y';
	}
	return result;
};


/***/ }),
/* 59 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var implementation = __webpack_require__(58);

var supportsDescriptors = __webpack_require__(41).supportsDescriptors;
var $gOPD = Object.getOwnPropertyDescriptor;
var $TypeError = TypeError;

module.exports = function getPolyfill() {
	if (!supportsDescriptors) {
		throw new $TypeError('RegExp.prototype.flags requires a true ES5 environment that supports property descriptors');
	}
	if ((/a/mig).flags === 'gim') {
		var descriptor = $gOPD(RegExp.prototype, 'flags');
		if (descriptor && typeof descriptor.get === 'function' && typeof (/a/).dotAll === 'boolean') {
			return descriptor.get;
		}
	}
	return implementation;
};


/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var strValue = String.prototype.valueOf;
var tryStringObject = function tryStringObject(value) {
	try {
		strValue.call(value);
		return true;
	} catch (e) {
		return false;
	}
};
var toStr = Object.prototype.toString;
var strClass = '[object String]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';

module.exports = function isString(value) {
	if (typeof value === 'string') {
		return true;
	}
	if (typeof value !== 'object') {
		return false;
	}
	return hasToStringTag ? tryStringObject(value) : toStr.call(value) === strClass;
};


/***/ }),
/* 61 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var $Map = typeof Map === 'function' && Map.prototype ? Map : null;
var $Set = typeof Set === 'function' && Set.prototype ? Set : null;

var exported;

if (!$Map) {
	// eslint-disable-next-line no-unused-vars
	exported = function isMap(x) {
		// `Map` is not present in this environment.
		return false;
	};
}

var $mapHas = $Map ? Map.prototype.has : null;
var $setHas = $Set ? Set.prototype.has : null;
if (!exported && !$mapHas) {
	// eslint-disable-next-line no-unused-vars
	exported = function isMap(x) {
		// `Map` does not have a `has` method
		return false;
	};
}

module.exports = exported || function isMap(x) {
	if (!x || typeof x !== 'object') {
		return false;
	}
	try {
		$mapHas.call(x);
		if ($setHas) {
			try {
				$setHas.call(x);
			} catch (e) {
				return true;
			}
		}
		return x instanceof $Map; // core-js workaround, pre-v2.5.0
	} catch (e) {}
	return false;
};


/***/ }),
/* 62 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var $Map = typeof Map === 'function' && Map.prototype ? Map : null;
var $Set = typeof Set === 'function' && Set.prototype ? Set : null;

var exported;

if (!$Set) {
	// eslint-disable-next-line no-unused-vars
	exported = function isSet(x) {
		// `Set` is not present in this environment.
		return false;
	};
}

var $mapHas = $Map ? Map.prototype.has : null;
var $setHas = $Set ? Set.prototype.has : null;
if (!exported && !$setHas) {
	// eslint-disable-next-line no-unused-vars
	exported = function isSet(x) {
		// `Set` does not have a `has` method
		return false;
	};
}

module.exports = exported || function isSet(x) {
	if (!x || typeof x !== 'object') {
		return false;
	}
	try {
		$setHas.call(x);
		if ($mapHas) {
			try {
				$mapHas.call(x);
			} catch (e) {
				return true;
			}
		}
		return x instanceof $Set; // core-js workaround, pre-v2.5.0
	} catch (e) {}
	return false;
};


/***/ }),
/* 63 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export styles */
/* harmony import */ var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1);
/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var clsx__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(5);
/* harmony import */ var _styles_withStyles__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(6);
/* harmony import */ var _utils_capitalize__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7);







var styles = function styles(theme) {
  return {
    /* Styles applied to the root element. */
    root: {
      userSelect: 'none',
      width: '1em',
      height: '1em',
      display: 'inline-block',
      fill: 'currentColor',
      flexShrink: 0,
      fontSize: theme.typography.pxToRem(24),
      transition: theme.transitions.create('fill', {
        duration: theme.transitions.duration.shorter
      })
    },

    /* Styles applied to the root element if `color="primary"`. */
    colorPrimary: {
      color: theme.palette.primary.main
    },

    /* Styles applied to the root element if `color="secondary"`. */
    colorSecondary: {
      color: theme.palette.secondary.main
    },

    /* Styles applied to the root element if `color="action"`. */
    colorAction: {
      color: theme.palette.action.active
    },

    /* Styles applied to the root element if `color="error"`. */
    colorError: {
      color: theme.palette.error.main
    },

    /* Styles applied to the root element if `color="disabled"`. */
    colorDisabled: {
      color: theme.palette.action.disabled
    },

    /* Styles applied to the root element if `fontSize="inherit"`. */
    fontSizeInherit: {
      fontSize: 'inherit'
    },

    /* Styles applied to the root element if `fontSize="small"`. */
    fontSizeSmall: {
      fontSize: theme.typography.pxToRem(20)
    },

    /* Styles applied to the root element if `fontSize="large"`. */
    fontSizeLarge: {
      fontSize: theme.typography.pxToRem(35)
    }
  };
};
var SvgIcon = react__WEBPACK_IMPORTED_MODULE_2___default.a.forwardRef(function SvgIcon(props, ref) {
  var children = props.children,
      classes = props.classes,
      className = props.className,
      _props$color = props.color,
      color = _props$color === void 0 ? 'inherit' : _props$color,
      _props$component = props.component,
      Component = _props$component === void 0 ? 'svg' : _props$component,
      _props$fontSize = props.fontSize,
      fontSize = _props$fontSize === void 0 ? 'default' : _props$fontSize,
      htmlColor = props.htmlColor,
      titleAccess = props.titleAccess,
      _props$viewBox = props.viewBox,
      viewBox = _props$viewBox === void 0 ? '0 0 24 24' : _props$viewBox,
      other = Object(_babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"])(props, ["children", "classes", "className", "color", "component", "fontSize", "htmlColor", "titleAccess", "viewBox"]);

  return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(Component, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])({
    className: Object(clsx__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"])(classes.root, className, color !== 'inherit' && classes["color".concat(Object(_utils_capitalize__WEBPACK_IMPORTED_MODULE_6__[/* default */ "a"])(color))], fontSize !== 'default' && classes["fontSize".concat(Object(_utils_capitalize__WEBPACK_IMPORTED_MODULE_6__[/* default */ "a"])(fontSize))]),
    focusable: "false",
    viewBox: viewBox,
    color: htmlColor,
    "aria-hidden": titleAccess ? undefined : 'true',
    role: titleAccess ? 'img' : 'presentation',
    ref: ref
  }, other), children, titleAccess ? react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("title", null, titleAccess) : null);
});
 false ? undefined : void 0;
SvgIcon.muiName = 'SvgIcon';
/* harmony default export */ __webpack_exports__["a"] = (Object(_styles_withStyles__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"])(styles, {
  name: 'MuiSvgIcon'
})(SvgIcon));

/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_RESULT__;/*! Hammer.JS - v2.0.7 - 2016-04-22
 * http://hammerjs.github.io/
 *
 * Copyright (c) 2016 Jorik Tangelder;
 * Licensed under the MIT license */
(function(window, document, exportName, undefined) {
  'use strict';

var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];
var TEST_ELEMENT = document.createElement('div');

var TYPE_FUNCTION = 'function';

var round = Math.round;
var abs = Math.abs;
var now = Date.now;

/**
 * set a timeout with a given scope
 * @param {Function} fn
 * @param {Number} timeout
 * @param {Object} context
 * @returns {number}
 */
function setTimeoutContext(fn, timeout, context) {
    return setTimeout(bindFn(fn, context), timeout);
}

/**
 * if the argument is an array, we want to execute the fn on each entry
 * if it aint an array we don't want to do a thing.
 * this is used by all the methods that accept a single and array argument.
 * @param {*|Array} arg
 * @param {String} fn
 * @param {Object} [context]
 * @returns {Boolean}
 */
function invokeArrayArg(arg, fn, context) {
    if (Array.isArray(arg)) {
        each(arg, context[fn], context);
        return true;
    }
    return false;
}

/**
 * walk objects and arrays
 * @param {Object} obj
 * @param {Function} iterator
 * @param {Object} context
 */
function each(obj, iterator, context) {
    var i;

    if (!obj) {
        return;
    }

    if (obj.forEach) {
        obj.forEach(iterator, context);
    } else if (obj.length !== undefined) {
        i = 0;
        while (i < obj.length) {
            iterator.call(context, obj[i], i, obj);
            i++;
        }
    } else {
        for (i in obj) {
            obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
        }
    }
}

/**
 * wrap a method with a deprecation warning and stack trace
 * @param {Function} method
 * @param {String} name
 * @param {String} message
 * @returns {Function} A new function wrapping the supplied method.
 */
function deprecate(method, name, message) {
    var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \n';
    return function() {
        var e = new Error('get-stack-trace');
        var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '')
            .replace(/^\s+at\s+/gm, '')
            .replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace';

        var log = window.console && (window.console.warn || window.console.log);
        if (log) {
            log.call(window.console, deprecationMessage, stack);
        }
        return method.apply(this, arguments);
    };
}

/**
 * extend object.
 * means that properties in dest will be overwritten by the ones in src.
 * @param {Object} target
 * @param {...Object} objects_to_assign
 * @returns {Object} target
 */
var assign;
if (typeof Object.assign !== 'function') {
    assign = function assign(target) {
        if (target === undefined || target === null) {
            throw new TypeError('Cannot convert undefined or null to object');
        }

        var output = Object(target);
        for (var index = 1; index < arguments.length; index++) {
            var source = arguments[index];
            if (source !== undefined && source !== null) {
                for (var nextKey in source) {
                    if (source.hasOwnProperty(nextKey)) {
                        output[nextKey] = source[nextKey];
                    }
                }
            }
        }
        return output;
    };
} else {
    assign = Object.assign;
}

/**
 * extend object.
 * means that properties in dest will be overwritten by the ones in src.
 * @param {Object} dest
 * @param {Object} src
 * @param {Boolean} [merge=false]
 * @returns {Object} dest
 */
var extend = deprecate(function extend(dest, src, merge) {
    var keys = Object.keys(src);
    var i = 0;
    while (i < keys.length) {
        if (!merge || (merge && dest[keys[i]] === undefined)) {
            dest[keys[i]] = src[keys[i]];
        }
        i++;
    }
    return dest;
}, 'extend', 'Use `assign`.');

/**
 * merge the values from src in the dest.
 * means that properties that exist in dest will not be overwritten by src
 * @param {Object} dest
 * @param {Object} src
 * @returns {Object} dest
 */
var merge = deprecate(function merge(dest, src) {
    return extend(dest, src, true);
}, 'merge', 'Use `assign`.');

/**
 * simple class inheritance
 * @param {Function} child
 * @param {Function} base
 * @param {Object} [properties]
 */
function inherit(child, base, properties) {
    var baseP = base.prototype,
        childP;

    childP = child.prototype = Object.create(baseP);
    childP.constructor = child;
    childP._super = baseP;

    if (properties) {
        assign(childP, properties);
    }
}

/**
 * simple function bind
 * @param {Function} fn
 * @param {Object} context
 * @returns {Function}
 */
function bindFn(fn, context) {
    return function boundFn() {
        return fn.apply(context, arguments);
    };
}

/**
 * let a boolean value also be a function that must return a boolean
 * this first item in args will be used as the context
 * @param {Boolean|Function} val
 * @param {Array} [args]
 * @returns {Boolean}
 */
function boolOrFn(val, args) {
    if (typeof val == TYPE_FUNCTION) {
        return val.apply(args ? args[0] || undefined : undefined, args);
    }
    return val;
}

/**
 * use the val2 when val1 is undefined
 * @param {*} val1
 * @param {*} val2
 * @returns {*}
 */
function ifUndefined(val1, val2) {
    return (val1 === undefined) ? val2 : val1;
}

/**
 * addEventListener with multiple events at once
 * @param {EventTarget} target
 * @param {String} types
 * @param {Function} handler
 */
function addEventListeners(target, types, handler) {
    each(splitStr(types), function(type) {
        target.addEventListener(type, handler, false);
    });
}

/**
 * removeEventListener with multiple events at once
 * @param {EventTarget} target
 * @param {String} types
 * @param {Function} handler
 */
function removeEventListeners(target, types, handler) {
    each(splitStr(types), function(type) {
        target.removeEventListener(type, handler, false);
    });
}

/**
 * find if a node is in the given parent
 * @method hasParent
 * @param {HTMLElement} node
 * @param {HTMLElement} parent
 * @return {Boolean} found
 */
function hasParent(node, parent) {
    while (node) {
        if (node == parent) {
            return true;
        }
        node = node.parentNode;
    }
    return false;
}

/**
 * small indexOf wrapper
 * @param {String} str
 * @param {String} find
 * @returns {Boolean} found
 */
function inStr(str, find) {
    return str.indexOf(find) > -1;
}

/**
 * split string on whitespace
 * @param {String} str
 * @returns {Array} words
 */
function splitStr(str) {
    return str.trim().split(/\s+/g);
}

/**
 * find if a array contains the object using indexOf or a simple polyFill
 * @param {Array} src
 * @param {String} find
 * @param {String} [findByKey]
 * @return {Boolean|Number} false when not found, or the index
 */
function inArray(src, find, findByKey) {
    if (src.indexOf && !findByKey) {
        return src.indexOf(find);
    } else {
        var i = 0;
        while (i < src.length) {
            if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) {
                return i;
            }
            i++;
        }
        return -1;
    }
}

/**
 * convert array-like objects to real arrays
 * @param {Object} obj
 * @returns {Array}
 */
function toArray(obj) {
    return Array.prototype.slice.call(obj, 0);
}

/**
 * unique array with objects based on a key (like 'id') or just by the array's value
 * @param {Array} src [{id:1},{id:2},{id:1}]
 * @param {String} [key]
 * @param {Boolean} [sort=False]
 * @returns {Array} [{id:1},{id:2}]
 */
function uniqueArray(src, key, sort) {
    var results = [];
    var values = [];
    var i = 0;

    while (i < src.length) {
        var val = key ? src[i][key] : src[i];
        if (inArray(values, val) < 0) {
            results.push(src[i]);
        }
        values[i] = val;
        i++;
    }

    if (sort) {
        if (!key) {
            results = results.sort();
        } else {
            results = results.sort(function sortUniqueArray(a, b) {
                return a[key] > b[key];
            });
        }
    }

    return results;
}

/**
 * get the prefixed property
 * @param {Object} obj
 * @param {String} property
 * @returns {String|Undefined} prefixed
 */
function prefixed(obj, property) {
    var prefix, prop;
    var camelProp = property[0].toUpperCase() + property.slice(1);

    var i = 0;
    while (i < VENDOR_PREFIXES.length) {
        prefix = VENDOR_PREFIXES[i];
        prop = (prefix) ? prefix + camelProp : property;

        if (prop in obj) {
            return prop;
        }
        i++;
    }
    return undefined;
}

/**
 * get a unique id
 * @returns {number} uniqueId
 */
var _uniqueId = 1;
function uniqueId() {
    return _uniqueId++;
}

/**
 * get the window object of an element
 * @param {HTMLElement} element
 * @returns {DocumentView|Window}
 */
function getWindowForElement(element) {
    var doc = element.ownerDocument || element;
    return (doc.defaultView || doc.parentWindow || window);
}

var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;

var SUPPORT_TOUCH = ('ontouchstart' in window);
var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined;
var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);

var INPUT_TYPE_TOUCH = 'touch';
var INPUT_TYPE_PEN = 'pen';
var INPUT_TYPE_MOUSE = 'mouse';
var INPUT_TYPE_KINECT = 'kinect';

var COMPUTE_INTERVAL = 25;

var INPUT_START = 1;
var INPUT_MOVE = 2;
var INPUT_END = 4;
var INPUT_CANCEL = 8;

var DIRECTION_NONE = 1;
var DIRECTION_LEFT = 2;
var DIRECTION_RIGHT = 4;
var DIRECTION_UP = 8;
var DIRECTION_DOWN = 16;

var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;

var PROPS_XY = ['x', 'y'];
var PROPS_CLIENT_XY = ['clientX', 'clientY'];

/**
 * create new input type manager
 * @param {Manager} manager
 * @param {Function} callback
 * @returns {Input}
 * @constructor
 */
function Input(manager, callback) {
    var self = this;
    this.manager = manager;
    this.callback = callback;
    this.element = manager.element;
    this.target = manager.options.inputTarget;

    // smaller wrapper around the handler, for the scope and the enabled state of the manager,
    // so when disabled the input events are completely bypassed.
    this.domHandler = function(ev) {
        if (boolOrFn(manager.options.enable, [manager])) {
            self.handler(ev);
        }
    };

    this.init();

}

Input.prototype = {
    /**
     * should handle the inputEvent data and trigger the callback
     * @virtual
     */
    handler: function() { },

    /**
     * bind the events
     */
    init: function() {
        this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
        this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);
        this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
    },

    /**
     * unbind the events
     */
    destroy: function() {
        this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);
        this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);
        this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
    }
};

/**
 * create new input type manager
 * called by the Manager constructor
 * @param {Hammer} manager
 * @returns {Input}
 */
function createInputInstance(manager) {
    var Type;
    var inputClass = manager.options.inputClass;

    if (inputClass) {
        Type = inputClass;
    } else if (SUPPORT_POINTER_EVENTS) {
        Type = PointerEventInput;
    } else if (SUPPORT_ONLY_TOUCH) {
        Type = TouchInput;
    } else if (!SUPPORT_TOUCH) {
        Type = MouseInput;
    } else {
        Type = TouchMouseInput;
    }
    return new (Type)(manager, inputHandler);
}

/**
 * handle input events
 * @param {Manager} manager
 * @param {String} eventType
 * @param {Object} input
 */
function inputHandler(manager, eventType, input) {
    var pointersLen = input.pointers.length;
    var changedPointersLen = input.changedPointers.length;
    var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0));
    var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0));

    input.isFirst = !!isFirst;
    input.isFinal = !!isFinal;

    if (isFirst) {
        manager.session = {};
    }

    // source event is the normalized value of the domEvents
    // like 'touchstart, mouseup, pointerdown'
    input.eventType = eventType;

    // compute scale, rotation etc
    computeInputData(manager, input);

    // emit secret event
    manager.emit('hammer.input', input);

    manager.recognize(input);
    manager.session.prevInput = input;
}

/**
 * extend the data with some usable properties like scale, rotate, velocity etc
 * @param {Object} manager
 * @param {Object} input
 */
function computeInputData(manager, input) {
    var session = manager.session;
    var pointers = input.pointers;
    var pointersLength = pointers.length;

    // store the first input to calculate the distance and direction
    if (!session.firstInput) {
        session.firstInput = simpleCloneInputData(input);
    }

    // to compute scale and rotation we need to store the multiple touches
    if (pointersLength > 1 && !session.firstMultiple) {
        session.firstMultiple = simpleCloneInputData(input);
    } else if (pointersLength === 1) {
        session.firstMultiple = false;
    }

    var firstInput = session.firstInput;
    var firstMultiple = session.firstMultiple;
    var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;

    var center = input.center = getCenter(pointers);
    input.timeStamp = now();
    input.deltaTime = input.timeStamp - firstInput.timeStamp;

    input.angle = getAngle(offsetCenter, center);
    input.distance = getDistance(offsetCenter, center);

    computeDeltaXY(session, input);
    input.offsetDirection = getDirection(input.deltaX, input.deltaY);

    var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);
    input.overallVelocityX = overallVelocity.x;
    input.overallVelocityY = overallVelocity.y;
    input.overallVelocity = (abs(overallVelocity.x) > abs(overallVelocity.y)) ? overallVelocity.x : overallVelocity.y;

    input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
    input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;

    input.maxPointers = !session.prevInput ? input.pointers.length : ((input.pointers.length >
        session.prevInput.maxPointers) ? input.pointers.length : session.prevInput.maxPointers);

    computeIntervalInputData(session, input);

    // find the correct target
    var target = manager.element;
    if (hasParent(input.srcEvent.target, target)) {
        target = input.srcEvent.target;
    }
    input.target = target;
}

function computeDeltaXY(session, input) {
    var center = input.center;
    var offset = session.offsetDelta || {};
    var prevDelta = session.prevDelta || {};
    var prevInput = session.prevInput || {};

    if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {
        prevDelta = session.prevDelta = {
            x: prevInput.deltaX || 0,
            y: prevInput.deltaY || 0
        };

        offset = session.offsetDelta = {
            x: center.x,
            y: center.y
        };
    }

    input.deltaX = prevDelta.x + (center.x - offset.x);
    input.deltaY = prevDelta.y + (center.y - offset.y);
}

/**
 * velocity is calculated every x ms
 * @param {Object} session
 * @param {Object} input
 */
function computeIntervalInputData(session, input) {
    var last = session.lastInterval || input,
        deltaTime = input.timeStamp - last.timeStamp,
        velocity, velocityX, velocityY, direction;

    if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
        var deltaX = input.deltaX - last.deltaX;
        var deltaY = input.deltaY - last.deltaY;

        var v = getVelocity(deltaTime, deltaX, deltaY);
        velocityX = v.x;
        velocityY = v.y;
        velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y;
        direction = getDirection(deltaX, deltaY);

        session.lastInterval = input;
    } else {
        // use latest velocity info if it doesn't overtake a minimum period
        velocity = last.velocity;
        velocityX = last.velocityX;
        velocityY = last.velocityY;
        direction = last.direction;
    }

    input.velocity = velocity;
    input.velocityX = velocityX;
    input.velocityY = velocityY;
    input.direction = direction;
}

/**
 * create a simple clone from the input used for storage of firstInput and firstMultiple
 * @param {Object} input
 * @returns {Object} clonedInputData
 */
function simpleCloneInputData(input) {
    // make a simple copy of the pointers because we will get a reference if we don't
    // we only need clientXY for the calculations
    var pointers = [];
    var i = 0;
    while (i < input.pointers.length) {
        pointers[i] = {
            clientX: round(input.pointers[i].clientX),
            clientY: round(input.pointers[i].clientY)
        };
        i++;
    }

    return {
        timeStamp: now(),
        pointers: pointers,
        center: getCenter(pointers),
        deltaX: input.deltaX,
        deltaY: input.deltaY
    };
}

/**
 * get the center of all the pointers
 * @param {Array} pointers
 * @return {Object} center contains `x` and `y` properties
 */
function getCenter(pointers) {
    var pointersLength = pointers.length;

    // no need to loop when only one touch
    if (pointersLength === 1) {
        return {
            x: round(pointers[0].clientX),
            y: round(pointers[0].clientY)
        };
    }

    var x = 0, y = 0, i = 0;
    while (i < pointersLength) {
        x += pointers[i].clientX;
        y += pointers[i].clientY;
        i++;
    }

    return {
        x: round(x / pointersLength),
        y: round(y / pointersLength)
    };
}

/**
 * calculate the velocity between two points. unit is in px per ms.
 * @param {Number} deltaTime
 * @param {Number} x
 * @param {Number} y
 * @return {Object} velocity `x` and `y`
 */
function getVelocity(deltaTime, x, y) {
    return {
        x: x / deltaTime || 0,
        y: y / deltaTime || 0
    };
}

/**
 * get the direction between two points
 * @param {Number} x
 * @param {Number} y
 * @return {Number} direction
 */
function getDirection(x, y) {
    if (x === y) {
        return DIRECTION_NONE;
    }

    if (abs(x) >= abs(y)) {
        return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
    }
    return y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
}

/**
 * calculate the absolute distance between two points
 * @param {Object} p1 {x, y}
 * @param {Object} p2 {x, y}
 * @param {Array} [props] containing x and y keys
 * @return {Number} distance
 */
function getDistance(p1, p2, props) {
    if (!props) {
        props = PROPS_XY;
    }
    var x = p2[props[0]] - p1[props[0]],
        y = p2[props[1]] - p1[props[1]];

    return Math.sqrt((x * x) + (y * y));
}

/**
 * calculate the angle between two coordinates
 * @param {Object} p1
 * @param {Object} p2
 * @param {Array} [props] containing x and y keys
 * @return {Number} angle
 */
function getAngle(p1, p2, props) {
    if (!props) {
        props = PROPS_XY;
    }
    var x = p2[props[0]] - p1[props[0]],
        y = p2[props[1]] - p1[props[1]];
    return Math.atan2(y, x) * 180 / Math.PI;
}

/**
 * calculate the rotation degrees between two pointersets
 * @param {Array} start array of pointers
 * @param {Array} end array of pointers
 * @return {Number} rotation
 */
function getRotation(start, end) {
    return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY);
}

/**
 * calculate the scale factor between two pointersets
 * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
 * @param {Array} start array of pointers
 * @param {Array} end array of pointers
 * @return {Number} scale
 */
function getScale(start, end) {
    return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
}

var MOUSE_INPUT_MAP = {
    mousedown: INPUT_START,
    mousemove: INPUT_MOVE,
    mouseup: INPUT_END
};

var MOUSE_ELEMENT_EVENTS = 'mousedown';
var MOUSE_WINDOW_EVENTS = 'mousemove mouseup';

/**
 * Mouse events input
 * @constructor
 * @extends Input
 */
function MouseInput() {
    this.evEl = MOUSE_ELEMENT_EVENTS;
    this.evWin = MOUSE_WINDOW_EVENTS;

    this.pressed = false; // mousedown state

    Input.apply(this, arguments);
}

inherit(MouseInput, Input, {
    /**
     * handle mouse events
     * @param {Object} ev
     */
    handler: function MEhandler(ev) {
        var eventType = MOUSE_INPUT_MAP[ev.type];

        // on start we want to have the left mouse button down
        if (eventType & INPUT_START && ev.button === 0) {
            this.pressed = true;
        }

        if (eventType & INPUT_MOVE && ev.which !== 1) {
            eventType = INPUT_END;
        }

        // mouse must be down
        if (!this.pressed) {
            return;
        }

        if (eventType & INPUT_END) {
            this.pressed = false;
        }

        this.callback(this.manager, eventType, {
            pointers: [ev],
            changedPointers: [ev],
            pointerType: INPUT_TYPE_MOUSE,
            srcEvent: ev
        });
    }
});

var POINTER_INPUT_MAP = {
    pointerdown: INPUT_START,
    pointermove: INPUT_MOVE,
    pointerup: INPUT_END,
    pointercancel: INPUT_CANCEL,
    pointerout: INPUT_CANCEL
};

// in IE10 the pointer types is defined as an enum
var IE10_POINTER_TYPE_ENUM = {
    2: INPUT_TYPE_TOUCH,
    3: INPUT_TYPE_PEN,
    4: INPUT_TYPE_MOUSE,
    5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816
};

var POINTER_ELEMENT_EVENTS = 'pointerdown';
var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel';

// IE10 has prefixed support, and case-sensitive
if (window.MSPointerEvent && !window.PointerEvent) {
    POINTER_ELEMENT_EVENTS = 'MSPointerDown';
    POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel';
}

/**
 * Pointer events input
 * @constructor
 * @extends Input
 */
function PointerEventInput() {
    this.evEl = POINTER_ELEMENT_EVENTS;
    this.evWin = POINTER_WINDOW_EVENTS;

    Input.apply(this, arguments);

    this.store = (this.manager.session.pointerEvents = []);
}

inherit(PointerEventInput, Input, {
    /**
     * handle mouse events
     * @param {Object} ev
     */
    handler: function PEhandler(ev) {
        var store = this.store;
        var removePointer = false;

        var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
        var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
        var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;

        var isTouch = (pointerType == INPUT_TYPE_TOUCH);

        // get index of the event in the store
        var storeIndex = inArray(store, ev.pointerId, 'pointerId');

        // start and mouse must be down
        if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
            if (storeIndex < 0) {
                store.push(ev);
                storeIndex = store.length - 1;
            }
        } else if (eventType & (INPUT_END | INPUT_CANCEL)) {
            removePointer = true;
        }

        // it not found, so the pointer hasn't been down (so it's probably a hover)
        if (storeIndex < 0) {
            return;
        }

        // update the event in the store
        store[storeIndex] = ev;

        this.callback(this.manager, eventType, {
            pointers: store,
            changedPointers: [ev],
            pointerType: pointerType,
            srcEvent: ev
        });

        if (removePointer) {
            // remove from the store
            store.splice(storeIndex, 1);
        }
    }
});

var SINGLE_TOUCH_INPUT_MAP = {
    touchstart: INPUT_START,
    touchmove: INPUT_MOVE,
    touchend: INPUT_END,
    touchcancel: INPUT_CANCEL
};

var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart';
var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel';

/**
 * Touch events input
 * @constructor
 * @extends Input
 */
function SingleTouchInput() {
    this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
    this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
    this.started = false;

    Input.apply(this, arguments);
}

inherit(SingleTouchInput, Input, {
    handler: function TEhandler(ev) {
        var type = SINGLE_TOUCH_INPUT_MAP[ev.type];

        // should we handle the touch events?
        if (type === INPUT_START) {
            this.started = true;
        }

        if (!this.started) {
            return;
        }

        var touches = normalizeSingleTouches.call(this, ev, type);

        // when done, reset the started state
        if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) {
            this.started = false;
        }

        this.callback(this.manager, type, {
            pointers: touches[0],
            changedPointers: touches[1],
            pointerType: INPUT_TYPE_TOUCH,
            srcEvent: ev
        });
    }
});

/**
 * @this {TouchInput}
 * @param {Object} ev
 * @param {Number} type flag
 * @returns {undefined|Array} [all, changed]
 */
function normalizeSingleTouches(ev, type) {
    var all = toArray(ev.touches);
    var changed = toArray(ev.changedTouches);

    if (type & (INPUT_END | INPUT_CANCEL)) {
        all = uniqueArray(all.concat(changed), 'identifier', true);
    }

    return [all, changed];
}

var TOUCH_INPUT_MAP = {
    touchstart: INPUT_START,
    touchmove: INPUT_MOVE,
    touchend: INPUT_END,
    touchcancel: INPUT_CANCEL
};

var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';

/**
 * Multi-user touch events input
 * @constructor
 * @extends Input
 */
function TouchInput() {
    this.evTarget = TOUCH_TARGET_EVENTS;
    this.targetIds = {};

    Input.apply(this, arguments);
}

inherit(TouchInput, Input, {
    handler: function MTEhandler(ev) {
        var type = TOUCH_INPUT_MAP[ev.type];
        var touches = getTouches.call(this, ev, type);
        if (!touches) {
            return;
        }

        this.callback(this.manager, type, {
            pointers: touches[0],
            changedPointers: touches[1],
            pointerType: INPUT_TYPE_TOUCH,
            srcEvent: ev
        });
    }
});

/**
 * @this {TouchInput}
 * @param {Object} ev
 * @param {Number} type flag
 * @returns {undefined|Array} [all, changed]
 */
function getTouches(ev, type) {
    var allTouches = toArray(ev.touches);
    var targetIds = this.targetIds;

    // when there is only one touch, the process can be simplified
    if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
        targetIds[allTouches[0].identifier] = true;
        return [allTouches, allTouches];
    }

    var i,
        targetTouches,
        changedTouches = toArray(ev.changedTouches),
        changedTargetTouches = [],
        target = this.target;

    // get target touches from touches
    targetTouches = allTouches.filter(function(touch) {
        return hasParent(touch.target, target);
    });

    // collect touches
    if (type === INPUT_START) {
        i = 0;
        while (i < targetTouches.length) {
            targetIds[targetTouches[i].identifier] = true;
            i++;
        }
    }

    // filter changed touches to only contain touches that exist in the collected target ids
    i = 0;
    while (i < changedTouches.length) {
        if (targetIds[changedTouches[i].identifier]) {
            changedTargetTouches.push(changedTouches[i]);
        }

        // cleanup removed touches
        if (type & (INPUT_END | INPUT_CANCEL)) {
            delete targetIds[changedTouches[i].identifier];
        }
        i++;
    }

    if (!changedTargetTouches.length) {
        return;
    }

    return [
        // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
        uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true),
        changedTargetTouches
    ];
}

/**
 * Combined touch and mouse input
 *
 * Touch has a higher priority then mouse, and while touching no mouse events are allowed.
 * This because touch devices also emit mouse events while doing a touch.
 *
 * @constructor
 * @extends Input
 */

var DEDUP_TIMEOUT = 2500;
var DEDUP_DISTANCE = 25;

function TouchMouseInput() {
    Input.apply(this, arguments);

    var handler = bindFn(this.handler, this);
    this.touch = new TouchInput(this.manager, handler);
    this.mouse = new MouseInput(this.manager, handler);

    this.primaryTouch = null;
    this.lastTouches = [];
}

inherit(TouchMouseInput, Input, {
    /**
     * handle mouse and touch events
     * @param {Hammer} manager
     * @param {String} inputEvent
     * @param {Object} inputData
     */
    handler: function TMEhandler(manager, inputEvent, inputData) {
        var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH),
            isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE);

        if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) {
            return;
        }

        // when we're in a touch event, record touches to  de-dupe synthetic mouse event
        if (isTouch) {
            recordTouches.call(this, inputEvent, inputData);
        } else if (isMouse && isSyntheticEvent.call(this, inputData)) {
            return;
        }

        this.callback(manager, inputEvent, inputData);
    },

    /**
     * remove the event listeners
     */
    destroy: function destroy() {
        this.touch.destroy();
        this.mouse.destroy();
    }
});

function recordTouches(eventType, eventData) {
    if (eventType & INPUT_START) {
        this.primaryTouch = eventData.changedPointers[0].identifier;
        setLastTouch.call(this, eventData);
    } else if (eventType & (INPUT_END | INPUT_CANCEL)) {
        setLastTouch.call(this, eventData);
    }
}

function setLastTouch(eventData) {
    var touch = eventData.changedPointers[0];

    if (touch.identifier === this.primaryTouch) {
        var lastTouch = {x: touch.clientX, y: touch.clientY};
        this.lastTouches.push(lastTouch);
        var lts = this.lastTouches;
        var removeLastTouch = function() {
            var i = lts.indexOf(lastTouch);
            if (i > -1) {
                lts.splice(i, 1);
            }
        };
        setTimeout(removeLastTouch, DEDUP_TIMEOUT);
    }
}

function isSyntheticEvent(eventData) {
    var x = eventData.srcEvent.clientX, y = eventData.srcEvent.clientY;
    for (var i = 0; i < this.lastTouches.length; i++) {
        var t = this.lastTouches[i];
        var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y);
        if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) {
            return true;
        }
    }
    return false;
}

var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction');
var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;

// magical touchAction value
var TOUCH_ACTION_COMPUTE = 'compute';
var TOUCH_ACTION_AUTO = 'auto';
var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented
var TOUCH_ACTION_NONE = 'none';
var TOUCH_ACTION_PAN_X = 'pan-x';
var TOUCH_ACTION_PAN_Y = 'pan-y';
var TOUCH_ACTION_MAP = getTouchActionProps();

/**
 * Touch Action
 * sets the touchAction property or uses the js alternative
 * @param {Manager} manager
 * @param {String} value
 * @constructor
 */
function TouchAction(manager, value) {
    this.manager = manager;
    this.set(value);
}

TouchAction.prototype = {
    /**
     * set the touchAction value on the element or enable the polyfill
     * @param {String} value
     */
    set: function(value) {
        // find out the touch-action by the event handlers
        if (value == TOUCH_ACTION_COMPUTE) {
            value = this.compute();
        }

        if (NATIVE_TOUCH_ACTION && this.manager.element.style && TOUCH_ACTION_MAP[value]) {
            this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
        }
        this.actions = value.toLowerCase().trim();
    },

    /**
     * just re-set the touchAction value
     */
    update: function() {
        this.set(this.manager.options.touchAction);
    },

    /**
     * compute the value for the touchAction property based on the recognizer's settings
     * @returns {String} value
     */
    compute: function() {
        var actions = [];
        each(this.manager.recognizers, function(recognizer) {
            if (boolOrFn(recognizer.options.enable, [recognizer])) {
                actions = actions.concat(recognizer.getTouchAction());
            }
        });
        return cleanTouchActions(actions.join(' '));
    },

    /**
     * this method is called on each input cycle and provides the preventing of the browser behavior
     * @param {Object} input
     */
    preventDefaults: function(input) {
        var srcEvent = input.srcEvent;
        var direction = input.offsetDirection;

        // if the touch action did prevented once this session
        if (this.manager.session.prevented) {
            srcEvent.preventDefault();
            return;
        }

        var actions = this.actions;
        var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE];
        var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y];
        var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X];

        if (hasNone) {
            //do not prevent defaults if this is a tap gesture

            var isTapPointer = input.pointers.length === 1;
            var isTapMovement = input.distance < 2;
            var isTapTouchTime = input.deltaTime < 250;

            if (isTapPointer && isTapMovement && isTapTouchTime) {
                return;
            }
        }

        if (hasPanX && hasPanY) {
            // `pan-x pan-y` means browser handles all scrolling/panning, do not prevent
            return;
        }

        if (hasNone ||
            (hasPanY && direction & DIRECTION_HORIZONTAL) ||
            (hasPanX && direction & DIRECTION_VERTICAL)) {
            return this.preventSrc(srcEvent);
        }
    },

    /**
     * call preventDefault to prevent the browser's default behavior (scrolling in most cases)
     * @param {Object} srcEvent
     */
    preventSrc: function(srcEvent) {
        this.manager.session.prevented = true;
        srcEvent.preventDefault();
    }
};

/**
 * when the touchActions are collected they are not a valid value, so we need to clean things up. *
 * @param {String} actions
 * @returns {*}
 */
function cleanTouchActions(actions) {
    // none
    if (inStr(actions, TOUCH_ACTION_NONE)) {
        return TOUCH_ACTION_NONE;
    }

    var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
    var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);

    // if both pan-x and pan-y are set (different recognizers
    // for different directions, e.g. horizontal pan but vertical swipe?)
    // we need none (as otherwise with pan-x pan-y combined none of these
    // recognizers will work, since the browser would handle all panning
    if (hasPanX && hasPanY) {
        return TOUCH_ACTION_NONE;
    }

    // pan-x OR pan-y
    if (hasPanX || hasPanY) {
        return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
    }

    // manipulation
    if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
        return TOUCH_ACTION_MANIPULATION;
    }

    return TOUCH_ACTION_AUTO;
}

function getTouchActionProps() {
    if (!NATIVE_TOUCH_ACTION) {
        return false;
    }
    var touchMap = {};
    var cssSupports = window.CSS && window.CSS.supports;
    ['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(function(val) {

        // If css.supports is not supported but there is native touch-action assume it supports
        // all values. This is the case for IE 10 and 11.
        touchMap[val] = cssSupports ? window.CSS.supports('touch-action', val) : true;
    });
    return touchMap;
}

/**
 * Recognizer flow explained; *
 * All recognizers have the initial state of POSSIBLE when a input session starts.
 * The definition of a input session is from the first input until the last input, with all it's movement in it. *
 * Example session for mouse-input: mousedown -> mousemove -> mouseup
 *
 * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
 * which determines with state it should be.
 *
 * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
 * POSSIBLE to give it another change on the next cycle.
 *
 *               Possible
 *                  |
 *            +-----+---------------+
 *            |                     |
 *      +-----+-----+               |
 *      |           |               |
 *   Failed      Cancelled          |
 *                          +-------+------+
 *                          |              |
 *                      Recognized       Began
 *                                         |
 *                                      Changed
 *                                         |
 *                                  Ended/Recognized
 */
var STATE_POSSIBLE = 1;
var STATE_BEGAN = 2;
var STATE_CHANGED = 4;
var STATE_ENDED = 8;
var STATE_RECOGNIZED = STATE_ENDED;
var STATE_CANCELLED = 16;
var STATE_FAILED = 32;

/**
 * Recognizer
 * Every recognizer needs to extend from this class.
 * @constructor
 * @param {Object} options
 */
function Recognizer(options) {
    this.options = assign({}, this.defaults, options || {});

    this.id = uniqueId();

    this.manager = null;

    // default is enable true
    this.options.enable = ifUndefined(this.options.enable, true);

    this.state = STATE_POSSIBLE;

    this.simultaneous = {};
    this.requireFail = [];
}

Recognizer.prototype = {
    /**
     * @virtual
     * @type {Object}
     */
    defaults: {},

    /**
     * set options
     * @param {Object} options
     * @return {Recognizer}
     */
    set: function(options) {
        assign(this.options, options);

        // also update the touchAction, in case something changed about the directions/enabled state
        this.manager && this.manager.touchAction.update();
        return this;
    },

    /**
     * recognize simultaneous with an other recognizer.
     * @param {Recognizer} otherRecognizer
     * @returns {Recognizer} this
     */
    recognizeWith: function(otherRecognizer) {
        if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
            return this;
        }

        var simultaneous = this.simultaneous;
        otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
        if (!simultaneous[otherRecognizer.id]) {
            simultaneous[otherRecognizer.id] = otherRecognizer;
            otherRecognizer.recognizeWith(this);
        }
        return this;
    },

    /**
     * drop the simultaneous link. it doesnt remove the link on the other recognizer.
     * @param {Recognizer} otherRecognizer
     * @returns {Recognizer} this
     */
    dropRecognizeWith: function(otherRecognizer) {
        if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {
            return this;
        }

        otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
        delete this.simultaneous[otherRecognizer.id];
        return this;
    },

    /**
     * recognizer can only run when an other is failing
     * @param {Recognizer} otherRecognizer
     * @returns {Recognizer} this
     */
    requireFailure: function(otherRecognizer) {
        if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {
            return this;
        }

        var requireFail = this.requireFail;
        otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
        if (inArray(requireFail, otherRecognizer) === -1) {
            requireFail.push(otherRecognizer);
            otherRecognizer.requireFailure(this);
        }
        return this;
    },

    /**
     * drop the requireFailure link. it does not remove the link on the other recognizer.
     * @param {Recognizer} otherRecognizer
     * @returns {Recognizer} this
     */
    dropRequireFailure: function(otherRecognizer) {
        if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {
            return this;
        }

        otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
        var index = inArray(this.requireFail, otherRecognizer);
        if (index > -1) {
            this.requireFail.splice(index, 1);
        }
        return this;
    },

    /**
     * has require failures boolean
     * @returns {boolean}
     */
    hasRequireFailures: function() {
        return this.requireFail.length > 0;
    },

    /**
     * if the recognizer can recognize simultaneous with an other recognizer
     * @param {Recognizer} otherRecognizer
     * @returns {Boolean}
     */
    canRecognizeWith: function(otherRecognizer) {
        return !!this.simultaneous[otherRecognizer.id];
    },

    /**
     * You should use `tryEmit` instead of `emit` directly to check
     * that all the needed recognizers has failed before emitting.
     * @param {Object} input
     */
    emit: function(input) {
        var self = this;
        var state = this.state;

        function emit(event) {
            self.manager.emit(event, input);
        }

        // 'panstart' and 'panmove'
        if (state < STATE_ENDED) {
            emit(self.options.event + stateStr(state));
        }

        emit(self.options.event); // simple 'eventName' events

        if (input.additionalEvent) { // additional event(panleft, panright, pinchin, pinchout...)
            emit(input.additionalEvent);
        }

        // panend and pancancel
        if (state >= STATE_ENDED) {
            emit(self.options.event + stateStr(state));
        }
    },

    /**
     * Check that all the require failure recognizers has failed,
     * if true, it emits a gesture event,
     * otherwise, setup the state to FAILED.
     * @param {Object} input
     */
    tryEmit: function(input) {
        if (this.canEmit()) {
            return this.emit(input);
        }
        // it's failing anyway
        this.state = STATE_FAILED;
    },

    /**
     * can we emit?
     * @returns {boolean}
     */
    canEmit: function() {
        var i = 0;
        while (i < this.requireFail.length) {
            if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
                return false;
            }
            i++;
        }
        return true;
    },

    /**
     * update the recognizer
     * @param {Object} inputData
     */
    recognize: function(inputData) {
        // make a new copy of the inputData
        // so we can change the inputData without messing up the other recognizers
        var inputDataClone = assign({}, inputData);

        // is is enabled and allow recognizing?
        if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
            this.reset();
            this.state = STATE_FAILED;
            return;
        }

        // reset when we've reached the end
        if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
            this.state = STATE_POSSIBLE;
        }

        this.state = this.process(inputDataClone);

        // the recognizer has recognized a gesture
        // so trigger an event
        if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
            this.tryEmit(inputDataClone);
        }
    },

    /**
     * return the state of the recognizer
     * the actual recognizing happens in this method
     * @virtual
     * @param {Object} inputData
     * @returns {Const} STATE
     */
    process: function(inputData) { }, // jshint ignore:line

    /**
     * return the preferred touch-action
     * @virtual
     * @returns {Array}
     */
    getTouchAction: function() { },

    /**
     * called when the gesture isn't allowed to recognize
     * like when another is being recognized or it is disabled
     * @virtual
     */
    reset: function() { }
};

/**
 * get a usable string, used as event postfix
 * @param {Const} state
 * @returns {String} state
 */
function stateStr(state) {
    if (state & STATE_CANCELLED) {
        return 'cancel';
    } else if (state & STATE_ENDED) {
        return 'end';
    } else if (state & STATE_CHANGED) {
        return 'move';
    } else if (state & STATE_BEGAN) {
        return 'start';
    }
    return '';
}

/**
 * direction cons to string
 * @param {Const} direction
 * @returns {String}
 */
function directionStr(direction) {
    if (direction == DIRECTION_DOWN) {
        return 'down';
    } else if (direction == DIRECTION_UP) {
        return 'up';
    } else if (direction == DIRECTION_LEFT) {
        return 'left';
    } else if (direction == DIRECTION_RIGHT) {
        return 'right';
    }
    return '';
}

/**
 * get a recognizer by name if it is bound to a manager
 * @param {Recognizer|String} otherRecognizer
 * @param {Recognizer} recognizer
 * @returns {Recognizer}
 */
function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
    var manager = recognizer.manager;
    if (manager) {
        return manager.get(otherRecognizer);
    }
    return otherRecognizer;
}

/**
 * This recognizer is just used as a base for the simple attribute recognizers.
 * @constructor
 * @extends Recognizer
 */
function AttrRecognizer() {
    Recognizer.apply(this, arguments);
}

inherit(AttrRecognizer, Recognizer, {
    /**
     * @namespace
     * @memberof AttrRecognizer
     */
    defaults: {
        /**
         * @type {Number}
         * @default 1
         */
        pointers: 1
    },

    /**
     * Used to check if it the recognizer receives valid input, like input.distance > 10.
     * @memberof AttrRecognizer
     * @param {Object} input
     * @returns {Boolean} recognized
     */
    attrTest: function(input) {
        var optionPointers = this.options.pointers;
        return optionPointers === 0 || input.pointers.length === optionPointers;
    },

    /**
     * Process the input and return the state for the recognizer
     * @memberof AttrRecognizer
     * @param {Object} input
     * @returns {*} State
     */
    process: function(input) {
        var state = this.state;
        var eventType = input.eventType;

        var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
        var isValid = this.attrTest(input);

        // on cancel input and we've recognized before, return STATE_CANCELLED
        if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
            return state | STATE_CANCELLED;
        } else if (isRecognized || isValid) {
            if (eventType & INPUT_END) {
                return state | STATE_ENDED;
            } else if (!(state & STATE_BEGAN)) {
                return STATE_BEGAN;
            }
            return state | STATE_CHANGED;
        }
        return STATE_FAILED;
    }
});

/**
 * Pan
 * Recognized when the pointer is down and moved in the allowed direction.
 * @constructor
 * @extends AttrRecognizer
 */
function PanRecognizer() {
    AttrRecognizer.apply(this, arguments);

    this.pX = null;
    this.pY = null;
}

inherit(PanRecognizer, AttrRecognizer, {
    /**
     * @namespace
     * @memberof PanRecognizer
     */
    defaults: {
        event: 'pan',
        threshold: 10,
        pointers: 1,
        direction: DIRECTION_ALL
    },

    getTouchAction: function() {
        var direction = this.options.direction;
        var actions = [];
        if (direction & DIRECTION_HORIZONTAL) {
            actions.push(TOUCH_ACTION_PAN_Y);
        }
        if (direction & DIRECTION_VERTICAL) {
            actions.push(TOUCH_ACTION_PAN_X);
        }
        return actions;
    },

    directionTest: function(input) {
        var options = this.options;
        var hasMoved = true;
        var distance = input.distance;
        var direction = input.direction;
        var x = input.deltaX;
        var y = input.deltaY;

        // lock to axis?
        if (!(direction & options.direction)) {
            if (options.direction & DIRECTION_HORIZONTAL) {
                direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;
                hasMoved = x != this.pX;
                distance = Math.abs(input.deltaX);
            } else {
                direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN;
                hasMoved = y != this.pY;
                distance = Math.abs(input.deltaY);
            }
        }
        input.direction = direction;
        return hasMoved && distance > options.threshold && direction & options.direction;
    },

    attrTest: function(input) {
        return AttrRecognizer.prototype.attrTest.call(this, input) &&
            (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input)));
    },

    emit: function(input) {

        this.pX = input.deltaX;
        this.pY = input.deltaY;

        var direction = directionStr(input.direction);

        if (direction) {
            input.additionalEvent = this.options.event + direction;
        }
        this._super.emit.call(this, input);
    }
});

/**
 * Pinch
 * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
 * @constructor
 * @extends AttrRecognizer
 */
function PinchRecognizer() {
    AttrRecognizer.apply(this, arguments);
}

inherit(PinchRecognizer, AttrRecognizer, {
    /**
     * @namespace
     * @memberof PinchRecognizer
     */
    defaults: {
        event: 'pinch',
        threshold: 0,
        pointers: 2
    },

    getTouchAction: function() {
        return [TOUCH_ACTION_NONE];
    },

    attrTest: function(input) {
        return this._super.attrTest.call(this, input) &&
            (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);
    },

    emit: function(input) {
        if (input.scale !== 1) {
            var inOut = input.scale < 1 ? 'in' : 'out';
            input.additionalEvent = this.options.event + inOut;
        }
        this._super.emit.call(this, input);
    }
});

/**
 * Press
 * Recognized when the pointer is down for x ms without any movement.
 * @constructor
 * @extends Recognizer
 */
function PressRecognizer() {
    Recognizer.apply(this, arguments);

    this._timer = null;
    this._input = null;
}

inherit(PressRecognizer, Recognizer, {
    /**
     * @namespace
     * @memberof PressRecognizer
     */
    defaults: {
        event: 'press',
        pointers: 1,
        time: 251, // minimal time of the pointer to be pressed
        threshold: 9 // a minimal movement is ok, but keep it low
    },

    getTouchAction: function() {
        return [TOUCH_ACTION_AUTO];
    },

    process: function(input) {
        var options = this.options;
        var validPointers = input.pointers.length === options.pointers;
        var validMovement = input.distance < options.threshold;
        var validTime = input.deltaTime > options.time;

        this._input = input;

        // we only allow little movement
        // and we've reached an end event, so a tap is possible
        if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) {
            this.reset();
        } else if (input.eventType & INPUT_START) {
            this.reset();
            this._timer = setTimeoutContext(function() {
                this.state = STATE_RECOGNIZED;
                this.tryEmit();
            }, options.time, this);
        } else if (input.eventType & INPUT_END) {
            return STATE_RECOGNIZED;
        }
        return STATE_FAILED;
    },

    reset: function() {
        clearTimeout(this._timer);
    },

    emit: function(input) {
        if (this.state !== STATE_RECOGNIZED) {
            return;
        }

        if (input && (input.eventType & INPUT_END)) {
            this.manager.emit(this.options.event + 'up', input);
        } else {
            this._input.timeStamp = now();
            this.manager.emit(this.options.event, this._input);
        }
    }
});

/**
 * Rotate
 * Recognized when two or more pointer are moving in a circular motion.
 * @constructor
 * @extends AttrRecognizer
 */
function RotateRecognizer() {
    AttrRecognizer.apply(this, arguments);
}

inherit(RotateRecognizer, AttrRecognizer, {
    /**
     * @namespace
     * @memberof RotateRecognizer
     */
    defaults: {
        event: 'rotate',
        threshold: 0,
        pointers: 2
    },

    getTouchAction: function() {
        return [TOUCH_ACTION_NONE];
    },

    attrTest: function(input) {
        return this._super.attrTest.call(this, input) &&
            (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);
    }
});

/**
 * Swipe
 * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
 * @constructor
 * @extends AttrRecognizer
 */
function SwipeRecognizer() {
    AttrRecognizer.apply(this, arguments);
}

inherit(SwipeRecognizer, AttrRecognizer, {
    /**
     * @namespace
     * @memberof SwipeRecognizer
     */
    defaults: {
        event: 'swipe',
        threshold: 10,
        velocity: 0.3,
        direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
        pointers: 1
    },

    getTouchAction: function() {
        return PanRecognizer.prototype.getTouchAction.call(this);
    },

    attrTest: function(input) {
        var direction = this.options.direction;
        var velocity;

        if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
            velocity = input.overallVelocity;
        } else if (direction & DIRECTION_HORIZONTAL) {
            velocity = input.overallVelocityX;
        } else if (direction & DIRECTION_VERTICAL) {
            velocity = input.overallVelocityY;
        }

        return this._super.attrTest.call(this, input) &&
            direction & input.offsetDirection &&
            input.distance > this.options.threshold &&
            input.maxPointers == this.options.pointers &&
            abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
    },

    emit: function(input) {
        var direction = directionStr(input.offsetDirection);
        if (direction) {
            this.manager.emit(this.options.event + direction, input);
        }

        this.manager.emit(this.options.event, input);
    }
});

/**
 * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
 * between the given interval and position. The delay option can be used to recognize multi-taps without firing
 * a single tap.
 *
 * The eventData from the emitted event contains the property `tapCount`, which contains the amount of
 * multi-taps being recognized.
 * @constructor
 * @extends Recognizer
 */
function TapRecognizer() {
    Recognizer.apply(this, arguments);

    // previous time and center,
    // used for tap counting
    this.pTime = false;
    this.pCenter = false;

    this._timer = null;
    this._input = null;
    this.count = 0;
}

inherit(TapRecognizer, Recognizer, {
    /**
     * @namespace
     * @memberof PinchRecognizer
     */
    defaults: {
        event: 'tap',
        pointers: 1,
        taps: 1,
        interval: 300, // max time between the multi-tap taps
        time: 250, // max time of the pointer to be down (like finger on the screen)
        threshold: 9, // a minimal movement is ok, but keep it low
        posThreshold: 10 // a multi-tap can be a bit off the initial position
    },

    getTouchAction: function() {
        return [TOUCH_ACTION_MANIPULATION];
    },

    process: function(input) {
        var options = this.options;

        var validPointers = input.pointers.length === options.pointers;
        var validMovement = input.distance < options.threshold;
        var validTouchTime = input.deltaTime < options.time;

        this.reset();

        if ((input.eventType & INPUT_START) && (this.count === 0)) {
            return this.failTimeout();
        }

        // we only allow little movement
        // and we've reached an end event, so a tap is possible
        if (validMovement && validTouchTime && validPointers) {
            if (input.eventType != INPUT_END) {
                return this.failTimeout();
            }

            var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true;
            var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;

            this.pTime = input.timeStamp;
            this.pCenter = input.center;

            if (!validMultiTap || !validInterval) {
                this.count = 1;
            } else {
                this.count += 1;
            }

            this._input = input;

            // if tap count matches we have recognized it,
            // else it has began recognizing...
            var tapCount = this.count % options.taps;
            if (tapCount === 0) {
                // no failing requirements, immediately trigger the tap event
                // or wait as long as the multitap interval to trigger
                if (!this.hasRequireFailures()) {
                    return STATE_RECOGNIZED;
                } else {
                    this._timer = setTimeoutContext(function() {
                        this.state = STATE_RECOGNIZED;
                        this.tryEmit();
                    }, options.interval, this);
                    return STATE_BEGAN;
                }
            }
        }
        return STATE_FAILED;
    },

    failTimeout: function() {
        this._timer = setTimeoutContext(function() {
            this.state = STATE_FAILED;
        }, this.options.interval, this);
        return STATE_FAILED;
    },

    reset: function() {
        clearTimeout(this._timer);
    },

    emit: function() {
        if (this.state == STATE_RECOGNIZED) {
            this._input.tapCount = this.count;
            this.manager.emit(this.options.event, this._input);
        }
    }
});

/**
 * Simple way to create a manager with a default set of recognizers.
 * @param {HTMLElement} element
 * @param {Object} [options]
 * @constructor
 */
function Hammer(element, options) {
    options = options || {};
    options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);
    return new Manager(element, options);
}

/**
 * @const {string}
 */
Hammer.VERSION = '2.0.7';

/**
 * default settings
 * @namespace
 */
Hammer.defaults = {
    /**
     * set if DOM events are being triggered.
     * But this is slower and unused by simple implementations, so disabled by default.
     * @type {Boolean}
     * @default false
     */
    domEvents: false,

    /**
     * The value for the touchAction property/fallback.
     * When set to `compute` it will magically set the correct value based on the added recognizers.
     * @type {String}
     * @default compute
     */
    touchAction: TOUCH_ACTION_COMPUTE,

    /**
     * @type {Boolean}
     * @default true
     */
    enable: true,

    /**
     * EXPERIMENTAL FEATURE -- can be removed/changed
     * Change the parent input target element.
     * If Null, then it is being set the to main element.
     * @type {Null|EventTarget}
     * @default null
     */
    inputTarget: null,

    /**
     * force an input class
     * @type {Null|Function}
     * @default null
     */
    inputClass: null,

    /**
     * Default recognizer setup when calling `Hammer()`
     * When creating a new Manager these will be skipped.
     * @type {Array}
     */
    preset: [
        // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
        [RotateRecognizer, {enable: false}],
        [PinchRecognizer, {enable: false}, ['rotate']],
        [SwipeRecognizer, {direction: DIRECTION_HORIZONTAL}],
        [PanRecognizer, {direction: DIRECTION_HORIZONTAL}, ['swipe']],
        [TapRecognizer],
        [TapRecognizer, {event: 'doubletap', taps: 2}, ['tap']],
        [PressRecognizer]
    ],

    /**
     * Some CSS properties can be used to improve the working of Hammer.
     * Add them to this method and they will be set when creating a new Manager.
     * @namespace
     */
    cssProps: {
        /**
         * Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
         * @type {String}
         * @default 'none'
         */
        userSelect: 'none',

        /**
         * Disable the Windows Phone grippers when pressing an element.
         * @type {String}
         * @default 'none'
         */
        touchSelect: 'none',

        /**
         * Disables the default callout shown when you touch and hold a touch target.
         * On iOS, when you touch and hold a touch target such as a link, Safari displays
         * a callout containing information about the link. This property allows you to disable that callout.
         * @type {String}
         * @default 'none'
         */
        touchCallout: 'none',

        /**
         * Specifies whether zooming is enabled. Used by IE10>
         * @type {String}
         * @default 'none'
         */
        contentZooming: 'none',

        /**
         * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
         * @type {String}
         * @default 'none'
         */
        userDrag: 'none',

        /**
         * Overrides the highlight color shown when the user taps a link or a JavaScript
         * clickable element in iOS. This property obeys the alpha value, if specified.
         * @type {String}
         * @default 'rgba(0,0,0,0)'
         */
        tapHighlightColor: 'rgba(0,0,0,0)'
    }
};

var STOP = 1;
var FORCED_STOP = 2;

/**
 * Manager
 * @param {HTMLElement} element
 * @param {Object} [options]
 * @constructor
 */
function Manager(element, options) {
    this.options = assign({}, Hammer.defaults, options || {});

    this.options.inputTarget = this.options.inputTarget || element;

    this.handlers = {};
    this.session = {};
    this.recognizers = [];
    this.oldCssProps = {};

    this.element = element;
    this.input = createInputInstance(this);
    this.touchAction = new TouchAction(this, this.options.touchAction);

    toggleCssProps(this, true);

    each(this.options.recognizers, function(item) {
        var recognizer = this.add(new (item[0])(item[1]));
        item[2] && recognizer.recognizeWith(item[2]);
        item[3] && recognizer.requireFailure(item[3]);
    }, this);
}

Manager.prototype = {
    /**
     * set options
     * @param {Object} options
     * @returns {Manager}
     */
    set: function(options) {
        assign(this.options, options);

        // Options that need a little more setup
        if (options.touchAction) {
            this.touchAction.update();
        }
        if (options.inputTarget) {
            // Clean up existing event listeners and reinitialize
            this.input.destroy();
            this.input.target = options.inputTarget;
            this.input.init();
        }
        return this;
    },

    /**
     * stop recognizing for this session.
     * This session will be discarded, when a new [input]start event is fired.
     * When forced, the recognizer cycle is stopped immediately.
     * @param {Boolean} [force]
     */
    stop: function(force) {
        this.session.stopped = force ? FORCED_STOP : STOP;
    },

    /**
     * run the recognizers!
     * called by the inputHandler function on every movement of the pointers (touches)
     * it walks through all the recognizers and tries to detect the gesture that is being made
     * @param {Object} inputData
     */
    recognize: function(inputData) {
        var session = this.session;
        if (session.stopped) {
            return;
        }

        // run the touch-action polyfill
        this.touchAction.preventDefaults(inputData);

        var recognizer;
        var recognizers = this.recognizers;

        // this holds the recognizer that is being recognized.
        // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
        // if no recognizer is detecting a thing, it is set to `null`
        var curRecognizer = session.curRecognizer;

        // reset when the last recognizer is recognized
        // or when we're in a new session
        if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) {
            curRecognizer = session.curRecognizer = null;
        }

        var i = 0;
        while (i < recognizers.length) {
            recognizer = recognizers[i];

            // find out if we are allowed try to recognize the input for this one.
            // 1.   allow if the session is NOT forced stopped (see the .stop() method)
            // 2.   allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
            //      that is being recognized.
            // 3.   allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
            //      this can be setup with the `recognizeWith()` method on the recognizer.
            if (session.stopped !== FORCED_STOP && ( // 1
                    !curRecognizer || recognizer == curRecognizer || // 2
                    recognizer.canRecognizeWith(curRecognizer))) { // 3
                recognizer.recognize(inputData);
            } else {
                recognizer.reset();
            }

            // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
            // current active recognizer. but only if we don't already have an active recognizer
            if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
                curRecognizer = session.curRecognizer = recognizer;
            }
            i++;
        }
    },

    /**
     * get a recognizer by its event name.
     * @param {Recognizer|String} recognizer
     * @returns {Recognizer|Null}
     */
    get: function(recognizer) {
        if (recognizer instanceof Recognizer) {
            return recognizer;
        }

        var recognizers = this.recognizers;
        for (var i = 0; i < recognizers.length; i++) {
            if (recognizers[i].options.event == recognizer) {
                return recognizers[i];
            }
        }
        return null;
    },

    /**
     * add a recognizer to the manager
     * existing recognizers with the same event name will be removed
     * @param {Recognizer} recognizer
     * @returns {Recognizer|Manager}
     */
    add: function(recognizer) {
        if (invokeArrayArg(recognizer, 'add', this)) {
            return this;
        }

        // remove existing
        var existing = this.get(recognizer.options.event);
        if (existing) {
            this.remove(existing);
        }

        this.recognizers.push(recognizer);
        recognizer.manager = this;

        this.touchAction.update();
        return recognizer;
    },

    /**
     * remove a recognizer by name or instance
     * @param {Recognizer|String} recognizer
     * @returns {Manager}
     */
    remove: function(recognizer) {
        if (invokeArrayArg(recognizer, 'remove', this)) {
            return this;
        }

        recognizer = this.get(recognizer);

        // let's make sure this recognizer exists
        if (recognizer) {
            var recognizers = this.recognizers;
            var index = inArray(recognizers, recognizer);

            if (index !== -1) {
                recognizers.splice(index, 1);
                this.touchAction.update();
            }
        }

        return this;
    },

    /**
     * bind event
     * @param {String} events
     * @param {Function} handler
     * @returns {EventEmitter} this
     */
    on: function(events, handler) {
        if (events === undefined) {
            return;
        }
        if (handler === undefined) {
            return;
        }

        var handlers = this.handlers;
        each(splitStr(events), function(event) {
            handlers[event] = handlers[event] || [];
            handlers[event].push(handler);
        });
        return this;
    },

    /**
     * unbind event, leave emit blank to remove all handlers
     * @param {String} events
     * @param {Function} [handler]
     * @returns {EventEmitter} this
     */
    off: function(events, handler) {
        if (events === undefined) {
            return;
        }

        var handlers = this.handlers;
        each(splitStr(events), function(event) {
            if (!handler) {
                delete handlers[event];
            } else {
                handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1);
            }
        });
        return this;
    },

    /**
     * emit event to the listeners
     * @param {String} event
     * @param {Object} data
     */
    emit: function(event, data) {
        // we also want to trigger dom events
        if (this.options.domEvents) {
            triggerDomEvent(event, data);
        }

        // no handlers, so skip it all
        var handlers = this.handlers[event] && this.handlers[event].slice();
        if (!handlers || !handlers.length) {
            return;
        }

        data.type = event;
        data.preventDefault = function() {
            data.srcEvent.preventDefault();
        };

        var i = 0;
        while (i < handlers.length) {
            handlers[i](data);
            i++;
        }
    },

    /**
     * destroy the manager and unbinds all events
     * it doesn't unbind dom events, that is the user own responsibility
     */
    destroy: function() {
        this.element && toggleCssProps(this, false);

        this.handlers = {};
        this.session = {};
        this.input.destroy();
        this.element = null;
    }
};

/**
 * add/remove the css properties as defined in manager.options.cssProps
 * @param {Manager} manager
 * @param {Boolean} add
 */
function toggleCssProps(manager, add) {
    var element = manager.element;
    if (!element.style) {
        return;
    }
    var prop;
    each(manager.options.cssProps, function(value, name) {
        prop = prefixed(element.style, name);
        if (add) {
            manager.oldCssProps[prop] = element.style[prop];
            element.style[prop] = value;
        } else {
            element.style[prop] = manager.oldCssProps[prop] || '';
        }
    });
    if (!add) {
        manager.oldCssProps = {};
    }
}

/**
 * trigger dom event
 * @param {String} event
 * @param {Object} data
 */
function triggerDomEvent(event, data) {
    var gestureEvent = document.createEvent('Event');
    gestureEvent.initEvent(event, true, true);
    gestureEvent.gesture = data;
    data.target.dispatchEvent(gestureEvent);
}

assign(Hammer, {
    INPUT_START: INPUT_START,
    INPUT_MOVE: INPUT_MOVE,
    INPUT_END: INPUT_END,
    INPUT_CANCEL: INPUT_CANCEL,

    STATE_POSSIBLE: STATE_POSSIBLE,
    STATE_BEGAN: STATE_BEGAN,
    STATE_CHANGED: STATE_CHANGED,
    STATE_ENDED: STATE_ENDED,
    STATE_RECOGNIZED: STATE_RECOGNIZED,
    STATE_CANCELLED: STATE_CANCELLED,
    STATE_FAILED: STATE_FAILED,

    DIRECTION_NONE: DIRECTION_NONE,
    DIRECTION_LEFT: DIRECTION_LEFT,
    DIRECTION_RIGHT: DIRECTION_RIGHT,
    DIRECTION_UP: DIRECTION_UP,
    DIRECTION_DOWN: DIRECTION_DOWN,
    DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,
    DIRECTION_VERTICAL: DIRECTION_VERTICAL,
    DIRECTION_ALL: DIRECTION_ALL,

    Manager: Manager,
    Input: Input,
    TouchAction: TouchAction,

    TouchInput: TouchInput,
    MouseInput: MouseInput,
    PointerEventInput: PointerEventInput,
    TouchMouseInput: TouchMouseInput,
    SingleTouchInput: SingleTouchInput,

    Recognizer: Recognizer,
    AttrRecognizer: AttrRecognizer,
    Tap: TapRecognizer,
    Pan: PanRecognizer,
    Swipe: SwipeRecognizer,
    Pinch: PinchRecognizer,
    Rotate: RotateRecognizer,
    Press: PressRecognizer,

    on: addEventListeners,
    off: removeEventListeners,
    each: each,
    merge: merge,
    extend: extend,
    assign: assign,
    inherit: inherit,
    bindFn: bindFn,
    prefixed: prefixed
});

// this prevents errors when Hammer is loaded in the presence of an AMD
//  style loader but by script tag, not by the loader.
var freeGlobal = (typeof window !== 'undefined' ? window : (typeof self !== 'undefined' ? self : {})); // jshint ignore:line
freeGlobal.Hammer = Hammer;

if (true) {
    !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
        return Hammer;
    }).call(exports, __webpack_require__, exports, module),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}

})(window, document, 'Hammer');


/***/ }),
/* 65 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _iterableToArray; });
function _iterableToArray(iter) {
  if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}

/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var reactIs = __webpack_require__(23);

/**
 * Copyright 2015, Yahoo! Inc.
 * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
 */
var REACT_STATICS = {
  childContextTypes: true,
  contextType: true,
  contextTypes: true,
  defaultProps: true,
  displayName: true,
  getDefaultProps: true,
  getDerivedStateFromError: true,
  getDerivedStateFromProps: true,
  mixins: true,
  propTypes: true,
  type: true
};
var KNOWN_STATICS = {
  name: true,
  length: true,
  prototype: true,
  caller: true,
  callee: true,
  arguments: true,
  arity: true
};
var FORWARD_REF_STATICS = {
  '$$typeof': true,
  render: true,
  defaultProps: true,
  displayName: true,
  propTypes: true
};
var MEMO_STATICS = {
  '$$typeof': true,
  compare: true,
  defaultProps: true,
  displayName: true,
  propTypes: true,
  type: true
};
var TYPE_STATICS = {};
TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;
TYPE_STATICS[reactIs.Memo] = MEMO_STATICS;

function getStatics(component) {
  // React v16.11 and below
  if (reactIs.isMemo(component)) {
    return MEMO_STATICS;
  } // React v16.12 and above


  return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;
}

var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getPrototypeOf = Object.getPrototypeOf;
var objectPrototype = Object.prototype;
function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
  if (typeof sourceComponent !== 'string') {
    // don't hoist over string (html) components
    if (objectPrototype) {
      var inheritedComponent = getPrototypeOf(sourceComponent);

      if (inheritedComponent && inheritedComponent !== objectPrototype) {
        hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
      }
    }

    var keys = getOwnPropertyNames(sourceComponent);

    if (getOwnPropertySymbols) {
      keys = keys.concat(getOwnPropertySymbols(sourceComponent));
    }

    var targetStatics = getStatics(targetComponent);
    var sourceStatics = getStatics(sourceComponent);

    for (var i = 0; i < keys.length; ++i) {
      var key = keys[i];

      if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {
        var descriptor = getOwnPropertyDescriptor(sourceComponent, key);

        try {
          // Avoid failures from read-only properties
          defineProperty(targetComponent, key, descriptor);
        } catch (e) {}
      }
    }
  }

  return targetComponent;
}

module.exports = hoistNonReactStatics;


/***/ }),
/* 67 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _arrayWithHoles; });
function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}

/***/ }),
/* 68 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _nonIterableRest; });
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance");
}

/***/ }),
/* 69 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _typeof; });
function _typeof(obj) {
  "@babel/helpers - typeof";

  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof = function _typeof(obj) {
      return typeof obj;
    };
  } else {
    _typeof = function _typeof(obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
  }

  return _typeof(obj);
}

/***/ }),
/* 70 */
/***/ (function(module, exports) {

function _extends() {
  module.exports = _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);
}

module.exports = _extends;

/***/ }),
/* 71 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/**!
 * @fileOverview Kickass library to create and place poppers near their reference elements.
 * @version 1.16.1
 * @license
 * Copyright (c) 2016 Federico Zivolo and contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && typeof navigator !== 'undefined';

var timeoutDuration = function () {
  var longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox'];
  for (var i = 0; i < longerTimeoutBrowsers.length; i += 1) {
    if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) {
      return 1;
    }
  }
  return 0;
}();

function microtaskDebounce(fn) {
  var called = false;
  return function () {
    if (called) {
      return;
    }
    called = true;
    window.Promise.resolve().then(function () {
      called = false;
      fn();
    });
  };
}

function taskDebounce(fn) {
  var scheduled = false;
  return function () {
    if (!scheduled) {
      scheduled = true;
      setTimeout(function () {
        scheduled = false;
        fn();
      }, timeoutDuration);
    }
  };
}

var supportsMicroTasks = isBrowser && window.Promise;

/**
* Create a debounced version of a method, that's asynchronously deferred
* but called in the minimum time possible.
*
* @method
* @memberof Popper.Utils
* @argument {Function} fn
* @returns {Function}
*/
var debounce = supportsMicroTasks ? microtaskDebounce : taskDebounce;

/**
 * Check if the given variable is a function
 * @method
 * @memberof Popper.Utils
 * @argument {Any} functionToCheck - variable to check
 * @returns {Boolean} answer to: is a function?
 */
function isFunction(functionToCheck) {
  var getType = {};
  return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}

/**
 * Get CSS computed property of the given element
 * @method
 * @memberof Popper.Utils
 * @argument {Eement} element
 * @argument {String} property
 */
function getStyleComputedProperty(element, property) {
  if (element.nodeType !== 1) {
    return [];
  }
  // NOTE: 1 DOM access here
  var window = element.ownerDocument.defaultView;
  var css = window.getComputedStyle(element, null);
  return property ? css[property] : css;
}

/**
 * Returns the parentNode or the host of the element
 * @method
 * @memberof Popper.Utils
 * @argument {Element} element
 * @returns {Element} parent
 */
function getParentNode(element) {
  if (element.nodeName === 'HTML') {
    return element;
  }
  return element.parentNode || element.host;
}

/**
 * Returns the scrolling parent of the given element
 * @method
 * @memberof Popper.Utils
 * @argument {Element} element
 * @returns {Element} scroll parent
 */
function getScrollParent(element) {
  // Return body, `getScroll` will take care to get the correct `scrollTop` from it
  if (!element) {
    return document.body;
  }

  switch (element.nodeName) {
    case 'HTML':
    case 'BODY':
      return element.ownerDocument.body;
    case '#document':
      return element.body;
  }

  // Firefox want us to check `-x` and `-y` variations as well

  var _getStyleComputedProp = getStyleComputedProperty(element),
      overflow = _getStyleComputedProp.overflow,
      overflowX = _getStyleComputedProp.overflowX,
      overflowY = _getStyleComputedProp.overflowY;

  if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) {
    return element;
  }

  return getScrollParent(getParentNode(element));
}

/**
 * Returns the reference node of the reference object, or the reference object itself.
 * @method
 * @memberof Popper.Utils
 * @param {Element|Object} reference - the reference element (the popper will be relative to this)
 * @returns {Element} parent
 */
function getReferenceNode(reference) {
  return reference && reference.referenceNode ? reference.referenceNode : reference;
}

var isIE11 = isBrowser && !!(window.MSInputMethodContext && document.documentMode);
var isIE10 = isBrowser && /MSIE 10/.test(navigator.userAgent);

/**
 * Determines if the browser is Internet Explorer
 * @method
 * @memberof Popper.Utils
 * @param {Number} version to check
 * @returns {Boolean} isIE
 */
function isIE(version) {
  if (version === 11) {
    return isIE11;
  }
  if (version === 10) {
    return isIE10;
  }
  return isIE11 || isIE10;
}

/**
 * Returns the offset parent of the given element
 * @method
 * @memberof Popper.Utils
 * @argument {Element} element
 * @returns {Element} offset parent
 */
function getOffsetParent(element) {
  if (!element) {
    return document.documentElement;
  }

  var noOffsetParent = isIE(10) ? document.body : null;

  // NOTE: 1 DOM access here
  var offsetParent = element.offsetParent || null;
  // Skip hidden elements which don't have an offsetParent
  while (offsetParent === noOffsetParent && element.nextElementSibling) {
    offsetParent = (element = element.nextElementSibling).offsetParent;
  }

  var nodeName = offsetParent && offsetParent.nodeName;

  if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') {
    return element ? element.ownerDocument.documentElement : document.documentElement;
  }

  // .offsetParent will return the closest TH, TD or TABLE in case
  // no offsetParent is present, I hate this job...
  if (['TH', 'TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') {
    return getOffsetParent(offsetParent);
  }

  return offsetParent;
}

function isOffsetContainer(element) {
  var nodeName = element.nodeName;

  if (nodeName === 'BODY') {
    return false;
  }
  return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element;
}

/**
 * Finds the root node (document, shadowDOM root) of the given element
 * @method
 * @memberof Popper.Utils
 * @argument {Element} node
 * @returns {Element} root node
 */
function getRoot(node) {
  if (node.parentNode !== null) {
    return getRoot(node.parentNode);
  }

  return node;
}

/**
 * Finds the offset parent common to the two provided nodes
 * @method
 * @memberof Popper.Utils
 * @argument {Element} element1
 * @argument {Element} element2
 * @returns {Element} common offset parent
 */
function findCommonOffsetParent(element1, element2) {
  // This check is needed to avoid errors in case one of the elements isn't defined for any reason
  if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) {
    return document.documentElement;
  }

  // Here we make sure to give as "start" the element that comes first in the DOM
  var order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING;
  var start = order ? element1 : element2;
  var end = order ? element2 : element1;

  // Get common ancestor container
  var range = document.createRange();
  range.setStart(start, 0);
  range.setEnd(end, 0);
  var commonAncestorContainer = range.commonAncestorContainer;

  // Both nodes are inside #document

  if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) {
    if (isOffsetContainer(commonAncestorContainer)) {
      return commonAncestorContainer;
    }

    return getOffsetParent(commonAncestorContainer);
  }

  // one of the nodes is inside shadowDOM, find which one
  var element1root = getRoot(element1);
  if (element1root.host) {
    return findCommonOffsetParent(element1root.host, element2);
  } else {
    return findCommonOffsetParent(element1, getRoot(element2).host);
  }
}

/**
 * Gets the scroll value of the given element in the given side (top and left)
 * @method
 * @memberof Popper.Utils
 * @argument {Element} element
 * @argument {String} side `top` or `left`
 * @returns {number} amount of scrolled pixels
 */
function getScroll(element) {
  var side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'top';

  var upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft';
  var nodeName = element.nodeName;

  if (nodeName === 'BODY' || nodeName === 'HTML') {
    var html = element.ownerDocument.documentElement;
    var scrollingElement = element.ownerDocument.scrollingElement || html;
    return scrollingElement[upperSide];
  }

  return element[upperSide];
}

/*
 * Sum or subtract the element scroll values (left and top) from a given rect object
 * @method
 * @memberof Popper.Utils
 * @param {Object} rect - Rect object you want to change
 * @param {HTMLElement} element - The element from the function reads the scroll values
 * @param {Boolean} subtract - set to true if you want to subtract the scroll values
 * @return {Object} rect - The modifier rect object
 */
function includeScroll(rect, element) {
  var subtract = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

  var scrollTop = getScroll(element, 'top');
  var scrollLeft = getScroll(element, 'left');
  var modifier = subtract ? -1 : 1;
  rect.top += scrollTop * modifier;
  rect.bottom += scrollTop * modifier;
  rect.left += scrollLeft * modifier;
  rect.right += scrollLeft * modifier;
  return rect;
}

/*
 * Helper to detect borders of a given element
 * @method
 * @memberof Popper.Utils
 * @param {CSSStyleDeclaration} styles
 * Result of `getStyleComputedProperty` on the given element
 * @param {String} axis - `x` or `y`
 * @return {number} borders - The borders size of the given axis
 */

function getBordersSize(styles, axis) {
  var sideA = axis === 'x' ? 'Left' : 'Top';
  var sideB = sideA === 'Left' ? 'Right' : 'Bottom';

  return parseFloat(styles['border' + sideA + 'Width']) + parseFloat(styles['border' + sideB + 'Width']);
}

function getSize(axis, body, html, computedStyle) {
  return Math.max(body['offset' + axis], body['scroll' + axis], html['client' + axis], html['offset' + axis], html['scroll' + axis], isIE(10) ? parseInt(html['offset' + axis]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Top' : 'Left')]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Bottom' : 'Right')]) : 0);
}

function getWindowSizes(document) {
  var body = document.body;
  var html = document.documentElement;
  var computedStyle = isIE(10) && getComputedStyle(html);

  return {
    height: getSize('Height', body, html, computedStyle),
    width: getSize('Width', body, html, computedStyle)
  };
}

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 defineProperty = function (obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
};

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;
};

/**
 * Given element offsets, generate an output similar to getBoundingClientRect
 * @method
 * @memberof Popper.Utils
 * @argument {Object} offsets
 * @returns {Object} ClientRect like output
 */
function getClientRect(offsets) {
  return _extends({}, offsets, {
    right: offsets.left + offsets.width,
    bottom: offsets.top + offsets.height
  });
}

/**
 * Get bounding client rect of given element
 * @method
 * @memberof Popper.Utils
 * @param {HTMLElement} element
 * @return {Object} client rect
 */
function getBoundingClientRect(element) {
  var rect = {};

  // IE10 10 FIX: Please, don't ask, the element isn't
  // considered in DOM in some circumstances...
  // This isn't reproducible in IE10 compatibility mode of IE11
  try {
    if (isIE(10)) {
      rect = element.getBoundingClientRect();
      var scrollTop = getScroll(element, 'top');
      var scrollLeft = getScroll(element, 'left');
      rect.top += scrollTop;
      rect.left += scrollLeft;
      rect.bottom += scrollTop;
      rect.right += scrollLeft;
    } else {
      rect = element.getBoundingClientRect();
    }
  } catch (e) {}

  var result = {
    left: rect.left,
    top: rect.top,
    width: rect.right - rect.left,
    height: rect.bottom - rect.top
  };

  // subtract scrollbar size from sizes
  var sizes = element.nodeName === 'HTML' ? getWindowSizes(element.ownerDocument) : {};
  var width = sizes.width || element.clientWidth || result.width;
  var height = sizes.height || element.clientHeight || result.height;

  var horizScrollbar = element.offsetWidth - width;
  var vertScrollbar = element.offsetHeight - height;

  // if an hypothetical scrollbar is detected, we must be sure it's not a `border`
  // we make this check conditional for performance reasons
  if (horizScrollbar || vertScrollbar) {
    var styles = getStyleComputedProperty(element);
    horizScrollbar -= getBordersSize(styles, 'x');
    vertScrollbar -= getBordersSize(styles, 'y');

    result.width -= horizScrollbar;
    result.height -= vertScrollbar;
  }

  return getClientRect(result);
}

function getOffsetRectRelativeToArbitraryNode(children, parent) {
  var fixedPosition = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

  var isIE10 = isIE(10);
  var isHTML = parent.nodeName === 'HTML';
  var childrenRect = getBoundingClientRect(children);
  var parentRect = getBoundingClientRect(parent);
  var scrollParent = getScrollParent(children);

  var styles = getStyleComputedProperty(parent);
  var borderTopWidth = parseFloat(styles.borderTopWidth);
  var borderLeftWidth = parseFloat(styles.borderLeftWidth);

  // In cases where the parent is fixed, we must ignore negative scroll in offset calc
  if (fixedPosition && isHTML) {
    parentRect.top = Math.max(parentRect.top, 0);
    parentRect.left = Math.max(parentRect.left, 0);
  }
  var offsets = getClientRect({
    top: childrenRect.top - parentRect.top - borderTopWidth,
    left: childrenRect.left - parentRect.left - borderLeftWidth,
    width: childrenRect.width,
    height: childrenRect.height
  });
  offsets.marginTop = 0;
  offsets.marginLeft = 0;

  // Subtract margins of documentElement in case it's being used as parent
  // we do this only on HTML because it's the only element that behaves
  // differently when margins are applied to it. The margins are included in
  // the box of the documentElement, in the other cases not.
  if (!isIE10 && isHTML) {
    var marginTop = parseFloat(styles.marginTop);
    var marginLeft = parseFloat(styles.marginLeft);

    offsets.top -= borderTopWidth - marginTop;
    offsets.bottom -= borderTopWidth - marginTop;
    offsets.left -= borderLeftWidth - marginLeft;
    offsets.right -= borderLeftWidth - marginLeft;

    // Attach marginTop and marginLeft because in some circumstances we may need them
    offsets.marginTop = marginTop;
    offsets.marginLeft = marginLeft;
  }

  if (isIE10 && !fixedPosition ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') {
    offsets = includeScroll(offsets, parent);
  }

  return offsets;
}

function getViewportOffsetRectRelativeToArtbitraryNode(element) {
  var excludeScroll = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

  var html = element.ownerDocument.documentElement;
  var relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html);
  var width = Math.max(html.clientWidth, window.innerWidth || 0);
  var height = Math.max(html.clientHeight, window.innerHeight || 0);

  var scrollTop = !excludeScroll ? getScroll(html) : 0;
  var scrollLeft = !excludeScroll ? getScroll(html, 'left') : 0;

  var offset = {
    top: scrollTop - relativeOffset.top + relativeOffset.marginTop,
    left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft,
    width: width,
    height: height
  };

  return getClientRect(offset);
}

/**
 * Check if the given element is fixed or is inside a fixed parent
 * @method
 * @memberof Popper.Utils
 * @argument {Element} element
 * @argument {Element} customContainer
 * @returns {Boolean} answer to "isFixed?"
 */
function isFixed(element) {
  var nodeName = element.nodeName;
  if (nodeName === 'BODY' || nodeName === 'HTML') {
    return false;
  }
  if (getStyleComputedProperty(element, 'position') === 'fixed') {
    return true;
  }
  var parentNode = getParentNode(element);
  if (!parentNode) {
    return false;
  }
  return isFixed(parentNode);
}

/**
 * Finds the first parent of an element that has a transformed property defined
 * @method
 * @memberof Popper.Utils
 * @argument {Element} element
 * @returns {Element} first transformed parent or documentElement
 */

function getFixedPositionOffsetParent(element) {
  // This check is needed to avoid errors in case one of the elements isn't defined for any reason
  if (!element || !element.parentElement || isIE()) {
    return document.documentElement;
  }
  var el = element.parentElement;
  while (el && getStyleComputedProperty(el, 'transform') === 'none') {
    el = el.parentElement;
  }
  return el || document.documentElement;
}

/**
 * Computed the boundaries limits and return them
 * @method
 * @memberof Popper.Utils
 * @param {HTMLElement} popper
 * @param {HTMLElement} reference
 * @param {number} padding
 * @param {HTMLElement} boundariesElement - Element used to define the boundaries
 * @param {Boolean} fixedPosition - Is in fixed position mode
 * @returns {Object} Coordinates of the boundaries
 */
function getBoundaries(popper, reference, padding, boundariesElement) {
  var fixedPosition = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;

  // NOTE: 1 DOM access here

  var boundaries = { top: 0, left: 0 };
  var offsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, getReferenceNode(reference));

  // Handle viewport case
  if (boundariesElement === 'viewport') {
    boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent, fixedPosition);
  } else {
    // Handle other cases based on DOM element used as boundaries
    var boundariesNode = void 0;
    if (boundariesElement === 'scrollParent') {
      boundariesNode = getScrollParent(getParentNode(reference));
      if (boundariesNode.nodeName === 'BODY') {
        boundariesNode = popper.ownerDocument.documentElement;
      }
    } else if (boundariesElement === 'window') {
      boundariesNode = popper.ownerDocument.documentElement;
    } else {
      boundariesNode = boundariesElement;
    }

    var offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent, fixedPosition);

    // In case of HTML, we need a different computation
    if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) {
      var _getWindowSizes = getWindowSizes(popper.ownerDocument),
          height = _getWindowSizes.height,
          width = _getWindowSizes.width;

      boundaries.top += offsets.top - offsets.marginTop;
      boundaries.bottom = height + offsets.top;
      boundaries.left += offsets.left - offsets.marginLeft;
      boundaries.right = width + offsets.left;
    } else {
      // for all the other DOM elements, this one is good
      boundaries = offsets;
    }
  }

  // Add paddings
  padding = padding || 0;
  var isPaddingNumber = typeof padding === 'number';
  boundaries.left += isPaddingNumber ? padding : padding.left || 0;
  boundaries.top += isPaddingNumber ? padding : padding.top || 0;
  boundaries.right -= isPaddingNumber ? padding : padding.right || 0;
  boundaries.bottom -= isPaddingNumber ? padding : padding.bottom || 0;

  return boundaries;
}

function getArea(_ref) {
  var width = _ref.width,
      height = _ref.height;

  return width * height;
}

/**
 * Utility used to transform the `auto` placement to the placement with more
 * available space.
 * @method
 * @memberof Popper.Utils
 * @argument {Object} data - The data object generated by update method
 * @argument {Object} options - Modifiers configuration and options
 * @returns {Object} The data object, properly modified
 */
function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement) {
  var padding = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;

  if (placement.indexOf('auto') === -1) {
    return placement;
  }

  var boundaries = getBoundaries(popper, reference, padding, boundariesElement);

  var rects = {
    top: {
      width: boundaries.width,
      height: refRect.top - boundaries.top
    },
    right: {
      width: boundaries.right - refRect.right,
      height: boundaries.height
    },
    bottom: {
      width: boundaries.width,
      height: boundaries.bottom - refRect.bottom
    },
    left: {
      width: refRect.left - boundaries.left,
      height: boundaries.height
    }
  };

  var sortedAreas = Object.keys(rects).map(function (key) {
    return _extends({
      key: key
    }, rects[key], {
      area: getArea(rects[key])
    });
  }).sort(function (a, b) {
    return b.area - a.area;
  });

  var filteredAreas = sortedAreas.filter(function (_ref2) {
    var width = _ref2.width,
        height = _ref2.height;
    return width >= popper.clientWidth && height >= popper.clientHeight;
  });

  var computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key;

  var variation = placement.split('-')[1];

  return computedPlacement + (variation ? '-' + variation : '');
}

/**
 * Get offsets to the reference element
 * @method
 * @memberof Popper.Utils
 * @param {Object} state
 * @param {Element} popper - the popper element
 * @param {Element} reference - the reference element (the popper will be relative to this)
 * @param {Element} fixedPosition - is in fixed position mode
 * @returns {Object} An object containing the offsets which will be applied to the popper
 */
function getReferenceOffsets(state, popper, reference) {
  var fixedPosition = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;

  var commonOffsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, getReferenceNode(reference));
  return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent, fixedPosition);
}

/**
 * Get the outer sizes of the given element (offset size + margins)
 * @method
 * @memberof Popper.Utils
 * @argument {Element} element
 * @returns {Object} object containing width and height properties
 */
function getOuterSizes(element) {
  var window = element.ownerDocument.defaultView;
  var styles = window.getComputedStyle(element);
  var x = parseFloat(styles.marginTop || 0) + parseFloat(styles.marginBottom || 0);
  var y = parseFloat(styles.marginLeft || 0) + parseFloat(styles.marginRight || 0);
  var result = {
    width: element.offsetWidth + y,
    height: element.offsetHeight + x
  };
  return result;
}

/**
 * Get the opposite placement of the given one
 * @method
 * @memberof Popper.Utils
 * @argument {String} placement
 * @returns {String} flipped placement
 */
function getOppositePlacement(placement) {
  var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' };
  return placement.replace(/left|right|bottom|top/g, function (matched) {
    return hash[matched];
  });
}

/**
 * Get offsets to the popper
 * @method
 * @memberof Popper.Utils
 * @param {Object} position - CSS position the Popper will get applied
 * @param {HTMLElement} popper - the popper element
 * @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this)
 * @param {String} placement - one of the valid placement options
 * @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper
 */
function getPopperOffsets(popper, referenceOffsets, placement) {
  placement = placement.split('-')[0];

  // Get popper node sizes
  var popperRect = getOuterSizes(popper);

  // Add position, width and height to our offsets object
  var popperOffsets = {
    width: popperRect.width,
    height: popperRect.height
  };

  // depending by the popper placement we have to compute its offsets slightly differently
  var isHoriz = ['right', 'left'].indexOf(placement) !== -1;
  var mainSide = isHoriz ? 'top' : 'left';
  var secondarySide = isHoriz ? 'left' : 'top';
  var measurement = isHoriz ? 'height' : 'width';
  var secondaryMeasurement = !isHoriz ? 'height' : 'width';

  popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2;
  if (placement === secondarySide) {
    popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement];
  } else {
    popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)];
  }

  return popperOffsets;
}

/**
 * Mimics the `find` method of Array
 * @method
 * @memberof Popper.Utils
 * @argument {Array} arr
 * @argument prop
 * @argument value
 * @returns index or -1
 */
function find(arr, check) {
  // use native find if supported
  if (Array.prototype.find) {
    return arr.find(check);
  }

  // use `filter` to obtain the same behavior of `find`
  return arr.filter(check)[0];
}

/**
 * Return the index of the matching object
 * @method
 * @memberof Popper.Utils
 * @argument {Array} arr
 * @argument prop
 * @argument value
 * @returns index or -1
 */
function findIndex(arr, prop, value) {
  // use native findIndex if supported
  if (Array.prototype.findIndex) {
    return arr.findIndex(function (cur) {
      return cur[prop] === value;
    });
  }

  // use `find` + `indexOf` if `findIndex` isn't supported
  var match = find(arr, function (obj) {
    return obj[prop] === value;
  });
  return arr.indexOf(match);
}

/**
 * Loop trough the list of modifiers and run them in order,
 * each of them will then edit the data object.
 * @method
 * @memberof Popper.Utils
 * @param {dataObject} data
 * @param {Array} modifiers
 * @param {String} ends - Optional modifier name used as stopper
 * @returns {dataObject}
 */
function runModifiers(modifiers, data, ends) {
  var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends));

  modifiersToRun.forEach(function (modifier) {
    if (modifier['function']) {
      // eslint-disable-line dot-notation
      console.warn('`modifier.function` is deprecated, use `modifier.fn`!');
    }
    var fn = modifier['function'] || modifier.fn; // eslint-disable-line dot-notation
    if (modifier.enabled && isFunction(fn)) {
      // Add properties to offsets to make them a complete clientRect object
      // we do this before each modifier to make sure the previous one doesn't
      // mess with these values
      data.offsets.popper = getClientRect(data.offsets.popper);
      data.offsets.reference = getClientRect(data.offsets.reference);

      data = fn(data, modifier);
    }
  });

  return data;
}

/**
 * Updates the position of the popper, computing the new offsets and applying
 * the new style.<br />
 * Prefer `scheduleUpdate` over `update` because of performance reasons.
 * @method
 * @memberof Popper
 */
function update() {
  // if popper is destroyed, don't perform any further update
  if (this.state.isDestroyed) {
    return;
  }

  var data = {
    instance: this,
    styles: {},
    arrowStyles: {},
    attributes: {},
    flipped: false,
    offsets: {}
  };

  // compute reference element offsets
  data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference, this.options.positionFixed);

  // compute auto placement, store placement inside the data object,
  // modifiers will be able to edit `placement` if needed
  // and refer to originalPlacement to know the original value
  data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding);

  // store the computed placement inside `originalPlacement`
  data.originalPlacement = data.placement;

  data.positionFixed = this.options.positionFixed;

  // compute the popper offsets
  data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement);

  data.offsets.popper.position = this.options.positionFixed ? 'fixed' : 'absolute';

  // run the modifiers
  data = runModifiers(this.modifiers, data);

  // the first `update` will call `onCreate` callback
  // the other ones will call `onUpdate` callback
  if (!this.state.isCreated) {
    this.state.isCreated = true;
    this.options.onCreate(data);
  } else {
    this.options.onUpdate(data);
  }
}

/**
 * Helper used to know if the given modifier is enabled.
 * @method
 * @memberof Popper.Utils
 * @returns {Boolean}
 */
function isModifierEnabled(modifiers, modifierName) {
  return modifiers.some(function (_ref) {
    var name = _ref.name,
        enabled = _ref.enabled;
    return enabled && name === modifierName;
  });
}

/**
 * Get the prefixed supported property name
 * @method
 * @memberof Popper.Utils
 * @argument {String} property (camelCase)
 * @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix)
 */
function getSupportedPropertyName(property) {
  var prefixes = [false, 'ms', 'Webkit', 'Moz', 'O'];
  var upperProp = property.charAt(0).toUpperCase() + property.slice(1);

  for (var i = 0; i < prefixes.length; i++) {
    var prefix = prefixes[i];
    var toCheck = prefix ? '' + prefix + upperProp : property;
    if (typeof document.body.style[toCheck] !== 'undefined') {
      return toCheck;
    }
  }
  return null;
}

/**
 * Destroys the popper.
 * @method
 * @memberof Popper
 */
function destroy() {
  this.state.isDestroyed = true;

  // touch DOM only if `applyStyle` modifier is enabled
  if (isModifierEnabled(this.modifiers, 'applyStyle')) {
    this.popper.removeAttribute('x-placement');
    this.popper.style.position = '';
    this.popper.style.top = '';
    this.popper.style.left = '';
    this.popper.style.right = '';
    this.popper.style.bottom = '';
    this.popper.style.willChange = '';
    this.popper.style[getSupportedPropertyName('transform')] = '';
  }

  this.disableEventListeners();

  // remove the popper if user explicitly asked for the deletion on destroy
  // do not use `remove` because IE11 doesn't support it
  if (this.options.removeOnDestroy) {
    this.popper.parentNode.removeChild(this.popper);
  }
  return this;
}

/**
 * Get the window associated with the element
 * @argument {Element} element
 * @returns {Window}
 */
function getWindow(element) {
  var ownerDocument = element.ownerDocument;
  return ownerDocument ? ownerDocument.defaultView : window;
}

function attachToScrollParents(scrollParent, event, callback, scrollParents) {
  var isBody = scrollParent.nodeName === 'BODY';
  var target = isBody ? scrollParent.ownerDocument.defaultView : scrollParent;
  target.addEventListener(event, callback, { passive: true });

  if (!isBody) {
    attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents);
  }
  scrollParents.push(target);
}

/**
 * Setup needed event listeners used to update the popper position
 * @method
 * @memberof Popper.Utils
 * @private
 */
function setupEventListeners(reference, options, state, updateBound) {
  // Resize event listener on window
  state.updateBound = updateBound;
  getWindow(reference).addEventListener('resize', state.updateBound, { passive: true });

  // Scroll event listener on scroll parents
  var scrollElement = getScrollParent(reference);
  attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents);
  state.scrollElement = scrollElement;
  state.eventsEnabled = true;

  return state;
}

/**
 * It will add resize/scroll events and start recalculating
 * position of the popper element when they are triggered.
 * @method
 * @memberof Popper
 */
function enableEventListeners() {
  if (!this.state.eventsEnabled) {
    this.state = setupEventListeners(this.reference, this.options, this.state, this.scheduleUpdate);
  }
}

/**
 * Remove event listeners used to update the popper position
 * @method
 * @memberof Popper.Utils
 * @private
 */
function removeEventListeners(reference, state) {
  // Remove resize event listener on window
  getWindow(reference).removeEventListener('resize', state.updateBound);

  // Remove scroll event listener on scroll parents
  state.scrollParents.forEach(function (target) {
    target.removeEventListener('scroll', state.updateBound);
  });

  // Reset state
  state.updateBound = null;
  state.scrollParents = [];
  state.scrollElement = null;
  state.eventsEnabled = false;
  return state;
}

/**
 * It will remove resize/scroll events and won't recalculate popper position
 * when they are triggered. It also won't trigger `onUpdate` callback anymore,
 * unless you call `update` method manually.
 * @method
 * @memberof Popper
 */
function disableEventListeners() {
  if (this.state.eventsEnabled) {
    cancelAnimationFrame(this.scheduleUpdate);
    this.state = removeEventListeners(this.reference, this.state);
  }
}

/**
 * Tells if a given input is a number
 * @method
 * @memberof Popper.Utils
 * @param {*} input to check
 * @return {Boolean}
 */
function isNumeric(n) {
  return n !== '' && !isNaN(parseFloat(n)) && isFinite(n);
}

/**
 * Set the style to the given popper
 * @method
 * @memberof Popper.Utils
 * @argument {Element} element - Element to apply the style to
 * @argument {Object} styles
 * Object with a list of properties and values which will be applied to the element
 */
function setStyles(element, styles) {
  Object.keys(styles).forEach(function (prop) {
    var unit = '';
    // add unit if the value is numeric and is one of the following
    if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) {
      unit = 'px';
    }
    element.style[prop] = styles[prop] + unit;
  });
}

/**
 * Set the attributes to the given popper
 * @method
 * @memberof Popper.Utils
 * @argument {Element} element - Element to apply the attributes to
 * @argument {Object} styles
 * Object with a list of properties and values which will be applied to the element
 */
function setAttributes(element, attributes) {
  Object.keys(attributes).forEach(function (prop) {
    var value = attributes[prop];
    if (value !== false) {
      element.setAttribute(prop, attributes[prop]);
    } else {
      element.removeAttribute(prop);
    }
  });
}

/**
 * @function
 * @memberof Modifiers
 * @argument {Object} data - The data object generated by `update` method
 * @argument {Object} data.styles - List of style properties - values to apply to popper element
 * @argument {Object} data.attributes - List of attribute properties - values to apply to popper element
 * @argument {Object} options - Modifiers configuration and options
 * @returns {Object} The same data object
 */
function applyStyle(data) {
  // any property present in `data.styles` will be applied to the popper,
  // in this way we can make the 3rd party modifiers add custom styles to it
  // Be aware, modifiers could override the properties defined in the previous
  // lines of this modifier!
  setStyles(data.instance.popper, data.styles);

  // any property present in `data.attributes` will be applied to the popper,
  // they will be set as HTML attributes of the element
  setAttributes(data.instance.popper, data.attributes);

  // if arrowElement is defined and arrowStyles has some properties
  if (data.arrowElement && Object.keys(data.arrowStyles).length) {
    setStyles(data.arrowElement, data.arrowStyles);
  }

  return data;
}

/**
 * Set the x-placement attribute before everything else because it could be used
 * to add margins to the popper margins needs to be calculated to get the
 * correct popper offsets.
 * @method
 * @memberof Popper.modifiers
 * @param {HTMLElement} reference - The reference element used to position the popper
 * @param {HTMLElement} popper - The HTML element used as popper
 * @param {Object} options - Popper.js options
 */
function applyStyleOnLoad(reference, popper, options, modifierOptions, state) {
  // compute reference element offsets
  var referenceOffsets = getReferenceOffsets(state, popper, reference, options.positionFixed);

  // compute auto placement, store placement inside the data object,
  // modifiers will be able to edit `placement` if needed
  // and refer to originalPlacement to know the original value
  var placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding);

  popper.setAttribute('x-placement', placement);

  // Apply `position` to popper before anything else because
  // without the position applied we can't guarantee correct computations
  setStyles(popper, { position: options.positionFixed ? 'fixed' : 'absolute' });

  return options;
}

/**
 * @function
 * @memberof Popper.Utils
 * @argument {Object} data - The data object generated by `update` method
 * @argument {Boolean} shouldRound - If the offsets should be rounded at all
 * @returns {Object} The popper's position offsets rounded
 *
 * The tale of pixel-perfect positioning. It's still not 100% perfect, but as
 * good as it can be within reason.
 * Discussion here: https://github.com/FezVrasta/popper.js/pull/715
 *
 * Low DPI screens cause a popper to be blurry if not using full pixels (Safari
 * as well on High DPI screens).
 *
 * Firefox prefers no rounding for positioning and does not have blurriness on
 * high DPI screens.
 *
 * Only horizontal placement and left/right values need to be considered.
 */
function getRoundedOffsets(data, shouldRound) {
  var _data$offsets = data.offsets,
      popper = _data$offsets.popper,
      reference = _data$offsets.reference;
  var round = Math.round,
      floor = Math.floor;

  var noRound = function noRound(v) {
    return v;
  };

  var referenceWidth = round(reference.width);
  var popperWidth = round(popper.width);

  var isVertical = ['left', 'right'].indexOf(data.placement) !== -1;
  var isVariation = data.placement.indexOf('-') !== -1;
  var sameWidthParity = referenceWidth % 2 === popperWidth % 2;
  var bothOddWidth = referenceWidth % 2 === 1 && popperWidth % 2 === 1;

  var horizontalToInteger = !shouldRound ? noRound : isVertical || isVariation || sameWidthParity ? round : floor;
  var verticalToInteger = !shouldRound ? noRound : round;

  return {
    left: horizontalToInteger(bothOddWidth && !isVariation && shouldRound ? popper.left - 1 : popper.left),
    top: verticalToInteger(popper.top),
    bottom: verticalToInteger(popper.bottom),
    right: horizontalToInteger(popper.right)
  };
}

var isFirefox = isBrowser && /Firefox/i.test(navigator.userAgent);

/**
 * @function
 * @memberof Modifiers
 * @argument {Object} data - The data object generated by `update` method
 * @argument {Object} options - Modifiers configuration and options
 * @returns {Object} The data object, properly modified
 */
function computeStyle(data, options) {
  var x = options.x,
      y = options.y;
  var popper = data.offsets.popper;

  // Remove this legacy support in Popper.js v2

  var legacyGpuAccelerationOption = find(data.instance.modifiers, function (modifier) {
    return modifier.name === 'applyStyle';
  }).gpuAcceleration;
  if (legacyGpuAccelerationOption !== undefined) {
    console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!');
  }
  var gpuAcceleration = legacyGpuAccelerationOption !== undefined ? legacyGpuAccelerationOption : options.gpuAcceleration;

  var offsetParent = getOffsetParent(data.instance.popper);
  var offsetParentRect = getBoundingClientRect(offsetParent);

  // Styles
  var styles = {
    position: popper.position
  };

  var offsets = getRoundedOffsets(data, window.devicePixelRatio < 2 || !isFirefox);

  var sideA = x === 'bottom' ? 'top' : 'bottom';
  var sideB = y === 'right' ? 'left' : 'right';

  // if gpuAcceleration is set to `true` and transform is supported,
  //  we use `translate3d` to apply the position to the popper we
  // automatically use the supported prefixed version if needed
  var prefixedProperty = getSupportedPropertyName('transform');

  // now, let's make a step back and look at this code closely (wtf?)
  // If the content of the popper grows once it's been positioned, it
  // may happen that the popper gets misplaced because of the new content
  // overflowing its reference element
  // To avoid this problem, we provide two options (x and y), which allow
  // the consumer to define the offset origin.
  // If we position a popper on top of a reference element, we can set
  // `x` to `top` to make the popper grow towards its top instead of
  // its bottom.
  var left = void 0,
      top = void 0;
  if (sideA === 'bottom') {
    // when offsetParent is <html> the positioning is relative to the bottom of the screen (excluding the scrollbar)
    // and not the bottom of the html element
    if (offsetParent.nodeName === 'HTML') {
      top = -offsetParent.clientHeight + offsets.bottom;
    } else {
      top = -offsetParentRect.height + offsets.bottom;
    }
  } else {
    top = offsets.top;
  }
  if (sideB === 'right') {
    if (offsetParent.nodeName === 'HTML') {
      left = -offsetParent.clientWidth + offsets.right;
    } else {
      left = -offsetParentRect.width + offsets.right;
    }
  } else {
    left = offsets.left;
  }
  if (gpuAcceleration && prefixedProperty) {
    styles[prefixedProperty] = 'translate3d(' + left + 'px, ' + top + 'px, 0)';
    styles[sideA] = 0;
    styles[sideB] = 0;
    styles.willChange = 'transform';
  } else {
    // othwerise, we use the standard `top`, `left`, `bottom` and `right` properties
    var invertTop = sideA === 'bottom' ? -1 : 1;
    var invertLeft = sideB === 'right' ? -1 : 1;
    styles[sideA] = top * invertTop;
    styles[sideB] = left * invertLeft;
    styles.willChange = sideA + ', ' + sideB;
  }

  // Attributes
  var attributes = {
    'x-placement': data.placement
  };

  // Update `data` attributes, styles and arrowStyles
  data.attributes = _extends({}, attributes, data.attributes);
  data.styles = _extends({}, styles, data.styles);
  data.arrowStyles = _extends({}, data.offsets.arrow, data.arrowStyles);

  return data;
}

/**
 * Helper used to know if the given modifier depends from another one.<br />
 * It checks if the needed modifier is listed and enabled.
 * @method
 * @memberof Popper.Utils
 * @param {Array} modifiers - list of modifiers
 * @param {String} requestingName - name of requesting modifier
 * @param {String} requestedName - name of requested modifier
 * @returns {Boolean}
 */
function isModifierRequired(modifiers, requestingName, requestedName) {
  var requesting = find(modifiers, function (_ref) {
    var name = _ref.name;
    return name === requestingName;
  });

  var isRequired = !!requesting && modifiers.some(function (modifier) {
    return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order;
  });

  if (!isRequired) {
    var _requesting = '`' + requestingName + '`';
    var requested = '`' + requestedName + '`';
    console.warn(requested + ' modifier is required by ' + _requesting + ' modifier in order to work, be sure to include it before ' + _requesting + '!');
  }
  return isRequired;
}

/**
 * @function
 * @memberof Modifiers
 * @argument {Object} data - The data object generated by update method
 * @argument {Object} options - Modifiers configuration and options
 * @returns {Object} The data object, properly modified
 */
function arrow(data, options) {
  var _data$offsets$arrow;

  // arrow depends on keepTogether in order to work
  if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) {
    return data;
  }

  var arrowElement = options.element;

  // if arrowElement is a string, suppose it's a CSS selector
  if (typeof arrowElement === 'string') {
    arrowElement = data.instance.popper.querySelector(arrowElement);

    // if arrowElement is not found, don't run the modifier
    if (!arrowElement) {
      return data;
    }
  } else {
    // if the arrowElement isn't a query selector we must check that the
    // provided DOM node is child of its popper node
    if (!data.instance.popper.contains(arrowElement)) {
      console.warn('WARNING: `arrow.element` must be child of its popper element!');
      return data;
    }
  }

  var placement = data.placement.split('-')[0];
  var _data$offsets = data.offsets,
      popper = _data$offsets.popper,
      reference = _data$offsets.reference;

  var isVertical = ['left', 'right'].indexOf(placement) !== -1;

  var len = isVertical ? 'height' : 'width';
  var sideCapitalized = isVertical ? 'Top' : 'Left';
  var side = sideCapitalized.toLowerCase();
  var altSide = isVertical ? 'left' : 'top';
  var opSide = isVertical ? 'bottom' : 'right';
  var arrowElementSize = getOuterSizes(arrowElement)[len];

  //
  // extends keepTogether behavior making sure the popper and its
  // reference have enough pixels in conjunction
  //

  // top/left side
  if (reference[opSide] - arrowElementSize < popper[side]) {
    data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize);
  }
  // bottom/right side
  if (reference[side] + arrowElementSize > popper[opSide]) {
    data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide];
  }
  data.offsets.popper = getClientRect(data.offsets.popper);

  // compute center of the popper
  var center = reference[side] + reference[len] / 2 - arrowElementSize / 2;

  // Compute the sideValue using the updated popper offsets
  // take popper margin in account because we don't have this info available
  var css = getStyleComputedProperty(data.instance.popper);
  var popperMarginSide = parseFloat(css['margin' + sideCapitalized]);
  var popperBorderSide = parseFloat(css['border' + sideCapitalized + 'Width']);
  var sideValue = center - data.offsets.popper[side] - popperMarginSide - popperBorderSide;

  // prevent arrowElement from being placed not contiguously to its popper
  sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0);

  data.arrowElement = arrowElement;
  data.offsets.arrow = (_data$offsets$arrow = {}, defineProperty(_data$offsets$arrow, side, Math.round(sideValue)), defineProperty(_data$offsets$arrow, altSide, ''), _data$offsets$arrow);

  return data;
}

/**
 * Get the opposite placement variation of the given one
 * @method
 * @memberof Popper.Utils
 * @argument {String} placement variation
 * @returns {String} flipped placement variation
 */
function getOppositeVariation(variation) {
  if (variation === 'end') {
    return 'start';
  } else if (variation === 'start') {
    return 'end';
  }
  return variation;
}

/**
 * List of accepted placements to use as values of the `placement` option.<br />
 * Valid placements are:
 * - `auto`
 * - `top`
 * - `right`
 * - `bottom`
 * - `left`
 *
 * Each placement can have a variation from this list:
 * - `-start`
 * - `-end`
 *
 * Variations are interpreted easily if you think of them as the left to right
 * written languages. Horizontally (`top` and `bottom`), `start` is left and `end`
 * is right.<br />
 * Vertically (`left` and `right`), `start` is top and `end` is bottom.
 *
 * Some valid examples are:
 * - `top-end` (on top of reference, right aligned)
 * - `right-start` (on right of reference, top aligned)
 * - `bottom` (on bottom, centered)
 * - `auto-end` (on the side with more space available, alignment depends by placement)
 *
 * @static
 * @type {Array}
 * @enum {String}
 * @readonly
 * @method placements
 * @memberof Popper
 */
var placements = ['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start'];

// Get rid of `auto` `auto-start` and `auto-end`
var validPlacements = placements.slice(3);

/**
 * Given an initial placement, returns all the subsequent placements
 * clockwise (or counter-clockwise).
 *
 * @method
 * @memberof Popper.Utils
 * @argument {String} placement - A valid placement (it accepts variations)
 * @argument {Boolean} counter - Set to true to walk the placements counterclockwise
 * @returns {Array} placements including their variations
 */
function clockwise(placement) {
  var counter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

  var index = validPlacements.indexOf(placement);
  var arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index));
  return counter ? arr.reverse() : arr;
}

var BEHAVIORS = {
  FLIP: 'flip',
  CLOCKWISE: 'clockwise',
  COUNTERCLOCKWISE: 'counterclockwise'
};

/**
 * @function
 * @memberof Modifiers
 * @argument {Object} data - The data object generated by update method
 * @argument {Object} options - Modifiers configuration and options
 * @returns {Object} The data object, properly modified
 */
function flip(data, options) {
  // if `inner` modifier is enabled, we can't use the `flip` modifier
  if (isModifierEnabled(data.instance.modifiers, 'inner')) {
    return data;
  }

  if (data.flipped && data.placement === data.originalPlacement) {
    // seems like flip is trying to loop, probably there's not enough space on any of the flippable sides
    return data;
  }

  var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, options.boundariesElement, data.positionFixed);

  var placement = data.placement.split('-')[0];
  var placementOpposite = getOppositePlacement(placement);
  var variation = data.placement.split('-')[1] || '';

  var flipOrder = [];

  switch (options.behavior) {
    case BEHAVIORS.FLIP:
      flipOrder = [placement, placementOpposite];
      break;
    case BEHAVIORS.CLOCKWISE:
      flipOrder = clockwise(placement);
      break;
    case BEHAVIORS.COUNTERCLOCKWISE:
      flipOrder = clockwise(placement, true);
      break;
    default:
      flipOrder = options.behavior;
  }

  flipOrder.forEach(function (step, index) {
    if (placement !== step || flipOrder.length === index + 1) {
      return data;
    }

    placement = data.placement.split('-')[0];
    placementOpposite = getOppositePlacement(placement);

    var popperOffsets = data.offsets.popper;
    var refOffsets = data.offsets.reference;

    // using floor because the reference offsets may contain decimals we are not going to consider here
    var floor = Math.floor;
    var overlapsRef = placement === 'left' && floor(popperOffsets.right) > floor(refOffsets.left) || placement === 'right' && floor(popperOffsets.left) < floor(refOffsets.right) || placement === 'top' && floor(popperOffsets.bottom) > floor(refOffsets.top) || placement === 'bottom' && floor(popperOffsets.top) < floor(refOffsets.bottom);

    var overflowsLeft = floor(popperOffsets.left) < floor(boundaries.left);
    var overflowsRight = floor(popperOffsets.right) > floor(boundaries.right);
    var overflowsTop = floor(popperOffsets.top) < floor(boundaries.top);
    var overflowsBottom = floor(popperOffsets.bottom) > floor(boundaries.bottom);

    var overflowsBoundaries = placement === 'left' && overflowsLeft || placement === 'right' && overflowsRight || placement === 'top' && overflowsTop || placement === 'bottom' && overflowsBottom;

    // flip the variation if required
    var isVertical = ['top', 'bottom'].indexOf(placement) !== -1;

    // flips variation if reference element overflows boundaries
    var flippedVariationByRef = !!options.flipVariations && (isVertical && variation === 'start' && overflowsLeft || isVertical && variation === 'end' && overflowsRight || !isVertical && variation === 'start' && overflowsTop || !isVertical && variation === 'end' && overflowsBottom);

    // flips variation if popper content overflows boundaries
    var flippedVariationByContent = !!options.flipVariationsByContent && (isVertical && variation === 'start' && overflowsRight || isVertical && variation === 'end' && overflowsLeft || !isVertical && variation === 'start' && overflowsBottom || !isVertical && variation === 'end' && overflowsTop);

    var flippedVariation = flippedVariationByRef || flippedVariationByContent;

    if (overlapsRef || overflowsBoundaries || flippedVariation) {
      // this boolean to detect any flip loop
      data.flipped = true;

      if (overlapsRef || overflowsBoundaries) {
        placement = flipOrder[index + 1];
      }

      if (flippedVariation) {
        variation = getOppositeVariation(variation);
      }

      data.placement = placement + (variation ? '-' + variation : '');

      // this object contains `position`, we want to preserve it along with
      // any additional property we may add in the future
      data.offsets.popper = _extends({}, data.offsets.popper, getPopperOffsets(data.instance.popper, data.offsets.reference, data.placement));

      data = runModifiers(data.instance.modifiers, data, 'flip');
    }
  });
  return data;
}

/**
 * @function
 * @memberof Modifiers
 * @argument {Object} data - The data object generated by update method
 * @argument {Object} options - Modifiers configuration and options
 * @returns {Object} The data object, properly modified
 */
function keepTogether(data) {
  var _data$offsets = data.offsets,
      popper = _data$offsets.popper,
      reference = _data$offsets.reference;

  var placement = data.placement.split('-')[0];
  var floor = Math.floor;
  var isVertical = ['top', 'bottom'].indexOf(placement) !== -1;
  var side = isVertical ? 'right' : 'bottom';
  var opSide = isVertical ? 'left' : 'top';
  var measurement = isVertical ? 'width' : 'height';

  if (popper[side] < floor(reference[opSide])) {
    data.offsets.popper[opSide] = floor(reference[opSide]) - popper[measurement];
  }
  if (popper[opSide] > floor(reference[side])) {
    data.offsets.popper[opSide] = floor(reference[side]);
  }

  return data;
}

/**
 * Converts a string containing value + unit into a px value number
 * @function
 * @memberof {modifiers~offset}
 * @private
 * @argument {String} str - Value + unit string
 * @argument {String} measurement - `height` or `width`
 * @argument {Object} popperOffsets
 * @argument {Object} referenceOffsets
 * @returns {Number|String}
 * Value in pixels, or original string if no values were extracted
 */
function toValue(str, measurement, popperOffsets, referenceOffsets) {
  // separate value from unit
  var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/);
  var value = +split[1];
  var unit = split[2];

  // If it's not a number it's an operator, I guess
  if (!value) {
    return str;
  }

  if (unit.indexOf('%') === 0) {
    var element = void 0;
    switch (unit) {
      case '%p':
        element = popperOffsets;
        break;
      case '%':
      case '%r':
      default:
        element = referenceOffsets;
    }

    var rect = getClientRect(element);
    return rect[measurement] / 100 * value;
  } else if (unit === 'vh' || unit === 'vw') {
    // if is a vh or vw, we calculate the size based on the viewport
    var size = void 0;
    if (unit === 'vh') {
      size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    } else {
      size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
    }
    return size / 100 * value;
  } else {
    // if is an explicit pixel unit, we get rid of the unit and keep the value
    // if is an implicit unit, it's px, and we return just the value
    return value;
  }
}

/**
 * Parse an `offset` string to extrapolate `x` and `y` numeric offsets.
 * @function
 * @memberof {modifiers~offset}
 * @private
 * @argument {String} offset
 * @argument {Object} popperOffsets
 * @argument {Object} referenceOffsets
 * @argument {String} basePlacement
 * @returns {Array} a two cells array with x and y offsets in numbers
 */
function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) {
  var offsets = [0, 0];

  // Use height if placement is left or right and index is 0 otherwise use width
  // in this way the first offset will use an axis and the second one
  // will use the other one
  var useHeight = ['right', 'left'].indexOf(basePlacement) !== -1;

  // Split the offset string to obtain a list of values and operands
  // The regex addresses values with the plus or minus sign in front (+10, -20, etc)
  var fragments = offset.split(/(\+|\-)/).map(function (frag) {
    return frag.trim();
  });

  // Detect if the offset string contains a pair of values or a single one
  // they could be separated by comma or space
  var divider = fragments.indexOf(find(fragments, function (frag) {
    return frag.search(/,|\s/) !== -1;
  }));

  if (fragments[divider] && fragments[divider].indexOf(',') === -1) {
    console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.');
  }

  // If divider is found, we divide the list of values and operands to divide
  // them by ofset X and Y.
  var splitRegex = /\s*,\s*|\s+/;
  var ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments];

  // Convert the values with units to absolute pixels to allow our computations
  ops = ops.map(function (op, index) {
    // Most of the units rely on the orientation of the popper
    var measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width';
    var mergeWithPrevious = false;
    return op
    // This aggregates any `+` or `-` sign that aren't considered operators
    // e.g.: 10 + +5 => [10, +, +5]
    .reduce(function (a, b) {
      if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) {
        a[a.length - 1] = b;
        mergeWithPrevious = true;
        return a;
      } else if (mergeWithPrevious) {
        a[a.length - 1] += b;
        mergeWithPrevious = false;
        return a;
      } else {
        return a.concat(b);
      }
    }, [])
    // Here we convert the string values into number values (in px)
    .map(function (str) {
      return toValue(str, measurement, popperOffsets, referenceOffsets);
    });
  });

  // Loop trough the offsets arrays and execute the operations
  ops.forEach(function (op, index) {
    op.forEach(function (frag, index2) {
      if (isNumeric(frag)) {
        offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1);
      }
    });
  });
  return offsets;
}

/**
 * @function
 * @memberof Modifiers
 * @argument {Object} data - The data object generated by update method
 * @argument {Object} options - Modifiers configuration and options
 * @argument {Number|String} options.offset=0
 * The offset value as described in the modifier description
 * @returns {Object} The data object, properly modified
 */
function offset(data, _ref) {
  var offset = _ref.offset;
  var placement = data.placement,
      _data$offsets = data.offsets,
      popper = _data$offsets.popper,
      reference = _data$offsets.reference;

  var basePlacement = placement.split('-')[0];

  var offsets = void 0;
  if (isNumeric(+offset)) {
    offsets = [+offset, 0];
  } else {
    offsets = parseOffset(offset, popper, reference, basePlacement);
  }

  if (basePlacement === 'left') {
    popper.top += offsets[0];
    popper.left -= offsets[1];
  } else if (basePlacement === 'right') {
    popper.top += offsets[0];
    popper.left += offsets[1];
  } else if (basePlacement === 'top') {
    popper.left += offsets[0];
    popper.top -= offsets[1];
  } else if (basePlacement === 'bottom') {
    popper.left += offsets[0];
    popper.top += offsets[1];
  }

  data.popper = popper;
  return data;
}

/**
 * @function
 * @memberof Modifiers
 * @argument {Object} data - The data object generated by `update` method
 * @argument {Object} options - Modifiers configuration and options
 * @returns {Object} The data object, properly modified
 */
function preventOverflow(data, options) {
  var boundariesElement = options.boundariesElement || getOffsetParent(data.instance.popper);

  // If offsetParent is the reference element, we really want to
  // go one step up and use the next offsetParent as reference to
  // avoid to make this modifier completely useless and look like broken
  if (data.instance.reference === boundariesElement) {
    boundariesElement = getOffsetParent(boundariesElement);
  }

  // NOTE: DOM access here
  // resets the popper's position so that the document size can be calculated excluding
  // the size of the popper element itself
  var transformProp = getSupportedPropertyName('transform');
  var popperStyles = data.instance.popper.style; // assignment to help minification
  var top = popperStyles.top,
      left = popperStyles.left,
      transform = popperStyles[transformProp];

  popperStyles.top = '';
  popperStyles.left = '';
  popperStyles[transformProp] = '';

  var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, boundariesElement, data.positionFixed);

  // NOTE: DOM access here
  // restores the original style properties after the offsets have been computed
  popperStyles.top = top;
  popperStyles.left = left;
  popperStyles[transformProp] = transform;

  options.boundaries = boundaries;

  var order = options.priority;
  var popper = data.offsets.popper;

  var check = {
    primary: function primary(placement) {
      var value = popper[placement];
      if (popper[placement] < boundaries[placement] && !options.escapeWithReference) {
        value = Math.max(popper[placement], boundaries[placement]);
      }
      return defineProperty({}, placement, value);
    },
    secondary: function secondary(placement) {
      var mainSide = placement === 'right' ? 'left' : 'top';
      var value = popper[mainSide];
      if (popper[placement] > boundaries[placement] && !options.escapeWithReference) {
        value = Math.min(popper[mainSide], boundaries[placement] - (placement === 'right' ? popper.width : popper.height));
      }
      return defineProperty({}, mainSide, value);
    }
  };

  order.forEach(function (placement) {
    var side = ['left', 'top'].indexOf(placement) !== -1 ? 'primary' : 'secondary';
    popper = _extends({}, popper, check[side](placement));
  });

  data.offsets.popper = popper;

  return data;
}

/**
 * @function
 * @memberof Modifiers
 * @argument {Object} data - The data object generated by `update` method
 * @argument {Object} options - Modifiers configuration and options
 * @returns {Object} The data object, properly modified
 */
function shift(data) {
  var placement = data.placement;
  var basePlacement = placement.split('-')[0];
  var shiftvariation = placement.split('-')[1];

  // if shift shiftvariation is specified, run the modifier
  if (shiftvariation) {
    var _data$offsets = data.offsets,
        reference = _data$offsets.reference,
        popper = _data$offsets.popper;

    var isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1;
    var side = isVertical ? 'left' : 'top';
    var measurement = isVertical ? 'width' : 'height';

    var shiftOffsets = {
      start: defineProperty({}, side, reference[side]),
      end: defineProperty({}, side, reference[side] + reference[measurement] - popper[measurement])
    };

    data.offsets.popper = _extends({}, popper, shiftOffsets[shiftvariation]);
  }

  return data;
}

/**
 * @function
 * @memberof Modifiers
 * @argument {Object} data - The data object generated by update method
 * @argument {Object} options - Modifiers configuration and options
 * @returns {Object} The data object, properly modified
 */
function hide(data) {
  if (!isModifierRequired(data.instance.modifiers, 'hide', 'preventOverflow')) {
    return data;
  }

  var refRect = data.offsets.reference;
  var bound = find(data.instance.modifiers, function (modifier) {
    return modifier.name === 'preventOverflow';
  }).boundaries;

  if (refRect.bottom < bound.top || refRect.left > bound.right || refRect.top > bound.bottom || refRect.right < bound.left) {
    // Avoid unnecessary DOM access if visibility hasn't changed
    if (data.hide === true) {
      return data;
    }

    data.hide = true;
    data.attributes['x-out-of-boundaries'] = '';
  } else {
    // Avoid unnecessary DOM access if visibility hasn't changed
    if (data.hide === false) {
      return data;
    }

    data.hide = false;
    data.attributes['x-out-of-boundaries'] = false;
  }

  return data;
}

/**
 * @function
 * @memberof Modifiers
 * @argument {Object} data - The data object generated by `update` method
 * @argument {Object} options - Modifiers configuration and options
 * @returns {Object} The data object, properly modified
 */
function inner(data) {
  var placement = data.placement;
  var basePlacement = placement.split('-')[0];
  var _data$offsets = data.offsets,
      popper = _data$offsets.popper,
      reference = _data$offsets.reference;

  var isHoriz = ['left', 'right'].indexOf(basePlacement) !== -1;

  var subtractLength = ['top', 'left'].indexOf(basePlacement) === -1;

  popper[isHoriz ? 'left' : 'top'] = reference[basePlacement] - (subtractLength ? popper[isHoriz ? 'width' : 'height'] : 0);

  data.placement = getOppositePlacement(placement);
  data.offsets.popper = getClientRect(popper);

  return data;
}

/**
 * Modifier function, each modifier can have a function of this type assigned
 * to its `fn` property.<br />
 * These functions will be called on each update, this means that you must
 * make sure they are performant enough to avoid performance bottlenecks.
 *
 * @function ModifierFn
 * @argument {dataObject} data - The data object generated by `update` method
 * @argument {Object} options - Modifiers configuration and options
 * @returns {dataObject} The data object, properly modified
 */

/**
 * Modifiers are plugins used to alter the behavior of your poppers.<br />
 * Popper.js uses a set of 9 modifiers to provide all the basic functionalities
 * needed by the library.
 *
 * Usually you don't want to override the `order`, `fn` and `onLoad` props.
 * All the other properties are configurations that could be tweaked.
 * @namespace modifiers
 */
var modifiers = {
  /**
   * Modifier used to shift the popper on the start or end of its reference
   * element.<br />
   * It will read the variation of the `placement` property.<br />
   * It can be one either `-end` or `-start`.
   * @memberof modifiers
   * @inner
   */
  shift: {
    /** @prop {number} order=100 - Index used to define the order of execution */
    order: 100,
    /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
    enabled: true,
    /** @prop {ModifierFn} */
    fn: shift
  },

  /**
   * The `offset` modifier can shift your popper on both its axis.
   *
   * It accepts the following units:
   * - `px` or unit-less, interpreted as pixels
   * - `%` or `%r`, percentage relative to the length of the reference element
   * - `%p`, percentage relative to the length of the popper element
   * - `vw`, CSS viewport width unit
   * - `vh`, CSS viewport height unit
   *
   * For length is intended the main axis relative to the placement of the popper.<br />
   * This means that if the placement is `top` or `bottom`, the length will be the
   * `width`. In case of `left` or `right`, it will be the `height`.
   *
   * You can provide a single value (as `Number` or `String`), or a pair of values
   * as `String` divided by a comma or one (or more) white spaces.<br />
   * The latter is a deprecated method because it leads to confusion and will be
   * removed in v2.<br />
   * Additionally, it accepts additions and subtractions between different units.
   * Note that multiplications and divisions aren't supported.
   *
   * Valid examples are:
   * ```
   * 10
   * '10%'
   * '10, 10'
   * '10%, 10'
   * '10 + 10%'
   * '10 - 5vh + 3%'
   * '-10px + 5vh, 5px - 6%'
   * ```
   * > **NB**: If you desire to apply offsets to your poppers in a way that may make them overlap
   * > with their reference element, unfortunately, you will have to disable the `flip` modifier.
   * > You can read more on this at this [issue](https://github.com/FezVrasta/popper.js/issues/373).
   *
   * @memberof modifiers
   * @inner
   */
  offset: {
    /** @prop {number} order=200 - Index used to define the order of execution */
    order: 200,
    /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
    enabled: true,
    /** @prop {ModifierFn} */
    fn: offset,
    /** @prop {Number|String} offset=0
     * The offset value as described in the modifier description
     */
    offset: 0
  },

  /**
   * Modifier used to prevent the popper from being positioned outside the boundary.
   *
   * A scenario exists where the reference itself is not within the boundaries.<br />
   * We can say it has "escaped the boundaries" — or just "escaped".<br />
   * In this case we need to decide whether the popper should either:
   *
   * - detach from the reference and remain "trapped" in the boundaries, or
   * - if it should ignore the boundary and "escape with its reference"
   *
   * When `escapeWithReference` is set to`true` and reference is completely
   * outside its boundaries, the popper will overflow (or completely leave)
   * the boundaries in order to remain attached to the edge of the reference.
   *
   * @memberof modifiers
   * @inner
   */
  preventOverflow: {
    /** @prop {number} order=300 - Index used to define the order of execution */
    order: 300,
    /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
    enabled: true,
    /** @prop {ModifierFn} */
    fn: preventOverflow,
    /**
     * @prop {Array} [priority=['left','right','top','bottom']]
     * Popper will try to prevent overflow following these priorities by default,
     * then, it could overflow on the left and on top of the `boundariesElement`
     */
    priority: ['left', 'right', 'top', 'bottom'],
    /**
     * @prop {number} padding=5
     * Amount of pixel used to define a minimum distance between the boundaries
     * and the popper. This makes sure the popper always has a little padding
     * between the edges of its container
     */
    padding: 5,
    /**
     * @prop {String|HTMLElement} boundariesElement='scrollParent'
     * Boundaries used by the modifier. Can be `scrollParent`, `window`,
     * `viewport` or any DOM element.
     */
    boundariesElement: 'scrollParent'
  },

  /**
   * Modifier used to make sure the reference and its popper stay near each other
   * without leaving any gap between the two. Especially useful when the arrow is
   * enabled and you want to ensure that it points to its reference element.
   * It cares only about the first axis. You can still have poppers with margin
   * between the popper and its reference element.
   * @memberof modifiers
   * @inner
   */
  keepTogether: {
    /** @prop {number} order=400 - Index used to define the order of execution */
    order: 400,
    /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
    enabled: true,
    /** @prop {ModifierFn} */
    fn: keepTogether
  },

  /**
   * This modifier is used to move the `arrowElement` of the popper to make
   * sure it is positioned between the reference element and its popper element.
   * It will read the outer size of the `arrowElement` node to detect how many
   * pixels of conjunction are needed.
   *
   * It has no effect if no `arrowElement` is provided.
   * @memberof modifiers
   * @inner
   */
  arrow: {
    /** @prop {number} order=500 - Index used to define the order of execution */
    order: 500,
    /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
    enabled: true,
    /** @prop {ModifierFn} */
    fn: arrow,
    /** @prop {String|HTMLElement} element='[x-arrow]' - Selector or node used as arrow */
    element: '[x-arrow]'
  },

  /**
   * Modifier used to flip the popper's placement when it starts to overlap its
   * reference element.
   *
   * Requires the `preventOverflow` modifier before it in order to work.
   *
   * **NOTE:** this modifier will interrupt the current update cycle and will
   * restart it if it detects the need to flip the placement.
   * @memberof modifiers
   * @inner
   */
  flip: {
    /** @prop {number} order=600 - Index used to define the order of execution */
    order: 600,
    /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
    enabled: true,
    /** @prop {ModifierFn} */
    fn: flip,
    /**
     * @prop {String|Array} behavior='flip'
     * The behavior used to change the popper's placement. It can be one of
     * `flip`, `clockwise`, `counterclockwise` or an array with a list of valid
     * placements (with optional variations)
     */
    behavior: 'flip',
    /**
     * @prop {number} padding=5
     * The popper will flip if it hits the edges of the `boundariesElement`
     */
    padding: 5,
    /**
     * @prop {String|HTMLElement} boundariesElement='viewport'
     * The element which will define the boundaries of the popper position.
     * The popper will never be placed outside of the defined boundaries
     * (except if `keepTogether` is enabled)
     */
    boundariesElement: 'viewport',
    /**
     * @prop {Boolean} flipVariations=false
     * The popper will switch placement variation between `-start` and `-end` when
     * the reference element overlaps its boundaries.
     *
     * The original placement should have a set variation.
     */
    flipVariations: false,
    /**
     * @prop {Boolean} flipVariationsByContent=false
     * The popper will switch placement variation between `-start` and `-end` when
     * the popper element overlaps its reference boundaries.
     *
     * The original placement should have a set variation.
     */
    flipVariationsByContent: false
  },

  /**
   * Modifier used to make the popper flow toward the inner of the reference element.
   * By default, when this modifier is disabled, the popper will be placed outside
   * the reference element.
   * @memberof modifiers
   * @inner
   */
  inner: {
    /** @prop {number} order=700 - Index used to define the order of execution */
    order: 700,
    /** @prop {Boolean} enabled=false - Whether the modifier is enabled or not */
    enabled: false,
    /** @prop {ModifierFn} */
    fn: inner
  },

  /**
   * Modifier used to hide the popper when its reference element is outside of the
   * popper boundaries. It will set a `x-out-of-boundaries` attribute which can
   * be used to hide with a CSS selector the popper when its reference is
   * out of boundaries.
   *
   * Requires the `preventOverflow` modifier before it in order to work.
   * @memberof modifiers
   * @inner
   */
  hide: {
    /** @prop {number} order=800 - Index used to define the order of execution */
    order: 800,
    /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
    enabled: true,
    /** @prop {ModifierFn} */
    fn: hide
  },

  /**
   * Computes the style that will be applied to the popper element to gets
   * properly positioned.
   *
   * Note that this modifier will not touch the DOM, it just prepares the styles
   * so that `applyStyle` modifier can apply it. This separation is useful
   * in case you need to replace `applyStyle` with a custom implementation.
   *
   * This modifier has `850` as `order` value to maintain backward compatibility
   * with previous versions of Popper.js. Expect the modifiers ordering method
   * to change in future major versions of the library.
   *
   * @memberof modifiers
   * @inner
   */
  computeStyle: {
    /** @prop {number} order=850 - Index used to define the order of execution */
    order: 850,
    /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
    enabled: true,
    /** @prop {ModifierFn} */
    fn: computeStyle,
    /**
     * @prop {Boolean} gpuAcceleration=true
     * If true, it uses the CSS 3D transformation to position the popper.
     * Otherwise, it will use the `top` and `left` properties
     */
    gpuAcceleration: true,
    /**
     * @prop {string} [x='bottom']
     * Where to anchor the X axis (`bottom` or `top`). AKA X offset origin.
     * Change this if your popper should grow in a direction different from `bottom`
     */
    x: 'bottom',
    /**
     * @prop {string} [x='left']
     * Where to anchor the Y axis (`left` or `right`). AKA Y offset origin.
     * Change this if your popper should grow in a direction different from `right`
     */
    y: 'right'
  },

  /**
   * Applies the computed styles to the popper element.
   *
   * All the DOM manipulations are limited to this modifier. This is useful in case
   * you want to integrate Popper.js inside a framework or view library and you
   * want to delegate all the DOM manipulations to it.
   *
   * Note that if you disable this modifier, you must make sure the popper element
   * has its position set to `absolute` before Popper.js can do its work!
   *
   * Just disable this modifier and define your own to achieve the desired effect.
   *
   * @memberof modifiers
   * @inner
   */
  applyStyle: {
    /** @prop {number} order=900 - Index used to define the order of execution */
    order: 900,
    /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
    enabled: true,
    /** @prop {ModifierFn} */
    fn: applyStyle,
    /** @prop {Function} */
    onLoad: applyStyleOnLoad,
    /**
     * @deprecated since version 1.10.0, the property moved to `computeStyle` modifier
     * @prop {Boolean} gpuAcceleration=true
     * If true, it uses the CSS 3D transformation to position the popper.
     * Otherwise, it will use the `top` and `left` properties
     */
    gpuAcceleration: undefined
  }
};

/**
 * The `dataObject` is an object containing all the information used by Popper.js.
 * This object is passed to modifiers and to the `onCreate` and `onUpdate` callbacks.
 * @name dataObject
 * @property {Object} data.instance The Popper.js instance
 * @property {String} data.placement Placement applied to popper
 * @property {String} data.originalPlacement Placement originally defined on init
 * @property {Boolean} data.flipped True if popper has been flipped by flip modifier
 * @property {Boolean} data.hide True if the reference element is out of boundaries, useful to know when to hide the popper
 * @property {HTMLElement} data.arrowElement Node used as arrow by arrow modifier
 * @property {Object} data.styles Any CSS property defined here will be applied to the popper. It expects the JavaScript nomenclature (eg. `marginBottom`)
 * @property {Object} data.arrowStyles Any CSS property defined here will be applied to the popper arrow. It expects the JavaScript nomenclature (eg. `marginBottom`)
 * @property {Object} data.boundaries Offsets of the popper boundaries
 * @property {Object} data.offsets The measurements of popper, reference and arrow elements
 * @property {Object} data.offsets.popper `top`, `left`, `width`, `height` values
 * @property {Object} data.offsets.reference `top`, `left`, `width`, `height` values
 * @property {Object} data.offsets.arrow] `top` and `left` offsets, only one of them will be different from 0
 */

/**
 * Default options provided to Popper.js constructor.<br />
 * These can be overridden using the `options` argument of Popper.js.<br />
 * To override an option, simply pass an object with the same
 * structure of the `options` object, as the 3rd argument. For example:
 * ```
 * new Popper(ref, pop, {
 *   modifiers: {
 *     preventOverflow: { enabled: false }
 *   }
 * })
 * ```
 * @type {Object}
 * @static
 * @memberof Popper
 */
var Defaults = {
  /**
   * Popper's placement.
   * @prop {Popper.placements} placement='bottom'
   */
  placement: 'bottom',

  /**
   * Set this to true if you want popper to position it self in 'fixed' mode
   * @prop {Boolean} positionFixed=false
   */
  positionFixed: false,

  /**
   * Whether events (resize, scroll) are initially enabled.
   * @prop {Boolean} eventsEnabled=true
   */
  eventsEnabled: true,

  /**
   * Set to true if you want to automatically remove the popper when
   * you call the `destroy` method.
   * @prop {Boolean} removeOnDestroy=false
   */
  removeOnDestroy: false,

  /**
   * Callback called when the popper is created.<br />
   * By default, it is set to no-op.<br />
   * Access Popper.js instance with `data.instance`.
   * @prop {onCreate}
   */
  onCreate: function onCreate() {},

  /**
   * Callback called when the popper is updated. This callback is not called
   * on the initialization/creation of the popper, but only on subsequent
   * updates.<br />
   * By default, it is set to no-op.<br />
   * Access Popper.js instance with `data.instance`.
   * @prop {onUpdate}
   */
  onUpdate: function onUpdate() {},

  /**
   * List of modifiers used to modify the offsets before they are applied to the popper.
   * They provide most of the functionalities of Popper.js.
   * @prop {modifiers}
   */
  modifiers: modifiers
};

/**
 * @callback onCreate
 * @param {dataObject} data
 */

/**
 * @callback onUpdate
 * @param {dataObject} data
 */

// Utils
// Methods
var Popper = function () {
  /**
   * Creates a new Popper.js instance.
   * @class Popper
   * @param {Element|referenceObject} reference - The reference element used to position the popper
   * @param {Element} popper - The HTML / XML element used as the popper
   * @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults)
   * @return {Object} instance - The generated Popper.js instance
   */
  function Popper(reference, popper) {
    var _this = this;

    var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    classCallCheck(this, Popper);

    this.scheduleUpdate = function () {
      return requestAnimationFrame(_this.update);
    };

    // make update() debounced, so that it only runs at most once-per-tick
    this.update = debounce(this.update.bind(this));

    // with {} we create a new object with the options inside it
    this.options = _extends({}, Popper.Defaults, options);

    // init state
    this.state = {
      isDestroyed: false,
      isCreated: false,
      scrollParents: []
    };

    // get reference and popper elements (allow jQuery wrappers)
    this.reference = reference && reference.jquery ? reference[0] : reference;
    this.popper = popper && popper.jquery ? popper[0] : popper;

    // Deep merge modifiers options
    this.options.modifiers = {};
    Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) {
      _this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {});
    });

    // Refactoring modifiers' list (Object => Array)
    this.modifiers = Object.keys(this.options.modifiers).map(function (name) {
      return _extends({
        name: name
      }, _this.options.modifiers[name]);
    })
    // sort the modifiers by order
    .sort(function (a, b) {
      return a.order - b.order;
    });

    // modifiers have the ability to execute arbitrary code when Popper.js get inited
    // such code is executed in the same order of its modifier
    // they could add new properties to their options configuration
    // BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`!
    this.modifiers.forEach(function (modifierOptions) {
      if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) {
        modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state);
      }
    });

    // fire the first update to position the popper in the right place
    this.update();

    var eventsEnabled = this.options.eventsEnabled;
    if (eventsEnabled) {
      // setup event listeners, they will take care of update the position in specific situations
      this.enableEventListeners();
    }

    this.state.eventsEnabled = eventsEnabled;
  }

  // We can't use class properties because they don't get listed in the
  // class prototype and break stuff like Sinon stubs


  createClass(Popper, [{
    key: 'update',
    value: function update$$1() {
      return update.call(this);
    }
  }, {
    key: 'destroy',
    value: function destroy$$1() {
      return destroy.call(this);
    }
  }, {
    key: 'enableEventListeners',
    value: function enableEventListeners$$1() {
      return enableEventListeners.call(this);
    }
  }, {
    key: 'disableEventListeners',
    value: function disableEventListeners$$1() {
      return disableEventListeners.call(this);
    }

    /**
     * Schedules an update. It will run on the next UI update available.
     * @method scheduleUpdate
     * @memberof Popper
     */


    /**
     * Collection of utilities useful when writing custom modifiers.
     * Starting from version 1.7, this method is available only if you
     * include `popper-utils.js` before `popper.js`.
     *
     * **DEPRECATION**: This way to access PopperUtils is deprecated
     * and will be removed in v2! Use the PopperUtils module directly instead.
     * Due to the high instability of the methods contained in Utils, we can't
     * guarantee them to follow semver. Use them at your own risk!
     * @static
     * @private
     * @type {Object}
     * @deprecated since version 1.8
     * @member Utils
     * @memberof Popper
     */

  }]);
  return Popper;
}();

/**
 * The `referenceObject` is an object that provides an interface compatible with Popper.js
 * and lets you use it as replacement of a real DOM node.<br />
 * You can use this method to position a popper relatively to a set of coordinates
 * in case you don't have a DOM node to use as reference.
 *
 * ```
 * new Popper(referenceObject, popperNode);
 * ```
 *
 * NB: This feature isn't supported in Internet Explorer 10.
 * @name referenceObject
 * @property {Function} data.getBoundingClientRect
 * A function that returns a set of coordinates compatible with the native `getBoundingClientRect` method.
 * @property {number} data.clientWidth
 * An ES6 getter that will return the width of the virtual reference element.
 * @property {number} data.clientHeight
 * An ES6 getter that will return the height of the virtual reference element.
 */


Popper.Utils = (typeof window !== 'undefined' ? window : global).PopperUtils;
Popper.placements = placements;
Popper.Defaults = Defaults;

/* harmony default export */ __webpack_exports__["a"] = (Popper);
//# sourceMappingURL=popper.js.map

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(33)))

/***/ }),
/* 72 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(Hammer) {/*
* picasso-plugin-hammer v0.27.1
* Copyright (c) 2019 QlikTech International AB
* Released under the MIT license.
*/


/* global Hammer */
var translateKnownTypes = {
  click: 'Tap',
  Click: 'Tap',
  tap: 'Tap',
  pan: 'Pan',
  swipe: 'Swipe',
  rotate: 'Rotate',
  press: 'Press',
  pinch: 'Pinch'
};
/**
 * Helper function for translating typical non-hammer gesture to a hammer gesture. Currently only supporting 'click'
 * @param {String} type Gesture type
 * @private
 */

function getGestureType(type) {
  return translateKnownTypes[type] || type;
}
/**
 * Manages event handlers for HammerJS. Assumes Hammer is loaded and added to the global namespace
 */


function hammer(chart, mediator, element) {
  var settings;
  var instance;
  var mc;
  var key;
  var hammerGestures = [];
  var isOn = true;
  /**
   * Set default settings
   * @private
   */

  function setDefaultSettings(newSettings) {
    key = newSettings.key; //eslint-disable-line

    settings = newSettings;
    instance = {
      chart: chart,
      mediator: mediator,
      settings: settings
    };
    settings.gestures = settings.gestures || [];

    if (settings.enable === undefined) {
      settings.enable = true;
    }
  }
  /**
   * @private
   * add hammer recognizers based on settings
   */


  function addRecognizers() {
    if (typeof settings.enable === 'function') {
      settings.enable = settings.enable.bind(instance)();
    }

    if (!settings.enable) {
      return; // interaction is disabled
    }

    settings.gestures.forEach(function (gesture) {
      gesture.options = gesture.options || {}; // handle action enable

      if (gesture.options.enable === undefined) {
        gesture.options.enable = true;
      }

      if (typeof gesture.options.enable === 'function') {
        gesture.options.enable = gesture.options.enable.bind(instance);
      } // setup hammer gestures


      var type = getGestureType(gesture.type);

      if (Hammer && Hammer[type]) {
        gesture.options.event = gesture.options.event || gesture.type.toLowerCase();
        mc = mc || new Hammer.Manager(element);
        mc.add(new Hammer[type](gesture.options));
        Object.keys(gesture.events).forEach(function (eventName) {
          gesture.events[eventName] = gesture.events[eventName].bind(instance);
          mc.on(eventName, gesture.events[eventName]);
        });
        hammerGestures.push(gesture);
      }
    }); // setup mixing hammer gestures

    settings.gestures.forEach(function (gesture) {
      var type = getGestureType(gesture.type);

      if (Hammer && Hammer[type]) {
        if (gesture.recognizeWith) {
          mc.get(gesture.options.event).recognizeWith(gesture.recognizeWith.split(' ').filter(function (e) {
            return e !== '';
          }));
        }

        if (gesture.requireFailure) {
          mc.get(gesture.options.event).requireFailure(gesture.requireFailure.split(' ').filter(function (e) {
            return e !== '';
          }));
        }
      }
    });
  }
  /**
   * @private
   * removes all added hammer recognizers and native events
   */


  function removeAddedEvents() {
    // remove hammer recognizers and registered events
    hammerGestures.forEach(function (gesture) {
      Object.keys(gesture.events).forEach(function (eventName) {
        mc.off(eventName, gesture.events[eventName]);
      });
      mc.remove(gesture.options.event);
    });
    hammerGestures = [];
  }

  return {
    /**
     * Getter for the key.
     */
    get key() {
      return key;
    },

    /**
     * Updates this with new settings
     * @typedef settings
     * @type {object}
     * @property {string} [type] - The interaction type. Is 'hammer' for this component
     * @property {boolean|function} [enable] - Should the interaction be enabled or not.
     * This is only run when adding event handlers. In effect at startup, update or during on/off.
     * It does not run during every event loop.
     * @property {object} [events] - The keys in this object is the names of native events
     * that should be added to the chart element and they should all point to function which
     * will be the corresponding event handler.
     */
    set: function set(newSettings) {
      setDefaultSettings(newSettings);
      removeAddedEvents();

      if (isOn) {
        addRecognizers();
      }
    },

    /**
     * Turns off interactions
     */
    off: function off() {
      isOn = false;
      removeAddedEvents();
    },

    /**
     * Turns off interactions
     */
    on: function on() {
      isOn = true;

      if (hammerGestures.length === 0) {
        addRecognizers();
      }
    },

    /**
     * Destroys and unbinds all event handlers
     */
    destroy: function destroy() {
      removeAddedEvents();

      if (mc) {
        mc.destroy();
      }

      mc = null;
      instance = null;
      settings = null;
    }
  };
}

function initialize(picasso) {
  picasso.interaction('hammer', hammer);
}

/* harmony default export */ __webpack_exports__["a"] = (initialize);
//# sourceMappingURL=picasso-hammer.esm.js.map

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(64)))

/***/ }),
/* 73 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/*
* picasso-plugin-q v0.27.1
* Copyright (c) 2019 QlikTech International AB
* Released under the MIT license.
*/


function _typeof(obj) {
  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof = function (obj) {
      return typeof obj;
    };
  } else {
    _typeof = function (obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
  }

  return _typeof(obj);
}

function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a 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);
  }
}

function _createClass(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties(Constructor, staticProps);
  return Constructor;
}

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function ownKeys(object, enumerableOnly) {
  var keys = Object.keys(object);

  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) symbols = symbols.filter(function (sym) {
      return Object.getOwnPropertyDescriptor(object, sym).enumerable;
    });
    keys.push.apply(keys, symbols);
  }

  return keys;
}

function _objectSpread2(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i] != null ? arguments[i] : {};

    if (i % 2) {
      ownKeys(source, true).forEach(function (key) {
        _defineProperty(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys(source).forEach(function (key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
      });
    }
  }

  return target;
}

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 _slicedToArray(arr, i) {
  return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}

function _toConsumableArray(arr) {
  return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}

function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) {
    for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];

    return arr2;
  }
}

function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}

function _iterableToArray(iter) {
  if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}

function _iterableToArrayLimit(arr, i) {
  if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
    return;
  }

  var _arr = [];
  var _n = true;
  var _d = false;
  var _e = undefined;

  try {
    for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);

      if (i && _arr.length === i) break;
    }
  } catch (err) {
    _d = true;
    _e = err;
  } finally {
    try {
      if (!_n && _i["return"] != null) _i["return"]();
    } finally {
      if (_d) throw _e;
    }
  }

  return _arr;
}

function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance");
}

function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance");
}

var hasOwn = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var defineProperty = Object.defineProperty;
var gOPD = Object.getOwnPropertyDescriptor;

var isArray = function isArray(arr) {
	if (typeof Array.isArray === 'function') {
		return Array.isArray(arr);
	}

	return toStr.call(arr) === '[object Array]';
};

var isPlainObject = function isPlainObject(obj) {
	if (!obj || toStr.call(obj) !== '[object Object]') {
		return false;
	}

	var hasOwnConstructor = hasOwn.call(obj, 'constructor');
	var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
	// Not own constructor property must be Object
	if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
		return false;
	}

	// Own properties are enumerated firstly, so to speed up,
	// if last one is own, then all properties are own.
	var key;
	for (key in obj) { /**/ }

	return typeof key === 'undefined' || hasOwn.call(obj, key);
};

// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target
var setProperty = function setProperty(target, options) {
	if (defineProperty && options.name === '__proto__') {
		defineProperty(target, options.name, {
			enumerable: true,
			configurable: true,
			value: options.newValue,
			writable: true
		});
	} else {
		target[options.name] = options.newValue;
	}
};

// Return undefined instead of __proto__ if '__proto__' is not an own property
var getProperty = function getProperty(obj, name) {
	if (name === '__proto__') {
		if (!hasOwn.call(obj, name)) {
			return void 0;
		} else if (gOPD) {
			// In early versions of node, obj['__proto__'] is buggy when obj has
			// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
			return gOPD(obj, name).value;
		}
	}

	return obj[name];
};

var extend = function extend() {
	var options, name, src, copy, copyIsArray, clone;
	var target = arguments[0];
	var i = 1;
	var length = arguments.length;
	var deep = false;

	// Handle a deep copy situation
	if (typeof target === 'boolean') {
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		i = 2;
	}
	if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
		target = {};
	}

	for (; i < length; ++i) {
		options = arguments[i];
		// Only deal with non-null/undefined values
		if (options != null) {
			// Extend the base object
			for (name in options) {
				src = getProperty(target, name);
				copy = getProperty(options, name);

				// Prevent never-ending loop
				if (target !== copy) {
					// Recurse if we're merging plain objects or arrays
					if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
						if (copyIsArray) {
							copyIsArray = false;
							clone = src && isArray(src) ? src : [];
						} else {
							clone = src && isPlainObject(src) ? src : {};
						}

						// Never move original objects, clone them
						setProperty(target, { name: name, newValue: extend(deep, clone, copy) });

					// Don't bring in undefined values
					} else if (typeof copy !== 'undefined') {
						setProperty(target, { name: name, newValue: copy });
					}
				}
			}
		}
	}

	// Return the modified object
	return target;
};

function getFieldAccessor(field, page, deps) {
  if (!field) {
    return -1;
  }

  var cache = deps.cache;
  var origin = field.origin ? field.origin() : null;

  if (origin) {
    field = origin;
  }

  var fieldIdx = cache.fields.indexOf(field);
  var attrIdx = -1;
  var attrDimIdx = -1;

  if (fieldIdx === -1) {
    for (var i = 0; i < cache.wrappedFields.length; i++) {
      attrDimIdx = cache.wrappedFields[i].attrDims.map(function (v) {
        return v.instance;
      }).indexOf(field);
      attrIdx = cache.wrappedFields[i].attrExps.map(function (v) {
        return v.instance;
      }).indexOf(field);

      if (attrDimIdx !== -1 || attrIdx !== -1) {
        fieldIdx = i;
        break;
      }
    }
  }

  fieldIdx -= page.qArea.qLeft;

  if (fieldIdx < 0 || fieldIdx >= page.qArea.qWidth) {
    // throw new Error('Field out of range');
    return -1;
  }

  if (attrDimIdx >= 0) {
    return function (row) {
      return row[fieldIdx].qAttrDims.qValues[attrDimIdx];
    };
  }

  if (attrIdx >= 0) {
    return function (row) {
      return row[fieldIdx].qAttrExps.qValues[attrIdx];
    };
  }

  return function (row) {
    return row[fieldIdx];
  };
} // TODO - handle 'other' value
// const specialTextValues = {
//   '-3': (meta) => {
//     if ('othersLabel' in meta) {
//       return meta.othersLabel;
//     }
//     return '';
//   }
// };

function datumExtract(propCfg, cell, _ref) {
  var key = _ref.key;
  var datum = {
    value: typeof propCfg.value === 'function' ? propCfg.value(cell) : typeof propCfg.value !== 'undefined' ? propCfg.value : cell // eslint-disable-line no-nested-ternary

  };
  datum.label = typeof propCfg.label === 'function' ? propCfg.label(cell) : typeof propCfg.label !== 'undefined' ? String(propCfg.label) : String(datum.value); // eslint-disable-line no-nested-ternary

  if (propCfg.field) {
    datum.source = {
      key: key,
      field: propCfg.field.key()
    };
  }

  return datum;
}

function cellToValue(_ref2) {
  var cache = _ref2.cache,
      f = _ref2.f,
      mainCell = _ref2.mainCell,
      p = _ref2.p,
      prop = _ref2.prop,
      page = _ref2.page,
      rowIdx = _ref2.rowIdx,
      row = _ref2.row,
      sourceKey = _ref2.sourceKey,
      target = _ref2.target,
      targetProp = _ref2.targetProp;
  var propCell = mainCell;

  if (p.field && p.field !== f) {
    var propCellFn = getFieldAccessor(p.field, page, {
      cache: cache
    });

    if (propCellFn === -1) {
      return;
    }

    propCell = extend({
      qRow: rowIdx
    }, propCellFn(row));
  }

  target[targetProp] = datumExtract(p, propCell, {
    key: sourceKey
  });
}

function extract(config, dataset, cache, util) {
  var cfgs = Array.isArray(config) ? config : [config];
  var dataItems = [];

  for (var i = 0; i < cfgs.length; i++) {
    if (typeof cfgs[i].field !== 'undefined') {
      var cube = dataset.raw();
      var sourceKey = dataset.key();
      var f = _typeof(cfgs[i].field) === 'object' ? cfgs[i].field : dataset.field(cfgs[i].field);

      var _util$normalizeConfig = util.normalizeConfig(cfgs[i], dataset),
          props = _util$normalizeConfig.props,
          main = _util$normalizeConfig.main;

      var propsArr = Object.keys(props);
      var track = !!cfgs[i].trackBy;

      var trackType = _typeof(cfgs[i].trackBy);

      var tracker = {};
      var trackedItems = [];
      var items = [];

      for (var j = 0; j < cube.qDataPages.length; j++) {
        var fn = getFieldAccessor(f, cube.qDataPages[j], {
          cache: cache
        });

        if (fn === -1) {
          continue;
        }

        for (var k = 0; k < cube.qDataPages[j].qMatrix.length; k++) {
          var rowIdx = cube.qDataPages[j].qArea.qTop + k;
          var mainCell = extend({
            qRow: rowIdx
          }, fn(cube.qDataPages[j].qMatrix[k]));
          var ret = datumExtract(main, mainCell, {
            key: sourceKey
          });
          var exclude = main.filter && !main.filter(mainCell);

          if (exclude) {
            continue;
          }

          for (var l = 0; l < propsArr.length; l++) {
            var p = props[propsArr[l]];
            var arr = p.fields || [p];

            if (p.fields) {
              ret[propsArr[l]] = [];
            } // loop through all props that need to be mapped and
            // assign 'value' and 'source' to each property


            for (var m = 0; m < arr.length; m++) {
              cellToValue({
                cache: cache,
                f: f,
                mainCell: mainCell,
                p: arr[m],
                prop: propsArr[l],
                props: props,
                page: cube.qDataPages[j],
                rowIdx: rowIdx,
                row: cube.qDataPages[j].qMatrix[k],
                sourceKey: sourceKey,
                target: p.fields ? ret[propsArr[l]] : ret,
                targetProp: p.fields ? m : propsArr[l]
              });
            }

            if (p.fields) {
              var fieldValues = ret[propsArr[l]].map(function (v) {
                return v.value;
              });
              var fieldLabels = ret[propsArr[l]].map(function (v) {
                return v.label;
              });
              ret[propsArr[l]] = {
                value: typeof p.value === 'function' ? p.value(fieldValues) : typeof p.value !== 'undefined' ? p.value : fieldValues,
                label: typeof p.label === 'function' ? p.label(fieldLabels) : typeof p.label !== 'undefined' ? String(p.label) : String(ret[propsArr[l]].value)
              };
            }
          } // collect items based on the trackBy value
          // items with the same trackBy value are placed in an array and reduced later


          if (track) {
            util.track({
              cfg: cfgs[i],
              itemData: mainCell,
              obj: ret,
              target: trackedItems,
              tracker: tracker,
              trackType: trackType
            });
          }

          items.push(ret);
        }
      } // reduce if items have been grouped


      if (track) {
        dataItems.push.apply(dataItems, _toConsumableArray(util.collect(trackedItems, {
          main: main,
          propsArr: propsArr,
          props: props
        })));
      } else {
        dataItems.push.apply(dataItems, items);
      }
    }
  }

  return dataItems;
}

function count(node) {
  var sum = 0,
      children = node.children,
      i = children && children.length;
  if (!i) sum = 1;
  else while (--i >= 0) sum += children[i].value;
  node.value = sum;
}

function node_count() {
  return this.eachAfter(count);
}

function node_each(callback) {
  var node = this, current, next = [node], children, i, n;
  do {
    current = next.reverse(), next = [];
    while (node = current.pop()) {
      callback(node), children = node.children;
      if (children) for (i = 0, n = children.length; i < n; ++i) {
        next.push(children[i]);
      }
    }
  } while (next.length);
  return this;
}

function node_eachBefore(callback) {
  var node = this, nodes = [node], children, i;
  while (node = nodes.pop()) {
    callback(node), children = node.children;
    if (children) for (i = children.length - 1; i >= 0; --i) {
      nodes.push(children[i]);
    }
  }
  return this;
}

function node_eachAfter(callback) {
  var node = this, nodes = [node], next = [], children, i, n;
  while (node = nodes.pop()) {
    next.push(node), children = node.children;
    if (children) for (i = 0, n = children.length; i < n; ++i) {
      nodes.push(children[i]);
    }
  }
  while (node = next.pop()) {
    callback(node);
  }
  return this;
}

function node_sum(value) {
  return this.eachAfter(function(node) {
    var sum = +value(node.data) || 0,
        children = node.children,
        i = children && children.length;
    while (--i >= 0) sum += children[i].value;
    node.value = sum;
  });
}

function node_sort(compare) {
  return this.eachBefore(function(node) {
    if (node.children) {
      node.children.sort(compare);
    }
  });
}

function node_path(end) {
  var start = this,
      ancestor = leastCommonAncestor(start, end),
      nodes = [start];
  while (start !== ancestor) {
    start = start.parent;
    nodes.push(start);
  }
  var k = nodes.length;
  while (end !== ancestor) {
    nodes.splice(k, 0, end);
    end = end.parent;
  }
  return nodes;
}

function leastCommonAncestor(a, b) {
  if (a === b) return a;
  var aNodes = a.ancestors(),
      bNodes = b.ancestors(),
      c = null;
  a = aNodes.pop();
  b = bNodes.pop();
  while (a === b) {
    c = a;
    a = aNodes.pop();
    b = bNodes.pop();
  }
  return c;
}

function node_ancestors() {
  var node = this, nodes = [node];
  while (node = node.parent) {
    nodes.push(node);
  }
  return nodes;
}

function node_descendants() {
  var nodes = [];
  this.each(function(node) {
    nodes.push(node);
  });
  return nodes;
}

function node_leaves() {
  var leaves = [];
  this.eachBefore(function(node) {
    if (!node.children) {
      leaves.push(node);
    }
  });
  return leaves;
}

function node_links() {
  var root = this, links = [];
  root.each(function(node) {
    if (node !== root) { // Don’t include the root’s parent, if any.
      links.push({source: node.parent, target: node});
    }
  });
  return links;
}

function hierarchy(data, children) {
  var root = new Node(data),
      valued = +data.value && (root.value = data.value),
      node,
      nodes = [root],
      child,
      childs,
      i,
      n;

  if (children == null) children = defaultChildren;

  while (node = nodes.pop()) {
    if (valued) node.value = +node.data.value;
    if ((childs = children(node.data)) && (n = childs.length)) {
      node.children = new Array(n);
      for (i = n - 1; i >= 0; --i) {
        nodes.push(child = node.children[i] = new Node(childs[i]));
        child.parent = node;
        child.depth = node.depth + 1;
      }
    }
  }

  return root.eachBefore(computeHeight);
}

function node_copy() {
  return hierarchy(this).eachBefore(copyData);
}

function defaultChildren(d) {
  return d.children;
}

function copyData(node) {
  node.data = node.data.data;
}

function computeHeight(node) {
  var height = 0;
  do node.height = height;
  while ((node = node.parent) && (node.height < ++height));
}

function Node(data) {
  this.data = data;
  this.depth =
  this.height = 0;
  this.parent = null;
}

Node.prototype = hierarchy.prototype = {
  constructor: Node,
  count: node_count,
  each: node_each,
  eachAfter: node_eachAfter,
  eachBefore: node_eachBefore,
  sum: node_sum,
  sort: node_sort,
  path: node_path,
  ancestors: node_ancestors,
  descendants: node_descendants,
  leaves: node_leaves,
  links: node_links,
  copy: node_copy
};

function required(f) {
  if (typeof f !== "function") throw new Error;
  return f;
}

var keyPrefix = "$", // Protect against keys like “__proto__”.
    preroot = {depth: -1},
    ambiguous = {};

function defaultId(d) {
  return d.id;
}

function defaultParentId(d) {
  return d.parentId;
}

function stratify() {
  var id = defaultId,
      parentId = defaultParentId;

  function stratify(data) {
    var d,
        i,
        n = data.length,
        root,
        parent,
        node,
        nodes = new Array(n),
        nodeId,
        nodeKey,
        nodeByKey = {};

    for (i = 0; i < n; ++i) {
      d = data[i], node = nodes[i] = new Node(d);
      if ((nodeId = id(d, i, data)) != null && (nodeId += "")) {
        nodeKey = keyPrefix + (node.id = nodeId);
        nodeByKey[nodeKey] = nodeKey in nodeByKey ? ambiguous : node;
      }
    }

    for (i = 0; i < n; ++i) {
      node = nodes[i], nodeId = parentId(data[i], i, data);
      if (nodeId == null || !(nodeId += "")) {
        if (root) throw new Error("multiple roots");
        root = node;
      } else {
        parent = nodeByKey[keyPrefix + nodeId];
        if (!parent) throw new Error("missing: " + nodeId);
        if (parent === ambiguous) throw new Error("ambiguous: " + nodeId);
        if (parent.children) parent.children.push(node);
        else parent.children = [node];
        node.parent = parent;
      }
    }

    if (!root) throw new Error("no root");
    root.parent = preroot;
    root.eachBefore(function(node) { node.depth = node.parent.depth + 1; --n; }).eachBefore(computeHeight);
    root.parent = null;
    if (n > 0) throw new Error("cycle");

    return root;
  }

  stratify.id = function(x) {
    return arguments.length ? (id = required(x), stratify) : id;
  };

  stratify.parentId = function(x) {
    return arguments.length ? (parentId = required(x), stratify) : parentId;
  };

  return stratify;
}

/**
 * Resolves the value at the given JSON path
 * @private
 * @param  {String} path [description]
 * @param  {Object} obj  [description]
 * @return {Object}      [description]
 *
 * @example
 * let path = "/path/to/paradise";
 * let obj = {
 *   path: {
 *     to: { paradise: "heaven"},
 *     from: {...}
 *   }
 * };
 * resolve( path, obj ); // "heaven"
 */
function resolve(path, obj) {
  if (path.charAt(0) === '/') {
    path = path.substring(1);
  }

  var arr = path.split('/');
  var subpath;
  var container = obj;

  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === '*' && Array.isArray(container)) {
      var carr = [];
      subpath = arr.slice(i + 1).join('/');

      for (var c = 0; c < container.length; c++) {
        var v = resolve(subpath, container[c]); // v.forEach(_ => _._parent = container[c]);

        if (Array.isArray(v)) {
          carr.push.apply(carr, _toConsumableArray(v));
        } else {
          carr.push(v);
        }
      }

      return carr; // return container.map(v => resolve(arr.slice(i + 1).join('/'), v));
    }

    if (!arr[i] && Array.isArray(container)) {
      var _carr = new Array(container.length);

      subpath = arr.slice(i + 1).join('/');

      for (var _c = 0; _c < container.length; _c++) {
        _carr[_c] = resolve(subpath, container[_c]);
      }

      return _carr; // return container.map(v => resolve(arr.slice(i + 1).join('/'), v));
    }

    if (arr[i] in container) {
      container = container[arr[i]];
    }
  }

  return container;
}

function flattenTree(children, steps, arrIndexAtTargetDepth) {
  var arr = [];

  if (!children || !children.length) {
    return arr;
  }

  if (steps <= 0) {
    var nodes = arrIndexAtTargetDepth >= 0 ? [children[arrIndexAtTargetDepth]] : children;
    arr.push.apply(arr, _toConsumableArray(nodes));
  } else {
    for (var i = 0; i < children.length; i++) {
      if (children[i].children && children[i].children.length) {
        arr.push.apply(arr, _toConsumableArray(flattenTree(children[i].children, steps - 1, arrIndexAtTargetDepth)));
      }
    }
  }

  return arr;
}

function treeAccessor(sourceDepth, targetDepth, arrIndexAtTargetDepth) {
  if (sourceDepth === targetDepth) {
    return function (d) {
      return d;
    };
  }

  if (sourceDepth > targetDepth) {
    // traverse upwards
    var steps = Math.max(0, Math.min(100, sourceDepth - targetDepth));

    var path = _toConsumableArray(Array(steps)).map(String.prototype.valueOf, 'parent').join('.');

    return Function('node', "return node.".concat(path, ";")); // eslint-disable-line no-new-func
  }

  if (targetDepth > sourceDepth) {
    // flatten descendants
    var _steps = Math.max(0, Math.min(100, targetDepth - sourceDepth));

    return function (node) {
      return flattenTree(node.children, _steps - 1, arrIndexAtTargetDepth);
    };
  }

  return false;
}
function findField(query, _ref) {
  var cache = _ref.cache;

  if (typeof query === 'number') {
    return cache.fields[query];
  }

  var allFields = cache.allFields;

  if (typeof query === 'function') {
    for (var i = 0; i < allFields.length; i++) {
      if (query(allFields[i])) {
        return allFields[i];
      }
    }

    return false;
  }

  if (typeof query === 'string') {
    for (var _i = 0; _i < allFields.length; _i++) {
      if (allFields[_i].key() === query || allFields[_i].title() === query) {
        return allFields[_i];
      }
    }
  } else if (query && allFields.indexOf(query) !== -1) {
    // assume 'query' is a field instance
    return query;
  }

  throw Error("Field not found: ".concat(query));
}

var DIM_RX = /^qDimensionInfo(?:\/(\d+))?/;
var M_RX = /^\/?qMeasureInfo\/(\d+)/;
var ATTR_EXPR_RX = /\/qAttrExprInfo\/(\d+)/;
var ATTR_DIM_RX = /\/qAttrDimInfo\/(\d+)/;

function getColumnOrder(dataset) {
  var qColumnOrder = dataset.raw().qColumnOrder;
  var fields = dataset.fields();
  return qColumnOrder && qColumnOrder.length === fields.length ? qColumnOrder : fields.map(function (f, i) {
    return i;
  });
}

function getDimensionColumnOrder(cube) {
  var order = cube.qColumnOrder && cube.qColumnOrder.length ? cube.qColumnOrder : cube.qDimensionInfo.map(function (d, ii) {
    return ii;
  });
  return order.filter(function (ii) {
    return ii < cube.qDimensionInfo.length;
  });
}

function getFieldDepth(field, _ref) {
  var cube = _ref.cube;

  if (!field) {
    return -1;
  }

  var key = field.origin && field.origin() ? field.origin().key() : field.key();
  var isFieldDimension = false;
  var fieldIdx = -1; // cache.fields.indexOf(field);

  var attrIdx = -1;
  var attrDimIdx = -1;
  var fieldDepth = -1;
  var pseudoMeasureIndex = -1;
  var measureIdx = -1;
  var remainder = key;
  var treeOrder = cube.qEffectiveInterColumnSortOrder;
  var columnOrder = getDimensionColumnOrder(cube);

  if (DIM_RX.test(remainder)) {
    isFieldDimension = true;
    fieldIdx = +DIM_RX.exec(remainder)[1];
    remainder = key.replace(DIM_RX, '');
  }

  if (M_RX.test(remainder)) {
    if (cube.qMode === 'K') {
      pseudoMeasureIndex = +M_RX.exec(remainder)[1];
    } else if (treeOrder && treeOrder.indexOf(-1) !== -1) {
      pseudoMeasureIndex = +M_RX.exec(remainder)[1];
      measureIdx = 0;
    } else {
      measureIdx = +M_RX.exec(remainder)[1];
    }

    remainder = remainder.replace(M_RX, '');
  }

  if (remainder) {
    if (ATTR_DIM_RX.exec(remainder)) {
      attrDimIdx = +ATTR_DIM_RX.exec(remainder)[1];
    } else if (ATTR_EXPR_RX.exec(remainder)) {
      attrIdx = +ATTR_EXPR_RX.exec(remainder)[1];
    }
  }

  if (isFieldDimension) {
    if (cube.qMode === 'S') {
      fieldDepth = columnOrder[fieldIdx];
    } else {
      fieldDepth = treeOrder ? treeOrder.indexOf(fieldIdx) : fieldIdx;
    }
  } else if (treeOrder && treeOrder.indexOf(-1) !== -1) {
    // if pseudo dimension exists in sort order
    fieldDepth = treeOrder.indexOf(-1); // depth of pesudodimension
  } else {
    // assume measure is at the bottom of the tree
    fieldDepth = cube.qDimensionInfo.length - (cube.qMode === 'K' ? 0 : 1);
  }

  return {
    fieldDepth: fieldDepth + 1,
    // +1 due to root node
    pseudoMeasureIndex: pseudoMeasureIndex,
    measureIdx: measureIdx,
    attrDimIdx: attrDimIdx,
    attrIdx: attrIdx
  };
}

function getFieldAccessor$1(sourceDepthObject, targetDepthObject) {
  var nodeFn = treeAccessor(sourceDepthObject.fieldDepth, targetDepthObject.fieldDepth, targetDepthObject.pseudoMeasureIndex);
  var valueFn;

  if (targetDepthObject.measureIdx >= 0) {
    valueFn = function valueFn(node) {
      return node.data.qValues[targetDepthObject.measureIdx];
    };
  } else {
    valueFn = function valueFn(node) {
      return node.data;
    };
  }

  var attrFn;

  if (targetDepthObject.attrDimIdx >= 0) {
    attrFn = function attrFn(data) {
      return data.qAttrDims.qValues[targetDepthObject.attrDimIdx];
    };
  } else if (targetDepthObject.attrIdx >= 0) {
    attrFn = function attrFn(data) {
      return data.qAttrExps.qValues[targetDepthObject.attrIdx];
    };
  }

  return {
    nodeFn: nodeFn,
    attrFn: attrFn,
    valueFn: valueFn
  };
}

function datumExtract$1(propCfg, cell, _ref2) {
  var key = _ref2.key;
  var datum = {
    value: typeof propCfg.value === 'function' ? propCfg.value(cell) : typeof propCfg.value !== 'undefined' ? propCfg.value : cell // eslint-disable-line no-nested-ternary

  };
  datum.label = typeof propCfg.label === 'function' ? propCfg.label(cell) : typeof propCfg.label !== 'undefined' ? String(propCfg.label) : String(datum.value); // eslint-disable-line no-nested-ternary

  if (propCfg.field) {
    datum.source = {
      key: key,
      field: propCfg.field.key()
    };
  }

  return datum;
}

function doIt(_ref3) {
  var propsArr = _ref3.propsArr,
      props = _ref3.props,
      item = _ref3.item,
      itemData = _ref3.itemData,
      ret = _ref3.ret,
      sourceKey = _ref3.sourceKey;

  for (var i = 0; i < propsArr.length; i++) {
    var pCfg = props[propsArr[i]];
    var arr = pCfg.fields || [pCfg];
    var coll = void 0;
    var collStr = void 0;

    if (pCfg.fields) {
      coll = [];
      collStr = [];
    }

    var _loop = function _loop(j) {
      var p = arr[j];
      var fn = void 0;
      var str = void 0;
      var value = void 0;
      var nodes = void 0;
      var cells = void 0;
      var label = void 0;

      if (p.type === 'primitive') {
        value = p.value;
        label = String(p.value);
      } else {
        if (typeof p.value === 'function') {
          fn = function fn(v) {
            return p.value(v, item);
          };
        }

        if (typeof p.label === 'function') {
          str = function str(v) {
            return p.label(v, item);
          };
        }

        if (p.accessor) {
          nodes = p.accessor(item);

          if (Array.isArray(nodes)) {
            // propably descendants
            cells = nodes.map(p.valueAccessor);

            if (p.attrAccessor) {
              cells = cells.map(p.attrAccessor);
            }

            if (fn) {
              value = cells.map(fn);
              fn = null;
            }

            if (str) {
              label = cells.map(str);
              str = null;
            }

            value = p.reduce ? p.reduce(value) : value;
            label = p.reduceLabel ? p.reduceLabel(label, value) : String(value);
          } else {
            value = p.attrAccessor ? p.attrAccessor(p.valueAccessor(nodes)) : p.valueAccessor(nodes);
            label = value;
          }
        } else {
          value = itemData;
          label = itemData;
        }
      }

      if (pCfg.fields) {
        var v = fn ? fn(value) : value;
        coll.push(v);
        collStr.push(str && label != null ? str(label) : label != null ? label : String(v));
      } else {
        var _v = fn ? fn(value) : value;

        ret[propsArr[i]] = {
          value: _v,
          label: str ? str(label) : label != null ? label : String(_v)
        };

        if (p.field) {
          ret[propsArr[i]].source = {
            field: p.field.key(),
            key: sourceKey
          };
        }
      }
    };

    for (var j = 0; j < arr.length; j++) {
      _loop(j);
    }

    if (coll) {
      ret[propsArr[i]] = {
        value: typeof pCfg.value === 'function' ? pCfg.value(coll, item) : coll,
        label: typeof pCfg.label === 'function' ? pCfg.label(collStr, item) : collStr
      };
    }
  }
}

var getHierarchy = function getHierarchy(cube, cache, config) {
  var rootPath = cube.qMode === 'K' ? '/qStackedDataPages/*/qData' : '/qTreeDataPages/*';
  var childNodes = cube.qMode === 'K' ? 'qSubNodes' : 'qNodes';
  var root = resolve(rootPath, cube);

  if (!root || !root[0]) {
    return null;
  }

  cache.tree = hierarchy(root[0], config.children || function (node) {
    return node[childNodes];
  });
  return cache.tree;
};

function getHierarchyForSMode(dataset) {
  var matrix = dataset.raw().qDataPages.length ? dataset.raw().qDataPages[0].qMatrix : [];
  var order = getColumnOrder(dataset);
  var fields = dataset.fields();
  var dimensions = dataset.fields().filter(function (f) {
    return f.type() === 'dimension';
  }).map(function (f) {
    return order.indexOf(fields.indexOf(f));
  });
  var measures = dataset.fields().filter(function (f) {
    return f.type() === 'measure';
  }).map(function (f) {
    return order.indexOf(fields.indexOf(f));
  });
  var root = {
    __id: '__root',
    qValues: []
  };
  var keys = {
    __root: root
  };

  for (var r = 0; r < matrix.length; r++) {
    var row = matrix[r];
    var id = '__root'; // let parent = root;

    var isNew = false;

    for (var c = 0; c < dimensions.length; c++) {
      var cell = row[dimensions[c]];
      var key = "".concat(id, "__").concat(cell.qText);

      if (!keys[key]) {
        keys[key] = _objectSpread2({
          __id: key,
          __parent: id,
          qValues: []
        }, cell);
        isNew = true;
      }

      id = key;
    }

    if (isNew) {
      for (var _c = 0; _c < measures.length; _c++) {
        var _cell = row[measures[_c]];
        keys[id].qValues.push(_cell);
      }
    }
  }

  var nodes = Object.keys(keys).map(function (key) {
    return keys[key];
  });
  var h = stratify().id(function (d) {
    return d.__id;
  }).parentId(function (d) {
    return d.__parent;
  })(nodes);
  return h;
}

var attachPropsAccessors = function attachPropsAccessors(_ref4) {
  var propsArr = _ref4.propsArr,
      props = _ref4.props,
      cube = _ref4.cube,
      cache = _ref4.cache,
      itemDepthObject = _ref4.itemDepthObject,
      f = _ref4.f;

  for (var i = 0; i < propsArr.length; i++) {
    var pCfg = props[propsArr[i]];
    var arr = pCfg.fields ? pCfg.fields : [pCfg];

    for (var j = 0; j < arr.length; j++) {
      var p = arr[j];

      if (p.field !== f) {
        var depthObject = getFieldDepth(p.field, {
          cube: cube,
          cache: cache
        });
        var accessors = getFieldAccessor$1(itemDepthObject, depthObject);
        p.accessor = accessors.nodeFn; // nodes accessor

        p.valueAccessor = accessors.valueFn; // cell accessor

        p.attrAccessor = accessors.attrFn; // attr cell accessor
      }
    }
  }
};

function augment() {
  var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var dataset = arguments.length > 1 ? arguments[1] : undefined;
  var cache = arguments.length > 2 ? arguments[2] : undefined;
  var util = arguments.length > 3 ? arguments[3] : undefined;
  var cube = dataset.raw();
  var sourceKey = dataset.key();
  var h = cube.qMode === 'S' ? getHierarchyForSMode(dataset) : getHierarchy(cube, cache, config);

  if (!h) {
    return null;
  }

  var height = h.height;
  var propDefs = [];

  for (var i = 0; i <= height; i++) {
    var f = null;

    if (i > 0) {
      if (cube.qMode === 'S') {
        var order = getDimensionColumnOrder(cube);
        var idx = order[i - 1];
        f = cache.fields[idx];
      } else {
        var _idx = cube.qEffectiveInterColumnSortOrder[i - 1]; // if (idx === -1) { // pseudo
        //   let childIdx = node.parent.children.indexOf(node);
        //   idx = cube.qDimensionInfo.length + childIdx; // measure field
        // }

        if (i > cube.qEffectiveInterColumnSortOrder.length) {
          _idx = cube.qDimensionInfo.length;
        }

        f = cache.fields[_idx];
      }
    }

    var _util$normalizeConfig = util.normalizeConfig(_objectSpread2({}, config, {
      field: f ? f.key() : undefined
    }), dataset),
        props = _util$normalizeConfig.props,
        main = _util$normalizeConfig.main;

    var propsArr = Object.keys(props);
    propDefs[i] = {
      propsArr: propsArr,
      props: props,
      main: main
    };
    var itemDepthObject = f ? getFieldDepth(f, {
      cube: cube,
      cache: cache
    }) : {
      fieldDepth: 0
    };
    attachPropsAccessors({
      propsArr: propsArr,
      props: props,
      cube: cube,
      cache: cache,
      itemDepthObject: itemDepthObject,
      f: f
    });
  }

  var replica = h.copy();
  var replicaDescendants = replica.descendants();
  var descendants = h.descendants();

  for (var _i = 0; _i < descendants.length; _i++) {
    var _propsArr = propDefs[descendants[_i].depth].propsArr;
    var props = propDefs[descendants[_i].depth].props;
    var main = propDefs[descendants[_i].depth].main;
    var item = replicaDescendants[_i];
    var itemData = item.data; // main.valueAccessor(currentOriginal);

    var ret = datumExtract$1(main, itemData, {
      key: sourceKey
    });
    doIt({
      propsArr: _propsArr,
      props: props,
      item: item,
      itemData: itemData,
      ret: ret,
      sourceKey: sourceKey,
      isTree: true
    });
    descendants[_i].data = ret;
  }

  return h;
}
function extract$1(config, dataset, cache, util) {
  var cfgs = Array.isArray(config) ? config : [config];
  var dataItems = [];

  for (var g = 0; g < cfgs.length; g++) {
    if (typeof cfgs[g].field !== 'undefined') {
      var cube = dataset.raw();
      var sourceKey = dataset.key();
      var h = getHierarchy(cube, cache, config);

      if (!h) {
        continue;
      }

      var f = _typeof(cfgs[g].field) === 'object' ? cfgs[g].field : dataset.field(cfgs[g].field);

      var _util$normalizeConfig2 = util.normalizeConfig(cfgs[g], dataset),
          props = _util$normalizeConfig2.props,
          main = _util$normalizeConfig2.main;

      var propsArr = Object.keys(props);
      var itemDepthObject = getFieldDepth(f, {
        cube: cube,
        cache: cache
      });

      var _getFieldAccessor = getFieldAccessor$1({
        fieldDepth: 0
      }, itemDepthObject),
          nodeFn = _getFieldAccessor.nodeFn,
          attrFn = _getFieldAccessor.attrFn,
          valueFn = _getFieldAccessor.valueFn;

      attachPropsAccessors({
        propsArr: propsArr,
        props: props,
        cube: cube,
        cache: cache,
        itemDepthObject: itemDepthObject,
        f: f
      });
      var track = !!cfgs[g].trackBy;

      var trackType = _typeof(cfgs[g].trackBy);

      var tracker = {};
      var trackedItems = [];
      var items = nodeFn(cache.tree);
      var mapped = [];

      for (var i = 0; i < items.length; i++) {
        var item = items[i];
        var itemData = attrFn ? attrFn(valueFn(item)) : valueFn(item);
        var exclude = main.filter && !main.filter(itemData);

        if (exclude) {
          continue;
        }

        var ret = datumExtract$1(main, itemData, {
          key: sourceKey
        });
        doIt({
          propsArr: propsArr,
          props: props,
          item: item,
          itemData: itemData,
          ret: ret,
          sourceKey: sourceKey
        }); // collect items based on the trackBy value
        // items with the same trackBy value are placed in an array and reduced later

        if (track) {
          util.track({
            cfg: cfgs[g],
            itemData: itemData,
            obj: ret,
            target: trackedItems,
            tracker: tracker,
            trackType: trackType
          });
        }

        mapped.push(ret);
      } // reduce if items have been grouped


      if (track) {
        dataItems.push.apply(dataItems, _toConsumableArray(util.collect(trackedItems, {
          main: main,
          propsArr: propsArr,
          props: props
        })));
      } else {
        dataItems.push.apply(dataItems, mapped);
      }
    }
  }

  return dataItems;
}

var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

function createCommonjsModule(fn, module) {
	return module = { exports: {} }, fn(module, module.exports), module.exports;
}

var format_min = createCommonjsModule(function (module) {
/*! javascript-number-formatter - v1.1.11 - http://mottie.github.com/javascript-number-formatter/ * © ecava */
!function(a,b){module.exports=b();}(commonjsGlobal,function(){return function(a,b){if(!a||isNaN(+b))return b;var c,d,e,f,g,h,i,j,k,l,m=a.length,n=a.search(/[0-9\-\+#]/),o=n>0?a.substring(0,n):"",p=a.split("").reverse().join(""),q=p.search(/[0-9\-\+#]/),r=m-q,s=a.substring(r,r+1),t=r+("."===s||","===s?1:0),u=q>0?a.substring(t,m):"";if(a=a.substring(n,t),b="-"===a.charAt(0)?-b:+b,c=b<0?b=-b:0,d=a.match(/[^\d\-\+#]/g),e=d&&d[d.length-1]||".",f=d&&d[1]&&d[0]||",",a=a.split(e),b=b.toFixed(a[1]&&a[1].length),b=+b+"",h=a[1]&&a[1].lastIndexOf("0"),j=b.split("."),(!j[1]||j[1]&&j[1].length<=h)&&(b=(+b).toFixed(h+1)),k=a[0].split(f),a[0]=k.join(""),g=a[0]&&a[0].indexOf("0"),g>-1)for(;j[0].length<a[0].length-g;)j[0]="0"+j[0];else 0===+j[0]&&(j[0]="");if(b=b.split("."),b[0]=j[0],i=k[1]&&k[k.length-1].length){for(l=b[0],p="",r=l.length%i,m=l.length,t=0;t<m;t++)p+=l.charAt(t),!((t-r+1)%i)&&t<m-i&&(p+=f);b[0]=p;}return b[1]=a[1]&&b[1]?e+b[1]:"",d=b.join(""),"0"!==d&&""!==d||(c=!1),o+((c?"-":"")+d)+u}});
});

function escapeRegExp(str) {
  return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
}

var SIprefixes = {
  3: 'k',
  6: 'M',
  9: 'G',
  12: 'T',
  15: 'P',
  18: 'E',
  21: 'Z',
  24: 'Y',
  '-3': 'm',
  '-6': 'μ',
  '-9': 'n',
  '-12': 'p',
  '-15': 'f',
  '-18': 'a',
  '-21': 'z',
  '-24': 'y'
},
    percentage = /%$/,
    //    scientific = /e[\+\-][0-9]+/,
radix = /^\(r(0[2-9]|[12]\d|3[0-6])\)/i,
    oct = /^\(oct\)/i,
    dec = /^\(dec\)/i,
    hex = /^\(hex\)/i,
    bin = /^\(bin\)/i,
    rom = /^\(rom\)/i,
    functional = /^(\(rom\)|\(bin\)|\(hex\)|\(dec\)|\(oct\)|\(r(0[2-9]|[12]\d|3[0-6])\))/i,
    prec = /#|0/g;

function formatRadix(value, fradix, pattern, decimal) {
  value = value.toString(fradix);

  if (pattern[1] === pattern[1].toUpperCase()) {
    value = value.toUpperCase();
  }

  if (value.length - value.indexOf('.') > 10) {
    // limit to 10 decimal places
    value = value.slice(0, value.indexOf('.') + 11);
  }

  return value.replace('.', decimal || '.');
} // value must be an integer
// value must not be in scientific notation


function formatRoman(value, pattern) {
  var i,
      s = '',
      v = Number(String(value).slice(-3)),
      nThousands = (value - v) / 1000,
      decimal = [0, 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900].reverse(),
      numeral = ['0', 'I', 'IV', 'V', 'IX', 'X', 'XL', 'L', 'XC', 'C', 'CD', 'D', 'CM'].reverse();

  while (v > 0) {
    for (i = 0; i < decimal.length; i++) {
      if (decimal[i] <= v) {
        s += numeral[i];
        v -= decimal[i];
        break;
      }
    }
  }

  for (i = 0; i < nThousands; i++) {
    s = "M".concat(s);
  }

  if (pattern[1] !== pattern[1].toUpperCase()) {
    s = s.toLowerCase();
  }

  return s;
}

function formatFunctional(value, pattern, d) {
  var temp;

  if (radix.test(pattern)) {
    value = formatRadix(value, Number(/\d{2}/.exec(pattern)[0]), pattern, d);
  } else if (oct.test(pattern)) {
    value = formatRadix(value, 8, pattern, d);
  } else if (dec.test(pattern)) {
    value = formatRadix(value, 10, pattern, d);
  } else if (hex.test(pattern)) {
    value = formatRadix(value, 16, pattern, d);
  } else if (bin.test(pattern)) {
    value = formatRadix(value, 2, pattern, d);
  } else if (rom.test(pattern)) {
    temp = '';

    if (value < 0) {
      temp = '-';
      value = -value;
    }

    value = Math.floor(value);

    if (value === 0) {
      value = '0';
    } else if (value <= 500000) {
      // limit in engine
      value = formatRoman(value, pattern);
      value = temp + value;
    } else {
      value = pattern + temp + value.toExponential(0); // to return same result as engine
    }
  }

  return value;
}

function escape(value, flags, justStr) {
  var str = escapeRegExp(value);

  if (justStr) {
    return str;
  }

  return new RegExp(str || '', flags);
}

function createRegExp(thousand, decimal) {
  if (decimal) {
    decimal = escapeRegExp(decimal);
  }

  if (thousand) {
    thousand = escapeRegExp(thousand);
  }

  return new RegExp("(?:[#0]+".concat(thousand, ")?[#0]+(?:").concat(decimal, "[#0]+)?"));
}

function getAbbreviations(localeInfo, listSeparator) {
  if (!localeInfo || !localeInfo.qNumericalAbbreviation) {
    return SIprefixes;
  }

  var abbreviations = {};
  var abbrs = localeInfo.qNumericalAbbreviation.split(listSeparator);
  abbrs.forEach(function (abbreviation) {
    var abbreviationTuple = abbreviation.split(':');

    if (abbreviationTuple.length === 2) {
      abbreviations[abbreviationTuple[0]] = abbreviationTuple[1];
    }
  });
  return abbreviations;
}

function preparePattern(o, t, d) {
  var parts,
      lastPart,
      pattern = o.pattern,
      numericPattern,
      prefix,
      postfix,
      groupTemp,
      decTemp,
      temp,
      regex;

  if (pattern.indexOf('A') >= 0) {
    // abbreviate SI
    pattern = pattern.replace('A', '');
    o.abbreviate = true;
  } // extract the numeric part from the pattern


  regex = createRegExp(t, d);
  numericPattern = pattern.match(regex);
  numericPattern = numericPattern ? numericPattern[0] : '';
  prefix = numericPattern ? pattern.substr(0, pattern.indexOf(numericPattern)) : pattern;
  postfix = numericPattern ? pattern.substring(pattern.indexOf(numericPattern) + numericPattern.length) : '';

  if (!numericPattern) {
    numericPattern = pattern ? '#' : '##########';
  }

  if (t && t === d) {
    // ignore grouping if grouping separator is same as decimal separator
    // extract decimal part
    parts = numericPattern.split(d);
    lastPart = parts.pop();
    numericPattern = parts.join('') + d + lastPart;
    t = '';
  } // formatting library does not support multiple characters as separator (nor +-).
  // do a temporary replacement


  groupTemp = t;
  t = /,/.test(d) ? '¤' : ',';

  if (groupTemp) {
    numericPattern = numericPattern.replace(escape(groupTemp, 'g'), t);
  }

  decTemp = d;
  d = '.';

  if (decTemp) {
    numericPattern = numericPattern.replace(escape(decTemp, 'g'), d);
  }

  temp = numericPattern.match(/#/g);
  temp = temp ? temp.length : 0;
  var splitPattern = pattern.split(decTemp);
  var matchPrecisionResult;

  if (splitPattern[1]) {
    matchPrecisionResult = splitPattern[1].match(prec);
  }

  o.prefix = prefix || '';
  o.postfix = postfix || '';
  o.pattern = pattern;
  o.maxPrecision = matchPrecisionResult ? matchPrecisionResult.length : 2;
  o.percentage = percentage.test(pattern);
  o.numericPattern = numericPattern || '';
  o.numericRegex = new RegExp("".concat(escape(t, null, true), "|").concat(escape(d, null, true)), 'g');
  o.groupTemp = groupTemp;
  o.decTemp = decTemp;
  o.t = t;
  o.d = d;
  o.temp = temp;
}

var NumberFormatter =
/*#__PURE__*/
function () {
  /**
   * @name NumberFormatter
   * @constructs
   * @param {Object} localeInfo
   * @param {String} pattern
   * @param {String} [thousand]
   * @param {String} [decimal]
   * @param {String} [type]
   */
  function NumberFormatter(localeInfo, pattern, thousand, decimal, type) {
    _classCallCheck(this, NumberFormatter);

    this.localeInfo = localeInfo;
    this.pattern = pattern;
    this.thousandDelimiter = thousand || ',';
    this.decimalDelimiter = decimal || '.';
    this.type = type || 'numeric'; // FIXME qListSep?
    // this.patternSeparator = this.localeInfo && this.localeInfo.qListSep ? this.localeInfo.qListSep : ';';

    this.patternSeparator = ';';
    this.abbreviations = getAbbreviations(localeInfo, this.patternSeparator);
    this.prepare();
  }

  _createClass(NumberFormatter, [{
    key: "clone",
    value: function clone() {
      var n = new NumberFormatter(this.localeInfo, this.pattern, this.thousandDelimiter, this.decimalDelimiter, this.type);
      n.subtype = this.subtype;
      return n;
    }
    /**
     * Formats a number according to a specific pattern.
     * Use # for optional numbers and 0 for padding.
     * @param {Number} value Number to format.
     * @param {String} [pattern] The pattern to apply.
     * @param {String} [t] Grouping separator.
     * @param {String} [d] Decimal delimiter.
     * @example
     * format(10, "0") // 10;
     * format(10, "#") // 10;
     * format(10, "##.#") // 10;
     * format(10, "##.0") // 10.0;
     * format(10, "000") // 010;
     * format(10.123, "0.0") // 10.1;
     * format(10.123, "0.00##") // 10.123; // at least 2 decimals, never more than 4
     * format(123456789, "#,###") // 123,456,789;
     * format(123456789, "####-####", "-") // 1-2345-6789;
     * format(10000, "#A") // 10k,  A -> SI abbreviation
     * format(1234567, "#.###A") // 1.235M;
     * format(0.0001, "#.#A") // 0.1m;
     *
     * format(0.257, "0.0%") // 25.7%; // will multiply by 100
     * format(9876, "$#,###") // $9,876;
     * format(-9876, "$#,###;$(#,###)") // $(9,876); // use ; for alternative formatting for negative values
     * format(10, "(r16)") // a; // radix 16
     * format(15, "(hex)") // f; // same as (r16)
     * format(15, "(HEX)") // F;
     * format(10, "(bin)") // 1010; // same as (r02)
     * format(10, "(oct)") // 12; // same as (r08)
     */

  }, {
    key: "format",
    value: function format(value, pattern, t, d) {
      this.prepare(pattern, t, d);
      return this.formatValue(value);
    }
  }, {
    key: "prepare",
    value: function prepare(pattern, t, d) {
      var prep;

      if (typeof pattern === 'undefined') {
        pattern = this.pattern;
      }

      if (typeof t === 'undefined') {
        t = this.thousandDelimiter;
      }

      if (typeof d === 'undefined') {
        d = this.decimalDelimiter;
      }

      if (!pattern) {
        this._prepared = {
          pattern: false
        };
        return;
      }

      this._prepared = {
        positive: {
          d: d,
          t: t,
          abbreviate: false,
          isFunctional: false,
          prefix: '',
          postfix: ''
        },
        negative: {
          d: d,
          t: t,
          abbreviate: false,
          isFunctional: false,
          prefix: '',
          postfix: ''
        },
        zero: {
          d: d,
          t: t,
          abbreviate: false,
          isFunctional: false,
          prefix: '',
          postfix: ''
        }
      };
      prep = this._prepared;
      pattern = pattern.split(this.patternSeparator);
      prep.positive.pattern = pattern[0];
      prep.negative.pattern = pattern[1];
      prep.zero.pattern = pattern[2];

      if (functional.test(pattern[0])) {
        prep.positive.isFunctional = true;
      }

      if (!pattern[1]) {
        prep.negative = false;
      } else if (functional.test(pattern[1])) {
        prep.negative.isFunctional = true;
      }

      if (!pattern[2]) {
        prep.zero = false;
      } else if (functional.test(pattern[2])) {
        prep.zero.isFunctional = true;
      }

      if (!prep.positive.isFunctional) {
        preparePattern(prep.positive, t, d);
      }

      if (prep.negative && !prep.negative.isFunctional) {
        preparePattern(prep.negative, t, d);
      }

      if (prep.zero && !prep.zero.isFunctional) {
        preparePattern(prep.zero, t, d);
      }
    }
  }, {
    key: "formatValue",
    value: function formatValue(value) {
      var prep = this._prepared,
          temp,
          exponent,
          abbr = '',
          absValue,
          num,
          sciValue = '',
          d,
          t,
          i,
          numericPattern,
          decimalPartPattern,
          original = value;

      if (isNaN(value)) {
        return "".concat(original);
      }

      value = +value;

      if (prep.pattern === false) {
        return value.toString();
      }

      if (value === 0 && prep.zero) {
        prep = prep.zero;
        return prep.pattern;
      }

      if (value < 0 && prep.negative) {
        prep = prep.negative;
        value = -value;
      } else {
        prep = prep.positive;
      }

      d = prep.d;
      t = prep.t;

      if (prep.isFunctional) {
        value = formatFunctional(value, prep.pattern, d);
      } else {
        if (prep.percentage) {
          value *= 100;
        }

        if (prep.abbreviate) {
          var abbrArray = Object.keys(this.abbreviations).map(function (key) {
            return parseInt(key, 10);
          }).sort(function (a, b) {
            return a - b;
          });
          var lowerAbbreviation;
          var upperAbbreviation = abbrArray[0];
          i = 0;
          exponent = Number(Number(value).toExponential().split('e')[1]);

          while (upperAbbreviation <= exponent && i < abbrArray.length) {
            i++;
            upperAbbreviation = abbrArray[i];
          }

          if (i > 0) {
            lowerAbbreviation = abbrArray[i - 1];
          }

          var suggestedAbbrExponent; // value and lower abbreviation is for values above 10, use the lower (move to the left <==)

          if (lowerAbbreviation && exponent > 0 && lowerAbbreviation > 0) {
            suggestedAbbrExponent = lowerAbbreviation; // value and lower abbreviation is for values below 0.1 (move to the right ==>)
          } else if (exponent < 0 && lowerAbbreviation < 0 || !lowerAbbreviation) {
            // upper abbreviation is also for values below 0.1 and precision allows for using the upper abbreviation(move to the right ==>)
            if (upperAbbreviation < 0 && upperAbbreviation - exponent <= prep.maxPrecision) {
              suggestedAbbrExponent = upperAbbreviation; // lower abbrevaition is smaller than exponent and we can't get away with not abbreviating
            } else if (lowerAbbreviation <= exponent && !(upperAbbreviation > 0 && -exponent <= prep.maxPrecision)) {
              // (move to left <==)
              suggestedAbbrExponent = lowerAbbreviation;
            }
          }

          if (suggestedAbbrExponent) {
            abbr = this.abbreviations[suggestedAbbrExponent];
            value /= Math.pow(10, suggestedAbbrExponent);
          }
        }

        absValue = Math.abs(value);
        temp = prep.temp;
        numericPattern = prep.numericPattern;
        decimalPartPattern = numericPattern.split(d)[1];

        if (this.type === 'I') {
          value = Math.round(value);
        }

        num = value;

        if (!decimalPartPattern && numericPattern.slice(-1)[0] === '#') {
          if (absValue >= Math.pow(10, temp) || absValue < 1 || absValue < 1e-4) {
            if (value === 0) {
              value = '0';
            } else if (absValue < 1e-4 || absValue >= 1e20) {
              // engine always formats values < 1e-4 in scientific form, values >= 1e20 can only be represented in scientific form
              value = num.toExponential(Math.max(1, Math.min(14, temp)) - 1);
              value = value.replace(/\.?0+(?=e)/, '');
              sciValue = '';
            } else {
              value = value.toPrecision(Math.max(1, Math.min(14, temp)));

              if (value.indexOf('.') >= 0) {
                value = value.replace(value.indexOf('e') < 0 ? /0+$/ : /\.?0+(?=e)/, '');
                value = value.replace('.', d);
              }
            }
          } else {
            numericPattern += d;
            temp = Math.max(0, Math.min(20, temp - Math.ceil(Math.log(absValue) / Math.log(10))));

            for (i = 0; i < temp; i++) {
              numericPattern += '#';
            }

            value = format_min(numericPattern, value);
          }
        } else if (absValue >= 1e15 || absValue > 0 && absValue <= 1e-14) {
          value = absValue ? absValue.toExponential(15).replace(/\.?0+(?=e)/, '') : '0';
        } else {
          var wholePart = Number(value.toFixed(Math.min(20, decimalPartPattern ? decimalPartPattern.length : 0)).split('.')[0]);
          var wholePartPattern = numericPattern.split(d)[0];
          wholePartPattern += d;
          value = format_min(wholePartPattern, wholePart) || '0';

          if (decimalPartPattern) {
            var nDecimals = Math.max(0, Math.min(14, decimalPartPattern.length)); // the length of e.g. 0000#####

            var nZeroes = decimalPartPattern.replace(/#+$/, '').length;
            var decimalPart = (this.type === 'I' ? 0 : absValue % 1).toFixed(nDecimals).slice(2).replace(/0+$/, ''); // remove trailing zeroes

            for (i = decimalPart.length; i < nZeroes; i++) {
              decimalPart += '0';
            }

            if (decimalPart) {
              value += d + decimalPart;
            }
          } else if (wholePart === 0) {
            // to avoid "-" being prefixed to value
            num = 0;
          }
        }

        value = value.replace(prep.numericRegex, function (m) {
          if (m === t) {
            return prep.groupTemp;
          }

          if (m === d) {
            return prep.decTemp;
          }

          return '';
        });

        if (num < 0 && !/^-/.test(value)) {
          value = "-".concat(value);
        }
      }

      return prep.prefix + value + sciValue + abbr + prep.postfix;
    }
  }], [{
    key: "getStaticFormatter",
    value: function getStaticFormatter() {
      return {
        prepare: function prepare() {},
        formatValue: function formatValue(v) {
          return "".concat(v);
        }
      };
    }
  }]);

  return NumberFormatter;
}();

function numberFormatFactory() {
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }

  return _construct(NumberFormatter, args);
}

function memoize(func) {
  var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var _opts$size = opts.size,
      size = _opts$size === void 0 ? 5000 : _opts$size,
      _opts$multipleArgumen = opts.multipleArguments,
      multipleArguments = _opts$multipleArgumen === void 0 ? false : _opts$multipleArgumen,
      _opts$toKey = opts.toKey,
      toKey = _opts$toKey === void 0 ? function (arg) {
    return arg;
  } : _opts$toKey;
  var cache = Object.create(null);
  var index = Object.create(null);
  var counter = 0;
  var fifo = 0; // First-In-First-Out index

  var _cacher2;

  var k;

  if (multipleArguments) {
    _cacher2 = function cacher() {
      k = toKey.apply(void 0, arguments);

      if (_cacher2.has(k)) {
        return _cacher2.get(k);
      }

      return _cacher2.set(k, func.apply(void 0, arguments));
    };
  } else {
    _cacher2 = function _cacher(arg) {
      k = toKey(arg);

      if (_cacher2.has(k)) {
        return _cacher2.get(k);
      }

      return _cacher2.set(k, func(arg));
    };
  }

  _cacher2.set = function (key, val) {
    if (counter >= size) {
      delete cache[index[fifo]];
      delete index[fifo];
      counter--;
      fifo++;
    }

    cache[key] = val;
    index[counter] = key;
    counter++;
    return val;
  };

  _cacher2.get = function (key) {
    return cache[key];
  };

  _cacher2.has = function (key) {
    return key in cache;
  };

  _cacher2.clear = function () {
    cache = Object.create(null);
    index = Object.create(null);
    counter = 0;
    fifo = 0;
  };

  _cacher2.size = function () {
    return counter;
  };

  return _cacher2;
}

function formatter(pattern, thousand, decimal, qType, localeInfo) {
  var qformat = numberFormatFactory(localeInfo, pattern, thousand, decimal, qType);
  var memoized = memoize(qformat.formatValue.bind(qformat), {
    // Handle NaN and cases where toString yields different result than +operator. Ex. a Date.
    toKey: function toKey(value) {
      return isNaN(value) ? value : +value;
    }
  });
  /**
   * Format a value according to the specified pattern created at construct
   *
   * @param  {Number} value   The number to be formatted
   * @return {String}         [description]
   */

  function format(value) {
    return memoized(value);
  }
  /**
    * Format a value according to a specific pattern
    * that is not the one specified in the constructor
    *
    * @param  {String} p   Pattern
    * @param  {Number} v   Value
    * @param  {String} t   Thousand
    * @param  {String} d   Decimal
    * @return {String}     Formatted value
    */


  format.format = function formatFn(p, v, t, d) {
    memoized.clear();
    return qformat.format(v, p, t, d);
  };
  /**
    * Change the pattern on existing formatter
    *
    * @param  {String} p     Pattern (optional)
    * @return {String}       Returns the pattern
    */


  format.pattern = function patternFn(p) {
    if (p) {
      memoized.clear();
      qformat.pattern = p;
      qformat.prepare();
    }

    return qformat.pattern;
  };
  /**
   * Set the locale for the formatter
   *
   * @param  {Object} args   Locale object for formatting
   * @return {Undefined}      Returns nothing
   */

  /* format.locale = function( ...args ) {
    locale = formatLocale( ...args );
    d3format = locale.format( pattern );
     return this;
  }; */


  return format;
}

/* eslint import/prefer-default-export: 0 */
var TYPES = {
  AUTO: 'U',
  INTEGER: 'I',
  NUMBER: 'R',
  FIXED_TO: 'F',
  MONEY: 'M',
  DATE: 'D',
  TIME: 'T',
  DATE_TIME: 'TS',
  INTERVAL: 'IV'
};

var DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
var DAYS_ABBR = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
var MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var MONTHS_ABBR = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var SECONDS_PER_DAY = 86400;

function pad(s, n) {
  for (var i = s.length; i < n; i++) {
    s = "0".concat(s);
  }

  return s;
}

function parseDate(d, twelveFormat) {
  var h = d.getUTCHours();
  var day = d.getUTCDay() - 1;

  if (twelveFormat) {
    h %= 12;

    if (!h) {
      // h == 0 -> 12
      h = 12;
    }
  }

  if (day < 0) {
    day = 6;
  }

  return {
    year: d.getUTCFullYear(),
    month: d.getUTCMonth(),
    day: day,
    date: d.getUTCDate(),
    h: h,
    m: d.getUTCMinutes(),
    s: d.getUTCSeconds(),
    f: d.getUTCMilliseconds(),
    t: d.getUTCHours() >= 12 ? 'pm' : 'am'
  };
}

function getRemainder(value) {
  var s = value.toString().split('.');

  if (s[1]) {
    s = Number("0.".concat(s[1]));
  } else {
    return 0;
  }

  return s;
}

function parseIntervalDays(days) {
  var d = days;
  var h = 24 * getRemainder(d);
  var m = 60 * getRemainder(h);
  var s = 60 * getRemainder(m);
  var ms = 1000 * getRemainder(s);
  return {
    d: Math.floor(d),
    h: Math.floor(h),
    m: Math.floor(m),
    s: Math.floor(s),
    f: Math.round(ms)
  };
}

function parseInterval(days, pattern) {
  var units = parseIntervalDays(days),
      d = units.d,
      h = units.h,
      m = units.m,
      s = units.s,
      f = units.f,
      w = 0,
      date;

  if (/w+|t+/gi.test(pattern)) {
    date = new Date(Date.UTC(1899, 11, 30 + Math.floor(days), 0, 0, Math.round(SECONDS_PER_DAY * (days - Math.floor(days)))));

    if (isNaN(date.getTime())) {
      date = null;
    }
  }

  if (!/D+/gi.test(pattern)) {
    h += d * 24;
  }

  if (!/h+/gi.test(pattern)) {
    m += h * 60;
  }

  if (!/m+/gi.test(pattern)) {
    s += m * 60;
  }

  if (/w+/gi.test(pattern)) {
    w = date ? date.getDay() - 1 : 0;

    if (w < 0) {
      w = 6;
    }
  }

  var someT = '';

  if (date) {
    someT = date.getUTCHours() >= 12 ? 'pm' : 'am';
  }

  return {
    year: 0,
    month: 0,
    day: w,
    date: d,
    h: h,
    m: m,
    s: s,
    f: f,
    t: someT
  };
}

function getMasks(inst, d) {
  return {
    'Y+|y+': {
      Y: "".concat(Number("".concat(d.year).slice(-2))),
      YY: pad("".concat(d.year).slice(-2), 2),
      YYY: pad("".concat(d.year).slice(-3), 3),
      def: function def(m) {
        // default
        return pad("".concat(d.year), m.length);
      }
    },
    'M+': {
      M: d.month + 1,
      MM: pad("".concat(d.month + 1), 2),
      MMM: inst.locale_months_abbr[d.month],
      def: inst.locale_months[d.month]
    },
    'W+|w+': {
      W: d.day,
      WW: pad("".concat(d.day), 2),
      WWW: inst.locale_days_abbr[d.day],
      def: inst.locale_days[d.day]
    },
    'D+|d+': {
      D: d.date,
      def: function def(m) {
        return pad("".concat(d.date), m.length);
      }
    },
    'h+|H+': {
      h: d.h,
      def: function def(m) {
        return pad("".concat(d.h), m.length);
      }
    },
    'm+': {
      m: d.m,
      def: function def(m) {
        return pad("".concat(d.m), m.length);
      }
    },
    's+|S+': {
      s: d.s,
      def: function def(m) {
        return pad("".concat(d.s), m.length);
      }
    },
    'f+|F+': {
      def: function def(m) {
        var f = "".concat(d.f),
            n = m.length - f.length;

        if (n > 0) {
          for (var i = 0; i < n; i++) {
            f += '0';
          }
        } else if (n < 0) {
          f = f.slice(0, m.length);
        }

        return f;
      }
    },
    't{1,2}|T{1,2}': {
      def: function def(m) {
        var t = d.t;

        if (m[0].toUpperCase() === m[0]) {
          t = t.toUpperCase();
        }

        t = t.slice(0, m.length);
        return t;
      }
    }
  };
}

var DateFormatter =
/*#__PURE__*/
function () {
  /**
   * @name DateFormatter
   * @constructs
   * @param {Object} localeInfo
   * @param {String} pattern
   */
  function DateFormatter(localeInfo, pattern, qtype) {
    _classCallCheck(this, DateFormatter);

    var info = localeInfo || {};

    if (!info.qCalendarStrings) {
      info.qCalendarStrings = {
        qLongDayNames: DAYS,
        qDayNames: DAYS_ABBR,
        qLongMonthNames: MONTHS,
        qMonthNames: MONTHS_ABBR
      };
    }

    this.localeInfo = info;
    this.locale_days = info.qCalendarStrings.qLongDayNames.slice();
    this.locale_days_abbr = info.qCalendarStrings.qDayNames.slice();
    this.locale_months = info.qCalendarStrings.qLongMonthNames.slice();
    this.locale_months_abbr = info.qCalendarStrings.qMonthNames.slice();

    if (!pattern) {
      var _patternMap;

      var patternMap = (_patternMap = {}, _defineProperty(_patternMap, TYPES.TIME, info.qTimeFmt || 'hh:mm:ss'), _defineProperty(_patternMap, TYPES.DATE, info.qDateFmt || 'YYYY-MM-DD'), _defineProperty(_patternMap, TYPES.DATE_TIME, info.qTimestampFmt || 'YYYY-MM-DD hh:mm:ss'), _patternMap);
      pattern = patternMap[qtype];
    }

    this.pattern = pattern;
  }

  _createClass(DateFormatter, [{
    key: "clone",
    value: function clone() {
      var n = new DateFormatter(this.localeInfo, this.pattern);
      n.subtype = this.subtype;
      return n;
    }
    /**
     * Formats a date according to given pattern
     * @param {Date} date The date to format.
     * @param {String} pattern The desired format of the date
     * var d = new Date(2013, 8, 15, 13, 55, 40, 987);
     * var n = new DateFormatter();
     * @example
     * m.format( d, 'YYYY-MM-DD hh:mm:ss.ffff') // 2013-08-15 13:55:40.9870
     * m.format( d, 'h:m:s tt') // 1:55:40 pm
     * m.format( d, 'h:m:s TT') // 1:55:40 PM
     * m.format( d, 'M/D/YYYY') // 8/15/2013
     * m.format( d, 'WWWW DD MMM') // Thursday 15 Aug
     * m.format( d, 'WWW DD MMMM @ hh:mm:ss') // Thu 15 August @ 13:55:40
     */

  }, {
    key: "format",
    value: function format(date, pattern) {
      // Fallback pattern is set in constructor
      if (!pattern) {
        pattern = this.pattern ? this.pattern : 'YYYY-MM-DD hh:mm:ss';
      }

      pattern = pattern.replace(/\[.+]|\[|]/g, '');
      var hasTwelveFlag = /t+/ig.test(pattern);
      var parsedDate;

      if (date instanceof Date) {
        parsedDate = parseDate(date, hasTwelveFlag);
      } else {
        if (date < 0) {
          // parseInterval don't support for negative values
          date = -date;
          pattern = "-".concat(pattern);
        }

        parsedDate = parseInterval(date, pattern);
      } // remove [] and everything inside it


      var masks = getMasks(this, parsedDate);
      var masksArr = [];

      for (var mask in masks) {
        if (Object.prototype.hasOwnProperty.call(masks, mask)) {
          masksArr.push(mask);
        }
      }

      var dateTimeRegex = new RegExp(masksArr.join('|'), 'g');
      var result = pattern.replace(dateTimeRegex, function (m) {
        var r;
        var mask;

        for (mask in masks) {
          if (Object.prototype.hasOwnProperty.call(masks, mask)) {
            r = new RegExp(mask);

            if (r.test(m)) {
              break;
            }
          }
        }

        if (!r) {
          return '';
        }

        var value;

        for (var submask in masks[mask]) {
          if (submask === m || submask.toLowerCase() === m) {
            value = masks[mask][submask];

            if (typeof value === 'undefined') {
              value = masks[mask][submask.toLowerCase()];
            }

            break;
          }
        }

        if (typeof value === 'undefined') {
          value = masks[mask].def;
        }

        if (typeof value === 'function') {
          value = value(m);
        }

        return value;
      });
      return result;
    }
  }]);

  return DateFormatter;
}();

function dateFormatFactory() {
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }

  return _construct(DateFormatter, args);
}

var MS_PER_DAY = 86400000;
function QlikTimeToDate(value) {
  return new Date(Date.UTC(1899, 11, 30 + Math.floor(value), 0, 0, 0, Math.round(MS_PER_DAY * (value - Math.floor(value)))));
}
function formatter$1(pattern) {
  var qtype = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'TS';
  var localeInfo = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  var qformat = dateFormatFactory(localeInfo, pattern, qtype);
  var memoized = memoize(qformat.format.bind(qformat), {
    toKey: function toKey(date) {
      return _typeof(date) === 'object' && typeof date.getTime === 'function' ? date.getTime() : date;
    }
  });
  /**
   * Prepare a value according to the specified qtype
   *
   * @param  {Number} value The value to be formatted
   * @return {Number}       The converted value (if applied)
   */

  function prepare(value) {
    if (qtype !== TYPES.INTERVAL) {
      return QlikTimeToDate(value);
    }

    return value;
  }
  /**
   * Format a value according to the specified pattern created at construct
   *
   * @param  {Date} value   The number to be formatted
   * @return {String}         [description]
   */


  function format(value) {
    value = prepare(value);
    return memoized(value);
  }
  /**
    * Format a value according to a specific pattern
    * that is not the one specified in the constructor
    *
    * @param  {String} p   Pattern
    * @param  {Date} v   Value
    * @return {String}     Formatted value
    */


  format.format = function formatFn(p, v) {
    memoized.clear();
    v = prepare(v);
    return qformat.format(v, p);
  };
  /**
   * Set the locale for the formatter
   *
   * @param  {Object} args   Locale object for formatting
   * @return {Undefined}      Returns nothing
   */


  format.locale = function locale(li) {
    qformat = dateFormatFactory(li, pattern, qtype);
    memoized = memoize(qformat.format.bind(qformat), {
      toKey: function toKey(date) {
        return _typeof(date) === 'object' ? date.getTime() : date;
      }
    });
    return this;
  };
  /**
   * Get or set the QType
   *
   * @param  {String} nqt New qType (optional)
   * @return {String}     Current qtype
   */


  format.qtype = function qtypeFn(nqt) {
    if (nqt !== undefined) {
      qtype = nqt;
      memoized.clear();
    }

    return qtype;
  };

  return format;
}

function createFromMetaInfo(meta, localeInfo) {
  if (meta && meta.qNumFormat && ['D', 'T', 'TS', 'IV'].indexOf(meta.qNumFormat.qType) !== -1) {
    return formatter$1(meta.qNumFormat.qFmt, meta.qNumFormat.qType, localeInfo);
  }

  var pattern = '#';
  var thousand = localeInfo && typeof localeInfo.qThousandSep !== 'undefined' ? localeInfo.qThousandSep : ',';
  var decimal = localeInfo && typeof localeInfo.qDecimalSep !== 'undefined' ? localeInfo.qDecimalSep : '.';
  var type = 'U';
  var isAuto = meta && !!meta.qIsAutoFormat;

  if (meta && meta.qNumFormat) {
    pattern = meta.qNumFormat.qFmt || pattern;
    thousand = meta.qNumFormat.qThou || thousand;
    decimal = meta.qNumFormat.qDec || decimal;
    type = meta.qNumFormat.qType || type;
    isAuto = isAuto && ['M'].indexOf(meta.qNumFormat.qType) === -1;
  } else {
    isAuto = true;
  }

  if (isAuto || type === 'U') {
    pattern = "#".concat(decimal, "##A");
    type = 'U';
  }

  return formatter(pattern, thousand, decimal, type, localeInfo);
}

function qField() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      meta = _ref.meta,
      _id = _ref.id,
      _key = _ref.key,
      localeInfo = _ref.localeInfo,
      fieldExtractor = _ref.fieldExtractor,
      value = _ref.value,
      _type = _ref.type,
      sourceField = _ref.sourceField;

  var values;
  var valueFn = value || (_type === 'dimension' ? function (d) {
    return d.qElemNo;
  } : function (d) {
    return d.qValue;
  });

  var labelFn = function labelFn(d) {
    return d.qText || '';
  };

  var reduce = _type === 'dimension' ? 'first' : 'avg';

  var _formatter = createFromMetaInfo(meta, localeInfo);

  var reduceLabel = _type === 'dimension' ? 'first' : function (labels, v) {
    return _formatter(v);
  };
  var f = {
    id: function id() {
      return _id;
    },
    key: function key() {
      return _key;
    },
    raw: function raw() {
      return meta;
    },
    title: function title() {
      return meta.qFallbackTitle || meta.label;
    },
    type: function type() {
      return _type;
    },
    origin: function origin() {
      return sourceField;
    },
    items: function items() {
      if (!values) {
        values = fieldExtractor(f);
      }

      return values;
    },
    min: function min() {
      return meta.qMin;
    },
    max: function max() {
      return meta.qMax;
    },
    value: valueFn,
    label: labelFn,
    reduce: reduce,
    reduceLabel: reduceLabel,
    formatter: function formatter() {
      return _formatter;
    },
    tags: function tags() {
      return meta.qTags;
    }
  };
  return f;
}

function createFields(path, obj, prefix, parentKey, opts) {
  return (obj[path] || []).map(function (meta, i) {
    var fieldKey = "".concat(parentKey ? "".concat(parentKey, "/") : '').concat(path, "/").concat(i);
    var f = {
      instance: qField(extend({
        id: "".concat(prefix ? "".concat(prefix, "/") : '').concat(fieldKey),
        key: fieldKey,
        meta: meta
      }, opts))
    };
    f.attrDims = createFields('qAttrDimInfo', meta, prefix, fieldKey, extend({}, opts, {
      value: function value(v) {
        return v.qElemNo;
      },
      type: 'dimension'
    }));
    f.attrExps = createFields('qAttrExprInfo', meta, prefix, fieldKey, extend({}, opts, {
      value: function value(v) {
        return v.qNum;
      },
      type: 'measure'
    }));
    f.measures = createFields('qMeasureInfo', meta, prefix, fieldKey, extend({}, opts, {
      value: function value(v) {
        return v.qValue;
      },
      type: 'measure'
    }));
    return f;
  });
}

function q() {
  var _cache$wrappedFields, _cache$wrappedFields2, _cache$allFields;

  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _key = _ref.key,
      data = _ref.data,
      _ref$config = _ref.config,
      config = _ref$config === void 0 ? {} : _ref$config;

  var cache = {
    fields: [],
    wrappedFields: [],
    allFields: [],
    virtualFields: []
  };
  var cube = data;

  if (!cube) {
    throw new Error('Missing "data" input');
  }

  if (!cube.qDimensionInfo) {
    throw new Error('The "data" input is not recognized as a hypercube');
  }

  var deps = q.util;
  var opts = {
    cache: cache,
    cube: cube,
    localeInfo: config.localeInfo,
    fieldExtractor: null,
    pages: null,
    hierarchy: function hierarchy() {
      return null;
    },
    virtualFields: config.virtualFields
  };
  var dataset = {
    key: function key() {
      return _key;
    },
    raw: function raw() {
      return cube;
    },
    field: function field(query) {
      return findField(query, opts);
    },
    fields: function fields() {
      return cache.fields.slice();
    },
    extract: function extract(extractionConfig) {
      return opts.extractor(extractionConfig, dataset, cache, deps);
    },
    hierarchy: function hierarchy(hierarchyConfig) {
      return opts.hierarchy(hierarchyConfig, dataset, cache, deps);
    },
    _cache: function _cache() {
      return cache;
    }
  };

  if (cube.qMode === 'K' || cube.qMode === 'T' || !cube.qMode && cube.qNodesOnDim) {
    opts.extractor = extract$1;
    opts.hierarchy = augment;
    opts.pages = cube.qMode === 'K' ? cube.qStackedDataPages : cube.qTreeDataPages;
  } else if (cube.qMode === 'S') {
    opts.extractor = extract;
    opts.pages = cube.qDataPages;
    opts.hierarchy = augment;
  } else {
    opts.extractor = function () {
      return [];
    }; // TODO - throw unsupported error?

  }

  opts.fieldExtractor = function (f) {
    return opts.extractor({
      field: f
    }, dataset, cache, deps);
  };

  var dimAcc = cube.qMode === 'S' ? function (d) {
    return d.qElemNumber;
  } : undefined;
  var measAcc = cube.qMode === 'S' ? function (d) {
    return d.qNum;
  } : undefined;

  (_cache$wrappedFields = cache.wrappedFields).push.apply(_cache$wrappedFields, _toConsumableArray(createFields('qDimensionInfo', cube, _key, '', extend({}, opts, {
    value: dimAcc,
    type: 'dimension'
  }))));

  (_cache$wrappedFields2 = cache.wrappedFields).push.apply(_cache$wrappedFields2, _toConsumableArray(createFields('qMeasureInfo', cube, _key, '', extend({}, opts, {
    value: measAcc,
    type: 'measure'
  }))));

  cache.fields = cache.wrappedFields.map(function (f) {
    return f.instance;
  });

  var traverse = function traverse(arr) {
    arr.forEach(function (f) {
      cache.allFields.push(f.instance);
      traverse(f.measures);
      traverse(f.attrDims);
      traverse(f.attrExps);
    });
  };

  traverse(cache.wrappedFields);
  (config.virtualFields || []).forEach(function (v) {
    // key: 'temporal',
    // from: 'qDimensionInfo/0',
    // override: {
    //   value: v => v.qNum,
    // },
    var sourceField = dataset.field(v.from);
    var f = qField(_objectSpread2({
      meta: sourceField.raw(),
      id: "".concat(_key, "/").concat(v.key),
      sourceField: sourceField,
      fieldExtractor: function fieldExtractor(ff) {
        return opts.extractor({
          field: ff
        }, dataset, cache, deps);
      },
      key: v.key,
      type: sourceField.type(),
      localeInfo: opts.localeInfo,
      value: sourceField.value
    }, v.override || {}));
    cache.virtualFields.push(f);
  });

  (_cache$allFields = cache.allFields).push.apply(_cache$allFields, _toConsumableArray(cache.virtualFields));

  return dataset;
}

var LAYOUT_TO_PROP = [['qHyperCube', 'qHyperCubeDef'], ['qTreeData', 'qTreeDataDef'], ['qDimensionInfo', 'qDimensions'], ['qMeasureInfo', 'qMeasures'], ['qAttrDimInfo', 'qAttributeDimensions'], ['qAttrExprInfo', 'qAttributeExpressions']];
var DIM_RX$1 = /\/qDimensionInfo(?:\/(\d+))?/;
var M_RX$1 = /\/qMeasureInfo\/(\d+)/;
var ATTR_DIM_RX$1 = /\/qAttrDimInfo\/(\d+)(?:\/(\d+))?/;
var ATTR_EXPR_RX$1 = /\/qAttrExprInfo\/(\d+)/;
var HC_RX = /\/?qHyperCube/;
var TD_RX = /\/?qTreeData/;

var SHORTEN_HC = function SHORTEN_HC(path) {
  return "".concat(path.substr(0, path.indexOf('/qHyperCubeDef') + 14));
}; // 14 = length of '/qHyperCubeDef'


var SHORTEN_TD = function SHORTEN_TD(path) {
  return "".concat(path.substr(0, path.indexOf('/qTreeDataDef') + 13));
}; // 13 = length of '/qTreeDataDef'


function extractFieldFromId(id, layout) {
  var path = id;
  var dimensionIdx = -1;
  var measureIdx = -1;
  var pathToCube = '';

  var shortenizer = function shortenizer(p) {
    return p;
  };

  if (HC_RX.test(id)) {
    pathToCube = "".concat(path.substr(0, path.indexOf('qHyperCube') + 10)); // 10 = length of 'qHyperCube'

    shortenizer = SHORTEN_HC;
  } else if (TD_RX.test(id)) {
    pathToCube = "".concat(path.substr(0, path.indexOf('qTreeData') + 9)); // 9 = length of 'qTreeData'

    shortenizer = SHORTEN_TD;
  }

  var shortenPath = true;

  if (DIM_RX$1.test(id)) {
    dimensionIdx = +DIM_RX$1.exec(id)[1];
  }

  if (M_RX$1.test(id)) {
    measureIdx = +M_RX$1.exec(id)[1];
  }

  if (ATTR_DIM_RX$1.test(id)) {
    measureIdx = -1;
    dimensionIdx = 0;
    var attrCol = +ATTR_DIM_RX$1.exec(path)[2];

    if (!isNaN(attrCol)) {
      dimensionIdx = attrCol;
      path = path.replace(/\/\d+$/, '');
    }

    shortenPath = false;
  }

  if (ATTR_EXPR_RX$1.test(id)) {
    // depends on number of measures + number of attr expressions
    // in dimensions and measures before this one
    var offset = measureIdx;

    if (layout) {
      measureIdx = 0;
      var hc = resolve(pathToCube, layout); // offset by number of measures

      measureIdx += (hc.qMeasureInfo || []).length; // offset by total number of attr expr in dimensions
      // (assuming attr expr in dimensions are ordered first)

      if (dimensionIdx > -1) {
        measureIdx = hc.qDimensionInfo.slice(0, dimensionIdx).reduce(function (v, dim) {
          return v + dim.qAttrExprInfo.length;
        }, measureIdx);
        dimensionIdx = -1;
      } else {
        measureIdx = hc.qDimensionInfo.reduce(function (v, dim) {
          return v + dim.qAttrExprInfo.length;
        }, measureIdx); // offset by total number of attr expr in measures before 'index'

        measureIdx = hc.qMeasureInfo.slice(0, offset).reduce(function (v, meas) {
          return v + meas.qAttrExprInfo.length;
        }, measureIdx);
      } // offset by the actual column value for the attribute expression itself


      measureIdx += +ATTR_EXPR_RX$1.exec(path)[1];
    } else if (dimensionIdx > -1) {
      dimensionIdx = -1;
      measureIdx = +ATTR_EXPR_RX$1.exec(path)[1];
    } else {
      measureIdx += +ATTR_EXPR_RX$1.exec(path)[1] + 1;
    }
  }

  LAYOUT_TO_PROP.forEach(function (_ref) {
    var _ref2 = _slicedToArray(_ref, 2),
        v = _ref2[0],
        prop = _ref2[1];

    path = path.replace(v, prop);
  });

  if (shortenPath) {
    path = shortenizer(path);
  }

  if (path && path[0] !== '/') {
    path = "/".concat(path);
  }

  return {
    measureIdx: measureIdx,
    dimensionIdx: dimensionIdx,
    path: path
  };
}
/**
 * Helper method to generate suitable QIX selection methods and parameters based on a brush instance.
 * @alias brush
 * @memberof picasso.q
 * @param {brush} brush A brush instance
 * @param {object} [opts]
 * @param {boolean} [opts.byCells=false] Whether to prefer selection by row index.
 * @param {string} [opts.primarySource] Field source to extract row indices from. If not specified, indices from first source are used.
 * @param {object} [layout] QIX data layout. Needed only when brushing on attribute expressions, to be able to calculate the measure index.
 * @return {object[]} An array of relevant selections
 */

function qBrush(brush) {
  var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var layout = arguments.length > 2 ? arguments[2] : undefined;
  var byCells = opts.byCells;
  var primarySource = opts.primarySource;
  var selections = [];
  var methods = {};
  var isActive = brush.isActive();
  var hasValues = false;
  brush.brushes().forEach(function (b) {
    var info = extractFieldFromId(b.id, layout);

    if (b.type === 'range' && info.measureIdx > -1 && info.dimensionIdx > -1) {
      var ranges = b.brush.ranges();

      if (ranges.length) {
        hasValues = true;

        if (!methods.multiRangeSelectTreeDataValues) {
          methods.multiRangeSelectTreeDataValues = {
            path: info.path,
            ranges: []
          };
        }

        ranges.forEach(function (range) {
          return methods.multiRangeSelectTreeDataValues.ranges.push({
            qMeasureIx: info.measureIdx,
            qDimensionIx: info.dimensionIdx,
            qRange: {
              qMin: range.min,
              qMax: range.max,
              qMinInclEq: true,
              qMaxInclEq: true
            }
          });
        });
      }
    } else {
      if (b.type === 'range' && info.measureIdx > -1) {
        var _ranges = b.brush.ranges();

        if (_ranges.length) {
          hasValues = true;

          if (!methods.rangeSelectHyperCubeValues) {
            methods.rangeSelectHyperCubeValues = {
              path: info.path,
              ranges: []
            };
          }

          _ranges.forEach(function (range) {
            return methods.rangeSelectHyperCubeValues.ranges.push({
              qMeasureIx: info.measureIdx,
              qRange: {
                qMin: range.min,
                qMax: range.max,
                qMinInclEq: true,
                qMaxInclEq: true
              }
            });
          });
        }
      }

      if (b.type === 'range' && info.dimensionIdx > -1) {
        var _ranges2 = b.brush.ranges();

        if (_ranges2.length) {
          hasValues = true;

          if (!methods.selectHyperCubeContinuousRange) {
            methods.selectHyperCubeContinuousRange = {
              path: info.path,
              ranges: []
            };
          }

          _ranges2.forEach(function (range) {
            return methods.selectHyperCubeContinuousRange.ranges.push({
              qDimIx: info.dimensionIdx,
              qRange: {
                qMin: range.min,
                qMax: range.max,
                qMinInclEq: true,
                qMaxInclEq: false
              }
            });
          });
        }
      }

      if (b.type === 'value' && info.dimensionIdx > -1) {
        if (byCells) {
          if (layout && layout.qHyperCube && (layout.qHyperCube.qMode === 'P' || layout.qHyperCube.qMode === 'T' || layout.qHyperCube.qMode === 'K')) {
            var hyperCube = layout.qHyperCube;
            var noOfLeftDims = hyperCube.qNoOfLeftDims;
            var dimInterColSortIdx = hyperCube.qEffectiveInterColumnSortOrder.indexOf(info.dimensionIdx);

            if (!methods.selectPivotCells) {
              methods.selectPivotCells = {
                path: info.path,
                cells: []
              };
            }

            if (b.id === primarySource || !primarySource && methods.selectPivotCells.cells.length === 0) {
              var validValues = b.brush.values().map(function (s) {
                return +s;
              }).filter(function (v) {
                return !isNaN(v);
              });

              if ((noOfLeftDims === 0 || dimInterColSortIdx >= noOfLeftDims) && noOfLeftDims > -1) {
                validValues.forEach(function (val) {
                  methods.selectPivotCells.cells.push({
                    qType: 'T',
                    qCol: val,
                    qRow: dimInterColSortIdx - noOfLeftDims
                  });
                });
              } else {
                validValues.forEach(function (val) {
                  methods.selectPivotCells.cells.push({
                    qType: 'L',
                    qCol: info.dimensionIdx,
                    qRow: val
                  });
                });
              }

              hasValues = !!methods.selectPivotCells.cells.length;
            }
          } else {
            if (!methods.selectHyperCubeCells) {
              methods.selectHyperCubeCells = {
                path: info.path,
                cols: []
              };
            }

            methods.selectHyperCubeCells.cols.push(info.dimensionIdx);

            if (b.id === primarySource || !primarySource && !methods.selectHyperCubeCells.values) {
              methods.selectHyperCubeCells.values = b.brush.values().map(function (s) {
                return +s;
              }).filter(function (v) {
                return !isNaN(v);
              });
              hasValues = !!methods.selectHyperCubeCells.values.length;
            }
          }
        } else {
          var values = b.brush.values().map(function (s) {
            return +s;
          }).filter(function (v) {
            return !isNaN(v);
          });
          hasValues = !!values.length;
          selections.push({
            params: [info.path, info.dimensionIdx, values, false],
            method: 'selectHyperCubeValues'
          });
        }
      }
    }
  });

  if (!hasValues && isActive) {
    return [{
      method: 'resetMadeSelections',
      params: []
    }];
  }

  if (methods.rangeSelectHyperCubeValues) {
    selections.push({
      method: 'rangeSelectHyperCubeValues',
      params: [methods.rangeSelectHyperCubeValues.path, methods.rangeSelectHyperCubeValues.ranges, [], true]
    });
  }

  if (methods.selectHyperCubeContinuousRange) {
    selections.push({
      method: 'selectHyperCubeContinuousRange',
      params: [methods.selectHyperCubeContinuousRange.path, methods.selectHyperCubeContinuousRange.ranges]
    });
  }

  if (methods.selectHyperCubeCells) {
    selections.push({
      method: 'selectHyperCubeCells',
      params: [methods.selectHyperCubeCells.path, methods.selectHyperCubeCells.values, methods.selectHyperCubeCells.cols]
    });
  }

  if (methods.selectPivotCells) {
    selections.push({
      method: 'selectPivotCells',
      params: [methods.selectPivotCells.path, methods.selectPivotCells.cells]
    });
  }

  if (methods.multiRangeSelectTreeDataValues) {
    selections.push({
      method: 'multiRangeSelectTreeDataValues',
      params: [methods.multiRangeSelectTreeDataValues.path, methods.multiRangeSelectTreeDataValues.ranges]
    });
  }

  return selections;
}

function initialize(picasso) {
  q.util = picasso.data('matrix').util;
  picasso.data('q', q);
  picasso.formatter('q-number', formatter);
  picasso.formatter('q-time', formatter$1);
}
initialize.qBrushHelper = qBrush; // deprecated

initialize.selections = qBrush;

/* harmony default export */ __webpack_exports__["a"] = (initialize);
//# sourceMappingURL=picasso-q.esm.js.map

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(33)))

/***/ }),
/* 74 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/**
 * A collection of shims that provide minimal functionality of the ES6 collections.
 *
 * These implementations are not meant to be used outside of the ResizeObserver
 * modules as they cover only a limited range of use cases.
 */
/* eslint-disable require-jsdoc, valid-jsdoc */
var MapShim = (function () {
    if (typeof Map !== 'undefined') {
        return Map;
    }
    /**
     * Returns index in provided array that matches the specified key.
     *
     * @param {Array<Array>} arr
     * @param {*} key
     * @returns {number}
     */
    function getIndex(arr, key) {
        var result = -1;
        arr.some(function (entry, index) {
            if (entry[0] === key) {
                result = index;
                return true;
            }
            return false;
        });
        return result;
    }
    return /** @class */ (function () {
        function class_1() {
            this.__entries__ = [];
        }
        Object.defineProperty(class_1.prototype, "size", {
            /**
             * @returns {boolean}
             */
            get: function () {
                return this.__entries__.length;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * @param {*} key
         * @returns {*}
         */
        class_1.prototype.get = function (key) {
            var index = getIndex(this.__entries__, key);
            var entry = this.__entries__[index];
            return entry && entry[1];
        };
        /**
         * @param {*} key
         * @param {*} value
         * @returns {void}
         */
        class_1.prototype.set = function (key, value) {
            var index = getIndex(this.__entries__, key);
            if (~index) {
                this.__entries__[index][1] = value;
            }
            else {
                this.__entries__.push([key, value]);
            }
        };
        /**
         * @param {*} key
         * @returns {void}
         */
        class_1.prototype.delete = function (key) {
            var entries = this.__entries__;
            var index = getIndex(entries, key);
            if (~index) {
                entries.splice(index, 1);
            }
        };
        /**
         * @param {*} key
         * @returns {void}
         */
        class_1.prototype.has = function (key) {
            return !!~getIndex(this.__entries__, key);
        };
        /**
         * @returns {void}
         */
        class_1.prototype.clear = function () {
            this.__entries__.splice(0);
        };
        /**
         * @param {Function} callback
         * @param {*} [ctx=null]
         * @returns {void}
         */
        class_1.prototype.forEach = function (callback, ctx) {
            if (ctx === void 0) { ctx = null; }
            for (var _i = 0, _a = this.__entries__; _i < _a.length; _i++) {
                var entry = _a[_i];
                callback.call(ctx, entry[1], entry[0]);
            }
        };
        return class_1;
    }());
})();

/**
 * Detects whether window and document objects are available in current environment.
 */
var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && window.document === document;

// Returns global object of a current environment.
var global$1 = (function () {
    if (typeof global !== 'undefined' && global.Math === Math) {
        return global;
    }
    if (typeof self !== 'undefined' && self.Math === Math) {
        return self;
    }
    if (typeof window !== 'undefined' && window.Math === Math) {
        return window;
    }
    // eslint-disable-next-line no-new-func
    return Function('return this')();
})();

/**
 * A shim for the requestAnimationFrame which falls back to the setTimeout if
 * first one is not supported.
 *
 * @returns {number} Requests' identifier.
 */
var requestAnimationFrame$1 = (function () {
    if (typeof requestAnimationFrame === 'function') {
        // It's required to use a bounded function because IE sometimes throws
        // an "Invalid calling object" error if rAF is invoked without the global
        // object on the left hand side.
        return requestAnimationFrame.bind(global$1);
    }
    return function (callback) { return setTimeout(function () { return callback(Date.now()); }, 1000 / 60); };
})();

// Defines minimum timeout before adding a trailing call.
var trailingTimeout = 2;
/**
 * Creates a wrapper function which ensures that provided callback will be
 * invoked only once during the specified delay period.
 *
 * @param {Function} callback - Function to be invoked after the delay period.
 * @param {number} delay - Delay after which to invoke callback.
 * @returns {Function}
 */
function throttle (callback, delay) {
    var leadingCall = false, trailingCall = false, lastCallTime = 0;
    /**
     * Invokes the original callback function and schedules new invocation if
     * the "proxy" was called during current request.
     *
     * @returns {void}
     */
    function resolvePending() {
        if (leadingCall) {
            leadingCall = false;
            callback();
        }
        if (trailingCall) {
            proxy();
        }
    }
    /**
     * Callback invoked after the specified delay. It will further postpone
     * invocation of the original function delegating it to the
     * requestAnimationFrame.
     *
     * @returns {void}
     */
    function timeoutCallback() {
        requestAnimationFrame$1(resolvePending);
    }
    /**
     * Schedules invocation of the original function.
     *
     * @returns {void}
     */
    function proxy() {
        var timeStamp = Date.now();
        if (leadingCall) {
            // Reject immediately following calls.
            if (timeStamp - lastCallTime < trailingTimeout) {
                return;
            }
            // Schedule new call to be in invoked when the pending one is resolved.
            // This is important for "transitions" which never actually start
            // immediately so there is a chance that we might miss one if change
            // happens amids the pending invocation.
            trailingCall = true;
        }
        else {
            leadingCall = true;
            trailingCall = false;
            setTimeout(timeoutCallback, delay);
        }
        lastCallTime = timeStamp;
    }
    return proxy;
}

// Minimum delay before invoking the update of observers.
var REFRESH_DELAY = 20;
// A list of substrings of CSS properties used to find transition events that
// might affect dimensions of observed elements.
var transitionKeys = ['top', 'right', 'bottom', 'left', 'width', 'height', 'size', 'weight'];
// Check if MutationObserver is available.
var mutationObserverSupported = typeof MutationObserver !== 'undefined';
/**
 * Singleton controller class which handles updates of ResizeObserver instances.
 */
var ResizeObserverController = /** @class */ (function () {
    /**
     * Creates a new instance of ResizeObserverController.
     *
     * @private
     */
    function ResizeObserverController() {
        /**
         * Indicates whether DOM listeners have been added.
         *
         * @private {boolean}
         */
        this.connected_ = false;
        /**
         * Tells that controller has subscribed for Mutation Events.
         *
         * @private {boolean}
         */
        this.mutationEventsAdded_ = false;
        /**
         * Keeps reference to the instance of MutationObserver.
         *
         * @private {MutationObserver}
         */
        this.mutationsObserver_ = null;
        /**
         * A list of connected observers.
         *
         * @private {Array<ResizeObserverSPI>}
         */
        this.observers_ = [];
        this.onTransitionEnd_ = this.onTransitionEnd_.bind(this);
        this.refresh = throttle(this.refresh.bind(this), REFRESH_DELAY);
    }
    /**
     * Adds observer to observers list.
     *
     * @param {ResizeObserverSPI} observer - Observer to be added.
     * @returns {void}
     */
    ResizeObserverController.prototype.addObserver = function (observer) {
        if (!~this.observers_.indexOf(observer)) {
            this.observers_.push(observer);
        }
        // Add listeners if they haven't been added yet.
        if (!this.connected_) {
            this.connect_();
        }
    };
    /**
     * Removes observer from observers list.
     *
     * @param {ResizeObserverSPI} observer - Observer to be removed.
     * @returns {void}
     */
    ResizeObserverController.prototype.removeObserver = function (observer) {
        var observers = this.observers_;
        var index = observers.indexOf(observer);
        // Remove observer if it's present in registry.
        if (~index) {
            observers.splice(index, 1);
        }
        // Remove listeners if controller has no connected observers.
        if (!observers.length && this.connected_) {
            this.disconnect_();
        }
    };
    /**
     * Invokes the update of observers. It will continue running updates insofar
     * it detects changes.
     *
     * @returns {void}
     */
    ResizeObserverController.prototype.refresh = function () {
        var changesDetected = this.updateObservers_();
        // Continue running updates if changes have been detected as there might
        // be future ones caused by CSS transitions.
        if (changesDetected) {
            this.refresh();
        }
    };
    /**
     * Updates every observer from observers list and notifies them of queued
     * entries.
     *
     * @private
     * @returns {boolean} Returns "true" if any observer has detected changes in
     *      dimensions of it's elements.
     */
    ResizeObserverController.prototype.updateObservers_ = function () {
        // Collect observers that have active observations.
        var activeObservers = this.observers_.filter(function (observer) {
            return observer.gatherActive(), observer.hasActive();
        });
        // Deliver notifications in a separate cycle in order to avoid any
        // collisions between observers, e.g. when multiple instances of
        // ResizeObserver are tracking the same element and the callback of one
        // of them changes content dimensions of the observed target. Sometimes
        // this may result in notifications being blocked for the rest of observers.
        activeObservers.forEach(function (observer) { return observer.broadcastActive(); });
        return activeObservers.length > 0;
    };
    /**
     * Initializes DOM listeners.
     *
     * @private
     * @returns {void}
     */
    ResizeObserverController.prototype.connect_ = function () {
        // Do nothing if running in a non-browser environment or if listeners
        // have been already added.
        if (!isBrowser || this.connected_) {
            return;
        }
        // Subscription to the "Transitionend" event is used as a workaround for
        // delayed transitions. This way it's possible to capture at least the
        // final state of an element.
        document.addEventListener('transitionend', this.onTransitionEnd_);
        window.addEventListener('resize', this.refresh);
        if (mutationObserverSupported) {
            this.mutationsObserver_ = new MutationObserver(this.refresh);
            this.mutationsObserver_.observe(document, {
                attributes: true,
                childList: true,
                characterData: true,
                subtree: true
            });
        }
        else {
            document.addEventListener('DOMSubtreeModified', this.refresh);
            this.mutationEventsAdded_ = true;
        }
        this.connected_ = true;
    };
    /**
     * Removes DOM listeners.
     *
     * @private
     * @returns {void}
     */
    ResizeObserverController.prototype.disconnect_ = function () {
        // Do nothing if running in a non-browser environment or if listeners
        // have been already removed.
        if (!isBrowser || !this.connected_) {
            return;
        }
        document.removeEventListener('transitionend', this.onTransitionEnd_);
        window.removeEventListener('resize', this.refresh);
        if (this.mutationsObserver_) {
            this.mutationsObserver_.disconnect();
        }
        if (this.mutationEventsAdded_) {
            document.removeEventListener('DOMSubtreeModified', this.refresh);
        }
        this.mutationsObserver_ = null;
        this.mutationEventsAdded_ = false;
        this.connected_ = false;
    };
    /**
     * "Transitionend" event handler.
     *
     * @private
     * @param {TransitionEvent} event
     * @returns {void}
     */
    ResizeObserverController.prototype.onTransitionEnd_ = function (_a) {
        var _b = _a.propertyName, propertyName = _b === void 0 ? '' : _b;
        // Detect whether transition may affect dimensions of an element.
        var isReflowProperty = transitionKeys.some(function (key) {
            return !!~propertyName.indexOf(key);
        });
        if (isReflowProperty) {
            this.refresh();
        }
    };
    /**
     * Returns instance of the ResizeObserverController.
     *
     * @returns {ResizeObserverController}
     */
    ResizeObserverController.getInstance = function () {
        if (!this.instance_) {
            this.instance_ = new ResizeObserverController();
        }
        return this.instance_;
    };
    /**
     * Holds reference to the controller's instance.
     *
     * @private {ResizeObserverController}
     */
    ResizeObserverController.instance_ = null;
    return ResizeObserverController;
}());

/**
 * Defines non-writable/enumerable properties of the provided target object.
 *
 * @param {Object} target - Object for which to define properties.
 * @param {Object} props - Properties to be defined.
 * @returns {Object} Target object.
 */
var defineConfigurable = (function (target, props) {
    for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) {
        var key = _a[_i];
        Object.defineProperty(target, key, {
            value: props[key],
            enumerable: false,
            writable: false,
            configurable: true
        });
    }
    return target;
});

/**
 * Returns the global object associated with provided element.
 *
 * @param {Object} target
 * @returns {Object}
 */
var getWindowOf = (function (target) {
    // Assume that the element is an instance of Node, which means that it
    // has the "ownerDocument" property from which we can retrieve a
    // corresponding global object.
    var ownerGlobal = target && target.ownerDocument && target.ownerDocument.defaultView;
    // Return the local global object if it's not possible extract one from
    // provided element.
    return ownerGlobal || global$1;
});

// Placeholder of an empty content rectangle.
var emptyRect = createRectInit(0, 0, 0, 0);
/**
 * Converts provided string to a number.
 *
 * @param {number|string} value
 * @returns {number}
 */
function toFloat(value) {
    return parseFloat(value) || 0;
}
/**
 * Extracts borders size from provided styles.
 *
 * @param {CSSStyleDeclaration} styles
 * @param {...string} positions - Borders positions (top, right, ...)
 * @returns {number}
 */
function getBordersSize(styles) {
    var positions = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        positions[_i - 1] = arguments[_i];
    }
    return positions.reduce(function (size, position) {
        var value = styles['border-' + position + '-width'];
        return size + toFloat(value);
    }, 0);
}
/**
 * Extracts paddings sizes from provided styles.
 *
 * @param {CSSStyleDeclaration} styles
 * @returns {Object} Paddings box.
 */
function getPaddings(styles) {
    var positions = ['top', 'right', 'bottom', 'left'];
    var paddings = {};
    for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) {
        var position = positions_1[_i];
        var value = styles['padding-' + position];
        paddings[position] = toFloat(value);
    }
    return paddings;
}
/**
 * Calculates content rectangle of provided SVG element.
 *
 * @param {SVGGraphicsElement} target - Element content rectangle of which needs
 *      to be calculated.
 * @returns {DOMRectInit}
 */
function getSVGContentRect(target) {
    var bbox = target.getBBox();
    return createRectInit(0, 0, bbox.width, bbox.height);
}
/**
 * Calculates content rectangle of provided HTMLElement.
 *
 * @param {HTMLElement} target - Element for which to calculate the content rectangle.
 * @returns {DOMRectInit}
 */
function getHTMLElementContentRect(target) {
    // Client width & height properties can't be
    // used exclusively as they provide rounded values.
    var clientWidth = target.clientWidth, clientHeight = target.clientHeight;
    // By this condition we can catch all non-replaced inline, hidden and
    // detached elements. Though elements with width & height properties less
    // than 0.5 will be discarded as well.
    //
    // Without it we would need to implement separate methods for each of
    // those cases and it's not possible to perform a precise and performance
    // effective test for hidden elements. E.g. even jQuery's ':visible' filter
    // gives wrong results for elements with width & height less than 0.5.
    if (!clientWidth && !clientHeight) {
        return emptyRect;
    }
    var styles = getWindowOf(target).getComputedStyle(target);
    var paddings = getPaddings(styles);
    var horizPad = paddings.left + paddings.right;
    var vertPad = paddings.top + paddings.bottom;
    // Computed styles of width & height are being used because they are the
    // only dimensions available to JS that contain non-rounded values. It could
    // be possible to utilize the getBoundingClientRect if only it's data wasn't
    // affected by CSS transformations let alone paddings, borders and scroll bars.
    var width = toFloat(styles.width), height = toFloat(styles.height);
    // Width & height include paddings and borders when the 'border-box' box
    // model is applied (except for IE).
    if (styles.boxSizing === 'border-box') {
        // Following conditions are required to handle Internet Explorer which
        // doesn't include paddings and borders to computed CSS dimensions.
        //
        // We can say that if CSS dimensions + paddings are equal to the "client"
        // properties then it's either IE, and thus we don't need to subtract
        // anything, or an element merely doesn't have paddings/borders styles.
        if (Math.round(width + horizPad) !== clientWidth) {
            width -= getBordersSize(styles, 'left', 'right') + horizPad;
        }
        if (Math.round(height + vertPad) !== clientHeight) {
            height -= getBordersSize(styles, 'top', 'bottom') + vertPad;
        }
    }
    // Following steps can't be applied to the document's root element as its
    // client[Width/Height] properties represent viewport area of the window.
    // Besides, it's as well not necessary as the <html> itself neither has
    // rendered scroll bars nor it can be clipped.
    if (!isDocumentElement(target)) {
        // In some browsers (only in Firefox, actually) CSS width & height
        // include scroll bars size which can be removed at this step as scroll
        // bars are the only difference between rounded dimensions + paddings
        // and "client" properties, though that is not always true in Chrome.
        var vertScrollbar = Math.round(width + horizPad) - clientWidth;
        var horizScrollbar = Math.round(height + vertPad) - clientHeight;
        // Chrome has a rather weird rounding of "client" properties.
        // E.g. for an element with content width of 314.2px it sometimes gives
        // the client width of 315px and for the width of 314.7px it may give
        // 314px. And it doesn't happen all the time. So just ignore this delta
        // as a non-relevant.
        if (Math.abs(vertScrollbar) !== 1) {
            width -= vertScrollbar;
        }
        if (Math.abs(horizScrollbar) !== 1) {
            height -= horizScrollbar;
        }
    }
    return createRectInit(paddings.left, paddings.top, width, height);
}
/**
 * Checks whether provided element is an instance of the SVGGraphicsElement.
 *
 * @param {Element} target - Element to be checked.
 * @returns {boolean}
 */
var isSVGGraphicsElement = (function () {
    // Some browsers, namely IE and Edge, don't have the SVGGraphicsElement
    // interface.
    if (typeof SVGGraphicsElement !== 'undefined') {
        return function (target) { return target instanceof getWindowOf(target).SVGGraphicsElement; };
    }
    // If it's so, then check that element is at least an instance of the
    // SVGElement and that it has the "getBBox" method.
    // eslint-disable-next-line no-extra-parens
    return function (target) { return (target instanceof getWindowOf(target).SVGElement &&
        typeof target.getBBox === 'function'); };
})();
/**
 * Checks whether provided element is a document element (<html>).
 *
 * @param {Element} target - Element to be checked.
 * @returns {boolean}
 */
function isDocumentElement(target) {
    return target === getWindowOf(target).document.documentElement;
}
/**
 * Calculates an appropriate content rectangle for provided html or svg element.
 *
 * @param {Element} target - Element content rectangle of which needs to be calculated.
 * @returns {DOMRectInit}
 */
function getContentRect(target) {
    if (!isBrowser) {
        return emptyRect;
    }
    if (isSVGGraphicsElement(target)) {
        return getSVGContentRect(target);
    }
    return getHTMLElementContentRect(target);
}
/**
 * Creates rectangle with an interface of the DOMRectReadOnly.
 * Spec: https://drafts.fxtf.org/geometry/#domrectreadonly
 *
 * @param {DOMRectInit} rectInit - Object with rectangle's x/y coordinates and dimensions.
 * @returns {DOMRectReadOnly}
 */
function createReadOnlyRect(_a) {
    var x = _a.x, y = _a.y, width = _a.width, height = _a.height;
    // If DOMRectReadOnly is available use it as a prototype for the rectangle.
    var Constr = typeof DOMRectReadOnly !== 'undefined' ? DOMRectReadOnly : Object;
    var rect = Object.create(Constr.prototype);
    // Rectangle's properties are not writable and non-enumerable.
    defineConfigurable(rect, {
        x: x, y: y, width: width, height: height,
        top: y,
        right: x + width,
        bottom: height + y,
        left: x
    });
    return rect;
}
/**
 * Creates DOMRectInit object based on the provided dimensions and the x/y coordinates.
 * Spec: https://drafts.fxtf.org/geometry/#dictdef-domrectinit
 *
 * @param {number} x - X coordinate.
 * @param {number} y - Y coordinate.
 * @param {number} width - Rectangle's width.
 * @param {number} height - Rectangle's height.
 * @returns {DOMRectInit}
 */
function createRectInit(x, y, width, height) {
    return { x: x, y: y, width: width, height: height };
}

/**
 * Class that is responsible for computations of the content rectangle of
 * provided DOM element and for keeping track of it's changes.
 */
var ResizeObservation = /** @class */ (function () {
    /**
     * Creates an instance of ResizeObservation.
     *
     * @param {Element} target - Element to be observed.
     */
    function ResizeObservation(target) {
        /**
         * Broadcasted width of content rectangle.
         *
         * @type {number}
         */
        this.broadcastWidth = 0;
        /**
         * Broadcasted height of content rectangle.
         *
         * @type {number}
         */
        this.broadcastHeight = 0;
        /**
         * Reference to the last observed content rectangle.
         *
         * @private {DOMRectInit}
         */
        this.contentRect_ = createRectInit(0, 0, 0, 0);
        this.target = target;
    }
    /**
     * Updates content rectangle and tells whether it's width or height properties
     * have changed since the last broadcast.
     *
     * @returns {boolean}
     */
    ResizeObservation.prototype.isActive = function () {
        var rect = getContentRect(this.target);
        this.contentRect_ = rect;
        return (rect.width !== this.broadcastWidth ||
            rect.height !== this.broadcastHeight);
    };
    /**
     * Updates 'broadcastWidth' and 'broadcastHeight' properties with a data
     * from the corresponding properties of the last observed content rectangle.
     *
     * @returns {DOMRectInit} Last observed content rectangle.
     */
    ResizeObservation.prototype.broadcastRect = function () {
        var rect = this.contentRect_;
        this.broadcastWidth = rect.width;
        this.broadcastHeight = rect.height;
        return rect;
    };
    return ResizeObservation;
}());

var ResizeObserverEntry = /** @class */ (function () {
    /**
     * Creates an instance of ResizeObserverEntry.
     *
     * @param {Element} target - Element that is being observed.
     * @param {DOMRectInit} rectInit - Data of the element's content rectangle.
     */
    function ResizeObserverEntry(target, rectInit) {
        var contentRect = createReadOnlyRect(rectInit);
        // According to the specification following properties are not writable
        // and are also not enumerable in the native implementation.
        //
        // Property accessors are not being used as they'd require to define a
        // private WeakMap storage which may cause memory leaks in browsers that
        // don't support this type of collections.
        defineConfigurable(this, { target: target, contentRect: contentRect });
    }
    return ResizeObserverEntry;
}());

var ResizeObserverSPI = /** @class */ (function () {
    /**
     * Creates a new instance of ResizeObserver.
     *
     * @param {ResizeObserverCallback} callback - Callback function that is invoked
     *      when one of the observed elements changes it's content dimensions.
     * @param {ResizeObserverController} controller - Controller instance which
     *      is responsible for the updates of observer.
     * @param {ResizeObserver} callbackCtx - Reference to the public
     *      ResizeObserver instance which will be passed to callback function.
     */
    function ResizeObserverSPI(callback, controller, callbackCtx) {
        /**
         * Collection of resize observations that have detected changes in dimensions
         * of elements.
         *
         * @private {Array<ResizeObservation>}
         */
        this.activeObservations_ = [];
        /**
         * Registry of the ResizeObservation instances.
         *
         * @private {Map<Element, ResizeObservation>}
         */
        this.observations_ = new MapShim();
        if (typeof callback !== 'function') {
            throw new TypeError('The callback provided as parameter 1 is not a function.');
        }
        this.callback_ = callback;
        this.controller_ = controller;
        this.callbackCtx_ = callbackCtx;
    }
    /**
     * Starts observing provided element.
     *
     * @param {Element} target - Element to be observed.
     * @returns {void}
     */
    ResizeObserverSPI.prototype.observe = function (target) {
        if (!arguments.length) {
            throw new TypeError('1 argument required, but only 0 present.');
        }
        // Do nothing if current environment doesn't have the Element interface.
        if (typeof Element === 'undefined' || !(Element instanceof Object)) {
            return;
        }
        if (!(target instanceof getWindowOf(target).Element)) {
            throw new TypeError('parameter 1 is not of type "Element".');
        }
        var observations = this.observations_;
        // Do nothing if element is already being observed.
        if (observations.has(target)) {
            return;
        }
        observations.set(target, new ResizeObservation(target));
        this.controller_.addObserver(this);
        // Force the update of observations.
        this.controller_.refresh();
    };
    /**
     * Stops observing provided element.
     *
     * @param {Element} target - Element to stop observing.
     * @returns {void}
     */
    ResizeObserverSPI.prototype.unobserve = function (target) {
        if (!arguments.length) {
            throw new TypeError('1 argument required, but only 0 present.');
        }
        // Do nothing if current environment doesn't have the Element interface.
        if (typeof Element === 'undefined' || !(Element instanceof Object)) {
            return;
        }
        if (!(target instanceof getWindowOf(target).Element)) {
            throw new TypeError('parameter 1 is not of type "Element".');
        }
        var observations = this.observations_;
        // Do nothing if element is not being observed.
        if (!observations.has(target)) {
            return;
        }
        observations.delete(target);
        if (!observations.size) {
            this.controller_.removeObserver(this);
        }
    };
    /**
     * Stops observing all elements.
     *
     * @returns {void}
     */
    ResizeObserverSPI.prototype.disconnect = function () {
        this.clearActive();
        this.observations_.clear();
        this.controller_.removeObserver(this);
    };
    /**
     * Collects observation instances the associated element of which has changed
     * it's content rectangle.
     *
     * @returns {void}
     */
    ResizeObserverSPI.prototype.gatherActive = function () {
        var _this = this;
        this.clearActive();
        this.observations_.forEach(function (observation) {
            if (observation.isActive()) {
                _this.activeObservations_.push(observation);
            }
        });
    };
    /**
     * Invokes initial callback function with a list of ResizeObserverEntry
     * instances collected from active resize observations.
     *
     * @returns {void}
     */
    ResizeObserverSPI.prototype.broadcastActive = function () {
        // Do nothing if observer doesn't have active observations.
        if (!this.hasActive()) {
            return;
        }
        var ctx = this.callbackCtx_;
        // Create ResizeObserverEntry instance for every active observation.
        var entries = this.activeObservations_.map(function (observation) {
            return new ResizeObserverEntry(observation.target, observation.broadcastRect());
        });
        this.callback_.call(ctx, entries, ctx);
        this.clearActive();
    };
    /**
     * Clears the collection of active observations.
     *
     * @returns {void}
     */
    ResizeObserverSPI.prototype.clearActive = function () {
        this.activeObservations_.splice(0);
    };
    /**
     * Tells whether observer has active observations.
     *
     * @returns {boolean}
     */
    ResizeObserverSPI.prototype.hasActive = function () {
        return this.activeObservations_.length > 0;
    };
    return ResizeObserverSPI;
}());

// Registry of internal observers. If WeakMap is not available use current shim
// for the Map collection as it has all required methods and because WeakMap
// can't be fully polyfilled anyway.
var observers = typeof WeakMap !== 'undefined' ? new WeakMap() : new MapShim();
/**
 * ResizeObserver API. Encapsulates the ResizeObserver SPI implementation
 * exposing only those methods and properties that are defined in the spec.
 */
var ResizeObserver = /** @class */ (function () {
    /**
     * Creates a new instance of ResizeObserver.
     *
     * @param {ResizeObserverCallback} callback - Callback that is invoked when
     *      dimensions of the observed elements change.
     */
    function ResizeObserver(callback) {
        if (!(this instanceof ResizeObserver)) {
            throw new TypeError('Cannot call a class as a function.');
        }
        if (!arguments.length) {
            throw new TypeError('1 argument required, but only 0 present.');
        }
        var controller = ResizeObserverController.getInstance();
        var observer = new ResizeObserverSPI(callback, controller, this);
        observers.set(this, observer);
    }
    return ResizeObserver;
}());
// Expose public methods of ResizeObserver.
[
    'observe',
    'unobserve',
    'disconnect'
].forEach(function (method) {
    ResizeObserver.prototype[method] = function () {
        var _a;
        return (_a = observers.get(this))[method].apply(_a, arguments);
    };
});

var index = (function () {
    // Export existing implementation if available.
    if (typeof global$1.ResizeObserver !== 'undefined') {
        return global$1.ResizeObserver;
    }
    return ResizeObserver;
})();

/* harmony default export */ __webpack_exports__["a"] = (index);

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(33)))

/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _interopRequireDefault = __webpack_require__(34);

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _react = _interopRequireDefault(__webpack_require__(0));

var _createSvgIcon = _interopRequireDefault(__webpack_require__(44));

var _default = (0, _createSvgIcon.default)(_react.default.createElement("path", {
  d: "M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
}), 'Clear');

exports.default = _default;

/***/ }),
/* 76 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXTERNAL MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/defineProperty.js
var defineProperty = __webpack_require__(22);

// EXTERNAL MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js + 1 modules
var objectWithoutProperties = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/@material-ui/utils/esm/deepmerge.js + 2 modules
var deepmerge = __webpack_require__(158);

// EXTERNAL MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/extends.js
var esm_extends = __webpack_require__(2);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/createBreakpoints.js


// Sorted ASC by size. That's important.
// It can't be configured as it's used statically for propTypes.
var keys = ['xs', 'sm', 'md', 'lg', 'xl']; // Keep in mind that @media is inclusive by the CSS specification.

function createBreakpoints(breakpoints) {
  var _breakpoints$values = breakpoints.values,
      values = _breakpoints$values === void 0 ? {
    xs: 0,
    sm: 600,
    md: 960,
    lg: 1280,
    xl: 1920
  } : _breakpoints$values,
      _breakpoints$unit = breakpoints.unit,
      unit = _breakpoints$unit === void 0 ? 'px' : _breakpoints$unit,
      _breakpoints$step = breakpoints.step,
      step = _breakpoints$step === void 0 ? 5 : _breakpoints$step,
      other = Object(objectWithoutProperties["a" /* default */])(breakpoints, ["values", "unit", "step"]);

  function up(key) {
    var value = typeof values[key] === 'number' ? values[key] : key;
    return "@media (min-width:".concat(value).concat(unit, ")");
  }

  function down(key) {
    var endIndex = keys.indexOf(key) + 1;
    var upperbound = values[keys[endIndex]];

    if (endIndex === keys.length) {
      // xl down applies to all sizes
      return up('xs');
    }

    var value = typeof upperbound === 'number' && endIndex > 0 ? upperbound : key;
    return "@media (max-width:".concat(value - step / 100).concat(unit, ")");
  }

  function between(start, end) {
    var endIndex = keys.indexOf(end);

    if (endIndex === keys.length - 1) {
      return up(start);
    }

    return "@media (min-width:".concat(typeof values[start] === 'number' ? values[start] : start).concat(unit, ") and ") + "(max-width:".concat((endIndex !== -1 && typeof values[keys[endIndex + 1]] === 'number' ? values[keys[endIndex + 1]] : end) - step / 100).concat(unit, ")");
  }

  function only(key) {
    return between(key, key);
  }

  function width(key) {
    return values[key];
  }

  return Object(esm_extends["a" /* default */])({
    keys: keys,
    values: values,
    up: up,
    down: down,
    between: between,
    only: only,
    width: width
  }, other);
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/createMixins.js


function createMixins(breakpoints, spacing, mixins) {
  var _toolbar;

  return Object(esm_extends["a" /* default */])({
    gutters: function gutters() {
      var styles = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      // To deprecate in v4.1
      //       warning(
      //         false,
      //         [
      //           'Material-UI: theme.mixins.gutters() is deprecated.',
      //           'You can use the source of the mixin directly:',
      //           `
      // paddingLeft: theme.spacing(2),
      // paddingRight: theme.spacing(2),
      // [theme.breakpoints.up('sm')]: {
      //   paddingLeft: theme.spacing(3),
      //   paddingRight: theme.spacing(3),
      // },
      // `,
      //         ].join('\n'),
      //       );
      return Object(esm_extends["a" /* default */])({
        paddingLeft: spacing(2),
        paddingRight: spacing(2)
      }, styles, Object(defineProperty["a" /* default */])({}, breakpoints.up('sm'), Object(esm_extends["a" /* default */])({
        paddingLeft: spacing(3),
        paddingRight: spacing(3)
      }, styles[breakpoints.up('sm')])));
    },
    toolbar: (_toolbar = {
      minHeight: 56
    }, Object(defineProperty["a" /* default */])(_toolbar, "".concat(breakpoints.up('xs'), " and (orientation: landscape)"), {
      minHeight: 48
    }), Object(defineProperty["a" /* default */])(_toolbar, breakpoints.up('sm'), {
      minHeight: 64
    }), _toolbar)
  }, mixins);
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/colors/common.js
var common = {
  black: '#000',
  white: '#fff'
};
/* harmony default export */ var colors_common = (common);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/colors/grey.js
var grey = {
  50: '#fafafa',
  100: '#f5f5f5',
  200: '#eeeeee',
  300: '#e0e0e0',
  400: '#bdbdbd',
  500: '#9e9e9e',
  600: '#757575',
  700: '#616161',
  800: '#424242',
  900: '#212121',
  A100: '#d5d5d5',
  A200: '#aaaaaa',
  A400: '#303030',
  A700: '#616161'
};
/* harmony default export */ var colors_grey = (grey);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/colors/indigo.js
var indigo = {
  50: '#e8eaf6',
  100: '#c5cae9',
  200: '#9fa8da',
  300: '#7986cb',
  400: '#5c6bc0',
  500: '#3f51b5',
  600: '#3949ab',
  700: '#303f9f',
  800: '#283593',
  900: '#1a237e',
  A100: '#8c9eff',
  A200: '#536dfe',
  A400: '#3d5afe',
  A700: '#304ffe'
};
/* harmony default export */ var colors_indigo = (indigo);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/colors/pink.js
var pink = {
  50: '#fce4ec',
  100: '#f8bbd0',
  200: '#f48fb1',
  300: '#f06292',
  400: '#ec407a',
  500: '#e91e63',
  600: '#d81b60',
  700: '#c2185b',
  800: '#ad1457',
  900: '#880e4f',
  A100: '#ff80ab',
  A200: '#ff4081',
  A400: '#f50057',
  A700: '#c51162'
};
/* harmony default export */ var colors_pink = (pink);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/colors/red.js
var red = {
  50: '#ffebee',
  100: '#ffcdd2',
  200: '#ef9a9a',
  300: '#e57373',
  400: '#ef5350',
  500: '#f44336',
  600: '#e53935',
  700: '#d32f2f',
  800: '#c62828',
  900: '#b71c1c',
  A100: '#ff8a80',
  A200: '#ff5252',
  A400: '#ff1744',
  A700: '#d50000'
};
/* harmony default export */ var colors_red = (red);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/colors/orange.js
var orange = {
  50: '#fff3e0',
  100: '#ffe0b2',
  200: '#ffcc80',
  300: '#ffb74d',
  400: '#ffa726',
  500: '#ff9800',
  600: '#fb8c00',
  700: '#f57c00',
  800: '#ef6c00',
  900: '#e65100',
  A100: '#ffd180',
  A200: '#ffab40',
  A400: '#ff9100',
  A700: '#ff6d00'
};
/* harmony default export */ var colors_orange = (orange);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/colors/blue.js
var blue = {
  50: '#e3f2fd',
  100: '#bbdefb',
  200: '#90caf9',
  300: '#64b5f6',
  400: '#42a5f5',
  500: '#2196f3',
  600: '#1e88e5',
  700: '#1976d2',
  800: '#1565c0',
  900: '#0d47a1',
  A100: '#82b1ff',
  A200: '#448aff',
  A400: '#2979ff',
  A700: '#2962ff'
};
/* harmony default export */ var colors_blue = (blue);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/colors/green.js
var green = {
  50: '#e8f5e9',
  100: '#c8e6c9',
  200: '#a5d6a7',
  300: '#81c784',
  400: '#66bb6a',
  500: '#4caf50',
  600: '#43a047',
  700: '#388e3c',
  800: '#2e7d32',
  900: '#1b5e20',
  A100: '#b9f6ca',
  A200: '#69f0ae',
  A400: '#00e676',
  A700: '#00c853'
};
/* harmony default export */ var colors_green = (green);
// EXTERNAL MODULE: ./node_modules/@material-ui/core/esm/styles/colorManipulator.js
var colorManipulator = __webpack_require__(11);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/createPalette.js












var light = {
  // The colors used to style the text.
  text: {
    // The most important text.
    primary: 'rgba(0, 0, 0, 0.87)',
    // Secondary text.
    secondary: 'rgba(0, 0, 0, 0.54)',
    // Disabled text have even lower visual prominence.
    disabled: 'rgba(0, 0, 0, 0.38)',
    // Text hints.
    hint: 'rgba(0, 0, 0, 0.38)'
  },
  // The color used to divide different elements.
  divider: 'rgba(0, 0, 0, 0.12)',
  // The background colors used to style the surfaces.
  // Consistency between these values is important.
  background: {
    paper: colors_common.white,
    default: colors_grey[50]
  },
  // The colors used to style the action elements.
  action: {
    // The color of an active action like an icon button.
    active: 'rgba(0, 0, 0, 0.54)',
    // The color of an hovered action.
    hover: 'rgba(0, 0, 0, 0.04)',
    hoverOpacity: 0.04,
    // The color of a selected action.
    selected: 'rgba(0, 0, 0, 0.08)',
    selectedOpacity: 0.08,
    // The color of a disabled action.
    disabled: 'rgba(0, 0, 0, 0.26)',
    // The background color of a disabled action.
    disabledBackground: 'rgba(0, 0, 0, 0.12)',
    disabledOpacity: 0.38,
    focus: 'rgba(0, 0, 0, 0.12)',
    focusOpacity: 0.12,
    activatedOpaciy: 0.12
  }
};
var dark = {
  text: {
    primary: colors_common.white,
    secondary: 'rgba(255, 255, 255, 0.7)',
    disabled: 'rgba(255, 255, 255, 0.5)',
    hint: 'rgba(255, 255, 255, 0.5)',
    icon: 'rgba(255, 255, 255, 0.5)'
  },
  divider: 'rgba(255, 255, 255, 0.12)',
  background: {
    paper: colors_grey[800],
    default: '#303030'
  },
  action: {
    active: colors_common.white,
    hover: 'rgba(255, 255, 255, 0.08)',
    hoverOpacity: 0.08,
    selected: 'rgba(255, 255, 255, 0.16)',
    selectedOpacity: 0.16,
    disabled: 'rgba(255, 255, 255, 0.3)',
    disabledBackground: 'rgba(255, 255, 255, 0.12)',
    disabledOpacity: 0.38,
    focus: 'rgba(255, 255, 255, 0.12)',
    focusOpacity: 0.12,
    activatedOpaciy: 0.24
  }
};

function addLightOrDark(intent, direction, shade, tonalOffset) {
  if (!intent[direction]) {
    if (intent.hasOwnProperty(shade)) {
      intent[direction] = intent[shade];
    } else if (direction === 'light') {
      intent.light = Object(colorManipulator["d" /* lighten */])(intent.main, tonalOffset);
    } else if (direction === 'dark') {
      intent.dark = Object(colorManipulator["a" /* darken */])(intent.main, tonalOffset * 1.5);
    }
  }
}

function createPalette(palette) {
  var _palette$primary = palette.primary,
      primary = _palette$primary === void 0 ? {
    light: colors_indigo[300],
    main: colors_indigo[500],
    dark: colors_indigo[700]
  } : _palette$primary,
      _palette$secondary = palette.secondary,
      secondary = _palette$secondary === void 0 ? {
    light: colors_pink.A200,
    main: colors_pink.A400,
    dark: colors_pink.A700
  } : _palette$secondary,
      _palette$error = palette.error,
      error = _palette$error === void 0 ? {
    light: colors_red[300],
    main: colors_red[500],
    dark: colors_red[700]
  } : _palette$error,
      _palette$warning = palette.warning,
      warning = _palette$warning === void 0 ? {
    light: colors_orange[300],
    main: colors_orange[500],
    dark: colors_orange[700]
  } : _palette$warning,
      _palette$info = palette.info,
      info = _palette$info === void 0 ? {
    light: colors_blue[300],
    main: colors_blue[500],
    dark: colors_blue[700]
  } : _palette$info,
      _palette$success = palette.success,
      success = _palette$success === void 0 ? {
    light: colors_green[300],
    main: colors_green[500],
    dark: colors_green[700]
  } : _palette$success,
      _palette$type = palette.type,
      type = _palette$type === void 0 ? 'light' : _palette$type,
      _palette$contrastThre = palette.contrastThreshold,
      contrastThreshold = _palette$contrastThre === void 0 ? 3 : _palette$contrastThre,
      _palette$tonalOffset = palette.tonalOffset,
      tonalOffset = _palette$tonalOffset === void 0 ? 0.2 : _palette$tonalOffset,
      other = Object(objectWithoutProperties["a" /* default */])(palette, ["primary", "secondary", "error", "warning", "info", "success", "type", "contrastThreshold", "tonalOffset"]); // Use the same logic as
  // Bootstrap: https://github.com/twbs/bootstrap/blob/1d6e3710dd447de1a200f29e8fa521f8a0908f70/scss/_functions.scss#L59
  // and material-components-web https://github.com/material-components/material-components-web/blob/ac46b8863c4dab9fc22c4c662dc6bd1b65dd652f/packages/mdc-theme/_functions.scss#L54


  function getContrastText(background) {
    if (!background) {
      throw new TypeError("Material-UI: missing background argument in getContrastText(".concat(background, ")."));
    }

    var contrastText = Object(colorManipulator["c" /* getContrastRatio */])(background, dark.text.primary) >= contrastThreshold ? dark.text.primary : light.text.primary;

    if (false) { var contrast; }

    return contrastText;
  }

  function augmentColor(color) {
    var mainShade = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 500;
    var lightShade = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 300;
    var darkShade = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 700;
    color = Object(esm_extends["a" /* default */])({}, color);

    if (!color.main && color[mainShade]) {
      color.main = color[mainShade];
    }

    if (false) {}

    addLightOrDark(color, 'light', lightShade, tonalOffset);
    addLightOrDark(color, 'dark', darkShade, tonalOffset);

    if (!color.contrastText) {
      color.contrastText = getContrastText(color.main);
    }

    return color;
  }

  var types = {
    dark: dark,
    light: light
  };

  if (false) {}

  var paletteOutput = Object(deepmerge["a" /* default */])(Object(esm_extends["a" /* default */])({
    // A collection of common colors.
    common: colors_common,
    // The palette type, can be light or dark.
    type: type,
    // The colors used to represent primary interface elements for a user.
    primary: augmentColor(primary),
    // The colors used to represent secondary interface elements for a user.
    secondary: augmentColor(secondary, 'A400', 'A200', 'A700'),
    // The colors used to represent interface elements that the user should be made aware of.
    error: augmentColor(error),
    // The colors used to represent potentially dangerous actions or important messages.
    warning: augmentColor(warning),
    // The colors used to present information to the user that is neutral and not necessarily important.
    info: augmentColor(info),
    // The colors used to indicate the successful completion of an action that user triggered.
    success: augmentColor(success),
    // The grey colors.
    grey: colors_grey,
    // Used by `getContrastText()` to maximize the contrast between
    // the background and the text.
    contrastThreshold: contrastThreshold,
    // Takes a background color and returns the text color that maximizes the contrast.
    getContrastText: getContrastText,
    // Generate a rich color object.
    augmentColor: augmentColor,
    // Used by the functions below to shift a color's luminance by approximately
    // two indexes within its tonal palette.
    // E.g., shift from Red 500 to Red 300 or Red 700.
    tonalOffset: tonalOffset
  }, types[type]), other);
  return paletteOutput;
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/createTypography.js




function round(value) {
  return Math.round(value * 1e5) / 1e5;
}

var caseAllCaps = {
  textTransform: 'uppercase'
};
var defaultFontFamily = '"Roboto", "Helvetica", "Arial", sans-serif';
/**
 * @see @link{https://material.io/design/typography/the-type-system.html}
 * @see @link{https://material.io/design/typography/understanding-typography.html}
 */

function createTypography(palette, typography) {
  var _ref = typeof typography === 'function' ? typography(palette) : typography,
      _ref$fontFamily = _ref.fontFamily,
      fontFamily = _ref$fontFamily === void 0 ? defaultFontFamily : _ref$fontFamily,
      _ref$fontSize = _ref.fontSize,
      fontSize = _ref$fontSize === void 0 ? 14 : _ref$fontSize,
      _ref$fontWeightLight = _ref.fontWeightLight,
      fontWeightLight = _ref$fontWeightLight === void 0 ? 300 : _ref$fontWeightLight,
      _ref$fontWeightRegula = _ref.fontWeightRegular,
      fontWeightRegular = _ref$fontWeightRegula === void 0 ? 400 : _ref$fontWeightRegula,
      _ref$fontWeightMedium = _ref.fontWeightMedium,
      fontWeightMedium = _ref$fontWeightMedium === void 0 ? 500 : _ref$fontWeightMedium,
      _ref$fontWeightBold = _ref.fontWeightBold,
      fontWeightBold = _ref$fontWeightBold === void 0 ? 700 : _ref$fontWeightBold,
      _ref$htmlFontSize = _ref.htmlFontSize,
      htmlFontSize = _ref$htmlFontSize === void 0 ? 16 : _ref$htmlFontSize,
      allVariants = _ref.allVariants,
      pxToRem2 = _ref.pxToRem,
      other = Object(objectWithoutProperties["a" /* default */])(_ref, ["fontFamily", "fontSize", "fontWeightLight", "fontWeightRegular", "fontWeightMedium", "fontWeightBold", "htmlFontSize", "allVariants", "pxToRem"]);

  if (false) {}

  var coef = fontSize / 14;

  var pxToRem = pxToRem2 || function (size) {
    return "".concat(size / htmlFontSize * coef, "rem");
  };

  var buildVariant = function buildVariant(fontWeight, size, lineHeight, letterSpacing, casing) {
    return Object(esm_extends["a" /* default */])({
      fontFamily: fontFamily,
      fontWeight: fontWeight,
      fontSize: pxToRem(size),
      // Unitless following https://meyerweb.com/eric/thoughts/2006/02/08/unitless-line-heights/
      lineHeight: lineHeight
    }, fontFamily === defaultFontFamily ? {
      letterSpacing: "".concat(round(letterSpacing / size), "em")
    } : {}, {}, casing, {}, allVariants);
  };

  var variants = {
    h1: buildVariant(fontWeightLight, 96, 1.167, -1.5),
    h2: buildVariant(fontWeightLight, 60, 1.2, -0.5),
    h3: buildVariant(fontWeightRegular, 48, 1.167, 0),
    h4: buildVariant(fontWeightRegular, 34, 1.235, 0.25),
    h5: buildVariant(fontWeightRegular, 24, 1.334, 0),
    h6: buildVariant(fontWeightMedium, 20, 1.6, 0.15),
    subtitle1: buildVariant(fontWeightRegular, 16, 1.75, 0.15),
    subtitle2: buildVariant(fontWeightMedium, 14, 1.57, 0.1),
    body1: buildVariant(fontWeightRegular, 16, 1.5, 0.15),
    body2: buildVariant(fontWeightRegular, 14, 1.43, 0.15),
    button: buildVariant(fontWeightMedium, 14, 1.75, 0.4, caseAllCaps),
    caption: buildVariant(fontWeightRegular, 12, 1.66, 0.4),
    overline: buildVariant(fontWeightRegular, 12, 2.66, 1, caseAllCaps)
  };
  return Object(deepmerge["a" /* default */])(Object(esm_extends["a" /* default */])({
    htmlFontSize: htmlFontSize,
    pxToRem: pxToRem,
    round: round,
    // TODO v5: remove
    fontFamily: fontFamily,
    fontSize: fontSize,
    fontWeightLight: fontWeightLight,
    fontWeightRegular: fontWeightRegular,
    fontWeightMedium: fontWeightMedium,
    fontWeightBold: fontWeightBold
  }, variants), other, {
    clone: false // No need to clone deep

  });
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/shadows.js
var shadowKeyUmbraOpacity = 0.2;
var shadowKeyPenumbraOpacity = 0.14;
var shadowAmbientShadowOpacity = 0.12;

function createShadow() {
  return ["".concat(arguments.length <= 0 ? undefined : arguments[0], "px ").concat(arguments.length <= 1 ? undefined : arguments[1], "px ").concat(arguments.length <= 2 ? undefined : arguments[2], "px ").concat(arguments.length <= 3 ? undefined : arguments[3], "px rgba(0,0,0,").concat(shadowKeyUmbraOpacity, ")"), "".concat(arguments.length <= 4 ? undefined : arguments[4], "px ").concat(arguments.length <= 5 ? undefined : arguments[5], "px ").concat(arguments.length <= 6 ? undefined : arguments[6], "px ").concat(arguments.length <= 7 ? undefined : arguments[7], "px rgba(0,0,0,").concat(shadowKeyPenumbraOpacity, ")"), "".concat(arguments.length <= 8 ? undefined : arguments[8], "px ").concat(arguments.length <= 9 ? undefined : arguments[9], "px ").concat(arguments.length <= 10 ? undefined : arguments[10], "px ").concat(arguments.length <= 11 ? undefined : arguments[11], "px rgba(0,0,0,").concat(shadowAmbientShadowOpacity, ")")].join(',');
} // Values from https://github.com/material-components/material-components-web/blob/be8747f94574669cb5e7add1a7c54fa41a89cec7/packages/mdc-elevation/_variables.scss


var shadows = ['none', createShadow(0, 2, 1, -1, 0, 1, 1, 0, 0, 1, 3, 0), createShadow(0, 3, 1, -2, 0, 2, 2, 0, 0, 1, 5, 0), createShadow(0, 3, 3, -2, 0, 3, 4, 0, 0, 1, 8, 0), createShadow(0, 2, 4, -1, 0, 4, 5, 0, 0, 1, 10, 0), createShadow(0, 3, 5, -1, 0, 5, 8, 0, 0, 1, 14, 0), createShadow(0, 3, 5, -1, 0, 6, 10, 0, 0, 1, 18, 0), createShadow(0, 4, 5, -2, 0, 7, 10, 1, 0, 2, 16, 1), createShadow(0, 5, 5, -3, 0, 8, 10, 1, 0, 3, 14, 2), createShadow(0, 5, 6, -3, 0, 9, 12, 1, 0, 3, 16, 2), createShadow(0, 6, 6, -3, 0, 10, 14, 1, 0, 4, 18, 3), createShadow(0, 6, 7, -4, 0, 11, 15, 1, 0, 4, 20, 3), createShadow(0, 7, 8, -4, 0, 12, 17, 2, 0, 5, 22, 4), createShadow(0, 7, 8, -4, 0, 13, 19, 2, 0, 5, 24, 4), createShadow(0, 7, 9, -4, 0, 14, 21, 2, 0, 5, 26, 4), createShadow(0, 8, 9, -5, 0, 15, 22, 2, 0, 6, 28, 5), createShadow(0, 8, 10, -5, 0, 16, 24, 2, 0, 6, 30, 5), createShadow(0, 8, 11, -5, 0, 17, 26, 2, 0, 6, 32, 5), createShadow(0, 9, 11, -5, 0, 18, 28, 2, 0, 7, 34, 6), createShadow(0, 9, 12, -6, 0, 19, 29, 2, 0, 7, 36, 6), createShadow(0, 10, 13, -6, 0, 20, 31, 3, 0, 8, 38, 7), createShadow(0, 10, 13, -6, 0, 21, 33, 3, 0, 8, 40, 7), createShadow(0, 10, 14, -6, 0, 22, 35, 3, 0, 8, 42, 7), createShadow(0, 11, 14, -7, 0, 23, 36, 3, 0, 9, 44, 8), createShadow(0, 11, 15, -7, 0, 24, 38, 3, 0, 9, 46, 8)];
/* harmony default export */ var styles_shadows = (shadows);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/shape.js
var shape = {
  borderRadius: 4
};
/* harmony default export */ var styles_shape = (shape);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/createSpacing.js
var warnOnce;
function createSpacing() {
  var spacingInput = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8;

  // Already transformed.
  if (spacingInput.mui) {
    return spacingInput;
  } // All components align to an 8dp square baseline grid for mobile, tablet, and desktop.
  // https://material.io/design/layout/understanding-layout.html#pixel-density


  var transform;

  if (typeof spacingInput === 'function') {
    transform = spacingInput;
  } else {
    if (false) {}

    transform = function transform(factor) {
      if (false) {}

      return spacingInput * factor;
    };
  }

  var spacing = function spacing() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    if (false) {}

    if (args.length === 0) {
      return transform(1);
    }

    if (args.length === 1) {
      return transform(args[0]);
    }

    return args.map(function (factor) {
      var output = transform(factor);
      return typeof output === 'number' ? "".concat(output, "px") : output;
    }).join(' ');
  }; // Backward compatibility, to remove in v5.


  Object.defineProperty(spacing, 'unit', {
    get: function get() {
      if (false) {}

      return spacingInput;
    }
  });
  spacing.mui = true;
  return spacing;
}
// EXTERNAL MODULE: ./node_modules/@material-ui/core/esm/styles/transitions.js
var transitions = __webpack_require__(31);

// EXTERNAL MODULE: ./node_modules/@material-ui/core/esm/styles/zIndex.js
var zIndex = __webpack_require__(35);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/createMuiTheme.js













function createMuiTheme() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  var _options$breakpoints = options.breakpoints,
      breakpointsInput = _options$breakpoints === void 0 ? {} : _options$breakpoints,
      _options$mixins = options.mixins,
      mixinsInput = _options$mixins === void 0 ? {} : _options$mixins,
      _options$palette = options.palette,
      paletteInput = _options$palette === void 0 ? {} : _options$palette,
      spacingInput = options.spacing,
      _options$typography = options.typography,
      typographyInput = _options$typography === void 0 ? {} : _options$typography,
      other = Object(objectWithoutProperties["a" /* default */])(options, ["breakpoints", "mixins", "palette", "spacing", "typography"]);

  var palette = createPalette(paletteInput);
  var breakpoints = createBreakpoints(breakpointsInput);
  var spacing = createSpacing(spacingInput);
  var muiTheme = Object(deepmerge["a" /* default */])({
    breakpoints: breakpoints,
    direction: 'ltr',
    mixins: createMixins(breakpoints, spacing, mixinsInput),
    overrides: {},
    // Inject custom styles
    palette: palette,
    props: {},
    // Provide default props
    shadows: styles_shadows,
    typography: createTypography(palette, typographyInput),
    spacing: spacing,
    shape: styles_shape,
    transitions: transitions["a" /* default */],
    zIndex: zIndex["a" /* default */]
  }, other);

  for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }

  muiTheme = args.reduce(function (acc, argument) {
    return Object(deepmerge["a" /* default */])(acc, argument);
  }, muiTheme);

  if (false) { var traverse, pseudoClasses; }

  return muiTheme;
}

/* harmony default export */ var styles_createMuiTheme = __webpack_exports__["a"] = (createMuiTheme);

/***/ }),
/* 77 */,
/* 78 */,
/* 79 */,
/* 80 */,
/* 81 */,
/* 82 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/** @license React v16.11.0
 * react.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

var h=__webpack_require__(52),n="function"===typeof Symbol&&Symbol.for,p=n?Symbol.for("react.element"):60103,q=n?Symbol.for("react.portal"):60106,r=n?Symbol.for("react.fragment"):60107,t=n?Symbol.for("react.strict_mode"):60108,u=n?Symbol.for("react.profiler"):60114,v=n?Symbol.for("react.provider"):60109,w=n?Symbol.for("react.context"):60110,x=n?Symbol.for("react.forward_ref"):60112,y=n?Symbol.for("react.suspense"):60113;n&&Symbol.for("react.suspense_list");
var z=n?Symbol.for("react.memo"):60115,aa=n?Symbol.for("react.lazy"):60116;n&&Symbol.for("react.fundamental");n&&Symbol.for("react.responder");n&&Symbol.for("react.scope");var A="function"===typeof Symbol&&Symbol.iterator;
function B(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var C={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},D={};
function E(a,b,c){this.props=a;this.context=b;this.refs=D;this.updater=c||C}E.prototype.isReactComponent={};E.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error(B(85));this.updater.enqueueSetState(this,a,b,"setState")};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate")};function F(){}F.prototype=E.prototype;function G(a,b,c){this.props=a;this.context=b;this.refs=D;this.updater=c||C}var H=G.prototype=new F;
H.constructor=G;h(H,E.prototype);H.isPureReactComponent=!0;var I={current:null},J={current:null},K=Object.prototype.hasOwnProperty,L={key:!0,ref:!0,__self:!0,__source:!0};
function M(a,b,c){var e,d={},g=null,l=null;if(null!=b)for(e in void 0!==b.ref&&(l=b.ref),void 0!==b.key&&(g=""+b.key),b)K.call(b,e)&&!L.hasOwnProperty(e)&&(d[e]=b[e]);var f=arguments.length-2;if(1===f)d.children=c;else if(1<f){for(var k=Array(f),m=0;m<f;m++)k[m]=arguments[m+2];d.children=k}if(a&&a.defaultProps)for(e in f=a.defaultProps,f)void 0===d[e]&&(d[e]=f[e]);return{$$typeof:p,type:a,key:g,ref:l,props:d,_owner:J.current}}
function ba(a,b){return{$$typeof:p,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}function N(a){return"object"===typeof a&&null!==a&&a.$$typeof===p}function escape(a){var b={"=":"=0",":":"=2"};return"$"+(""+a).replace(/[=:]/g,function(a){return b[a]})}var O=/\/+/g,P=[];function Q(a,b,c,e){if(P.length){var d=P.pop();d.result=a;d.keyPrefix=b;d.func=c;d.context=e;d.count=0;return d}return{result:a,keyPrefix:b,func:c,context:e,count:0}}
function R(a){a.result=null;a.keyPrefix=null;a.func=null;a.context=null;a.count=0;10>P.length&&P.push(a)}
function S(a,b,c,e){var d=typeof a;if("undefined"===d||"boolean"===d)a=null;var g=!1;if(null===a)g=!0;else switch(d){case "string":case "number":g=!0;break;case "object":switch(a.$$typeof){case p:case q:g=!0}}if(g)return c(e,a,""===b?"."+T(a,0):b),1;g=0;b=""===b?".":b+":";if(Array.isArray(a))for(var l=0;l<a.length;l++){d=a[l];var f=b+T(d,l);g+=S(d,f,c,e)}else if(null===a||"object"!==typeof a?f=null:(f=A&&a[A]||a["@@iterator"],f="function"===typeof f?f:null),"function"===typeof f)for(a=f.call(a),l=
0;!(d=a.next()).done;)d=d.value,f=b+T(d,l++),g+=S(d,f,c,e);else if("object"===d)throw c=""+a,Error(B(31,"[object Object]"===c?"object with keys {"+Object.keys(a).join(", ")+"}":c,""));return g}function U(a,b,c){return null==a?0:S(a,"",b,c)}function T(a,b){return"object"===typeof a&&null!==a&&null!=a.key?escape(a.key):b.toString(36)}function ca(a,b){a.func.call(a.context,b,a.count++)}
function da(a,b,c){var e=a.result,d=a.keyPrefix;a=a.func.call(a.context,b,a.count++);Array.isArray(a)?V(a,e,c,function(a){return a}):null!=a&&(N(a)&&(a=ba(a,d+(!a.key||b&&b.key===a.key?"":(""+a.key).replace(O,"$&/")+"/")+c)),e.push(a))}function V(a,b,c,e,d){var g="";null!=c&&(g=(""+c).replace(O,"$&/")+"/");b=Q(b,g,e,d);U(a,da,b);R(b)}function W(){var a=I.current;if(null===a)throw Error(B(321));return a}
var X={Children:{map:function(a,b,c){if(null==a)return a;var e=[];V(a,e,null,b,c);return e},forEach:function(a,b,c){if(null==a)return a;b=Q(null,null,b,c);U(a,ca,b);R(b)},count:function(a){return U(a,function(){return null},null)},toArray:function(a){var b=[];V(a,b,null,function(a){return a});return b},only:function(a){if(!N(a))throw Error(B(143));return a}},createRef:function(){return{current:null}},Component:E,PureComponent:G,createContext:function(a,b){void 0===b&&(b=null);a={$$typeof:w,_calculateChangedBits:b,
_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null};a.Provider={$$typeof:v,_context:a};return a.Consumer=a},forwardRef:function(a){return{$$typeof:x,render:a}},lazy:function(a){return{$$typeof:aa,_ctor:a,_status:-1,_result:null}},memo:function(a,b){return{$$typeof:z,type:a,compare:void 0===b?null:b}},useCallback:function(a,b){return W().useCallback(a,b)},useContext:function(a,b){return W().useContext(a,b)},useEffect:function(a,b){return W().useEffect(a,b)},useImperativeHandle:function(a,
b,c){return W().useImperativeHandle(a,b,c)},useDebugValue:function(){},useLayoutEffect:function(a,b){return W().useLayoutEffect(a,b)},useMemo:function(a,b){return W().useMemo(a,b)},useReducer:function(a,b,c){return W().useReducer(a,b,c)},useRef:function(a){return W().useRef(a)},useState:function(a){return W().useState(a)},Fragment:r,Profiler:u,StrictMode:t,Suspense:y,createElement:M,cloneElement:function(a,b,c){if(null===a||void 0===a)throw Error(B(267,a));var e=h({},a.props),d=a.key,g=a.ref,l=a._owner;
if(null!=b){void 0!==b.ref&&(g=b.ref,l=J.current);void 0!==b.key&&(d=""+b.key);if(a.type&&a.type.defaultProps)var f=a.type.defaultProps;for(k in b)K.call(b,k)&&!L.hasOwnProperty(k)&&(e[k]=void 0===b[k]&&void 0!==f?f[k]:b[k])}var k=arguments.length-2;if(1===k)e.children=c;else if(1<k){f=Array(k);for(var m=0;m<k;m++)f[m]=arguments[m+2];e.children=f}return{$$typeof:p,type:a.type,key:d,ref:g,props:e,_owner:l}},createFactory:function(a){var b=M.bind(null,a);b.type=a;return b},isValidElement:N,version:"16.11.0",
__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{ReactCurrentDispatcher:I,ReactCurrentBatchConfig:{suspense:null},ReactCurrentOwner:J,IsSomeRendererActing:{current:!1},assign:h}},Y={default:X},Z=Y&&X||Y;module.exports=Z.default||Z;


/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/** @license React v16.11.0
 * react-dom.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

/*
 Modernizr 3.0.0pre (Custom Build) | MIT
*/
var aa=__webpack_require__(0),n=__webpack_require__(52),q=__webpack_require__(84);function u(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}if(!aa)throw Error(u(227));var ba=null,ca={};
function da(){if(ba)for(var a in ca){var b=ca[a],c=ba.indexOf(a);if(!(-1<c))throw Error(u(96,a));if(!ea[c]){if(!b.extractEvents)throw Error(u(97,a));ea[c]=b;c=b.eventTypes;for(var d in c){var e=void 0;var f=c[d],g=b,h=d;if(fa.hasOwnProperty(h))throw Error(u(99,h));fa[h]=f;var k=f.phasedRegistrationNames;if(k){for(e in k)k.hasOwnProperty(e)&&ha(k[e],g,h);e=!0}else f.registrationName?(ha(f.registrationName,g,h),e=!0):e=!1;if(!e)throw Error(u(98,d,a));}}}}
function ha(a,b,c){if(ia[a])throw Error(u(100,a));ia[a]=b;ja[a]=b.eventTypes[c].dependencies}var ea=[],fa={},ia={},ja={};function ka(a,b,c,d,e,f,g,h,k){var l=Array.prototype.slice.call(arguments,3);try{b.apply(c,l)}catch(m){this.onError(m)}}var la=!1,ma=null,na=!1,oa=null,pa={onError:function(a){la=!0;ma=a}};function qa(a,b,c,d,e,f,g,h,k){la=!1;ma=null;ka.apply(pa,arguments)}
function ra(a,b,c,d,e,f,g,h,k){qa.apply(this,arguments);if(la){if(la){var l=ma;la=!1;ma=null}else throw Error(u(198));na||(na=!0,oa=l)}}var sa=null,ua=null,va=null;function wa(a,b,c){var d=a.type||"unknown-event";a.currentTarget=va(c);ra(d,b,void 0,a);a.currentTarget=null}function xa(a,b){if(null==b)throw Error(u(30));if(null==a)return b;if(Array.isArray(a)){if(Array.isArray(b))return a.push.apply(a,b),a;a.push(b);return a}return Array.isArray(b)?[a].concat(b):[a,b]}
function ya(a,b,c){Array.isArray(a)?a.forEach(b,c):a&&b.call(c,a)}var za=null;function Aa(a){if(a){var b=a._dispatchListeners,c=a._dispatchInstances;if(Array.isArray(b))for(var d=0;d<b.length&&!a.isPropagationStopped();d++)wa(a,b[d],c[d]);else b&&wa(a,b,c);a._dispatchListeners=null;a._dispatchInstances=null;a.isPersistent()||a.constructor.release(a)}}function Ba(a){null!==a&&(za=xa(za,a));a=za;za=null;if(a){ya(a,Aa);if(za)throw Error(u(95));if(na)throw a=oa,na=!1,oa=null,a;}}
var Ca={injectEventPluginOrder:function(a){if(ba)throw Error(u(101));ba=Array.prototype.slice.call(a);da()},injectEventPluginsByName:function(a){var b=!1,c;for(c in a)if(a.hasOwnProperty(c)){var d=a[c];if(!ca.hasOwnProperty(c)||ca[c]!==d){if(ca[c])throw Error(u(102,c));ca[c]=d;b=!0}}b&&da()}};
function Da(a,b){var c=a.stateNode;if(!c)return null;var d=sa(c);if(!d)return null;c=d[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":(d=!d.disabled)||(a=a.type,d=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!d;break a;default:a=!1}if(a)return null;if(c&&"function"!==typeof c)throw Error(u(231,b,typeof c));
return c}var Ea=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;Ea.hasOwnProperty("ReactCurrentDispatcher")||(Ea.ReactCurrentDispatcher={current:null});Ea.hasOwnProperty("ReactCurrentBatchConfig")||(Ea.ReactCurrentBatchConfig={suspense:null});
var Fa=/^(.*)[\\\/]/,w="function"===typeof Symbol&&Symbol.for,Ga=w?Symbol.for("react.element"):60103,Ha=w?Symbol.for("react.portal"):60106,Ia=w?Symbol.for("react.fragment"):60107,Ja=w?Symbol.for("react.strict_mode"):60108,Ka=w?Symbol.for("react.profiler"):60114,La=w?Symbol.for("react.provider"):60109,Ma=w?Symbol.for("react.context"):60110,Na=w?Symbol.for("react.concurrent_mode"):60111,Oa=w?Symbol.for("react.forward_ref"):60112,Pa=w?Symbol.for("react.suspense"):60113,Qa=w?Symbol.for("react.suspense_list"):
60120,Ra=w?Symbol.for("react.memo"):60115,Sa=w?Symbol.for("react.lazy"):60116;w&&Symbol.for("react.fundamental");w&&Symbol.for("react.responder");w&&Symbol.for("react.scope");var Ta="function"===typeof Symbol&&Symbol.iterator;function Ua(a){if(null===a||"object"!==typeof a)return null;a=Ta&&a[Ta]||a["@@iterator"];return"function"===typeof a?a:null}
function Va(a){if(-1===a._status){a._status=0;var b=a._ctor;b=b();a._result=b;b.then(function(b){0===a._status&&(b=b.default,a._status=1,a._result=b)},function(b){0===a._status&&(a._status=2,a._result=b)})}}
function Wa(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case Ia:return"Fragment";case Ha:return"Portal";case Ka:return"Profiler";case Ja:return"StrictMode";case Pa:return"Suspense";case Qa:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Ma:return"Context.Consumer";case La:return"Context.Provider";case Oa:var b=a.render;b=b.displayName||b.name||"";return a.displayName||(""!==b?"ForwardRef("+b+")":
"ForwardRef");case Ra:return Wa(a.type);case Sa:if(a=1===a._status?a._result:null)return Wa(a)}return null}function Xa(a){var b="";do{a:switch(a.tag){case 3:case 4:case 6:case 7:case 10:case 9:var c="";break a;default:var d=a._debugOwner,e=a._debugSource,f=Wa(a.type);c=null;d&&(c=Wa(d.type));d=f;f="";e?f=" (at "+e.fileName.replace(Fa,"")+":"+e.lineNumber+")":c&&(f=" (created by "+c+")");c="\n    in "+(d||"Unknown")+f}b+=c;a=a.return}while(a);return b}
var Ya=!("undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement),Za=null,$a=null,ab=null;function bb(a){if(a=ua(a)){if("function"!==typeof Za)throw Error(u(280));var b=sa(a.stateNode);Za(a.stateNode,a.type,b)}}function cb(a){$a?ab?ab.push(a):ab=[a]:$a=a}function db(){if($a){var a=$a,b=ab;ab=$a=null;bb(a);if(b)for(a=0;a<b.length;a++)bb(b[a])}}function eb(a,b){return a(b)}function fb(a,b,c,d){return a(b,c,d)}function gb(){}
var hb=eb,ib=!1,jb=!1;function kb(){if(null!==$a||null!==ab)gb(),db()}new Map;var lb=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,mb=Object.prototype.hasOwnProperty,nb={},ob={};
function pb(a){if(mb.call(ob,a))return!0;if(mb.call(nb,a))return!1;if(lb.test(a))return ob[a]=!0;nb[a]=!0;return!1}function qb(a,b,c,d){if(null!==c&&0===c.type)return!1;switch(typeof b){case "function":case "symbol":return!0;case "boolean":if(d)return!1;if(null!==c)return!c.acceptsBooleans;a=a.toLowerCase().slice(0,5);return"data-"!==a&&"aria-"!==a;default:return!1}}
function rb(a,b,c,d){if(null===b||"undefined"===typeof b||qb(a,b,c,d))return!0;if(d)return!1;if(null!==c)switch(c.type){case 3:return!b;case 4:return!1===b;case 5:return isNaN(b);case 6:return isNaN(b)||1>b}return!1}function B(a,b,c,d,e,f){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f}var D={};
"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){D[a]=new B(a,0,!1,a,null,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];D[b]=new B(b,1,!1,a[1],null,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){D[a]=new B(a,2,!1,a.toLowerCase(),null,!1)});
["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){D[a]=new B(a,2,!1,a,null,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){D[a]=new B(a,3,!1,a.toLowerCase(),null,!1)});
["checked","multiple","muted","selected"].forEach(function(a){D[a]=new B(a,3,!0,a,null,!1)});["capture","download"].forEach(function(a){D[a]=new B(a,4,!1,a,null,!1)});["cols","rows","size","span"].forEach(function(a){D[a]=new B(a,6,!1,a,null,!1)});["rowSpan","start"].forEach(function(a){D[a]=new B(a,5,!1,a.toLowerCase(),null,!1)});var sb=/[\-:]([a-z])/g;function tb(a){return a[1].toUpperCase()}
"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(sb,
tb);D[b]=new B(b,1,!1,a,null,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(sb,tb);D[b]=new B(b,1,!1,a,"http://www.w3.org/1999/xlink",!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(sb,tb);D[b]=new B(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1)});["tabIndex","crossOrigin"].forEach(function(a){D[a]=new B(a,1,!1,a.toLowerCase(),null,!1)});
D.xlinkHref=new B("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0);["src","href","action","formAction"].forEach(function(a){D[a]=new B(a,1,!1,a.toLowerCase(),null,!0)});function ub(a){switch(typeof a){case "boolean":case "number":case "object":case "string":case "undefined":return a;default:return""}}
function vb(a,b,c,d){var e=D.hasOwnProperty(b)?D[b]:null;var f=null!==e?0===e.type:d?!1:!(2<b.length)||"o"!==b[0]&&"O"!==b[0]||"n"!==b[1]&&"N"!==b[1]?!1:!0;f||(rb(b,c,e,d)&&(c=null),d||null===e?pb(b)&&(null===c?a.removeAttribute(b):a.setAttribute(b,""+c)):e.mustUseProperty?a[e.propertyName]=null===c?3===e.type?!1:"":c:(b=e.attributeName,d=e.attributeNamespace,null===c?a.removeAttribute(b):(e=e.type,c=3===e||4===e&&!0===c?"":""+c,d?a.setAttributeNS(d,b,c):a.setAttribute(b,c))))}
function wb(a){var b=a.type;return(a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===b)}
function xb(a){var b=wb(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=""+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=""+a},stopTracking:function(){a._valueTracker=
null;delete a[b]}}}}function yb(a){a._valueTracker||(a._valueTracker=xb(a))}function zb(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d="";a&&(d=wb(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Ab(a,b){var c=b.checked;return n({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}
function Bb(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=ub(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value}}function Cb(a,b){b=b.checked;null!=b&&vb(a,"checked",b,!1)}
function Eb(a,b){Cb(a,b);var c=ub(b.value),d=b.type;if(null!=c)if("number"===d){if(0===c&&""===a.value||a.value!=c)a.value=""+c}else a.value!==""+c&&(a.value=""+c);else if("submit"===d||"reset"===d){a.removeAttribute("value");return}b.hasOwnProperty("value")?Fb(a,b.type,c):b.hasOwnProperty("defaultValue")&&Fb(a,b.type,ub(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}
function Gb(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;""!==c&&(a.name="");a.defaultChecked=!a.defaultChecked;a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c)}
function Fb(a,b,c){if("number"!==b||a.ownerDocument.activeElement!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c)}function Hb(a){var b="";aa.Children.forEach(a,function(a){null!=a&&(b+=a)});return b}function Ib(a,b){a=n({children:void 0},b);if(b=Hb(b.children))a.children=b;return a}
function Jb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e<c.length;e++)b["$"+c[e]]=!0;for(c=0;c<a.length;c++)e=b.hasOwnProperty("$"+a[c].value),a[c].selected!==e&&(a[c].selected=e),e&&d&&(a[c].defaultSelected=!0)}else{c=""+ub(c);b=null;for(e=0;e<a.length;e++){if(a[e].value===c){a[e].selected=!0;d&&(a[e].defaultSelected=!0);return}null!==b||a[e].disabled||(b=a[e])}null!==b&&(b.selected=!0)}}
function Kb(a,b){if(null!=b.dangerouslySetInnerHTML)throw Error(u(91));return n({},b,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}function Lb(a,b){var c=b.value;if(null==c){c=b.defaultValue;b=b.children;if(null!=b){if(null!=c)throw Error(u(92));if(Array.isArray(b)){if(!(1>=b.length))throw Error(u(93));b=b[0]}c=b}null==c&&(c="")}a._wrapperState={initialValue:ub(c)}}
function Mb(a,b){var c=ub(b.value),d=ub(b.defaultValue);null!=c&&(c=""+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=""+d)}function Nb(a){var b=a.textContent;b===a._wrapperState.initialValue&&""!==b&&null!==b&&(a.value=b)}var Ob={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"};
function Pb(a){switch(a){case "svg":return"http://www.w3.org/2000/svg";case "math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function Qb(a,b){return null==a||"http://www.w3.org/1999/xhtml"===a?Pb(b):"http://www.w3.org/2000/svg"===a&&"foreignObject"===b?"http://www.w3.org/1999/xhtml":a}
var Rb,Sb=function(a){return"undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,c,d,e)})}:a}(function(a,b){if(a.namespaceURI!==Ob.svg||"innerHTML"in a)a.innerHTML=b;else{Rb=Rb||document.createElement("div");Rb.innerHTML="<svg>"+b.valueOf().toString()+"</svg>";for(b=Rb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});
function Tb(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}function Ub(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c["Webkit"+a]="webkit"+b;c["Moz"+a]="moz"+b;return c}var Vb={animationend:Ub("Animation","AnimationEnd"),animationiteration:Ub("Animation","AnimationIteration"),animationstart:Ub("Animation","AnimationStart"),transitionend:Ub("Transition","TransitionEnd")},Wb={},Xb={};
Ya&&(Xb=document.createElement("div").style,"AnimationEvent"in window||(delete Vb.animationend.animation,delete Vb.animationiteration.animation,delete Vb.animationstart.animation),"TransitionEvent"in window||delete Vb.transitionend.transition);function Yb(a){if(Wb[a])return Wb[a];if(!Vb[a])return a;var b=Vb[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in Xb)return Wb[a]=b[c];return a}var Zb=Yb("animationend"),$b=Yb("animationiteration"),ac=Yb("animationstart"),bc=Yb("transitionend"),dc="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting".split(" ");
function ec(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else{a=b;do b=a,0!==(b.effectTag&1026)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function fc(a){if(13===a.tag){var b=a.memoizedState;null===b&&(a=a.alternate,null!==a&&(b=a.memoizedState));if(null!==b)return b.dehydrated}return null}function gc(a){if(ec(a)!==a)throw Error(u(188));}
function hc(a){var b=a.alternate;if(!b){b=ec(a);if(null===b)throw Error(u(188));return b!==a?null:a}for(var c=a,d=b;;){var e=c.return;if(null===e)break;var f=e.alternate;if(null===f){d=e.return;if(null!==d){c=d;continue}break}if(e.child===f.child){for(f=e.child;f;){if(f===c)return gc(e),a;if(f===d)return gc(e),b;f=f.sibling}throw Error(u(188));}if(c.return!==d.return)c=e,d=f;else{for(var g=!1,h=e.child;h;){if(h===c){g=!0;c=e;d=f;break}if(h===d){g=!0;d=e;c=f;break}h=h.sibling}if(!g){for(h=f.child;h;){if(h===
c){g=!0;c=f;d=e;break}if(h===d){g=!0;d=f;c=e;break}h=h.sibling}if(!g)throw Error(u(189));}}if(c.alternate!==d)throw Error(u(190));}if(3!==c.tag)throw Error(u(188));return c.stateNode.current===c?a:b}function ic(a){a=hc(a);if(!a)return null;for(var b=a;;){if(5===b.tag||6===b.tag)return b;if(b.child)b.child.return=b,b=b.child;else{if(b===a)break;for(;!b.sibling;){if(!b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}}return null}
var jc,kc,lc,mc=!1,nc=[],oc=null,pc=null,qc=null,rc=new Map,sc=new Map,tc=[],uc="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput close cancel copy cut paste click change contextmenu reset submit".split(" "),vc="focus blur dragenter dragleave mouseover mouseout pointerover pointerout gotpointercapture lostpointercapture".split(" ");
function wc(a){var b=xc(a);uc.forEach(function(c){yc(c,a,b)});vc.forEach(function(c){yc(c,a,b)})}function zc(a,b,c,d){return{blockedOn:a,topLevelType:b,eventSystemFlags:c|32,nativeEvent:d}}function Ac(a,b){switch(a){case "focus":case "blur":oc=null;break;case "dragenter":case "dragleave":pc=null;break;case "mouseover":case "mouseout":qc=null;break;case "pointerover":case "pointerout":rc.delete(b.pointerId);break;case "gotpointercapture":case "lostpointercapture":sc.delete(b.pointerId)}}
function Bc(a,b,c,d,e){if(null===a||a.nativeEvent!==e)return a=zc(b,c,d,e),null!==b&&(b=Cc(b),null!==b&&kc(b)),a;a.eventSystemFlags|=d;return a}function Dc(a,b,c,d){switch(b){case "focus":return oc=Bc(oc,a,b,c,d),!0;case "dragenter":return pc=Bc(pc,a,b,c,d),!0;case "mouseover":return qc=Bc(qc,a,b,c,d),!0;case "pointerover":var e=d.pointerId;rc.set(e,Bc(rc.get(e)||null,a,b,c,d));return!0;case "gotpointercapture":return e=d.pointerId,sc.set(e,Bc(sc.get(e)||null,a,b,c,d)),!0}return!1}
function Ec(a){var b=Fc(a.target);if(null!==b){var c=ec(b);if(null!==c)if(b=c.tag,13===b){if(b=fc(c),null!==b){a.blockedOn=b;q.unstable_runWithPriority(a.priority,function(){lc(c)});return}}else if(3===b&&c.stateNode.hydrate){a.blockedOn=3===c.tag?c.stateNode.containerInfo:null;return}}a.blockedOn=null}function Gc(a){if(null!==a.blockedOn)return!1;var b=Hc(a.topLevelType,a.eventSystemFlags,a.nativeEvent);if(null!==b){var c=Cc(b);null!==c&&kc(c);a.blockedOn=b;return!1}return!0}
function Ic(a,b,c){Gc(a)&&c.delete(b)}function Jc(){for(mc=!1;0<nc.length;){var a=nc[0];if(null!==a.blockedOn){a=Cc(a.blockedOn);null!==a&&jc(a);break}var b=Hc(a.topLevelType,a.eventSystemFlags,a.nativeEvent);null!==b?a.blockedOn=b:nc.shift()}null!==oc&&Gc(oc)&&(oc=null);null!==pc&&Gc(pc)&&(pc=null);null!==qc&&Gc(qc)&&(qc=null);rc.forEach(Ic);sc.forEach(Ic)}function Kc(a,b){a.blockedOn===b&&(a.blockedOn=null,mc||(mc=!0,q.unstable_scheduleCallback(q.unstable_NormalPriority,Jc)))}
function Lc(a){function b(b){return Kc(b,a)}if(0<nc.length){Kc(nc[0],a);for(var c=1;c<nc.length;c++){var d=nc[c];d.blockedOn===a&&(d.blockedOn=null)}}null!==oc&&Kc(oc,a);null!==pc&&Kc(pc,a);null!==qc&&Kc(qc,a);rc.forEach(b);sc.forEach(b);for(c=0;c<tc.length;c++)d=tc[c],d.blockedOn===a&&(d.blockedOn=null);for(;0<tc.length&&(c=tc[0],null===c.blockedOn);)Ec(c),null===c.blockedOn&&tc.shift()}
function Mc(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}function Nc(a){do a=a.return;while(a&&5!==a.tag);return a?a:null}function Oc(a,b,c){if(b=Da(a,c.dispatchConfig.phasedRegistrationNames[b]))c._dispatchListeners=xa(c._dispatchListeners,b),c._dispatchInstances=xa(c._dispatchInstances,a)}
function Pc(a){if(a&&a.dispatchConfig.phasedRegistrationNames){for(var b=a._targetInst,c=[];b;)c.push(b),b=Nc(b);for(b=c.length;0<b--;)Oc(c[b],"captured",a);for(b=0;b<c.length;b++)Oc(c[b],"bubbled",a)}}function Qc(a,b,c){a&&c&&c.dispatchConfig.registrationName&&(b=Da(a,c.dispatchConfig.registrationName))&&(c._dispatchListeners=xa(c._dispatchListeners,b),c._dispatchInstances=xa(c._dispatchInstances,a))}function Rc(a){a&&a.dispatchConfig.registrationName&&Qc(a._targetInst,null,a)}
function Sc(a){ya(a,Pc)}function Tc(){return!0}function Uc(){return!1}function E(a,b,c,d){this.dispatchConfig=a;this._targetInst=b;this.nativeEvent=c;a=this.constructor.Interface;for(var e in a)a.hasOwnProperty(e)&&((b=a[e])?this[e]=b(c):"target"===e?this.target=d:this[e]=c[e]);this.isDefaultPrevented=(null!=c.defaultPrevented?c.defaultPrevented:!1===c.returnValue)?Tc:Uc;this.isPropagationStopped=Uc;return this}
n(E.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!==typeof a.returnValue&&(a.returnValue=!1),this.isDefaultPrevented=Tc)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():"unknown"!==typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=Tc)},persist:function(){this.isPersistent=Tc},isPersistent:Uc,destructor:function(){var a=this.constructor.Interface,
b;for(b in a)this[b]=null;this.nativeEvent=this._targetInst=this.dispatchConfig=null;this.isPropagationStopped=this.isDefaultPrevented=Uc;this._dispatchInstances=this._dispatchListeners=null}});E.Interface={type:null,target:null,currentTarget:function(){return null},eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};
E.extend=function(a){function b(){}function c(){return d.apply(this,arguments)}var d=this;b.prototype=d.prototype;var e=new b;n(e,c.prototype);c.prototype=e;c.prototype.constructor=c;c.Interface=n({},d.Interface,a);c.extend=d.extend;Vc(c);return c};Vc(E);function Wc(a,b,c,d){if(this.eventPool.length){var e=this.eventPool.pop();this.call(e,a,b,c,d);return e}return new this(a,b,c,d)}
function Xc(a){if(!(a instanceof this))throw Error(u(279));a.destructor();10>this.eventPool.length&&this.eventPool.push(a)}function Vc(a){a.eventPool=[];a.getPooled=Wc;a.release=Xc}var Yc=E.extend({animationName:null,elapsedTime:null,pseudoElement:null}),Zc=E.extend({clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}}),$c=E.extend({view:null,detail:null}),ad=$c.extend({relatedTarget:null});
function bd(a){var b=a.keyCode;"charCode"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;10===a&&(a=13);return 32<=a||13===a?a:0}
var cd={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},ed={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",
116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},fd={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function gd(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):(a=fd[a])?!!b[a]:!1}function hd(){return gd}
var id=$c.extend({key:function(a){if(a.key){var b=cd[a.key]||a.key;if("Unidentified"!==b)return b}return"keypress"===a.type?(a=bd(a),13===a?"Enter":String.fromCharCode(a)):"keydown"===a.type||"keyup"===a.type?ed[a.keyCode]||"Unidentified":""},location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:hd,charCode:function(a){return"keypress"===a.type?bd(a):0},keyCode:function(a){return"keydown"===a.type||"keyup"===a.type?a.keyCode:0},which:function(a){return"keypress"===
a.type?bd(a):"keydown"===a.type||"keyup"===a.type?a.keyCode:0}}),jd=0,kd=0,ld=!1,md=!1,nd=$c.extend({screenX:null,screenY:null,clientX:null,clientY:null,pageX:null,pageY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:hd,button:null,buttons:null,relatedTarget:function(a){return a.relatedTarget||(a.fromElement===a.srcElement?a.toElement:a.fromElement)},movementX:function(a){if("movementX"in a)return a.movementX;var b=jd;jd=a.screenX;return ld?"mousemove"===a.type?a.screenX-
b:0:(ld=!0,0)},movementY:function(a){if("movementY"in a)return a.movementY;var b=kd;kd=a.screenY;return md?"mousemove"===a.type?a.screenY-b:0:(md=!0,0)}}),od=nd.extend({pointerId:null,width:null,height:null,pressure:null,tangentialPressure:null,tiltX:null,tiltY:null,twist:null,pointerType:null,isPrimary:null}),pd=nd.extend({dataTransfer:null}),qd=$c.extend({touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:hd}),rd=E.extend({propertyName:null,
elapsedTime:null,pseudoElement:null}),sd=nd.extend({deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:null,deltaMode:null}),td=[["blur","blur",0],["cancel","cancel",0],["click","click",0],["close","close",0],["contextmenu","contextMenu",0],["copy","copy",0],["cut","cut",0],["auxclick","auxClick",0],["dblclick","doubleClick",0],["dragend","dragEnd",
0],["dragstart","dragStart",0],["drop","drop",0],["focus","focus",0],["input","input",0],["invalid","invalid",0],["keydown","keyDown",0],["keypress","keyPress",0],["keyup","keyUp",0],["mousedown","mouseDown",0],["mouseup","mouseUp",0],["paste","paste",0],["pause","pause",0],["play","play",0],["pointercancel","pointerCancel",0],["pointerdown","pointerDown",0],["pointerup","pointerUp",0],["ratechange","rateChange",0],["reset","reset",0],["seeked","seeked",0],["submit","submit",0],["touchcancel","touchCancel",
0],["touchend","touchEnd",0],["touchstart","touchStart",0],["volumechange","volumeChange",0],["drag","drag",1],["dragenter","dragEnter",1],["dragexit","dragExit",1],["dragleave","dragLeave",1],["dragover","dragOver",1],["mousemove","mouseMove",1],["mouseout","mouseOut",1],["mouseover","mouseOver",1],["pointermove","pointerMove",1],["pointerout","pointerOut",1],["pointerover","pointerOver",1],["scroll","scroll",1],["toggle","toggle",1],["touchmove","touchMove",1],["wheel","wheel",1],["abort","abort",
2],[Zb,"animationEnd",2],[$b,"animationIteration",2],[ac,"animationStart",2],["canplay","canPlay",2],["canplaythrough","canPlayThrough",2],["durationchange","durationChange",2],["emptied","emptied",2],["encrypted","encrypted",2],["ended","ended",2],["error","error",2],["gotpointercapture","gotPointerCapture",2],["load","load",2],["loadeddata","loadedData",2],["loadedmetadata","loadedMetadata",2],["loadstart","loadStart",2],["lostpointercapture","lostPointerCapture",2],["playing","playing",2],["progress",
"progress",2],["seeking","seeking",2],["stalled","stalled",2],["suspend","suspend",2],["timeupdate","timeUpdate",2],[bc,"transitionEnd",2],["waiting","waiting",2]],ud={},vd={},xd=0;for(;xd<td.length;xd++){var yd=td[xd],zd=yd[0],Ad=yd[1],Bd=yd[2],Cd="on"+(Ad[0].toUpperCase()+Ad.slice(1)),Dd={phasedRegistrationNames:{bubbled:Cd,captured:Cd+"Capture"},dependencies:[zd],eventPriority:Bd};ud[Ad]=Dd;vd[zd]=Dd}
var Ed={eventTypes:ud,getEventPriority:function(a){a=vd[a];return void 0!==a?a.eventPriority:2},extractEvents:function(a,b,c,d){var e=vd[a];if(!e)return null;switch(a){case "keypress":if(0===bd(c))return null;case "keydown":case "keyup":a=id;break;case "blur":case "focus":a=ad;break;case "click":if(2===c.button)return null;case "auxclick":case "dblclick":case "mousedown":case "mousemove":case "mouseup":case "mouseout":case "mouseover":case "contextmenu":a=nd;break;case "drag":case "dragend":case "dragenter":case "dragexit":case "dragleave":case "dragover":case "dragstart":case "drop":a=
pd;break;case "touchcancel":case "touchend":case "touchmove":case "touchstart":a=qd;break;case Zb:case $b:case ac:a=Yc;break;case bc:a=rd;break;case "scroll":a=$c;break;case "wheel":a=sd;break;case "copy":case "cut":case "paste":a=Zc;break;case "gotpointercapture":case "lostpointercapture":case "pointercancel":case "pointerdown":case "pointermove":case "pointerout":case "pointerover":case "pointerup":a=od;break;default:a=E}b=a.getPooled(e,b,c,d);Sc(b);return b}},Fd=q.unstable_UserBlockingPriority,
Gd=q.unstable_runWithPriority,Hd=Ed.getEventPriority,Id=10,Jd=[];
function Kd(a){var b=a.targetInst,c=b;do{if(!c){a.ancestors.push(c);break}var d=c;if(3===d.tag)d=d.stateNode.containerInfo;else{for(;d.return;)d=d.return;d=3!==d.tag?null:d.stateNode.containerInfo}if(!d)break;b=c.tag;5!==b&&6!==b||a.ancestors.push(c);c=Fc(d)}while(c);for(c=0;c<a.ancestors.length;c++){b=a.ancestors[c];var e=Mc(a.nativeEvent);d=a.topLevelType;for(var f=a.nativeEvent,g=a.eventSystemFlags,h=null,k=0;k<ea.length;k++){var l=ea[k];l&&(l=l.extractEvents(d,b,f,e,g))&&(h=xa(h,l))}Ba(h)}}
var Ld=!0;function F(a,b){Md(b,a,!1)}function Md(a,b,c){switch(Hd(b)){case 0:var d=Nd.bind(null,b,1);break;case 1:d=Od.bind(null,b,1);break;default:d=Pd.bind(null,b,1)}c?a.addEventListener(b,d,!0):a.addEventListener(b,d,!1)}function Nd(a,b,c){ib||gb();var d=Pd,e=ib;ib=!0;try{fb(d,a,b,c)}finally{(ib=e)||kb()}}function Od(a,b,c){Gd(Fd,Pd.bind(null,a,b,c))}
function Qd(a,b,c,d){if(Jd.length){var e=Jd.pop();e.topLevelType=a;e.eventSystemFlags=b;e.nativeEvent=c;e.targetInst=d;a=e}else a={topLevelType:a,eventSystemFlags:b,nativeEvent:c,targetInst:d,ancestors:[]};try{if(b=Kd,c=a,jb)b(c,void 0);else{jb=!0;try{hb(b,c,void 0)}finally{jb=!1,kb()}}}finally{a.topLevelType=null,a.nativeEvent=null,a.targetInst=null,a.ancestors.length=0,Jd.length<Id&&Jd.push(a)}}
function Pd(a,b,c){if(Ld)if(0<nc.length&&-1<uc.indexOf(a))a=zc(null,a,b,c),nc.push(a);else{var d=Hc(a,b,c);null===d?Ac(a,c):-1<uc.indexOf(a)?(a=zc(d,a,b,c),nc.push(a)):Dc(d,a,b,c)||(Ac(a,c),Qd(a,b,c,null))}}function Hc(a,b,c){var d=Mc(c);d=Fc(d);if(null!==d){var e=ec(d);if(null===e)d=null;else{var f=e.tag;if(13===f){d=fc(e);if(null!==d)return d;d=null}else if(3===f){if(e.stateNode.hydrate)return 3===e.tag?e.stateNode.containerInfo:null;d=null}else e!==d&&(d=null)}}Qd(a,b,c,d);return null}
function Rd(a){if(!Ya)return!1;a="on"+a;var b=a in document;b||(b=document.createElement("div"),b.setAttribute(a,"return;"),b="function"===typeof b[a]);return b}var Sd=new ("function"===typeof WeakMap?WeakMap:Map);function xc(a){var b=Sd.get(a);void 0===b&&(b=new Set,Sd.set(a,b));return b}
function yc(a,b,c){if(!c.has(a)){switch(a){case "scroll":Md(b,"scroll",!0);break;case "focus":case "blur":Md(b,"focus",!0);Md(b,"blur",!0);c.add("blur");c.add("focus");break;case "cancel":case "close":Rd(a)&&Md(b,a,!0);break;case "invalid":case "submit":case "reset":break;default:-1===dc.indexOf(a)&&F(a,b)}c.add(a)}}
var Td={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,
floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Ud=["Webkit","ms","Moz","O"];Object.keys(Td).forEach(function(a){Ud.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);Td[b]=Td[a]})});function Vd(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||Td.hasOwnProperty(a)&&Td[a]?(""+b).trim():b+"px"}
function Wd(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=Vd(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e}}var Xd=n({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});
function Yd(a,b){if(b){if(Xd[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(u(137,a,""));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(u(60));if(!("object"===typeof b.dangerouslySetInnerHTML&&"__html"in b.dangerouslySetInnerHTML))throw Error(u(61));}if(null!=b.style&&"object"!==typeof b.style)throw Error(u(62,""));}}
function Zd(a,b){if(-1===a.indexOf("-"))return"string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return!1;default:return!0}}function $d(a,b){a=9===a.nodeType||11===a.nodeType?a:a.ownerDocument;var c=xc(a);b=ja[b];for(var d=0;d<b.length;d++)yc(b[d],a,c)}function ae(){}
function be(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}function ce(a){for(;a&&a.firstChild;)a=a.firstChild;return a}function de(a,b){var c=ce(a);a=0;for(var d;c;){if(3===c.nodeType){d=a+c.textContent.length;if(a<=b&&d>=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=ce(c)}}
function ee(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?ee(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}function fe(){for(var a=window,b=be();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=be(a.document)}return b}
function ge(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)}var he="$",ie="/$",je="$?",ke="$!",le=null,me=null;function ne(a,b){switch(a){case "button":case "input":case "select":case "textarea":return!!b.autoFocus}return!1}
function oe(a,b){return"textarea"===a||"option"===a||"noscript"===a||"string"===typeof b.children||"number"===typeof b.children||"object"===typeof b.dangerouslySetInnerHTML&&null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html}var pe="function"===typeof setTimeout?setTimeout:void 0,qe="function"===typeof clearTimeout?clearTimeout:void 0;function re(a){for(;null!=a;a=a.nextSibling){var b=a.nodeType;if(1===b||3===b)break}return a}
function se(a){a=a.previousSibling;for(var b=0;a;){if(8===a.nodeType){var c=a.data;if(c===he||c===ke||c===je){if(0===b)return a;b--}else c===ie&&b++}a=a.previousSibling}return null}var te=Math.random().toString(36).slice(2),ue="__reactInternalInstance$"+te,ve="__reactEventHandlers$"+te,we="__reactContainere$"+te;
function Fc(a){var b=a[ue];if(b)return b;for(var c=a.parentNode;c;){if(b=c[we]||c[ue]){c=b.alternate;if(null!==b.child||null!==c&&null!==c.child)for(a=se(a);null!==a;){if(c=a[ue])return c;a=se(a)}return b}a=c;c=a.parentNode}return null}function Cc(a){a=a[ue]||a[we];return!a||5!==a.tag&&6!==a.tag&&13!==a.tag&&3!==a.tag?null:a}function xe(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(u(33));}function ye(a){return a[ve]||null}var ze=null,Ae=null,Be=null;
function Ce(){if(Be)return Be;var a,b=Ae,c=b.length,d,e="value"in ze?ze.value:ze.textContent,f=e.length;for(a=0;a<c&&b[a]===e[a];a++);var g=c-a;for(d=1;d<=g&&b[c-d]===e[f-d];d++);return Be=e.slice(a,1<d?1-d:void 0)}var De=E.extend({data:null}),Ee=E.extend({data:null}),Fe=[9,13,27,32],Ge=Ya&&"CompositionEvent"in window,He=null;Ya&&"documentMode"in document&&(He=document.documentMode);
var Ie=Ya&&"TextEvent"in window&&!He,Je=Ya&&(!Ge||He&&8<He&&11>=He),Ke=String.fromCharCode(32),Le={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["compositionend","keypress","textInput","paste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:"blur compositionend keydown keypress keyup mousedown".split(" ")},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart",
captured:"onCompositionStartCapture"},dependencies:"blur compositionstart keydown keypress keyup mousedown".split(" ")},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:"blur compositionupdate keydown keypress keyup mousedown".split(" ")}},Me=!1;
function Ne(a,b){switch(a){case "keyup":return-1!==Fe.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "blur":return!0;default:return!1}}function Oe(a){a=a.detail;return"object"===typeof a&&"data"in a?a.data:null}var Pe=!1;function Qe(a,b){switch(a){case "compositionend":return Oe(b);case "keypress":if(32!==b.which)return null;Me=!0;return Ke;case "textInput":return a=b.data,a===Ke&&Me?null:a;default:return null}}
function Re(a,b){if(Pe)return"compositionend"===a||!Ge&&Ne(a,b)?(a=Ce(),Be=Ae=ze=null,Pe=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1<b.char.length)return b.char;if(b.which)return String.fromCharCode(b.which)}return null;case "compositionend":return Je&&"ko"!==b.locale?null:b.data;default:return null}}
var Se={eventTypes:Le,extractEvents:function(a,b,c,d){var e;if(Ge)b:{switch(a){case "compositionstart":var f=Le.compositionStart;break b;case "compositionend":f=Le.compositionEnd;break b;case "compositionupdate":f=Le.compositionUpdate;break b}f=void 0}else Pe?Ne(a,c)&&(f=Le.compositionEnd):"keydown"===a&&229===c.keyCode&&(f=Le.compositionStart);f?(Je&&"ko"!==c.locale&&(Pe||f!==Le.compositionStart?f===Le.compositionEnd&&Pe&&(e=Ce()):(ze=d,Ae="value"in ze?ze.value:ze.textContent,Pe=!0)),f=De.getPooled(f,
b,c,d),e?f.data=e:(e=Oe(c),null!==e&&(f.data=e)),Sc(f),e=f):e=null;(a=Ie?Qe(a,c):Re(a,c))?(b=Ee.getPooled(Le.beforeInput,b,c,d),b.data=a,Sc(b)):b=null;return null===e?b:null===b?e:[e,b]}},Te={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Ue(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return"input"===b?!!Te[a.type]:"textarea"===b?!0:!1}
var Ve={change:{phasedRegistrationNames:{bubbled:"onChange",captured:"onChangeCapture"},dependencies:"blur change click focus input keydown keyup selectionchange".split(" ")}};function We(a,b,c){a=E.getPooled(Ve.change,a,b,c);a.type="change";cb(c);Sc(a);return a}var Xe=null,Ye=null;function Ze(a){Ba(a)}function $e(a){var b=xe(a);if(zb(b))return a}function af(a,b){if("change"===a)return b}var bf=!1;Ya&&(bf=Rd("input")&&(!document.documentMode||9<document.documentMode));
function cf(){Xe&&(Xe.detachEvent("onpropertychange",df),Ye=Xe=null)}function df(a){if("value"===a.propertyName&&$e(Ye))if(a=We(Ye,a,Mc(a)),ib)Ba(a);else{ib=!0;try{eb(Ze,a)}finally{ib=!1,kb()}}}function ef(a,b,c){"focus"===a?(cf(),Xe=b,Ye=c,Xe.attachEvent("onpropertychange",df)):"blur"===a&&cf()}function ff(a){if("selectionchange"===a||"keyup"===a||"keydown"===a)return $e(Ye)}function gf(a,b){if("click"===a)return $e(b)}function hf(a,b){if("input"===a||"change"===a)return $e(b)}
var jf={eventTypes:Ve,_isInputEventSupported:bf,extractEvents:function(a,b,c,d){var e=b?xe(b):window,f=e.nodeName&&e.nodeName.toLowerCase();if("select"===f||"input"===f&&"file"===e.type)var g=af;else if(Ue(e))if(bf)g=hf;else{g=ff;var h=ef}else(f=e.nodeName)&&"input"===f.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)&&(g=gf);if(g&&(g=g(a,b)))return We(g,c,d);h&&h(a,e,b);"blur"===a&&(a=e._wrapperState)&&a.controlled&&"number"===e.type&&Fb(e,"number",e.value)}},kf={mouseEnter:{registrationName:"onMouseEnter",
dependencies:["mouseout","mouseover"]},mouseLeave:{registrationName:"onMouseLeave",dependencies:["mouseout","mouseover"]},pointerEnter:{registrationName:"onPointerEnter",dependencies:["pointerout","pointerover"]},pointerLeave:{registrationName:"onPointerLeave",dependencies:["pointerout","pointerover"]}},lf,mf={eventTypes:kf,extractEvents:function(a,b,c,d,e){var f="mouseover"===a||"pointerover"===a,g="mouseout"===a||"pointerout"===a;if(f&&0===(e&32)&&(c.relatedTarget||c.fromElement)||!g&&!f)return null;
e=d.window===d?d:(e=d.ownerDocument)?e.defaultView||e.parentWindow:window;if(g){if(g=b,b=(b=c.relatedTarget||c.toElement)?Fc(b):null,null!==b&&(f=ec(b),b!==f||5!==b.tag&&6!==b.tag))b=null}else g=null;if(g===b)return null;if("mouseout"===a||"mouseover"===a){var h=nd;var k=kf.mouseLeave;var l=kf.mouseEnter;var m="mouse"}else if("pointerout"===a||"pointerover"===a)h=od,k=kf.pointerLeave,l=kf.pointerEnter,m="pointer";a=null==g?e:xe(g);e=null==b?e:xe(b);k=h.getPooled(k,g,c,d);k.type=m+"leave";k.target=
a;k.relatedTarget=e;d=h.getPooled(l,b,c,d);d.type=m+"enter";d.target=e;d.relatedTarget=a;h=g;m=b;if(h&&m)a:{l=h;a=m;g=0;for(b=l;b;b=Nc(b))g++;b=0;for(e=a;e;e=Nc(e))b++;for(;0<g-b;)l=Nc(l),g--;for(;0<b-g;)a=Nc(a),b--;for(;g--;){if(l===a||l===a.alternate)break a;l=Nc(l);a=Nc(a)}l=null}else l=null;a=l;for(l=[];h&&h!==a;){g=h.alternate;if(null!==g&&g===a)break;l.push(h);h=Nc(h)}for(h=[];m&&m!==a;){g=m.alternate;if(null!==g&&g===a)break;h.push(m);m=Nc(m)}for(m=0;m<l.length;m++)Qc(l[m],"bubbled",k);for(m=
h.length;0<m--;)Qc(h[m],"captured",d);if(c===lf)return lf=null,[k];lf=c;return[k,d]}};function nf(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var of="function"===typeof Object.is?Object.is:nf,pf=Object.prototype.hasOwnProperty;function qf(a,b){if(of(a,b))return!0;if("object"!==typeof a||null===a||"object"!==typeof b||null===b)return!1;var c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return!1;for(d=0;d<c.length;d++)if(!pf.call(b,c[d])||!of(a[c[d]],b[c[d]]))return!1;return!0}
var rf=Ya&&"documentMode"in document&&11>=document.documentMode,sf={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:"blur contextmenu dragend focus keydown keyup mousedown mouseup selectionchange".split(" ")}},tf=null,uf=null,vf=null,wf=!1;
function xf(a,b){var c=b.window===b?b.document:9===b.nodeType?b:b.ownerDocument;if(wf||null==tf||tf!==be(c))return null;c=tf;"selectionStart"in c&&ge(c)?c={start:c.selectionStart,end:c.selectionEnd}:(c=(c.ownerDocument&&c.ownerDocument.defaultView||window).getSelection(),c={anchorNode:c.anchorNode,anchorOffset:c.anchorOffset,focusNode:c.focusNode,focusOffset:c.focusOffset});return vf&&qf(vf,c)?null:(vf=c,a=E.getPooled(sf.select,uf,a,b),a.type="select",a.target=tf,Sc(a),a)}
var yf={eventTypes:sf,extractEvents:function(a,b,c,d){var e=d.window===d?d.document:9===d.nodeType?d:d.ownerDocument,f;if(!(f=!e)){a:{e=xc(e);f=ja.onSelect;for(var g=0;g<f.length;g++)if(!e.has(f[g])){e=!1;break a}e=!0}f=!e}if(f)return null;e=b?xe(b):window;switch(a){case "focus":if(Ue(e)||"true"===e.contentEditable)tf=e,uf=b,vf=null;break;case "blur":vf=uf=tf=null;break;case "mousedown":wf=!0;break;case "contextmenu":case "mouseup":case "dragend":return wf=!1,xf(c,d);case "selectionchange":if(rf)break;
case "keydown":case "keyup":return xf(c,d)}return null}};Ca.injectEventPluginOrder("ResponderEventPlugin SimpleEventPlugin EnterLeaveEventPlugin ChangeEventPlugin SelectEventPlugin BeforeInputEventPlugin".split(" "));var zf=Cc;sa=ye;ua=zf;va=xe;Ca.injectEventPluginsByName({SimpleEventPlugin:Ed,EnterLeaveEventPlugin:mf,ChangeEventPlugin:jf,SelectEventPlugin:yf,BeforeInputEventPlugin:Se});new Set;var Af=[],Bf=-1;function G(a){0>Bf||(a.current=Af[Bf],Af[Bf]=null,Bf--)}
function I(a,b){Bf++;Af[Bf]=a.current;a.current=b}var Cf={},J={current:Cf},K={current:!1},Df=Cf;function Ef(a,b){var c=a.type.contextTypes;if(!c)return Cf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}function L(a){a=a.childContextTypes;return null!==a&&void 0!==a}
function Ff(a){G(K,a);G(J,a)}function Gf(a){G(K,a);G(J,a)}function Hf(a,b,c){if(J.current!==Cf)throw Error(u(168));I(J,b,a);I(K,c,a)}function If(a,b,c){var d=a.stateNode;a=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in a))throw Error(u(108,Wa(b)||"Unknown",e));return n({},c,{},d)}function Jf(a){var b=a.stateNode;b=b&&b.__reactInternalMemoizedMergedChildContext||Cf;Df=J.current;I(J,b,a);I(K,K.current,a);return!0}
function Kf(a,b,c){var d=a.stateNode;if(!d)throw Error(u(169));c?(b=If(a,b,Df),d.__reactInternalMemoizedMergedChildContext=b,G(K,a),G(J,a),I(J,b,a)):G(K,a);I(K,c,a)}
var Lf=q.unstable_runWithPriority,Mf=q.unstable_scheduleCallback,Nf=q.unstable_cancelCallback,Of=q.unstable_shouldYield,Pf=q.unstable_requestPaint,Qf=q.unstable_now,Rf=q.unstable_getCurrentPriorityLevel,Sf=q.unstable_ImmediatePriority,Tf=q.unstable_UserBlockingPriority,Uf=q.unstable_NormalPriority,Vf=q.unstable_LowPriority,Wf=q.unstable_IdlePriority,Xf={},Yf=void 0!==Pf?Pf:function(){},Zf=null,$f=null,ag=!1,bg=Qf(),cg=1E4>bg?Qf:function(){return Qf()-bg};
function dg(){switch(Rf()){case Sf:return 99;case Tf:return 98;case Uf:return 97;case Vf:return 96;case Wf:return 95;default:throw Error(u(332));}}function eg(a){switch(a){case 99:return Sf;case 98:return Tf;case 97:return Uf;case 96:return Vf;case 95:return Wf;default:throw Error(u(332));}}function fg(a,b){a=eg(a);return Lf(a,b)}function gg(a,b,c){a=eg(a);return Mf(a,b,c)}function hg(a){null===Zf?(Zf=[a],$f=Mf(Sf,ig)):Zf.push(a);return Xf}function jg(){if(null!==$f){var a=$f;$f=null;Nf(a)}ig()}
function ig(){if(!ag&&null!==Zf){ag=!0;var a=0;try{var b=Zf;fg(99,function(){for(;a<b.length;a++){var c=b[a];do c=c(!0);while(null!==c)}});Zf=null}catch(c){throw null!==Zf&&(Zf=Zf.slice(a+1)),Mf(Sf,jg),c;}finally{ag=!1}}}var kg=3;function lg(a,b,c){c/=10;return 1073741821-(((1073741821-a+b/10)/c|0)+1)*c}function mg(a,b){if(a&&a.defaultProps){b=n({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c])}return b}var ng={current:null},og=null,pg=null,qg=null;function rg(){qg=pg=og=null}
function sg(a,b){var c=a.type._context;I(ng,c._currentValue,a);c._currentValue=b}function tg(a){var b=ng.current;G(ng,a);a.type._context._currentValue=b}function ug(a,b){for(;null!==a;){var c=a.alternate;if(a.childExpirationTime<b)a.childExpirationTime=b,null!==c&&c.childExpirationTime<b&&(c.childExpirationTime=b);else if(null!==c&&c.childExpirationTime<b)c.childExpirationTime=b;else break;a=a.return}}
function vg(a,b){og=a;qg=pg=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(a.expirationTime>=b&&(wg=!0),a.firstContext=null)}function xg(a,b){if(qg!==a&&!1!==b&&0!==b){if("number"!==typeof b||1073741823===b)qg=a,b=1073741823;b={context:a,observedBits:b,next:null};if(null===pg){if(null===og)throw Error(u(308));pg=b;og.dependencies={expirationTime:0,firstContext:b,responders:null}}else pg=pg.next=b}return a._currentValue}var yg=!1;
function zg(a){return{baseState:a,firstUpdate:null,lastUpdate:null,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}}function Ag(a){return{baseState:a.baseState,firstUpdate:a.firstUpdate,lastUpdate:a.lastUpdate,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}}
function Bg(a,b){return{expirationTime:a,suspenseConfig:b,tag:0,payload:null,callback:null,next:null,nextEffect:null}}function Cg(a,b){null===a.lastUpdate?a.firstUpdate=a.lastUpdate=b:(a.lastUpdate.next=b,a.lastUpdate=b)}
function Dg(a,b){var c=a.alternate;if(null===c){var d=a.updateQueue;var e=null;null===d&&(d=a.updateQueue=zg(a.memoizedState))}else d=a.updateQueue,e=c.updateQueue,null===d?null===e?(d=a.updateQueue=zg(a.memoizedState),e=c.updateQueue=zg(c.memoizedState)):d=a.updateQueue=Ag(e):null===e&&(e=c.updateQueue=Ag(d));null===e||d===e?Cg(d,b):null===d.lastUpdate||null===e.lastUpdate?(Cg(d,b),Cg(e,b)):(Cg(d,b),e.lastUpdate=b)}
function Eg(a,b){var c=a.updateQueue;c=null===c?a.updateQueue=zg(a.memoizedState):Fg(a,c);null===c.lastCapturedUpdate?c.firstCapturedUpdate=c.lastCapturedUpdate=b:(c.lastCapturedUpdate.next=b,c.lastCapturedUpdate=b)}function Fg(a,b){var c=a.alternate;null!==c&&b===c.updateQueue&&(b=a.updateQueue=Ag(b));return b}
function Gg(a,b,c,d,e,f){switch(c.tag){case 1:return a=c.payload,"function"===typeof a?a.call(f,d,e):a;case 3:a.effectTag=a.effectTag&-4097|64;case 0:a=c.payload;e="function"===typeof a?a.call(f,d,e):a;if(null===e||void 0===e)break;return n({},d,e);case 2:yg=!0}return d}
function Hg(a,b,c,d,e){yg=!1;b=Fg(a,b);for(var f=b.baseState,g=null,h=0,k=b.firstUpdate,l=f;null!==k;){var m=k.expirationTime;m<e?(null===g&&(g=k,f=l),h<m&&(h=m)):(Ig(m,k.suspenseConfig),l=Gg(a,b,k,l,c,d),null!==k.callback&&(a.effectTag|=32,k.nextEffect=null,null===b.lastEffect?b.firstEffect=b.lastEffect=k:(b.lastEffect.nextEffect=k,b.lastEffect=k)));k=k.next}m=null;for(k=b.firstCapturedUpdate;null!==k;){var C=k.expirationTime;C<e?(null===m&&(m=k,null===g&&(f=l)),h<C&&(h=C)):(l=Gg(a,b,k,l,c,d),null!==
k.callback&&(a.effectTag|=32,k.nextEffect=null,null===b.lastCapturedEffect?b.firstCapturedEffect=b.lastCapturedEffect=k:(b.lastCapturedEffect.nextEffect=k,b.lastCapturedEffect=k)));k=k.next}null===g&&(b.lastUpdate=null);null===m?b.lastCapturedUpdate=null:a.effectTag|=32;null===g&&null===m&&(f=l);b.baseState=f;b.firstUpdate=g;b.firstCapturedUpdate=m;Jg(h);a.expirationTime=h;a.memoizedState=l}
function Kg(a,b,c){null!==b.firstCapturedUpdate&&(null!==b.lastUpdate&&(b.lastUpdate.next=b.firstCapturedUpdate,b.lastUpdate=b.lastCapturedUpdate),b.firstCapturedUpdate=b.lastCapturedUpdate=null);Lg(b.firstEffect,c);b.firstEffect=b.lastEffect=null;Lg(b.firstCapturedEffect,c);b.firstCapturedEffect=b.lastCapturedEffect=null}function Lg(a,b){for(;null!==a;){var c=a.callback;if(null!==c){a.callback=null;var d=b;if("function"!==typeof c)throw Error(u(191,c));c.call(d)}a=a.nextEffect}}
var Mg=Ea.ReactCurrentBatchConfig,Ng=(new aa.Component).refs;function Og(a,b,c,d){b=a.memoizedState;c=c(d,b);c=null===c||void 0===c?b:n({},b,c);a.memoizedState=c;d=a.updateQueue;null!==d&&0===a.expirationTime&&(d.baseState=c)}
var Sg={isMounted:function(a){return(a=a._reactInternalFiber)?ec(a)===a:!1},enqueueSetState:function(a,b,c){a=a._reactInternalFiber;var d=Pg(),e=Mg.suspense;d=Qg(d,a,e);e=Bg(d,e);e.payload=b;void 0!==c&&null!==c&&(e.callback=c);Dg(a,e);Rg(a,d)},enqueueReplaceState:function(a,b,c){a=a._reactInternalFiber;var d=Pg(),e=Mg.suspense;d=Qg(d,a,e);e=Bg(d,e);e.tag=1;e.payload=b;void 0!==c&&null!==c&&(e.callback=c);Dg(a,e);Rg(a,d)},enqueueForceUpdate:function(a,b){a=a._reactInternalFiber;var c=Pg(),d=Mg.suspense;
c=Qg(c,a,d);d=Bg(c,d);d.tag=2;void 0!==b&&null!==b&&(d.callback=b);Dg(a,d);Rg(a,c)}};function Tg(a,b,c,d,e,f,g){a=a.stateNode;return"function"===typeof a.shouldComponentUpdate?a.shouldComponentUpdate(d,f,g):b.prototype&&b.prototype.isPureReactComponent?!qf(c,d)||!qf(e,f):!0}
function Ug(a,b,c){var d=!1,e=Cf;var f=b.contextType;"object"===typeof f&&null!==f?f=xg(f):(e=L(b)?Df:J.current,d=b.contextTypes,f=(d=null!==d&&void 0!==d)?Ef(a,e):Cf);b=new b(c,f);a.memoizedState=null!==b.state&&void 0!==b.state?b.state:null;b.updater=Sg;a.stateNode=b;b._reactInternalFiber=a;d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=e,a.__reactInternalMemoizedMaskedChildContext=f);return b}
function Vg(a,b,c,d){a=b.state;"function"===typeof b.componentWillReceiveProps&&b.componentWillReceiveProps(c,d);"function"===typeof b.UNSAFE_componentWillReceiveProps&&b.UNSAFE_componentWillReceiveProps(c,d);b.state!==a&&Sg.enqueueReplaceState(b,b.state,null)}
function Wg(a,b,c,d){var e=a.stateNode;e.props=c;e.state=a.memoizedState;e.refs=Ng;var f=b.contextType;"object"===typeof f&&null!==f?e.context=xg(f):(f=L(b)?Df:J.current,e.context=Ef(a,f));f=a.updateQueue;null!==f&&(Hg(a,f,c,e,d),e.state=a.memoizedState);f=b.getDerivedStateFromProps;"function"===typeof f&&(Og(a,b,f,c),e.state=a.memoizedState);"function"===typeof b.getDerivedStateFromProps||"function"===typeof e.getSnapshotBeforeUpdate||"function"!==typeof e.UNSAFE_componentWillMount&&"function"!==
typeof e.componentWillMount||(b=e.state,"function"===typeof e.componentWillMount&&e.componentWillMount(),"function"===typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),b!==e.state&&Sg.enqueueReplaceState(e,e.state,null),f=a.updateQueue,null!==f&&(Hg(a,f,c,e,d),e.state=a.memoizedState));"function"===typeof e.componentDidMount&&(a.effectTag|=4)}var Xg=Array.isArray;
function Yg(a,b,c){a=c.ref;if(null!==a&&"function"!==typeof a&&"object"!==typeof a){if(c._owner){c=c._owner;if(c){if(1!==c.tag)throw Error(u(309));var d=c.stateNode}if(!d)throw Error(u(147,a));var e=""+a;if(null!==b&&null!==b.ref&&"function"===typeof b.ref&&b.ref._stringRef===e)return b.ref;b=function(a){var b=d.refs;b===Ng&&(b=d.refs={});null===a?delete b[e]:b[e]=a};b._stringRef=e;return b}if("string"!==typeof a)throw Error(u(284));if(!c._owner)throw Error(u(290,a));}return a}
function Zg(a,b){if("textarea"!==a.type)throw Error(u(31,"[object Object]"===Object.prototype.toString.call(b)?"object with keys {"+Object.keys(b).join(", ")+"}":b,""));}
function $g(a){function b(b,c){if(a){var d=b.lastEffect;null!==d?(d.nextEffect=c,b.lastEffect=c):b.firstEffect=b.lastEffect=c;c.nextEffect=null;c.effectTag=8}}function c(c,d){if(!a)return null;for(;null!==d;)b(c,d),d=d.sibling;return null}function d(a,b){for(a=new Map;null!==b;)null!==b.key?a.set(b.key,b):a.set(b.index,b),b=b.sibling;return a}function e(a,b,c){a=ah(a,b,c);a.index=0;a.sibling=null;return a}function f(b,c,d){b.index=d;if(!a)return c;d=b.alternate;if(null!==d)return d=d.index,d<c?(b.effectTag=
2,c):d;b.effectTag=2;return c}function g(b){a&&null===b.alternate&&(b.effectTag=2);return b}function h(a,b,c,d){if(null===b||6!==b.tag)return b=bh(c,a.mode,d),b.return=a,b;b=e(b,c,d);b.return=a;return b}function k(a,b,c,d){if(null!==b&&b.elementType===c.type)return d=e(b,c.props,d),d.ref=Yg(a,b,c),d.return=a,d;d=ch(c.type,c.key,c.props,null,a.mode,d);d.ref=Yg(a,b,c);d.return=a;return d}function l(a,b,c,d){if(null===b||4!==b.tag||b.stateNode.containerInfo!==c.containerInfo||b.stateNode.implementation!==
c.implementation)return b=dh(c,a.mode,d),b.return=a,b;b=e(b,c.children||[],d);b.return=a;return b}function m(a,b,c,d,f){if(null===b||7!==b.tag)return b=eh(c,a.mode,d,f),b.return=a,b;b=e(b,c,d);b.return=a;return b}function C(a,b,c){if("string"===typeof b||"number"===typeof b)return b=bh(""+b,a.mode,c),b.return=a,b;if("object"===typeof b&&null!==b){switch(b.$$typeof){case Ga:return c=ch(b.type,b.key,b.props,null,a.mode,c),c.ref=Yg(a,null,b),c.return=a,c;case Ha:return b=dh(b,a.mode,c),b.return=a,b}if(Xg(b)||
Ua(b))return b=eh(b,a.mode,c,null),b.return=a,b;Zg(a,b)}return null}function y(a,b,c,d){var e=null!==b?b.key:null;if("string"===typeof c||"number"===typeof c)return null!==e?null:h(a,b,""+c,d);if("object"===typeof c&&null!==c){switch(c.$$typeof){case Ga:return c.key===e?c.type===Ia?m(a,b,c.props.children,d,e):k(a,b,c,d):null;case Ha:return c.key===e?l(a,b,c,d):null}if(Xg(c)||Ua(c))return null!==e?null:m(a,b,c,d,null);Zg(a,c)}return null}function H(a,b,c,d,e){if("string"===typeof d||"number"===typeof d)return a=
a.get(c)||null,h(b,a,""+d,e);if("object"===typeof d&&null!==d){switch(d.$$typeof){case Ga:return a=a.get(null===d.key?c:d.key)||null,d.type===Ia?m(b,a,d.props.children,e,d.key):k(b,a,d,e);case Ha:return a=a.get(null===d.key?c:d.key)||null,l(b,a,d,e)}if(Xg(d)||Ua(d))return a=a.get(c)||null,m(b,a,d,e,null);Zg(b,d)}return null}function z(e,g,h,k){for(var l=null,m=null,r=g,x=g=0,A=null;null!==r&&x<h.length;x++){r.index>x?(A=r,r=null):A=r.sibling;var p=y(e,r,h[x],k);if(null===p){null===r&&(r=A);break}a&&
r&&null===p.alternate&&b(e,r);g=f(p,g,x);null===m?l=p:m.sibling=p;m=p;r=A}if(x===h.length)return c(e,r),l;if(null===r){for(;x<h.length;x++)r=C(e,h[x],k),null!==r&&(g=f(r,g,x),null===m?l=r:m.sibling=r,m=r);return l}for(r=d(e,r);x<h.length;x++)A=H(r,e,x,h[x],k),null!==A&&(a&&null!==A.alternate&&r.delete(null===A.key?x:A.key),g=f(A,g,x),null===m?l=A:m.sibling=A,m=A);a&&r.forEach(function(a){return b(e,a)});return l}function ta(e,g,h,k){var l=Ua(h);if("function"!==typeof l)throw Error(u(150));h=l.call(h);
if(null==h)throw Error(u(151));for(var m=l=null,r=g,x=g=0,A=null,p=h.next();null!==r&&!p.done;x++,p=h.next()){r.index>x?(A=r,r=null):A=r.sibling;var z=y(e,r,p.value,k);if(null===z){null===r&&(r=A);break}a&&r&&null===z.alternate&&b(e,r);g=f(z,g,x);null===m?l=z:m.sibling=z;m=z;r=A}if(p.done)return c(e,r),l;if(null===r){for(;!p.done;x++,p=h.next())p=C(e,p.value,k),null!==p&&(g=f(p,g,x),null===m?l=p:m.sibling=p,m=p);return l}for(r=d(e,r);!p.done;x++,p=h.next())p=H(r,e,x,p.value,k),null!==p&&(a&&null!==
p.alternate&&r.delete(null===p.key?x:p.key),g=f(p,g,x),null===m?l=p:m.sibling=p,m=p);a&&r.forEach(function(a){return b(e,a)});return l}return function(a,d,f,h){var k="object"===typeof f&&null!==f&&f.type===Ia&&null===f.key;k&&(f=f.props.children);var l="object"===typeof f&&null!==f;if(l)switch(f.$$typeof){case Ga:a:{l=f.key;for(k=d;null!==k;){if(k.key===l)if(7===k.tag?f.type===Ia:k.elementType===f.type){c(a,k.sibling);d=e(k,f.type===Ia?f.props.children:f.props,h);d.ref=Yg(a,k,f);d.return=a;a=d;break a}else{c(a,
k);break}else b(a,k);k=k.sibling}f.type===Ia?(d=eh(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=ch(f.type,f.key,f.props,null,a.mode,h),h.ref=Yg(a,d,f),h.return=a,a=h)}return g(a);case Ha:a:{for(k=f.key;null!==d;){if(d.key===k)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[],h);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=dh(f,a.mode,h);d.return=a;a=d}return g(a)}if("string"===
typeof f||"number"===typeof f)return f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f,h),d.return=a,a=d):(c(a,d),d=bh(f,a.mode,h),d.return=a,a=d),g(a);if(Xg(f))return z(a,d,f,h);if(Ua(f))return ta(a,d,f,h);l&&Zg(a,f);if("undefined"===typeof f&&!k)switch(a.tag){case 1:case 0:throw a=a.type,Error(u(152,a.displayName||a.name||"Component"));}return c(a,d)}}var fh=$g(!0),gh=$g(!1),hh={},ih={current:hh},jh={current:hh},kh={current:hh};function lh(a){if(a===hh)throw Error(u(174));return a}
function mh(a,b){I(kh,b,a);I(jh,a,a);I(ih,hh,a);var c=b.nodeType;switch(c){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:Qb(null,"");break;default:c=8===c?b.parentNode:b,b=c.namespaceURI||null,c=c.tagName,b=Qb(b,c)}G(ih,a);I(ih,b,a)}function nh(a){G(ih,a);G(jh,a);G(kh,a)}function oh(a){lh(kh.current);var b=lh(ih.current);var c=Qb(b,a.type);b!==c&&(I(jh,a,a),I(ih,c,a))}function ph(a){jh.current===a&&(G(ih,a),G(jh,a))}var M={current:0};
function qh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||c.data===je||c.data===ke))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.effectTag&64))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}function rh(a,b){return{responder:a,props:b}}
var sh=Ea.ReactCurrentDispatcher,N=Ea.ReactCurrentBatchConfig,th=0,uh=null,O=null,vh=null,wh=null,P=null,xh=null,yh=0,zh=null,Ah=0,Bh=!1,Ch=null,Gh=0;function Q(){throw Error(u(321));}function Hh(a,b){if(null===b)return!1;for(var c=0;c<b.length&&c<a.length;c++)if(!of(a[c],b[c]))return!1;return!0}
function Ih(a,b,c,d,e,f){th=f;uh=b;vh=null!==a?a.memoizedState:null;sh.current=null===vh?Jh:Kh;b=c(d,e);if(Bh){do Bh=!1,Gh+=1,vh=null!==a?a.memoizedState:null,xh=wh,zh=P=O=null,sh.current=Kh,b=c(d,e);while(Bh);Ch=null;Gh=0}sh.current=Lh;a=uh;a.memoizedState=wh;a.expirationTime=yh;a.updateQueue=zh;a.effectTag|=Ah;a=null!==O&&null!==O.next;th=0;xh=P=wh=vh=O=uh=null;yh=0;zh=null;Ah=0;if(a)throw Error(u(300));return b}
function Mh(){sh.current=Lh;th=0;xh=P=wh=vh=O=uh=null;yh=0;zh=null;Ah=0;Bh=!1;Ch=null;Gh=0}function Nh(){var a={memoizedState:null,baseState:null,queue:null,baseUpdate:null,next:null};null===P?wh=P=a:P=P.next=a;return P}function Oh(){if(null!==xh)P=xh,xh=P.next,O=vh,vh=null!==O?O.next:null;else{if(null===vh)throw Error(u(310));O=vh;var a={memoizedState:O.memoizedState,baseState:O.baseState,queue:O.queue,baseUpdate:O.baseUpdate,next:null};P=null===P?wh=a:P.next=a;vh=O.next}return P}
function Ph(a,b){return"function"===typeof b?b(a):b}
function Qh(a){var b=Oh(),c=b.queue;if(null===c)throw Error(u(311));c.lastRenderedReducer=a;if(0<Gh){var d=c.dispatch;if(null!==Ch){var e=Ch.get(c);if(void 0!==e){Ch.delete(c);var f=b.memoizedState;do f=a(f,e.action),e=e.next;while(null!==e);of(f,b.memoizedState)||(wg=!0);b.memoizedState=f;b.baseUpdate===c.last&&(b.baseState=f);c.lastRenderedState=f;return[f,d]}}return[b.memoizedState,d]}d=c.last;var g=b.baseUpdate;f=b.baseState;null!==g?(null!==d&&(d.next=null),d=g.next):d=null!==d?d.next:null;if(null!==
d){var h=e=null,k=d,l=!1;do{var m=k.expirationTime;m<th?(l||(l=!0,h=g,e=f),m>yh&&(yh=m,Jg(yh))):(Ig(m,k.suspenseConfig),f=k.eagerReducer===a?k.eagerState:a(f,k.action));g=k;k=k.next}while(null!==k&&k!==d);l||(h=g,e=f);of(f,b.memoizedState)||(wg=!0);b.memoizedState=f;b.baseUpdate=h;b.baseState=e;c.lastRenderedState=f}return[b.memoizedState,c.dispatch]}
function Rh(a){var b=Nh();"function"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a=b.queue={last:null,dispatch:null,lastRenderedReducer:Ph,lastRenderedState:a};a=a.dispatch=Sh.bind(null,uh,a);return[b.memoizedState,a]}function Th(a){return Qh(Ph,a)}function Uh(a,b,c,d){a={tag:a,create:b,destroy:c,deps:d,next:null};null===zh?(zh={lastEffect:null},zh.lastEffect=a.next=a):(b=zh.lastEffect,null===b?zh.lastEffect=a.next=a:(c=b.next,b.next=a,a.next=c,zh.lastEffect=a));return a}
function Vh(a,b,c,d){var e=Nh();Ah|=a;e.memoizedState=Uh(b,c,void 0,void 0===d?null:d)}function Wh(a,b,c,d){var e=Oh();d=void 0===d?null:d;var f=void 0;if(null!==O){var g=O.memoizedState;f=g.destroy;if(null!==d&&Hh(d,g.deps)){Uh(0,c,f,d);return}}Ah|=a;e.memoizedState=Uh(b,c,f,d)}function Xh(a,b){return Vh(516,192,a,b)}function Yh(a,b){return Wh(516,192,a,b)}
function Zh(a,b){if("function"===typeof b)return a=a(),b(a),function(){b(null)};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null}}function $h(){}function ai(a,b){Nh().memoizedState=[a,void 0===b?null:b];return a}function bi(a,b){var c=Oh();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Hh(b,d[1]))return d[0];c.memoizedState=[a,b];return a}
function Sh(a,b,c){if(!(25>Gh))throw Error(u(301));var d=a.alternate;if(a===uh||null!==d&&d===uh)if(Bh=!0,a={expirationTime:th,suspenseConfig:null,action:c,eagerReducer:null,eagerState:null,next:null},null===Ch&&(Ch=new Map),c=Ch.get(b),void 0===c)Ch.set(b,a);else{for(b=c;null!==b.next;)b=b.next;b.next=a}else{var e=Pg(),f=Mg.suspense;e=Qg(e,a,f);f={expirationTime:e,suspenseConfig:f,action:c,eagerReducer:null,eagerState:null,next:null};var g=b.last;if(null===g)f.next=f;else{var h=g.next;null!==h&&
(f.next=h);g.next=f}b.last=f;if(0===a.expirationTime&&(null===d||0===d.expirationTime)&&(d=b.lastRenderedReducer,null!==d))try{var k=b.lastRenderedState,l=d(k,c);f.eagerReducer=d;f.eagerState=l;if(of(l,k))return}catch(m){}finally{}Rg(a,e)}}
var Lh={readContext:xg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useResponder:Q,useDeferredValue:Q,useTransition:Q},Jh={readContext:xg,useCallback:ai,useContext:xg,useEffect:Xh,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Vh(4,36,Zh.bind(null,b,a),c)},useLayoutEffect:function(a,b){return Vh(4,36,a,b)},useMemo:function(a,b){var c=Nh();b=void 0===b?null:b;a=a();c.memoizedState=
[a,b];return a},useReducer:function(a,b,c){var d=Nh();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a=d.queue={last:null,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};a=a.dispatch=Sh.bind(null,uh,a);return[d.memoizedState,a]},useRef:function(a){var b=Nh();a={current:a};return b.memoizedState=a},useState:Rh,useDebugValue:$h,useResponder:rh,useDeferredValue:function(a,b){var c=Rh(a),d=c[0],e=c[1];Xh(function(){q.unstable_next(function(){var c=N.suspense;N.suspense=void 0===b?null:b;try{e(a)}finally{N.suspense=
c}})},[a,b]);return d},useTransition:function(a){var b=Rh(!1),c=b[0],d=b[1];return[ai(function(b){d(!0);q.unstable_next(function(){var c=N.suspense;N.suspense=void 0===a?null:a;try{d(!1),b()}finally{N.suspense=c}})},[a,c]),c]}},Kh={readContext:xg,useCallback:bi,useContext:xg,useEffect:Yh,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Wh(4,36,Zh.bind(null,b,a),c)},useLayoutEffect:function(a,b){return Wh(4,36,a,b)},useMemo:function(a,b){var c=Oh();b=void 0===b?
null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Hh(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a},useReducer:Qh,useRef:function(){return Oh().memoizedState},useState:Th,useDebugValue:$h,useResponder:rh,useDeferredValue:function(a,b){var c=Th(a),d=c[0],e=c[1];Yh(function(){q.unstable_next(function(){var c=N.suspense;N.suspense=void 0===b?null:b;try{e(a)}finally{N.suspense=c}})},[a,b]);return d},useTransition:function(a){var b=Th(!1),c=b[0],d=b[1];return[bi(function(b){d(!0);q.unstable_next(function(){var c=
N.suspense;N.suspense=void 0===a?null:a;try{d(!1),b()}finally{N.suspense=c}})},[a,c]),c]}},ci=null,di=null,ei=!1;function fi(a,b){var c=gi(5,null,null,0);c.elementType="DELETED";c.type="DELETED";c.stateNode=b;c.return=a;c.effectTag=8;null!==a.lastEffect?(a.lastEffect.nextEffect=c,a.lastEffect=c):a.firstEffect=a.lastEffect=c}
function hi(a,b){switch(a.tag){case 5:var c=a.type;b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b;return null!==b?(a.stateNode=b,!0):!1;case 6:return b=""===a.pendingProps||3!==b.nodeType?null:b,null!==b?(a.stateNode=b,!0):!1;case 13:return!1;default:return!1}}
function ii(a){if(ei){var b=di;if(b){var c=b;if(!hi(a,b)){b=re(c.nextSibling);if(!b||!hi(a,b)){a.effectTag=a.effectTag&-1025|2;ei=!1;ci=a;return}fi(ci,c)}ci=a;di=re(b.firstChild)}else a.effectTag=a.effectTag&-1025|2,ei=!1,ci=a}}function ji(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&13!==a.tag;)a=a.return;ci=a}
function ki(a){if(a!==ci)return!1;if(!ei)return ji(a),ei=!0,!1;var b=a.type;if(5!==a.tag||"head"!==b&&"body"!==b&&!oe(b,a.memoizedProps))for(b=di;b;)fi(a,b),b=re(b.nextSibling);ji(a);if(13===a.tag){a=a.memoizedState;a=null!==a?a.dehydrated:null;if(!a)throw Error(u(317));a:{a=a.nextSibling;for(b=0;a;){if(8===a.nodeType){var c=a.data;if(c===ie){if(0===b){di=re(a.nextSibling);break a}b--}else c!==he&&c!==ke&&c!==je||b++}a=a.nextSibling}di=null}}else di=ci?re(a.stateNode.nextSibling):null;return!0}
function li(){di=ci=null;ei=!1}var mi=Ea.ReactCurrentOwner,wg=!1;function R(a,b,c,d){b.child=null===a?gh(b,null,c,d):fh(b,a.child,c,d)}function ni(a,b,c,d,e){c=c.render;var f=b.ref;vg(b,e);d=Ih(a,b,c,d,f,e);if(null!==a&&!wg)return b.updateQueue=a.updateQueue,b.effectTag&=-517,a.expirationTime<=e&&(a.expirationTime=0),oi(a,b,e);b.effectTag|=1;R(a,b,d,e);return b.child}
function pi(a,b,c,d,e,f){if(null===a){var g=c.type;if("function"===typeof g&&!qi(g)&&void 0===g.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=g,ri(a,b,g,d,e,f);a=ch(c.type,null,d,null,b.mode,f);a.ref=b.ref;a.return=b;return b.child=a}g=a.child;if(e<f&&(e=g.memoizedProps,c=c.compare,c=null!==c?c:qf,c(e,d)&&a.ref===b.ref))return oi(a,b,f);b.effectTag|=1;a=ah(g,d,f);a.ref=b.ref;a.return=b;return b.child=a}
function ri(a,b,c,d,e,f){return null!==a&&qf(a.memoizedProps,d)&&a.ref===b.ref&&(wg=!1,e<f)?oi(a,b,f):si(a,b,c,d,f)}function ti(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.effectTag|=128}function si(a,b,c,d,e){var f=L(c)?Df:J.current;f=Ef(b,f);vg(b,e);c=Ih(a,b,c,d,f,e);if(null!==a&&!wg)return b.updateQueue=a.updateQueue,b.effectTag&=-517,a.expirationTime<=e&&(a.expirationTime=0),oi(a,b,e);b.effectTag|=1;R(a,b,c,e);return b.child}
function ui(a,b,c,d,e){if(L(c)){var f=!0;Jf(b)}else f=!1;vg(b,e);if(null===b.stateNode)null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2),Ug(b,c,d,e),Wg(b,c,d,e),d=!0;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var k=g.context,l=c.contextType;"object"===typeof l&&null!==l?l=xg(l):(l=L(c)?Df:J.current,l=Ef(b,l));var m=c.getDerivedStateFromProps,C="function"===typeof m||"function"===typeof g.getSnapshotBeforeUpdate;C||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&
"function"!==typeof g.componentWillReceiveProps||(h!==d||k!==l)&&Vg(b,g,d,l);yg=!1;var y=b.memoizedState;k=g.state=y;var H=b.updateQueue;null!==H&&(Hg(b,H,d,g,e),k=b.memoizedState);h!==d||y!==k||K.current||yg?("function"===typeof m&&(Og(b,c,m,d),k=b.memoizedState),(h=yg||Tg(b,c,h,d,y,k,l))?(C||"function"!==typeof g.UNSAFE_componentWillMount&&"function"!==typeof g.componentWillMount||("function"===typeof g.componentWillMount&&g.componentWillMount(),"function"===typeof g.UNSAFE_componentWillMount&&
g.UNSAFE_componentWillMount()),"function"===typeof g.componentDidMount&&(b.effectTag|=4)):("function"===typeof g.componentDidMount&&(b.effectTag|=4),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=l,d=h):("function"===typeof g.componentDidMount&&(b.effectTag|=4),d=!1)}else g=b.stateNode,h=b.memoizedProps,g.props=b.type===b.elementType?h:mg(b.type,h),k=g.context,l=c.contextType,"object"===typeof l&&null!==l?l=xg(l):(l=L(c)?Df:J.current,l=Ef(b,l)),m=c.getDerivedStateFromProps,(C=
"function"===typeof m||"function"===typeof g.getSnapshotBeforeUpdate)||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==d||k!==l)&&Vg(b,g,d,l),yg=!1,k=b.memoizedState,y=g.state=k,H=b.updateQueue,null!==H&&(Hg(b,H,d,g,e),y=b.memoizedState),h!==d||k!==y||K.current||yg?("function"===typeof m&&(Og(b,c,m,d),y=b.memoizedState),(m=yg||Tg(b,c,h,d,k,y,l))?(C||"function"!==typeof g.UNSAFE_componentWillUpdate&&"function"!==typeof g.componentWillUpdate||
("function"===typeof g.componentWillUpdate&&g.componentWillUpdate(d,y,l),"function"===typeof g.UNSAFE_componentWillUpdate&&g.UNSAFE_componentWillUpdate(d,y,l)),"function"===typeof g.componentDidUpdate&&(b.effectTag|=4),"function"===typeof g.getSnapshotBeforeUpdate&&(b.effectTag|=256)):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&k===a.memoizedState||(b.effectTag|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&k===a.memoizedState||(b.effectTag|=256),b.memoizedProps=
d,b.memoizedState=y),g.props=d,g.state=y,g.context=l,d=m):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&k===a.memoizedState||(b.effectTag|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&k===a.memoizedState||(b.effectTag|=256),d=!1);return vi(a,b,c,d,f,e)}
function vi(a,b,c,d,e,f){ti(a,b);var g=0!==(b.effectTag&64);if(!d&&!g)return e&&Kf(b,c,!1),oi(a,b,f);d=b.stateNode;mi.current=b;var h=g&&"function"!==typeof c.getDerivedStateFromError?null:d.render();b.effectTag|=1;null!==a&&g?(b.child=fh(b,a.child,null,f),b.child=fh(b,null,h,f)):R(a,b,h,f);b.memoizedState=d.state;e&&Kf(b,c,!0);return b.child}function wi(a){var b=a.stateNode;b.pendingContext?Hf(a,b.pendingContext,b.pendingContext!==b.context):b.context&&Hf(a,b.context,!1);mh(a,b.containerInfo)}
var xi={dehydrated:null,retryTime:0};
function yi(a,b,c){var d=b.mode,e=b.pendingProps,f=M.current,g=!1,h;(h=0!==(b.effectTag&64))||(h=0!==(f&2)&&(null===a||null!==a.memoizedState));h?(g=!0,b.effectTag&=-65):null!==a&&null===a.memoizedState||void 0===e.fallback||!0===e.unstable_avoidThisFallback||(f|=1);I(M,f&1,b);if(null===a){void 0!==e.fallback&&ii(b);if(g){g=e.fallback;e=eh(null,d,0,null);e.return=b;if(0===(b.mode&2))for(a=null!==b.memoizedState?b.child.child:b.child,e.child=a;null!==a;)a.return=e,a=a.sibling;c=eh(g,d,c,null);c.return=
b;e.sibling=c;b.memoizedState=xi;b.child=e;return c}d=e.children;b.memoizedState=null;return b.child=gh(b,null,d,c)}if(null!==a.memoizedState){a=a.child;d=a.sibling;if(g){e=e.fallback;c=ah(a,a.pendingProps,0);c.return=b;if(0===(b.mode&2)&&(g=null!==b.memoizedState?b.child.child:b.child,g!==a.child))for(c.child=g;null!==g;)g.return=c,g=g.sibling;d=ah(d,e,d.expirationTime);d.return=b;c.sibling=d;c.childExpirationTime=0;b.memoizedState=xi;b.child=c;return d}c=fh(b,a.child,e.children,c);b.memoizedState=
null;return b.child=c}a=a.child;if(g){g=e.fallback;e=eh(null,d,0,null);e.return=b;e.child=a;null!==a&&(a.return=e);if(0===(b.mode&2))for(a=null!==b.memoizedState?b.child.child:b.child,e.child=a;null!==a;)a.return=e,a=a.sibling;c=eh(g,d,c,null);c.return=b;e.sibling=c;c.effectTag|=2;e.childExpirationTime=0;b.memoizedState=xi;b.child=e;return c}b.memoizedState=null;return b.child=fh(b,a,e.children,c)}
function zi(a,b){a.expirationTime<b&&(a.expirationTime=b);var c=a.alternate;null!==c&&c.expirationTime<b&&(c.expirationTime=b);ug(a.return,b)}function Ai(a,b,c,d,e,f){var g=a.memoizedState;null===g?a.memoizedState={isBackwards:b,rendering:null,last:d,tail:c,tailExpiration:0,tailMode:e,lastEffect:f}:(g.isBackwards=b,g.rendering=null,g.last=d,g.tail=c,g.tailExpiration=0,g.tailMode=e,g.lastEffect=f)}
function Bi(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;R(a,b,d.children,c);d=M.current;if(0!==(d&2))d=d&1|2,b.effectTag|=64;else{if(null!==a&&0!==(a.effectTag&64))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&zi(a,c);else if(19===a.tag)zi(a,c);else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===b)break a;for(;null===a.sibling;){if(null===a.return||a.return===b)break a;a=a.return}a.sibling.return=a.return;a=a.sibling}d&=1}I(M,d,b);if(0===(b.mode&2))b.memoizedState=
null;else switch(e){case "forwards":c=b.child;for(e=null;null!==c;)a=c.alternate,null!==a&&null===qh(a)&&(e=c),c=c.sibling;c=e;null===c?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null);Ai(b,!1,e,c,f,b.lastEffect);break;case "backwards":c=null;e=b.child;for(b.child=null;null!==e;){a=e.alternate;if(null!==a&&null===qh(a)){b.child=e;break}a=e.sibling;e.sibling=c;c=e;e=a}Ai(b,!0,c,null,f,b.lastEffect);break;case "together":Ai(b,!1,null,null,void 0,b.lastEffect);break;default:b.memoizedState=null}return b.child}
function oi(a,b,c){null!==a&&(b.dependencies=a.dependencies);var d=b.expirationTime;0!==d&&Jg(d);if(b.childExpirationTime<c)return null;if(null!==a&&b.child!==a.child)throw Error(u(153));if(null!==b.child){a=b.child;c=ah(a,a.pendingProps,a.expirationTime);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=ah(a,a.pendingProps,a.expirationTime),c.return=b;c.sibling=null}return b.child}function Ci(a){a.effectTag|=4}var Hi,Ii,Ji,Ki;
Hi=function(a,b){for(var c=b.child;null!==c;){if(5===c.tag||6===c.tag)a.appendChild(c.stateNode);else if(4!==c.tag&&null!==c.child){c.child.return=c;c=c.child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return}c.sibling.return=c.return;c=c.sibling}};Ii=function(){};
Ji=function(a,b,c,d,e){var f=a.memoizedProps;if(f!==d){var g=b.stateNode;lh(ih.current);a=null;switch(c){case "input":f=Ab(g,f);d=Ab(g,d);a=[];break;case "option":f=Ib(g,f);d=Ib(g,d);a=[];break;case "select":f=n({},f,{value:void 0});d=n({},d,{value:void 0});a=[];break;case "textarea":f=Kb(g,f);d=Kb(g,d);a=[];break;default:"function"!==typeof f.onClick&&"function"===typeof d.onClick&&(g.onclick=ae)}Yd(c,d);var h,k;c=null;for(h in f)if(!d.hasOwnProperty(h)&&f.hasOwnProperty(h)&&null!=f[h])if("style"===
h)for(k in g=f[h],g)g.hasOwnProperty(k)&&(c||(c={}),c[k]="");else"dangerouslySetInnerHTML"!==h&&"children"!==h&&"suppressContentEditableWarning"!==h&&"suppressHydrationWarning"!==h&&"autoFocus"!==h&&(ia.hasOwnProperty(h)?a||(a=[]):(a=a||[]).push(h,null));for(h in d){var l=d[h];g=null!=f?f[h]:void 0;if(d.hasOwnProperty(h)&&l!==g&&(null!=l||null!=g))if("style"===h)if(g){for(k in g)!g.hasOwnProperty(k)||l&&l.hasOwnProperty(k)||(c||(c={}),c[k]="");for(k in l)l.hasOwnProperty(k)&&g[k]!==l[k]&&(c||(c={}),
c[k]=l[k])}else c||(a||(a=[]),a.push(h,c)),c=l;else"dangerouslySetInnerHTML"===h?(l=l?l.__html:void 0,g=g?g.__html:void 0,null!=l&&g!==l&&(a=a||[]).push(h,""+l)):"children"===h?g===l||"string"!==typeof l&&"number"!==typeof l||(a=a||[]).push(h,""+l):"suppressContentEditableWarning"!==h&&"suppressHydrationWarning"!==h&&(ia.hasOwnProperty(h)?(null!=l&&$d(e,h),a||g===l||(a=[])):(a=a||[]).push(h,l))}c&&(a=a||[]).push("style",c);e=a;(b.updateQueue=e)&&Ci(b)}};Ki=function(a,b,c,d){c!==d&&Ci(b)};
function Li(a,b){switch(a.tailMode){case "hidden":b=a.tail;for(var c=null;null!==b;)null!==b.alternate&&(c=b),b=b.sibling;null===c?a.tail=null:c.sibling=null;break;case "collapsed":c=a.tail;for(var d=null;null!==c;)null!==c.alternate&&(d=c),c=c.sibling;null===d?b||null===a.tail?a.tail=null:a.tail.sibling=null:d.sibling=null}}
function Mi(a){switch(a.tag){case 1:L(a.type)&&Ff(a);var b=a.effectTag;return b&4096?(a.effectTag=b&-4097|64,a):null;case 3:nh(a);Gf(a);b=a.effectTag;if(0!==(b&64))throw Error(u(285));a.effectTag=b&-4097|64;return a;case 5:return ph(a),null;case 13:return G(M,a),b=a.effectTag,b&4096?(a.effectTag=b&-4097|64,a):null;case 19:return G(M,a),null;case 4:return nh(a),null;case 10:return tg(a),null;default:return null}}function Ni(a,b){return{value:a,source:b,stack:Xa(b)}}
var Oi="function"===typeof WeakSet?WeakSet:Set;function Pi(a,b){var c=b.source,d=b.stack;null===d&&null!==c&&(d=Xa(c));null!==c&&Wa(c.type);b=b.value;null!==a&&1===a.tag&&Wa(a.type);try{console.error(b)}catch(e){setTimeout(function(){throw e;})}}function Qi(a,b){try{b.props=a.memoizedProps,b.state=a.memoizedState,b.componentWillUnmount()}catch(c){Ri(a,c)}}function Si(a){var b=a.ref;if(null!==b)if("function"===typeof b)try{b(null)}catch(c){Ri(a,c)}else b.current=null}
function Ti(a,b){switch(b.tag){case 0:case 11:case 15:Ui(2,0,b);break;case 1:if(b.effectTag&256&&null!==a){var c=a.memoizedProps,d=a.memoizedState;a=b.stateNode;b=a.getSnapshotBeforeUpdate(b.elementType===b.type?c:mg(b.type,c),d);a.__reactInternalSnapshotBeforeUpdate=b}break;case 3:case 5:case 6:case 4:case 17:break;default:throw Error(u(163));}}
function Ui(a,b,c){c=c.updateQueue;c=null!==c?c.lastEffect:null;if(null!==c){var d=c=c.next;do{if(0!==(d.tag&a)){var e=d.destroy;d.destroy=void 0;void 0!==e&&e()}0!==(d.tag&b)&&(e=d.create,d.destroy=e());d=d.next}while(d!==c)}}
function Vi(a,b,c){"function"===typeof Wi&&Wi(b);switch(b.tag){case 0:case 11:case 14:case 15:a=b.updateQueue;if(null!==a&&(a=a.lastEffect,null!==a)){var d=a.next;fg(97<c?97:c,function(){var a=d;do{var c=a.destroy;if(void 0!==c){var g=b;try{c()}catch(h){Ri(g,h)}}a=a.next}while(a!==d)})}break;case 1:Si(b);c=b.stateNode;"function"===typeof c.componentWillUnmount&&Qi(b,c);break;case 5:Si(b);break;case 4:Xi(a,b,c)}}
function Yi(a){var b=a.alternate;a.return=null;a.child=null;a.memoizedState=null;a.updateQueue=null;a.dependencies=null;a.alternate=null;a.firstEffect=null;a.lastEffect=null;a.pendingProps=null;a.memoizedProps=null;null!==b&&Yi(b)}function Zi(a){return 5===a.tag||3===a.tag||4===a.tag}
function $i(a){a:{for(var b=a.return;null!==b;){if(Zi(b)){var c=b;break a}b=b.return}throw Error(u(160));}b=c.stateNode;switch(c.tag){case 5:var d=!1;break;case 3:b=b.containerInfo;d=!0;break;case 4:b=b.containerInfo;d=!0;break;default:throw Error(u(161));}c.effectTag&16&&(Tb(b,""),c.effectTag&=-17);a:b:for(c=a;;){for(;null===c.sibling;){if(null===c.return||Zi(c.return)){c=null;break a}c=c.return}c.sibling.return=c.return;for(c=c.sibling;5!==c.tag&&6!==c.tag&&18!==c.tag;){if(c.effectTag&2)continue b;
if(null===c.child||4===c.tag)continue b;else c.child.return=c,c=c.child}if(!(c.effectTag&2)){c=c.stateNode;break a}}for(var e=a;;){var f=5===e.tag||6===e.tag;if(f){var g=f?e.stateNode:e.stateNode.instance;if(c)if(d){f=b;var h=g;g=c;8===f.nodeType?f.parentNode.insertBefore(h,g):f.insertBefore(h,g)}else b.insertBefore(g,c);else d?(h=b,8===h.nodeType?(f=h.parentNode,f.insertBefore(g,h)):(f=h,f.appendChild(g)),h=h._reactRootContainer,null!==h&&void 0!==h||null!==f.onclick||(f.onclick=ae)):b.appendChild(g)}else if(4!==
e.tag&&null!==e.child){e.child.return=e;e=e.child;continue}if(e===a)break;for(;null===e.sibling;){if(null===e.return||e.return===a)return;e=e.return}e.sibling.return=e.return;e=e.sibling}}
function Xi(a,b,c){for(var d=b,e=!1,f,g;;){if(!e){e=d.return;a:for(;;){if(null===e)throw Error(u(160));f=e.stateNode;switch(e.tag){case 5:g=!1;break a;case 3:f=f.containerInfo;g=!0;break a;case 4:f=f.containerInfo;g=!0;break a}e=e.return}e=!0}if(5===d.tag||6===d.tag){a:for(var h=a,k=d,l=c,m=k;;)if(Vi(h,m,l),null!==m.child&&4!==m.tag)m.child.return=m,m=m.child;else{if(m===k)break;for(;null===m.sibling;){if(null===m.return||m.return===k)break a;m=m.return}m.sibling.return=m.return;m=m.sibling}g?(h=
f,k=d.stateNode,8===h.nodeType?h.parentNode.removeChild(k):h.removeChild(k)):f.removeChild(d.stateNode)}else if(4===d.tag){if(null!==d.child){f=d.stateNode.containerInfo;g=!0;d.child.return=d;d=d.child;continue}}else if(Vi(a,d,c),null!==d.child){d.child.return=d;d=d.child;continue}if(d===b)break;for(;null===d.sibling;){if(null===d.return||d.return===b)return;d=d.return;4===d.tag&&(e=!1)}d.sibling.return=d.return;d=d.sibling}}
function aj(a,b){switch(b.tag){case 0:case 11:case 14:case 15:Ui(4,8,b);break;case 1:break;case 5:var c=b.stateNode;if(null!=c){var d=b.memoizedProps,e=null!==a?a.memoizedProps:d;a=b.type;var f=b.updateQueue;b.updateQueue=null;if(null!==f){c[ve]=d;"input"===a&&"radio"===d.type&&null!=d.name&&Cb(c,d);Zd(a,e);b=Zd(a,d);for(e=0;e<f.length;e+=2){var g=f[e],h=f[e+1];"style"===g?Wd(c,h):"dangerouslySetInnerHTML"===g?Sb(c,h):"children"===g?Tb(c,h):vb(c,g,h,b)}switch(a){case "input":Eb(c,d);break;case "textarea":Mb(c,
d);break;case "select":b=c._wrapperState.wasMultiple,c._wrapperState.wasMultiple=!!d.multiple,a=d.value,null!=a?Jb(c,!!d.multiple,a,!1):b!==!!d.multiple&&(null!=d.defaultValue?Jb(c,!!d.multiple,d.defaultValue,!0):Jb(c,!!d.multiple,d.multiple?[]:"",!1))}}}break;case 6:if(null===b.stateNode)throw Error(u(162));b.stateNode.nodeValue=b.memoizedProps;break;case 3:b=b.stateNode;b.hydrate&&(b.hydrate=!1,Lc(b.containerInfo));break;case 12:break;case 13:c=b;null===b.memoizedState?d=!1:(d=!0,c=b.child,bj=cg());
if(null!==c)a:for(a=c;;){if(5===a.tag)f=a.stateNode,d?(f=f.style,"function"===typeof f.setProperty?f.setProperty("display","none","important"):f.display="none"):(f=a.stateNode,e=a.memoizedProps.style,e=void 0!==e&&null!==e&&e.hasOwnProperty("display")?e.display:null,f.style.display=Vd("display",e));else if(6===a.tag)a.stateNode.nodeValue=d?"":a.memoizedProps;else if(13===a.tag&&null!==a.memoizedState&&null===a.memoizedState.dehydrated){f=a.child.sibling;f.return=a;a=f;continue}else if(null!==a.child){a.child.return=
a;a=a.child;continue}if(a===c)break a;for(;null===a.sibling;){if(null===a.return||a.return===c)break a;a=a.return}a.sibling.return=a.return;a=a.sibling}cj(b);break;case 19:cj(b);break;case 17:break;case 20:break;case 21:break;default:throw Error(u(163));}}function cj(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Oi);b.forEach(function(b){var d=dj.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}var ej="function"===typeof WeakMap?WeakMap:Map;
function fj(a,b,c){c=Bg(c,null);c.tag=3;c.payload={element:null};var d=b.value;c.callback=function(){gj||(gj=!0,hj=d);Pi(a,b)};return c}
function ij(a,b,c){c=Bg(c,null);c.tag=3;var d=a.type.getDerivedStateFromError;if("function"===typeof d){var e=b.value;c.payload=function(){Pi(a,b);return d(e)}}var f=a.stateNode;null!==f&&"function"===typeof f.componentDidCatch&&(c.callback=function(){"function"!==typeof d&&(null===jj?jj=new Set([this]):jj.add(this),Pi(a,b));var c=b.stack;this.componentDidCatch(b.value,{componentStack:null!==c?c:""})});return c}
var kj=Math.ceil,lj=Ea.ReactCurrentDispatcher,mj=Ea.ReactCurrentOwner,S=0,nj=8,oj=16,pj=32,qj=0,rj=1,sj=2,tj=3,uj=4,vj=5,T=S,U=null,V=null,W=0,X=qj,wj=null,xj=1073741823,yj=1073741823,zj=null,Aj=0,Bj=!1,bj=0,Cj=500,Y=null,gj=!1,hj=null,jj=null,Dj=!1,Ej=null,Fj=90,Gj=null,Hj=0,Ij=null,Jj=0;function Pg(){return(T&(oj|pj))!==S?1073741821-(cg()/10|0):0!==Jj?Jj:Jj=1073741821-(cg()/10|0)}
function Qg(a,b,c){b=b.mode;if(0===(b&2))return 1073741823;var d=dg();if(0===(b&4))return 99===d?1073741823:1073741822;if((T&oj)!==S)return W;if(null!==c)a=lg(a,c.timeoutMs|0||5E3,250);else switch(d){case 99:a=1073741823;break;case 98:a=lg(a,150,100);break;case 97:case 96:a=lg(a,5E3,250);break;case 95:a=2;break;default:throw Error(u(326));}null!==U&&a===W&&--a;return a}
function Rg(a,b){if(50<Hj)throw Hj=0,Ij=null,Error(u(185));a=Kj(a,b);if(null!==a){var c=dg();1073741823===b?(T&nj)!==S&&(T&(oj|pj))===S?Lj(a):(Z(a),T===S&&jg()):Z(a);(T&4)===S||98!==c&&99!==c||(null===Gj?Gj=new Map([[a,b]]):(c=Gj.get(a),(void 0===c||c>b)&&Gj.set(a,b)))}}
function Kj(a,b){a.expirationTime<b&&(a.expirationTime=b);var c=a.alternate;null!==c&&c.expirationTime<b&&(c.expirationTime=b);var d=a.return,e=null;if(null===d&&3===a.tag)e=a.stateNode;else for(;null!==d;){c=d.alternate;d.childExpirationTime<b&&(d.childExpirationTime=b);null!==c&&c.childExpirationTime<b&&(c.childExpirationTime=b);if(null===d.return&&3===d.tag){e=d.stateNode;break}d=d.return}null!==e&&(U===e&&(Jg(b),X===uj&&Mj(e,W)),Nj(e,b));return e}
function Oj(a){var b=a.lastExpiredTime;if(0!==b)return b;b=a.firstPendingTime;if(!Pj(a,b))return b;b=a.lastPingedTime;a=a.nextKnownPendingLevel;return b>a?b:a}
function Z(a){if(0!==a.lastExpiredTime)a.callbackExpirationTime=1073741823,a.callbackPriority=99,a.callbackNode=hg(Lj.bind(null,a));else{var b=Oj(a),c=a.callbackNode;if(0===b)null!==c&&(a.callbackNode=null,a.callbackExpirationTime=0,a.callbackPriority=90);else{var d=Pg();1073741823===b?d=99:1===b||2===b?d=95:(d=10*(1073741821-b)-10*(1073741821-d),d=0>=d?99:250>=d?98:5250>=d?97:95);if(null!==c){var e=a.callbackPriority;if(a.callbackExpirationTime===b&&e>=d)return;c!==Xf&&Nf(c)}a.callbackExpirationTime=
b;a.callbackPriority=d;b=1073741823===b?hg(Lj.bind(null,a)):gg(d,Qj.bind(null,a),{timeout:10*(1073741821-b)-cg()});a.callbackNode=b}}}
function Qj(a,b){Jj=0;if(b)return b=Pg(),Rj(a,b),Z(a),null;var c=Oj(a);if(0!==c){b=a.callbackNode;if((T&(oj|pj))!==S)throw Error(u(327));Sj();a===U&&c===W||Tj(a,c);if(null!==V){var d=T;T|=oj;var e=Uj(a);do try{Vj();break}catch(h){Wj(a,h)}while(1);rg();T=d;lj.current=e;if(X===rj)throw b=wj,Tj(a,c),Mj(a,c),Z(a),b;if(null===V)switch(e=a.finishedWork=a.current.alternate,a.finishedExpirationTime=c,d=X,U=null,d){case qj:case rj:throw Error(u(345));case sj:Rj(a,2<c?2:c);break;case tj:Mj(a,c);d=a.lastSuspendedTime;
c===d&&(a.nextKnownPendingLevel=Xj(e));if(1073741823===xj&&(e=bj+Cj-cg(),10<e)){if(Bj){var f=a.lastPingedTime;if(0===f||f>=c){a.lastPingedTime=c;Tj(a,c);break}}f=Oj(a);if(0!==f&&f!==c)break;if(0!==d&&d!==c){a.lastPingedTime=d;break}a.timeoutHandle=pe(Yj.bind(null,a),e);break}Yj(a);break;case uj:Mj(a,c);d=a.lastSuspendedTime;c===d&&(a.nextKnownPendingLevel=Xj(e));if(Bj&&(e=a.lastPingedTime,0===e||e>=c)){a.lastPingedTime=c;Tj(a,c);break}e=Oj(a);if(0!==e&&e!==c)break;if(0!==d&&d!==c){a.lastPingedTime=
d;break}1073741823!==yj?d=10*(1073741821-yj)-cg():1073741823===xj?d=0:(d=10*(1073741821-xj)-5E3,e=cg(),c=10*(1073741821-c)-e,d=e-d,0>d&&(d=0),d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*kj(d/1960))-d,c<d&&(d=c));if(10<d){a.timeoutHandle=pe(Yj.bind(null,a),d);break}Yj(a);break;case vj:if(1073741823!==xj&&null!==zj){f=xj;var g=zj;d=g.busyMinDurationMs|0;0>=d?d=0:(e=g.busyDelayMs|0,f=cg()-(10*(1073741821-f)-(g.timeoutMs|0||5E3)),d=f<=e?0:e+d-f);if(10<d){Mj(a,c);a.timeoutHandle=
pe(Yj.bind(null,a),d);break}}Yj(a);break;default:throw Error(u(329));}Z(a);if(a.callbackNode===b)return Qj.bind(null,a)}}return null}
function Lj(a){var b=a.lastExpiredTime;b=0!==b?b:1073741823;if(a.finishedExpirationTime===b)Yj(a);else{if((T&(oj|pj))!==S)throw Error(u(327));Sj();a===U&&b===W||Tj(a,b);if(null!==V){var c=T;T|=oj;var d=Uj(a);do try{Zj();break}catch(e){Wj(a,e)}while(1);rg();T=c;lj.current=d;if(X===rj)throw c=wj,Tj(a,b),Mj(a,b),Z(a),c;if(null!==V)throw Error(u(261));a.finishedWork=a.current.alternate;a.finishedExpirationTime=b;U=null;Yj(a);Z(a)}}return null}
function ak(){if(null!==Gj){var a=Gj;Gj=null;a.forEach(function(a,c){Rj(c,a);Z(c)});jg()}}function bk(a,b){var c=T;T|=1;try{return a(b)}finally{T=c,T===S&&jg()}}function ck(a,b){var c=T;T&=-2;T|=nj;try{return a(b)}finally{T=c,T===S&&jg()}}
function Tj(a,b){a.finishedWork=null;a.finishedExpirationTime=0;var c=a.timeoutHandle;-1!==c&&(a.timeoutHandle=-1,qe(c));if(null!==V)for(c=V.return;null!==c;){var d=c;switch(d.tag){case 1:var e=d.type.childContextTypes;null!==e&&void 0!==e&&Ff(d);break;case 3:nh(d);Gf(d);break;case 5:ph(d);break;case 4:nh(d);break;case 13:G(M,d);break;case 19:G(M,d);break;case 10:tg(d)}c=c.return}U=a;V=ah(a.current,null,b);W=b;X=qj;wj=null;yj=xj=1073741823;zj=null;Aj=0;Bj=!1}
function Wj(a,b){do{try{rg();Mh();if(null===V||null===V.return)return X=rj,wj=b,null;a:{var c=a,d=V.return,e=V,f=b;b=W;e.effectTag|=2048;e.firstEffect=e.lastEffect=null;if(null!==f&&"object"===typeof f&&"function"===typeof f.then){var g=f,h=0!==(M.current&1),k=d;do{var l;if(l=13===k.tag){var m=k.memoizedState;if(null!==m)l=null!==m.dehydrated?!0:!1;else{var C=k.memoizedProps;l=void 0===C.fallback?!1:!0!==C.unstable_avoidThisFallback?!0:h?!1:!0}}if(l){var y=k.updateQueue;if(null===y){var H=new Set;
H.add(g);k.updateQueue=H}else y.add(g);if(0===(k.mode&2)){k.effectTag|=64;e.effectTag&=-2981;if(1===e.tag)if(null===e.alternate)e.tag=17;else{var z=Bg(1073741823,null);z.tag=2;Dg(e,z)}e.expirationTime=1073741823;break a}f=void 0;e=b;var ta=c.pingCache;null===ta?(ta=c.pingCache=new ej,f=new Set,ta.set(g,f)):(f=ta.get(g),void 0===f&&(f=new Set,ta.set(g,f)));if(!f.has(e)){f.add(e);var r=dk.bind(null,c,g,e);g.then(r,r)}k.effectTag|=4096;k.expirationTime=b;break a}k=k.return}while(null!==k);f=Error((Wa(e.type)||
"A React component")+" suspended while rendering, but no fallback UI was specified.\n\nAdd a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display."+Xa(e))}X!==vj&&(X=sj);f=Ni(f,e);k=d;do{switch(k.tag){case 3:g=f;k.effectTag|=4096;k.expirationTime=b;var x=fj(k,g,b);Eg(k,x);break a;case 1:g=f;var A=k.type,p=k.stateNode;if(0===(k.effectTag&64)&&("function"===typeof A.getDerivedStateFromError||null!==p&&"function"===typeof p.componentDidCatch&&
(null===jj||!jj.has(p)))){k.effectTag|=4096;k.expirationTime=b;var t=ij(k,g,b);Eg(k,t);break a}}k=k.return}while(null!==k)}V=ek(V)}catch(v){b=v;continue}break}while(1)}function Uj(){var a=lj.current;lj.current=Lh;return null===a?Lh:a}function Ig(a,b){a<xj&&2<a&&(xj=a);null!==b&&a<yj&&2<a&&(yj=a,zj=b)}function Jg(a){a>Aj&&(Aj=a)}function Zj(){for(;null!==V;)V=fk(V)}function Vj(){for(;null!==V&&!Of();)V=fk(V)}
function fk(a){var b=gk(a.alternate,a,W);a.memoizedProps=a.pendingProps;null===b&&(b=ek(a));mj.current=null;return b}
function ek(a){V=a;do{var b=V.alternate;a=V.return;if(0===(V.effectTag&2048)){a:{var c=b;b=V;var d=W;var e=b.pendingProps;switch(b.tag){case 2:break;case 16:break;case 15:case 0:break;case 1:L(b.type)&&Ff(b);break;case 3:nh(b);Gf(b);e=b.stateNode;e.pendingContext&&(e.context=e.pendingContext,e.pendingContext=null);(null===c||null===c.child)&&ki(b)&&Ci(b);Ii(b);break;case 5:ph(b);d=lh(kh.current);var f=b.type;if(null!==c&&null!=b.stateNode)Ji(c,b,f,e,d),c.ref!==b.ref&&(b.effectTag|=128);else if(e){var g=
lh(ih.current);if(ki(b)){e=b;var h=e.stateNode;c=e.type;var k=e.memoizedProps,l=d;h[ue]=e;h[ve]=k;f=void 0;d=h;switch(c){case "iframe":case "object":case "embed":F("load",d);break;case "video":case "audio":for(h=0;h<dc.length;h++)F(dc[h],d);break;case "source":F("error",d);break;case "img":case "image":case "link":F("error",d);F("load",d);break;case "form":F("reset",d);F("submit",d);break;case "details":F("toggle",d);break;case "input":Bb(d,k);F("invalid",d);$d(l,"onChange");break;case "select":d._wrapperState=
{wasMultiple:!!k.multiple};F("invalid",d);$d(l,"onChange");break;case "textarea":Lb(d,k),F("invalid",d),$d(l,"onChange")}Yd(c,k);h=null;for(f in k)k.hasOwnProperty(f)&&(g=k[f],"children"===f?"string"===typeof g?d.textContent!==g&&(h=["children",g]):"number"===typeof g&&d.textContent!==""+g&&(h=["children",""+g]):ia.hasOwnProperty(f)&&null!=g&&$d(l,f));switch(c){case "input":yb(d);Gb(d,k,!0);break;case "textarea":yb(d);Nb(d,k);break;case "select":case "option":break;default:"function"===typeof k.onClick&&
(d.onclick=ae)}f=h;e.updateQueue=f;e=null!==f?!0:!1;e&&Ci(b)}else{c=b;l=f;k=e;h=9===d.nodeType?d:d.ownerDocument;g===Ob.html&&(g=Pb(l));g===Ob.html?"script"===l?(k=h.createElement("div"),k.innerHTML="<script>\x3c/script>",h=k.removeChild(k.firstChild)):"string"===typeof k.is?h=h.createElement(l,{is:k.is}):(h=h.createElement(l),"select"===l&&(l=h,k.multiple?l.multiple=!0:k.size&&(l.size=k.size))):h=h.createElementNS(g,l);k=h;k[ue]=c;k[ve]=e;Hi(k,b,!1,!1);b.stateNode=k;l=f;c=e;var m=d,C=Zd(l,c);switch(l){case "iframe":case "object":case "embed":F("load",
k);d=c;break;case "video":case "audio":for(d=0;d<dc.length;d++)F(dc[d],k);d=c;break;case "source":F("error",k);d=c;break;case "img":case "image":case "link":F("error",k);F("load",k);d=c;break;case "form":F("reset",k);F("submit",k);d=c;break;case "details":F("toggle",k);d=c;break;case "input":Bb(k,c);d=Ab(k,c);F("invalid",k);$d(m,"onChange");break;case "option":d=Ib(k,c);break;case "select":k._wrapperState={wasMultiple:!!c.multiple};d=n({},c,{value:void 0});F("invalid",k);$d(m,"onChange");break;case "textarea":Lb(k,
c);d=Kb(k,c);F("invalid",k);$d(m,"onChange");break;default:d=c}Yd(l,d);h=void 0;g=l;var y=k,H=d;for(h in H)if(H.hasOwnProperty(h)){var z=H[h];"style"===h?Wd(y,z):"dangerouslySetInnerHTML"===h?(z=z?z.__html:void 0,null!=z&&Sb(y,z)):"children"===h?"string"===typeof z?("textarea"!==g||""!==z)&&Tb(y,z):"number"===typeof z&&Tb(y,""+z):"suppressContentEditableWarning"!==h&&"suppressHydrationWarning"!==h&&"autoFocus"!==h&&(ia.hasOwnProperty(h)?null!=z&&$d(m,h):null!=z&&vb(y,h,z,C))}switch(l){case "input":yb(k);
Gb(k,c,!1);break;case "textarea":yb(k);Nb(k,c);break;case "option":null!=c.value&&k.setAttribute("value",""+ub(c.value));break;case "select":d=k;d.multiple=!!c.multiple;k=c.value;null!=k?Jb(d,!!c.multiple,k,!1):null!=c.defaultValue&&Jb(d,!!c.multiple,c.defaultValue,!0);break;default:"function"===typeof d.onClick&&(k.onclick=ae)}(e=ne(f,e))&&Ci(b)}null!==b.ref&&(b.effectTag|=128)}else if(null===b.stateNode)throw Error(u(166));break;case 6:if(c&&null!=b.stateNode)Ki(c,b,c.memoizedProps,e);else{if("string"!==
typeof e&&null===b.stateNode)throw Error(u(166));d=lh(kh.current);lh(ih.current);ki(b)?(e=b,f=e.stateNode,d=e.memoizedProps,f[ue]=e,(e=f.nodeValue!==d)&&Ci(b)):(f=b,e=(9===d.nodeType?d:d.ownerDocument).createTextNode(e),e[ue]=f,b.stateNode=e)}break;case 11:break;case 13:G(M,b);e=b.memoizedState;if(0!==(b.effectTag&64)){b.expirationTime=d;break a}e=null!==e;f=!1;null===c?void 0!==b.memoizedProps.fallback&&ki(b):(d=c.memoizedState,f=null!==d,e||null===d||(d=c.child.sibling,null!==d&&(k=b.firstEffect,
null!==k?(b.firstEffect=d,d.nextEffect=k):(b.firstEffect=b.lastEffect=d,d.nextEffect=null),d.effectTag=8)));if(e&&!f&&0!==(b.mode&2))if(null===c&&!0!==b.memoizedProps.unstable_avoidThisFallback||0!==(M.current&1))X===qj&&(X=tj);else{if(X===qj||X===tj)X=uj;0!==Aj&&null!==U&&(Mj(U,W),Nj(U,Aj))}if(e||f)b.effectTag|=4;break;case 7:break;case 8:break;case 12:break;case 4:nh(b);Ii(b);break;case 10:tg(b);break;case 9:break;case 14:break;case 17:L(b.type)&&Ff(b);break;case 19:G(M,b);e=b.memoizedState;if(null===
e)break;f=0!==(b.effectTag&64);k=e.rendering;if(null===k)if(f)Li(e,!1);else{if(X!==qj||null!==c&&0!==(c.effectTag&64))for(c=b.child;null!==c;){k=qh(c);if(null!==k){b.effectTag|=64;Li(e,!1);f=k.updateQueue;null!==f&&(b.updateQueue=f,b.effectTag|=4);null===e.lastEffect&&(b.firstEffect=null);b.lastEffect=e.lastEffect;e=d;for(f=b.child;null!==f;)d=f,c=e,d.effectTag&=2,d.nextEffect=null,d.firstEffect=null,d.lastEffect=null,k=d.alternate,null===k?(d.childExpirationTime=0,d.expirationTime=c,d.child=null,
d.memoizedProps=null,d.memoizedState=null,d.updateQueue=null,d.dependencies=null):(d.childExpirationTime=k.childExpirationTime,d.expirationTime=k.expirationTime,d.child=k.child,d.memoizedProps=k.memoizedProps,d.memoizedState=k.memoizedState,d.updateQueue=k.updateQueue,c=k.dependencies,d.dependencies=null===c?null:{expirationTime:c.expirationTime,firstContext:c.firstContext,responders:c.responders}),f=f.sibling;I(M,M.current&1|2,b);b=b.child;break a}c=c.sibling}}else{if(!f)if(c=qh(k),null!==c){if(b.effectTag|=
64,f=!0,d=c.updateQueue,null!==d&&(b.updateQueue=d,b.effectTag|=4),Li(e,!0),null===e.tail&&"hidden"===e.tailMode){b=b.lastEffect=e.lastEffect;null!==b&&(b.nextEffect=null);break}}else cg()>e.tailExpiration&&1<d&&(b.effectTag|=64,f=!0,Li(e,!1),b.expirationTime=b.childExpirationTime=d-1);e.isBackwards?(k.sibling=b.child,b.child=k):(d=e.last,null!==d?d.sibling=k:b.child=k,e.last=k)}if(null!==e.tail){0===e.tailExpiration&&(e.tailExpiration=cg()+500);d=e.tail;e.rendering=d;e.tail=d.sibling;e.lastEffect=
b.lastEffect;d.sibling=null;e=M.current;e=f?e&1|2:e&1;I(M,e,b);b=d;break a}break;case 20:break;case 21:break;default:throw Error(u(156,b.tag));}b=null}e=V;if(1===W||1!==e.childExpirationTime){f=0;for(d=e.child;null!==d;)c=d.expirationTime,k=d.childExpirationTime,c>f&&(f=c),k>f&&(f=k),d=d.sibling;e.childExpirationTime=f}if(null!==b)return b;null!==a&&0===(a.effectTag&2048)&&(null===a.firstEffect&&(a.firstEffect=V.firstEffect),null!==V.lastEffect&&(null!==a.lastEffect&&(a.lastEffect.nextEffect=V.firstEffect),
a.lastEffect=V.lastEffect),1<V.effectTag&&(null!==a.lastEffect?a.lastEffect.nextEffect=V:a.firstEffect=V,a.lastEffect=V))}else{b=Mi(V,W);if(null!==b)return b.effectTag&=2047,b;null!==a&&(a.firstEffect=a.lastEffect=null,a.effectTag|=2048)}b=V.sibling;if(null!==b)return b;V=a}while(null!==V);X===qj&&(X=vj);return null}function Xj(a){var b=a.expirationTime;a=a.childExpirationTime;return b>a?b:a}function Yj(a){var b=dg();fg(99,ik.bind(null,a,b));return null}
function ik(a,b){Sj();if((T&(oj|pj))!==S)throw Error(u(327));var c=a.finishedWork,d=a.finishedExpirationTime;if(null===c)return null;a.finishedWork=null;a.finishedExpirationTime=0;if(c===a.current)throw Error(u(177));a.callbackNode=null;a.callbackExpirationTime=0;a.callbackPriority=90;a.nextKnownPendingLevel=0;var e=Xj(c);a.firstPendingTime=e;d<=a.lastSuspendedTime?a.firstSuspendedTime=a.lastSuspendedTime=a.nextKnownPendingLevel=0:d<=a.firstSuspendedTime&&(a.firstSuspendedTime=d-1);d<=a.lastPingedTime&&
(a.lastPingedTime=0);d<=a.lastExpiredTime&&(a.lastExpiredTime=0);a===U&&(V=U=null,W=0);1<c.effectTag?null!==c.lastEffect?(c.lastEffect.nextEffect=c,e=c.firstEffect):e=c:e=c.firstEffect;if(null!==e){var f=T;T|=pj;mj.current=null;le=Ld;var g=fe();if(ge(g)){if("selectionStart"in g)var h={start:g.selectionStart,end:g.selectionEnd};else a:{h=(h=g.ownerDocument)&&h.defaultView||window;var k=h.getSelection&&h.getSelection();if(k&&0!==k.rangeCount){h=k.anchorNode;var l=k.anchorOffset,m=k.focusNode;k=k.focusOffset;
try{h.nodeType,m.nodeType}catch(Db){h=null;break a}var C=0,y=-1,H=-1,z=0,ta=0,r=g,x=null;b:for(;;){for(var A;;){r!==h||0!==l&&3!==r.nodeType||(y=C+l);r!==m||0!==k&&3!==r.nodeType||(H=C+k);3===r.nodeType&&(C+=r.nodeValue.length);if(null===(A=r.firstChild))break;x=r;r=A}for(;;){if(r===g)break b;x===h&&++z===l&&(y=C);x===m&&++ta===k&&(H=C);if(null!==(A=r.nextSibling))break;r=x;x=r.parentNode}r=A}h=-1===y||-1===H?null:{start:y,end:H}}else h=null}h=h||{start:0,end:0}}else h=null;me={focusedElem:g,selectionRange:h};
Ld=!1;Y=e;do try{jk()}catch(Db){if(null===Y)throw Error(u(330));Ri(Y,Db);Y=Y.nextEffect}while(null!==Y);Y=e;do try{for(g=a,h=b;null!==Y;){var p=Y.effectTag;p&16&&Tb(Y.stateNode,"");if(p&128){var t=Y.alternate;if(null!==t){var v=t.ref;null!==v&&("function"===typeof v?v(null):v.current=null)}}switch(p&1038){case 2:$i(Y);Y.effectTag&=-3;break;case 6:$i(Y);Y.effectTag&=-3;aj(Y.alternate,Y);break;case 1024:Y.effectTag&=-1025;break;case 1028:Y.effectTag&=-1025;aj(Y.alternate,Y);break;case 4:aj(Y.alternate,
Y);break;case 8:l=Y,Xi(g,l,h),Yi(l)}Y=Y.nextEffect}}catch(Db){if(null===Y)throw Error(u(330));Ri(Y,Db);Y=Y.nextEffect}while(null!==Y);v=me;t=fe();p=v.focusedElem;h=v.selectionRange;if(t!==p&&p&&p.ownerDocument&&ee(p.ownerDocument.documentElement,p)){null!==h&&ge(p)&&(t=h.start,v=h.end,void 0===v&&(v=t),"selectionStart"in p?(p.selectionStart=t,p.selectionEnd=Math.min(v,p.value.length)):(v=(t=p.ownerDocument||document)&&t.defaultView||window,v.getSelection&&(v=v.getSelection(),l=p.textContent.length,
g=Math.min(h.start,l),h=void 0===h.end?g:Math.min(h.end,l),!v.extend&&g>h&&(l=h,h=g,g=l),l=de(p,g),m=de(p,h),l&&m&&(1!==v.rangeCount||v.anchorNode!==l.node||v.anchorOffset!==l.offset||v.focusNode!==m.node||v.focusOffset!==m.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),v.removeAllRanges(),g>h?(v.addRange(t),v.extend(m.node,m.offset)):(t.setEnd(m.node,m.offset),v.addRange(t))))));t=[];for(v=p;v=v.parentNode;)1===v.nodeType&&t.push({element:v,left:v.scrollLeft,top:v.scrollTop});"function"===
typeof p.focus&&p.focus();for(p=0;p<t.length;p++)v=t[p],v.element.scrollLeft=v.left,v.element.scrollTop=v.top}me=null;Ld=!!le;le=null;a.current=c;Y=e;do try{for(p=d;null!==Y;){var Dh=Y.effectTag;if(Dh&36){var cc=Y.alternate;t=Y;v=p;switch(t.tag){case 0:case 11:case 15:Ui(16,32,t);break;case 1:var dd=t.stateNode;if(t.effectTag&4)if(null===cc)dd.componentDidMount();else{var hk=t.elementType===t.type?cc.memoizedProps:mg(t.type,cc.memoizedProps);dd.componentDidUpdate(hk,cc.memoizedState,dd.__reactInternalSnapshotBeforeUpdate)}var Eh=
t.updateQueue;null!==Eh&&Kg(t,Eh,dd,v);break;case 3:var Fh=t.updateQueue;if(null!==Fh){g=null;if(null!==t.child)switch(t.child.tag){case 5:g=t.child.stateNode;break;case 1:g=t.child.stateNode}Kg(t,Fh,g,v)}break;case 5:var xk=t.stateNode;null===cc&&t.effectTag&4&&ne(t.type,t.memoizedProps)&&xk.focus();break;case 6:break;case 4:break;case 12:break;case 13:if(null===t.memoizedState){var Di=t.alternate;if(null!==Di){var Ei=Di.memoizedState;if(null!==Ei){var Fi=Ei.dehydrated;null!==Fi&&Lc(Fi)}}}break;
case 19:case 17:case 20:case 21:break;default:throw Error(u(163));}}if(Dh&128){t=void 0;var wd=Y.ref;if(null!==wd){var Gi=Y.stateNode;switch(Y.tag){case 5:t=Gi;break;default:t=Gi}"function"===typeof wd?wd(t):wd.current=t}}Y=Y.nextEffect}}catch(Db){if(null===Y)throw Error(u(330));Ri(Y,Db);Y=Y.nextEffect}while(null!==Y);Y=null;Yf();T=f}else a.current=c;if(Dj)Dj=!1,Ej=a,Fj=b;else for(Y=e;null!==Y;)b=Y.nextEffect,Y.nextEffect=null,Y=b;b=a.firstPendingTime;0===b&&(jj=null);1073741823===b?a===Ij?Hj++:(Hj=
0,Ij=a):Hj=0;"function"===typeof kk&&kk(c.stateNode,d);Z(a);if(gj)throw gj=!1,a=hj,hj=null,a;if((T&nj)!==S)return null;jg();return null}function jk(){for(;null!==Y;){var a=Y.effectTag;0!==(a&256)&&Ti(Y.alternate,Y);0===(a&512)||Dj||(Dj=!0,gg(97,function(){Sj();return null}));Y=Y.nextEffect}}function Sj(){if(90!==Fj){var a=97<Fj?97:Fj;Fj=90;return fg(a,lk)}}
function lk(){if(null===Ej)return!1;var a=Ej;Ej=null;if((T&(oj|pj))!==S)throw Error(u(331));var b=T;T|=pj;for(a=a.current.firstEffect;null!==a;){try{var c=a;if(0!==(c.effectTag&512))switch(c.tag){case 0:case 11:case 15:Ui(128,0,c),Ui(0,64,c)}}catch(d){if(null===a)throw Error(u(330));Ri(a,d)}c=a.nextEffect;a.nextEffect=null;a=c}T=b;jg();return!0}function mk(a,b,c){b=Ni(c,b);b=fj(a,b,1073741823);Dg(a,b);a=Kj(a,1073741823);null!==a&&Z(a)}
function Ri(a,b){if(3===a.tag)mk(a,a,b);else for(var c=a.return;null!==c;){if(3===c.tag){mk(c,a,b);break}else if(1===c.tag){var d=c.stateNode;if("function"===typeof c.type.getDerivedStateFromError||"function"===typeof d.componentDidCatch&&(null===jj||!jj.has(d))){a=Ni(b,a);a=ij(c,a,1073741823);Dg(c,a);c=Kj(c,1073741823);null!==c&&Z(c);break}}c=c.return}}
function dk(a,b,c){var d=a.pingCache;null!==d&&d.delete(b);U===a&&W===c?X===uj||X===tj&&1073741823===xj&&cg()-bj<Cj?Tj(a,W):Bj=!0:Pj(a,c)&&(b=a.lastPingedTime,0!==b&&b<c||(a.lastPingedTime=c,a.finishedExpirationTime===c&&(a.finishedExpirationTime=0,a.finishedWork=null),Z(a)))}function dj(a,b){var c=a.stateNode;null!==c&&c.delete(b);b=0;0===b&&(b=Pg(),b=Qg(b,a,null));a=Kj(a,b);null!==a&&Z(a)}var gk;
gk=function(a,b,c){var d=b.expirationTime;if(null!==a){var e=b.pendingProps;if(a.memoizedProps!==e||K.current)wg=!0;else{if(d<c){wg=!1;switch(b.tag){case 3:wi(b);li();break;case 5:oh(b);if(b.mode&4&&1!==c&&e.hidden)return b.expirationTime=b.childExpirationTime=1,null;break;case 1:L(b.type)&&Jf(b);break;case 4:mh(b,b.stateNode.containerInfo);break;case 10:sg(b,b.memoizedProps.value);break;case 13:if(null!==b.memoizedState){d=b.child.childExpirationTime;if(0!==d&&d>=c)return yi(a,b,c);I(M,M.current&
1,b);b=oi(a,b,c);return null!==b?b.sibling:null}I(M,M.current&1,b);break;case 19:d=b.childExpirationTime>=c;if(0!==(a.effectTag&64)){if(d)return Bi(a,b,c);b.effectTag|=64}e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null);I(M,M.current,b);if(!d)return null}return oi(a,b,c)}wg=!1}}else wg=!1;b.expirationTime=0;switch(b.tag){case 2:d=b.type;null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2);a=b.pendingProps;e=Ef(b,J.current);vg(b,c);e=Ih(null,b,d,a,e,c);b.effectTag|=1;if("object"===
typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof){b.tag=1;Mh();if(L(d)){var f=!0;Jf(b)}else f=!1;b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null;var g=d.getDerivedStateFromProps;"function"===typeof g&&Og(b,d,g,a);e.updater=Sg;b.stateNode=e;e._reactInternalFiber=b;Wg(b,d,a,c);b=vi(null,b,d,!0,f,c)}else b.tag=0,R(null,b,e,c),b=b.child;return b;case 16:e=b.elementType;null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2);a=b.pendingProps;Va(e);if(1!==e._status)throw e._result;
e=e._result;b.type=e;f=b.tag=nk(e);a=mg(e,a);switch(f){case 0:b=si(null,b,e,a,c);break;case 1:b=ui(null,b,e,a,c);break;case 11:b=ni(null,b,e,a,c);break;case 14:b=pi(null,b,e,mg(e.type,a),d,c);break;default:throw Error(u(306,e,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:mg(d,e),si(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:mg(d,e),ui(a,b,d,e,c);case 3:wi(b);d=b.updateQueue;if(null===d)throw Error(u(282));e=b.memoizedState;e=null!==e?e.element:
null;Hg(b,d,b.pendingProps,null,c);d=b.memoizedState.element;if(d===e)li(),b=oi(a,b,c);else{if(e=b.stateNode.hydrate)di=re(b.stateNode.containerInfo.firstChild),ci=b,e=ei=!0;if(e)for(c=gh(b,null,d,c),b.child=c;c;)c.effectTag=c.effectTag&-3|1024,c=c.sibling;else R(a,b,d,c),li();b=b.child}return b;case 5:return oh(b),null===a&&ii(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,oe(d,e)?g=null:null!==f&&oe(d,f)&&(b.effectTag|=16),ti(a,b),b.mode&4&&1!==c&&e.hidden?(b.expirationTime=
b.childExpirationTime=1,b=null):(R(a,b,g,c),b=b.child),b;case 6:return null===a&&ii(b),null;case 13:return yi(a,b,c);case 4:return mh(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=fh(b,null,d,c):R(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:mg(d,e),ni(a,b,d,e,c);case 7:return R(a,b,b.pendingProps,c),b.child;case 8:return R(a,b,b.pendingProps.children,c),b.child;case 12:return R(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;
e=b.pendingProps;g=b.memoizedProps;f=e.value;sg(b,f);if(null!==g){var h=g.value;f=of(h,f)?0:("function"===typeof d._calculateChangedBits?d._calculateChangedBits(h,f):1073741823)|0;if(0===f){if(g.children===e.children&&!K.current){b=oi(a,b,c);break a}}else for(h=b.child,null!==h&&(h.return=b);null!==h;){var k=h.dependencies;if(null!==k){g=h.child;for(var l=k.firstContext;null!==l;){if(l.context===d&&0!==(l.observedBits&f)){1===h.tag&&(l=Bg(c,null),l.tag=2,Dg(h,l));h.expirationTime<c&&(h.expirationTime=
c);l=h.alternate;null!==l&&l.expirationTime<c&&(l.expirationTime=c);ug(h.return,c);k.expirationTime<c&&(k.expirationTime=c);break}l=l.next}}else g=10===h.tag?h.type===b.type?null:h.child:h.child;if(null!==g)g.return=h;else for(g=h;null!==g;){if(g===b){g=null;break}h=g.sibling;if(null!==h){h.return=g.return;g=h;break}g=g.return}h=g}}R(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,f=b.pendingProps,d=f.children,vg(b,c),e=xg(e,f.unstable_observedBits),d=d(e),b.effectTag|=1,R(a,b,d,c),b.child;
case 14:return e=b.type,f=mg(e,b.pendingProps),f=mg(e.type,f),pi(a,b,e,f,d,c);case 15:return ri(a,b,b.type,b.pendingProps,d,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:mg(d,e),null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2),b.tag=1,L(d)?(a=!0,Jf(b)):a=!1,vg(b,c),Ug(b,d,e,c),Wg(b,d,e,c),vi(null,b,d,!0,a,c);case 19:return Bi(a,b,c)}throw Error(u(156,b.tag));};var kk=null,Wi=null;
function ok(a){if("undefined"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)return!1;var b=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(b.isDisabled||!b.supportsFiber)return!0;try{var c=b.inject(a);kk=function(a){try{b.onCommitFiberRoot(c,a,void 0,64===(a.current.effectTag&64))}catch(e){}};Wi=function(a){try{b.onCommitFiberUnmount(c,a)}catch(e){}}}catch(d){}return!0}
function pk(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.effectTag=0;this.lastEffect=this.firstEffect=this.nextEffect=null;this.childExpirationTime=this.expirationTime=0;this.alternate=null}function gi(a,b,c,d){return new pk(a,b,c,d)}
function qi(a){a=a.prototype;return!(!a||!a.isReactComponent)}function nk(a){if("function"===typeof a)return qi(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Oa)return 11;if(a===Ra)return 14}return 2}
function ah(a,b){var c=a.alternate;null===c?(c=gi(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.effectTag=0,c.nextEffect=null,c.firstEffect=null,c.lastEffect=null);c.childExpirationTime=a.childExpirationTime;c.expirationTime=a.expirationTime;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{expirationTime:b.expirationTime,
firstContext:b.firstContext,responders:b.responders};c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}
function ch(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)qi(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case Ia:return eh(c.children,e,f,b);case Na:g=8;e|=7;break;case Ja:g=8;e|=1;break;case Ka:return a=gi(12,c,b,e|8),a.elementType=Ka,a.type=Ka,a.expirationTime=f,a;case Pa:return a=gi(13,c,b,e),a.type=Pa,a.elementType=Pa,a.expirationTime=f,a;case Qa:return a=gi(19,c,b,e),a.elementType=Qa,a.expirationTime=f,a;default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case La:g=
10;break a;case Ma:g=9;break a;case Oa:g=11;break a;case Ra:g=14;break a;case Sa:g=16;d=null;break a}throw Error(u(130,null==a?a:typeof a,""));}b=gi(g,c,b,e);b.elementType=a;b.type=d;b.expirationTime=f;return b}function eh(a,b,c,d){a=gi(7,a,d,b);a.expirationTime=c;return a}function bh(a,b,c){a=gi(6,a,null,b);a.expirationTime=c;return a}
function dh(a,b,c){b=gi(4,null!==a.children?a.children:[],a.key,b);b.expirationTime=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}
function qk(a,b,c){this.tag=b;this.current=null;this.containerInfo=a;this.pingCache=this.pendingChildren=null;this.finishedExpirationTime=0;this.finishedWork=null;this.timeoutHandle=-1;this.pendingContext=this.context=null;this.hydrate=c;this.callbackNode=null;this.callbackPriority=90;this.lastExpiredTime=this.lastPingedTime=this.nextKnownPendingLevel=this.lastSuspendedTime=this.firstSuspendedTime=this.firstPendingTime=0}
function Pj(a,b){var c=a.firstSuspendedTime;a=a.lastSuspendedTime;return 0!==c&&c>=b&&a<=b}function Mj(a,b){var c=a.firstSuspendedTime,d=a.lastSuspendedTime;c<b&&(a.firstSuspendedTime=b);if(d>b||0===c)a.lastSuspendedTime=b;b<=a.lastPingedTime&&(a.lastPingedTime=0);b<=a.lastExpiredTime&&(a.lastExpiredTime=0)}
function Nj(a,b){b>a.firstPendingTime&&(a.firstPendingTime=b);var c=a.firstSuspendedTime;0!==c&&(b>=c?a.firstSuspendedTime=a.lastSuspendedTime=a.nextKnownPendingLevel=0:b>=a.lastSuspendedTime&&(a.lastSuspendedTime=b+1),b>a.nextKnownPendingLevel&&(a.nextKnownPendingLevel=b))}function Rj(a,b){var c=a.lastExpiredTime;if(0===c||c>b)a.lastExpiredTime=b}
function rk(a,b,c,d){var e=b.current,f=Pg(),g=Mg.suspense;f=Qg(f,e,g);a:if(c){c=c._reactInternalFiber;b:{if(ec(c)!==c||1!==c.tag)throw Error(u(170));var h=c;do{switch(h.tag){case 3:h=h.stateNode.context;break b;case 1:if(L(h.type)){h=h.stateNode.__reactInternalMemoizedMergedChildContext;break b}}h=h.return}while(null!==h);throw Error(u(171));}if(1===c.tag){var k=c.type;if(L(k)){c=If(c,k,h);break a}}c=h}else c=Cf;null===b.context?b.context=c:b.pendingContext=c;b=Bg(f,g);b.payload={element:a};d=void 0===
d?null:d;null!==d&&(b.callback=d);Dg(e,b);Rg(e,f);return f}function sk(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function tk(a,b){a=a.memoizedState;null!==a&&null!==a.dehydrated&&a.retryTime<b&&(a.retryTime=b)}function uk(a,b){tk(a,b);(a=a.alternate)&&tk(a,b)}
function vk(a,b,c){var d=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:Ha,key:null==d?null:""+d,children:a,containerInfo:b,implementation:c}}jc=function(a){if(13===a.tag){var b=lg(Pg(),150,100);Rg(a,b);uk(a,b)}};kc=function(a){if(13===a.tag){Pg();var b=kg++;Rg(a,b);uk(a,b)}};lc=function(a){if(13===a.tag){var b=Pg();b=Qg(b,a,null);Rg(a,b);uk(a,b)}};
Za=function(a,b,c){switch(b){case "input":Eb(a,c);b=c.name;if("radio"===c.type&&null!=b){for(c=a;c.parentNode;)c=c.parentNode;c=c.querySelectorAll("input[name="+JSON.stringify(""+b)+'][type="radio"]');for(b=0;b<c.length;b++){var d=c[b];if(d!==a&&d.form===a.form){var e=ye(d);if(!e)throw Error(u(90));zb(d);Eb(d,e)}}}break;case "textarea":Mb(a,c);break;case "select":b=c.value,null!=b&&Jb(a,!!c.multiple,b,!1)}};
function wk(a,b,c){c=null!=c&&!0===c.hydrate;var d=new qk(a,b,c),e=gi(3,null,null,2===b?7:1===b?3:0);d.current=e;e.stateNode=d;a[we]=d.current;c&&0!==b&&wc(9===a.nodeType?a:a.ownerDocument);this._internalRoot=d}wk.prototype.render=function(a,b){var c=this._internalRoot;rk(a,c,null,void 0===b?null:b)};wk.prototype.unmount=function(a){var b=this._internalRoot;rk(null,b,null,void 0===a?null:a)};
function yk(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType&&(8!==a.nodeType||" react-mount-point-unstable "!==a.nodeValue))}eb=bk;fb=function(a,b,c,d){var e=T;T|=4;try{return fg(98,a.bind(null,b,c,d))}finally{T=e,T===S&&jg()}};gb=function(){(T&(1|oj|pj))===S&&(ak(),Sj())};hb=function(a,b){var c=T;T|=2;try{return a(b)}finally{T=c,T===S&&jg()}};
function zk(a,b){b||(b=a?9===a.nodeType?a.documentElement:a.firstChild:null,b=!(!b||1!==b.nodeType||!b.hasAttribute("data-reactroot")));if(!b)for(var c;c=a.lastChild;)a.removeChild(c);return new wk(a,0,b?{hydrate:!0}:void 0)}
function Ak(a,b,c,d,e){var f=c._reactRootContainer;if(f){var g=f._internalRoot;if("function"===typeof e){var h=e;e=function(){var a=sk(g);h.call(a)}}rk(b,g,a,e)}else{f=c._reactRootContainer=zk(c,d);g=f._internalRoot;if("function"===typeof e){var k=e;e=function(){var a=sk(g);k.call(a)}}ck(function(){rk(b,g,a,e)})}return sk(g)}function Bk(a,b){var c=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!yk(b))throw Error(u(200));return vk(a,b,null,c)}
var Ck={createPortal:Bk,findDOMNode:function(a){if(null==a)return null;if(1===a.nodeType)return a;var b=a._reactInternalFiber;if(void 0===b){if("function"===typeof a.render)throw Error(u(188));throw Error(u(268,Object.keys(a)));}a=ic(b);a=null===a?null:a.stateNode;return a},hydrate:function(a,b,c){if(!yk(b))throw Error(u(200));return Ak(null,a,b,!0,c)},render:function(a,b,c){if(!yk(b))throw Error(u(200));return Ak(null,a,b,!1,c)},unstable_renderSubtreeIntoContainer:function(a,b,c,d){if(!yk(c))throw Error(u(200));
if(null==a||void 0===a._reactInternalFiber)throw Error(u(38));return Ak(a,b,c,!1,d)},unmountComponentAtNode:function(a){if(!yk(a))throw Error(u(40));return a._reactRootContainer?(ck(function(){Ak(null,null,a,!1,function(){a._reactRootContainer=null})}),!0):!1},unstable_createPortal:function(){return Bk.apply(void 0,arguments)},unstable_batchedUpdates:bk,flushSync:function(a,b){if((T&(oj|pj))!==S)throw Error(u(187));var c=T;T|=1;try{return fg(99,a.bind(null,b))}finally{T=c,jg()}},__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{Events:[Cc,
xe,ye,Ca.injectEventPluginsByName,fa,Sc,function(a){ya(a,Rc)},cb,db,Pd,Ba,Sj,{current:!1}]}};
(function(a){var b=a.findFiberByHostInstance;return ok(n({},a,{overrideHookState:null,overrideProps:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:Ea.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){a=ic(a);return null===a?null:a.stateNode},findFiberByHostInstance:function(a){return b?b(a):null},findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null}))})({findFiberByHostInstance:Fc,bundleType:0,version:"16.11.0",
rendererPackageName:"react-dom"});var Dk={default:Ck},Ek=Dk&&Ck||Dk;module.exports=Ek.default||Ek;


/***/ }),
/* 84 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


if (true) {
  module.exports = __webpack_require__(85);
} else {}


/***/ }),
/* 85 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/** @license React v0.17.0
 * scheduler.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

Object.defineProperty(exports,"__esModule",{value:!0});var f,g,h,k,l;
if("undefined"===typeof window||"function"!==typeof MessageChannel){var p=null,q=null,t=function(){if(null!==p)try{var a=exports.unstable_now();p(!0,a);p=null}catch(b){throw setTimeout(t,0),b;}},u=Date.now();exports.unstable_now=function(){return Date.now()-u};f=function(a){null!==p?setTimeout(f,0,a):(p=a,setTimeout(t,0))};g=function(a,b){q=setTimeout(a,b)};h=function(){clearTimeout(q)};k=function(){return!1};l=exports.unstable_forceFrameRate=function(){}}else{var w=window.performance,x=window.Date,
y=window.setTimeout,z=window.clearTimeout,A=window.requestAnimationFrame,B=window.cancelAnimationFrame;"undefined"!==typeof console&&("function"!==typeof A&&console.error("This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills"),"function"!==typeof B&&console.error("This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills"));if("object"===typeof w&&
"function"===typeof w.now)exports.unstable_now=function(){return w.now()};else{var C=x.now();exports.unstable_now=function(){return x.now()-C}}var D=!1,E=null,F=-1,G=5,H=0;k=function(){return exports.unstable_now()>=H};l=function(){};exports.unstable_forceFrameRate=function(a){0>a||125<a?console.error("forceFrameRate takes a positive int between 0 and 125, forcing framerates higher than 125 fps is not unsupported"):G=0<a?Math.floor(1E3/a):33.33};var I=new MessageChannel,J=I.port2;I.port1.onmessage=
function(){if(null!==E){var a=exports.unstable_now();H=a+G;try{E(!0,a)?J.postMessage(null):(D=!1,E=null)}catch(b){throw J.postMessage(null),b;}}else D=!1};f=function(a){E=a;D||(D=!0,J.postMessage(null))};g=function(a,b){F=y(function(){a(exports.unstable_now())},b)};h=function(){z(F);F=-1}}function K(a,b){var c=a.length;a.push(b);a:for(;;){var d=Math.floor((c-1)/2),e=a[d];if(void 0!==e&&0<L(e,b))a[d]=b,a[c]=e,c=d;else break a}}function M(a){a=a[0];return void 0===a?null:a}
function N(a){var b=a[0];if(void 0!==b){var c=a.pop();if(c!==b){a[0]=c;a:for(var d=0,e=a.length;d<e;){var m=2*(d+1)-1,n=a[m],v=m+1,r=a[v];if(void 0!==n&&0>L(n,c))void 0!==r&&0>L(r,n)?(a[d]=r,a[v]=c,d=v):(a[d]=n,a[m]=c,d=m);else if(void 0!==r&&0>L(r,c))a[d]=r,a[v]=c,d=v;else break a}}return b}return null}function L(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}var O=[],P=[],Q=1,R=null,S=3,T=!1,U=!1,V=!1;
function W(a){for(var b=M(P);null!==b;){if(null===b.callback)N(P);else if(b.startTime<=a)N(P),b.sortIndex=b.expirationTime,K(O,b);else break;b=M(P)}}function X(a){V=!1;W(a);if(!U)if(null!==M(O))U=!0,f(Y);else{var b=M(P);null!==b&&g(X,b.startTime-a)}}
function Y(a,b){U=!1;V&&(V=!1,h());T=!0;var c=S;try{W(b);for(R=M(O);null!==R&&(!(R.expirationTime>b)||a&&!k());){var d=R.callback;if(null!==d){R.callback=null;S=R.priorityLevel;var e=d(R.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?R.callback=e:R===M(O)&&N(O);W(b)}else N(O);R=M(O)}if(null!==R)var m=!0;else{var n=M(P);null!==n&&g(X,n.startTime-b);m=!1}return m}finally{R=null,S=c,T=!1}}
function Z(a){switch(a){case 1:return-1;case 2:return 250;case 5:return 1073741823;case 4:return 1E4;default:return 5E3}}var aa=l;exports.unstable_ImmediatePriority=1;exports.unstable_UserBlockingPriority=2;exports.unstable_NormalPriority=3;exports.unstable_IdlePriority=5;exports.unstable_LowPriority=4;exports.unstable_runWithPriority=function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=S;S=a;try{return b()}finally{S=c}};
exports.unstable_next=function(a){switch(S){case 1:case 2:case 3:var b=3;break;default:b=S}var c=S;S=b;try{return a()}finally{S=c}};
exports.unstable_scheduleCallback=function(a,b,c){var d=exports.unstable_now();if("object"===typeof c&&null!==c){var e=c.delay;e="number"===typeof e&&0<e?d+e:d;c="number"===typeof c.timeout?c.timeout:Z(a)}else c=Z(a),e=d;c=e+c;a={id:Q++,callback:b,priorityLevel:a,startTime:e,expirationTime:c,sortIndex:-1};e>d?(a.sortIndex=e,K(P,a),null===M(O)&&a===M(P)&&(V?h():V=!0,g(X,e-d))):(a.sortIndex=c,K(O,a),U||T||(U=!0,f(Y)));return a};exports.unstable_cancelCallback=function(a){a.callback=null};
exports.unstable_wrapCallback=function(a){var b=S;return function(){var c=S;S=b;try{return a.apply(this,arguments)}finally{S=c}}};exports.unstable_getCurrentPriorityLevel=function(){return S};exports.unstable_shouldYield=function(){var a=exports.unstable_now();W(a);var b=M(O);return b!==R&&null!==R&&null!==b&&null!==b.callback&&b.startTime<=a&&b.expirationTime<R.expirationTime||k()};exports.unstable_requestPaint=aa;exports.unstable_continueExecution=function(){U||T||(U=!0,f(Y))};
exports.unstable_pauseExecution=function(){};exports.unstable_getFirstCallbackNode=function(){return M(O)};exports.unstable_Profiling=null;


/***/ }),
/* 86 */
/***/ (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.
 */



var ReactPropTypesSecret = __webpack_require__(87);

function emptyFunction() {}
function emptyFunctionWithReset() {}
emptyFunctionWithReset.resetWarningCache = emptyFunction;

module.exports = function() {
  function shim(props, propName, componentName, location, propFullName, secret) {
    if (secret === ReactPropTypesSecret) {
      // It is still safe when called from React.
      return;
    }
    var err = new Error(
      'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
      'Use PropTypes.checkPropTypes() to call them. ' +
      'Read more at http://fb.me/use-check-prop-types'
    );
    err.name = 'Invariant Violation';
    throw err;
  };
  shim.isRequired = shim;
  function getShim() {
    return shim;
  };
  // Important!
  // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
  var ReactPropTypes = {
    array: shim,
    bool: shim,
    func: shim,
    number: shim,
    object: shim,
    string: shim,
    symbol: shim,

    any: shim,
    arrayOf: getShim,
    element: shim,
    elementType: shim,
    instanceOf: getShim,
    node: shim,
    objectOf: getShim,
    oneOf: getShim,
    oneOfType: getShim,
    shape: getShim,
    exact: getShim,

    checkPropTypes: emptyFunctionWithReset,
    resetWarningCache: emptyFunction
  };

  ReactPropTypes.PropTypes = ReactPropTypes;

  return ReactPropTypes;
};


/***/ }),
/* 87 */
/***/ (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.
 */



var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';

module.exports = ReactPropTypesSecret;


/***/ }),
/* 88 */
/***/ (function(module, exports, __webpack_require__) {

/**
 * Copyright (c) 2014-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.
 */

var runtime = (function (exports) {
  "use strict";

  var Op = Object.prototype;
  var hasOwn = Op.hasOwnProperty;
  var undefined; // More compressible than void 0.
  var $Symbol = typeof Symbol === "function" ? Symbol : {};
  var iteratorSymbol = $Symbol.iterator || "@@iterator";
  var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
  var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";

  function wrap(innerFn, outerFn, self, tryLocsList) {
    // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
    var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
    var generator = Object.create(protoGenerator.prototype);
    var context = new Context(tryLocsList || []);

    // The ._invoke method unifies the implementations of the .next,
    // .throw, and .return methods.
    generator._invoke = makeInvokeMethod(innerFn, self, context);

    return generator;
  }
  exports.wrap = wrap;

  // Try/catch helper to minimize deoptimizations. Returns a completion
  // record like context.tryEntries[i].completion. This interface could
  // have been (and was previously) designed to take a closure to be
  // invoked without arguments, but in all the cases we care about we
  // already have an existing method we want to call, so there's no need
  // to create a new function object. We can even get away with assuming
  // the method takes exactly one argument, since that happens to be true
  // in every case, so we don't have to touch the arguments object. The
  // only additional allocation required is the completion record, which
  // has a stable shape and so hopefully should be cheap to allocate.
  function tryCatch(fn, obj, arg) {
    try {
      return { type: "normal", arg: fn.call(obj, arg) };
    } catch (err) {
      return { type: "throw", arg: err };
    }
  }

  var GenStateSuspendedStart = "suspendedStart";
  var GenStateSuspendedYield = "suspendedYield";
  var GenStateExecuting = "executing";
  var GenStateCompleted = "completed";

  // Returning this object from the innerFn has the same effect as
  // breaking out of the dispatch switch statement.
  var ContinueSentinel = {};

  // Dummy constructor functions that we use as the .constructor and
  // .constructor.prototype properties for functions that return Generator
  // objects. For full spec compliance, you may wish to configure your
  // minifier not to mangle the names of these two functions.
  function Generator() {}
  function GeneratorFunction() {}
  function GeneratorFunctionPrototype() {}

  // This is a polyfill for %IteratorPrototype% for environments that
  // don't natively support it.
  var IteratorPrototype = {};
  IteratorPrototype[iteratorSymbol] = function () {
    return this;
  };

  var getProto = Object.getPrototypeOf;
  var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  if (NativeIteratorPrototype &&
      NativeIteratorPrototype !== Op &&
      hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
    // This environment has a native %IteratorPrototype%; use it instead
    // of the polyfill.
    IteratorPrototype = NativeIteratorPrototype;
  }

  var Gp = GeneratorFunctionPrototype.prototype =
    Generator.prototype = Object.create(IteratorPrototype);
  GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
  GeneratorFunctionPrototype.constructor = GeneratorFunction;
  GeneratorFunctionPrototype[toStringTagSymbol] =
    GeneratorFunction.displayName = "GeneratorFunction";

  // Helper for defining the .next, .throw, and .return methods of the
  // Iterator interface in terms of a single ._invoke method.
  function defineIteratorMethods(prototype) {
    ["next", "throw", "return"].forEach(function(method) {
      prototype[method] = function(arg) {
        return this._invoke(method, arg);
      };
    });
  }

  exports.isGeneratorFunction = function(genFun) {
    var ctor = typeof genFun === "function" && genFun.constructor;
    return ctor
      ? ctor === GeneratorFunction ||
        // For the native GeneratorFunction constructor, the best we can
        // do is to check its .name property.
        (ctor.displayName || ctor.name) === "GeneratorFunction"
      : false;
  };

  exports.mark = function(genFun) {
    if (Object.setPrototypeOf) {
      Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
    } else {
      genFun.__proto__ = GeneratorFunctionPrototype;
      if (!(toStringTagSymbol in genFun)) {
        genFun[toStringTagSymbol] = "GeneratorFunction";
      }
    }
    genFun.prototype = Object.create(Gp);
    return genFun;
  };

  // Within the body of any async function, `await x` is transformed to
  // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
  // `hasOwn.call(value, "__await")` to determine if the yielded value is
  // meant to be awaited.
  exports.awrap = function(arg) {
    return { __await: arg };
  };

  function AsyncIterator(generator) {
    function invoke(method, arg, resolve, reject) {
      var record = tryCatch(generator[method], generator, arg);
      if (record.type === "throw") {
        reject(record.arg);
      } else {
        var result = record.arg;
        var value = result.value;
        if (value &&
            typeof value === "object" &&
            hasOwn.call(value, "__await")) {
          return Promise.resolve(value.__await).then(function(value) {
            invoke("next", value, resolve, reject);
          }, function(err) {
            invoke("throw", err, resolve, reject);
          });
        }

        return Promise.resolve(value).then(function(unwrapped) {
          // When a yielded Promise is resolved, its final value becomes
          // the .value of the Promise<{value,done}> result for the
          // current iteration.
          result.value = unwrapped;
          resolve(result);
        }, function(error) {
          // If a rejected Promise was yielded, throw the rejection back
          // into the async generator function so it can be handled there.
          return invoke("throw", error, resolve, reject);
        });
      }
    }

    var previousPromise;

    function enqueue(method, arg) {
      function callInvokeWithMethodAndArg() {
        return new Promise(function(resolve, reject) {
          invoke(method, arg, resolve, reject);
        });
      }

      return previousPromise =
        // If enqueue has been called before, then we want to wait until
        // all previous Promises have been resolved before calling invoke,
        // so that results are always delivered in the correct order. If
        // enqueue has not been called before, then it is important to
        // call invoke immediately, without waiting on a callback to fire,
        // so that the async generator function has the opportunity to do
        // any necessary setup in a predictable way. This predictability
        // is why the Promise constructor synchronously invokes its
        // executor callback, and why async functions synchronously
        // execute code before the first await. Since we implement simple
        // async functions in terms of async generators, it is especially
        // important to get this right, even though it requires care.
        previousPromise ? previousPromise.then(
          callInvokeWithMethodAndArg,
          // Avoid propagating failures to Promises returned by later
          // invocations of the iterator.
          callInvokeWithMethodAndArg
        ) : callInvokeWithMethodAndArg();
    }

    // Define the unified helper method that is used to implement .next,
    // .throw, and .return (see defineIteratorMethods).
    this._invoke = enqueue;
  }

  defineIteratorMethods(AsyncIterator.prototype);
  AsyncIterator.prototype[asyncIteratorSymbol] = function () {
    return this;
  };
  exports.AsyncIterator = AsyncIterator;

  // Note that simple async functions are implemented on top of
  // AsyncIterator objects; they just return a Promise for the value of
  // the final result produced by the iterator.
  exports.async = function(innerFn, outerFn, self, tryLocsList) {
    var iter = new AsyncIterator(
      wrap(innerFn, outerFn, self, tryLocsList)
    );

    return exports.isGeneratorFunction(outerFn)
      ? iter // If outerFn is a generator, return the full iterator.
      : iter.next().then(function(result) {
          return result.done ? result.value : iter.next();
        });
  };

  function makeInvokeMethod(innerFn, self, context) {
    var state = GenStateSuspendedStart;

    return function invoke(method, arg) {
      if (state === GenStateExecuting) {
        throw new Error("Generator is already running");
      }

      if (state === GenStateCompleted) {
        if (method === "throw") {
          throw arg;
        }

        // Be forgiving, per 25.3.3.3.3 of the spec:
        // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
        return doneResult();
      }

      context.method = method;
      context.arg = arg;

      while (true) {
        var delegate = context.delegate;
        if (delegate) {
          var delegateResult = maybeInvokeDelegate(delegate, context);
          if (delegateResult) {
            if (delegateResult === ContinueSentinel) continue;
            return delegateResult;
          }
        }

        if (context.method === "next") {
          // Setting context._sent for legacy support of Babel's
          // function.sent implementation.
          context.sent = context._sent = context.arg;

        } else if (context.method === "throw") {
          if (state === GenStateSuspendedStart) {
            state = GenStateCompleted;
            throw context.arg;
          }

          context.dispatchException(context.arg);

        } else if (context.method === "return") {
          context.abrupt("return", context.arg);
        }

        state = GenStateExecuting;

        var record = tryCatch(innerFn, self, context);
        if (record.type === "normal") {
          // If an exception is thrown from innerFn, we leave state ===
          // GenStateExecuting and loop back for another invocation.
          state = context.done
            ? GenStateCompleted
            : GenStateSuspendedYield;

          if (record.arg === ContinueSentinel) {
            continue;
          }

          return {
            value: record.arg,
            done: context.done
          };

        } else if (record.type === "throw") {
          state = GenStateCompleted;
          // Dispatch the exception by looping back around to the
          // context.dispatchException(context.arg) call above.
          context.method = "throw";
          context.arg = record.arg;
        }
      }
    };
  }

  // Call delegate.iterator[context.method](context.arg) and handle the
  // result, either by returning a { value, done } result from the
  // delegate iterator, or by modifying context.method and context.arg,
  // setting context.delegate to null, and returning the ContinueSentinel.
  function maybeInvokeDelegate(delegate, context) {
    var method = delegate.iterator[context.method];
    if (method === undefined) {
      // A .throw or .return when the delegate iterator has no .throw
      // method always terminates the yield* loop.
      context.delegate = null;

      if (context.method === "throw") {
        // Note: ["return"] must be used for ES3 parsing compatibility.
        if (delegate.iterator["return"]) {
          // If the delegate iterator has a return method, give it a
          // chance to clean up.
          context.method = "return";
          context.arg = undefined;
          maybeInvokeDelegate(delegate, context);

          if (context.method === "throw") {
            // If maybeInvokeDelegate(context) changed context.method from
            // "return" to "throw", let that override the TypeError below.
            return ContinueSentinel;
          }
        }

        context.method = "throw";
        context.arg = new TypeError(
          "The iterator does not provide a 'throw' method");
      }

      return ContinueSentinel;
    }

    var record = tryCatch(method, delegate.iterator, context.arg);

    if (record.type === "throw") {
      context.method = "throw";
      context.arg = record.arg;
      context.delegate = null;
      return ContinueSentinel;
    }

    var info = record.arg;

    if (! info) {
      context.method = "throw";
      context.arg = new TypeError("iterator result is not an object");
      context.delegate = null;
      return ContinueSentinel;
    }

    if (info.done) {
      // Assign the result of the finished delegate to the temporary
      // variable specified by delegate.resultName (see delegateYield).
      context[delegate.resultName] = info.value;

      // Resume execution at the desired location (see delegateYield).
      context.next = delegate.nextLoc;

      // If context.method was "throw" but the delegate handled the
      // exception, let the outer generator proceed normally. If
      // context.method was "next", forget context.arg since it has been
      // "consumed" by the delegate iterator. If context.method was
      // "return", allow the original .return call to continue in the
      // outer generator.
      if (context.method !== "return") {
        context.method = "next";
        context.arg = undefined;
      }

    } else {
      // Re-yield the result returned by the delegate method.
      return info;
    }

    // The delegate iterator is finished, so forget it and continue with
    // the outer generator.
    context.delegate = null;
    return ContinueSentinel;
  }

  // Define Generator.prototype.{next,throw,return} in terms of the
  // unified ._invoke helper method.
  defineIteratorMethods(Gp);

  Gp[toStringTagSymbol] = "Generator";

  // A Generator should always return itself as the iterator object when the
  // @@iterator function is called on it. Some browsers' implementations of the
  // iterator prototype chain incorrectly implement this, causing the Generator
  // object to not be returned from this call. This ensures that doesn't happen.
  // See https://github.com/facebook/regenerator/issues/274 for more details.
  Gp[iteratorSymbol] = function() {
    return this;
  };

  Gp.toString = function() {
    return "[object Generator]";
  };

  function pushTryEntry(locs) {
    var entry = { tryLoc: locs[0] };

    if (1 in locs) {
      entry.catchLoc = locs[1];
    }

    if (2 in locs) {
      entry.finallyLoc = locs[2];
      entry.afterLoc = locs[3];
    }

    this.tryEntries.push(entry);
  }

  function resetTryEntry(entry) {
    var record = entry.completion || {};
    record.type = "normal";
    delete record.arg;
    entry.completion = record;
  }

  function Context(tryLocsList) {
    // The root entry object (effectively a try statement without a catch
    // or a finally block) gives us a place to store values thrown from
    // locations where there is no enclosing try statement.
    this.tryEntries = [{ tryLoc: "root" }];
    tryLocsList.forEach(pushTryEntry, this);
    this.reset(true);
  }

  exports.keys = function(object) {
    var keys = [];
    for (var key in object) {
      keys.push(key);
    }
    keys.reverse();

    // Rather than returning an object with a next method, we keep
    // things simple and return the next function itself.
    return function next() {
      while (keys.length) {
        var key = keys.pop();
        if (key in object) {
          next.value = key;
          next.done = false;
          return next;
        }
      }

      // To avoid creating an additional object, we just hang the .value
      // and .done properties off the next function object itself. This
      // also ensures that the minifier will not anonymize the function.
      next.done = true;
      return next;
    };
  };

  function values(iterable) {
    if (iterable) {
      var iteratorMethod = iterable[iteratorSymbol];
      if (iteratorMethod) {
        return iteratorMethod.call(iterable);
      }

      if (typeof iterable.next === "function") {
        return iterable;
      }

      if (!isNaN(iterable.length)) {
        var i = -1, next = function next() {
          while (++i < iterable.length) {
            if (hasOwn.call(iterable, i)) {
              next.value = iterable[i];
              next.done = false;
              return next;
            }
          }

          next.value = undefined;
          next.done = true;

          return next;
        };

        return next.next = next;
      }
    }

    // Return an iterator with no values.
    return { next: doneResult };
  }
  exports.values = values;

  function doneResult() {
    return { value: undefined, done: true };
  }

  Context.prototype = {
    constructor: Context,

    reset: function(skipTempReset) {
      this.prev = 0;
      this.next = 0;
      // Resetting context._sent for legacy support of Babel's
      // function.sent implementation.
      this.sent = this._sent = undefined;
      this.done = false;
      this.delegate = null;

      this.method = "next";
      this.arg = undefined;

      this.tryEntries.forEach(resetTryEntry);

      if (!skipTempReset) {
        for (var name in this) {
          // Not sure about the optimal order of these conditions:
          if (name.charAt(0) === "t" &&
              hasOwn.call(this, name) &&
              !isNaN(+name.slice(1))) {
            this[name] = undefined;
          }
        }
      }
    },

    stop: function() {
      this.done = true;

      var rootEntry = this.tryEntries[0];
      var rootRecord = rootEntry.completion;
      if (rootRecord.type === "throw") {
        throw rootRecord.arg;
      }

      return this.rval;
    },

    dispatchException: function(exception) {
      if (this.done) {
        throw exception;
      }

      var context = this;
      function handle(loc, caught) {
        record.type = "throw";
        record.arg = exception;
        context.next = loc;

        if (caught) {
          // If the dispatched exception was caught by a catch block,
          // then let that catch block handle the exception normally.
          context.method = "next";
          context.arg = undefined;
        }

        return !! caught;
      }

      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        var record = entry.completion;

        if (entry.tryLoc === "root") {
          // Exception thrown outside of any try block that could handle
          // it, so set the completion value of the entire function to
          // throw the exception.
          return handle("end");
        }

        if (entry.tryLoc <= this.prev) {
          var hasCatch = hasOwn.call(entry, "catchLoc");
          var hasFinally = hasOwn.call(entry, "finallyLoc");

          if (hasCatch && hasFinally) {
            if (this.prev < entry.catchLoc) {
              return handle(entry.catchLoc, true);
            } else if (this.prev < entry.finallyLoc) {
              return handle(entry.finallyLoc);
            }

          } else if (hasCatch) {
            if (this.prev < entry.catchLoc) {
              return handle(entry.catchLoc, true);
            }

          } else if (hasFinally) {
            if (this.prev < entry.finallyLoc) {
              return handle(entry.finallyLoc);
            }

          } else {
            throw new Error("try statement without catch or finally");
          }
        }
      }
    },

    abrupt: function(type, arg) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.tryLoc <= this.prev &&
            hasOwn.call(entry, "finallyLoc") &&
            this.prev < entry.finallyLoc) {
          var finallyEntry = entry;
          break;
        }
      }

      if (finallyEntry &&
          (type === "break" ||
           type === "continue") &&
          finallyEntry.tryLoc <= arg &&
          arg <= finallyEntry.finallyLoc) {
        // Ignore the finally entry if control is not jumping to a
        // location outside the try/catch block.
        finallyEntry = null;
      }

      var record = finallyEntry ? finallyEntry.completion : {};
      record.type = type;
      record.arg = arg;

      if (finallyEntry) {
        this.method = "next";
        this.next = finallyEntry.finallyLoc;
        return ContinueSentinel;
      }

      return this.complete(record);
    },

    complete: function(record, afterLoc) {
      if (record.type === "throw") {
        throw record.arg;
      }

      if (record.type === "break" ||
          record.type === "continue") {
        this.next = record.arg;
      } else if (record.type === "return") {
        this.rval = this.arg = record.arg;
        this.method = "return";
        this.next = "end";
      } else if (record.type === "normal" && afterLoc) {
        this.next = afterLoc;
      }

      return ContinueSentinel;
    },

    finish: function(finallyLoc) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.finallyLoc === finallyLoc) {
          this.complete(entry.completion, entry.afterLoc);
          resetTryEntry(entry);
          return ContinueSentinel;
        }
      }
    },

    "catch": function(tryLoc) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.tryLoc === tryLoc) {
          var record = entry.completion;
          if (record.type === "throw") {
            var thrown = record.arg;
            resetTryEntry(entry);
          }
          return thrown;
        }
      }

      // The context.catch method must only be called with a location
      // argument that corresponds to a known catch block.
      throw new Error("illegal catch attempt");
    },

    delegateYield: function(iterable, resultName, nextLoc) {
      this.delegate = {
        iterator: values(iterable),
        resultName: resultName,
        nextLoc: nextLoc
      };

      if (this.method === "next") {
        // Deliberately forget the last sent value so that we don't
        // accidentally pass it on to the delegate.
        this.arg = undefined;
      }

      return ContinueSentinel;
    }
  };

  // Regardless of whether this script is executing as a CommonJS module
  // or not, return the runtime object so that we can declare the variable
  // regeneratorRuntime in the outer scope, which allows this module to be
  // injected easily by `bin/regenerator --include-runtime script.js`.
  return exports;

}(
  // If this script is executing as a CommonJS module, use module.exports
  // as the regeneratorRuntime namespace. Otherwise create a new empty
  // object. Either way, the resulting object will be used to initialize
  // the regeneratorRuntime variable at the top of this file.
   true ? module.exports : undefined
));

try {
  regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
  // This module should not be running in strict mode, so the above
  // assignment should always work unless something is misconfigured. Just
  // in case runtime.js accidentally runs in strict mode, we can escape
  // strict mode using a global Function call. This could conceivably fail
  // if a Content Security Policy forbids using Function, but in that case
  // the proper solution is to fix the accidental strict mode problem. If
  // you've misconfigured your bundler to force strict mode and applied a
  // CSP to forbid Function, and you're not willing to fix either of those
  // problems, please detail your unique predicament in a GitHub issue.
  Function("r", "regeneratorRuntime = r")(runtime);
}


/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/** @license React v16.12.0
 * react-is.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

Object.defineProperty(exports,"__esModule",{value:!0});
var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b?Symbol.for("react.suspense_list"):
60120,r=b?Symbol.for("react.memo"):60115,t=b?Symbol.for("react.lazy"):60116,v=b?Symbol.for("react.fundamental"):60117,w=b?Symbol.for("react.responder"):60118,x=b?Symbol.for("react.scope"):60119;function y(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function z(a){return y(a)===m}
exports.typeOf=y;exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;exports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;
exports.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||"object"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===v||a.$$typeof===w||a.$$typeof===x)};exports.isAsyncMode=function(a){return z(a)||y(a)===l};exports.isConcurrentMode=z;exports.isContextConsumer=function(a){return y(a)===k};exports.isContextProvider=function(a){return y(a)===h};
exports.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return y(a)===n};exports.isFragment=function(a){return y(a)===e};exports.isLazy=function(a){return y(a)===t};exports.isMemo=function(a){return y(a)===r};exports.isPortal=function(a){return y(a)===d};exports.isProfiler=function(a){return y(a)===g};exports.isStrictMode=function(a){return y(a)===f};exports.isSuspense=function(a){return y(a)===p};


/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {

/**
 * enigma.js v2.6.3
 * Copyright (c) 2019 QlikTech International AB
 * This library is licensed under MIT - See the LICENSE file for full details
 */

(function (global, factory) {
   true ? module.exports = factory() :
  undefined;
}(this, (function () { 'use strict';

  /**
   * Utility functions
   */

  var util = {};

  util.isObject = function isObject(arg) {
    return typeof arg === 'object' && arg !== null;
  };

  util.isNumber = function isNumber(arg) {
    return typeof arg === 'number';
  };

  util.isUndefined = function isUndefined(arg) {
    return arg === void 0;
  };

  util.isFunction = function isFunction(arg){
    return typeof arg === 'function';
  };


  /**
   * EventEmitter class
   */

  function EventEmitter() {
    EventEmitter.init.call(this);
  }
  var nodeEventEmitter = EventEmitter;

  // Backwards-compat with node 0.10.x
  EventEmitter.EventEmitter = EventEmitter;

  EventEmitter.prototype._events = undefined;
  EventEmitter.prototype._maxListeners = undefined;

  // By default EventEmitters will print a warning if more than 10 listeners are
  // added to it. This is a useful default which helps finding memory leaks.
  EventEmitter.defaultMaxListeners = 10;

  EventEmitter.init = function() {
    this._events = this._events || {};
    this._maxListeners = this._maxListeners || undefined;
  };

  // Obviously not all Emitters should be limited to 10. This function allows
  // that to be increased. Set to zero for unlimited.
  EventEmitter.prototype.setMaxListeners = function(n) {
    if (!util.isNumber(n) || n < 0 || isNaN(n))
      throw TypeError('n must be a positive number');
    this._maxListeners = n;
    return this;
  };

  EventEmitter.prototype.emit = function(type) {
    var er, handler, len, args, i, listeners;

    if (!this._events)
      this._events = {};

    // If there is no 'error' event listener then throw.
    if (type === 'error' && !this._events.error) {
      er = arguments[1];
      if (er instanceof Error) {
        throw er; // Unhandled 'error' event
      } else {
        throw Error('Uncaught, unspecified "error" event.');
      }
    }

    handler = this._events[type];

    if (util.isUndefined(handler))
      return false;

    if (util.isFunction(handler)) {
      switch (arguments.length) {
        // fast cases
        case 1:
          handler.call(this);
          break;
        case 2:
          handler.call(this, arguments[1]);
          break;
        case 3:
          handler.call(this, arguments[1], arguments[2]);
          break;
        // slower
        default:
          len = arguments.length;
          args = new Array(len - 1);
          for (i = 1; i < len; i++)
            args[i - 1] = arguments[i];
          handler.apply(this, args);
      }
    } else if (util.isObject(handler)) {
      len = arguments.length;
      args = new Array(len - 1);
      for (i = 1; i < len; i++)
        args[i - 1] = arguments[i];

      listeners = handler.slice();
      len = listeners.length;
      for (i = 0; i < len; i++)
        listeners[i].apply(this, args);
    }

    return true;
  };

  EventEmitter.prototype.addListener = function(type, listener) {
    var m;

    if (!util.isFunction(listener))
      throw TypeError('listener must be a function');

    if (!this._events)
      this._events = {};

    // To avoid recursion in the case that type === "newListener"! Before
    // adding it to the listeners, first emit "newListener".
    if (this._events.newListener)
      this.emit('newListener', type,
                util.isFunction(listener.listener) ?
                listener.listener : listener);

    if (!this._events[type])
      // Optimize the case of one listener. Don't need the extra array object.
      this._events[type] = listener;
    else if (util.isObject(this._events[type]))
      // If we've already got an array, just append.
      this._events[type].push(listener);
    else
      // Adding the second element, need to change to array.
      this._events[type] = [this._events[type], listener];

    // Check for listener leak
    if (util.isObject(this._events[type]) && !this._events[type].warned) {
      var m;
      if (!util.isUndefined(this._maxListeners)) {
        m = this._maxListeners;
      } else {
        m = EventEmitter.defaultMaxListeners;
      }

      if (m && m > 0 && this._events[type].length > m) {
        this._events[type].warned = true;

        if (util.isFunction(console.error)) {
          console.error('(node) warning: possible EventEmitter memory ' +
                        'leak detected. %d listeners added. ' +
                        'Use emitter.setMaxListeners() to increase limit.',
                        this._events[type].length);
        }
        if (util.isFunction(console.trace))
          console.trace();
      }
    }

    return this;
  };

  EventEmitter.prototype.on = EventEmitter.prototype.addListener;

  EventEmitter.prototype.once = function(type, listener) {
    if (!util.isFunction(listener))
      throw TypeError('listener must be a function');

    var fired = false;

    function g() {
      this.removeListener(type, g);

      if (!fired) {
        fired = true;
        listener.apply(this, arguments);
      }
    }

    g.listener = listener;
    this.on(type, g);

    return this;
  };

  // emits a 'removeListener' event iff the listener was removed
  EventEmitter.prototype.removeListener = function(type, listener) {
    var list, position, length, i;

    if (!util.isFunction(listener))
      throw TypeError('listener must be a function');

    if (!this._events || !this._events[type])
      return this;

    list = this._events[type];
    length = list.length;
    position = -1;

    if (list === listener ||
        (util.isFunction(list.listener) && list.listener === listener)) {
      delete this._events[type];
      if (this._events.removeListener)
        this.emit('removeListener', type, listener);

    } else if (util.isObject(list)) {
      for (i = length; i-- > 0;) {
        if (list[i] === listener ||
            (list[i].listener && list[i].listener === listener)) {
          position = i;
          break;
        }
      }

      if (position < 0)
        return this;

      if (list.length === 1) {
        list.length = 0;
        delete this._events[type];
      } else {
        list.splice(position, 1);
      }

      if (this._events.removeListener)
        this.emit('removeListener', type, listener);
    }

    return this;
  };

  EventEmitter.prototype.removeAllListeners = function(type) {
    var key, listeners;

    if (!this._events)
      return this;

    // not listening for removeListener, no need to emit
    if (!this._events.removeListener) {
      if (arguments.length === 0)
        this._events = {};
      else if (this._events[type])
        delete this._events[type];
      return this;
    }

    // emit removeListener for all listeners on all events
    if (arguments.length === 0) {
      for (key in this._events) {
        if (key === 'removeListener') continue;
        this.removeAllListeners(key);
      }
      this.removeAllListeners('removeListener');
      this._events = {};
      return this;
    }

    listeners = this._events[type];

    if (util.isFunction(listeners)) {
      this.removeListener(type, listeners);
    } else if (Array.isArray(listeners)) {
      // LIFO order
      while (listeners.length)
        this.removeListener(type, listeners[listeners.length - 1]);
    }
    delete this._events[type];

    return this;
  };

  EventEmitter.prototype.listeners = function(type) {
    var ret;
    if (!this._events || !this._events[type])
      ret = [];
    else if (util.isFunction(this._events[type]))
      ret = [this._events[type]];
    else
      ret = this._events[type].slice();
    return ret;
  };

  EventEmitter.listenerCount = function(emitter, type) {
    var ret;
    if (!emitter._events || !emitter._events[type])
      ret = 0;
    else if (util.isFunction(emitter._events[type]))
      ret = 1;
    else
      ret = emitter._events[type].length;
    return ret;
  };

  /**
  * @module EventEmitter
  * @private
  */

  var Events = {
    /**
    * Function used to add event handling to objects passed in.
    * @param {Object} obj Object instance that will get event handling.
    */
    mixin: function mixin(obj) {
      Object.keys(nodeEventEmitter.prototype).forEach(function (key) {
        obj[key] = nodeEventEmitter.prototype[key];
      });
      nodeEventEmitter.init(obj);
    }
  };

  function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

  function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

  function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

  function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

  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 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 _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

  function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

  /**
   * Error containing a custom error code.
   * @extends Error
   * @property {number} code The error code as defined by `errorCodes`
   * @property {boolean} enigmaError=true
   */
  var EnigmaError =
  /*#__PURE__*/
  function (_Error) {
    _inherits(EnigmaError, _Error);

    function EnigmaError(name, code) {
      var _this;

      _classCallCheck(this, EnigmaError);

      _this = _possibleConstructorReturn(this, _getPrototypeOf(EnigmaError).call(this, name));
      _this.code = code;
      _this.enigmaError = true;
      return _this;
    }

    return EnigmaError;
  }(_wrapNativeSuper(Error));
  /**
   * Create an enigmaError
   * @param {Number} code A proper error code from `errorCodes`
   * @param {String} name A message/name of the enigmaError.
   * @returns {EnigmaError}
   */


  function createEnigmaError(code, name) {
    return new EnigmaError(name, code);
  }

  /**
   * @enum
   */
  var errorCodes = {
    /**
     * You're trying to send data on a socket that's not created
     * @type {number}
     */
    NOT_CONNECTED: -1,

    /**
     * The object you're trying to fetch does not exist
     * @type {number}
     */
    OBJECT_NOT_FOUND: -2,

    /**
     * Unexpected RPC response, expected array of patches
     * @type {number}
     */
    EXPECTED_ARRAY_OF_PATCHES: -3,

    /**
     * Patchee is not an object we can patch
     * @type {number}
     */
    PATCH_HAS_NO_PARENT: -4,

    /**
     * This entry is already defined with another key
     * @type {number}
     */
    ENTRY_ALREADY_DEFINED: -5,

    /**
     * You need to supply a configuration
     * @type {number}
     */
    NO_CONFIG_SUPPLIED: -6,

    /**
     * There's no promise object available (polyfill required?)
     * @type {number}
     */
    PROMISE_REQUIRED: -7,

    /**
     * The schema struct type you requested does not exist
     * @type {number}
     */
    SCHEMA_STRUCT_TYPE_NOT_FOUND: -8,

    /**
     * Can't override this function
     * @type {number}
     */
    SCHEMA_MIXIN_CANT_OVERRIDE_FUNCTION: -9,

    /**
     * Extend is not allowed for this mixin
     * @type {number}
     */
    SCHEMA_MIXIN_EXTEND_NOT_ALLOWED: -10,

    /**
     * Session suspended - no interaction allowed
     * @type {number}
     */
    SESSION_SUSPENDED: -11,

    /**
     * onlyIfAttached supplied, but you got SESSION_CREATED
     * @type {number}
     */
    SESSION_NOT_ATTACHED: -12
  };

  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

  function _classCallCheck$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }

  function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  var RPC_CLOSE_NORMAL = 1000;
  var RPC_CLOSE_MANUAL_SUSPEND = 4000;
  var cacheId = 0;
  /**
   * The QIX Engine session object
   */

  var Session =
  /*#__PURE__*/
  function () {
    /**
     * Handle all JSON-RPC notification event, 'notification:*. Or handle a specific JSON-RPC
     * notification event, 'notification:OnConnected'. These events depend on the product you use QIX
     * Engine from.
     * @event Session#notification
     * @type {Object}
     */

    /**
    * Handle websocket messages. Generally used in debugging purposes. traffic:* will handle all
    * websocket messages, traffic:sent will handle outgoing messages and traffic:received will handle
    * incoming messages.
    * @event Session#traffic
    * @type {Object}
    */
    function Session(options) {
      _classCallCheck$1(this, Session);

      var session = this;
      Object.assign(session, options);
      this.Promise = this.config.Promise;
      this.definition = this.config.definition;
      Events.mixin(session);
      cacheId += 1;
      session.id = cacheId;
      session.rpc.on('socket-error', session.onRpcError.bind(session));
      session.rpc.on('closed', session.onRpcClosed.bind(session));
      session.rpc.on('message', session.onRpcMessage.bind(session));
      session.rpc.on('notification', session.onRpcNotification.bind(session));
      session.rpc.on('traffic', session.onRpcTraffic.bind(session));
      session.on('closed', function () {
        return session.onSessionClosed();
      });
    }
    /**
    * Event handler for re-triggering error events from RPC.
    * @private
    * @emits socket-error
    * @param {Error} err Webocket error event.
    */


    _createClass(Session, [{
      key: "onRpcError",
      value: function onRpcError(err) {
        if (this.suspendResume.isSuspended) {
          return;
        }

        this.emit('socket-error', err);
      }
      /**
      * Event handler for the RPC close event.
      * @private
      * @emits Session#suspended
      * @emits Session#closed
      * @param {Event} evt WebSocket close event.
      */

    }, {
      key: "onRpcClosed",
      value: function onRpcClosed(evt) {
        var _this = this;

        /**
         * Handle suspended state. This event is triggered in two cases (listed below). It is useful
         * in scenarios where you for example want to block interaction in your application until you
         * are resumed again. If config.suspendOnClose is true and there was a network disconnect
         * (socked closed) or if you ran session.suspend().
         * @event Session#suspended
         * @type {Object}
         * @param {Object} evt Event object.
         * @param {String} evt.initiator String indication what triggered the suspended state. Possible
         * values network, manual.
         */
        if (this.suspendResume.isSuspended) {
          return;
        }

        if (evt.code === RPC_CLOSE_NORMAL || evt.code === RPC_CLOSE_MANUAL_SUSPEND) {
          return;
        }

        if (this.config.suspendOnClose) {
          var code = evt.code,
              reason = evt.reason;
          this.suspendResume.suspend().then(function () {
            return _this.emit('suspended', {
              initiator: 'network',
              code: code,
              reason: reason
            });
          });
        } else {
          this.emit('closed', evt);
        }
      }
      /**
      * Event handler for the RPC message event.
      * @private
      * @param {Object} response JSONRPC response.
      */

    }, {
      key: "onRpcMessage",
      value: function onRpcMessage(response) {
        var _this2 = this;

        if (this.suspendResume.isSuspended) {
          return;
        }

        if (response.change) {
          response.change.forEach(function (handle) {
            return _this2.emitHandleChanged(handle);
          });
        }

        if (response.close) {
          response.close.forEach(function (handle) {
            return _this2.emitHandleClosed(handle);
          });
        }
      }
      /**
      * Event handler for the RPC notification event.
      * @private
      * @emits Session#notification
      * @param {Object} response The JSONRPC notification.
      */

    }, {
      key: "onRpcNotification",
      value: function onRpcNotification(response) {
        this.emit('notification:*', response.method, response.params);
        this.emit("notification:".concat(response.method), response.params);
      }
      /**
      * Event handler for the RPC traffic event.
      * @private
      * @emits Session#traffic
      * @param {String} dir The traffic direction, sent or received.
      * @param {Object} data JSONRPC request/response/WebSocket message.
      * @param {Number} handle The associated handle.
      */

    }, {
      key: "onRpcTraffic",
      value: function onRpcTraffic(dir, data, handle) {
        this.emit('traffic:*', dir, data);
        this.emit("traffic:".concat(dir), data);
        var api = this.apis.getApi(handle);

        if (api) {
          api.emit('traffic:*', dir, data);
          api.emit("traffic:".concat(dir), data);
        }
      }
      /**
      * Event handler for cleaning up API instances when a session has been closed.
      * @private
      * @emits API#closed
      */

    }, {
      key: "onSessionClosed",
      value: function onSessionClosed() {
        this.apis.getApis().forEach(function (entry) {
          entry.api.emit('closed');
          entry.api.removeAllListeners();
        });
        this.apis.clear();
      }
      /**
       * Function used to get an API for a backend object.
       * @private
       * @param {Object} args Arguments used to create object API.
       * @param {Number} args.handle Handle of the backend object.
       * @param {String} args.id ID of the backend object.
       * @param {String} args.type QIX type of the backend object. Can for example
       *                           be "Doc" or "GenericVariable".
       * @param {String} args.genericType Custom type of the backend object, if defined in qInfo.
       * @returns {*} Returns the generated and possibly augmented API.
       */

    }, {
      key: "getObjectApi",
      value: function getObjectApi(args) {
        var handle = args.handle,
            id = args.id,
            type = args.type,
            genericType = args.genericType;
        var api = this.apis.getApi(handle);

        if (api) {
          return api;
        }

        var factory = this.definition.generate(type);
        api = factory(this, handle, id, genericType);
        this.apis.add(handle, api);
        return api;
      }
      /**
      * Establishes the websocket against the configured URL and returns the Global instance.
      * @emits Session#opened
      * @returns {Promise<Object>} Eventually resolved if the connection was successful.
      */

    }, {
      key: "open",
      value: function open() {
        var _this3 = this;

        /**
         * Handle opened state. This event is triggered whenever the websocket is connected and ready for
         * communication.
         * @event Session#opened
         * @type {Object}
         */
        if (!this.globalPromise) {
          var args = {
            handle: -1,
            id: 'Global',
            type: 'Global',
            genericType: 'Global'
          };
          this.globalPromise = this.rpc.open().then(function () {
            return _this3.getObjectApi(args);
          }).then(function (global) {
            _this3.emit('opened');

            return global;
          });
        }

        return this.globalPromise;
      }
      /**
      * Function used to send data on the RPC socket.
      * @param {Object} request The request to be sent. (data and some meta info)
      * @returns {Object} Returns a promise instance.
      */

    }, {
      key: "send",
      value: function send(request) {
        var _this4 = this;

        if (this.suspendResume.isSuspended) {
          return this.Promise.reject(createEnigmaError(errorCodes.SESSION_SUSPENDED, 'Session suspended'));
        }

        request.id = this.rpc.createRequestId();
        var promise = this.intercept.executeRequests(this, this.Promise.resolve(request)).then(function (augmentedRequest) {
          var data = _objectSpread({}, _this4.config.protocol, {}, augmentedRequest); // the outKey value is used by multiple-out interceptor, at some point
          // we need to refactor that implementation and figure out how to transport
          // this value without hijacking the JSONRPC request object:


          delete data.outKey;

          var response = _this4.rpc.send(data);

          augmentedRequest.retry = function () {
            return _this4.send(request);
          };

          return _this4.intercept.executeResponses(_this4, response, augmentedRequest);
        });
        Session.addToPromiseChain(promise, 'requestId', request.id);
        return promise;
      }
      /**
      * Suspends the enigma.js session by closing the websocket and rejecting all method calls
      * until is has been resumed again.
      * @emits Session#suspended
      * @param {Number} [code=4000] - The reason code for suspending the connection.
      * @param {String} [reason=""] - The human readable string describing
      * why the connection is suspended.
      * @returns {Promise<Object>} Eventually resolved when the websocket has been closed.
      */

    }, {
      key: "suspend",
      value: function suspend() {
        var _this5 = this;

        var code = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 4000;
        var reason = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
        return this.suspendResume.suspend(code, reason).then(function () {
          return _this5.emit('suspended', {
            initiator: 'manual',
            code: code,
            reason: reason
          });
        });
      }
      /**
      * Resumes a previously suspended enigma.js session by re-creating the websocket and,
      * if possible, re-open the document as well as refreshing the internal cashes. If successful,
      * changed events will be triggered on all generated APIs, and on the ones it was unable to
      * restore, the closed event will be triggered.
      * @emits Session#resumed
      * @param {Boolean} onlyIfAttached If true, resume only if the session was re-attached properly.
      * @returns {Promise<Object>} Eventually resolved when the websocket (and potentially the
      * previously opened document, and generated APIs) has been restored, rejected when it fails any
      * of those steps, or when onlyIfAttached is true and a new session was created.
      */

    }, {
      key: "resume",
      value: function resume(onlyIfAttached) {
        var _this6 = this;

        /**
         * Handle resumed state. This event is triggered when the session was properly resumed. It is
         * useful in scenarios where you for example can close blocking modal dialogs and allow the user
         * to interact with your application again.
         * @event Session#resumed
         * @type {Object}
         */
        return this.suspendResume.resume(onlyIfAttached).then(function (value) {
          _this6.emit('resumed');

          return value;
        });
      }
      /**
      * Closes the websocket and cleans up internal caches, also triggers the closed event
      * on all generated APIs. Note that you have to manually invoke this when you want to
      * close a session and config.suspendOnClose is true.
      * @emits Session#closed
      * @param {Number} [code=1000] - The reason code for closing the connection.
      * @param {String} [reason=""] - The human readable string describing why the connection is closed.
      * @returns {Promise<Object>} Eventually resolved when the websocket has been closed.
      */

    }, {
      key: "close",
      value: function close() {
        var _this7 = this;

        var code = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1000;
        var reason = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';

        /**
         * Handle closed state. This event is triggered when the underlying websocket is closed and
         * config.suspendOnClose is false.
         * @event Session#closed
         * @type {Object}
         */
        this.globalPromise = undefined;
        return this.rpc.close(code, reason).then(function (evt) {
          return _this7.emit('closed', evt);
        });
      }
      /**
      * Given a handle, this function will emit the 'changed' event on the
      * corresponding API instance.
      * @private
      * @param {Number} handle The handle of the API instance.
      * @emits API#changed
      */

    }, {
      key: "emitHandleChanged",
      value: function emitHandleChanged(handle) {
        var api = this.apis.getApi(handle);

        if (api) {
          api.emit('changed');
        }
      }
      /**
      * Given a handle, this function will emit the 'closed' event on the
      * corresponding API instance.
      * @private
      * @param {Number} handle The handle of the API instance.
      * @emits API#closed
      */

    }, {
      key: "emitHandleClosed",
      value: function emitHandleClosed(handle) {
        var api = this.apis.getApi(handle);

        if (api) {
          api.emit('closed');
          api.removeAllListeners();
        }
      }
      /**
      * Function used to add info on the promise chain.
      * @private
      * @param {Promise<Object>} promise The promise to add info on.
      * @param {String} name The property to add info on.
      * @param {Any} value The info to add.
      */

    }], [{
      key: "addToPromiseChain",
      value: function addToPromiseChain(promise, name, value) {
        promise[name] = value;
        var then = promise.then;

        promise.then = function patchedThen() {
          for (var _len = arguments.length, params = new Array(_len), _key = 0; _key < _len; _key++) {
            params[_key] = arguments[_key];
          }

          var chain = then.apply(this, params);
          Session.addToPromiseChain(chain, name, value);
          return chain;
        };
      }
    }]);

    return Session;
  }();

  function _classCallCheck$2(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

  function _defineProperties$1(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); } }

  function _createClass$1(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$1(Constructor.prototype, protoProps); if (staticProps) _defineProperties$1(Constructor, staticProps); return Constructor; }
  /**
  * Key-value cache
  * @private
  */

  var KeyValueCache =
  /*#__PURE__*/
  function () {
    function KeyValueCache() {
      _classCallCheck$2(this, KeyValueCache);

      this.entries = {};
    }
    /**
    * Adds an entry.
    * @private
    * @function KeyValueCache#add
    * @param {String} key The key representing an entry.
    * @param {*} entry The entry to be added.
    */


    _createClass$1(KeyValueCache, [{
      key: "add",
      value: function add(key, entry) {
        key += '';

        if (typeof this.entries[key] !== 'undefined') {
          throw createEnigmaError(errorCodes.ENTRY_ALREADY_DEFINED, "Entry already defined with key ".concat(key));
        }

        this.entries[key] = entry;
      }
      /**
      * Sets an entry.
      * @private
      * @function KeyValueCache#set
      * @param {String} key The key representing an entry.
      * @param {*} entry The entry.
      */

    }, {
      key: "set",
      value: function set(key, entry) {
        key += '';
        this.entries[key] = entry;
      }
      /**
      * Removes an entry.
      * @private
      * @function KeyValueCache#remove
      * @param {String} key The key representing an entry.
      */

    }, {
      key: "remove",
      value: function remove(key) {
        delete this.entries[key];
      }
      /**
      * Gets an entry.
      * @private
      * @function KeyValueCache#get
      * @param {String} key The key representing an entry.
      * @returns {*} The entry for the key.
      */

    }, {
      key: "get",
      value: function get(key) {
        return this.entries[key];
      }
      /**
      * Gets a list of all entries.
      * @private
      * @function KeyValueCache#getAll
      * @returns {Array} The list of entries including its `key` and `value` properties.
      */

    }, {
      key: "getAll",
      value: function getAll() {
        var _this = this;

        return Object.keys(this.entries).map(function (key) {
          return {
            key: key,
            value: _this.entries[key]
          };
        });
      }
      /**
      * Gets a key for an entry.
      * @private
      * @function KeyValueCache#getKey
      * @param {*} entry The entry to locate the key for.
      * @returns {String} The key representing an entry.
      */

    }, {
      key: "getKey",
      value: function getKey(entry) {
        var _this2 = this;

        return Object.keys(this.entries).filter(function (key) {
          return _this2.entries[key] === entry;
        })[0];
      }
      /**
      * Clears the cache of all entries.
      * @private
      * @function KeyValueCache#clear
      */

    }, {
      key: "clear",
      value: function clear() {
        this.entries = {};
      }
    }]);

    return KeyValueCache;
  }();

  function _classCallCheck$3(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

  function _defineProperties$2(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); } }

  function _createClass$2(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$2(Constructor.prototype, protoProps); if (staticProps) _defineProperties$2(Constructor, staticProps); return Constructor; }

  function _typeof$1(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$1 = function _typeof(obj) { return typeof obj; }; } else { _typeof$1 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$1(obj); }
  var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  /**
  * Returns the camelCase counterpart of a symbol.
  * @private
  * @param {String} symbol The symbol.
  * @return the camelCase counterpart.
  */

  function toCamelCase(symbol) {
    return symbol.substring(0, 1).toLowerCase() + symbol.substring(1);
  }
  /**
   * A facade function that allows parameters to be passed either by name
   * (through an object), or by position (through an array).
   * @private
   * @param {Function} base The function that is being overriden. Will be
   *                        called with parameters in array-form.
   * @param {Object} defaults Parameter list and it's default values.
   * @param {*} params The parameters.
   */


  function namedParamFacade(base, defaults) {
    for (var _len = arguments.length, params = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
      params[_key - 2] = arguments[_key];
    }

    if (params.length === 1 && _typeof$1(params[0]) === 'object' && !Array.isArray(params[0])) {
      var valid = Object.keys(params[0]).every(function (key) {
        return hasOwnProperty$1.call(defaults, key);
      });

      if (valid) {
        params = Object.keys(defaults).map(function (key) {
          return params[0][key] || defaults[key];
        });
      }
    }

    return base.apply(this, params);
  }
  /**
  * Qix schema definition.
  * @private
  */


  var Schema =
  /*#__PURE__*/
  function () {
    /**
    * Create a new schema instance.
    * @private
    * @param {Configuration} config The configuration for QIX.
    */
    function Schema(config) {
      _classCallCheck$3(this, Schema);

      this.config = config;
      this.Promise = config.Promise;
      this.schema = config.schema;
      this.mixins = new KeyValueCache();
      this.types = new KeyValueCache();
    }

    _createClass$2(Schema, [{
      key: "registerMixin",
      value: function registerMixin(_ref) {
        var _this = this;

        var types = _ref.types,
            type = _ref.type,
            extend = _ref.extend,
            override = _ref.override,
            init = _ref.init;

        if (!Array.isArray(types)) {
          types = [types];
        } // to support a single type


        if (type) {
          types.push(type);
        }

        var cached = {
          extend: extend,
          override: override,
          init: init
        };
        types.forEach(function (typeKey) {
          var entryList = _this.mixins.get(typeKey);

          if (entryList) {
            entryList.push(cached);
          } else {
            _this.mixins.add(typeKey, [cached]);
          }
        });
      }
      /**
      * Function used to generate a type definition.
      * @private
      * @param {String} type The type.
      * @returns {{create: Function, def: Object}} Returns an object with a definition
      *          of the type and a create factory.
      */

    }, {
      key: "generate",
      value: function generate(type) {
        var entry = this.types.get(type);

        if (entry) {
          return entry;
        }

        if (!this.schema.structs[type]) {
          throw createEnigmaError(errorCodes.SCHEMA_STRUCT_TYPE_NOT_FOUND, "".concat(type, " not found"));
        }

        var factory = this.generateApi(type, this.schema.structs[type]);
        this.types.add(type, factory);
        return factory;
      }
      /**
      * Function used to generate an API definition for a given type.
      * @private
      * @param {String} type The type to generate.
      * @param {Object} schema The schema describing the type.
      * @returns {{create: (function(session:Object, handle:Number, id:String,
      *          customKey:String)), def: Object}} Returns the API definition.
      */

    }, {
      key: "generateApi",
      value: function generateApi(type, schema) {
        var api = Object.create({});
        this.generateDefaultApi(api, schema); // Generate default

        this.mixinType(type, api); // Mixin default type

        this.mixinNamedParamFacade(api, schema); // Mixin named parameter support

        return function create(session, handle, id, customKey) {
          var _this2 = this;

          var instance = Object.create(api);
          Events.mixin(instance); // Always mixin event-emitter per instance

          Object.defineProperties(instance, {
            session: {
              enumerable: true,
              value: session
            },
            handle: {
              enumerable: true,
              value: handle,
              writable: true
            },
            id: {
              enumerable: true,
              value: id
            },
            type: {
              enumerable: true,
              value: type
            },
            genericType: {
              enumerable: true,
              value: customKey
            }
          });
          var mixinList = this.mixins.get(type) || [];

          if (customKey !== type) {
            this.mixinType(customKey, instance); // Mixin custom types

            mixinList = mixinList.concat(this.mixins.get(customKey) || []);
          }

          mixinList.forEach(function (mixin) {
            if (typeof mixin.init === 'function') {
              mixin.init({
                config: _this2.config,
                api: instance
              });
            }
          });
          return instance;
        }.bind(this);
      }
      /**
      * Function used to generate the methods with the right handlers to the object
      * API that is being generated.
      * @private
      * @param {Object} api The object API that is currently being generated.
      * @param {Object} schema The API definition.
      */

    }, {
      key: "generateDefaultApi",
      value: function generateDefaultApi(api, schema) {
        Object.keys(schema).forEach(function (method) {
          var out = schema[method].Out;
          var outKey = out.length === 1 ? out[0].Name : -1;
          var fnName = toCamelCase(method);

          api[fnName] = function generatedMethod() {
            for (var _len2 = arguments.length, params = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
              params[_key2] = arguments[_key2];
            }

            return this.session.send({
              handle: this.handle,
              method: method,
              params: params,
              outKey: outKey
            });
          };
        });
      }
      /**
      * Function used to add mixin methods to a specified API.
      * @private
      * @param {String} type Used to specify which mixin should be woven in.
      * @param {Object} api The object that will be woven.
      */

    }, {
      key: "mixinType",
      value: function mixinType(type, api) {
        var mixinList = this.mixins.get(type);

        if (mixinList) {
          mixinList.forEach(function (_ref2) {
            var _ref2$extend = _ref2.extend,
                extend = _ref2$extend === void 0 ? {} : _ref2$extend,
                _ref2$override = _ref2.override,
                override = _ref2$override === void 0 ? {} : _ref2$override;
            Object.keys(override).forEach(function (key) {
              if (typeof api[key] === 'function' && typeof override[key] === 'function') {
                var baseFn = api[key];

                api[key] = function wrappedFn() {
                  for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
                    args[_key3] = arguments[_key3];
                  }

                  return override[key].apply(this, [baseFn.bind(this)].concat(args));
                };
              } else {
                throw createEnigmaError(errorCodes.SCHEMA_MIXIN_CANT_OVERRIDE_FUNCTION, "No function to override. Type: ".concat(type, " function: ").concat(key));
              }
            });
            Object.keys(extend).forEach(function (key) {
              // handle overrides
              if (typeof api[key] === 'function' && typeof extend[key] === 'function') {
                throw createEnigmaError(errorCodes.SCHEMA_MIXIN_EXTEND_NOT_ALLOWED, "Extend is not allowed for this mixin. Type: ".concat(type, " function: ").concat(key));
              } else {
                api[key] = extend[key];
              }
            });
          });
        }
      }
      /**
      * Function used to mixin the named parameter facade.
      * @private
      * @param {Object} api The object API that is currently being generated.
      * @param {Object} schema The API definition.
      */

    }, {
      key: "mixinNamedParamFacade",
      value: function mixinNamedParamFacade(api, schema) {
        Object.keys(schema).forEach(function (key) {
          var fnName = toCamelCase(key);
          var base = api[fnName];
          var defaults = schema[key].In.reduce(function (result, item) {
            result[item.Name] = item.DefaultValue;
            return result;
          }, {});

          api[fnName] = function namedParamWrapper() {
            for (var _len4 = arguments.length, params = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
              params[_key4] = arguments[_key4];
            }

            return namedParamFacade.apply(this, [base, defaults].concat(params));
          };
        });
      }
    }]);

    return Schema;
  }();

  function _classCallCheck$4(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

  function _defineProperties$3(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); } }

  function _createClass$3(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$3(Constructor.prototype, protoProps); if (staticProps) _defineProperties$3(Constructor, staticProps); return Constructor; }
  /**
   * Helper class for handling RPC calls
   * @private
   */

  var RPCResolver =
  /*#__PURE__*/
  function () {
    function RPCResolver(id, handle, resolve, reject) {
      _classCallCheck$4(this, RPCResolver);

      Events.mixin(this);
      this.id = id;
      this.handle = handle;
      this.resolve = resolve;
      this.reject = reject;
    }

    _createClass$3(RPCResolver, [{
      key: "resolveWith",
      value: function resolveWith(data) {
        this.resolve(data);
        this.emit('resolved', this.id);
      }
    }, {
      key: "rejectWith",
      value: function rejectWith(err) {
        this.reject(err);
        this.emit('rejected', this.id);
      }
    }]);

    return RPCResolver;
  }();

  function _classCallCheck$5(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

  function _defineProperties$4(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); } }

  function _createClass$4(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$4(Constructor.prototype, protoProps); if (staticProps) _defineProperties$4(Constructor, staticProps); return Constructor; }
  /**
  * This class handles remote procedure calls on a web socket.
  * @private
  */

  var RPC =
  /*#__PURE__*/
  function () {
    /**
    * Create a new RPC instance.
    * @private
    * @param {Object} options The configuration options for this class.
    * @param {Function} options.Promise The promise constructor to use.
    * @param {String} options.url The complete websocket URL used to connect.
    * @param {Function} options.createSocket The function callback to create a WebSocket.
    */
    function RPC(options) {
      _classCallCheck$5(this, RPC);

      Object.assign(this, options);
      Events.mixin(this);
      this.resolvers = {};
      this.requestId = 0;
      this.openedPromise = undefined;
    }
    /**
    * Opens a connection to the configured endpoint.
    * @private
    * @param {Boolean} force - ignores all previous and outstanding open calls if set to true.
    * @returns {Object} A promise instance.
    */


    _createClass$4(RPC, [{
      key: "open",
      value: function open() {
        var _this = this;

        var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

        if (!force && this.openedPromise) {
          return this.openedPromise;
        }

        try {
          this.socket = this.createSocket(this.url);
        } catch (err) {
          return this.Promise.reject(err);
        }

        this.socket.onopen = this.onOpen.bind(this);
        this.socket.onclose = this.onClose.bind(this);
        this.socket.onerror = this.onError.bind(this);
        this.socket.onmessage = this.onMessage.bind(this);
        this.openedPromise = new this.Promise(function (resolve, reject) {
          return _this.registerResolver('opened', null, resolve, reject);
        });
        this.closedPromise = new this.Promise(function (resolve, reject) {
          return _this.registerResolver('closed', null, resolve, reject);
        });
        return this.openedPromise;
      }
      /**
      * Resolves the open promise when a connection is successfully established.
      * @private
      */

    }, {
      key: "onOpen",
      value: function onOpen() {
        var _this2 = this;

        this.resolvers.opened.resolveWith(function () {
          return _this2.closedPromise;
        });
      }
      /**
      * Resolves the close promise when a connection is closed.
      * @private
      * @param {Object} event - The event describing close.
      */

    }, {
      key: "onClose",
      value: function onClose(event) {
        this.emit('closed', event);

        if (this.resolvers && this.resolvers.closed) {
          this.resolvers.closed.resolveWith(event);
        }

        this.rejectAllOutstandingResolvers({
          code: -1,
          message: 'Socket closed'
        });
      }
      /**
      * Closes a connection.
      * @private
      * @param {Number} [code=1000] - The reason code for closing the connection.
      * @param {String} [reason=""] - The human readable string describing why the connection is closed.
      * @returns {Object} Returns a promise instance.
      */

    }, {
      key: "close",
      value: function close() {
        var code = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1000;
        var reason = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';

        if (this.socket) {
          this.socket.close(code, reason);
          this.socket = null;
        }

        return this.closedPromise;
      }
      /**
      * Emits an error event and rejects the open promise if an error is raised on the connection.
      * @private
      * @param {Object} event - The event describing the error.
      */

    }, {
      key: "onError",
      value: function onError(event) {
        if (this.resolvers.opened) {
          this.resolvers.opened.rejectWith(event);
        } else {
          // only emit errors after the initial open promise has been resolved,
          // this makes it possible to catch early websocket errors as well
          // as run-time ones:
          this.emit('socket-error', event);
        }

        this.rejectAllOutstandingResolvers({
          code: -1,
          message: 'Socket error'
        });
      }
      /**
      * Parses the onMessage event on the connection and resolve the promise for the request.
      * @private
      * @param {Object} event - The event describing the message.
      */

    }, {
      key: "onMessage",
      value: function onMessage(event) {
        var data = JSON.parse(event.data);
        var resolver = this.resolvers[data.id] || {};
        this.emit('traffic', 'received', data, resolver.handle);

        if (typeof data.id !== 'undefined') {
          this.emit('message', data);
          this.resolvers[data.id].resolveWith(data);
        } else {
          this.emit(data.params ? 'notification' : 'message', data);
        }
      }
      /**
      * Rejects all outstanding resolvers.
      * @private
      * @param {Object} reason - The reject reason.
      */

    }, {
      key: "rejectAllOutstandingResolvers",
      value: function rejectAllOutstandingResolvers(reason) {
        var _this3 = this;

        Object.keys(this.resolvers).forEach(function (id) {
          if (id === 'opened' || id === 'closed') {
            return; // "opened" and "closed" should not be handled here
          }

          var resolver = _this3.resolvers[id];
          resolver.rejectWith(reason);
        });
      }
      /**
      * Unregisters a resolver.
      * @private
      * @param {Number|String} id - The ID to unregister the resolver with.
      */

    }, {
      key: "unregisterResolver",
      value: function unregisterResolver(id) {
        var resolver = this.resolvers[id];
        resolver.removeAllListeners();
        delete this.resolvers[id];
      }
      /**
      * Registers a resolver.
      * @private
      * @param {Number|String} id - The ID to register the resolver with.
      * @param {Number} handle - The associated handle.
      * @returns {Function} The promise executor function.
      */

    }, {
      key: "registerResolver",
      value: function registerResolver(id, handle, resolve, reject) {
        var _this4 = this;

        var resolver = new RPCResolver(id, handle, resolve, reject);
        this.resolvers[id] = resolver;
        resolver.on('resolved', function (resolvedId) {
          return _this4.unregisterResolver(resolvedId);
        });
        resolver.on('rejected', function (rejectedId) {
          return _this4.unregisterResolver(rejectedId);
        });
      }
      /**
      * Sends data on the socket.
      * @private
      * @param {Object} data - The data to send.
      * @returns {Object} A promise instance.
      */

    }, {
      key: "send",
      value: function send(data) {
        var _this5 = this;

        if (!this.socket || this.socket.readyState !== this.socket.OPEN) {
          var error = createEnigmaError(errorCodes.NOT_CONNECTED, 'Not connected');
          return this.Promise.reject(error);
        }

        if (!data.id) {
          data.id = this.createRequestId();
        }

        data.jsonrpc = '2.0';
        return new this.Promise(function (resolve, reject) {
          _this5.socket.send(JSON.stringify(data));

          _this5.emit('traffic', 'sent', data, data.handle);

          return _this5.registerResolver(data.id, data.handle, resolve, reject);
        });
      }
    }, {
      key: "createRequestId",
      value: function createRequestId() {
        this.requestId += 1;
        return this.requestId;
      }
    }]);

    return RPC;
  }();

  function _classCallCheck$6(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

  function _defineProperties$5(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); } }

  function _createClass$5(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$5(Constructor.prototype, protoProps); if (staticProps) _defineProperties$5(Constructor, staticProps); return Constructor; }
  var ON_ATTACHED_TIMEOUT_MS = 5000;
  var RPC_CLOSE_MANUAL_SUSPEND$1 = 4000;

  var SuspendResume =
  /*#__PURE__*/
  function () {
    /**
    * Creates a new SuspendResume instance.
    * @private
    * @param {Object} options The configuration option for this class.
    * @param {Promise<Object>} options.Promise The promise constructor to use.
    * @param {RPC} options.rpc The RPC instance to use when communicating towards Engine.
    * @param {ApiCache} options.apis The ApiCache instance to use.
    */
    function SuspendResume(options) {
      var _this = this;

      _classCallCheck$6(this, SuspendResume);

      Object.assign(this, options);
      this.isSuspended = false;
      this.rpc.on('traffic', function (dir, data) {
        if (dir === 'sent' && data.method === 'OpenDoc') {
          _this.openDocParams = data.params;
        }
      });
    }
    /**
    * Function used to restore the rpc connection.
    * @private
    * @param {Boolean} onlyIfAttached - if true, the returned promise will resolve
    *                                   only if the session can be re-attached.
    * @returns {Object} Returns a promise instance.
    */


    _createClass$5(SuspendResume, [{
      key: "restoreRpcConnection",
      value: function restoreRpcConnection(onlyIfAttached) {
        var _this2 = this;

        return this.reopen(ON_ATTACHED_TIMEOUT_MS).then(function (sessionState) {
          if (sessionState === 'SESSION_CREATED' && onlyIfAttached) {
            return _this2.Promise.reject(createEnigmaError(errorCodes.SESSION_NOT_ATTACHED, 'Not attached'));
          }

          return _this2.Promise.resolve();
        });
      }
      /**
      * Function used to restore the global API.
      * @private
      * @param {Object} changed - A list where the restored APIs will be added.
      * @returns {Object} Returns a promise instance.
      */

    }, {
      key: "restoreGlobal",
      value: function restoreGlobal(changed) {
        var global = this.apis.getApisByType('Global').pop();
        changed.push(global.api);
        return this.Promise.resolve();
      }
      /**
      * Function used to restore the doc API.
      * @private
      * @param {String} sessionState - The state of the session, attached or created.
      * @param {Array} closed - A list where the closed of APIs APIs will be added.
      * @param {Object} changed - A list where the restored APIs will be added.
      * @returns {Object} Returns a promise instance.
      */

    }, {
      key: "restoreDoc",
      value: function restoreDoc(closed, changed) {
        var _this3 = this;

        var doc = this.apis.getApisByType('Doc').pop();

        if (!doc) {
          return this.Promise.resolve();
        }

        return this.rpc.send({
          method: 'GetActiveDoc',
          handle: -1,
          params: []
        }).then(function (response) {
          if (response.error && _this3.openDocParams) {
            return _this3.rpc.send({
              method: 'OpenDoc',
              handle: -1,
              params: _this3.openDocParams
            });
          }

          return response;
        }).then(function (response) {
          if (response.error) {
            closed.push(doc.api);
            return _this3.Promise.resolve();
          }

          var handle = response.result.qReturn.qHandle;
          doc.api.handle = handle;
          changed.push(doc.api);
          return _this3.Promise.resolve(doc.api);
        });
      }
      /**
      * Function used to restore the APIs on the doc.
      * @private
      * @param {Object} doc - The doc API on which the APIs we want to restore exist.
      * @param {Array} closed - A list where the closed of APIs APIs will be added.
      * @param {Object} changed - A list where the restored APIs will be added.
      * @returns {Object} Returns a promise instance.
      */

    }, {
      key: "restoreDocObjects",
      value: function restoreDocObjects(doc, closed, changed) {
        var _this4 = this;

        var tasks = [];
        var apis = this.apis.getApis().map(function (entry) {
          return entry.api;
        }).filter(function (api) {
          return api.type !== 'Global' && api.type !== 'Doc';
        });

        if (!doc) {
          apis.forEach(function (api) {
            return closed.push(api);
          });
          return this.Promise.resolve();
        }

        apis.forEach(function (api) {
          var method = SuspendResume.buildGetMethodName(api.type);

          if (!method) {
            closed.push(api);
          } else {
            var request = _this4.rpc.send({
              method: method,
              handle: doc.handle,
              params: [api.id]
            }).then(function (response) {
              if (response.error || !response.result.qReturn.qHandle) {
                closed.push(api);
              } else {
                api.handle = response.result.qReturn.qHandle;
                changed.push(api);
              }
            });

            tasks.push(request);
          }
        });
        return this.Promise.all(tasks);
      }
      /**
      * Set the instance as suspended.
      * @private
      * @param {Number} [code=4000] - The reason code for suspending the connection.
      * @param {String} [reason=""] - The human readable string describing
      * why the connection is suspended.
      */

    }, {
      key: "suspend",
      value: function suspend() {
        var code = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : RPC_CLOSE_MANUAL_SUSPEND$1;
        var reason = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
        this.isSuspended = true;
        return this.rpc.close(code, reason);
      }
      /**
      * Resumes a previously suspended RPC connection, and refreshes the API cache.
      *                                APIs unabled to be restored has their 'closed'
      *                                event triggered, otherwise 'changed'.
      * @private
      * @emits API#changed
      * @emits APIfunction@#closed
      * @param {Boolean} onlyIfAttached if true, resume only if the session was re-attached.
      * @returns {Promise<Object>} Eventually resolved if the RPC connection was successfully resumed,
      *                    otherwise rejected.
      */

    }, {
      key: "resume",
      value: function resume(onlyIfAttached) {
        var _this5 = this;

        var changed = [];
        var closed = [];
        return this.restoreRpcConnection(onlyIfAttached).then(function () {
          return _this5.restoreGlobal(changed);
        }).then(function () {
          return _this5.restoreDoc(closed, changed);
        }).then(function (doc) {
          return _this5.restoreDocObjects(doc, closed, changed);
        }).then(function () {
          _this5.isSuspended = false;

          _this5.apis.clear();

          closed.forEach(function (api) {
            api.emit('closed');
            api.removeAllListeners();
          });
          changed.forEach(function (api) {
            _this5.apis.add(api.handle, api);

            if (api.type !== 'Global') {
              api.emit('changed');
            }
          });
        })["catch"](function (err) {
          return _this5.rpc.close().then(function () {
            return _this5.Promise.reject(err);
          });
        });
      }
      /**
      * Reopens the connection and waits for the OnConnected notification.
      * @private
      * @param {Number} timeout - The time to wait for the OnConnected notification.
      * @returns {Object} A promise containing the session state (SESSION_CREATED or SESSION_ATTACHED).
      */

    }, {
      key: "reopen",
      value: function reopen(timeout) {
        var _this6 = this;

        var timer;
        var notificationResolve;
        var notificationReceived = false;
        var notificationPromise = new this.Promise(function (resolve) {
          notificationResolve = resolve;
        });

        var waitForNotification = function waitForNotification() {
          if (!notificationReceived) {
            timer = setTimeout(function () {
              return notificationResolve('SESSION_CREATED');
            }, timeout);
          }

          return notificationPromise;
        };

        var onNotification = function onNotification(data) {
          if (data.method !== 'OnConnected') return;
          clearTimeout(timer);
          notificationResolve(data.params.qSessionState);
          notificationReceived = true;
        };

        this.rpc.on('notification', onNotification);
        return this.rpc.open(true).then(waitForNotification).then(function (state) {
          _this6.rpc.removeListener('notification', onNotification);

          return state;
        })["catch"](function (err) {
          _this6.rpc.removeListener('notification', onNotification);

          return _this6.Promise.reject(err);
        });
      }
      /**
      * Function used to build the get method names for Doc APIs.
      * @private
      * @param {String} type - The API type.
      * @returns {String} Returns the get method name, or undefined if the type cannot be restored.
      */

    }], [{
      key: "buildGetMethodName",
      value: function buildGetMethodName(type) {
        if (type === 'Field' || type === 'Variable') {
          return null;
        }

        if (type === 'GenericVariable') {
          return 'GetVariableById';
        }

        return type.replace('Generic', 'Get');
      }
    }]);

    return SuspendResume;
  }();

  var SUCCESS_KEY = 'qSuccess';
  function deltaRequestInterceptor(session, request) {
    var delta = session.config.protocol.delta && request.outKey !== -1 && request.outKey !== SUCCESS_KEY;

    if (delta) {
      request.delta = delta;
    }

    return request;
  }

  /**
  * Response interceptor for generating APIs. Handles the quirks of engine not
  * returning an error when an object is missing.
  * @private
  * @param {Session} session - The session the intercept is being executed on.
  * @param {Object} request - The JSON-RPC request.
  * @param {Object} response - The response.
  * @returns {Object} - Returns the generated API
  */

  function apiResponseInterceptor(session, request, response) {
    if (response.qHandle && response.qType) {
      return session.getObjectApi({
        handle: response.qHandle,
        type: response.qType,
        id: response.qGenericId,
        genericType: response.qGenericType
      });
    }

    if (response.qHandle === null && response.qType === null) {
      var error = createEnigmaError(errorCodes.OBJECT_NOT_FOUND, 'Object not found');
      return session.config.Promise.reject(error);
    }

    return response;
  }

  var hasOwn = Object.prototype.hasOwnProperty;
  var toStr = Object.prototype.toString;
  var defineProperty = Object.defineProperty;
  var gOPD = Object.getOwnPropertyDescriptor;

  var isArray = function isArray(arr) {
  	if (typeof Array.isArray === 'function') {
  		return Array.isArray(arr);
  	}

  	return toStr.call(arr) === '[object Array]';
  };

  var isPlainObject = function isPlainObject(obj) {
  	if (!obj || toStr.call(obj) !== '[object Object]') {
  		return false;
  	}

  	var hasOwnConstructor = hasOwn.call(obj, 'constructor');
  	var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
  	// Not own constructor property must be Object
  	if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
  		return false;
  	}

  	// Own properties are enumerated firstly, so to speed up,
  	// if last one is own, then all properties are own.
  	var key;
  	for (key in obj) { /**/ }

  	return typeof key === 'undefined' || hasOwn.call(obj, key);
  };

  // If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target
  var setProperty = function setProperty(target, options) {
  	if (defineProperty && options.name === '__proto__') {
  		defineProperty(target, options.name, {
  			enumerable: true,
  			configurable: true,
  			value: options.newValue,
  			writable: true
  		});
  	} else {
  		target[options.name] = options.newValue;
  	}
  };

  // Return undefined instead of __proto__ if '__proto__' is not an own property
  var getProperty = function getProperty(obj, name) {
  	if (name === '__proto__') {
  		if (!hasOwn.call(obj, name)) {
  			return void 0;
  		} else if (gOPD) {
  			// In early versions of node, obj['__proto__'] is buggy when obj has
  			// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
  			return gOPD(obj, name).value;
  		}
  	}

  	return obj[name];
  };

  var extend = function extend() {
  	var options, name, src, copy, copyIsArray, clone;
  	var target = arguments[0];
  	var i = 1;
  	var length = arguments.length;
  	var deep = false;

  	// Handle a deep copy situation
  	if (typeof target === 'boolean') {
  		deep = target;
  		target = arguments[1] || {};
  		// skip the boolean and the target
  		i = 2;
  	}
  	if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
  		target = {};
  	}

  	for (; i < length; ++i) {
  		options = arguments[i];
  		// Only deal with non-null/undefined values
  		if (options != null) {
  			// Extend the base object
  			for (name in options) {
  				src = getProperty(target, name);
  				copy = getProperty(options, name);

  				// Prevent never-ending loop
  				if (target !== copy) {
  					// Recurse if we're merging plain objects or arrays
  					if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
  						if (copyIsArray) {
  							copyIsArray = false;
  							clone = src && isArray(src) ? src : [];
  						} else {
  							clone = src && isPlainObject(src) ? src : {};
  						}

  						// Never move original objects, clone them
  						setProperty(target, { name: name, newValue: extend(deep, clone, copy) });

  					// Don't bring in undefined values
  					} else if (typeof copy !== 'undefined') {
  						setProperty(target, { name: name, newValue: copy });
  					}
  				}
  			}
  		}
  	}

  	// Return the modified object
  	return target;
  };

  function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

  function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

  function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

  function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

  function _typeof$2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$2 = function _typeof(obj) { return typeof obj; }; } else { _typeof$2 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$2(obj); }
  var extend$1 = extend.bind(null, true);
  var JSONPatch = {};
  var isArray$1 = Array.isArray;

  function isObject(v) {
    return v != null && !Array.isArray(v) && _typeof$2(v) === 'object';
  }

  function isUndef(v) {
    return typeof v === 'undefined';
  }

  function isFunction(v) {
    return typeof v === 'function';
  }
  /**
  * Generate an exact duplicate (with no references) of a specific value.
  *
  * @private
  * @param {Object} The value to duplicate
  * @returns {Object} a unique, duplicated value
  */


  function generateValue(val) {
    if (val) {
      return extend$1({}, {
        val: val
      }).val;
    }

    return val;
  }
  /**
  * An additional type checker used to determine if the property is of internal
  * use or not a type that can be translated into JSON (like functions).
  *
  * @private
  * @param {Object} obj The object which has the property to check
  * @param {String} The property name to check
  * @returns {Boolean} Whether the property is deemed special or not
  */


  function isSpecialProperty(obj, key) {
    return isFunction(obj[key]) || key.substring(0, 2) === '$$' || key.substring(0, 1) === '_';
  }
  /**
  * Finds the parent object from a JSON-Pointer ("/foo/bar/baz" = "bar" is "baz" parent),
  * also creates the object structure needed.
  *
  * @private
  * @param {Object} data The root object to traverse through
  * @param {String} The JSON-Pointer string to use when traversing
  * @returns {Object} The parent object
  */


  function getParent(data, str) {
    var seperator = '/';
    var parts = str.substring(1).split(seperator).slice(0, -1);
    var numPart;
    parts.forEach(function (part, i) {
      if (i === parts.length) {
        return;
      }

      numPart = +part;
      var newPart = !isNaN(numPart) ? [] : {};
      data[numPart || part] = isUndef(data[numPart || part]) ? newPart : data[part];
      data = data[numPart || part];
    });
    return data;
  }
  /**
  * Cleans an object of all its properties, unless they're deemed special or
  * cannot be removed by configuration.
  *
  * @private
  * @param {Object} obj The object to clean
  */


  function emptyObject(obj) {
    Object.keys(obj).forEach(function (key) {
      var config = Object.getOwnPropertyDescriptor(obj, key);

      if (config.configurable && !isSpecialProperty(obj, key)) {
        delete obj[key];
      }
    });
  }
  /**
  * Compare an object with another, could be object, array, number, string, bool.
  * @private
  * @param {Object} a The first object to compare
  * @param {Object} a The second object to compare
  * @returns {Boolean} Whether the objects are identical
  */


  function compare(a, b) {
    var isIdentical = true;

    if (isObject(a) && isObject(b)) {
      if (Object.keys(a).length !== Object.keys(b).length) {
        return false;
      }

      Object.keys(a).forEach(function (key) {
        if (!compare(a[key], b[key])) {
          isIdentical = false;
        }
      });
      return isIdentical;
    }

    if (isArray$1(a) && isArray$1(b)) {
      if (a.length !== b.length) {
        return false;
      }

      for (var i = 0, l = a.length; i < l; i += 1) {
        if (!compare(a[i], b[i])) {
          return false;
        }
      }

      return true;
    }

    return a === b;
  }
  /**
  * Generates patches by comparing two arrays.
  *
  * @private
  * @param {Array} oldA The old (original) array, which will be patched
  * @param {Array} newA The new array, which will be used to compare against
  * @returns {Array} An array of patches (if any)
  */


  function patchArray(original, newA, basePath) {
    var patches = [];
    var oldA = original.slice();
    var tmpIdx = -1;

    function findIndex(a, id, idx) {
      if (a[idx] && isUndef(a[idx].qInfo)) {
        return null;
      }

      if (a[idx] && a[idx].qInfo.qId === id) {
        // shortcut if identical
        return idx;
      }

      for (var ii = 0, ll = a.length; ii < ll; ii += 1) {
        if (a[ii] && a[ii].qInfo.qId === id) {
          return ii;
        }
      }

      return -1;
    }

    if (compare(newA, oldA)) {
      // array is unchanged
      return patches;
    }

    if (!isUndef(newA[0]) && isUndef(newA[0].qInfo)) {
      // we cannot create patches without unique identifiers, replace array...
      patches.push({
        op: 'replace',
        path: basePath,
        value: newA
      });
      return patches;
    }

    for (var i = oldA.length - 1; i >= 0; i -= 1) {
      tmpIdx = findIndex(newA, oldA[i].qInfo && oldA[i].qInfo.qId, i);

      if (tmpIdx === -1) {
        patches.push({
          op: 'remove',
          path: "".concat(basePath, "/").concat(i)
        });
        oldA.splice(i, 1);
      } else {
        patches = patches.concat(JSONPatch.generate(oldA[i], newA[tmpIdx], "".concat(basePath, "/").concat(i)));
      }
    }

    for (var _i = 0, l = newA.length; _i < l; _i += 1) {
      tmpIdx = findIndex(oldA, newA[_i].qInfo && newA[_i].qInfo.qId);

      if (tmpIdx === -1) {
        patches.push({
          op: 'add',
          path: "".concat(basePath, "/").concat(_i),
          value: newA[_i]
        });
        oldA.splice(_i, 0, newA[_i]);
      } else if (tmpIdx !== _i) {
        patches.push({
          op: 'move',
          path: "".concat(basePath, "/").concat(_i),
          from: "".concat(basePath, "/").concat(tmpIdx)
        });
        oldA.splice(_i, 0, oldA.splice(tmpIdx, 1)[0]);
      }
    }

    return patches;
  }
  /**
  * Generate an array of JSON-Patch:es following the JSON-Patch Specification Draft.
  *
  * See [specification draft](http://tools.ietf.org/html/draft-ietf-appsawg-json-patch-10)
  *
  * Does NOT currently generate patches for arrays (will replace them)
  * @private
  * @param {Object} original The object to patch to
  * @param {Object} newData The object to patch from
  * @param {String} [basePath] The base path to use when generating the paths for
  *                            the patches (normally not used)
  * @returns {Array} An array of patches
  */


  JSONPatch.generate = function generate(original, newData, basePath) {
    basePath = basePath || '';
    var patches = [];
    Object.keys(newData).forEach(function (key) {
      var val = generateValue(newData[key]);
      var oldVal = original[key];
      var tmpPath = "".concat(basePath, "/").concat(key);

      if (compare(val, oldVal) || isSpecialProperty(newData, key)) {
        return;
      }

      if (isUndef(oldVal)) {
        // property does not previously exist
        patches.push({
          op: 'add',
          path: tmpPath,
          value: val
        });
      } else if (isObject(val) && isObject(oldVal)) {
        // we need to generate sub-patches for this, since it already exist
        patches = patches.concat(JSONPatch.generate(oldVal, val, tmpPath));
      } else if (isArray$1(val) && isArray$1(oldVal)) {
        patches = patches.concat(patchArray(oldVal, val, tmpPath));
      } else {
        // it's a simple property (bool, string, number)
        patches.push({
          op: 'replace',
          path: "".concat(basePath, "/").concat(key),
          value: val
        });
      }
    });
    Object.keys(original).forEach(function (key) {
      if (isUndef(newData[key]) && !isSpecialProperty(original, key)) {
        // this property does not exist anymore
        patches.push({
          op: 'remove',
          path: "".concat(basePath, "/").concat(key)
        });
      }
    });
    return patches;
  };
  /**
  * Apply a list of patches to an object.
  * @private
  * @param {Object} original The object to patch
  * @param {Array} patches The list of patches to apply
  */


  JSONPatch.apply = function apply(original, patches) {
    patches.forEach(function (patch) {
      var parent = getParent(original, patch.path);
      var key = patch.path.split('/').splice(-1)[0];
      var target = key && isNaN(+key) ? parent[key] : parent[+key] || parent;
      var from = patch.from ? patch.from.split('/').splice(-1)[0] : null;

      if (patch.path === '/') {
        parent = null;
        target = original;
      }

      if (patch.op === 'add' || patch.op === 'replace') {
        if (isArray$1(parent)) {
          // trust indexes from patches, so don't replace the index if it's an add
          if (key === '-') {
            key = parent.length;
          }

          parent.splice(+key, patch.op === 'add' ? 0 : 1, patch.value);
        } else if (isArray$1(target) && isArray$1(patch.value)) {
          var _target;

          var newValues = patch.value.slice(); // keep array reference if possible...

          target.length = 0;

          (_target = target).push.apply(_target, _toConsumableArray(newValues));
        } else if (isObject(target) && isObject(patch.value)) {
          // keep object reference if possible...
          emptyObject(target);
          extend$1(target, patch.value);
        } else if (!parent) {
          throw createEnigmaError(errorCodes.PATCH_HAS_NO_PARENT, 'Patchee is not an object we can patch');
        } else {
          // simple value
          parent[key] = patch.value;
        }
      } else if (patch.op === 'move') {
        var oldParent = getParent(original, patch.from);

        if (isArray$1(parent)) {
          parent.splice(+key, 0, oldParent.splice(+from, 1)[0]);
        } else {
          parent[key] = oldParent[from];
          delete oldParent[from];
        }
      } else if (patch.op === 'remove') {
        if (isArray$1(parent)) {
          parent.splice(+key, 1);
        } else {
          delete parent[key];
        }
      }
    });
  };
  /**
  * Deep clone an object.
  * @private
  * @param {Object} obj The object to clone
  * @returns {Object} A new object identical to the `obj`
  */


  JSONPatch.clone = function clone(obj) {
    return extend$1({}, obj);
  };
  /**
  * Creates a JSON-patch.
  * @private
  * @param {String} op The operation of the patch. Available values: "add", "remove", "move"
  * @param {Object} [val] The value to set the `path` to. If `op` is `move`, `val`
  *                       is the "from JSON-path" path
  * @param {String} path The JSON-path for the property to change (e.g. "/qHyperCubeDef/columnOrder")
  * @returns {Object} A patch following the JSON-patch specification
  */


  JSONPatch.createPatch = function createPatch(op, val, path) {
    var patch = {
      op: op.toLowerCase(),
      path: path
    };

    if (patch.op === 'move') {
      patch.from = val;
    } else if (typeof val !== 'undefined') {
      patch.value = val;
    }

    return patch;
  };
  /**
  * Apply the differences of two objects (keeping references if possible).
  * Identical to running `JSONPatch.apply(original, JSONPatch.generate(original, newData));`
  * @private
  * @param {Object} original The object to update/patch
  * @param {Object} newData the object to diff against
  *
  * @example
  * var obj1 = { foo: [1,2,3], bar: { baz: true, qux: 1 } };
  * var obj2 = { foo: [4,5,6], bar: { baz: false } };
  * JSONPatch.updateObject(obj1, obj2);
  * // => { foo: [4,5,6], bar: { baz: false } };
  */


  JSONPatch.updateObject = function updateObject(original, newData) {
    if (!Object.keys(original).length) {
      extend$1(original, newData);
      return;
    }

    JSONPatch.apply(original, JSONPatch.generate(original, newData));
  };

  function _typeof$3(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$3 = function _typeof(obj) { return typeof obj; }; } else { _typeof$3 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$3(obj); }
  var sessions = {};
  /**
  * Function to make sure we release handle caches when they are closed.
  * @private
  * @param {Session} session The session instance to listen on.
  */

  var bindSession = function bindSession(session) {
    if (!sessions[session.id]) {
      var cache = {};
      sessions[session.id] = cache;
      session.on('traffic:received', function (data) {
        return data.close && data.close.forEach(function (handle) {
          return delete cache[handle];
        });
      });
      session.on('closed', function () {
        return delete sessions[session.id];
      });
    }
  };
  /**
  * Simple function that ensures the session events has been bound, and returns
  * either an existing key-value cache or creates one for the specified handle.
  * @private
  * @param {Session} session The session that owns the handle.
  * @param {Number} handle The object handle to retrieve the cache for.
  * @returns {KeyValueCache} The cache instance.
  */


  var getHandleCache = function getHandleCache(session, handle) {
    bindSession(session);
    var cache = sessions[session.id];

    if (!cache[handle]) {
      cache[handle] = new KeyValueCache();
    }

    return cache[handle];
  };
  /**
  * Function used to apply a list of patches and return the patched value.
  * @private
  * @param {Session} session The session.
  * @param {Number} handle The object handle.
  * @param {String} cacheId The cacheId.
  * @param {Array} patches The patches.
  * @returns {Object} Returns the patched value.
  */


  var patchValue = function patchValue(session, handle, cacheId, patches) {
    var cache = getHandleCache(session, handle);
    var entry = cache.get(cacheId);

    if (typeof entry === 'undefined') {
      entry = Array.isArray(patches[0].value) ? [] : {};
    }

    if (patches.length) {
      if (patches[0].path === '/' && _typeof$3(patches[0].value) !== 'object') {
        // 'plain' values on root path is not supported (no object reference),
        // so we simply store the value directly:
        entry = patches[0].value;
      } else {
        JSONPatch.apply(entry, patches);
      }

      cache.set(cacheId, entry);
    }

    return entry;
  };
  /**
  * Process delta interceptor.
  * @private
  * @param {Session} session The session the intercept is being executed on.
  * @param {Object} request The JSON-RPC request.
  * @param {Object} response The response.
  * @returns {Object} Returns the patched response
  */


  function deltaResponseInterceptor(session, request, response) {
    var delta = response.delta,
        result = response.result;

    if (delta) {
      // when delta is on the response data is expected to be an array of patches:
      Object.keys(result).forEach(function (key) {
        if (!Array.isArray(result[key])) {
          throw createEnigmaError(errorCodes.EXPECTED_ARRAY_OF_PATCHES, 'Unexpected RPC response, expected array of patches');
        }

        result[key] = patchValue(session, request.handle, "".concat(request.method, "-").concat(key), result[key]);
      }); // return a cloned response object to avoid patched object references:

      return JSON.parse(JSON.stringify(response));
    }

    return response;
  } // export object reference for testing purposes:

  deltaResponseInterceptor.sessions = sessions;

  /**
  * Process error interceptor.
  * @private
  * @param {Session} session - The session the intercept is being executed on.
  * @param {Object} request - The JSON-RPC request.
  * @param {Object} response - The response.
  * @returns {Object} - Returns the defined error for an error, else the response.
  */
  function errorResponseInterceptor(session, request, response) {
    if (typeof response.error !== 'undefined') {
      var data = response.error;
      var error = new Error(data.message);
      error.code = data.code;
      error.parameter = data.parameter;
      return session.config.Promise.reject(error);
    }

    return response;
  }

  var RETURN_KEY = 'qReturn';
  /**
  * Picks out the result "out" parameter based on the QIX method+schema, with
  * some specific handling for some methods that breaks the predictable protocol.
  * @private
  * @param {Session} session - The session the intercept is being executed on.
  * @param {Object} request - The JSON-RPC request.
  * @param {Object} response - The response.
  * @returns {Object} - Returns the result property on the response
  */

  function outParamResponseInterceptor(session, request, response) {
    if (request.method === 'CreateSessionApp' || request.method === 'CreateSessionAppFromApp') {
      // this method returns multiple out params that we need
      // to normalize before processing the response further:
      response[RETURN_KEY].qGenericId = response.qSessionAppId || response[RETURN_KEY].qGenericId;
    } else if (request.method === 'GetInteract') {
      // this method returns a qReturn value when it should only return
      // meta.outKey:
      delete response[RETURN_KEY];
    }

    if (hasOwnProperty.call(response, RETURN_KEY)) {
      return response[RETURN_KEY];
    }

    if (request.outKey !== -1) {
      return response[request.outKey];
    }

    return response;
  }

  /**
  * Process result interceptor.
  * @private
  * @param {Session} session - The session the intercept is being executed on.
  * @param {Object} request - The JSON-RPC request.
  * @param {Object} response - The response.
  * @returns {Object} - Returns the result property on the response
  */
  function resultResponseInterceptor(session, request, response) {
    return response.result;
  }

  function _toConsumableArray$1(arr) { return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _nonIterableSpread$1(); }

  function _nonIterableSpread$1() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

  function _iterableToArray$1(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

  function _arrayWithoutHoles$1(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

  function _classCallCheck$7(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

  function _defineProperties$6(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); } }

  function _createClass$6(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$6(Constructor.prototype, protoProps); if (staticProps) _defineProperties$6(Constructor, staticProps); return Constructor; }
  /**
   * Interceptors is a concept similar to mixins, but run on a lower level. The interceptor concept
   * can augment either the requests (i.e. before sent to QIX Engine), or the responses (i.e. after
   * QIX Engine has sent a response). The interceptor promises runs in parallel to the regular
   * promises used in enigma.js, which means that it can be really useful when you want to normalize
   * behaviors in your application.
   * @interface Interceptor
   */

  /**
    * @class InterceptorRequest
    * @implements {Interceptor}
    */

  /**
   * @class InterceptorResponse
   * @implements {Interceptor}
   */

  /**
   * This method is invoked when a request is about to be sent to QIX Engine.
   * @function InterceptorRequest#onFulfilled
   * @param {Session} session The session executing the interceptor.
   * @param {Object} request The JSON-RPC request that will be sent.
   */

  /**
   * This method is invoked when a previous interceptor has rejected the
   * promise, use this to handle for example errors before they are sent into mixins.
   * @function InterceptorResponse#onRejected
   * @param {Session} session The session executing the interceptor. You may use .retry() to retry
   * sending it to QIX Engine.
   * @param {Object} request The JSON-RPC request resulting in this error.
   * @param {Object} error Whatever the previous interceptor is rejected with.
   */

  /**
   * This method is invoked when a promise has been successfully resolved,
   * use this to modify the result or reject the promise chain before it is sent
   * to mixins.
   * @function InterceptorResponse#onFulfilled
   * @param {Session} session The session executing the interceptor.
   * @param {Object} request The JSON-RPC request resulting in this response.
   * @param {Object} result Whatever the previous interceptor is resolved with.
   */

  var Intercept =
  /*#__PURE__*/
  function () {
    /**
    * Create a new Intercept instance.
    * @private
    * @param {Object} options The configuration options for this class.
    * @param {Promise<Object>} options.Promise The promise constructor to use.
    * @param {ApiCache} options.apis The ApiCache instance to use.
    * @param {Array<Object>} [options.request] The additional request interceptors to use.
    * @param {Array<Object>} [options.response] The additional response interceptors to use.
    */
    function Intercept(options) {
      _classCallCheck$7(this, Intercept);

      Object.assign(this, options);
      this.request = [{
        onFulfilled: deltaRequestInterceptor
      }].concat(_toConsumableArray$1(this.request || []));
      this.response = [{
        onFulfilled: errorResponseInterceptor
      }, {
        onFulfilled: deltaResponseInterceptor
      }, {
        onFulfilled: resultResponseInterceptor
      }, {
        onFulfilled: outParamResponseInterceptor
      }].concat(_toConsumableArray$1(this.response || []), [{
        onFulfilled: apiResponseInterceptor
      }]);
    }
    /**
    * Execute the request interceptor queue, each interceptor will get the result from
    * the previous interceptor.
    * @private
    * @param {Session} session The session instance to execute against.
    * @param {Promise<Object>} promise The promise to chain on to.
    * @returns {Promise<Object>}
    */


    _createClass$6(Intercept, [{
      key: "executeRequests",
      value: function executeRequests(session, promise) {
        var _this = this;

        return this.request.reduce(function (interception, interceptor) {
          var intercept = interceptor.onFulfilled && interceptor.onFulfilled.bind(_this, session);
          return interception.then(intercept);
        }, promise);
      }
      /**
      * Execute the response interceptor queue, each interceptor will get the result from
      * the previous interceptor.
      * @private
      * @param {Session} session The session instance to execute against.
      * @param {Promise<Object>} promise The promise to chain on to.
      * @param {Object} request The JSONRPC request object for the intercepted response.
      * @returns {Promise<Object>}
      */

    }, {
      key: "executeResponses",
      value: function executeResponses(session, promise, request) {
        var _this2 = this;

        return this.response.reduce(function (interception, interceptor) {
          return interception.then(interceptor.onFulfilled && interceptor.onFulfilled.bind(_this2, session, request), interceptor.onRejected && interceptor.onRejected.bind(_this2, session, request));
        }, promise);
      }
    }]);

    return Intercept;
  }();

  function _typeof$4(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$4 = function _typeof(obj) { return typeof obj; }; } else { _typeof$4 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$4(obj); }

  function _classCallCheck$8(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

  function _defineProperties$7(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); } }

  function _createClass$7(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$7(Constructor.prototype, protoProps); if (staticProps) _defineProperties$7(Constructor, staticProps); return Constructor; }

  function _possibleConstructorReturn$1(self, call) { if (call && (_typeof$4(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized$1(self); }

  function _assertThisInitialized$1(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

  function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }

  function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf$1(object); if (object === null) break; } return object; }

  function _getPrototypeOf$1(o) { _getPrototypeOf$1 = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf$1(o); }

  function _inherits$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf$1(subClass, superClass); }

  function _setPrototypeOf$1(o, p) { _setPrototypeOf$1 = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf$1(o, p); }
  /**
  * API cache for instances of QIX types, e.g. GenericObject.
  * @private
  * @extends KeyValueCache
  */

  var ApiCache =
  /*#__PURE__*/
  function (_KeyValueCache) {
    _inherits$1(ApiCache, _KeyValueCache);

    function ApiCache() {
      _classCallCheck$8(this, ApiCache);

      return _possibleConstructorReturn$1(this, _getPrototypeOf$1(ApiCache).apply(this, arguments));
    }

    _createClass$7(ApiCache, [{
      key: "add",

      /**
      * Adds an API.
      * @private
      * @function ApiCache#add
      * @param {Number} handle - The handle for the API.
      * @param {*} api - The API.
      * @returns {{api: *}} The entry.
      */
      value: function add(handle, api) {
        var _this = this;

        var entry = {
          api: api
        };

        _get(_getPrototypeOf$1(ApiCache.prototype), "add", this).call(this, handle.toString(), entry);

        api.on('closed', function () {
          return _this.remove(handle);
        });
        return entry;
      }
      /**
      * Gets an API.
      * @private
      * @function ApiCache#getApi
      * @param {Number} handle - The handle for the API.
      * @returns {*} The API for the handle.
      */

    }, {
      key: "getApi",
      value: function getApi(handle) {
        var entry = typeof handle !== 'undefined' ? this.get(handle.toString()) : undefined;
        return entry && entry.api;
      }
      /**
      * Gets a list of APIs.
      * @private
      * @function ApiCache#getApis
      * @returns {Array} The list of entries including `handle` and `api` properties for each entry.
      */

    }, {
      key: "getApis",
      value: function getApis() {
        return _get(_getPrototypeOf$1(ApiCache.prototype), "getAll", this).call(this).map(function (entry) {
          return {
            handle: entry.key,
            api: entry.value.api
          };
        });
      }
      /**
      * Gets a list of APIs with a given type.
      * @private
      * @function ApiCache#getApisByType
      * @param {String} type - The type of APIs to get.
      * @returns {Array} The list of entries including `handle` and `api` properties for each entry.
      */

    }, {
      key: "getApisByType",
      value: function getApisByType(type) {
        return this.getApis().filter(function (entry) {
          return entry.api.type === type;
        });
      }
    }]);

    return ApiCache;
  }(KeyValueCache);

  function _classCallCheck$9(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

  function _defineProperties$8(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); } }

  function _createClass$8(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$8(Constructor.prototype, protoProps); if (staticProps) _defineProperties$8(Constructor, staticProps); return Constructor; }
  /**
   * The enigma.js configuration object.
   * @interface Configuration
   * @property {Object} schema Object containing the specification for the API to generate.
   * Corresponds to a specific version of the QIX Engine API.
   * @property {String} url String containing a proper websocker URL to QIX Engine.
   * @property {Function} [createSocket] A function to use when instantiating the WebSocket,
   * mandatory for Node.js.
   * @property {Object} [Promise] ES6-compatible Promise library.
   * @property {Boolean} [suspendOnClose=false] Set to true if the session should be suspended
   * instead of closed when the websocket is closed.
   * @property {Array<Mixin>} [mixins=[]] Mixins to extend/augment the QIX Engine API. Mixins
   * are applied in the array order.
   * @property {Array} [requestInterceptors=[]] Interceptors for augmenting requests before they
   * are sent to QIX Engine. Interceptors are applied in the array order.
   * @property {Array} [responseInterceptors=[]] Interceptors for augmenting responses before they
   * are passed into mixins and end-users. Interceptors are applied in the array order.
   * @property {Object} [protocol={}] An object containing additional JSON-RPC request parameters.
   * @property {Boolean} [protocol.delta=true] Set to false to disable the use of the
   * bandwidth-reducing delta protocol.
   */

  /**
   * Mixin object to extend/augment the QIX Engine API
   * @interface Mixin
   * @property {String|Array<String>} types String or array of strings containing the API-types that
   * will be mixed in.
   * @property {Object} [extend] Object literal containing the methods that will be extended on the
   * specified API.
   * @property {Object} [override] Object literal containing the methods to override existing methods.
   * @property {Function} [init] Init function that, if defined, will run when an API is instantiated.
   * It runs with Promise and API object as parameters
   */

  /**
   * The API for generated APIs depends on the QIX Engine schema you pass into your Configuration,
   * and on what QIX struct the API has.
   * @interface API
   * @property {String} id Contains the unique identifier for this API.
   * @property {String} type Contains the schema class name for this API.
   * @property {String} genericType Corresponds to the qInfo.qType property on the generic object's
   * properties object.
   * @property {Session} session Contains a reference to the session that this API belongs to.
   * @property {Number} handle Contains the handle QIX Engine assigned to the API. Used interally in
   * enigma.js for caches and JSON-RPC requests.
   */

  /**
   * Handle changes on the API. The changed event is triggered whenever enigma.js or QIX Engine has
   * identified potential changes on the underlying properties or hypercubes and you should re-fetch
   * your data.
   * @event API#changed
   * @type {Object}
   */

  /**
   * Handle closed API. The closed event is triggered whenever QIX Engine considers an API closed.
   * It usually means that it no longer exist in the QIX Engine document or session.
   * @event API#closed
   * @type {Object}
   */

  /**
   * Handle JSON-RPC requests/responses for this API. Generally used in debugging purposes.
   * traffic:* will handle all websocket messages, traffic:sent will handle outgoing messages
   * and traffic:received will handle incoming messages.
   * @event API#traffic
   * @type {Object}
   */

  /**
  * Qix service.
  */

  var Qix =
  /*#__PURE__*/
  function () {
    function Qix() {
      _classCallCheck$9(this, Qix);
    }

    _createClass$8(Qix, null, [{
      key: "getSession",

      /**
      * Function used to get a session.
      * @private
      * @param {Configuration} config The configuration object for this session.
      * @returns {Session} Returns a session instance.
      */
      value: function getSession(config) {
        var createSocket = config.createSocket,
            Promise = config.Promise,
            requestInterceptors = config.requestInterceptors,
            responseInterceptors = config.responseInterceptors,
            url = config.url;
        var apis = new ApiCache();
        var intercept = new Intercept({
          apis: apis,
          Promise: Promise,
          request: requestInterceptors,
          response: responseInterceptors
        });
        var rpc = new RPC({
          createSocket: createSocket,
          Promise: Promise,
          url: url
        });
        var suspendResume = new SuspendResume({
          apis: apis,
          Promise: Promise,
          rpc: rpc
        });
        var session = new Session({
          apis: apis,
          config: config,
          intercept: intercept,
          rpc: rpc,
          suspendResume: suspendResume
        });
        return session;
      }
      /**
      * Function used to create a QIX session.
      * @param {Configuration} config The configuration object for the QIX session.
      * @returns {Session} Returns a new QIX session.
      */

    }, {
      key: "create",
      value: function create(config) {
        Qix.configureDefaults(config);
        config.mixins.forEach(function (mixin) {
          config.definition.registerMixin(mixin);
        });
        return Qix.getSession(config);
      }
      /**
      * Function used to configure defaults.
      * @private
      * @param {Configuration} config The configuration object for how to connect
      *                               and retrieve end QIX APIs.
      */

    }, {
      key: "configureDefaults",
      value: function configureDefaults(config) {
        if (!config) {
          throw createEnigmaError(errorCodes.NO_CONFIG_SUPPLIED, 'You need to supply a configuration.');
        } // eslint-disable-next-line no-restricted-globals


        if (!config.Promise && typeof Promise === 'undefined') {
          throw createEnigmaError(errorCodes.PROMISE_REQUIRED, 'Your environment has no Promise implementation. You must provide a Promise implementation in the config.');
        }

        if (typeof config.createSocket !== 'function' && typeof WebSocket === 'function') {
          // eslint-disable-next-line no-undef
          config.createSocket = function (url) {
            return new WebSocket(url);
          };
        }

        if (typeof config.suspendOnClose === 'undefined') {
          config.suspendOnClose = false;
        }

        config.protocol = config.protocol || {};
        config.protocol.delta = typeof config.protocol.delta !== 'undefined' ? config.protocol.delta : true; // eslint-disable-next-line no-restricted-globals

        config.Promise = config.Promise || Promise;
        config.mixins = config.mixins || [];
        config.definition = config.definition || new Schema(config);
      }
    }]);

    return Qix;
  }();

  return Qix;

})));
//# sourceMappingURL=enigma.js.map


/***/ }),
/* 91 */
/***/ (function(module) {

module.exports = JSON.parse("{\"structs\":{\"Field\":{\"GetCardinal\":{\"In\":[],\"Out\":[]},\"GetAndMode\":{\"In\":[],\"Out\":[]},\"SelectValues\":{\"In\":[{\"Name\":\"qFieldValues\",\"DefaultValue\":[{\"qText\":\"\",\"qIsNumeric\":false,\"qNumber\":0}]},{\"Name\":\"qToggleMode\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"Select\":{\"In\":[{\"Name\":\"qMatch\",\"DefaultValue\":\"\"},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qExcludedValuesMode\",\"DefaultValue\":0,\"Optional\":true}],\"Out\":[]},\"ToggleSelect\":{\"In\":[{\"Name\":\"qMatch\",\"DefaultValue\":\"\"},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qExcludedValuesMode\",\"DefaultValue\":0,\"Optional\":true}],\"Out\":[]},\"ClearAllButThis\":{\"In\":[{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"SelectPossible\":{\"In\":[{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"SelectExcluded\":{\"In\":[{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"SelectAll\":{\"In\":[{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"Lock\":{\"In\":[],\"Out\":[]},\"Unlock\":{\"In\":[],\"Out\":[]},\"GetNxProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProperties\"}]},\"SetNxProperties\":{\"In\":[{\"Name\":\"qProperties\",\"DefaultValue\":{\"qOneAndOnlyOne\":false}}],\"Out\":[]},\"SetAndMode\":{\"In\":[{\"Name\":\"qAndMode\",\"DefaultValue\":false}],\"Out\":[]},\"SelectAlternative\":{\"In\":[{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"LowLevelSelect\":{\"In\":[{\"Name\":\"qValues\",\"DefaultValue\":[0]},{\"Name\":\"qToggleMode\",\"DefaultValue\":false},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"Clear\":{\"In\":[],\"Out\":[]}},\"Variable\":{\"GetContent\":{\"In\":[],\"Out\":[{\"Name\":\"qContent\"}]},\"GetRawContent\":{\"In\":[],\"Out\":[]},\"SetContent\":{\"In\":[{\"Name\":\"qContent\",\"DefaultValue\":\"\"},{\"Name\":\"qUpdateMRU\",\"DefaultValue\":false}],\"Out\":[]},\"ForceContent\":{\"In\":[{\"Name\":\"qs\",\"DefaultValue\":\"\"},{\"Name\":\"qd\",\"DefaultValue\":0}],\"Out\":[]},\"GetNxProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProperties\"}]},\"SetNxProperties\":{\"In\":[{\"Name\":\"qProperties\",\"DefaultValue\":{\"qName\":\"\",\"qNumberPresentation\":{\"qType\":0,\"qnDec\":0,\"qUseThou\":0,\"qFmt\":\"\",\"qDec\":\"\",\"qThou\":\"\"},\"qIncludeInBookmark\":false,\"qUsePredefListedValues\":false,\"qPreDefinedList\":[\"\"]}}],\"Out\":[]}},\"GenericObject\":{\"GetLayout\":{\"In\":[],\"Out\":[{\"Name\":\"qLayout\"}]},\"GetListObjectData\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qPages\",\"DefaultValue\":[{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0}]}],\"Out\":[{\"Name\":\"qDataPages\"}]},\"GetHyperCubeData\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qPages\",\"DefaultValue\":[{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0}]}],\"Out\":[{\"Name\":\"qDataPages\"}]},\"GetHyperCubeReducedData\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qPages\",\"DefaultValue\":[{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0}]},{\"Name\":\"qZoomFactor\",\"DefaultValue\":0},{\"Name\":\"qReductionMode\",\"DefaultValue\":0}],\"Out\":[{\"Name\":\"qDataPages\"}]},\"GetHyperCubePivotData\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qPages\",\"DefaultValue\":[{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0}]}],\"Out\":[{\"Name\":\"qDataPages\"}]},\"GetHyperCubeStackData\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qPages\",\"DefaultValue\":[{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0}]},{\"Name\":\"qMaxNbrCells\",\"DefaultValue\":0,\"Optional\":true}],\"Out\":[{\"Name\":\"qDataPages\"}]},\"GetHyperCubeContinuousData\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qOptions\",\"DefaultValue\":{\"qStart\":0,\"qEnd\":0,\"qNbrPoints\":0,\"qMaxNbrTicks\":0,\"qMaxNumberLines\":0}},{\"Name\":\"qReverseSort\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qDataPages\"},{\"Name\":\"qAxisData\"}]},\"GetHyperCubeTreeData\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qNodeOptions\",\"DefaultValue\":{\"qMaxNbrOfNodes\":0,\"qTreeNodes\":[{\"qArea\":{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0},\"qAllValues\":false}],\"qTreeLevels\":{\"qLeft\":0,\"qDepth\":0}},\"Optional\":true}],\"Out\":[{\"Name\":\"qNodes\"}]},\"GetHyperCubeBinnedData\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qPages\",\"DefaultValue\":[{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0}]},{\"Name\":\"qViewport\",\"DefaultValue\":{\"qWidth\":0,\"qHeight\":0,\"qZoomLevel\":0}},{\"Name\":\"qDataRanges\",\"DefaultValue\":[{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0}]},{\"Name\":\"qMaxNbrCells\",\"DefaultValue\":0},{\"Name\":\"qQueryLevel\",\"DefaultValue\":0},{\"Name\":\"qBinningMethod\",\"DefaultValue\":0}],\"Out\":[{\"Name\":\"qDataPages\"}]},\"ApplyPatches\":{\"In\":[{\"Name\":\"qPatches\",\"DefaultValue\":[{\"qOp\":0,\"qPath\":\"\",\"qValue\":\"\"}]},{\"Name\":\"qSoftPatch\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"ClearSoftPatches\":{\"In\":[],\"Out\":[]},\"SetProperties\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qExtendsId\":\"\",\"qMetaDef\":{}}}],\"Out\":[]},\"GetProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProp\"}]},\"GetEffectiveProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProp\"}]},\"SetFullPropertyTree\":{\"In\":[{\"Name\":\"qPropEntry\",\"DefaultValue\":{\"qProperty\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qExtendsId\":\"\",\"qMetaDef\":{}},\"qChildren\":[],\"qEmbeddedSnapshotRef\":null}}],\"Out\":[]},\"GetFullPropertyTree\":{\"In\":[],\"Out\":[{\"Name\":\"qPropEntry\"}]},\"GetInfo\":{\"In\":[],\"Out\":[{\"Name\":\"qInfo\"}]},\"ClearSelections\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qColIndices\",\"DefaultValue\":[0],\"Optional\":true}],\"Out\":[]},\"ExportData\":{\"In\":[{\"Name\":\"qFileType\",\"DefaultValue\":0},{\"Name\":\"qPath\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qFileName\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qExportState\",\"DefaultValue\":0,\"Optional\":true}],\"Out\":[{\"Name\":\"qUrl\"},{\"Name\":\"qWarnings\"}]},\"SelectListObjectValues\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qValues\",\"DefaultValue\":[0]},{\"Name\":\"qToggleMode\",\"DefaultValue\":false},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SelectListObjectPossible\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SelectListObjectExcluded\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SelectListObjectAlternative\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SelectListObjectAll\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SelectListObjectContinuousRange\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRanges\",\"DefaultValue\":[{\"qMin\":0,\"qMax\":0,\"qMinInclEq\":false,\"qMaxInclEq\":false}]},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SearchListObjectFor\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qMatch\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"AbortListObjectSearch\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"}],\"Out\":[]},\"AcceptListObjectSearch\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qToggleMode\",\"DefaultValue\":false},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"ExpandLeft\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRow\",\"DefaultValue\":0},{\"Name\":\"qCol\",\"DefaultValue\":0},{\"Name\":\"qAll\",\"DefaultValue\":false}],\"Out\":[]},\"ExpandTop\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRow\",\"DefaultValue\":0},{\"Name\":\"qCol\",\"DefaultValue\":0},{\"Name\":\"qAll\",\"DefaultValue\":false}],\"Out\":[]},\"CollapseLeft\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRow\",\"DefaultValue\":0},{\"Name\":\"qCol\",\"DefaultValue\":0},{\"Name\":\"qAll\",\"DefaultValue\":false}],\"Out\":[]},\"CollapseTop\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRow\",\"DefaultValue\":0},{\"Name\":\"qCol\",\"DefaultValue\":0},{\"Name\":\"qAll\",\"DefaultValue\":false}],\"Out\":[]},\"DrillUp\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qDimNo\",\"DefaultValue\":0},{\"Name\":\"qNbrSteps\",\"DefaultValue\":0}],\"Out\":[]},\"Lock\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qColIndices\",\"DefaultValue\":[0],\"Optional\":true}],\"Out\":[]},\"Unlock\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qColIndices\",\"DefaultValue\":[0],\"Optional\":true}],\"Out\":[]},\"SelectHyperCubeValues\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qDimNo\",\"DefaultValue\":0},{\"Name\":\"qValues\",\"DefaultValue\":[0]},{\"Name\":\"qToggleMode\",\"DefaultValue\":false}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SelectHyperCubeCells\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRowIndices\",\"DefaultValue\":[0]},{\"Name\":\"qColIndices\",\"DefaultValue\":[0]},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qDeselectOnlyOneSelected\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SelectPivotCells\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qSelections\",\"DefaultValue\":[{\"qType\":0,\"qCol\":0,\"qRow\":0}]},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qDeselectOnlyOneSelected\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"RangeSelectHyperCubeValues\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRanges\",\"DefaultValue\":[{\"qRange\":{\"qMin\":0,\"qMax\":0,\"qMinInclEq\":false,\"qMaxInclEq\":false},\"qMeasureIx\":0}]},{\"Name\":\"qColumnsToSelect\",\"DefaultValue\":[0],\"Optional\":true},{\"Name\":\"qOrMode\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qDeselectOnlyOneSelected\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"MultiRangeSelectHyperCubeValues\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRanges\",\"DefaultValue\":[{\"qRanges\":[{\"qRange\":{\"qMin\":0,\"qMax\":0,\"qMinInclEq\":false,\"qMaxInclEq\":false},\"qMeasureIx\":0}],\"qColumnsToSelect\":[0]}]},{\"Name\":\"qOrMode\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qDeselectOnlyOneSelected\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"MultiRangeSelectTreeDataValues\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRanges\",\"DefaultValue\":[{\"qRanges\":[{\"qRange\":{\"qMin\":0,\"qMax\":0,\"qMinInclEq\":false,\"qMaxInclEq\":false},\"qMeasureIx\":0,\"qDimensionIx\":0}]}]},{\"Name\":\"qOrMode\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qDeselectOnlyOneSelected\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SelectHyperCubeContinuousRange\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRanges\",\"DefaultValue\":[{\"qRange\":{\"qMin\":0,\"qMax\":0,\"qMinInclEq\":false,\"qMaxInclEq\":false},\"qDimIx\":0}]},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"GetChild\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"GetChildInfos\":{\"In\":[],\"Out\":[{\"Name\":\"qInfos\"}]},\"CreateChild\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qExtendsId\":\"\",\"qMetaDef\":{}}},{\"Name\":\"qPropForThis\",\"DefaultValue\":null,\"Optional\":true}],\"Out\":[{\"Name\":\"qInfo\"}]},\"DestroyChild\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"},{\"Name\":\"qPropForThis\",\"DefaultValue\":null,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"DestroyAllChildren\":{\"In\":[{\"Name\":\"qPropForThis\",\"DefaultValue\":null,\"Optional\":true}],\"Out\":[]},\"SetChildArrayOrder\":{\"In\":[{\"Name\":\"qIds\",\"DefaultValue\":[\"\"]}],\"Out\":[]},\"GetLinkedObjects\":{\"In\":[],\"Out\":[{\"Name\":\"qItems\"}]},\"CopyFrom\":{\"In\":[{\"Name\":\"qFromId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"BeginSelections\":{\"In\":[{\"Name\":\"qPaths\",\"DefaultValue\":[\"\"]}],\"Out\":[]},\"EndSelections\":{\"In\":[{\"Name\":\"qAccept\",\"DefaultValue\":false}],\"Out\":[]},\"ResetMadeSelections\":{\"In\":[],\"Out\":[]},\"EmbedSnapshotObject\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"GetSnapshotObject\":{\"In\":[],\"Out\":[]},\"Publish\":{\"In\":[],\"Out\":[]},\"UnPublish\":{\"In\":[],\"Out\":[]},\"Approve\":{\"In\":[],\"Out\":[]},\"UnApprove\":{\"In\":[],\"Out\":[]}},\"GenericDimension\":{\"GetLayout\":{\"In\":[],\"Out\":[{\"Name\":\"qLayout\"}]},\"ApplyPatches\":{\"In\":[{\"Name\":\"qPatches\",\"DefaultValue\":[{\"qOp\":0,\"qPath\":\"\",\"qValue\":\"\"}]}],\"Out\":[]},\"SetProperties\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qDim\":{\"qGrouping\":0,\"qFieldDefs\":[\"\"],\"qFieldLabels\":[\"\"],\"qLabelExpression\":\"\"},\"qMetaDef\":{}}}],\"Out\":[]},\"GetProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProp\"}]},\"GetInfo\":{\"In\":[],\"Out\":[{\"Name\":\"qInfo\"}]},\"GetDimension\":{\"In\":[],\"Out\":[{\"Name\":\"qDim\"}]},\"GetLinkedObjects\":{\"In\":[],\"Out\":[{\"Name\":\"qItems\"}]},\"Publish\":{\"In\":[],\"Out\":[]},\"UnPublish\":{\"In\":[],\"Out\":[]},\"Approve\":{\"In\":[],\"Out\":[]},\"UnApprove\":{\"In\":[],\"Out\":[]}},\"GenericBookmark\":{\"GetFieldValues\":{\"In\":[{\"Name\":\"qField\",\"DefaultValue\":\"\"},{\"Name\":\"qGetExcludedValues\",\"DefaultValue\":false},{\"Name\":\"qDataPage\",\"DefaultValue\":{\"qStartIndex\":0,\"qEndIndex\":0}}],\"Out\":[{\"Name\":\"qFieldValues\"}]},\"GetLayout\":{\"In\":[],\"Out\":[{\"Name\":\"qLayout\"}]},\"ApplyPatches\":{\"In\":[{\"Name\":\"qPatches\",\"DefaultValue\":[{\"qOp\":0,\"qPath\":\"\",\"qValue\":\"\"}]}],\"Out\":[]},\"SetProperties\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qMetaDef\":{}}}],\"Out\":[]},\"GetProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProp\"}]},\"GetInfo\":{\"In\":[],\"Out\":[{\"Name\":\"qInfo\"}]},\"Apply\":{\"In\":[],\"Out\":[{\"Name\":\"qSuccess\"}]},\"Publish\":{\"In\":[],\"Out\":[]},\"UnPublish\":{\"In\":[],\"Out\":[]},\"Approve\":{\"In\":[],\"Out\":[]},\"UnApprove\":{\"In\":[],\"Out\":[]}},\"GenericVariable\":{\"GetLayout\":{\"In\":[],\"Out\":[{\"Name\":\"qLayout\"}]},\"ApplyPatches\":{\"In\":[{\"Name\":\"qPatches\",\"DefaultValue\":[{\"qOp\":0,\"qPath\":\"\",\"qValue\":\"\"}]}],\"Out\":[]},\"SetProperties\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qMetaDef\":{},\"qName\":\"\",\"qComment\":\"\",\"qNumberPresentation\":{\"qType\":0,\"qnDec\":0,\"qUseThou\":0,\"qFmt\":\"\",\"qDec\":\"\",\"qThou\":\"\"},\"qIncludeInBookmark\":false,\"qDefinition\":\"\"}}],\"Out\":[]},\"GetProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProp\"}]},\"GetInfo\":{\"In\":[],\"Out\":[{\"Name\":\"qInfo\"}]},\"SetStringValue\":{\"In\":[{\"Name\":\"qVal\",\"DefaultValue\":\"\"}],\"Out\":[]},\"SetNumValue\":{\"In\":[{\"Name\":\"qVal\",\"DefaultValue\":0}],\"Out\":[]},\"SetDualValue\":{\"In\":[{\"Name\":\"qText\",\"DefaultValue\":\"\"},{\"Name\":\"qNum\",\"DefaultValue\":0}],\"Out\":[]}},\"GenericMeasure\":{\"GetLayout\":{\"In\":[],\"Out\":[{\"Name\":\"qLayout\"}]},\"ApplyPatches\":{\"In\":[{\"Name\":\"qPatches\",\"DefaultValue\":[{\"qOp\":0,\"qPath\":\"\",\"qValue\":\"\"}]}],\"Out\":[]},\"SetProperties\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qMeasure\":{\"qLabel\":\"\",\"qDef\":\"\",\"qGrouping\":0,\"qExpressions\":[\"\"],\"qActiveExpression\":0,\"qLabelExpression\":\"\"},\"qMetaDef\":{}}}],\"Out\":[]},\"GetProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProp\"}]},\"GetInfo\":{\"In\":[],\"Out\":[{\"Name\":\"qInfo\"}]},\"GetMeasure\":{\"In\":[],\"Out\":[{\"Name\":\"qMeasure\"}]},\"GetLinkedObjects\":{\"In\":[],\"Out\":[{\"Name\":\"qItems\"}]},\"Publish\":{\"In\":[],\"Out\":[]},\"UnPublish\":{\"In\":[],\"Out\":[]},\"Approve\":{\"In\":[],\"Out\":[]},\"UnApprove\":{\"In\":[],\"Out\":[]}},\"Doc\":{\"GetField\":{\"In\":[{\"Name\":\"qFieldName\",\"DefaultValue\":\"\"},{\"Name\":\"qStateName\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[]},\"GetFieldDescription\":{\"In\":[{\"Name\":\"qFieldName\",\"DefaultValue\":\"\"}],\"Out\":[]},\"GetVariable\":{\"In\":[{\"Name\":\"qName\",\"DefaultValue\":\"\"}],\"Out\":[]},\"GetLooselyCoupledVector\":{\"In\":[],\"Out\":[{\"Name\":\"qv\"}]},\"SetLooselyCoupledVector\":{\"In\":[{\"Name\":\"qv\",\"DefaultValue\":[0]}],\"Out\":[]},\"Evaluate\":{\"In\":[{\"Name\":\"qExpression\",\"DefaultValue\":\"\"}],\"Out\":[]},\"EvaluateEx\":{\"In\":[{\"Name\":\"qExpression\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qValue\"}]},\"ClearAll\":{\"In\":[{\"Name\":\"qLockedAlso\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qStateName\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[]},\"LockAll\":{\"In\":[{\"Name\":\"qStateName\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[]},\"UnlockAll\":{\"In\":[{\"Name\":\"qStateName\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[]},\"Back\":{\"In\":[],\"Out\":[]},\"Forward\":{\"In\":[],\"Out\":[]},\"CreateVariable\":{\"In\":[{\"Name\":\"qName\",\"DefaultValue\":\"\"}],\"Out\":[]},\"RemoveVariable\":{\"In\":[{\"Name\":\"qName\",\"DefaultValue\":\"\"}],\"Out\":[]},\"GetLocaleInfo\":{\"In\":[],\"Out\":[]},\"GetTablesAndKeys\":{\"In\":[{\"Name\":\"qWindowSize\",\"DefaultValue\":{\"qcx\":0,\"qcy\":0}},{\"Name\":\"qNullSize\",\"DefaultValue\":{\"qcx\":0,\"qcy\":0}},{\"Name\":\"qCellHeight\",\"DefaultValue\":0},{\"Name\":\"qSyntheticMode\",\"DefaultValue\":false},{\"Name\":\"qIncludeSysVars\",\"DefaultValue\":false}],\"Out\":[{\"Name\":\"qtr\"},{\"Name\":\"qk\"}]},\"GetViewDlgSaveInfo\":{\"In\":[],\"Out\":[]},\"SetViewDlgSaveInfo\":{\"In\":[{\"Name\":\"qInfo\",\"DefaultValue\":{\"qPos\":{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0},\"qCtlInfo\":{\"qInternalView\":{\"qTables\":[{\"qPos\":{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0},\"qCaption\":\"\"}],\"qBroomPoints\":[{\"qPos\":{\"qx\":0,\"qy\":0},\"qTable\":\"\",\"qFields\":[\"\"]}],\"qConnectionPoints\":[{\"qPos\":{\"qx\":0,\"qy\":0},\"qFields\":[\"\"]}],\"qZoomFactor\":0},\"qSourceView\":{\"qTables\":[{\"qPos\":{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0},\"qCaption\":\"\"}],\"qBroomPoints\":[{\"qPos\":{\"qx\":0,\"qy\":0},\"qTable\":\"\",\"qFields\":[\"\"]}],\"qConnectionPoints\":[{\"qPos\":{\"qx\":0,\"qy\":0},\"qFields\":[\"\"]}],\"qZoomFactor\":0}},\"qMode\":0}}],\"Out\":[]},\"GetEmptyScript\":{\"In\":[{\"Name\":\"qLocalizedMainSection\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[]},\"DoReload\":{\"In\":[{\"Name\":\"qMode\",\"DefaultValue\":0,\"Optional\":true},{\"Name\":\"qPartial\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qDebug\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"GetScriptBreakpoints\":{\"In\":[],\"Out\":[{\"Name\":\"qBreakpoints\"}]},\"SetScriptBreakpoints\":{\"In\":[{\"Name\":\"qBreakpoints\",\"DefaultValue\":[{\"qbufferName\":\"\",\"qlineIx\":0,\"qEnabled\":false}]}],\"Out\":[]},\"GetScript\":{\"In\":[],\"Out\":[{\"Name\":\"qScript\"}]},\"GetTextMacros\":{\"In\":[],\"Out\":[{\"Name\":\"qMacros\"}]},\"SetFetchLimit\":{\"In\":[{\"Name\":\"qLimit\",\"DefaultValue\":0}],\"Out\":[]},\"DoSave\":{\"In\":[{\"Name\":\"qFileName\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[]},\"GetTableData\":{\"In\":[{\"Name\":\"qOffset\",\"DefaultValue\":0},{\"Name\":\"qRows\",\"DefaultValue\":0},{\"Name\":\"qSyntheticMode\",\"DefaultValue\":false},{\"Name\":\"qTableName\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qData\"}]},\"GetAppLayout\":{\"In\":[],\"Out\":[{\"Name\":\"qLayout\"}]},\"SetAppProperties\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qTitle\":\"\",\"qLastReloadTime\":\"\",\"qMigrationHash\":\"\",\"qSavedInProductVersion\":\"\",\"qThumbnail\":{\"qUrl\":\"\"}}}],\"Out\":[]},\"GetAppProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProp\"}]},\"GetLineage\":{\"In\":[],\"Out\":[{\"Name\":\"qLineage\"}]},\"CreateSessionObject\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qExtendsId\":\"\",\"qMetaDef\":{}}}],\"Out\":[]},\"DestroySessionObject\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"CreateObject\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qExtendsId\":\"\",\"qMetaDef\":{}}}],\"Out\":[{\"Name\":\"qInfo\"}]},\"DestroyObject\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"GetObject\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"GetObjects\":{\"In\":[{\"Name\":\"qOptions\",\"DefaultValue\":{\"qTypes\":[\"\"],\"qIncludeSessionObjects\":false,\"qData\":{}}}],\"Out\":[{\"Name\":\"qList\"}]},\"GetBookmarks\":{\"In\":[{\"Name\":\"qOptions\",\"DefaultValue\":{\"qTypes\":[\"\"],\"qData\":{}}}],\"Out\":[{\"Name\":\"qList\"}]},\"CloneObject\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qCloneId\"}]},\"CreateDraft\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qDraftId\"}]},\"CommitDraft\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"DestroyDraft\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"},{\"Name\":\"qSourceId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"Undo\":{\"In\":[],\"Out\":[{\"Name\":\"qSuccess\"}]},\"Redo\":{\"In\":[],\"Out\":[{\"Name\":\"qSuccess\"}]},\"ClearUndoBuffer\":{\"In\":[],\"Out\":[]},\"CreateDimension\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qDim\":{\"qGrouping\":0,\"qFieldDefs\":[\"\"],\"qFieldLabels\":[\"\"],\"qLabelExpression\":\"\"},\"qMetaDef\":{}}}],\"Out\":[{\"Name\":\"qInfo\"}]},\"DestroyDimension\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"GetDimension\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"CloneDimension\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qCloneId\"}]},\"CreateMeasure\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qMeasure\":{\"qLabel\":\"\",\"qDef\":\"\",\"qGrouping\":0,\"qExpressions\":[\"\"],\"qActiveExpression\":0,\"qLabelExpression\":\"\"},\"qMetaDef\":{}}}],\"Out\":[{\"Name\":\"qInfo\"}]},\"DestroyMeasure\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"GetMeasure\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"CloneMeasure\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qCloneId\"}]},\"CreateSessionVariable\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qMetaDef\":{},\"qName\":\"\",\"qComment\":\"\",\"qNumberPresentation\":{\"qType\":0,\"qnDec\":0,\"qUseThou\":0,\"qFmt\":\"\",\"qDec\":\"\",\"qThou\":\"\"},\"qIncludeInBookmark\":false,\"qDefinition\":\"\"}}],\"Out\":[]},\"DestroySessionVariable\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"CreateVariableEx\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qMetaDef\":{},\"qName\":\"\",\"qComment\":\"\",\"qNumberPresentation\":{\"qType\":0,\"qnDec\":0,\"qUseThou\":0,\"qFmt\":\"\",\"qDec\":\"\",\"qThou\":\"\"},\"qIncludeInBookmark\":false,\"qDefinition\":\"\"}}],\"Out\":[{\"Name\":\"qInfo\"}]},\"DestroyVariableById\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"DestroyVariableByName\":{\"In\":[{\"Name\":\"qName\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"GetVariableById\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"GetVariableByName\":{\"In\":[{\"Name\":\"qName\",\"DefaultValue\":\"\"}],\"Out\":[]},\"MigrateVariables\":{\"In\":[],\"Out\":[]},\"MigrateDerivedFields\":{\"In\":[],\"Out\":[]},\"CheckExpression\":{\"In\":[{\"Name\":\"qExpr\",\"DefaultValue\":\"\"},{\"Name\":\"qLabels\",\"DefaultValue\":[\"\"],\"Optional\":true}],\"Out\":[{\"Name\":\"qErrorMsg\"},{\"Name\":\"qBadFieldNames\"},{\"Name\":\"qDangerousFieldNames\"}]},\"CheckNumberOrExpression\":{\"In\":[{\"Name\":\"qExpr\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qErrorMsg\"},{\"Name\":\"qBadFieldNames\"}]},\"AddAlternateState\":{\"In\":[{\"Name\":\"qStateName\",\"DefaultValue\":\"\"}],\"Out\":[]},\"RemoveAlternateState\":{\"In\":[{\"Name\":\"qStateName\",\"DefaultValue\":\"\"}],\"Out\":[]},\"CreateBookmark\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qMetaDef\":{}}}],\"Out\":[{\"Name\":\"qInfo\"}]},\"DestroyBookmark\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"GetBookmark\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"ApplyBookmark\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"CloneBookmark\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qCloneId\"}]},\"AddFieldFromExpression\":{\"In\":[{\"Name\":\"qName\",\"DefaultValue\":\"\"},{\"Name\":\"qExpr\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"GetFieldOnTheFlyByName\":{\"In\":[{\"Name\":\"qReadableName\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qName\"}]},\"GetAllInfos\":{\"In\":[],\"Out\":[{\"Name\":\"qInfos\"}]},\"Resume\":{\"In\":[],\"Out\":[]},\"AbortModal\":{\"In\":[{\"Name\":\"qAccept\",\"DefaultValue\":false}],\"Out\":[]},\"Publish\":{\"In\":[{\"Name\":\"qStreamId\",\"DefaultValue\":\"\"},{\"Name\":\"qName\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[]},\"UnPublish\":{\"In\":[],\"Out\":[]},\"GetMatchingFields\":{\"In\":[{\"Name\":\"qTags\",\"DefaultValue\":[\"\"]},{\"Name\":\"qMatchingFieldMode\",\"DefaultValue\":0,\"Optional\":true}],\"Out\":[{\"Name\":\"qFieldNames\"}]},\"FindMatchingFields\":{\"In\":[{\"Name\":\"qFieldName\",\"DefaultValue\":\"\"},{\"Name\":\"qTags\",\"DefaultValue\":[\"\"]}],\"Out\":[{\"Name\":\"qFieldNames\"}]},\"Scramble\":{\"In\":[{\"Name\":\"qFieldName\",\"DefaultValue\":\"\"}],\"Out\":[]},\"SaveObjects\":{\"In\":[],\"Out\":[]},\"GetAssociationScores\":{\"In\":[{\"Name\":\"qTable1\",\"DefaultValue\":\"\"},{\"Name\":\"qTable2\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qScore\"}]},\"GetMediaList\":{\"In\":[],\"Out\":[{\"Name\":\"qList\"}]},\"GetContentLibraries\":{\"In\":[],\"Out\":[{\"Name\":\"qList\"}]},\"GetLibraryContent\":{\"In\":[{\"Name\":\"qName\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qList\"}]},\"DoReloadEx\":{\"In\":[{\"Name\":\"qParams\",\"DefaultValue\":{\"qMode\":0,\"qPartial\":false,\"qDebug\":false},\"Optional\":true}],\"Out\":[{\"Name\":\"qResult\"}]},\"BackCount\":{\"In\":[],\"Out\":[]},\"ForwardCount\":{\"In\":[],\"Out\":[]},\"ExportReducedData\":{\"In\":[{\"Name\":\"qOptions\",\"DefaultValue\":{\"qBookmarkId\":\"\",\"qExpires\":0},\"Optional\":true}],\"Out\":[{\"Name\":\"qDownloadInfo\"}]},\"SetScript\":{\"In\":[{\"Name\":\"qScript\",\"DefaultValue\":\"\"}],\"Out\":[]},\"CheckScriptSyntax\":{\"In\":[],\"Out\":[{\"Name\":\"qErrors\"}]},\"GetFavoriteVariables\":{\"In\":[],\"Out\":[{\"Name\":\"qNames\"}]},\"SetFavoriteVariables\":{\"In\":[{\"Name\":\"qNames\",\"DefaultValue\":[\"\"]}],\"Out\":[]},\"GetIncludeFileContent\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qContent\"}]},\"CreateConnection\":{\"In\":[{\"Name\":\"qConnection\",\"DefaultValue\":{\"qId\":\"\",\"qName\":\"\",\"qConnectionString\":\"\",\"qType\":\"\",\"qUserName\":\"\",\"qPassword\":\"\",\"qModifiedDate\":\"\",\"qMeta\":{\"qName\":\"\"},\"qLogOn\":0}}],\"Out\":[{\"Name\":\"qConnectionId\"}]},\"ModifyConnection\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qConnection\",\"DefaultValue\":{\"qId\":\"\",\"qName\":\"\",\"qConnectionString\":\"\",\"qType\":\"\",\"qUserName\":\"\",\"qPassword\":\"\",\"qModifiedDate\":\"\",\"qMeta\":{\"qName\":\"\"},\"qLogOn\":0}},{\"Name\":\"qOverrideCredentials\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"DeleteConnection\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"GetConnection\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qConnection\"}]},\"GetConnections\":{\"In\":[],\"Out\":[{\"Name\":\"qConnections\"}]},\"GetDatabaseInfo\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qInfo\"}]},\"GetDatabases\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qDatabases\"}]},\"GetDatabaseOwners\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qDatabase\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[{\"Name\":\"qOwners\"}]},\"GetDatabaseTables\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qDatabase\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qOwner\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[{\"Name\":\"qTables\"}]},\"GetDatabaseTableFields\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qDatabase\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qOwner\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qTable\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qFields\"}]},\"GetDatabaseTablePreview\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qDatabase\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qOwner\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qTable\",\"DefaultValue\":\"\"},{\"Name\":\"qConditions\",\"DefaultValue\":{\"qType\":0,\"qWherePredicate\":\"\"},\"Optional\":true}],\"Out\":[{\"Name\":\"qPreview\"},{\"Name\":\"qRowCount\"}]},\"GetFolderItemsForConnection\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qRelativePath\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[{\"Name\":\"qFolderItems\"}]},\"GuessFileType\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qRelativePath\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[{\"Name\":\"qDataFormat\"}]},\"GetFileTables\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qRelativePath\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qDataFormat\",\"DefaultValue\":{\"qType\":0,\"qLabel\":\"\",\"qQuote\":\"\",\"qComment\":\"\",\"qDelimiter\":{\"qName\":\"\",\"qScriptCode\":\"\",\"qNumber\":0,\"qIsMultiple\":false},\"qCodePage\":0,\"qHeaderSize\":0,\"qRecordSize\":0,\"qTabSize\":0,\"qIgnoreEOF\":false,\"qFixedWidthDelimiters\":\"\"}}],\"Out\":[{\"Name\":\"qTables\"}]},\"GetFileTableFields\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qRelativePath\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qDataFormat\",\"DefaultValue\":{\"qType\":0,\"qLabel\":\"\",\"qQuote\":\"\",\"qComment\":\"\",\"qDelimiter\":{\"qName\":\"\",\"qScriptCode\":\"\",\"qNumber\":0,\"qIsMultiple\":false},\"qCodePage\":0,\"qHeaderSize\":0,\"qRecordSize\":0,\"qTabSize\":0,\"qIgnoreEOF\":false,\"qFixedWidthDelimiters\":\"\"}},{\"Name\":\"qTable\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qFields\"},{\"Name\":\"qFormatSpec\"}]},\"GetFileTablePreview\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qRelativePath\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qDataFormat\",\"DefaultValue\":{\"qType\":0,\"qLabel\":\"\",\"qQuote\":\"\",\"qComment\":\"\",\"qDelimiter\":{\"qName\":\"\",\"qScriptCode\":\"\",\"qNumber\":0,\"qIsMultiple\":false},\"qCodePage\":0,\"qHeaderSize\":0,\"qRecordSize\":0,\"qTabSize\":0,\"qIgnoreEOF\":false,\"qFixedWidthDelimiters\":\"\"}},{\"Name\":\"qTable\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qPreview\"},{\"Name\":\"qFormatSpec\"}]},\"GetFileTablesEx\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qRelativePath\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qDataFormat\",\"DefaultValue\":{\"qType\":0,\"qLabel\":\"\",\"qQuote\":\"\",\"qComment\":\"\",\"qDelimiter\":{\"qName\":\"\",\"qScriptCode\":\"\",\"qNumber\":0,\"qIsMultiple\":false},\"qCodePage\":0,\"qHeaderSize\":0,\"qRecordSize\":0,\"qTabSize\":0,\"qIgnoreEOF\":false,\"qFixedWidthDelimiters\":\"\"}}],\"Out\":[{\"Name\":\"qTables\"}]},\"SendGenericCommandToCustomConnector\":{\"In\":[{\"Name\":\"qProvider\",\"DefaultValue\":\"\"},{\"Name\":\"qCommand\",\"DefaultValue\":\"\"},{\"Name\":\"qMethod\",\"DefaultValue\":\"\"},{\"Name\":\"qParameters\",\"DefaultValue\":[\"\"]},{\"Name\":\"qAppendConnection\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qResult\"}]},\"SearchSuggest\":{\"In\":[{\"Name\":\"qOptions\",\"DefaultValue\":{\"qSearchFields\":[\"\"],\"qContext\":0,\"qCharEncoding\":0,\"qAttributes\":[\"\"]}},{\"Name\":\"qTerms\",\"DefaultValue\":[\"\"]}],\"Out\":[{\"Name\":\"qResult\"}]},\"SearchAssociations\":{\"In\":[{\"Name\":\"qOptions\",\"DefaultValue\":{\"qSearchFields\":[\"\"],\"qContext\":0,\"qCharEncoding\":0,\"qAttributes\":[\"\"]}},{\"Name\":\"qTerms\",\"DefaultValue\":[\"\"]},{\"Name\":\"qPage\",\"DefaultValue\":{\"qOffset\":0,\"qCount\":0,\"qMaxNbrFieldMatches\":0,\"qGroupOptions\":[{\"qGroupType\":0,\"qOffset\":0,\"qCount\":0}],\"qGroupItemOptions\":[{\"qGroupItemType\":0,\"qOffset\":0,\"qCount\":0}]}}],\"Out\":[{\"Name\":\"qResults\"}]},\"SelectAssociations\":{\"In\":[{\"Name\":\"qOptions\",\"DefaultValue\":{\"qSearchFields\":[\"\"],\"qContext\":0,\"qCharEncoding\":0,\"qAttributes\":[\"\"]}},{\"Name\":\"qTerms\",\"DefaultValue\":[\"\"]},{\"Name\":\"qMatchIx\",\"DefaultValue\":0},{\"Name\":\"qSoftLock\",\"DefaultValue\":null,\"Optional\":true}],\"Out\":[]},\"SearchResults\":{\"In\":[{\"Name\":\"qOptions\",\"DefaultValue\":{\"qSearchFields\":[\"\"],\"qContext\":0,\"qCharEncoding\":0,\"qAttributes\":[\"\"]}},{\"Name\":\"qTerms\",\"DefaultValue\":[\"\"]},{\"Name\":\"qPage\",\"DefaultValue\":{\"qOffset\":0,\"qCount\":0,\"qMaxNbrFieldMatches\":0,\"qGroupOptions\":[{\"qGroupType\":0,\"qOffset\":0,\"qCount\":0}],\"qGroupItemOptions\":[{\"qGroupItemType\":0,\"qOffset\":0,\"qCount\":0}]}}],\"Out\":[{\"Name\":\"qResult\"}]},\"SearchObjects\":{\"In\":[{\"Name\":\"qOptions\",\"DefaultValue\":{\"qAttributes\":[\"\"],\"qCharEncoding\":0}},{\"Name\":\"qTerms\",\"DefaultValue\":[\"\"]},{\"Name\":\"qPage\",\"DefaultValue\":{\"qOffset\":0,\"qCount\":0,\"qMaxNbrFieldMatches\":0,\"qGroupOptions\":[{\"qGroupType\":0,\"qOffset\":0,\"qCount\":0}],\"qGroupItemOptions\":[{\"qGroupItemType\":0,\"qOffset\":0,\"qCount\":0}]}}],\"Out\":[{\"Name\":\"qResult\"}]},\"GetScriptEx\":{\"In\":[],\"Out\":[{\"Name\":\"qScript\"}]}},\"Global\":{\"AbortRequest\":{\"In\":[{\"Name\":\"qRequestId\",\"DefaultValue\":0}],\"Out\":[]},\"AbortAll\":{\"In\":[],\"Out\":[]},\"GetProgress\":{\"In\":[{\"Name\":\"qRequestId\",\"DefaultValue\":0}],\"Out\":[{\"Name\":\"qProgressData\"}]},\"QvVersion\":{\"In\":[],\"Out\":[]},\"OSVersion\":{\"In\":[],\"Out\":[]},\"OSName\":{\"In\":[],\"Out\":[]},\"QTProduct\":{\"In\":[],\"Out\":[]},\"GetDocList\":{\"In\":[],\"Out\":[{\"Name\":\"qDocList\"}]},\"GetInteract\":{\"In\":[{\"Name\":\"qRequestId\",\"DefaultValue\":0}],\"Out\":[{\"Name\":\"qDef\"}]},\"InteractDone\":{\"In\":[{\"Name\":\"qRequestId\",\"DefaultValue\":0},{\"Name\":\"qDef\",\"DefaultValue\":{\"qType\":0,\"qTitle\":\"\",\"qMsg\":\"\",\"qButtons\":0,\"qLine\":\"\",\"qOldLineNr\":0,\"qNewLineNr\":0,\"qPath\":\"\",\"qHidden\":false,\"qResult\":0,\"qInput\":\"\"}}],\"Out\":[]},\"GetAuthenticatedUser\":{\"In\":[],\"Out\":[]},\"CreateDocEx\":{\"In\":[{\"Name\":\"qDocName\",\"DefaultValue\":\"\"},{\"Name\":\"qUserName\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qPassword\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qSerial\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qLocalizedScriptMainSection\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[{\"Name\":\"qDocId\"}]},\"GetActiveDoc\":{\"In\":[],\"Out\":[]},\"AllowCreateApp\":{\"In\":[],\"Out\":[]},\"CreateApp\":{\"In\":[{\"Name\":\"qAppName\",\"DefaultValue\":\"\"},{\"Name\":\"qLocalizedScriptMainSection\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"},{\"Name\":\"qAppId\"}]},\"DeleteApp\":{\"In\":[{\"Name\":\"qAppId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"IsDesktopMode\":{\"In\":[],\"Out\":[]},\"GetConfiguration\":{\"In\":[],\"Out\":[{\"Name\":\"qConfig\"}]},\"CancelRequest\":{\"In\":[{\"Name\":\"qRequestId\",\"DefaultValue\":0}],\"Out\":[]},\"ShutdownProcess\":{\"In\":[],\"Out\":[]},\"ReloadExtensionList\":{\"In\":[],\"Out\":[]},\"ReplaceAppFromID\":{\"In\":[{\"Name\":\"qTargetAppId\",\"DefaultValue\":\"\"},{\"Name\":\"qSrcAppID\",\"DefaultValue\":\"\"},{\"Name\":\"qIds\",\"DefaultValue\":[\"\"]}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"ReplaceAppFromPath\":{\"In\":[{\"Name\":\"qTargetAppId\",\"DefaultValue\":\"\"},{\"Name\":\"qSrcPath\",\"DefaultValue\":\"\"},{\"Name\":\"qIds\",\"DefaultValue\":[\"\"]},{\"Name\":\"qNoData\",\"DefaultValue\":false}],\"Out\":[]},\"CopyApp\":{\"In\":[{\"Name\":\"qTargetAppId\",\"DefaultValue\":\"\"},{\"Name\":\"qSrcAppId\",\"DefaultValue\":\"\"},{\"Name\":\"qIds\",\"DefaultValue\":[\"\"]}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"ImportApp\":{\"In\":[{\"Name\":\"qAppId\",\"DefaultValue\":\"\"},{\"Name\":\"qSrcPath\",\"DefaultValue\":\"\"},{\"Name\":\"qIds\",\"DefaultValue\":[\"\"]}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"ImportAppEx\":{\"In\":[{\"Name\":\"qAppId\",\"DefaultValue\":\"\"},{\"Name\":\"qSrcPath\",\"DefaultValue\":\"\"},{\"Name\":\"qIds\",\"DefaultValue\":[\"\"]},{\"Name\":\"qExcludeConnections\",\"DefaultValue\":false}],\"Out\":[]},\"ExportApp\":{\"In\":[{\"Name\":\"qTargetPath\",\"DefaultValue\":\"\"},{\"Name\":\"qSrcAppId\",\"DefaultValue\":\"\"},{\"Name\":\"qIds\",\"DefaultValue\":[\"\"]},{\"Name\":\"qNoData\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"PublishApp\":{\"In\":[{\"Name\":\"qAppId\",\"DefaultValue\":\"\"},{\"Name\":\"qName\",\"DefaultValue\":\"\"},{\"Name\":\"qStreamId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"IsPersonalMode\":{\"In\":[],\"Out\":[]},\"GetUniqueID\":{\"In\":[],\"Out\":[{\"Name\":\"qUniqueID\"}]},\"OpenDoc\":{\"In\":[{\"Name\":\"qDocName\",\"DefaultValue\":\"\"},{\"Name\":\"qUserName\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qPassword\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qSerial\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qNoData\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"CreateSessionApp\":{\"In\":[],\"Out\":[{\"Name\":\"qSessionAppId\"}]},\"CreateSessionAppFromApp\":{\"In\":[{\"Name\":\"qSrcAppId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSessionAppId\"}]},\"ProductVersion\":{\"In\":[],\"Out\":[]},\"GetAppEntry\":{\"In\":[{\"Name\":\"qAppID\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qEntry\"}]},\"ConfigureReload\":{\"In\":[{\"Name\":\"qCancelOnScriptError\",\"DefaultValue\":false},{\"Name\":\"qUseErrorData\",\"DefaultValue\":false},{\"Name\":\"qInteractOnError\",\"DefaultValue\":false}],\"Out\":[]},\"CancelReload\":{\"In\":[],\"Out\":[]},\"GetBNF\":{\"In\":[{\"Name\":\"qBnfType\",\"DefaultValue\":0}],\"Out\":[{\"Name\":\"qBnfDefs\"}]},\"GetFunctions\":{\"In\":[{\"Name\":\"qGroup\",\"DefaultValue\":0,\"Optional\":true}],\"Out\":[{\"Name\":\"qFunctions\"}]},\"GetOdbcDsns\":{\"In\":[],\"Out\":[{\"Name\":\"qOdbcDsns\"}]},\"GetOleDbProviders\":{\"In\":[],\"Out\":[{\"Name\":\"qOleDbProviders\"}]},\"GetDatabasesFromConnectionString\":{\"In\":[{\"Name\":\"qConnection\",\"DefaultValue\":{\"qId\":\"\",\"qName\":\"\",\"qConnectionString\":\"\",\"qType\":\"\",\"qUserName\":\"\",\"qPassword\":\"\",\"qModifiedDate\":\"\",\"qMeta\":{\"qName\":\"\"},\"qLogOn\":0}}],\"Out\":[{\"Name\":\"qDatabases\"}]},\"IsValidConnectionString\":{\"In\":[{\"Name\":\"qConnection\",\"DefaultValue\":{\"qId\":\"\",\"qName\":\"\",\"qConnectionString\":\"\",\"qType\":\"\",\"qUserName\":\"\",\"qPassword\":\"\",\"qModifiedDate\":\"\",\"qMeta\":{\"qName\":\"\"},\"qLogOn\":0}}],\"Out\":[]},\"GetDefaultAppFolder\":{\"In\":[],\"Out\":[{\"Name\":\"qPath\"}]},\"GetMyDocumentsFolder\":{\"In\":[],\"Out\":[{\"Name\":\"qFolder\"}]},\"GetLogicalDriveStrings\":{\"In\":[],\"Out\":[{\"Name\":\"qDrives\"}]},\"GetFolderItemsForPath\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qFolderItems\"}]},\"GetSupportedCodePages\":{\"In\":[],\"Out\":[{\"Name\":\"qCodePages\"}]},\"GetCustomConnectors\":{\"In\":[{\"Name\":\"qReloadList\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qConnectors\"}]},\"GetStreamList\":{\"In\":[],\"Out\":[{\"Name\":\"qStreamList\"}]},\"EngineVersion\":{\"In\":[],\"Out\":[{\"Name\":\"qVersion\"}]},\"GetBaseBNF\":{\"In\":[{\"Name\":\"qBnfType\",\"DefaultValue\":0}],\"Out\":[{\"Name\":\"qBnfDefs\"},{\"Name\":\"qBnfHash\"}]},\"GetBaseBNFHash\":{\"In\":[{\"Name\":\"qBnfType\",\"DefaultValue\":0}],\"Out\":[{\"Name\":\"qBnfHash\"}]},\"GetBaseBNFString\":{\"In\":[{\"Name\":\"qBnfType\",\"DefaultValue\":0}],\"Out\":[{\"Name\":\"qBnfStr\"},{\"Name\":\"qBnfHash\"}]}}},\"enums\":{\"LocalizedMessageCode\":{\"LOCMSG_SCRIPTEDITOR_EMPTY_MESSAGE\":0,\"LOCMSG_SCRIPTEDITOR_PROGRESS_SAVING_STARTED\":1,\"LOCMSG_SCRIPTEDITOR_PROGRESS_BYTES_LEFT\":2,\"LOCMSG_SCRIPTEDITOR_PROGRESS_STORING_TABLES\":3,\"LOCMSG_SCRIPTEDITOR_PROGRESS_QVD_ROWS_SO_FAR\":4,\"LOCMSG_SCRIPTEDITOR_PROGRESS_CONNECTED\":5,\"LOCMSG_SCRIPTEDITOR_PROGRESS_CONNECTING_TO\":6,\"LOCMSG_SCRIPTEDITOR_PROGRESS_CONNECT_FAILED\":7,\"LOCMSG_SCRIPTEDITOR_PROGRESS_QVD_ROWISH\":8,\"LOCMSG_SCRIPTEDITOR_PROGRESS_QVD_COLUMNAR\":9,\"LOCMSG_SCRIPTEDITOR_ERROR\":10,\"LOCMSG_SCRIPTEDITOR_DONE\":11,\"LOCMSG_SCRIPTEDITOR_LOAD_EXTERNAL_DATA\":12,\"LOCMSG_SCRIPTEDITOR_PROGRESS_OLD_QVD_ISLOADING\":13,\"LOCMSG_SCRIPTEDITOR_PROGRESS_QVC_LOADING\":14,\"LOCMSG_SCRIPTEDITOR_PROGRESS_QVD_BUFFERED\":15,\"LOCMSG_SCRIPTEDITOR_PROGRESS_QVC_PREPARING\":16,\"LOCMSG_SCRIPTEDITOR_PROGRESS_QVC_APPENDING\":17,\"LOCMSG_SCRIPTEDITOR_REMOVE_SYNTHETIC\":18,\"LOCMSG_SCRIPTEDITOR_PENDING_LINKEDTABLE_FETCHING\":19,\"LOCMSG_SCRIPTEDITOR_RELOAD\":20,\"LOCMSG_SCRIPTEDITOR_LINES_FETCHED\":21,\"LOCMSG_SCRIPTEDITOR_SEARCHINDEX_START\":22,\"LOCMSG_SCRIPTEDITOR_SEARCHINDEX_FIELD\":23,\"LOCMSG_SCRIPTEDITOR_SEARCHINDEX_SUCCESS\":24,\"LOCMSG_SCRIPTEDITOR_SEARCHINDEX_FAILURE\":25,\"LOCMSG_SCRIPTEDITOR_SEARCHINDEX_STARTABORT\":26,\"LOCMSG_SCRIPTEDITOR_SEARCHINDEX_ENDABORT\":27,\"LOCMSG_SCRIPTEDITOR_SEARCHINDEX_TIMEOUT\":28,\"LOCMSG_SCRIPTEDITOR_SEARCHINDEX_OUTOFMEMORY\":29},\"LocalizedErrorCode\":{\"LOCERR_INTERNAL_ERROR\":-128,\"LOCERR_GENERIC_UNKNOWN\":-1,\"LOCERR_GENERIC_OK\":0,\"LOCERR_GENERIC_NOT_SET\":1,\"LOCERR_GENERIC_NOT_FOUND\":2,\"LOCERR_GENERIC_ALREADY_EXISTS\":3,\"LOCERR_GENERIC_INVALID_PATH\":4,\"LOCERR_GENERIC_ACCESS_DENIED\":5,\"LOCERR_GENERIC_OUT_OF_MEMORY\":6,\"LOCERR_GENERIC_NOT_INITIALIZED\":7,\"LOCERR_GENERIC_INVALID_PARAMETERS\":8,\"LOCERR_GENERIC_EMPTY_PARAMETERS\":9,\"LOCERR_GENERIC_INTERNAL_ERROR\":10,\"LOCERR_GENERIC_CORRUPT_DATA\":11,\"LOCERR_GENERIC_MEMORY_INCONSISTENCY\":12,\"LOCERR_GENERIC_INVISIBLE_OWNER_ABORT\":13,\"LOCERR_GENERIC_PROHIBIT_VALIDATE\":14,\"LOCERR_GENERIC_ABORTED\":15,\"LOCERR_GENERIC_CONNECTION_LOST\":16,\"LOCERR_GENERIC_UNSUPPORTED_IN_PRODUCT_VERSION\":17,\"LOCERR_GENERIC_REST_CONNECTION_FAILURE\":18,\"LOCERR_GENERIC_MEMORY_LIMIT_REACHED\":19,\"LOCERR_HTTP_400\":400,\"LOCERR_HTTP_401\":401,\"LOCERR_HTTP_402\":402,\"LOCERR_HTTP_403\":403,\"LOCERR_HTTP_404\":404,\"LOCERR_HTTP_405\":405,\"LOCERR_HTTP_406\":406,\"LOCERR_HTTP_407\":407,\"LOCERR_HTTP_408\":408,\"LOCERR_HTTP_409\":409,\"LOCERR_HTTP_410\":410,\"LOCERR_HTTP_411\":411,\"LOCERR_HTTP_412\":412,\"LOCERR_HTTP_413\":413,\"LOCERR_HTTP_414\":414,\"LOCERR_HTTP_415\":415,\"LOCERR_HTTP_416\":416,\"LOCERR_HTTP_417\":417,\"LOCERR_HTTP_422\":422,\"LOCERR_HTTP_429\":429,\"LOCERR_HTTP_500\":500,\"LOCERR_HTTP_501\":501,\"LOCERR_HTTP_502\":502,\"LOCERR_HTTP_503\":503,\"LOCERR_HTTP_504\":504,\"LOCERR_HTTP_505\":505,\"LOCERR_HTTP_509\":509,\"LOCERR_HTTP_COULD_NOT_RESOLVE_HOST\":700,\"LOCERR_APP_ALREADY_EXISTS\":1000,\"LOCERR_APP_INVALID_NAME\":1001,\"LOCERR_APP_ALREADY_OPEN\":1002,\"LOCERR_APP_NOT_FOUND\":1003,\"LOCERR_APP_IMPORT_FAILED\":1004,\"LOCERR_APP_SAVE_FAILED\":1005,\"LOCERR_APP_CREATE_FAILED\":1006,\"LOCERR_APP_INVALID\":1007,\"LOCERR_APP_CONNECT_FAILED\":1008,\"LOCERR_APP_ALREADY_OPEN_IN_DIFFERENT_MODE\":1009,\"LOCERR_APP_MIGRATION_COULD_NOT_CONTACT_MIGRATION_SERVICE\":1010,\"LOCERR_APP_MIGRATION_COULD_NOT_START_MIGRATION\":1011,\"LOCERR_APP_MIGRATION_FAILURE\":1012,\"LOCERR_APP_SCRIPT_MISSING\":1013,\"LOCERR_APP_EXPORT_FAILED\":1014,\"LOCERR_CONNECTION_ALREADY_EXISTS\":2000,\"LOCERR_CONNECTION_NOT_FOUND\":2001,\"LOCERR_CONNECTION_FAILED_TO_LOAD\":2002,\"LOCERR_CONNECTION_FAILED_TO_IMPORT\":2003,\"LOCERR_CONNECTION_NAME_IS_INVALID\":2004,\"LOCERR_CONNECTOR_NO_FILE_STREAMING_SUPPORT\":2300,\"LOCERR_CONNECTOR_FILESIZE_EXCEEDED_BUFFER_SIZE\":2301,\"LOCERR_FILE_ACCESS_DENIED\":3000,\"LOCERR_FILE_NAME_INVALID\":3001,\"LOCERR_FILE_CORRUPT\":3002,\"LOCERR_FILE_NOT_FOUND\":3003,\"LOCERR_FILE_FORMAT_UNSUPPORTED\":3004,\"LOCERR_FILE_OPENED_IN_UNSUPPORTED_MODE\":3005,\"LOCERR_FILE_TABLE_NOT_FOUND\":3006,\"LOCERR_USER_ACCESS_DENIED\":4000,\"LOCERR_USER_IMPERSONATION_FAILED\":4001,\"LOCERR_SERVER_OUT_OF_SESSION_AND_USER_CALS\":5000,\"LOCERR_SERVER_OUT_OF_SESSION_CALS\":5001,\"LOCERR_SERVER_OUT_OF_USAGE_CALS\":5002,\"LOCERR_SERVER_OUT_OF_CALS\":5003,\"LOCERR_SERVER_OUT_OF_NAMED_CALS\":5004,\"LOCERR_SERVER_OFF_DUTY\":5005,\"LOCERR_SERVER_BUSY\":5006,\"LOCERR_SERVER_LICENSE_EXPIRED\":5007,\"LOCERR_SERVER_AJAX_DISABLED\":5008,\"LOCERR_HC_INVALID_OBJECT\":6000,\"LOCERR_HC_RESULT_TOO_LARGE\":6001,\"LOCERR_HC_INVALID_OBJECT_STATE\":6002,\"LOCERR_HC_MODAL_OBJECT_ERROR\":6003,\"LOCERR_CALC_INVALID_DEF\":7000,\"LOCERR_CALC_NOT_IN_LIB\":7001,\"LOCERR_CALC_HEAP_ERROR\":7002,\"LOCERR_CALC_TOO_LARGE\":7003,\"LOCERR_CALC_TIMEOUT\":7004,\"LOCERR_CALC_EVAL_CONDITION_FAILED\":7005,\"LOCERR_CALC_MIXED_LINKED_AGGREGATION\":7006,\"LOCERR_CALC_MISSING_LINKED\":7007,\"LOCERR_CALC_INVALID_COL_SORT\":7008,\"LOCERR_CALC_PAGES_TOO_LARGE\":7009,\"LOCERR_CALC_SEMANTIC_FIELD_NOT_ALLOWED\":7010,\"LOCERR_CALC_VALIDATION_STATE_INVALID\":7011,\"LOCERR_CALC_PIVOT_DIMENSIONS_ALREADY_EXISTS\":7012,\"LOCERR_CALC_MISSING_LINKED_FIELD\":7013,\"LOCERR_CALC_NOT_CALCULATED\":7014,\"LOCERR_LAYOUT_EXTENDS_INVALID_ID\":8000,\"LOCERR_LAYOUT_LINKED_OBJECT_NOT_FOUND\":8001,\"LOCERR_LAYOUT_LINKED_OBJECT_INVALID\":8002,\"LOCERR_PERSISTENCE_WRITE_FAILED\":9000,\"LOCERR_PERSISTENCE_READ_FAILED\":9001,\"LOCERR_PERSISTENCE_DELETE_FAILED\":9002,\"LOCERR_PERSISTENCE_NOT_FOUND\":9003,\"LOCERR_PERSISTENCE_UNSUPPORTED_VERSION\":9004,\"LOCERR_PERSISTENCE_MIGRATION_FAILED_READ_ONLY\":9005,\"LOCERR_PERSISTENCE_MIGRATION_CANCELLED\":9006,\"LOCERR_PERSISTENCE_MIGRATION_BACKUP_FAILED\":9007,\"LOCERR_PERSISTENCE_DISK_FULL\":9008,\"LOCERR_PERSISTENCE_NOT_SUPPORTED_FOR_SESSION_APP\":9009,\"LOCERR_PERSISTENCE_SYNC_SET_CHUNK_INVALID_PARAMETERS\":9510,\"LOCERR_PERSISTENCE_SYNC_GET_CHUNK_INVALID_PARAMETERS\":9511,\"LOCERR_SCRIPT_DATASOURCE_ACCESS_DENIED\":10000,\"LOCERR_RELOAD_IN_PROGRESS\":11000,\"LOCERR_RELOAD_TABLE_X_NOT_FOUND\":11001,\"LOCERR_RELOAD_UNKNOWN_STATEMENT\":11002,\"LOCERR_RELOAD_EXPECTED_SOMETHING_FOUND_UNKNOWN\":11003,\"LOCERR_RELOAD_EXPECTED_NOTHING_FOUND_UNKNOWN\":11004,\"LOCERR_RELOAD_EXPECTED_ONE_OF_1_TOKENS_FOUND_UNKNOWN\":11005,\"LOCERR_RELOAD_EXPECTED_ONE_OF_2_TOKENS_FOUND_UNKNOWN\":11006,\"LOCERR_RELOAD_EXPECTED_ONE_OF_3_TOKENS_FOUND_UNKNOWN\":11007,\"LOCERR_RELOAD_EXPECTED_ONE_OF_4_TOKENS_FOUND_UNKNOWN\":11008,\"LOCERR_RELOAD_EXPECTED_ONE_OF_5_TOKENS_FOUND_UNKNOWN\":11009,\"LOCERR_RELOAD_EXPECTED_ONE_OF_6_TOKENS_FOUND_UNKNOWN\":11010,\"LOCERR_RELOAD_EXPECTED_ONE_OF_7_TOKENS_FOUND_UNKNOWN\":11011,\"LOCERR_RELOAD_EXPECTED_ONE_OF_8_OR_MORE_TOKENS_FOUND_UNKNOWN\":11012,\"LOCERR_RELOAD_FIELD_X_NOT_FOUND\":11013,\"LOCERR_RELOAD_MAPPING_TABLE_X_NOT_FOUND\":11014,\"LOCERR_RELOAD_LIB_CONNECTION_X_NOT_FOUND\":11015,\"LOCERR_RELOAD_NAME_ALREADY_TAKEN\":11016,\"LOCERR_RELOAD_WRONG_FILE_FORMAT_DIF\":11017,\"LOCERR_RELOAD_WRONG_FILE_FORMAT_BIFF\":11018,\"LOCERR_RELOAD_WRONG_FILE_FORMAT_ENCRYPTED\":11019,\"LOCERR_RELOAD_OPEN_FILE_ERROR\":11020,\"LOCERR_RELOAD_AUTO_GENERATE_COUNT\":11021,\"LOCERR_RELOAD_PE_ILLEGAL_PREFIX_COMB\":11022,\"LOCERR_RELOAD_MATCHING_CONTROL_STATEMENT_ERROR\":11023,\"LOCERR_RELOAD_MATCHING_LIBPATH_X_NOT_FOUND\":11024,\"LOCERR_RELOAD_MATCHING_LIBPATH_X_INVALID\":11025,\"LOCERR_RELOAD_MATCHING_LIBPATH_X_OUTSIDE\":11026,\"LOCERR_RELOAD_NO_QUALIFIED_PATH_FOR_FILE\":11027,\"LOCERR_RELOAD_MODE_STATEMENT_ONLY_FOR_LIB_PATHS\":11028,\"LOCERR_RELOAD_INCONSISTENT_USE_OF_SEMANTIC_FIELDS\":11029,\"LOCERR_RELOAD_NO_OPEN_DATABASE\":11030,\"LOCERR_RELOAD_AGGREGATION_REQUIRED_BY_GROUP_BY\":11031,\"LOCERR_RELOAD_CONNECT_MUST_USE_LIB_PREFIX_IN_THIS_MODE\":11032,\"LOCERR_RELOAD_ODBC_CONNECT_FAILED\":11033,\"LOCERR_RELOAD_OLEDB_CONNECT_FAILED\":11034,\"LOCERR_RELOAD_CUSTOM_CONNECT_FAILED\":11035,\"LOCERR_RELOAD_ODBC_READ_FAILED\":11036,\"LOCERR_RELOAD_OLEDB_READ_FAILED\":11037,\"LOCERR_RELOAD_CUSTOM_READ_FAILED\":11038,\"LOCERR_RELOAD_BINARY_LOAD_PROHIBITED\":11039,\"LOCERR_RELOAD_CONNECTOR_START_FAILED\":11040,\"LOCERR_RELOAD_CONNECTOR_NOT_RESPONDING\":11041,\"LOCERR_RELOAD_CONNECTOR_REPLY_ERROR\":11042,\"LOCERR_RELOAD_CONNECTOR_CONNECT_ERROR\":11043,\"LOCERR_RELOAD_CONNECTOR_NOT_FOUND_ERROR\":11044,\"LOCERR_RELOAD_INPUT_FIELD_WITH_DUPLICATE_KEYS\":11045,\"LOCERR_RELOAD_CONCATENATE_LOAD_NO_PREVIOUS_TABLE\":11046,\"LOCERR_PERSONAL_NEW_VERSION_AVAILABLE\":12000,\"LOCERR_PERSONAL_VERSION_EXPIRED\":12001,\"LOCERR_PERSONAL_SECTION_ACCESS_DETECTED\":12002,\"LOCERR_PERSONAL_APP_DELETION_FAILED\":12003,\"LOCERR_USER_AUTHENTICATION_FAILURE\":12004,\"LOCERR_EXPORT_OUT_OF_MEMORY\":13000,\"LOCERR_EXPORT_NO_DATA\":13001,\"LOCERR_SYNC_INVALID_OFFSET\":14000,\"LOCERR_SEARCH_TIMEOUT\":15000,\"LOCERR_DIRECT_DISCOVERY_LINKED_EXPRESSION_FAIL\":16000,\"LOCERR_DIRECT_DISCOVERY_ROWCOUNT_OVERFLOW\":16001,\"LOCERR_DIRECT_DISCOVERY_EMPTY_RESULT\":16002,\"LOCERR_DIRECT_DISCOVERY_DB_CONNECTION_FAILED\":16003,\"LOCERR_DIRECT_DISCOVERY_MEASURE_NOT_ALLOWED\":16004,\"LOCERR_DIRECT_DISCOVERY_DETAIL_NOT_ALLOWED\":16005,\"LOCERR_DIRECT_DISCOVERY_NOT_SYNTH_CIRCULAR_ALLOWED\":16006,\"LOCERR_DIRECT_DISCOVERY_ONLY_ONE_DD_TABLE_ALLOWED\":16007,\"LOCERR_DIRECT_DISCOVERY_DB_AUTHORIZATION_FAILED\":16008,\"LOCERR_SMART_LOAD_TABLE_NOT_FOUND\":17000,\"LOCERR_SMART_LOAD_TABLE_DUPLICATED\":17001,\"LOCERR_VARIABLE_NO_NAME\":18000,\"LOCERR_VARIABLE_DUPLICATE_NAME\":18001,\"LOCERR_VARIABLE_INCONSISTENCY\":18002,\"LOCERR_MEDIA_LIBRARY_LIST_FAILED\":19000,\"LOCERR_MEDIA_LIBRARY_CONTENT_FAILED\":19001,\"LOCERR_MEDIA_BUNDLING_FAILED\":19002,\"LOCERR_MEDIA_UNBUNDLING_FAILED\":19003,\"LOCERR_MEDIA_LIBRARY_NOT_FOUND\":19004,\"LOCERR_FEATURE_DISABLED\":20000,\"LOCERR_JSON_RPC_INVALID_REQUEST\":-32600,\"LOCERR_JSON_RPC_METHOD_NOT_FOUND\":-32601,\"LOCERR_JSON_RPC_INVALID_PARAMETERS\":-32602,\"LOCERR_JSON_RPC_INTERNAL_ERROR\":-32603,\"LOCERR_JSON_RPC_PARSE_ERROR\":-32700,\"LOCERR_MQ_SOCKET_CONNECT_FAILURE\":33000,\"LOCERR_MQ_SOCKET_OPEN_FAILURE\":33001,\"LOCERR_MQ_PROTOCOL_NO_RESPONE\":33002,\"LOCERR_MQ_PROTOCOL_LIBRARY_EXCEPTION\":33003,\"LOCERR_MQ_PROTOCOL_CONNECTION_CLOSED\":33004,\"LOCERR_MQ_PROTOCOL_CHANNEL_CLOSED\":33005,\"LOCERR_MQ_PROTOCOL_UNKNOWN_ERROR\":33006,\"LOCERR_MQ_PROTOCOL_INVALID_STATUS\":33007,\"LOCERR_EXTENGINE_GRPC_STATUS_OK\":22000,\"LOCERR_EXTENGINE_GRPC_STATUS_CANCELLED\":22001,\"LOCERR_EXTENGINE_GRPC_STATUS_UNKNOWN\":22002,\"LOCERR_EXTENGINE_GRPC_STATUS_INVALID_ARGUMENT\":22003,\"LOCERR_EXTENGINE_GRPC_STATUS_DEADLINE_EXCEEDED\":22004,\"LOCERR_EXTENGINE_GRPC_STATUS_NOT_FOUND\":22005,\"LOCERR_EXTENGINE_GRPC_STATUS_ALREADY_EXISTS\":22006,\"LOCERR_EXTENGINE_GRPC_STATUS_PERMISSION_DENIED\":22007,\"LOCERR_EXTENGINE_GRPC_STATUS_RESOURCE_EXHAUSTED\":22008,\"LOCERR_EXTENGINE_GRPC_STATUS_FAILED_PRECONDITION\":22009,\"LOCERR_EXTENGINE_GRPC_STATUS_ABORTED\":22010,\"LOCERR_EXTENGINE_GRPC_STATUS_OUT_OF_RANGE\":22011,\"LOCERR_EXTENGINE_GRPC_STATUS_UNIMPLEMENTED\":22012,\"LOCERR_EXTENGINE_GRPC_STATUS_INTERNAL\":22013,\"LOCERR_EXTENGINE_GRPC_STATUS_UNAVAILABLE\":22014,\"LOCERR_EXTENGINE_GRPC_STATUS_DATA_LOSS\":22015,\"LOCERR_EXTENGINE_GRPC_STATUS_UNAUTHENTICATED\":22016,\"LOCERR_LXW_INVALID_OBJ\":23001,\"LOCERR_LXW_INVALID_FILE\":23002,\"LOCERR_LXW_INVALID_SHEET\":23003,\"LOCERR_LXW_INVALID_EXPORT_RANGE\":23004,\"LOCERR_LXW_ERROR\":23005,\"LOCERR_LXW_ERROR_MEMORY_MALLOC_FAILED\":23006,\"LOCERR_LXW_ERROR_CREATING_XLSX_FILE\":23007,\"LOCERR_LXW_ERROR_CREATING_TMPFILE\":23008,\"LOCERR_LXW_ERROR_ZIP_FILE_OPERATION\":23009,\"LOCERR_LXW_ERROR_ZIP_FILE_ADD\":23010,\"LOCERR_LXW_ERROR_ZIP_CLOSE\":23011,\"LOCERR_LXW_ERROR_NULL_PARAMETER_IGNORED\":23012,\"LOCERR_LXW_ERROR_MAX_STRING_LENGTH_EXCEEDED\":23013,\"LOCERR_LXW_ERROR_255_STRING_LENGTH_EXCEEDED\":23014,\"LOCERR_LXW_ERROR_SHARED_STRING_INDEX_NOT_FOUND\":23015,\"LOCERR_LXW_ERROR_WORKSHEET_INDEX_OUT_OF_RANGE\":23016,\"LOCERR_LXW_ERROR_WORKSHEET_MAX_NUMBER_URLS_EXCEEDED\":23017,\"LOCERR_CURL_UNSUPPORTED_PROTOCOL\":30000,\"LOCERR_CURL_COULDNT_RESOLVE_PROXY\":30001,\"LOCERR_CURL_COULDNT_CONNECT\":30002,\"LOCERR_CURL_REMOTE_ACCESS_DENIED\":30003,\"LOCERR_CURL_FTP_ACCEPT_FAILED\":30004,\"LOCERR_CURL_FTP_ACCEPT_TIMEOUT\":30005,\"LOCERR_CURL_FTP_CANT_GET_HOST\":30006,\"LOCERR_CURL_PARTIAL_FILE\":30007,\"LOCERR_CURL_QUOTE_ERROR\":30008,\"LOCERR_CURL_WRITE_ERROR\":30009,\"LOCERR_CURL_UPLOAD_FAILED\":30010,\"LOCERR_CURL_OUT_OF_MEMORY\":30011,\"LOCERR_CURL_OPERATION_TIMEDOUT\":30012,\"LOCERR_CURL_FTP_COULDNT_USE_REST\":30013,\"LOCERR_CURL_HTTP_POST_ERROR\":30014,\"LOCERR_CURL_SSL_CONNECT_ERROR\":30015,\"LOCERR_CURL_FILE_COULDNT_READ_FILE\":30016,\"LOCERR_CURL_LDAP_CANNOT_BIND\":30017,\"LOCERR_CURL_LDAP_SEARCH_FAILED\":30018,\"LOCERR_CURL_TOO_MANY_REDIRECTS\":30019,\"LOCERR_CURL_PEER_FAILED_VERIFICATION\":30020,\"LOCERR_CURL_GOT_NOTHING\":30021,\"LOCERR_CURL_SSL_ENGINE_NOTFOUND\":30022,\"LOCERR_CURL_SSL_ENGINE_SETFAILED\":30023,\"LOCERR_CURL_SSL_CERTPROBLEM\":30024,\"LOCERR_CURL_SSL_CIPHER\":30025,\"LOCERR_CURL_SSL_CACERT\":30026,\"LOCERR_CURL_BAD_CONTENT_ENCODING\":30027,\"LOCERR_CURL_LDAP_INVALID_URL\":30028,\"LOCERR_CURL_USE_SSL_FAILED\":30029,\"LOCERR_CURL_SSL_ENGINE_INITFAILED\":30030,\"LOCERR_CURL_LOGIN_DENIED\":30031,\"LOCERR_CURL_TFTP_NOTFOUND\":30032,\"LOCERR_CURL_TFTP_ILLEGAL\":30033,\"LOCERR_CURL_SSH\":30034},\"LocalizedWarningCode\":{\"LOCWARN_PERSONAL_RELOAD_REQUIRED\":0,\"LOCWARN_PERSONAL_VERSION_EXPIRES_SOON\":1,\"LOCWARN_EXPORT_DATA_TRUNCATED\":1000,\"LOCWARN_COULD_NOT_OPEN_ALL_OBJECTS\":2000},\"GrpType\":{\"GRP_NX_NONE\":0,\"GRP_NX_HIEARCHY\":1,\"GRP_NX_COLLECTION\":2},\"ExportFileType\":{\"EXPORT_CSV_C\":0,\"EXPORT_CSV_T\":1,\"EXPORT_OOXML\":2},\"ExportState\":{\"EXPORT_POSSIBLE\":0,\"EXPORT_ALL\":1},\"DimCellType\":{\"NX_DIM_CELL_VALUE\":0,\"NX_DIM_CELL_EMPTY\":1,\"NX_DIM_CELL_NORMAL\":2,\"NX_DIM_CELL_TOTAL\":3,\"NX_DIM_CELL_OTHER\":4,\"NX_DIM_CELL_AGGR\":5,\"NX_DIM_CELL_PSEUDO\":6,\"NX_DIM_CELL_ROOT\":7,\"NX_DIM_CELL_NULL\":8,\"NX_DIM_CELL_GENERATED\":9},\"StackElemType\":{\"NX_STACK_CELL_NORMAL\":0,\"NX_STACK_CELL_TOTAL\":1,\"NX_STACK_CELL_OTHER\":2,\"NX_STACK_CELL_SUM\":3,\"NX_STACK_CELL_VALUE\":4,\"NX_STACK_CELL_PSEUDO\":5},\"SortIndicatorType\":{\"NX_SORT_INDICATE_NONE\":0,\"NX_SORT_INDICATE_ASC\":1,\"NX_SORT_INDICATE_DESC\":2},\"DimensionType\":{\"NX_DIMENSION_TYPE_DISCRETE\":0,\"NX_DIMENSION_TYPE_NUMERIC\":1,\"NX_DIMENSION_TYPE_TIME\":2},\"FieldSelectionMode\":{\"SELECTION_MODE_NORMAL\":0,\"SELECTION_MODE_AND\":1,\"SELECTION_MODE_NOT\":2},\"FrequencyMode\":{\"NX_FREQUENCY_NONE\":0,\"NX_FREQUENCY_VALUE\":1,\"NX_FREQUENCY_PERCENT\":2,\"NX_FREQUENCY_RELATIVE\":3},\"DataReductionMode\":{\"DATA_REDUCTION_NONE\":0,\"DATA_REDUCTION_ONEDIM\":1,\"DATA_REDUCTION_SCATTERED\":2,\"DATA_REDUCTION_CLUSTERED\":3,\"DATA_REDUCTION_STACKED\":4},\"HypercubeMode\":{\"DATA_MODE_STRAIGHT\":0,\"DATA_MODE_PIVOT\":1,\"DATA_MODE_PIVOT_STACK\":2,\"DATA_MODE_TREE\":3},\"PatchOperationType\":{\"Add\":0,\"Remove\":1,\"Replace\":2},\"SelectionCellType\":{\"NX_CELL_DATA\":0,\"NX_CELL_TOP\":1,\"NX_CELL_LEFT\":2},\"MatchingFieldMode\":{\"MATCHINGFIELDMODE_MATCH_ALL\":0,\"MATCHINGFIELDMODE_MATCH_ONE\":1},\"SessionState\":{\"SESSION_CREATED\":0,\"SESSION_ATTACHED\":1,\"SESSION_ERROR_NO_LICENSE\":2,\"SESSION_ERROR_LICENSE_RENEW\":3},\"ReloadState\":{\"RELOAD_PAUSED\":0,\"RELOAD_STARTED\":1,\"RELOAD_ABORTED\":2},\"QrsChangeType\":{\"QRS_CHANGE_UNDEFINED\":0,\"QRS_CHANGE_ADD\":1,\"QRS_CHANGE_UPDATE\":2,\"QRS_CHANGE_DELETE\":3},\"ExtEngineDataType\":{\"NX_EXT_DATATYPE_STRING\":0,\"NX_EXT_DATATYPE_DOUBLE\":1,\"NX_EXT_DATATYPE_BOTH\":2},\"ExtEngineFunctionType\":{\"NX_EXT_FUNCTIONTYPE_SCALAR\":0,\"NX_EXT_FUNCTIONTYPE_AGGR\":1,\"NX_EXT_FUNCTIONTYPE_TENSOR\":2},\"ExtEngineMsgType\":{\"NX_EXT_MSGTYPE_FUNCTION_CALL\":1,\"NX_EXT_MSGTYPE_SCRIPT_CALL\":2,\"NX_EXT_MSGTYPE_RETURN_VALUE\":3,\"NX_EXT_MSGTYPE_RETURN_MULTIPLE\":4,\"NX_EXT_MSGTYPE_RETURN_ERROR\":5}},\"version\":\"12.170.2\"}");

/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {

/**
 * enigma.js v2.6.3
 * Copyright (c) 2019 QlikTech International AB
 * This library is licensed under MIT - See the LICENSE file for full details
 */

(function (global, factory) {
	 true ? module.exports = factory() :
	undefined;
}(this, (function () { 'use strict';

	function createCommonjsModule(fn, module) {
		return module = { exports: {} }, fn(module, module.exports), module.exports;
	}

	// Copyright Joyent, Inc. and other Node contributors.

	// If obj.hasOwnProperty has been overridden, then calling
	// obj.hasOwnProperty(prop) will break.
	// See: https://github.com/joyent/node/issues/1707
	function hasOwnProperty(obj, prop) {
	  return Object.prototype.hasOwnProperty.call(obj, prop);
	}

	var decode = function(qs, sep, eq, options) {
	  sep = sep || '&';
	  eq = eq || '=';
	  var obj = {};

	  if (typeof qs !== 'string' || qs.length === 0) {
	    return obj;
	  }

	  var regexp = /\+/g;
	  qs = qs.split(sep);

	  var maxKeys = 1000;
	  if (options && typeof options.maxKeys === 'number') {
	    maxKeys = options.maxKeys;
	  }

	  var len = qs.length;
	  // maxKeys <= 0 means that we should not limit keys count
	  if (maxKeys > 0 && len > maxKeys) {
	    len = maxKeys;
	  }

	  for (var i = 0; i < len; ++i) {
	    var x = qs[i].replace(regexp, '%20'),
	        idx = x.indexOf(eq),
	        kstr, vstr, k, v;

	    if (idx >= 0) {
	      kstr = x.substr(0, idx);
	      vstr = x.substr(idx + 1);
	    } else {
	      kstr = x;
	      vstr = '';
	    }

	    k = decodeURIComponent(kstr);
	    v = decodeURIComponent(vstr);

	    if (!hasOwnProperty(obj, k)) {
	      obj[k] = v;
	    } else if (Array.isArray(obj[k])) {
	      obj[k].push(v);
	    } else {
	      obj[k] = [obj[k], v];
	    }
	  }

	  return obj;
	};

	// Copyright Joyent, Inc. and other Node contributors.

	var stringifyPrimitive = function(v) {
	  switch (typeof v) {
	    case 'string':
	      return v;

	    case 'boolean':
	      return v ? 'true' : 'false';

	    case 'number':
	      return isFinite(v) ? v : '';

	    default:
	      return '';
	  }
	};

	var encode = function(obj, sep, eq, name) {
	  sep = sep || '&';
	  eq = eq || '=';
	  if (obj === null) {
	    obj = undefined;
	  }

	  if (typeof obj === 'object') {
	    return Object.keys(obj).map(function(k) {
	      var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
	      if (Array.isArray(obj[k])) {
	        return obj[k].map(function(v) {
	          return ks + encodeURIComponent(stringifyPrimitive(v));
	        }).join(sep);
	      } else {
	        return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
	      }
	    }).join(sep);

	  }

	  if (!name) return '';
	  return encodeURIComponent(stringifyPrimitive(name)) + eq +
	         encodeURIComponent(stringifyPrimitive(obj));
	};

	var querystring = createCommonjsModule(function (module, exports) {

	exports.decode = exports.parse = decode;
	exports.encode = exports.stringify = encode;
	});
	var querystring_1 = querystring.decode;
	var querystring_2 = querystring.parse;
	var querystring_3 = querystring.encode;
	var querystring_4 = querystring.stringify;

	function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }

	function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
	/**
	* The Qlik Sense configuration object.
	* @typedef {Object} SenseConfiguration
	* @property {String} [appId] The app id. If omitted, only the global object is returned.
	*                            Otherwise both global and app object are returned.
	* @property {Boolean} [noData=false] Whether to open the app without data.
	* @property {Boolean} [secure=true] Set to false if an unsecure WebSocket should be used.
	* @property {String} [host] Host address.
	* @property {Number} [port] Port to connect to.
	* @property {String} [prefix="/"] The absolute base path to use when connecting.
	*                             Used for proxy prefixes.
	* @property {String} [subpath=""] The subpath.
	* @property {String} [route=""] Used to instruct Proxy to route to the correct receiver.
	* @property {String} [identity=""] Identity to use.
	* @property {Object} [urlParams={}] Used to add parameters to the WebSocket URL.
	* @property {Number} [ttl] A value in seconds that QIX Engine should keep the session
	*                             alive after socket disconnect (only works if QIX Engine supports it).
	*/

	function replaceLeadingAndTrailingSlashes(str) {
	  return str.replace(/(^[/]+)|([/]+$)/g, '');
	}

	var SenseUtilities =
	/*#__PURE__*/
	function () {
	  function SenseUtilities() {
	    _classCallCheck(this, SenseUtilities);
	  }

	  _createClass(SenseUtilities, null, [{
	    key: "configureDefaults",

	    /**
	    * Ensures that the configuration has defaults set.
	    *
	    * @private
	    * @param {SenseConfiguration} senseConfig The configuration to ensure defaults on.
	    */
	    value: function configureDefaults(senseConfig) {
	      if (!senseConfig.host) {
	        senseConfig.host = 'localhost';
	      }

	      if (typeof senseConfig.secure === 'undefined') {
	        senseConfig.secure = true;
	      }

	      if (!senseConfig.appId && !senseConfig.route) {
	        senseConfig.route = 'app/engineData';
	      }

	      if (typeof senseConfig.noData === 'undefined') {
	        senseConfig.noData = false;
	      }
	    }
	    /**
	    * Function used to build an URL.
	    * @param {SenseConfiguration} urlConfig - The URL configuration object.
	    * @returns {String} Returns the websocket URL.
	    */

	  }, {
	    key: "buildUrl",
	    value: function buildUrl(urlConfig) {
	      SenseUtilities.configureDefaults(urlConfig);
	      var secure = urlConfig.secure,
	          host = urlConfig.host,
	          port = urlConfig.port,
	          prefix = urlConfig.prefix,
	          subpath = urlConfig.subpath,
	          route = urlConfig.route,
	          identity = urlConfig.identity,
	          urlParams = urlConfig.urlParams,
	          ttl = urlConfig.ttl,
	          appId = urlConfig.appId;
	      var url = '';
	      url += "".concat(secure ? 'wss' : 'ws', "://");
	      url += host || 'localhost';

	      if (port) {
	        url += ":".concat(port);
	      }

	      if (prefix) {
	        url += "/".concat(replaceLeadingAndTrailingSlashes(prefix));
	      }

	      if (subpath) {
	        url += "/".concat(replaceLeadingAndTrailingSlashes(subpath));
	      }

	      if (route) {
	        url += "/".concat(replaceLeadingAndTrailingSlashes(route));
	      } else if (appId) {
	        url += "/app/".concat(encodeURIComponent(appId));
	      }

	      if (identity) {
	        url += "/identity/".concat(encodeURIComponent(identity));
	      }

	      if (ttl) {
	        url += "/ttl/".concat(ttl);
	      }

	      if (urlParams) {
	        url += "?".concat(querystring.stringify(urlParams));
	      }

	      return url;
	    }
	  }]);

	  return SenseUtilities;
	}();

	return SenseUtilities;

})));
//# sourceMappingURL=sense-utilities.js.map


/***/ }),
/* 93 */
/***/ (function(module, exports) {

function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}

module.exports = _arrayWithHoles;

/***/ }),
/* 94 */
/***/ (function(module, exports) {

function _iterableToArrayLimit(arr, i) {
  if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
    return;
  }

  var _arr = [];
  var _n = true;
  var _d = false;
  var _e = undefined;

  try {
    for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);

      if (i && _arr.length === i) break;
    }
  } catch (err) {
    _d = true;
    _e = err;
  } finally {
    try {
      if (!_n && _i["return"] != null) _i["return"]();
    } finally {
      if (_d) throw _e;
    }
  }

  return _arr;
}

module.exports = _iterableToArrayLimit;

/***/ }),
/* 95 */
/***/ (function(module, exports) {

function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance");
}

module.exports = _nonIterableRest;

/***/ }),
/* 96 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var keysShim;
if (!Object.keys) {
	// modified from https://github.com/es-shims/es5-shim
	var has = Object.prototype.hasOwnProperty;
	var toStr = Object.prototype.toString;
	var isArgs = __webpack_require__(54); // eslint-disable-line global-require
	var isEnumerable = Object.prototype.propertyIsEnumerable;
	var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
	var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
	var dontEnums = [
		'toString',
		'toLocaleString',
		'valueOf',
		'hasOwnProperty',
		'isPrototypeOf',
		'propertyIsEnumerable',
		'constructor'
	];
	var equalsConstructorPrototype = function (o) {
		var ctor = o.constructor;
		return ctor && ctor.prototype === o;
	};
	var excludedKeys = {
		$applicationCache: true,
		$console: true,
		$external: true,
		$frame: true,
		$frameElement: true,
		$frames: true,
		$innerHeight: true,
		$innerWidth: true,
		$onmozfullscreenchange: true,
		$onmozfullscreenerror: true,
		$outerHeight: true,
		$outerWidth: true,
		$pageXOffset: true,
		$pageYOffset: true,
		$parent: true,
		$scrollLeft: true,
		$scrollTop: true,
		$scrollX: true,
		$scrollY: true,
		$self: true,
		$webkitIndexedDB: true,
		$webkitStorageInfo: true,
		$window: true
	};
	var hasAutomationEqualityBug = (function () {
		/* global window */
		if (typeof window === 'undefined') { return false; }
		for (var k in window) {
			try {
				if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
					try {
						equalsConstructorPrototype(window[k]);
					} catch (e) {
						return true;
					}
				}
			} catch (e) {
				return true;
			}
		}
		return false;
	}());
	var equalsConstructorPrototypeIfNotBuggy = function (o) {
		/* global window */
		if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
			return equalsConstructorPrototype(o);
		}
		try {
			return equalsConstructorPrototype(o);
		} catch (e) {
			return false;
		}
	};

	keysShim = function keys(object) {
		var isObject = object !== null && typeof object === 'object';
		var isFunction = toStr.call(object) === '[object Function]';
		var isArguments = isArgs(object);
		var isString = isObject && toStr.call(object) === '[object String]';
		var theKeys = [];

		if (!isObject && !isFunction && !isArguments) {
			throw new TypeError('Object.keys called on a non-object');
		}

		var skipProto = hasProtoEnumBug && isFunction;
		if (isString && object.length > 0 && !has.call(object, 0)) {
			for (var i = 0; i < object.length; ++i) {
				theKeys.push(String(i));
			}
		}

		if (isArguments && object.length > 0) {
			for (var j = 0; j < object.length; ++j) {
				theKeys.push(String(j));
			}
		} else {
			for (var name in object) {
				if (!(skipProto && name === 'prototype') && has.call(object, name)) {
					theKeys.push(String(name));
				}
			}
		}

		if (hasDontEnumBug) {
			var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);

			for (var k = 0; k < dontEnums.length; ++k) {
				if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
					theKeys.push(dontEnums[k]);
				}
			}
		}
		return theKeys;
	};
}
module.exports = keysShim;


/***/ }),
/* 97 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


// http://www.ecma-international.org/ecma-262/6.0/#sec-object.is

var numberIsNaN = function (value) {
	return value !== value;
};

module.exports = function is(a, b) {
	if (a === 0 && b === 0) {
		return 1 / a === 1 / b;
	}
	if (a === b) {
		return true;
	}
	if (numberIsNaN(a) && numberIsNaN(b)) {
		return true;
	}
	return false;
};



/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var has = __webpack_require__(99);
var regexExec = RegExp.prototype.exec;
var gOPD = Object.getOwnPropertyDescriptor;

var tryRegexExecCall = function tryRegexExec(value) {
	try {
		var lastIndex = value.lastIndex;
		value.lastIndex = 0; // eslint-disable-line no-param-reassign

		regexExec.call(value);
		return true;
	} catch (e) {
		return false;
	} finally {
		value.lastIndex = lastIndex; // eslint-disable-line no-param-reassign
	}
};
var toStr = Object.prototype.toString;
var regexClass = '[object RegExp]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';

module.exports = function isRegex(value) {
	if (!value || typeof value !== 'object') {
		return false;
	}
	if (!hasToStringTag) {
		return toStr.call(value) === regexClass;
	}

	var descriptor = gOPD(value, 'lastIndex');
	var hasLastIndexDataProperty = descriptor && has(descriptor, 'value');
	if (!hasLastIndexDataProperty) {
		return false;
	}

	return tryRegexExecCall(value);
};


/***/ }),
/* 99 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var bind = __webpack_require__(40);

module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);


/***/ }),
/* 100 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* eslint no-invalid-this: 1 */

var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var slice = Array.prototype.slice;
var toStr = Object.prototype.toString;
var funcType = '[object Function]';

module.exports = function bind(that) {
    var target = this;
    if (typeof target !== 'function' || toStr.call(target) !== funcType) {
        throw new TypeError(ERROR_MESSAGE + target);
    }
    var args = slice.call(arguments, 1);

    var bound;
    var binder = function () {
        if (this instanceof bound) {
            var result = target.apply(
                this,
                args.concat(slice.call(arguments))
            );
            if (Object(result) === result) {
                return result;
            }
            return this;
        } else {
            return target.apply(
                that,
                args.concat(slice.call(arguments))
            );
        }
    };

    var boundLength = Math.max(0, target.length - args.length);
    var boundArgs = [];
    for (var i = 0; i < boundLength; i++) {
        boundArgs.push('$' + i);
    }

    bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);

    if (target.prototype) {
        var Empty = function Empty() {};
        Empty.prototype = target.prototype;
        bound.prototype = new Empty();
        Empty.prototype = null;
    }

    return bound;
};


/***/ }),
/* 101 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var define = __webpack_require__(41);
var callBind = __webpack_require__(56);

var implementation = __webpack_require__(58);
var getPolyfill = __webpack_require__(59);
var shim = __webpack_require__(102);

var flagsBound = callBind(implementation);

define(flagsBound, {
	getPolyfill: getPolyfill,
	implementation: implementation,
	shim: shim
});

module.exports = flagsBound;


/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var supportsDescriptors = __webpack_require__(41).supportsDescriptors;
var getPolyfill = __webpack_require__(59);
var gOPD = Object.getOwnPropertyDescriptor;
var defineProperty = Object.defineProperty;
var TypeErr = TypeError;
var getProto = Object.getPrototypeOf;
var regex = /a/;

module.exports = function shimFlags() {
	if (!supportsDescriptors || !getProto) {
		throw new TypeErr('RegExp.prototype.flags requires a true ES5 environment that supports property descriptors');
	}
	var polyfill = getPolyfill();
	var proto = getProto(regex);
	var descriptor = gOPD(proto, 'flags');
	if (!descriptor || descriptor.get !== polyfill) {
		defineProperty(proto, 'flags', {
			configurable: true,
			enumerable: false,
			get: polyfill
		});
	}
	return polyfill;
};


/***/ }),
/* 103 */
/***/ (function(module, exports) {

var toString = {}.toString;

module.exports = Array.isArray || function (arr) {
  return toString.call(arr) == '[object Array]';
};


/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var getDay = Date.prototype.getDay;
var tryDateObject = function tryDateGetDayCall(value) {
	try {
		getDay.call(value);
		return true;
	} catch (e) {
		return false;
	}
};

var toStr = Object.prototype.toString;
var dateClass = '[object Date]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';

module.exports = function isDateObject(value) {
	if (typeof value !== 'object' || value === null) {
		return false;
	}
	return hasToStringTag ? tryDateObject(value) : toStr.call(value) === dateClass;
};


/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var isString = __webpack_require__(60);
var isNumber = __webpack_require__(106);
var isBoolean = __webpack_require__(107);
var isSymbol = __webpack_require__(108);
var isBigInt = __webpack_require__(109);

// eslint-disable-next-line consistent-return
module.exports = function whichBoxedPrimitive(value) {
	// eslint-disable-next-line eqeqeq
	if (value == null || (typeof value !== 'object' && typeof value !== 'function')) {
		return null;
	}
	if (isString(value)) {
		return 'String';
	}
	if (isNumber(value)) {
		return 'Number';
	}
	if (isBoolean(value)) {
		return 'Boolean';
	}
	if (isSymbol(value)) {
		return 'Symbol';
	}
	if (isBigInt(value)) {
		return 'BigInt';
	}
};


/***/ }),
/* 106 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var numToStr = Number.prototype.toString;
var tryNumberObject = function tryNumberObject(value) {
	try {
		numToStr.call(value);
		return true;
	} catch (e) {
		return false;
	}
};
var toStr = Object.prototype.toString;
var numClass = '[object Number]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';

module.exports = function isNumberObject(value) {
	if (typeof value === 'number') {
		return true;
	}
	if (typeof value !== 'object') {
		return false;
	}
	return hasToStringTag ? tryNumberObject(value) : toStr.call(value) === numClass;
};


/***/ }),
/* 107 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var boolToStr = Boolean.prototype.toString;

var tryBooleanObject = function booleanBrandCheck(value) {
	try {
		boolToStr.call(value);
		return true;
	} catch (e) {
		return false;
	}
};
var toStr = Object.prototype.toString;
var boolClass = '[object Boolean]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';

module.exports = function isBoolean(value) {
	if (typeof value === 'boolean') {
		return true;
	}
	if (value === null || typeof value !== 'object') {
		return false;
	}
	return hasToStringTag && Symbol.toStringTag in value ? tryBooleanObject(value) : toStr.call(value) === boolClass;
};


/***/ }),
/* 108 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var toStr = Object.prototype.toString;
var hasSymbols = __webpack_require__(42)();

if (hasSymbols) {
	var symToStr = Symbol.prototype.toString;
	var symStringRegex = /^Symbol\(.*\)$/;
	var isSymbolObject = function isRealSymbolObject(value) {
		if (typeof value.valueOf() !== 'symbol') {
			return false;
		}
		return symStringRegex.test(symToStr.call(value));
	};

	module.exports = function isSymbol(value) {
		if (typeof value === 'symbol') {
			return true;
		}
		if (toStr.call(value) !== '[object Symbol]') {
			return false;
		}
		try {
			return isSymbolObject(value);
		} catch (e) {
			return false;
		}
	};
} else {

	module.exports = function isSymbol(value) {
		// this environment does not support Symbols.
		return  false && false;
	};
}


/***/ }),
/* 109 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


if (typeof BigInt === 'function') {
	var bigIntValueOf = BigInt.prototype.valueOf;
	var tryBigInt = function tryBigIntObject(value) {
		try {
			bigIntValueOf.call(value);
			return true;
		} catch (e) {
		}
		return false;
	};

	module.exports = function isBigInt(value) {
		if (
			value === null
			|| typeof value === 'undefined'
			|| typeof value === 'boolean'
			|| typeof value === 'string'
			|| typeof value === 'number'
			|| typeof value === 'symbol'
			|| typeof value === 'function'
		) {
			return false;
		}
		if (typeof value === 'bigint') { // eslint-disable-line valid-typeof
			return true;
		}

		return tryBigInt(value);
	};
} else {
	module.exports = function isBigInt(value) {
		return  false && false;
	};
}


/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var isMap = __webpack_require__(61);
var isSet = __webpack_require__(62);
var isWeakMap = __webpack_require__(111);
var isWeakSet = __webpack_require__(112);

module.exports = function whichCollection(value) {
	if (value && typeof value === 'object') {
		if (isMap(value)) {
			return 'Map';
		}
		if (isSet(value)) {
			return 'Set';
		}
		if (isWeakMap(value)) {
			return 'WeakMap';
		}
		if (isWeakSet(value)) {
			return 'WeakSet';
		}
	}
	return false;
};


/***/ }),
/* 111 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var $WeakMap = typeof WeakMap === 'function' && WeakMap.prototype ? WeakMap : null;
var $WeakSet = typeof WeakSet === 'function' && WeakSet.prototype ? WeakSet : null;

var exported;

if (!$WeakMap) {
	// eslint-disable-next-line no-unused-vars
	exported = function isWeakMap(x) {
		// `WeakMap` is not present in this environment.
		return false;
	};
}

var $mapHas = $WeakMap ? $WeakMap.prototype.has : null;
var $setHas = $WeakSet ? $WeakSet.prototype.has : null;
if (!exported && !$mapHas) {
	// eslint-disable-next-line no-unused-vars
	exported = function isWeakMap(x) {
		// `WeakMap` does not have a `has` method
		return false;
	};
}

module.exports = exported || function isWeakMap(x) {
	if (!x || typeof x !== 'object') {
		return false;
	}
	try {
		$mapHas.call(x, $mapHas);
		if ($setHas) {
			try {
				$setHas.call(x, $setHas);
			} catch (e) {
				return true;
			}
		}
		return x instanceof $WeakMap; // core-js workaround, pre-v3
	} catch (e) {}
	return false;
};


/***/ }),
/* 112 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var $WeakMap = typeof WeakMap === 'function' && WeakMap.prototype ? WeakMap : null;
var $WeakSet = typeof WeakSet === 'function' && WeakSet.prototype ? WeakSet : null;

var exported;

if (!$WeakMap) {
	// eslint-disable-next-line no-unused-vars
	exported = function isWeakSet(x) {
		// `WeakSet` is not present in this environment.
		return false;
	};
}

var $mapHas = $WeakMap ? $WeakMap.prototype.has : null;
var $setHas = $WeakSet ? $WeakSet.prototype.has : null;
if (!exported && !$setHas) {
	// eslint-disable-next-line no-unused-vars
	module.exports = function isWeakSet(x) {
		// `WeakSet` does not have a `has` method
		return false;
	};
}

module.exports = exported || function isWeakSet(x) {
	if (!x || typeof x !== 'object') {
		return false;
	}
	try {
		$setHas.call(x, $setHas);
		if ($mapHas) {
			try {
				$mapHas.call(x, $mapHas);
			} catch (e) {
				return true;
			}
		}
		return x instanceof $WeakSet; // core-js workaround, pre-v3
	} catch (e) {}
	return false;
};


/***/ }),
/* 113 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(process) {

/* eslint global-require: 0 */
// the code is structured this way so that bundlers can
// alias out `has-symbols` to `() => true` or `() => false` if your target
// environments' Symbol capabilities are known, and then use
// dead code elimination on the rest of this module.
//
// Similarly, `isarray` can be aliased to `Array.isArray` if
// available in all target environments.

var isArguments = __webpack_require__(55);

if (__webpack_require__(42)() || __webpack_require__(57)()) {
	var $iterator = Symbol.iterator;
	// Symbol is available natively or shammed
	// natively:
	//  - Chrome >= 38
	//  - Edge 12-14?, Edge >= 15 for sure
	//  - FF >= 36
	//  - Safari >= 9
	//  - node >= 0.12
	module.exports = function getIterator(iterable) {
		// alternatively, `iterable[$iterator]?.()`
		if (iterable != null && typeof iterable[$iterator] !== 'undefined') {
			return iterable[$iterator]();
		}
		if (isArguments(iterable)) {
			// arguments objects lack Symbol.iterator
			// - node 0.12
			return Array.prototype[$iterator].call(iterable);
		}
	};
} else {
	// Symbol is not available, native or shammed
	var isArray = __webpack_require__(115);
	var isString = __webpack_require__(60);
	var GetIntrinsic = __webpack_require__(30);
	var $Map = GetIntrinsic('%Map%', true);
	var $Set = GetIntrinsic('%Set%', true);
	var callBound = __webpack_require__(43);
	var $arrayPush = callBound('Array.prototype.push');
	var $charCodeAt = callBound('String.prototype.charCodeAt');
	var $stringSlice = callBound('String.prototype.slice');

	var advanceStringIndex = function advanceStringIndex(S, index) {
		var length = S.length;
		if ((index + 1) >= length) {
			return index + 1;
		}

		var first = $charCodeAt(S, index);
		if (first < 0xD800 || first > 0xDBFF) {
			return index + 1;
		}

		var second = $charCodeAt(S, index + 1);
		if (second < 0xDC00 || second > 0xDFFF) {
			return index + 1;
		}

		return index + 2;
	};

	var getArrayIterator = function getArrayIterator(arraylike) {
		var i = 0;
		return {
			next: function next() {
				var done = i >= arraylike.length;
				var value;
				if (!done) {
					value = arraylike[i];
					i += 1;
				}
				return {
					done: done,
					value: value
				};
			}
		};
	};

	var getNonCollectionIterator = function getNonCollectionIterator(iterable) {
		if (isArray(iterable) || isArguments(iterable)) {
			return getArrayIterator(iterable);
		}
		if (isString(iterable)) {
			var i = 0;
			return {
				next: function next() {
					var nextIndex = advanceStringIndex(iterable, i);
					var value = $stringSlice(iterable, i, nextIndex);
					i = nextIndex;
					return {
						done: nextIndex > iterable.length,
						value: value
					};
				}
			};
		}
	};

	if (!$Map && !$Set) {
		// the only language iterables are Array, String, arguments
		// - Safari <= 6.0
		// - Chrome < 38
		// - node < 0.12
		// - FF < 13
		// - IE < 11
		// - Edge < 11

		module.exports = getNonCollectionIterator;
	} else {
		// either Map or Set are available, but Symbol is not
		// - es6-shim on an ES5 browser
		// - Safari 6.2 (maybe 6.1?)
		// - FF v[13, 36)
		// - IE 11
		// - Edge 11
		// - Safari v[6, 9)

		var isMap = __webpack_require__(61);
		var isSet = __webpack_require__(62);

		// Firefox >= 27, IE 11, Safari 6.2 - 9, Edge 11, es6-shim in older envs, all have forEach
		var $mapForEach = callBound('Map.prototype.forEach', true);
		var $setForEach = callBound('Set.prototype.forEach', true);
		if (typeof process === 'undefined' || !process.versions || !process.versions.node) { // "if is not node"

			// Firefox 17 - 26 has `.iterator()`, whose iterator `.next()` either
			// returns a value, or throws a StopIteration object. These browsers
			// do not have any other mechanism for iteration.
			var $mapIterator = callBound('Map.prototype.iterator', true);
			var $setIterator = callBound('Set.prototype.iterator', true);
			var getStopIterationIterator = function (iterator) {
				var done = false;
				return {
					next: function next() {
						try {
							return {
								done: done,
								value: done ? undefined : iterator.next()
							};
						} catch (e) {
							done = true;
							return {
								done: true,
								value: undefined
							};
						}
					}
				};
			};
		}
		// Firefox 27-35, and some older es6-shim versions, use a string "@@iterator" property
		// this returns a proper iterator object, so we should use it instead of forEach.
		// newer es6-shim versions use a string "_es6-shim iterator_" property.
		var $mapAtAtIterator = callBound('Map.prototype.@@iterator', true) || callBound('Map.prototype._es6-shim iterator_', true);
		var $setAtAtIterator = callBound('Set.prototype.@@iterator', true) || callBound('Set.prototype._es6-shim iterator_', true);

		var getCollectionIterator = function getCollectionIterator(iterable) {
			if (isMap(iterable)) {
				if ($mapIterator) {
					return getStopIterationIterator($mapIterator(iterable));
				}
				if ($mapAtAtIterator) {
					return $mapAtAtIterator(iterable);
				}
				if ($mapForEach) {
					var entries = [];
					$mapForEach(iterable, function (v, k) {
						$arrayPush(entries, [k, v]);
					});
					return getArrayIterator(entries);
				}
			}
			if (isSet(iterable)) {
				if ($setIterator) {
					return getStopIterationIterator($setIterator(iterable));
				}
				if ($setAtAtIterator) {
					return $setAtAtIterator(iterable);
				}
				if ($setForEach) {
					var values = [];
					$setForEach(iterable, function (v) {
						$arrayPush(values, v);
					});
					return getArrayIterator(values);
				}
			}
		};

		module.exports = function getIterator(iterable) {
			return getCollectionIterator(iterable) || getNonCollectionIterator(iterable);
		};
	}
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(114)))

/***/ }),
/* 114 */
/***/ (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; };


/***/ }),
/* 115 */
/***/ (function(module, exports) {

var toString = {}.toString;

module.exports = Array.isArray || function (arr) {
  return toString.call(arr) == '[object Array]';
};


/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var GetIntrinsic = __webpack_require__(30);
var callBound = __webpack_require__(43);
var inspect = __webpack_require__(117);

var $TypeError = GetIntrinsic('%TypeError%');
var $WeakMap = GetIntrinsic('%WeakMap%', true);
var $Map = GetIntrinsic('%Map%', true);
var $push = callBound('Array.prototype.push');

var $weakMapGet = callBound('WeakMap.prototype.get', true);
var $weakMapSet = callBound('WeakMap.prototype.set', true);
var $weakMapHas = callBound('WeakMap.prototype.has', true);
var $mapGet = callBound('Map.prototype.get', true);
var $mapSet = callBound('Map.prototype.set', true);
var $mapHas = callBound('Map.prototype.has', true);
var objectGet = function (objects, key) { // eslint-disable-line consistent-return
	for (var i = 0; i < objects.length; i += 1) {
		if (objects[i].key === key) {
			return objects[i].value;
		}
	}
};
var objectSet = function (objects, key, value) {
	for (var i = 0; i < objects.length; i += 1) {
		if (objects[i].key === key) {
			objects[i].value = value; // eslint-disable-line no-param-reassign
			return;
		}
	}
	$push(objects, {
		key: key,
		value: value
	});
};
var objectHas = function (objects, key) {
	for (var i = 0; i < objects.length; i += 1) {
		if (objects[i].key === key) {
			return true;
		}
	}
	return false;
};

module.exports = function getSideChannel() {
	var $wm;
	var $m;
	var $o;
	var channel = {
		assert: function (key) {
			if (!channel.has(key)) {
				throw new $TypeError('Side channel does not contain ' + inspect(key));
			}
		},
		get: function (key) { // eslint-disable-line consistent-return
			if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
				if ($wm) {
					return $weakMapGet($wm, key);
				}
			} else if ($Map) {
				if ($m) {
					return $mapGet($m, key);
				}
			} else {
				if ($o) { // eslint-disable-line no-lonely-if
					return objectGet($o, key);
				}
			}
		},
		has: function (key) {
			if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
				if ($wm) {
					return $weakMapHas($wm, key);
				}
			} else if ($Map) {
				if ($m) {
					return $mapHas($m, key);
				}
			} else {
				if ($o) { // eslint-disable-line no-lonely-if
					return objectHas($o, key);
				}
			}
			return false;
		},
		set: function (key, value) {
			if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
				if (!$wm) {
					$wm = new $WeakMap();
				}
				$weakMapSet($wm, key, value);
			} else if ($Map) {
				if (!$m) {
					$m = new $Map();
				}
				$mapSet($m, key, value);
			} else {
				if (!$o) {
					$o = [];
				}
				objectSet($o, key, value);
			}
		}
	};
	return channel;
};


/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {

var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForEach = hasMap && Map.prototype.forEach;
var hasSet = typeof Set === 'function' && Set.prototype;
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
var setForEach = hasSet && Set.prototype.forEach;
var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype;
var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype;
var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
var booleanValueOf = Boolean.prototype.valueOf;
var objectToString = Object.prototype.toString;
var match = String.prototype.match;
var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null;

var inspectCustom = __webpack_require__(118).custom;
var inspectSymbol = inspectCustom && isSymbol(inspectCustom) ? inspectCustom : null;

module.exports = function inspect_(obj, options, depth, seen) {
    var opts = options || {};

    if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) {
        throw new TypeError('option "quoteStyle" must be "single" or "double"');
    }

    if (typeof obj === 'undefined') {
        return 'undefined';
    }
    if (obj === null) {
        return 'null';
    }
    if (typeof obj === 'boolean') {
        return obj ? 'true' : 'false';
    }

    if (typeof obj === 'string') {
        return inspectString(obj, opts);
    }
    if (typeof obj === 'number') {
        if (obj === 0) {
            return Infinity / obj > 0 ? '0' : '-0';
        }
        return String(obj);
    }
    if (typeof obj === 'bigint') { // eslint-disable-line valid-typeof
        return String(obj) + 'n';
    }

    var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
    if (typeof depth === 'undefined') { depth = 0; }
    if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
        return '[Object]';
    }

    if (typeof seen === 'undefined') {
        seen = [];
    } else if (indexOf(seen, obj) >= 0) {
        return '[Circular]';
    }

    function inspect(value, from) {
        if (from) {
            seen = seen.slice();
            seen.push(from);
        }
        return inspect_(value, opts, depth + 1, seen);
    }

    if (typeof obj === 'function') {
        var name = nameOf(obj);
        return '[Function' + (name ? ': ' + name : '') + ']';
    }
    if (isSymbol(obj)) {
        var symString = Symbol.prototype.toString.call(obj);
        return typeof obj === 'object' ? markBoxed(symString) : symString;
    }
    if (isElement(obj)) {
        var s = '<' + String(obj.nodeName).toLowerCase();
        var attrs = obj.attributes || [];
        for (var i = 0; i < attrs.length; i++) {
            s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts);
        }
        s += '>';
        if (obj.childNodes && obj.childNodes.length) { s += '...'; }
        s += '</' + String(obj.nodeName).toLowerCase() + '>';
        return s;
    }
    if (isArray(obj)) {
        if (obj.length === 0) { return '[]'; }
        return '[ ' + arrObjKeys(obj, inspect).join(', ') + ' ]';
    }
    if (isError(obj)) {
        var parts = arrObjKeys(obj, inspect);
        if (parts.length === 0) { return '[' + String(obj) + ']'; }
        return '{ [' + String(obj) + '] ' + parts.join(', ') + ' }';
    }
    if (typeof obj === 'object') {
        if (inspectSymbol && typeof obj[inspectSymbol] === 'function') {
            return obj[inspectSymbol]();
        } else if (typeof obj.inspect === 'function') {
            return obj.inspect();
        }
    }
    if (isMap(obj)) {
        var mapParts = [];
        mapForEach.call(obj, function (value, key) {
            mapParts.push(inspect(key, obj) + ' => ' + inspect(value, obj));
        });
        return collectionOf('Map', mapSize.call(obj), mapParts);
    }
    if (isSet(obj)) {
        var setParts = [];
        setForEach.call(obj, function (value) {
            setParts.push(inspect(value, obj));
        });
        return collectionOf('Set', setSize.call(obj), setParts);
    }
    if (isWeakMap(obj)) {
        return weakCollectionOf('WeakMap');
    }
    if (isWeakSet(obj)) {
        return weakCollectionOf('WeakSet');
    }
    if (isNumber(obj)) {
        return markBoxed(inspect(Number(obj)));
    }
    if (isBigInt(obj)) {
        return markBoxed(inspect(bigIntValueOf.call(obj)));
    }
    if (isBoolean(obj)) {
        return markBoxed(booleanValueOf.call(obj));
    }
    if (isString(obj)) {
        return markBoxed(inspect(String(obj)));
    }
    if (!isDate(obj) && !isRegExp(obj)) {
        var xs = arrObjKeys(obj, inspect);
        if (xs.length === 0) { return '{}'; }
        return '{ ' + xs.join(', ') + ' }';
    }
    return String(obj);
};

function wrapQuotes(s, defaultStyle, opts) {
    var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'";
    return quoteChar + s + quoteChar;
}

function quote(s) {
    return String(s).replace(/"/g, '&quot;');
}

function isArray(obj) { return toStr(obj) === '[object Array]'; }
function isDate(obj) { return toStr(obj) === '[object Date]'; }
function isRegExp(obj) { return toStr(obj) === '[object RegExp]'; }
function isError(obj) { return toStr(obj) === '[object Error]'; }
function isSymbol(obj) { return toStr(obj) === '[object Symbol]'; }
function isString(obj) { return toStr(obj) === '[object String]'; }
function isNumber(obj) { return toStr(obj) === '[object Number]'; }
function isBigInt(obj) { return toStr(obj) === '[object BigInt]'; }
function isBoolean(obj) { return toStr(obj) === '[object Boolean]'; }

var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };
function has(obj, key) {
    return hasOwn.call(obj, key);
}

function toStr(obj) {
    return objectToString.call(obj);
}

function nameOf(f) {
    if (f.name) { return f.name; }
    var m = match.call(f, /^function\s*([\w$]+)/);
    if (m) { return m[1]; }
    return null;
}

function indexOf(xs, x) {
    if (xs.indexOf) { return xs.indexOf(x); }
    for (var i = 0, l = xs.length; i < l; i++) {
        if (xs[i] === x) { return i; }
    }
    return -1;
}

function isMap(x) {
    if (!mapSize || !x || typeof x !== 'object') {
        return false;
    }
    try {
        mapSize.call(x);
        try {
            setSize.call(x);
        } catch (s) {
            return true;
        }
        return x instanceof Map; // core-js workaround, pre-v2.5.0
    } catch (e) {}
    return false;
}

function isWeakMap(x) {
    if (!weakMapHas || !x || typeof x !== 'object') {
        return false;
    }
    try {
        weakMapHas.call(x, weakMapHas);
        try {
            weakSetHas.call(x, weakSetHas);
        } catch (s) {
            return true;
        }
        return x instanceof WeakMap; // core-js workaround, pre-v2.5.0
    } catch (e) {}
    return false;
}

function isSet(x) {
    if (!setSize || !x || typeof x !== 'object') {
        return false;
    }
    try {
        setSize.call(x);
        try {
            mapSize.call(x);
        } catch (m) {
            return true;
        }
        return x instanceof Set; // core-js workaround, pre-v2.5.0
    } catch (e) {}
    return false;
}

function isWeakSet(x) {
    if (!weakSetHas || !x || typeof x !== 'object') {
        return false;
    }
    try {
        weakSetHas.call(x, weakSetHas);
        try {
            weakMapHas.call(x, weakMapHas);
        } catch (s) {
            return true;
        }
        return x instanceof WeakSet; // core-js workaround, pre-v2.5.0
    } catch (e) {}
    return false;
}

function isElement(x) {
    if (!x || typeof x !== 'object') { return false; }
    if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
        return true;
    }
    return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function';
}

function inspectString(str, opts) {
    // eslint-disable-next-line no-control-regex
    var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte);
    return wrapQuotes(s, 'single', opts);
}

function lowbyte(c) {
    var n = c.charCodeAt(0);
    var x = {
        8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r'
    }[n];
    if (x) { return '\\' + x; }
    return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16);
}

function markBoxed(str) {
    return 'Object(' + str + ')';
}

function weakCollectionOf(type) {
    return type + ' { ? }';
}

function collectionOf(type, size, entries) {
    return type + ' (' + size + ') {' + entries.join(', ') + '}';
}

function arrObjKeys(obj, inspect) {
    var isArr = isArray(obj);
    var xs = [];
    if (isArr) {
        xs.length = obj.length;
        for (var i = 0; i < obj.length; i++) {
            xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';
        }
    }
    for (var key in obj) { // eslint-disable-line no-restricted-syntax
        if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
        if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
        if ((/[^\w$]/).test(key)) {
            xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));
        } else {
            xs.push(key + ': ' + inspect(obj[key], obj));
        }
    }
    return xs;
}


/***/ }),
/* 118 */
/***/ (function(module, exports) {

/* (ignored) */

/***/ }),
/* 119 */
/***/ (function(module, exports) {

// Unique ID creation requires a high quality random # generator.  In the
// browser this is a little complicated due to unknown quality of Math.random()
// and inconsistent support for the `crypto` API.  We do the best we can via
// feature-detection

// getRandomValues needs to be invoked in a context where "this" is a Crypto
// implementation. Also, find the complete implementation of crypto on IE11.
var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
                      (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));

if (getRandomValues) {
  // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
  var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef

  module.exports = function whatwgRNG() {
    getRandomValues(rnds8);
    return rnds8;
  };
} else {
  // Math.random()-based (RNG)
  //
  // If all else fails, use Math.random().  It's fast, but is of unspecified
  // quality.
  var rnds = new Array(16);

  module.exports = function mathRNG() {
    for (var i = 0, r; i < 16; i++) {
      if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
      rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
    }

    return rnds;
  };
}


/***/ }),
/* 120 */
/***/ (function(module, exports) {

/**
 * Convert array of 16 byte values to UUID string format of the form:
 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
 */
var byteToHex = [];
for (var i = 0; i < 256; ++i) {
  byteToHex[i] = (i + 0x100).toString(16).substr(1);
}

function bytesToUuid(buf, offset) {
  var i = offset || 0;
  var bth = byteToHex;
  // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
  return ([
    bth[buf[i++]], bth[buf[i++]],
    bth[buf[i++]], bth[buf[i++]], '-',
    bth[buf[i++]], bth[buf[i++]], '-',
    bth[buf[i++]], bth[buf[i++]], '-',
    bth[buf[i++]], bth[buf[i++]], '-',
    bth[buf[i++]], bth[buf[i++]],
    bth[buf[i++]], bth[buf[i++]],
    bth[buf[i++]], bth[buf[i++]]
  ]).join('');
}

module.exports = bytesToUuid;


/***/ }),
/* 121 */
/***/ (function(module, exports) {

function _extends() {
  module.exports = _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);
}

module.exports = _extends;

/***/ }),
/* 122 */
/***/ (function(module, exports) {

function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) {
    for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
      arr2[i] = arr[i];
    }

    return arr2;
  }
}

module.exports = _arrayWithoutHoles;

/***/ }),
/* 123 */
/***/ (function(module, exports) {

function _iterableToArray(iter) {
  if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}

module.exports = _iterableToArray;

/***/ }),
/* 124 */
/***/ (function(module, exports) {

function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance");
}

module.exports = _nonIterableSpread;

/***/ }),
/* 125 */
/***/ (function(module, exports, __webpack_require__) {

var content = __webpack_require__(126);

if (typeof content === 'string') {
  content = [[module.i, content, '']];
}

var options = {}

options.insert = "head";
options.singleton = false;

var update = __webpack_require__(128)(content, options);

if (content.locals) {
  module.exports = content.locals;
}


/***/ }),
/* 126 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(127)(false);
// Module
exports.push([module.i, ".ReactTable{position:relative;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;border:1px solid rgba(0,0,0,0.1)}.ReactTable *{box-sizing:border-box}.ReactTable .rt-table{-webkit-box-flex:1;-ms-flex:auto 1;flex:auto 1;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;-webkit-box-align:stretch;-ms-flex-align:stretch;align-items:stretch;width:100%;border-collapse:collapse;overflow:auto}.ReactTable .rt-thead{-webkit-box-flex:1;-ms-flex:1 0 auto;flex:1 0 auto;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.ReactTable .rt-thead.-headerGroups{background:rgba(0,0,0,0.03);border-bottom:1px solid rgba(0,0,0,0.05)}.ReactTable .rt-thead.-filters{border-bottom:1px solid rgba(0,0,0,0.05)}.ReactTable .rt-thead.-filters input,.ReactTable .rt-thead.-filters select{border:1px solid rgba(0,0,0,0.1);background:#fff;padding:5px 7px;font-size:inherit;border-radius:3px;font-weight:normal;outline-width:0}.ReactTable .rt-thead.-filters .rt-th{border-right:1px solid rgba(0,0,0,0.02)}.ReactTable .rt-thead.-header{box-shadow:0 2px 15px 0 rgba(0,0,0,0.15)}.ReactTable .rt-thead .rt-tr{text-align:center}.ReactTable .rt-thead .rt-th,.ReactTable .rt-thead .rt-td{padding:5px 5px;line-height:normal;position:relative;border-right:1px solid rgba(0,0,0,0.05);transition:box-shadow 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);box-shadow:inset 0 0 0 0 transparent}.ReactTable .rt-thead .rt-th.-sort-asc,.ReactTable .rt-thead .rt-td.-sort-asc{box-shadow:inset 0 3px 0 0 rgba(0,0,0,0.6)}.ReactTable .rt-thead .rt-th.-sort-desc,.ReactTable .rt-thead .rt-td.-sort-desc{box-shadow:inset 0 -3px 0 0 rgba(0,0,0,0.6)}.ReactTable .rt-thead .rt-th.-cursor-pointer,.ReactTable .rt-thead .rt-td.-cursor-pointer{cursor:pointer}.ReactTable .rt-thead .rt-th:last-child,.ReactTable .rt-thead .rt-td:last-child{border-right:0}.ReactTable .rt-thead .rt-th:focus{outline-width:0}.ReactTable .rt-thead .rt-resizable-header{overflow:visible}.ReactTable .rt-thead .rt-resizable-header:last-child{overflow:hidden}.ReactTable .rt-thead .rt-resizable-header-content{overflow:hidden;text-overflow:ellipsis}.ReactTable .rt-thead .rt-header-pivot{border-right-color:#f7f7f7}.ReactTable .rt-thead .rt-header-pivot:after,.ReactTable .rt-thead .rt-header-pivot:before{left:100%;top:50%;border:solid transparent;content:\" \";height:0;width:0;position:absolute;pointer-events:none}.ReactTable .rt-thead .rt-header-pivot:after{border-color:rgba(255,255,255,0);border-left-color:#fff;border-width:8px;margin-top:-8px}.ReactTable .rt-thead .rt-header-pivot:before{border-color:rgba(102,102,102,0);border-left-color:#f7f7f7;border-width:10px;margin-top:-10px}.ReactTable .rt-tbody{-webkit-box-flex:99999;-ms-flex:99999 1 auto;flex:99999 1 auto;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;overflow:auto}.ReactTable .rt-tbody .rt-tr-group{border-bottom:solid 1px rgba(0,0,0,0.05)}.ReactTable .rt-tbody .rt-tr-group:last-child{border-bottom:0}.ReactTable .rt-tbody .rt-td{border-right:1px solid rgba(0,0,0,0.02)}.ReactTable .rt-tbody .rt-td:last-child{border-right:0}.ReactTable .rt-tbody .rt-expandable{cursor:pointer;text-overflow:clip}.ReactTable .rt-tr-group{-webkit-box-flex:1;-ms-flex:1 0 auto;flex:1 0 auto;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;-webkit-box-align:stretch;-ms-flex-align:stretch;align-items:stretch}.ReactTable .rt-tr{-webkit-box-flex:1;-ms-flex:1 0 auto;flex:1 0 auto;display:-webkit-inline-box;display:-ms-inline-flexbox;display:inline-flex}.ReactTable .rt-th,.ReactTable .rt-td{-webkit-box-flex:1;-ms-flex:1 0 0px;flex:1 0 0;white-space:nowrap;text-overflow:ellipsis;padding:7px 5px;overflow:hidden;transition:.3s ease;transition-property:width,min-width,padding,opacity}.ReactTable .rt-th.-hidden,.ReactTable .rt-td.-hidden{width:0 !important;min-width:0 !important;padding:0 !important;border:0 !important;opacity:0 !important}.ReactTable .rt-expander{display:inline-block;position:relative;margin:0;color:transparent;margin:0 10px}.ReactTable .rt-expander:after{content:'';position:absolute;width:0;height:0;top:50%;left:50%;-webkit-transform:translate(-50%, -50%) rotate(-90deg);transform:translate(-50%, -50%) rotate(-90deg);border-left:5.04px solid transparent;border-right:5.04px solid transparent;border-top:7px solid rgba(0,0,0,0.8);transition:all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);cursor:pointer}.ReactTable .rt-expander.-open:after{-webkit-transform:translate(-50%, -50%) rotate(0);transform:translate(-50%, -50%) rotate(0)}.ReactTable .rt-resizer{display:inline-block;position:absolute;width:36px;top:0;bottom:0;right:-18px;cursor:col-resize;z-index:10}.ReactTable .rt-tfoot{-webkit-box-flex:1;-ms-flex:1 0 auto;flex:1 0 auto;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;box-shadow:0 0 15px 0 rgba(0,0,0,0.15)}.ReactTable .rt-tfoot .rt-td{border-right:1px solid rgba(0,0,0,0.05)}.ReactTable .rt-tfoot .rt-td:last-child{border-right:0}.ReactTable.-striped .rt-tr.-odd{background:rgba(0,0,0,0.03)}.ReactTable.-highlight .rt-tbody .rt-tr:not(.-padRow):hover{background:rgba(0,0,0,0.05)}.ReactTable .-pagination{z-index:1;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-pack:justify;-ms-flex-pack:justify;justify-content:space-between;-webkit-box-align:stretch;-ms-flex-align:stretch;align-items:stretch;-ms-flex-wrap:wrap;flex-wrap:wrap;padding:3px;box-shadow:0 0 15px 0 rgba(0,0,0,0.1);border-top:2px solid rgba(0,0,0,0.1)}.ReactTable .-pagination input,.ReactTable .-pagination select{border:1px solid rgba(0,0,0,0.1);background:#fff;padding:5px 7px;font-size:inherit;border-radius:3px;font-weight:normal;outline-width:0}.ReactTable .-pagination .-btn{-webkit-appearance:none;-moz-appearance:none;appearance:none;display:block;width:100%;height:100%;border:0;border-radius:3px;padding:6px;font-size:1em;color:rgba(0,0,0,0.6);background:rgba(0,0,0,0.1);transition:all .1s ease;cursor:pointer;outline-width:0}.ReactTable .-pagination .-btn[disabled]{opacity:.5;cursor:default}.ReactTable .-pagination .-btn:not([disabled]):hover{background:rgba(0,0,0,0.3);color:#fff}.ReactTable .-pagination .-previous,.ReactTable .-pagination .-next{-webkit-box-flex:1;-ms-flex:1;flex:1;text-align:center}.ReactTable .-pagination .-center{-webkit-box-flex:1.5;-ms-flex:1.5;flex:1.5;text-align:center;margin-bottom:0;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row;-ms-flex-wrap:wrap;flex-wrap:wrap;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-ms-flex-pack:distribute;justify-content:space-around}.ReactTable .-pagination .-pageInfo{display:inline-block;margin:3px 10px;white-space:nowrap}.ReactTable .-pagination .-pageJump{display:inline-block}.ReactTable .-pagination .-pageJump input{width:70px;text-align:center}.ReactTable .-pagination .-pageSizeOptions{margin:3px 10px}.ReactTable .rt-noData{display:block;position:absolute;left:50%;top:50%;-webkit-transform:translate(-50%, -50%);transform:translate(-50%, -50%);background:rgba(255,255,255,0.8);transition:all .3s ease;z-index:1;pointer-events:none;padding:20px;color:rgba(0,0,0,0.5)}.ReactTable .-loading{display:block;position:absolute;left:0;right:0;top:0;bottom:0;background:rgba(255,255,255,0.8);transition:all .3s ease;z-index:-1;opacity:0;pointer-events:none}.ReactTable .-loading>div{position:absolute;display:block;text-align:center;width:100%;top:50%;left:0;font-size:15px;color:rgba(0,0,0,0.6);-webkit-transform:translateY(-52%);transform:translateY(-52%);transition:all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94)}.ReactTable .-loading.-active{opacity:1;z-index:2;pointer-events:all}.ReactTable .-loading.-active>div{-webkit-transform:translateY(50%);transform:translateY(50%)}.ReactTable .rt-resizing .rt-th,.ReactTable .rt-resizing .rt-td{transition:none !important;cursor:col-resize;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}\n", ""]);


/***/ }),
/* 127 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/*
  MIT License http://www.opensource.org/licenses/mit-license.php
  Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
// eslint-disable-next-line func-names
module.exports = function (useSourceMap) {
  var list = []; // return the list of modules as css string

  list.toString = function toString() {
    return this.map(function (item) {
      var content = cssWithMappingToString(item, useSourceMap);

      if (item[2]) {
        return "@media ".concat(item[2], "{").concat(content, "}");
      }

      return content;
    }).join('');
  }; // import a list of modules into the list
  // eslint-disable-next-line func-names


  list.i = function (modules, mediaQuery) {
    if (typeof modules === 'string') {
      // eslint-disable-next-line no-param-reassign
      modules = [[null, modules, '']];
    }

    var alreadyImportedModules = {};

    for (var i = 0; i < this.length; i++) {
      // eslint-disable-next-line prefer-destructuring
      var id = this[i][0];

      if (id != null) {
        alreadyImportedModules[id] = true;
      }
    }

    for (var _i = 0; _i < modules.length; _i++) {
      var item = modules[_i]; // skip already imported module
      // this implementation is not 100% perfect for weird media query combinations
      // when a module is imported multiple times with different media queries.
      // I hope this will never occur (Hey this way we have smaller bundles)

      if (item[0] == null || !alreadyImportedModules[item[0]]) {
        if (mediaQuery && !item[2]) {
          item[2] = mediaQuery;
        } else if (mediaQuery) {
          item[2] = "(".concat(item[2], ") and (").concat(mediaQuery, ")");
        }

        list.push(item);
      }
    }
  };

  return list;
};

function cssWithMappingToString(item, useSourceMap) {
  var content = item[1] || ''; // eslint-disable-next-line prefer-destructuring

  var cssMapping = item[3];

  if (!cssMapping) {
    return content;
  }

  if (useSourceMap && typeof btoa === 'function') {
    var sourceMapping = toComment(cssMapping);
    var sourceURLs = cssMapping.sources.map(function (source) {
      return "/*# sourceURL=".concat(cssMapping.sourceRoot).concat(source, " */");
    });
    return [content].concat(sourceURLs).concat([sourceMapping]).join('\n');
  }

  return [content].join('\n');
} // Adapted from convert-source-map (MIT)


function toComment(sourceMap) {
  // eslint-disable-next-line no-undef
  var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
  var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
  return "/*# ".concat(data, " */");
}

/***/ }),
/* 128 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var stylesInDom = {};

var isOldIE = function isOldIE() {
  var memo;
  return function memorize() {
    if (typeof memo === 'undefined') {
      // Test for IE <= 9 as proposed by Browserhacks
      // @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805
      // Tests for existence of standard globals is to allow style-loader
      // to operate correctly into non-standard environments
      // @see https://github.com/webpack-contrib/style-loader/issues/177
      memo = Boolean(window && document && document.all && !window.atob);
    }

    return memo;
  };
}();

var getTarget = function getTarget() {
  var memo = {};
  return function memorize(target) {
    if (typeof memo[target] === 'undefined') {
      var styleTarget = document.querySelector(target); // Special case to return head of iframe instead of iframe itself

      if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {
        try {
          // This will throw an exception if access to iframe is blocked
          // due to cross-origin restrictions
          styleTarget = styleTarget.contentDocument.head;
        } catch (e) {
          // istanbul ignore next
          styleTarget = null;
        }
      }

      memo[target] = styleTarget;
    }

    return memo[target];
  };
}();

function listToStyles(list, options) {
  var styles = [];
  var newStyles = {};

  for (var i = 0; i < list.length; i++) {
    var item = list[i];
    var id = options.base ? item[0] + options.base : item[0];
    var css = item[1];
    var media = item[2];
    var sourceMap = item[3];
    var part = {
      css: css,
      media: media,
      sourceMap: sourceMap
    };

    if (!newStyles[id]) {
      styles.push(newStyles[id] = {
        id: id,
        parts: [part]
      });
    } else {
      newStyles[id].parts.push(part);
    }
  }

  return styles;
}

function addStylesToDom(styles, options) {
  for (var i = 0; i < styles.length; i++) {
    var item = styles[i];
    var domStyle = stylesInDom[item.id];
    var j = 0;

    if (domStyle) {
      domStyle.refs++;

      for (; j < domStyle.parts.length; j++) {
        domStyle.parts[j](item.parts[j]);
      }

      for (; j < item.parts.length; j++) {
        domStyle.parts.push(addStyle(item.parts[j], options));
      }
    } else {
      var parts = [];

      for (; j < item.parts.length; j++) {
        parts.push(addStyle(item.parts[j], options));
      }

      stylesInDom[item.id] = {
        id: item.id,
        refs: 1,
        parts: parts
      };
    }
  }
}

function insertStyleElement(options) {
  var style = document.createElement('style');

  if (typeof options.attributes.nonce === 'undefined') {
    var nonce =  true ? __webpack_require__.nc : undefined;

    if (nonce) {
      options.attributes.nonce = nonce;
    }
  }

  Object.keys(options.attributes).forEach(function (key) {
    style.setAttribute(key, options.attributes[key]);
  });

  if (typeof options.insert === 'function') {
    options.insert(style);
  } else {
    var target = getTarget(options.insert || 'head');

    if (!target) {
      throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");
    }

    target.appendChild(style);
  }

  return style;
}

function removeStyleElement(style) {
  // istanbul ignore if
  if (style.parentNode === null) {
    return false;
  }

  style.parentNode.removeChild(style);
}
/* istanbul ignore next  */


var replaceText = function replaceText() {
  var textStore = [];
  return function replace(index, replacement) {
    textStore[index] = replacement;
    return textStore.filter(Boolean).join('\n');
  };
}();

function applyToSingletonTag(style, index, remove, obj) {
  var css = remove ? '' : obj.css; // For old IE

  /* istanbul ignore if  */

  if (style.styleSheet) {
    style.styleSheet.cssText = replaceText(index, css);
  } else {
    var cssNode = document.createTextNode(css);
    var childNodes = style.childNodes;

    if (childNodes[index]) {
      style.removeChild(childNodes[index]);
    }

    if (childNodes.length) {
      style.insertBefore(cssNode, childNodes[index]);
    } else {
      style.appendChild(cssNode);
    }
  }
}

function applyToTag(style, options, obj) {
  var css = obj.css;
  var media = obj.media;
  var sourceMap = obj.sourceMap;

  if (media) {
    style.setAttribute('media', media);
  }

  if (sourceMap && btoa) {
    css += "\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))), " */");
  } // For old IE

  /* istanbul ignore if  */


  if (style.styleSheet) {
    style.styleSheet.cssText = css;
  } else {
    while (style.firstChild) {
      style.removeChild(style.firstChild);
    }

    style.appendChild(document.createTextNode(css));
  }
}

var singleton = null;
var singletonCounter = 0;

function addStyle(obj, options) {
  var style;
  var update;
  var remove;

  if (options.singleton) {
    var styleIndex = singletonCounter++;
    style = singleton || (singleton = insertStyleElement(options));
    update = applyToSingletonTag.bind(null, style, styleIndex, false);
    remove = applyToSingletonTag.bind(null, style, styleIndex, true);
  } else {
    style = insertStyleElement(options);
    update = applyToTag.bind(null, style, options);

    remove = function remove() {
      removeStyleElement(style);
    };
  }

  update(obj);
  return function updateStyle(newObj) {
    if (newObj) {
      if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) {
        return;
      }

      update(obj = newObj);
    } else {
      remove();
    }
  };
}

module.exports = function (list, options) {
  options = options || {};
  options.attributes = typeof options.attributes === 'object' ? options.attributes : {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
  // tags it will allow on a page

  if (!options.singleton && typeof options.singleton !== 'boolean') {
    options.singleton = isOldIE();
  }

  var styles = listToStyles(list, options);
  addStylesToDom(styles, options);
  return function update(newList) {
    var mayRemove = [];

    for (var i = 0; i < styles.length; i++) {
      var item = styles[i];
      var domStyle = stylesInDom[item.id];

      if (domStyle) {
        domStyle.refs--;
        mayRemove.push(domStyle);
      }
    }

    if (newList) {
      var newStyles = listToStyles(newList, options);
      addStylesToDom(newStyles, options);
    }

    for (var _i = 0; _i < mayRemove.length; _i++) {
      var _domStyle = mayRemove[_i];

      if (_domStyle.refs === 0) {
        for (var j = 0; j < _domStyle.parts.length; j++) {
          _domStyle.parts[j]();
        }

        delete stylesInDom[_domStyle.id];
      }
    }
  };
};

/***/ }),
/* 129 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
var src_namespaceObject = {};
__webpack_require__.r(src_namespaceObject);
__webpack_require__.d(src_namespaceObject, "easeLinear", function() { return linear_linear; });
__webpack_require__.d(src_namespaceObject, "easeQuad", function() { return quadInOut; });
__webpack_require__.d(src_namespaceObject, "easeQuadIn", function() { return quadIn; });
__webpack_require__.d(src_namespaceObject, "easeQuadOut", function() { return quadOut; });
__webpack_require__.d(src_namespaceObject, "easeQuadInOut", function() { return quadInOut; });
__webpack_require__.d(src_namespaceObject, "easeCubic", function() { return cubic_cubicInOut; });
__webpack_require__.d(src_namespaceObject, "easeCubicIn", function() { return cubicIn; });
__webpack_require__.d(src_namespaceObject, "easeCubicOut", function() { return cubicOut; });
__webpack_require__.d(src_namespaceObject, "easeCubicInOut", function() { return cubic_cubicInOut; });
__webpack_require__.d(src_namespaceObject, "easePoly", function() { return polyInOut; });
__webpack_require__.d(src_namespaceObject, "easePolyIn", function() { return polyIn; });
__webpack_require__.d(src_namespaceObject, "easePolyOut", function() { return polyOut; });
__webpack_require__.d(src_namespaceObject, "easePolyInOut", function() { return polyInOut; });
__webpack_require__.d(src_namespaceObject, "easeSin", function() { return sinInOut; });
__webpack_require__.d(src_namespaceObject, "easeSinIn", function() { return sinIn; });
__webpack_require__.d(src_namespaceObject, "easeSinOut", function() { return sinOut; });
__webpack_require__.d(src_namespaceObject, "easeSinInOut", function() { return sinInOut; });
__webpack_require__.d(src_namespaceObject, "easeExp", function() { return expInOut; });
__webpack_require__.d(src_namespaceObject, "easeExpIn", function() { return expIn; });
__webpack_require__.d(src_namespaceObject, "easeExpOut", function() { return expOut; });
__webpack_require__.d(src_namespaceObject, "easeExpInOut", function() { return expInOut; });
__webpack_require__.d(src_namespaceObject, "easeCircle", function() { return circleInOut; });
__webpack_require__.d(src_namespaceObject, "easeCircleIn", function() { return circleIn; });
__webpack_require__.d(src_namespaceObject, "easeCircleOut", function() { return circleOut; });
__webpack_require__.d(src_namespaceObject, "easeCircleInOut", function() { return circleInOut; });
__webpack_require__.d(src_namespaceObject, "easeBounce", function() { return bounceOut; });
__webpack_require__.d(src_namespaceObject, "easeBounceIn", function() { return bounceIn; });
__webpack_require__.d(src_namespaceObject, "easeBounceOut", function() { return bounceOut; });
__webpack_require__.d(src_namespaceObject, "easeBounceInOut", function() { return bounceInOut; });
__webpack_require__.d(src_namespaceObject, "easeBack", function() { return backInOut; });
__webpack_require__.d(src_namespaceObject, "easeBackIn", function() { return backIn; });
__webpack_require__.d(src_namespaceObject, "easeBackOut", function() { return backOut; });
__webpack_require__.d(src_namespaceObject, "easeBackInOut", function() { return backInOut; });
__webpack_require__.d(src_namespaceObject, "easeElastic", function() { return elastic_elasticOut; });
__webpack_require__.d(src_namespaceObject, "easeElasticIn", function() { return elasticIn; });
__webpack_require__.d(src_namespaceObject, "easeElasticOut", function() { return elastic_elasticOut; });
__webpack_require__.d(src_namespaceObject, "easeElasticInOut", function() { return elasticInOut; });

// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__(0);
var react_default = /*#__PURE__*/__webpack_require__.n(react);

// EXTERNAL MODULE: ./node_modules/react-dom/index.js
var react_dom = __webpack_require__(10);
var react_dom_default = /*#__PURE__*/__webpack_require__.n(react_dom);

// EXTERNAL MODULE: ./node_modules/@material-ui/core/esm/styles/createMuiTheme.js + 15 modules
var createMuiTheme = __webpack_require__(76);

// EXTERNAL MODULE: ./node_modules/@material-ui/styles/node_modules/@babel/runtime/helpers/esm/extends.js
var esm_extends = __webpack_require__(17);

// EXTERNAL MODULE: ./node_modules/prop-types/index.js
var prop_types = __webpack_require__(1);
var prop_types_default = /*#__PURE__*/__webpack_require__.n(prop_types);

// EXTERNAL MODULE: ./node_modules/@material-ui/styles/esm/useTheme/ThemeContext.js
var ThemeContext = __webpack_require__(36);

// EXTERNAL MODULE: ./node_modules/@material-ui/styles/esm/useTheme/useTheme.js
var useTheme = __webpack_require__(154);

// EXTERNAL MODULE: ./node_modules/@material-ui/styles/esm/ThemeProvider/nested.js
var nested = __webpack_require__(37);

// CONCATENATED MODULE: ./node_modules/@material-ui/styles/esm/ThemeProvider/ThemeProvider.js






 // To support composition of theme.

function mergeOuterLocalTheme(outerTheme, localTheme) {
  if (typeof localTheme === 'function') {
    var mergedTheme = localTheme(outerTheme);

    if (false) {}

    return mergedTheme;
  }

  return Object(esm_extends["a" /* default */])({}, outerTheme, {}, localTheme);
}
/**
 * This component takes a `theme` prop.
 * It makes the `theme` available down the React tree thanks to React context.
 * This component should preferably be used at **the root of your component tree**.
 */


function ThemeProvider(props) {
  var children = props.children,
      localTheme = props.theme;
  var outerTheme = Object(useTheme["a" /* default */])();

  if (false) {}

  var theme = react_default.a.useMemo(function () {
    var output = outerTheme === null ? localTheme : mergeOuterLocalTheme(outerTheme, localTheme);

    if (output != null) {
      output[nested["a" /* default */]] = outerTheme !== null;
    }

    return output;
  }, [localTheme, outerTheme]);
  return react_default.a.createElement(ThemeContext["a" /* default */].Provider, {
    value: theme
  }, children);
}

 false ? undefined : void 0;

if (false) {}

/* harmony default export */ var ThemeProvider_ThemeProvider = (ThemeProvider);
// CONCATENATED MODULE: ./src/themes/Colors.js
var Colors = {
  // Signature Colors
  QLIK_GREEN: '#009845',
  QLIK_GREY: '#54565A',
  // Flood Colors
  TANZANITE: '#009845',
  SLATE: '#244B5A',
  TURQUOISE: '#006580',
  TURQUOISE_LIGHT: '#0180a3',
  TURQUOISE_DARK: '#00485b',
  AQUAMARINE: '#10CFC9',
  WINE: '#4c0038',
  WINE_LIGHT: '#c12e9a',
  WINE_DARK: '#870064',
  AMETHYST: '#655DC6',
  STONE: '#C4CFDA',
  // Supporting Colors
  SAPPHIRE: '#005CB9',
  EMERALD: '#006937',
  EMERALD_LIGHT: '#008243',
  EMERALD_DARK: '#004f28',
  RUBY: '#E7004C',
  // Highlight Colors
  CORAL: '#FF8E9F',
  TOPAZ: '#FFC72A',
  PERIDOT: '#C2D500',
  // GREYs
  // https://www.w3schools.com/colors/colors_picker.asp
  GREY_0: '#000000',
  GREY_5: '#0d0d0d',
  GREY_10: '#1a1a1a',
  GREY_15: '#262626',
  GREY_20: '#333333',
  GREY_25: '#404040',
  GREY_30: '#4d4d4d',
  GREY_35: '#595959',
  GREY_40: '#666666',
  GREY_45: '#737373',
  GREY_50: '#808080',
  GREY_55: '#8c8c8c',
  GREY_60: '#999999',
  GREY_65: '#a6a6a6',
  GREY_70: '#b3b3b3',
  GREY_75: '#bfbfbf',
  GREY_80: '#cccccc',
  GREY_85: '#d9d9d9',
  GREY_90: '#e6e6e6',
  GREY_95: '#f2f2f2',
  GREY_100: '#ffffff'
};
/* harmony default export */ var themes_Colors = (Colors);
// CONCATENATED MODULE: ./src/themes/Light.js

 // const theme = {

var Light_theme = Object(createMuiTheme["a" /* default */])({
  palette: {
    primary: {
      light: themes_Colors.TURQUOISE_LIGHT,
      main: themes_Colors.TURQUOISE,
      dark: themes_Colors.TURQUOISE_DARK,
      contrastText: '#fff'
    },
    secondary: {
      light: themes_Colors.WINE_LIGHT,
      main: themes_Colors.WINE,
      dark: themes_Colors.WINE_DARK,
      contrastText: '#fff'
    },
    success: {
      light: themes_Colors.EMERALD,
      main: themes_Colors.EMERALD,
      dark: themes_Colors.EMERALD,
      contrastText: '#fff'
    },
    error: {
      light: themes_Colors.RUBY,
      main: themes_Colors.RUBY,
      dark: themes_Colors.RUBY,
      contrastText: '#fff'
    },
    info: {
      // SAPPHIRE
      light: themes_Colors.AQUAMARINE,
      main: themes_Colors.AQUAMARINE,
      dark: themes_Colors.AQUAMARINE,
      contrastText: '#fff'
    }
  },
  shape: {
    borderRadius: 0
  },
  overrides: {
    MuiButton: {
      text: {
        borderRadius: 3,
        borderColor: '#FFFFFF',
        border: 5
      }
    },
    MuiListItemText: {
      primary: {
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        display: 'block',
        fontSize: 12
      }
    },
    MuiMenuItem: {
      root: {
        borderBottom: "1px solid ".concat(themes_Colors.GREY_80),
        fontSize: 12,
        '&.selected': {
          backgroundColor: themes_Colors.QLIK_GREEN,
          color: '#FFF',
          borderBottom: "1px solid ".concat(themes_Colors.GREY_100),
          '&:hover': {
            backgroundColor: themes_Colors.QLIK_GREEN
          },
          '& .MuiListItemIcon-root': {
            minWidth: 10,
            '& .MuiSvgIcon-root': {
              fill: '#FFF',
              width: '0.5em',
              height: '0.5em'
            }
          }
        },
        '&.excluded': {
          backgroundColor: themes_Colors.GREY_80,
          color: '#000',
          borderBottom: "1px solid ".concat(themes_Colors.GREY_100),
          '&:hover': {
            color: '#FFF',
            backgroundColor: themes_Colors.QLIK_GREEN
          }
        }
      }
    },
    MuiSlider: {
      root: {
        height: 8
      },
      thumb: {
        height: 24,
        width: 'auto',
        padding: 5,
        borderRadius: 0,
        backgroundColor: '#fff',
        border: '2px solid currentColor',
        marginTop: -10,
        marginLeft: -12,
        '&:focus,&:hover,&$active': {
          boxShadow: 'inherit'
        },
        '& .bar': {
          height: 10,
          width: 1,
          backgroundColor: 'currentColor',
          marginLeft: 1,
          marginRight: 1
        }
      },
      active: {},
      valueLabel: {
        left: 'calc(-50% + 4px)'
      },
      track: {
        height: 5,
        borderRadius: 0
      },
      rail: {
        height: 5,
        borderRadius: 0
      }
    },
    MuiList: {
      root: {
        maxHeight: 310,
        overflowY: 'scroll'
      },
      padding: {
        paddingTop: 0,
        paddingBottom: 0
      }
    },
    MuiListItem: {
      root: {
        borderBottom: "1px solid ".concat(themes_Colors.GREY_85)
      }
    }
  }
});
/* harmony default export */ var Light = (Light_theme);
// CONCATENATED MODULE: ./src/themes/Dark.js
// https://material-ui.com/customization/default-theme/

var Dark_theme = {
  palette: {
    common: {
      black: '#000',
      white: '#fff'
    },
    type: 'dark',
    primary: {
      light: themes_Colors.SLATE_LIGHT,
      main: themes_Colors.SLATE,
      dark: themes_Colors.SLATE_DARK,
      contrastText: '#fff'
    },
    secondary: {
      light: themes_Colors.WINE_LIGHT,
      main: themes_Colors.WINE,
      dark: themes_Colors.WINE_DARK,
      contrastText: '#fff'
    },
    error: {
      light: '#e57373',
      main: '#f44336',
      dark: '#d32f2f',
      contrastText: '#fff'
    },
    warning: {
      light: '#ffb74d',
      main: '#ff9800',
      dark: '#f57c00',
      contrastText: 'rgba(0, 0, 0, 0.87)'
    },
    info: {
      light: '#64b5f6',
      main: '#2196f3',
      dark: '#1976d2',
      contrastText: '#fff'
    },
    success: {
      light: '#81c784',
      main: '#4caf50',
      dark: '#388e3c',
      contrastText: 'rgba(0, 0, 0, 0.87)'
    },
    contrastThreshold: 3,
    tonalOffset: 0.2,
    text: {
      primary: '#fff',
      secondary: 'rgba(255, 255, 255, 0.7)',
      disabled: 'rgba(255, 255, 255, 0.5)',
      hint: 'rgba(255, 255, 255, 0.5)',
      icon: 'rgba(255, 255, 255, 0.5)'
    },
    divider: 'rgba(255, 255, 255, 0.12)',
    background: {
      paper: '#424242',
      "default": '#303030'
    },
    action: {
      active: '#fff',
      hover: 'rgba(255, 255, 255, 0.08)',
      hoverOpacity: 0.08,
      selected: 'rgba(255, 255, 255, 0.16)',
      selectedOpacity: 0.16,
      disabled: 'rgba(255, 255, 255, 0.3)',
      disabledBackground: 'rgba(255, 255, 255, 0.12)'
    }
  },
  shadows: ['none', '0px 2px 1px -1px rgba(0,0,0,0.2),0px 1px 1px 0px rgba(0,0,0,0.14),0px 1px 3px 0px rgba(0,0,0,0.12)', '0px 3px 1px -2px rgba(0,0,0,0.2),0px 2px 2px 0px rgba(0,0,0,0.14),0px 1px 5px 0px rgba(0,0,0,0.12)', '0px 3px 3px -2px rgba(0,0,0,0.2),0px 3px 4px 0px rgba(0,0,0,0.14),0px 1px 8px 0px rgba(0,0,0,0.12)', '0px 2px 4px -1px rgba(0,0,0,0.2),0px 4px 5px 0px rgba(0,0,0,0.14),0px 1px 10px 0px rgba(0,0,0,0.12)', '0px 3px 5px -1px rgba(0,0,0,0.2),0px 5px 8px 0px rgba(0,0,0,0.14),0px 1px 14px 0px rgba(0,0,0,0.12)', '0px 3px 5px -1px rgba(0,0,0,0.2),0px 6px 10px 0px rgba(0,0,0,0.14),0px 1px 18px 0px rgba(0,0,0,0.12)', '0px 4px 5px -2px rgba(0,0,0,0.2),0px 7px 10px 1px rgba(0,0,0,0.14),0px 2px 16px 1px rgba(0,0,0,0.12)', '0px 5px 5px -3px rgba(0,0,0,0.2),0px 8px 10px 1px rgba(0,0,0,0.14),0px 3px 14px 2px rgba(0,0,0,0.12)', '0px 5px 6px -3px rgba(0,0,0,0.2),0px 9px 12px 1px rgba(0,0,0,0.14),0px 3px 16px 2px rgba(0,0,0,0.12)', '0px 6px 6px -3px rgba(0,0,0,0.2),0px 10px 14px 1px rgba(0,0,0,0.14),0px 4px 18px 3px rgba(0,0,0,0.12)', '0px 6px 7px -4px rgba(0,0,0,0.2),0px 11px 15px 1px rgba(0,0,0,0.14),0px 4px 20px 3px rgba(0,0,0,0.12)', '0px 7px 8px -4px rgba(0,0,0,0.2),0px 12px 17px 2px rgba(0,0,0,0.14),0px 5px 22px 4px rgba(0,0,0,0.12)', '0px 7px 8px -4px rgba(0,0,0,0.2),0px 13px 19px 2px rgba(0,0,0,0.14),0px 5px 24px 4px rgba(0,0,0,0.12)', '0px 7px 9px -4px rgba(0,0,0,0.2),0px 14px 21px 2px rgba(0,0,0,0.14),0px 5px 26px 4px rgba(0,0,0,0.12)', '0px 8px 9px -5px rgba(0,0,0,0.2),0px 15px 22px 2px rgba(0,0,0,0.14),0px 6px 28px 5px rgba(0,0,0,0.12)', '0px 8px 10px -5px rgba(0,0,0,0.2),0px 16px 24px 2px rgba(0,0,0,0.14),0px 6px 30px 5px rgba(0,0,0,0.12)', '0px 8px 11px -5px rgba(0,0,0,0.2),0px 17px 26px 2px rgba(0,0,0,0.14),0px 6px 32px 5px rgba(0,0,0,0.12)', '0px 9px 11px -5px rgba(0,0,0,0.2),0px 18px 28px 2px rgba(0,0,0,0.14),0px 7px 34px 6px rgba(0,0,0,0.12)', '0px 9px 12px -6px rgba(0,0,0,0.2),0px 19px 29px 2px rgba(0,0,0,0.14),0px 7px 36px 6px rgba(0,0,0,0.12)', '0px 10px 13px -6px rgba(0,0,0,0.2),0px 20px 31px 3px rgba(0,0,0,0.14),0px 8px 38px 7px rgba(0,0,0,0.12)', '0px 10px 13px -6px rgba(0,0,0,0.2),0px 21px 33px 3px rgba(0,0,0,0.14),0px 8px 40px 7px rgba(0,0,0,0.12)', '0px 10px 14px -6px rgba(0,0,0,0.2),0px 22px 35px 3px rgba(0,0,0,0.14),0px 8px 42px 7px rgba(0,0,0,0.12)', '0px 11px 14px -7px rgba(0,0,0,0.2),0px 23px 36px 3px rgba(0,0,0,0.14),0px 9px 44px 8px rgba(0,0,0,0.12)', '0px 11px 15px -7px rgba(0,0,0,0.2),0px 24px 38px 3px rgba(0,0,0,0.14),0px 9px 46px 8px rgba(0,0,0,0.12)'],
  shape: {
    borderRadius: 0
  },
  overrides: {
    MuiButton: {
      text: {
        borderRadius: 3,
        borderColor: '#FFFFFF',
        border: 5
      }
    },
    MuiSlider: {
      root: {
        height: 8
      },
      thumb: {
        height: 24,
        width: 'auto',
        padding: 5,
        borderRadius: 0,
        // backgroundColor: 'currentColor',
        backgroundColor: '#fff',
        border: '2px solid currentColor',
        marginTop: -10,
        marginLeft: -12,
        '&:focus,&:hover,&$active': {
          boxShadow: 'inherit'
        },
        '& .bar': {
          height: 10,
          width: 1,
          opacity: 0.5,
          marginLeft: 1,
          marginRight: 1
        }
      },
      active: {},
      valueLabel: {
        left: 'calc(-50% + 4px)'
      },
      track: {
        height: 5,
        borderRadius: 0
      },
      rail: {
        height: 5,
        borderRadius: 0
      }
    },
    MuiList: {
      padding: {
        paddingTop: 0,
        paddingBottom: 0
      }
    },
    MuiListItem: {
      root: {
        borderBottom: "1px solid ".concat(themes_Colors.GREY_30)
      }
    }
  }
};
/* harmony default export */ var Dark = (Dark_theme);
// CONCATENATED MODULE: ./src/themes/themes.js



var QdtThemes = {
  Light: Light,
  Dark: Dark,
  Colors: themes_Colors
};
/* harmony default export */ var themes = (QdtThemes);

// CONCATENATED MODULE: ./src/qdtNova.jsx
 //eslint-disable-line

 //eslint-disable-line


 // TODO: Support turning components into extensions
// TODO: Return an object containing the current app, layout, model, element, and instance of component

/* harmony default export */ var qdtNova = (function (supernova) {
  return function (Component, options) {
    return function () {
      return (
        /* env */
        {
          component: function component() {
            var app = supernova.useApp();
            var layout = supernova.useLayout();
            var model = supernova.useModel();
            var element = supernova.useElement();
            var theme = options.theme ? Object(createMuiTheme["a" /* default */])(options.theme) : Object(createMuiTheme["a" /* default */])(Light);
            supernova.useEffect(function () {
              react_dom_default.a.render(react_default.a.createElement(ThemeProvider_ThemeProvider, {
                theme: theme
              }, theme.palette.type, react_default.a.createElement(Component, {
                app: app,
                layout: layout,
                model: model,
                options: options
              })), element);
            }, [app, layout, model, element]);
            supernova.useEffect(function () {
              return function () {
                return react_dom_default.a.unmountComponentAtNode(element);
              };
            }, []);
          }
        }
      );
    };
  };
});
// EXTERNAL MODULE: ./node_modules/@babel/runtime/regenerator/index.js
var regenerator = __webpack_require__(8);
var regenerator_default = /*#__PURE__*/__webpack_require__.n(regenerator);

// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/asyncToGenerator.js
var asyncToGenerator = __webpack_require__(13);
var asyncToGenerator_default = /*#__PURE__*/__webpack_require__.n(asyncToGenerator);

// EXTERNAL MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js + 1 modules
var objectWithoutProperties = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/extends.js
var helpers_esm_extends = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/clsx/dist/clsx.m.js
var clsx_m = __webpack_require__(5);

// EXTERNAL MODULE: ./node_modules/@material-ui/core/esm/styles/withStyles.js + 1 modules
var withStyles = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/@material-ui/core/esm/styles/colorManipulator.js
var colorManipulator = __webpack_require__(11);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/utils/setRef.js
// TODO v5: make it private
function setRef(ref, value) {
  if (typeof ref === 'function') {
    ref(value);
  } else if (ref) {
    ref.current = value;
  }
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/utils/useForkRef.js


function useForkRef(refA, refB) {
  /**
   * This will create a new function if the ref props change and are defined.
   * This means react will call the old forkRef with `null` and the new forkRef
   * with the ref. Cleanup naturally emerges from this behavior
   */
  return react_default.a.useMemo(function () {
    if (refA == null && refB == null) {
      return null;
    }

    return function (refValue) {
      setRef(refA, refValue);
      setRef(refB, refValue);
    };
  }, [refA, refB]);
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/utils/useEventCallback.js

var useEnhancedEffect = typeof window !== 'undefined' ? react_default.a.useLayoutEffect : react_default.a.useEffect;
/**
 * https://github.com/facebook/react/issues/14099#issuecomment-440013892
 *
 * @param {function} fn
 */

function useEventCallback(fn) {
  var ref = react_default.a.useRef(fn);
  useEnhancedEffect(function () {
    ref.current = fn;
  });
  return react_default.a.useCallback(function () {
    return (0, ref.current).apply(void 0, arguments);
  }, []);
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/NoSsr/NoSsr.js



var NoSsr_useEnhancedEffect = typeof window !== 'undefined' && "production" !== 'test' ? react_default.a.useLayoutEffect : react_default.a.useEffect;
/**
 * NoSsr purposely removes components from the subject of Server Side Rendering (SSR).
 *
 * This component can be useful in a variety of situations:
 * - Escape hatch for broken dependencies not supporting SSR.
 * - Improve the time-to-first paint on the client by only rendering above the fold.
 * - Reduce the rendering time on the server.
 * - Under too heavy server load, you can turn on service degradation.
 */

function NoSsr(props) {
  var children = props.children,
      _props$defer = props.defer,
      defer = _props$defer === void 0 ? false : _props$defer,
      _props$fallback = props.fallback,
      fallback = _props$fallback === void 0 ? null : _props$fallback;

  var _React$useState = react_default.a.useState(false),
      mountedState = _React$useState[0],
      setMountedState = _React$useState[1];

  NoSsr_useEnhancedEffect(function () {
    if (!defer) {
      setMountedState(true);
    }
  }, [defer]);
  react_default.a.useEffect(function () {
    if (defer) {
      setMountedState(true);
    }
  }, [defer]); // We need the Fragment here to force react-docgen to recognise NoSsr as a component.

  return react_default.a.createElement(react_default.a.Fragment, null, mountedState ? children : fallback);
}

 false ? undefined : void 0;

if (false) {}

/* harmony default export */ var NoSsr_NoSsr = (NoSsr);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/utils/focusVisible.js
// based on https://github.com/WICG/focus-visible/blob/v4.1.5/src/focus-visible.js


var hadKeyboardEvent = true;
var hadFocusVisibleRecently = false;
var hadFocusVisibleRecentlyTimeout = null;
var inputTypesWhitelist = {
  text: true,
  search: true,
  url: true,
  tel: true,
  email: true,
  password: true,
  number: true,
  date: true,
  month: true,
  week: true,
  time: true,
  datetime: true,
  'datetime-local': true
};
/**
 * Computes whether the given element should automatically trigger the
 * `focus-visible` class being added, i.e. whether it should always match
 * `:focus-visible` when focused.
 * @param {Element} node
 * @return {boolean}
 */

function focusTriggersKeyboardModality(node) {
  var type = node.type,
      tagName = node.tagName;

  if (tagName === 'INPUT' && inputTypesWhitelist[type] && !node.readOnly) {
    return true;
  }

  if (tagName === 'TEXTAREA' && !node.readOnly) {
    return true;
  }

  if (node.isContentEditable) {
    return true;
  }

  return false;
}
/**
 * Keep track of our keyboard modality state with `hadKeyboardEvent`.
 * If the most recent user interaction was via the keyboard;
 * and the key press did not include a meta, alt/option, or control key;
 * then the modality is keyboard. Otherwise, the modality is not keyboard.
 * @param {KeyboardEvent} event
 */


function focusVisible_handleKeyDown(event) {
  if (event.metaKey || event.altKey || event.ctrlKey) {
    return;
  }

  hadKeyboardEvent = true;
}
/**
 * If at any point a user clicks with a pointing device, ensure that we change
 * the modality away from keyboard.
 * This avoids the situation where a user presses a key on an already focused
 * element, and then clicks on a different element, focusing it with a
 * pointing device, while we still think we're in keyboard modality.
 */


function handlePointerDown() {
  hadKeyboardEvent = false;
}

function handleVisibilityChange() {
  if (this.visibilityState === 'hidden') {
    // If the tab becomes active again, the browser will handle calling focus
    // on the element (Safari actually calls it twice).
    // If this tab change caused a blur on an element with focus-visible,
    // re-apply the class when the user switches back to the tab.
    if (hadFocusVisibleRecently) {
      hadKeyboardEvent = true;
    }
  }
}

function prepare(doc) {
  doc.addEventListener('keydown', focusVisible_handleKeyDown, true);
  doc.addEventListener('mousedown', handlePointerDown, true);
  doc.addEventListener('pointerdown', handlePointerDown, true);
  doc.addEventListener('touchstart', handlePointerDown, true);
  doc.addEventListener('visibilitychange', handleVisibilityChange, true);
}

function teardown(doc) {
  doc.removeEventListener('keydown', focusVisible_handleKeyDown, true);
  doc.removeEventListener('mousedown', handlePointerDown, true);
  doc.removeEventListener('pointerdown', handlePointerDown, true);
  doc.removeEventListener('touchstart', handlePointerDown, true);
  doc.removeEventListener('visibilitychange', handleVisibilityChange, true);
}

function focusVisible_isFocusVisible(event) {
  var target = event.target;

  try {
    return target.matches(':focus-visible');
  } catch (error) {} // browsers not implementing :focus-visible will throw a SyntaxError
  // we use our own heuristic for those browsers
  // rethrow might be better if it's not the expected error but do we really
  // want to crash if focus-visible malfunctioned?
  // no need for validFocusTarget check. the user does that by attaching it to
  // focusable events only


  return hadKeyboardEvent || focusTriggersKeyboardModality(target);
}
/**
 * Should be called if a blur event is fired on a focus-visible element
 */


function handleBlurVisible() {
  // To detect a tab/window switch, we look for a blur event followed
  // rapidly by a visibility change.
  // If we don't see a visibility change within 100ms, it's probably a
  // regular focus change.
  hadFocusVisibleRecently = true;
  window.clearTimeout(hadFocusVisibleRecentlyTimeout);
  hadFocusVisibleRecentlyTimeout = window.setTimeout(function () {
    hadFocusVisibleRecently = false;
  }, 100);
}

function useIsFocusVisible() {
  var ref = react_default.a.useCallback(function (instance) {
    var node = react_dom_default.a.findDOMNode(instance);

    if (node != null) {
      prepare(node.ownerDocument);
    }
  }, []);
  return {
    isFocusVisible: focusVisible_isFocusVisible,
    onBlurVisible: handleBlurVisible,
    ref: ref
  };
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js
function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) {
    for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
      arr2[i] = arr[i];
    }

    return arr2;
  }
}
// EXTERNAL MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/iterableToArray.js
var iterableToArray = __webpack_require__(65);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js
function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance");
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js



function _toConsumableArray(arr) {
  return _arrayWithoutHoles(arr) || Object(iterableToArray["a" /* default */])(arr) || _nonIterableSpread();
}
// CONCATENATED MODULE: ./node_modules/react-transition-group/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js
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;
}
// CONCATENATED MODULE: ./node_modules/react-transition-group/node_modules/@babel/runtime/helpers/esm/extends.js
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);
}
// CONCATENATED MODULE: ./node_modules/react-transition-group/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js
function _inheritsLoose(subClass, superClass) {
  subClass.prototype = Object.create(superClass.prototype);
  subClass.prototype.constructor = subClass;
  subClass.__proto__ = superClass;
}
// CONCATENATED MODULE: ./node_modules/react-transition-group/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js
function _assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return self;
}
// CONCATENATED MODULE: ./node_modules/react-transition-group/esm/TransitionGroupContext.js

/* harmony default export */ var TransitionGroupContext = (react_default.a.createContext(null));
// CONCATENATED MODULE: ./node_modules/react-transition-group/esm/utils/ChildMapping.js

/**
 * Given `this.props.children`, return an object mapping key to child.
 *
 * @param {*} children `this.props.children`
 * @return {object} Mapping of key to child
 */

function getChildMapping(children, mapFn) {
  var mapper = function mapper(child) {
    return mapFn && Object(react["isValidElement"])(child) ? mapFn(child) : child;
  };

  var result = Object.create(null);
  if (children) react["Children"].map(children, function (c) {
    return c;
  }).forEach(function (child) {
    // run the map function here instead so that the key is the computed one
    result[child.key] = mapper(child);
  });
  return result;
}
/**
 * When you're adding or removing children some may be added or removed in the
 * same render pass. We want to show *both* since we want to simultaneously
 * animate elements in and out. This function takes a previous set of keys
 * and a new set of keys and merges them with its best guess of the correct
 * ordering. In the future we may expose some of the utilities in
 * ReactMultiChild to make this easy, but for now React itself does not
 * directly have this concept of the union of prevChildren and nextChildren
 * so we implement it here.
 *
 * @param {object} prev prev children as returned from
 * `ReactTransitionChildMapping.getChildMapping()`.
 * @param {object} next next children as returned from
 * `ReactTransitionChildMapping.getChildMapping()`.
 * @return {object} a key set that contains all keys in `prev` and all keys
 * in `next` in a reasonable order.
 */

function mergeChildMappings(prev, next) {
  prev = prev || {};
  next = next || {};

  function getValueForKey(key) {
    return key in next ? next[key] : prev[key];
  } // For each key of `next`, the list of keys to insert before that key in
  // the combined list


  var nextKeysPending = Object.create(null);
  var pendingKeys = [];

  for (var prevKey in prev) {
    if (prevKey in next) {
      if (pendingKeys.length) {
        nextKeysPending[prevKey] = pendingKeys;
        pendingKeys = [];
      }
    } else {
      pendingKeys.push(prevKey);
    }
  }

  var i;
  var childMapping = {};

  for (var nextKey in next) {
    if (nextKeysPending[nextKey]) {
      for (i = 0; i < nextKeysPending[nextKey].length; i++) {
        var pendingNextKey = nextKeysPending[nextKey][i];
        childMapping[nextKeysPending[nextKey][i]] = getValueForKey(pendingNextKey);
      }
    }

    childMapping[nextKey] = getValueForKey(nextKey);
  } // Finally, add the keys which didn't appear before any key in `next`


  for (i = 0; i < pendingKeys.length; i++) {
    childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]);
  }

  return childMapping;
}

function getProp(child, prop, props) {
  return props[prop] != null ? props[prop] : child.props[prop];
}

function getInitialChildMapping(props, onExited) {
  return getChildMapping(props.children, function (child) {
    return Object(react["cloneElement"])(child, {
      onExited: onExited.bind(null, child),
      in: true,
      appear: getProp(child, 'appear', props),
      enter: getProp(child, 'enter', props),
      exit: getProp(child, 'exit', props)
    });
  });
}
function getNextChildMapping(nextProps, prevChildMapping, onExited) {
  var nextChildMapping = getChildMapping(nextProps.children);
  var children = mergeChildMappings(prevChildMapping, nextChildMapping);
  Object.keys(children).forEach(function (key) {
    var child = children[key];
    if (!Object(react["isValidElement"])(child)) return;
    var hasPrev = key in prevChildMapping;
    var hasNext = key in nextChildMapping;
    var prevChild = prevChildMapping[key];
    var isLeaving = Object(react["isValidElement"])(prevChild) && !prevChild.props.in; // item is new (entering)

    if (hasNext && (!hasPrev || isLeaving)) {
      // console.log('entering', key)
      children[key] = Object(react["cloneElement"])(child, {
        onExited: onExited.bind(null, child),
        in: true,
        exit: getProp(child, 'exit', nextProps),
        enter: getProp(child, 'enter', nextProps)
      });
    } else if (!hasNext && hasPrev && !isLeaving) {
      // item is old (exiting)
      // console.log('leaving', key)
      children[key] = Object(react["cloneElement"])(child, {
        in: false
      });
    } else if (hasNext && hasPrev && Object(react["isValidElement"])(prevChild)) {
      // item hasn't changed transition states
      // copy over the last transition props;
      // console.log('unchanged', key)
      children[key] = Object(react["cloneElement"])(child, {
        onExited: onExited.bind(null, child),
        in: prevChild.props.in,
        exit: getProp(child, 'exit', nextProps),
        enter: getProp(child, 'enter', nextProps)
      });
    }
  });
  return children;
}
// CONCATENATED MODULE: ./node_modules/react-transition-group/esm/TransitionGroup.js









var TransitionGroup_values = Object.values || function (obj) {
  return Object.keys(obj).map(function (k) {
    return obj[k];
  });
};

var defaultProps = {
  component: 'div',
  childFactory: function childFactory(child) {
    return child;
  }
  /**
   * The `<TransitionGroup>` component manages a set of transition components
   * (`<Transition>` and `<CSSTransition>`) in a list. Like with the transition
   * components, `<TransitionGroup>` is a state machine for managing the mounting
   * and unmounting of components over time.
   *
   * Consider the example below. As items are removed or added to the TodoList the
   * `in` prop is toggled automatically by the `<TransitionGroup>`.
   *
   * Note that `<TransitionGroup>`  does not define any animation behavior!
   * Exactly _how_ a list item animates is up to the individual transition
   * component. This means you can mix and match animations across different list
   * items.
   */

};

var TransitionGroup_TransitionGroup =
/*#__PURE__*/
function (_React$Component) {
  _inheritsLoose(TransitionGroup, _React$Component);

  function TransitionGroup(props, context) {
    var _this;

    _this = _React$Component.call(this, props, context) || this;

    var handleExited = _this.handleExited.bind(_assertThisInitialized(_assertThisInitialized(_this))); // Initial children should all be entering, dependent on appear


    _this.state = {
      contextValue: {
        isMounting: true
      },
      handleExited: handleExited,
      firstRender: true
    };
    return _this;
  }

  var _proto = TransitionGroup.prototype;

  _proto.componentDidMount = function componentDidMount() {
    this.mounted = true;
    this.setState({
      contextValue: {
        isMounting: false
      }
    });
  };

  _proto.componentWillUnmount = function componentWillUnmount() {
    this.mounted = false;
  };

  TransitionGroup.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, _ref) {
    var prevChildMapping = _ref.children,
        handleExited = _ref.handleExited,
        firstRender = _ref.firstRender;
    return {
      children: firstRender ? getInitialChildMapping(nextProps, handleExited) : getNextChildMapping(nextProps, prevChildMapping, handleExited),
      firstRender: false
    };
  };

  _proto.handleExited = function handleExited(child, node) {
    var currentChildMapping = getChildMapping(this.props.children);
    if (child.key in currentChildMapping) return;

    if (child.props.onExited) {
      child.props.onExited(node);
    }

    if (this.mounted) {
      this.setState(function (state) {
        var children = _extends({}, state.children);

        delete children[child.key];
        return {
          children: children
        };
      });
    }
  };

  _proto.render = function render() {
    var _this$props = this.props,
        Component = _this$props.component,
        childFactory = _this$props.childFactory,
        props = _objectWithoutPropertiesLoose(_this$props, ["component", "childFactory"]);

    var contextValue = this.state.contextValue;
    var children = TransitionGroup_values(this.state.children).map(childFactory);
    delete props.appear;
    delete props.enter;
    delete props.exit;

    if (Component === null) {
      return react_default.a.createElement(TransitionGroupContext.Provider, {
        value: contextValue
      }, children);
    }

    return react_default.a.createElement(TransitionGroupContext.Provider, {
      value: contextValue
    }, react_default.a.createElement(Component, props, children));
  };

  return TransitionGroup;
}(react_default.a.Component);

TransitionGroup_TransitionGroup.propTypes =  false ? undefined : {};
TransitionGroup_TransitionGroup.defaultProps = defaultProps;
/* harmony default export */ var esm_TransitionGroup = (TransitionGroup_TransitionGroup);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/ButtonBase/Ripple.js




var Ripple_useEnhancedEffect = typeof window === 'undefined' ? react_default.a.useEffect : react_default.a.useLayoutEffect;
/**
 * @ignore - internal component.
 */

function Ripple(props) {
  var classes = props.classes,
      _props$pulsate = props.pulsate,
      pulsate = _props$pulsate === void 0 ? false : _props$pulsate,
      rippleX = props.rippleX,
      rippleY = props.rippleY,
      rippleSize = props.rippleSize,
      inProp = props.in,
      _props$onExited = props.onExited,
      onExited = _props$onExited === void 0 ? function () {} : _props$onExited,
      timeout = props.timeout;

  var _React$useState = react_default.a.useState(false),
      leaving = _React$useState[0],
      setLeaving = _React$useState[1];

  var rippleClassName = Object(clsx_m["a" /* default */])(classes.ripple, classes.rippleVisible, pulsate && classes.ripplePulsate);
  var rippleStyles = {
    width: rippleSize,
    height: rippleSize,
    top: -(rippleSize / 2) + rippleY,
    left: -(rippleSize / 2) + rippleX
  };
  var childClassName = Object(clsx_m["a" /* default */])(classes.child, leaving && classes.childLeaving, pulsate && classes.childPulsate);
  var handleExited = useEventCallback(onExited); // Ripple is used for user feedback (e.g. click or press) so we want to apply styles with the highest priority

  Ripple_useEnhancedEffect(function () {
    if (!inProp) {
      // react-transition-group#onExit
      setLeaving(true); // react-transition-group#onExited

      var timeoutId = setTimeout(handleExited, timeout);
      return function () {
        clearTimeout(timeoutId);
      };
    }

    return undefined;
  }, [handleExited, inProp, timeout]);
  return react_default.a.createElement("span", {
    className: rippleClassName,
    style: rippleStyles
  }, react_default.a.createElement("span", {
    className: childClassName
  }));
}

 false ? undefined : void 0;
/* harmony default export */ var ButtonBase_Ripple = (Ripple);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/ButtonBase/TouchRipple.js









var DURATION = 550;
var DELAY_RIPPLE = 80;
var TouchRipple_styles = function styles(theme) {
  return {
    /* Styles applied to the root element. */
    root: {
      overflow: 'hidden',
      pointerEvents: 'none',
      position: 'absolute',
      zIndex: 0,
      top: 0,
      right: 0,
      bottom: 0,
      left: 0,
      borderRadius: 'inherit'
    },

    /* Styles applied to the internal `Ripple` components `ripple` class. */
    ripple: {
      opacity: 0,
      position: 'absolute'
    },

    /* Styles applied to the internal `Ripple` components `rippleVisible` class. */
    rippleVisible: {
      opacity: 0.3,
      transform: 'scale(1)',
      animation: "$enter ".concat(DURATION, "ms ").concat(theme.transitions.easing.easeInOut)
    },

    /* Styles applied to the internal `Ripple` components `ripplePulsate` class. */
    ripplePulsate: {
      animationDuration: "".concat(theme.transitions.duration.shorter, "ms")
    },

    /* Styles applied to the internal `Ripple` components `child` class. */
    child: {
      opacity: 1,
      display: 'block',
      width: '100%',
      height: '100%',
      borderRadius: '50%',
      backgroundColor: 'currentColor'
    },

    /* Styles applied to the internal `Ripple` components `childLeaving` class. */
    childLeaving: {
      opacity: 0,
      animation: "$exit ".concat(DURATION, "ms ").concat(theme.transitions.easing.easeInOut)
    },

    /* Styles applied to the internal `Ripple` components `childPulsate` class. */
    childPulsate: {
      position: 'absolute',
      left: 0,
      top: 0,
      animation: "$pulsate 2500ms ".concat(theme.transitions.easing.easeInOut, " 200ms infinite")
    },
    '@keyframes enter': {
      '0%': {
        transform: 'scale(0)',
        opacity: 0.1
      },
      '100%': {
        transform: 'scale(1)',
        opacity: 0.3
      }
    },
    '@keyframes exit': {
      '0%': {
        opacity: 1
      },
      '100%': {
        opacity: 0
      }
    },
    '@keyframes pulsate': {
      '0%': {
        transform: 'scale(1)'
      },
      '50%': {
        transform: 'scale(0.92)'
      },
      '100%': {
        transform: 'scale(1)'
      }
    }
  };
};
/**
 * @ignore - internal component.
 *
 * TODO v5: Make private
 */

var TouchRipple_TouchRipple = react_default.a.forwardRef(function TouchRipple(props, ref) {
  var _props$center = props.center,
      centerProp = _props$center === void 0 ? false : _props$center,
      classes = props.classes,
      className = props.className,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["center", "classes", "className"]);

  var _React$useState = react_default.a.useState([]),
      ripples = _React$useState[0],
      setRipples = _React$useState[1];

  var nextKey = react_default.a.useRef(0);
  var rippleCallback = react_default.a.useRef(null);
  react_default.a.useEffect(function () {
    if (rippleCallback.current) {
      rippleCallback.current();
      rippleCallback.current = null;
    }
  }, [ripples]); // Used to filter out mouse emulated events on mobile.

  var ignoringMouseDown = react_default.a.useRef(false); // We use a timer in order to only show the ripples for touch "click" like events.
  // We don't want to display the ripple for touch scroll events.

  var startTimer = react_default.a.useRef(null); // This is the hook called once the previous timeout is ready.

  var startTimerCommit = react_default.a.useRef(null);
  var container = react_default.a.useRef(null);
  react_default.a.useEffect(function () {
    return function () {
      clearTimeout(startTimer.current);
    };
  }, []);
  var startCommit = react_default.a.useCallback(function (params) {
    var pulsate = params.pulsate,
        rippleX = params.rippleX,
        rippleY = params.rippleY,
        rippleSize = params.rippleSize,
        cb = params.cb;
    setRipples(function (oldRipples) {
      return [].concat(_toConsumableArray(oldRipples), [react_default.a.createElement(ButtonBase_Ripple, {
        key: nextKey.current,
        classes: classes,
        timeout: DURATION,
        pulsate: pulsate,
        rippleX: rippleX,
        rippleY: rippleY,
        rippleSize: rippleSize
      })]);
    });
    nextKey.current += 1;
    rippleCallback.current = cb;
  }, [classes]);
  var start = react_default.a.useCallback(function () {
    var event = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var cb = arguments.length > 2 ? arguments[2] : undefined;
    var _options$pulsate = options.pulsate,
        pulsate = _options$pulsate === void 0 ? false : _options$pulsate,
        _options$center = options.center,
        center = _options$center === void 0 ? centerProp || options.pulsate : _options$center,
        _options$fakeElement = options.fakeElement,
        fakeElement = _options$fakeElement === void 0 ? false : _options$fakeElement;

    if (event.type === 'mousedown' && ignoringMouseDown.current) {
      ignoringMouseDown.current = false;
      return;
    }

    if (event.type === 'touchstart') {
      ignoringMouseDown.current = true;
    }

    var element = fakeElement ? null : container.current;
    var rect = element ? element.getBoundingClientRect() : {
      width: 0,
      height: 0,
      left: 0,
      top: 0
    }; // Get the size of the ripple

    var rippleX;
    var rippleY;
    var rippleSize;

    if (center || event.clientX === 0 && event.clientY === 0 || !event.clientX && !event.touches) {
      rippleX = Math.round(rect.width / 2);
      rippleY = Math.round(rect.height / 2);
    } else {
      var clientX = event.clientX ? event.clientX : event.touches[0].clientX;
      var clientY = event.clientY ? event.clientY : event.touches[0].clientY;
      rippleX = Math.round(clientX - rect.left);
      rippleY = Math.round(clientY - rect.top);
    }

    if (center) {
      rippleSize = Math.sqrt((2 * Math.pow(rect.width, 2) + Math.pow(rect.height, 2)) / 3); // For some reason the animation is broken on Mobile Chrome if the size if even.

      if (rippleSize % 2 === 0) {
        rippleSize += 1;
      }
    } else {
      var sizeX = Math.max(Math.abs((element ? element.clientWidth : 0) - rippleX), rippleX) * 2 + 2;
      var sizeY = Math.max(Math.abs((element ? element.clientHeight : 0) - rippleY), rippleY) * 2 + 2;
      rippleSize = Math.sqrt(Math.pow(sizeX, 2) + Math.pow(sizeY, 2));
    } // Touche devices


    if (event.touches) {
      // check that this isn't another touchstart due to multitouch
      // otherwise we will only clear a single timer when unmounting while two
      // are running
      if (startTimerCommit.current === null) {
        // Prepare the ripple effect.
        startTimerCommit.current = function () {
          startCommit({
            pulsate: pulsate,
            rippleX: rippleX,
            rippleY: rippleY,
            rippleSize: rippleSize,
            cb: cb
          });
        }; // Delay the execution of the ripple effect.


        startTimer.current = setTimeout(function () {
          if (startTimerCommit.current) {
            startTimerCommit.current();
            startTimerCommit.current = null;
          }
        }, DELAY_RIPPLE); // We have to make a tradeoff with this value.
      }
    } else {
      startCommit({
        pulsate: pulsate,
        rippleX: rippleX,
        rippleY: rippleY,
        rippleSize: rippleSize,
        cb: cb
      });
    }
  }, [centerProp, startCommit]);
  var pulsate = react_default.a.useCallback(function () {
    start({}, {
      pulsate: true
    });
  }, [start]);
  var stop = react_default.a.useCallback(function (event, cb) {
    clearTimeout(startTimer.current); // The touch interaction occurs too quickly.
    // We still want to show ripple effect.

    if (event.type === 'touchend' && startTimerCommit.current) {
      event.persist();
      startTimerCommit.current();
      startTimerCommit.current = null;
      startTimer.current = setTimeout(function () {
        stop(event, cb);
      });
      return;
    }

    startTimerCommit.current = null;
    setRipples(function (oldRipples) {
      if (oldRipples.length > 0) {
        return oldRipples.slice(1);
      }

      return oldRipples;
    });
    rippleCallback.current = cb;
  }, []);
  react_default.a.useImperativeHandle(ref, function () {
    return {
      pulsate: pulsate,
      start: start,
      stop: stop
    };
  }, [pulsate, start, stop]);
  return react_default.a.createElement("span", Object(helpers_esm_extends["a" /* default */])({
    className: Object(clsx_m["a" /* default */])(classes.root, className),
    ref: container
  }, other), react_default.a.createElement(esm_TransitionGroup, {
    component: null,
    exit: true
  }, ripples));
});
 false ? undefined : void 0;
/* harmony default export */ var ButtonBase_TouchRipple = (Object(withStyles["a" /* default */])(TouchRipple_styles, {
  flip: false,
  name: 'MuiTouchRipple'
})(react_default.a.memo(TouchRipple_TouchRipple)));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/ButtonBase/ButtonBase.js













var ButtonBase_styles = {
  /* Styles applied to the root element. */
  root: {
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    position: 'relative',
    WebkitTapHighlightColor: 'transparent',
    backgroundColor: 'transparent',
    // Reset default value
    // We disable the focus ring for mouse, touch and keyboard users.
    outline: 0,
    border: 0,
    margin: 0,
    // Remove the margin in Safari
    borderRadius: 0,
    padding: 0,
    // Remove the padding in Firefox
    cursor: 'pointer',
    userSelect: 'none',
    verticalAlign: 'middle',
    '-moz-appearance': 'none',
    // Reset
    '-webkit-appearance': 'none',
    // Reset
    textDecoration: 'none',
    // So we take precedent over the style of a native <a /> element.
    color: 'inherit',
    '&::-moz-focus-inner': {
      borderStyle: 'none' // Remove Firefox dotted outline.

    },
    '&$disabled': {
      pointerEvents: 'none',
      // Disable link interactions
      cursor: 'default'
    }
  },

  /* Pseudo-class applied to the root element if `disabled={true}`. */
  disabled: {},

  /* Pseudo-class applied to the root element if keyboard focused. */
  focusVisible: {}
};
/**
 * `ButtonBase` contains as few styles as possible.
 * It aims to be a simple building block for creating a button.
 * It contains a load of style reset and some focus/ripple logic.
 */

var ButtonBase_ButtonBase = react_default.a.forwardRef(function ButtonBase(props, ref) {
  var action = props.action,
      buttonRefProp = props.buttonRef,
      _props$centerRipple = props.centerRipple,
      centerRipple = _props$centerRipple === void 0 ? false : _props$centerRipple,
      children = props.children,
      classes = props.classes,
      className = props.className,
      _props$component = props.component,
      component = _props$component === void 0 ? 'button' : _props$component,
      _props$disabled = props.disabled,
      disabled = _props$disabled === void 0 ? false : _props$disabled,
      _props$disableRipple = props.disableRipple,
      disableRipple = _props$disableRipple === void 0 ? false : _props$disableRipple,
      _props$disableTouchRi = props.disableTouchRipple,
      disableTouchRipple = _props$disableTouchRi === void 0 ? false : _props$disableTouchRi,
      _props$focusRipple = props.focusRipple,
      focusRipple = _props$focusRipple === void 0 ? false : _props$focusRipple,
      focusVisibleClassName = props.focusVisibleClassName,
      onBlur = props.onBlur,
      onClick = props.onClick,
      onFocus = props.onFocus,
      onFocusVisible = props.onFocusVisible,
      onKeyDown = props.onKeyDown,
      onKeyUp = props.onKeyUp,
      onMouseDown = props.onMouseDown,
      onMouseLeave = props.onMouseLeave,
      onMouseUp = props.onMouseUp,
      onTouchEnd = props.onTouchEnd,
      onTouchMove = props.onTouchMove,
      onTouchStart = props.onTouchStart,
      onDragLeave = props.onDragLeave,
      _props$tabIndex = props.tabIndex,
      tabIndex = _props$tabIndex === void 0 ? 0 : _props$tabIndex,
      TouchRippleProps = props.TouchRippleProps,
      _props$type = props.type,
      type = _props$type === void 0 ? 'button' : _props$type,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["action", "buttonRef", "centerRipple", "children", "classes", "className", "component", "disabled", "disableRipple", "disableTouchRipple", "focusRipple", "focusVisibleClassName", "onBlur", "onClick", "onFocus", "onFocusVisible", "onKeyDown", "onKeyUp", "onMouseDown", "onMouseLeave", "onMouseUp", "onTouchEnd", "onTouchMove", "onTouchStart", "onDragLeave", "tabIndex", "TouchRippleProps", "type"]);

  var buttonRef = react_default.a.useRef(null);

  function getButtonNode() {
    // #StrictMode ready
    return react_dom_default.a.findDOMNode(buttonRef.current);
  }

  var rippleRef = react_default.a.useRef(null);

  var _React$useState = react_default.a.useState(false),
      focusVisible = _React$useState[0],
      setFocusVisible = _React$useState[1];

  if (disabled && focusVisible) {
    setFocusVisible(false);
  }

  var _useIsFocusVisible = useIsFocusVisible(),
      isFocusVisible = _useIsFocusVisible.isFocusVisible,
      onBlurVisible = _useIsFocusVisible.onBlurVisible,
      focusVisibleRef = _useIsFocusVisible.ref;

  react_default.a.useImperativeHandle(action, function () {
    return {
      focusVisible: function focusVisible() {
        setFocusVisible(true);
        buttonRef.current.focus();
      }
    };
  }, []);
  react_default.a.useEffect(function () {
    if (focusVisible && focusRipple && !disableRipple) {
      rippleRef.current.pulsate();
    }
  }, [disableRipple, focusRipple, focusVisible]);

  function useRippleHandler(rippleAction, eventCallback) {
    var skipRippleAction = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : disableTouchRipple;
    return useEventCallback(function (event) {
      if (eventCallback) {
        eventCallback(event);
      }

      var ignore = skipRippleAction;

      if (!ignore && rippleRef.current) {
        rippleRef.current[rippleAction](event);
      }

      return true;
    });
  }

  var handleMouseDown = useRippleHandler('start', onMouseDown);
  var handleDragLeave = useRippleHandler('stop', onDragLeave);
  var handleMouseUp = useRippleHandler('stop', onMouseUp);
  var handleMouseLeave = useRippleHandler('stop', function (event) {
    if (focusVisible) {
      event.preventDefault();
    }

    if (onMouseLeave) {
      onMouseLeave(event);
    }
  });
  var handleTouchStart = useRippleHandler('start', onTouchStart);
  var handleTouchEnd = useRippleHandler('stop', onTouchEnd);
  var handleTouchMove = useRippleHandler('stop', onTouchMove);
  var handleBlur = useRippleHandler('stop', function (event) {
    if (focusVisible) {
      onBlurVisible(event);
      setFocusVisible(false);
    }

    if (onBlur) {
      onBlur(event);
    }
  }, false);
  var handleFocus = useEventCallback(function (event) {
    if (disabled) {
      return;
    } // Fix for https://github.com/facebook/react/issues/7769


    if (!buttonRef.current) {
      buttonRef.current = event.currentTarget;
    }

    if (isFocusVisible(event)) {
      setFocusVisible(true);

      if (onFocusVisible) {
        onFocusVisible(event);
      }
    }

    if (onFocus) {
      onFocus(event);
    }
  });

  var isNonNativeButton = function isNonNativeButton() {
    var button = getButtonNode();
    return component && component !== 'button' && !(button.tagName === 'A' && button.href);
  };
  /**
   * IE 11 shim for https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat
   */


  var keydownRef = react_default.a.useRef(false);
  var handleKeyDown = useEventCallback(function (event) {
    // Check if key is already down to avoid repeats being counted as multiple activations
    if (focusRipple && !keydownRef.current && focusVisible && rippleRef.current && event.key === ' ') {
      keydownRef.current = true;
      event.persist();
      rippleRef.current.stop(event, function () {
        rippleRef.current.start(event);
      });
    }

    if (onKeyDown) {
      onKeyDown(event);
    } // Keyboard accessibility for non interactive elements


    if (event.target === event.currentTarget && isNonNativeButton() && event.key === 'Enter') {
      event.preventDefault();

      if (onClick) {
        onClick(event);
      }
    }
  });
  var handleKeyUp = useEventCallback(function (event) {
    // calling preventDefault in keyUp on a <button> will not dispatch a click event if Space is pressed
    // https://codesandbox.io/s/button-keyup-preventdefault-dn7f0
    if (focusRipple && event.key === ' ' && rippleRef.current && focusVisible && !event.defaultPrevented) {
      keydownRef.current = false;
      event.persist();
      rippleRef.current.stop(event, function () {
        rippleRef.current.pulsate(event);
      });
    }

    if (onKeyUp) {
      onKeyUp(event);
    } // Keyboard accessibility for non interactive elements


    if (event.target === event.currentTarget && isNonNativeButton() && event.key === ' ' && !event.defaultPrevented) {
      event.preventDefault();

      if (onClick) {
        onClick(event);
      }
    }
  });
  var ComponentProp = component;

  if (ComponentProp === 'button' && other.href) {
    ComponentProp = 'a';
  }

  var buttonProps = {};

  if (ComponentProp === 'button') {
    buttonProps.type = type;
    buttonProps.disabled = disabled;
  } else {
    if (ComponentProp !== 'a' || !other.href) {
      buttonProps.role = 'button';
    }

    buttonProps['aria-disabled'] = disabled;
  }

  var handleUserRef = useForkRef(buttonRefProp, ref);
  var handleOwnRef = useForkRef(focusVisibleRef, buttonRef);
  var handleRef = useForkRef(handleUserRef, handleOwnRef);
  return react_default.a.createElement(ComponentProp, Object(helpers_esm_extends["a" /* default */])({
    className: Object(clsx_m["a" /* default */])(classes.root, className, focusVisible && [classes.focusVisible, focusVisibleClassName], disabled && classes.disabled),
    onBlur: handleBlur,
    onClick: onClick,
    onFocus: handleFocus,
    onKeyDown: handleKeyDown,
    onKeyUp: handleKeyUp,
    onMouseDown: handleMouseDown,
    onMouseLeave: handleMouseLeave,
    onMouseUp: handleMouseUp,
    onDragLeave: handleDragLeave,
    onTouchEnd: handleTouchEnd,
    onTouchMove: handleTouchMove,
    onTouchStart: handleTouchStart,
    ref: handleRef,
    tabIndex: disabled ? -1 : tabIndex
  }, buttonProps, other), children, !disableRipple && !disabled ? react_default.a.createElement(NoSsr_NoSsr, null, react_default.a.createElement(ButtonBase_TouchRipple, Object(helpers_esm_extends["a" /* default */])({
    ref: rippleRef,
    center: centerRipple
  }, TouchRippleProps))) : null);
});
 false ? undefined : void 0;
/* harmony default export */ var esm_ButtonBase_ButtonBase = (Object(withStyles["a" /* default */])(ButtonBase_styles, {
  name: 'MuiButtonBase'
})(ButtonBase_ButtonBase));
// EXTERNAL MODULE: ./node_modules/@material-ui/core/esm/utils/capitalize.js
var capitalize = __webpack_require__(7);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Button/Button.js









var Button_styles = function styles(theme) {
  return {
    /* Styles applied to the root element. */
    root: Object(helpers_esm_extends["a" /* default */])({}, theme.typography.button, {
      boxSizing: 'border-box',
      minWidth: 64,
      padding: '6px 16px',
      borderRadius: theme.shape.borderRadius,
      color: theme.palette.text.primary,
      transition: theme.transitions.create(['background-color', 'box-shadow', 'border'], {
        duration: theme.transitions.duration.short
      }),
      '&:hover': {
        textDecoration: 'none',
        backgroundColor: Object(colorManipulator["b" /* fade */])(theme.palette.text.primary, theme.palette.action.hoverOpacity),
        // Reset on touch devices, it doesn't add specificity
        '@media (hover: none)': {
          backgroundColor: 'transparent'
        },
        '&$disabled': {
          backgroundColor: 'transparent'
        }
      },
      '&$disabled': {
        color: theme.palette.action.disabled
      }
    }),

    /* Styles applied to the span element that wraps the children. */
    label: {
      width: '100%',
      // Ensure the correct width for iOS Safari
      display: 'inherit',
      alignItems: 'inherit',
      justifyContent: 'inherit'
    },

    /* Styles applied to the root element if `variant="text"`. */
    text: {
      padding: '6px 8px'
    },

    /* Styles applied to the root element if `variant="text"` and `color="primary"`. */
    textPrimary: {
      color: theme.palette.primary.main,
      '&:hover': {
        backgroundColor: Object(colorManipulator["b" /* fade */])(theme.palette.primary.main, theme.palette.action.hoverOpacity),
        // Reset on touch devices, it doesn't add specificity
        '@media (hover: none)': {
          backgroundColor: 'transparent'
        }
      }
    },

    /* Styles applied to the root element if `variant="text"` and `color="secondary"`. */
    textSecondary: {
      color: theme.palette.secondary.main,
      '&:hover': {
        backgroundColor: Object(colorManipulator["b" /* fade */])(theme.palette.secondary.main, theme.palette.action.hoverOpacity),
        // Reset on touch devices, it doesn't add specificity
        '@media (hover: none)': {
          backgroundColor: 'transparent'
        }
      }
    },

    /* Styles applied to the root element if `variant="outlined"`. */
    outlined: {
      padding: '5px 15px',
      border: "1px solid ".concat(theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)'),
      '&$disabled': {
        border: "1px solid ".concat(theme.palette.action.disabledBackground)
      }
    },

    /* Styles applied to the root element if `variant="outlined"` and `color="primary"`. */
    outlinedPrimary: {
      color: theme.palette.primary.main,
      border: "1px solid ".concat(Object(colorManipulator["b" /* fade */])(theme.palette.primary.main, 0.5)),
      '&:hover': {
        border: "1px solid ".concat(theme.palette.primary.main),
        backgroundColor: Object(colorManipulator["b" /* fade */])(theme.palette.primary.main, theme.palette.action.hoverOpacity),
        // Reset on touch devices, it doesn't add specificity
        '@media (hover: none)': {
          backgroundColor: 'transparent'
        }
      }
    },

    /* Styles applied to the root element if `variant="outlined"` and `color="secondary"`. */
    outlinedSecondary: {
      color: theme.palette.secondary.main,
      border: "1px solid ".concat(Object(colorManipulator["b" /* fade */])(theme.palette.secondary.main, 0.5)),
      '&:hover': {
        border: "1px solid ".concat(theme.palette.secondary.main),
        backgroundColor: Object(colorManipulator["b" /* fade */])(theme.palette.secondary.main, theme.palette.action.hoverOpacity),
        // Reset on touch devices, it doesn't add specificity
        '@media (hover: none)': {
          backgroundColor: 'transparent'
        }
      },
      '&$disabled': {
        border: "1px solid ".concat(theme.palette.action.disabled)
      }
    },

    /* Styles applied to the root element if `variant="contained"`. */
    contained: {
      color: theme.palette.getContrastText(theme.palette.grey[300]),
      backgroundColor: theme.palette.grey[300],
      boxShadow: theme.shadows[2],
      '&:hover': {
        backgroundColor: theme.palette.grey.A100,
        boxShadow: theme.shadows[4],
        // Reset on touch devices, it doesn't add specificity
        '@media (hover: none)': {
          boxShadow: theme.shadows[2],
          backgroundColor: theme.palette.grey[300]
        },
        '&$disabled': {
          backgroundColor: theme.palette.action.disabledBackground
        }
      },
      '&$focusVisible': {
        boxShadow: theme.shadows[6]
      },
      '&:active': {
        boxShadow: theme.shadows[8]
      },
      '&$disabled': {
        color: theme.palette.action.disabled,
        boxShadow: theme.shadows[0],
        backgroundColor: theme.palette.action.disabledBackground
      }
    },

    /* Styles applied to the root element if `variant="contained"` and `color="primary"`. */
    containedPrimary: {
      color: theme.palette.primary.contrastText,
      backgroundColor: theme.palette.primary.main,
      '&:hover': {
        backgroundColor: theme.palette.primary.dark,
        // Reset on touch devices, it doesn't add specificity
        '@media (hover: none)': {
          backgroundColor: theme.palette.primary.main
        }
      }
    },

    /* Styles applied to the root element if `variant="contained"` and `color="secondary"`. */
    containedSecondary: {
      color: theme.palette.secondary.contrastText,
      backgroundColor: theme.palette.secondary.main,
      '&:hover': {
        backgroundColor: theme.palette.secondary.dark,
        // Reset on touch devices, it doesn't add specificity
        '@media (hover: none)': {
          backgroundColor: theme.palette.secondary.main
        }
      }
    },

    /* Styles applied to the root element if `disableElevation={true}`. */
    disableElevation: {
      boxShadow: 'none',
      '&:hover': {
        boxShadow: 'none'
      },
      '&$focusVisible': {
        boxShadow: 'none'
      },
      '&:active': {
        boxShadow: 'none'
      },
      '&$disabled': {
        boxShadow: 'none'
      }
    },

    /* Pseudo-class applied to the ButtonBase root element if the button is keyboard focused. */
    focusVisible: {},

    /* Pseudo-class applied to the root element if `disabled={true}`. */
    disabled: {},

    /* Styles applied to the root element if `color="inherit"`. */
    colorInherit: {
      color: 'inherit',
      borderColor: 'currentColor'
    },

    /* Styles applied to the root element if `size="small"` and `variant="text"`. */
    textSizeSmall: {
      padding: '4px 5px',
      fontSize: theme.typography.pxToRem(13)
    },

    /* Styles applied to the root element if `size="large"` and `variant="text"`. */
    textSizeLarge: {
      padding: '8px 11px',
      fontSize: theme.typography.pxToRem(15)
    },

    /* Styles applied to the root element if `size="small"` and `variant="outlined"`. */
    outlinedSizeSmall: {
      padding: '3px 9px',
      fontSize: theme.typography.pxToRem(13)
    },

    /* Styles applied to the root element if `size="large"` and `variant="outlined"`. */
    outlinedSizeLarge: {
      padding: '7px 21px',
      fontSize: theme.typography.pxToRem(15)
    },

    /* Styles applied to the root element if `size="small"` and `variant="contained"`. */
    containedSizeSmall: {
      padding: '4px 10px',
      fontSize: theme.typography.pxToRem(13)
    },

    /* Styles applied to the root element if `size="large"` and `variant="contained"`. */
    containedSizeLarge: {
      padding: '8px 22px',
      fontSize: theme.typography.pxToRem(15)
    },

    /* Styles applied to the root element if `size="small"`. */
    sizeSmall: {},

    /* Styles applied to the root element if `size="large"`. */
    sizeLarge: {},

    /* Styles applied to the root element if `fullWidth={true}`. */
    fullWidth: {
      width: '100%'
    },

    /* Styles applied to the startIcon element if supplied. */
    startIcon: {
      display: 'inherit',
      marginRight: 8,
      marginLeft: -4,
      '&$iconSizeSmall': {
        marginLeft: -2
      }
    },

    /* Styles applied to the endIcon element if supplied. */
    endIcon: {
      display: 'inherit',
      marginRight: -4,
      marginLeft: 8,
      '&$iconSizeSmall': {
        marginRight: -2
      }
    },

    /* Styles applied to the icon element if supplied and `size="small"`. */
    iconSizeSmall: {
      '& > *:first-child': {
        fontSize: 18
      }
    },

    /* Styles applied to the icon element if supplied and `size="medium"`. */
    iconSizeMedium: {
      '& > *:first-child': {
        fontSize: 20
      }
    },

    /* Styles applied to the icon element if supplied and `size="large"`. */
    iconSizeLarge: {
      '& > *:first-child': {
        fontSize: 22
      }
    }
  };
};
var Button_Button = react_default.a.forwardRef(function Button(props, ref) {
  var children = props.children,
      classes = props.classes,
      className = props.className,
      _props$color = props.color,
      color = _props$color === void 0 ? 'default' : _props$color,
      _props$component = props.component,
      component = _props$component === void 0 ? 'button' : _props$component,
      _props$disabled = props.disabled,
      disabled = _props$disabled === void 0 ? false : _props$disabled,
      _props$disableElevati = props.disableElevation,
      disableElevation = _props$disableElevati === void 0 ? false : _props$disableElevati,
      _props$disableFocusRi = props.disableFocusRipple,
      disableFocusRipple = _props$disableFocusRi === void 0 ? false : _props$disableFocusRi,
      endIconProp = props.endIcon,
      focusVisibleClassName = props.focusVisibleClassName,
      _props$fullWidth = props.fullWidth,
      fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,
      _props$size = props.size,
      size = _props$size === void 0 ? 'medium' : _props$size,
      startIconProp = props.startIcon,
      _props$type = props.type,
      type = _props$type === void 0 ? 'button' : _props$type,
      _props$variant = props.variant,
      variant = _props$variant === void 0 ? 'text' : _props$variant,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["children", "classes", "className", "color", "component", "disabled", "disableElevation", "disableFocusRipple", "endIcon", "focusVisibleClassName", "fullWidth", "size", "startIcon", "type", "variant"]);

  var startIcon = startIconProp && react_default.a.createElement("span", {
    className: Object(clsx_m["a" /* default */])(classes.startIcon, classes["iconSize".concat(Object(capitalize["a" /* default */])(size))])
  }, startIconProp);
  var endIcon = endIconProp && react_default.a.createElement("span", {
    className: Object(clsx_m["a" /* default */])(classes.endIcon, classes["iconSize".concat(Object(capitalize["a" /* default */])(size))])
  }, endIconProp);
  return react_default.a.createElement(esm_ButtonBase_ButtonBase, Object(helpers_esm_extends["a" /* default */])({
    className: Object(clsx_m["a" /* default */])(classes.root, classes[variant], className, color === 'inherit' ? classes.colorInherit : color !== 'default' && classes["".concat(variant).concat(Object(capitalize["a" /* default */])(color))], size !== 'medium' && [classes["".concat(variant, "Size").concat(Object(capitalize["a" /* default */])(size))], classes["size".concat(Object(capitalize["a" /* default */])(size))]], disableElevation && classes.disableElevation, disabled && classes.disabled, fullWidth && classes.fullWidth),
    component: component,
    disabled: disabled,
    focusRipple: !disableFocusRipple,
    focusVisibleClassName: Object(clsx_m["a" /* default */])(classes.focusVisible, focusVisibleClassName),
    ref: ref,
    type: type
  }, other), react_default.a.createElement("span", {
    className: classes.label
  }, startIcon, children, endIcon));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_Button_Button = (Object(withStyles["a" /* default */])(Button_styles, {
  name: 'MuiButton'
})(Button_Button));
// EXTERNAL MODULE: ./node_modules/@material-ui/styles/esm/getThemeProps/getThemeProps.js
var getThemeProps = __webpack_require__(155);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/utils/ownerDocument.js
function ownerDocument(node) {
  return node && node.ownerDocument || document;
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Portal/Portal.js







function getContainer(container) {
  container = typeof container === 'function' ? container() : container; // #StrictMode ready

  return react_dom_default.a.findDOMNode(container);
}

var Portal_useEnhancedEffect = typeof window !== 'undefined' ? react_default.a.useLayoutEffect : react_default.a.useEffect;
/**
 * Portals provide a first-class way to render children into a DOM node
 * that exists outside the DOM hierarchy of the parent component.
 */

var Portal_Portal = react_default.a.forwardRef(function Portal(props, ref) {
  var children = props.children,
      container = props.container,
      _props$disablePortal = props.disablePortal,
      disablePortal = _props$disablePortal === void 0 ? false : _props$disablePortal,
      onRendered = props.onRendered;

  var _React$useState = react_default.a.useState(null),
      mountNode = _React$useState[0],
      setMountNode = _React$useState[1];

  var handleRef = useForkRef(react_default.a.isValidElement(children) ? children.ref : null, ref);
  Portal_useEnhancedEffect(function () {
    if (!disablePortal) {
      setMountNode(getContainer(container) || document.body);
    }
  }, [container, disablePortal]);
  Portal_useEnhancedEffect(function () {
    if (mountNode && !disablePortal) {
      setRef(ref, mountNode);
      return function () {
        setRef(ref, null);
      };
    }

    return undefined;
  }, [ref, mountNode, disablePortal]);
  Portal_useEnhancedEffect(function () {
    if (onRendered && (mountNode || disablePortal)) {
      onRendered();
    }
  }, [onRendered, mountNode, disablePortal]);

  if (disablePortal) {
    if (react_default.a.isValidElement(children)) {
      return react_default.a.cloneElement(children, {
        ref: handleRef
      });
    }

    return children;
  }

  return mountNode ? react_dom_default.a.createPortal(children, mountNode) : mountNode;
});
 false ? undefined : void 0;

if (false) {}

/* harmony default export */ var esm_Portal_Portal = (Portal_Portal);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/utils/createChainedFunction.js
/**
 * Safe chained function
 *
 * Will only create a new function if needed,
 * otherwise will pass back existing functions or null.
 *
 * @param {function} functions to chain
 * @returns {function|null}
 */
function createChainedFunction() {
  for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {
    funcs[_key] = arguments[_key];
  }

  return funcs.reduce(function (acc, func) {
    if (func == null) {
      return acc;
    }

    if (false) {}

    return function chainedFunction() {
      for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }

      acc.apply(this, args);
      func.apply(this, args);
    };
  }, function () {});
}
// EXTERNAL MODULE: ./node_modules/@material-ui/core/esm/styles/zIndex.js
var zIndex = __webpack_require__(35);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/classCallCheck.js
function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/createClass.js
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);
  }
}

function _createClass(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties(Constructor, staticProps);
  return Constructor;
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/utils/getScrollbarSize.js
// A change of the browser zoom change the scrollbar size.
// Credit https://github.com/twbs/bootstrap/blob/3ffe3a5d82f6f561b82ff78d82b32a7d14aed558/js/src/modal.js#L512-L519
function getScrollbarSize() {
  var scrollDiv = document.createElement('div');
  scrollDiv.style.width = '99px';
  scrollDiv.style.height = '99px';
  scrollDiv.style.position = 'absolute';
  scrollDiv.style.top = '-9999px';
  scrollDiv.style.overflow = 'scroll';
  document.body.appendChild(scrollDiv);
  var scrollbarSize = scrollDiv.offsetWidth - scrollDiv.clientWidth;
  document.body.removeChild(scrollDiv);
  return scrollbarSize;
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/utils/ownerWindow.js

function ownerWindow(node) {
  var doc = ownerDocument(node);
  return doc.defaultView || window;
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Modal/ModalManager.js





 // Is a vertical scrollbar displayed?

function isOverflowing(container) {
  var doc = ownerDocument(container);

  if (doc.body === container) {
    return ownerWindow(doc).innerWidth > doc.documentElement.clientWidth;
  }

  return container.scrollHeight > container.clientHeight;
}

function ariaHidden(node, show) {
  if (show) {
    node.setAttribute('aria-hidden', 'true');
  } else {
    node.removeAttribute('aria-hidden');
  }
}

function getPaddingRight(node) {
  return parseInt(window.getComputedStyle(node)['padding-right'], 10) || 0;
}

function ariaHiddenSiblings(container, mountNode, currentNode) {
  var nodesToExclude = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
  var show = arguments.length > 4 ? arguments[4] : undefined;
  var blacklist = [mountNode, currentNode].concat(_toConsumableArray(nodesToExclude));
  var blacklistTagNames = ['TEMPLATE', 'SCRIPT', 'STYLE'];
  [].forEach.call(container.children, function (node) {
    if (node.nodeType === 1 && blacklist.indexOf(node) === -1 && blacklistTagNames.indexOf(node.tagName) === -1) {
      ariaHidden(node, show);
    }
  });
}

function findIndexOf(containerInfo, callback) {
  var idx = -1;
  containerInfo.some(function (item, index) {
    if (callback(item)) {
      idx = index;
      return true;
    }

    return false;
  });
  return idx;
}

function handleContainer(containerInfo, props) {
  var restoreStyle = [];
  var restorePaddings = [];
  var container = containerInfo.container;
  var fixedNodes;

  if (!props.disableScrollLock) {
    if (isOverflowing(container)) {
      // Compute the size before applying overflow hidden to avoid any scroll jumps.
      var scrollbarSize = getScrollbarSize();
      restoreStyle.push({
        value: container.style.paddingRight,
        key: 'padding-right',
        el: container
      }); // Use computed style, here to get the real padding to add our scrollbar width.

      container.style['padding-right'] = "".concat(getPaddingRight(container) + scrollbarSize, "px"); // .mui-fixed is a global helper.

      fixedNodes = ownerDocument(container).querySelectorAll('.mui-fixed');
      [].forEach.call(fixedNodes, function (node) {
        restorePaddings.push(node.style.paddingRight);
        node.style.paddingRight = "".concat(getPaddingRight(node) + scrollbarSize, "px");
      });
    } // Improve Gatsby support
    // https://css-tricks.com/snippets/css/force-vertical-scrollbar/


    var parent = container.parentElement;
    var scrollContainer = parent.nodeName === 'HTML' && window.getComputedStyle(parent)['overflow-y'] === 'scroll' ? parent : container; // Block the scroll even if no scrollbar is visible to account for mobile keyboard
    // screensize shrink.

    restoreStyle.push({
      value: scrollContainer.style.overflow,
      key: 'overflow',
      el: scrollContainer
    });
    scrollContainer.style.overflow = 'hidden';
  }

  var restore = function restore() {
    if (fixedNodes) {
      [].forEach.call(fixedNodes, function (node, i) {
        if (restorePaddings[i]) {
          node.style.paddingRight = restorePaddings[i];
        } else {
          node.style.removeProperty('padding-right');
        }
      });
    }

    restoreStyle.forEach(function (_ref) {
      var value = _ref.value,
          el = _ref.el,
          key = _ref.key;

      if (value) {
        el.style.setProperty(key, value);
      } else {
        el.style.removeProperty(key);
      }
    });
  };

  return restore;
}

function getHiddenSiblings(container) {
  var hiddenSiblings = [];
  [].forEach.call(container.children, function (node) {
    if (node.getAttribute && node.getAttribute('aria-hidden') === 'true') {
      hiddenSiblings.push(node);
    }
  });
  return hiddenSiblings;
}
/**
 * @ignore - do not document.
 *
 * Proper state management for containers and the modals in those containers.
 * Simplified, but inspired by react-overlay's ModalManager class.
 * Used by the Modal to ensure proper styling of containers.
 */


var ModalManager_ModalManager =
/*#__PURE__*/
function () {
  function ModalManager() {
    _classCallCheck(this, ModalManager);

    // this.modals[modalIndex] = modal
    this.modals = []; // this.containers[containerIndex] = {
    //   modals: [],
    //   container,
    //   restore: null,
    // }

    this.containers = [];
  }

  _createClass(ModalManager, [{
    key: "add",
    value: function add(modal, container) {
      var modalIndex = this.modals.indexOf(modal);

      if (modalIndex !== -1) {
        return modalIndex;
      }

      modalIndex = this.modals.length;
      this.modals.push(modal); // If the modal we are adding is already in the DOM.

      if (modal.modalRef) {
        ariaHidden(modal.modalRef, false);
      }

      var hiddenSiblingNodes = getHiddenSiblings(container);
      ariaHiddenSiblings(container, modal.mountNode, modal.modalRef, hiddenSiblingNodes, true);
      var containerIndex = findIndexOf(this.containers, function (item) {
        return item.container === container;
      });

      if (containerIndex !== -1) {
        this.containers[containerIndex].modals.push(modal);
        return modalIndex;
      }

      this.containers.push({
        modals: [modal],
        container: container,
        restore: null,
        hiddenSiblingNodes: hiddenSiblingNodes
      });
      return modalIndex;
    }
  }, {
    key: "mount",
    value: function mount(modal, props) {
      var containerIndex = findIndexOf(this.containers, function (item) {
        return item.modals.indexOf(modal) !== -1;
      });
      var containerInfo = this.containers[containerIndex];

      if (!containerInfo.restore) {
        containerInfo.restore = handleContainer(containerInfo, props);
      }
    }
  }, {
    key: "remove",
    value: function remove(modal) {
      var modalIndex = this.modals.indexOf(modal);

      if (modalIndex === -1) {
        return modalIndex;
      }

      var containerIndex = findIndexOf(this.containers, function (item) {
        return item.modals.indexOf(modal) !== -1;
      });
      var containerInfo = this.containers[containerIndex];
      containerInfo.modals.splice(containerInfo.modals.indexOf(modal), 1);
      this.modals.splice(modalIndex, 1); // If that was the last modal in a container, clean up the container.

      if (containerInfo.modals.length === 0) {
        // The modal might be closed before it had the chance to be mounted in the DOM.
        if (containerInfo.restore) {
          containerInfo.restore();
        }

        if (modal.modalRef) {
          // In case the modal wasn't in the DOM yet.
          ariaHidden(modal.modalRef, true);
        }

        ariaHiddenSiblings(containerInfo.container, modal.mountNode, modal.modalRef, containerInfo.hiddenSiblingNodes, false);
        this.containers.splice(containerIndex, 1);
      } else {
        // Otherwise make sure the next top modal is visible to a screen reader.
        var nextTop = containerInfo.modals[containerInfo.modals.length - 1]; // as soon as a modal is adding its modalRef is undefined. it can't set
        // aria-hidden because the dom element doesn't exist either
        // when modal was unmounted before modalRef gets null

        if (nextTop.modalRef) {
          ariaHidden(nextTop.modalRef, false);
        }
      }

      return modalIndex;
    }
  }, {
    key: "isTopModal",
    value: function isTopModal(modal) {
      return this.modals.length > 0 && this.modals[this.modals.length - 1] === modal;
    }
  }]);

  return ModalManager;
}();


// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Modal/TrapFocus.js
/* eslint-disable consistent-return, jsx-a11y/no-noninteractive-tabindex */





/**
 * @ignore - internal component.
 */

function TrapFocus(props) {
  var children = props.children,
      _props$disableAutoFoc = props.disableAutoFocus,
      disableAutoFocus = _props$disableAutoFoc === void 0 ? false : _props$disableAutoFoc,
      _props$disableEnforce = props.disableEnforceFocus,
      disableEnforceFocus = _props$disableEnforce === void 0 ? false : _props$disableEnforce,
      _props$disableRestore = props.disableRestoreFocus,
      disableRestoreFocus = _props$disableRestore === void 0 ? false : _props$disableRestore,
      getDoc = props.getDoc,
      isEnabled = props.isEnabled,
      open = props.open;
  var ignoreNextEnforceFocus = react_default.a.useRef();
  var sentinelStart = react_default.a.useRef(null);
  var sentinelEnd = react_default.a.useRef(null);
  var nodeToRestore = react_default.a.useRef();
  var rootRef = react_default.a.useRef(null); // can be removed once we drop support for non ref forwarding class components

  var handleOwnRef = react_default.a.useCallback(function (instance) {
    // #StrictMode ready
    rootRef.current = react_dom_default.a.findDOMNode(instance);
  }, []);
  var handleRef = useForkRef(children.ref, handleOwnRef); // ⚠️ You may rely on React.useMemo as a performance optimization, not as a semantic guarantee.
  // https://reactjs.org/docs/hooks-reference.html#usememo

  react_default.a.useMemo(function () {
    if (!open || typeof window === 'undefined') {
      return;
    }

    nodeToRestore.current = getDoc().activeElement;
  }, [open]); // eslint-disable-line react-hooks/exhaustive-deps

  react_default.a.useEffect(function () {
    if (!open) {
      return;
    }

    var doc = ownerDocument(rootRef.current); // We might render an empty child.

    if (!disableAutoFocus && rootRef.current && !rootRef.current.contains(doc.activeElement)) {
      if (!rootRef.current.hasAttribute('tabIndex')) {
        if (false) {}

        rootRef.current.setAttribute('tabIndex', -1);
      }

      rootRef.current.focus();
    }

    var contain = function contain() {
      if (disableEnforceFocus || !isEnabled() || ignoreNextEnforceFocus.current) {
        ignoreNextEnforceFocus.current = false;
        return;
      }

      if (rootRef.current && !rootRef.current.contains(doc.activeElement)) {
        rootRef.current.focus();
      }
    };

    var loopFocus = function loopFocus(event) {
      // 9 = Tab
      if (disableEnforceFocus || !isEnabled() || event.keyCode !== 9) {
        return;
      } // Make sure the next tab starts from the right place.


      if (doc.activeElement === rootRef.current) {
        // We need to ignore the next contain as
        // it will try to move the focus back to the rootRef element.
        ignoreNextEnforceFocus.current = true;

        if (event.shiftKey) {
          sentinelEnd.current.focus();
        } else {
          sentinelStart.current.focus();
        }
      }
    };

    doc.addEventListener('focus', contain, true);
    doc.addEventListener('keydown', loopFocus, true); // With Edge, Safari and Firefox, no focus related events are fired when the focused area stops being a focused area
    // e.g. https://bugzilla.mozilla.org/show_bug.cgi?id=559561.
    //
    // The whatwg spec defines how the browser should behave but does not explicitly mention any events:
    // https://html.spec.whatwg.org/multipage/interaction.html#focus-fixup-rule.

    var interval = setInterval(function () {
      contain();
    }, 50);
    return function () {
      clearInterval(interval);
      doc.removeEventListener('focus', contain, true);
      doc.removeEventListener('keydown', loopFocus, true); // restoreLastFocus()

      if (!disableRestoreFocus) {
        // In IE 11 it is possible for document.activeElement to be null resulting
        // in nodeToRestore.current being null.
        // Not all elements in IE 11 have a focus method.
        // Once IE 11 support is dropped the focus() call can be unconditional.
        if (nodeToRestore.current && nodeToRestore.current.focus) {
          nodeToRestore.current.focus();
        }

        nodeToRestore.current = null;
      }
    };
  }, [disableAutoFocus, disableEnforceFocus, disableRestoreFocus, isEnabled, open]);
  return react_default.a.createElement(react_default.a.Fragment, null, react_default.a.createElement("div", {
    tabIndex: 0,
    ref: sentinelStart,
    "data-test": "sentinelStart"
  }), react_default.a.cloneElement(children, {
    ref: handleRef
  }), react_default.a.createElement("div", {
    tabIndex: 0,
    ref: sentinelEnd,
    "data-test": "sentinelEnd"
  }));
}

 false ? undefined : void 0;
/*

In the future, we should be able to replace TrapFocus with:
https://github.com/facebook/react/blob/master/packages/react-events/docs/FocusScope.md

```jsx
import FocusScope from 'react-dom/FocusScope';

function TrapFocus(props) {
  const {
    children
    disableAutoFocus = false,
    disableEnforceFocus = false,
    disableRestoreFocus = false,
    open,
  } = props;

  if (!open) {
    return children;
  }

  return (
    <FocusScope
      autoFocus={!disableAutoFocus}
      contain={!disableEnforceFocus}
      restoreFocus={!disableRestoreFocus}
    >
      {children}
    </FocusScope>
  );
}
```

*/

/* harmony default export */ var Modal_TrapFocus = (TrapFocus);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Modal/SimpleBackdrop.js




var SimpleBackdrop_styles = {
  /* Styles applied to the root element. */
  root: {
    zIndex: -1,
    position: 'fixed',
    right: 0,
    bottom: 0,
    top: 0,
    left: 0,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    WebkitTapHighlightColor: 'transparent'
  },

  /* Styles applied to the root element if `invisible={true}`. */
  invisible: {
    backgroundColor: 'transparent'
  }
};
/**
 * @ignore - internal component.
 */

var SimpleBackdrop_SimpleBackdrop = react_default.a.forwardRef(function SimpleBackdrop(props, ref) {
  var _props$invisible = props.invisible,
      invisible = _props$invisible === void 0 ? false : _props$invisible,
      open = props.open,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["invisible", "open"]);

  return open ? react_default.a.createElement("div", Object(helpers_esm_extends["a" /* default */])({
    "aria-hidden": true,
    ref: ref
  }, other, {
    style: Object(helpers_esm_extends["a" /* default */])({}, SimpleBackdrop_styles.root, {}, invisible ? SimpleBackdrop_styles.invisible : {}, {}, other.style)
  })) : null;
});
 false ? undefined : void 0;
/* harmony default export */ var Modal_SimpleBackdrop = (SimpleBackdrop_SimpleBackdrop);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Modal/Modal.js

















function Modal_getContainer(container) {
  container = typeof container === 'function' ? container() : container;
  return react_dom_default.a.findDOMNode(container);
}

function getHasTransition(props) {
  return props.children ? props.children.props.hasOwnProperty('in') : false;
} // A modal manager used to track and manage the state of open Modals.
// Modals don't open on the server so this won't conflict with concurrent requests.


var defaultManager = new ModalManager_ModalManager();
var Modal_styles = function styles(theme) {
  return {
    /* Styles applied to the root element. */
    root: {
      position: 'fixed',
      zIndex: theme.zIndex.modal,
      right: 0,
      bottom: 0,
      top: 0,
      left: 0
    },

    /* Styles applied to the root element if the `Modal` has exited. */
    hidden: {
      visibility: 'hidden'
    }
  };
};
/**
 * Modal is a lower-level construct that is leveraged by the following components:
 *
 * - [Dialog](/api/dialog/)
 * - [Drawer](/api/drawer/)
 * - [Menu](/api/menu/)
 * - [Popover](/api/popover/)
 *
 * If you are creating a modal dialog, you probably want to use the [Dialog](/api/dialog/) component
 * rather than directly using Modal.
 *
 * This component shares many concepts with [react-overlays](https://react-bootstrap.github.io/react-overlays/#modals).
 */

var Modal_Modal = react_default.a.forwardRef(function Modal(inProps, ref) {
  var theme = Object(useTheme["a" /* default */])();
  var props = Object(getThemeProps["a" /* default */])({
    name: 'MuiModal',
    props: Object(helpers_esm_extends["a" /* default */])({}, inProps),
    theme: theme
  });

  var _props$BackdropCompon = props.BackdropComponent,
      BackdropComponent = _props$BackdropCompon === void 0 ? Modal_SimpleBackdrop : _props$BackdropCompon,
      BackdropProps = props.BackdropProps,
      children = props.children,
      _props$closeAfterTran = props.closeAfterTransition,
      closeAfterTransition = _props$closeAfterTran === void 0 ? false : _props$closeAfterTran,
      container = props.container,
      _props$disableAutoFoc = props.disableAutoFocus,
      disableAutoFocus = _props$disableAutoFoc === void 0 ? false : _props$disableAutoFoc,
      _props$disableBackdro = props.disableBackdropClick,
      disableBackdropClick = _props$disableBackdro === void 0 ? false : _props$disableBackdro,
      _props$disableEnforce = props.disableEnforceFocus,
      disableEnforceFocus = _props$disableEnforce === void 0 ? false : _props$disableEnforce,
      _props$disableEscapeK = props.disableEscapeKeyDown,
      disableEscapeKeyDown = _props$disableEscapeK === void 0 ? false : _props$disableEscapeK,
      _props$disablePortal = props.disablePortal,
      disablePortal = _props$disablePortal === void 0 ? false : _props$disablePortal,
      _props$disableRestore = props.disableRestoreFocus,
      disableRestoreFocus = _props$disableRestore === void 0 ? false : _props$disableRestore,
      _props$disableScrollL = props.disableScrollLock,
      disableScrollLock = _props$disableScrollL === void 0 ? false : _props$disableScrollL,
      _props$hideBackdrop = props.hideBackdrop,
      hideBackdrop = _props$hideBackdrop === void 0 ? false : _props$hideBackdrop,
      _props$keepMounted = props.keepMounted,
      keepMounted = _props$keepMounted === void 0 ? false : _props$keepMounted,
      _props$manager = props.manager,
      manager = _props$manager === void 0 ? defaultManager : _props$manager,
      onBackdropClick = props.onBackdropClick,
      onClose = props.onClose,
      onEscapeKeyDown = props.onEscapeKeyDown,
      onRendered = props.onRendered,
      open = props.open,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["BackdropComponent", "BackdropProps", "children", "closeAfterTransition", "container", "disableAutoFocus", "disableBackdropClick", "disableEnforceFocus", "disableEscapeKeyDown", "disablePortal", "disableRestoreFocus", "disableScrollLock", "hideBackdrop", "keepMounted", "manager", "onBackdropClick", "onClose", "onEscapeKeyDown", "onRendered", "open"]);

  var _React$useState = react_default.a.useState(true),
      exited = _React$useState[0],
      setExited = _React$useState[1];

  var modal = react_default.a.useRef({});
  var mountNodeRef = react_default.a.useRef(null);
  var modalRef = react_default.a.useRef(null);
  var handleRef = useForkRef(modalRef, ref);
  var hasTransition = getHasTransition(props);

  var getDoc = function getDoc() {
    return ownerDocument(mountNodeRef.current);
  };

  var getModal = function getModal() {
    modal.current.modalRef = modalRef.current;
    modal.current.mountNode = mountNodeRef.current;
    return modal.current;
  };

  var handleMounted = function handleMounted() {
    manager.mount(getModal(), {
      disableScrollLock: disableScrollLock
    }); // Fix a bug on Chrome where the scroll isn't initially 0.

    modalRef.current.scrollTop = 0;
  };

  var handleOpen = useEventCallback(function () {
    var resolvedContainer = Modal_getContainer(container) || getDoc().body;
    manager.add(getModal(), resolvedContainer); // The element was already mounted.

    if (modalRef.current) {
      handleMounted();
    }
  });
  var isTopModal = react_default.a.useCallback(function () {
    return manager.isTopModal(getModal());
  }, [manager]);
  var handlePortalRef = useEventCallback(function (node) {
    mountNodeRef.current = node;

    if (!node) {
      return;
    }

    if (onRendered) {
      onRendered();
    }

    if (open && isTopModal()) {
      handleMounted();
    } else {
      ariaHidden(modalRef.current, true);
    }
  });
  var handleClose = react_default.a.useCallback(function () {
    manager.remove(getModal());
  }, [manager]);
  react_default.a.useEffect(function () {
    return function () {
      handleClose();
    };
  }, [handleClose]);
  react_default.a.useEffect(function () {
    if (open) {
      handleOpen();
    } else if (!hasTransition || !closeAfterTransition) {
      handleClose();
    }
  }, [open, handleClose, hasTransition, closeAfterTransition, handleOpen]);

  if (!keepMounted && !open && (!hasTransition || exited)) {
    return null;
  }

  var handleEnter = function handleEnter() {
    setExited(false);
  };

  var handleExited = function handleExited() {
    setExited(true);

    if (closeAfterTransition) {
      handleClose();
    }
  };

  var handleBackdropClick = function handleBackdropClick(event) {
    if (event.target !== event.currentTarget) {
      return;
    }

    if (onBackdropClick) {
      onBackdropClick(event);
    }

    if (!disableBackdropClick && onClose) {
      onClose(event, 'backdropClick');
    }
  };

  var handleKeyDown = function handleKeyDown(event) {
    // The handler doesn't take event.defaultPrevented into account:
    //
    // event.preventDefault() is meant to stop default behaviours like
    // clicking a checkbox to check it, hitting a button to submit a form,
    // and hitting left arrow to move the cursor in a text input etc.
    // Only special HTML elements have these default behaviors.
    if (event.key !== 'Escape' || !isTopModal()) {
      return;
    } // Swallow the event, in case someone is listening for the escape key on the body.


    event.stopPropagation();

    if (onEscapeKeyDown) {
      onEscapeKeyDown(event);
    }

    if (!disableEscapeKeyDown && onClose) {
      onClose(event, 'escapeKeyDown');
    }
  };

  var inlineStyle = Modal_styles(theme || {
    zIndex: zIndex["a" /* default */]
  });
  var childProps = {};

  if (children.props.tabIndex === undefined) {
    childProps.tabIndex = children.props.tabIndex || '-1';
  } // It's a Transition like component


  if (hasTransition) {
    childProps.onEnter = createChainedFunction(handleEnter, children.props.onEnter);
    childProps.onExited = createChainedFunction(handleExited, children.props.onExited);
  }

  return react_default.a.createElement(esm_Portal_Portal, {
    ref: handlePortalRef,
    container: container,
    disablePortal: disablePortal
  }, react_default.a.createElement("div", Object(helpers_esm_extends["a" /* default */])({
    ref: handleRef,
    onKeyDown: handleKeyDown,
    role: "presentation"
  }, other, {
    style: Object(helpers_esm_extends["a" /* default */])({}, inlineStyle.root, {}, !open && exited ? inlineStyle.hidden : {}, {}, other.style)
  }), hideBackdrop ? null : react_default.a.createElement(BackdropComponent, Object(helpers_esm_extends["a" /* default */])({
    open: open,
    onClick: handleBackdropClick
  }, BackdropProps)), react_default.a.createElement(Modal_TrapFocus, {
    disableEnforceFocus: disableEnforceFocus,
    disableAutoFocus: disableAutoFocus,
    disableRestoreFocus: disableRestoreFocus,
    getDoc: getDoc,
    isEnabled: isTopModal,
    open: open
  }, react_default.a.cloneElement(children, childProps))));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_Modal_Modal = (Modal_Modal);
// EXTERNAL MODULE: ./node_modules/@material-ui/core/esm/styles/defaultTheme.js
var defaultTheme = __webpack_require__(26);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/useTheme.js


function useTheme_useTheme() {
  return Object(useTheme["a" /* default */])() || defaultTheme["a" /* default */];
}
// CONCATENATED MODULE: ./src/components/QdtModal/QdtModalStyles.js
var QdtModalStyles_styles = function styles(theme) {
  return {
    modalContainer: {
      position: 'absolute',
      width: '90%',
      maxWidth: 500,
      backgroundColor: theme.palette.background.paper,
      border: "1px solid ".concat(theme.palette.grey[300]),
      boxShadow: theme.shadows[5],
      // padding: theme.spacing(2, 4, 3),
      padding: 0,
      top: '50%',
      left: '50%',
      transform: 'translate(-50%, -50%)'
    },
    modalHeader: {
      padding: 15,
      fontSize: '1.1em',
      fontWeight: 900,
      backgroundColor: theme.palette.grey[100],
      // width: '100%',
      width: 'auto',
      position: 'relative'
    },
    modalBody: {
      padding: 15,
      width: 'auto',
      position: 'relative'
    },
    modalFooter: {
      padding: 15,
      borderTop: "1px solid ".concat(theme.palette.grey[300]),
      backgroundColor: theme.palette.grey[100],
      textAlign: 'right',
      position: 'relative',
      width: 'auto'
    }
  };
};

/* harmony default export */ var QdtModalStyles = (QdtModalStyles_styles);
// CONCATENATED MODULE: ./src/components/QdtModal/QdtModal.jsx






var QdtModal_QdtModal = function QdtModal(_ref) {
  var open = _ref.open,
      header = _ref.header,
      body = _ref.body,
      footer = _ref.footer,
      handleClose = _ref.handleClose;
  var theme = useTheme_useTheme();
  var style = QdtModalStyles(theme);
  return react_default.a.createElement("div", null, react_default.a.createElement(esm_Modal_Modal, {
    open: open,
    onClose: handleClose,
    "aria-labelledby": "QdtModal",
    "aria-describedby": "QdtModal"
  }, react_default.a.createElement("div", {
    style: style.modalContainer
  }, header && react_default.a.createElement("div", {
    style: style.modalHeader
  }, header), body && react_default.a.createElement("div", {
    style: style.modalBody
  }, body), footer && react_default.a.createElement("div", {
    style: style.modalFooter
  }, footer))));
};

QdtModal_QdtModal.propTypes = {
  open: prop_types_default.a.bool.isRequired,
  handleClose: prop_types_default.a.func,
  header: prop_types_default.a.string,
  body: prop_types_default.a.string,
  footer: prop_types_default.a.string
};
QdtModal_QdtModal.defaultProps = {
  handleClose: null,
  header: null,
  body: null,
  footer: null
};
/* harmony default export */ var components_QdtModal_QdtModal = (QdtModal_QdtModal);
// CONCATENATED MODULE: ./src/utils/ConnectionLost.jsx
 //eslint-disable-line

 //eslint-disable-line



/* harmony default export */ var ConnectionLost = (function (_ref) {
  var refreshUrl = _ref.refreshUrl,
      timeoutMessage = _ref.timeoutMessage;
  var element = document.createElement('div');
  var header = 'Connection lost';
  var body = timeoutMessage || 'Your connection to the Qlik Sense server is lost due to inactivity, refresh to continue working.';

  var refresh = function refresh() {
    return refreshUrl ? window.location = refreshUrl : window.location.reload();
  };

  var footer = react_default.a.createElement(esm_Button_Button, {
    variant: "contained",
    onClick: refresh
  }, "Refresh");
  react_dom_default.a.unmountComponentAtNode(element);
  react_dom_default.a.render(react_default.a.createElement(components_QdtModal_QdtModal, {
    open: true,
    header: header,
    body: body,
    footer: footer
  }), element);
});
// CONCATENATED MODULE: ./src/qdtEnigma.js




var enigma = __webpack_require__(90);

var schema = __webpack_require__(91);

var SenseUtilities = __webpack_require__(92);

var MAX_RETRIES = 3;
var responseInterceptors = [{
  // We only want to handle failed responses from QIX Engine:
  onRejected: function retryAbortedError(sessionReference, request, error) {
    // We only want to handle aborted QIX errors:
    if (error.code === schema.enums.LocalizedErrorCode.LOCERR_GENERIC_ABORTED) {
      // We keep track of how many consecutive times we have tried to do this call:
      request.tries = (request.tries || 0) + 1; // We do not want to get stuck in an infinite loop here if something has gone
      // awry, so we only retry until we have reached MAX_RETRIES:

      if (request.tries <= MAX_RETRIES) {
        return request.retry();
      }
    } // If it was not an aborted QIX call, or if we reached MAX_RETRIES, we let the error
    // trickle down to potential other interceptors, and finally down to resolving/rejecting
    // the initial promise that the user got when invoking the QIX method:


    return this.Promise.reject(error);
  }
}];

var qdtEnigma =
/*#__PURE__*/
function () {
  var _ref = asyncToGenerator_default()(
  /*#__PURE__*/
  regenerator_default.a.mark(function _callee(config) {
    var myConfig, timeoutMessage, core, suspendOnClose, url, session, global;
    return regenerator_default.a.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            myConfig = config;
            timeoutMessage = myConfig.timeoutMessage, core = myConfig.core, suspendOnClose = myConfig.suspendOnClose; // Make it work for Qlik Core scaling https://github.com/qlik-oss/core-scaling
            // qlikcore/engine:12.248.0

            if (core) {
              myConfig.subpath = myConfig.prefix ? "".concat(myConfig.prefix, "/app") : 'app';
              myConfig.route = "doc/".concat(myConfig.appId);
            }

            url = SenseUtilities.buildUrl(myConfig);
            session = enigma.create({
              schema: schema,
              url: url,
              responseInterceptors: responseInterceptors,
              suspendOnClose: suspendOnClose
            });
            _context.next = 7;
            return session.open();

          case 7:
            global = _context.sent;

            if (!core) {
              _context.next = 10;
              break;
            }

            return _context.abrupt("return", global.getActiveDoc());

          case 10:
            session.on('closed', function () {
              console.error('Session ended.');
              var refreshUrl = window.location.origin; // if (identity) refreshUrl += `?identity=${myConfig.identity}`;

              ConnectionLost({
                refreshUrl: refreshUrl,
                timeoutMessage: timeoutMessage
              });
            });
            session.on('suspended', function () {
              console.error('Session suspended.');
              var refreshUrl = window.location.origin; // if (identity) refreshUrl += `?identity=${myConfig.identity}`;

              ConnectionLost({
                refreshUrl: refreshUrl,
                timeoutMessage: timeoutMessage
              });
            });
            return _context.abrupt("return", global.openDoc(myConfig.appId));

          case 13:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

  return function qdtEnigma(_x) {
    return _ref.apply(this, arguments);
  };
}();

/* harmony default export */ var src_qdtEnigma = (qdtEnigma);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/defineProperty.js
var defineProperty = __webpack_require__(18);
var defineProperty_default = /*#__PURE__*/__webpack_require__.n(defineProperty);

// CONCATENATED MODULE: ./src/qdtCapabilityApp.js




function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { defineProperty_default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

// import utility from './utilities';
// let qlik;
// let { qlik } = utility.qlobals;
var globals = {
  qlik: null,
  resize: null
};
var capabilityApisPromise;

var loadCapabilityApis =
/*#__PURE__*/
function () {
  var _ref = asyncToGenerator_default()(
  /*#__PURE__*/
  regenerator_default.a.mark(function _callee(config) {
    var capabilityApisJS, prefix, capabilityApisCSS;
    return regenerator_default.a.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;

            if (!capabilityApisPromise) {
              _context.next = 5;
              break;
            }

            _context.next = 4;
            return capabilityApisPromise;

          case 4:
            return _context.abrupt("return");

          case 5:
            capabilityApisJS = document.createElement('script');
            prefix = config.prefix !== '' ? "/".concat(config.prefix) : '';
            capabilityApisJS.src = "".concat((config.secure ? 'https://' : 'http://') + config.host + (config.port ? ":".concat(config.port) : '') + prefix, "/resources/assets/external/requirejs/require.js");
            document.head.appendChild(capabilityApisJS);
            capabilityApisJS.loaded = new Promise(function (resolve) {
              capabilityApisJS.onload = function () {
                resolve();
              };
            });
            capabilityApisCSS = document.createElement('link');
            capabilityApisCSS.href = "".concat((config.secure ? 'https://' : 'http://') + config.host + (config.port ? ":".concat(config.port) : '') + prefix, "/resources/autogenerated/qlik-styles.css");
            capabilityApisCSS.type = 'text/css';
            capabilityApisCSS.rel = 'stylesheet';
            document.head.appendChild(capabilityApisCSS);
            capabilityApisCSS.loaded = new Promise(function (resolve) {
              capabilityApisCSS.onload = function () {
                resolve();
              };
            });
            capabilityApisPromise = Promise.all([capabilityApisJS.loaded, capabilityApisCSS.loaded]);
            _context.next = 19;
            return capabilityApisPromise;

          case 19:
            _context.next = 24;
            break;

          case 21:
            _context.prev = 21;
            _context.t0 = _context["catch"](0);
            throw new Error(_context.t0);

          case 24:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 21]]);
  }));

  return function loadCapabilityApis(_x) {
    return _ref.apply(this, arguments);
  };
}();

var qApp =
/*#__PURE__*/
function () {
  var _ref2 = asyncToGenerator_default()(
  /*#__PURE__*/
  regenerator_default.a.mark(function _callee2(config) {
    var prefix;
    return regenerator_default.a.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.prev = 0;
            _context2.next = 3;
            return loadCapabilityApis(config);

          case 3:
            prefix = config.prefix !== '' ? "/".concat(config.prefix, "/") : '/';

            window.require.config({
              baseUrl: "".concat((config.secure ? 'https://' : 'http://') + config.host + (config.port ? ":".concat(config.port) : '') + prefix, "resources"),
              paths: {
                qlik: "".concat((config.secure ? 'https://' : 'http://') + config.host + (config.port ? ":".concat(config.port) : '') + prefix, "resources/js/qlik")
              },
              webIntegrationId: config.webIntegrationId,
              config: {
                text: {
                  useXhr: function useXhr() {
                    return true;
                  }
                }
              }
            });

            return _context2.abrupt("return", new Promise(function (resolve) {
              if (globals.qlik) {
                var app = globals.qlik.openApp(config.appId, _objectSpread({}, config, {
                  isSecure: config.secure,
                  prefix: prefix
                })); // apply theme set in QSE

                app.theme.get().then(function (theme) {
                  theme.apply();
                });
                resolve(app);
              } else {
                window.require(['js/qlik'], function (q) {
                  globals.qlik = q;

                  globals.resize = function () {
                    q.resize();
                  };

                  var app = q.openApp(config.appId, _objectSpread({}, config, {
                    isSecure: config.secure,
                    prefix: prefix
                  }));
                  resolve(app);
                });
              }
            }));

          case 8:
            _context2.prev = 8;
            _context2.t0 = _context2["catch"](0);
            throw new Error(_context2.t0);

          case 11:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[0, 8]]);
  }));

  return function qApp(_x2) {
    return _ref2.apply(this, arguments);
  };
}();

/* harmony default export */ var qdtCapabilityApp = (qApp);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/CssBaseline/CssBaseline.js





var CssBaseline_html = {
  WebkitFontSmoothing: 'antialiased',
  // Antialiasing.
  MozOsxFontSmoothing: 'grayscale',
  // Antialiasing.
  // Change from `box-sizing: content-box` so that `width`
  // is not affected by `padding` or `border`.
  boxSizing: 'border-box'
};
var CssBaseline_body = function body(theme) {
  return Object(helpers_esm_extends["a" /* default */])({
    color: theme.palette.text.primary
  }, theme.typography.body2, {
    backgroundColor: theme.palette.background.default,
    '@media print': {
      // Save printer ink.
      backgroundColor: theme.palette.common.white
    }
  });
};
var CssBaseline_styles = function styles(theme) {
  return {
    '@global': {
      html: CssBaseline_html,
      '*, *::before, *::after': {
        boxSizing: 'inherit'
      },
      'strong, b': {
        fontWeight: theme.typography.fontWeightBold
      },
      body: Object(helpers_esm_extends["a" /* default */])({
        margin: 0
      }, CssBaseline_body(theme), {
        // Add support for document.body.requestFullScreen().
        // Other elements, if background transparent, are not supported.
        '&::backdrop': {
          backgroundColor: theme.palette.background.default
        }
      })
    }
  };
};
/**
 * Kickstart an elegant, consistent, and simple baseline to build upon.
 */

function CssBaseline(props) {
  /* eslint-disable no-unused-vars */
  var _props$children = props.children,
      children = _props$children === void 0 ? null : _props$children,
      classes = props.classes;
  /* eslint-enable no-unused-vars */

  return react_default.a.createElement(react_default.a.Fragment, null, children);
}

 false ? undefined : void 0;

if (false) {}

/* harmony default export */ var CssBaseline_CssBaseline = (Object(withStyles["a" /* default */])(CssBaseline_styles, {
  name: 'MuiCssBaseline'
})(CssBaseline));
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/slicedToArray.js
var slicedToArray = __webpack_require__(15);
var slicedToArray_default = /*#__PURE__*/__webpack_require__.n(slicedToArray);

// EXTERNAL MODULE: ./node_modules/deep-equal/index.js
var deep_equal = __webpack_require__(38);
var deep_equal_default = /*#__PURE__*/__webpack_require__.n(deep_equal);

// EXTERNAL MODULE: ./src/utils/merge.js
var merge = __webpack_require__(3);

// CONCATENATED MODULE: ./src/hooks/useSessionObject.jsx





function useSessionObject_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function useSessionObject_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { useSessionObject_ownKeys(Object(source), true).forEach(function (key) { defineProperty_default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { useSessionObject_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

 // eslint-disable-line



var defaultHyperCubeDef = {
  qDimensions: [],
  qMeasures: [],
  qInitialDataFetch: [{
    qTop: 0,
    qLeft: 0,
    qWidth: 10,
    qHeight: 1000
  }],
  qSortByAscii: 1,
  qSortByLoadOrder: 1,
  qInterColumnSortOrder: [],
  qSuppressZero: true,
  qSuppressMissing: true
};
var defaultListObjectDef = {
  qDef: {
    qSortCriterias: [{
      qSortByState: 0
    }]
  },
  qInitialDataFetch: [{
    qTop: 0,
    qWidth: 1,
    qHeight: 10000
  }],
  qSortByAscii: 1,
  qSortByLoadOrder: 1,
  qInterColumnSortOrder: [],
  qSuppressZero: true,
  qSuppressMissing: true
};

var useSessionObject_useSessionObject = function useSessionObject(_ref) {
  var app = _ref.app,
      propertiesProp = _ref.properties,
      onLayoutChange = _ref.onLayoutChange;

  var properties = useSessionObject_objectSpread({}, propertiesProp);

  properties.qInfo = {
    qType: 'qdt'
  };

  if (properties.qHyperCubeDef) {
    properties.qHyperCubeDef = Object(merge["a" /* default */])(defaultHyperCubeDef, properties.qHyperCubeDef);
  }

  if (properties.qListObjectDef) {
    properties.qListObjectDef = Object(merge["a" /* default */])(defaultListObjectDef, properties.qListObjectDef);
  }

  var staleProperties = Object(react["useRef"])();
  var qProp = Object(react["useRef"])();
  qProp.current = properties;
  var model = Object(react["useRef"])(null);

  var _useState = Object(react["useState"])(null),
      _useState2 = slicedToArray_default()(_useState, 2),
      layout = _useState2[0],
      setLayout = _useState2[1];

  var onLayoutChangeRef = Object(react["useRef"])(onLayoutChange);
  Object(react["useEffect"])(function () {
    onLayoutChangeRef.current = onLayoutChange;
  }, [onLayoutChange]);
  Object(react["useEffect"])(function () {
    asyncToGenerator_default()(
    /*#__PURE__*/
    regenerator_default.a.mark(function _callee2() {
      return regenerator_default.a.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return app.createSessionObject(qProp.current);

            case 2:
              model.current = _context2.sent;
              model.current.on('changed',
              /*#__PURE__*/
              asyncToGenerator_default()(
              /*#__PURE__*/
              regenerator_default.a.mark(function _callee() {
                var _layout;

                return regenerator_default.a.wrap(function _callee$(_context) {
                  while (1) {
                    switch (_context.prev = _context.next) {
                      case 0:
                        _context.next = 2;
                        return model.current.getLayout();

                      case 2:
                        _layout = _context.sent;
                        setLayout(_layout);

                        if (onLayoutChangeRef.current) {
                          onLayoutChangeRef.current({
                            layout: _layout
                          });
                        }

                      case 5:
                      case "end":
                        return _context.stop();
                    }
                  }
                }, _callee);
              })));
              model.current.setProperties(qProp.current);

            case 5:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }))();

    return function () {
      asyncToGenerator_default()(
      /*#__PURE__*/
      regenerator_default.a.mark(function _callee3() {
        return regenerator_default.a.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                app.destroySessionObject(model.current.id);

              case 1:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3);
      }))();
    };
  }, [app]); // eslint-disable-line

  if (model.current && !deep_equal_default()(staleProperties.current, properties)) {
    // setLayout(null);
    asyncToGenerator_default()(
    /*#__PURE__*/
    regenerator_default.a.mark(function _callee4() {
      return regenerator_default.a.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              _context4.next = 2;
              return model.current.setProperties(qProp.current);

            case 2:
            case "end":
              return _context4.stop();
          }
        }
      }, _callee4);
    }))();
  }

  staleProperties.current = properties;
  return {
    model: model.current,
    layout: layout
  };
};

/* harmony default export */ var hooks_useSessionObject = (useSessionObject_useSessionObject);
// CONCATENATED MODULE: ./src/components/QdtComponent/QdtComponent.jsx



var QdtComponent = react_default.a.forwardRef(function (_ref, _ref2) {
  var Component = _ref.Component,
      options = _ref.options,
      app = _ref.app,
      properties = _ref.properties,
      LoadingComponent = _ref.LoadingComponent,
      onLayoutChange = _ref.onLayoutChange;
  var componentRef = _ref2.componentRef,
      modelRef = _ref2.modelRef,
      layoutRef = _ref2.layoutRef;

  var _useSessionObject = hooks_useSessionObject({
    app: app,
    properties: properties,
    onLayoutChange: onLayoutChange
  }),
      model = _useSessionObject.model,
      layout = _useSessionObject.layout;

  modelRef.current = model; //eslint-disable-line

  layoutRef.current = layout; //eslint-disable-line

  return react_default.a.createElement(react_default.a.Fragment, null, !layout && !LoadingComponent && react_default.a.createElement("div", null, "Loading..."), !layout && LoadingComponent && react_default.a.createElement(LoadingComponent, null), layout && react_default.a.createElement(Component, {
    ref: componentRef,
    app: app,
    model: model,
    layout: layout,
    options: options
  }));
});
QdtComponent.propTypes = {
  Component: prop_types_default.a.func.isRequired,
  options: prop_types_default.a.object,
  app: prop_types_default.a.object.isRequired,
  properties: prop_types_default.a.object,
  LoadingComponent: prop_types_default.a.func,
  onLayoutChange: prop_types_default.a.func
};
QdtComponent.defaultProps = {
  options: {},
  properties: {},
  LoadingComponent: null,
  onLayoutChange: null
};
/* harmony default export */ var QdtComponent_QdtComponent = (QdtComponent);
// CONCATENATED MODULE: ./src/qdtCompose.jsx
 //eslint-disable-line

 //eslint-disable-line

 //eslint-disable-line

 //eslint-disable-line



/* harmony default export */ var qdtCompose = (function (_ref) {
  var element = _ref.element,
      themeProp = _ref.theme,
      componentProp = _ref.component,
      optionsProp = _ref.options,
      appProp = _ref.app,
      propertiesProp = _ref.properties,
      loadingProp = _ref.loading,
      onLayoutChangeProp = _ref.onLayoutChange;
  var theme = themeProp ? Object(createMuiTheme["a" /* default */])(themeProp) : Object(createMuiTheme["a" /* default */])(Light);
  var Component = componentProp;
  var options = optionsProp;
  var app = appProp;
  var properties = propertiesProp;
  var LoadingComponent = loadingProp;
  var onLayoutChange = onLayoutChangeProp;
  var ref = {
    componentRef: react_default.a.createRef(),
    modelRef: react_default.a.createRef(),
    layoutRef: react_default.a.createRef()
  };
  react_dom_default.a.unmountComponentAtNode(element);
  react_dom_default.a.render(react_default.a.createElement(ThemeProvider_ThemeProvider, {
    theme: theme
  }, react_default.a.createElement(CssBaseline_CssBaseline, null), react_default.a.createElement(QdtComponent_QdtComponent, {
    Component: Component,
    options: options,
    app: app,
    properties: properties,
    LoadingComponent: LoadingComponent,
    onLayoutChange: onLayoutChange,
    ref: ref
  })), element);

  var update = function update(_ref2) {
    var updatedThemeProp = _ref2.theme,
        updatedComponentProp = _ref2.component,
        updatedOptionsProp = _ref2.options,
        updatedAppProp = _ref2.app,
        updatedPropertiesProp = _ref2.properties,
        updatedLoadingProp = _ref2.loading,
        updatedOnLayoutChangeProp = _ref2.onLayoutChange;
    theme = updatedThemeProp ? Object(createMuiTheme["a" /* default */])(updatedThemeProp) : Object(createMuiTheme["a" /* default */])(Light);
    Component = updatedComponentProp || Component;
    options = updatedOptionsProp || options;
    app = updatedAppProp || app;
    properties = updatedPropertiesProp || properties;
    LoadingComponent = updatedLoadingProp || LoadingComponent;
    onLayoutChange = updatedOnLayoutChangeProp || onLayoutChange;
    react_dom_default.a.render(react_default.a.createElement(ThemeProvider_ThemeProvider, {
      theme: theme
    }, react_default.a.createElement(CssBaseline_CssBaseline, null), react_default.a.createElement(QdtComponent_QdtComponent, {
      Component: Component,
      options: options,
      app: app,
      properties: properties,
      LoadingComponent: LoadingComponent,
      onLayoutChange: onLayoutChange,
      ref: ref
    })), element);
  };

  var clear = function clear() {
    react_dom_default.a.render(react_default.a.createElement(ThemeProvider_ThemeProvider, {
      theme: theme
    }, react_default.a.createElement(CssBaseline_CssBaseline, null), react_default.a.createElement(QdtComponent_QdtComponent, {
      Component: function Component() {
        return null;
      },
      options: {},
      app: app,
      properties: {},
      LoadingComponent: LoadingComponent,
      onLayoutChange: null,
      ref: ref
    })), element);
  };

  var destroy = function destroy() {
    react_dom_default.a.unmountComponentAtNode(element);
  };

  return {
    element: element,
    theme: theme,
    update: update,
    clear: clear,
    destroy: destroy,
    componentRef: ref.componentRef,
    modelRef: ref.modelRef,
    layoutRef: ref.layoutRef
  };
});
// CONCATENATED MODULE: ./node_modules/gsap/gsap-core.js
function gsap_core_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function gsap_core_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }

/*!
 * GSAP 3.2.0
 * https://greensock.com
 *
 * @license Copyright 2008-2020, GreenSock. All rights reserved.
 * Subject to the terms at https://greensock.com/standard-license or for
 * Club GreenSock members, the agreement issued with that membership.
 * @author: Jack Doyle, jack@greensock.com
*/

/* eslint-disable */
var _config = {
  autoSleep: 120,
  force3D: "auto",
  nullTargetWarn: 1,
  units: {
    lineHeight: ""
  }
},
    _defaults = {
  duration: .5,
  overwrite: false,
  delay: 0
},
    _bigNum = 1e8,
    _tinyNum = 1 / _bigNum,
    _2PI = Math.PI * 2,
    _HALF_PI = _2PI / 4,
    _gsID = 0,
    _sqrt = Math.sqrt,
    _cos = Math.cos,
    _sin = Math.sin,
    _isString = function _isString(value) {
  return typeof value === "string";
},
    _isFunction = function _isFunction(value) {
  return typeof value === "function";
},
    _isNumber = function _isNumber(value) {
  return typeof value === "number";
},
    _isUndefined = function _isUndefined(value) {
  return typeof value === "undefined";
},
    _isObject = function _isObject(value) {
  return typeof value === "object";
},
    _isNotFalse = function _isNotFalse(value) {
  return value !== false;
},
    _windowExists = function _windowExists() {
  return typeof window !== "undefined";
},
    _isFuncOrString = function _isFuncOrString(value) {
  return _isFunction(value) || _isString(value);
},
    _isArray = Array.isArray,
    _strictNumExp = /(?:-?\.?\d|\.)+/gi,
    //only numbers (including negatives and decimals) but NOT relative values.
_numExp = /[-+=.]*\d+[.e\-+]*\d*[e\-\+]*\d*/g,
    //finds any numbers, including ones that start with += or -=, negative numbers, and ones in scientific notation like 1e-8.
_numWithUnitExp = /[-+=.]*\d+[.e-]*\d*[a-z%]*/g,
    _complexStringNumExp = /[-+=.]*\d+(?:\.|e-|e)*\d*/gi,
    //duplicate so that while we're looping through matches from exec(), it doesn't contaminate the lastIndex of _numExp which we use to search for colors too.
_parenthesesExp = /\(([^()]+)\)/i,
    //finds the string between parentheses.
_relExp = /[+-]=-?[\.\d]+/,
    _delimitedValueExp = /[#\-+.]*\b[a-z\d-=+%.]+/gi,
    _globalTimeline,
    _win,
    _coreInitted,
    _doc,
    _globals = {},
    _installScope = {},
    _coreReady,
    _install = function _install(scope) {
  return (_installScope = _merge(scope, _globals)) && gsap;
},
    _missingPlugin = function _missingPlugin(property, value) {
  return console.warn("Invalid property", property, "set to", value, "Missing plugin? gsap.registerPlugin()");
},
    _warn = function _warn(message, suppress) {
  return !suppress && console.warn(message);
},
    _addGlobal = function _addGlobal(name, obj) {
  return name && (_globals[name] = obj) && _installScope && (_installScope[name] = obj) || _globals;
},
    _emptyFunc = function _emptyFunc() {
  return 0;
},
    _reservedProps = {},
    _lazyTweens = [],
    _lazyLookup = {},
    _lastRenderedFrame,
    _plugins = {},
    _effects = {},
    _nextGCFrame = 30,
    _harnessPlugins = [],
    _callbackNames = "onComplete,onUpdate,onStart,onRepeat,onReverseComplete,onInterrupt",
    _harness = function _harness(targets) {
  var target = targets[0],
      harnessPlugin,
      i;

  if (!_isObject(target) && !_isFunction(target)) {
    targets = [targets];
  }

  if (!(harnessPlugin = (target._gsap || {}).harness)) {
    i = _harnessPlugins.length;

    while (i-- && !_harnessPlugins[i].targetTest(target)) {}

    harnessPlugin = _harnessPlugins[i];
  }

  i = targets.length;

  while (i--) {
    targets[i] && (targets[i]._gsap || (targets[i]._gsap = new GSCache(targets[i], harnessPlugin))) || targets.splice(i, 1);
  }

  return targets;
},
    _getCache = function _getCache(target) {
  return target._gsap || _harness(toArray(target))[0]._gsap;
},
    _getProperty = function _getProperty(target, property) {
  var currentValue = target[property];
  return _isFunction(currentValue) ? target[property]() : _isUndefined(currentValue) && target.getAttribute(property) || currentValue;
},
    _forEachName = function _forEachName(names, func) {
  return (names = names.split(",")).forEach(func) || names;
},
    //split a comma-delimited list of names into an array, then run a forEach() function and return the split array (this is just a way to consolidate/shorten some code).
_round = function _round(value) {
  return Math.round(value * 100000) / 100000 || 0;
},
    _arrayContainsAny = function _arrayContainsAny(toSearch, toFind) {
  //searches one array to find matches for any of the items in the toFind array. As soon as one is found, it returns true. It does NOT return all the matches; it's simply a boolean search.
  var l = toFind.length,
      i = 0;

  for (; toSearch.indexOf(toFind[i]) < 0 && ++i < l;) {}

  return i < l;
},
    _parseVars = function _parseVars(params, type, parent) {
  //reads the arguments passed to one of the key methods and figures out if the user is defining things with the OLD/legacy syntax where the duration is the 2nd parameter, and then it adjusts things accordingly and spits back the corrected vars object (with the duration added if necessary, as well as runBackwards or startAt or immediateRender). type 0 = to()/staggerTo(), 1 = from()/staggerFrom(), 2 = fromTo()/staggerFromTo()
  var isLegacy = _isNumber(params[1]),
      varsIndex = (isLegacy ? 2 : 1) + (type < 2 ? 0 : 1),
      vars = params[varsIndex],
      irVars;

  if (isLegacy) {
    vars.duration = params[1];
  }

  vars.parent = parent;

  if (type) {
    irVars = vars;

    while (parent && !("immediateRender" in irVars)) {
      // inheritance hasn't happened yet, but someone may have set a default in an ancestor timeline. We could do vars.immediateRender = _isNotFalse(_inheritDefaults(vars).immediateRender) but that'd exact a slight performance penalty because _inheritDefaults() also runs in the Tween constructor. We're paying a small kb price here to gain speed.
      irVars = parent.vars.defaults || {};
      parent = _isNotFalse(parent.vars.inherit) && parent.parent;
    }

    vars.immediateRender = _isNotFalse(irVars.immediateRender);

    if (type < 2) {
      vars.runBackwards = 1;
    } else {
      vars.startAt = params[varsIndex - 1]; // "from" vars
    }
  }

  return vars;
},
    _lazyRender = function _lazyRender() {
  var l = _lazyTweens.length,
      a = _lazyTweens.slice(0),
      i,
      tween;

  _lazyLookup = {};
  _lazyTweens.length = 0;

  for (i = 0; i < l; i++) {
    tween = a[i];

    if (tween && tween._lazy) {
      tween.render(tween._lazy[0], tween._lazy[1], true)._lazy = 0;
    }
  }
},
    _lazySafeRender = function _lazySafeRender(animation, time, suppressEvents, force) {
  if (_lazyTweens.length) {
    _lazyRender();
  }

  animation.render(time, suppressEvents, force);

  if (_lazyTweens.length) {
    //in case rendering caused any tweens to lazy-init, we should render them because typically when someone calls seek() or time() or progress(), they expect an immediate render.
    _lazyRender();
  }
},
    _numericIfPossible = function _numericIfPossible(value) {
  var n = parseFloat(value);
  return (n || n === 0) && (value + "").match(_delimitedValueExp).length < 2 ? n : value;
},
    _passThrough = function _passThrough(p) {
  return p;
},
    _setDefaults = function _setDefaults(obj, defaults) {
  for (var p in defaults) {
    if (!(p in obj)) {
      obj[p] = defaults[p];
    }
  }

  return obj;
},
    _setKeyframeDefaults = function _setKeyframeDefaults(obj, defaults) {
  for (var p in defaults) {
    if (!(p in obj) && p !== "duration" && p !== "ease") {
      obj[p] = defaults[p];
    }
  }
},
    _merge = function _merge(base, toMerge) {
  for (var p in toMerge) {
    base[p] = toMerge[p];
  }

  return base;
},
    _mergeDeep = function _mergeDeep(base, toMerge) {
  for (var p in toMerge) {
    base[p] = _isObject(toMerge[p]) ? _mergeDeep(base[p] || (base[p] = {}), toMerge[p]) : toMerge[p];
  }

  return base;
},
    _copyExcluding = function _copyExcluding(obj, excluding) {
  var copy = {},
      p;

  for (p in obj) {
    if (!(p in excluding)) {
      copy[p] = obj[p];
    }
  }

  return copy;
},
    _inheritDefaults = function _inheritDefaults(vars) {
  var parent = vars.parent || _globalTimeline,
      func = vars.keyframes ? _setKeyframeDefaults : _setDefaults;

  if (_isNotFalse(vars.inherit)) {
    while (parent) {
      func(vars, parent.vars.defaults);
      parent = parent.parent;
    }
  }

  return vars;
},
    _arraysMatch = function _arraysMatch(a1, a2) {
  var i = a1.length,
      match = i === a2.length;

  while (match && i-- && a1[i] === a2[i]) {}

  return i < 0;
},
    _addLinkedListItem = function _addLinkedListItem(parent, child, firstProp, lastProp, sortBy) {
  if (firstProp === void 0) {
    firstProp = "_first";
  }

  if (lastProp === void 0) {
    lastProp = "_last";
  }

  var prev = parent[lastProp],
      t;

  if (sortBy) {
    t = child[sortBy];

    while (prev && prev[sortBy] > t) {
      prev = prev._prev;
    }
  }

  if (prev) {
    child._next = prev._next;
    prev._next = child;
  } else {
    child._next = parent[firstProp];
    parent[firstProp] = child;
  }

  if (child._next) {
    child._next._prev = child;
  } else {
    parent[lastProp] = child;
  }

  child._prev = prev;
  child.parent = parent;
  return child;
},
    _removeLinkedListItem = function _removeLinkedListItem(parent, child, firstProp, lastProp) {
  if (firstProp === void 0) {
    firstProp = "_first";
  }

  if (lastProp === void 0) {
    lastProp = "_last";
  }

  var prev = child._prev,
      next = child._next;

  if (prev) {
    prev._next = next;
  } else if (parent[firstProp] === child) {
    parent[firstProp] = next;
  }

  if (next) {
    next._prev = prev;
  } else if (parent[lastProp] === child) {
    parent[lastProp] = prev;
  }

  child._dp = parent; //record the parent as _dp just so we can revert if necessary. But parent should be null to indicate the item isn't in a linked list.

  child._next = child._prev = child.parent = null;
},
    _removeFromParent = function _removeFromParent(child, onlyIfParentHasAutoRemove) {
  if (child.parent && (!onlyIfParentHasAutoRemove || child.parent.autoRemoveChildren)) {
    child.parent.remove(child);
  }

  child._act = 0;
},
    _uncache = function _uncache(animation) {
  var a = animation;

  while (a) {
    a._dirty = 1;
    a = a.parent;
  }

  return animation;
},
    _recacheAncestors = function _recacheAncestors(animation) {
  var parent = animation.parent;

  while (parent && parent.parent) {
    //sometimes we must force a re-sort of all children and update the duration/totalDuration of all ancestor timelines immediately in case, for example, in the middle of a render loop, one tween alters another tween's timeScale which shoves its startTime before 0, forcing the parent timeline to shift around and shiftChildren() which could affect that next tween's render (startTime). Doesn't matter for the root timeline though.
    parent._dirty = 1;
    parent.totalDuration();
    parent = parent.parent;
  }

  return animation;
},
    _hasNoPausedAncestors = function _hasNoPausedAncestors(animation) {
  return !animation || animation._ts && _hasNoPausedAncestors(animation.parent);
},
    _elapsedCycleDuration = function _elapsedCycleDuration(animation) {
  return animation._repeat ? _animationCycle(animation._tTime, animation = animation.duration() + animation._rDelay) * animation : 0;
},
    // feed in the totalTime and cycleDuration and it'll return the cycle (iteration minus 1) and if the playhead is exactly at the very END, it will NOT bump up to the next cycle.
_animationCycle = function _animationCycle(tTime, cycleDuration) {
  return (tTime /= cycleDuration) && ~~tTime === tTime ? ~~tTime - 1 : ~~tTime;
},
    _parentToChildTotalTime = function _parentToChildTotalTime(parentTime, child) {
  return (parentTime - child._start) * child._ts + (child._ts >= 0 ? 0 : child._dirty ? child.totalDuration() : child._tDur);
},
    _setEnd = function _setEnd(animation) {
  return animation._end = _round(animation._start + (animation._tDur / Math.abs(animation._ts || animation._pauseTS || _tinyNum) || 0));
},

/*
_totalTimeToTime = (clampedTotalTime, duration, repeat, repeatDelay, yoyo) => {
	let cycleDuration = duration + repeatDelay,
		time = _round(clampedTotalTime % cycleDuration);
	if (time > duration) {
		time = duration;
	}
	return (yoyo && (~~(clampedTotalTime / cycleDuration) & 1)) ? duration - time : time;
},
*/
_addToTimeline = function _addToTimeline(timeline, child, position) {
  child.parent && _removeFromParent(child);
  child._start = _round(position + child._delay);
  child._end = _round(child._start + (child.totalDuration() / Math.abs(child.timeScale()) || 0));

  _addLinkedListItem(timeline, child, "_first", "_last", timeline._sort ? "_start" : 0);

  timeline._recent = child;

  if (child._time || !child._dur && child._initted) {
    //in case, for example, the _start is moved on a tween that has already rendered. Imagine it's at its end state, then the startTime is moved WAY later (after the end of this timeline), it should render at its beginning.
    var curTime = (timeline.rawTime() - child._start) * child._ts;

    if (!child._dur || _clamp(0, child.totalDuration(), curTime) - child._tTime > _tinyNum) {
      child.render(curTime, true);
    }
  } //if the timeline has already ended but the inserted tween/timeline extends the duration, we should enable this timeline again so that it renders properly. We should also align the playhead with the parent timeline's when appropriate.


  if (_uncache(timeline)._dp && timeline._initted && timeline._time >= timeline._dur && timeline._ts) {
    //in case any of the ancestors had completed but should now be enabled...
    if (timeline._dur < timeline.duration()) {
      var tl = timeline;

      while (tl._dp) {
        tl.rawTime() >= 0 && tl.totalTime(tl._tTime, true); //moves the timeline (shifts its startTime) if necessary, and also enables it. If it's currently zero, though, it may not be scheduled to render until later so there's no need to force it to align with the current playhead position. Only move to catch up with the playhead.

        tl = tl._dp;
      }
    }

    timeline._zTime = -_tinyNum; // helps ensure that the next render() will be forced (crossingStart = true in render()), even if the duration hasn't changed (we're adding a child which would need to get rendered). Definitely an edge case. Note: we MUST do this AFTER the loop above where the totalTime() might trigger a render() because this _addToTimeline() method gets called from the Animation constructor, BEFORE tweens even record their targets, etc. so we wouldn't want things to get triggered in the wrong order.
  }

  return timeline;
},
    _attemptInitTween = function _attemptInitTween(tween, totalTime, force, suppressEvents) {
  _initTween(tween, totalTime);

  if (!tween._initted) {
    return 1;
  }

  if (!force && tween._pt && (tween._dur && tween.vars.lazy !== false || !tween._dur && tween.vars.lazy) && _lastRenderedFrame !== _ticker.frame) {
    _lazyTweens.push(tween);

    tween._lazy = [totalTime, suppressEvents];
    return 1;
  }
},
    _renderZeroDurationTween = function _renderZeroDurationTween(tween, totalTime, suppressEvents, force) {
  var prevRatio = tween._zTime < 0 ? 0 : 1,
      ratio = totalTime < 0 ? 0 : 1,
      repeatDelay = tween._rDelay,
      tTime = 0,
      pt,
      iteration,
      prevIteration;

  if (repeatDelay && tween._repeat) {
    //in case there's a zero-duration tween that has a repeat with a repeatDelay
    tTime = _clamp(0, tween._tDur, totalTime);
    iteration = _animationCycle(tTime, repeatDelay);
    prevIteration = _animationCycle(tween._tTime, repeatDelay);

    if (iteration !== prevIteration) {
      prevRatio = 1 - ratio;

      if (tween.vars.repeatRefresh && tween._initted) {
        tween.invalidate();
      }
    }
  }

  if (!tween._initted && _attemptInitTween(tween, totalTime, force, suppressEvents)) {
    //if we render the very beginning (time == 0) of a fromTo(), we must force the render (normal tweens wouldn't need to render at a time of 0 when the prevTime was also 0). This is also mandatory to make sure overwriting kicks in immediately.
    return;
  }

  if (ratio !== prevRatio || force || tween._zTime === _tinyNum || !totalTime && tween._zTime) {
    tween._zTime = totalTime || (suppressEvents ? _tinyNum : 0); //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect.

    tween.ratio = ratio;

    if (tween._from) {
      ratio = 1 - ratio;
    }

    tween._time = 0;
    tween._tTime = tTime;

    if (!suppressEvents) {
      _callback(tween, "onStart");
    }

    pt = tween._pt;

    while (pt) {
      pt.r(ratio, pt.d);
      pt = pt._next;
    }

    if (!ratio && tween._startAt && !tween._onUpdate && tween._start) {
      //if the tween is positioned at the VERY beginning (_start 0) of its parent timeline, it's illegal for the playhead to go back further, so we should not render the recorded startAt values.
      tween._startAt.render(totalTime, true, force);
    }

    if (tween._onUpdate && !suppressEvents) {
      _callback(tween, "onUpdate");
    }

    if (tTime && tween._repeat && !suppressEvents && tween.parent) {
      _callback(tween, "onRepeat");
    }

    if ((totalTime >= tween._tDur || totalTime < 0) && tween.ratio === ratio) {
      tween.ratio && _removeFromParent(tween, 1);

      if (!suppressEvents) {
        _callback(tween, tween.ratio ? "onComplete" : "onReverseComplete", true);

        tween._prom && tween._prom();
      }
    }
  }
},
    _findNextPauseTween = function _findNextPauseTween(animation, prevTime, time) {
  var child;

  if (time > prevTime) {
    child = animation._first;

    while (child && child._start <= time) {
      if (!child._dur && child.data === "isPause" && child._start > prevTime) {
        return child;
      }

      child = child._next;
    }
  } else {
    child = animation._last;

    while (child && child._start >= time) {
      if (!child._dur && child.data === "isPause" && child._start < prevTime) {
        return child;
      }

      child = child._prev;
    }
  }
},
    _setDuration = function _setDuration(animation, duration, skipUncache) {
  var repeat = animation._repeat,
      dur = _round(duration);

  animation._dur = dur;
  animation._tDur = !repeat ? dur : repeat < 0 ? 1e12 : _round(dur * (repeat + 1) + animation._rDelay * repeat);
  !skipUncache && _uncache(animation.parent);
  animation.parent && _setEnd(animation);
  return animation;
},
    _onUpdateTotalDuration = function _onUpdateTotalDuration(animation) {
  return animation instanceof Timeline ? _uncache(animation) : _setDuration(animation, animation._dur);
},
    _zeroPosition = {
  _start: 0,
  endTime: _emptyFunc
},
    _parsePosition = function _parsePosition(animation, position) {
  var labels = animation.labels,
      recent = animation._recent || _zeroPosition,
      clippedDuration = animation.duration() >= _bigNum ? recent.endTime(false) : animation._dur,
      //in case there's a child that infinitely repeats, users almost never intend for the insertion point of a new child to be based on a SUPER long value like that so we clip it and assume the most recently-added child's endTime should be used instead.
  i,
      offset;

  if (_isString(position) && (isNaN(position) || position in labels)) {
    //if the string is a number like "1", check to see if there's a label with that name, otherwise interpret it as a number (absolute value).
    i = position.charAt(0);

    if (i === "<" || i === ">") {
      return (i === "<" ? recent._start : recent.endTime(recent._repeat >= 0)) + (parseFloat(position.substr(1)) || 0);
    }

    i = position.indexOf("=");

    if (i < 0) {
      if (!(position in labels)) {
        labels[position] = clippedDuration;
      }

      return labels[position];
    }

    offset = +(position.charAt(i - 1) + position.substr(i + 1));
    return i > 1 ? _parsePosition(animation, position.substr(0, i - 1)) + offset : clippedDuration + offset;
  }

  return position == null ? clippedDuration : +position;
},
    _conditionalReturn = function _conditionalReturn(value, func) {
  return value || value === 0 ? func(value) : func;
},
    _clamp = function _clamp(min, max, value) {
  return value < min ? min : value > max ? max : value;
},
    getUnit = function getUnit(value) {
  return (value + "").substr((parseFloat(value) + "").length);
},
    clamp = function clamp(min, max, value) {
  return _conditionalReturn(value, function (v) {
    return _clamp(min, max, v);
  });
},
    _slice = [].slice,
    _isArrayLike = function _isArrayLike(value, nonEmpty) {
  return value && _isObject(value) && "length" in value && (!nonEmpty && !value.length || value.length - 1 in value && _isObject(value[0])) && !value.nodeType && value !== _win;
},
    _flatten = function _flatten(ar, leaveStrings, accumulator) {
  if (accumulator === void 0) {
    accumulator = [];
  }

  return ar.forEach(function (value) {
    var _accumulator;

    return _isString(value) && !leaveStrings || _isArrayLike(value, 1) ? (_accumulator = accumulator).push.apply(_accumulator, toArray(value)) : accumulator.push(value);
  }) || accumulator;
},
    //takes any value and returns an array. If it's a string (and leaveStrings isn't true), it'll use document.querySelectorAll() and convert that to an array. It'll also accept iterables like jQuery objects.
toArray = function toArray(value, leaveStrings) {
  return _isString(value) && !leaveStrings && (_coreInitted || !_wake()) ? _slice.call(_doc.querySelectorAll(value), 0) : _isArray(value) ? _flatten(value, leaveStrings) : _isArrayLike(value) ? _slice.call(value, 0) : value ? [value] : [];
},
    shuffle = function shuffle(a) {
  return a.sort(function () {
    return .5 - Math.random();
  });
},
    // alternative that's a bit faster and more reliably diverse but bigger:   for (let j, v, i = a.length; i; j = ~~(Math.random() * i), v = a[--i], a[i] = a[j], a[j] = v); return a;
//for distributing values across an array. Can accept a number, a function or (most commonly) a function which can contain the following properties: {base, amount, from, ease, grid, axis, length, each}. Returns a function that expects the following parameters: index, target, array. Recognizes the following
distribute = function distribute(v) {
  if (_isFunction(v)) {
    return v;
  }

  var vars = _isObject(v) ? v : {
    each: v
  },
      //n:1 is just to indicate v was a number; we leverage that later to set v according to the length we get. If a number is passed in, we treat it like the old stagger value where 0.1, for example, would mean that things would be distributed with 0.1 between each element in the array rather than a total "amount" that's chunked out among them all.
  ease = _parseEase(vars.ease),
      from = vars.from || 0,
      base = parseFloat(vars.base) || 0,
      cache = {},
      isDecimal = from > 0 && from < 1,
      ratios = isNaN(from) || isDecimal,
      axis = vars.axis,
      ratioX = from,
      ratioY = from;

  if (_isString(from)) {
    ratioX = ratioY = {
      center: .5,
      edges: .5,
      end: 1
    }[from] || 0;
  } else if (!isDecimal && ratios) {
    ratioX = from[0];
    ratioY = from[1];
  }

  return function (i, target, a) {
    var l = (a || vars).length,
        distances = cache[l],
        originX,
        originY,
        x,
        y,
        d,
        j,
        max,
        min,
        wrapAt;

    if (!distances) {
      wrapAt = vars.grid === "auto" ? 0 : (vars.grid || [1, _bigNum])[1];

      if (!wrapAt) {
        max = -_bigNum;

        while (max < (max = a[wrapAt++].getBoundingClientRect().left) && wrapAt < l) {}

        wrapAt--;
      }

      distances = cache[l] = [];
      originX = ratios ? Math.min(wrapAt, l) * ratioX - .5 : from % wrapAt;
      originY = ratios ? l * ratioY / wrapAt - .5 : from / wrapAt | 0;
      max = 0;
      min = _bigNum;

      for (j = 0; j < l; j++) {
        x = j % wrapAt - originX;
        y = originY - (j / wrapAt | 0);
        distances[j] = d = !axis ? _sqrt(x * x + y * y) : Math.abs(axis === "y" ? y : x);

        if (d > max) {
          max = d;
        }

        if (d < min) {
          min = d;
        }
      }

      from === "random" && shuffle(distances);
      distances.max = max - min;
      distances.min = min;
      distances.v = l = (parseFloat(vars.amount) || parseFloat(vars.each) * (wrapAt > l ? l - 1 : !axis ? Math.max(wrapAt, l / wrapAt) : axis === "y" ? l / wrapAt : wrapAt) || 0) * (from === "edges" ? -1 : 1);
      distances.b = l < 0 ? base - l : base;
      distances.u = getUnit(vars.amount || vars.each) || 0; //unit

      ease = ease && l < 0 ? _invertEase(ease) : ease;
    }

    l = (distances[i] - distances.min) / distances.max || 0;
    return _round(distances.b + (ease ? ease(l) : l) * distances.v) + distances.u; //round in order to work around floating point errors
  };
},
    _roundModifier = function _roundModifier(v) {
  //pass in 0.1 get a function that'll round to the nearest tenth, or 5 to round to the closest 5, or 0.001 to the closest 1000th, etc.
  var p = v < 1 ? Math.pow(10, (v + "").length - 2) : 1; //to avoid floating point math errors (like 24 * 0.1 == 2.4000000000000004), we chop off at a specific number of decimal places (much faster than toFixed()

  return function (raw) {
    return ~~(Math.round(parseFloat(raw) / v) * v * p) / p + (_isNumber(raw) ? 0 : getUnit(raw));
  };
},
    snap = function snap(snapTo, value) {
  var isArray = _isArray(snapTo),
      radius,
      is2D;

  if (!isArray && _isObject(snapTo)) {
    radius = isArray = snapTo.radius || _bigNum;

    if (snapTo.values) {
      snapTo = toArray(snapTo.values);

      if (is2D = !_isNumber(snapTo[0])) {
        radius *= radius; //performance optimization so we don't have to Math.sqrt() in the loop.
      }
    } else {
      snapTo = _roundModifier(snapTo.increment);
    }
  }

  return _conditionalReturn(value, !isArray ? _roundModifier(snapTo) : _isFunction(snapTo) ? function (raw) {
    is2D = snapTo(raw);
    return Math.abs(is2D - raw) <= radius ? is2D : raw;
  } : function (raw) {
    var x = parseFloat(is2D ? raw.x : raw),
        y = parseFloat(is2D ? raw.y : 0),
        min = _bigNum,
        closest = 0,
        i = snapTo.length,
        dx,
        dy;

    while (i--) {
      if (is2D) {
        dx = snapTo[i].x - x;
        dy = snapTo[i].y - y;
        dx = dx * dx + dy * dy;
      } else {
        dx = Math.abs(snapTo[i] - x);
      }

      if (dx < min) {
        min = dx;
        closest = i;
      }
    }

    closest = !radius || min <= radius ? snapTo[closest] : raw;
    return is2D || closest === raw || _isNumber(raw) ? closest : closest + getUnit(raw);
  });
},
    random = function random(min, max, roundingIncrement, returnFunction) {
  return _conditionalReturn(_isArray(min) ? !max : roundingIncrement === true ? !!(roundingIncrement = 0) : !returnFunction, function () {
    return _isArray(min) ? min[~~(Math.random() * min.length)] : (roundingIncrement = roundingIncrement || 1e-5) && (returnFunction = roundingIncrement < 1 ? Math.pow(10, (roundingIncrement + "").length - 2) : 1) && ~~(Math.round((min + Math.random() * (max - min)) / roundingIncrement) * roundingIncrement * returnFunction) / returnFunction;
  });
},
    pipe = function pipe() {
  for (var _len = arguments.length, functions = new Array(_len), _key = 0; _key < _len; _key++) {
    functions[_key] = arguments[_key];
  }

  return function (value) {
    return functions.reduce(function (v, f) {
      return f(v);
    }, value);
  };
},
    unitize = function unitize(func, unit) {
  return function (value) {
    return func(parseFloat(value)) + (unit || getUnit(value));
  };
},
    normalize = function normalize(min, max, value) {
  return mapRange(min, max, 0, 1, value);
},
    _wrapArray = function _wrapArray(a, wrapper, value) {
  return _conditionalReturn(value, function (index) {
    return a[~~wrapper(index)];
  });
},
    gsap_core_wrap = function wrap(min, max, value) {
  // NOTE: wrap() CANNOT be an arrow function! A very odd compiling bug causes problems (unrelated to GSAP).
  var range = max - min;
  return _isArray(min) ? _wrapArray(min, wrap(0, min.length), max) : _conditionalReturn(value, function (value) {
    return (range + (value - min) % range) % range + min;
  });
},
    wrapYoyo = function wrapYoyo(min, max, value) {
  var range = max - min,
      total = range * 2;
  return _isArray(min) ? _wrapArray(min, wrapYoyo(0, min.length - 1), max) : _conditionalReturn(value, function (value) {
    value = (total + (value - min) % total) % total;
    return min + (value > range ? total - value : value);
  });
},
    _replaceRandom = function _replaceRandom(value) {
  //replaces all occurrences of random(...) in a string with the calculated random value. can be a range like random(-100, 100, 5) or an array like random([0, 100, 500])
  var prev = 0,
      s = "",
      i,
      nums,
      end,
      isArray;

  while (~(i = value.indexOf("random(", prev))) {
    end = value.indexOf(")", i);
    isArray = value.charAt(i + 7) === "[";
    nums = value.substr(i + 7, end - i - 7).match(isArray ? _delimitedValueExp : _strictNumExp);
    s += value.substr(prev, i - prev) + random(isArray ? nums : +nums[0], +nums[1], +nums[2] || 1e-5);
    prev = end + 1;
  }

  return s + value.substr(prev, value.length - prev);
},
    mapRange = function mapRange(inMin, inMax, outMin, outMax, value) {
  var inRange = inMax - inMin,
      outRange = outMax - outMin;
  return _conditionalReturn(value, function (value) {
    return outMin + (value - inMin) / inRange * outRange;
  });
},
    interpolate = function interpolate(start, end, progress, mutate) {
  var func = isNaN(start + end) ? 0 : function (p) {
    return (1 - p) * start + p * end;
  };

  if (!func) {
    var isString = _isString(start),
        master = {},
        p,
        i,
        interpolators,
        l,
        il;

    progress === true && (mutate = 1) && (progress = null);

    if (isString) {
      start = {
        p: start
      };
      end = {
        p: end
      };
    } else if (_isArray(start) && !_isArray(end)) {
      interpolators = [];
      l = start.length;
      il = l - 2;

      for (i = 1; i < l; i++) {
        interpolators.push(interpolate(start[i - 1], start[i])); //build the interpolators up front as a performance optimization so that when the function is called many times, it can just reuse them.
      }

      l--;

      func = function func(p) {
        p *= l;
        var i = Math.min(il, ~~p);
        return interpolators[i](p - i);
      };

      progress = end;
    } else if (!mutate) {
      start = _merge(_isArray(start) ? [] : {}, start);
    }

    if (!interpolators) {
      for (p in end) {
        _addPropTween.call(master, start, p, "get", end[p]);
      }

      func = function func(p) {
        return _renderPropTweens(p, master) || (isString ? start.p : start);
      };
    }
  }

  return _conditionalReturn(progress, func);
},
    _getLabelInDirection = function _getLabelInDirection(timeline, fromTime, backward) {
  //used for nextLabel() and previousLabel()
  var labels = timeline.labels,
      min = _bigNum,
      p,
      distance,
      label;

  for (p in labels) {
    distance = labels[p] - fromTime;

    if (distance < 0 === !!backward && distance && min > (distance = Math.abs(distance))) {
      label = p;
      min = distance;
    }
  }

  return label;
},
    _callback = function _callback(animation, type, executeLazyFirst) {
  var v = animation.vars,
      callback = v[type],
      params,
      scope;

  if (!callback) {
    return;
  }

  params = v[type + "Params"];
  scope = v.callbackScope || animation;

  if (executeLazyFirst && _lazyTweens.length) {
    //in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onUpdate on a timeline that reports/checks tweened values.
    _lazyRender();
  }

  return params ? callback.apply(scope, params) : callback.call(scope);
},
    _interrupt = function _interrupt(animation) {
  _removeFromParent(animation);

  if (animation.progress() < 1) {
    _callback(animation, "onInterrupt");
  }

  return animation;
},
    _quickTween,
    _createPlugin = function _createPlugin(config) {
  config = !config.name && config["default"] || config; //UMD packaging wraps things oddly, so for example MotionPathHelper becomes {MotionPathHelper:MotionPathHelper, default:MotionPathHelper}.

  var name = config.name,
      isFunc = _isFunction(config),
      Plugin = name && !isFunc && config.init ? function () {
    this._props = [];
  } : config,
      //in case someone passes in an object that's not a plugin, like CustomEase
  instanceDefaults = {
    init: _emptyFunc,
    render: _renderPropTweens,
    add: _addPropTween,
    kill: _killPropTweensOf,
    modifier: _addPluginModifier,
    rawVars: 0
  },
      statics = {
    targetTest: 0,
    get: 0,
    getSetter: _getSetter,
    aliases: {},
    register: 0
  };

  _wake();

  if (config !== Plugin) {
    if (_plugins[name]) {
      return;
    }

    _setDefaults(Plugin, _setDefaults(_copyExcluding(config, instanceDefaults), statics)); //static methods


    _merge(Plugin.prototype, _merge(instanceDefaults, _copyExcluding(config, statics))); //instance methods


    _plugins[Plugin.prop = name] = Plugin;

    if (config.targetTest) {
      _harnessPlugins.push(Plugin);

      _reservedProps[name] = 1;
    }

    name = (name === "css" ? "CSS" : name.charAt(0).toUpperCase() + name.substr(1)) + "Plugin"; //for the global name. "motionPath" should become MotionPathPlugin
  }

  _addGlobal(name, Plugin);

  if (config.register) {
    config.register(gsap, Plugin, PropTween);
  }
},

/*
 * --------------------------------------------------------------------------------------
 * COLORS
 * --------------------------------------------------------------------------------------
 */
_255 = 255,
    _colorLookup = {
  aqua: [0, _255, _255],
  lime: [0, _255, 0],
  silver: [192, 192, 192],
  black: [0, 0, 0],
  maroon: [128, 0, 0],
  teal: [0, 128, 128],
  blue: [0, 0, _255],
  navy: [0, 0, 128],
  white: [_255, _255, _255],
  olive: [128, 128, 0],
  yellow: [_255, _255, 0],
  orange: [_255, 165, 0],
  gray: [128, 128, 128],
  purple: [128, 0, 128],
  green: [0, 128, 0],
  red: [_255, 0, 0],
  pink: [_255, 192, 203],
  cyan: [0, _255, _255],
  transparent: [_255, _255, _255, 0]
},
    _hue = function _hue(h, m1, m2) {
  h = h < 0 ? h + 1 : h > 1 ? h - 1 : h;
  return (h * 6 < 1 ? m1 + (m2 - m1) * h * 6 : h < .5 ? m2 : h * 3 < 2 ? m1 + (m2 - m1) * (2 / 3 - h) * 6 : m1) * _255 + .5 | 0;
},
    splitColor = function splitColor(v, toHSL, forceAlpha) {
  var a = !v ? _colorLookup.black : _isNumber(v) ? [v >> 16, v >> 8 & _255, v & _255] : 0,
      r,
      g,
      b,
      h,
      s,
      l,
      max,
      min,
      d,
      wasHSL;

  if (!a) {
    if (v.substr(-1) === ",") {
      //sometimes a trailing comma is included and we should chop it off (typically from a comma-delimited list of values like a textShadow:"2px 2px 2px blue, 5px 5px 5px rgb(255,0,0)" - in this example "blue," has a trailing comma. We could strip it out inside parseComplex() but we'd need to do it to the beginning and ending values plus it wouldn't provide protection from other potential scenarios like if the user passes in a similar value.
      v = v.substr(0, v.length - 1);
    }

    if (_colorLookup[v]) {
      a = _colorLookup[v];
    } else if (v.charAt(0) === "#") {
      if (v.length === 4) {
        //for shorthand like #9F0
        r = v.charAt(1);
        g = v.charAt(2);
        b = v.charAt(3);
        v = "#" + r + r + g + g + b + b;
      }

      v = parseInt(v.substr(1), 16);
      a = [v >> 16, v >> 8 & _255, v & _255];
    } else if (v.substr(0, 3) === "hsl") {
      a = wasHSL = v.match(_strictNumExp);

      if (!toHSL) {
        h = +a[0] % 360 / 360;
        s = +a[1] / 100;
        l = +a[2] / 100;
        g = l <= .5 ? l * (s + 1) : l + s - l * s;
        r = l * 2 - g;

        if (a.length > 3) {
          a[3] *= 1; //cast as number
        }

        a[0] = _hue(h + 1 / 3, r, g);
        a[1] = _hue(h, r, g);
        a[2] = _hue(h - 1 / 3, r, g);
      } else if (~v.indexOf("=")) {
        //if relative values are found, just return the raw strings with the relative prefixes in place.
        a = v.match(_numExp);
        forceAlpha && a.length < 4 && (a[3] = 1);
        return a;
      }
    } else {
      a = v.match(_strictNumExp) || _colorLookup.transparent;
    }

    a = a.map(Number);
  }

  if (toHSL && !wasHSL) {
    r = a[0] / _255;
    g = a[1] / _255;
    b = a[2] / _255;
    max = Math.max(r, g, b);
    min = Math.min(r, g, b);
    l = (max + min) / 2;

    if (max === min) {
      h = s = 0;
    } else {
      d = max - min;
      s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
      h = max === r ? (g - b) / d + (g < b ? 6 : 0) : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
      h *= 60;
    }

    a[0] = ~~(h + .5);
    a[1] = ~~(s * 100 + .5);
    a[2] = ~~(l * 100 + .5);
  }

  forceAlpha && a.length < 4 && (a[3] = 1);
  return a;
},
    _colorOrderData = function _colorOrderData(v) {
  // strips out the colors from the string, finds all the numeric slots (with units) and returns an array of those. The Array also has a "c" property which is an Array of the index values where the colors belong. This is to help work around issues where there's a mis-matched order of color/numeric data like drop-shadow(#f00 0px 1px 2px) and drop-shadow(0x 1px 2px #f00). This is basically a helper function used in _formatColors()
  var values = [],
      c = [],
      i = -1;
  v.split(_colorExp).forEach(function (v) {
    var a = v.match(_numWithUnitExp) || [];
    values.push.apply(values, a);
    c.push(i += a.length + 1);
  });
  values.c = c;
  return values;
},
    _formatColors = function _formatColors(s, toHSL, orderMatchData) {
  var result = "",
      colors = (s + result).match(_colorExp),
      type = toHSL ? "hsla(" : "rgba(",
      i = 0,
      c,
      shell,
      d,
      l;

  if (!colors) {
    return s;
  }

  colors = colors.map(function (color) {
    return (color = splitColor(color, toHSL, 1)) && type + (toHSL ? color[0] + "," + color[1] + "%," + color[2] + "%," + color[3] : color.join(",")) + ")";
  });

  if (orderMatchData) {
    d = _colorOrderData(s);
    c = orderMatchData.c;

    if (c.join(result) !== d.c.join(result)) {
      shell = s.replace(_colorExp, "1").split(_numWithUnitExp);
      l = shell.length - 1;

      for (; i < l; i++) {
        result += shell[i] + (~c.indexOf(i) ? colors.shift() || type + "0,0,0,0)" : (d.length ? d : colors.length ? colors : orderMatchData).shift());
      }
    }
  }

  if (!shell) {
    shell = s.split(_colorExp);
    l = shell.length - 1;

    for (; i < l; i++) {
      result += shell[i] + colors[i];
    }
  }

  return result + shell[l];
},
    _colorExp = function () {
  var s = "(?:\\b(?:(?:rgb|rgba|hsl|hsla)\\(.+?\\))|\\B#(?:[0-9a-f]{3}){1,2}\\b",
      //we'll dynamically build this Regular Expression to conserve file size. After building it, it will be able to find rgb(), rgba(), # (hexadecimal), and named color values like red, blue, purple, etc.,
  p;

  for (p in _colorLookup) {
    s += "|" + p + "\\b";
  }

  return new RegExp(s + ")", "gi");
}(),
    _hslExp = /hsl[a]?\(/,
    _colorStringFilter = function _colorStringFilter(a) {
  var combined = a.join(" "),
      toHSL;
  _colorExp.lastIndex = 0;

  if (_colorExp.test(combined)) {
    toHSL = _hslExp.test(combined);
    a[1] = _formatColors(a[1], toHSL);
    a[0] = _formatColors(a[0], toHSL, _colorOrderData(a[1])); // make sure the order of numbers/colors match with the END value.

    return true;
  }
},

/*
 * --------------------------------------------------------------------------------------
 * TICKER
 * --------------------------------------------------------------------------------------
 */
_tickerActive,
    _ticker = function () {
  var _getTime = Date.now,
      _lagThreshold = 500,
      _adjustedLag = 33,
      _startTime = _getTime(),
      _lastUpdate = _startTime,
      _gap = 1 / 240,
      _nextTime = _gap,
      _listeners = [],
      _id,
      _req,
      _raf,
      _self,
      _tick = function _tick(v) {
    var elapsed = _getTime() - _lastUpdate,
        manual = v === true,
        overlap,
        dispatch;

    if (elapsed > _lagThreshold) {
      _startTime += elapsed - _adjustedLag;
    }

    _lastUpdate += elapsed;
    _self.time = (_lastUpdate - _startTime) / 1000;
    overlap = _self.time - _nextTime;

    if (overlap > 0 || manual) {
      _self.frame++;
      _nextTime += overlap + (overlap >= _gap ? 0.004 : _gap - overlap);
      dispatch = 1;
    }

    if (!manual) {
      //make sure the request is made before we dispatch the "tick" event so that timing is maintained. Otherwise, if processing the "tick" requires a bunch of time (like 15ms) and we're using a setTimeout() that's based on 16.7ms, it'd technically take 31.7ms between frames otherwise.
      _id = _req(_tick);
    }

    if (dispatch) {
      _listeners.forEach(function (l) {
        return l(_self.time, elapsed, _self.frame, v);
      });
    }
  };

  _self = {
    time: 0,
    frame: 0,
    tick: function tick() {
      _tick(true);
    },
    wake: function wake() {
      if (_coreReady) {
        if (!_coreInitted && _windowExists()) {
          _win = _coreInitted = window;
          _doc = _win.document || {};
          _globals.gsap = gsap;
          (_win.gsapVersions || (_win.gsapVersions = [])).push(gsap.version);

          _install(_installScope || _win.GreenSockGlobals || !_win.gsap && _win || {});

          _raf = _win.requestAnimationFrame;
        }

        _id && _self.sleep();

        _req = _raf || function (f) {
          return setTimeout(f, (_nextTime - _self.time) * 1000 + 1 | 0);
        };

        _tickerActive = 1;

        _tick(2);
      }
    },
    sleep: function sleep() {
      (_raf ? _win.cancelAnimationFrame : clearTimeout)(_id);
      _tickerActive = 0;
      _req = _emptyFunc;
    },
    lagSmoothing: function lagSmoothing(threshold, adjustedLag) {
      _lagThreshold = threshold || 1 / _tinyNum; //zero should be interpreted as basically unlimited

      _adjustedLag = Math.min(adjustedLag, _lagThreshold, 0);
    },
    fps: function fps(_fps) {
      _gap = 1 / (_fps || 240);
      _nextTime = _self.time + _gap;
    },
    add: function add(callback) {
      _listeners.indexOf(callback) < 0 && _listeners.push(callback);

      _wake();
    },
    remove: function remove(callback) {
      var i;
      ~(i = _listeners.indexOf(callback)) && _listeners.splice(i, 1);
    },
    _listeners: _listeners
  };
  return _self;
}(),
    _wake = function _wake() {
  return !_tickerActive && _ticker.wake();
},
    //also ensures the core classes are initialized.

/*
* -------------------------------------------------
* EASING
* -------------------------------------------------
*/
_easeMap = {},
    _customEaseExp = /^[\d.\-M][\d.\-,\s]/,
    _quotesExp = /["']/g,
    _parseObjectInString = function _parseObjectInString(value) {
  //takes a string like "{wiggles:10, type:anticipate})" and turns it into a real object. Notice it ends in ")" and includes the {} wrappers. This is because we only use this function for parsing ease configs and prioritized optimization rather than reusability.
  var obj = {},
      split = value.substr(1, value.length - 3).split(":"),
      key = split[0],
      i = 1,
      l = split.length,
      index,
      val,
      parsedVal;

  for (; i < l; i++) {
    val = split[i];
    index = i !== l - 1 ? val.lastIndexOf(",") : val.length;
    parsedVal = val.substr(0, index);
    obj[key] = isNaN(parsedVal) ? parsedVal.replace(_quotesExp, "").trim() : +parsedVal;
    key = val.substr(index + 1).trim();
  }

  return obj;
},
    _configEaseFromString = function _configEaseFromString(name) {
  //name can be a string like "elastic.out(1,0.5)", and pass in _easeMap as obj and it'll parse it out and call the actual function like _easeMap.Elastic.easeOut.config(1,0.5). It will also parse custom ease strings as long as CustomEase is loaded and registered (internally as _easeMap._CE).
  var split = (name + "").split("("),
      ease = _easeMap[split[0]];
  return ease && split.length > 1 && ease.config ? ease.config.apply(null, ~name.indexOf("{") ? [_parseObjectInString(split[1])] : _parenthesesExp.exec(name)[1].split(",").map(_numericIfPossible)) : _easeMap._CE && _customEaseExp.test(name) ? _easeMap._CE("", name) : ease;
},
    _invertEase = function _invertEase(ease) {
  return function (p) {
    return 1 - ease(1 - p);
  };
},
    // potential future feature - allow yoyoEase to be set in children and have those affected when the parent/ancestor timeline yoyos. Not sure it's worth the kb.
// _propagateYoyoEase = (timeline, isYoyo) => {
// 	let child = timeline._first, ease;
// 	while (child) {
// 		if (child instanceof Timeline) {
// 			_propagateYoyoEase(child, isYoyo);
// 		} else if (child.vars.yoyoEase && (!child._yoyo || !child._repeat) && child._yoyo !== isYoyo) {
// 			if (child.timeline) {
// 				_propagateYoyoEase(child.timeline, isYoyo);
// 			} else {
// 				ease = child._ease;
// 				child._ease = child._yEase;
// 				child._yEase = ease;
// 				child._yoyo = isYoyo;
// 			}
// 		}
// 		child = child._next;
// 	}
// },
_parseEase = function _parseEase(ease, defaultEase) {
  return !ease ? defaultEase : (_isFunction(ease) ? ease : _easeMap[ease] || _configEaseFromString(ease)) || defaultEase;
},
    _insertEase = function _insertEase(names, easeIn, easeOut, easeInOut) {
  if (easeOut === void 0) {
    easeOut = function easeOut(p) {
      return 1 - easeIn(1 - p);
    };
  }

  if (easeInOut === void 0) {
    easeInOut = function easeInOut(p) {
      return p < .5 ? easeIn(p * 2) / 2 : 1 - easeIn((1 - p) * 2) / 2;
    };
  }

  var ease = {
    easeIn: easeIn,
    easeOut: easeOut,
    easeInOut: easeInOut
  },
      lowercaseName;

  _forEachName(names, function (name) {
    _easeMap[name] = _globals[name] = ease;
    _easeMap[lowercaseName = name.toLowerCase()] = easeOut;

    for (var p in ease) {
      _easeMap[lowercaseName + (p === "easeIn" ? ".in" : p === "easeOut" ? ".out" : ".inOut")] = _easeMap[name + "." + p] = ease[p];
    }
  });

  return ease;
},
    _easeInOutFromOut = function _easeInOutFromOut(easeOut) {
  return function (p) {
    return p < .5 ? (1 - easeOut(1 - p * 2)) / 2 : .5 + easeOut((p - .5) * 2) / 2;
  };
},
    _configElastic = function _configElastic(type, amplitude, period) {
  var p1 = amplitude >= 1 ? amplitude : 1,
      //note: if amplitude is < 1, we simply adjust the period for a more natural feel. Otherwise the math doesn't work right and the curve starts at 1.
  p2 = (period || (type ? .3 : .45)) / (amplitude < 1 ? amplitude : 1),
      p3 = p2 / _2PI * (Math.asin(1 / p1) || 0),
      easeOut = function easeOut(p) {
    return p === 1 ? 1 : p1 * Math.pow(2, -10 * p) * _sin((p - p3) * p2) + 1;
  },
      ease = type === "out" ? easeOut : type === "in" ? function (p) {
    return 1 - easeOut(1 - p);
  } : _easeInOutFromOut(easeOut);

  p2 = _2PI / p2; //precalculate to optimize

  ease.config = function (amplitude, period) {
    return _configElastic(type, amplitude, period);
  };

  return ease;
},
    _configBack = function _configBack(type, overshoot) {
  if (overshoot === void 0) {
    overshoot = 1.70158;
  }

  var easeOut = function easeOut(p) {
    return p ? --p * p * ((overshoot + 1) * p + overshoot) + 1 : 0;
  },
      ease = type === "out" ? easeOut : type === "in" ? function (p) {
    return 1 - easeOut(1 - p);
  } : _easeInOutFromOut(easeOut);

  ease.config = function (overshoot) {
    return _configBack(type, overshoot);
  };

  return ease;
}; // a cheaper (kb and cpu) but more mild way to get a parameterized weighted ease by feeding in a value between -1 (easeIn) and 1 (easeOut) where 0 is linear.
// _weightedEase = ratio => {
// 	let y = 0.5 + ratio / 2;
// 	return p => (2 * (1 - p) * p * y + p * p);
// },
// a stronger (but more expensive kb/cpu) parameterized weighted ease that lets you feed in a value between -1 (easeIn) and 1 (easeOut) where 0 is linear.
// _weightedEaseStrong = ratio => {
// 	ratio = .5 + ratio / 2;
// 	let o = 1 / 3 * (ratio < .5 ? ratio : 1 - ratio),
// 		b = ratio - o,
// 		c = ratio + o;
// 	return p => p === 1 ? p : 3 * b * (1 - p) * (1 - p) * p + 3 * c * (1 - p) * p * p + p * p * p;
// };


_forEachName("Linear,Quad,Cubic,Quart,Quint,Strong", function (name, i) {
  var power = i < 5 ? i + 1 : i;

  _insertEase(name + ",Power" + (power - 1), i ? function (p) {
    return Math.pow(p, power);
  } : function (p) {
    return p;
  }, function (p) {
    return 1 - Math.pow(1 - p, power);
  }, function (p) {
    return p < .5 ? Math.pow(p * 2, power) / 2 : 1 - Math.pow((1 - p) * 2, power) / 2;
  });
});

_easeMap.Linear.easeNone = _easeMap.none = _easeMap.Linear.easeIn;

_insertEase("Elastic", _configElastic("in"), _configElastic("out"), _configElastic());

(function (n, c) {
  var n1 = 1 / c,
      n2 = 2 * n1,
      n3 = 2.5 * n1,
      easeOut = function easeOut(p) {
    return p < n1 ? n * p * p : p < n2 ? n * Math.pow(p - 1.5 / c, 2) + .75 : p < n3 ? n * (p -= 2.25 / c) * p + .9375 : n * Math.pow(p - 2.625 / c, 2) + .984375;
  };

  _insertEase("Bounce", function (p) {
    return 1 - easeOut(1 - p);
  }, easeOut);
})(7.5625, 2.75);

_insertEase("Expo", function (p) {
  return p ? Math.pow(2, 10 * (p - 1)) : 0;
});

_insertEase("Circ", function (p) {
  return -(_sqrt(1 - p * p) - 1);
});

_insertEase("Sine", function (p) {
  return -_cos(p * _HALF_PI) + 1;
});

_insertEase("Back", _configBack("in"), _configBack("out"), _configBack());

_easeMap.SteppedEase = _easeMap.steps = _globals.SteppedEase = {
  config: function config(steps, immediateStart) {
    if (steps === void 0) {
      steps = 1;
    }

    var p1 = 1 / steps,
        p2 = steps + (immediateStart ? 0 : 1),
        p3 = immediateStart ? 1 : 0,
        max = 1 - _tinyNum;
    return function (p) {
      return ((p2 * _clamp(0, max, p) | 0) + p3) * p1;
    };
  }
};
_defaults.ease = _easeMap["quad.out"];
/*
 * --------------------------------------------------------------------------------------
 * CACHE
 * --------------------------------------------------------------------------------------
 */

var GSCache = function GSCache(target, harness) {
  this.id = _gsID++;
  target._gsap = this;
  this.target = target;
  this.harness = harness;
  this.get = harness ? harness.get : _getProperty;
  this.set = harness ? harness.getSetter : _getSetter;
};
/*
 * --------------------------------------------------------------------------------------
 * ANIMATION
 * --------------------------------------------------------------------------------------
 */

var Animation =
/*#__PURE__*/
function () {
  function Animation(vars, time) {
    var parent = vars.parent || _globalTimeline;
    this.vars = vars;
    this._delay = +vars.delay || 0;

    if (this._repeat = vars.repeat || 0) {
      this._rDelay = vars.repeatDelay || 0;
      this._yoyo = !!vars.yoyo || !!vars.yoyoEase;
    }

    this._ts = 1;

    _setDuration(this, +vars.duration, 1);

    this.data = vars.data;
    _tickerActive || _ticker.wake();
    parent && _addToTimeline(parent, this, time || time === 0 ? time : parent._time);
    vars.reversed && this.reversed(true);
    vars.paused && this.paused(true);
  }

  var _proto = Animation.prototype;

  _proto.delay = function delay(value) {
    if (value || value === 0) {
      this._delay = value;
      return this;
    }

    return this._delay;
  };

  _proto.duration = function duration(value) {
    return arguments.length ? _setDuration(this, value) : this.totalDuration() && this._dur;
  };

  _proto.totalDuration = function totalDuration(value) {
    if (!arguments.length) {
      return this._tDur;
    }

    this._dirty = 0;
    return _setDuration(this, this._repeat < 0 ? value : (value - this._repeat * this._rDelay) / (this._repeat + 1));
  };

  _proto.totalTime = function totalTime(_totalTime, suppressEvents) {
    _wake();

    if (!arguments.length) {
      return this._tTime;
    }

    var parent = this.parent || this._dp;

    if (parent && parent.smoothChildTiming && this._ts) {
      // if (!parent._dp && parent._time === parent._dur) { // if a root timeline completes...and then a while later one of its children resumes, we must shoot the playhead forward to where it should be raw-wise, otherwise the child will jump to the end. Down side: this assumes it's using the _ticker.time as a reference.
      // 	parent._time = _ticker.time - parent._start;
      // }
      this._start = _round(parent._time - (this._ts > 0 ? _totalTime / this._ts : ((this._dirty ? this.totalDuration() : this._tDur) - _totalTime) / -this._ts));

      _setEnd(this);

      if (!parent._dirty) {
        //for performance improvement. If the parent's cache is already dirty, it already took care of marking the ancestors as dirty too, so skip the function call here.
        _uncache(parent);
      } //in case any of the ancestor timelines had completed but should now be enabled, we should reset their totalTime() which will also ensure that they're lined up properly and enabled. Skip for animations that are on the root (wasteful). Example: a TimelineLite.exportRoot() is performed when there's a paused tween on the root, the export will not complete until that tween is unpaused, but imagine a child gets restarted later, after all [unpaused] tweens have completed. The start of that child would get pushed out, but one of the ancestors may have completed.


      while (parent.parent) {
        if (parent.parent._time !== parent._start + (parent._ts >= 0 ? parent._tTime / parent._ts : (parent.totalDuration() - parent._tTime) / -parent._ts)) {
          parent.totalTime(parent._tTime, true);
        }

        parent = parent.parent;
      }

      if (!this.parent && this._dp.autoRemoveChildren) {
        //if the animation doesn't have a parent, put it back into its last parent (recorded as _dp for exactly cases like this). Limit to parents with autoRemoveChildren (like globalTimeline) so that if the user manually removes an animation from a timeline and then alters its playhead, it doesn't get added back in.
        _addToTimeline(this._dp, this, this._start - this._delay);
      }
    }

    if (this._tTime !== _totalTime || !this._dur && !suppressEvents || Math.abs(this._zTime) === _tinyNum) {
      this._ts || (this._pTime = _totalTime); // otherwise, if an animation is paused, then the playhead is moved back to zero, then resumed, it'd revert back to the original time at the pause

      _lazySafeRender(this, _totalTime, suppressEvents);
    }

    return this;
  };

  _proto.time = function time(value, suppressEvents) {
    return arguments.length ? this.totalTime(Math.min(this.totalDuration(), value + _elapsedCycleDuration(this)) % this._dur || (value ? this._dur : 0), suppressEvents) : this._time; // note: if the modulus results in 0, the playhead could be exactly at the end or the beginning, and we always defer to the END with a non-zero value, otherwise if you set the time() to the very end (duration()), it would render at the START!
  };

  _proto.totalProgress = function totalProgress(value, suppressEvents) {
    return arguments.length ? this.totalTime(this.totalDuration() * value, suppressEvents) : this.totalDuration() ? Math.min(1, this._tTime / this._tDur) : this.ratio;
  };

  _proto.progress = function progress(value, suppressEvents) {
    return arguments.length ? this.totalTime(this.duration() * (this._yoyo && !(this.iteration() & 1) ? 1 - value : value) + _elapsedCycleDuration(this), suppressEvents) : this.duration() ? Math.min(1, this._time / this._dur) : this.ratio;
  };

  _proto.iteration = function iteration(value, suppressEvents) {
    var cycleDuration = this.duration() + this._rDelay;

    return arguments.length ? this.totalTime(this._time + (value - 1) * cycleDuration, suppressEvents) : this._repeat ? _animationCycle(this._tTime, cycleDuration) + 1 : 1;
  };

  _proto.timeScale = function timeScale(value) {
    if (!arguments.length) {
      return this._ts || this._pauseTS || 0;
    }

    if (this._pauseTS !== null) {
      this._pauseTS = value;
      return this;
    }

    var tTime = this.parent && this._ts ? _parentToChildTotalTime(this.parent._time, this) : this._tTime; // make sure to do the parentToChildTotalTime() BEFORE setting the new _ts because the old one must be used in that calculation.

    this._ts = value; // prioritize rendering where the parent's playhead lines up instead of this._tTime because there could be a tween that's animating another tween's timeScale in the same rendering loop (same parent), thus if the timeScale tween renders first, it would alter _start BEFORE _tTime was set on that tick (in the rendering loop), effectively freezing it until the timeScale tween finishes.

    return _recacheAncestors(this.totalTime(tTime, true));
  };

  _proto.paused = function paused(value) {
    var isPaused = !this._ts;

    if (!arguments.length) {
      return isPaused;
    }

    if (isPaused !== value) {
      if (value) {
        this._pauseTS = this._ts;
        this._pTime = this._tTime || Math.max(-this._delay, this.rawTime()); // if the pause occurs during the delay phase, make sure that's factored in when resuming.

        this._ts = this._act = 0; //we use a timeScale of 0 to indicate a paused state, but we record the old "real" timeScale as _pauseTS so we can revert when unpaused.
      } else {
        _wake();

        this._ts = this._pauseTS || 1;
        this._pauseTS = null; //only defer to _pTime (pauseTime) if tTime is zero. Remember, someone could pause() an animation, then scrub the playhead and resume(). If the parent doesn't have smoothChildTiming, we render at the rawTime() because the startTime won't get updated.

        this.totalTime(this.parent && !this.parent.smoothChildTiming ? this.rawTime() : this._tTime || this._pTime, this.progress() === 1 && (this._tTime -= _tinyNum) && Math.abs(this._zTime) !== _tinyNum); // edge case: animation.progress(1).pause().play() wouldn't render again because the playhead is already at the end, but the call to totalTime() below will add it back to its parent...and not remove it again (since removing only happens upon rendering at a new time). Offsetting the _tTime slightly is done simply to cause the final render in totalTime() that'll pop it off its timeline (if autoRemoveChildren is true, of course). Check to make sure _zTime isn't -_tinyNum to avoid an edge case where the playhead is pushed to the end but INSIDE a tween/callback, the timeline itself is paused thus halting rendering and leaving a few unrendered. When resuming, it wouldn't render those otherwise.
      }
    }

    return this;
  };

  _proto.startTime = function startTime(value) {
    if (arguments.length) {
      if (this.parent && this.parent._sort) {
        _addToTimeline(this.parent, this, value - this._delay);
      }

      return this;
    }

    return this._start;
  };

  _proto.endTime = function endTime(includeRepeats) {
    return this._start + (_isNotFalse(includeRepeats) ? this.totalDuration() : this.duration()) / Math.abs(this._ts);
  };

  _proto.rawTime = function rawTime(wrapRepeats) {
    var parent = this.parent || this._dp; // _dp = detatched parent

    return !parent ? this._tTime : wrapRepeats && (!this._ts || this._repeat && this._time && this.totalProgress() < 1) ? this._tTime % (this._dur + this._rDelay) : !this._ts ? this._tTime : _parentToChildTotalTime(parent.rawTime(wrapRepeats), this);
  } // globalTime(rawTime) {
  // 	let animation = this,
  // 		time = arguments.length ? rawTime : animation.rawTime();
  // 	while (animation) {
  // 		time = animation._start + time / (animation._ts || 1);
  // 		animation = animation.parent;
  // 	}
  // 	return time;
  // }
  ;

  _proto.repeat = function repeat(value) {
    if (arguments.length) {
      this._repeat = value;
      return _onUpdateTotalDuration(this);
    }

    return this._repeat;
  };

  _proto.repeatDelay = function repeatDelay(value) {
    if (arguments.length) {
      this._rDelay = value;
      return _onUpdateTotalDuration(this);
    }

    return this._rDelay;
  };

  _proto.yoyo = function yoyo(value) {
    if (arguments.length) {
      this._yoyo = value;
      return this;
    }

    return this._yoyo;
  };

  _proto.seek = function seek(position, suppressEvents) {
    return this.totalTime(_parsePosition(this, position), _isNotFalse(suppressEvents));
  };

  _proto.restart = function restart(includeDelay, suppressEvents) {
    return this.play().totalTime(includeDelay ? -this._delay : 0, _isNotFalse(suppressEvents));
  };

  _proto.play = function play(from, suppressEvents) {
    if (from != null) {
      this.seek(from, suppressEvents);
    }

    return this.reversed(false).paused(false);
  };

  _proto.reverse = function reverse(from, suppressEvents) {
    if (from != null) {
      this.seek(from || this.totalDuration(), suppressEvents);
    }

    return this.reversed(true).paused(false);
  };

  _proto.pause = function pause(atTime, suppressEvents) {
    if (atTime != null) {
      this.seek(atTime, suppressEvents);
    }

    return this.paused(true);
  };

  _proto.resume = function resume() {
    return this.paused(false);
  };

  _proto.reversed = function reversed(value) {
    var ts = this._ts || this._pauseTS || 0;

    if (arguments.length) {
      if (value !== this.reversed()) {
        this[this._pauseTS === null ? "_ts" : "_pauseTS"] = Math.abs(ts) * (value ? -1 : 1);
        this.totalTime(this._tTime, true);
      }

      return this;
    }

    return ts < 0;
  };

  _proto.invalidate = function invalidate() {
    this._initted = 0;
    this._zTime = -_tinyNum;
    return this;
  };

  _proto.isActive = function isActive(hasStarted) {
    var parent = this.parent || this._dp,
        start = this._start,
        rawTime;
    return !!(!parent || this._ts && (this._initted || !hasStarted) && parent.isActive(hasStarted) && (rawTime = parent.rawTime(true)) >= start && rawTime < this.endTime(true) - _tinyNum);
  };

  _proto.eventCallback = function eventCallback(type, callback, params) {
    var vars = this.vars;

    if (arguments.length > 1) {
      if (!callback) {
        delete vars[type];
      } else {
        vars[type] = callback;

        if (params) {
          vars[type + "Params"] = params;
        }

        if (type === "onUpdate") {
          this._onUpdate = callback;
        }
      }

      return this;
    }

    return vars[type];
  };

  _proto.then = function then(onFulfilled) {
    var self = this;
    return new Promise(function (resolve) {
      var f = _isFunction(onFulfilled) ? onFulfilled : _passThrough,
          _resolve = function _resolve() {
        var _then = self.then;
        self.then = null; // temporarily null the then() method to avoid an infinite loop (see https://github.com/greensock/GSAP/issues/322)

        _isFunction(f) && (f = f(self)) && (f.then || f === self) && (self.then = _then);
        resolve(f);
        self.then = _then;
      };

      if (self._initted && self.totalProgress() === 1 && self._ts >= 0 || !self._tTime && self._ts < 0) {
        _resolve();
      } else {
        self._prom = _resolve;
      }
    });
  };

  _proto.kill = function kill() {
    _interrupt(this);
  };

  return Animation;
}();

_setDefaults(Animation.prototype, {
  _time: 0,
  _start: 0,
  _end: 0,
  _tTime: 0,
  _tDur: 0,
  _dirty: 0,
  _repeat: 0,
  _yoyo: false,
  parent: null,
  _initted: false,
  _rDelay: 0,
  _ts: 1,
  _dp: 0,
  ratio: 0,
  _zTime: -_tinyNum,
  _prom: 0,
  _pauseTS: null
});
/*
 * -------------------------------------------------
 * TIMELINE
 * -------------------------------------------------
 */


var Timeline =
/*#__PURE__*/
function (_Animation) {
  gsap_core_inheritsLoose(Timeline, _Animation);

  function Timeline(vars, time) {
    var _this;

    if (vars === void 0) {
      vars = {};
    }

    _this = _Animation.call(this, vars, time) || this;
    _this.labels = {};
    _this.smoothChildTiming = !!vars.smoothChildTiming;
    _this.autoRemoveChildren = !!vars.autoRemoveChildren;
    _this._sort = _isNotFalse(vars.sortChildren);
    return _this;
  }

  var _proto2 = Timeline.prototype;

  _proto2.to = function to(targets, vars, position) {
    new Tween(targets, _parseVars(arguments, 0, this), _parsePosition(this, _isNumber(vars) ? arguments[3] : position));
    return this;
  };

  _proto2.from = function from(targets, vars, position) {
    new Tween(targets, _parseVars(arguments, 1, this), _parsePosition(this, _isNumber(vars) ? arguments[3] : position));
    return this;
  };

  _proto2.fromTo = function fromTo(targets, fromVars, toVars, position) {
    new Tween(targets, _parseVars(arguments, 2, this), _parsePosition(this, _isNumber(fromVars) ? arguments[4] : position));
    return this;
  };

  _proto2.set = function set(targets, vars, position) {
    vars.duration = 0;
    vars.parent = this;

    if (!vars.repeatDelay) {
      vars.repeat = 0;
    }

    vars.immediateRender = !!vars.immediateRender;
    new Tween(targets, vars, _parsePosition(this, position));
    return this;
  };

  _proto2.call = function call(callback, params, position) {
    return _addToTimeline(this, Tween.delayedCall(0, callback, params), _parsePosition(this, position));
  } //ONLY for backward compatibility! Maybe delete?
  ;

  _proto2.staggerTo = function staggerTo(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams) {
    vars.duration = duration;
    vars.stagger = vars.stagger || stagger;
    vars.onComplete = onCompleteAll;
    vars.onCompleteParams = onCompleteAllParams;
    vars.parent = this;
    new Tween(targets, vars, _parsePosition(this, position));
    return this;
  };

  _proto2.staggerFrom = function staggerFrom(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams) {
    vars.runBackwards = 1;
    vars.immediateRender = _isNotFalse(vars.immediateRender);
    return this.staggerTo(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams);
  };

  _proto2.staggerFromTo = function staggerFromTo(targets, duration, fromVars, toVars, stagger, position, onCompleteAll, onCompleteAllParams) {
    toVars.startAt = fromVars;
    toVars.immediateRender = _isNotFalse(toVars.immediateRender);
    return this.staggerTo(targets, duration, toVars, stagger, position, onCompleteAll, onCompleteAllParams);
  };

  _proto2.render = function render(totalTime, suppressEvents, force) {
    var prevTime = this._time,
        tDur = this._dirty ? this.totalDuration() : this._tDur,
        dur = this._dur,
        tTime = this !== _globalTimeline && totalTime > tDur - _tinyNum && totalTime >= 0 ? tDur : totalTime < _tinyNum ? 0 : totalTime,
        crossingStart = this._zTime < 0 !== totalTime < 0 && (this._initted || !dur),
        time,
        child,
        next,
        iteration,
        cycleDuration,
        prevPaused,
        pauseTween,
        timeScale,
        prevStart,
        prevIteration,
        yoyo,
        isYoyo;

    if (tTime !== this._tTime || force || crossingStart) {
      if (prevTime !== this._time && dur) {
        //if totalDuration() finds a child with a negative startTime and smoothChildTiming is true, things get shifted around internally so we need to adjust the time accordingly. For example, if a tween starts at -30 we must shift EVERYTHING forward 30 seconds and move this timeline's startTime backward by 30 seconds so that things align with the playhead (no jump).
        tTime += this._time - prevTime;
        totalTime += this._time - prevTime;
      }

      time = tTime;
      prevStart = this._start;
      timeScale = this._ts;
      prevPaused = !timeScale;

      if (crossingStart) {
        if (!dur) {
          prevTime = this._zTime;
        }

        if (totalTime || !suppressEvents) {
          //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect.
          this._zTime = totalTime;
        }
      }

      if (this._repeat) {
        //adjust the time for repeats and yoyos
        yoyo = this._yoyo;
        cycleDuration = dur + this._rDelay;
        time = _round(tTime % cycleDuration); //round to avoid floating point errors. (4 % 0.8 should be 0 but some browsers report it as 0.79999999!)

        if (time > dur || tDur === tTime) {
          time = dur;
        }

        iteration = ~~(tTime / cycleDuration);

        if (iteration && iteration === tTime / cycleDuration) {
          time = dur;
          iteration--;
        }

        prevIteration = _animationCycle(this._tTime, cycleDuration);

        if (yoyo && iteration & 1) {
          time = dur - time;
          isYoyo = 1;
        }
        /*
        make sure children at the end/beginning of the timeline are rendered properly. If, for example,
        a 3-second long timeline rendered at 2.9 seconds previously, and now renders at 3.2 seconds (which
        would get translated to 2.8 seconds if the timeline yoyos or 0.2 seconds if it just repeats), there
        could be a callback or a short tween that's at 2.95 or 3 seconds in which wouldn't render. So
        we need to push the timeline to the end (and/or beginning depending on its yoyo value). Also we must
        ensure that zero-duration tweens at the very beginning or end of the Timeline work.
        */


        if (iteration !== prevIteration && !this._lock) {
          var rewinding = yoyo && prevIteration & 1,
              doesWrap = rewinding === (yoyo && iteration & 1);

          if (iteration < prevIteration) {
            rewinding = !rewinding;
          }

          prevTime = rewinding ? 0 : dur;
          this._lock = 1;
          this.render(prevTime, suppressEvents, !dur)._lock = 0;

          if (!suppressEvents && this.parent) {
            _callback(this, "onRepeat");
          }

          this.vars.repeatRefresh && !isYoyo && (this.invalidate()._lock = 1);

          if (prevTime !== this._time || prevPaused !== !this._ts) {
            return this;
          }

          if (doesWrap) {
            this._lock = 2;
            prevTime = rewinding ? dur + 0.0001 : -0.0001;
            this.render(prevTime, true);
            this.vars.repeatRefresh && !isYoyo && this.invalidate();
          }

          this._lock = 0;

          if (!this._ts && !prevPaused) {
            return this;
          } //in order for yoyoEase to work properly when there's a stagger, we must swap out the ease in each sub-tween.
          //_propagateYoyoEase(this, isYoyo);

        }
      }

      if (this._hasPause && !this._forcing && this._lock < 2) {
        pauseTween = _findNextPauseTween(this, _round(prevTime), _round(time));

        if (pauseTween) {
          tTime -= time - (time = pauseTween._start);
        }
      }

      this._tTime = tTime;
      this._time = time;
      this._act = !timeScale; //as long as it's not paused, force it to be active so that if the user renders independent of the parent timeline, it'll be forced to re-render on the next tick.

      if (!this._initted) {
        this._onUpdate = this.vars.onUpdate;
        this._initted = 1;
        this._zTime = totalTime;
      }

      if (!prevTime && time && !suppressEvents) {
        _callback(this, "onStart");
      }

      if (time >= prevTime && totalTime >= 0) {
        child = this._first;

        while (child) {
          next = child._next;

          if ((child._act || time >= child._start) && child._ts && pauseTween !== child) {
            if (child.parent !== this) {
              // an extreme edge case - the child's render could do something like kill() the "next" one in the linked list, or reparent it. In that case we must re-initiate the whole render to be safe.
              return this.render(totalTime, suppressEvents, force);
            }

            child.render(child._ts > 0 ? (time - child._start) * child._ts : (child._dirty ? child.totalDuration() : child._tDur) + (time - child._start) * child._ts, suppressEvents, force);

            if (time !== this._time || !this._ts && !prevPaused) {
              //in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
              pauseTween = 0;
              next && (tTime += this._zTime = -_tinyNum); // it didn't finish rendering, so flag zTime as negative so that so that the next time render() is called it'll be forced (to render any remaining children)

              break;
            }
          }

          child = next;
        }
      } else {
        child = this._last;
        var adjustedTime = totalTime < 0 ? totalTime : time; //when the playhead goes backward beyond the start of this timeline, we must pass that information down to the child animations so that zero-duration tweens know whether to render their starting or ending values.

        while (child) {
          next = child._prev;

          if ((child._act || adjustedTime <= child._end) && child._ts && pauseTween !== child) {
            if (child.parent !== this) {
              // an extreme edge case - the child's render could do something like kill() the "next" one in the linked list, or reparent it. In that case we must re-initiate the whole render to be safe.
              return this.render(totalTime, suppressEvents, force);
            }

            child.render(child._ts > 0 ? (adjustedTime - child._start) * child._ts : (child._dirty ? child.totalDuration() : child._tDur) + (adjustedTime - child._start) * child._ts, suppressEvents, force);

            if (time !== this._time || !this._ts && !prevPaused) {
              //in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
              pauseTween = 0;
              next && (tTime += this._zTime = adjustedTime ? -_tinyNum : _tinyNum); // it didn't finish rendering, so adjust zTime so that so that the next time render() is called it'll be forced (to render any remaining children)

              break;
            }
          }

          child = next;
        }
      }

      if (pauseTween && !suppressEvents) {
        this.pause();
        pauseTween.render(time >= prevTime ? 0 : -_tinyNum)._zTime = time >= prevTime ? 1 : -1;

        if (this._ts) {
          //the callback resumed playback! So since we may have held back the playhead due to where the pause is positioned, go ahead and jump to where it's SUPPOSED to be (if no pause happened).
          this._start = prevStart; //if the pause was at an earlier time and the user resumed in the callback, it could reposition the timeline (changing its startTime), throwing things off slightly, so we make sure the _start doesn't shift.

          _setEnd(this);

          return this.render(totalTime, suppressEvents, force);
        }
      }

      if (this._onUpdate && !suppressEvents) {
        _callback(this, "onUpdate", true);
      }

      if (tTime === tDur && tDur >= this.totalDuration() || !tTime && this._ts < 0) if (prevStart === this._start || Math.abs(timeScale) !== Math.abs(this._ts)) {
        (totalTime || !dur) && (totalTime && this._ts > 0 || !tTime && this._ts < 0) && _removeFromParent(this, 1); // don't remove if the timeline is reversed and the playhead isn't at 0, otherwise tl.progress(1).reverse() won't work. Only remove if the playhead is at the end and timeScale is positive, or if the playhead is at 0 and the timeScale is negative.

        if (!suppressEvents && !(totalTime < 0 && !prevTime)) {
          _callback(this, tTime === tDur ? "onComplete" : "onReverseComplete", true);

          this._prom && this._prom();
        }
      }
    }

    return this;
  };

  _proto2.add = function add(child, position) {
    var _this2 = this;

    if (!_isNumber(position)) {
      position = _parsePosition(this, position);
    }

    if (!(child instanceof Animation)) {
      if (_isArray(child)) {
        child.forEach(function (obj) {
          return _this2.add(obj, position);
        });
        return _uncache(this);
      }

      if (_isString(child)) {
        return this.addLabel(child, position);
      }

      if (_isFunction(child)) {
        child = Tween.delayedCall(0, child);
      } else {
        return this;
      }
    }

    return this !== child ? _addToTimeline(this, child, position) : this; //don't allow a timeline to be added to itself as a child!
  };

  _proto2.getChildren = function getChildren(nested, tweens, timelines, ignoreBeforeTime) {
    if (nested === void 0) {
      nested = true;
    }

    if (tweens === void 0) {
      tweens = true;
    }

    if (timelines === void 0) {
      timelines = true;
    }

    if (ignoreBeforeTime === void 0) {
      ignoreBeforeTime = -_bigNum;
    }

    var a = [],
        child = this._first;

    while (child) {
      if (child._start >= ignoreBeforeTime) {
        if (child instanceof Tween) {
          if (tweens) {
            a.push(child);
          }
        } else {
          if (timelines) {
            a.push(child);
          }

          if (nested) {
            a.push.apply(a, child.getChildren(true, tweens, timelines));
          }
        }
      }

      child = child._next;
    }

    return a;
  };

  _proto2.getById = function getById(id) {
    var animations = this.getChildren(1, 1, 1),
        i = animations.length;

    while (i--) {
      if (animations[i].vars.id === id) {
        return animations[i];
      }
    }
  };

  _proto2.remove = function remove(child) {
    if (_isString(child)) {
      return this.removeLabel(child);
    }

    if (_isFunction(child)) {
      return this.killTweensOf(child);
    }

    _removeLinkedListItem(this, child);

    if (child === this._recent) {
      this._recent = this._last;
    }

    return _uncache(this);
  };

  _proto2.totalTime = function totalTime(_totalTime2, suppressEvents) {
    if (!arguments.length) {
      return this._tTime;
    }

    this._forcing = 1;

    if (!this.parent && !this._dp && this._ts) {
      //special case for the global timeline (or any other that has no parent or detached parent).
      this._start = _round(_ticker.time - (this._ts > 0 ? _totalTime2 / this._ts : (this.totalDuration() - _totalTime2) / -this._ts));
    }

    _Animation.prototype.totalTime.call(this, _totalTime2, suppressEvents);

    this._forcing = 0;
    return this;
  };

  _proto2.addLabel = function addLabel(label, position) {
    this.labels[label] = _parsePosition(this, position);
    return this;
  };

  _proto2.removeLabel = function removeLabel(label) {
    delete this.labels[label];
    return this;
  };

  _proto2.addPause = function addPause(position, callback, params) {
    var t = Tween.delayedCall(0, callback || _emptyFunc, params);
    t.data = "isPause";
    this._hasPause = 1;
    return _addToTimeline(this, t, _parsePosition(this, position));
  };

  _proto2.removePause = function removePause(position) {
    var child = this._first;
    position = _parsePosition(this, position);

    while (child) {
      if (child._start === position && child.data === "isPause") {
        _removeFromParent(child);
      }

      child = child._next;
    }
  };

  _proto2.killTweensOf = function killTweensOf(targets, props, onlyActive) {
    var tweens = this.getTweensOf(targets, onlyActive),
        i = tweens.length;

    while (i--) {
      _overwritingTween !== tweens[i] && tweens[i].kill(targets, props);
    }

    return this;
  };

  _proto2.getTweensOf = function getTweensOf(targets, onlyActive) {
    var a = [],
        parsedTargets = toArray(targets),
        child = this._first,
        children;

    while (child) {
      if (child instanceof Tween) {
        if (_arrayContainsAny(child._targets, parsedTargets) && (!onlyActive || child.isActive(onlyActive === "started"))) {
          a.push(child);
        }
      } else if ((children = child.getTweensOf(parsedTargets, onlyActive)).length) {
        a.push.apply(a, children);
      }

      child = child._next;
    }

    return a;
  };

  _proto2.tweenTo = function tweenTo(position, vars) {
    vars = vars || {};

    var tl = this,
        endTime = _parsePosition(tl, position),
        startAt = vars.startAt,
        tween = Tween.to(tl, _setDefaults(vars, {
      ease: "none",
      lazy: false,
      time: endTime,
      duration: vars.duration || Math.abs(endTime - (startAt && "time" in startAt ? startAt.time : tl._time)) / tl.timeScale() || _tinyNum,
      onStart: function onStart() {
        tl.pause();
        var duration = vars.duration || Math.abs(endTime - tl._time) / tl.timeScale();

        if (tween._dur !== duration) {
          _setDuration(tween, duration).render(tween._time, true, true);
        }

        if (vars.onStart) {
          //in case the user had an onStart in the vars - we don't want to overwrite it.
          vars.onStart.apply(tween, vars.onStartParams || []);
        }
      }
    }));

    return tween;
  };

  _proto2.tweenFromTo = function tweenFromTo(fromPosition, toPosition, vars) {
    return this.tweenTo(toPosition, _setDefaults({
      startAt: {
        time: _parsePosition(this, fromPosition)
      }
    }, vars));
  };

  _proto2.recent = function recent() {
    return this._recent;
  };

  _proto2.nextLabel = function nextLabel(afterTime) {
    if (afterTime === void 0) {
      afterTime = this._time;
    }

    return _getLabelInDirection(this, _parsePosition(this, afterTime));
  };

  _proto2.previousLabel = function previousLabel(beforeTime) {
    if (beforeTime === void 0) {
      beforeTime = this._time;
    }

    return _getLabelInDirection(this, _parsePosition(this, beforeTime), 1);
  };

  _proto2.currentLabel = function currentLabel(value) {
    return arguments.length ? this.seek(value, true) : this.previousLabel(this._time + _tinyNum);
  };

  _proto2.shiftChildren = function shiftChildren(amount, adjustLabels, ignoreBeforeTime) {
    if (ignoreBeforeTime === void 0) {
      ignoreBeforeTime = 0;
    }

    var child = this._first,
        labels = this.labels,
        p;

    while (child) {
      if (child._start >= ignoreBeforeTime) {
        child._start += amount;
      }

      child = child._next;
    }

    if (adjustLabels) {
      for (p in labels) {
        if (labels[p] >= ignoreBeforeTime) {
          labels[p] += amount;
        }
      }
    }

    return _uncache(this);
  };

  _proto2.invalidate = function invalidate() {
    var child = this._first;
    this._lock = 0;

    while (child) {
      child.invalidate();
      child = child._next;
    }

    return _Animation.prototype.invalidate.call(this);
  };

  _proto2.clear = function clear(includeLabels) {
    if (includeLabels === void 0) {
      includeLabels = true;
    }

    var child = this._first,
        next;

    while (child) {
      next = child._next;
      this.remove(child);
      child = next;
    }

    this._time = this._tTime = 0;

    if (includeLabels) {
      this.labels = {};
    }

    return _uncache(this);
  };

  _proto2.totalDuration = function totalDuration(value) {
    var max = 0,
        self = this,
        child = self._last,
        prevStart = _bigNum,
        prev,
        end,
        start,
        parent;

    if (arguments.length) {
      return self._repeat < 0 ? self : self.timeScale(self.totalDuration() / value);
    }

    if (self._dirty) {
      parent = self.parent;

      while (child) {
        prev = child._prev; //record it here in case the tween changes position in the sequence...

        if (child._dirty) {
          child.totalDuration(); //could change the tween._startTime, so make sure the animation's cache is clean before analyzing it.
        }

        start = child._start;

        if (start > prevStart && self._sort && child._ts && !self._lock) {
          //in case one of the tweens shifted out of order, it needs to be re-inserted into the correct position in the sequence
          self._lock = 1; //prevent endless recursive calls - there are methods that get triggered that check duration/totalDuration when we add().

          _addToTimeline(self, child, start - child._delay)._lock = 0;
        } else {
          prevStart = start;
        }

        if (start < 0 && child._ts) {
          //children aren't allowed to have negative startTimes unless smoothChildTiming is true, so adjust here if one is found.
          max -= start;

          if (!parent && !self._dp || parent && parent.smoothChildTiming) {
            self._start += start / self._ts;
            self._time -= start;
            self._tTime -= start;
          }

          self.shiftChildren(-start, false, -1e20);
          prevStart = 0;
        }

        end = _setEnd(child);

        if (end > max && child._ts) {
          max = end;
        }

        child = prev;
      }

      _setDuration(self, self === _globalTimeline && self._time > max ? self._time : Math.min(_bigNum, max), 1);

      self._dirty = 0;
    }

    return self._tDur;
  };

  Timeline.updateRoot = function updateRoot(time) {
    if (_globalTimeline._ts) {
      _lazySafeRender(_globalTimeline, _parentToChildTotalTime(time, _globalTimeline));

      _lastRenderedFrame = _ticker.frame;
    }

    if (_ticker.frame >= _nextGCFrame) {
      _nextGCFrame += _config.autoSleep || 120;
      var child = _globalTimeline._first;
      if (!child || !child._ts) if (_config.autoSleep && _ticker._listeners.length < 2) {
        while (child && !child._ts) {
          child = child._next;
        }

        if (!child) {
          _ticker.sleep();
        }
      }
    }
  };

  return Timeline;
}(Animation);

_setDefaults(Timeline.prototype, {
  _lock: 0,
  _hasPause: 0,
  _forcing: 0
});

var _addComplexStringPropTween = function _addComplexStringPropTween(target, prop, start, end, setter, stringFilter, funcParam) {
  //note: we call _addComplexStringPropTween.call(tweenInstance...) to ensure that it's scoped properly. We may call it from within a plugin too, thus "this" would refer to the plugin.
  var pt = new PropTween(this._pt, target, prop, 0, 1, _renderComplexString, null, setter),
      index = 0,
      matchIndex = 0,
      result,
      startNums,
      color,
      endNum,
      chunk,
      startNum,
      hasRandom,
      a;
  pt.b = start;
  pt.e = end;
  start += ""; //ensure values are strings

  end += "";

  if (hasRandom = ~end.indexOf("random(")) {
    end = _replaceRandom(end);
  }

  if (stringFilter) {
    a = [start, end];
    stringFilter(a, target, prop); //pass an array with the starting and ending values and let the filter do whatever it needs to the values.

    start = a[0];
    end = a[1];
  }

  startNums = start.match(_complexStringNumExp) || [];

  while (result = _complexStringNumExp.exec(end)) {
    endNum = result[0];
    chunk = end.substring(index, result.index);

    if (color) {
      color = (color + 1) % 5;
    } else if (chunk.substr(-5) === "rgba(") {
      color = 1;
    }

    if (endNum !== startNums[matchIndex++]) {
      startNum = parseFloat(startNums[matchIndex - 1]) || 0; //these nested PropTweens are handled in a special way - we'll never actually call a render or setter method on them. We'll just loop through them in the parent complex string PropTween's render method.

      pt._pt = {
        _next: pt._pt,
        p: chunk || matchIndex === 1 ? chunk : ",",
        //note: SVG spec allows omission of comma/space when a negative sign is wedged between two numbers, like 2.5-5.3 instead of 2.5,-5.3 but when tweening, the negative value may switch to positive, so we insert the comma just in case.
        s: startNum,
        c: endNum.charAt(1) === "=" ? parseFloat(endNum.substr(2)) * (endNum.charAt(0) === "-" ? -1 : 1) : parseFloat(endNum) - startNum,
        m: color && color < 4 ? Math.round : 0
      };
      index = _complexStringNumExp.lastIndex;
    }
  }

  pt.c = index < end.length ? end.substring(index, end.length) : ""; //we use the "c" of the PropTween to store the final part of the string (after the last number)

  pt.fp = funcParam;

  if (_relExp.test(end) || hasRandom) {
    pt.e = 0; //if the end string contains relative values or dynamic random(...) values, delete the end it so that on the final render we don't actually set it to the string with += or -= characters (forces it to use the calculated value).
  }

  this._pt = pt; //start the linked list with this new PropTween. Remember, we call _addComplexStringPropTween.call(tweenInstance...) to ensure that it's scoped properly. We may call it from within a plugin too, thus "this" would refer to the plugin.

  return pt;
},
    _addPropTween = function _addPropTween(target, prop, start, end, index, targets, modifier, stringFilter, funcParam) {
  if (_isFunction(end)) {
    end = end(index || 0, target, targets);
  }

  var currentValue = target[prop],
      parsedStart = start !== "get" ? start : !_isFunction(currentValue) ? currentValue : funcParam ? target[prop.indexOf("set") || !_isFunction(target["get" + prop.substr(3)]) ? prop : "get" + prop.substr(3)](funcParam) : target[prop](),
      setter = !_isFunction(currentValue) ? _setterPlain : funcParam ? _setterFuncWithParam : _setterFunc,
      pt;

  if (_isString(end)) {
    if (~end.indexOf("random(")) {
      end = _replaceRandom(end);
    }

    if (end.charAt(1) === "=") {
      end = parseFloat(parsedStart) + parseFloat(end.substr(2)) * (end.charAt(0) === "-" ? -1 : 1) + (getUnit(parsedStart) || 0);
    }
  }

  if (parsedStart !== end) {
    if (!isNaN(parsedStart + end)) {
      pt = new PropTween(this._pt, target, prop, +parsedStart || 0, end - (parsedStart || 0), typeof currentValue === "boolean" ? _renderBoolean : _renderPlain, 0, setter);

      if (funcParam) {
        pt.fp = funcParam;
      }

      if (modifier) {
        pt.modifier(modifier, this, target);
      }

      return this._pt = pt;
    }

    !currentValue && !(prop in target) && _missingPlugin(prop, end);
    return _addComplexStringPropTween.call(this, target, prop, parsedStart, end, setter, stringFilter || _config.stringFilter, funcParam);
  }
},
    //creates a copy of the vars object and processes any function-based values (putting the resulting values directly into the copy) as well as strings with "random()" in them. It does NOT process relative values.
_processVars = function _processVars(vars, index, target, targets, tween) {
  if (_isFunction(vars)) {
    vars = _parseFuncOrString(vars, tween, index, target, targets);
  }

  if (!_isObject(vars) || vars.style && vars.nodeType || _isArray(vars)) {
    return _isString(vars) ? _parseFuncOrString(vars, tween, index, target, targets) : vars;
  }

  var copy = {},
      p;

  for (p in vars) {
    copy[p] = _parseFuncOrString(vars[p], tween, index, target, targets);
  }

  return copy;
},
    _checkPlugin = function _checkPlugin(property, vars, tween, index, target, targets) {
  var plugin, pt, ptLookup, i;

  if (_plugins[property] && (plugin = new _plugins[property]()).init(target, plugin.rawVars ? vars[property] : _processVars(vars[property], index, target, targets, tween), tween, index, targets) !== false) {
    tween._pt = pt = new PropTween(tween._pt, target, property, 0, 1, plugin.render, plugin, 0, plugin.priority);

    if (tween !== _quickTween) {
      ptLookup = tween._ptLookup[tween._targets.indexOf(target)]; //note: we can't use tween._ptLookup[index] because for staggered tweens, the index from the fullTargets array won't match what it is in each individual tween that spawns from the stagger.

      i = plugin._props.length;

      while (i--) {
        ptLookup[plugin._props[i]] = pt;
      }
    }
  }

  return plugin;
},
    _overwritingTween,
    //store a reference temporarily so we can avoid overwriting itself.
_initTween = function _initTween(tween, time) {
  var vars = tween.vars,
      ease = vars.ease,
      startAt = vars.startAt,
      immediateRender = vars.immediateRender,
      lazy = vars.lazy,
      onUpdate = vars.onUpdate,
      onUpdateParams = vars.onUpdateParams,
      callbackScope = vars.callbackScope,
      runBackwards = vars.runBackwards,
      yoyoEase = vars.yoyoEase,
      keyframes = vars.keyframes,
      autoRevert = vars.autoRevert,
      dur = tween._dur,
      prevStartAt = tween._startAt,
      targets = tween._targets,
      parent = tween.parent,
      fullTargets = parent && parent.data === "nested" ? parent.parent._targets : targets,
      autoOverwrite = tween._overwrite === "auto",
      tl = tween.timeline,
      cleanVars,
      i,
      p,
      pt,
      target,
      hasPriority,
      gsData,
      harness,
      plugin,
      ptLookup,
      index,
      harnessVars;

  if (tl && (!keyframes || !ease)) {
    ease = "none";
  }

  tween._ease = _parseEase(ease, _defaults.ease);
  tween._yEase = yoyoEase ? _invertEase(_parseEase(yoyoEase === true ? ease : yoyoEase, _defaults.ease)) : 0;

  if (yoyoEase && tween._yoyo && !tween._repeat) {
    //there must have been a parent timeline with yoyo:true that is currently in its yoyo phase, so flip the eases.
    yoyoEase = tween._yEase;
    tween._yEase = tween._ease;
    tween._ease = yoyoEase;
  }

  if (!tl) {
    //if there's an internal timeline, skip all the parsing because we passed that task down the chain.
    if (prevStartAt) {
      prevStartAt.render(-1, true).kill();
    }

    if (startAt) {
      _removeFromParent(tween._startAt = Tween.set(targets, _setDefaults({
        data: "isStart",
        overwrite: false,
        parent: parent,
        immediateRender: true,
        lazy: _isNotFalse(lazy),
        startAt: null,
        delay: 0,
        onUpdate: onUpdate,
        onUpdateParams: onUpdateParams,
        callbackScope: callbackScope,
        stagger: 0
      }, startAt))); //copy the properties/values into a new object to avoid collisions, like var to = {x:0}, from = {x:500}; timeline.fromTo(e, from, to).fromTo(e, to, from);


      if (immediateRender) {
        if (time > 0) {
          !autoRevert && (tween._startAt = 0); //tweens that render immediately (like most from() and fromTo() tweens) shouldn't revert when their parent timeline's playhead goes backward past the startTime because the initial render could have happened anytime and it shouldn't be directly correlated to this tween's startTime. Imagine setting up a complex animation where the beginning states of various objects are rendered immediately but the tween doesn't happen for quite some time - if we revert to the starting values as soon as the playhead goes backward past the tween's startTime, it will throw things off visually. Reversion should only happen in Timeline instances where immediateRender was false or when autoRevert is explicitly set to true.
        } else if (dur) {
          return; //we skip initialization here so that overwriting doesn't occur until the tween actually begins. Otherwise, if you create several immediateRender:true tweens of the same target/properties to drop into a Timeline, the last one created would overwrite the first ones because they didn't get placed into the timeline yet before the first render occurs and kicks in overwriting.
        }
      }
    } else if (runBackwards && dur) {
      //from() tweens must be handled uniquely: their beginning values must be rendered but we don't want overwriting to occur yet (when time is still 0). Wait until the tween actually begins before doing all the routines like overwriting. At that time, we should render at the END of the tween to ensure that things initialize correctly (remember, from() tweens go backwards)
      if (prevStartAt) {
        !autoRevert && (tween._startAt = 0);
      } else {
        if (time) {
          //in rare cases (like if a from() tween runs and then is invalidate()-ed), immediateRender could be true but the initial forced-render gets skipped, so there's no need to force the render in this context when the _time is greater than 0
          immediateRender = false;
        }

        _removeFromParent(tween._startAt = Tween.set(targets, _merge(_copyExcluding(vars, _reservedProps), {
          overwrite: false,
          data: "isFromStart",
          //we tag the tween with as "isFromStart" so that if [inside a plugin] we need to only do something at the very END of a tween, we have a way of identifying this tween as merely the one that's setting the beginning values for a "from()" tween. For example, clearProps in CSSPlugin should only get applied at the very END of a tween and without this tag, from(...{height:100, clearProps:"height", delay:1}) would wipe the height at the beginning of the tween and after 1 second, it'd kick back in.
          lazy: immediateRender && _isNotFalse(lazy),
          immediateRender: immediateRender,
          //zero-duration tweens render immediately by default, but if we're not specifically instructed to render this tween immediately, we should skip this and merely _init() to record the starting values (rendering them immediately would push them to completion which is wasteful in that case - we'd have to render(-1) immediately after)
          stagger: 0,
          parent: parent //ensures that nested tweens that had a stagger are handled properly, like gsap.from(".class", {y:gsap.utils.wrap([-100,100])})

        })));

        if (!immediateRender) {
          _initTween(tween._startAt, _tinyNum); //ensures that the initial values are recorded

        } else if (!time) {
          return;
        }
      }
    }

    cleanVars = _copyExcluding(vars, _reservedProps);
    tween._pt = 0;
    harness = targets[0] ? _getCache(targets[0]).harness : 0;
    harnessVars = harness && vars[harness.prop]; //someone may need to specify CSS-specific values AND non-CSS values, like if the element has an "x" property plus it's a standard DOM element. We allow people to distinguish by wrapping plugin-specific stuff in a css:{} object for example.

    lazy = dur && _isNotFalse(lazy) || lazy && !dur;

    for (i = 0; i < targets.length; i++) {
      target = targets[i];
      gsData = target._gsap || _harness(targets)[i]._gsap;
      tween._ptLookup[i] = ptLookup = {};

      if (_lazyLookup[gsData.id]) {
        _lazyRender(); //if other tweens of the same target have recently initted but haven't rendered yet, we've got to force the render so that the starting values are correct (imagine populating a timeline with a bunch of sequential tweens and then jumping to the end)

      }

      index = fullTargets === targets ? i : fullTargets.indexOf(target);

      if (harness && (plugin = new harness()).init(target, harnessVars || cleanVars, tween, index, fullTargets) !== false) {
        tween._pt = pt = new PropTween(tween._pt, target, plugin.name, 0, 1, plugin.render, plugin, 0, plugin.priority);

        plugin._props.forEach(function (name) {
          ptLookup[name] = pt;
        });

        if (plugin.priority) {
          hasPriority = 1;
        }
      }

      if (!harness || harnessVars) {
        for (p in cleanVars) {
          if (_plugins[p] && (plugin = _checkPlugin(p, cleanVars, tween, index, target, fullTargets))) {
            if (plugin.priority) {
              hasPriority = 1;
            }
          } else {
            ptLookup[p] = pt = _addPropTween.call(tween, target, p, "get", cleanVars[p], index, fullTargets, 0, vars.stringFilter);
          }
        }
      }

      if (tween._op && tween._op[i]) {
        tween.kill(target, tween._op[i]);
      }

      if (autoOverwrite && tween._pt) {
        _overwritingTween = tween;

        _globalTimeline.killTweensOf(target, ptLookup, "started"); //Also make sure the overwriting doesn't overwrite THIS tween!!!


        _overwritingTween = 0;
      }

      if (tween._pt && lazy) {
        _lazyLookup[gsData.id] = 1;
      }
    }

    if (hasPriority) {
      _sortPropTweensByPriority(tween);
    }

    if (tween._onInit) {
      //plugins like RoundProps must wait until ALL of the PropTweens are instantiated. In the plugin's init() function, it sets the _onInit on the tween instance. May not be pretty/intuitive, but it's fast and keeps file size down.
      tween._onInit(tween);
    }
  }

  tween._from = !tl && !!vars.runBackwards; //nested timelines should never run backwards - the backwards-ness is in the child tweens.

  tween._onUpdate = onUpdate;
  tween._initted = 1;
},
    _addAliasesToVars = function _addAliasesToVars(targets, vars) {
  var harness = targets[0] ? _getCache(targets[0]).harness : 0,
      propertyAliases = harness && harness.aliases,
      copy,
      p,
      i,
      aliases;

  if (!propertyAliases) {
    return vars;
  }

  copy = _merge({}, vars);

  for (p in propertyAliases) {
    if (p in copy) {
      aliases = propertyAliases[p].split(",");
      i = aliases.length;

      while (i--) {
        copy[aliases[i]] = copy[p];
      }
    }
  }

  return copy;
},
    _parseFuncOrString = function _parseFuncOrString(value, tween, i, target, targets) {
  return _isFunction(value) ? value.call(tween, i, target, targets) : _isString(value) && ~value.indexOf("random(") ? _replaceRandom(value) : value;
},
    _staggerTweenProps = _callbackNames + ",repeat,repeatDelay,yoyo,repeatRefresh,yoyoEase",
    _staggerPropsToSkip = (_staggerTweenProps + ",id,stagger,delay,duration,paused").split(",");
/*
 * --------------------------------------------------------------------------------------
 * TWEEN
 * --------------------------------------------------------------------------------------
 */


var Tween =
/*#__PURE__*/
function (_Animation2) {
  gsap_core_inheritsLoose(Tween, _Animation2);

  function Tween(targets, vars, time) {
    var _this3;

    if (typeof vars === "number") {
      time.duration = vars;
      vars = time;
      time = null;
    }

    _this3 = _Animation2.call(this, _inheritDefaults(vars), time) || this;
    var _this3$vars = _this3.vars,
        duration = _this3$vars.duration,
        delay = _this3$vars.delay,
        immediateRender = _this3$vars.immediateRender,
        stagger = _this3$vars.stagger,
        overwrite = _this3$vars.overwrite,
        keyframes = _this3$vars.keyframes,
        defaults = _this3$vars.defaults,
        parsedTargets = (_isArray(targets) ? _isNumber(targets[0]) : "length" in vars) ? [targets] : toArray(targets),
        tl,
        i,
        copy,
        l,
        p,
        curTarget,
        staggerFunc,
        staggerVarsToMerge;
    _this3._targets = parsedTargets.length ? _harness(parsedTargets) : _warn("GSAP target " + targets + " not found. https://greensock.com", !_config.nullTargetWarn) || [];
    _this3._ptLookup = []; //PropTween lookup. An array containing an object for each target, having keys for each tweening property

    _this3._overwrite = overwrite;

    if (keyframes || stagger || _isFuncOrString(duration) || _isFuncOrString(delay)) {
      vars = _this3.vars;
      tl = _this3.timeline = new Timeline({
        data: "nested",
        defaults: defaults || {}
      });
      tl.kill();
      tl.parent = gsap_core_assertThisInitialized(_this3);

      if (keyframes) {
        _setDefaults(tl.vars.defaults, {
          ease: "none"
        });

        keyframes.forEach(function (frame) {
          return tl.to(parsedTargets, frame, ">");
        });
      } else {
        l = parsedTargets.length;
        staggerFunc = stagger ? distribute(stagger) : _emptyFunc;

        if (_isObject(stagger)) {
          //users can pass in callbacks like onStart/onComplete in the stagger object. These should fire with each individual tween.
          for (p in stagger) {
            if (~_staggerTweenProps.indexOf(p)) {
              if (!staggerVarsToMerge) {
                staggerVarsToMerge = {};
              }

              staggerVarsToMerge[p] = stagger[p];
            }
          }
        }

        for (i = 0; i < l; i++) {
          copy = {};

          for (p in vars) {
            if (_staggerPropsToSkip.indexOf(p) < 0) {
              copy[p] = vars[p];
            }
          }

          copy.stagger = 0;

          if (staggerVarsToMerge) {
            _merge(copy, staggerVarsToMerge);
          }

          if (vars.yoyoEase && !vars.repeat) {
            //so that propagation works properly when a ancestor timeline yoyos
            copy.yoyoEase = vars.yoyoEase;
          }

          curTarget = parsedTargets[i]; //don't just copy duration or delay because if they're a string or function, we'd end up in an infinite loop because _isFuncOrString() would evaluate as true in the child tweens, entering this loop, etc. So we parse the value straight from vars and default to 0.

          copy.duration = +_parseFuncOrString(duration, gsap_core_assertThisInitialized(_this3), i, curTarget, parsedTargets);
          copy.delay = (+_parseFuncOrString(delay, gsap_core_assertThisInitialized(_this3), i, curTarget, parsedTargets) || 0) - _this3._delay;

          if (!stagger && l === 1 && copy.delay) {
            // if someone does delay:"random(1, 5)", repeat:-1, for example, the delay shouldn't be inside the repeat.
            _this3._delay = delay = copy.delay;
            _this3._start += delay;
            copy.delay = 0;
          }

          tl.to(curTarget, copy, staggerFunc(i, curTarget, parsedTargets));
        }

        duration = delay = 0;
      }

      duration || _this3.duration(duration = tl.duration());
    } else {
      _this3.timeline = 0; //speed optimization, faster lookups (no going up the prototype chain)
    }

    if (overwrite === true) {
      _overwritingTween = gsap_core_assertThisInitialized(_this3);

      _globalTimeline.killTweensOf(parsedTargets);

      _overwritingTween = 0;
    }

    if (immediateRender || !duration && !keyframes && _this3._start === _this3.parent._time && _isNotFalse(immediateRender) && _hasNoPausedAncestors(gsap_core_assertThisInitialized(_this3)) && _this3.parent.data !== "nested") {
      _this3._tTime = -_tinyNum; //forces a render without having to set the render() "force" parameter to true because we want to allow lazying by default (using the "force" parameter always forces an immediate full render)

      _this3.render(Math.max(0, -delay)); //in case delay is negative

    }

    return _this3;
  }

  var _proto3 = Tween.prototype;

  _proto3.render = function render(totalTime, suppressEvents, force) {
    var prevTime = this._time,
        tDur = this._tDur,
        dur = this._dur,
        tTime = totalTime > tDur - _tinyNum && totalTime >= 0 ? tDur : totalTime < _tinyNum ? 0 : totalTime,
        time,
        pt,
        iteration,
        cycleDuration,
        prevIteration,
        isYoyo,
        ratio,
        timeline,
        yoyoEase;

    if (!dur) {
      _renderZeroDurationTween(this, totalTime, suppressEvents, force);
    } else if (tTime !== this._tTime || !totalTime || force || this._startAt && this._zTime < 0 !== totalTime < 0) {
      //this senses if we're crossing over the start time, in which case we must record _zTime and force the render, but we do it in this lengthy conditional way for performance reasons (usually we can skip the calculations): this._initted && (this._zTime < 0) !== (totalTime < 0)
      time = tTime;
      timeline = this.timeline;

      if (this._repeat) {
        //adjust the time for repeats and yoyos
        cycleDuration = dur + this._rDelay;
        time = _round(tTime % cycleDuration); //round to avoid floating point errors. (4 % 0.8 should be 0 but some browsers report it as 0.79999999!)

        if (time > dur || tDur === tTime) {
          // the tDur === tTime is for edge cases where there's a lengthy decimal on the duration and it may reach the very end but the time is rendered as not-quite-there (remember, tDur is rounded to 4 decimals whereas dur isn't)
          time = dur;
        }

        iteration = ~~(tTime / cycleDuration);

        if (iteration && iteration === tTime / cycleDuration) {
          time = dur;
          iteration--;
        }

        isYoyo = this._yoyo && iteration & 1;

        if (isYoyo) {
          yoyoEase = this._yEase;
          time = dur - time;
        }

        prevIteration = _animationCycle(this._tTime, cycleDuration);

        if (time === prevTime && !force && this._initted) {
          //could be during the repeatDelay part. No need to render and fire callbacks.
          return this;
        }

        if (iteration !== prevIteration) {
          //timeline && this._yEase && _propagateYoyoEase(timeline, isYoyo);
          //repeatRefresh functionality
          if (this.vars.repeatRefresh && !isYoyo && !this._lock) {
            this._lock = force = 1; //force, otherwise if lazy is true, the _attemptInitTween() will return and we'll jump out and get caught bouncing on each tick.

            this.render(cycleDuration * iteration, true).invalidate()._lock = 0;
          }
        }
      }

      if (!this._initted && _attemptInitTween(this, time, force, suppressEvents)) {
        this._tTime = 0; // in constructor if immediateRender is true, we set _tTime to -_tinyNum to have the playhead cross the starting point but we can't leave _tTime as a negative number.

        return this;
      }

      this._tTime = tTime;
      this._time = time;

      if (!this._act && this._ts) {
        this._act = 1; //as long as it's not paused, force it to be active so that if the user renders independent of the parent timeline, it'll be forced to re-render on the next tick.

        this._lazy = 0;
      }

      this.ratio = ratio = (yoyoEase || this._ease)(time / dur);

      if (this._from) {
        this.ratio = ratio = 1 - ratio;
      }

      if (!prevTime && time && !suppressEvents) {
        _callback(this, "onStart");
      }

      pt = this._pt;

      while (pt) {
        pt.r(ratio, pt.d);
        pt = pt._next;
      }

      timeline && timeline.render(totalTime < 0 ? totalTime : !time && isYoyo ? -_tinyNum : timeline._dur * ratio, suppressEvents, force) || this._startAt && (this._zTime = totalTime);

      if (this._onUpdate && !suppressEvents) {
        if (totalTime < 0 && this._startAt) {
          this._startAt.render(totalTime, true, force); //note: for performance reasons, we tuck this conditional logic inside less traveled areas (most tweens don't have an onUpdate). We'd just have it at the end before the onComplete, but the values should be updated before any onUpdate is called, so we ALSO put it here and then if it's not called, we do so later near the onComplete.

        }

        _callback(this, "onUpdate");
      }

      if (this._repeat) if (iteration !== prevIteration && this.vars.onRepeat && !suppressEvents && this.parent) {
        _callback(this, "onRepeat");
      }

      if ((tTime === this._tDur || !tTime) && this._tTime === tTime) {
        if (totalTime < 0 && this._startAt && !this._onUpdate) {
          this._startAt.render(totalTime, true, force);
        }

        (totalTime || !dur) && (totalTime && this._ts > 0 || !tTime && this._ts < 0) && _removeFromParent(this, 1); // don't remove if we're rendering at exactly a time of 0, as there could be autoRevert values that should get set on the next tick (if the playhead goes backward beyond the startTime, negative totalTime). Don't remove if the timeline is reversed and the playhead isn't at 0, otherwise tl.progress(1).reverse() won't work. Only remove if the playhead is at the end and timeScale is positive, or if the playhead is at 0 and the timeScale is negative.

        if (!suppressEvents && !(totalTime < 0 && !prevTime)) {
          _callback(this, tTime === tDur ? "onComplete" : "onReverseComplete", true);

          this._prom && this._prom();
        }
      }
    }

    return this;
  };

  _proto3.targets = function targets() {
    return this._targets;
  };

  _proto3.invalidate = function invalidate() {
    this._pt = this._op = this._startAt = this._onUpdate = this._act = this._lazy = 0;
    this._ptLookup = [];

    if (this.timeline) {
      this.timeline.invalidate();
    }

    return _Animation2.prototype.invalidate.call(this);
  };

  _proto3.kill = function kill(targets, vars) {
    if (vars === void 0) {
      vars = "all";
    }

    if (!targets && (!vars || vars === "all")) {
      this._lazy = 0;

      if (this.parent) {
        return _interrupt(this);
      }
    }

    if (this.timeline) {
      this.timeline.killTweensOf(targets, vars, _overwritingTween && _overwritingTween.vars.overwrite !== true);
      return this;
    }

    var parsedTargets = this._targets,
        killingTargets = targets ? toArray(targets) : parsedTargets,
        propTweenLookup = this._ptLookup,
        firstPT = this._pt,
        overwrittenProps,
        curLookup,
        curOverwriteProps,
        props,
        p,
        pt,
        i;

    if ((!vars || vars === "all") && _arraysMatch(parsedTargets, killingTargets)) {
      return _interrupt(this);
    }

    overwrittenProps = this._op = this._op || [];

    if (vars !== "all") {
      //so people can pass in a comma-delimited list of property names
      if (_isString(vars)) {
        p = {};

        _forEachName(vars, function (name) {
          return p[name] = 1;
        });

        vars = p;
      }

      vars = _addAliasesToVars(parsedTargets, vars);
    }

    i = parsedTargets.length;

    while (i--) {
      if (~killingTargets.indexOf(parsedTargets[i])) {
        curLookup = propTweenLookup[i];

        if (vars === "all") {
          overwrittenProps[i] = vars;
          props = curLookup;
          curOverwriteProps = {};
        } else {
          curOverwriteProps = overwrittenProps[i] = overwrittenProps[i] || {};
          props = vars;
        }

        for (p in props) {
          pt = curLookup && curLookup[p];

          if (pt) {
            if (!("kill" in pt.d) || pt.d.kill(p) === true) {
              _removeLinkedListItem(this, pt, "_pt");
            }

            delete curLookup[p];
          }

          if (curOverwriteProps !== "all") {
            curOverwriteProps[p] = 1;
          }
        }
      }
    }

    if (this._initted && !this._pt && firstPT) {
      //if all tweening properties are killed, kill the tween. Without this line, if there's a tween with multiple targets and then you killTweensOf() each target individually, the tween would technically still remain active and fire its onComplete even though there aren't any more properties tweening.
      _interrupt(this);
    }

    return this;
  };

  Tween.to = function to(targets, vars) {
    return new Tween(targets, vars, arguments[2]);
  };

  Tween.from = function from(targets, vars) {
    return new Tween(targets, _parseVars(arguments, 1));
  };

  Tween.delayedCall = function delayedCall(delay, callback, params, scope) {
    return new Tween(callback, 0, {
      immediateRender: false,
      lazy: false,
      overwrite: false,
      delay: delay,
      onComplete: callback,
      onReverseComplete: callback,
      onCompleteParams: params,
      onReverseCompleteParams: params,
      callbackScope: scope
    });
  };

  Tween.fromTo = function fromTo(targets, fromVars, toVars) {
    return new Tween(targets, _parseVars(arguments, 2));
  };

  Tween.set = function set(targets, vars) {
    vars.duration = 0;

    if (!vars.repeatDelay) {
      vars.repeat = 0;
    }

    return new Tween(targets, vars);
  };

  Tween.killTweensOf = function killTweensOf(targets, props, onlyActive) {
    return _globalTimeline.killTweensOf(targets, props, onlyActive);
  };

  return Tween;
}(Animation);

_setDefaults(Tween.prototype, {
  _targets: [],
  _lazy: 0,
  _startAt: 0,
  _op: 0,
  _onInit: 0
}); //add the pertinent timeline methods to Tween instances so that users can chain conveniently and create a timeline automatically. (removed due to concerns that it'd ultimately add to more confusion especially for beginners)
// _forEachName("to,from,fromTo,set,call,add,addLabel,addPause", name => {
// 	Tween.prototype[name] = function() {
// 		let tl = new Timeline();
// 		return _addToTimeline(tl, this)[name].apply(tl, toArray(arguments));
// 	}
// });
//for backward compatibility. Leverage the timeline calls.


_forEachName("staggerTo,staggerFrom,staggerFromTo", function (name) {
  Tween[name] = function () {
    var tl = new Timeline(),
        params = _slice.call(arguments, 0);

    params.splice(name === "staggerFromTo" ? 5 : 4, 0, 0);
    return tl[name].apply(tl, params);
  };
});
/*
 * --------------------------------------------------------------------------------------
 * PROPTWEEN
 * --------------------------------------------------------------------------------------
 */


var _setterPlain = function _setterPlain(target, property, value) {
  return target[property] = value;
},
    _setterFunc = function _setterFunc(target, property, value) {
  return target[property](value);
},
    _setterFuncWithParam = function _setterFuncWithParam(target, property, value, data) {
  return target[property](data.fp, value);
},
    _setterAttribute = function _setterAttribute(target, property, value) {
  return target.setAttribute(property, value);
},
    _getSetter = function _getSetter(target, property) {
  return _isFunction(target[property]) ? _setterFunc : _isUndefined(target[property]) && target.setAttribute ? _setterAttribute : _setterPlain;
},
    _renderPlain = function _renderPlain(ratio, data) {
  return data.set(data.t, data.p, Math.round((data.s + data.c * ratio) * 10000) / 10000, data);
},
    _renderBoolean = function _renderBoolean(ratio, data) {
  return data.set(data.t, data.p, !!(data.s + data.c * ratio), data);
},
    _renderComplexString = function _renderComplexString(ratio, data) {
  var pt = data._pt,
      s = "";

  if (!ratio && data.b) {
    //b = beginning string
    s = data.b;
  } else if (ratio === 1 && data.e) {
    //e = ending string
    s = data.e;
  } else {
    while (pt) {
      s = pt.p + (pt.m ? pt.m(pt.s + pt.c * ratio) : Math.round((pt.s + pt.c * ratio) * 10000) / 10000) + s; //we use the "p" property for the text inbetween (like a suffix). And in the context of a complex string, the modifier (m) is typically just Math.round(), like for RGB colors.

      pt = pt._next;
    }

    s += data.c; //we use the "c" of the PropTween to store the final chunk of non-numeric text.
  }

  data.set(data.t, data.p, s, data);
},
    _renderPropTweens = function _renderPropTweens(ratio, data) {
  var pt = data._pt;

  while (pt) {
    pt.r(ratio, pt.d);
    pt = pt._next;
  }
},
    _addPluginModifier = function _addPluginModifier(modifier, tween, target, property) {
  var pt = this._pt,
      next;

  while (pt) {
    next = pt._next;

    if (pt.p === property) {
      pt.modifier(modifier, tween, target);
    }

    pt = next;
  }
},
    _killPropTweensOf = function _killPropTweensOf(property) {
  var pt = this._pt,
      hasNonDependentRemaining,
      next;

  while (pt) {
    next = pt._next;

    if (pt.p === property && !pt.op || pt.op === property) {
      _removeLinkedListItem(this, pt, "_pt");
    } else if (!pt.dep) {
      hasNonDependentRemaining = 1;
    }

    pt = next;
  }

  return !hasNonDependentRemaining;
},
    _setterWithModifier = function _setterWithModifier(target, property, value, data) {
  data.mSet(target, property, data.m.call(data.tween, value, data.mt), data);
},
    _sortPropTweensByPriority = function _sortPropTweensByPriority(parent) {
  var pt = parent._pt,
      next,
      pt2,
      first,
      last; //sorts the PropTween linked list in order of priority because some plugins need to do their work after ALL of the PropTweens were created (like RoundPropsPlugin and ModifiersPlugin)

  while (pt) {
    next = pt._next;
    pt2 = first;

    while (pt2 && pt2.pr > pt.pr) {
      pt2 = pt2._next;
    }

    if (pt._prev = pt2 ? pt2._prev : last) {
      pt._prev._next = pt;
    } else {
      first = pt;
    }

    if (pt._next = pt2) {
      pt2._prev = pt;
    } else {
      last = pt;
    }

    pt = next;
  }

  parent._pt = first;
}; //PropTween key: t = target, p = prop, r = renderer, d = data, s = start, c = change, op = overwriteProperty (ONLY populated when it's different than p), pr = priority, _next/_prev for the linked list siblings, set = setter, m = modifier, mSet = modifierSetter (the original setter, before a modifier was added)


var PropTween =
/*#__PURE__*/
function () {
  function PropTween(next, target, prop, start, change, renderer, data, setter, priority) {
    this.t = target;
    this.s = start;
    this.c = change;
    this.p = prop;
    this.r = renderer || _renderPlain;
    this.d = data || this;
    this.set = setter || _setterPlain;
    this.pr = priority || 0;
    this._next = next;

    if (next) {
      next._prev = this;
    }
  }

  var _proto4 = PropTween.prototype;

  _proto4.modifier = function modifier(func, tween, target) {
    this.mSet = this.mSet || this.set; //in case it was already set (a PropTween can only have one modifier)

    this.set = _setterWithModifier;
    this.m = func;
    this.mt = target; //modifier target

    this.tween = tween;
  };

  return PropTween;
}(); //Initialization tasks

_forEachName(_callbackNames + ",parent,duration,ease,delay,overwrite,runBackwards,startAt,yoyo,immediateRender,repeat,repeatDelay,data,paused,reversed,lazy,callbackScope,stringFilter,id,yoyoEase,stagger,inherit,repeatRefresh,keyframes,autoRevert", function (name) {
  _reservedProps[name] = 1;
  if (name.substr(0, 2) === "on") _reservedProps[name + "Params"] = 1;
});

_globals.TweenMax = _globals.TweenLite = Tween;
_globals.TimelineLite = _globals.TimelineMax = Timeline;
_globalTimeline = new Timeline({
  sortChildren: false,
  defaults: _defaults,
  autoRemoveChildren: true,
  id: "root",
  smoothChildTiming: true
});
_config.stringFilter = _colorStringFilter;
/*
 * --------------------------------------------------------------------------------------
 * GSAP
 * --------------------------------------------------------------------------------------
 */

var _gsap = {
  registerPlugin: function registerPlugin() {
    for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args[_key2] = arguments[_key2];
    }

    args.forEach(function (config) {
      return _createPlugin(config);
    });
  },
  timeline: function timeline(vars) {
    return new Timeline(vars);
  },
  getTweensOf: function getTweensOf(targets, onlyActive) {
    return _globalTimeline.getTweensOf(targets, onlyActive);
  },
  getProperty: function getProperty(target, property, unit, uncache) {
    if (_isString(target)) {
      //in case selector text or an array is passed in
      target = toArray(target)[0];
    }

    var getter = _getCache(target || {}).get,
        format = unit ? _passThrough : _numericIfPossible;

    if (unit === "native") {
      unit = "";
    }

    return !target ? target : !property ? function (property, unit, uncache) {
      return format((_plugins[property] && _plugins[property].get || getter)(target, property, unit, uncache));
    } : format((_plugins[property] && _plugins[property].get || getter)(target, property, unit, uncache));
  },
  quickSetter: function quickSetter(target, property, unit) {
    target = toArray(target);

    if (target.length > 1) {
      var setters = target.map(function (t) {
        return gsap.quickSetter(t, property, unit);
      }),
          l = setters.length;
      return function (value) {
        var i = l;

        while (i--) {
          setters[i](value);
        }
      };
    }

    target = target[0] || {};

    var Plugin = _plugins[property],
        cache = _getCache(target),
        setter = Plugin ? function (value) {
      var p = new Plugin();
      _quickTween._pt = 0;
      p.init(target, unit ? value + unit : value, _quickTween, 0, [target]);
      p.render(1, p);
      _quickTween._pt && _renderPropTweens(1, _quickTween);
    } : cache.set(target, property);

    return Plugin ? setter : function (value) {
      return setter(target, property, unit ? value + unit : value, cache, 1);
    };
  },
  isTweening: function isTweening(targets) {
    return _globalTimeline.getTweensOf(targets, true).length > 0;
  },
  defaults: function defaults(value) {
    if (value && value.ease) {
      value.ease = _parseEase(value.ease, _defaults.ease);
    }

    return _mergeDeep(_defaults, value || {});
  },
  config: function config(value) {
    return _mergeDeep(_config, value || {});
  },
  registerEffect: function registerEffect(_ref) {
    var name = _ref.name,
        effect = _ref.effect,
        plugins = _ref.plugins,
        defaults = _ref.defaults,
        extendTimeline = _ref.extendTimeline;
    (plugins || "").split(",").forEach(function (pluginName) {
      return pluginName && !_plugins[pluginName] && !_globals[pluginName] && _warn(name + " effect requires " + pluginName + " plugin.");
    });

    _effects[name] = function (targets, vars) {
      return effect(toArray(targets), _setDefaults(vars || {}, defaults));
    };

    if (extendTimeline) {
      Timeline.prototype[name] = function (targets, vars, position) {
        return this.add(_effects[name](targets, _isObject(vars) ? vars : (position = vars) && {}), position);
      };
    }
  },
  registerEase: function registerEase(name, ease) {
    _easeMap[name] = _parseEase(ease);
  },
  parseEase: function parseEase(ease, defaultEase) {
    return arguments.length ? _parseEase(ease, defaultEase) : _easeMap;
  },
  getById: function getById(id) {
    return _globalTimeline.getById(id);
  },
  exportRoot: function exportRoot(vars, includeDelayedCalls) {
    if (vars === void 0) {
      vars = {};
    }

    var tl = new Timeline(vars),
        child,
        next;
    tl.smoothChildTiming = _isNotFalse(vars.smoothChildTiming);

    _globalTimeline.remove(tl);

    tl._dp = 0; //otherwise it'll get re-activated when adding children and be re-introduced into _globalTimeline's linked list (then added to itself).

    tl._time = tl._tTime = _globalTimeline._time;
    child = _globalTimeline._first;

    while (child) {
      next = child._next;

      if (includeDelayedCalls || !(!child._dur && child instanceof Tween && child.vars.onComplete === child._targets[0])) {
        _addToTimeline(tl, child, child._start - child._delay);
      }

      child = next;
    }

    _addToTimeline(_globalTimeline, tl, 0);

    return tl;
  },
  utils: {
    wrap: gsap_core_wrap,
    wrapYoyo: wrapYoyo,
    distribute: distribute,
    random: random,
    snap: snap,
    normalize: normalize,
    getUnit: getUnit,
    clamp: clamp,
    splitColor: splitColor,
    toArray: toArray,
    mapRange: mapRange,
    pipe: pipe,
    unitize: unitize,
    interpolate: interpolate,
    shuffle: shuffle
  },
  install: _install,
  effects: _effects,
  ticker: _ticker,
  updateRoot: Timeline.updateRoot,
  plugins: _plugins,
  globalTimeline: _globalTimeline,
  core: {
    PropTween: PropTween,
    globals: _addGlobal,
    Tween: Tween,
    Timeline: Timeline,
    Animation: Animation,
    getCache: _getCache
  }
};

_forEachName("to,from,fromTo,delayedCall,set,killTweensOf", function (name) {
  return _gsap[name] = Tween[name];
});

_ticker.add(Timeline.updateRoot);

_quickTween = _gsap.to({}, {
  duration: 0
}); // ---- EXTRA PLUGINS --------------------------------------------------------

var _getPluginPropTween = function _getPluginPropTween(plugin, prop) {
  var pt = plugin._pt;

  while (pt && pt.p !== prop && pt.op !== prop && pt.fp !== prop) {
    pt = pt._next;
  }

  return pt;
},
    _addModifiers = function _addModifiers(tween, modifiers) {
  var targets = tween._targets,
      p,
      i,
      pt;

  for (p in modifiers) {
    i = targets.length;

    while (i--) {
      pt = tween._ptLookup[i][p];

      if (pt && (pt = pt.d)) {
        if (pt._pt) {
          // is a plugin
          pt = _getPluginPropTween(pt, p);
        }

        pt && pt.modifier && pt.modifier(modifiers[p], tween, targets[i], p);
      }
    }
  }
},
    _buildModifierPlugin = function _buildModifierPlugin(name, modifier) {
  return {
    name: name,
    rawVars: 1,
    //don't pre-process function-based values or "random()" strings.
    init: function init(target, vars, tween) {
      tween._onInit = function (tween) {
        var temp, p;

        if (_isString(vars)) {
          temp = {};

          _forEachName(vars, function (name) {
            return temp[name] = 1;
          }); //if the user passes in a comma-delimited list of property names to roundProps, like "x,y", we round to whole numbers.


          vars = temp;
        }

        if (modifier) {
          temp = {};

          for (p in vars) {
            temp[p] = modifier(vars[p]);
          }

          vars = temp;
        }

        _addModifiers(tween, vars);
      };
    }
  };
}; //register core plugins


var gsap = _gsap.registerPlugin({
  name: "attr",
  init: function init(target, vars, tween, index, targets) {
    for (var p in vars) {
      this.add(target, "setAttribute", (target.getAttribute(p) || 0) + "", vars[p], index, targets, 0, 0, p); //this.add(target, "setAttribute", (target.getAttribute((p in target.dataset ? (p = "data-" + p) : p)) || 0) + "", vars[p], index, targets, 0, 0, p);

      this._props.push(p);
    }
  }
}, {
  name: "endArray",
  init: function init(target, value) {
    var i = value.length;

    while (i--) {
      this.add(target, i, target[i] || 0, value[i]);
    }
  }
}, _buildModifierPlugin("roundProps", _roundModifier), _buildModifierPlugin("modifiers"), _buildModifierPlugin("snap", snap)) || _gsap; //to prevent the core plugins from being dropped via aggressive tree shaking, we must include them in the variable declaration in this way.

Tween.version = Timeline.version = gsap.version = "3.2.0";
_coreReady = 1;

if (_windowExists()) {
  _wake();
}

var Power0 = _easeMap.Power0,
    Power1 = _easeMap.Power1,
    Power2 = _easeMap.Power2,
    Power3 = _easeMap.Power3,
    Power4 = _easeMap.Power4,
    Linear = _easeMap.Linear,
    Quad = _easeMap.Quad,
    Cubic = _easeMap.Cubic,
    Quart = _easeMap.Quart,
    Quint = _easeMap.Quint,
    Strong = _easeMap.Strong,
    Elastic = _easeMap.Elastic,
    Back = _easeMap.Back,
    SteppedEase = _easeMap.SteppedEase,
    Bounce = _easeMap.Bounce,
    Sine = _easeMap.Sine,
    Expo = _easeMap.Expo,
    Circ = _easeMap.Circ;

 //export some internal methods/orojects for use in CSSPlugin so that we can externalize that file and allow custom builds that exclude it.


// CONCATENATED MODULE: ./node_modules/gsap/CSSPlugin.js
/*!
 * CSSPlugin 3.2.0
 * https://greensock.com
 *
 * Copyright 2008-2020, GreenSock. All rights reserved.
 * Subject to the terms at https://greensock.com/standard-license or for
 * Club GreenSock members, the agreement issued with that membership.
 * @author: Jack Doyle, jack@greensock.com
*/

/* eslint-disable */


var CSSPlugin_win,
    CSSPlugin_doc,
    _docElement,
    _pluginInitted,
    _tempDiv,
    _tempDivStyler,
    _recentSetterPlugin,
    CSSPlugin_windowExists = function _windowExists() {
  return typeof window !== "undefined";
},
    _transformProps = {},
    _RAD2DEG = 180 / Math.PI,
    _DEG2RAD = Math.PI / 180,
    _atan2 = Math.atan2,
    CSSPlugin_bigNum = 1e8,
    _capsExp = /([A-Z])/g,
    _horizontalExp = /(?:left|right|width|margin|padding|x)/i,
    _complexExp = /[\s,\(]\S/,
    _propertyAliases = {
  autoAlpha: "opacity,visibility",
  scale: "scaleX,scaleY",
  alpha: "opacity"
},
    _renderCSSProp = function _renderCSSProp(ratio, data) {
  return data.set(data.t, data.p, Math.round((data.s + data.c * ratio) * 10000) / 10000 + data.u, data);
},
    _renderPropWithEnd = function _renderPropWithEnd(ratio, data) {
  return data.set(data.t, data.p, ratio === 1 ? data.e : Math.round((data.s + data.c * ratio) * 10000) / 10000 + data.u, data);
},
    _renderCSSPropWithBeginning = function _renderCSSPropWithBeginning(ratio, data) {
  return data.set(data.t, data.p, ratio ? Math.round((data.s + data.c * ratio) * 10000) / 10000 + data.u : data.b, data);
},
    //if units change, we need a way to render the original unit/value when the tween goes all the way back to the beginning (ratio:0)
_renderRoundedCSSProp = function _renderRoundedCSSProp(ratio, data) {
  var value = data.s + data.c * ratio;
  data.set(data.t, data.p, ~~(value + (value < 0 ? -.5 : .5)) + data.u, data);
},
    _renderNonTweeningValue = function _renderNonTweeningValue(ratio, data) {
  return data.set(data.t, data.p, ratio ? data.e : data.b, data);
},
    _renderNonTweeningValueOnlyAtEnd = function _renderNonTweeningValueOnlyAtEnd(ratio, data) {
  return data.set(data.t, data.p, ratio !== 1 ? data.b : data.e, data);
},
    _setterCSSStyle = function _setterCSSStyle(target, property, value) {
  return target.style[property] = value;
},
    _setterCSSProp = function _setterCSSProp(target, property, value) {
  return target.style.setProperty(property, value);
},
    _setterTransform = function _setterTransform(target, property, value) {
  return target._gsap[property] = value;
},
    _setterScale = function _setterScale(target, property, value) {
  return target._gsap.scaleX = target._gsap.scaleY = value;
},
    _setterScaleWithRender = function _setterScaleWithRender(target, property, value, data, ratio) {
  var cache = target._gsap;
  cache.scaleX = cache.scaleY = value;
  cache.renderTransform(ratio, cache);
},
    _setterTransformWithRender = function _setterTransformWithRender(target, property, value, data, ratio) {
  var cache = target._gsap;
  cache[property] = value;
  cache.renderTransform(ratio, cache);
},
    _transformProp = "transform",
    _transformOriginProp = _transformProp + "Origin",
    _supports3D,
    _createElement = function _createElement(type, ns) {
  var e = CSSPlugin_doc.createElementNS ? CSSPlugin_doc.createElementNS((ns || "http://www.w3.org/1999/xhtml").replace(/^https/, "http"), type) : CSSPlugin_doc.createElement(type); //some servers swap in https for http in the namespace which can break things, making "style" inaccessible.

  return e.style ? e : CSSPlugin_doc.createElement(type); //some environments won't allow access to the element's style when created with a namespace in which case we default to the standard createElement() to work around the issue. Also note that when GSAP is embedded directly inside an SVG file, createElement() won't allow access to the style object in Firefox (see https://greensock.com/forums/topic/20215-problem-using-tweenmax-in-standalone-self-containing-svg-file-err-cannot-set-property-csstext-of-undefined/).
},
    _getComputedProperty = function _getComputedProperty(target, property, skipPrefixFallback) {
  var cs = getComputedStyle(target);
  return cs[property] || cs.getPropertyValue(property.replace(_capsExp, "-$1").toLowerCase()) || cs.getPropertyValue(property) || !skipPrefixFallback && _getComputedProperty(target, _checkPropPrefix(property) || property, 1) || ""; //css variables may not need caps swapped out for dashes and lowercase.
},
    _prefixes = "O,Moz,ms,Ms,Webkit".split(","),
    _checkPropPrefix = function _checkPropPrefix(property, element, preferPrefix) {
  var e = element || _tempDiv,
      s = e.style,
      i = 5;

  if (property in s && !preferPrefix) {
    return property;
  }

  property = property.charAt(0).toUpperCase() + property.substr(1);

  while (i-- && !(_prefixes[i] + property in s)) {}

  return i < 0 ? null : (i === 3 ? "ms" : i >= 0 ? _prefixes[i] : "") + property;
},
    _initCore = function _initCore() {
  if (CSSPlugin_windowExists()) {
    CSSPlugin_win = window;
    CSSPlugin_doc = CSSPlugin_win.document;
    _docElement = CSSPlugin_doc.documentElement;
    _tempDiv = _createElement("div") || {
      style: {}
    };
    _tempDivStyler = _createElement("div");
    _transformProp = _checkPropPrefix(_transformProp);
    _transformOriginProp = _checkPropPrefix(_transformOriginProp);
    _tempDiv.style.cssText = "border-width:0;line-height:0;position:absolute;padding:0"; //make sure to override certain properties that may contaminate measurements, in case the user has overreaching style sheets.

    _supports3D = !!_checkPropPrefix("perspective");
    _pluginInitted = 1;
  }
},
    _getBBoxHack = function _getBBoxHack(swapIfPossible) {
  //works around issues in some browsers (like Firefox) that don't correctly report getBBox() on SVG elements inside a <defs> element and/or <mask>. We try creating an SVG, adding it to the documentElement and toss the element in there so that it's definitely part of the rendering tree, then grab the bbox and if it works, we actually swap out the original getBBox() method for our own that does these extra steps whenever getBBox is needed. This helps ensure that performance is optimal (only do all these extra steps when absolutely necessary...most elements don't need it).
  var svg = _createElement("svg", this.ownerSVGElement && this.ownerSVGElement.getAttribute("xmlns") || "http://www.w3.org/2000/svg"),
      oldParent = this.parentNode,
      oldSibling = this.nextSibling,
      oldCSS = this.style.cssText,
      bbox;

  _docElement.appendChild(svg);

  svg.appendChild(this);
  this.style.display = "block";

  if (swapIfPossible) {
    try {
      bbox = this.getBBox();
      this._gsapBBox = this.getBBox; //store the original

      this.getBBox = _getBBoxHack;
    } catch (e) {}
  } else if (this._gsapBBox) {
    bbox = this._gsapBBox();
  }

  if (oldSibling) {
    oldParent.insertBefore(this, oldSibling);
  } else {
    oldParent.appendChild(this);
  }

  _docElement.removeChild(svg);

  this.style.cssText = oldCSS;
  return bbox;
},
    _getAttributeFallbacks = function _getAttributeFallbacks(target, attributesArray) {
  var i = attributesArray.length;

  while (i--) {
    if (target.hasAttribute(attributesArray[i])) {
      return target.getAttribute(attributesArray[i]);
    }
  }
},
    _getBBox = function _getBBox(target) {
  var bounds;

  try {
    bounds = target.getBBox(); //Firefox throws errors if you try calling getBBox() on an SVG element that's not rendered (like in a <symbol> or <defs>). https://bugzilla.mozilla.org/show_bug.cgi?id=612118
  } catch (error) {
    bounds = _getBBoxHack.call(target, true);
  } //some browsers (like Firefox) misreport the bounds if the element has zero width and height (it just assumes it's at x:0, y:0), thus we need to manually grab the position in that case.


  return bounds && !bounds.width && !bounds.x && !bounds.y ? {
    x: +_getAttributeFallbacks(target, ["x", "cx", "x1"]) || 0,
    y: +_getAttributeFallbacks(target, ["y", "cy", "y1"]) || 0,
    width: 0,
    height: 0
  } : bounds;
},
    _isSVG = function _isSVG(e) {
  return !!(e.getCTM && (!e.parentNode || e.ownerSVGElement) && _getBBox(e));
},
    //reports if the element is an SVG on which getBBox() actually works
_removeProperty = function _removeProperty(target, property) {
  if (property) {
    var style = target.style;

    if (property in _transformProps) {
      property = _transformProp;
    }

    if (style.removeProperty) {
      if (property.substr(0, 2) === "ms" || property.substr(0, 6) === "webkit") {
        //Microsoft and some Webkit browsers don't conform to the standard of capitalizing the first prefix character, so we adjust so that when we prefix the caps with a dash, it's correct (otherwise it'd be "ms-transform" instead of "-ms-transform" for IE9, for example)
        property = "-" + property;
      }

      style.removeProperty(property.replace(_capsExp, "-$1").toLowerCase());
    } else {
      //note: old versions of IE use "removeAttribute()" instead of "removeProperty()"
      style.removeAttribute(property);
    }
  }
},
    CSSPlugin_addNonTweeningPT = function _addNonTweeningPT(plugin, target, property, beginning, end, onlySetAtEnd) {
  var pt = new PropTween(plugin._pt, target, property, 0, 1, onlySetAtEnd ? _renderNonTweeningValueOnlyAtEnd : _renderNonTweeningValue);
  plugin._pt = pt;
  pt.b = beginning;
  pt.e = end;

  plugin._props.push(property);

  return pt;
},
    _nonConvertibleUnits = {
  deg: 1,
  rad: 1,
  turn: 1
},
    //takes a single value like 20px and converts it to the unit specified, like "%", returning only the numeric amount.
CSSPlugin_convertToUnit = function _convertToUnit(target, property, value, unit) {
  var curValue = parseFloat(value) || 0,
      curUnit = (value + "").trim().substr((curValue + "").length) || "px",
      // some browsers leave extra whitespace at the beginning of CSS variables, hence the need to trim()
  style = _tempDiv.style,
      horizontal = _horizontalExp.test(property),
      isRootSVG = target.tagName.toLowerCase() === "svg",
      measureProperty = (isRootSVG ? "client" : "offset") + (horizontal ? "Width" : "Height"),
      amount = 100,
      toPixels = unit === "px",
      px,
      parent,
      cache,
      isSVG;

  if (unit === curUnit || !curValue || _nonConvertibleUnits[unit] || _nonConvertibleUnits[curUnit]) {
    return curValue;
  }

  isSVG = target.getCTM && _isSVG(target);

  if (unit === "%" && (_transformProps[property] || ~property.indexOf("adius"))) {
    //transforms and borderRadius are relative to the size of the element itself!
    return _round(curValue / (isSVG ? target.getBBox()[horizontal ? "width" : "height"] : target[measureProperty]) * amount);
  }

  style[horizontal ? "width" : "height"] = amount + (toPixels ? curUnit : unit);
  parent = ~property.indexOf("adius") || unit === "em" && target.appendChild && !isRootSVG ? target : target.parentNode;

  if (isSVG) {
    parent = (target.ownerSVGElement || {}).parentNode;
  }

  if (!parent || parent === CSSPlugin_doc || !parent.appendChild) {
    parent = CSSPlugin_doc.body;
  }

  cache = parent._gsap;

  if (cache && unit === "%" && cache.width && horizontal && cache.time === _ticker.time) {
    return _round(curValue / cache.width * amount);
  } else {
    parent === target && (style.position = "static"); // like for borderRadius, if it's a % we must have it relative to the target itself but that may not have position: relative or position: absolute in which case it'd go up the chain until it finds its offsetParent (bad). position: static protects against that.

    parent.appendChild(_tempDiv);
    px = _tempDiv[measureProperty];
    parent.removeChild(_tempDiv);
    style.position = "absolute";

    if (horizontal && unit === "%") {
      cache = _getCache(parent);
      cache.time = _ticker.time;
      cache.width = parent[measureProperty];
    }
  }

  return _round(toPixels ? px * curValue / amount : amount / px * curValue);
},
    CSSPlugin_get = function _get(target, property, unit, uncache) {
  var value;

  if (!_pluginInitted) {
    _initCore();
  }

  if (property in _propertyAliases && property !== "transform") {
    property = _propertyAliases[property];

    if (~property.indexOf(",")) {
      property = property.split(",")[0];
    }
  }

  if (_transformProps[property] && property !== "transform") {
    value = CSSPlugin_parseTransform(target, uncache);
    value = property !== "transformOrigin" ? value[property] : _firstTwoOnly(_getComputedProperty(target, _transformOriginProp)) + " " + value.zOrigin + "px";
  } else {
    value = target.style[property];

    if (!value || value === "auto" || uncache || ~(value + "").indexOf("calc(")) {
      value = _specialProps[property] && _specialProps[property](target, property, unit) || _getComputedProperty(target, property) || _getProperty(target, property) || (property === "opacity" ? 1 : 0); // note: some browsers, like Firefox, don't report borderRadius correctly! Instead, it only reports every corner like  borderTopLeftRadius
    }
  }

  return unit && !~(value + "").indexOf(" ") ? CSSPlugin_convertToUnit(target, property, value, unit) + unit : value;
},
    CSSPlugin_tweenComplexCSSString = function _tweenComplexCSSString(target, prop, start, end) {
  //note: we call _tweenComplexCSSString.call(pluginInstance...) to ensure that it's scoped properly. We may call it from within a plugin too, thus "this" would refer to the plugin.
  if (!start || start === "none") {
    // some browsers like Safari actually PREFER the prefixed property and mis-report the unprefixed value like clipPath (BUG). In other words, even though clipPath exists in the style ("clipPath" in target.style) and it's set in the CSS properly (along with -webkit-clip-path), Safari reports clipPath as "none" whereas WebkitClipPath reports accurately like "ellipse(100% 0% at 50% 0%)", so in this case we must SWITCH to using the prefixed property instead. See https://greensock.com/forums/topic/18310-clippath-doesnt-work-on-ios/
    var p = _checkPropPrefix(prop, target, 1),
        s = p && _getComputedProperty(target, p, 1);

    if (s && s !== start) {
      prop = p;
      start = s;
    }
  }

  var pt = new PropTween(this._pt, target.style, prop, 0, 1, _renderComplexString),
      index = 0,
      matchIndex = 0,
      a,
      result,
      startValues,
      startNum,
      color,
      startValue,
      endValue,
      endNum,
      chunk,
      endUnit,
      startUnit,
      relative,
      endValues;
  pt.b = start;
  pt.e = end;
  start += ""; //ensure values are strings

  end += "";

  if (end === "auto") {
    target.style[prop] = end;
    end = _getComputedProperty(target, prop) || end;
    target.style[prop] = start;
  }

  a = [start, end];

  _colorStringFilter(a); //pass an array with the starting and ending values and let the filter do whatever it needs to the values. If colors are found, it returns true and then we must match where the color shows up order-wise because for things like boxShadow, sometimes the browser provides the computed values with the color FIRST, but the user provides it with the color LAST, so flip them if necessary. Same for drop-shadow().


  start = a[0];
  end = a[1];
  startValues = start.match(_numWithUnitExp) || [];
  endValues = end.match(_numWithUnitExp) || [];

  if (endValues.length) {
    while (result = _numWithUnitExp.exec(end)) {
      endValue = result[0];
      chunk = end.substring(index, result.index);

      if (color) {
        color = (color + 1) % 5;
      } else if (chunk.substr(-5) === "rgba(" || chunk.substr(-5) === "hsla(") {
        color = 1;
      }

      if (endValue !== (startValue = startValues[matchIndex++] || "")) {
        startNum = parseFloat(startValue) || 0;
        startUnit = startValue.substr((startNum + "").length);
        relative = endValue.charAt(1) === "=" ? +(endValue.charAt(0) + "1") : 0;

        if (relative) {
          endValue = endValue.substr(2);
        }

        endNum = parseFloat(endValue);
        endUnit = endValue.substr((endNum + "").length);
        index = _numWithUnitExp.lastIndex - endUnit.length;

        if (!endUnit) {
          //if something like "perspective:300" is passed in and we must add a unit to the end
          endUnit = endUnit || _config.units[prop] || startUnit;

          if (index === end.length) {
            end += endUnit;
            pt.e += endUnit;
          }
        }

        if (startUnit !== endUnit) {
          startNum = CSSPlugin_convertToUnit(target, prop, startValue, endUnit) || 0;
        } //these nested PropTweens are handled in a special way - we'll never actually call a render or setter method on them. We'll just loop through them in the parent complex string PropTween's render method.


        pt._pt = {
          _next: pt._pt,
          p: chunk || matchIndex === 1 ? chunk : ",",
          //note: SVG spec allows omission of comma/space when a negative sign is wedged between two numbers, like 2.5-5.3 instead of 2.5,-5.3 but when tweening, the negative value may switch to positive, so we insert the comma just in case.
          s: startNum,
          c: relative ? relative * endNum : endNum - startNum,
          m: color && color < 4 ? Math.round : 0
        };
      }
    }

    pt.c = index < end.length ? end.substring(index, end.length) : ""; //we use the "c" of the PropTween to store the final part of the string (after the last number)
  } else {
    pt.r = prop === "display" && end === "none" ? _renderNonTweeningValueOnlyAtEnd : _renderNonTweeningValue;
  }

  if (_relExp.test(end)) {
    pt.e = 0; //if the end string contains relative values or dynamic random(...) values, delete the end it so that on the final render we don't actually set it to the string with += or -= characters (forces it to use the calculated value).
  }

  this._pt = pt; //start the linked list with this new PropTween. Remember, we call _tweenComplexCSSString.call(pluginInstance...) to ensure that it's scoped properly. We may call it from within another plugin too, thus "this" would refer to the plugin.

  return pt;
},
    _keywordToPercent = {
  top: "0%",
  bottom: "100%",
  left: "0%",
  right: "100%",
  center: "50%"
},
    _convertKeywordsToPercentages = function _convertKeywordsToPercentages(value) {
  var split = value.split(" "),
      x = split[0],
      y = split[1] || "50%";

  if (x === "top" || x === "bottom" || y === "left" || y === "right") {
    //the user provided them in the wrong order, so flip them
    value = x;
    x = y;
    y = value;
  }

  split[0] = _keywordToPercent[x] || x;
  split[1] = _keywordToPercent[y] || y;
  return split.join(" ");
},
    _renderClearProps = function _renderClearProps(ratio, data) {
  if (data.tween && data.tween._time === data.tween._dur) {
    var target = data.t,
        style = target.style,
        props = data.u,
        prop,
        clearTransforms,
        i;

    if (props === "all" || props === true) {
      style.cssText = "";
      clearTransforms = 1;
    } else {
      props = props.split(",");
      i = props.length;

      while (--i > -1) {
        prop = props[i];

        if (_transformProps[prop]) {
          clearTransforms = 1;
          prop = prop === "transformOrigin" ? _transformOriginProp : _transformProp;
        }

        _removeProperty(target, prop);
      }
    }

    if (clearTransforms) {
      _removeProperty(target, _transformProp);

      clearTransforms = target._gsap;

      if (clearTransforms) {
        if (clearTransforms.svg) {
          target.removeAttribute("transform");
        }

        CSSPlugin_parseTransform(target, 1); // force all the cached values back to "normal"/identity, otherwise if there's another tween that's already set to render transforms on this element, it could display the wrong values.

      }
    }
  }
},
    // note: specialProps should return 1 if (and only if) they have a non-zero priority. It indicates we need to sort the linked list.
_specialProps = {
  clearProps: function clearProps(plugin, target, property, endValue, tween) {
    if (tween.data !== "isFromStart") {
      var pt = plugin._pt = new PropTween(plugin._pt, target, property, 0, 0, _renderClearProps);
      pt.u = endValue;
      pt.pr = -10;
      pt.tween = tween;

      plugin._props.push(property);

      return 1;
    }
  }
  /* className feature (about 0.4kb gzipped).
  , className(plugin, target, property, endValue, tween) {
  	let _renderClassName = (ratio, data) => {
  			data.css.render(ratio, data.css);
  			if (!ratio || ratio === 1) {
  				let inline = data.rmv,
  					target = data.t,
  					p;
  				target.setAttribute("class", ratio ? data.e : data.b);
  				for (p in inline) {
  					_removeProperty(target, p);
  				}
  			}
  		},
  		_getAllStyles = (target) => {
  			let styles = {},
  				computed = getComputedStyle(target),
  				p;
  			for (p in computed) {
  				if (isNaN(p) && p !== "cssText" && p !== "length") {
  					styles[p] = computed[p];
  				}
  			}
  			_setDefaults(styles, _parseTransform(target, 1));
  			return styles;
  		},
  		startClassList = target.getAttribute("class"),
  		style = target.style,
  		cssText = style.cssText,
  		cache = target._gsap,
  		classPT = cache.classPT,
  		inlineToRemoveAtEnd = {},
  		data = {t:target, plugin:plugin, rmv:inlineToRemoveAtEnd, b:startClassList, e:(endValue.charAt(1) !== "=") ? endValue : startClassList.replace(new RegExp("(?:\\s|^)" + endValue.substr(2) + "(?![\\w-])"), "") + ((endValue.charAt(0) === "+") ? " " + endValue.substr(2) : "")},
  		changingVars = {},
  		startVars = _getAllStyles(target),
  		transformRelated = /(transform|perspective)/i,
  		endVars, p;
  	if (classPT) {
  		classPT.r(1, classPT.d);
  		_removeLinkedListItem(classPT.d.plugin, classPT, "_pt");
  	}
  	target.setAttribute("class", data.e);
  	endVars = _getAllStyles(target, true);
  	target.setAttribute("class", startClassList);
  	for (p in endVars) {
  		if (endVars[p] !== startVars[p] && !transformRelated.test(p)) {
  			changingVars[p] = endVars[p];
  			if (!style[p] && style[p] !== "0") {
  				inlineToRemoveAtEnd[p] = 1;
  			}
  		}
  	}
  	cache.classPT = plugin._pt = new PropTween(plugin._pt, target, "className", 0, 0, _renderClassName, data, 0, -11);
  	if (style.cssText !== cssText) { //only apply if things change. Otherwise, in cases like a background-image that's pulled dynamically, it could cause a refresh. See https://greensock.com/forums/topic/20368-possible-gsap-bug-switching-classnames-in-chrome/.
  		style.cssText = cssText; //we recorded cssText before we swapped classes and ran _getAllStyles() because in cases when a className tween is overwritten, we remove all the related tweening properties from that class change (otherwise class-specific stuff can't override properties we've directly set on the target's style object due to specificity).
  	}
  	_parseTransform(target, true); //to clear the caching of transforms
  	data.css = new gsap.plugins.css();
  	data.css.init(target, changingVars, tween);
  	plugin._props.push(...data.css._props);
  	return 1;
  }
  */

},

/*
 * --------------------------------------------------------------------------------------
 * TRANSFORMS
 * --------------------------------------------------------------------------------------
 */
_identity2DMatrix = [1, 0, 0, 1, 0, 0],
    _rotationalProperties = {},
    _isNullTransform = function _isNullTransform(value) {
  return value === "matrix(1, 0, 0, 1, 0, 0)" || value === "none" || !value;
},
    CSSPlugin_getComputedTransformMatrixAsArray = function _getComputedTransformMatrixAsArray(target) {
  var matrixString = _getComputedProperty(target, _transformProp);

  return _isNullTransform(matrixString) ? _identity2DMatrix : matrixString.substr(7).match(_numExp).map(_round);
},
    _getMatrix = function _getMatrix(target, force2D) {
  var cache = target._gsap,
      style = target.style,
      matrix = CSSPlugin_getComputedTransformMatrixAsArray(target),
      parent,
      nextSibling,
      temp,
      addedToDOM;

  if (cache.svg && target.getAttribute("transform")) {
    temp = target.transform.baseVal.consolidate().matrix; //ensures that even complex values like "translate(50,60) rotate(135,0,0)" are parsed because it mashes it into a matrix.

    matrix = [temp.a, temp.b, temp.c, temp.d, temp.e, temp.f];
    return matrix.join(",") === "1,0,0,1,0,0" ? _identity2DMatrix : matrix;
  } else if (matrix === _identity2DMatrix && !target.offsetParent && target !== _docElement && !cache.svg) {
    //note: if offsetParent is null, that means the element isn't in the normal document flow, like if it has display:none or one of its ancestors has display:none). Firefox returns null for getComputedStyle() if the element is in an iframe that has display:none. https://bugzilla.mozilla.org/show_bug.cgi?id=548397
    //browsers don't report transforms accurately unless the element is in the DOM and has a display value that's not "none". Firefox and Microsoft browsers have a partial bug where they'll report transforms even if display:none BUT not any percentage-based values like translate(-50%, 8px) will be reported as if it's translate(0, 8px).
    temp = style.display;
    style.display = "block";
    parent = target.parentNode;

    if (!parent || !target.offsetParent) {
      addedToDOM = 1; //flag

      nextSibling = target.nextSibling;

      _docElement.appendChild(target); //we must add it to the DOM in order to get values properly

    }

    matrix = CSSPlugin_getComputedTransformMatrixAsArray(target);

    if (temp) {
      style.display = temp;
    } else {
      _removeProperty(target, "display");
    }

    if (addedToDOM) {
      if (nextSibling) {
        parent.insertBefore(target, nextSibling);
      } else if (parent) {
        parent.appendChild(target);
      } else {
        _docElement.removeChild(target);
      }
    }
  }

  return force2D && matrix.length > 6 ? [matrix[0], matrix[1], matrix[4], matrix[5], matrix[12], matrix[13]] : matrix;
},
    _applySVGOrigin = function _applySVGOrigin(target, origin, originIsAbsolute, smooth, matrixArray, pluginToAddPropTweensTo) {
  var cache = target._gsap,
      matrix = matrixArray || _getMatrix(target, true),
      xOriginOld = cache.xOrigin || 0,
      yOriginOld = cache.yOrigin || 0,
      xOffsetOld = cache.xOffset || 0,
      yOffsetOld = cache.yOffset || 0,
      a = matrix[0],
      b = matrix[1],
      c = matrix[2],
      d = matrix[3],
      tx = matrix[4],
      ty = matrix[5],
      originSplit = origin.split(" "),
      xOrigin = parseFloat(originSplit[0]) || 0,
      yOrigin = parseFloat(originSplit[1]) || 0,
      bounds,
      determinant,
      x,
      y;

  if (!originIsAbsolute) {
    bounds = _getBBox(target);
    xOrigin = bounds.x + (~originSplit[0].indexOf("%") ? xOrigin / 100 * bounds.width : xOrigin);
    yOrigin = bounds.y + (~(originSplit[1] || originSplit[0]).indexOf("%") ? yOrigin / 100 * bounds.height : yOrigin);
  } else if (matrix !== _identity2DMatrix && (determinant = a * d - b * c)) {
    //if it's zero (like if scaleX and scaleY are zero), skip it to avoid errors with dividing by zero.
    x = xOrigin * (d / determinant) + yOrigin * (-c / determinant) + (c * ty - d * tx) / determinant;
    y = xOrigin * (-b / determinant) + yOrigin * (a / determinant) - (a * ty - b * tx) / determinant;
    xOrigin = x;
    yOrigin = y;
  }

  if (smooth || smooth !== false && cache.smooth) {
    tx = xOrigin - xOriginOld;
    ty = yOrigin - yOriginOld;
    cache.xOffset = xOffsetOld + (tx * a + ty * c) - tx;
    cache.yOffset = yOffsetOld + (tx * b + ty * d) - ty;
  } else {
    cache.xOffset = cache.yOffset = 0;
  }

  cache.xOrigin = xOrigin;
  cache.yOrigin = yOrigin;
  cache.smooth = !!smooth;
  cache.origin = origin;
  cache.originIsAbsolute = !!originIsAbsolute;
  target.style[_transformOriginProp] = "0px 0px"; //otherwise, if someone sets  an origin via CSS, it will likely interfere with the SVG transform attribute ones (because remember, we're baking the origin into the matrix() value).

  if (pluginToAddPropTweensTo) {
    CSSPlugin_addNonTweeningPT(pluginToAddPropTweensTo, cache, "xOrigin", xOriginOld, xOrigin);

    CSSPlugin_addNonTweeningPT(pluginToAddPropTweensTo, cache, "yOrigin", yOriginOld, yOrigin);

    CSSPlugin_addNonTweeningPT(pluginToAddPropTweensTo, cache, "xOffset", xOffsetOld, cache.xOffset);

    CSSPlugin_addNonTweeningPT(pluginToAddPropTweensTo, cache, "yOffset", yOffsetOld, cache.yOffset);
  }
},
    CSSPlugin_parseTransform = function _parseTransform(target, uncache) {
  var cache = target._gsap || new GSCache(target);

  if ("x" in cache && !uncache && !cache.uncache) {
    return cache;
  }

  var style = target.style,
      invertedScaleX = cache.scaleX < 0,
      xOrigin = cache.xOrigin || 0,
      yOrigin = cache.yOrigin || 0,
      px = "px",
      deg = "deg",
      origin = _getComputedProperty(target, _transformOriginProp) || "0",
      x,
      y,
      z,
      scaleX,
      scaleY,
      rotation,
      rotationX,
      rotationY,
      skewX,
      skewY,
      perspective,
      matrix,
      angle,
      cos,
      sin,
      a,
      b,
      c,
      d,
      a12,
      a22,
      t1,
      t2,
      t3,
      a13,
      a23,
      a33,
      a42,
      a43,
      a32;
  x = y = z = rotation = rotationX = rotationY = skewX = skewY = perspective = 0;
  scaleX = scaleY = 1;
  cache.svg = !!(target.getCTM && _isSVG(target));
  matrix = _getMatrix(target, cache.svg);

  if (cache.svg) {
    _applySVGOrigin(target, origin, cache.originIsAbsolute, cache.smooth !== false, matrix);
  }

  if (matrix !== _identity2DMatrix) {
    a = matrix[0]; //a11

    b = matrix[1]; //a21

    c = matrix[2]; //a31

    d = matrix[3]; //a41

    x = a12 = matrix[4];
    y = a22 = matrix[5]; //2D matrix

    if (matrix.length === 6) {
      scaleX = Math.sqrt(a * a + b * b);
      scaleY = Math.sqrt(d * d + c * c);
      rotation = a || b ? _atan2(b, a) * _RAD2DEG : 0; //note: if scaleX is 0, we cannot accurately measure rotation. Same for skewX with a scaleY of 0. Therefore, we default to the previously recorded value (or zero if that doesn't exist).

      skewX = c || d ? _atan2(c, d) * _RAD2DEG + rotation : 0;

      if (cache.svg) {
        x -= xOrigin - (xOrigin * a + yOrigin * c);
        y -= yOrigin - (xOrigin * b + yOrigin * d);
      } //3D matrix

    } else {
      a32 = matrix[6];
      a42 = matrix[7];
      a13 = matrix[8];
      a23 = matrix[9];
      a33 = matrix[10];
      a43 = matrix[11];
      x = matrix[12];
      y = matrix[13];
      z = matrix[14];
      angle = _atan2(a32, a33);
      rotationX = angle * _RAD2DEG; //rotationX

      if (angle) {
        cos = Math.cos(-angle);
        sin = Math.sin(-angle);
        t1 = a12 * cos + a13 * sin;
        t2 = a22 * cos + a23 * sin;
        t3 = a32 * cos + a33 * sin;
        a13 = a12 * -sin + a13 * cos;
        a23 = a22 * -sin + a23 * cos;
        a33 = a32 * -sin + a33 * cos;
        a43 = a42 * -sin + a43 * cos;
        a12 = t1;
        a22 = t2;
        a32 = t3;
      } //rotationY


      angle = _atan2(-c, a33);
      rotationY = angle * _RAD2DEG;

      if (angle) {
        cos = Math.cos(-angle);
        sin = Math.sin(-angle);
        t1 = a * cos - a13 * sin;
        t2 = b * cos - a23 * sin;
        t3 = c * cos - a33 * sin;
        a43 = d * sin + a43 * cos;
        a = t1;
        b = t2;
        c = t3;
      } //rotationZ


      angle = _atan2(b, a);
      rotation = angle * _RAD2DEG;

      if (angle) {
        cos = Math.cos(angle);
        sin = Math.sin(angle);
        t1 = a * cos + b * sin;
        t2 = a12 * cos + a22 * sin;
        b = b * cos - a * sin;
        a22 = a22 * cos - a12 * sin;
        a = t1;
        a12 = t2;
      }

      if (rotationX && Math.abs(rotationX) + Math.abs(rotation) > 359.9) {
        //when rotationY is set, it will often be parsed as 180 degrees different than it should be, and rotationX and rotation both being 180 (it looks the same), so we adjust for that here.
        rotationX = rotation = 0;
        rotationY = 180 - rotationY;
      }

      scaleX = _round(Math.sqrt(a * a + b * b + c * c));
      scaleY = _round(Math.sqrt(a22 * a22 + a32 * a32));
      angle = _atan2(a12, a22);
      skewX = Math.abs(angle) > 0.0002 ? angle * _RAD2DEG : 0;
      perspective = a43 ? 1 / (a43 < 0 ? -a43 : a43) : 0;
    }

    if (cache.svg) {
      //sense if there are CSS transforms applied on an SVG element in which case we must overwrite them when rendering. The transform attribute is more reliable cross-browser, but we can't just remove the CSS ones because they may be applied in a CSS rule somewhere (not just inline).
      matrix = target.getAttribute("transform");
      cache.forceCSS = target.setAttribute("transform", "") || !_isNullTransform(_getComputedProperty(target, _transformProp));
      matrix && target.setAttribute("transform", matrix);
    }
  }

  if (Math.abs(skewX) > 90 && Math.abs(skewX) < 270) {
    if (invertedScaleX) {
      scaleX *= -1;
      skewX += rotation <= 0 ? 180 : -180;
      rotation += rotation <= 0 ? 180 : -180;
    } else {
      scaleY *= -1;
      skewX += skewX <= 0 ? 180 : -180;
    }
  }

  cache.x = ((cache.xPercent = x && Math.round(target.offsetWidth / 2) === Math.round(-x) ? -50 : 0) ? 0 : x) + px;
  cache.y = ((cache.yPercent = y && Math.round(target.offsetHeight / 2) === Math.round(-y) ? -50 : 0) ? 0 : y) + px;
  cache.z = z + px;
  cache.scaleX = _round(scaleX);
  cache.scaleY = _round(scaleY);
  cache.rotation = _round(rotation) + deg;
  cache.rotationX = _round(rotationX) + deg;
  cache.rotationY = _round(rotationY) + deg;
  cache.skewX = skewX + deg;
  cache.skewY = skewY + deg;
  cache.transformPerspective = perspective + px;

  if (cache.zOrigin = parseFloat(origin.split(" ")[2]) || 0) {
    style[_transformOriginProp] = _firstTwoOnly(origin);
  }

  cache.xOffset = cache.yOffset = 0;
  cache.force3D = _config.force3D;
  cache.renderTransform = cache.svg ? CSSPlugin_renderSVGTransforms : _supports3D ? _renderCSSTransforms : _renderNon3DTransforms;
  cache.uncache = 0;
  return cache;
},
    _firstTwoOnly = function _firstTwoOnly(value) {
  return (value = value.split(" "))[0] + " " + value[1];
},
    //for handling transformOrigin values, stripping out the 3rd dimension
CSSPlugin_addPxTranslate = function _addPxTranslate(target, start, value) {
  var unit = getUnit(start);
  return _round(parseFloat(start) + parseFloat(CSSPlugin_convertToUnit(target, "x", value + "px", unit))) + unit;
},
    _renderNon3DTransforms = function _renderNon3DTransforms(ratio, cache) {
  cache.z = "0px";
  cache.rotationY = cache.rotationX = "0deg";
  cache.force3D = 0;

  _renderCSSTransforms(ratio, cache);
},
    _zeroDeg = "0deg",
    _zeroPx = "0px",
    _endParenthesis = ") ",
    _renderCSSTransforms = function _renderCSSTransforms(ratio, cache) {
  var _ref = cache || this,
      xPercent = _ref.xPercent,
      yPercent = _ref.yPercent,
      x = _ref.x,
      y = _ref.y,
      z = _ref.z,
      rotation = _ref.rotation,
      rotationY = _ref.rotationY,
      rotationX = _ref.rotationX,
      skewX = _ref.skewX,
      skewY = _ref.skewY,
      scaleX = _ref.scaleX,
      scaleY = _ref.scaleY,
      transformPerspective = _ref.transformPerspective,
      force3D = _ref.force3D,
      target = _ref.target,
      zOrigin = _ref.zOrigin,
      transforms = "",
      use3D = force3D === "auto" && ratio && ratio !== 1 || force3D === true; // Safari has a bug that causes it not to render 3D transform-origin values properly, so we force the z origin to 0, record it in the cache, and then do the math here to offset the translate values accordingly (basically do the 3D transform-origin part manually)


  if (zOrigin && (rotationX !== _zeroDeg || rotationY !== _zeroDeg)) {
    var angle = parseFloat(rotationY) * _DEG2RAD,
        a13 = Math.sin(angle),
        a33 = Math.cos(angle),
        cos;

    angle = parseFloat(rotationX) * _DEG2RAD;
    cos = Math.cos(angle);
    x = CSSPlugin_addPxTranslate(target, x, a13 * cos * -zOrigin);
    y = CSSPlugin_addPxTranslate(target, y, -Math.sin(angle) * -zOrigin);
    z = CSSPlugin_addPxTranslate(target, z, a33 * cos * -zOrigin + zOrigin);
  }

  if (transformPerspective !== _zeroPx) {
    transforms += "perspective(" + transformPerspective + _endParenthesis;
  }

  if (xPercent || yPercent) {
    transforms += "translate(" + xPercent + "%, " + yPercent + "%) ";
  }

  if (use3D || x !== _zeroPx || y !== _zeroPx || z !== _zeroPx) {
    transforms += z !== _zeroPx || use3D ? "translate3d(" + x + ", " + y + ", " + z + ") " : "translate(" + x + ", " + y + _endParenthesis;
  }

  if (rotation !== _zeroDeg) {
    transforms += "rotate(" + rotation + _endParenthesis;
  }

  if (rotationY !== _zeroDeg) {
    transforms += "rotateY(" + rotationY + _endParenthesis;
  }

  if (rotationX !== _zeroDeg) {
    transforms += "rotateX(" + rotationX + _endParenthesis;
  }

  if (skewX !== _zeroDeg || skewY !== _zeroDeg) {
    transforms += "skew(" + skewX + ", " + skewY + _endParenthesis;
  }

  if (scaleX !== 1 || scaleY !== 1) {
    transforms += "scale(" + scaleX + ", " + scaleY + _endParenthesis;
  }

  target.style[_transformProp] = transforms || "translate(0, 0)";
},
    CSSPlugin_renderSVGTransforms = function _renderSVGTransforms(ratio, cache) {
  var _ref2 = cache || this,
      xPercent = _ref2.xPercent,
      yPercent = _ref2.yPercent,
      x = _ref2.x,
      y = _ref2.y,
      rotation = _ref2.rotation,
      skewX = _ref2.skewX,
      skewY = _ref2.skewY,
      scaleX = _ref2.scaleX,
      scaleY = _ref2.scaleY,
      target = _ref2.target,
      xOrigin = _ref2.xOrigin,
      yOrigin = _ref2.yOrigin,
      xOffset = _ref2.xOffset,
      yOffset = _ref2.yOffset,
      forceCSS = _ref2.forceCSS,
      tx = parseFloat(x),
      ty = parseFloat(y),
      a11,
      a21,
      a12,
      a22,
      temp;

  rotation = parseFloat(rotation);
  skewX = parseFloat(skewX);
  skewY = parseFloat(skewY);

  if (skewY) {
    //for performance reasons, we combine all skewing into the skewX and rotation values. Remember, a skewY of 10 degrees looks the same as a rotation of 10 degrees plus a skewX of 10 degrees.
    skewY = parseFloat(skewY);
    skewX += skewY;
    rotation += skewY;
  }

  if (rotation || skewX) {
    rotation *= _DEG2RAD;
    skewX *= _DEG2RAD;
    a11 = Math.cos(rotation) * scaleX;
    a21 = Math.sin(rotation) * scaleX;
    a12 = Math.sin(rotation - skewX) * -scaleY;
    a22 = Math.cos(rotation - skewX) * scaleY;

    if (skewX) {
      skewY *= _DEG2RAD;
      temp = Math.tan(skewX - skewY);
      temp = Math.sqrt(1 + temp * temp);
      a12 *= temp;
      a22 *= temp;

      if (skewY) {
        temp = Math.tan(skewY);
        temp = Math.sqrt(1 + temp * temp);
        a11 *= temp;
        a21 *= temp;
      }
    }

    a11 = _round(a11);
    a21 = _round(a21);
    a12 = _round(a12);
    a22 = _round(a22);
  } else {
    a11 = scaleX;
    a22 = scaleY;
    a21 = a12 = 0;
  }

  if (tx && !~(x + "").indexOf("px") || ty && !~(y + "").indexOf("px")) {
    tx = CSSPlugin_convertToUnit(target, "x", x, "px");
    ty = CSSPlugin_convertToUnit(target, "y", y, "px");
  }

  if (xOrigin || yOrigin || xOffset || yOffset) {
    tx = _round(tx + xOrigin - (xOrigin * a11 + yOrigin * a12) + xOffset);
    ty = _round(ty + yOrigin - (xOrigin * a21 + yOrigin * a22) + yOffset);
  }

  if (xPercent || yPercent) {
    //The SVG spec doesn't support percentage-based translation in the "transform" attribute, so we merge it into the translation to simulate it.
    temp = target.getBBox();
    tx = _round(tx + xPercent / 100 * temp.width);
    ty = _round(ty + yPercent / 100 * temp.height);
  }

  temp = "matrix(" + a11 + "," + a21 + "," + a12 + "," + a22 + "," + tx + "," + ty + ")";
  target.setAttribute("transform", temp);

  if (forceCSS) {
    //some browsers prioritize CSS transforms over the transform attribute. When we sense that the user has CSS transforms applied, we must overwrite them this way (otherwise some browser simply won't render the  transform attribute changes!)
    target.style[_transformProp] = temp;
  }
},
    CSSPlugin_addRotationalPropTween = function _addRotationalPropTween(plugin, target, property, startNum, endValue, relative) {
  var cap = 360,
      isString = _isString(endValue),
      endNum = parseFloat(endValue) * (isString && ~endValue.indexOf("rad") ? _RAD2DEG : 1),
      change = relative ? endNum * relative : endNum - startNum,
      finalValue = startNum + change + "deg",
      direction,
      pt;

  if (isString) {
    direction = endValue.split("_")[1];

    if (direction === "short") {
      change %= cap;

      if (change !== change % (cap / 2)) {
        change += change < 0 ? cap : -cap;
      }
    }

    if (direction === "cw" && change < 0) {
      change = (change + cap * CSSPlugin_bigNum) % cap - ~~(change / cap) * cap;
    } else if (direction === "ccw" && change > 0) {
      change = (change - cap * CSSPlugin_bigNum) % cap - ~~(change / cap) * cap;
    }
  }

  plugin._pt = pt = new PropTween(plugin._pt, target, property, startNum, change, _renderPropWithEnd);
  pt.e = finalValue;
  pt.u = "deg";

  plugin._props.push(property);

  return pt;
},
    CSSPlugin_addRawTransformPTs = function _addRawTransformPTs(plugin, transforms, target) {
  //for handling cases where someone passes in a whole transform string, like transform: "scale(2, 3) rotate(20deg) translateY(30em)"
  var style = _tempDivStyler.style,
      startCache = target._gsap,
      exclude = "perspective,force3D,transformOrigin,svgOrigin",
      endCache,
      p,
      startValue,
      endValue,
      startNum,
      endNum,
      startUnit,
      endUnit;
  style.cssText = getComputedStyle(target).cssText + ";position:absolute;display:block;"; //%-based translations will fail unless we set the width/height to match the original target (and padding/borders can affect it)

  style[_transformProp] = transforms;

  CSSPlugin_doc.body.appendChild(_tempDivStyler);

  endCache = CSSPlugin_parseTransform(_tempDivStyler, 1);

  for (p in _transformProps) {
    startValue = startCache[p];
    endValue = endCache[p];

    if (startValue !== endValue && exclude.indexOf(p) < 0) {
      //tweening to no perspective gives very unintuitive results - just keep the same perspective in that case.
      startUnit = getUnit(startValue);
      endUnit = getUnit(endValue);
      startNum = startUnit !== endUnit ? CSSPlugin_convertToUnit(target, p, startValue, endUnit) : parseFloat(startValue);
      endNum = parseFloat(endValue);
      plugin._pt = new PropTween(plugin._pt, startCache, p, startNum, endNum - startNum, _renderCSSProp);
      plugin._pt.u = endUnit || 0;

      plugin._props.push(p);
    }
  }

  CSSPlugin_doc.body.removeChild(_tempDivStyler);
}; // handle splitting apart padding, margin, borderWidth, and borderRadius into their 4 components. Firefox, for example, won't report borderRadius correctly - it will only do borderTopLeftRadius and the other corners. We also want to handle paddingTop, marginLeft, borderRightWidth, etc.


_forEachName("padding,margin,Width,Radius", function (name, index) {
  var t = "Top",
      r = "Right",
      b = "Bottom",
      l = "Left",
      props = (index < 3 ? [t, r, b, l] : [t + l, t + r, b + r, b + l]).map(function (side) {
    return index < 2 ? name + side : "border" + side + name;
  });

  _specialProps[index > 1 ? "border" + name : name] = function (plugin, target, property, endValue, tween) {
    var a, vars;

    if (arguments.length < 4) {
      // getter, passed target, property, and unit (from _get())
      a = props.map(function (prop) {
        return CSSPlugin_get(plugin, prop, property);
      });
      vars = a.join(" ");
      return vars.split(a[0]).length === 5 ? a[0] : vars;
    }

    a = (endValue + "").split(" ");
    vars = {};
    props.forEach(function (prop, i) {
      return vars[prop] = a[i] = a[i] || a[(i - 1) / 2 | 0];
    });
    plugin.init(target, vars, tween);
  };
});

var CSSPlugin = {
  name: "css",
  register: _initCore,
  targetTest: function targetTest(target) {
    return target.style && target.nodeType;
  },
  init: function init(target, vars, tween, index, targets) {
    var props = this._props,
        style = target.style,
        startValue,
        endValue,
        endNum,
        startNum,
        type,
        specialProp,
        p,
        startUnit,
        endUnit,
        relative,
        isTransformRelated,
        transformPropTween,
        cache,
        smooth,
        hasPriority;

    if (!_pluginInitted) {
      _initCore();
    }

    for (p in vars) {
      if (p === "autoRound") {
        continue;
      }

      endValue = vars[p];

      if (_plugins[p] && _checkPlugin(p, vars, tween, index, target, targets)) {
        //plugins
        continue;
      }

      type = typeof endValue;
      specialProp = _specialProps[p];

      if (type === "function") {
        endValue = endValue.call(tween, index, target, targets);
        type = typeof endValue;
      }

      if (type === "string" && ~endValue.indexOf("random(")) {
        endValue = _replaceRandom(endValue);
      }

      if (specialProp) {
        if (specialProp(this, target, p, endValue, tween)) {
          hasPriority = 1;
        }
      } else if (p.substr(0, 2) === "--") {
        //CSS variable
        this.add(style, "setProperty", getComputedStyle(target).getPropertyValue(p) + "", endValue + "", index, targets, 0, 0, p);
      } else {
        startValue = CSSPlugin_get(target, p);
        startNum = parseFloat(startValue);
        relative = type === "string" && endValue.charAt(1) === "=" ? +(endValue.charAt(0) + "1") : 0;

        if (relative) {
          endValue = endValue.substr(2);
        }

        endNum = parseFloat(endValue);

        if (p in _propertyAliases) {
          if (p === "autoAlpha") {
            //special case where we control the visibility along with opacity. We still allow the opacity value to pass through and get tweened.
            if (startNum === 1 && CSSPlugin_get(target, "visibility") === "hidden" && endNum) {
              //if visibility is initially set to "hidden", we should interpret that as intent to make opacity 0 (a convenience)
              startNum = 0;
            }

            CSSPlugin_addNonTweeningPT(this, style, "visibility", startNum ? "inherit" : "hidden", endNum ? "inherit" : "hidden", !endNum);
          }

          if (p !== "scale" && p !== "transform") {
            p = _propertyAliases[p];

            if (~p.indexOf(",")) {
              p = p.split(",")[0];
            }
          }
        }

        isTransformRelated = p in _transformProps; //--- TRANSFORM-RELATED ---

        if (isTransformRelated) {
          if (!transformPropTween) {
            cache = target._gsap;
            cache.renderTransform || CSSPlugin_parseTransform(target); // if, for example, gsap.set(... {transform:"translateX(50vw)"}), the _get() call doesn't parse the transform, thus cache.renderTransform won't be set yet so force the parsing of the transform here.

            smooth = vars.smoothOrigin !== false && cache.smooth;
            transformPropTween = this._pt = new PropTween(this._pt, style, _transformProp, 0, 1, cache.renderTransform, cache, 0, -1); //the first time through, create the rendering PropTween so that it runs LAST (in the linked list, we keep adding to the beginning)

            transformPropTween.dep = 1; //flag it as dependent so that if things get killed/overwritten and this is the only PropTween left, we can safely kill the whole tween.
          }

          if (p === "scale") {
            this._pt = new PropTween(this._pt, cache, "scaleY", cache.scaleY, relative ? relative * endNum : endNum - cache.scaleY);
            props.push("scaleY", p);
            p += "X";
          } else if (p === "transformOrigin") {
            endValue = _convertKeywordsToPercentages(endValue); //in case something like "left top" or "bottom right" is passed in. Convert to percentages.

            if (cache.svg) {
              _applySVGOrigin(target, endValue, 0, smooth, 0, this);
            } else {
              endUnit = parseFloat(endValue.split(" ")[2]); //handle the zOrigin separately!

              if (endUnit !== cache.zOrigin) {
                CSSPlugin_addNonTweeningPT(this, cache, "zOrigin", cache.zOrigin, endUnit);
              }

              CSSPlugin_addNonTweeningPT(this, style, p, _firstTwoOnly(startValue), _firstTwoOnly(endValue));
            }

            continue;
          } else if (p === "svgOrigin") {
            _applySVGOrigin(target, endValue, 1, smooth, 0, this);

            continue;
          } else if (p in _rotationalProperties) {
            CSSPlugin_addRotationalPropTween(this, cache, p, startNum, endValue, relative);

            continue;
          } else if (p === "smoothOrigin") {
            CSSPlugin_addNonTweeningPT(this, cache, "smooth", cache.smooth, endValue);

            continue;
          } else if (p === "force3D") {
            cache[p] = endValue;
            continue;
          } else if (p === "transform") {
            CSSPlugin_addRawTransformPTs(this, endValue, target);

            continue;
          }
        } else if (!(p in style)) {
          p = _checkPropPrefix(p) || p;
        }

        if (isTransformRelated || (endNum || endNum === 0) && (startNum || startNum === 0) && !_complexExp.test(endValue) && p in style) {
          startUnit = (startValue + "").substr((startNum + "").length);
          endUnit = (endValue + "").substr((endNum + "").length) || (p in _config.units ? _config.units[p] : startUnit);

          if (startUnit !== endUnit) {
            startNum = CSSPlugin_convertToUnit(target, p, startValue, endUnit);
          }

          this._pt = new PropTween(this._pt, isTransformRelated ? cache : style, p, startNum, relative ? relative * endNum : endNum - startNum, endUnit === "px" && vars.autoRound !== false && !isTransformRelated ? _renderRoundedCSSProp : _renderCSSProp);
          this._pt.u = endUnit || 0;

          if (startUnit !== endUnit) {
            //when the tween goes all the way back to the beginning, we need to revert it to the OLD/ORIGINAL value (with those units). We record that as a "b" (beginning) property and point to a render method that handles that. (performance optimization)
            this._pt.b = startValue;
            this._pt.r = _renderCSSPropWithBeginning;
          }
        } else if (!(p in style)) {
          if (p in target) {
            //maybe it's not a style - it could be a property added directly to an element in which case we'll try to animate that.
            this.add(target, p, target[p], endValue, index, targets);
          } else {
            _missingPlugin(p, endValue);

            continue;
          }
        } else {
          CSSPlugin_tweenComplexCSSString.call(this, target, p, startValue, endValue);
        }

        props.push(p);
      }
    }

    if (hasPriority) {
      _sortPropTweensByPriority(this);
    }
  },
  get: CSSPlugin_get,
  aliases: _propertyAliases,
  getSetter: function getSetter(target, property, plugin) {
    //returns a setter function that accepts target, property, value and applies it accordingly. Remember, properties like "x" aren't as simple as target.style.property = value because they've got to be applied to a proxy object and then merged into a transform string in a renderer.
    var p = _propertyAliases[property];
    p && p.indexOf(",") < 0 && (property = p);
    return property in _transformProps && property !== _transformOriginProp && (target._gsap.x || CSSPlugin_get(target, "x")) ? plugin && _recentSetterPlugin === plugin ? property === "scale" ? _setterScale : _setterTransform : (_recentSetterPlugin = plugin || {}) && (property === "scale" ? _setterScaleWithRender : _setterTransformWithRender) : target.style && !_isUndefined(target.style[property]) ? _setterCSSStyle : ~property.indexOf("-") ? _setterCSSProp : _getSetter(target, property);
  }
};
gsap.utils.checkPrefix = _checkPropPrefix;

(function (positionAndScale, rotation, others, aliases) {
  var all = _forEachName(positionAndScale + "," + rotation + "," + others, function (name) {
    _transformProps[name] = 1;
  });

  _forEachName(rotation, function (name) {
    _config.units[name] = "deg";
    _rotationalProperties[name] = 1;
  });

  _propertyAliases[all[13]] = positionAndScale + "," + rotation;

  _forEachName(aliases, function (name) {
    var split = name.split(":");
    _propertyAliases[split[1]] = all[split[0]];
  });
})("x,y,z,scale,scaleX,scaleY,xPercent,yPercent", "rotation,rotationX,rotationY,skewX,skewY", "transform,transformOrigin,svgOrigin,force3D,smoothOrigin,transformPerspective", "0:translateX,1:translateY,2:translateZ,8:rotate,8:rotationZ,8:rotateZ,9:rotateX,10:rotateY");

_forEachName("x,y,z,top,right,bottom,left,width,height,fontSize,padding,margin,perspective", function (name) {
  _config.units[name] = "px";
});

gsap.registerPlugin(CSSPlugin);

// CONCATENATED MODULE: ./node_modules/gsap/index.js


var gsapWithCSS = gsap.registerPlugin(CSSPlugin) || gsap,
    // to protect from tree shaking
TweenMaxWithCSS = gsapWithCSS.core.Tween;

// EXTERNAL MODULE: ./node_modules/three/build/three.js
var three = __webpack_require__(12);

// CONCATENATED MODULE: ./src/hooks/useThree.jsx



var useThree_useThree = function useThree(_ref) {
  var layout = _ref.layout,
      options = _ref.options;
  var scene = new three["Scene"]();
  var renderer;
  var maxNumberOfBars = 0;
  var showCameraHelper = 0;
  var mapWidth = window.innerWidth;
  var mapHeight = window.innerHeight;

  if (options.domElement) {
    mapWidth = options.domElement.getBoundingClientRect().width;
    mapHeight = options.domElement.getBoundingClientRect().height;
  } else if (options.canvas) {
    mapWidth = options.canvas.width;
    mapHeight = options.canvas.height;
  }

  var camera = new three["PerspectiveCamera"](45, mapWidth / mapHeight, 0.1, 1000);
  camera.name = 'camera';

  var minimizeBars = function minimizeBars() {
    for (var index = 0; index <= maxNumberOfBars; index += 1) {
      var bar = scene.getObjectByName("bar-".concat(index), true);
      TweenMaxWithCSS.to(bar.scale, 1, {
        y: 1
      }); // 0 creates errors

      TweenMaxWithCSS.to(bar.position, 1, {
        y: 1
      });
      TweenMaxWithCSS.to(bar.material, 1, {
        opacity: 0
      });
    }
  };

  var raiseBars = function raiseBars() {
    for (var index = 0; index <= maxNumberOfBars; index += 1) {
      var bar = scene.getObjectByName("bar-".concat(index), true);
      TweenMaxWithCSS.to(bar.scale, 2, {
        y: bar.userData.y
      }); // 0 creates errors

      TweenMaxWithCSS.to(bar.position, 2, {
        y: bar.userData.y / 2
      });
      TweenMaxWithCSS.to(bar.material, 1, {
        opacity: 1
      });
    }
  }; // Create Bars


  var createBar = function createBar(_ref2) {
    var _ref2$posx = _ref2.posx,
        posx = _ref2$posx === void 0 ? 0 : _ref2$posx,
        _ref2$posz = _ref2.posz,
        posz = _ref2$posz === void 0 ? 0 : _ref2$posz,
        _ref2$posy = _ref2.posy,
        posy = _ref2$posy === void 0 ? 0 : _ref2$posy,
        _ref2$width = _ref2.width,
        width = _ref2$width === void 0 ? 4 : _ref2$width,
        _ref2$height = _ref2.height,
        height = _ref2$height === void 0 ? 4 : _ref2$height,
        _ref2$depth = _ref2.depth,
        depth = _ref2$depth === void 0 ? 4 : _ref2$depth,
        _ref2$order = _ref2.order,
        order = _ref2$order === void 0 ? 1 : _ref2$order,
        _ref2$maxBarUmberFro = _ref2.maxBarΝumberFromData,
        maxBarΝumberFromData = _ref2$maxBarUmberFro === void 0 ? 10 : _ref2$maxBarUmberFro,
        _ref2$color = _ref2.color,
        color = _ref2$color === void 0 ? 0xfffff : _ref2$color;
    return new Promise(function (resolve) {
      var max = 3000;
      var ratio = Number(posy) / Number(maxBarΝumberFromData); // ) / 100) * max;

      var y = max * ratio;
      var _posy = 1;
      var geometry = new three["BoxGeometry"](width, height, depth, 1, 1, 1);
      var material = new three["MeshLambertMaterial"]({
        color: color,
        transparent: true
      });
      var bar = new three["Mesh"](geometry, material);
      bar.position.set(posx, _posy, posz);
      bar.name = "bar-".concat(order);
      bar.userData.y = y;
      bar.material.opacity = 1;
      scene.add(bar); // Animate

      TweenMaxWithCSS.to(bar.scale, 1, {
        y: y,
        delay: order * 0.1 + 1
      });
      TweenMaxWithCSS.to(bar.position, 1, {
        y: y / 2,
        delay: order * 0.1 + 1
      });
      maxNumberOfBars = order;
      resolve(true);
    });
  }; // create two three.js lights to illuminate the model


  var createLights = function createLights() {
    var directionalLight = new three["DirectionalLight"](0xffffff);
    directionalLight.position.set(-90, 200, 130).normalize();
    directionalLight.name = 'light-1';
    scene.add(directionalLight);
    var directionalLight2 = new three["DirectionalLight"](0xffffff, 0.3);
    directionalLight2.position.set(90, 20, -100).normalize();
    directionalLight2.name = 'light-2';
    scene.add(directionalLight2);

    if (showCameraHelper) {
      var helper = new three["CameraHelper"](camera);
      scene.add(helper);
    }
  };

  var handleWindowResize = function handleWindowResize() {
    mapWidth = window.innerWidth;
    mapHeight = window.innerHeight;

    if (options.domElement) {
      mapWidth = options.domElement.getBoundingClientRect().width;
      mapHeight = options.domElement.getBoundingClientRect().height;
    } else if (options.canvas) {
      mapWidth = options.canvas.width;
      mapHeight = options.canvas.height;
    }

    camera.aspect = mapWidth / mapHeight;
    renderer.setSize(mapWidth, mapHeight);
  };

  var finalRender = function finalRender() {
    if (!renderer) {
      if (options.domElement) {
        renderer = new three["WebGLRenderer"]();
        renderer.setSize(options.domElement.getBoundingClientRect().width, options.domElement.getBoundingClientRect().height);
        options.domElement.appendChild(renderer.domElement);
      } else {
        // use the Mapbox GL JS map canvas for three.js
        renderer = new three["WebGLRenderer"]({
          canvas: options.canvas,
          context: options.context,
          antialias: true
        });
        renderer.autoClear = false;
      }
    }

    window.addEventListener('resize', handleWindowResize, false);
    renderer.state.reset(); // call the render function

    renderer.render(scene, camera);
  }; // Create Ground Plane


  var createGroundPlane = function createGroundPlane() {
    // renderer.setClearColor(new Color(0xEEEEEE, 1.0));
    // renderer.setSize(window.innerWidth, window.innerHeight);
    // renderer.shadowMapEnabled = true;
    // create the ground plane
    var planeGeometry = new three["PlaneGeometry"](60, 20);
    var planeMaterial = new three["MeshLambertMaterial"]({
      color: 0xffffff
    });
    var plane = new three["Mesh"](planeGeometry, planeMaterial);
    plane.receiveShadow = true; // rotate and position the plane

    plane.rotation.x = -0.5 * Math.PI;
    plane.position.x = 15;
    plane.position.y = 0;
    plane.position.z = 0; // add the plane to the scene

    scene.add(plane); // create a cube
    // const cubeGeometry = new BoxGeometry(4, 4, 4);
    // const cubeMaterial = new MeshLambertMaterial({ color: 0xff0000 });
    // const cube = new Mesh(cubeGeometry, cubeMaterial);
    // cube.castShadow = true;
    // // position the cube
    // cube.position.x = -4;
    // cube.position.y = 3;
    // cube.position.z = 0;
    // // add the cube to the scene
    // scene.add(cube);
    // createBar = (posx, posz, posy, width, height, depth, order, maxBarΝumberFromData)
    // createBar(-4, 0, 3, 4, 4, 4, 1, 8);

    createBar({
      posx: -4,
      posy: 3
    });
    var sphereGeometry = new three["SphereGeometry"](4, 20, 20);
    var sphereMaterial = new three["MeshLambertMaterial"]({
      color: 0x7777ff
    });
    var sphere = new three["Mesh"](sphereGeometry, sphereMaterial); // position the sphere

    sphere.position.x = 20;
    sphere.position.y = 4;
    sphere.position.z = 2;
    sphere.castShadow = true; // add the sphere to the scene

    scene.add(sphere); // position and point the camera to the center of the scene

    camera.position.x = -30;
    camera.position.y = 40;
    camera.position.z = 30;
    camera.lookAt(scene.position); // add spotlight for the shadows

    var spotLight = new three["SpotLight"](0xffffff);
    spotLight.position.set(-40, 60, -10);
    spotLight.castShadow = true;
    scene.add(spotLight);
    finalRender();
  };

  var createScene = function createScene() {
    // eslint-disable-line
    createLights();
  }; // For mapbox


  var renderScene = function renderScene(mapboxgl, matrix) {
    // parameters to ensure the model is georeferenced correctly on the map
    var modelOrigin = [-97.531708, 39.305878];
    var modelAltitude = 0;
    var modelRotate = [Math.PI / 2, 0, 0];
    var modelAsMercatorCoordinate = mapboxgl.MercatorCoordinate.fromLngLat(modelOrigin, modelAltitude); // transformation parameters to position, rotate and scale the 3D model onto the map

    var modelTransform = {
      translateX: modelAsMercatorCoordinate.x,
      translateY: modelAsMercatorCoordinate.y,
      translateZ: modelAsMercatorCoordinate.z,
      rotateX: modelRotate[0],
      rotateY: modelRotate[1],
      rotateZ: modelRotate[2],

      /* Since our 3D model is in real world meters, a scale transform needs to be
      * applied since the CustomLayerInterface expects units in MercatorCoordinates.
      */
      scale: modelAsMercatorCoordinate.meterInMercatorCoordinateUnits()
    };
    var rotationX = new three["Matrix4"]().makeRotationAxis(new three["Vector3"](1, 0, 0), modelTransform.rotateX);
    var rotationY = new three["Matrix4"]().makeRotationAxis(new three["Vector3"](0, 1, 0), modelTransform.rotateY);
    var rotationZ = new three["Matrix4"]().makeRotationAxis(new three["Vector3"](0, 0, 1), modelTransform.rotateZ);
    var m = new three["Matrix4"]().fromArray(matrix);
    var l = new three["Matrix4"]().makeTranslation(modelTransform.translateX, modelTransform.translateY, modelTransform.translateZ).scale(new three["Vector3"](modelTransform.scale, -modelTransform.scale, modelTransform.scale)).multiply(rotationX).multiply(rotationY).multiply(rotationZ);
    camera.projectionMatrix = m.multiply(l);
  };

  if (options.canvas || options.domElement) createScene();
  return {
    scene: scene,
    layout: layout,
    createBar: createBar,
    minimizeBars: minimizeBars,
    raiseBars: raiseBars,
    renderScene: renderScene,
    createGroundPlane: createGroundPlane,
    finalRender: finalRender
  };
};

/* harmony default export */ var hooks_useThree = (useThree_useThree);
// CONCATENATED MODULE: ./src/components/QdtButton/QdtButton.jsx




function QdtButton_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function QdtButton_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { QdtButton_ownKeys(Object(source), true).forEach(function (key) { defineProperty_default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { QdtButton_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

/**
 * @name QdtButton
 * @param {object} app - Qlik Sense app
 * @param {object} vis - Qlik Sense visualization
 * @param {string} type [clearSelections, exportData, exportImg, exportPdf] - The button action
 * @param {string} label - The text on the button
*/


 // import '../../styles/index.scss';
// Sept 2018 BUG. Adds the current www folder in the path
// const urlFix = (url) => {
//   const tempUrl = url.split('/');
//   const sbstrIndex = url.indexOf('tempcontent');
//   const _url = `${tempUrl[0]}//${tempUrl[2]}/${url.substring(sbstrIndex, url.length)}`;
//   return _url;
// };

var QdtButton_QdtButton = function QdtButton(_ref) {
  var app = _ref.app,
      optionsProp = _ref.options;
  var defaultOptions = {};

  var options = QdtButton_objectSpread({}, defaultOptions, {}, optionsProp);

  var handleClick = Object(react["useCallback"])(
  /*#__PURE__*/
  asyncToGenerator_default()(
  /*#__PURE__*/
  regenerator_default.a.mark(function _callee() {
    return regenerator_default.a.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            app.clearAll();

          case 1:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  })), [app]);
  return react_default.a.createElement(react_default.a.Fragment, null, react_default.a.createElement(esm_Button_Button, {
    variant: "contained",
    color: "primary",
    onClick: handleClick
  }, options.label));
};

QdtButton_QdtButton.propTypes = {
  app: prop_types_default.a.object.isRequired,
  options: prop_types_default.a.object
};
QdtButton_QdtButton.defaultProps = {
  options: {}
};
/* harmony default export */ var components_QdtButton_QdtButton = (QdtButton_QdtButton);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Grid/Grid.js


// A grid component using the following libs as inspiration.
//
// For the implementation:
// - https://getbootstrap.com/docs/4.3/layout/grid/
// - https://github.com/kristoferjoseph/flexboxgrid/blob/master/src/css/flexboxgrid.css
// - https://github.com/roylee0704/react-flexbox-grid
// - https://material.angularjs.org/latest/layout/introduction
//
// Follow this flexbox Guide to better understand the underlying model:
// - https://css-tricks.com/snippets/css/a-guide-to-flexbox/





var SPACINGS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var GRID_SIZES = ['auto', true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

function generateGrid(globalStyles, theme, breakpoint) {
  var styles = {};
  GRID_SIZES.forEach(function (size) {
    var key = "grid-".concat(breakpoint, "-").concat(size);

    if (size === true) {
      // For the auto layouting
      styles[key] = {
        flexBasis: 0,
        flexGrow: 1,
        maxWidth: '100%'
      };
      return;
    }

    if (size === 'auto') {
      styles[key] = {
        flexBasis: 'auto',
        flexGrow: 0,
        maxWidth: 'none'
      };
      return;
    } // Keep 7 significant numbers.


    var width = "".concat(Math.round(size / 12 * 10e7) / 10e5, "%"); // Close to the bootstrap implementation:
    // https://github.com/twbs/bootstrap/blob/8fccaa2439e97ec72a4b7dc42ccc1f649790adb0/scss/mixins/_grid.scss#L41

    styles[key] = {
      flexBasis: width,
      flexGrow: 0,
      maxWidth: width
    };
  }); // No need for a media query for the first size.

  if (breakpoint === 'xs') {
    Object(helpers_esm_extends["a" /* default */])(globalStyles, styles);
  } else {
    globalStyles[theme.breakpoints.up(breakpoint)] = styles;
  }
}

function getOffset(val) {
  var div = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  var parse = parseFloat(val);
  return "".concat(parse / div).concat(String(val).replace(String(parse), '') || 'px');
}

function generateGutter(theme, breakpoint) {
  var styles = {};
  SPACINGS.forEach(function (spacing) {
    var themeSpacing = theme.spacing(spacing);

    if (themeSpacing === 0) {
      return;
    }

    styles["spacing-".concat(breakpoint, "-").concat(spacing)] = {
      margin: "-".concat(getOffset(themeSpacing, 2)),
      width: "calc(100% + ".concat(getOffset(themeSpacing), ")"),
      '& > $item': {
        padding: getOffset(themeSpacing, 2)
      }
    };
  });
  return styles;
} // Default CSS values
// flex: '0 1 auto',
// flexDirection: 'row',
// alignItems: 'flex-start',
// flexWrap: 'nowrap',
// justifyContent: 'flex-start',


var Grid_styles = function styles(theme) {
  return Object(helpers_esm_extends["a" /* default */])({
    /* Styles applied to the root element */
    root: {},

    /* Styles applied to the root element if `container={true}`. */
    container: {
      boxSizing: 'border-box',
      display: 'flex',
      flexWrap: 'wrap',
      width: '100%'
    },

    /* Styles applied to the root element if `item={true}`. */
    item: {
      boxSizing: 'border-box',
      margin: '0' // For instance, it's useful when used with a `figure` element.

    },

    /* Styles applied to the root element if `zeroMinWidth={true}`. */
    zeroMinWidth: {
      minWidth: 0
    },

    /* Styles applied to the root element if `direction="column"`. */
    'direction-xs-column': {
      flexDirection: 'column'
    },

    /* Styles applied to the root element if `direction="column-reverse"`. */
    'direction-xs-column-reverse': {
      flexDirection: 'column-reverse'
    },

    /* Styles applied to the root element if `direction="rwo-reverse"`. */
    'direction-xs-row-reverse': {
      flexDirection: 'row-reverse'
    },

    /* Styles applied to the root element if `wrap="nowrap"`. */
    'wrap-xs-nowrap': {
      flexWrap: 'nowrap'
    },

    /* Styles applied to the root element if `wrap="reverse"`. */
    'wrap-xs-wrap-reverse': {
      flexWrap: 'wrap-reverse'
    },

    /* Styles applied to the root element if `alignItems="center"`. */
    'align-items-xs-center': {
      alignItems: 'center'
    },

    /* Styles applied to the root element if `alignItems="flex-start"`. */
    'align-items-xs-flex-start': {
      alignItems: 'flex-start'
    },

    /* Styles applied to the root element if `alignItems="flex-end"`. */
    'align-items-xs-flex-end': {
      alignItems: 'flex-end'
    },

    /* Styles applied to the root element if `alignItems="baseline"`. */
    'align-items-xs-baseline': {
      alignItems: 'baseline'
    },

    /* Styles applied to the root element if `alignContent="center"`. */
    'align-content-xs-center': {
      alignContent: 'center'
    },

    /* Styles applied to the root element if `alignContent="flex-start"`. */
    'align-content-xs-flex-start': {
      alignContent: 'flex-start'
    },

    /* Styles applied to the root element if `alignContent="flex-end"`. */
    'align-content-xs-flex-end': {
      alignContent: 'flex-end'
    },

    /* Styles applied to the root element if `alignContent="space-between"`. */
    'align-content-xs-space-between': {
      alignContent: 'space-between'
    },

    /* Styles applied to the root element if `alignContent="space-around"`. */
    'align-content-xs-space-around': {
      alignContent: 'space-around'
    },

    /* Styles applied to the root element if `justify="center"`. */
    'justify-xs-center': {
      justifyContent: 'center'
    },

    /* Styles applied to the root element if `justify="flex-end"`. */
    'justify-xs-flex-end': {
      justifyContent: 'flex-end'
    },

    /* Styles applied to the root element if `justify="space-between"`. */
    'justify-xs-space-between': {
      justifyContent: 'space-between'
    },

    /* Styles applied to the root element if `justify="space-around"`. */
    'justify-xs-space-around': {
      justifyContent: 'space-around'
    },

    /* Styles applied to the root element if `justify="space-evenly"`. */
    'justify-xs-space-evenly': {
      justifyContent: 'space-evenly'
    }
  }, generateGutter(theme, 'xs'), {}, theme.breakpoints.keys.reduce(function (accumulator, key) {
    // Use side effect over immutability for better performance.
    generateGrid(accumulator, theme, key);
    return accumulator;
  }, {}));
};
var Grid_Grid = react_default.a.forwardRef(function Grid(props, ref) {
  var _props$alignContent = props.alignContent,
      alignContent = _props$alignContent === void 0 ? 'stretch' : _props$alignContent,
      _props$alignItems = props.alignItems,
      alignItems = _props$alignItems === void 0 ? 'stretch' : _props$alignItems,
      classes = props.classes,
      classNameProp = props.className,
      _props$component = props.component,
      Component = _props$component === void 0 ? 'div' : _props$component,
      _props$container = props.container,
      container = _props$container === void 0 ? false : _props$container,
      _props$direction = props.direction,
      direction = _props$direction === void 0 ? 'row' : _props$direction,
      _props$item = props.item,
      item = _props$item === void 0 ? false : _props$item,
      _props$justify = props.justify,
      justify = _props$justify === void 0 ? 'flex-start' : _props$justify,
      _props$lg = props.lg,
      lg = _props$lg === void 0 ? false : _props$lg,
      _props$md = props.md,
      md = _props$md === void 0 ? false : _props$md,
      _props$sm = props.sm,
      sm = _props$sm === void 0 ? false : _props$sm,
      _props$spacing = props.spacing,
      spacing = _props$spacing === void 0 ? 0 : _props$spacing,
      _props$wrap = props.wrap,
      wrap = _props$wrap === void 0 ? 'wrap' : _props$wrap,
      _props$xl = props.xl,
      xl = _props$xl === void 0 ? false : _props$xl,
      _props$xs = props.xs,
      xs = _props$xs === void 0 ? false : _props$xs,
      _props$zeroMinWidth = props.zeroMinWidth,
      zeroMinWidth = _props$zeroMinWidth === void 0 ? false : _props$zeroMinWidth,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["alignContent", "alignItems", "classes", "className", "component", "container", "direction", "item", "justify", "lg", "md", "sm", "spacing", "wrap", "xl", "xs", "zeroMinWidth"]);

  var className = Object(clsx_m["a" /* default */])(classes.root, classNameProp, container && [classes.container, spacing !== 0 && classes["spacing-xs-".concat(String(spacing))]], item && classes.item, zeroMinWidth && classes.zeroMinWidth, direction !== 'row' && classes["direction-xs-".concat(String(direction))], wrap !== 'wrap' && classes["wrap-xs-".concat(String(wrap))], alignItems !== 'stretch' && classes["align-items-xs-".concat(String(alignItems))], alignContent !== 'stretch' && classes["align-content-xs-".concat(String(alignContent))], justify !== 'flex-start' && classes["justify-xs-".concat(String(justify))], xs !== false && classes["grid-xs-".concat(String(xs))], sm !== false && classes["grid-sm-".concat(String(sm))], md !== false && classes["grid-md-".concat(String(md))], lg !== false && classes["grid-lg-".concat(String(lg))], xl !== false && classes["grid-xl-".concat(String(xl))]);
  return react_default.a.createElement(Component, Object(helpers_esm_extends["a" /* default */])({
    className: className,
    ref: ref
  }, other));
});
 false ? undefined : void 0;
var StyledGrid = Object(withStyles["a" /* default */])(Grid_styles, {
  name: 'MuiGrid'
})(Grid_Grid);

if (false) { var requireProp; }

/* harmony default export */ var esm_Grid_Grid = (StyledGrid);
// CONCATENATED MODULE: ./src/components/QdtKpi/QdtKpi.jsx
/**
 * @name QdtKpi
 * @param {object} layout - Qlik object layout
 * @param {object} options - Options
 * @param {string} options.variant - 'contained' OR 'outlined'
 * @param {string} options.color - 'primary' OR 'secondary'
 * @param {string} options.fontSize - Any font size value, ie '4rem', '10px', 24 etc
*/






var QdtKpi_QdtKpi = function QdtKpi(_ref) {
  var layout = _ref.layout,
      optionsProp = _ref.options;
  var defaultOptions = {
    variant: 'contained',
    color: 'primary',
    fontSize: '4rem',
    custom: null
  };
  var options = Object(merge["a" /* default */])(defaultOptions, optionsProp);
  var variant = options.variant,
      color = options.color,
      fontSize = options.fontSize;
  var KPIGrid = Object(withStyles["a" /* default */])(function (theme) {
    return {
      root: {
        color: variant === 'contained' ? theme.palette[color].contrastText : theme.palette[color].main,
        backgroundColor: variant === 'contained' ? theme.palette[color].main : false,
        border: '1px solid',
        borderColor: theme.palette[color].light,
        fontSize: fontSize,
        height: '100%',
        padding: 50
      }
    };
  })(esm_Grid_Grid);
  var value = Object(react["useMemo"])(function () {
    return layout.qHyperCube.qDataPages[0].qMatrix[0][0].qText;
  }, [layout]);
  return react_default.a.createElement(react_default.a.Fragment, null, !options.custom && react_default.a.createElement(KPIGrid, {
    container: true,
    direction: "row",
    justify: "center",
    alignItems: "center",
    className: "qdt-kpi"
  }, value), options.custom && react_default.a.createElement(esm_Grid_Grid, {
    container: true,
    direction: "row",
    justify: "center",
    alignItems: "center",
    className: "qdt-kpi",
    style: options.custom
  }, value));
};

QdtKpi_QdtKpi.propTypes = {
  layout: prop_types_default.a.object,
  options: prop_types_default.a.object
};
QdtKpi_QdtKpi.defaultProps = {
  layout: null,
  options: {}
};
/* harmony default export */ var components_QdtKpi_QdtKpi = (QdtKpi_QdtKpi);
// EXTERNAL MODULE: ./node_modules/classnames/index.js
var classnames = __webpack_require__(9);
var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/InputBase/utils.js
// Supports determination of isControlled().
// Controlled input accepts its current value as a prop.
//
// @see https://facebook.github.io/react/docs/forms.html#controlled-components
// @param value
// @returns {boolean} true if string (including '') or number (including zero)
function hasValue(value) {
  return value != null && !(Array.isArray(value) && value.length === 0);
} // Determine if field is empty or filled.
// Response determines if label is presented above field or as placeholder.
//
// @param obj
// @param SSR
// @returns {boolean} False when not present or empty string.
//                    True when any number or string with length.

function isFilled(obj) {
  var SSR = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  return obj && (hasValue(obj.value) && obj.value !== '' || SSR && hasValue(obj.defaultValue) && obj.defaultValue !== '');
} // Determine if an Input is adorned on start.
// It's corresponding to the left with LTR.
//
// @param obj
// @returns {boolean} False when no adornments.
//                    True when adorned at the start.

function isAdornedStart(obj) {
  return obj.startAdornment;
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/utils/isMuiElement.js

function isMuiElement(element, muiNames) {
  return react_default.a.isValidElement(element) && muiNames.indexOf(element.type.muiName) !== -1;
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/FormControl/FormControlContext.js

/**
 * @ignore - internal component.
 */

var FormControlContext = react_default.a.createContext();

if (false) {}

function useFormControl() {
  return react_default.a.useContext(FormControlContext);
}
/* harmony default export */ var FormControl_FormControlContext = (FormControlContext);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/FormControl/FormControl.js










var FormControl_styles = {
  /* Styles applied to the root element. */
  root: {
    display: 'inline-flex',
    flexDirection: 'column',
    position: 'relative',
    // Reset fieldset default style.
    minWidth: 0,
    padding: 0,
    margin: 0,
    border: 0,
    zIndex: 0,
    // Fix blur label text issue
    verticalAlign: 'top' // Fix alignment issue on Safari.

  },

  /* Styles applied to the root element if `margin="normal"`. */
  marginNormal: {
    marginTop: 16,
    marginBottom: 8
  },

  /* Styles applied to the root element if `margin="dense"`. */
  marginDense: {
    marginTop: 8,
    marginBottom: 4
  },

  /* Styles applied to the root element if `fullWidth={true}`. */
  fullWidth: {
    width: '100%'
  }
};
/**
 * Provides context such as filled/focused/error/required for form inputs.
 * Relying on the context provides high flexibility and ensures that the state always stays
 * consistent across the children of the `FormControl`.
 * This context is used by the following components:
 *
 *  - FormLabel
 *  - FormHelperText
 *  - Input
 *  - InputLabel
 *
 * You can find one composition example below and more going to [the demos](/components/text-fields/#components).
 *
 * ```jsx
 * <FormControl>
 *   <InputLabel htmlFor="my-input">Email address</InputLabel>
 *   <Input id="my-input" aria-describedby="my-helper-text" />
 *   <FormHelperText id="my-helper-text">We'll never share your email.</FormHelperText>
 * </FormControl>
 * ```
 *
 * ⚠️Only one input can be used within a FormControl.
 */

var FormControl_FormControl = react_default.a.forwardRef(function FormControl(props, ref) {
  var children = props.children,
      classes = props.classes,
      className = props.className,
      _props$color = props.color,
      color = _props$color === void 0 ? 'primary' : _props$color,
      _props$component = props.component,
      Component = _props$component === void 0 ? 'div' : _props$component,
      _props$disabled = props.disabled,
      disabled = _props$disabled === void 0 ? false : _props$disabled,
      _props$error = props.error,
      error = _props$error === void 0 ? false : _props$error,
      _props$fullWidth = props.fullWidth,
      fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,
      _props$hiddenLabel = props.hiddenLabel,
      hiddenLabel = _props$hiddenLabel === void 0 ? false : _props$hiddenLabel,
      _props$margin = props.margin,
      margin = _props$margin === void 0 ? 'none' : _props$margin,
      _props$required = props.required,
      required = _props$required === void 0 ? false : _props$required,
      size = props.size,
      _props$variant = props.variant,
      variant = _props$variant === void 0 ? 'standard' : _props$variant,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["children", "classes", "className", "color", "component", "disabled", "error", "fullWidth", "hiddenLabel", "margin", "required", "size", "variant"]);

  var _React$useState = react_default.a.useState(function () {
    // We need to iterate through the children and find the Input in order
    // to fully support server-side rendering.
    var initialAdornedStart = false;

    if (children) {
      react_default.a.Children.forEach(children, function (child) {
        if (!isMuiElement(child, ['Input', 'Select'])) {
          return;
        }

        var input = isMuiElement(child, ['Select']) ? child.props.input : child;

        if (input && isAdornedStart(input.props)) {
          initialAdornedStart = true;
        }
      });
    }

    return initialAdornedStart;
  }),
      adornedStart = _React$useState[0],
      setAdornedStart = _React$useState[1];

  var _React$useState2 = react_default.a.useState(function () {
    // We need to iterate through the children and find the Input in order
    // to fully support server-side rendering.
    var initialFilled = false;

    if (children) {
      react_default.a.Children.forEach(children, function (child) {
        if (!isMuiElement(child, ['Input', 'Select'])) {
          return;
        }

        if (isFilled(child.props, true)) {
          initialFilled = true;
        }
      });
    }

    return initialFilled;
  }),
      filled = _React$useState2[0],
      setFilled = _React$useState2[1];

  var _React$useState3 = react_default.a.useState(false),
      focused = _React$useState3[0],
      setFocused = _React$useState3[1];

  if (disabled && focused) {
    setFocused(false);
  }

  var registerEffect;

  if (false) { var registeredInput; }

  var onFilled = react_default.a.useCallback(function () {
    setFilled(true);
  }, []);
  var onEmpty = react_default.a.useCallback(function () {
    setFilled(false);
  }, []);
  var childContext = {
    adornedStart: adornedStart,
    setAdornedStart: setAdornedStart,
    color: color,
    disabled: disabled,
    error: error,
    filled: filled,
    focused: focused,
    fullWidth: fullWidth,
    hiddenLabel: hiddenLabel,
    margin: (size === 'small' ? 'dense' : undefined) || margin,
    onBlur: function onBlur() {
      setFocused(false);
    },
    onEmpty: onEmpty,
    onFilled: onFilled,
    onFocus: function onFocus() {
      setFocused(true);
    },
    registerEffect: registerEffect,
    required: required,
    variant: variant
  };
  return react_default.a.createElement(FormControl_FormControlContext.Provider, {
    value: childContext
  }, react_default.a.createElement(Component, Object(helpers_esm_extends["a" /* default */])({
    className: Object(clsx_m["a" /* default */])(classes.root, className, margin !== 'none' && classes["margin".concat(Object(capitalize["a" /* default */])(margin))], fullWidth && classes.fullWidth),
    ref: ref
  }, other), children));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_FormControl_FormControl = (Object(withStyles["a" /* default */])(FormControl_styles, {
  name: 'MuiFormControl'
})(FormControl_FormControl));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/FormControl/formControlState.js
function formControlState(_ref) {
  var props = _ref.props,
      states = _ref.states,
      muiFormControl = _ref.muiFormControl;
  return states.reduce(function (acc, state) {
    acc[state] = props[state];

    if (muiFormControl) {
      if (typeof props[state] === 'undefined') {
        acc[state] = muiFormControl[state];
      }
    }

    return acc;
  }, {});
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/FormControl/useFormControl.js


function useFormControl_useFormControl() {
  return react_default.a.useContext(FormControl_FormControlContext);
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/FormLabel/FormLabel.js









var FormLabel_styles = function styles(theme) {
  return {
    /* Styles applied to the root element. */
    root: Object(helpers_esm_extends["a" /* default */])({
      color: theme.palette.text.secondary
    }, theme.typography.body1, {
      lineHeight: 1,
      padding: 0,
      '&$focused': {
        color: theme.palette.primary.main
      },
      '&$disabled': {
        color: theme.palette.text.disabled
      },
      '&$error': {
        color: theme.palette.error.main
      }
    }),

    /* Styles applied to the root element if the color is secondary. */
    colorSecondary: {
      '&$focused': {
        color: theme.palette.secondary.main
      }
    },

    /* Pseudo-class applied to the root element if `focused={true}`. */
    focused: {},

    /* Pseudo-class applied to the root element if `disabled={true}`. */
    disabled: {},

    /* Pseudo-class applied to the root element if `error={true}`. */
    error: {},

    /* Pseudo-class applied to the root element if `filled={true}`. */
    filled: {},

    /* Pseudo-class applied to the root element if `required={true}`. */
    required: {},

    /* Styles applied to the asterisk element. */
    asterisk: {
      '&$error': {
        color: theme.palette.error.main
      }
    }
  };
};
var FormLabel_FormLabel = react_default.a.forwardRef(function FormLabel(props, ref) {
  var children = props.children,
      classes = props.classes,
      className = props.className,
      color = props.color,
      _props$component = props.component,
      Component = _props$component === void 0 ? 'label' : _props$component,
      disabled = props.disabled,
      error = props.error,
      filled = props.filled,
      focused = props.focused,
      required = props.required,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["children", "classes", "className", "color", "component", "disabled", "error", "filled", "focused", "required"]);

  var muiFormControl = useFormControl_useFormControl();
  var fcs = formControlState({
    props: props,
    muiFormControl: muiFormControl,
    states: ['color', 'required', 'focused', 'disabled', 'error', 'filled']
  });
  return react_default.a.createElement(Component, Object(helpers_esm_extends["a" /* default */])({
    className: Object(clsx_m["a" /* default */])(classes.root, classes["color".concat(Object(capitalize["a" /* default */])(fcs.color || 'primary'))], className, fcs.disabled && classes.disabled, fcs.error && classes.error, fcs.filled && classes.filled, fcs.focused && classes.focused, fcs.required && classes.required),
    ref: ref
  }, other), children, fcs.required && react_default.a.createElement("span", {
    className: Object(clsx_m["a" /* default */])(classes.asterisk, fcs.error && classes.error)
  }, "\u2009", '*'));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_FormLabel_FormLabel = (Object(withStyles["a" /* default */])(FormLabel_styles, {
  name: 'MuiFormLabel'
})(FormLabel_FormLabel));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/InputLabel/InputLabel.js









var InputLabel_styles = function styles(theme) {
  return {
    /* Styles applied to the root element. */
    root: {
      display: 'block',
      transformOrigin: 'top left'
    },

    /* Pseudo-class applied to the root element if `focused={true}`. */
    focused: {},

    /* Pseudo-class applied to the root element if `disabled={true}`. */
    disabled: {},

    /* Pseudo-class applied to the root element if `error={true}`. */
    error: {},

    /* Pseudo-class applied to the root element if `required={true}`. */
    required: {},

    /* Pseudo-class applied to the asterisk element. */
    asterisk: {},

    /* Styles applied to the root element if the component is a descendant of `FormControl`. */
    formControl: {
      position: 'absolute',
      left: 0,
      top: 0,
      // slight alteration to spec spacing to match visual spec result
      transform: 'translate(0, 24px) scale(1)'
    },

    /* Styles applied to the root element if `margin="dense"`. */
    marginDense: {
      // Compensation for the `Input.inputDense` style.
      transform: 'translate(0, 21px) scale(1)'
    },

    /* Styles applied to the `input` element if `shrink={true}`. */
    shrink: {
      transform: 'translate(0, 1.5px) scale(0.75)',
      transformOrigin: 'top left'
    },

    /* Styles applied to the `input` element if `disableAnimation={false}`. */
    animated: {
      transition: theme.transitions.create(['color', 'transform'], {
        duration: theme.transitions.duration.shorter,
        easing: theme.transitions.easing.easeOut
      })
    },

    /* Styles applied to the root element if `variant="filled"`. */
    filled: {
      // Chrome's autofill feature gives the input field a yellow background.
      // Since the input field is behind the label in the HTML tree,
      // the input field is drawn last and hides the label with an opaque background color.
      // zIndex: 1 will raise the label above opaque background-colors of input.
      zIndex: 1,
      pointerEvents: 'none',
      transform: 'translate(12px, 20px) scale(1)',
      '&$marginDense': {
        transform: 'translate(12px, 17px) scale(1)'
      },
      '&$shrink': {
        transform: 'translate(12px, 10px) scale(0.75)',
        '&$marginDense': {
          transform: 'translate(12px, 7px) scale(0.75)'
        }
      }
    },

    /* Styles applied to the root element if `variant="outlined"`. */
    outlined: {
      // see comment above on filled.zIndex
      zIndex: 1,
      pointerEvents: 'none',
      transform: 'translate(14px, 20px) scale(1)',
      '&$marginDense': {
        transform: 'translate(14px, 12px) scale(1)'
      },
      '&$shrink': {
        transform: 'translate(14px, -6px) scale(0.75)'
      }
    }
  };
};
var InputLabel_InputLabel = react_default.a.forwardRef(function InputLabel(props, ref) {
  var classes = props.classes,
      className = props.className,
      _props$disableAnimati = props.disableAnimation,
      disableAnimation = _props$disableAnimati === void 0 ? false : _props$disableAnimati,
      margin = props.margin,
      shrinkProp = props.shrink,
      variant = props.variant,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["classes", "className", "disableAnimation", "margin", "shrink", "variant"]);

  var muiFormControl = useFormControl_useFormControl();
  var shrink = shrinkProp;

  if (typeof shrink === 'undefined' && muiFormControl) {
    shrink = muiFormControl.filled || muiFormControl.focused || muiFormControl.adornedStart;
  }

  var fcs = formControlState({
    props: props,
    muiFormControl: muiFormControl,
    states: ['margin', 'variant']
  });
  return react_default.a.createElement(esm_FormLabel_FormLabel, Object(helpers_esm_extends["a" /* default */])({
    "data-shrink": shrink,
    className: Object(clsx_m["a" /* default */])(classes.root, className, muiFormControl && classes.formControl, !disableAnimation && classes.animated, shrink && classes.shrink, fcs.margin === 'dense' && classes.marginDense, {
      'filled': classes.filled,
      'outlined': classes.outlined
    }[fcs.variant]),
    classes: {
      focused: classes.focused,
      disabled: classes.disabled,
      error: classes.error,
      required: classes.required,
      asterisk: classes.asterisk
    },
    ref: ref
  }, other));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_InputLabel_InputLabel = (Object(withStyles["a" /* default */])(InputLabel_styles, {
  name: 'MuiInputLabel'
})(InputLabel_InputLabel));
// EXTERNAL MODULE: ./node_modules/@material-ui/styles/esm/mergeClasses/mergeClasses.js
var mergeClasses = __webpack_require__(156);

// EXTERNAL MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js
var arrayWithHoles = __webpack_require__(67);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js
function _iterableToArrayLimit(arr, i) {
  if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
    return;
  }

  var _arr = [];
  var _n = true;
  var _d = false;
  var _e = undefined;

  try {
    for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);

      if (i && _arr.length === i) break;
    }
  } catch (err) {
    _d = true;
    _e = err;
  } finally {
    try {
      if (!_n && _i["return"] != null) _i["return"]();
    } finally {
      if (_d) throw _e;
    }
  }

  return _arr;
}
// EXTERNAL MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js
var nonIterableRest = __webpack_require__(68);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/slicedToArray.js



function _slicedToArray(arr, i) {
  return Object(arrayWithHoles["a" /* default */])(arr) || _iterableToArrayLimit(arr, i) || Object(nonIterableRest["a" /* default */])();
}
// EXTERNAL MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/typeof.js
var esm_typeof = __webpack_require__(69);

// EXTERNAL MODULE: ./node_modules/react-is/index.js
var react_is = __webpack_require__(23);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/utils/debounce.js
// Corresponds to 10 frames at 60 Hz.
// A few bytes payload overhead when lodash/debounce is ~3 kB and debounce ~300 B.
function debounce(func) {
  var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;
  var timeout;

  function debounced() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    // eslint-disable-next-line consistent-this
    var that = this;

    var later = function later() {
      func.apply(that, args);
    };

    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  }

  debounced.clear = function () {
    clearTimeout(timeout);
  };

  return debounced;
}
// CONCATENATED MODULE: ./node_modules/react-transition-group/esm/config.js
/* harmony default export */ var esm_config = ({
  disabled: false
});
// CONCATENATED MODULE: ./node_modules/react-transition-group/esm/Transition.js








var UNMOUNTED = 'unmounted';
var EXITED = 'exited';
var ENTERING = 'entering';
var ENTERED = 'entered';
var EXITING = 'exiting';
/**
 * The Transition component lets you describe a transition from one component
 * state to another _over time_ with a simple declarative API. Most commonly
 * it's used to animate the mounting and unmounting of a component, but can also
 * be used to describe in-place transition states as well.
 *
 * ---
 *
 * **Note**: `Transition` is a platform-agnostic base component. If you're using
 * transitions in CSS, you'll probably want to use
 * [`CSSTransition`](https://reactcommunity.org/react-transition-group/css-transition)
 * instead. It inherits all the features of `Transition`, but contains
 * additional features necessary to play nice with CSS transitions (hence the
 * name of the component).
 *
 * ---
 *
 * By default the `Transition` component does not alter the behavior of the
 * component it renders, it only tracks "enter" and "exit" states for the
 * components. It's up to you to give meaning and effect to those states. For
 * example we can add styles to a component when it enters or exits:
 *
 * ```jsx
 * import { Transition } from 'react-transition-group';
 *
 * const duration = 300;
 *
 * const defaultStyle = {
 *   transition: `opacity ${duration}ms ease-in-out`,
 *   opacity: 0,
 * }
 *
 * const transitionStyles = {
 *   entering: { opacity: 1 },
 *   entered:  { opacity: 1 },
 *   exiting:  { opacity: 0 },
 *   exited:  { opacity: 0 },
 * };
 *
 * const Fade = ({ in: inProp }) => (
 *   <Transition in={inProp} timeout={duration}>
 *     {state => (
 *       <div style={{
 *         ...defaultStyle,
 *         ...transitionStyles[state]
 *       }}>
 *         I'm a fade Transition!
 *       </div>
 *     )}
 *   </Transition>
 * );
 * ```
 *
 * There are 4 main states a Transition can be in:
 *  - `'entering'`
 *  - `'entered'`
 *  - `'exiting'`
 *  - `'exited'`
 *
 * Transition state is toggled via the `in` prop. When `true` the component
 * begins the "Enter" stage. During this stage, the component will shift from
 * its current transition state, to `'entering'` for the duration of the
 * transition and then to the `'entered'` stage once it's complete. Let's take
 * the following example (we'll use the
 * [useState](https://reactjs.org/docs/hooks-reference.html#usestate) hook):
 *
 * ```jsx
 * function App() {
 *   const [inProp, setInProp] = useState(false);
 *   return (
 *     <div>
 *       <Transition in={inProp} timeout={500}>
 *         {state => (
 *           // ...
 *         )}
 *       </Transition>
 *       <button onClick={() => setInProp(true)}>
 *         Click to Enter
 *       </button>
 *     </div>
 *   );
 * }
 * ```
 *
 * When the button is clicked the component will shift to the `'entering'` state
 * and stay there for 500ms (the value of `timeout`) before it finally switches
 * to `'entered'`.
 *
 * When `in` is `false` the same thing happens except the state moves from
 * `'exiting'` to `'exited'`.
 */

var Transition_Transition =
/*#__PURE__*/
function (_React$Component) {
  _inheritsLoose(Transition, _React$Component);

  function Transition(props, context) {
    var _this;

    _this = _React$Component.call(this, props, context) || this;
    var parentGroup = context; // In the context of a TransitionGroup all enters are really appears

    var appear = parentGroup && !parentGroup.isMounting ? props.enter : props.appear;
    var initialStatus;
    _this.appearStatus = null;

    if (props.in) {
      if (appear) {
        initialStatus = EXITED;
        _this.appearStatus = ENTERING;
      } else {
        initialStatus = ENTERED;
      }
    } else {
      if (props.unmountOnExit || props.mountOnEnter) {
        initialStatus = UNMOUNTED;
      } else {
        initialStatus = EXITED;
      }
    }

    _this.state = {
      status: initialStatus
    };
    _this.nextCallback = null;
    return _this;
  }

  Transition.getDerivedStateFromProps = function getDerivedStateFromProps(_ref, prevState) {
    var nextIn = _ref.in;

    if (nextIn && prevState.status === UNMOUNTED) {
      return {
        status: EXITED
      };
    }

    return null;
  }; // getSnapshotBeforeUpdate(prevProps) {
  //   let nextStatus = null
  //   if (prevProps !== this.props) {
  //     const { status } = this.state
  //     if (this.props.in) {
  //       if (status !== ENTERING && status !== ENTERED) {
  //         nextStatus = ENTERING
  //       }
  //     } else {
  //       if (status === ENTERING || status === ENTERED) {
  //         nextStatus = EXITING
  //       }
  //     }
  //   }
  //   return { nextStatus }
  // }


  var _proto = Transition.prototype;

  _proto.componentDidMount = function componentDidMount() {
    this.updateStatus(true, this.appearStatus);
  };

  _proto.componentDidUpdate = function componentDidUpdate(prevProps) {
    var nextStatus = null;

    if (prevProps !== this.props) {
      var status = this.state.status;

      if (this.props.in) {
        if (status !== ENTERING && status !== ENTERED) {
          nextStatus = ENTERING;
        }
      } else {
        if (status === ENTERING || status === ENTERED) {
          nextStatus = EXITING;
        }
      }
    }

    this.updateStatus(false, nextStatus);
  };

  _proto.componentWillUnmount = function componentWillUnmount() {
    this.cancelNextCallback();
  };

  _proto.getTimeouts = function getTimeouts() {
    var timeout = this.props.timeout;
    var exit, enter, appear;
    exit = enter = appear = timeout;

    if (timeout != null && typeof timeout !== 'number') {
      exit = timeout.exit;
      enter = timeout.enter; // TODO: remove fallback for next major

      appear = timeout.appear !== undefined ? timeout.appear : enter;
    }

    return {
      exit: exit,
      enter: enter,
      appear: appear
    };
  };

  _proto.updateStatus = function updateStatus(mounting, nextStatus) {
    if (mounting === void 0) {
      mounting = false;
    }

    if (nextStatus !== null) {
      // nextStatus will always be ENTERING or EXITING.
      this.cancelNextCallback();
      var node = react_dom_default.a.findDOMNode(this);

      if (nextStatus === ENTERING) {
        this.performEnter(node, mounting);
      } else {
        this.performExit(node);
      }
    } else if (this.props.unmountOnExit && this.state.status === EXITED) {
      this.setState({
        status: UNMOUNTED
      });
    }
  };

  _proto.performEnter = function performEnter(node, mounting) {
    var _this2 = this;

    var enter = this.props.enter;
    var appearing = this.context ? this.context.isMounting : mounting;
    var timeouts = this.getTimeouts();
    var enterTimeout = appearing ? timeouts.appear : timeouts.enter; // no enter animation skip right to ENTERED
    // if we are mounting and running this it means appear _must_ be set

    if (!mounting && !enter || esm_config.disabled) {
      this.safeSetState({
        status: ENTERED
      }, function () {
        _this2.props.onEntered(node);
      });
      return;
    }

    this.props.onEnter(node, appearing);
    this.safeSetState({
      status: ENTERING
    }, function () {
      _this2.props.onEntering(node, appearing);

      _this2.onTransitionEnd(node, enterTimeout, function () {
        _this2.safeSetState({
          status: ENTERED
        }, function () {
          _this2.props.onEntered(node, appearing);
        });
      });
    });
  };

  _proto.performExit = function performExit(node) {
    var _this3 = this;

    var exit = this.props.exit;
    var timeouts = this.getTimeouts(); // no exit animation skip right to EXITED

    if (!exit || esm_config.disabled) {
      this.safeSetState({
        status: EXITED
      }, function () {
        _this3.props.onExited(node);
      });
      return;
    }

    this.props.onExit(node);
    this.safeSetState({
      status: EXITING
    }, function () {
      _this3.props.onExiting(node);

      _this3.onTransitionEnd(node, timeouts.exit, function () {
        _this3.safeSetState({
          status: EXITED
        }, function () {
          _this3.props.onExited(node);
        });
      });
    });
  };

  _proto.cancelNextCallback = function cancelNextCallback() {
    if (this.nextCallback !== null) {
      this.nextCallback.cancel();
      this.nextCallback = null;
    }
  };

  _proto.safeSetState = function safeSetState(nextState, callback) {
    // This shouldn't be necessary, but there are weird race conditions with
    // setState callbacks and unmounting in testing, so always make sure that
    // we can cancel any pending setState callbacks after we unmount.
    callback = this.setNextCallback(callback);
    this.setState(nextState, callback);
  };

  _proto.setNextCallback = function setNextCallback(callback) {
    var _this4 = this;

    var active = true;

    this.nextCallback = function (event) {
      if (active) {
        active = false;
        _this4.nextCallback = null;
        callback(event);
      }
    };

    this.nextCallback.cancel = function () {
      active = false;
    };

    return this.nextCallback;
  };

  _proto.onTransitionEnd = function onTransitionEnd(node, timeout, handler) {
    this.setNextCallback(handler);
    var doesNotHaveTimeoutOrListener = timeout == null && !this.props.addEndListener;

    if (!node || doesNotHaveTimeoutOrListener) {
      setTimeout(this.nextCallback, 0);
      return;
    }

    if (this.props.addEndListener) {
      this.props.addEndListener(node, this.nextCallback);
    }

    if (timeout != null) {
      setTimeout(this.nextCallback, timeout);
    }
  };

  _proto.render = function render() {
    var status = this.state.status;

    if (status === UNMOUNTED) {
      return null;
    }

    var _this$props = this.props,
        children = _this$props.children,
        childProps = _objectWithoutPropertiesLoose(_this$props, ["children"]); // filter props for Transtition


    delete childProps.in;
    delete childProps.mountOnEnter;
    delete childProps.unmountOnExit;
    delete childProps.appear;
    delete childProps.enter;
    delete childProps.exit;
    delete childProps.timeout;
    delete childProps.addEndListener;
    delete childProps.onEnter;
    delete childProps.onEntering;
    delete childProps.onEntered;
    delete childProps.onExit;
    delete childProps.onExiting;
    delete childProps.onExited;

    if (typeof children === 'function') {
      // allows for nested Transitions
      return react_default.a.createElement(TransitionGroupContext.Provider, {
        value: null
      }, children(status, childProps));
    }

    var child = react_default.a.Children.only(children);
    return (// allows for nested Transitions
      react_default.a.createElement(TransitionGroupContext.Provider, {
        value: null
      }, react_default.a.cloneElement(child, childProps))
    );
  };

  return Transition;
}(react_default.a.Component);

Transition_Transition.contextType = TransitionGroupContext;
Transition_Transition.propTypes =  false ? undefined : {};

function noop() {}

Transition_Transition.defaultProps = {
  in: false,
  mountOnEnter: false,
  unmountOnExit: false,
  appear: false,
  enter: true,
  exit: true,
  onEnter: noop,
  onEntering: noop,
  onEntered: noop,
  onExit: noop,
  onExiting: noop,
  onExited: noop
};
Transition_Transition.UNMOUNTED = 0;
Transition_Transition.EXITED = 1;
Transition_Transition.ENTERING = 2;
Transition_Transition.ENTERED = 3;
Transition_Transition.EXITING = 4;
/* harmony default export */ var esm_Transition = (Transition_Transition);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/transitions/utils.js
var reflow = function reflow(node) {
  return node.scrollTop;
};
function getTransitionProps(props, options) {
  var timeout = props.timeout,
      _props$style = props.style,
      style = _props$style === void 0 ? {} : _props$style;
  return {
    duration: style.transitionDuration || typeof timeout === 'number' ? timeout : timeout[options.mode] || 0,
    delay: style.transitionDelay
  };
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Grow/Grow.js









function getScale(value) {
  return "scale(".concat(value, ", ").concat(Math.pow(value, 2), ")");
}

var Grow_styles = {
  entering: {
    opacity: 1,
    transform: getScale(1)
  },
  entered: {
    opacity: 1,
    transform: 'none'
  }
};
/**
 * The Grow transition is used by the [Tooltip](/components/tooltips/) and
 * [Popover](/components/popover/) components.
 * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.
 */

var Grow_Grow = react_default.a.forwardRef(function Grow(props, ref) {
  var children = props.children,
      inProp = props.in,
      onEnter = props.onEnter,
      onExit = props.onExit,
      style = props.style,
      _props$timeout = props.timeout,
      timeout = _props$timeout === void 0 ? 'auto' : _props$timeout,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["children", "in", "onEnter", "onExit", "style", "timeout"]);

  var timer = react_default.a.useRef();
  var autoTimeout = react_default.a.useRef();
  var handleRef = useForkRef(children.ref, ref);
  var theme = useTheme_useTheme();

  var handleEnter = function handleEnter(node, isAppearing) {
    reflow(node); // So the animation always start from the start.

    var _getTransitionProps = getTransitionProps({
      style: style,
      timeout: timeout
    }, {
      mode: 'enter'
    }),
        transitionDuration = _getTransitionProps.duration,
        delay = _getTransitionProps.delay;

    var duration;

    if (timeout === 'auto') {
      duration = theme.transitions.getAutoHeightDuration(node.clientHeight);
      autoTimeout.current = duration;
    } else {
      duration = transitionDuration;
    }

    node.style.transition = [theme.transitions.create('opacity', {
      duration: duration,
      delay: delay
    }), theme.transitions.create('transform', {
      duration: duration * 0.666,
      delay: delay
    })].join(',');

    if (onEnter) {
      onEnter(node, isAppearing);
    }
  };

  var handleExit = function handleExit(node) {
    var _getTransitionProps2 = getTransitionProps({
      style: style,
      timeout: timeout
    }, {
      mode: 'exit'
    }),
        transitionDuration = _getTransitionProps2.duration,
        delay = _getTransitionProps2.delay;

    var duration;

    if (timeout === 'auto') {
      duration = theme.transitions.getAutoHeightDuration(node.clientHeight);
      autoTimeout.current = duration;
    } else {
      duration = transitionDuration;
    }

    node.style.transition = [theme.transitions.create('opacity', {
      duration: duration,
      delay: delay
    }), theme.transitions.create('transform', {
      duration: duration * 0.666,
      delay: delay || duration * 0.333
    })].join(',');
    node.style.opacity = '0';
    node.style.transform = getScale(0.75);

    if (onExit) {
      onExit(node);
    }
  };

  var addEndListener = function addEndListener(_, next) {
    if (timeout === 'auto') {
      timer.current = setTimeout(next, autoTimeout.current || 0);
    }
  };

  react_default.a.useEffect(function () {
    return function () {
      clearTimeout(timer.current);
    };
  }, []);
  return react_default.a.createElement(esm_Transition, Object(helpers_esm_extends["a" /* default */])({
    appear: true,
    in: inProp,
    onEnter: handleEnter,
    onExit: handleExit,
    addEndListener: addEndListener,
    timeout: timeout === 'auto' ? null : timeout
  }, other), function (state, childProps) {
    return react_default.a.cloneElement(children, Object(helpers_esm_extends["a" /* default */])({
      style: Object(helpers_esm_extends["a" /* default */])({
        opacity: 0,
        transform: getScale(0.75),
        visibility: state === 'exited' && !inProp ? 'hidden' : undefined
      }, Grow_styles[state], {}, style, {}, children.props.style),
      ref: handleRef
    }, childProps));
  });
});
 false ? undefined : void 0;
Grow_Grow.muiSupportAuto = true;
/* harmony default export */ var esm_Grow_Grow = (Grow_Grow);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Paper/Paper.js






var Paper_styles = function styles(theme) {
  var elevations = {};
  theme.shadows.forEach(function (shadow, index) {
    elevations["elevation".concat(index)] = {
      boxShadow: shadow
    };
  });
  return Object(helpers_esm_extends["a" /* default */])({
    /* Styles applied to the root element. */
    root: {
      backgroundColor: theme.palette.background.paper,
      color: theme.palette.text.primary,
      transition: theme.transitions.create('box-shadow')
    },

    /* Styles applied to the root element if `square={false}`. */
    rounded: {
      borderRadius: theme.shape.borderRadius
    },

    /* Styles applied to the root element if `variant="outlined"` */
    outlined: {
      border: "1px solid ".concat(theme.palette.divider)
    }
  }, elevations);
};
var Paper_Paper = react_default.a.forwardRef(function Paper(props, ref) {
  var classes = props.classes,
      className = props.className,
      _props$component = props.component,
      Component = _props$component === void 0 ? 'div' : _props$component,
      _props$square = props.square,
      square = _props$square === void 0 ? false : _props$square,
      _props$elevation = props.elevation,
      elevation = _props$elevation === void 0 ? 1 : _props$elevation,
      _props$variant = props.variant,
      variant = _props$variant === void 0 ? 'elevation' : _props$variant,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["classes", "className", "component", "square", "elevation", "variant"]);

  if (false) {}

  return react_default.a.createElement(Component, Object(helpers_esm_extends["a" /* default */])({
    className: Object(clsx_m["a" /* default */])(classes.root, className, variant === 'outlined' ? classes.outlined : classes["elevation".concat(elevation)], !square && classes.rounded),
    ref: ref
  }, other));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_Paper_Paper = (Object(withStyles["a" /* default */])(Paper_styles, {
  name: 'MuiPaper'
})(Paper_Paper));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Popover/Popover.js















function getOffsetTop(rect, vertical) {
  var offset = 0;

  if (typeof vertical === 'number') {
    offset = vertical;
  } else if (vertical === 'center') {
    offset = rect.height / 2;
  } else if (vertical === 'bottom') {
    offset = rect.height;
  }

  return offset;
}
function getOffsetLeft(rect, horizontal) {
  var offset = 0;

  if (typeof horizontal === 'number') {
    offset = horizontal;
  } else if (horizontal === 'center') {
    offset = rect.width / 2;
  } else if (horizontal === 'right') {
    offset = rect.width;
  }

  return offset;
}

function getTransformOriginValue(transformOrigin) {
  return [transformOrigin.horizontal, transformOrigin.vertical].map(function (n) {
    return typeof n === 'number' ? "".concat(n, "px") : n;
  }).join(' ');
} // Sum the scrollTop between two elements.


function getScrollParent(parent, child) {
  var element = child;
  var scrollTop = 0;

  while (element && element !== parent) {
    element = element.parentElement;
    scrollTop += element.scrollTop;
  }

  return scrollTop;
}

function getAnchorEl(anchorEl) {
  return typeof anchorEl === 'function' ? anchorEl() : anchorEl;
}

var Popover_styles = {
  /* Styles applied to the root element */
  root: {},

  /* Styles applied to the `Paper` component. */
  paper: {
    position: 'absolute',
    overflowY: 'auto',
    overflowX: 'hidden',
    // So we see the popover when it's empty.
    // It's most likely on issue on userland.
    minWidth: 16,
    minHeight: 16,
    maxWidth: 'calc(100% - 32px)',
    maxHeight: 'calc(100% - 32px)',
    // We disable the focus ring for mouse, touch and keyboard users.
    outline: 0
  }
};
var Popover_Popover = react_default.a.forwardRef(function Popover(props, ref) {
  var action = props.action,
      anchorEl = props.anchorEl,
      _props$anchorOrigin = props.anchorOrigin,
      anchorOrigin = _props$anchorOrigin === void 0 ? {
    vertical: 'top',
    horizontal: 'left'
  } : _props$anchorOrigin,
      anchorPosition = props.anchorPosition,
      _props$anchorReferenc = props.anchorReference,
      anchorReference = _props$anchorReferenc === void 0 ? 'anchorEl' : _props$anchorReferenc,
      children = props.children,
      classes = props.classes,
      className = props.className,
      containerProp = props.container,
      _props$elevation = props.elevation,
      elevation = _props$elevation === void 0 ? 8 : _props$elevation,
      getContentAnchorEl = props.getContentAnchorEl,
      _props$marginThreshol = props.marginThreshold,
      marginThreshold = _props$marginThreshol === void 0 ? 16 : _props$marginThreshol,
      onEnter = props.onEnter,
      onEntered = props.onEntered,
      onEntering = props.onEntering,
      onExit = props.onExit,
      onExited = props.onExited,
      onExiting = props.onExiting,
      open = props.open,
      _props$PaperProps = props.PaperProps,
      PaperProps = _props$PaperProps === void 0 ? {} : _props$PaperProps,
      _props$transformOrigi = props.transformOrigin,
      transformOrigin = _props$transformOrigi === void 0 ? {
    vertical: 'top',
    horizontal: 'left'
  } : _props$transformOrigi,
      _props$TransitionComp = props.TransitionComponent,
      TransitionComponent = _props$TransitionComp === void 0 ? esm_Grow_Grow : _props$TransitionComp,
      _props$transitionDura = props.transitionDuration,
      transitionDurationProp = _props$transitionDura === void 0 ? 'auto' : _props$transitionDura,
      _props$TransitionProp = props.TransitionProps,
      TransitionProps = _props$TransitionProp === void 0 ? {} : _props$TransitionProp,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["action", "anchorEl", "anchorOrigin", "anchorPosition", "anchorReference", "children", "classes", "className", "container", "elevation", "getContentAnchorEl", "marginThreshold", "onEnter", "onEntered", "onEntering", "onExit", "onExited", "onExiting", "open", "PaperProps", "transformOrigin", "TransitionComponent", "transitionDuration", "TransitionProps"]);

  var paperRef = react_default.a.useRef(); // Returns the top/left offset of the position
  // to attach to on the anchor element (or body if none is provided)

  var getAnchorOffset = react_default.a.useCallback(function (contentAnchorOffset) {
    if (anchorReference === 'anchorPosition') {
      if (false) {}

      return anchorPosition;
    }

    var resolvedAnchorEl = getAnchorEl(anchorEl);
    var containerWindow = ownerWindow(resolvedAnchorEl); // If an anchor element wasn't provided, just use the parent body element of this Popover

    var anchorElement = resolvedAnchorEl instanceof containerWindow.Element ? resolvedAnchorEl : ownerDocument(paperRef.current).body;
    var anchorRect = anchorElement.getBoundingClientRect();

    if (false) { var box; }

    var anchorVertical = contentAnchorOffset === 0 ? anchorOrigin.vertical : 'center';
    return {
      top: anchorRect.top + getOffsetTop(anchorRect, anchorVertical),
      left: anchorRect.left + getOffsetLeft(anchorRect, anchorOrigin.horizontal)
    };
  }, [anchorEl, anchorOrigin.horizontal, anchorOrigin.vertical, anchorPosition, anchorReference]); // Returns the vertical offset of inner content to anchor the transform on if provided

  var getContentAnchorOffset = react_default.a.useCallback(function (element) {
    var contentAnchorOffset = 0;

    if (getContentAnchorEl && anchorReference === 'anchorEl') {
      var contentAnchorEl = getContentAnchorEl(element);

      if (contentAnchorEl && element.contains(contentAnchorEl)) {
        var scrollTop = getScrollParent(element, contentAnchorEl);
        contentAnchorOffset = contentAnchorEl.offsetTop + contentAnchorEl.clientHeight / 2 - scrollTop || 0;
      } // != the default value


      if (false) {}
    }

    return contentAnchorOffset;
  }, [anchorOrigin.vertical, anchorReference, getContentAnchorEl]); // Return the base transform origin using the element
  // and taking the content anchor offset into account if in use

  var getTransformOrigin = react_default.a.useCallback(function (elemRect) {
    var contentAnchorOffset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
    return {
      vertical: getOffsetTop(elemRect, transformOrigin.vertical) + contentAnchorOffset,
      horizontal: getOffsetLeft(elemRect, transformOrigin.horizontal)
    };
  }, [transformOrigin.horizontal, transformOrigin.vertical]);
  var getPositioningStyle = react_default.a.useCallback(function (element) {
    // Check if the parent has requested anchoring on an inner content node
    var contentAnchorOffset = getContentAnchorOffset(element);
    var elemRect = {
      width: element.offsetWidth,
      height: element.offsetHeight
    }; // Get the transform origin point on the element itself

    var elemTransformOrigin = getTransformOrigin(elemRect, contentAnchorOffset);

    if (anchorReference === 'none') {
      return {
        top: null,
        left: null,
        transformOrigin: getTransformOriginValue(elemTransformOrigin)
      };
    } // Get the offset of of the anchoring element


    var anchorOffset = getAnchorOffset(contentAnchorOffset); // Calculate element positioning

    var top = anchorOffset.top - elemTransformOrigin.vertical;
    var left = anchorOffset.left - elemTransformOrigin.horizontal;
    var bottom = top + elemRect.height;
    var right = left + elemRect.width; // Use the parent window of the anchorEl if provided

    var containerWindow = ownerWindow(getAnchorEl(anchorEl)); // Window thresholds taking required margin into account

    var heightThreshold = containerWindow.innerHeight - marginThreshold;
    var widthThreshold = containerWindow.innerWidth - marginThreshold; // Check if the vertical axis needs shifting

    if (top < marginThreshold) {
      var diff = top - marginThreshold;
      top -= diff;
      elemTransformOrigin.vertical += diff;
    } else if (bottom > heightThreshold) {
      var _diff = bottom - heightThreshold;

      top -= _diff;
      elemTransformOrigin.vertical += _diff;
    }

    if (false) {} // Check if the horizontal axis needs shifting


    if (left < marginThreshold) {
      var _diff2 = left - marginThreshold;

      left -= _diff2;
      elemTransformOrigin.horizontal += _diff2;
    } else if (right > widthThreshold) {
      var _diff3 = right - widthThreshold;

      left -= _diff3;
      elemTransformOrigin.horizontal += _diff3;
    }

    return {
      top: "".concat(Math.round(top), "px"),
      left: "".concat(Math.round(left), "px"),
      transformOrigin: getTransformOriginValue(elemTransformOrigin)
    };
  }, [anchorEl, anchorReference, getAnchorOffset, getContentAnchorOffset, getTransformOrigin, marginThreshold]);
  var setPositioningStyles = react_default.a.useCallback(function () {
    var element = paperRef.current;

    if (!element) {
      return;
    }

    var positioning = getPositioningStyle(element);

    if (positioning.top !== null) {
      element.style.top = positioning.top;
    }

    if (positioning.left !== null) {
      element.style.left = positioning.left;
    }

    element.style.transformOrigin = positioning.transformOrigin;
  }, [getPositioningStyle]);

  var handleEntering = function handleEntering(element, isAppearing) {
    if (onEntering) {
      onEntering(element, isAppearing);
    }

    setPositioningStyles();
  };

  var handlePaperRef = react_default.a.useCallback(function (instance) {
    // #StrictMode ready
    paperRef.current = react_dom_default.a.findDOMNode(instance);
  }, []);
  react_default.a.useEffect(function () {
    if (open) {
      setPositioningStyles();
    }
  });
  react_default.a.useImperativeHandle(action, function () {
    return open ? {
      updatePosition: function updatePosition() {
        setPositioningStyles();
      }
    } : null;
  }, [open, setPositioningStyles]);
  react_default.a.useEffect(function () {
    if (!open) {
      return undefined;
    }

    var handleResize = debounce(function () {
      setPositioningStyles();
    });
    window.addEventListener('resize', handleResize);
    return function () {
      handleResize.clear();
      window.removeEventListener('rezise', handleResize);
    };
  }, [open, setPositioningStyles]);
  var transitionDuration = transitionDurationProp;

  if (transitionDurationProp === 'auto' && !TransitionComponent.muiSupportAuto) {
    transitionDuration = undefined;
  } // If the container prop is provided, use that
  // If the anchorEl prop is provided, use its parent body element as the container
  // If neither are provided let the Modal take care of choosing the container


  var container = containerProp || (anchorEl ? ownerDocument(getAnchorEl(anchorEl)).body : undefined);
  return react_default.a.createElement(esm_Modal_Modal, Object(helpers_esm_extends["a" /* default */])({
    container: container,
    open: open,
    ref: ref,
    BackdropProps: {
      invisible: true
    },
    className: Object(clsx_m["a" /* default */])(classes.root, className)
  }, other), react_default.a.createElement(TransitionComponent, Object(helpers_esm_extends["a" /* default */])({
    appear: true,
    in: open,
    onEnter: onEnter,
    onEntered: onEntered,
    onExit: onExit,
    onExited: onExited,
    onExiting: onExiting,
    timeout: transitionDuration
  }, TransitionProps, {
    onEntering: createChainedFunction(handleEntering, TransitionProps.onEntering)
  }), react_default.a.createElement(esm_Paper_Paper, Object(helpers_esm_extends["a" /* default */])({
    elevation: elevation,
    ref: handlePaperRef
  }, PaperProps, {
    className: Object(clsx_m["a" /* default */])(classes.paper, PaperProps.className)
  }), children)));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_Popover_Popover = (Object(withStyles["a" /* default */])(Popover_styles, {
  name: 'MuiPopover'
})(Popover_Popover));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/List/ListContext.js

/**
 * @ignore - internal component.
 */

var ListContext = react_default.a.createContext({});

if (false) {}

/* harmony default export */ var List_ListContext = (ListContext);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/List/List.js







var List_styles = {
  /* Styles applied to the root element. */
  root: {
    listStyle: 'none',
    margin: 0,
    padding: 0,
    position: 'relative'
  },

  /* Styles applied to the root element if `disablePadding={false}`. */
  padding: {
    paddingTop: 8,
    paddingBottom: 8
  },

  /* Styles applied to the root element if dense. */
  dense: {},

  /* Styles applied to the root element if a `subheader` is provided. */
  subheader: {
    paddingTop: 0
  }
};
var List_List = react_default.a.forwardRef(function List(props, ref) {
  var children = props.children,
      classes = props.classes,
      className = props.className,
      _props$component = props.component,
      Component = _props$component === void 0 ? 'ul' : _props$component,
      _props$dense = props.dense,
      dense = _props$dense === void 0 ? false : _props$dense,
      _props$disablePadding = props.disablePadding,
      disablePadding = _props$disablePadding === void 0 ? false : _props$disablePadding,
      subheader = props.subheader,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["children", "classes", "className", "component", "dense", "disablePadding", "subheader"]);

  var context = react_default.a.useMemo(function () {
    return {
      dense: dense
    };
  }, [dense]);
  return react_default.a.createElement(List_ListContext.Provider, {
    value: context
  }, react_default.a.createElement(Component, Object(helpers_esm_extends["a" /* default */])({
    className: Object(clsx_m["a" /* default */])(classes.root, className, dense && classes.dense, !disablePadding && classes.padding, subheader && classes.subheader),
    ref: ref
  }, other), subheader, children));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_List_List = (Object(withStyles["a" /* default */])(List_styles, {
  name: 'MuiList'
})(List_List));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/MenuList/MenuList.js











function nextItem(list, item, disableListWrap) {
  if (list === item) {
    return list.firstChild;
  }

  if (item && item.nextElementSibling) {
    return item.nextElementSibling;
  }

  return disableListWrap ? null : list.firstChild;
}

function previousItem(list, item, disableListWrap) {
  if (list === item) {
    return disableListWrap ? list.firstChild : list.lastChild;
  }

  if (item && item.previousElementSibling) {
    return item.previousElementSibling;
  }

  return disableListWrap ? null : list.lastChild;
}

function textCriteriaMatches(nextFocus, textCriteria) {
  if (textCriteria === undefined) {
    return true;
  }

  var text = nextFocus.innerText;

  if (text === undefined) {
    // jsdom doesn't support innerText
    text = nextFocus.textContent;
  }

  text = text.trim().toLowerCase();

  if (text.length === 0) {
    return false;
  }

  if (textCriteria.repeating) {
    return text[0] === textCriteria.keys[0];
  }

  return text.indexOf(textCriteria.keys.join('')) === 0;
}

function moveFocus(list, currentFocus, disableListWrap, traversalFunction, textCriteria) {
  var wrappedOnce = false;
  var nextFocus = traversalFunction(list, currentFocus, currentFocus ? disableListWrap : false);

  while (nextFocus) {
    // Prevent infinite loop.
    if (nextFocus === list.firstChild) {
      if (wrappedOnce) {
        return false;
      }

      wrappedOnce = true;
    } // Move to the next element.


    if (!nextFocus.hasAttribute('tabindex') || nextFocus.disabled || nextFocus.getAttribute('aria-disabled') === 'true' || !textCriteriaMatches(nextFocus, textCriteria)) {
      nextFocus = traversalFunction(list, nextFocus, disableListWrap);
    } else {
      nextFocus.focus();
      return true;
    }
  }

  return false;
}

var MenuList_useEnhancedEffect = typeof window === 'undefined' ? react_default.a.useEffect : react_default.a.useLayoutEffect;
/**
 * A permanently displayed menu following https://www.w3.org/TR/wai-aria-practices/#menubutton
 * It's exposed to help customization of the [`Menu`](/api/menu/) component. If you
 * use it separately you need to move focus into the component manually. Once
 * the focus is placed inside the component it is fully keyboard accessible.
 */

var MenuList_MenuList = react_default.a.forwardRef(function MenuList(props, ref) {
  var actions = props.actions,
      _props$autoFocus = props.autoFocus,
      autoFocus = _props$autoFocus === void 0 ? false : _props$autoFocus,
      _props$autoFocusItem = props.autoFocusItem,
      autoFocusItem = _props$autoFocusItem === void 0 ? false : _props$autoFocusItem,
      children = props.children,
      className = props.className,
      onKeyDown = props.onKeyDown,
      _props$disableListWra = props.disableListWrap,
      disableListWrap = _props$disableListWra === void 0 ? false : _props$disableListWra,
      _props$variant = props.variant,
      variant = _props$variant === void 0 ? 'selectedMenu' : _props$variant,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["actions", "autoFocus", "autoFocusItem", "children", "className", "onKeyDown", "disableListWrap", "variant"]);

  var listRef = react_default.a.useRef(null);
  var textCriteriaRef = react_default.a.useRef({
    keys: [],
    repeating: true,
    previousKeyMatched: true,
    lastTime: null
  });
  MenuList_useEnhancedEffect(function () {
    if (autoFocus) {
      listRef.current.focus();
    }
  }, [autoFocus]);
  react_default.a.useImperativeHandle(actions, function () {
    return {
      adjustStyleForScrollbar: function adjustStyleForScrollbar(containerElement, theme) {
        // Let's ignore that piece of logic if users are already overriding the width
        // of the menu.
        var noExplicitWidth = !listRef.current.style.width;

        if (containerElement.clientHeight < listRef.current.clientHeight && noExplicitWidth) {
          var scrollbarSize = "".concat(getScrollbarSize(true), "px");
          listRef.current.style[theme.direction === 'rtl' ? 'paddingLeft' : 'paddingRight'] = scrollbarSize;
          listRef.current.style.width = "calc(100% + ".concat(scrollbarSize, ")");
        }

        return listRef.current;
      }
    };
  }, []);

  var handleKeyDown = function handleKeyDown(event) {
    var list = listRef.current;
    var key = event.key;
    /**
     * @type {Element} - will always be defined since we are in a keydown handler
     * attached to an element. A keydown event is either dispatched to the activeElement
     * or document.body or document.documentElement. Only the first case will
     * trigger this specific handler.
     */

    var currentFocus = ownerDocument(list).activeElement;

    if (key === 'ArrowDown') {
      // Prevent scroll of the page
      event.preventDefault();
      moveFocus(list, currentFocus, disableListWrap, nextItem);
    } else if (key === 'ArrowUp') {
      event.preventDefault();
      moveFocus(list, currentFocus, disableListWrap, previousItem);
    } else if (key === 'Home') {
      event.preventDefault();
      moveFocus(list, null, disableListWrap, nextItem);
    } else if (key === 'End') {
      event.preventDefault();
      moveFocus(list, null, disableListWrap, previousItem);
    } else if (key.length === 1) {
      var criteria = textCriteriaRef.current;
      var lowerKey = key.toLowerCase();
      var currTime = performance.now();

      if (criteria.keys.length > 0) {
        // Reset
        if (currTime - criteria.lastTime > 500) {
          criteria.keys = [];
          criteria.repeating = true;
          criteria.previousKeyMatched = true;
        } else if (criteria.repeating && lowerKey !== criteria.keys[0]) {
          criteria.repeating = false;
        }
      }

      criteria.lastTime = currTime;
      criteria.keys.push(lowerKey);
      var keepFocusOnCurrent = currentFocus && !criteria.repeating && textCriteriaMatches(currentFocus, criteria);

      if (criteria.previousKeyMatched && (keepFocusOnCurrent || moveFocus(list, currentFocus, false, nextItem, criteria))) {
        event.preventDefault();
      } else {
        criteria.previousKeyMatched = false;
      }
    }

    if (onKeyDown) {
      onKeyDown(event);
    }
  };

  var handleOwnRef = react_default.a.useCallback(function (instance) {
    // #StrictMode ready
    listRef.current = react_dom_default.a.findDOMNode(instance);
  }, []);
  var handleRef = useForkRef(handleOwnRef, ref);
  /**
   * the index of the item should receive focus
   * in a `variant="selectedMenu"` it's the first `selected` item
   * otherwise it's the very first item.
   */

  var activeItemIndex = -1; // since we inject focus related props into children we have to do a lookahead
  // to check if there is a `selected` item. We're looking for the last `selected`
  // item and use the first valid item as a fallback

  react_default.a.Children.forEach(children, function (child, index) {
    if (!react_default.a.isValidElement(child)) {
      return;
    }

    if (false) {}

    if (!child.props.disabled) {
      if (variant === 'selectedMenu' && child.props.selected) {
        activeItemIndex = index;
      } else if (activeItemIndex === -1) {
        activeItemIndex = index;
      }
    }
  });
  var items = react_default.a.Children.map(children, function (child, index) {
    if (index === activeItemIndex) {
      var newChildProps = {};

      if (autoFocusItem) {
        newChildProps.autoFocus = true;
      }

      if (child.props.tabIndex === undefined && variant === 'selectedMenu') {
        newChildProps.tabIndex = 0;
      }

      if (newChildProps !== null) {
        return react_default.a.cloneElement(child, newChildProps);
      }
    }

    return child;
  });
  return react_default.a.createElement(esm_List_List, Object(helpers_esm_extends["a" /* default */])({
    role: "menu",
    ref: handleRef,
    className: className,
    onKeyDown: handleKeyDown,
    tabIndex: autoFocus ? 0 : -1
  }, other), items);
});
 false ? undefined : void 0;
/* harmony default export */ var esm_MenuList_MenuList = (MenuList_MenuList);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Menu/Menu.js












var RTL_ORIGIN = {
  vertical: 'top',
  horizontal: 'right'
};
var LTR_ORIGIN = {
  vertical: 'top',
  horizontal: 'left'
};
var Menu_styles = {
  /* Styles applied to the `Paper` component. */
  paper: {
    // specZ: The maximum height of a simple menu should be one or more rows less than the view
    // height. This ensures a tapable area outside of the simple menu with which to dismiss
    // the menu.
    maxHeight: 'calc(100% - 96px)',
    // Add iOS momentum scrolling.
    WebkitOverflowScrolling: 'touch'
  },

  /* Styles applied to the `List` component via `MenuList`. */
  list: {
    // We disable the focus ring for mouse, touch and keyboard users.
    outline: 0
  }
};
var Menu_Menu = react_default.a.forwardRef(function Menu(props, ref) {
  var _props$autoFocus = props.autoFocus,
      autoFocus = _props$autoFocus === void 0 ? true : _props$autoFocus,
      children = props.children,
      classes = props.classes,
      _props$disableAutoFoc = props.disableAutoFocusItem,
      disableAutoFocusItem = _props$disableAutoFoc === void 0 ? false : _props$disableAutoFoc,
      _props$MenuListProps = props.MenuListProps,
      MenuListProps = _props$MenuListProps === void 0 ? {} : _props$MenuListProps,
      onClose = props.onClose,
      onEntering = props.onEntering,
      open = props.open,
      _props$PaperProps = props.PaperProps,
      PaperProps = _props$PaperProps === void 0 ? {} : _props$PaperProps,
      PopoverClasses = props.PopoverClasses,
      _props$transitionDura = props.transitionDuration,
      transitionDuration = _props$transitionDura === void 0 ? 'auto' : _props$transitionDura,
      _props$variant = props.variant,
      variant = _props$variant === void 0 ? 'selectedMenu' : _props$variant,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["autoFocus", "children", "classes", "disableAutoFocusItem", "MenuListProps", "onClose", "onEntering", "open", "PaperProps", "PopoverClasses", "transitionDuration", "variant"]);

  var theme = useTheme_useTheme();
  var autoFocusItem = autoFocus && !disableAutoFocusItem && open;
  var menuListActionsRef = react_default.a.useRef(null);
  var contentAnchorRef = react_default.a.useRef(null);

  var getContentAnchorEl = function getContentAnchorEl() {
    return contentAnchorRef.current;
  };

  var handleEntering = function handleEntering(element, isAppearing) {
    if (menuListActionsRef.current) {
      menuListActionsRef.current.adjustStyleForScrollbar(element, theme);
    }

    if (onEntering) {
      onEntering(element, isAppearing);
    }
  };

  var handleListKeyDown = function handleListKeyDown(event) {
    if (event.key === 'Tab') {
      event.preventDefault();

      if (onClose) {
        onClose(event, 'tabKeyDown');
      }
    }
  };
  /**
   * the index of the item should receive focus
   * in a `variant="selectedMenu"` it's the first `selected` item
   * otherwise it's the very first item.
   */


  var activeItemIndex = -1; // since we inject focus related props into children we have to do a lookahead
  // to check if there is a `selected` item. We're looking for the last `selected`
  // item and use the first valid item as a fallback

  react_default.a.Children.map(children, function (child, index) {
    if (!react_default.a.isValidElement(child)) {
      return;
    }

    if (false) {}

    if (!child.props.disabled) {
      if (variant !== "menu" && child.props.selected) {
        activeItemIndex = index;
      } else if (activeItemIndex === -1) {
        activeItemIndex = index;
      }
    }
  });
  var items = react_default.a.Children.map(children, function (child, index) {
    if (index === activeItemIndex) {
      return react_default.a.cloneElement(child, {
        ref: function ref(instance) {
          // #StrictMode ready
          contentAnchorRef.current = react_dom_default.a.findDOMNode(instance);
          setRef(child.ref, instance);
        }
      });
    }

    return child;
  });
  return react_default.a.createElement(esm_Popover_Popover, Object(helpers_esm_extends["a" /* default */])({
    getContentAnchorEl: getContentAnchorEl,
    classes: PopoverClasses,
    onClose: onClose,
    onEntering: handleEntering,
    anchorOrigin: theme.direction === 'rtl' ? RTL_ORIGIN : LTR_ORIGIN,
    transformOrigin: theme.direction === 'rtl' ? RTL_ORIGIN : LTR_ORIGIN,
    PaperProps: Object(helpers_esm_extends["a" /* default */])({}, PaperProps, {
      classes: Object(helpers_esm_extends["a" /* default */])({}, PaperProps.classes, {
        root: classes.paper
      })
    }),
    open: open,
    ref: ref,
    transitionDuration: transitionDuration
  }, other), react_default.a.createElement(esm_MenuList_MenuList, Object(helpers_esm_extends["a" /* default */])({
    onKeyDown: handleListKeyDown,
    actions: menuListActionsRef,
    autoFocus: autoFocus && (activeItemIndex === -1 || disableAutoFocusItem),
    autoFocusItem: autoFocusItem,
    variant: variant
  }, MenuListProps, {
    className: Object(clsx_m["a" /* default */])(classes.list, MenuListProps.className)
  }), items));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_Menu_Menu = (Object(withStyles["a" /* default */])(Menu_styles, {
  name: 'MuiMenu'
})(Menu_Menu));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/utils/useControlled.js
/* eslint-disable react-hooks/rules-of-hooks, react-hooks/exhaustive-deps */

function useControlled(_ref) {
  var controlled = _ref.controlled,
      defaultProp = _ref.default,
      name = _ref.name;

  var _React$useRef = react_default.a.useRef(controlled !== undefined),
      isControlled = _React$useRef.current;

  var _React$useState = react_default.a.useState(defaultProp),
      valueState = _React$useState[0],
      setValue = _React$useState[1];

  var value = isControlled ? controlled : valueState;

  if (false) { var _React$useRef2, defaultValue; }

  var setValueIfUncontrolled = react_default.a.useCallback(function (newValue) {
    if (!isControlled) {
      setValue(newValue);
    }
  }, []);
  return [value, setValueIfUncontrolled];
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Select/SelectInput.js
















function areEqualValues(a, b) {
  if (Object(esm_typeof["a" /* default */])(b) === 'object' && b !== null) {
    return a === b;
  }

  return String(a) === String(b);
}

function isEmpty(display) {
  return display == null || typeof display === 'string' && !display.trim();
}
/**
 * @ignore - internal component.
 */


var SelectInput_SelectInput = react_default.a.forwardRef(function SelectInput(props, ref) {
  var autoFocus = props.autoFocus,
      autoWidth = props.autoWidth,
      children = props.children,
      classes = props.classes,
      className = props.className,
      defaultValue = props.defaultValue,
      disabled = props.disabled,
      displayEmpty = props.displayEmpty,
      IconComponent = props.IconComponent,
      inputRefProp = props.inputRef,
      labelId = props.labelId,
      _props$MenuProps = props.MenuProps,
      MenuProps = _props$MenuProps === void 0 ? {} : _props$MenuProps,
      multiple = props.multiple,
      name = props.name,
      onBlur = props.onBlur,
      onChange = props.onChange,
      onClose = props.onClose,
      onFocus = props.onFocus,
      onOpen = props.onOpen,
      openProp = props.open,
      readOnly = props.readOnly,
      renderValue = props.renderValue,
      required = props.required,
      _props$SelectDisplayP = props.SelectDisplayProps,
      SelectDisplayProps = _props$SelectDisplayP === void 0 ? {} : _props$SelectDisplayP,
      tabIndexProp = props.tabIndex,
      type = props.type,
      valueProp = props.value,
      _props$variant = props.variant,
      variant = _props$variant === void 0 ? 'standard' : _props$variant,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["autoFocus", "autoWidth", "children", "classes", "className", "defaultValue", "disabled", "displayEmpty", "IconComponent", "inputRef", "labelId", "MenuProps", "multiple", "name", "onBlur", "onChange", "onClose", "onFocus", "onOpen", "open", "readOnly", "renderValue", "required", "SelectDisplayProps", "tabIndex", "type", "value", "variant"]);

  var _useControlled = useControlled({
    controlled: valueProp,
    default: defaultValue,
    name: 'SelectInput'
  }),
      _useControlled2 = _slicedToArray(_useControlled, 2),
      value = _useControlled2[0],
      setValue = _useControlled2[1];

  var inputRef = react_default.a.useRef(null);

  var _React$useState = react_default.a.useState(null),
      displayNode = _React$useState[0],
      setDisplayNode = _React$useState[1];

  var _React$useRef = react_default.a.useRef(openProp != null),
      isOpenControlled = _React$useRef.current;

  var _React$useState2 = react_default.a.useState(),
      menuMinWidthState = _React$useState2[0],
      setMenuMinWidthState = _React$useState2[1];

  var _React$useState3 = react_default.a.useState(false),
      openState = _React$useState3[0],
      setOpenState = _React$useState3[1];

  var handleRef = useForkRef(ref, inputRefProp);
  react_default.a.useImperativeHandle(handleRef, function () {
    return {
      focus: function focus() {
        displayNode.focus();
      },
      node: inputRef.current,
      value: value
    };
  }, [displayNode, value]);
  react_default.a.useEffect(function () {
    if (autoFocus && displayNode) {
      displayNode.focus();
    }
  }, [autoFocus, displayNode]);

  var update = function update(open, event) {
    if (open) {
      if (onOpen) {
        onOpen(event);
      }
    } else if (onClose) {
      onClose(event);
    }

    if (!isOpenControlled) {
      setMenuMinWidthState(autoWidth ? null : displayNode.clientWidth);
      setOpenState(open);
    }
  };

  var handleMouseDown = function handleMouseDown(event) {
    // Ignore everything but left-click
    if (event.button !== 0) {
      return;
    } // Hijack the default focus behavior.


    event.preventDefault();
    displayNode.focus();
    update(true, event);
  };

  var handleClose = function handleClose(event) {
    update(false, event);
  };

  var handleItemClick = function handleItemClick(child) {
    return function (event) {
      if (!multiple) {
        update(false, event);
      }

      var newValue;

      if (multiple) {
        newValue = Array.isArray(value) ? _toConsumableArray(value) : [];
        var itemIndex = value.indexOf(child.props.value);

        if (itemIndex === -1) {
          newValue.push(child.props.value);
        } else {
          newValue.splice(itemIndex, 1);
        }
      } else {
        newValue = child.props.value;
      }

      setValue(newValue);

      if (onChange) {
        event.persist(); // Preact support, target is read only property on a native event.

        Object.defineProperty(event, 'target', {
          writable: true,
          value: {
            value: newValue,
            name: name
          }
        });
        onChange(event, child);
      }
    };
  };

  var handleKeyDown = function handleKeyDown(event) {
    if (!readOnly) {
      var validKeys = [' ', 'ArrowUp', 'ArrowDown', // The native select doesn't respond to enter on MacOS, but it's recommended by
      // https://www.w3.org/TR/wai-aria-practices/examples/listbox/listbox-collapsible.html
      'Enter'];

      if (validKeys.indexOf(event.key) !== -1) {
        event.preventDefault();
        update(true, event);
      }
    }
  };

  var open = displayNode !== null && (isOpenControlled ? openProp : openState);

  var handleBlur = function handleBlur(event) {
    // if open event.stopImmediatePropagation
    if (!open && onBlur) {
      event.persist(); // Preact support, target is read only property on a native event.

      Object.defineProperty(event, 'target', {
        writable: true,
        value: {
          value: value,
          name: name
        }
      });
      onBlur(event);
    }
  };

  delete other['aria-invalid'];
  var display;
  var displaySingle;
  var displayMultiple = [];
  var computeDisplay = false;
  var foundMatch = false; // No need to display any value if the field is empty.

  if (isFilled({
    value: value
  }) || displayEmpty) {
    if (renderValue) {
      display = renderValue(value);
    } else {
      computeDisplay = true;
    }
  }

  var items = react_default.a.Children.map(children, function (child) {
    if (!react_default.a.isValidElement(child)) {
      return null;
    }

    if (false) {}

    var selected;

    if (multiple) {
      if (!Array.isArray(value)) {
        throw new Error('Material-UI: the `value` prop must be an array ' + 'when using the `Select` component with `multiple`.');
      }

      selected = value.some(function (v) {
        return areEqualValues(v, child.props.value);
      });

      if (selected && computeDisplay) {
        displayMultiple.push(child.props.children);
      }
    } else {
      selected = areEqualValues(value, child.props.value);

      if (selected && computeDisplay) {
        displaySingle = child.props.children;
      }
    }

    if (selected) {
      foundMatch = true;
    }

    return react_default.a.cloneElement(child, {
      'aria-selected': selected ? 'true' : undefined,
      onClick: handleItemClick(child),
      onKeyUp: function onKeyUp(event) {
        if (event.key === ' ') {
          // otherwise our MenuItems dispatches a click event
          // it's not behavior of the native <option> and causes
          // the select to close immediately since we open on space keydown
          event.preventDefault();
        }

        var onKeyUp = child.props.onKeyUp;

        if (typeof onKeyUp === 'function') {
          onKeyUp(event);
        }
      },
      role: 'option',
      selected: selected,
      value: undefined,
      // The value is most likely not a valid HTML attribute.
      'data-value': child.props.value // Instead, we provide it as a data attribute.

    });
  });

  if (false) {}

  if (computeDisplay) {
    display = multiple ? displayMultiple.join(', ') : displaySingle;
  } // Avoid performing a layout computation in the render method.


  var menuMinWidth = menuMinWidthState;

  if (!autoWidth && isOpenControlled && displayNode) {
    menuMinWidth = displayNode.clientWidth;
  }

  var tabIndex;

  if (typeof tabIndexProp !== 'undefined') {
    tabIndex = tabIndexProp;
  } else {
    tabIndex = disabled ? null : 0;
  }

  var buttonId = SelectDisplayProps.id || (name ? "mui-component-select-".concat(name) : undefined);
  return react_default.a.createElement(react_default.a.Fragment, null, react_default.a.createElement("div", Object(helpers_esm_extends["a" /* default */])({
    className: Object(clsx_m["a" /* default */])(classes.root, // TODO v5: merge root and select
    classes.select, classes.selectMenu, classes[variant], className, disabled && classes.disabled),
    ref: setDisplayNode,
    tabIndex: tabIndex,
    role: "button",
    "aria-expanded": open ? 'true' : undefined,
    "aria-labelledby": "".concat(labelId || '', " ").concat(buttonId || ''),
    "aria-haspopup": "listbox",
    onKeyDown: handleKeyDown,
    onMouseDown: disabled || readOnly ? null : handleMouseDown,
    onBlur: handleBlur,
    onFocus: onFocus
  }, SelectDisplayProps, {
    // The id is required for proper a11y
    id: buttonId
  }), isEmpty(display) ? // eslint-disable-next-line react/no-danger
  react_default.a.createElement("span", {
    dangerouslySetInnerHTML: {
      __html: '&#8203;'
    }
  }) : display), react_default.a.createElement("input", Object(helpers_esm_extends["a" /* default */])({
    value: Array.isArray(value) ? value.join(',') : value,
    name: name,
    ref: inputRef,
    type: "hidden",
    autoFocus: autoFocus
  }, other)), react_default.a.createElement(IconComponent, {
    className: Object(clsx_m["a" /* default */])(classes.icon, classes["icon".concat(Object(capitalize["a" /* default */])(variant))], open && classes.iconOpen)
  }), react_default.a.createElement(esm_Menu_Menu, Object(helpers_esm_extends["a" /* default */])({
    id: "menu-".concat(name || ''),
    anchorEl: displayNode,
    open: open,
    onClose: handleClose
  }, MenuProps, {
    MenuListProps: Object(helpers_esm_extends["a" /* default */])({
      'aria-labelledby': labelId,
      role: 'listbox',
      disableListWrap: true
    }, MenuProps.MenuListProps),
    PaperProps: Object(helpers_esm_extends["a" /* default */])({}, MenuProps.PaperProps, {
      style: Object(helpers_esm_extends["a" /* default */])({
        minWidth: menuMinWidth
      }, MenuProps.PaperProps != null ? MenuProps.PaperProps.style : null)
    })
  }), items));
});
 false ? undefined : void 0;
/* harmony default export */ var Select_SelectInput = (SelectInput_SelectInput);
// EXTERNAL MODULE: ./node_modules/@material-ui/core/esm/SvgIcon/SvgIcon.js
var SvgIcon = __webpack_require__(63);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/internal/svg-icons/createSvgIcon.js



function createSvgIcon(path, displayName) {
  var Component = react_default.a.memo(react_default.a.forwardRef(function (props, ref) {
    return react_default.a.createElement(SvgIcon["a" /* default */], Object(helpers_esm_extends["a" /* default */])({}, props, {
      ref: ref
    }), path);
  }));

  if (false) {}

  Component.muiName = SvgIcon["a" /* default */].muiName;
  return Component;
}
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/internal/svg-icons/ArrowDropDown.js


/**
 * @ignore - internal component.
 */

/* harmony default export */ var ArrowDropDown = (createSvgIcon(react_default.a.createElement("path", {
  d: "M7 10l5 5 5-5z"
}), 'ArrowDropDown'));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/TextareaAutosize/TextareaAutosize.js







function getStyleValue(computedStyle, property) {
  return parseInt(computedStyle[property], 10) || 0;
}

var TextareaAutosize_useEnhancedEffect = typeof window !== 'undefined' ? react_default.a.useLayoutEffect : react_default.a.useEffect;
var TextareaAutosize_styles = {
  /* Styles applied to the shadow textarea element. */
  shadow: {
    // Visibility needed to hide the extra text area on iPads
    visibility: 'hidden',
    // Remove from the content flow
    position: 'absolute',
    // Ignore the scrollbar width
    overflow: 'hidden',
    height: 0,
    top: 0,
    left: 0,
    // Create a new layer, increase the isolation of the computed values
    transform: 'translateZ(0)'
  }
};
var TextareaAutosize_TextareaAutosize = react_default.a.forwardRef(function TextareaAutosize(props, ref) {
  var onChange = props.onChange,
      rows = props.rows,
      rowsMax = props.rowsMax,
      _props$rowsMin = props.rowsMin,
      rowsMinProp = _props$rowsMin === void 0 ? 1 : _props$rowsMin,
      style = props.style,
      value = props.value,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["onChange", "rows", "rowsMax", "rowsMin", "style", "value"]);

  var rowsMin = rows || rowsMinProp;

  var _React$useRef = react_default.a.useRef(value != null),
      isControlled = _React$useRef.current;

  var inputRef = react_default.a.useRef(null);
  var handleRef = useForkRef(ref, inputRef);
  var shadowRef = react_default.a.useRef(null);

  var _React$useState = react_default.a.useState({}),
      state = _React$useState[0],
      setState = _React$useState[1];

  var syncHeight = react_default.a.useCallback(function () {
    var input = inputRef.current;
    var computedStyle = window.getComputedStyle(input);
    var inputShallow = shadowRef.current;
    inputShallow.style.width = computedStyle.width;
    inputShallow.value = input.value || props.placeholder || 'x';
    var boxSizing = computedStyle['box-sizing'];
    var padding = getStyleValue(computedStyle, 'padding-bottom') + getStyleValue(computedStyle, 'padding-top');
    var border = getStyleValue(computedStyle, 'border-bottom-width') + getStyleValue(computedStyle, 'border-top-width'); // The height of the inner content

    var innerHeight = inputShallow.scrollHeight - padding; // Measure height of a textarea with a single row

    inputShallow.value = 'x';
    var singleRowHeight = inputShallow.scrollHeight - padding; // The height of the outer content

    var outerHeight = innerHeight;

    if (rowsMin) {
      outerHeight = Math.max(Number(rowsMin) * singleRowHeight, outerHeight);
    }

    if (rowsMax) {
      outerHeight = Math.min(Number(rowsMax) * singleRowHeight, outerHeight);
    }

    outerHeight = Math.max(outerHeight, singleRowHeight); // Take the box sizing into account for applying this value as a style.

    var outerHeightStyle = outerHeight + (boxSizing === 'border-box' ? padding + border : 0);
    var overflow = Math.abs(outerHeight - innerHeight) <= 1;
    setState(function (prevState) {
      // Need a large enough different to update the height.
      // This prevents infinite rendering loop.
      if (outerHeightStyle > 0 && Math.abs((prevState.outerHeightStyle || 0) - outerHeightStyle) > 1 || prevState.overflow !== overflow) {
        return {
          overflow: overflow,
          outerHeightStyle: outerHeightStyle
        };
      }

      return prevState;
    });
  }, [rowsMax, rowsMin, props.placeholder]);
  react_default.a.useEffect(function () {
    var handleResize = debounce(function () {
      syncHeight();
    });
    window.addEventListener('resize', handleResize);
    return function () {
      handleResize.clear();
      window.removeEventListener('resize', handleResize);
    };
  }, [syncHeight]);
  TextareaAutosize_useEnhancedEffect(function () {
    syncHeight();
  });

  var handleChange = function handleChange(event) {
    if (!isControlled) {
      syncHeight();
    }

    if (onChange) {
      onChange(event);
    }
  };

  return react_default.a.createElement(react_default.a.Fragment, null, react_default.a.createElement("textarea", Object(helpers_esm_extends["a" /* default */])({
    value: value,
    onChange: handleChange,
    ref: handleRef // Apply the rows prop to get a "correct" first SSR paint
    ,
    rows: rowsMin,
    style: Object(helpers_esm_extends["a" /* default */])({
      height: state.outerHeightStyle,
      // Need a large enough different to allow scrolling.
      // This prevents infinite rendering loop.
      overflow: state.overflow ? 'hidden' : null
    }, style)
  }, other)), react_default.a.createElement("textarea", {
    "aria-hidden": true,
    className: props.className,
    readOnly: true,
    ref: shadowRef,
    tabIndex: -1,
    style: Object(helpers_esm_extends["a" /* default */])({}, TextareaAutosize_styles.shadow, {}, style)
  }));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_TextareaAutosize_TextareaAutosize = (TextareaAutosize_TextareaAutosize);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/InputBase/InputBase.js



/* eslint-disable jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */











var InputBase_styles = function styles(theme) {
  var light = theme.palette.type === 'light';
  var placeholder = {
    color: 'currentColor',
    opacity: light ? 0.42 : 0.5,
    transition: theme.transitions.create('opacity', {
      duration: theme.transitions.duration.shorter
    })
  };
  var placeholderHidden = {
    opacity: '0 !important'
  };
  var placeholderVisible = {
    opacity: light ? 0.42 : 0.5
  };
  return {
    '@global': {
      '@keyframes mui-auto-fill': {
        from: {}
      },
      '@keyframes mui-auto-fill-cancel': {
        from: {}
      }
    },

    /* Styles applied to the root element. */
    root: Object(helpers_esm_extends["a" /* default */])({}, theme.typography.body1, {
      color: theme.palette.text.primary,
      lineHeight: '1.1875em',
      // Reset (19px), match the native input line-height
      boxSizing: 'border-box',
      // Prevent padding issue with fullWidth.
      position: 'relative',
      cursor: 'text',
      display: 'inline-flex',
      alignItems: 'center',
      '&$disabled': {
        color: theme.palette.text.disabled,
        cursor: 'default'
      }
    }),

    /* Styles applied to the root element if the component is a descendant of `FormControl`. */
    formControl: {},

    /* Styles applied to the root element if the component is focused. */
    focused: {},

    /* Styles applied to the root element if `disabled={true}`. */
    disabled: {},

    /* Styles applied to the root element if `startAdornment` is provided. */
    adornedStart: {},

    /* Styles applied to the root element if `endAdornment` is provided. */
    adornedEnd: {},

    /* Pseudo-class applied to the root element if `error={true}`. */
    error: {},

    /* Styles applied to the `input` element if `margin="dense"`. */
    marginDense: {},

    /* Styles applied to the root element if `multiline={true}`. */
    multiline: {
      padding: "".concat(8 - 2, "px 0 ").concat(8 - 1, "px"),
      '&$marginDense': {
        paddingTop: 4 - 1
      }
    },

    /* Styles applied to the root element if the color is secondary. */
    colorSecondary: {},

    /* Styles applied to the root element if `fullWidth={true}`. */
    fullWidth: {
      width: '100%'
    },

    /* Styles applied to the `input` element. */
    input: {
      font: 'inherit',
      color: 'currentColor',
      padding: "".concat(8 - 2, "px 0 ").concat(8 - 1, "px"),
      border: 0,
      boxSizing: 'content-box',
      background: 'none',
      height: '1.1875em',
      // Reset (19px), match the native input line-height
      margin: 0,
      // Reset for Safari
      WebkitTapHighlightColor: 'transparent',
      display: 'block',
      // Make the flex item shrink with Firefox
      minWidth: 0,
      width: '100%',
      // Fix IE 11 width issue
      animationName: 'mui-auto-fill-cancel',
      '&::-webkit-input-placeholder': placeholder,
      '&::-moz-placeholder': placeholder,
      // Firefox 19+
      '&:-ms-input-placeholder': placeholder,
      // IE 11
      '&::-ms-input-placeholder': placeholder,
      // Edge
      '&:focus': {
        outline: 0
      },
      // Reset Firefox invalid required input style
      '&:invalid': {
        boxShadow: 'none'
      },
      '&::-webkit-search-decoration': {
        // Remove the padding when type=search.
        '-webkit-appearance': 'none'
      },
      // Show and hide the placeholder logic
      'label[data-shrink=false] + $formControl &': {
        '&::-webkit-input-placeholder': placeholderHidden,
        '&::-moz-placeholder': placeholderHidden,
        // Firefox 19+
        '&:-ms-input-placeholder': placeholderHidden,
        // IE 11
        '&::-ms-input-placeholder': placeholderHidden,
        // Edge
        '&:focus::-webkit-input-placeholder': placeholderVisible,
        '&:focus::-moz-placeholder': placeholderVisible,
        // Firefox 19+
        '&:focus:-ms-input-placeholder': placeholderVisible,
        // IE 11
        '&:focus::-ms-input-placeholder': placeholderVisible // Edge

      },
      '&$disabled': {
        opacity: 1 // Reset iOS opacity

      },
      '&:-webkit-autofill': {
        animationDuration: '5000s',
        animationName: 'mui-auto-fill'
      }
    },

    /* Styles applied to the `input` element if `margin="dense"`. */
    inputMarginDense: {
      paddingTop: 4 - 1
    },

    /* Styles applied to the `input` element if `multiline={true}`. */
    inputMultiline: {
      height: 'auto',
      resize: 'none',
      padding: 0
    },

    /* Styles applied to the `input` element if `type="search"`. */
    inputTypeSearch: {
      // Improve type search style.
      '-moz-appearance': 'textfield',
      '-webkit-appearance': 'textfield'
    },

    /* Styles applied to the `input` element if `startAdornment` is provided. */
    inputAdornedStart: {},

    /* Styles applied to the `input` element if `endAdornment` is provided. */
    inputAdornedEnd: {},

    /* Styles applied to the `input` element if `hiddenLabel={true}`. */
    inputHiddenLabel: {}
  };
};
var InputBase_useEnhancedEffect = typeof window === 'undefined' ? react_default.a.useEffect : react_default.a.useLayoutEffect;
/**
 * `InputBase` contains as few styles as possible.
 * It aims to be a simple building block for creating an input.
 * It contains a load of style reset and some state logic.
 */

var InputBase_InputBase = react_default.a.forwardRef(function InputBase(props, ref) {
  var ariaDescribedby = props['aria-describedby'],
      autoComplete = props.autoComplete,
      autoFocus = props.autoFocus,
      classes = props.classes,
      className = props.className,
      color = props.color,
      defaultValue = props.defaultValue,
      disabled = props.disabled,
      endAdornment = props.endAdornment,
      error = props.error,
      _props$fullWidth = props.fullWidth,
      fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,
      id = props.id,
      _props$inputComponent = props.inputComponent,
      inputComponent = _props$inputComponent === void 0 ? 'input' : _props$inputComponent,
      _props$inputProps = props.inputProps,
      inputPropsProp = _props$inputProps === void 0 ? {} : _props$inputProps,
      inputRefProp = props.inputRef,
      margin = props.margin,
      _props$multiline = props.multiline,
      multiline = _props$multiline === void 0 ? false : _props$multiline,
      name = props.name,
      onBlur = props.onBlur,
      onChange = props.onChange,
      onClick = props.onClick,
      onFocus = props.onFocus,
      onKeyDown = props.onKeyDown,
      onKeyUp = props.onKeyUp,
      placeholder = props.placeholder,
      readOnly = props.readOnly,
      renderSuffix = props.renderSuffix,
      rows = props.rows,
      rowsMax = props.rowsMax,
      rowsMin = props.rowsMin,
      startAdornment = props.startAdornment,
      _props$type = props.type,
      type = _props$type === void 0 ? 'text' : _props$type,
      valueProp = props.value,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["aria-describedby", "autoComplete", "autoFocus", "classes", "className", "color", "defaultValue", "disabled", "endAdornment", "error", "fullWidth", "id", "inputComponent", "inputProps", "inputRef", "margin", "multiline", "name", "onBlur", "onChange", "onClick", "onFocus", "onKeyDown", "onKeyUp", "placeholder", "readOnly", "renderSuffix", "rows", "rowsMax", "rowsMin", "startAdornment", "type", "value"]);

  var value = inputPropsProp.value != null ? inputPropsProp.value : valueProp;

  var _React$useRef = react_default.a.useRef(value != null),
      isControlled = _React$useRef.current;

  var inputRef = react_default.a.useRef();
  var handleInputRefWarning = react_default.a.useCallback(function (instance) {
    if (false) {}
  }, []);
  var handleInputPropsRefProp = useForkRef(inputPropsProp.ref, handleInputRefWarning);
  var handleInputRefProp = useForkRef(inputRefProp, handleInputPropsRefProp);
  var handleInputRef = useForkRef(inputRef, handleInputRefProp);

  var _React$useState = react_default.a.useState(false),
      focused = _React$useState[0],
      setFocused = _React$useState[1];

  var muiFormControl = useFormControl();

  if (false) {}

  var fcs = formControlState({
    props: props,
    muiFormControl: muiFormControl,
    states: ['color', 'disabled', 'error', 'hiddenLabel', 'margin', 'required', 'filled']
  });
  fcs.focused = muiFormControl ? muiFormControl.focused : focused; // The blur won't fire when the disabled state is set on a focused input.
  // We need to book keep the focused state manually.

  react_default.a.useEffect(function () {
    if (!muiFormControl && disabled && focused) {
      setFocused(false);

      if (onBlur) {
        onBlur();
      }
    }
  }, [muiFormControl, disabled, focused, onBlur]);
  var onFilled = muiFormControl && muiFormControl.onFilled;
  var onEmpty = muiFormControl && muiFormControl.onEmpty;
  var checkDirty = react_default.a.useCallback(function (obj) {
    if (isFilled(obj)) {
      if (onFilled) {
        onFilled();
      }
    } else if (onEmpty) {
      onEmpty();
    }
  }, [onFilled, onEmpty]);
  InputBase_useEnhancedEffect(function () {
    if (isControlled) {
      checkDirty({
        value: value
      });
    }
  }, [value, checkDirty, isControlled]);

  var handleFocus = function handleFocus(event) {
    // Fix a bug with IE 11 where the focus/blur events are triggered
    // while the input is disabled.
    if (fcs.disabled) {
      event.stopPropagation();
      return;
    }

    if (onFocus) {
      onFocus(event);
    }

    if (inputPropsProp.onFocus) {
      inputPropsProp.onFocus(event);
    }

    if (muiFormControl && muiFormControl.onFocus) {
      muiFormControl.onFocus(event);
    } else {
      setFocused(true);
    }
  };

  var handleBlur = function handleBlur(event) {
    if (onBlur) {
      onBlur(event);
    }

    if (inputPropsProp.onBlur) {
      inputPropsProp.onBlur(event);
    }

    if (muiFormControl && muiFormControl.onBlur) {
      muiFormControl.onBlur(event);
    } else {
      setFocused(false);
    }
  };

  var handleChange = function handleChange(event) {
    if (!isControlled) {
      var element = event.target || inputRef.current;

      if (element == null) {
        throw new TypeError('Material-UI: Expected valid input target. ' + 'Did you use a custom `inputComponent` and forget to forward refs? ' + 'See https://material-ui.com/r/input-component-ref-interface for more info.');
      }

      checkDirty({
        value: element.value
      });
    }

    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args[_key - 1] = arguments[_key];
    }

    if (inputPropsProp.onChange) {
      inputPropsProp.onChange.apply(inputPropsProp, [event].concat(args));
    } // Perform in the willUpdate


    if (onChange) {
      onChange.apply(void 0, [event].concat(args));
    }
  }; // Check the input state on mount, in case it was filled by the user
  // or auto filled by the browser before the hydration (for SSR).


  react_default.a.useEffect(function () {
    checkDirty(inputRef.current);
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  var handleClick = function handleClick(event) {
    if (inputRef.current && event.currentTarget === event.target) {
      inputRef.current.focus();
    }

    if (onClick) {
      onClick(event);
    }
  };

  var InputComponent = inputComponent;

  var inputProps = Object(helpers_esm_extends["a" /* default */])({}, inputPropsProp, {
    ref: handleInputRef
  });

  if (typeof InputComponent !== 'string') {
    inputProps = Object(helpers_esm_extends["a" /* default */])({
      // Rename ref to inputRef as we don't know the
      // provided `inputComponent` structure.
      inputRef: handleInputRef,
      type: type
    }, inputProps, {
      ref: null
    });
  } else if (multiline) {
    if (rows && !rowsMax && !rowsMin) {
      InputComponent = 'textarea';
    } else {
      inputProps = Object(helpers_esm_extends["a" /* default */])({
        rows: rows,
        rowsMax: rowsMax
      }, inputProps);
      InputComponent = esm_TextareaAutosize_TextareaAutosize;
    }
  } else {
    inputProps = Object(helpers_esm_extends["a" /* default */])({
      type: type
    }, inputProps);
  }

  var handleAutoFill = function handleAutoFill(event) {
    // Provide a fake value as Chrome might not let you access it for security reasons.
    checkDirty(event.animationName === 'mui-auto-fill-cancel' ? inputRef.current : {
      value: 'x'
    });
  };

  react_default.a.useEffect(function () {
    if (muiFormControl) {
      muiFormControl.setAdornedStart(Boolean(startAdornment));
    }
  }, [muiFormControl, startAdornment]);
  return react_default.a.createElement("div", Object(helpers_esm_extends["a" /* default */])({
    className: Object(clsx_m["a" /* default */])(classes.root, classes["color".concat(Object(capitalize["a" /* default */])(fcs.color || 'primary'))], className, fcs.disabled && classes.disabled, fcs.error && classes.error, fullWidth && classes.fullWidth, fcs.focused && classes.focused, muiFormControl && classes.formControl, multiline && classes.multiline, startAdornment && classes.adornedStart, endAdornment && classes.adornedEnd, fcs.margin === 'dense' && classes.marginDense),
    onClick: handleClick,
    ref: ref
  }, other), startAdornment, react_default.a.createElement(FormControl_FormControlContext.Provider, {
    value: null
  }, react_default.a.createElement(InputComponent, Object(helpers_esm_extends["a" /* default */])({
    "aria-invalid": fcs.error,
    "aria-describedby": ariaDescribedby,
    autoComplete: autoComplete,
    autoFocus: autoFocus,
    defaultValue: defaultValue,
    disabled: fcs.disabled,
    id: id,
    onAnimationStart: handleAutoFill,
    name: name,
    placeholder: placeholder,
    readOnly: readOnly,
    required: fcs.required,
    rows: rows,
    value: value,
    onKeyDown: onKeyDown,
    onKeyUp: onKeyUp
  }, inputProps, {
    className: Object(clsx_m["a" /* default */])(classes.input, inputPropsProp.className, fcs.disabled && classes.disabled, multiline && classes.inputMultiline, fcs.hiddenLabel && classes.inputHiddenLabel, startAdornment && classes.inputAdornedStart, endAdornment && classes.inputAdornedEnd, type === 'search' && classes.inputTypeSearch, fcs.margin === 'dense' && classes.inputMarginDense),
    onBlur: handleBlur,
    onChange: handleChange,
    onFocus: handleFocus
  }))), endAdornment, renderSuffix ? renderSuffix(Object(helpers_esm_extends["a" /* default */])({}, fcs, {
    startAdornment: startAdornment
  })) : null);
});
 false ? undefined : void 0;
/* harmony default export */ var esm_InputBase_InputBase = (Object(withStyles["a" /* default */])(InputBase_styles, {
  name: 'MuiInputBase'
})(InputBase_InputBase));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Input/Input.js








var Input_styles = function styles(theme) {
  var light = theme.palette.type === 'light';
  var bottomLineColor = light ? 'rgba(0, 0, 0, 0.42)' : 'rgba(255, 255, 255, 0.7)';
  return {
    /* Styles applied to the root element. */
    root: {
      position: 'relative'
    },

    /* Styles applied to the root element if the component is a descendant of `FormControl`. */
    formControl: {
      'label + &': {
        marginTop: 16
      }
    },

    /* Styles applied to the root element if the component is focused. */
    focused: {},

    /* Styles applied to the root element if `disabled={true}`. */
    disabled: {},

    /* Styles applied to the root element if color secondary. */
    colorSecondary: {
      '&$underline:after': {
        borderBottomColor: theme.palette.secondary.main
      }
    },

    /* Styles applied to the root element if `disableUnderline={false}`. */
    underline: {
      '&:after': {
        borderBottom: "2px solid ".concat(theme.palette.primary.main),
        left: 0,
        bottom: 0,
        // Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242
        content: '""',
        position: 'absolute',
        right: 0,
        transform: 'scaleX(0)',
        transition: theme.transitions.create('transform', {
          duration: theme.transitions.duration.shorter,
          easing: theme.transitions.easing.easeOut
        }),
        pointerEvents: 'none' // Transparent to the hover style.

      },
      '&$focused:after': {
        transform: 'scaleX(1)'
      },
      '&$error:after': {
        borderBottomColor: theme.palette.error.main,
        transform: 'scaleX(1)' // error is always underlined in red

      },
      '&:before': {
        borderBottom: "1px solid ".concat(bottomLineColor),
        left: 0,
        bottom: 0,
        // Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242
        content: '"\\00a0"',
        position: 'absolute',
        right: 0,
        transition: theme.transitions.create('border-bottom-color', {
          duration: theme.transitions.duration.shorter
        }),
        pointerEvents: 'none' // Transparent to the hover style.

      },
      '&:hover:not($disabled):before': {
        borderBottom: "2px solid ".concat(theme.palette.text.primary),
        // Reset on touch devices, it doesn't add specificity
        '@media (hover: none)': {
          borderBottom: "1px solid ".concat(bottomLineColor)
        }
      },
      '&$disabled:before': {
        borderBottomStyle: 'dotted'
      }
    },

    /* Pseudo-class applied to the root element if `error={true}`. */
    error: {},

    /* Styles applied to the `input` element if `margin="dense"`. */
    marginDense: {},

    /* Styles applied to the root element if `multiline={true}`. */
    multiline: {},

    /* Styles applied to the root element if `fullWidth={true}`. */
    fullWidth: {},

    /* Styles applied to the `input` element. */
    input: {},

    /* Styles applied to the `input` element if `margin="dense"`. */
    inputMarginDense: {},

    /* Styles applied to the `input` element if `multiline={true}`. */
    inputMultiline: {},

    /* Styles applied to the `input` element if `type="search"`. */
    inputTypeSearch: {}
  };
};
var Input_Input = react_default.a.forwardRef(function Input(props, ref) {
  var disableUnderline = props.disableUnderline,
      classes = props.classes,
      _props$fullWidth = props.fullWidth,
      fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,
      _props$inputComponent = props.inputComponent,
      inputComponent = _props$inputComponent === void 0 ? 'input' : _props$inputComponent,
      _props$multiline = props.multiline,
      multiline = _props$multiline === void 0 ? false : _props$multiline,
      _props$type = props.type,
      type = _props$type === void 0 ? 'text' : _props$type,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["disableUnderline", "classes", "fullWidth", "inputComponent", "multiline", "type"]);

  return react_default.a.createElement(esm_InputBase_InputBase, Object(helpers_esm_extends["a" /* default */])({
    classes: Object(helpers_esm_extends["a" /* default */])({}, classes, {
      root: Object(clsx_m["a" /* default */])(classes.root, !disableUnderline && classes.underline),
      underline: null
    }),
    fullWidth: fullWidth,
    inputComponent: inputComponent,
    multiline: multiline,
    ref: ref,
    type: type
  }, other));
});
 false ? undefined : void 0;
Input_Input.muiName = 'Input';
/* harmony default export */ var esm_Input_Input = (Object(withStyles["a" /* default */])(Input_styles, {
  name: 'MuiInput'
})(Input_Input));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/NativeSelect/NativeSelectInput.js







/**
 * @ignore - internal component.
 */

var NativeSelectInput_NativeSelectInput = react_default.a.forwardRef(function NativeSelectInput(props, ref) {
  var classes = props.classes,
      className = props.className,
      disabled = props.disabled,
      IconComponent = props.IconComponent,
      inputRef = props.inputRef,
      _props$variant = props.variant,
      variant = _props$variant === void 0 ? 'standard' : _props$variant,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["classes", "className", "disabled", "IconComponent", "inputRef", "variant"]);

  return react_default.a.createElement(react_default.a.Fragment, null, react_default.a.createElement("select", Object(helpers_esm_extends["a" /* default */])({
    className: Object(clsx_m["a" /* default */])(classes.root, // TODO v5: merge root and select
    classes.select, classes[variant], className, disabled && classes.disabled),
    disabled: disabled,
    ref: inputRef || ref
  }, other)), props.multiple ? null : react_default.a.createElement(IconComponent, {
    className: Object(clsx_m["a" /* default */])(classes.icon, classes["icon".concat(Object(capitalize["a" /* default */])(variant))])
  }));
});
 false ? undefined : void 0;
/* harmony default export */ var NativeSelect_NativeSelectInput = (NativeSelectInput_NativeSelectInput);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/NativeSelect/NativeSelect.js










var NativeSelect_styles = function styles(theme) {
  return {
    /* Styles applied to the select component `root` class. */
    root: {},

    /* Styles applied to the select component `select` class. */
    select: {
      '-moz-appearance': 'none',
      // Reset
      '-webkit-appearance': 'none',
      // Reset
      // When interacting quickly, the text can end up selected.
      // Native select can't be selected either.
      userSelect: 'none',
      borderRadius: 0,
      // Reset
      minWidth: 16,
      // So it doesn't collapse.
      cursor: 'pointer',
      '&:focus': {
        // Show that it's not an text input
        backgroundColor: theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.05)' : 'rgba(255, 255, 255, 0.05)',
        borderRadius: 0 // Reset Chrome style

      },
      // Remove IE 11 arrow
      '&::-ms-expand': {
        display: 'none'
      },
      '&$disabled': {
        cursor: 'default'
      },
      '&[multiple]': {
        height: 'auto'
      },
      '&:not([multiple]) option, &:not([multiple]) optgroup': {
        backgroundColor: theme.palette.background.paper
      },
      '&&': {
        paddingRight: 24
      }
    },

    /* Styles applied to the select component if `variant="filled"`. */
    filled: {
      '&&': {
        paddingRight: 32
      }
    },

    /* Styles applied to the select component if `variant="outlined"`. */
    outlined: {
      borderRadius: theme.shape.borderRadius,
      '&&': {
        paddingRight: 32
      }
    },

    /* Styles applied to the select component `selectMenu` class. */
    selectMenu: {
      height: 'auto',
      // Reset
      textOverflow: 'ellipsis',
      whiteSpace: 'nowrap',
      overflow: 'hidden'
    },

    /* Pseudo-class applied to the select component `disabled` class. */
    disabled: {},

    /* Styles applied to the icon component. */
    icon: {
      // We use a position absolute over a flexbox in order to forward the pointer events
      // to the input and to support wrapping tags..
      position: 'absolute',
      right: 0,
      top: 'calc(50% - 12px)',
      // Center vertically
      color: theme.palette.action.active,
      pointerEvents: 'none' // Don't block pointer events on the select under the icon.

    },

    /* Styles applied to the icon component if the popup is open. */
    iconOpen: {
      transform: 'rotate(180deg)'
    },

    /* Styles applied to the icon component if `variant="filled"`. */
    iconFilled: {
      right: 7
    },

    /* Styles applied to the icon component if `variant="outlined"`. */
    iconOutlined: {
      right: 7
    }
  };
};
var defaultInput = react_default.a.createElement(esm_Input_Input, null);
/**
 * An alternative to `<Select native />` with a much smaller bundle size footprint.
 */

var NativeSelect_NativeSelect = react_default.a.forwardRef(function NativeSelect(props, ref) {
  var children = props.children,
      classes = props.classes,
      _props$IconComponent = props.IconComponent,
      IconComponent = _props$IconComponent === void 0 ? ArrowDropDown : _props$IconComponent,
      _props$input = props.input,
      input = _props$input === void 0 ? defaultInput : _props$input,
      inputProps = props.inputProps,
      variant = props.variant,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["children", "classes", "IconComponent", "input", "inputProps", "variant"]);

  var muiFormControl = useFormControl_useFormControl();
  var fcs = formControlState({
    props: props,
    muiFormControl: muiFormControl,
    states: ['variant']
  });
  return react_default.a.cloneElement(input, Object(helpers_esm_extends["a" /* default */])({
    // Most of the logic is implemented in `NativeSelectInput`.
    // The `Select` component is a simple API wrapper to expose something better to play with.
    inputComponent: NativeSelect_NativeSelectInput,
    inputProps: Object(helpers_esm_extends["a" /* default */])({
      children: children,
      classes: classes,
      IconComponent: IconComponent,
      variant: fcs.variant,
      type: undefined
    }, inputProps, {}, input ? input.props.inputProps : {}),
    ref: ref
  }, other));
});
 false ? undefined : void 0;
NativeSelect_NativeSelect.muiName = 'Select';
/* harmony default export */ var esm_NativeSelect_NativeSelect = (Object(withStyles["a" /* default */])(NativeSelect_styles, {
  name: 'MuiNativeSelect'
})(NativeSelect_NativeSelect));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/FilledInput/FilledInput.js








var FilledInput_styles = function styles(theme) {
  var light = theme.palette.type === 'light';
  var bottomLineColor = light ? 'rgba(0, 0, 0, 0.42)' : 'rgba(255, 255, 255, 0.7)';
  var backgroundColor = light ? 'rgba(0, 0, 0, 0.09)' : 'rgba(255, 255, 255, 0.09)';
  return {
    /* Styles applied to the root element. */
    root: {
      position: 'relative',
      backgroundColor: backgroundColor,
      borderTopLeftRadius: theme.shape.borderRadius,
      borderTopRightRadius: theme.shape.borderRadius,
      transition: theme.transitions.create('background-color', {
        duration: theme.transitions.duration.shorter,
        easing: theme.transitions.easing.easeOut
      }),
      '&:hover': {
        backgroundColor: light ? 'rgba(0, 0, 0, 0.13)' : 'rgba(255, 255, 255, 0.13)',
        // Reset on touch devices, it doesn't add specificity
        '@media (hover: none)': {
          backgroundColor: backgroundColor
        }
      },
      '&$focused': {
        backgroundColor: light ? 'rgba(0, 0, 0, 0.09)' : 'rgba(255, 255, 255, 0.09)'
      },
      '&$disabled': {
        backgroundColor: light ? 'rgba(0, 0, 0, 0.12)' : 'rgba(255, 255, 255, 0.12)'
      }
    },

    /* Styles applied to the root element if color secondary. */
    colorSecondary: {
      '&$underline:after': {
        borderBottomColor: theme.palette.secondary.main
      }
    },

    /* Styles applied to the root element if `disableUnderline={false}`. */
    underline: {
      '&:after': {
        borderBottom: "2px solid ".concat(theme.palette.primary.main),
        left: 0,
        bottom: 0,
        // Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242
        content: '""',
        position: 'absolute',
        right: 0,
        transform: 'scaleX(0)',
        transition: theme.transitions.create('transform', {
          duration: theme.transitions.duration.shorter,
          easing: theme.transitions.easing.easeOut
        }),
        pointerEvents: 'none' // Transparent to the hover style.

      },
      '&$focused:after': {
        transform: 'scaleX(1)'
      },
      '&$error:after': {
        borderBottomColor: theme.palette.error.main,
        transform: 'scaleX(1)' // error is always underlined in red

      },
      '&:before': {
        borderBottom: "1px solid ".concat(bottomLineColor),
        left: 0,
        bottom: 0,
        // Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242
        content: '"\\00a0"',
        position: 'absolute',
        right: 0,
        transition: theme.transitions.create('border-bottom-color', {
          duration: theme.transitions.duration.shorter
        }),
        pointerEvents: 'none' // Transparent to the hover style.

      },
      '&:hover:before': {
        borderBottom: "1px solid ".concat(theme.palette.text.primary)
      },
      '&$disabled:before': {
        borderBottomStyle: 'dotted'
      }
    },

    /* Pseudo-class applied to the root element if the component is focused. */
    focused: {},

    /* Pseudo-class applied to the root element if `disabled={true}`. */
    disabled: {},

    /* Styles applied to the root element if `startAdornment` is provided. */
    adornedStart: {
      paddingLeft: 12
    },

    /* Styles applied to the root element if `endAdornment` is provided. */
    adornedEnd: {
      paddingRight: 12
    },

    /* Pseudo-class applied to the root element if `error={true}`. */
    error: {},

    /* Styles applied to the `input` element if `margin="dense"`. */
    marginDense: {},

    /* Styles applied to the root element if `multiline={true}`. */
    multiline: {
      padding: '27px 12px 10px',
      '&$marginDense': {
        paddingTop: 23,
        paddingBottom: 6
      }
    },

    /* Styles applied to the `input` element. */
    input: {
      padding: '27px 12px 10px',
      '&:-webkit-autofill': {
        WebkitBoxShadow: theme.palette.type === 'dark' ? '0 0 0 100px #266798 inset' : null,
        WebkitTextFillColor: theme.palette.type === 'dark' ? '#fff' : null,
        borderTopLeftRadius: 'inherit',
        borderTopRightRadius: 'inherit'
      }
    },

    /* Styles applied to the `input` element if `margin="dense"`. */
    inputMarginDense: {
      paddingTop: 23,
      paddingBottom: 6
    },

    /* Styles applied to the `input` if in `<FormControl hiddenLabel />`. */
    inputHiddenLabel: {
      paddingTop: 18,
      paddingBottom: 19,
      '&$inputMarginDense': {
        paddingTop: 10,
        paddingBottom: 11
      }
    },

    /* Styles applied to the `input` element if `multiline={true}`. */
    inputMultiline: {
      padding: 0
    },

    /* Styles applied to the `input` element if `startAdornment` is provided. */
    inputAdornedStart: {
      paddingLeft: 0
    },

    /* Styles applied to the `input` element if `endAdornment` is provided. */
    inputAdornedEnd: {
      paddingRight: 0
    }
  };
};
var FilledInput_FilledInput = react_default.a.forwardRef(function FilledInput(props, ref) {
  var disableUnderline = props.disableUnderline,
      classes = props.classes,
      _props$fullWidth = props.fullWidth,
      fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,
      _props$inputComponent = props.inputComponent,
      inputComponent = _props$inputComponent === void 0 ? 'input' : _props$inputComponent,
      _props$multiline = props.multiline,
      multiline = _props$multiline === void 0 ? false : _props$multiline,
      _props$type = props.type,
      type = _props$type === void 0 ? 'text' : _props$type,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["disableUnderline", "classes", "fullWidth", "inputComponent", "multiline", "type"]);

  return react_default.a.createElement(esm_InputBase_InputBase, Object(helpers_esm_extends["a" /* default */])({
    classes: Object(helpers_esm_extends["a" /* default */])({}, classes, {
      root: Object(clsx_m["a" /* default */])(classes.root, !disableUnderline && classes.underline),
      underline: null
    }),
    fullWidth: fullWidth,
    inputComponent: inputComponent,
    multiline: multiline,
    ref: ref,
    type: type
  }, other));
});
 false ? undefined : void 0;
FilledInput_FilledInput.muiName = 'Input';
/* harmony default export */ var esm_FilledInput_FilledInput = (Object(withStyles["a" /* default */])(FilledInput_styles, {
  name: 'MuiFilledInput'
})(FilledInput_FilledInput));
// EXTERNAL MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/defineProperty.js
var esm_defineProperty = __webpack_require__(22);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/OutlinedInput/NotchedOutline.js









var NotchedOutline_styles = function styles(theme) {
  return {
    /* Styles applied to the root element. */
    root: {
      position: 'absolute',
      bottom: 0,
      right: 0,
      top: -5,
      left: 0,
      margin: 0,
      padding: 0,
      paddingLeft: 8,
      pointerEvents: 'none',
      borderRadius: 'inherit',
      borderStyle: 'solid',
      borderWidth: 1
    },

    /* Styles applied to the legend element when `labelWidth` is provided. */
    legend: {
      textAlign: 'left',
      padding: 0,
      lineHeight: '11px',
      // sync with `height` in `legend` styles
      transition: theme.transitions.create('width', {
        duration: 150,
        easing: theme.transitions.easing.easeOut
      })
    },

    /* Styles applied to the legend element. */
    legendLabelled: {
      display: 'block',
      width: 'auto',
      textAlign: 'left',
      padding: 0,
      height: 11,
      // sync with `lineHeight` in `legend` styles
      fontSize: '0.75em',
      visibility: 'hidden',
      maxWidth: 0.01,
      transition: theme.transitions.create('max-width', {
        duration: 50,
        easing: theme.transitions.easing.easeOut
      }),
      '& span': {
        paddingLeft: 5,
        paddingRight: 5
      }
    },

    /* Styles applied to the legend element is notched. */
    legendNotched: {
      maxWidth: 1000,
      transition: theme.transitions.create('max-width', {
        duration: 100,
        easing: theme.transitions.easing.easeOut,
        delay: 50
      })
    }
  };
};
/**
 * @ignore - internal component.
 */

var NotchedOutline_NotchedOutline = react_default.a.forwardRef(function NotchedOutline(props, ref) {
  var children = props.children,
      classes = props.classes,
      className = props.className,
      label = props.label,
      labelWidthProp = props.labelWidth,
      notched = props.notched,
      style = props.style,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["children", "classes", "className", "label", "labelWidth", "notched", "style"]);

  var theme = useTheme_useTheme();
  var align = theme.direction === 'rtl' ? 'right' : 'left';

  if (label !== undefined) {
    return react_default.a.createElement("fieldset", Object(helpers_esm_extends["a" /* default */])({
      "aria-hidden": true,
      className: Object(clsx_m["a" /* default */])(classes.root, className),
      ref: ref,
      style: style
    }, other), react_default.a.createElement("legend", {
      className: Object(clsx_m["a" /* default */])(classes.legendLabelled, notched && classes.legendNotched)
    }, label ? react_default.a.createElement("span", null, label) : react_default.a.createElement("span", {
      dangerouslySetInnerHTML: {
        __html: '&#8203;'
      }
    })));
  }

  var labelWidth = labelWidthProp > 0 ? labelWidthProp * 0.75 + 8 : 0.01;
  return react_default.a.createElement("fieldset", Object(helpers_esm_extends["a" /* default */])({
    "aria-hidden": true,
    style: Object(helpers_esm_extends["a" /* default */])(Object(esm_defineProperty["a" /* default */])({}, "padding".concat(Object(capitalize["a" /* default */])(align)), 8), style),
    className: Object(clsx_m["a" /* default */])(classes.root, className),
    ref: ref
  }, other), react_default.a.createElement("legend", {
    className: classes.legend,
    style: {
      // IE 11: fieldset with legend does not render
      // a border radius. This maintains consistency
      // by always having a legend rendered
      width: notched ? labelWidth : 0.01
    }
  }, react_default.a.createElement("span", {
    dangerouslySetInnerHTML: {
      __html: '&#8203;'
    }
  })));
});
 false ? undefined : void 0;
/* harmony default export */ var OutlinedInput_NotchedOutline = (Object(withStyles["a" /* default */])(NotchedOutline_styles, {
  name: 'PrivateNotchedOutline'
})(NotchedOutline_NotchedOutline));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/OutlinedInput/OutlinedInput.js









var OutlinedInput_styles = function styles(theme) {
  var borderColor = theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)';
  return {
    /* Styles applied to the root element. */
    root: {
      position: 'relative',
      borderRadius: theme.shape.borderRadius,
      '&:hover $notchedOutline': {
        borderColor: theme.palette.text.primary
      },
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        '&:hover $notchedOutline': {
          borderColor: borderColor
        }
      },
      '&$focused $notchedOutline': {
        borderColor: theme.palette.primary.main,
        borderWidth: 2
      },
      '&$error $notchedOutline': {
        borderColor: theme.palette.error.main
      },
      '&$disabled $notchedOutline': {
        borderColor: theme.palette.action.disabled
      }
    },

    /* Styles applied to the root element if the color is secondary. */
    colorSecondary: {
      '&$focused $notchedOutline': {
        borderColor: theme.palette.secondary.main
      }
    },

    /* Styles applied to the root element if the component is focused. */
    focused: {},

    /* Styles applied to the root element if `disabled={true}`. */
    disabled: {},

    /* Styles applied to the root element if `startAdornment` is provided. */
    adornedStart: {
      paddingLeft: 14
    },

    /* Styles applied to the root element if `endAdornment` is provided. */
    adornedEnd: {
      paddingRight: 14
    },

    /* Pseudo-class applied to the root element if `error={true}`. */
    error: {},

    /* Styles applied to the `input` element if `margin="dense"`. */
    marginDense: {},

    /* Styles applied to the root element if `multiline={true}`. */
    multiline: {
      padding: '18.5px 14px',
      '&$marginDense': {
        paddingTop: 10.5,
        paddingBottom: 10.5
      }
    },

    /* Styles applied to the `NotchedOutline` element. */
    notchedOutline: {
      borderColor: borderColor
    },

    /* Styles applied to the `input` element. */
    input: {
      padding: '18.5px 14px',
      '&:-webkit-autofill': {
        WebkitBoxShadow: theme.palette.type === 'dark' ? '0 0 0 100px #266798 inset' : null,
        WebkitTextFillColor: theme.palette.type === 'dark' ? '#fff' : null,
        borderRadius: 'inherit'
      }
    },

    /* Styles applied to the `input` element if `margin="dense"`. */
    inputMarginDense: {
      paddingTop: 10.5,
      paddingBottom: 10.5
    },

    /* Styles applied to the `input` element if `multiline={true}`. */
    inputMultiline: {
      padding: 0
    },

    /* Styles applied to the `input` element if `startAdornment` is provided. */
    inputAdornedStart: {
      paddingLeft: 0
    },

    /* Styles applied to the `input` element if `endAdornment` is provided. */
    inputAdornedEnd: {
      paddingRight: 0
    }
  };
};
var OutlinedInput_OutlinedInput = react_default.a.forwardRef(function OutlinedInput(props, ref) {
  var classes = props.classes,
      _props$fullWidth = props.fullWidth,
      fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,
      _props$inputComponent = props.inputComponent,
      inputComponent = _props$inputComponent === void 0 ? 'input' : _props$inputComponent,
      label = props.label,
      _props$labelWidth = props.labelWidth,
      labelWidth = _props$labelWidth === void 0 ? 0 : _props$labelWidth,
      _props$multiline = props.multiline,
      multiline = _props$multiline === void 0 ? false : _props$multiline,
      notched = props.notched,
      _props$type = props.type,
      type = _props$type === void 0 ? 'text' : _props$type,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["classes", "fullWidth", "inputComponent", "label", "labelWidth", "multiline", "notched", "type"]);

  return react_default.a.createElement(esm_InputBase_InputBase, Object(helpers_esm_extends["a" /* default */])({
    renderSuffix: function renderSuffix(state) {
      return react_default.a.createElement(OutlinedInput_NotchedOutline, {
        className: classes.notchedOutline,
        label: label,
        labelWidth: labelWidth,
        notched: typeof notched !== 'undefined' ? notched : Boolean(state.startAdornment || state.filled || state.focused)
      });
    },
    classes: Object(helpers_esm_extends["a" /* default */])({}, classes, {
      root: Object(clsx_m["a" /* default */])(classes.root, classes.underline),
      notchedOutline: null
    }),
    fullWidth: fullWidth,
    inputComponent: inputComponent,
    multiline: multiline,
    ref: ref,
    type: type
  }, other));
});
 false ? undefined : void 0;
OutlinedInput_OutlinedInput.muiName = 'Input';
/* harmony default export */ var esm_OutlinedInput_OutlinedInput = (Object(withStyles["a" /* default */])(OutlinedInput_styles, {
  name: 'MuiOutlinedInput'
})(OutlinedInput_OutlinedInput));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Select/Select.js















var Select_styles = NativeSelect_styles;

var Select_ref = react_default.a.createElement(esm_Input_Input, null);

var Select_ref2 = react_default.a.createElement(esm_FilledInput_FilledInput, null);

var Select_Select = react_default.a.forwardRef(function Select(props, ref) {
  var _props$autoWidth = props.autoWidth,
      autoWidth = _props$autoWidth === void 0 ? false : _props$autoWidth,
      children = props.children,
      classes = props.classes,
      _props$displayEmpty = props.displayEmpty,
      displayEmpty = _props$displayEmpty === void 0 ? false : _props$displayEmpty,
      _props$IconComponent = props.IconComponent,
      IconComponent = _props$IconComponent === void 0 ? ArrowDropDown : _props$IconComponent,
      id = props.id,
      input = props.input,
      inputProps = props.inputProps,
      label = props.label,
      labelId = props.labelId,
      _props$labelWidth = props.labelWidth,
      labelWidth = _props$labelWidth === void 0 ? 0 : _props$labelWidth,
      MenuProps = props.MenuProps,
      _props$multiple = props.multiple,
      multiple = _props$multiple === void 0 ? false : _props$multiple,
      _props$native = props.native,
      native = _props$native === void 0 ? false : _props$native,
      onClose = props.onClose,
      onOpen = props.onOpen,
      open = props.open,
      renderValue = props.renderValue,
      SelectDisplayProps = props.SelectDisplayProps,
      _props$variant = props.variant,
      variantProps = _props$variant === void 0 ? 'standard' : _props$variant,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["autoWidth", "children", "classes", "displayEmpty", "IconComponent", "id", "input", "inputProps", "label", "labelId", "labelWidth", "MenuProps", "multiple", "native", "onClose", "onOpen", "open", "renderValue", "SelectDisplayProps", "variant"]);

  var inputComponent = native ? NativeSelect_NativeSelectInput : Select_SelectInput;
  var muiFormControl = useFormControl_useFormControl();
  var fcs = formControlState({
    props: props,
    muiFormControl: muiFormControl,
    states: ['variant']
  });
  var variant = fcs.variant || variantProps;
  var InputComponent = input || {
    standard: Select_ref,
    outlined: react_default.a.createElement(esm_OutlinedInput_OutlinedInput, {
      label: label,
      labelWidth: labelWidth
    }),
    filled: Select_ref2
  }[variant];
  return react_default.a.cloneElement(InputComponent, Object(helpers_esm_extends["a" /* default */])({
    // Most of the logic is implemented in `SelectInput`.
    // The `Select` component is a simple API wrapper to expose something better to play with.
    inputComponent: inputComponent,
    inputProps: Object(helpers_esm_extends["a" /* default */])({
      children: children,
      IconComponent: IconComponent,
      variant: variant,
      type: undefined,
      // We render a select. We can ignore the type provided by the `Input`.
      multiple: multiple
    }, native ? {
      id: id
    } : {
      autoWidth: autoWidth,
      displayEmpty: displayEmpty,
      labelId: labelId,
      MenuProps: MenuProps,
      onClose: onClose,
      onOpen: onOpen,
      open: open,
      renderValue: renderValue,
      SelectDisplayProps: Object(helpers_esm_extends["a" /* default */])({
        id: id
      }, SelectDisplayProps)
    }, {}, inputProps, {
      classes: inputProps ? Object(mergeClasses["a" /* default */])({
        baseClasses: classes,
        newClasses: inputProps.classes,
        Component: Select
      }) : classes
    }, input ? input.props.inputProps : {}),
    ref: ref
  }, other));
});
 false ? undefined : void 0;
Select_Select.muiName = 'Select';
/* harmony default export */ var esm_Select_Select = (Object(withStyles["a" /* default */])(Select_styles, {
  name: 'MuiSelect'
})(Select_Select));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/ListItem/ListItem.js












var ListItem_styles = function styles(theme) {
  return {
    /* Styles applied to the (normally root) `component` element. May be wrapped by a `container`. */
    root: {
      display: 'flex',
      justifyContent: 'flex-start',
      alignItems: 'center',
      position: 'relative',
      textDecoration: 'none',
      width: '100%',
      boxSizing: 'border-box',
      textAlign: 'left',
      paddingTop: 8,
      paddingBottom: 8,
      '&$focusVisible': {
        backgroundColor: theme.palette.action.selected
      },
      '&$selected, &$selected:hover': {
        backgroundColor: theme.palette.action.selected
      },
      '&$disabled': {
        opacity: 0.5
      }
    },

    /* Styles applied to the `container` element if `children` includes `ListItemSecondaryAction`. */
    container: {
      position: 'relative'
    },

    /* Pseudo-class applied to the `component`'s `focusVisibleClassName` prop if `button={true}`. */
    focusVisible: {},

    /* Styles applied to the `component` element if dense. */
    dense: {
      paddingTop: 4,
      paddingBottom: 4
    },

    /* Styles applied to the `component` element if `alignItems="flex-start"`. */
    alignItemsFlexStart: {
      alignItems: 'flex-start'
    },

    /* Pseudo-class applied to the inner `component` element if `disabled={true}`. */
    disabled: {},

    /* Styles applied to the inner `component` element if `divider={true}`. */
    divider: {
      borderBottom: "1px solid ".concat(theme.palette.divider),
      backgroundClip: 'padding-box'
    },

    /* Styles applied to the inner `component` element if `disableGutters={false}`. */
    gutters: {
      paddingLeft: 16,
      paddingRight: 16
    },

    /* Styles applied to the inner `component` element if `button={true}`. */
    button: {
      transition: theme.transitions.create('background-color', {
        duration: theme.transitions.duration.shortest
      }),
      '&:hover': {
        textDecoration: 'none',
        backgroundColor: theme.palette.action.hover,
        // Reset on touch devices, it doesn't add specificity
        '@media (hover: none)': {
          backgroundColor: 'transparent'
        }
      }
    },

    /* Styles applied to the `component` element if `children` includes `ListItemSecondaryAction`. */
    secondaryAction: {
      // Add some space to avoid collision as `ListItemSecondaryAction`
      // is absolutely positioned.
      paddingRight: 48
    },

    /* Pseudo-class applied to the root element if `selected={true}`. */
    selected: {}
  };
};
var ListItem_useEnhancedEffect = typeof window === 'undefined' ? react_default.a.useEffect : react_default.a.useLayoutEffect;
/**
 * Uses an additional container component if `ListItemSecondaryAction` is the last child.
 */

var ListItem_ListItem = react_default.a.forwardRef(function ListItem(props, ref) {
  var _props$alignItems = props.alignItems,
      alignItems = _props$alignItems === void 0 ? 'center' : _props$alignItems,
      _props$autoFocus = props.autoFocus,
      autoFocus = _props$autoFocus === void 0 ? false : _props$autoFocus,
      _props$button = props.button,
      button = _props$button === void 0 ? false : _props$button,
      childrenProp = props.children,
      classes = props.classes,
      className = props.className,
      componentProp = props.component,
      _props$ContainerCompo = props.ContainerComponent,
      ContainerComponent = _props$ContainerCompo === void 0 ? 'li' : _props$ContainerCompo,
      _props$ContainerProps = props.ContainerProps;
  _props$ContainerProps = _props$ContainerProps === void 0 ? {} : _props$ContainerProps;

  var ContainerClassName = _props$ContainerProps.className,
      ContainerProps = Object(objectWithoutProperties["a" /* default */])(_props$ContainerProps, ["className"]),
      _props$dense = props.dense,
      dense = _props$dense === void 0 ? false : _props$dense,
      _props$disabled = props.disabled,
      disabled = _props$disabled === void 0 ? false : _props$disabled,
      _props$disableGutters = props.disableGutters,
      disableGutters = _props$disableGutters === void 0 ? false : _props$disableGutters,
      _props$divider = props.divider,
      divider = _props$divider === void 0 ? false : _props$divider,
      focusVisibleClassName = props.focusVisibleClassName,
      _props$selected = props.selected,
      selected = _props$selected === void 0 ? false : _props$selected,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["alignItems", "autoFocus", "button", "children", "classes", "className", "component", "ContainerComponent", "ContainerProps", "dense", "disabled", "disableGutters", "divider", "focusVisibleClassName", "selected"]);

  var context = react_default.a.useContext(List_ListContext);
  var childContext = {
    dense: dense || context.dense || false,
    alignItems: alignItems
  };
  var listItemRef = react_default.a.useRef(null);
  ListItem_useEnhancedEffect(function () {
    if (autoFocus) {
      if (listItemRef.current) {
        listItemRef.current.focus();
      } else if (false) {}
    }
  }, [autoFocus]);
  var children = react_default.a.Children.toArray(childrenProp);
  var hasSecondaryAction = children.length && isMuiElement(children[children.length - 1], ['ListItemSecondaryAction']);
  var handleOwnRef = react_default.a.useCallback(function (instance) {
    // #StrictMode ready
    listItemRef.current = react_dom_default.a.findDOMNode(instance);
  }, []);
  var handleRef = useForkRef(handleOwnRef, ref);

  var componentProps = Object(helpers_esm_extends["a" /* default */])({
    className: Object(clsx_m["a" /* default */])(classes.root, className, childContext.dense && classes.dense, !disableGutters && classes.gutters, divider && classes.divider, disabled && classes.disabled, button && classes.button, alignItems !== "center" && classes.alignItemsFlexStart, hasSecondaryAction && classes.secondaryAction, selected && classes.selected),
    disabled: disabled
  }, other);

  var Component = componentProp || 'li';

  if (button) {
    componentProps.component = componentProp || 'div';
    componentProps.focusVisibleClassName = Object(clsx_m["a" /* default */])(classes.focusVisible, focusVisibleClassName);
    Component = esm_ButtonBase_ButtonBase;
  }

  if (hasSecondaryAction) {
    // Use div by default.
    Component = !componentProps.component && !componentProp ? 'div' : Component; // Avoid nesting of li > li.

    if (ContainerComponent === 'li') {
      if (Component === 'li') {
        Component = 'div';
      } else if (componentProps.component === 'li') {
        componentProps.component = 'div';
      }
    }

    return react_default.a.createElement(List_ListContext.Provider, {
      value: childContext
    }, react_default.a.createElement(ContainerComponent, Object(helpers_esm_extends["a" /* default */])({
      className: Object(clsx_m["a" /* default */])(classes.container, ContainerClassName),
      ref: handleRef
    }, ContainerProps), react_default.a.createElement(Component, componentProps, children), children.pop()));
  }

  return react_default.a.createElement(List_ListContext.Provider, {
    value: childContext
  }, react_default.a.createElement(Component, Object(helpers_esm_extends["a" /* default */])({
    ref: handleRef
  }, componentProps), children));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_ListItem_ListItem = (Object(withStyles["a" /* default */])(ListItem_styles, {
  name: 'MuiListItem'
})(ListItem_ListItem));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/MenuItem/MenuItem.js








var MenuItem_styles = function styles(theme) {
  return {
    /* Styles applied to the root element. */
    root: Object(helpers_esm_extends["a" /* default */])({}, theme.typography.body1, Object(esm_defineProperty["a" /* default */])({
      minHeight: 48,
      paddingTop: 6,
      paddingBottom: 6,
      boxSizing: 'border-box',
      width: 'auto',
      overflow: 'hidden',
      whiteSpace: 'nowrap'
    }, theme.breakpoints.up('sm'), {
      minHeight: 'auto'
    })),
    // TODO v5: remove

    /* Styles applied to the root element if `disableGutters={false}`. */
    gutters: {},

    /* Styles applied to the root element if `selected={true}`. */
    selected: {},

    /* Styles applied to the root element if dense. */
    dense: Object(helpers_esm_extends["a" /* default */])({}, theme.typography.body2, {
      minHeight: 'auto'
    })
  };
};
var MenuItem_MenuItem = react_default.a.forwardRef(function MenuItem(props, ref) {
  var classes = props.classes,
      className = props.className,
      _props$component = props.component,
      component = _props$component === void 0 ? 'li' : _props$component,
      _props$disableGutters = props.disableGutters,
      disableGutters = _props$disableGutters === void 0 ? false : _props$disableGutters,
      _props$role = props.role,
      role = _props$role === void 0 ? 'menuitem' : _props$role,
      selected = props.selected,
      tabIndexProp = props.tabIndex,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["classes", "className", "component", "disableGutters", "role", "selected", "tabIndex"]);

  var tabIndex;

  if (!props.disabled) {
    tabIndex = tabIndexProp !== undefined ? tabIndexProp : -1;
  }

  return react_default.a.createElement(esm_ListItem_ListItem, Object(helpers_esm_extends["a" /* default */])({
    button: true,
    role: role,
    tabIndex: tabIndex,
    component: component,
    selected: selected,
    disableGutters: disableGutters,
    classes: {
      dense: classes.dense
    },
    className: Object(clsx_m["a" /* default */])(classes.root, className, selected && classes.selected, !disableGutters && classes.gutters),
    ref: ref
  }, other));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_MenuItem_MenuItem = (Object(withStyles["a" /* default */])(MenuItem_styles, {
  name: 'MuiMenuItem'
})(MenuItem_MenuItem));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/ListItemIcon/ListItemIcon.js







var ListItemIcon_styles = function styles(theme) {
  return {
    /* Styles applied to the root element. */
    root: {
      minWidth: 56,
      color: theme.palette.action.active,
      flexShrink: 0,
      display: 'inline-flex'
    },

    /* Styles applied to the root element when the parent `ListItem` uses `alignItems="flex-start"`. */
    alignItemsFlexStart: {
      marginTop: 8
    }
  };
};
/**
 * A simple wrapper to apply `List` styles to an `Icon` or `SvgIcon`.
 */

var ListItemIcon_ListItemIcon = react_default.a.forwardRef(function ListItemIcon(props, ref) {
  var classes = props.classes,
      className = props.className,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["classes", "className"]);

  var context = react_default.a.useContext(List_ListContext);
  return react_default.a.createElement("div", Object(helpers_esm_extends["a" /* default */])({
    className: Object(clsx_m["a" /* default */])(classes.root, className, context.alignItems === 'flex-start' && classes.alignItemsFlexStart),
    ref: ref
  }, other));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_ListItemIcon_ListItemIcon = (Object(withStyles["a" /* default */])(ListItemIcon_styles, {
  name: 'MuiListItemIcon'
})(ListItemIcon_ListItemIcon));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Typography/Typography.js







var Typography_styles = function styles(theme) {
  return {
    /* Styles applied to the root element. */
    root: {
      margin: 0
    },

    /* Styles applied to the root element if `variant="body2"`. */
    body2: theme.typography.body2,

    /* Styles applied to the root element if `variant="body1"`. */
    body1: theme.typography.body1,

    /* Styles applied to the root element if `variant="caption"`. */
    caption: theme.typography.caption,

    /* Styles applied to the root element if `variant="button"`. */
    button: theme.typography.button,

    /* Styles applied to the root element if `variant="h1"`. */
    h1: theme.typography.h1,

    /* Styles applied to the root element if `variant="h2"`. */
    h2: theme.typography.h2,

    /* Styles applied to the root element if `variant="h3"`. */
    h3: theme.typography.h3,

    /* Styles applied to the root element if `variant="h4"`. */
    h4: theme.typography.h4,

    /* Styles applied to the root element if `variant="h5"`. */
    h5: theme.typography.h5,

    /* Styles applied to the root element if `variant="h6"`. */
    h6: theme.typography.h6,

    /* Styles applied to the root element if `variant="subtitle1"`. */
    subtitle1: theme.typography.subtitle1,

    /* Styles applied to the root element if `variant="subtitle2"`. */
    subtitle2: theme.typography.subtitle2,

    /* Styles applied to the root element if `variant="overline"`. */
    overline: theme.typography.overline,

    /* Styles applied to the root element if `variant="srOnly"`. Only accessible to screen readers. */
    srOnly: {
      position: 'absolute',
      height: 1,
      width: 1,
      overflow: 'hidden'
    },

    /* Styles applied to the root element if `align="left"`. */
    alignLeft: {
      textAlign: 'left'
    },

    /* Styles applied to the root element if `align="center"`. */
    alignCenter: {
      textAlign: 'center'
    },

    /* Styles applied to the root element if `align="right"`. */
    alignRight: {
      textAlign: 'right'
    },

    /* Styles applied to the root element if `align="justify"`. */
    alignJustify: {
      textAlign: 'justify'
    },

    /* Styles applied to the root element if `nowrap={true}`. */
    noWrap: {
      overflow: 'hidden',
      textOverflow: 'ellipsis',
      whiteSpace: 'nowrap'
    },

    /* Styles applied to the root element if `gutterBottom={true}`. */
    gutterBottom: {
      marginBottom: '0.35em'
    },

    /* Styles applied to the root element if `paragraph={true}`. */
    paragraph: {
      marginBottom: 16
    },

    /* Styles applied to the root element if `color="inherit"`. */
    colorInherit: {
      color: 'inherit'
    },

    /* Styles applied to the root element if `color="primary"`. */
    colorPrimary: {
      color: theme.palette.primary.main
    },

    /* Styles applied to the root element if `color="secondary"`. */
    colorSecondary: {
      color: theme.palette.secondary.main
    },

    /* Styles applied to the root element if `color="textPrimary"`. */
    colorTextPrimary: {
      color: theme.palette.text.primary
    },

    /* Styles applied to the root element if `color="textSecondary"`. */
    colorTextSecondary: {
      color: theme.palette.text.secondary
    },

    /* Styles applied to the root element if `color="error"`. */
    colorError: {
      color: theme.palette.error.main
    },

    /* Styles applied to the root element if `display="inline"`. */
    displayInline: {
      display: 'inline'
    },

    /* Styles applied to the root element if `display="block"`. */
    displayBlock: {
      display: 'block'
    }
  };
};
var defaultVariantMapping = {
  h1: 'h1',
  h2: 'h2',
  h3: 'h3',
  h4: 'h4',
  h5: 'h5',
  h6: 'h6',
  subtitle1: 'h6',
  subtitle2: 'h6',
  body1: 'p',
  body2: 'p'
};
var Typography_Typography = react_default.a.forwardRef(function Typography(props, ref) {
  var _props$align = props.align,
      align = _props$align === void 0 ? 'inherit' : _props$align,
      classes = props.classes,
      className = props.className,
      _props$color = props.color,
      color = _props$color === void 0 ? 'initial' : _props$color,
      component = props.component,
      _props$display = props.display,
      display = _props$display === void 0 ? 'initial' : _props$display,
      _props$gutterBottom = props.gutterBottom,
      gutterBottom = _props$gutterBottom === void 0 ? false : _props$gutterBottom,
      _props$noWrap = props.noWrap,
      noWrap = _props$noWrap === void 0 ? false : _props$noWrap,
      _props$paragraph = props.paragraph,
      paragraph = _props$paragraph === void 0 ? false : _props$paragraph,
      _props$variant = props.variant,
      variant = _props$variant === void 0 ? 'body1' : _props$variant,
      _props$variantMapping = props.variantMapping,
      variantMapping = _props$variantMapping === void 0 ? defaultVariantMapping : _props$variantMapping,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["align", "classes", "className", "color", "component", "display", "gutterBottom", "noWrap", "paragraph", "variant", "variantMapping"]);

  var Component = component || (paragraph ? 'p' : variantMapping[variant] || defaultVariantMapping[variant]) || 'span';
  return react_default.a.createElement(Component, Object(helpers_esm_extends["a" /* default */])({
    className: Object(clsx_m["a" /* default */])(classes.root, className, variant !== 'inherit' && classes[variant], color !== 'initial' && classes["color".concat(Object(capitalize["a" /* default */])(color))], noWrap && classes.noWrap, gutterBottom && classes.gutterBottom, paragraph && classes.paragraph, align !== 'inherit' && classes["align".concat(Object(capitalize["a" /* default */])(align))], display !== 'initial' && classes["display".concat(Object(capitalize["a" /* default */])(display))]),
    ref: ref
  }, other));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_Typography_Typography = (Object(withStyles["a" /* default */])(Typography_styles, {
  name: 'MuiTypography'
})(Typography_Typography));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/ListItemText/ListItemText.js








var ListItemText_styles = {
  /* Styles applied to the root element. */
  root: {
    flex: '1 1 auto',
    minWidth: 0,
    marginTop: 4,
    marginBottom: 4
  },

  /* Styles applied to the `Typography` components if primary and secondary are set. */
  multiline: {
    marginTop: 6,
    marginBottom: 6
  },

  /* Styles applied to the `Typography` components if dense. */
  dense: {},

  /* Styles applied to the root element if `inset={true}`. */
  inset: {
    paddingLeft: 56
  },

  /* Styles applied to the primary `Typography` component. */
  primary: {},

  /* Styles applied to the secondary `Typography` component. */
  secondary: {}
};
var ListItemText_ListItemText = react_default.a.forwardRef(function ListItemText(props, ref) {
  var children = props.children,
      classes = props.classes,
      className = props.className,
      _props$disableTypogra = props.disableTypography,
      disableTypography = _props$disableTypogra === void 0 ? false : _props$disableTypogra,
      _props$inset = props.inset,
      inset = _props$inset === void 0 ? false : _props$inset,
      primaryProp = props.primary,
      primaryTypographyProps = props.primaryTypographyProps,
      secondaryProp = props.secondary,
      secondaryTypographyProps = props.secondaryTypographyProps,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["children", "classes", "className", "disableTypography", "inset", "primary", "primaryTypographyProps", "secondary", "secondaryTypographyProps"]);

  var _React$useContext = react_default.a.useContext(List_ListContext),
      dense = _React$useContext.dense;

  var primary = primaryProp != null ? primaryProp : children;

  if (primary != null && primary.type !== esm_Typography_Typography && !disableTypography) {
    primary = react_default.a.createElement(esm_Typography_Typography, Object(helpers_esm_extends["a" /* default */])({
      variant: dense ? 'body2' : 'body1',
      className: classes.primary,
      component: "span"
    }, primaryTypographyProps), primary);
  }

  var secondary = secondaryProp;

  if (secondary != null && secondary.type !== esm_Typography_Typography && !disableTypography) {
    secondary = react_default.a.createElement(esm_Typography_Typography, Object(helpers_esm_extends["a" /* default */])({
      variant: "body2",
      className: classes.secondary,
      color: "textSecondary"
    }, secondaryTypographyProps), secondary);
  }

  return react_default.a.createElement("div", Object(helpers_esm_extends["a" /* default */])({
    className: Object(clsx_m["a" /* default */])(classes.root, className, dense && classes.dense, inset && classes.inset, primary && secondary && classes.multiline),
    ref: ref
  }, other), primary, secondary);
});
 false ? undefined : void 0;
/* harmony default export */ var esm_ListItemText_ListItemText = (Object(withStyles["a" /* default */])(ListItemText_styles, {
  name: 'MuiListItemText'
})(ListItemText_ListItemText));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/LinearProgress/LinearProgress.js









var TRANSITION_DURATION = 4; // seconds

var LinearProgress_styles = function styles(theme) {
  var getColor = function getColor(color) {
    return theme.palette.type === 'light' ? Object(colorManipulator["d" /* lighten */])(color, 0.62) : Object(colorManipulator["a" /* darken */])(color, 0.5);
  };

  var backgroundPrimary = getColor(theme.palette.primary.main);
  var backgroundSecondary = getColor(theme.palette.secondary.main);
  return {
    /* Styles applied to the root element. */
    root: {
      position: 'relative',
      overflow: 'hidden',
      height: 4
    },

    /* Styles applied to the root and bar2 element if `color="primary"`; bar2 if `variant="buffer"`. */
    colorPrimary: {
      backgroundColor: backgroundPrimary
    },

    /* Styles applied to the root and bar2 elements if `color="secondary"`; bar2 if `variant="buffer"`. */
    colorSecondary: {
      backgroundColor: backgroundSecondary
    },

    /* Styles applied to the root element if `variant="determinate"`. */
    determinate: {},

    /* Styles applied to the root element if `variant="indeterminate"`. */
    indeterminate: {},

    /* Styles applied to the root element if `variant="buffer"`. */
    buffer: {
      backgroundColor: 'transparent'
    },

    /* Styles applied to the root element if `variant="query"`. */
    query: {
      transform: 'rotate(180deg)'
    },

    /* Styles applied to the additional bar element if `variant="buffer"`. */
    dashed: {
      position: 'absolute',
      marginTop: 0,
      height: '100%',
      width: '100%',
      animation: '$buffer 3s infinite linear'
    },

    /* Styles applied to the additional bar element if `variant="buffer"` and `color="primary"`. */
    dashedColorPrimary: {
      backgroundImage: "radial-gradient(".concat(backgroundPrimary, " 0%, ").concat(backgroundPrimary, " 16%, transparent 42%)"),
      backgroundSize: '10px 10px',
      backgroundPosition: '0px -23px'
    },

    /* Styles applied to the additional bar element if `variant="buffer"` and `color="secondary"`. */
    dashedColorSecondary: {
      backgroundImage: "radial-gradient(".concat(backgroundSecondary, " 0%, ").concat(backgroundSecondary, " 16%, transparent 42%)"),
      backgroundSize: '10px 10px',
      backgroundPosition: '0px -23px'
    },

    /* Styles applied to the layered bar1 and bar2 elements. */
    bar: {
      width: '100%',
      position: 'absolute',
      left: 0,
      bottom: 0,
      top: 0,
      transition: 'transform 0.2s linear',
      transformOrigin: 'left'
    },

    /* Styles applied to the bar elements if `color="primary"`; bar2 if `variant` not "buffer". */
    barColorPrimary: {
      backgroundColor: theme.palette.primary.main
    },

    /* Styles applied to the bar elements if `color="secondary"`; bar2 if `variant` not "buffer". */
    barColorSecondary: {
      backgroundColor: theme.palette.secondary.main
    },

    /* Styles applied to the bar1 element if `variant="indeterminate or query"`. */
    bar1Indeterminate: {
      width: 'auto',
      animation: '$indeterminate1 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite'
    },

    /* Styles applied to the bar1 element if `variant="determinate"`. */
    bar1Determinate: {
      transition: "transform .".concat(TRANSITION_DURATION, "s linear")
    },

    /* Styles applied to the bar1 element if `variant="buffer"`. */
    bar1Buffer: {
      zIndex: 1,
      transition: "transform .".concat(TRANSITION_DURATION, "s linear")
    },

    /* Styles applied to the bar2 element if `variant="indeterminate or query"`. */
    bar2Indeterminate: {
      width: 'auto',
      animation: '$indeterminate2 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite'
    },

    /* Styles applied to the bar2 element if `variant="buffer"`. */
    bar2Buffer: {
      transition: "transform .".concat(TRANSITION_DURATION, "s linear")
    },
    // Legends:
    // || represents the viewport
    // -  represents a light background
    // x  represents a dark background
    '@keyframes indeterminate1': {
      //  |-----|---x-||-----||-----|
      '0%': {
        left: '-35%',
        right: '100%'
      },
      //  |-----|-----||-----||xxxx-|
      '60%': {
        left: '100%',
        right: '-90%'
      },
      '100%': {
        left: '100%',
        right: '-90%'
      }
    },
    '@keyframes indeterminate2': {
      //  |xxxxx|xxxxx||-----||-----|
      '0%': {
        left: '-200%',
        right: '100%'
      },
      //  |-----|-----||-----||-x----|
      '60%': {
        left: '107%',
        right: '-8%'
      },
      '100%': {
        left: '107%',
        right: '-8%'
      }
    },
    '@keyframes buffer': {
      '0%': {
        opacity: 1,
        backgroundPosition: '0px -23px'
      },
      '50%': {
        opacity: 0,
        backgroundPosition: '0px -23px'
      },
      '100%': {
        opacity: 1,
        backgroundPosition: '-200px -23px'
      }
    }
  };
};
/**
 * ## ARIA
 *
 * If the progress bar is describing the loading progress of a particular region of a page,
 * you should use `aria-describedby` to point to the progress bar, and set the `aria-busy`
 * attribute to `true` on that region until it has finished loading.
 */

var LinearProgress_LinearProgress = react_default.a.forwardRef(function LinearProgress(props, ref) {
  var classes = props.classes,
      className = props.className,
      _props$color = props.color,
      color = _props$color === void 0 ? 'primary' : _props$color,
      value = props.value,
      valueBuffer = props.valueBuffer,
      _props$variant = props.variant,
      variant = _props$variant === void 0 ? 'indeterminate' : _props$variant,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["classes", "className", "color", "value", "valueBuffer", "variant"]);

  var theme = useTheme_useTheme();
  var rootProps = {};
  var inlineStyles = {
    bar1: {},
    bar2: {}
  };

  if (variant === 'determinate' || variant === 'buffer') {
    if (value !== undefined) {
      rootProps['aria-valuenow'] = Math.round(value);
      var transform = value - 100;

      if (theme.direction === 'rtl') {
        transform = -transform;
      }

      inlineStyles.bar1.transform = "translateX(".concat(transform, "%)");
    } else if (false) {}
  }

  if (variant === 'buffer') {
    if (valueBuffer !== undefined) {
      var _transform = (valueBuffer || 0) - 100;

      if (theme.direction === 'rtl') {
        _transform = -_transform;
      }

      inlineStyles.bar2.transform = "translateX(".concat(_transform, "%)");
    } else if (false) {}
  }

  return react_default.a.createElement("div", Object(helpers_esm_extends["a" /* default */])({
    className: Object(clsx_m["a" /* default */])(classes.root, classes["color".concat(Object(capitalize["a" /* default */])(color))], className, {
      'determinate': classes.determinate,
      'indeterminate': classes.indeterminate,
      'buffer': classes.buffer,
      'query': classes.query
    }[variant]),
    role: "progressbar"
  }, rootProps, {
    ref: ref
  }, other), variant === 'buffer' ? react_default.a.createElement("div", {
    className: Object(clsx_m["a" /* default */])(classes.dashed, classes["dashedColor".concat(Object(capitalize["a" /* default */])(color))])
  }) : null, react_default.a.createElement("div", {
    className: Object(clsx_m["a" /* default */])(classes.bar, classes["barColor".concat(Object(capitalize["a" /* default */])(color))], (variant === 'indeterminate' || variant === 'query') && classes.bar1Indeterminate, {
      'determinate': classes.bar1Determinate,
      'buffer': classes.bar1Buffer
    }[variant]),
    style: inlineStyles.bar1
  }), variant === 'determinate' ? null : react_default.a.createElement("div", {
    className: Object(clsx_m["a" /* default */])(classes.bar, (variant === 'indeterminate' || variant === 'query') && classes.bar2Indeterminate, variant === 'buffer' ? [classes["color".concat(Object(capitalize["a" /* default */])(color))], classes.bar2Buffer] : classes["barColor".concat(Object(capitalize["a" /* default */])(color))]),
    style: inlineStyles.bar2
  }));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_LinearProgress_LinearProgress = (Object(withStyles["a" /* default */])(LinearProgress_styles, {
  name: 'MuiLinearProgress'
})(LinearProgress_LinearProgress));
// EXTERNAL MODULE: ./node_modules/uuid/v4.js
var v4 = __webpack_require__(27);
var v4_default = /*#__PURE__*/__webpack_require__.n(v4);

// EXTERNAL MODULE: ./node_modules/@material-ui/icons/Search.js
var Search = __webpack_require__(28);
var Search_default = /*#__PURE__*/__webpack_require__.n(Search);

// EXTERNAL MODULE: ./node_modules/@material-ui/icons/Check.js
var Check = __webpack_require__(21);
var Check_default = /*#__PURE__*/__webpack_require__.n(Check);

// CONCATENATED MODULE: ./src/components/QdtSelect/QdtSelect.jsx
/**
 * @name QdtSelect
 * @param {object} layout - Qlik object layout
 * @param {string} model - Qlik object model
 * @param {options} object - Options
*/









var QdtSelect_QdtSelect = function QdtSelect(_ref) {
  var _layout$qListObject3, _layout$qListObject3$, _layout$qListObject4, _layout$qListObject4$;

  var layout = _ref.layout,
      model = _ref.model,
      optionsProp = _ref.options;
  var defaultOptions = {
    multiple: false
  };
  var options = Object(merge["a" /* default */])(defaultOptions, optionsProp);

  var _useRef = Object(react["useRef"])(v4_default()()),
      id = _useRef.current;

  var selectValue = Object(react["useMemo"])(function () {
    var _layout$qListObject, _layout$qListObject$q;

    var sv = ((_layout$qListObject = layout.qListObject) === null || _layout$qListObject === void 0 ? void 0 : (_layout$qListObject$q = _layout$qListObject.qDataPages[0]) === null || _layout$qListObject$q === void 0 ? void 0 : _layout$qListObject$q.qMatrix.filter(function (row) {
      return row[0].qState === 'S';
    })) || [];
    return options.multiple ? sv : sv[0];
  }, [layout.qListObject, options.multiple]);
  var selectRenderValue = Object(react["useMemo"])(function (selected) {
    var _layout$qListObject2, _layout$qListObject2$;

    if (!selected) return;

    if (selected.length === 1) {
      return selected[0][0].qText;
    }

    return "".concat(selected.length, " of ").concat((_layout$qListObject2 = layout.qListObject) === null || _layout$qListObject2 === void 0 ? void 0 : (_layout$qListObject2$ = _layout$qListObject2.qSize) === null || _layout$qListObject2$ === void 0 ? void 0 : _layout$qListObject2$.qcy, " selected");
  }, [layout]);
  var handleOpen = Object(react["useCallback"])(function () {
    model.beginSelections(['/qListObjectDef']);
  }, [model]);
  var handleClose = Object(react["useCallback"])(function () {
    model.endSelections(true);
  }, [model]);
  var handleChange = Object(react["useCallback"])(function (event) {
    var qValues = options.multiple ? event.target.value.map(function (v) {
      return v[0].qElemNumber;
    }) : [event.target.value];
    model.selectListObjectValues('/qListObjectDef', qValues, false);
  }, [model, options.multiple]);
  var handleSearch = Object(react["useCallback"])(function (event) {
    model.searchListObjectFor('/qListObjectDef', event.target.value);
  }, [model]);
  return react_default.a.createElement(react_default.a.Fragment, null, react_default.a.createElement(esm_FormControl_FormControl, {
    variant: "outlined",
    style: {
      width: '100%'
    }
  }, react_default.a.createElement(esm_InputLabel_InputLabel, {
    id: "".concat(id, "-label")
  }, (_layout$qListObject3 = layout.qListObject) === null || _layout$qListObject3 === void 0 ? void 0 : (_layout$qListObject3$ = _layout$qListObject3.qDimensionInfo) === null || _layout$qListObject3$ === void 0 ? void 0 : _layout$qListObject3$.qFallbackTitle), react_default.a.createElement(esm_Select_Select, {
    labelId: "".concat(id, "-label"),
    id: id,
    multiple: options.multiple,
    value: selectValue,
    renderValue: selectRenderValue,
    onOpen: handleOpen,
    onClose: handleClose,
    onChange: handleChange,
    input: react_default.a.createElement(esm_Input_Input, null)
  }, react_default.a.createElement(esm_MenuItem_MenuItem, null, react_default.a.createElement(esm_ListItemIcon_ListItemIcon, null, react_default.a.createElement(Search_default.a, null)), react_default.a.createElement(esm_Input_Input, {
    type: "search",
    onChange: handleSearch,
    disableUnderline: true
  })), (_layout$qListObject4 = layout.qListObject) === null || _layout$qListObject4 === void 0 ? void 0 : (_layout$qListObject4$ = _layout$qListObject4.qDataPages[0]) === null || _layout$qListObject4$ === void 0 ? void 0 : _layout$qListObject4$.qMatrix.map(function (row) {
    return react_default.a.createElement(esm_MenuItem_MenuItem, {
      key: row[0].qElemNumber,
      value: row[0].qElemNumber,
      className: classnames_default()({
        selected: row[0].qState === 'S',
        excluded: row[0].qState === 'X'
      })
    }, react_default.a.createElement(esm_ListItemText_ListItemText, {
      primary: row[0].qText
    }), row[0].qState === 'S' && react_default.a.createElement(esm_ListItemIcon_ListItemIcon, null, react_default.a.createElement(Check_default.a, null)));
  })), react_default.a.createElement(esm_LinearProgress_LinearProgress, {
    variant: "determinate",
    value: 80
  })));
};

QdtSelect_QdtSelect.propTypes = {
  layout: prop_types_default.a.object,
  model: prop_types_default.a.object,
  options: prop_types_default.a.object
};
QdtSelect_QdtSelect.defaultProps = {
  layout: null,
  model: null,
  options: {}
};
/* harmony default export */ var components_QdtSelect_QdtSelect = (QdtSelect_QdtSelect);
// CONCATENATED MODULE: ./src/components/QdtSelect/QdtSelectSimple.jsx
/**
 * @name QdtSelect
 * @param {object} layout - Qlik object layout
 * @param {string} model - Qlik object model
 * @param {options} object - Options
*/







var QdtSelectSimple_QdtSelect = function QdtSelect(_ref) {
  var _layout$qListObject2, _layout$qListObject2$, _layout$qListObject3, _layout$qListObject3$;

  var layout = _ref.layout,
      model = _ref.model,
      optionsProp = _ref.options;
  var defaultOptions = {
    multiple: false
  };
  var options = Object(merge["a" /* default */])(defaultOptions, optionsProp);

  var _useRef = Object(react["useRef"])(v4_default()()),
      id = _useRef.current;

  var selectValue = Object(react["useMemo"])(function () {
    var _layout$qListObject, _layout$qListObject$q;

    var sv = ((_layout$qListObject = layout.qListObject) === null || _layout$qListObject === void 0 ? void 0 : (_layout$qListObject$q = _layout$qListObject.qDataPages[0]) === null || _layout$qListObject$q === void 0 ? void 0 : _layout$qListObject$q.qMatrix.filter(function (row) {
      return row[0].qState === 'S';
    })) || [];
    return options.multiple ? sv : sv[0];
  }, [layout.qListObject, options.multiple]);
  var handleOpen = Object(react["useCallback"])(function () {
    model.beginSelections(['/qListObjectDef']);
  }, [model]);
  var handleClose = Object(react["useCallback"])(function () {
    model.endSelections(true);
  }, [model]);
  var handleChange = Object(react["useCallback"])(function (event) {
    model.selectListObjectValues('/qListObjectDef', [event.target.value], false);
  }, [model]);
  return react_default.a.createElement(react_default.a.Fragment, null, react_default.a.createElement(esm_FormControl_FormControl, {
    variant: "outlined",
    style: {
      width: '100%'
    }
  }, react_default.a.createElement(esm_InputLabel_InputLabel, {
    id: "".concat(id, "-label")
  }, (_layout$qListObject2 = layout.qListObject) === null || _layout$qListObject2 === void 0 ? void 0 : (_layout$qListObject2$ = _layout$qListObject2.qDimensionInfo) === null || _layout$qListObject2$ === void 0 ? void 0 : _layout$qListObject2$.qFallbackTitle), react_default.a.createElement(esm_Select_Select, {
    labelId: "".concat(id, "-label"),
    id: id,
    multiple: options.multiple,
    value: selectValue,
    onOpen: handleOpen,
    onClose: handleClose,
    onChange: handleChange,
    input: react_default.a.createElement(esm_Input_Input, {
      disableUnderline: true
    })
  }, (_layout$qListObject3 = layout.qListObject) === null || _layout$qListObject3 === void 0 ? void 0 : (_layout$qListObject3$ = _layout$qListObject3.qDataPages[0]) === null || _layout$qListObject3$ === void 0 ? void 0 : _layout$qListObject3$.qMatrix.map(function (row) {
    return react_default.a.createElement(esm_MenuItem_MenuItem, {
      key: row[0].qElemNumber,
      value: row[0].qElemNumber,
      className: classnames_default()({
        selected: row[0].qState === 'S',
        excluded: row[0].qState === 'X'
      })
    }, react_default.a.createElement(esm_ListItemText_ListItemText, {
      primary: row[0].qText
    }));
  }))));
};

QdtSelectSimple_QdtSelect.propTypes = {
  layout: prop_types_default.a.object,
  model: prop_types_default.a.object,
  options: prop_types_default.a.object
};
QdtSelectSimple_QdtSelect.defaultProps = {
  layout: null,
  model: null,
  options: {}
};
/* harmony default export */ var QdtSelectSimple = (QdtSelectSimple_QdtSelect);
// CONCATENATED MODULE: ./src/components/QdtList/QdtList.jsx
/**
 * @name QdtSelect
 * @param {object} layout - Qlik object layout
 * @param {string} model - Qlik object model
 * @param {options} object - Options
*/









var QdtList_QdtList = function QdtList(_ref) {
  var _layout$qListObject, _layout$qListObject$q;

  var layout = _ref.layout,
      model = _ref.model,
      optionsProp = _ref.options;
  var defaultOptions = {
    multiple: false,
    height: 400
  };
  var options = Object(merge["a" /* default */])(defaultOptions, optionsProp);

  var _useRef = Object(react["useRef"])(v4_default()()),
      id = _useRef.current;

  var handleSelect = Object(react["useCallback"])(function (qElemNumber) {
    var toggle = !options.multiple;
    model.selectListObjectValues('/qListObjectDef', [qElemNumber], toggle);
  }, [model, options.multiple]);
  var handleSearch = Object(react["useCallback"])(function (event) {
    model.searchListObjectFor('/qListObjectDef', event.target.value);
  }, [model]);
  return react_default.a.createElement(esm_FormControl_FormControl, {
    variant: "outlined",
    style: {
      width: '100%'
    }
  }, react_default.a.createElement(esm_Paper_Paper, null, react_default.a.createElement(esm_MenuList_MenuList, {
    component: "nav",
    className: "qdt-list",
    style: {
      height: options.height,
      overflow: 'auto'
    }
  }, react_default.a.createElement(esm_MenuItem_MenuItem, null, react_default.a.createElement(esm_ListItemIcon_ListItemIcon, null, react_default.a.createElement(Search_default.a, null)), react_default.a.createElement(esm_Input_Input, {
    type: "search",
    onChange: handleSearch,
    id: "".concat(id, "-label"),
    disableUnderline: true
  })), (_layout$qListObject = layout.qListObject) === null || _layout$qListObject === void 0 ? void 0 : (_layout$qListObject$q = _layout$qListObject.qDataPages[0]) === null || _layout$qListObject$q === void 0 ? void 0 : _layout$qListObject$q.qMatrix.map(function (row) {
    return react_default.a.createElement(esm_MenuItem_MenuItem, {
      key: row[0].qElemNumber,
      className: classnames_default()({
        selected: row[0].qState === 'S',
        excluded: row[0].qState === 'X'
      }),
      onClick: function onClick() {
        return handleSelect(row[0].qElemNumber);
      }
    }, react_default.a.createElement(esm_ListItemText_ListItemText, {
      primary: row[0].qText
    }), row[0].qState === 'S' && react_default.a.createElement(esm_ListItemIcon_ListItemIcon, null, react_default.a.createElement(Check_default.a, null)));
  }))));
};

QdtList_QdtList.propTypes = {
  layout: prop_types_default.a.object,
  model: prop_types_default.a.object,
  options: prop_types_default.a.object
};
QdtList_QdtList.defaultProps = {
  layout: null,
  model: null,
  options: {}
};
/* harmony default export */ var components_QdtList_QdtList = (QdtList_QdtList);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/toConsumableArray.js
var toConsumableArray = __webpack_require__(16);
var toConsumableArray_default = /*#__PURE__*/__webpack_require__.n(toConsumableArray);

// CONCATENATED MODULE: ./node_modules/react-table/es/utils.js
var utils_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; };

function _objectWithoutProperties(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; }





//
/* harmony default export */ var utils = ({
  get: get,
  set: set,
  takeRight: takeRight,
  last: last,
  orderBy: orderBy,
  range: utils_range,
  remove: remove,
  clone: clone,
  getFirstDefined: getFirstDefined,
  sum: sum,
  makeTemplateComponent: makeTemplateComponent,
  groupBy: groupBy,
  isArray: isArray,
  splitProps: splitProps,
  compactObject: compactObject,
  isSortingDesc: isSortingDesc,
  normalizeComponent: normalizeComponent,
  asPx: asPx
});

function get(obj, path, def) {
  if (!path) {
    return obj;
  }
  var pathObj = makePathArray(path);
  var val = void 0;
  try {
    val = pathObj.reduce(function (current, pathPart) {
      return current[pathPart];
    }, obj);
  } catch (e) {
    // continue regardless of error
  }
  return typeof val !== 'undefined' ? val : def;
}

function set() {
  var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var path = arguments[1];
  var value = arguments[2];

  var keys = makePathArray(path);
  var keyPart = void 0;
  var cursor = obj;
  while ((keyPart = keys.shift()) && keys.length) {
    if (!cursor[keyPart]) {
      cursor[keyPart] = {};
    }
    cursor = cursor[keyPart];
  }
  cursor[keyPart] = value;
  return obj;
}

function takeRight(arr, n) {
  var start = n > arr.length ? 0 : arr.length - n;
  return arr.slice(start);
}

function last(arr) {
  return arr[arr.length - 1];
}

function utils_range(n) {
  var arr = [];
  for (var i = 0; i < n; i += 1) {
    arr.push(n);
  }
  return arr;
}

function orderBy(arr, funcs, dirs, indexKey) {
  return arr.sort(function (rowA, rowB) {
    for (var i = 0; i < funcs.length; i += 1) {
      var comp = funcs[i];
      var desc = dirs[i] === false || dirs[i] === 'desc';
      var sortInt = comp(rowA, rowB);
      if (sortInt) {
        return desc ? -sortInt : sortInt;
      }
    }
    // Use the row index for tie breakers
    return dirs[0] ? rowA[indexKey] - rowB[indexKey] : rowB[indexKey] - rowA[indexKey];
  });
}

function remove(a, b) {
  return a.filter(function (o, i) {
    var r = b(o);
    if (r) {
      a.splice(i, 1);
      return true;
    }
    return false;
  });
}

function clone(a) {
  try {
    return JSON.parse(JSON.stringify(a, function (key, value) {
      if (typeof value === 'function') {
        return value.toString();
      }
      return value;
    }));
  } catch (e) {
    return a;
  }
}

function getFirstDefined() {
  for (var i = 0; i < arguments.length; i += 1) {
    if (typeof (arguments.length <= i ? undefined : arguments[i]) !== 'undefined') {
      return arguments.length <= i ? undefined : arguments[i];
    }
  }
}

function sum(arr) {
  return arr.reduce(function (a, b) {
    return a + b;
  }, 0);
}

function makeTemplateComponent(compClass, displayName) {
  if (!displayName) {
    throw new Error('No displayName found for template component:', compClass);
  }
  var cmp = function cmp(_ref) {
    var children = _ref.children,
        className = _ref.className,
        rest = _objectWithoutProperties(_ref, ['children', 'className']);

    return react_default.a.createElement(
      'div',
      utils_extends({ className: classnames_default()(compClass, className) }, rest),
      children
    );
  };
  cmp.displayName = displayName;
  return cmp;
}

function groupBy(xs, key) {
  return xs.reduce(function (rv, x, i) {
    var resKey = typeof key === 'function' ? key(x, i) : x[key];
    rv[resKey] = isArray(rv[resKey]) ? rv[resKey] : [];
    rv[resKey].push(x);
    return rv;
  }, {});
}

function asPx(value) {
  value = Number(value);
  return Number.isNaN(value) ? null : value + 'px';
}

function isArray(a) {
  return Array.isArray(a);
}

// ########################################################################
// Non-exported Helpers
// ########################################################################

function makePathArray(obj) {
  return flattenDeep(obj).join('.').replace(/\[/g, '.').replace(/\]/g, '').split('.');
}

function flattenDeep(arr) {
  var newArr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

  if (!isArray(arr)) {
    newArr.push(arr);
  } else {
    for (var i = 0; i < arr.length; i += 1) {
      flattenDeep(arr[i], newArr);
    }
  }
  return newArr;
}

function splitProps(_ref2) {
  var className = _ref2.className,
      style = _ref2.style,
      rest = _objectWithoutProperties(_ref2, ['className', 'style']);

  return {
    className: className,
    style: style,
    rest: rest || {}
  };
}

function compactObject(obj) {
  var newObj = {};
  if (obj) {
    Object.keys(obj).map(function (key) {
      if (Object.prototype.hasOwnProperty.call(obj, key) && obj[key] !== undefined && typeof obj[key] !== 'undefined') {
        newObj[key] = obj[key];
      }
      return true;
    });
  }
  return newObj;
}

function isSortingDesc(d) {
  return !!(d.sort === 'desc' || d.desc === true || d.asc === false);
}

function normalizeComponent(Comp, props) {
  var fallback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Comp;

  if (react_is["isElement"](Comp) || typeof Comp === 'string') {
    return Comp;
  } else if (react_is["isValidElementType"](Comp)) {
    return react_default.a.createElement(Comp, props);
  }

  return fallback;
}
//# sourceMappingURL=data:application/json;base64, 
// CONCATENATED MODULE: ./node_modules/react-table/es/lifecycle.js
var lifecycle_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; }; }();

function lifecycle_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(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; }

function _inherits(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; }

/* harmony default export */ var lifecycle = (function (Base) {
  return function (_Base) {
    _inherits(_class, _Base);

    function _class(props) {
      lifecycle_classCallCheck(this, _class);

      var _this = _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).call(this, props));

      var defaultState = {
        page: props.defaultPage,
        pageSize: props.defaultPageSize,
        sorted: props.defaultSorted,
        expanded: props.defaultExpanded,
        filtered: props.defaultFiltered,
        resized: props.defaultResized,
        currentlyResizing: false,
        skipNextSort: false
      };
      var resolvedState = _this.getResolvedState(props, defaultState);
      var dataModel = _this.getDataModel(resolvedState, true);

      _this.state = _this.calculateNewResolvedState(dataModel);
      return _this;
    }

    lifecycle_createClass(_class, [{
      key: 'componentDidMount',
      value: function componentDidMount() {
        this.fireFetchData();
      }
    }, {
      key: 'componentDidUpdate',
      value: function componentDidUpdate(prevProps, prevState) {
        var oldState = this.getResolvedState(prevProps, prevState);
        var newState = this.getResolvedState(this.props, this.state);

        // Do a deep compare of new and old `defaultOption` and
        // if they are different reset `option = defaultOption`
        var defaultableOptions = ['sorted', 'filtered', 'resized', 'expanded'];
        defaultableOptions.forEach(function (x) {
          var defaultName = 'default' + (x.charAt(0).toUpperCase() + x.slice(1));
          if (JSON.stringify(oldState[defaultName]) !== JSON.stringify(newState[defaultName])) {
            newState[x] = newState[defaultName];
          }
        });

        // If they change these table options, we need to reset defaults
        // or else we could get into a state where the user has changed the UI
        // and then disabled the ability to change it back.
        // e.g. If `filterable` has changed, set `filtered = defaultFiltered`
        var resettableOptions = ['sortable', 'filterable', 'resizable'];
        resettableOptions.forEach(function (x) {
          if (oldState[x] !== newState[x]) {
            var baseName = x.replace('able', '');
            var optionName = baseName + 'ed';
            var defaultName = 'default' + (optionName.charAt(0).toUpperCase() + optionName.slice(1));
            newState[optionName] = newState[defaultName];
          }
        });

        // Props that trigger a data update
        if (oldState.data !== newState.data || oldState.columns !== newState.columns || oldState.pivotBy !== newState.pivotBy || oldState.sorted !== newState.sorted || oldState.filtered !== newState.filtered) {
          this.setStateWithData(this.getDataModel(newState, oldState.data !== newState.data));
        }
      }
    }, {
      key: 'calculateNewResolvedState',
      value: function calculateNewResolvedState(dataModel) {
        var oldState = this.getResolvedState();
        var newResolvedState = this.getResolvedState({}, dataModel);
        var freezeWhenExpanded = newResolvedState.freezeWhenExpanded;

        // Default to unfrozen state

        newResolvedState.frozen = false;

        // If freezeWhenExpanded is set, check for frozen conditions
        if (freezeWhenExpanded) {
          // if any rows are expanded, freeze the existing data and sorting
          var keys = Object.keys(newResolvedState.expanded);
          for (var i = 0; i < keys.length; i += 1) {
            if (newResolvedState.expanded[keys[i]]) {
              newResolvedState.frozen = true;
              break;
            }
          }
        }

        // If the data isn't frozen and either the data or
        // sorting model has changed, update the data
        if (oldState.frozen && !newResolvedState.frozen || oldState.sorted !== newResolvedState.sorted || oldState.filtered !== newResolvedState.filtered || oldState.showFilters !== newResolvedState.showFilters || !newResolvedState.frozen && oldState.resolvedData !== newResolvedState.resolvedData) {
          // Handle collapseOnsortedChange & collapseOnDataChange
          if (oldState.sorted !== newResolvedState.sorted && this.props.collapseOnSortingChange || oldState.filtered !== newResolvedState.filtered || oldState.showFilters !== newResolvedState.showFilters || oldState.sortedData && !newResolvedState.frozen && oldState.resolvedData !== newResolvedState.resolvedData && this.props.collapseOnDataChange) {
            newResolvedState.expanded = {};
          }

          Object.assign(newResolvedState, this.getSortedData(newResolvedState));
        }

        // Set page to 0 if filters change
        if (oldState.filtered !== newResolvedState.filtered) {
          newResolvedState.page = 0;
        }

        // Calculate pageSize all the time
        if (newResolvedState.sortedData) {
          newResolvedState.pages = newResolvedState.manual ? newResolvedState.pages : Math.ceil(newResolvedState.sortedData.length / newResolvedState.pageSize);
          newResolvedState.page = newResolvedState.manual ? newResolvedState.page : Math.max(newResolvedState.page >= newResolvedState.pages ? newResolvedState.pages - 1 : newResolvedState.page, 0);
        }

        return newResolvedState;
      }
    }, {
      key: 'setStateWithData',
      value: function setStateWithData(dataModel, cb) {
        var _this2 = this;

        var oldState = this.getResolvedState();
        var newResolvedState = this.calculateNewResolvedState(dataModel);

        return this.setState(newResolvedState, function () {
          if (cb) {
            cb();
          }
          if (oldState.page !== newResolvedState.page || oldState.pageSize !== newResolvedState.pageSize || oldState.sorted !== newResolvedState.sorted || oldState.filtered !== newResolvedState.filtered) {
            _this2.fireFetchData();
          }
        });
      }
    }]);

    return _class;
  }(Base);
});
//# sourceMappingURL=data:application/json;base64, 
// CONCATENATED MODULE: ./node_modules/react-table/es/methods.js
var methods_slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var methods_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 methods_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; }; }();

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function methods_toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function methods_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function methods_possibleConstructorReturn(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; }

function methods_inherits(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; }




/* harmony default export */ var methods = (function (Base) {
  return function (_Base) {
    methods_inherits(_class, _Base);

    function _class() {
      methods_classCallCheck(this, _class);

      return methods_possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).apply(this, arguments));
    }

    methods_createClass(_class, [{
      key: 'getResolvedState',
      value: function getResolvedState(props, state) {
        var resolvedState = methods_extends({}, utils.compactObject(this.state), utils.compactObject(this.props), utils.compactObject(state), utils.compactObject(props));
        return resolvedState;
      }
    }, {
      key: 'getDataModel',
      value: function getDataModel(newState, dataChanged) {
        var _this2 = this;

        var columns = newState.columns,
            _newState$pivotBy = newState.pivotBy,
            pivotBy = _newState$pivotBy === undefined ? [] : _newState$pivotBy,
            data = newState.data,
            resolveData = newState.resolveData,
            pivotIDKey = newState.pivotIDKey,
            pivotValKey = newState.pivotValKey,
            subRowsKey = newState.subRowsKey,
            aggregatedKey = newState.aggregatedKey,
            nestingLevelKey = newState.nestingLevelKey,
            originalKey = newState.originalKey,
            indexKey = newState.indexKey,
            groupedByPivotKey = newState.groupedByPivotKey,
            SubComponent = newState.SubComponent;

        // Determine Header Groups

        var hasHeaderGroups = false;
        columns.forEach(function (column) {
          if (column.columns) {
            hasHeaderGroups = true;
          }
        });

        var columnsWithExpander = [].concat(methods_toConsumableArray(columns));

        var expanderColumn = columns.find(function (col) {
          return col.expander || col.columns && col.columns.some(function (col2) {
            return col2.expander;
          });
        });
        // The actual expander might be in the columns field of a group column
        if (expanderColumn && !expanderColumn.expander) {
          expanderColumn = expanderColumn.columns.find(function (col) {
            return col.expander;
          });
        }

        // If we have SubComponent's we need to make sure we have an expander column
        if (SubComponent && !expanderColumn) {
          expanderColumn = { expander: true };
          columnsWithExpander = [expanderColumn].concat(methods_toConsumableArray(columnsWithExpander));
        }

        var makeDecoratedColumn = function makeDecoratedColumn(column, parentColumn) {
          var dcol = void 0;
          if (column.expander) {
            dcol = methods_extends({}, _this2.props.column, _this2.props.expanderDefaults, column);
          } else {
            dcol = methods_extends({}, _this2.props.column, column);
          }

          // Ensure minWidth is not greater than maxWidth if set
          if (dcol.maxWidth < dcol.minWidth) {
            dcol.minWidth = dcol.maxWidth;
          }

          if (parentColumn) {
            dcol.parentColumn = parentColumn;
          }

          // First check for string accessor
          if (typeof dcol.accessor === 'string') {
            dcol.id = dcol.id || dcol.accessor;
            var accessorString = dcol.accessor;
            dcol.accessor = function (row) {
              return utils.get(row, accessorString);
            };
            return dcol;
          }

          // Fall back to functional accessor (but require an ID)
          if (dcol.accessor && !dcol.id) {
            console.warn(dcol);
            throw new Error('A column id is required if using a non-string accessor for column above.');
          }

          // Fall back to an undefined accessor
          if (!dcol.accessor) {
            dcol.accessor = function () {
              return undefined;
            };
          }

          return dcol;
        };

        var allDecoratedColumns = [];

        // Decorate the columns
        var decorateAndAddToAll = function decorateAndAddToAll(column, parentColumn) {
          var decoratedColumn = makeDecoratedColumn(column, parentColumn);
          allDecoratedColumns.push(decoratedColumn);
          return decoratedColumn;
        };

        var decoratedColumns = columnsWithExpander.map(function (column) {
          if (column.columns) {
            return methods_extends({}, column, {
              columns: column.columns.map(function (d) {
                return decorateAndAddToAll(d, column);
              })
            });
          }
          return decorateAndAddToAll(column);
        });

        // Build the visible columns, headers and flat column list
        var visibleColumns = decoratedColumns.slice();
        var allVisibleColumns = [];

        visibleColumns = visibleColumns.map(function (column) {
          if (column.columns) {
            var visibleSubColumns = column.columns.filter(function (d) {
              return pivotBy.indexOf(d.id) > -1 ? false : utils.getFirstDefined(d.show, true);
            });
            return methods_extends({}, column, {
              columns: visibleSubColumns
            });
          }
          return column;
        });

        visibleColumns = visibleColumns.filter(function (column) {
          return column.columns ? column.columns.length : pivotBy.indexOf(column.id) > -1 ? false : utils.getFirstDefined(column.show, true);
        });

        // Find any custom pivot location
        var pivotIndex = visibleColumns.findIndex(function (col) {
          return col.pivot;
        });

        // Handle Pivot Columns
        if (pivotBy.length) {
          // Retrieve the pivot columns in the correct pivot order
          var pivotColumns = [];
          pivotBy.forEach(function (pivotID) {
            var found = allDecoratedColumns.find(function (d) {
              return d.id === pivotID;
            });
            if (found) {
              pivotColumns.push(found);
            }
          });

          var PivotParentColumn = pivotColumns.reduce(function (prev, current) {
            return prev && prev === current.parentColumn && current.parentColumn;
          }, pivotColumns[0].parentColumn);

          var PivotGroupHeader = hasHeaderGroups && PivotParentColumn.Header;
          PivotGroupHeader = PivotGroupHeader || function () {
            return react_default.a.createElement(
              'strong',
              null,
              'Pivoted'
            );
          };

          var pivotColumnGroup = {
            Header: PivotGroupHeader,
            columns: pivotColumns.map(function (col) {
              return methods_extends({}, _this2.props.pivotDefaults, col, {
                pivoted: true
              });
            })

            // Place the pivotColumns back into the visibleColumns
          };if (pivotIndex >= 0) {
            pivotColumnGroup = methods_extends({}, visibleColumns[pivotIndex], pivotColumnGroup);
            visibleColumns.splice(pivotIndex, 1, pivotColumnGroup);
          } else {
            visibleColumns.unshift(pivotColumnGroup);
          }
        }

        // Build Header Groups
        var headerGroups = [];
        var currentSpan = [];

        // A convenience function to add a header and reset the currentSpan
        var addHeader = function addHeader(columns, column) {
          headerGroups.push(methods_extends({}, _this2.props.column, column, {
            columns: columns
          }));
          currentSpan = [];
        };

        // Build flast list of allVisibleColumns and HeaderGroups
        visibleColumns.forEach(function (column) {
          if (column.columns) {
            allVisibleColumns = allVisibleColumns.concat(column.columns);
            if (currentSpan.length > 0) {
              addHeader(currentSpan);
            }
            addHeader(column.columns, column);
            return;
          }
          allVisibleColumns.push(column);
          currentSpan.push(column);
        });
        if (hasHeaderGroups && currentSpan.length > 0) {
          addHeader(currentSpan);
        }

        // Access the data
        var accessRow = function accessRow(d, i) {
          var _row;

          var level = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;

          var row = (_row = {}, _defineProperty(_row, originalKey, d), _defineProperty(_row, indexKey, i), _defineProperty(_row, subRowsKey, d[subRowsKey]), _defineProperty(_row, nestingLevelKey, level), _row);
          allDecoratedColumns.forEach(function (column) {
            if (column.expander) return;
            row[column.id] = column.accessor(d);
          });
          if (row[subRowsKey]) {
            row[subRowsKey] = row[subRowsKey].map(function (d, i) {
              return accessRow(d, i, level + 1);
            });
          }
          return row;
        };

        // // If the data hasn't changed, just use the cached data
        var resolvedData = this.resolvedData;
        // If the data has changed, run the data resolver and cache the result
        if (!this.resolvedData || dataChanged) {
          resolvedData = resolveData(data);
          this.resolvedData = resolvedData;
        }
        // Use the resolved data
        resolvedData = resolvedData.map(function (d, i) {
          return accessRow(d, i);
        });

        // TODO: Make it possible to fabricate nested rows without pivoting
        var aggregatingColumns = allVisibleColumns.filter(function (d) {
          return !d.expander && d.aggregate;
        });

        // If pivoting, recursively group the data
        var aggregate = function aggregate(rows) {
          var aggregationValues = {};
          aggregatingColumns.forEach(function (column) {
            var values = rows.map(function (d) {
              return d[column.id];
            });
            aggregationValues[column.id] = column.aggregate(values, rows);
          });
          return aggregationValues;
        };
        if (pivotBy.length) {
          var groupRecursively = function groupRecursively(rows, keys) {
            var i = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;

            // This is the last level, just return the rows
            if (i === keys.length) {
              return rows;
            }
            // Group the rows together for this level
            var groupedRows = Object.entries(utils.groupBy(rows, keys[i])).map(function (_ref) {
              var _ref3;

              var _ref2 = methods_slicedToArray(_ref, 2),
                  key = _ref2[0],
                  value = _ref2[1];

              return _ref3 = {}, _defineProperty(_ref3, pivotIDKey, keys[i]), _defineProperty(_ref3, pivotValKey, key), _defineProperty(_ref3, keys[i], key), _defineProperty(_ref3, subRowsKey, value), _defineProperty(_ref3, nestingLevelKey, i), _defineProperty(_ref3, groupedByPivotKey, true), _ref3;
            });
            // Recurse into the subRows
            groupedRows = groupedRows.map(function (rowGroup) {
              var _extends2;

              var subRows = groupRecursively(rowGroup[subRowsKey], keys, i + 1);
              return methods_extends({}, rowGroup, (_extends2 = {}, _defineProperty(_extends2, subRowsKey, subRows), _defineProperty(_extends2, aggregatedKey, true), _extends2), aggregate(subRows));
            });
            return groupedRows;
          };
          resolvedData = groupRecursively(resolvedData, pivotBy);
        }

        return methods_extends({}, newState, {
          resolvedData: resolvedData,
          allVisibleColumns: allVisibleColumns,
          headerGroups: headerGroups,
          allDecoratedColumns: allDecoratedColumns,
          hasHeaderGroups: hasHeaderGroups
        });
      }
    }, {
      key: 'getSortedData',
      value: function getSortedData(resolvedState) {
        var manual = resolvedState.manual,
            sorted = resolvedState.sorted,
            filtered = resolvedState.filtered,
            defaultFilterMethod = resolvedState.defaultFilterMethod,
            resolvedData = resolvedState.resolvedData,
            allDecoratedColumns = resolvedState.allDecoratedColumns;


        var sortMethodsByColumnID = {};

        allDecoratedColumns.filter(function (col) {
          return col.sortMethod;
        }).forEach(function (col) {
          sortMethodsByColumnID[col.id] = col.sortMethod;
        });

        // Resolve the data from either manual data or sorted data
        return {
          sortedData: manual ? resolvedData : this.sortData(this.filterData(resolvedData, filtered, defaultFilterMethod, allDecoratedColumns), sorted, sortMethodsByColumnID)
        };
      }
    }, {
      key: 'fireFetchData',
      value: function fireFetchData() {
        // determine the current state, preferring certain state values over props
        var currentState = methods_extends({}, this.getResolvedState(), {
          page: this.getStateOrProp('page'),
          pageSize: this.getStateOrProp('pageSize'),
          filtered: this.getStateOrProp('filtered')
        });

        this.props.onFetchData(currentState, this);
      }
    }, {
      key: 'getPropOrState',
      value: function getPropOrState(key) {
        return utils.getFirstDefined(this.props[key], this.state[key]);
      }
    }, {
      key: 'getStateOrProp',
      value: function getStateOrProp(key) {
        return utils.getFirstDefined(this.state[key], this.props[key]);
      }
    }, {
      key: 'filterData',
      value: function filterData(data, filtered, defaultFilterMethod, allVisibleColumns) {
        var _this3 = this;

        var filteredData = data;

        if (filtered.length) {
          filteredData = filtered.reduce(function (filteredSoFar, nextFilter) {
            var column = allVisibleColumns.find(function (x) {
              return x.id === nextFilter.id;
            });

            // Don't filter hidden columns or columns that have had their filters disabled
            if (!column || column.filterable === false) {
              return filteredSoFar;
            }

            var filterMethod = column.filterMethod || defaultFilterMethod;

            // If 'filterAll' is set to true, pass the entire dataset to the filter method
            if (column.filterAll) {
              return filterMethod(nextFilter, filteredSoFar, column);
            }
            return filteredSoFar.filter(function (row) {
              return filterMethod(nextFilter, row, column);
            });
          }, filteredData);

          // Apply the filter to the subrows if we are pivoting, and then
          // filter any rows without subcolumns because it would be strange to show
          filteredData = filteredData.map(function (row) {
            if (!row[_this3.props.subRowsKey]) {
              return row;
            }
            return methods_extends({}, row, _defineProperty({}, _this3.props.subRowsKey, _this3.filterData(row[_this3.props.subRowsKey], filtered, defaultFilterMethod, allVisibleColumns)));
          }).filter(function (row) {
            if (!row[_this3.props.subRowsKey]) {
              return true;
            }
            return row[_this3.props.subRowsKey].length > 0;
          });
        }

        return filteredData;
      }
    }, {
      key: 'sortData',
      value: function sortData(data, sorted) {
        var _this4 = this;

        var sortMethodsByColumnID = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

        if (!sorted.length) {
          return data;
        }

        var sortedData = (this.props.orderByMethod || utils.orderBy)(data, sorted.map(function (sort) {
          // Support custom sorting methods for each column
          if (sortMethodsByColumnID[sort.id]) {
            return function (a, b) {
              return sortMethodsByColumnID[sort.id](a[sort.id], b[sort.id], sort.desc);
            };
          }
          return function (a, b) {
            return _this4.props.defaultSortMethod(a[sort.id], b[sort.id], sort.desc);
          };
        }), sorted.map(function (d) {
          return !d.desc;
        }), this.props.indexKey);

        sortedData.forEach(function (row) {
          if (!row[_this4.props.subRowsKey]) {
            return;
          }
          row[_this4.props.subRowsKey] = _this4.sortData(row[_this4.props.subRowsKey], sorted, sortMethodsByColumnID);
        });

        return sortedData;
      }
    }, {
      key: 'getMinRows',
      value: function getMinRows() {
        return utils.getFirstDefined(this.props.minRows, this.getStateOrProp('pageSize'));
      }

      // User actions

    }, {
      key: 'onPageChange',
      value: function onPageChange(page) {
        var _props = this.props,
            onPageChange = _props.onPageChange,
            collapseOnPageChange = _props.collapseOnPageChange;


        var newState = { page: page };
        if (collapseOnPageChange) {
          newState.expanded = {};
        }
        this.setStateWithData(newState, function () {
          return onPageChange && onPageChange(page);
        });
      }
    }, {
      key: 'onPageSizeChange',
      value: function onPageSizeChange(newPageSize) {
        var onPageSizeChange = this.props.onPageSizeChange;

        var _getResolvedState = this.getResolvedState(),
            pageSize = _getResolvedState.pageSize,
            page = _getResolvedState.page;

        // Normalize the page to display


        var currentRow = pageSize * page;
        var newPage = Math.floor(currentRow / newPageSize);

        this.setStateWithData({
          pageSize: newPageSize,
          page: newPage
        }, function () {
          return onPageSizeChange && onPageSizeChange(newPageSize, newPage);
        });
      }
    }, {
      key: 'sortColumn',
      value: function sortColumn(column, additive) {
        var _getResolvedState2 = this.getResolvedState(),
            sorted = _getResolvedState2.sorted,
            skipNextSort = _getResolvedState2.skipNextSort,
            defaultSortDesc = _getResolvedState2.defaultSortDesc;

        var firstSortDirection = Object.prototype.hasOwnProperty.call(column, 'defaultSortDesc') ? column.defaultSortDesc : defaultSortDesc;
        var secondSortDirection = !firstSortDirection;

        // we can't stop event propagation from the column resize move handlers
        // attached to the document because of react's synthetic events
        // so we have to prevent the sort function from actually sorting
        // if we click on the column resize element within a header.
        if (skipNextSort) {
          this.setStateWithData({
            skipNextSort: false
          });
          return;
        }

        var onSortedChange = this.props.onSortedChange;


        var newSorted = utils.clone(sorted || []).map(function (d) {
          d.desc = utils.isSortingDesc(d);
          return d;
        });
        if (!utils.isArray(column)) {
          // Single-Sort
          var existingIndex = newSorted.findIndex(function (d) {
            return d.id === column.id;
          });
          if (existingIndex > -1) {
            var existing = newSorted[existingIndex];
            if (existing.desc === secondSortDirection) {
              if (additive) {
                newSorted.splice(existingIndex, 1);
              } else {
                existing.desc = firstSortDirection;
                newSorted = [existing];
              }
            } else {
              existing.desc = secondSortDirection;
              if (!additive) {
                newSorted = [existing];
              }
            }
          } else if (additive) {
            newSorted.push({
              id: column.id,
              desc: firstSortDirection
            });
          } else {
            newSorted = [{
              id: column.id,
              desc: firstSortDirection
            }];
          }
        } else {
          // Multi-Sort
          var _existingIndex = newSorted.findIndex(function (d) {
            return d.id === column[0].id;
          });
          // Existing Sorted Column
          if (_existingIndex > -1) {
            var _existing = newSorted[_existingIndex];
            if (_existing.desc === secondSortDirection) {
              if (additive) {
                newSorted.splice(_existingIndex, column.length);
              } else {
                column.forEach(function (d, i) {
                  newSorted[_existingIndex + i].desc = firstSortDirection;
                });
              }
            } else {
              column.forEach(function (d, i) {
                newSorted[_existingIndex + i].desc = secondSortDirection;
              });
            }
            if (!additive) {
              newSorted = newSorted.slice(_existingIndex, column.length);
            }
            // New Sort Column
          } else if (additive) {
            newSorted = newSorted.concat(column.map(function (d) {
              return {
                id: d.id,
                desc: firstSortDirection
              };
            }));
          } else {
            newSorted = column.map(function (d) {
              return {
                id: d.id,
                desc: firstSortDirection
              };
            });
          }
        }

        this.setStateWithData({
          page: !sorted.length && newSorted.length || !additive ? 0 : this.state.page,
          sorted: newSorted
        }, function () {
          return onSortedChange && onSortedChange(newSorted, column, additive);
        });
      }
    }, {
      key: 'filterColumn',
      value: function filterColumn(column, value) {
        var _getResolvedState3 = this.getResolvedState(),
            filtered = _getResolvedState3.filtered;

        var onFilteredChange = this.props.onFilteredChange;

        // Remove old filter first if it exists

        var newFiltering = (filtered || []).filter(function (x) {
          return x.id !== column.id;
        });

        if (value !== '') {
          newFiltering.push({
            id: column.id,
            value: value
          });
        }

        this.setStateWithData({
          filtered: newFiltering
        }, function () {
          return onFilteredChange && onFilteredChange(newFiltering, column, value);
        });
      }
    }, {
      key: 'resizeColumnStart',
      value: function resizeColumnStart(event, column, isTouch) {
        var _this5 = this;

        event.stopPropagation();
        var parentWidth = event.target.parentElement.getBoundingClientRect().width;

        var pageX = void 0;
        if (isTouch) {
          pageX = event.changedTouches[0].pageX;
        } else {
          pageX = event.pageX;
        }

        this.trapEvents = true;
        this.setStateWithData({
          currentlyResizing: {
            id: column.id,
            startX: pageX,
            parentWidth: parentWidth
          }
        }, function () {
          if (isTouch) {
            document.addEventListener('touchmove', _this5.resizeColumnMoving);
            document.addEventListener('touchcancel', _this5.resizeColumnEnd);
            document.addEventListener('touchend', _this5.resizeColumnEnd);
          } else {
            document.addEventListener('mousemove', _this5.resizeColumnMoving);
            document.addEventListener('mouseup', _this5.resizeColumnEnd);
            document.addEventListener('mouseleave', _this5.resizeColumnEnd);
          }
        });
      }
    }, {
      key: 'resizeColumnMoving',
      value: function resizeColumnMoving(event) {
        event.stopPropagation();
        var _props2 = this.props,
            onResizedChange = _props2.onResizedChange,
            column = _props2.column;

        var _getResolvedState4 = this.getResolvedState(),
            resized = _getResolvedState4.resized,
            currentlyResizing = _getResolvedState4.currentlyResizing,
            columns = _getResolvedState4.columns;

        var currentColumn = columns.find(function (c) {
          return c.accessor === currentlyResizing.id || c.id === currentlyResizing.id;
        });
        var minResizeWidth = currentColumn && currentColumn.minResizeWidth != null ? currentColumn.minResizeWidth : column.minResizeWidth;

        // Delete old value
        var newResized = resized.filter(function (x) {
          return x.id !== currentlyResizing.id;
        });

        var pageX = void 0;

        if (event.type === 'touchmove') {
          pageX = event.changedTouches[0].pageX;
        } else if (event.type === 'mousemove') {
          pageX = event.pageX;
        }

        var newWidth = Math.max(currentlyResizing.parentWidth + pageX - currentlyResizing.startX, minResizeWidth);

        newResized.push({
          id: currentlyResizing.id,
          value: newWidth
        });

        this.setStateWithData({
          resized: newResized
        }, function () {
          return onResizedChange && onResizedChange(newResized, event);
        });
      }
    }, {
      key: 'resizeColumnEnd',
      value: function resizeColumnEnd(event) {
        event.stopPropagation();
        var isTouch = event.type === 'touchend' || event.type === 'touchcancel';

        if (isTouch) {
          document.removeEventListener('touchmove', this.resizeColumnMoving);
          document.removeEventListener('touchcancel', this.resizeColumnEnd);
          document.removeEventListener('touchend', this.resizeColumnEnd);
        }

        // If its a touch event clear the mouse one's as well because sometimes
        // the mouseDown event gets called as well, but the mouseUp event doesn't
        document.removeEventListener('mousemove', this.resizeColumnMoving);
        document.removeEventListener('mouseup', this.resizeColumnEnd);
        document.removeEventListener('mouseleave', this.resizeColumnEnd);

        // The touch events don't propagate up to the sorting's onMouseDown event so
        // no need to prevent it from happening or else the first click after a touch
        // event resize will not sort the column.
        if (!isTouch) {
          this.setStateWithData({
            skipNextSort: true,
            currentlyResizing: false
          });
        }
      }
    }]);

    return _class;
  }(Base);
});
//# sourceMappingURL=data:application/json;base64, 
// CONCATENATED MODULE: ./node_modules/react-table/es/pagination.js
var pagination_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 pagination_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; };

function pagination_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function pagination_possibleConstructorReturn(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; }

function pagination_inherits(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 pagination_defaultButton = function defaultButton(props) {
  return react_default.a.createElement(
    'button',
    pagination_extends({ type: 'button' }, props, { className: '-btn' }),
    props.children
  );
};

var pagination_ReactTablePagination = function (_Component) {
  pagination_inherits(ReactTablePagination, _Component);

  function ReactTablePagination(props) {
    pagination_classCallCheck(this, ReactTablePagination);

    var _this = pagination_possibleConstructorReturn(this, (ReactTablePagination.__proto__ || Object.getPrototypeOf(ReactTablePagination)).call(this, props));

    _this.getSafePage = _this.getSafePage.bind(_this);
    _this.changePage = _this.changePage.bind(_this);
    _this.applyPage = _this.applyPage.bind(_this);

    _this.state = {
      page: props.page
    };
    return _this;
  }

  pagination_createClass(ReactTablePagination, [{
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps, prevState) {
      if (prevProps.page !== this.props.page && prevState.page !== this.state.page) {
        // this is probably safe because we only update when old/new state.page are different
        // eslint-disable-next-line react/no-did-update-set-state
        this.setState({
          page: this.props.page
        });
      }
    }
  }, {
    key: 'getSafePage',
    value: function getSafePage(page) {
      if (Number.isNaN(page)) {
        page = this.props.page;
      }
      return Math.min(Math.max(page, 0), this.props.pages - 1);
    }
  }, {
    key: 'changePage',
    value: function changePage(page) {
      page = this.getSafePage(page);
      this.setState({ page: page });
      if (this.props.page !== page) {
        this.props.onPageChange(page);
      }
    }
  }, {
    key: 'applyPage',
    value: function applyPage(e) {
      if (e) {
        e.preventDefault();
      }
      var page = this.state.page;
      this.changePage(page === '' ? this.props.page : page);
    }
  }, {
    key: 'getPageJumpProperties',
    value: function getPageJumpProperties() {
      var _this2 = this;

      return {
        onKeyPress: function onKeyPress(e) {
          if (e.which === 13 || e.keyCode === 13) {
            _this2.applyPage();
          }
        },
        onBlur: this.applyPage,
        value: this.state.page === '' ? '' : this.state.page + 1,
        onChange: function onChange(e) {
          var val = e.target.value;
          var page = val - 1;
          if (val === '') {
            return _this2.setState({ page: val });
          }
          _this2.setState({ page: _this2.getSafePage(page) });
        },
        inputType: this.state.page === '' ? 'text' : 'number',
        pageJumpText: this.props.pageJumpText
      };
    }
  }, {
    key: 'render',
    value: function render() {
      var _this3 = this;

      var _props = this.props,
          pages = _props.pages,
          page = _props.page,
          showPageSizeOptions = _props.showPageSizeOptions,
          pageSizeOptions = _props.pageSizeOptions,
          pageSize = _props.pageSize,
          showPageJump = _props.showPageJump,
          canPrevious = _props.canPrevious,
          canNext = _props.canNext,
          onPageSizeChange = _props.onPageSizeChange,
          className = _props.className,
          PreviousComponent = _props.PreviousComponent,
          NextComponent = _props.NextComponent,
          renderPageJump = _props.renderPageJump,
          renderCurrentPage = _props.renderCurrentPage,
          renderTotalPagesCount = _props.renderTotalPagesCount,
          renderPageSizeOptions = _props.renderPageSizeOptions;


      return react_default.a.createElement(
        'div',
        { className: classnames_default()(className, '-pagination'), style: this.props.style },
        react_default.a.createElement(
          'div',
          { className: '-previous' },
          react_default.a.createElement(
            PreviousComponent,
            {
              onClick: function onClick() {
                if (!canPrevious) return;
                _this3.changePage(page - 1);
              },
              disabled: !canPrevious
            },
            this.props.previousText
          )
        ),
        react_default.a.createElement(
          'div',
          { className: '-center' },
          react_default.a.createElement(
            'span',
            { className: '-pageInfo' },
            this.props.pageText,
            ' ',
            showPageJump ? renderPageJump(this.getPageJumpProperties()) : renderCurrentPage(page),
            ' ',
            this.props.ofText,
            ' ',
            renderTotalPagesCount(pages)
          ),
          showPageSizeOptions && renderPageSizeOptions({
            pageSize: pageSize,
            rowsSelectorText: this.props.rowsSelectorText,
            pageSizeOptions: pageSizeOptions,
            onPageSizeChange: onPageSizeChange,
            rowsText: this.props.rowsText
          })
        ),
        react_default.a.createElement(
          'div',
          { className: '-next' },
          react_default.a.createElement(
            NextComponent,
            {
              onClick: function onClick() {
                if (!canNext) return;
                _this3.changePage(page + 1);
              },
              disabled: !canNext
            },
            this.props.nextText
          )
        )
      );
    }
  }]);

  return ReactTablePagination;
}(react["Component"]);

pagination_ReactTablePagination.defaultProps = {
  PreviousComponent: pagination_defaultButton,
  NextComponent: pagination_defaultButton,
  renderPageJump: function renderPageJump(_ref) {
    var onChange = _ref.onChange,
        value = _ref.value,
        onBlur = _ref.onBlur,
        onKeyPress = _ref.onKeyPress,
        inputType = _ref.inputType,
        pageJumpText = _ref.pageJumpText;
    return react_default.a.createElement(
      'div',
      { className: '-pageJump' },
      react_default.a.createElement('input', {
        'aria-label': pageJumpText,
        type: inputType,
        onChange: onChange,
        value: value,
        onBlur: onBlur,
        onKeyPress: onKeyPress
      })
    );
  },
  renderCurrentPage: function renderCurrentPage(page) {
    return react_default.a.createElement(
      'span',
      { className: '-currentPage' },
      page + 1
    );
  },
  renderTotalPagesCount: function renderTotalPagesCount(pages) {
    return react_default.a.createElement(
      'span',
      { className: '-totalPages' },
      pages || 1
    );
  },
  renderPageSizeOptions: function renderPageSizeOptions(_ref2) {
    var pageSize = _ref2.pageSize,
        pageSizeOptions = _ref2.pageSizeOptions,
        rowsSelectorText = _ref2.rowsSelectorText,
        onPageSizeChange = _ref2.onPageSizeChange,
        rowsText = _ref2.rowsText;
    return react_default.a.createElement(
      'span',
      { className: 'select-wrap -pageSizeOptions' },
      react_default.a.createElement(
        'select',
        {
          'aria-label': rowsSelectorText,
          onChange: function onChange(e) {
            return onPageSizeChange(Number(e.target.value));
          },
          value: pageSize
        },
        pageSizeOptions.map(function (option, i) {
          return (
            // eslint-disable-next-line react/no-array-index-key
            react_default.a.createElement(
              'option',
              { key: i, value: option },
              option + ' ' + rowsText
            )
          );
        })
      )
    );
  }
};
/* harmony default export */ var pagination = (pagination_ReactTablePagination);
//# sourceMappingURL=data:application/json;base64, 
// CONCATENATED MODULE: ./node_modules/react-table/es/defaultProps.js
var defaultProps_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; };

function defaultProps_objectWithoutProperties(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 emptyObj = function emptyObj() {
  return {};
};

/* harmony default export */ var es_defaultProps = ({
  // General
  data: [],
  resolveData: function resolveData(data) {
    return data;
  },
  loading: false,
  showPagination: true,
  showPaginationTop: false,
  showPaginationBottom: true,
  showPageSizeOptions: true,
  pageSizeOptions: [5, 10, 20, 25, 50, 100],
  defaultPage: 0,
  defaultPageSize: 20,
  showPageJump: true,
  collapseOnSortingChange: true,
  collapseOnPageChange: true,
  collapseOnDataChange: true,
  freezeWhenExpanded: false,
  sortable: true,
  multiSort: true,
  resizable: true,
  filterable: false,
  defaultSortDesc: false,
  defaultSorted: [],
  defaultFiltered: [],
  defaultResized: [],
  defaultExpanded: {},
  // eslint-disable-next-line no-unused-vars
  defaultFilterMethod: function defaultFilterMethod(filter, row, column) {
    var id = filter.pivotId || filter.id;
    return row[id] !== undefined ? String(row[id]).startsWith(filter.value) : true;
  },
  // eslint-disable-next-line no-unused-vars
  defaultSortMethod: function defaultSortMethod(a, b, desc) {
    // force null and undefined to the bottom
    a = a === null || a === undefined ? '' : a;
    b = b === null || b === undefined ? '' : b;
    // force any string values to lowercase
    a = typeof a === 'string' ? a.toLowerCase() : a;
    b = typeof b === 'string' ? b.toLowerCase() : b;
    // Return either 1 or -1 to indicate a sort priority
    if (a > b) {
      return 1;
    }
    if (a < b) {
      return -1;
    }
    // returning 0, undefined or any falsey value will use subsequent sorts or
    // the index as a tiebreaker
    return 0;
  },

  // Controlled State Props
  // page: undefined,
  // pageSize: undefined,
  // sorted: [],
  // filtered: [],
  // resized: [],
  // expanded: {},

  // Controlled State Callbacks
  onPageChange: undefined,
  onPageSizeChange: undefined,
  onSortedChange: undefined,
  onFilteredChange: undefined,
  onResizedChange: undefined,
  onExpandedChange: undefined,

  // Pivoting
  pivotBy: undefined,

  // Key Constants
  pivotValKey: '_pivotVal',
  pivotIDKey: '_pivotID',
  subRowsKey: '_subRows',
  aggregatedKey: '_aggregated',
  nestingLevelKey: '_nestingLevel',
  originalKey: '_original',
  indexKey: '_index',
  groupedByPivotKey: '_groupedByPivot',

  // Server-side Callbacks
  onFetchData: function onFetchData() {
    return null;
  },

  // Classes
  className: '',
  style: {},

  // Component decorators
  getProps: emptyObj,
  getTableProps: emptyObj,
  getTheadGroupProps: emptyObj,
  getTheadGroupTrProps: emptyObj,
  getTheadGroupThProps: emptyObj,
  getTheadProps: emptyObj,
  getTheadTrProps: emptyObj,
  getTheadThProps: emptyObj,
  getTheadFilterProps: emptyObj,
  getTheadFilterTrProps: emptyObj,
  getTheadFilterThProps: emptyObj,
  getTbodyProps: emptyObj,
  getTrGroupProps: emptyObj,
  getTrProps: emptyObj,
  getTdProps: emptyObj,
  getTfootProps: emptyObj,
  getTfootTrProps: emptyObj,
  getTfootTdProps: emptyObj,
  getPaginationProps: emptyObj,
  getLoadingProps: emptyObj,
  getNoDataProps: emptyObj,
  getResizerProps: emptyObj,

  // Global Column Defaults
  column: {
    // Renderers
    Cell: undefined,
    Header: undefined,
    Footer: undefined,
    Aggregated: undefined,
    Pivot: undefined,
    PivotValue: undefined,
    Expander: undefined,
    Filter: undefined,
    Placeholder: undefined,
    // All Columns
    sortable: undefined, // use table default
    resizable: undefined, // use table default
    filterable: undefined, // use table default
    show: true,
    minWidth: 100,
    minResizeWidth: 11,
    // Cells only
    className: '',
    style: {},
    getProps: emptyObj,
    // Pivot only
    aggregate: undefined,
    // Headers only
    headerClassName: '',
    headerStyle: {},
    getHeaderProps: emptyObj,
    // Footers only
    footerClassName: '',
    footerStyle: {},
    getFooterProps: emptyObj,
    filterMethod: undefined,
    filterAll: false,
    sortMethod: undefined
  },

  // Global Expander Column Defaults
  expanderDefaults: {
    sortable: false,
    resizable: false,
    filterable: false,
    width: 35
  },

  pivotDefaults: {
    // extend the defaults for pivoted columns here
  },

  // Text
  previousText: 'Previous',
  nextText: 'Next',
  loadingText: 'Loading...',
  noDataText: 'No rows found',
  pageText: 'Page',
  ofText: 'of',
  rowsText: 'rows',
  pageJumpText: 'jump to page',
  rowsSelectorText: 'rows per page',

  // Components
  TableComponent: function TableComponent(_ref) {
    var children = _ref.children,
        className = _ref.className,
        rest = defaultProps_objectWithoutProperties(_ref, ['children', 'className']);

    return react_default.a.createElement(
      'div',
      defaultProps_extends({
        className: classnames_default()('rt-table', className),
        role: 'grid'
        // tabIndex='0'
      }, rest),
      children
    );
  },
  TheadComponent: utils.makeTemplateComponent('rt-thead', 'Thead'),
  TbodyComponent: utils.makeTemplateComponent('rt-tbody', 'Tbody'),
  TrGroupComponent: function TrGroupComponent(_ref2) {
    var children = _ref2.children,
        className = _ref2.className,
        rest = defaultProps_objectWithoutProperties(_ref2, ['children', 'className']);

    return react_default.a.createElement(
      'div',
      defaultProps_extends({ className: classnames_default()('rt-tr-group', className), role: 'rowgroup' }, rest),
      children
    );
  },
  TrComponent: function TrComponent(_ref3) {
    var children = _ref3.children,
        className = _ref3.className,
        rest = defaultProps_objectWithoutProperties(_ref3, ['children', 'className']);

    return react_default.a.createElement(
      'div',
      defaultProps_extends({ className: classnames_default()('rt-tr', className), role: 'row' }, rest),
      children
    );
  },
  ThComponent: function ThComponent(_ref4) {
    var toggleSort = _ref4.toggleSort,
        className = _ref4.className,
        children = _ref4.children,
        rest = defaultProps_objectWithoutProperties(_ref4, ['toggleSort', 'className', 'children']);

    return (
      // eslint-disable-next-line jsx-a11y/click-events-have-key-events
      react_default.a.createElement(
        'div',
        defaultProps_extends({
          className: classnames_default()('rt-th', className),
          onClick: function onClick(e) {
            return toggleSort && toggleSort(e);
          },
          role: 'columnheader',
          tabIndex: '-1' // Resolves eslint issues without implementing keyboard navigation incorrectly
        }, rest),
        children
      )
    );
  },
  TdComponent: function TdComponent(_ref5) {
    var toggleSort = _ref5.toggleSort,
        className = _ref5.className,
        children = _ref5.children,
        rest = defaultProps_objectWithoutProperties(_ref5, ['toggleSort', 'className', 'children']);

    return react_default.a.createElement(
      'div',
      defaultProps_extends({ className: classnames_default()('rt-td', className), role: 'gridcell' }, rest),
      children
    );
  },
  TfootComponent: utils.makeTemplateComponent('rt-tfoot', 'Tfoot'),
  FilterComponent: function FilterComponent(_ref6) {
    var filter = _ref6.filter,
        _onChange = _ref6.onChange,
        column = _ref6.column;
    return react_default.a.createElement('input', {
      type: 'text',
      style: {
        width: '100%'
      },
      placeholder: column.Placeholder,
      value: filter ? filter.value : '',
      onChange: function onChange(event) {
        return _onChange(event.target.value);
      }
    });
  },
  ExpanderComponent: function ExpanderComponent(_ref7) {
    var isExpanded = _ref7.isExpanded;
    return react_default.a.createElement(
      'div',
      { className: classnames_default()('rt-expander', isExpanded && '-open') },
      '\u2022'
    );
  },
  PivotValueComponent: function PivotValueComponent(_ref8) {
    var subRows = _ref8.subRows,
        value = _ref8.value;
    return react_default.a.createElement(
      'span',
      null,
      value,
      ' ',
      subRows && '(' + subRows.length + ')'
    );
  },
  AggregatedComponent: function AggregatedComponent(_ref9) {
    var subRows = _ref9.subRows,
        column = _ref9.column;

    var previewValues = subRows.filter(function (d) {
      return typeof d[column.id] !== 'undefined';
    }).map(function (row, i) {
      return (
        // eslint-disable-next-line react/no-array-index-key
        react_default.a.createElement(
          'span',
          { key: i },
          row[column.id],
          i < subRows.length - 1 ? ', ' : ''
        )
      );
    });
    return react_default.a.createElement(
      'span',
      null,
      previewValues
    );
  },
  PivotComponent: undefined, // this is a computed default generated using
  // the ExpanderComponent and PivotValueComponent at run-time in methods.js
  PaginationComponent: pagination,
  PreviousComponent: undefined,
  NextComponent: undefined,
  LoadingComponent: function LoadingComponent(_ref10) {
    var className = _ref10.className,
        loading = _ref10.loading,
        loadingText = _ref10.loadingText,
        rest = defaultProps_objectWithoutProperties(_ref10, ['className', 'loading', 'loadingText']);

    return react_default.a.createElement(
      'div',
      defaultProps_extends({ className: classnames_default()('-loading', { '-active': loading }, className) }, rest),
      react_default.a.createElement(
        'div',
        { className: '-loading-inner' },
        loadingText
      )
    );
  },
  NoDataComponent: utils.makeTemplateComponent('rt-noData', 'NoData'),
  ResizerComponent: utils.makeTemplateComponent('rt-resizer', 'Resizer'),
  PadRowComponent: function PadRowComponent() {
    return react_default.a.createElement(
      'span',
      null,
      '\xA0'
    );
  }
});
//# sourceMappingURL=data:application/json;base64, 
// CONCATENATED MODULE: ./node_modules/react-table/es/propTypes.js


/* harmony default export */ var propTypes = ({
  // General
  data: prop_types_default.a.any,
  loading: prop_types_default.a.bool,
  showPagination: prop_types_default.a.bool,
  showPaginationTop: prop_types_default.a.bool,
  showPaginationBottom: prop_types_default.a.bool,
  showPageSizeOptions: prop_types_default.a.bool,
  pageSizeOptions: prop_types_default.a.array,
  defaultPageSize: prop_types_default.a.number,
  showPageJump: prop_types_default.a.bool,
  collapseOnSortingChange: prop_types_default.a.bool,
  collapseOnPageChange: prop_types_default.a.bool,
  collapseOnDataChange: prop_types_default.a.bool,
  freezeWhenExpanded: prop_types_default.a.bool,
  sortable: prop_types_default.a.bool,
  resizable: prop_types_default.a.bool,
  filterable: prop_types_default.a.bool,
  defaultSortDesc: prop_types_default.a.bool,
  defaultSorted: prop_types_default.a.array,
  defaultFiltered: prop_types_default.a.array,
  defaultResized: prop_types_default.a.array,
  defaultExpanded: prop_types_default.a.object,
  defaultFilterMethod: prop_types_default.a.func,
  defaultSortMethod: prop_types_default.a.func,

  // Controlled State Callbacks
  onPageChange: prop_types_default.a.func,
  onPageSizeChange: prop_types_default.a.func,
  onSortedChange: prop_types_default.a.func,
  onFilteredChange: prop_types_default.a.func,
  onResizedChange: prop_types_default.a.func,
  onExpandedChange: prop_types_default.a.func,

  // Pivoting
  pivotBy: prop_types_default.a.array,

  // Key Constants
  pivotValKey: prop_types_default.a.string,
  pivotIDKey: prop_types_default.a.string,
  subRowsKey: prop_types_default.a.string,
  aggregatedKey: prop_types_default.a.string,
  nestingLevelKey: prop_types_default.a.string,
  originalKey: prop_types_default.a.string,
  indexKey: prop_types_default.a.string,
  groupedByPivotKey: prop_types_default.a.string,

  // Server-side Callbacks
  onFetchData: prop_types_default.a.func,

  // Classes
  className: prop_types_default.a.string,
  style: prop_types_default.a.object,

  // Component decorators
  getProps: prop_types_default.a.func,
  getTableProps: prop_types_default.a.func,
  getTheadGroupProps: prop_types_default.a.func,
  getTheadGroupTrProps: prop_types_default.a.func,
  getTheadGroupThProps: prop_types_default.a.func,
  getTheadProps: prop_types_default.a.func,
  getTheadTrProps: prop_types_default.a.func,
  getTheadThProps: prop_types_default.a.func,
  getTheadFilterProps: prop_types_default.a.func,
  getTheadFilterTrProps: prop_types_default.a.func,
  getTheadFilterThProps: prop_types_default.a.func,
  getTbodyProps: prop_types_default.a.func,
  getTrGroupProps: prop_types_default.a.func,
  getTrProps: prop_types_default.a.func,
  getTdProps: prop_types_default.a.func,
  getTfootProps: prop_types_default.a.func,
  getTfootTrProps: prop_types_default.a.func,
  getTfootTdProps: prop_types_default.a.func,
  getPaginationProps: prop_types_default.a.func,
  getLoadingProps: prop_types_default.a.func,
  getNoDataProps: prop_types_default.a.func,
  getResizerProps: prop_types_default.a.func,

  // Global Column Defaults
  columns: prop_types_default.a.arrayOf(prop_types_default.a.shape({
    // Renderers
    Cell: prop_types_default.a.oneOfType([prop_types_default.a.element, prop_types_default.a.string, prop_types_default.a.elementType]),
    Header: prop_types_default.a.oneOfType([prop_types_default.a.element, prop_types_default.a.string, prop_types_default.a.elementType]),
    Footer: prop_types_default.a.oneOfType([prop_types_default.a.element, prop_types_default.a.string, prop_types_default.a.elementType]),
    Aggregated: prop_types_default.a.oneOfType([prop_types_default.a.element, prop_types_default.a.string, prop_types_default.a.elementType]),
    Pivot: prop_types_default.a.oneOfType([prop_types_default.a.element, prop_types_default.a.string, prop_types_default.a.elementType]),
    PivotValue: prop_types_default.a.oneOfType([prop_types_default.a.element, prop_types_default.a.string, prop_types_default.a.elementType]),
    Expander: prop_types_default.a.oneOfType([prop_types_default.a.element, prop_types_default.a.string, prop_types_default.a.elementType]),
    Filter: prop_types_default.a.oneOfType([prop_types_default.a.element, prop_types_default.a.elementType]),

    // All Columns
    sortable: prop_types_default.a.bool, // use table default
    resizable: prop_types_default.a.bool, // use table default
    filterable: prop_types_default.a.bool, // use table default
    show: prop_types_default.a.bool,
    minWidth: prop_types_default.a.number,
    minResizeWidth: prop_types_default.a.number,

    // Cells only
    className: prop_types_default.a.string,
    style: prop_types_default.a.object,
    getProps: prop_types_default.a.func,

    // Pivot only
    aggregate: prop_types_default.a.func,

    // Headers only
    headerClassName: prop_types_default.a.string,
    headerStyle: prop_types_default.a.object,
    getHeaderProps: prop_types_default.a.func,

    // Footers only
    footerClassName: prop_types_default.a.string,
    footerStyle: prop_types_default.a.object,
    getFooterProps: prop_types_default.a.func,
    filterMethod: prop_types_default.a.func,
    filterAll: prop_types_default.a.bool,
    sortMethod: prop_types_default.a.func
  })),

  // Global Expander Column Defaults
  expanderDefaults: prop_types_default.a.shape({
    sortable: prop_types_default.a.bool,
    resizable: prop_types_default.a.bool,
    filterable: prop_types_default.a.bool,
    width: prop_types_default.a.number
  }),

  pivotDefaults: prop_types_default.a.object,

  // Text
  previousText: prop_types_default.a.node,
  nextText: prop_types_default.a.node,
  loadingText: prop_types_default.a.node,
  noDataText: prop_types_default.a.node,
  pageText: prop_types_default.a.node,
  ofText: prop_types_default.a.node,
  rowsText: prop_types_default.a.node,
  pageJumpText: prop_types_default.a.node,
  rowsSelectorText: prop_types_default.a.node,

  // Components
  TableComponent: prop_types_default.a.elementType,
  TheadComponent: prop_types_default.a.elementType,
  TbodyComponent: prop_types_default.a.elementType,
  TrGroupComponent: prop_types_default.a.elementType,
  TrComponent: prop_types_default.a.elementType,
  ThComponent: prop_types_default.a.elementType,
  TdComponent: prop_types_default.a.elementType,
  TfootComponent: prop_types_default.a.elementType,
  FilterComponent: prop_types_default.a.elementType,
  ExpanderComponent: prop_types_default.a.elementType,
  PivotValueComponent: prop_types_default.a.elementType,
  AggregatedComponent: prop_types_default.a.elementType,
  // this is a computed default generated using
  PivotComponent: prop_types_default.a.elementType,
  // the ExpanderComponent and PivotValueComponent at run-time in methods.js
  PaginationComponent: prop_types_default.a.elementType,
  PreviousComponent: prop_types_default.a.elementType,
  NextComponent: prop_types_default.a.elementType,
  LoadingComponent: prop_types_default.a.elementType,
  NoDataComponent: prop_types_default.a.elementType,
  ResizerComponent: prop_types_default.a.elementType,
  PadRowComponent: prop_types_default.a.elementType
});
//# sourceMappingURL=data:application/json;base64, 
// CONCATENATED MODULE: ./node_modules/react-table/es/index.js
var es_slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var es_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 es_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; }; }();

function es_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function es_possibleConstructorReturn(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; }

function es_inherits(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 ReactTableDefaults = es_defaultProps;

var es_ReactTable = function (_Methods) {
  es_inherits(ReactTable, _Methods);

  function ReactTable(props) {
    es_classCallCheck(this, ReactTable);

    var _this = es_possibleConstructorReturn(this, (ReactTable.__proto__ || Object.getPrototypeOf(ReactTable)).call(this, props));

    _this.getResolvedState = _this.getResolvedState.bind(_this);
    _this.getDataModel = _this.getDataModel.bind(_this);
    _this.getSortedData = _this.getSortedData.bind(_this);
    _this.fireFetchData = _this.fireFetchData.bind(_this);
    _this.getPropOrState = _this.getPropOrState.bind(_this);
    _this.getStateOrProp = _this.getStateOrProp.bind(_this);
    _this.filterData = _this.filterData.bind(_this);
    _this.sortData = _this.sortData.bind(_this);
    _this.getMinRows = _this.getMinRows.bind(_this);
    _this.onPageChange = _this.onPageChange.bind(_this);
    _this.onPageSizeChange = _this.onPageSizeChange.bind(_this);
    _this.sortColumn = _this.sortColumn.bind(_this);
    _this.filterColumn = _this.filterColumn.bind(_this);
    _this.resizeColumnStart = _this.resizeColumnStart.bind(_this);
    _this.resizeColumnEnd = _this.resizeColumnEnd.bind(_this);
    _this.resizeColumnMoving = _this.resizeColumnMoving.bind(_this);
    return _this;
  }

  es_createClass(ReactTable, [{
    key: 'render',
    value: function render() {
      var _this2 = this;

      var resolvedState = this.getResolvedState();
      var children = resolvedState.children,
          className = resolvedState.className,
          style = resolvedState.style,
          getProps = resolvedState.getProps,
          getTableProps = resolvedState.getTableProps,
          getTheadGroupProps = resolvedState.getTheadGroupProps,
          getTheadGroupTrProps = resolvedState.getTheadGroupTrProps,
          getTheadGroupThProps = resolvedState.getTheadGroupThProps,
          getTheadProps = resolvedState.getTheadProps,
          getTheadTrProps = resolvedState.getTheadTrProps,
          getTheadThProps = resolvedState.getTheadThProps,
          getTheadFilterProps = resolvedState.getTheadFilterProps,
          getTheadFilterTrProps = resolvedState.getTheadFilterTrProps,
          getTheadFilterThProps = resolvedState.getTheadFilterThProps,
          getTbodyProps = resolvedState.getTbodyProps,
          getTrGroupProps = resolvedState.getTrGroupProps,
          getTrProps = resolvedState.getTrProps,
          getTdProps = resolvedState.getTdProps,
          getTfootProps = resolvedState.getTfootProps,
          getTfootTrProps = resolvedState.getTfootTrProps,
          getTfootTdProps = resolvedState.getTfootTdProps,
          getPaginationProps = resolvedState.getPaginationProps,
          getLoadingProps = resolvedState.getLoadingProps,
          getNoDataProps = resolvedState.getNoDataProps,
          getResizerProps = resolvedState.getResizerProps,
          showPagination = resolvedState.showPagination,
          showPaginationTop = resolvedState.showPaginationTop,
          showPaginationBottom = resolvedState.showPaginationBottom,
          manual = resolvedState.manual,
          loadingText = resolvedState.loadingText,
          noDataText = resolvedState.noDataText,
          sortable = resolvedState.sortable,
          multiSort = resolvedState.multiSort,
          resizable = resolvedState.resizable,
          filterable = resolvedState.filterable,
          pivotIDKey = resolvedState.pivotIDKey,
          pivotValKey = resolvedState.pivotValKey,
          pivotBy = resolvedState.pivotBy,
          subRowsKey = resolvedState.subRowsKey,
          aggregatedKey = resolvedState.aggregatedKey,
          originalKey = resolvedState.originalKey,
          indexKey = resolvedState.indexKey,
          groupedByPivotKey = resolvedState.groupedByPivotKey,
          loading = resolvedState.loading,
          pageSize = resolvedState.pageSize,
          page = resolvedState.page,
          sorted = resolvedState.sorted,
          filtered = resolvedState.filtered,
          resized = resolvedState.resized,
          expanded = resolvedState.expanded,
          pages = resolvedState.pages,
          onExpandedChange = resolvedState.onExpandedChange,
          TableComponent = resolvedState.TableComponent,
          TheadComponent = resolvedState.TheadComponent,
          TbodyComponent = resolvedState.TbodyComponent,
          TrGroupComponent = resolvedState.TrGroupComponent,
          TrComponent = resolvedState.TrComponent,
          ThComponent = resolvedState.ThComponent,
          TdComponent = resolvedState.TdComponent,
          TfootComponent = resolvedState.TfootComponent,
          PaginationComponent = resolvedState.PaginationComponent,
          LoadingComponent = resolvedState.LoadingComponent,
          SubComponent = resolvedState.SubComponent,
          NoDataComponent = resolvedState.NoDataComponent,
          ResizerComponent = resolvedState.ResizerComponent,
          ExpanderComponent = resolvedState.ExpanderComponent,
          PivotValueComponent = resolvedState.PivotValueComponent,
          PivotComponent = resolvedState.PivotComponent,
          AggregatedComponent = resolvedState.AggregatedComponent,
          FilterComponent = resolvedState.FilterComponent,
          PadRowComponent = resolvedState.PadRowComponent,
          resolvedData = resolvedState.resolvedData,
          allVisibleColumns = resolvedState.allVisibleColumns,
          headerGroups = resolvedState.headerGroups,
          hasHeaderGroups = resolvedState.hasHeaderGroups,
          sortedData = resolvedState.sortedData,
          currentlyResizing = resolvedState.currentlyResizing;

      // Pagination

      var startRow = pageSize * page;
      var endRow = startRow + pageSize;
      var pageRows = manual ? resolvedData : sortedData.slice(startRow, endRow);
      var minRows = this.getMinRows();
      var padRows = utils.range(Math.max(minRows - pageRows.length, 0));

      var hasColumnFooter = allVisibleColumns.some(function (d) {
        return d.Footer;
      });
      var hasFilters = filterable || allVisibleColumns.some(function (d) {
        return d.filterable;
      });

      var recurseRowsViewIndex = function recurseRowsViewIndex(rows) {
        var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
        var index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : -1;
        return [rows.map(function (row, i) {
          index += 1;
          var rowWithViewIndex = es_extends({}, row, {
            _viewIndex: index
          });
          var newPath = path.concat([i]);
          if (rowWithViewIndex[subRowsKey] && utils.get(expanded, newPath)) {
            var _recurseRowsViewIndex = recurseRowsViewIndex(rowWithViewIndex[subRowsKey], newPath, index);

            var _recurseRowsViewIndex2 = es_slicedToArray(_recurseRowsViewIndex, 2);

            rowWithViewIndex[subRowsKey] = _recurseRowsViewIndex2[0];
            index = _recurseRowsViewIndex2[1];
          }
          return rowWithViewIndex;
        }), index];
      };

      var _recurseRowsViewIndex3 = recurseRowsViewIndex(pageRows);

      var _recurseRowsViewIndex4 = es_slicedToArray(_recurseRowsViewIndex3, 1);

      pageRows = _recurseRowsViewIndex4[0];


      var canPrevious = page > 0;
      var canNext = page + 1 < pages;

      var rowMinWidth = utils.sum(allVisibleColumns.map(function (d) {
        var resizedColumn = resized.find(function (x) {
          return x.id === d.id;
        }) || {};
        return utils.getFirstDefined(resizedColumn.value, d.width, d.minWidth);
      }));

      var rowIndex = -1;

      var finalState = es_extends({}, resolvedState, {
        startRow: startRow,
        endRow: endRow,
        pageRows: pageRows,
        minRows: minRows,
        padRows: padRows,
        hasColumnFooter: hasColumnFooter,
        canPrevious: canPrevious,
        canNext: canNext,
        rowMinWidth: rowMinWidth
      });

      var rootProps = utils.splitProps(getProps(finalState, undefined, undefined, this));
      var tableProps = utils.splitProps(getTableProps(finalState, undefined, undefined, this));
      var tBodyProps = utils.splitProps(getTbodyProps(finalState, undefined, undefined, this));
      var loadingProps = getLoadingProps(finalState, undefined, undefined, this);
      var noDataProps = getNoDataProps(finalState, undefined, undefined, this);

      // Visual Components

      var makeHeaderGroup = function makeHeaderGroup(column, i) {
        var resizedValue = function resizedValue(col) {
          return (resized.find(function (x) {
            return x.id === col.id;
          }) || {}).value;
        };
        var flex = utils.sum(column.columns.map(function (col) {
          return col.width || resizedValue(col) ? 0 : col.minWidth;
        }));
        var width = utils.sum(column.columns.map(function (col) {
          return utils.getFirstDefined(resizedValue(col), col.width, col.minWidth);
        }));
        var maxWidth = utils.sum(column.columns.map(function (col) {
          return utils.getFirstDefined(resizedValue(col), col.width, col.maxWidth);
        }));

        var theadGroupThProps = utils.splitProps(getTheadGroupThProps(finalState, undefined, column, _this2));
        var columnHeaderProps = utils.splitProps(column.getHeaderProps(finalState, undefined, column, _this2));

        var classes = [column.headerClassName, theadGroupThProps.className, columnHeaderProps.className];

        var styles = es_extends({}, column.headerStyle, theadGroupThProps.style, columnHeaderProps.style);

        var rest = es_extends({}, theadGroupThProps.rest, columnHeaderProps.rest);

        var flexStyles = {
          flex: flex + ' 0 auto',
          width: utils.asPx(width),
          maxWidth: utils.asPx(maxWidth)
        };

        return react_default.a.createElement(
          ThComponent,
          es_extends({
            key: i + '-' + column.id,
            className: classnames_default()(classes),
            style: es_extends({}, styles, flexStyles)
          }, rest),
          utils.normalizeComponent(column.Header, {
            data: sortedData,
            column: column
          })
        );
      };

      var makeHeaderGroups = function makeHeaderGroups() {
        var theadGroupProps = utils.splitProps(getTheadGroupProps(finalState, undefined, undefined, _this2));
        var theadGroupTrProps = utils.splitProps(getTheadGroupTrProps(finalState, undefined, undefined, _this2));
        return react_default.a.createElement(
          TheadComponent,
          es_extends({
            className: classnames_default()('-headerGroups', theadGroupProps.className),
            style: es_extends({}, theadGroupProps.style, {
              minWidth: rowMinWidth + 'px'
            })
          }, theadGroupProps.rest),
          react_default.a.createElement(
            TrComponent,
            es_extends({
              className: theadGroupTrProps.className,
              style: theadGroupTrProps.style
            }, theadGroupTrProps.rest),
            headerGroups.map(makeHeaderGroup)
          )
        );
      };

      var makeHeader = function makeHeader(column, i) {
        var resizedCol = resized.find(function (x) {
          return x.id === column.id;
        }) || {};
        var sort = sorted.find(function (d) {
          return d.id === column.id;
        });
        var show = typeof column.show === 'function' ? column.show() : column.show;
        var width = utils.getFirstDefined(resizedCol.value, column.width, column.minWidth);
        var maxWidth = utils.getFirstDefined(resizedCol.value, column.width, column.maxWidth);
        var theadThProps = utils.splitProps(getTheadThProps(finalState, undefined, column, _this2));
        var columnHeaderProps = utils.splitProps(column.getHeaderProps(finalState, undefined, column, _this2));

        var classes = [column.headerClassName, theadThProps.className, columnHeaderProps.className];

        var styles = es_extends({}, column.headerStyle, theadThProps.style, columnHeaderProps.style);

        var rest = es_extends({}, theadThProps.rest, columnHeaderProps.rest);

        var isResizable = utils.getFirstDefined(column.resizable, resizable, false);
        var resizer = isResizable ? react_default.a.createElement(ResizerComponent, es_extends({
          onMouseDown: function onMouseDown(e) {
            return _this2.resizeColumnStart(e, column, false);
          },
          onTouchStart: function onTouchStart(e) {
            return _this2.resizeColumnStart(e, column, true);
          }
        }, getResizerProps('finalState', undefined, column, _this2))) : null;

        var isSortable = utils.getFirstDefined(column.sortable, sortable, false);

        return react_default.a.createElement(
          ThComponent,
          es_extends({
            key: i + '-' + column.id,
            className: classnames_default()(classes, isResizable && 'rt-resizable-header', sort ? sort.desc ? '-sort-desc' : '-sort-asc' : '', isSortable && '-cursor-pointer', !show && '-hidden', pivotBy && pivotBy.slice(0, -1).includes(column.id) && 'rt-header-pivot'),
            style: es_extends({}, styles, {
              flex: width + ' 0 auto',
              width: utils.asPx(width),
              maxWidth: utils.asPx(maxWidth)
            }),
            toggleSort: function toggleSort(e) {
              if (isSortable) _this2.sortColumn(column, multiSort ? e.shiftKey : false);
            }
          }, rest),
          react_default.a.createElement(
            'div',
            { className: classnames_default()(isResizable && 'rt-resizable-header-content') },
            utils.normalizeComponent(column.Header, {
              data: sortedData,
              column: column
            })
          ),
          resizer
        );
      };

      var makeHeaders = function makeHeaders() {
        var theadProps = utils.splitProps(getTheadProps(finalState, undefined, undefined, _this2));
        var theadTrProps = utils.splitProps(getTheadTrProps(finalState, undefined, undefined, _this2));
        return react_default.a.createElement(
          TheadComponent,
          es_extends({
            className: classnames_default()('-header', theadProps.className),
            style: es_extends({}, theadProps.style, {
              minWidth: rowMinWidth + 'px'
            })
          }, theadProps.rest),
          react_default.a.createElement(
            TrComponent,
            es_extends({
              className: theadTrProps.className,
              style: theadTrProps.style
            }, theadTrProps.rest),
            allVisibleColumns.map(makeHeader)
          )
        );
      };

      var makeFilter = function makeFilter(column, i) {
        var resizedCol = resized.find(function (x) {
          return x.id === column.id;
        }) || {};
        var width = utils.getFirstDefined(resizedCol.value, column.width, column.minWidth);
        var maxWidth = utils.getFirstDefined(resizedCol.value, column.width, column.maxWidth);
        var theadFilterThProps = utils.splitProps(getTheadFilterThProps(finalState, undefined, column, _this2));
        var columnHeaderProps = utils.splitProps(column.getHeaderProps(finalState, undefined, column, _this2));

        var classes = [column.headerClassName, theadFilterThProps.className, columnHeaderProps.className];

        var styles = es_extends({}, column.headerStyle, theadFilterThProps.style, columnHeaderProps.style);

        var rest = es_extends({}, theadFilterThProps.rest, columnHeaderProps.rest);

        var filter = filtered.find(function (filter) {
          return filter.id === column.id;
        });

        var ResolvedFilterComponent = column.Filter || FilterComponent;

        var isFilterable = utils.getFirstDefined(column.filterable, filterable, false);

        return react_default.a.createElement(
          ThComponent,
          es_extends({
            key: i + '-' + column.id,
            className: classnames_default()(classes),
            style: es_extends({}, styles, {
              flex: width + ' 0 auto',
              width: utils.asPx(width),
              maxWidth: utils.asPx(maxWidth)
            })
          }, rest),
          isFilterable ? utils.normalizeComponent(ResolvedFilterComponent, {
            column: column,
            filter: filter,
            onChange: function onChange(value) {
              return _this2.filterColumn(column, value);
            }
          }, es_defaultProps.column.Filter) : null
        );
      };

      var makeFilters = function makeFilters() {
        var theadFilterProps = utils.splitProps(getTheadFilterProps(finalState, undefined, undefined, _this2));
        var theadFilterTrProps = utils.splitProps(getTheadFilterTrProps(finalState, undefined, undefined, _this2));
        return react_default.a.createElement(
          TheadComponent,
          es_extends({
            className: classnames_default()('-filters', theadFilterProps.className),
            style: es_extends({}, theadFilterProps.style, {
              minWidth: rowMinWidth + 'px'
            })
          }, theadFilterProps.rest),
          react_default.a.createElement(
            TrComponent,
            es_extends({
              className: theadFilterTrProps.className,
              style: theadFilterTrProps.style
            }, theadFilterTrProps.rest),
            allVisibleColumns.map(makeFilter)
          )
        );
      };

      var makePageRow = function makePageRow(row, i) {
        var path = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];

        var rowInfo = {
          original: row[originalKey],
          row: row,
          index: row[indexKey],
          viewIndex: rowIndex += 1,
          pageSize: pageSize,
          page: page,
          level: path.length,
          nestingPath: path.concat([i]),
          aggregated: row[aggregatedKey],
          groupedByPivot: row[groupedByPivotKey],
          subRows: row[subRowsKey]
        };
        var isExpanded = utils.get(expanded, rowInfo.nestingPath);
        var trGroupProps = getTrGroupProps(finalState, rowInfo, undefined, _this2);
        var trProps = utils.splitProps(getTrProps(finalState, rowInfo, undefined, _this2));
        return react_default.a.createElement(
          TrGroupComponent,
          es_extends({ key: rowInfo.nestingPath.join('_') }, trGroupProps),
          react_default.a.createElement(
            TrComponent,
            es_extends({
              className: classnames_default()(trProps.className, row._viewIndex % 2 ? '-even' : '-odd'),
              style: trProps.style
            }, trProps.rest),
            allVisibleColumns.map(function (column, i2) {
              var resizedCol = resized.find(function (x) {
                return x.id === column.id;
              }) || {};
              var show = typeof column.show === 'function' ? column.show() : column.show;
              var width = utils.getFirstDefined(resizedCol.value, column.width, column.minWidth);
              var maxWidth = utils.getFirstDefined(resizedCol.value, column.width, column.maxWidth);
              var tdProps = utils.splitProps(getTdProps(finalState, rowInfo, column, _this2));
              var columnProps = utils.splitProps(column.getProps(finalState, rowInfo, column, _this2));

              var classes = [tdProps.className, column.className, columnProps.className];

              var styles = es_extends({}, tdProps.style, column.style, columnProps.style);

              var cellInfo = es_extends({}, rowInfo, {
                isExpanded: isExpanded,
                column: es_extends({}, column),
                value: rowInfo.row[column.id],
                pivoted: column.pivoted,
                expander: column.expander,
                resized: resized,
                show: show,
                width: width,
                maxWidth: maxWidth,
                tdProps: tdProps,
                columnProps: columnProps,
                classes: classes,
                styles: styles
              });

              var value = cellInfo.value;

              var useOnExpanderClick = void 0;
              var isBranch = void 0;
              var isPreview = void 0;

              var onExpanderClick = function onExpanderClick(e) {
                var newExpanded = utils.clone(expanded);
                if (isExpanded) {
                  newExpanded = utils.set(newExpanded, cellInfo.nestingPath, false);
                } else {
                  newExpanded = utils.set(newExpanded, cellInfo.nestingPath, {});
                }

                return _this2.setStateWithData({
                  expanded: newExpanded
                }, function () {
                  return onExpandedChange && onExpandedChange(newExpanded, cellInfo.nestingPath, e, cellInfo);
                });
              };

              // Default to a standard cell
              var resolvedCell = utils.normalizeComponent(column.Cell, cellInfo, value);

              // Resolve Renderers
              var ResolvedAggregatedComponent = column.Aggregated || (!column.aggregate ? AggregatedComponent : column.Cell);
              var ResolvedExpanderComponent = column.Expander || ExpanderComponent;
              var ResolvedPivotValueComponent = column.PivotValue || PivotValueComponent;
              var DefaultResolvedPivotComponent = PivotComponent || function (props) {
                return react_default.a.createElement(
                  'div',
                  null,
                  react_default.a.createElement(ResolvedExpanderComponent, props),
                  react_default.a.createElement(ResolvedPivotValueComponent, props)
                );
              };
              var ResolvedPivotComponent = column.Pivot || DefaultResolvedPivotComponent;

              // Is this cell expandable?
              if (cellInfo.pivoted || cellInfo.expander) {
                // Make it expandable by defualt
                cellInfo.expandable = true;
                useOnExpanderClick = true;
                // If pivoted, has no subRows, and does not have a subComponent,
                // do not make expandable
                if (cellInfo.pivoted && !cellInfo.subRows && !SubComponent) {
                  cellInfo.expandable = false;
                }
              }

              if (cellInfo.pivoted) {
                // Is this column a branch?
                isBranch = rowInfo.row[pivotIDKey] === column.id && cellInfo.subRows;
                // Should this column be blank?
                isPreview = pivotBy.indexOf(column.id) > pivotBy.indexOf(rowInfo.row[pivotIDKey]) && cellInfo.subRows;
                // Pivot Cell Render Override
                if (isBranch) {
                  // isPivot
                  resolvedCell = utils.normalizeComponent(ResolvedPivotComponent, es_extends({}, cellInfo, {
                    value: row[pivotValKey]
                  }), row[pivotValKey]);
                } else if (isPreview) {
                  // Show the pivot preview
                  resolvedCell = utils.normalizeComponent(ResolvedAggregatedComponent, cellInfo, value);
                } else {
                  resolvedCell = null;
                }
              } else if (cellInfo.aggregated) {
                resolvedCell = utils.normalizeComponent(ResolvedAggregatedComponent, cellInfo, value);
              }

              if (cellInfo.expander) {
                resolvedCell = utils.normalizeComponent(ResolvedExpanderComponent, cellInfo, row[pivotValKey]);
                if (pivotBy) {
                  if (cellInfo.groupedByPivot) {
                    resolvedCell = null;
                  }
                  if (!cellInfo.subRows && !SubComponent) {
                    resolvedCell = null;
                  }
                }
              }

              var resolvedOnExpanderClick = useOnExpanderClick ? onExpanderClick : function () {};

              // If there are multiple onClick events, make sure they don't
              // override eachother. This should maybe be expanded to handle all
              // function attributes
              var interactionProps = {
                onClick: resolvedOnExpanderClick
              };

              if (tdProps.rest.onClick) {
                interactionProps.onClick = function (e) {
                  tdProps.rest.onClick(e, function () {
                    return resolvedOnExpanderClick(e);
                  });
                };
              }

              if (columnProps.rest.onClick) {
                interactionProps.onClick = function (e) {
                  columnProps.rest.onClick(e, function () {
                    return resolvedOnExpanderClick(e);
                  });
                };
              }

              // Return the cell
              return react_default.a.createElement(
                TdComponent
                // eslint-disable-next-line react/no-array-index-key
                ,
                es_extends({ key: i2 + '-' + column.id,
                  className: classnames_default()(classes, !cellInfo.expandable && !show && 'hidden', cellInfo.expandable && 'rt-expandable', (isBranch || isPreview) && 'rt-pivot'),
                  style: es_extends({}, styles, {
                    flex: width + ' 0 auto',
                    width: utils.asPx(width),
                    maxWidth: utils.asPx(maxWidth)
                  })
                }, tdProps.rest, columnProps.rest, interactionProps),
                resolvedCell
              );
            })
          ),
          rowInfo.subRows && isExpanded && rowInfo.subRows.map(function (d, i) {
            return makePageRow(d, i, rowInfo.nestingPath);
          }),
          SubComponent && !rowInfo.subRows && isExpanded && SubComponent(rowInfo, function () {
            var newExpanded = utils.clone(expanded);

            utils.set(newExpanded, rowInfo.nestingPath, false);
          })
        );
      };

      var makePadColumn = function makePadColumn(column, i) {
        var resizedCol = resized.find(function (x) {
          return x.id === column.id;
        }) || {};
        var show = typeof column.show === 'function' ? column.show() : column.show;
        var width = utils.getFirstDefined(resizedCol.value, column.width, column.minWidth);
        var flex = width;
        var maxWidth = utils.getFirstDefined(resizedCol.value, column.width, column.maxWidth);
        var tdProps = utils.splitProps(getTdProps(finalState, undefined, column, _this2));
        var columnProps = utils.splitProps(column.getProps(finalState, undefined, column, _this2));

        var classes = [tdProps.className, column.className, columnProps.className];

        var styles = es_extends({}, tdProps.style, column.style, columnProps.style);

        return react_default.a.createElement(
          TdComponent,
          es_extends({
            key: i + '-' + column.id,
            className: classnames_default()(classes, !show && 'hidden'),
            style: es_extends({}, styles, {
              flex: flex + ' 0 auto',
              width: utils.asPx(width),
              maxWidth: utils.asPx(maxWidth)
            })
          }, tdProps.rest),
          utils.normalizeComponent(PadRowComponent)
        );
      };

      var makePadRow = function makePadRow(row, i) {
        var trGroupProps = getTrGroupProps(finalState, undefined, undefined, _this2);
        var trProps = utils.splitProps(getTrProps(finalState, undefined, undefined, _this2));
        return react_default.a.createElement(
          TrGroupComponent,
          es_extends({ key: 'pad-' + i }, trGroupProps),
          react_default.a.createElement(
            TrComponent,
            {
              className: classnames_default()('-padRow', (pageRows.length + i) % 2 ? '-even' : '-odd', trProps.className),
              style: trProps.style || {}
            },
            allVisibleColumns.map(makePadColumn)
          )
        );
      };

      var makeColumnFooter = function makeColumnFooter(column, i) {
        var resizedCol = resized.find(function (x) {
          return x.id === column.id;
        }) || {};
        var show = typeof column.show === 'function' ? column.show() : column.show;
        var width = utils.getFirstDefined(resizedCol.value, column.width, column.minWidth);
        var maxWidth = utils.getFirstDefined(resizedCol.value, column.width, column.maxWidth);
        var tFootTdProps = utils.splitProps(getTfootTdProps(finalState, undefined, column, _this2));
        var columnProps = utils.splitProps(column.getProps(finalState, undefined, column, _this2));
        var columnFooterProps = utils.splitProps(column.getFooterProps(finalState, undefined, column, _this2));

        var classes = [tFootTdProps.className, column.className, columnProps.className, columnFooterProps.className];

        var styles = es_extends({}, tFootTdProps.style, column.style, columnProps.style, columnFooterProps.style);

        return react_default.a.createElement(
          TdComponent,
          es_extends({
            key: i + '-' + column.id,
            className: classnames_default()(classes, !show && 'hidden'),
            style: es_extends({}, styles, {
              flex: width + ' 0 auto',
              width: utils.asPx(width),
              maxWidth: utils.asPx(maxWidth)
            })
          }, columnProps.rest, tFootTdProps.rest, columnFooterProps.rest),
          utils.normalizeComponent(column.Footer, {
            data: sortedData,
            column: column
          })
        );
      };

      var makeColumnFooters = function makeColumnFooters() {
        var tFootProps = utils.splitProps(getTfootProps(finalState, undefined, undefined, _this2));
        var tFootTrProps = utils.splitProps(getTfootTrProps(finalState, undefined, undefined, _this2));
        return react_default.a.createElement(
          TfootComponent,
          es_extends({
            className: tFootProps.className,
            style: es_extends({}, tFootProps.style, {
              minWidth: rowMinWidth + 'px'
            })
          }, tFootProps.rest),
          react_default.a.createElement(
            TrComponent,
            es_extends({
              className: classnames_default()(tFootTrProps.className),
              style: tFootTrProps.style
            }, tFootTrProps.rest),
            allVisibleColumns.map(makeColumnFooter)
          )
        );
      };

      var makePagination = function makePagination(isTop) {
        var paginationProps = utils.splitProps(getPaginationProps(finalState, undefined, undefined, _this2));
        return react_default.a.createElement(PaginationComponent, es_extends({}, resolvedState, {
          pages: pages,
          canPrevious: canPrevious,
          canNext: canNext,
          onPageChange: _this2.onPageChange,
          onPageSizeChange: _this2.onPageSizeChange,
          className: paginationProps.className,
          style: paginationProps.style,
          isTop: isTop
        }, paginationProps.rest));
      };

      var makeTable = function makeTable() {
        return react_default.a.createElement(
          'div',
          es_extends({
            className: classnames_default()('ReactTable', className, rootProps.className),
            style: es_extends({}, style, rootProps.style)
          }, rootProps.rest),
          showPagination && showPaginationTop ? react_default.a.createElement(
            'div',
            { className: 'pagination-top' },
            makePagination(true)
          ) : null,
          react_default.a.createElement(
            TableComponent,
            es_extends({
              className: classnames_default()(tableProps.className, currentlyResizing ? 'rt-resizing' : ''),
              style: tableProps.style
            }, tableProps.rest),
            hasHeaderGroups ? makeHeaderGroups() : null,
            makeHeaders(),
            hasFilters ? makeFilters() : null,
            react_default.a.createElement(
              TbodyComponent,
              es_extends({
                className: classnames_default()(tBodyProps.className),
                style: es_extends({}, tBodyProps.style, {
                  minWidth: rowMinWidth + 'px'
                })
              }, tBodyProps.rest),
              pageRows.map(function (d, i) {
                return makePageRow(d, i);
              }),
              padRows.map(makePadRow)
            ),
            hasColumnFooter ? makeColumnFooters() : null
          ),
          showPagination && showPaginationBottom ? react_default.a.createElement(
            'div',
            { className: 'pagination-bottom' },
            makePagination(false)
          ) : null,
          !pageRows.length && react_default.a.createElement(
            NoDataComponent,
            noDataProps,
            utils.normalizeComponent(noDataText)
          ),
          react_default.a.createElement(LoadingComponent, es_extends({ loading: loading, loadingText: loadingText }, loadingProps))
        );
      };

      // childProps are optionally passed to a function-as-a-child
      return children ? children(finalState, makeTable, this) : makeTable();
    }
  }]);

  return ReactTable;
}(methods(lifecycle(react["Component"])));

es_ReactTable.propTypes = propTypes;
es_ReactTable.defaultProps = es_defaultProps;
/* harmony default export */ var es = (es_ReactTable);
//# sourceMappingURL=data:application/json;base64, 
// EXTERNAL MODULE: ./node_modules/react-table/react-table.css
var react_table = __webpack_require__(125);

// CONCATENATED MODULE: ./src/components/QdtTable/QdtTable.jsx





/**
 * @name QdtTable
 * @param {object} layout - Qlik object layout
 * @param {string} model - Qlik object model
 * @param {options} object - Options
*/




 // import '../../styles/index.scss';
// TODO - set qColumnOrder in useHyperCube so it can be used here.

var QdtTable_QdtTable = function QdtTable(_ref) {
  var layout = _ref.layout,
      model = _ref.model,
      optionsProp = _ref.options;
  var defaultOptions = {
    minRows: undefined,
    pageSize: 10,
    style: {
      height: '100%'
    }
  };
  var options = Object(merge["a" /* default */])(defaultOptions, optionsProp);
  var ref = Object(react["useRef"])(null);
  var columns = Object(react["useMemo"])(function () {
    var _layout$qHyperCube, _layout$qHyperCube$qD, _layout$qHyperCube2, _layout$qHyperCube2$q;

    return layout ? [].concat(toConsumableArray_default()((_layout$qHyperCube = layout.qHyperCube) === null || _layout$qHyperCube === void 0 ? void 0 : (_layout$qHyperCube$qD = _layout$qHyperCube.qDimensionInfo) === null || _layout$qHyperCube$qD === void 0 ? void 0 : _layout$qHyperCube$qD.map(function (col, index) {
      return {
        Header: col.qFallbackTitle,
        accessor: function accessor(d) {
          return d[index].qText;
        },
        colorIndex: col.qAttrExprInfo.findIndex(function (attr) {
          return attr.id === 'color';
        }),
        defaultSortDesc: col.qSortIndicator === 'D',
        id: col.qFallbackTitle,
        qInterColumnIndex: index,
        qPath: "/qHyperCubeDef/qDimensions/".concat(index),
        qSortIndicator: col.qSortIndicator,
        qReverseSort: col.qReverseSort // getProps: (state, rowInfo) => {
        //   console.log(rowInfo);
        // },

      };
    })), toConsumableArray_default()((_layout$qHyperCube2 = layout.qHyperCube) === null || _layout$qHyperCube2 === void 0 ? void 0 : (_layout$qHyperCube2$q = _layout$qHyperCube2.qMeasureInfo) === null || _layout$qHyperCube2$q === void 0 ? void 0 : _layout$qHyperCube2$q.map(function (col, index) {
      var _layout$qHyperCube4, _layout$qHyperCube4$q;

      return {
        Header: col.qFallbackTitle,
        accessor: function accessor(d) {
          var _layout$qHyperCube3, _layout$qHyperCube3$q;

          return d[index + ((_layout$qHyperCube3 = layout.qHyperCube) === null || _layout$qHyperCube3 === void 0 ? void 0 : (_layout$qHyperCube3$q = _layout$qHyperCube3.qDimensionInfo) === null || _layout$qHyperCube3$q === void 0 ? void 0 : _layout$qHyperCube3$q.length)].qText;
        },
        defaultSortDesc: col.qSortIndicator === 'D',
        id: col.qFallbackTitle,
        qInterColumnIndex: index + ((_layout$qHyperCube4 = layout.qHyperCube) === null || _layout$qHyperCube4 === void 0 ? void 0 : (_layout$qHyperCube4$q = _layout$qHyperCube4.qDimensionInfo) === null || _layout$qHyperCube4$q === void 0 ? void 0 : _layout$qHyperCube4$q.length),
        qPath: "/qHyperCubeDef/qMeasures/".concat(index),
        qSortIndicator: col.qSortIndicator,
        qReverseSort: col.qReverseSort // getProps: (state, rowInfo) => {
        //   console.log(rowInfo);
        // },

      };
    }))) : [];
  }, [layout]);

  var _useState = Object(react["useState"])(true),
      _useState2 = slicedToArray_default()(_useState, 2),
      loading = _useState2[0],
      setLoading = _useState2[1];

  var pages = Object(react["useMemo"])(function () {
    return layout && Math.ceil(layout.qHyperCube.qSize.qcy / options.pageSize);
  }, [layout, options.pageSize]);

  var _useState3 = Object(react["useState"])(0),
      _useState4 = slicedToArray_default()(_useState3, 2),
      page = _useState4[0],
      setPage = _useState4[1];

  Object(react["useEffect"])(function () {
    if (page >= pages) {
      setPage(0);
    }
  }, [page, pages]);

  var _useState5 = Object(react["useState"])(null),
      _useState6 = slicedToArray_default()(_useState5, 2),
      data = _useState6[0],
      setData = _useState6[1];

  Object(react["useEffect"])(function () {
    if (!layout) return;

    asyncToGenerator_default()(
    /*#__PURE__*/
    regenerator_default.a.mark(function _callee() {
      var _layout$qHyperCube5;

      var dataPages;
      return regenerator_default.a.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              setLoading(true);
              _context.next = 3;
              return model.getHyperCubeData('/qHyperCubeDef', [{
                qWidth: (_layout$qHyperCube5 = layout.qHyperCube) === null || _layout$qHyperCube5 === void 0 ? void 0 : _layout$qHyperCube5.qSize.qcx,
                qHeight: options.pageSize,
                qTop: options.pageSize * page
              }]);

            case 3:
              dataPages = _context.sent;
              setData(dataPages[0]);
              setLoading(false);

            case 6:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }))();
  }, [layout, model, options.pageSize, page]);
  var handlePageChange = Object(react["useCallback"])(function (pageIndex) {
    setPage(pageIndex);
  }, []);
  var handleSortedChange = Object(react["useCallback"])(
  /*#__PURE__*/
  function () {
    var _ref3 = asyncToGenerator_default()(
    /*#__PURE__*/
    regenerator_default.a.mark(function _callee2(newSorted, column) {
      return regenerator_default.a.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              if (!(column.qSortIndicator === 'N')) {
                _context2.next = 7;
                break;
              }

              if (!column.qPath.includes('qDimensions')) {
                _context2.next = 4;
                break;
              }

              _context2.next = 4;
              return model.applyPatches([{
                qOp: 'add',
                qPath: "".concat(column.qPath, "/qDef/qSortCriterias"),
                qValue: JSON.stringify([{
                  qSortByLoadOrder: 1
                }])
              }]);

            case 4:
              if (!column.qPath.includes('qMeasures')) {
                _context2.next = 7;
                break;
              }

              _context2.next = 7;
              return model.applyPatches([{
                qOp: 'add',
                qPath: "".concat(column.qPath, "/qSortBy"),
                qValue: JSON.stringify({
                  qSortByLoadOrder: 1
                })
              }]);

            case 7:
              _context2.next = 9;
              return model.applyPatches([{
                qOp: 'replace',
                qPath: "".concat(column.qPath, "/qDef/qReverseSort"),
                qValue: JSON.stringify(newSorted[0].desc !== column.defaultSortDesc !== !!column.qReverseSort)
              }, {
                qOp: 'replace',
                qPath: '/qHyperCubeDef/qInterColumnSortOrder',
                qValue: JSON.stringify(toConsumableArray_default()(layout.qHyperCube.qEffectiveInterColumnSortOrder).sort(function (a, b) {
                  return a === column.qInterColumnIndex ? -1 : b === column.qInterColumnIndex ? 1 : 0;
                })) //eslint-disable-line

              }]);

            case 9:
              setPage(0);

            case 10:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));

    return function (_x, _x2) {
      return _ref3.apply(this, arguments);
    };
  }(), [model, layout]);
  return react_default.a.createElement("div", {
    ref: ref
  }, react_default.a.createElement(es, {
    manual: true,
    data: data ? data.qMatrix : [],
    columns: columns,
    pages: pages,
    page: page,
    loading: loading,
    onPageChange: handlePageChange,
    onSortedChange: handleSortedChange,
    defaultPageSize: options.pageSize,
    minRows: options.minRows,
    showPageSizeOptions: false,
    multiSort: false,
    className: "-striped",
    style: options.style,
    getTdProps: function getTdProps(_, rowInfo, column) {
      return {
        onClick: function onClick(e, handleOriginal) {
          if (column && rowInfo && column.qPath.includes('qDimensions') && rowInfo.original[column.qInterColumnIndex].qstate !== 'L') {
            model.selectHyperCubeValues('/qHyperCubeDef', column.qInterColumnIndex, [rowInfo.original[column.qInterColumnIndex].qElemNumber], true);
          }

          if (handleOriginal) {
            handleOriginal();
          }
        }
      };
    }
  }));
};

QdtTable_QdtTable.propTypes = {
  layout: prop_types_default.a.object,
  model: prop_types_default.a.object,
  options: prop_types_default.a.object
};
QdtTable_QdtTable.defaultProps = {
  layout: null,
  model: null,
  options: {}
};
/* harmony default export */ var components_QdtTable_QdtTable = (QdtTable_QdtTable);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/ButtonGroup/ButtonGroup.js









 // Force a side effect so we don't have any override priority issue.
// eslint-disable-next-line no-unused-expressions

esm_Button_Button.styles;
var ButtonGroup_styles = function styles(theme) {
  return {
    /* Styles applied to the root element. */
    root: {
      display: 'inline-flex',
      borderRadius: theme.shape.borderRadius
    },

    /* Styles applied to the root element if `variant="contained"`. */
    contained: {
      boxShadow: theme.shadows[2]
    },

    /* Pseudo-class applied to child elements if `disabled={true}`. */
    disabled: {},

    /* Styles applied to the root element if `fullWidth={true}`. */
    fullWidth: {
      width: '100%'
    },

    /* Styles applied to the root element if `orientation="vertical"`. */
    vertical: {
      flexDirection: 'column'
    },

    /* Styles applied to the children. */
    grouped: {
      minWidth: 40
    },

    /* Styles applied to the children if `orientation="horizontal"`. */
    groupedHorizontal: {
      '&:not(:first-child)': {
        borderTopLeftRadius: 0,
        borderBottomLeftRadius: 0
      },
      '&:not(:last-child)': {
        borderTopRightRadius: 0,
        borderBottomRightRadius: 0
      }
    },

    /* Styles applied to the children if `orientation="vertical"`. */
    groupedVertical: {
      '&:not(:first-child)': {
        borderTopRightRadius: 0,
        borderTopLeftRadius: 0
      },
      '&:not(:last-child)': {
        borderBottomRightRadius: 0,
        borderBottomLeftRadius: 0
      }
    },

    /* Styles applied to the children if `variant="text"`. */
    groupedText: {},

    /* Styles applied to the children if `variant="text"` and `orientation="horizontal"`. */
    groupedTextHorizontal: {
      '&:not(:last-child)': {
        borderRight: "1px solid ".concat(theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)')
      }
    },

    /* Styles applied to the children if `variant="text"` and `orientation="vertical"`. */
    groupedTextVertical: {
      '&:not(:last-child)': {
        borderBottom: "1px solid ".concat(theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)')
      }
    },

    /* Styles applied to the children if `variant="text"` and `color="primary"`. */
    groupedTextPrimary: {
      '&:not(:last-child)': {
        borderColor: Object(colorManipulator["b" /* fade */])(theme.palette.primary.main, 0.5)
      }
    },

    /* Styles applied to the children if `variant="text"` and `color="secondary"`. */
    groupedTextSecondary: {
      '&:not(:last-child)': {
        borderColor: Object(colorManipulator["b" /* fade */])(theme.palette.secondary.main, 0.5)
      }
    },

    /* Styles applied to the children if `variant="outlined"`. */
    groupedOutlined: {},

    /* Styles applied to the children if `variant="outlined"` and `orientation="horizontal"`. */
    groupedOutlinedHorizontal: {
      '&:not(:first-child)': {
        marginLeft: -1
      },
      '&:not(:last-child)': {
        borderRightColor: 'transparent'
      }
    },

    /* Styles applied to the children if `variant="outlined"` and `orientation="vertical"`. */
    groupedOutlinedVertical: {
      '&:not(:first-child)': {
        marginTop: -1
      },
      '&:not(:last-child)': {
        borderBottomColor: 'transparent'
      }
    },

    /* Styles applied to the children if `variant="outlined"` and `color="primary"`. */
    groupedOutlinedPrimary: {
      '&:hover': {
        borderColor: theme.palette.primary.main
      }
    },

    /* Styles applied to the children if `variant="outlined"` and `color="secondary"`. */
    groupedOutlinedSecondary: {
      '&:hover': {
        borderColor: theme.palette.secondary.main
      }
    },

    /* Styles applied to the children if `variant="contained"`. */
    groupedContained: {
      boxShadow: 'none'
    },

    /* Styles applied to the children if `variant="contained"` and `orientation="horizontal"`. */
    groupedContainedHorizontal: {
      '&:not(:last-child)': {
        borderRight: "1px solid ".concat(theme.palette.grey[400]),
        '&$disabled': {
          borderRight: "1px solid ".concat(theme.palette.action.disabled)
        }
      }
    },

    /* Styles applied to the children if `variant="contained"` and `orientation="vertical"`. */
    groupedContainedVertical: {
      '&:not(:last-child)': {
        borderBottom: "1px solid ".concat(theme.palette.grey[400]),
        '&$disabled': {
          borderBottom: "1px solid ".concat(theme.palette.action.disabled)
        }
      }
    },

    /* Styles applied to the children if `variant="contained"` and `color="primary"`. */
    groupedContainedPrimary: {
      '&:not(:last-child)': {
        borderColor: theme.palette.primary.dark
      }
    },

    /* Styles applied to the children if `variant="contained"` and `color="secondary"`. */
    groupedContainedSecondary: {
      '&:not(:last-child)': {
        borderColor: theme.palette.secondary.dark
      }
    }
  };
};
var ButtonGroup_ButtonGroup = react_default.a.forwardRef(function ButtonGroup(props, ref) {
  var children = props.children,
      classes = props.classes,
      className = props.className,
      _props$color = props.color,
      color = _props$color === void 0 ? 'default' : _props$color,
      _props$component = props.component,
      Component = _props$component === void 0 ? 'div' : _props$component,
      _props$disabled = props.disabled,
      disabled = _props$disabled === void 0 ? false : _props$disabled,
      _props$disableFocusRi = props.disableFocusRipple,
      disableFocusRipple = _props$disableFocusRi === void 0 ? false : _props$disableFocusRi,
      _props$disableRipple = props.disableRipple,
      disableRipple = _props$disableRipple === void 0 ? false : _props$disableRipple,
      _props$fullWidth = props.fullWidth,
      fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,
      _props$orientation = props.orientation,
      orientation = _props$orientation === void 0 ? 'horizontal' : _props$orientation,
      _props$size = props.size,
      size = _props$size === void 0 ? 'medium' : _props$size,
      _props$variant = props.variant,
      variant = _props$variant === void 0 ? 'outlined' : _props$variant,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["children", "classes", "className", "color", "component", "disabled", "disableFocusRipple", "disableRipple", "fullWidth", "orientation", "size", "variant"]);

  var buttonClassName = Object(clsx_m["a" /* default */])(classes.grouped, classes["grouped".concat(Object(capitalize["a" /* default */])(orientation))], classes["grouped".concat(Object(capitalize["a" /* default */])(variant))], classes["grouped".concat(Object(capitalize["a" /* default */])(variant)).concat(Object(capitalize["a" /* default */])(orientation))], classes["grouped".concat(Object(capitalize["a" /* default */])(variant)).concat(color !== 'default' ? Object(capitalize["a" /* default */])(color) : '')], disabled && classes.disabled);
  return react_default.a.createElement(Component, Object(helpers_esm_extends["a" /* default */])({
    role: "group",
    className: Object(clsx_m["a" /* default */])(classes.root, className, fullWidth && classes.fullWidth, variant === 'contained' && classes.contained, orientation === 'vertical' && classes.vertical),
    ref: ref
  }, other), react_default.a.Children.map(children, function (child) {
    if (!react_default.a.isValidElement(child)) {
      return null;
    }

    if (false) {}

    return react_default.a.cloneElement(child, {
      className: Object(clsx_m["a" /* default */])(buttonClassName, child.props.className),
      disabled: child.props.disabled || disabled,
      color: child.props.color || color,
      disableFocusRipple: disableFocusRipple,
      disableRipple: disableRipple,
      fullWidth: fullWidth,
      size: child.props.size || size,
      variant: child.props.variant || variant
    });
  }));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_ButtonGroup_ButtonGroup = (Object(withStyles["a" /* default */])(ButtonGroup_styles, {
  name: 'MuiButtonGroup'
})(ButtonGroup_ButtonGroup));
// CONCATENATED MODULE: ./node_modules/@material-ui/icons/node_modules/@babel/runtime/helpers/esm/extends.js
function extends_extends() {
  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_extends.apply(this, arguments);
}
// CONCATENATED MODULE: ./node_modules/@material-ui/icons/esm/utils/createSvgIcon.js



function createSvgIcon_createSvgIcon(path, displayName) {
  var Component = react_default.a.memo(react_default.a.forwardRef(function (props, ref) {
    return react_default.a.createElement(SvgIcon["a" /* default */], extends_extends({
      ref: ref
    }, props), path);
  }));

  if (false) {}

  Component.muiName = SvgIcon["a" /* default */].muiName;
  return Component;
}
// CONCATENATED MODULE: ./node_modules/@material-ui/icons/esm/SkipPrevious.js


/* harmony default export */ var SkipPrevious = (createSvgIcon_createSvgIcon(react_default.a.createElement("path", {
  d: "M6 6h2v12H6zm3.5 6l8.5 6V6z"
}), 'SkipPrevious'));
// CONCATENATED MODULE: ./node_modules/@material-ui/icons/esm/PlayArrow.js


/* harmony default export */ var PlayArrow = (createSvgIcon_createSvgIcon(react_default.a.createElement("path", {
  d: "M8 5v14l11-7z"
}), 'PlayArrow'));
// CONCATENATED MODULE: ./node_modules/@material-ui/icons/esm/Pause.js


/* harmony default export */ var Pause = (createSvgIcon_createSvgIcon(react_default.a.createElement("path", {
  d: "M6 19h4V5H6v14zm8-14v14h4V5h-4z"
}), 'Pause'));
// CONCATENATED MODULE: ./node_modules/@material-ui/icons/esm/Stop.js


/* harmony default export */ var Stop = (createSvgIcon_createSvgIcon(react_default.a.createElement("path", {
  d: "M6 6h12v12H6z"
}), 'Stop'));
// CONCATENATED MODULE: ./node_modules/@material-ui/icons/esm/SkipNext.js


/* harmony default export */ var SkipNext = (createSvgIcon_createSvgIcon(react_default.a.createElement("path", {
  d: "M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"
}), 'SkipNext'));
// CONCATENATED MODULE: ./src/components/QdtSequencer/QdtSequencer.jsx




/**
 * @name QdtSequencer
 * @param {array} cols - Dimension for the data to cycle through
 * @param {number} delay [5] - Loop through the results in given seconds.
 * @param {number} keyCode [null] - If we want to control the sequencer with a key stroke. Toggles playing.
 * @param {bool} navigation [true] - If we want to show / hide the navigation and use only key strokes
 * @description
 * Loop through a dimension and make selections.
*/






var QdtSequencer_QdtSequencer = function QdtSequencer(_ref) {
  var layout = _ref.layout,
      model = _ref.model,
      optionsProp = _ref.options;
  var defaultOptions = {
    variant: 'outlined',
    color: 'primary',
    size: 'small',
    toggleSelections: false,
    delay: 5,
    defaultRow: -1
  };
  var options = Object(merge["a" /* default */])(defaultOptions, optionsProp);
  var qMatrix = Object(react["useMemo"])(function () {
    var _layout$qListObject, _layout$qListObject$q;

    return (layout === null || layout === void 0 ? void 0 : (_layout$qListObject = layout.qListObject) === null || _layout$qListObject === void 0 ? void 0 : (_layout$qListObject$q = _layout$qListObject.qDataPages[0]) === null || _layout$qListObject$q === void 0 ? void 0 : _layout$qListObject$q.qMatrix) || [];
  }, [layout]);
  var initialized = Object(react["useRef"])(false);
  var playTimeout = Object(react["useRef"])(null);
  var currentRowIndex = Object(react["useRef"])(options.defaultRow);

  var _useState = Object(react["useState"])(false),
      _useState2 = slicedToArray_default()(_useState, 2),
      playing = _useState2[0],
      setplaying = _useState2[1];

  var select = Object(react["useCallback"])(function (qElemNumber) {
    var toggle = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
    var ignoreLock = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
    return model.selectListObjectValues('/qListObjectDef', [qElemNumber], toggle, ignoreLock);
  }, [model]);
  var clearSelections = Object(react["useCallback"])(function () {
    return model.clearSelections('/qListObjectDef');
  }, [model]);
  var reset = Object(react["useCallback"])(function () {
    if (playTimeout.current) clearTimeout(playTimeout.current);
    currentRowIndex.current = options.defaultRow;

    if (options.defaultRow !== -1) {
      select(qMatrix[options.defaultRow][0].qElemNumber, options.toggleSelections, true);
    } else {
      clearSelections();
    }
  }, [options.defaultRow, options.toggleSelections, select, qMatrix, clearSelections]);
  var previous = Object(react["useCallback"])(
  /*#__PURE__*/
  asyncToGenerator_default()(
  /*#__PURE__*/
  regenerator_default.a.mark(function _callee() {
    return regenerator_default.a.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            if (!qMatrix[currentRowIndex.current - 1]) {
              _context.next = 4;
              break;
            }

            _context.next = 3;
            return select(qMatrix[currentRowIndex.current - 1][0].qElemNumber, options.toggleSelections, true);

          case 3:
            currentRowIndex.current -= 1;

          case 4:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  })), [qMatrix, options.toggleSelections, select]);
  var next = Object(react["useCallback"])(
  /*#__PURE__*/
  asyncToGenerator_default()(
  /*#__PURE__*/
  regenerator_default.a.mark(function _callee2() {
    return regenerator_default.a.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            if (!qMatrix[currentRowIndex.current + 1]) {
              _context2.next = 4;
              break;
            }

            _context2.next = 3;
            return select(qMatrix[currentRowIndex.current + 1][0].qElemNumber, options.toggleSelections, true);

          case 3:
            currentRowIndex.current += 1;

          case 4:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  })), [qMatrix, options.toggleSelections, select]);
  var play = Object(react["useCallback"])(
  /*#__PURE__*/
  asyncToGenerator_default()(
  /*#__PURE__*/
  regenerator_default.a.mark(function _callee3() {
    return regenerator_default.a.wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            if (!qMatrix[currentRowIndex.current + 1]) {
              _context3.next = 7;
              break;
            }

            setplaying(true);
            _context3.next = 4;
            return next();

          case 4:
            playTimeout.current = setTimeout(function () {
              play();
            }, options.delay * 1000);
            _context3.next = 8;
            break;

          case 7:
            setplaying(false);

          case 8:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3);
  })), [qMatrix, next, options.delay]);
  var pause = Object(react["useCallback"])(function () {
    if (playTimeout.current) clearTimeout(playTimeout.current);
    setplaying(false);
  }, []);
  var stop = Object(react["useCallback"])(function () {
    if (playTimeout.current) clearTimeout(playTimeout.current);
    setplaying(false);
    reset();
  }, [reset]); // if not initialized after qMatrix has data, reset

  Object(react["useEffect"])(function () {
    if (qMatrix.length && !initialized.current) {
      reset();
      initialized.current = true;
    }
  }, [qMatrix, reset, select]);
  return react_default.a.createElement(esm_ButtonGroup_ButtonGroup, {
    size: options.size,
    variant: options.variant,
    color: options.color,
    "aria-label": "qdt-sequencer"
  }, react_default.a.createElement(esm_Button_Button, {
    onClick: previous,
    disabled: currentRowIndex.current === options.defaultRow
  }, react_default.a.createElement(SkipPrevious, null)), react_default.a.createElement(esm_Button_Button, {
    onClick: play,
    disabled: playing
  }, react_default.a.createElement(PlayArrow, null)), react_default.a.createElement(esm_Button_Button, {
    onClick: pause,
    disabled: !playing
  }, react_default.a.createElement(Pause, null)), react_default.a.createElement(esm_Button_Button, {
    onClick: stop,
    disabled: currentRowIndex.current === options.defaultRow
  }, react_default.a.createElement(Stop, null)), react_default.a.createElement(esm_Button_Button, {
    onClick: next,
    disabled: currentRowIndex.current >= qMatrix.length
  }, react_default.a.createElement(SkipNext, null)));
};

QdtSequencer_QdtSequencer.propTypes = {
  layout: prop_types_default.a.object,
  model: prop_types_default.a.object,
  options: prop_types_default.a.object
};
QdtSequencer_QdtSequencer.defaultProps = {
  layout: null,
  model: null,
  options: {}
};
/* harmony default export */ var components_QdtSequencer_QdtSequencer = (QdtSequencer_QdtSequencer);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Slider/ValueLabel.js





var ValueLabel_styles = function styles(theme) {
  return {
    thumb: {
      '&$open': {
        '& $offset': {
          transform: 'scale(1) translateY(-10px)'
        }
      }
    },
    open: {},
    offset: Object(helpers_esm_extends["a" /* default */])({
      zIndex: 1
    }, theme.typography.body2, {
      fontSize: theme.typography.pxToRem(12),
      lineHeight: 1.2,
      transition: theme.transitions.create(['transform'], {
        duration: theme.transitions.duration.shortest
      }),
      top: -34,
      transformOrigin: 'bottom center',
      transform: 'scale(0)',
      position: 'absolute'
    }),
    circle: {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      width: 32,
      height: 32,
      borderRadius: '50% 50% 50% 0',
      backgroundColor: 'currentColor',
      transform: 'rotate(-45deg)'
    },
    label: {
      color: theme.palette.primary.contrastText,
      transform: 'rotate(45deg)'
    }
  };
};
/**
 * @ignore - internal component.
 */


function ValueLabel(props) {
  var children = props.children,
      classes = props.classes,
      className = props.className,
      open = props.open,
      value = props.value,
      valueLabelDisplay = props.valueLabelDisplay;

  if (valueLabelDisplay === 'off') {
    return children;
  }

  return react_default.a.cloneElement(children, {
    className: Object(clsx_m["a" /* default */])(children.props.className, (open || valueLabelDisplay === 'on') && classes.open, classes.thumb)
  }, react_default.a.createElement("span", {
    className: Object(clsx_m["a" /* default */])(classes.offset, className)
  }, react_default.a.createElement("span", {
    className: classes.circle
  }, react_default.a.createElement("span", {
    className: classes.label
  }, value))));
}

/* harmony default export */ var Slider_ValueLabel = (Object(withStyles["a" /* default */])(ValueLabel_styles, {
  name: 'PrivateValueLabel'
})(ValueLabel));
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Slider/Slider.js



















function asc(a, b) {
  return a - b;
}

function Slider_clamp(value, min, max) {
  return Math.min(Math.max(min, value), max);
}

function findClosest(values, currentValue) {
  var _values$reduce = values.reduce(function (acc, value, index) {
    var distance = Math.abs(currentValue - value);

    if (acc === null || distance < acc.distance || distance === acc.distance) {
      return {
        distance: distance,
        index: index
      };
    }

    return acc;
  }, null),
      closestIndex = _values$reduce.index;

  return closestIndex;
}

function trackFinger(event, touchId) {
  if (touchId.current !== undefined && event.changedTouches) {
    for (var i = 0; i < event.changedTouches.length; i += 1) {
      var touch = event.changedTouches[i];

      if (touch.identifier === touchId.current) {
        return {
          x: touch.clientX,
          y: touch.clientY
        };
      }
    }

    return false;
  }

  return {
    x: event.clientX,
    y: event.clientY
  };
}

function valueToPercent(value, min, max) {
  return (value - min) * 100 / (max - min);
}

function percentToValue(percent, min, max) {
  return (max - min) * percent + min;
}

function getDecimalPrecision(num) {
  // This handles the case when num is very small (0.00000001), js will turn this into 1e-8.
  // When num is bigger than 1 or less than -1 it won't get converted to this notation so it's fine.
  if (Math.abs(num) < 1) {
    var parts = num.toExponential().split('e-');
    var matissaDecimalPart = parts[0].split('.')[1];
    return (matissaDecimalPart ? matissaDecimalPart.length : 0) + parseInt(parts[1], 10);
  }

  var decimalPart = num.toString().split('.')[1];
  return decimalPart ? decimalPart.length : 0;
}

function roundValueToStep(value, step, min) {
  var nearest = Math.round((value - min) / step) * step + min;
  return Number(nearest.toFixed(getDecimalPrecision(step)));
}

function setValueIndex(_ref) {
  var values = _ref.values,
      source = _ref.source,
      newValue = _ref.newValue,
      index = _ref.index;

  // Performance shortcut
  if (values[index] === newValue) {
    return source;
  }

  var output = _toConsumableArray(values);

  output[index] = newValue;
  return output;
}

function focusThumb(_ref2) {
  var sliderRef = _ref2.sliderRef,
      activeIndex = _ref2.activeIndex,
      setActive = _ref2.setActive;

  if (!sliderRef.current.contains(document.activeElement) || Number(document.activeElement.getAttribute('data-index')) !== activeIndex) {
    sliderRef.current.querySelector("[data-index=\"".concat(activeIndex, "\"]")).focus();
  }

  if (setActive) {
    setActive(activeIndex);
  }
}

var axisProps = {
  horizontal: {
    offset: function offset(percent) {
      return {
        left: "".concat(percent, "%")
      };
    },
    leap: function leap(percent) {
      return {
        width: "".concat(percent, "%")
      };
    }
  },
  'horizontal-reverse': {
    offset: function offset(percent) {
      return {
        right: "".concat(percent, "%")
      };
    },
    leap: function leap(percent) {
      return {
        width: "".concat(percent, "%")
      };
    }
  },
  vertical: {
    offset: function offset(percent) {
      return {
        bottom: "".concat(percent, "%")
      };
    },
    leap: function leap(percent) {
      return {
        height: "".concat(percent, "%")
      };
    }
  }
};

var Identity = function Identity(x) {
  return x;
};

var Slider_styles = function styles(theme) {
  return {
    /* Styles applied to the root element. */
    root: {
      height: 2,
      width: '100%',
      boxSizing: 'content-box',
      padding: '13px 0',
      display: 'inline-block',
      position: 'relative',
      cursor: 'pointer',
      touchAction: 'none',
      color: theme.palette.primary.main,
      WebkitTapHighlightColor: 'transparent',
      '&$disabled': {
        pointerEvents: 'none',
        cursor: 'default',
        color: theme.palette.grey[400]
      },
      '&$vertical': {
        width: 2,
        height: '100%',
        padding: '0 13px'
      },
      // The primary input mechanism of the device includes a pointing device of limited accuracy.
      '@media (pointer: coarse)': {
        // Reach 42px touch target, about ~8mm on screen.
        padding: '20px 0',
        '&$vertical': {
          padding: '0 20px'
        }
      }
    },

    /* Styles applied to the root element if `color="primary"`. */
    colorPrimary: {// TODO v5: move the style here
    },

    /* Styles applied to the root element if `color="secondary"`. */
    colorSecondary: {
      color: theme.palette.secondary.main
    },

    /* Styles applied to the root element if `marks` is provided with at least one label. */
    marked: {
      marginBottom: 20,
      '&$vertical': {
        marginBottom: 'auto',
        marginRight: 20
      }
    },

    /* Pseudo-class applied to the root element if `orientation="vertical"`. */
    vertical: {},

    /* Pseudo-class applied to the root and thumb element if `disabled={true}`. */
    disabled: {},

    /* Styles applied to the rail element. */
    rail: {
      display: 'block',
      position: 'absolute',
      width: '100%',
      height: 2,
      borderRadius: 1,
      backgroundColor: 'currentColor',
      opacity: 0.38,
      '$vertical &': {
        height: '100%',
        width: 2
      }
    },

    /* Styles applied to the track element. */
    track: {
      display: 'block',
      position: 'absolute',
      height: 2,
      borderRadius: 1,
      backgroundColor: 'currentColor',
      '$vertical &': {
        width: 2
      }
    },

    /* Styles applied to the track element if `track={false}`. */
    trackFalse: {
      '& $track': {
        display: 'none'
      }
    },

    /* Styles applied to the track element if `track="inverted"`. */
    trackInverted: {
      '& $track': {
        backgroundColor: // Same logic as the LinearProgress track color
        theme.palette.type === 'light' ? Object(colorManipulator["d" /* lighten */])(theme.palette.primary.main, 0.62) : Object(colorManipulator["a" /* darken */])(theme.palette.primary.main, 0.5)
      },
      '& $rail': {
        opacity: 1
      }
    },

    /* Styles applied to the thumb element. */
    thumb: {
      position: 'absolute',
      width: 12,
      height: 12,
      marginLeft: -6,
      marginTop: -5,
      boxSizing: 'border-box',
      borderRadius: '50%',
      outline: 0,
      backgroundColor: 'currentColor',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      transition: theme.transitions.create(['box-shadow'], {
        duration: theme.transitions.duration.shortest
      }),
      '&::after': {
        position: 'absolute',
        content: '""',
        borderRadius: '50%',
        // reach 42px hit target (2 * 15 + thumb diameter)
        left: -15,
        top: -15,
        right: -15,
        bottom: -15
      },
      '&$focusVisible,&:hover': {
        boxShadow: "0px 0px 0px 8px ".concat(Object(colorManipulator["b" /* fade */])(theme.palette.primary.main, 0.16)),
        '@media (hover: none)': {
          boxShadow: 'none'
        }
      },
      '&$active': {
        boxShadow: "0px 0px 0px 14px ".concat(Object(colorManipulator["b" /* fade */])(theme.palette.primary.main, 0.16))
      },
      '&$disabled': {
        width: 8,
        height: 8,
        marginLeft: -4,
        marginTop: -3,
        '&:hover': {
          boxShadow: 'none'
        }
      },
      '$vertical &': {
        marginLeft: -5,
        marginBottom: -6
      },
      '$vertical &$disabled': {
        marginLeft: -3,
        marginBottom: -4
      }
    },

    /* Styles applied to the thumb element if `color="primary"`. */
    thumbColorPrimary: {// TODO v5: move the style here
    },

    /* Styles applied to the thumb element if `color="secondary"`. */
    thumbColorSecondary: {
      '&$focusVisible,&:hover': {
        boxShadow: "0px 0px 0px 8px ".concat(Object(colorManipulator["b" /* fade */])(theme.palette.secondary.main, 0.16))
      },
      '&$active': {
        boxShadow: "0px 0px 0px 14px ".concat(Object(colorManipulator["b" /* fade */])(theme.palette.secondary.main, 0.16))
      }
    },

    /* Pseudo-class applied to the thumb element if it's active. */
    active: {},

    /* Pseudo-class applied to the thumb element if keyboard focused. */
    focusVisible: {},

    /* Styles applied to the thumb label element. */
    valueLabel: {},

    /* Styles applied to the mark element. */
    mark: {
      position: 'absolute',
      width: 2,
      height: 2,
      borderRadius: 1,
      backgroundColor: 'currentColor'
    },

    /* Styles applied to the mark element if active (depending on the value). */
    markActive: {
      backgroundColor: theme.palette.background.paper,
      opacity: 0.8
    },

    /* Styles applied to the mark label element. */
    markLabel: Object(helpers_esm_extends["a" /* default */])({}, theme.typography.body2, {
      color: theme.palette.text.secondary,
      position: 'absolute',
      top: 26,
      transform: 'translateX(-50%)',
      whiteSpace: 'nowrap',
      '$vertical &': {
        top: 'auto',
        left: 26,
        transform: 'translateY(50%)'
      },
      '@media (pointer: coarse)': {
        top: 40,
        '$vertical &': {
          left: 31
        }
      }
    }),

    /* Styles applied to the mark label element if active (depending on the value). */
    markLabelActive: {
      color: theme.palette.text.primary
    }
  };
};
var Slider_Slider = react_default.a.forwardRef(function Slider(props, ref) {
  var ariaLabel = props['aria-label'],
      ariaLabelledby = props['aria-labelledby'],
      ariaValuetext = props['aria-valuetext'],
      classes = props.classes,
      className = props.className,
      _props$color = props.color,
      color = _props$color === void 0 ? 'primary' : _props$color,
      _props$component = props.component,
      Component = _props$component === void 0 ? 'span' : _props$component,
      defaultValue = props.defaultValue,
      _props$disabled = props.disabled,
      disabled = _props$disabled === void 0 ? false : _props$disabled,
      getAriaLabel = props.getAriaLabel,
      getAriaValueText = props.getAriaValueText,
      _props$marks = props.marks,
      marksProp = _props$marks === void 0 ? false : _props$marks,
      _props$max = props.max,
      max = _props$max === void 0 ? 100 : _props$max,
      _props$min = props.min,
      min = _props$min === void 0 ? 0 : _props$min,
      name = props.name,
      onChange = props.onChange,
      onChangeCommitted = props.onChangeCommitted,
      onMouseDown = props.onMouseDown,
      _props$orientation = props.orientation,
      orientation = _props$orientation === void 0 ? 'horizontal' : _props$orientation,
      _props$scale = props.scale,
      scale = _props$scale === void 0 ? Identity : _props$scale,
      _props$step = props.step,
      step = _props$step === void 0 ? 1 : _props$step,
      _props$ThumbComponent = props.ThumbComponent,
      ThumbComponent = _props$ThumbComponent === void 0 ? 'span' : _props$ThumbComponent,
      _props$track = props.track,
      track = _props$track === void 0 ? 'normal' : _props$track,
      valueProp = props.value,
      _props$ValueLabelComp = props.ValueLabelComponent,
      ValueLabelComponent = _props$ValueLabelComp === void 0 ? Slider_ValueLabel : _props$ValueLabelComp,
      _props$valueLabelDisp = props.valueLabelDisplay,
      valueLabelDisplay = _props$valueLabelDisp === void 0 ? 'off' : _props$valueLabelDisp,
      _props$valueLabelForm = props.valueLabelFormat,
      valueLabelFormat = _props$valueLabelForm === void 0 ? Identity : _props$valueLabelForm,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["aria-label", "aria-labelledby", "aria-valuetext", "classes", "className", "color", "component", "defaultValue", "disabled", "getAriaLabel", "getAriaValueText", "marks", "max", "min", "name", "onChange", "onChangeCommitted", "onMouseDown", "orientation", "scale", "step", "ThumbComponent", "track", "value", "ValueLabelComponent", "valueLabelDisplay", "valueLabelFormat"]);

  var theme = useTheme_useTheme();
  var touchId = react_default.a.useRef(); // We can't use the :active browser pseudo-classes.
  // - The active state isn't triggered when clicking on the rail.
  // - The active state isn't transfered when inversing a range slider.

  var _React$useState = react_default.a.useState(-1),
      active = _React$useState[0],
      setActive = _React$useState[1];

  var _React$useState2 = react_default.a.useState(-1),
      open = _React$useState2[0],
      setOpen = _React$useState2[1];

  var _useControlled = useControlled({
    controlled: valueProp,
    default: defaultValue,
    name: 'Slider'
  }),
      _useControlled2 = _slicedToArray(_useControlled, 2),
      valueDerived = _useControlled2[0],
      setValueState = _useControlled2[1];

  var range = Array.isArray(valueDerived);
  var instanceRef = react_default.a.useRef();
  var values = range ? _toConsumableArray(valueDerived).sort(asc) : [valueDerived];
  values = values.map(function (value) {
    return Slider_clamp(value, min, max);
  });
  var marks = marksProp === true && step !== null ? _toConsumableArray(Array(Math.floor((max - min) / step) + 1)).map(function (_, index) {
    return {
      value: min + step * index
    };
  }) : marksProp || [];
  instanceRef.current = {
    source: valueDerived // Keep track of the input value to leverage immutable state comparison.

  };

  var _useIsFocusVisible = useIsFocusVisible(),
      isFocusVisible = _useIsFocusVisible.isFocusVisible,
      onBlurVisible = _useIsFocusVisible.onBlurVisible,
      focusVisibleRef = _useIsFocusVisible.ref;

  var _React$useState3 = react_default.a.useState(-1),
      focusVisible = _React$useState3[0],
      setFocusVisible = _React$useState3[1];

  var sliderRef = react_default.a.useRef();
  var handleFocusRef = useForkRef(focusVisibleRef, sliderRef);
  var handleRef = useForkRef(ref, handleFocusRef);
  var handleFocus = useEventCallback(function (event) {
    var index = Number(event.currentTarget.getAttribute('data-index'));

    if (isFocusVisible(event)) {
      setFocusVisible(index);
    }

    setOpen(index);
  });
  var handleBlur = useEventCallback(function () {
    if (focusVisible !== -1) {
      setFocusVisible(-1);
      onBlurVisible();
    }

    setOpen(-1);
  });
  var handleMouseOver = useEventCallback(function (event) {
    var index = Number(event.currentTarget.getAttribute('data-index'));
    setOpen(index);
  });
  var handleMouseLeave = useEventCallback(function () {
    setOpen(-1);
  });
  var handleKeyDown = useEventCallback(function (event) {
    var index = Number(event.currentTarget.getAttribute('data-index'));
    var value = values[index];
    var tenPercents = (max - min) / 10;
    var marksValues = marks.map(function (mark) {
      return mark.value;
    });
    var marksIndex = marksValues.indexOf(value);
    var newValue;

    switch (event.key) {
      case 'Home':
        newValue = min;
        break;

      case 'End':
        newValue = max;
        break;

      case 'PageUp':
        if (step) {
          newValue = value + tenPercents;
        }

        break;

      case 'PageDown':
        if (step) {
          newValue = value - tenPercents;
        }

        break;

      case 'ArrowRight':
      case 'ArrowUp':
        if (step) {
          newValue = value + step;
        } else {
          newValue = marksValues[marksIndex + 1] || marksValues[marksValues.length - 1];
        }

        break;

      case 'ArrowLeft':
      case 'ArrowDown':
        if (step) {
          newValue = value - step;
        } else {
          newValue = marksValues[marksIndex - 1] || marksValues[0];
        }

        break;

      default:
        return;
    } // Prevent scroll of the page


    event.preventDefault();

    if (step) {
      newValue = roundValueToStep(newValue, step, min);
    }

    newValue = Slider_clamp(newValue, min, max);

    if (range) {
      var previousValue = newValue;
      newValue = setValueIndex({
        values: values,
        source: valueDerived,
        newValue: newValue,
        index: index
      }).sort(asc);
      focusThumb({
        sliderRef: sliderRef,
        activeIndex: newValue.indexOf(previousValue)
      });
    }

    setValueState(newValue);
    setFocusVisible(index);

    if (onChange) {
      onChange(event, newValue);
    }

    if (onChangeCommitted) {
      onChangeCommitted(event, newValue);
    }
  });
  var previousIndex = react_default.a.useRef();
  var axis = orientation;

  if (theme.direction === 'rtl' && orientation !== "vertical") {
    axis += '-reverse';
  }

  var getFingerNewValue = function getFingerNewValue(_ref3) {
    var finger = _ref3.finger,
        _ref3$move = _ref3.move,
        move = _ref3$move === void 0 ? false : _ref3$move,
        values2 = _ref3.values,
        source = _ref3.source;
    var slider = sliderRef.current;

    var _slider$getBoundingCl = slider.getBoundingClientRect(),
        width = _slider$getBoundingCl.width,
        height = _slider$getBoundingCl.height,
        bottom = _slider$getBoundingCl.bottom,
        left = _slider$getBoundingCl.left;

    var percent;

    if (axis.indexOf('vertical') === 0) {
      percent = (bottom - finger.y) / height;
    } else {
      percent = (finger.x - left) / width;
    }

    if (axis.indexOf('-reverse') !== -1) {
      percent = 1 - percent;
    }

    var newValue;
    newValue = percentToValue(percent, min, max);

    if (step) {
      newValue = roundValueToStep(newValue, step, min);
    } else {
      var marksValues = marks.map(function (mark) {
        return mark.value;
      });
      var closestIndex = findClosest(marksValues, newValue);
      newValue = marksValues[closestIndex];
    }

    newValue = Slider_clamp(newValue, min, max);
    var activeIndex = 0;

    if (range) {
      if (!move) {
        activeIndex = findClosest(values2, newValue);
      } else {
        activeIndex = previousIndex.current;
      }

      var previousValue = newValue;
      newValue = setValueIndex({
        values: values2,
        source: source,
        newValue: newValue,
        index: activeIndex
      }).sort(asc);
      activeIndex = newValue.indexOf(previousValue);
      previousIndex.current = activeIndex;
    }

    return {
      newValue: newValue,
      activeIndex: activeIndex
    };
  };

  var handleTouchMove = useEventCallback(function (event) {
    var finger = trackFinger(event, touchId);

    if (!finger) {
      return;
    }

    var _getFingerNewValue = getFingerNewValue({
      finger: finger,
      move: true,
      values: values,
      source: valueDerived
    }),
        newValue = _getFingerNewValue.newValue,
        activeIndex = _getFingerNewValue.activeIndex;

    focusThumb({
      sliderRef: sliderRef,
      activeIndex: activeIndex,
      setActive: setActive
    });
    setValueState(newValue);

    if (onChange) {
      onChange(event, newValue);
    }
  });
  var handleTouchEnd = useEventCallback(function (event) {
    var finger = trackFinger(event, touchId);

    if (!finger) {
      return;
    }

    var _getFingerNewValue2 = getFingerNewValue({
      finger: finger,
      values: values,
      source: valueDerived
    }),
        newValue = _getFingerNewValue2.newValue;

    setActive(-1);

    if (event.type === 'touchend') {
      setOpen(-1);
    }

    if (onChangeCommitted) {
      onChangeCommitted(event, newValue);
    }

    touchId.current = undefined;
    var doc = ownerDocument(sliderRef.current);
    doc.removeEventListener('mousemove', handleTouchMove);
    doc.removeEventListener('mouseup', handleTouchEnd);
    doc.removeEventListener('touchmove', handleTouchMove);
    doc.removeEventListener('touchend', handleTouchEnd);
  });
  var handleTouchStart = useEventCallback(function (event) {
    // Workaround as Safari has partial support for touchAction: 'none'.
    event.preventDefault();
    var touch = event.changedTouches[0];

    if (touch != null) {
      // A number that uniquely identifies the current finger in the touch session.
      touchId.current = touch.identifier;
    }

    var finger = trackFinger(event, touchId);

    var _getFingerNewValue3 = getFingerNewValue({
      finger: finger,
      values: values,
      source: valueDerived
    }),
        newValue = _getFingerNewValue3.newValue,
        activeIndex = _getFingerNewValue3.activeIndex;

    focusThumb({
      sliderRef: sliderRef,
      activeIndex: activeIndex,
      setActive: setActive
    });
    setValueState(newValue);

    if (onChange) {
      onChange(event, newValue);
    }

    var doc = ownerDocument(sliderRef.current);
    doc.addEventListener('touchmove', handleTouchMove);
    doc.addEventListener('touchend', handleTouchEnd);
  });
  react_default.a.useEffect(function () {
    var slider = sliderRef.current;
    slider.addEventListener('touchstart', handleTouchStart);
    var doc = ownerDocument(slider);
    return function () {
      slider.removeEventListener('touchstart', handleTouchStart);
      doc.removeEventListener('mousemove', handleTouchMove);
      doc.removeEventListener('mouseup', handleTouchEnd);
      doc.removeEventListener('touchmove', handleTouchMove);
      doc.removeEventListener('touchend', handleTouchEnd);
    };
  }, [handleTouchEnd, handleTouchMove, handleTouchStart]);
  var handleMouseDown = useEventCallback(function (event) {
    if (onMouseDown) {
      onMouseDown(event);
    }

    event.preventDefault();
    var finger = trackFinger(event, touchId);

    var _getFingerNewValue4 = getFingerNewValue({
      finger: finger,
      values: values,
      source: valueDerived
    }),
        newValue = _getFingerNewValue4.newValue,
        activeIndex = _getFingerNewValue4.activeIndex;

    focusThumb({
      sliderRef: sliderRef,
      activeIndex: activeIndex,
      setActive: setActive
    });
    setValueState(newValue);

    if (onChange) {
      onChange(event, newValue);
    }

    var doc = ownerDocument(sliderRef.current);
    doc.addEventListener('mousemove', handleTouchMove);
    doc.addEventListener('mouseup', handleTouchEnd);
  });
  var trackOffset = valueToPercent(range ? values[0] : min, min, max);
  var trackLeap = valueToPercent(values[values.length - 1], min, max) - trackOffset;

  var trackStyle = Object(helpers_esm_extends["a" /* default */])({}, axisProps[axis].offset(trackOffset), {}, axisProps[axis].leap(trackLeap));

  return react_default.a.createElement(Component, Object(helpers_esm_extends["a" /* default */])({
    ref: handleRef,
    className: Object(clsx_m["a" /* default */])(classes.root, classes["color".concat(Object(capitalize["a" /* default */])(color))], className, disabled && classes.disabled, marks.length > 0 && marks.some(function (mark) {
      return mark.label;
    }) && classes.marked, track === false && classes.trackFalse, orientation === 'vertical' && classes.vertical, track === 'inverted' && classes.trackInverted),
    onMouseDown: handleMouseDown
  }, other), react_default.a.createElement("span", {
    className: classes.rail
  }), react_default.a.createElement("span", {
    className: classes.track,
    style: trackStyle
  }), react_default.a.createElement("input", {
    value: values.join(','),
    name: name,
    type: "hidden"
  }), marks.map(function (mark) {
    var percent = valueToPercent(mark.value, min, max);
    var style = axisProps[axis].offset(percent);
    var markActive;

    if (track === false) {
      markActive = values.indexOf(mark.value) !== -1;
    } else {
      markActive = track === 'normal' && (range ? mark.value >= values[0] && mark.value <= values[values.length - 1] : mark.value <= values[0]) || track === 'inverted' && (range ? mark.value <= values[0] || mark.value >= values[values.length - 1] : mark.value >= values[0]);
    }

    return react_default.a.createElement(react_default.a.Fragment, {
      key: mark.value
    }, react_default.a.createElement("span", {
      style: style,
      className: Object(clsx_m["a" /* default */])(classes.mark, markActive && classes.markActive)
    }), react_default.a.createElement("span", {
      "aria-hidden": true,
      style: style,
      className: Object(clsx_m["a" /* default */])(classes.markLabel, markActive && classes.markLabelActive)
    }, mark.label));
  }), values.map(function (value, index) {
    var percent = valueToPercent(value, min, max);
    var style = axisProps[axis].offset(percent);
    return react_default.a.createElement(ValueLabelComponent, {
      key: index,
      valueLabelFormat: valueLabelFormat,
      valueLabelDisplay: valueLabelDisplay,
      className: classes.valueLabel,
      value: typeof valueLabelFormat === 'function' ? valueLabelFormat(scale(value), index) : valueLabelFormat,
      index: index,
      open: open === index || active === index || valueLabelDisplay === 'on',
      disabled: disabled
    }, react_default.a.createElement(ThumbComponent, {
      className: Object(clsx_m["a" /* default */])(classes.thumb, classes["thumbColor".concat(Object(capitalize["a" /* default */])(color))], active === index && classes.active, disabled && classes.disabled, focusVisible === index && classes.focusVisible),
      tabIndex: disabled ? null : 0,
      role: "slider",
      style: style,
      "data-index": index,
      "aria-label": getAriaLabel ? getAriaLabel(index) : ariaLabel,
      "aria-labelledby": ariaLabelledby,
      "aria-orientation": orientation,
      "aria-valuemax": scale(max),
      "aria-valuemin": scale(min),
      "aria-valuenow": scale(value),
      "aria-valuetext": getAriaValueText ? getAriaValueText(scale(value), index) : ariaValuetext,
      onKeyDown: handleKeyDown,
      onFocus: handleFocus,
      onBlur: handleBlur,
      onMouseOver: handleMouseOver,
      onMouseLeave: handleMouseLeave
    }));
  }));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_Slider_Slider = (Object(withStyles["a" /* default */])(Slider_styles, {
  name: 'MuiSlider'
})(Slider_Slider));
// CONCATENATED MODULE: ./src/components/QdtSlider/QdtSlider.jsx


/**
 * @name QdtSequencer
 * @param {array} cols - Dimension for the data to cycle through
 * @param {number} delay [5] - Loop through the results in given seconds.
 * @param {bool} selectRow [false] - If we want each cycled row to be selected.
 * @param {number} keyCode [null] - If we want to control the sequencer with a key stroke. Toggles play.
 * @param {bool} navigation [true] - If we want to show / hide the navigation and use only key strokes
 * @description
 * Loop through a dimension and make selections.
*/





var QdtSlider_QdtSlider = function QdtSlider(_ref) {
  var layout = _ref.layout,
      model = _ref.model,
      optionsProp = _ref.options;
  var defaultOptions = {
    variant: 'outlined',
    color: 'primary',
    size: 'small',
    ariaLabel: 'QdtSlider',
    min: 0,
    step: 1
  };
  var options = Object(merge["a" /* default */])(defaultOptions, optionsProp);

  var _useState = Object(react["useState"])(0),
      _useState2 = slicedToArray_default()(_useState, 2),
      value = _useState2[0],
      setValue = _useState2[1];

  var ThumbComponent = function ThumbComponent(props) {
    var aria = props['aria-valuenow'];
    return react_default.a.createElement("div", props, layout.qListObject.qDataPages[0].qMatrix[aria][0].qText);
  };

  ThumbComponent.propTypes = {
    'aria-valuenow': prop_types_default.a.number.isRequired
  };

  var handleChange = function handleChange(event, index) {
    return setValue(index);
  };

  var handleChangeCommitted = function handleChangeCommitted(event, index) {
    return model.selectListObjectValues('/qListObjectDef', [layout.qListObject.qDataPages[0].qMatrix[index][0].qElemNumber], false);
  };

  var max = Object(react["useMemo"])(function () {
    return layout.qListObject.qDataPages[0].qMatrix.length;
  }, [layout.qListObject.qDataPages]);
  Object(react["useEffect"])(function () {
    var selected = 0;
    layout.qListObject.qDataPages[0].qMatrix.forEach(function (val, index) {
      if (val[0].qState === 'S') selected = index;
    });
    setValue(selected);
  }, [layout.qListObject.qDataPages]);
  return react_default.a.createElement("div", {
    style: {
      paddingLeft: 15
    }
  }, react_default.a.createElement(esm_Slider_Slider, {
    ThumbComponent: ThumbComponent,
    color: options.color,
    valueLabelDisplay: "auto",
    "aria-label": options.ariaLabel,
    value: value,
    onChange: handleChange,
    onChangeCommitted: handleChangeCommitted,
    min: options.min,
    step: options.xtep,
    max: max
  }));
};

QdtSlider_QdtSlider.propTypes = {
  layout: prop_types_default.a.object,
  model: prop_types_default.a.object,
  options: prop_types_default.a.object
};
QdtSlider_QdtSlider.defaultProps = {
  layout: null,
  model: null,
  options: {}
};
/* harmony default export */ var components_QdtSlider_QdtSlider = (QdtSlider_QdtSlider);
// EXTERNAL MODULE: ./node_modules/mapbox-gl/dist/mapbox-gl.js
var mapbox_gl = __webpack_require__(32);
var mapbox_gl_default = /*#__PURE__*/__webpack_require__.n(mapbox_gl);

// CONCATENATED MODULE: ./src/styles/index.js
var palette = ['#3399CC', // Light Blue
'#CC6666', // Light Red
'#99CC66', // Light Green
'#275378', // Blue
'#B35A01', // Orange
'#B974FD', // Purple
'#993300', // Dark Red
'#99CCCC', // Very light blue
'#669933', // Green
'#898989', // Gray
'#EDA1A1', '#C6E2A9', '#D4B881', '#137D77', // Dark Green
'#D7C2EC', // Light purple
'#FF5500', // Bright Orange
'#15DFDF', // Terquase
'#93A77E', // Olive Green
'#CB5090', // Dark Pink
'#BFBFBF', // Light Gray
'#d6d6d6', // Lighter Gray
'#eaeaea' // Even Lighter Gray
];
var styles_theme = {
  palette: palette,
  primary: palette[3],
  primaryLight: palette[0],
  secondary: palette[4],
  secondaryLight: palette[1],
  tertiary: palette[8],
  tertiaryLight: palette[2],
  quaternary: {},
  quinary: {},
  senary: {}
};
/* harmony default export */ var src_styles = (styles_theme);
// CONCATENATED MODULE: ./src/components/QdtMapbox/QdtMapBox.jsx




function QdtMapBox_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function QdtMapBox_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { QdtMapBox_ownKeys(Object(source), true).forEach(function (key) { defineProperty_default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { QdtMapBox_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }





 // @TODO REMOVE

var QdtMapBox_QdtMapBox = function QdtMapBox(_ref) {
  var _layout$qHyperCube, _layout$qHyperCube2, _layout$qHyperCube2$q;

  var layout = _ref.layout,
      model = _ref.model,
      optionsProp = _ref.options;
  // https://docs.mapbox.com/mapbox-gl-js/api/#cameraoptions
  var defaultOptions = {
    accessToken: 'pk.eyJ1IjoiYXJ0dXJvbXVub3oiLCJhIjoiY2swODR2NmlhNDYwaDNicDBlcnB6YmR0OSJ9.AgG7MN8DX1aFuG1DfbFr_Q',
    style: 'mapbox://styles/mapbox/streets-v11',
    center: [-74.50, 40],
    zoom: 4,
    pitch: 0,
    bearing: 0,
    circleRadius: 5,
    width: '100%',
    height: '100%',
    // minWidth: 'auto',
    // minHeight: 'auto',
    legend: true,
    // @TODO - Dock options left, top, bottom or none
    tooltip: null,
    createLayers: true,
    extraLayers: null,
    flyTo: null,
    handleMapCallback: null,
    interactive: true
  };
  var options = Object(merge["a" /* default */])(defaultOptions, optionsProp);
  if (optionsProp.center) options.center = optionsProp.center; // Deep merges the array and we have center: (4) [-74.5, 40, -140, 50], which breaks mapbox

  var node = Object(react["useRef"])(null);

  var _useState = Object(react["useState"])(null),
      _useState2 = slicedToArray_default()(_useState, 2),
      map = _useState2[0],
      setMap = _useState2[1];

  var _useState3 = Object(react["useState"])(false),
      _useState4 = slicedToArray_default()(_useState3, 2),
      isLoaded = _useState4[0],
      setIsLoaded = _useState4[1];

  var qData = (_layout$qHyperCube = layout.qHyperCube) === null || _layout$qHyperCube === void 0 ? void 0 : _layout$qHyperCube.qDataPages[0];
  var qMatrix = qData ? qData.qMatrix : [];
  var property = options.createLayers ? (_layout$qHyperCube2 = layout.qHyperCube) === null || _layout$qHyperCube2 === void 0 ? void 0 : (_layout$qHyperCube2$q = _layout$qHyperCube2.qDimensionInfo[3]) === null || _layout$qHyperCube2$q === void 0 ? void 0 : _layout$qHyperCube2$q.qFallbackTitle : null;
  var mapData = [];
  var GeoJSON = null;
  var propertyChildren = null;
  var propertyChildrenWithColors = null;
  var handleSelection = Object(react["useCallback"])(function (value) {
    var toggle = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
    model.selectHyperCubeValues('/qHyperCubeDef', 0, [value], toggle);
  }, [model]);
  var handleClearSelections = Object(react["useCallback"])(function () {
    return model.clearSelections('/qHyperCubeDef');
  }, [model]);

  function buildFeatureSimplified(obj) {
    var featureObj = {
      type: 'Feature',
      properties: defineProperty_default()({
        count: 1,
        userID: obj.id
      }, property, obj[property]),
      geometry: {
        type: 'Point',
        coordinates: [obj.lng, obj.lat]
      }
    }; // if no tooltip callback specified, do not add description property

    if (options.tooltip !== null) {
      featureObj.properties.description = options.tooltip(obj);
    }

    return featureObj;
  }

  var createPropertyChilderFromQData = function createPropertyChilderFromQData() {
    propertyChildren = toConsumableArray_default()(new Set(qMatrix.map(function (array) {
      return array[3].qText;
    })));
    propertyChildrenWithColors = propertyChildren.reduce(function (r, e, i) {
      return r.push(e, src_styles.palette[i]) && r;
    }, []);
  }; // ========================================================
  // Convert qMatrix to GeoJSON
  //
  // Given the qMatrix Data, it converts it to properly formatted GeoJSON


  function buildGeoJSON() {
    var goodGeoJSON = {
      type: 'FeatureCollection',
      features: []
    };
    qMatrix.map(function (array) {
      if (typeof array[1].qNum !== 'number' || typeof array[2].qNum !== 'number') return false;
      var obj = {
        id: Number(array[0].qNum),
        lat: Number(array[1].qNum),
        lng: Number(array[2].qNum)
      };
      obj[property] = array[3].qText;
      var feature = buildFeatureSimplified(obj);
      goodGeoJSON.features.push(feature);
      return obj;
    });
    return goodGeoJSON;
  } // ========================================================
  // Build Layer


  function buildLayer() {
    var match = ['match', ['get', property]].concat(toConsumableArray_default()(propertyChildrenWithColors), ['#FFF']);
    var layer = {
      id: 'dots',
      type: 'circle',
      source: 'hyperCubeData',
      paint: {
        'circle-stroke-width': 0,
        'circle-radius': options.circleRadius,
        'circle-color': match,
        'circle-opacity': 1
      }
    };
    return layer;
  } // ======================================================
  // Build Map Items (Source, Layers)
  //
  // Using the GeoJSON and map object, we create a Layer for the dots and add them to the map
  // This function also sets up the periodic update to cycle through the dots


  var buildMap = function buildMap() {
    map.addSource('hyperCubeData', {
      type: 'geojson',
      data: GeoJSON
    });
    var layer = buildLayer();
    map.addLayer(layer);

    if (options.extraLayers && options.extraLayers.length) {
      options.extraLayers.map(function (_layer) {
        return map.addLayer(_layer);
      });
    } // ==== Tooltip Start ===== //


    if (options.tooltip !== null) {
      // Create a popup, but don't add it to the map yet.
      var popup = new mapbox_gl_default.a.Popup({
        closeButton: false,
        closeOnClick: false,
        className: 'qdt-components-mb-tooltip'
      });
      map.on('mouseenter', 'dots', function (e) {
        // Change the cursor style as a UI indicator.
        map.getCanvas().style.cursor = 'pointer';
        var coordinates = e.features[0].geometry.coordinates.slice();
        var description = e.features[0].properties.description; // Ensure that if the map is zoomed out such that multiple
        // copies of the feature are visible, the popup appears
        // over the copy being pointed to.

        while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
          coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
        } // Populate the popup and set its coordinates
        // based on the feature found.


        popup.setLngLat(coordinates).setHTML(description).addTo(map);
      });
      map.on('mouseleave', 'dots', function () {
        map.getCanvas().style.cursor = '';
        popup.remove();
      });
    } // ==== End Tooltip ======= //

  }; // ==========================================================================
  // Updates the map to display the appropriate layer


  var updateLayers = function updateLayers() {
    var nextChunk = qMatrix.map(function (array) {
      var obj = defineProperty_default()({
        id: Number(array[0].qNum),
        lat: Number(array[1].qNum),
        lng: Number(array[2].qNum)
      }, property, array[3].qText);

      return buildFeatureSimplified(obj);
    });

    if (GeoJSON) {
      GeoJSON = QdtMapBox_objectSpread({}, GeoJSON, {
        features: [].concat(toConsumableArray_default()(GeoJSON.features), toConsumableArray_default()(nextChunk))
      });
      map.getSource('hyperCubeData').setData(GeoJSON);
    } else {
      GeoJSON = buildGeoJSON();
      buildMap();
    }
  };

  var mapInit = function mapInit() {
    mapbox_gl_default.a.accessToken = options.accessToken;

    var _map = new mapbox_gl_default.a.Map(QdtMapBox_objectSpread({
      container: node.current
    }, options));

    setMap(_map);
  };

  Object(react["useEffect"])(function () {
    if (qData && options.createLayers) createPropertyChilderFromQData();
    if (!map) mapInit();

    if (map) {
      // After Map is loaded, update GeoJSON & save Map object before continuing
      map.on('load', function () {
        if (options.createLayers) updateLayers(qData); // Draw the first set of data, in case we load all
        // if (options.handleMapCallback) options.handleMapCallback({ map, mapboxgl, layout });

        setIsLoaded(true);
        mapData = [].concat(toConsumableArray_default()(mapData), toConsumableArray_default()(qMatrix));
      });
    } // eslint-disable-next-line react-hooks/exhaustive-deps

  }, [map]);
  Object(react["useEffect"])(function () {
    if (isLoaded && map && layout && options.handleMapCallback) {
      options.handleMapCallback({
        map: map,
        mapboxgl: mapbox_gl_default.a,
        layout: layout,
        handleSelection: handleSelection,
        handleClearSelections: handleClearSelections
      });
    }
  }, [map, isLoaded, layout]); // eslint-disable-line

  return react_default.a.createElement(react_default.a.Fragment, null, react_default.a.createElement("div", {
    ref: node,
    style: {
      width: options.width,
      height: options.height
    }
  }), react_default.a.createElement("div", {
    style: {
      display: 'block',
      position: 'relative',
      height: 20,
      padding: 2,
      fontSize: 11
    }
  }, options.legend && propertyChildrenWithColors && propertyChildrenWithColors.map(function (value, index) {
    return index % 2 === 0 ? react_default.a.createElement("div", {
      style: {
        display: 'inline-block'
      }
    }, value, ":") : react_default.a.createElement("div", {
      style: {
        width: 10,
        height: 10,
        backgroundColor: value,
        display: 'inline-block',
        marginRight: 10,
        marginLeft: 3
      }
    });
  })));
};

QdtMapBox_QdtMapBox.propTypes = {
  layout: prop_types_default.a.object,
  model: prop_types_default.a.object,
  options: prop_types_default.a.object
};
QdtMapBox_QdtMapBox.defaultProps = {
  layout: null,
  model: null,
  options: {}
};
/* harmony default export */ var QdtMapbox_QdtMapBox = (QdtMapBox_QdtMapBox);
// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/IconButton/IconButton.js










var IconButton_styles = function styles(theme) {
  return {
    /* Styles applied to the root element. */
    root: {
      textAlign: 'center',
      flex: '0 0 auto',
      fontSize: theme.typography.pxToRem(24),
      padding: 12,
      borderRadius: '50%',
      overflow: 'visible',
      // Explicitly set the default value to solve a bug on IE 11.
      color: theme.palette.action.active,
      transition: theme.transitions.create('background-color', {
        duration: theme.transitions.duration.shortest
      }),
      '&:hover': {
        backgroundColor: Object(colorManipulator["b" /* fade */])(theme.palette.action.active, theme.palette.action.hoverOpacity),
        // Reset on touch devices, it doesn't add specificity
        '@media (hover: none)': {
          backgroundColor: 'transparent'
        }
      },
      '&$disabled': {
        backgroundColor: 'transparent',
        color: theme.palette.action.disabled
      }
    },

    /* Styles applied to the root element if `edge="start"`. */
    edgeStart: {
      marginLeft: -12,
      '$sizeSmall&': {
        marginLeft: -3
      }
    },

    /* Styles applied to the root element if `edge="end"`. */
    edgeEnd: {
      marginRight: -12,
      '$sizeSmall&': {
        marginRight: -3
      }
    },

    /* Styles applied to the root element if `color="inherit"`. */
    colorInherit: {
      color: 'inherit'
    },

    /* Styles applied to the root element if `color="primary"`. */
    colorPrimary: {
      color: theme.palette.primary.main,
      '&:hover': {
        backgroundColor: Object(colorManipulator["b" /* fade */])(theme.palette.primary.main, theme.palette.action.hoverOpacity),
        // Reset on touch devices, it doesn't add specificity
        '@media (hover: none)': {
          backgroundColor: 'transparent'
        }
      }
    },

    /* Styles applied to the root element if `color="secondary"`. */
    colorSecondary: {
      color: theme.palette.secondary.main,
      '&:hover': {
        backgroundColor: Object(colorManipulator["b" /* fade */])(theme.palette.secondary.main, theme.palette.action.hoverOpacity),
        // Reset on touch devices, it doesn't add specificity
        '@media (hover: none)': {
          backgroundColor: 'transparent'
        }
      }
    },

    /* Pseudo-class applied to the root element if `disabled={true}`. */
    disabled: {},

    /* Styles applied to the root element if `size="small"`. */
    sizeSmall: {
      padding: 3,
      fontSize: theme.typography.pxToRem(18)
    },

    /* Styles applied to the children container element. */
    label: {
      width: '100%',
      display: 'flex',
      alignItems: 'inherit',
      justifyContent: 'inherit'
    }
  };
};
/**
 * Refer to the [Icons](/components/icons/) section of the documentation
 * regarding the available icon options.
 */

var IconButton_IconButton = react_default.a.forwardRef(function IconButton(props, ref) {
  var _props$edge = props.edge,
      edge = _props$edge === void 0 ? false : _props$edge,
      children = props.children,
      classes = props.classes,
      className = props.className,
      _props$color = props.color,
      color = _props$color === void 0 ? 'default' : _props$color,
      _props$disabled = props.disabled,
      disabled = _props$disabled === void 0 ? false : _props$disabled,
      _props$disableFocusRi = props.disableFocusRipple,
      disableFocusRipple = _props$disableFocusRi === void 0 ? false : _props$disableFocusRi,
      _props$size = props.size,
      size = _props$size === void 0 ? 'medium' : _props$size,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["edge", "children", "classes", "className", "color", "disabled", "disableFocusRipple", "size"]);

  return react_default.a.createElement(esm_ButtonBase_ButtonBase, Object(helpers_esm_extends["a" /* default */])({
    className: Object(clsx_m["a" /* default */])(classes.root, className, color !== 'default' && classes["color".concat(Object(capitalize["a" /* default */])(color))], disabled && classes.disabled, size === "small" && classes["size".concat(Object(capitalize["a" /* default */])(size))], {
      'start': classes.edgeStart,
      'end': classes.edgeEnd
    }[edge]),
    centerRipple: true,
    focusRipple: !disableFocusRipple,
    disabled: disabled,
    ref: ref
  }, other), react_default.a.createElement("span", {
    className: classes.label
  }, children));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_IconButton_IconButton = (Object(withStyles["a" /* default */])(IconButton_styles, {
  name: 'MuiIconButton'
})(IconButton_IconButton));
// CONCATENATED MODULE: ./node_modules/@material-ui/icons/esm/BorderClear.js


/* harmony default export */ var BorderClear = (createSvgIcon_createSvgIcon(react_default.a.createElement("path", {
  d: "M7 5h2V3H7v2zm0 8h2v-2H7v2zm0 8h2v-2H7v2zm4-4h2v-2h-2v2zm0 4h2v-2h-2v2zm-8 0h2v-2H3v2zm0-4h2v-2H3v2zm0-4h2v-2H3v2zm0-4h2V7H3v2zm0-4h2V3H3v2zm8 8h2v-2h-2v2zm8 4h2v-2h-2v2zm0-4h2v-2h-2v2zm0 8h2v-2h-2v2zm0-12h2V7h-2v2zm-8 0h2V7h-2v2zm8-6v2h2V3h-2zm-8 2h2V3h-2v2zm4 16h2v-2h-2v2zm0-8h2v-2h-2v2zm0-8h2V3h-2v2z"
}), 'BorderClear'));
// CONCATENATED MODULE: ./node_modules/@material-ui/icons/esm/Cancel.js


/* harmony default export */ var Cancel = (createSvgIcon_createSvgIcon(react_default.a.createElement("path", {
  d: "M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"
}), 'Cancel'));
// EXTERNAL MODULE: ./node_modules/@material-ui/styles/esm/makeStyles/makeStyles.js + 31 modules
var makeStyles = __webpack_require__(157);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/makeStyles.js




function makeStyles_makeStyles(stylesOrCreator) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  return Object(makeStyles["a" /* default */])(stylesOrCreator, Object(helpers_esm_extends["a" /* default */])({
    defaultTheme: defaultTheme["a" /* default */]
  }, options));
}

/* harmony default export */ var styles_makeStyles = (makeStyles_makeStyles);
// CONCATENATED MODULE: ./src/components/QdtSelections/QdtSelectionsStyles.js

var useStyles = styles_makeStyles(function (theme) {
  return {
    container: {},
    field: {
      fontSize: 12,
      fontWeight: 700,
      textAlign: 'left',
      lineHeight: 1,
      textTransform: 'none',
      paddingTop: 2,
      paddingLeft: 5,
      whiteSpace: 'nowrap',
      overflow: 'hidden',
      textOverflow: 'ellipsis'
    },
    selected: {
      fontSize: 10,
      textTransform: 'none',
      textAlign: 'left',
      paddingLeft: 5,
      paddingBottom: 1,
      whiteSpace: 'nowrap',
      overflow: 'hidden',
      textOverflow: 'ellipsis'
    },
    icon: {
      justifyContent: 'flex-end',
      alignItems: 'center',
      display: 'flex',
      opacity: 0.5,
      paddingRight: 1
    },
    menuList: {
      overflow: 'auto'
    },
    primaryGrid: {
      backgroundColor: theme.palette.grey[300],
      border: '1px solid',
      borderColor: theme.palette.grey[300],
      height: 38
    },
    buttonGroup: {
      backgroundColor: theme.palette.grey[200],
      height: 38
    },
    selectedItemButton: {
      width: 148,
      backgroundColor: theme.palette.grey[100],
      borderTop: 0,
      borderBottom: 0,
      padding: 0,
      borderColor: theme.palette.grey[300],
      justifyContent: 'start'
    },
    linearProgressRoot: {
      backgroundColor: theme.palette.grey[300]
    },
    linearProgressBar: {
      backgroundColor: theme.palette.success.main
    }
  };
});
/* harmony default export */ var QdtSelectionsStyles = (useStyles);
// CONCATENATED MODULE: ./src/components/QdtSelections/QdtPopperContents.jsx



 // import SearchIcon from '@material-ui/icons/Search';




var QdtPopperContents_QdtSelectionsPopper = function QdtSelectionsPopper(_ref) {
  var _layout$qListObject, _layout$qListObject$q;

  var open = _ref.open,
      qField = _ref.qField,
      app = _ref.app;

  var _useSessionObject = hooks_useSessionObject({
    app: app,
    properties: {
      qListObjectDef: {
        qDef: {
          qFieldDefs: [qField],
          qSortCriterias: [{
            qSortByState: 1
          }]
        },
        qInitialDataFetch: [{
          qWidth: 1,
          qHeight: 1000
        }]
      }
    }
  }),
      layout = _useSessionObject.layout,
      model = _useSessionObject.model;

  var handleSelect = Object(react["useCallback"])(function (qElemNumber) {
    model.selectListObjectValues('/qListObjectDef', [qElemNumber], true, true);
  }, [model]); // const handleSearch = useCallback((event) => {
  //   model.searchListObjectFor('/qListObjectDef', event.target.value);
  // }, [model]);

  Object(react["useEffect"])(function () {
    if (open && model) model.beginSelections(['/qListObjectDef']);
    if (!open && model) model.endSelections(true);
  }, [open, model]);
  return react_default.a.createElement(esm_MenuList_MenuList, {
    component: "nav"
  }, layout === null || layout === void 0 ? void 0 : (_layout$qListObject = layout.qListObject) === null || _layout$qListObject === void 0 ? void 0 : (_layout$qListObject$q = _layout$qListObject.qDataPages[0]) === null || _layout$qListObject$q === void 0 ? void 0 : _layout$qListObject$q.qMatrix.map(function (row) {
    return react_default.a.createElement(esm_MenuItem_MenuItem, {
      key: row[0].qElemNumber,
      value: row[0],
      className: classnames_default()({
        selected: row[0].qState === 'S',
        excluded: row[0].qState === 'X'
      }),
      onClick: function onClick() {
        return handleSelect(row[0].qElemNumber);
      },
      button: true
    }, react_default.a.createElement(esm_ListItemText_ListItemText, {
      primary: row[0].qText
    }), row[0].qState === 'S' && react_default.a.createElement(esm_ListItemIcon_ListItemIcon, null, react_default.a.createElement(Check_default.a, null)));
  }));
};

QdtPopperContents_QdtSelectionsPopper.propTypes = {
  open: prop_types_default.a.bool.isRequired,
  app: prop_types_default.a.object.isRequired,
  qField: prop_types_default.a.string
};
QdtPopperContents_QdtSelectionsPopper.defaultProps = {
  qField: null
};
/* harmony default export */ var QdtSelections_QdtPopperContents = (QdtPopperContents_QdtSelectionsPopper);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/extends.js
var helpers_extends = __webpack_require__(70);
var extends_default = /*#__PURE__*/__webpack_require__.n(helpers_extends);

// EXTERNAL MODULE: ./node_modules/popper.js/dist/esm/popper.js
var esm_popper = __webpack_require__(71);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Popper/Popper.js













function flipPlacement(placement, theme) {
  var direction = theme && theme.direction || 'ltr';

  if (direction === 'ltr') {
    return placement;
  }

  switch (placement) {
    case 'bottom-end':
      return 'bottom-start';

    case 'bottom-start':
      return 'bottom-end';

    case 'top-end':
      return 'top-start';

    case 'top-start':
      return 'top-end';

    default:
      return placement;
  }
}

function Popper_getAnchorEl(anchorEl) {
  return typeof anchorEl === 'function' ? anchorEl() : anchorEl;
}

var Popper_useEnhancedEffect = typeof window !== 'undefined' ? react_default.a.useLayoutEffect : react_default.a.useEffect;
var defaultPopperOptions = {};
/**
 * Poppers rely on the 3rd party library [Popper.js](https://github.com/FezVrasta/popper.js) for positioning.
 */

var Popper_Popper = react_default.a.forwardRef(function Popper(props, ref) {
  var anchorEl = props.anchorEl,
      children = props.children,
      container = props.container,
      _props$disablePortal = props.disablePortal,
      disablePortal = _props$disablePortal === void 0 ? false : _props$disablePortal,
      _props$keepMounted = props.keepMounted,
      keepMounted = _props$keepMounted === void 0 ? false : _props$keepMounted,
      modifiers = props.modifiers,
      open = props.open,
      _props$placement = props.placement,
      initialPlacement = _props$placement === void 0 ? 'bottom' : _props$placement,
      _props$popperOptions = props.popperOptions,
      popperOptions = _props$popperOptions === void 0 ? defaultPopperOptions : _props$popperOptions,
      popperRefProp = props.popperRef,
      _props$transition = props.transition,
      transition = _props$transition === void 0 ? false : _props$transition,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["anchorEl", "children", "container", "disablePortal", "keepMounted", "modifiers", "open", "placement", "popperOptions", "popperRef", "transition"]);

  var tooltipRef = react_default.a.useRef(null);
  var ownRef = useForkRef(tooltipRef, ref);
  var popperRef = react_default.a.useRef(null);
  var handlePopperRef = useForkRef(popperRef, popperRefProp);
  var handlePopperRefRef = react_default.a.useRef(handlePopperRef);
  Popper_useEnhancedEffect(function () {
    handlePopperRefRef.current = handlePopperRef;
  }, [handlePopperRef]);
  react_default.a.useImperativeHandle(popperRefProp, function () {
    return popperRef.current;
  }, []);

  var _React$useState = react_default.a.useState(true),
      exited = _React$useState[0],
      setExited = _React$useState[1];

  var theme = Object(useTheme["a" /* default */])();
  var rtlPlacement = flipPlacement(initialPlacement, theme);
  /**
   * placement initialized from prop but can change during lifetime if modifiers.flip.
   * modifiers.flip is essentially a flip for controlled/uncontrolled behavior
   */

  var _React$useState2 = react_default.a.useState(rtlPlacement),
      placement = _React$useState2[0],
      setPlacement = _React$useState2[1];

  react_default.a.useEffect(function () {
    if (popperRef.current) {
      popperRef.current.update();
    }
  });
  var handleOpen = react_default.a.useCallback(function () {
    if (!tooltipRef.current || !anchorEl || !open) {
      return;
    }

    if (popperRef.current) {
      popperRef.current.destroy();
      handlePopperRefRef.current(null);
    }

    var handlePopperUpdate = function handlePopperUpdate(data) {
      setPlacement(data.placement);
    };

    var resolvedAnchorEl = Popper_getAnchorEl(anchorEl);

    if (false) { var box, containerWindow; }

    var popper = new esm_popper["a" /* default */](Popper_getAnchorEl(anchorEl), tooltipRef.current, Object(helpers_esm_extends["a" /* default */])({
      placement: rtlPlacement
    }, popperOptions, {
      modifiers: Object(helpers_esm_extends["a" /* default */])({}, disablePortal ? {} : {
        // It's using scrollParent by default, we can use the viewport when using a portal.
        preventOverflow: {
          boundariesElement: 'window'
        }
      }, {}, modifiers, {}, popperOptions.modifiers),
      // We could have been using a custom modifier like react-popper is doing.
      // But it seems this is the best public API for this use case.
      onCreate: createChainedFunction(handlePopperUpdate, popperOptions.onCreate),
      onUpdate: createChainedFunction(handlePopperUpdate, popperOptions.onUpdate)
    }));
    handlePopperRefRef.current(popper);
  }, [anchorEl, disablePortal, modifiers, open, rtlPlacement, popperOptions]);
  var handleRef = react_default.a.useCallback(function (node) {
    setRef(ownRef, node);
    handleOpen();
  }, [ownRef, handleOpen]);

  var handleEnter = function handleEnter() {
    setExited(false);
  };

  var handleClose = function handleClose() {
    if (!popperRef.current) {
      return;
    }

    popperRef.current.destroy();
    handlePopperRefRef.current(null);
  };

  var handleExited = function handleExited() {
    setExited(true);
    handleClose();
  };

  react_default.a.useEffect(function () {
    // Let's update the popper position.
    handleOpen();
  }, [handleOpen]);
  react_default.a.useEffect(function () {
    return function () {
      handleClose();
    };
  }, []);
  react_default.a.useEffect(function () {
    if (!open && !transition) {
      // Otherwise handleExited will call this.
      handleClose();
    }
  }, [open, transition]);

  if (!keepMounted && !open && (!transition || exited)) {
    return null;
  }

  var childProps = {
    placement: placement
  };

  if (transition) {
    childProps.TransitionProps = {
      in: open,
      onEnter: handleEnter,
      onExited: handleExited
    };
  }

  return react_default.a.createElement(esm_Portal_Portal, {
    disablePortal: disablePortal,
    container: container
  }, react_default.a.createElement("div", Object(helpers_esm_extends["a" /* default */])({
    ref: handleRef,
    role: "tooltip"
  }, other, {
    style: Object(helpers_esm_extends["a" /* default */])({
      // Prevents scroll issue, waiting for Popper.js to add this style once initiated.
      position: 'fixed',
      // Fix Popper.js display issue
      top: 0,
      left: 0
    }, other.style)
  }), typeof children === 'function' ? children(childProps) : children));
});
 false ? undefined : void 0;
/* harmony default export */ var esm_Popper_Popper = (Popper_Popper);
// EXTERNAL MODULE: ./node_modules/@material-ui/core/esm/styles/transitions.js
var transitions = __webpack_require__(31);

// CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/Fade/Fade.js









var Fade_styles = {
  entering: {
    opacity: 1
  },
  entered: {
    opacity: 1
  }
};
var defaultTimeout = {
  enter: transitions["b" /* duration */].enteringScreen,
  exit: transitions["b" /* duration */].leavingScreen
};
/**
 * The Fade transition is used by the [Modal](/components/modal/) component.
 * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.
 */

var Fade_Fade = react_default.a.forwardRef(function Fade(props, ref) {
  var children = props.children,
      inProp = props.in,
      onEnter = props.onEnter,
      onExit = props.onExit,
      style = props.style,
      _props$timeout = props.timeout,
      timeout = _props$timeout === void 0 ? defaultTimeout : _props$timeout,
      other = Object(objectWithoutProperties["a" /* default */])(props, ["children", "in", "onEnter", "onExit", "style", "timeout"]);

  var theme = useTheme_useTheme();
  var handleRef = useForkRef(children.ref, ref);

  var handleEnter = function handleEnter(node, isAppearing) {
    reflow(node); // So the animation always start from the start.

    var transitionProps = getTransitionProps({
      style: style,
      timeout: timeout
    }, {
      mode: 'enter'
    });
    node.style.webkitTransition = theme.transitions.create('opacity', transitionProps);
    node.style.transition = theme.transitions.create('opacity', transitionProps);

    if (onEnter) {
      onEnter(node, isAppearing);
    }
  };

  var handleExit = function handleExit(node) {
    var transitionProps = getTransitionProps({
      style: style,
      timeout: timeout
    }, {
      mode: 'exit'
    });
    node.style.webkitTransition = theme.transitions.create('opacity', transitionProps);
    node.style.transition = theme.transitions.create('opacity', transitionProps);

    if (onExit) {
      onExit(node);
    }
  };

  return react_default.a.createElement(esm_Transition, Object(helpers_esm_extends["a" /* default */])({
    appear: true,
    in: inProp,
    onEnter: handleEnter,
    onExit: handleExit,
    timeout: timeout
  }, other), function (state, childProps) {
    return react_default.a.cloneElement(children, Object(helpers_esm_extends["a" /* default */])({
      style: Object(helpers_esm_extends["a" /* default */])({
        opacity: 0,
        visibility: state === 'exited' && !inProp ? 'hidden' : undefined
      }, Fade_styles[state], {}, style, {}, children.props.style),
      ref: handleRef
    }, childProps));
  });
});
 false ? undefined : void 0;
/* harmony default export */ var esm_Fade_Fade = (Fade_Fade);
// CONCATENATED MODULE: ./src/components/QdtPopper/QdtPopperStyles.js

var QdtPopperStyles_useStyles = styles_makeStyles(function (theme) {
  return {
    popper: {
      zIndex: 9999999
    },
    popperPaper: {
      backgroundColor: theme.palette.common.white,
      marginTop: 10,
      background: '#88b7d5',
      border: "1px solid ".concat(theme.palette.grey[300]),
      minWidth: 200,
      width: 234,
      maxHeight: 332,
      overflow: 'auto',
      '&::after': {
        bottom: 'calc(100% - 11px)',
        left: '50%',
        border: 'solid transparent',
        content: '""',
        height: 0,
        width: 0,
        position: 'absolute',
        pointerEvents: 'none',
        borderColor: 'rgba(136, 183, 213, 0)',
        borderBottomColor: theme.palette.grey[300],
        borderWidth: 10,
        marginLeft: -10
      },
      '&::before': {
        bottom: 'calc(100% - 11px)',
        left: '50%',
        border: 'solid transparent',
        content: '""',
        height: 0,
        width: 0,
        position: 'absolute',
        pointerEvents: 'none',
        borderColor: 'rgba(194, 225, 245, 0)',
        borderBottomColor: theme.palette.grey[300],
        borderWidth: 11,
        marginLeft: -11
      }
    }
  };
});
/* harmony default export */ var QdtPopperStyles = (QdtPopperStyles_useStyles);
// CONCATENATED MODULE: ./src/components/QdtPopper/QdtPopper.jsx






var QdtPopper_QdtPopper = function QdtPopper(_ref) {
  var open = _ref.open,
      anchorEl = _ref.anchorEl,
      contents = _ref.contents,
      onCallback = _ref.onCallback;
  var classes = QdtPopperStyles();
  var popperEl = Object(react["useRef"])(null);

  var handleClick = function handleClick(event) {
    if (popperEl.current && !popperEl.current.contains(event.target)) {
      onCallback();
    }
  };

  Object(react["useEffect"])(function () {
    document.addEventListener('click', handleClick);
    return function () {
      return document.removeEventListener('click', handleClick);
    };
  }, [handleClick]);
  return react_default.a.createElement(esm_Popper_Popper, {
    open: open,
    placement: "bottom",
    anchorEl: anchorEl,
    transition: true,
    ref: popperEl,
    className: classes.popper,
    style: {
      zIndex: 9999999
    },
    modifiers: {
      flip: {
        enabled: true
      },
      preventOverflow: {
        enabled: true,
        boundariesElement: 'scrollParent'
      },
      arrow: {
        enabled: true
      }
    }
  }, function (_ref2) {
    var TransitionProps = _ref2.TransitionProps;
    return react_default.a.createElement(esm_Fade_Fade, extends_default()({}, TransitionProps, {
      timeout: 350
    }), react_default.a.createElement(esm_Paper_Paper, {
      className: classes.popperPaper
    }, contents));
  });
};

QdtPopper_QdtPopper.propTypes = {
  open: prop_types_default.a.bool.isRequired,
  anchorEl: prop_types_default.a.object.isRequired,
  contents: prop_types_default.a.func,
  onCallback: prop_types_default.a.func
};
QdtPopper_QdtPopper.defaultProps = {
  onCallback: null,
  contents: null
};
/* harmony default export */ var components_QdtPopper_QdtPopper = (QdtPopper_QdtPopper);
// CONCATENATED MODULE: ./src/components/QdtSelections/QdtSelections.jsx




/**
 * @name QdtSelections
 * @param {object} layout - Qlik object layout
 * @param {object} options - Options
 * @param {string} options.variant - 'contained' OR 'outlined'
 * @param {string} options.color - 'primary' OR 'secondary'
 * @param {string} options.fontSize - Any font size value, ie '4rem', '10px', 24 etc
*/
 //








var QdtSelections_QdtSelections = function QdtSelections(_ref) {
  var layout = _ref.layout,
      app = _ref.app;
  var elementsRef = Object(react["useRef"])([]);

  var _useState = Object(react["useState"])(null),
      _useState2 = slicedToArray_default()(_useState, 2),
      currentElementIndex = _useState2[0],
      setCurrentElementIndex = _useState2[1];

  var classes = QdtSelectionsStyles();
  var qSelections = layout.qSelectionObject.qSelections; // const handleClick = (event) => {
  //   if (currentElementIndex) {
  //     const outsideClick = !elementsRef.current[currentElementIndex - 1].contains(event.target);
  //     if (outsideClick) setCurrentElementIndex(null);
  //   }
  // };

  var handleCurrentElement = function handleCurrentElement(index) {
    if (currentElementIndex === index + 1) {
      setCurrentElementIndex(null);
    } else {
      setCurrentElementIndex(index + 1);
    }
  };

  var clearFieldSelections =
  /*#__PURE__*/
  function () {
    var _ref2 = asyncToGenerator_default()(
    /*#__PURE__*/
    regenerator_default.a.mark(function _callee(field) {
      var qObject;
      return regenerator_default.a.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              setCurrentElementIndex(null);
              _context.next = 3;
              return app.getField(field);

            case 3:
              qObject = _context.sent;
              qObject.clear();

            case 5:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function clearFieldSelections(_x) {
      return _ref2.apply(this, arguments);
    };
  }();

  var clearAll = function clearAll() {
    setCurrentElementIndex(null);
    app.clearAll();
  }; // useEffect(() => {
  //   document.addEventListener('click', handleClick);
  //   return () => document.removeEventListener('click', handleClick);
  // }, [elementsRef, handleClick]);


  return react_default.a.createElement(react_default.a.Fragment, null, react_default.a.createElement("div", {
    className: "qdt-selections"
  }, react_default.a.createElement(esm_Grid_Grid, {
    container: true,
    direction: "row",
    alignItems: "center",
    className: classes.primaryGrid
  }, react_default.a.createElement(esm_ButtonGroup_ButtonGroup, {
    className: classes.buttonGroup
  }, react_default.a.createElement(esm_IconButton_IconButton, {
    "aria-label": "delete",
    size: "small",
    onClick: clearAll
  }, react_default.a.createElement(BorderClear, {
    fontSize: "inherit"
  }))), react_default.a.createElement(esm_ButtonGroup_ButtonGroup, null, qSelections.length && qSelections.map(function (row, index) {
    return react_default.a.createElement(esm_Button_Button, {
      key: row.field,
      ref: function ref(_ref3) {
        elementsRef.current[index] = _ref3;
      },
      className: classes.selectedItemButton
    }, react_default.a.createElement(esm_Grid_Grid, {
      container: true,
      className: classes.container
    }, react_default.a.createElement(esm_Grid_Grid, {
      item: true,
      xs: 10,
      onClick: function onClick() {
        return handleCurrentElement(index, row.qField);
      }
    }, react_default.a.createElement(esm_Typography_Typography, {
      className: classes.field
    }, row.qField), react_default.a.createElement(esm_Typography_Typography, {
      className: classes.selected
    }, row.qSelectedCount === 1 ? row.qSelected : "".concat(row.qSelectedCount, " of ").concat(row.qTotal))), react_default.a.createElement(esm_Grid_Grid, {
      item: true,
      xs: 2,
      className: classes.icon,
      onClick: function onClick() {
        return clearFieldSelections(row.qField);
      }
    }, react_default.a.createElement(Cancel, {
      fontSize: "small"
    })), react_default.a.createElement(esm_Grid_Grid, {
      item: true,
      xs: 12
    }, react_default.a.createElement(esm_LinearProgress_LinearProgress, {
      variant: "determinate",
      classes: {
        root: classes.linearProgressRoot,
        bar: classes.linearProgressBar
      },
      value: row.qSelectedCount / row.qTotal * 100
    }))));
  })))), react_default.a.createElement("div", null), qSelections && qSelections.map(function (row, index) {
    return (// <QdtSelectionsPopper
      //   key={row.qField}
      //   open={currentElementIndex - 1 === index}
      //   anchorEl={elementsRef.current[currentElementIndex - 1]}
      //   qField={row.qField}
      //   app={app}
      //   setCurrentElementIndex={setCurrentElementIndex}
      // />
      react_default.a.createElement(components_QdtPopper_QdtPopper, {
        key: row.qField,
        open: currentElementIndex - 1 === index,
        anchorEl: elementsRef.current[currentElementIndex - 1],
        contents: react_default.a.createElement(QdtSelections_QdtPopperContents, {
          open: currentElementIndex - 1 === index,
          qField: row.qField,
          app: app
        }),
        onCallback: function onCallback() {
          return setCurrentElementIndex(null);
        }
      })
    );
  }));
};

QdtSelections_QdtSelections.propTypes = {
  layout: prop_types_default.a.object.isRequired,
  app: prop_types_default.a.object.isRequired
};
QdtSelections_QdtSelections.defaultProps = {};
/* harmony default export */ var components_QdtSelections_QdtSelections = (QdtSelections_QdtSelections);
// CONCATENATED MODULE: ./src/components/QdtSearch/QdtPopperContents.jsx






var QdtPopperContents_QdtPopperContents = function QdtPopperContents(_ref) {
  var _layout$qListObject, _layout$qListObject$q;

  var open = _ref.open,
      layout = _ref.layout,
      model = _ref.model,
      options = _ref.options,
      handleClose = _ref.handleClose;
  var handleSelect = Object(react["useCallback"])(function (row) {
    model.selectListObjectValues('/qListObjectDef', [row.qElemNumber], options.multiple, true);
    if (!options.multiple) handleClose(row.qText);
  }, [handleClose, model, options.multiple]); // const handleSearch = useCallback((event) => {
  //   model.searchListObjectFor('/qListObjectDef', event.target.value);
  // }, [model]);

  Object(react["useEffect"])(function () {
    if (open && model) model.beginSelections(['/qListObjectDef']);
    if (!open && model) model.endSelections(true);
  }, [open, model]);
  return react_default.a.createElement(esm_MenuList_MenuList, {
    component: "nav"
  }, layout === null || layout === void 0 ? void 0 : (_layout$qListObject = layout.qListObject) === null || _layout$qListObject === void 0 ? void 0 : (_layout$qListObject$q = _layout$qListObject.qDataPages[0]) === null || _layout$qListObject$q === void 0 ? void 0 : _layout$qListObject$q.qMatrix.map(function (row) {
    return react_default.a.createElement(esm_MenuItem_MenuItem, {
      key: row[0].qElemNumber,
      value: row[0],
      className: classnames_default()({
        selected: row[0].qState === 'S',
        excluded: row[0].qState === 'X'
      }),
      onClick: function onClick() {
        return handleSelect(row[0]);
      },
      button: true
    }, react_default.a.createElement(esm_ListItemText_ListItemText, {
      primary: row[0].qText
    }), row[0].qState === 'S' && react_default.a.createElement(esm_ListItemIcon_ListItemIcon, null, react_default.a.createElement(Check_default.a, null)));
  }));
};

QdtPopperContents_QdtPopperContents.propTypes = {
  open: prop_types_default.a.bool.isRequired,
  layout: prop_types_default.a.object.isRequired,
  model: prop_types_default.a.object.isRequired,
  options: prop_types_default.a.object.isRequired,
  handleClose: prop_types_default.a.func.isRequired
};
QdtPopperContents_QdtPopperContents.defaultProps = {};
/* harmony default export */ var QdtSearch_QdtPopperContents = (QdtPopperContents_QdtPopperContents);
// CONCATENATED MODULE: ./src/components/QdtSearch/QdtSearchStyles.js
var QdtSearchStyles_styles = {
  alignMiddle: {
    display: 'flex',
    alignItems: 'center' // justifyContent: 'center',

  }
};
/* harmony default export */ var QdtSearchStyles = (QdtSearchStyles_styles);
// CONCATENATED MODULE: ./src/components/QdtSearch/QdtSearch.jsx


/**
 * @name QdtSearch
 * @param {object} layout - Qlik object layout
 * @param {string} model - Qlik object model
 * @param {options} object - Options
*/









var QdtSearch_QdtSearch = function QdtSearch(_ref) {
  var layout = _ref.layout,
      model = _ref.model,
      optionsProp = _ref.options;
  var defaultOptions = {
    multiple: false,
    height: 400
  };
  var options = Object(merge["a" /* default */])(defaultOptions, optionsProp);
  var inputRef = Object(react["useRef"])(null);

  var _useState = Object(react["useState"])(null),
      _useState2 = slicedToArray_default()(_useState, 2),
      anchorEl = _useState2[0],
      setAnchorEl = _useState2[1];

  var _useState3 = Object(react["useState"])(''),
      _useState4 = slicedToArray_default()(_useState3, 2),
      inputValue = _useState4[0],
      setInputValue = _useState4[1];

  var open = Boolean(anchorEl);

  var handleSearch = function handleSearch(event) {
    model.searchListObjectFor('/qListObjectDef', event.target.value);
    setInputValue(event.target.value);
  };

  var handleClick = function handleClick(event) {
    return setAnchorEl(anchorEl ? null : event.currentTarget);
  };

  var handleClose = function handleClose(qText) {
    setAnchorEl(null);
    setInputValue(qText);
  };

  return react_default.a.createElement("form", {
    noValidate: true,
    autoComplete: "off",
    style: QdtSearchStyles.alignMiddle
  }, react_default.a.createElement(esm_ListItemIcon_ListItemIcon, null, react_default.a.createElement(Search_default.a, null)), react_default.a.createElement(esm_Input_Input, {
    type: "search",
    onChange: handleSearch,
    value: inputValue,
    onClick: handleClick,
    disableUnderline: true,
    ref: inputRef
  }), react_default.a.createElement(components_QdtPopper_QdtPopper, {
    open: open,
    anchorEl: anchorEl,
    contents: react_default.a.createElement(QdtSearch_QdtPopperContents, {
      open: open,
      layout: layout,
      model: model,
      options: options,
      handleClose: handleClose
    }),
    onCallback: handleClose
  }));
};

QdtSearch_QdtSearch.propTypes = {
  layout: prop_types_default.a.object,
  model: prop_types_default.a.object,
  options: prop_types_default.a.object
};
QdtSearch_QdtSearch.defaultProps = {
  layout: null,
  model: null,
  options: {}
};
/* harmony default export */ var components_QdtSearch_QdtSearch = (QdtSearch_QdtSearch);
// CONCATENATED MODULE: ./src/components/QdtThree/QdtThree.jsx
/**
 * @name QdtThree
*/




var QdtThree_QdtThree = function QdtThree(_ref) {
  var layout = _ref.layout;
  var node = Object(react["useRef"])(null); // const { createGroundPlane } = useThree({ layout, options: { canvas: node.current } });

  Object(react["useEffect"])(function () {
    if (node) {
      var _useThree = hooks_useThree({
        layout: layout,
        options: {
          domElement: node.current
        }
      }),
          createGroundPlane = _useThree.createGroundPlane; // eslint-disable-line


      createGroundPlane();
    }
  }, [layout, node]);
  return react_default.a.createElement("div", {
    ref: node,
    className: "qdt-three",
    style: {
      width: '100%',
      height: '100%',
      minWidth: '100%',
      minHeight: '100%'
    }
  });
};

QdtThree_QdtThree.propTypes = {
  layout: prop_types_default.a.object
};
QdtThree_QdtThree.defaultProps = {
  layout: null
};
/* harmony default export */ var components_QdtThree_QdtThree = (QdtThree_QdtThree);
// CONCATENATED MODULE: ./node_modules/picasso.js/dist/picasso.esm.js
/*
* picasso.js v0.27.1
* Copyright (c) 2019 QlikTech International AB
* Released under the MIT license.
*/


var ARG_LENGTH = {
  a: 7,
  c: 6,
  h: 1,
  l: 2,
  m: 2,
  q: 4,
  s: 4,
  t: 2,
  v: 1,
  z: 0
};
var SEGMENT_PATTERN = /([astvzqmhlc])([^astvzqmhlc]*)/ig;
var NUMBER = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;

function parseValues(args) {
  var numbers = args.match(NUMBER);
  return numbers ? numbers.map(Number) : [];
}
/**
 * parse an svg path data string. Generates an Array
 * of commands where each command is an Array of the
 * form `[command, arg1, arg2, ...]`
 *
 * https://www.w3.org/TR/SVG/paths.html#PathDataGeneralInformation
 * @ignore
 *
 * @param {string} path
 * @returns {array}
 */


function parse(path) {
  var data = [];
  var p = String(path).trim(); // A path data segment (if there is one) must begin with a "moveto" command

  if (p[0] !== 'M' && p[0] !== 'm') {
    return data;
  }

  p.replace(SEGMENT_PATTERN, function (_, command, args) {
    var type = command.toLowerCase();
    var theArgs = parseValues(args);
    var theCommand = command; // overloaded moveTo

    if (type === 'm' && theArgs.length > 2) {
      data.push([theCommand].concat(theArgs.splice(0, 2)));
      type = 'l';
      theCommand = theCommand === 'm' ? 'l' : 'L';
    } // Ignore invalid commands


    if (theArgs.length < ARG_LENGTH[type]) {
      return '';
    }

    data.push([theCommand].concat(theArgs.splice(0, ARG_LENGTH[type]))); // The command letter can be eliminated on subsequent commands if the
    // same command is used multiple times in a row (e.g., you can drop the
    // second "L" in "M 100 200 L 200 100 L -100 -200" and use
    // "M 100 200 L 200 100 -100 -200" instead).

    while (theArgs.length >= ARG_LENGTH[type] && theArgs.length && ARG_LENGTH[type]) {
      data.push([theCommand].concat(theArgs.splice(0, ARG_LENGTH[type])));
    }

    return '';
  });
  return data;
}

var parsePath = parse;

function picasso_esm_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

function picasso_esm_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);
  }
}

function picasso_esm_createClass(Constructor, protoProps, staticProps) {
  if (protoProps) picasso_esm_defineProperties(Constructor.prototype, protoProps);
  if (staticProps) picasso_esm_defineProperties(Constructor, staticProps);
  return Constructor;
}

function picasso_esm_toConsumableArray(arr) {
  return picasso_esm_arrayWithoutHoles(arr) || _iterableToArray(arr) || picasso_esm_nonIterableSpread();
}

function picasso_esm_arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) {
    for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
      arr2[i] = arr[i];
    }

    return arr2;
  }
}

function _iterableToArray(iter) {
  if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}

function picasso_esm_nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance");
}
/**
 * Work around for https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8438884/
 * @ignore
 */


function supportsSvgPathArgument(window) {
  var canvas = window.document.createElement('canvas');
  var g = canvas.getContext('2d');
  var p = new window.Path2D('M0 0 L1 1');
  g.strokeStyle = 'red';
  g.lineWidth = 1;
  g.stroke(p);
  var imgData = g.getImageData(0, 0, 1, 1);
  return imgData.data[0] === 255; // Check if pixel is red
}

function rotatePoint(point, angle) {
  var nx = point.x * Math.cos(angle) - point.y * Math.sin(angle);
  var ny = point.y * Math.cos(angle) + point.x * Math.sin(angle);
  point.x = nx;
  point.y = ny;
}

function translatePoint(point, dx, dy) {
  point.x += dx;
  point.y += dy;
}

function scalePoint(point, s) {
  point.x *= s;
  point.y *= s;
}

function polyFillPath2D(window) {
  if (typeof window === 'undefined' || !window.CanvasRenderingContext2D) {
    return;
  }

  if (window.Path2D && supportsSvgPathArgument(window)) {
    return;
  }
  /**
     * Crates a Path2D polyfill object
     * @constructor
     * @ignore
     * @param {String} path
     */


  var Path2D =
  /*#__PURE__*/
  function () {
    function Path2D(path) {
      picasso_esm_classCallCheck(this, Path2D);

      this.segments = [];

      if (path && path instanceof Path2D) {
        var _this$segments;

        (_this$segments = this.segments).push.apply(_this$segments, picasso_esm_toConsumableArray(path.segments));
      } else if (path) {
        this.segments = parsePath(path);
      }
    }

    picasso_esm_createClass(Path2D, [{
      key: "addPath",
      value: function addPath(path) {
        if (path && path instanceof Path2D) {
          var _this$segments2;

          (_this$segments2 = this.segments).push.apply(_this$segments2, picasso_esm_toConsumableArray(path.segments));
        }
      }
    }, {
      key: "moveTo",
      value: function moveTo(x, y) {
        this.segments.push(['M', x, y]);
      }
    }, {
      key: "lineTo",
      value: function lineTo(x, y) {
        this.segments.push(['L', x, y]);
      }
    }, {
      key: "arc",
      value: function arc(x, y, r, start, end, ccw) {
        this.segments.push(['AC', x, y, r, start, end, !!ccw]);
      }
    }, {
      key: "arcTo",
      value: function arcTo(x1, y1, x2, y2, r) {
        this.segments.push(['AT', x1, y1, x2, y2, r]);
      }
    }, {
      key: "ellipse",
      value: function ellipse(x, y, rx, ry, angle, start, end, ccw) {
        this.segments.push(['E', x, y, rx, ry, angle, start, end, !!ccw]);
      }
    }, {
      key: "closePath",
      value: function closePath() {
        this.segments.push(['Z']);
      }
    }, {
      key: "bezierCurveTo",
      value: function bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) {
        this.segments.push(['C', cp1x, cp1y, cp2x, cp2y, x, y]);
      }
    }, {
      key: "quadraticCurveTo",
      value: function quadraticCurveTo(cpx, cpy, x, y) {
        this.segments.push(['Q', cpx, cpy, x, y]);
      }
    }, {
      key: "rect",
      value: function rect(x, y, width, height) {
        this.segments.push(['R', x, y, width, height]);
      }
    }]);

    return Path2D;
  }();

  var cFill = window.CanvasRenderingContext2D.prototype.fill;
  var cStroke = window.CanvasRenderingContext2D.prototype.stroke;

  function buildPath(canvas, segments) {
    var endAngle;
    var startAngle;
    var largeArcFlag;
    var sweepFlag;
    var endPoint;
    var midPoint;
    var angle;
    var lambda;
    var t1;
    var t2;
    var x;
    var x1;
    var y;
    var y1;
    var r;
    var rx;
    var ry;
    var w;
    var h;
    var pathType;
    var centerPoint;
    var cpx;
    var cpy;
    var qcpx;
    var qcpy;
    var ccw;
    var startPoint = {
      x: 0,
      y: 0
    };
    var currentPoint = {
      x: 0,
      y: 0
    };
    canvas.beginPath();

    for (var i = 0; i < segments.length; ++i) {
      var s = segments[i];
      pathType = s[0]; // Reset control point if command is not cubic

      if (pathType !== 'S' && pathType !== 's' && pathType !== 'C' && pathType !== 'c') {
        cpx = null;
        cpy = null;
      }

      if (pathType !== 'T' && pathType !== 't' && pathType !== 'Q' && pathType !== 'q') {
        qcpx = null;
        qcpy = null;
      }

      switch (pathType) {
        case 'm':
        case 'M':
          if (pathType === 'm') {
            x += s[1];
            y += s[2];
          } else {
            x = s[1];
            y = s[2];
          }

          if (pathType === 'M' || !startPoint) {
            startPoint = {
              x: x,
              y: y
            };
          }

          canvas.moveTo(x, y);
          break;

        case 'l':
          x += s[1];
          y += s[2];
          canvas.lineTo(x, y);
          break;

        case 'L':
          x = s[1];
          y = s[2];
          canvas.lineTo(x, y);
          break;

        case 'H':
          x = s[1];
          canvas.lineTo(x, y);
          break;

        case 'h':
          x += s[1];
          canvas.lineTo(x, y);
          break;

        case 'V':
          y = s[1];
          canvas.lineTo(x, y);
          break;

        case 'v':
          y += s[1];
          canvas.lineTo(x, y);
          break;

        case 'a':
        case 'A':
          if (pathType === 'a') {
            x += s[6];
            y += s[7];
          } else {
            x = s[6];
            y = s[7];
          }

          rx = s[1]; // rx

          ry = s[2]; // ry

          angle = s[3] * Math.PI / 180;
          largeArcFlag = !!s[4];
          sweepFlag = !!s[5];
          endPoint = {
            x: x,
            y: y
          }; // https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes

          midPoint = {
            x: (currentPoint.x - endPoint.x) / 2,
            y: (currentPoint.y - endPoint.y) / 2
          };
          rotatePoint(midPoint, -angle); // radius correction

          lambda = midPoint.x * midPoint.x / (rx * rx) + midPoint.y * midPoint.y / (ry * ry);

          if (lambda > 1) {
            lambda = Math.sqrt(lambda);
            rx *= lambda;
            ry *= lambda;
          }

          centerPoint = {
            x: rx * midPoint.y / ry,
            y: -(ry * midPoint.x) / rx
          };
          t1 = rx * rx * ry * ry;
          t2 = rx * rx * midPoint.y * midPoint.y + ry * ry * midPoint.x * midPoint.x;

          if (sweepFlag !== largeArcFlag) {
            scalePoint(centerPoint, Math.sqrt((t1 - t2) / t2) || 0);
          } else {
            scalePoint(centerPoint, -Math.sqrt((t1 - t2) / t2) || 0);
          }

          startAngle = Math.atan2((midPoint.y - centerPoint.y) / ry, (midPoint.x - centerPoint.x) / rx);
          endAngle = Math.atan2(-(midPoint.y + centerPoint.y) / ry, -(midPoint.x + centerPoint.x) / rx);
          rotatePoint(centerPoint, angle);
          translatePoint(centerPoint, (endPoint.x + currentPoint.x) / 2, (endPoint.y + currentPoint.y) / 2);
          canvas.save();
          canvas.translate(centerPoint.x, centerPoint.y);
          canvas.rotate(angle);
          canvas.scale(rx, ry);
          canvas.arc(0, 0, 1, startAngle, endAngle, !sweepFlag);
          canvas.restore();
          break;

        case 'C':
          cpx = s[3]; // Last control point

          cpy = s[4];
          x = s[5];
          y = s[6];
          canvas.bezierCurveTo(s[1], s[2], cpx, cpy, x, y);
          break;

        case 'c':
          canvas.bezierCurveTo(s[1] + x, s[2] + y, s[3] + x, s[4] + y, s[5] + x, s[6] + y);
          cpx = s[3] + x; // Last control point

          cpy = s[4] + y;
          x += s[5];
          y += s[6];
          break;

        case 'S':
          if (cpx === null || cpx === null) {
            cpx = x;
            cpy = y;
          }

          canvas.bezierCurveTo(2 * x - cpx, 2 * y - cpy, s[1], s[2], s[3], s[4]);
          cpx = s[1]; // last control point

          cpy = s[2];
          x = s[3];
          y = s[4];
          break;

        case 's':
          if (cpx === null || cpx === null) {
            cpx = x;
            cpy = y;
          }

          canvas.bezierCurveTo(2 * x - cpx, 2 * y - cpy, s[1] + x, s[2] + y, s[3] + x, s[4] + y);
          cpx = s[1] + x; // last control point

          cpy = s[2] + y;
          x += s[3];
          y += s[4];
          break;

        case 'Q':
          qcpx = s[1]; // last control point

          qcpy = s[2];
          x = s[3];
          y = s[4];
          canvas.quadraticCurveTo(qcpx, qcpy, x, y);
          break;

        case 'q':
          qcpx = s[1] + x; // last control point

          qcpy = s[2] + y;
          x += s[3];
          y += s[4];
          canvas.quadraticCurveTo(qcpx, qcpy, x, y);
          break;

        case 'T':
          if (qcpx === null || qcpx === null) {
            qcpx = x;
            qcpy = y;
          }

          qcpx = 2 * x - qcpx; // last control point

          qcpy = 2 * y - qcpy;
          x = s[1];
          y = s[2];
          canvas.quadraticCurveTo(qcpx, qcpy, x, y);
          break;

        case 't':
          if (qcpx === null || qcpx === null) {
            qcpx = x;
            qcpy = y;
          }

          qcpx = 2 * x - qcpx; // last control point

          qcpy = 2 * y - qcpy;
          x += s[1];
          y += s[2];
          canvas.quadraticCurveTo(qcpx, qcpy, x, y);
          break;

        case 'z':
        case 'Z':
          x = startPoint.x;
          y = startPoint.y;
          startPoint = undefined;
          canvas.closePath();
          break;

        case 'AC':
          // arc
          x = s[1];
          y = s[2];
          r = s[3];
          startAngle = s[4];
          endAngle = s[5];
          ccw = s[6];
          canvas.arc(x, y, r, startAngle, endAngle, ccw);
          break;

        case 'AT':
          // arcTo
          x1 = s[1];
          y1 = s[2];
          x = s[3];
          y = s[4];
          r = s[5];
          canvas.arcTo(x1, y1, x, y, r);
          break;

        case 'E':
          // ellipse
          x = s[1];
          y = s[2];
          rx = s[3];
          ry = s[4];
          angle = s[5];
          startAngle = s[6];
          endAngle = s[7];
          ccw = s[8];
          canvas.save();
          canvas.translate(x, y);
          canvas.rotate(angle);
          canvas.scale(rx, ry);
          canvas.arc(0, 0, 1, startAngle, endAngle, ccw);
          canvas.restore();
          break;

        case 'R':
          // rect
          x = s[1];
          y = s[2];
          w = s[3];
          h = s[4];
          startPoint = {
            x: x,
            y: y
          };
          canvas.rect(x, y, w, h);
          break;

        default: // throw new Error(`${pathType} is not implemented`); ?

      }

      currentPoint.x = x;
      currentPoint.y = y;
    }
  }

  window.CanvasRenderingContext2D.prototype.fill = function fill() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    var fillRule = 'nonzero';

    if (args.length === 0 || args.length === 1 && typeof args[0] === 'string') {
      cFill.apply(this, args);
      return;
    }

    if (arguments.length === 2) {
      fillRule = args[1];
    }

    var path = args[0];
    buildPath(this, path.segments);
    cFill.call(this, fillRule);
  };

  window.CanvasRenderingContext2D.prototype.stroke = function stroke(path) {
    if (!path) {
      cStroke.call(this);
      return;
    }

    buildPath(this, path.segments);
    cStroke.call(this);
  };

  window.Path2D = Path2D;
}

var path2dPolyfill = polyFillPath2D;

if (typeof window !== 'undefined') {
  path2dPolyfill(window);
}

var src = {
  path2dPolyfill: path2dPolyfill,
  parsePath: parsePath
};
var src_2 = src.parsePath;

var hasOwn = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var picasso_esm_defineProperty = Object.defineProperty;
var gOPD = Object.getOwnPropertyDescriptor;

var picasso_esm_isArray = function isArray(arr) {
	if (typeof Array.isArray === 'function') {
		return Array.isArray(arr);
	}

	return toStr.call(arr) === '[object Array]';
};

var isPlainObject = function isPlainObject(obj) {
	if (!obj || toStr.call(obj) !== '[object Object]') {
		return false;
	}

	var hasOwnConstructor = hasOwn.call(obj, 'constructor');
	var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
	// Not own constructor property must be Object
	if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
		return false;
	}

	// Own properties are enumerated firstly, so to speed up,
	// if last one is own, then all properties are own.
	var key;
	for (key in obj) { /**/ }

	return typeof key === 'undefined' || hasOwn.call(obj, key);
};

// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target
var setProperty = function setProperty(target, options) {
	if (picasso_esm_defineProperty && options.name === '__proto__') {
		picasso_esm_defineProperty(target, options.name, {
			enumerable: true,
			configurable: true,
			value: options.newValue,
			writable: true
		});
	} else {
		target[options.name] = options.newValue;
	}
};

// Return undefined instead of __proto__ if '__proto__' is not an own property
var getProperty = function getProperty(obj, name) {
	if (name === '__proto__') {
		if (!hasOwn.call(obj, name)) {
			return void 0;
		} else if (gOPD) {
			// In early versions of node, obj['__proto__'] is buggy when obj has
			// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
			return gOPD(obj, name).value;
		}
	}

	return obj[name];
};

var extend = function extend() {
	var options, name, src, copy, copyIsArray, clone;
	var target = arguments[0];
	var i = 1;
	var length = arguments.length;
	var deep = false;

	// Handle a deep copy situation
	if (typeof target === 'boolean') {
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		i = 2;
	}
	if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
		target = {};
	}

	for (; i < length; ++i) {
		options = arguments[i];
		// Only deal with non-null/undefined values
		if (options != null) {
			// Extend the base object
			for (name in options) {
				src = getProperty(target, name);
				copy = getProperty(options, name);

				// Prevent never-ending loop
				if (target !== copy) {
					// Recurse if we're merging plain objects or arrays
					if (deep && copy && (isPlainObject(copy) || (copyIsArray = picasso_esm_isArray(copy)))) {
						if (copyIsArray) {
							copyIsArray = false;
							clone = src && picasso_esm_isArray(src) ? src : [];
						} else {
							clone = src && isPlainObject(src) ? src : {};
						}

						// Never move original objects, clone them
						setProperty(target, { name: name, newValue: extend(deep, clone, copy) });

					// Don't bring in undefined values
					} else if (typeof copy !== 'undefined') {
						setProperty(target, { name: name, newValue: copy });
					}
				}
			}
		}
	}

	// Return the modified object
	return target;
};

var about = {
  version: '0.27.1'
};

function _typeof(obj) {
  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof = function (obj) {
      return typeof obj;
    };
  } else {
    _typeof = function (obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
  }

  return _typeof(obj);
}

function _classCallCheck$1(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

function _defineProperties$1(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);
  }
}

function _createClass$1(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties$1(Constructor, staticProps);
  return Constructor;
}

function dist_picasso_esm_defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function picasso_esm_ownKeys(object, enumerableOnly) {
  var keys = Object.keys(object);

  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly) symbols = symbols.filter(function (sym) {
      return Object.getOwnPropertyDescriptor(object, sym).enumerable;
    });
    keys.push.apply(keys, symbols);
  }

  return keys;
}

function _objectSpread2(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i] != null ? arguments[i] : {};

    if (i % 2) {
      picasso_esm_ownKeys(source, true).forEach(function (key) {
        dist_picasso_esm_defineProperty(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      picasso_esm_ownKeys(source).forEach(function (key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
      });
    }
  }

  return target;
}

function picasso_esm_inherits(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }

  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      writable: true,
      configurable: true
    }
  });
  if (superClass) _setPrototypeOf(subClass, 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 picasso_esm_assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return self;
}

function picasso_esm_possibleConstructorReturn(self, call) {
  if (call && (typeof call === "object" || typeof call === "function")) {
    return call;
  }

  return picasso_esm_assertThisInitialized(self);
}

function _superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = _getPrototypeOf(object);
    if (object === null) break;
  }

  return object;
}

function picasso_esm_get(target, property, receiver) {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    picasso_esm_get = Reflect.get;
  } else {
    picasso_esm_get = function _get(target, property, receiver) {
      var base = _superPropBase(target, property);

      if (!base) return;
      var desc = Object.getOwnPropertyDescriptor(base, property);

      if (desc.get) {
        return desc.get.call(receiver);
      }

      return desc.value;
    };
  }

  return picasso_esm_get(target, property, receiver || target);
}

function picasso_esm_slicedToArray(arr, i) {
  return _arrayWithHoles(arr) || picasso_esm_iterableToArrayLimit(arr, i) || _nonIterableRest();
}

function _toConsumableArray$1(arr) {
  return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _nonIterableSpread$1();
}

function _arrayWithoutHoles$1(arr) {
  if (Array.isArray(arr)) {
    for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];

    return arr2;
  }
}

function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}

function _iterableToArray$1(iter) {
  if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}

function picasso_esm_iterableToArrayLimit(arr, i) {
  if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
    return;
  }

  var _arr = [];
  var _n = true;
  var _d = false;
  var _e = undefined;

  try {
    for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);

      if (i && _arr.length === i) break;
    }
  } catch (err) {
    _d = true;
    _e = err;
  } finally {
    try {
      if (!_n && _i["return"] != null) _i["return"]();
    } finally {
      if (_d) throw _e;
    }
  }

  return _arr;
}

function _nonIterableSpread$1() {
  throw new TypeError("Invalid attempt to spread non-iterable instance");
}

function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance");
}

/**
 * Initilize a new dock configuration
 * @private
 * @param {object} [settings] - Settings object
 * @returns {object} A dock configuration instance
 * @example
 * let instance = dockConfig({
 *  dock: 'left',
 *  displayOrder: 2,
 *  prioOrder: 1,
 *  preferredSize: 33,
 *  minimumLayoutMode: 'L',
 *  show: true
 * });
 */
function dockConfig() {
  var settings = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var callbackContext = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

  var _settings$dock = settings.dock,
      _dock = _settings$dock === void 0 ? 'center' : _settings$dock,
      _settings$displayOrde = settings.displayOrder,
      _displayOrder = _settings$displayOrde === void 0 ? 0 : _settings$displayOrde,
      _settings$prioOrder = settings.prioOrder,
      _prioOrder = _settings$prioOrder === void 0 ? 0 : _settings$prioOrder,
      _settings$preferredSi = settings.preferredSize,
      preferredSize = _settings$preferredSi === void 0 ? 0 : _settings$preferredSi,
      _minimumLayoutMode = settings.minimumLayoutMode,
      _settings$show = settings.show,
      _show = _settings$show === void 0 ? true : _settings$show; // avoid empty string dock


  _dock = _dock || 'center';
  /**
   * @private
   */

  return {
    /**
     * Returns the preferred size of a component.
     * The return value of the function can either be a number representing the required size in the dock direction
     * or an object with a `size` and `edgeBleed` property.
     * @param {object} [inner]
     * @param {object} [outer]
     * @returns {number|object} Returns the computed preferred size
     * @example
     * dockConfig.computePreferredSize(() => 150); // Require a size of 150 in the dock direction
     *
     * dockConfig.computePreferredSize(() => ({
     *  size: 150,
     *  edgeBleed: {
     *    left: 50,
     *    right: 50
     *  }
     * })); // Require a size of 150 in the dock direction and a bleed size of 50 to the left and right dock direction
     */
    computePreferredSize: function computePreferredSize(_ref) {
      var inner = _ref.inner,
          outer = _ref.outer;

      if (typeof preferredSize === 'function') {
        return preferredSize({
          inner: inner,
          outer: outer,
          dock: this.dock()
        }, callbackContext);
      }

      return preferredSize;
    },

    /**
     * Set the dock direction, supported values are left | right | top | bottom. Any other value will be interpreted as center dock.
     * @param {string} [val=''] - Dock direction
     * @returns {this} The current context
     * @example
     * dockConfig.dock('left');
     */
    dock: function dock(val) {
      if (typeof val !== 'undefined') {
        _dock = val;
        return this;
      }

      return typeof _dock === 'function' ? _dock(callbackContext) : _dock;
    },

    /**
     * The `displayOrder` property is used by the layout engine to lay out components.
     * Components are interpreted in the ascending order of the `displayOrder` value. The layout engine apply the value in two ways,
     * the first is the order in which components are rendererd. The second is the area components are laid out in
     * when they have a direction, i.e. docked to either top, bottom, left or right.
     *
     * If docked at the same area, the component with a higher `displayOrder` will be rendered
     * on top of the component with a lower `displayOrder`. It can be seen as defining a z-index.
     * A lower `displayOrder` also means that a component will be laid out first in a given direction,
     * i.e. laid out closer to the central area (non-directional area) then a component with a higher `displayOrder`.
     * It can in this case be seen as the x-index or y-index.
     * @param {number} [val=0] - The display order
     * @returns {this|number} The current context or display order
     * @example
     * dockConfig.displayOrder(99);
     */
    displayOrder: function displayOrder(val) {
      if (typeof val !== 'undefined') {
        _displayOrder = val;
        return this;
      }

      return typeof _displayOrder === 'function' ? _displayOrder(callbackContext) : _displayOrder;
    },

    /**
     * The `prioOrder` property is used to define the order in which components are added to the layout engine,
     * this is done before any components are laid out. When there is not enough space to add any more components
     * to a given area, all components not all ready added, are then discarded. The `prioOrder` is interpreted
     * in the ascending order. Such that a lower value is added to the layout engine first.
     * @param {number} [val=0] - The prio order
     * @returns {this|number} The current context or prio order
     * @example
     * dockConfig.prioOrder(-1);
     */
    prioOrder: function prioOrder(val) {
      if (typeof val !== 'undefined') {
        _prioOrder = val;
        return this;
      }

      return typeof _prioOrder === 'function' ? _prioOrder(callbackContext) : _prioOrder;
    },

    /**
     * Ger or set the minimumLayoutMode
     * @param {string|object} [val] - The minimum layout mode
     * @returns {string|object|this} If no parameter is passed the current context is returned, else the current layout mode.
     * @example
     * dockConfig.minimumLayoutMode('L');
     * dockConfig.minimumLayoutMode({ width: 'S', height: 'L' });
     */
    minimumLayoutMode: function minimumLayoutMode(val) {
      if (typeof val !== 'undefined') {
        _minimumLayoutMode = val;
        return this;
      }

      return typeof _minimumLayoutMode === 'function' ? _minimumLayoutMode(callbackContext) : _minimumLayoutMode;
    },

    /**
     * Set the component visibility. If false the component is not added to the layout engine.
     * @param {boolean} [val=true] - Toggle visibility
     * @returns {this|boolean} The current context or show
     */
    show: function show(val) {
      if (typeof val !== 'undefined') {
        _show = val;
        return this;
      }

      return typeof _show === 'function' ? _show(callbackContext) : _show;
    }
  };
}

function roundRect(rect) {
  rect.x = Math.floor(rect.x);
  rect.y = Math.floor(rect.y);
  rect.width = Math.floor(rect.width);
  rect.height = Math.floor(rect.height);
}

function resolveContainerRects(rect, settings) {
  var containerRect = {
    x: 0,
    y: 0,
    width: 0,
    height: 0
  };
  var logicalContainerRect = {
    x: 0,
    y: 0,
    width: 0,
    height: 0
  }; // Check input object for size

  containerRect.width = rect.width || 0;
  containerRect.height = rect.height || 0;

  if (typeof settings.size !== 'undefined') {
    containerRect.width = isNaN(settings.size.width) ? containerRect.width : settings.size.width;
    containerRect.height = isNaN(settings.size.height) ? containerRect.height : settings.size.height;
  }

  if (typeof settings.logicalSize !== 'undefined') {
    logicalContainerRect.width = isNaN(settings.logicalSize.width) ? containerRect.width : settings.logicalSize.width;
    logicalContainerRect.height = isNaN(settings.logicalSize.height) ? containerRect.height : settings.logicalSize.height;
    logicalContainerRect.align = isNaN(settings.logicalSize.align) ? 0.5 : Math.min(Math.max(settings.logicalSize.align, 0), 1);
    logicalContainerRect.preserveAspectRatio = settings.logicalSize.preserveAspectRatio;
  } else {
    logicalContainerRect.width = containerRect.width;
    logicalContainerRect.height = containerRect.height;
    logicalContainerRect.preserveAspectRatio = false;
  }

  roundRect(logicalContainerRect);
  roundRect(containerRect);
  return {
    logicalContainerRect: logicalContainerRect,
    containerRect: containerRect
  };
}
function resolveSettings(s) {
  var settings = {
    center: {
      minWidthRatio: 0.5,
      minHeightRatio: 0.5,
      minWidth: 0,
      minHeight: 0
    }
  };
  extend(true, settings, s);
  settings.center.minWidthRatio = Math.min(Math.max(settings.center.minWidthRatio, 0), 1); // Only accept value between 0-1

  settings.center.minHeightRatio = Math.min(Math.max(settings.center.minHeightRatio, 0), 1); // Only accept value between 0-1

  settings.center.minWidth = Math.max(settings.center.minWidth, 0); // Consider <= 0 to be falsy and fallback to ratio

  settings.center.minHeight = Math.max(settings.center.minHeight, 0); // Consider <= 0 to be falsy and fallback to ratio

  return settings;
}

function isNumber(v) {
  return typeof v === 'number' && !isNaN(v);
}
function notNumber(value) {
  return typeof value !== 'number' || isNaN(value);
}

function getMinMax(points) {
  var num = points.length;
  var xMin = NaN;
  var xMax = NaN;
  var yMin = NaN;
  var yMax = NaN;

  for (var i = 0; i < num; i++) {
    xMin = isNaN(xMin) ? points[i].x : Math.min(xMin, points[i].x);
    xMax = isNaN(xMax) ? points[i].x : Math.max(xMax, points[i].x);
    yMin = isNaN(yMin) ? points[i].y : Math.min(yMin, points[i].y);
    yMax = isNaN(yMax) ? points[i].y : Math.max(yMax, points[i].y);
  }

  return [xMin, yMin, xMax, yMax];
}
/**
 * @ignore
 * @param {oject} line
 * @returns {point[]} Array of points
 */

function lineToPoints(line) {
  var x1 = line.x1 || 0;
  var y1 = line.y1 || 0;
  var x2 = line.x2 || 0;
  var y2 = line.y2 || 0;
  return [{
    x: x1,
    y: y1
  }, {
    x: x2,
    y: y2
  }];
}
/**
 * @ignore
 * @param {oject} rect
 * @returns {point[]} Array of points
 */

function rectToPoints(rect) {
  return [{
    x: rect.x,
    y: rect.y
  }, {
    x: rect.x + rect.width,
    y: rect.y
  }, {
    x: rect.x + rect.width,
    y: rect.y + rect.height
  }, {
    x: rect.x,
    y: rect.y + rect.height
  }];
}
function pointsToRect(points) {
  var _getMinMax = getMinMax(points),
      _getMinMax2 = picasso_esm_slicedToArray(_getMinMax, 4),
      xMin = _getMinMax2[0],
      yMin = _getMinMax2[1],
      xMax = _getMinMax2[2],
      yMax = _getMinMax2[3];

  return {
    x: xMin,
    y: yMin,
    width: xMax - xMin,
    height: yMax - yMin
  };
}
function pointsToCircle(points, r) {
  return {
    cx: points[0].x,
    cy: points[0].y,
    r: r
  };
}
function pointsToLine(points) {
  return {
    x1: points[0].x,
    y1: points[0].y,
    x2: points[1].x,
    y2: points[1].y
  };
}
/**
 * @ignore
 * @param {oject}
 * @returns {string} Type of geometry
 */

function getShapeType(shape) {
  var _ref = shape || {},
      x = _ref.x,
      y = _ref.y,
      width = _ref.width,
      height = _ref.height,
      x1 = _ref.x1,
      x2 = _ref.x2,
      y1 = _ref.y1,
      y2 = _ref.y2,
      cx = _ref.cx,
      cy = _ref.cy,
      r = _ref.r,
      vertices = _ref.vertices;

  if (isNumber(cx) && isNumber(cy) && isNumber(r)) {
    return 'circle';
  }

  if (isNumber(x1) && isNumber(x2) && isNumber(y1) && isNumber(y2)) {
    return 'line';
  }

  if (isNumber(x) && isNumber(y) && isNumber(width) && isNumber(height)) {
    return 'rect';
  }

  if (isNumber(x) && isNumber(y)) {
    return 'point';
  }

  if (Array.isArray(vertices)) {
    return 'polygon';
  }

  return null;
}
function expandRect(size, rect) {
  return {
    x: rect.x - size,
    y: rect.y - size,
    width: rect.width + size,
    height: rect.height + size
  };
}

function createRect(x, y, width, height, margin) {
  return {
    x: isNaN(x) ? 0 : x,
    y: isNaN(x) ? 0 : y,
    width: isNaN(x) ? 0 : width,
    height: isNaN(x) ? 0 : height,
    margin: isNaN(margin) ? 0 : margin
  };
}

function cacheSize(c, reducedRect, layoutRect) {
  if (typeof c.cachedSize === 'undefined') {
    var dock = c.config.dock();
    var size = c.comp.preferredSize({
      inner: reducedRect,
      outer: layoutRect,
      dock: dock
    }); // backwards compatibility

    if (!isNaN(size)) {
      size = {
        width: size,
        height: size
      };
    } else if (size && !isNaN(size.size)) {
      size.width = size.size;
      size.height = size.size;
    }

    var relevantSize;

    if (dock === 'top' || dock === 'bottom') {
      relevantSize = size.height;
    } else if (dock === 'right' || dock === 'left') {
      relevantSize = size.width;
    } else {
      relevantSize = Math.max(size.width, size.height);
    }

    c.cachedSize = Math.ceil(relevantSize);
    c.edgeBleed = size.edgeBleed || 0;
  }

  return c.cachedSize;
}

function validateReduceRect(rect, reducedRect, settings) {
  // Absolute value for width/height should have predence over relative value
  var minReduceWidth = Math.min(settings.center.minWidth, rect.width) || Math.max(rect.width * settings.center.minWidthRatio, 1);
  var minReduceHeight = Math.min(settings.center.minHeight, rect.height) || Math.max(rect.height * settings.center.minHeightRatio, 1);
  return reducedRect.width >= minReduceWidth && reducedRect.height >= minReduceHeight;
}

function reduceDocRect(reducedRect, c) {
  switch (c.config.dock()) {
    case 'top':
      reducedRect.y += c.cachedSize;
      reducedRect.height -= c.cachedSize;
      break;

    case 'bottom':
      reducedRect.height -= c.cachedSize;
      break;

    case 'left':
      reducedRect.x += c.cachedSize;
      reducedRect.width -= c.cachedSize;
      break;

    case 'right':
      reducedRect.width -= c.cachedSize;
      break;

    default:
  }
}

function addEdgeBleed(currentEdgeBleed, c) {
  var edgeBleed = c.edgeBleed;

  if (!edgeBleed) {
    return;
  }

  currentEdgeBleed.left = Math.max(currentEdgeBleed.left, edgeBleed.left || 0);
  currentEdgeBleed.right = Math.max(currentEdgeBleed.right, edgeBleed.right || 0);
  currentEdgeBleed.top = Math.max(currentEdgeBleed.top, edgeBleed.top || 0);
  currentEdgeBleed.bottom = Math.max(currentEdgeBleed.bottom, edgeBleed.bottom || 0);
}

function reduceEdgeBleed(layoutRect, reducedRect, edgeBleed) {
  if (reducedRect.x < edgeBleed.left) {
    reducedRect.width -= edgeBleed.left - reducedRect.x;
    reducedRect.x = edgeBleed.left;
  }

  var reducedRectRightBoundary = layoutRect.width - (reducedRect.x + reducedRect.width);

  if (reducedRectRightBoundary < edgeBleed.right) {
    reducedRect.width -= edgeBleed.right - reducedRectRightBoundary;
  }

  if (reducedRect.y < edgeBleed.top) {
    reducedRect.height -= edgeBleed.top - reducedRect.y;
    reducedRect.y = edgeBleed.top;
  }

  var reducedRectBottomBoundary = layoutRect.height - (reducedRect.y + reducedRect.height);

  if (reducedRectBottomBoundary < edgeBleed.bottom) {
    reducedRect.height -= edgeBleed.bottom - reducedRectBottomBoundary;
  }
}

function reduceSingleLayoutRect(layoutRect, reducedRect, edgeBleed, c, settings) {
  var newReduceRect = extend({}, reducedRect);
  var newEdgeBleed = extend({}, edgeBleed);
  reduceDocRect(newReduceRect, c);
  addEdgeBleed(newEdgeBleed, c);
  reduceEdgeBleed(layoutRect, newReduceRect, newEdgeBleed);
  var isValid = validateReduceRect(layoutRect, newReduceRect, settings);

  if (!isValid) {
    return false;
  }

  reduceDocRect(reducedRect, c);
  addEdgeBleed(edgeBleed, c);
  return true;
}
/**
 * Updates the visible and hidden components based on components that are docked to other components.
 * For example, assume a component called myRect:
 * {
 *  key: 'myRect',
 *  type: 'rect',
 *  dock: 'bottom'
 * }
 * and a component called myLine:
 * {
 *  key: 'myLine',
 *  type: 'line',
 *  dock: '@myRect'
 * }
 * if the layout engine decides to hide myRect, then myLine should be hidden as well.
 * @param {Array} visible - Components to be decided if they should be hidden or not.
 * @param {Array} hidden - Components that are already hidden.
 * @returns {Object} containing the new visible components and additional components to be hidden.
 * @ignore
 */


function filterReferencedDocks(visible, hidden) {
  if (hidden.length === 0) {
    return;
  }

  for (var i = 0; i < visible.length; ++i) {
    var v = visible[i];

    if (v.referencedDocks.length) {
      var isAllHidden = v.referencedDocks.every(function (refDock) {
        return hidden.some(function (h) {
          return h.key === refDock;
        });
      });

      if (isAllHidden) {
        hidden.push(visible.splice(i, 1)[0]);
      }
    }
  }
}

function reduceLayoutRect(_ref) {
  var layoutRect = _ref.layoutRect,
      visible = _ref.visible,
      hidden = _ref.hidden,
      settings = _ref.settings;
  var reducedRect = createRect(layoutRect.x, layoutRect.y, layoutRect.width, layoutRect.height);
  var edgeBleed = {
    left: 0,
    right: 0,
    top: 0,
    bottom: 0
  };
  var sortedComponents = visible.slice();
  sortedComponents.sort(function (a, b) {
    return a.config.prioOrder() - b.config.prioOrder();
  }); // lower prioOrder will have higher prio

  for (var i = 0; i < sortedComponents.length; ++i) {
    var c = sortedComponents[i];
    cacheSize(c, reducedRect, layoutRect);

    if (!reduceSingleLayoutRect(layoutRect, reducedRect, edgeBleed, c, settings)) {
      hidden.push(sortedComponents.splice(i, 1)[0]);
      --i;
    }
  }

  filterReferencedDocks(visible, hidden);
  var filteredUnsortedComps = visible.filter(function (c) {
    return sortedComponents.indexOf(c) !== -1;
  });
  visible.length = 0;
  visible.push.apply(visible, _toConsumableArray$1(filteredUnsortedComps));
  reduceEdgeBleed(layoutRect, reducedRect, edgeBleed);
  return reducedRect;
}

function computeRect(rect) {
  return {
    x: rect.margin.left + rect.x * rect.scaleRatio.x,
    y: rect.margin.top + rect.y * rect.scaleRatio.y,
    width: rect.width * rect.scaleRatio.x,
    height: rect.height * rect.scaleRatio.y
  };
}

function appendScaleRatio(rect, outerRect, layoutRect, containerRect) {
  var scaleRatio = {
    x: containerRect.width / layoutRect.width,
    y: containerRect.height / layoutRect.height
  };
  var margin = {
    left: 0,
    top: 0
  };

  if (layoutRect.preserveAspectRatio) {
    var xLessThenY = scaleRatio.x < scaleRatio.y; // To preserve the aspect ratio, take the smallest ratio and apply in both directions to "meet" the size of the container

    var minRatio = Math.min(scaleRatio.x, scaleRatio.y);
    scaleRatio.x = minRatio;
    scaleRatio.y = minRatio;
    var area = xLessThenY ? 'height' : 'width';
    var spread = (containerRect[area] - layoutRect[area] * scaleRatio.x) * layoutRect.align;
    margin.left = xLessThenY ? 0 : spread;
    margin.top = xLessThenY ? spread : 0;
  }

  rect.scaleRatio = scaleRatio;
  rect.margin = margin;
  outerRect.scaleRatio = scaleRatio;
  outerRect.margin = margin;
  layoutRect.scaleRatio = scaleRatio;
  layoutRect.margin = margin;
}

function boundingBox(rects) {
  var _ref2;

  var points = (_ref2 = []).concat.apply(_ref2, _toConsumableArray$1(rects.map(rectToPoints)));

  return pointsToRect(points);
}

function positionComponents(_ref3) {
  var visible = _ref3.visible,
      layoutRect = _ref3.layoutRect,
      reducedRect = _ref3.reducedRect,
      containerRect = _ref3.containerRect,
      translation = _ref3.translation;
  var vRect = createRect(reducedRect.x, reducedRect.y, reducedRect.width, reducedRect.height);
  var hRect = createRect(reducedRect.x, reducedRect.y, reducedRect.width, reducedRect.height);
  var referencedComponents = {};
  var referenceArray = visible.slice();
  var elementOrder = referenceArray.slice().sort(function (a, b) {
    return a.config.displayOrder() - b.config.displayOrder();
  });
  visible.sort(function (a, b) {
    if (b.referencedDocks.length > 0) {
      return -1;
    }

    if (a.referencedDocks.length > 0) {
      return 1;
    }

    var diff = a.config.displayOrder() - b.config.displayOrder();

    if (diff === 0) {
      return referenceArray.indexOf(a) - referenceArray.indexOf(b);
    }

    return diff;
  }).forEach(function (c) {
    var outerRect = {};
    var rect = {};
    var d = c.config.dock();

    switch (d) {
      case 'top':
        outerRect.height = rect.height = c.cachedSize;
        outerRect.width = layoutRect.width;
        rect.width = vRect.width;
        outerRect.x = layoutRect.x;
        rect.x = vRect.x;
        outerRect.y = rect.y = vRect.y - c.cachedSize;
        vRect.y -= c.cachedSize;
        vRect.height += c.cachedSize;
        break;

      case 'bottom':
        outerRect.x = layoutRect.x;
        rect.x = vRect.x;
        outerRect.y = rect.y = vRect.y + vRect.height;
        outerRect.width = layoutRect.width;
        rect.width = vRect.width;
        outerRect.height = rect.height = c.cachedSize;
        vRect.height += c.cachedSize;
        break;

      case 'left':
        outerRect.x = rect.x = hRect.x - c.cachedSize;
        outerRect.y = layoutRect.y;
        rect.y = hRect.y;
        outerRect.width = rect.width = c.cachedSize;
        outerRect.height = layoutRect.height;
        rect.height = hRect.height;
        hRect.x -= c.cachedSize;
        hRect.width += c.cachedSize;
        break;

      case 'right':
        outerRect.x = rect.x = hRect.x + hRect.width;
        outerRect.y = layoutRect.y;
        rect.y = hRect.y;
        outerRect.width = rect.width = c.cachedSize;
        outerRect.height = layoutRect.height;
        rect.height = hRect.height;
        hRect.width += c.cachedSize;
        break;

      case 'center':
        outerRect.x = rect.x = reducedRect.x;
        outerRect.y = rect.y = reducedRect.y;
        outerRect.width = rect.width = reducedRect.width;
        outerRect.height = rect.height = reducedRect.height;
        break;

      default:
        if (c.referencedDocks.length > 0) {
          var refs = c.referencedDocks.map(function (ref) {
            return referencedComponents[ref];
          }).filter(function (ref) {
            return !!ref;
          });

          if (refs.length > 0) {
            outerRect = boundingBox(refs.map(function (ref) {
              return ref.outerRect;
            }));
            rect = boundingBox(refs.map(function (ref) {
              return ref.r;
            }));
          }
        }

        break;
    }

    if (c.key) {
      referencedComponents[c.key] = {
        // store the size of this component
        r: rect,
        outerRect: outerRect
      };
    }

    appendScaleRatio(rect, outerRect, layoutRect, containerRect);
    rect.edgeBleed = c.edgeBleed;
    rect.computed = computeRect(rect);
    outerRect.edgeBleed = c.edgeBleed;
    outerRect.computed = computeRect(outerRect);
    rect.x += translation.x;
    rect.y += translation.y;
    outerRect.x += translation.x;
    outerRect.y += translation.y;
    c.comp.resize(rect, outerRect);
    c.cachedSize = undefined;
    c.edgeBleed = undefined;
  });
  return visible.map(function (c) {
    return elementOrder.indexOf(c);
  });
}

function checkShowSettings(strategySettings, dockSettings, logicalContainerRect) {
  var layoutModes = strategySettings.layoutModes || {};
  var minimumLayoutMode = dockSettings.minimumLayoutMode();
  var show = dockSettings.show();

  if (show && _typeof(minimumLayoutMode) === 'object') {
    show = layoutModes[minimumLayoutMode.width] && layoutModes[minimumLayoutMode.height] && logicalContainerRect.width >= layoutModes[minimumLayoutMode.width].width && logicalContainerRect.height >= layoutModes[minimumLayoutMode.height].height;
  } else if (show && minimumLayoutMode !== undefined) {
    show = layoutModes[minimumLayoutMode] && logicalContainerRect.width >= layoutModes[minimumLayoutMode].width && logicalContainerRect.height >= layoutModes[minimumLayoutMode].height;
  }

  return show;
}

function validateComponent(component) {
  if (!component.settings && !component.settings) {
    throw new Error('Invalid component settings');
  }

  if (!component.resize || typeof component.resize !== 'function') {
    throw new Error('Component is missing resize function');
  }

  if (!component.dockConfig && !component.preferredSize) {
    throw new Error('Component is missing preferredSize function');
  }
}

function filterComponents(components, settings, rect) {
  var visible = [];
  var hidden = []; // check show settings

  for (var i = 0; i < components.length; ++i) {
    var comp = components[i];
    validateComponent(comp); // backwards compatibility

    var config = void 0;

    if (comp.instance) {
      config = comp.instance.dockConfig();
    } else {
      config = dockConfig(comp.settings.layout);
    }

    var key = comp.settings.key;
    var d = config.dock();
    var referencedDocks = /@/.test(d) ? d.split(',').map(function (s) {
      return s.replace(/^\s*@/, '');
    }) : [];

    if (checkShowSettings(settings, config, rect)) {
      visible.push({
        comp: comp,
        key: key,
        config: config,
        referencedDocks: referencedDocks
      });
    } else {
      hidden.push({
        comp: comp,
        key: key,
        config: config,
        referencedDocks: referencedDocks
      });
    }
  }

  return [visible, hidden];
}
/**
 * @typedef {object} dock-layout-settings
 * @property {object} [logicalSize] - Logical size
 * @property {number} [logicalSize.width] - Width in pixels
 * @property {number} [logicalSize.height] - Height in pixels
 * @property {boolean} [logicalSize.preserveAspectRatio=false] - If true, takes the smallest ratio of width/height between logical and physical size ( physical / logical )
 * @property {number} [logicalSize.align=0.5] - Normalized value between 0-1. Defines how the space around the scaled axis is spread in the container, with 0.5 meaning the spread is equal on both sides. Only applicable if preserveAspectRatio is set to true
 * @property {object} [center] - Define how much space the center dock area requires
 * @property {number} [center.minWidthRatio=0.5] - Value between 0 and 1
 * @property {number} [center.minHeightRatio=0.5] - Value between 0 and 1
 * @property {number} [center.minWidth] - Width in pixels
 * @property {number} [center.minHeight] - Height in pixels
 * @property {object<string, {width: number, height: number}>} [layoutModes] Dictionary with named sizes
 */


function dockLayout(initialSettings) {
  var settings = resolveSettings(initialSettings);
  var docker = {};

  docker.layout = function layout(rect) {
    var components = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

    if (!rect || isNaN(rect.x) || isNaN(rect.y) || isNaN(rect.width) || isNaN(rect.height)) {
      throw new Error('Invalid rect');
    }

    if (!components.length) {
      return {
        visible: [],
        hidden: []
      };
    }

    var _resolveContainerRect = resolveContainerRects(rect, settings),
        logicalContainerRect = _resolveContainerRect.logicalContainerRect,
        containerRect = _resolveContainerRect.containerRect;

    var _filterComponents = filterComponents(components, settings, logicalContainerRect),
        _filterComponents2 = picasso_esm_slicedToArray(_filterComponents, 2),
        visible = _filterComponents2[0],
        hidden = _filterComponents2[1];

    var reducedRect = reduceLayoutRect({
      layoutRect: logicalContainerRect,
      visible: visible,
      hidden: hidden,
      settings: settings
    });
    var translation = {
      x: rect.x,
      y: rect.y
    };
    var order = positionComponents({
      visible: visible,
      layoutRect: logicalContainerRect,
      reducedRect: reducedRect,
      containerRect: containerRect,
      translation: translation
    });
    hidden.forEach(function (c) {
      c.comp.visible = false; // set empty rects on hidden components

      var r = createRect();
      c.comp.resize(r, r);
    });
    return {
      visible: visible.map(function (v) {
        return v.comp;
      }),
      hidden: hidden.map(function (h) {
        return h.comp;
      }),
      order: order
    };
  };

  docker.settings = function settingsFn(s) {
    settings = resolveSettings(s);
  };

  return docker;
}

/* global navigator */
function detectTouchSupport(e) {
  if ('ontouchstart' in e && 'ontouchend' in e || navigator.maxTouchPoints > 1) {
    return true;
  }

  return false;
}
function isTouchEvent(e) {
  return !!e.changedTouches;
}
function isValidTapEvent(e, eventInfo) {
  var isTouch = isTouchEvent(e);
  var ee = isTouch ? e.changedTouches[0] : e;
  var dt = Date.now() - eventInfo.time;
  var dx = isNaN(eventInfo.x) ? 0 : Math.abs(ee.clientX - eventInfo.x);
  var dy = isNaN(eventInfo.y) ? 0 : Math.abs(ee.clientY - eventInfo.y);
  return (e.button === 0 || isTouch) && !eventInfo.multiTouch && dx <= 12 && dy <= 12 && dt <= 300;
}

// import types from './types';

/**
 * @ignore
 * @param {Array<data-source>} dataSources
 * @param {any} { logger }
 * @returns {function}
 */
function datasets(dataSources, _ref) {
  var types = _ref.types,
      logger = _ref.logger;
  var data = {};
  var sets = [];

  if (!Array.isArray(dataSources)) {
    logger.warn('Deprecated: "data-source" configuration"');
    sets.push(dataSources);
  } else {
    sets.push.apply(sets, _toConsumableArray$1(dataSources));
  }

  sets.forEach(function (d, i) {
    var datasetFactory = types(d.type);

    if (datasetFactory) {
      var key = d.key;

      if (typeof d.key === 'undefined') {
        logger.warn("Missing key for dataset. Using index '".concat(i, "' as key."));
        key = i;
      }

      var dataset = datasetFactory({
        key: key,
        data: d.data,
        config: d.config
      });
      data[key] = dataset;
    }
  });
  /**
   * Returns the `dataset` which has `key` as identifier
   * @ignore
   * @param {string} key - The dataset identifier
   * @returns {dataset}
   */

  var fn = function fn(key) {
    if (key) {
      return data[key];
    }

    return data[Object.keys(data)[0]];
  };

  return fn;
}
/**
 * @typedef {object} data-source
 * @property {string} key - Unique identifier for this data source
 * @property {string} type - The dataset type
 * @property {any} data
 */

var pi = Math.PI,
    tau = 2 * pi,
    epsilon = 1e-6,
    tauEpsilon = tau - epsilon;

function Path() {
  this._x0 = this._y0 = // start of current subpath
  this._x1 = this._y1 = null; // end of current subpath
  this._ = "";
}

function picasso_esm_path() {
  return new Path;
}

Path.prototype = picasso_esm_path.prototype = {
  constructor: Path,
  moveTo: function(x, y) {
    this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y);
  },
  closePath: function() {
    if (this._x1 !== null) {
      this._x1 = this._x0, this._y1 = this._y0;
      this._ += "Z";
    }
  },
  lineTo: function(x, y) {
    this._ += "L" + (this._x1 = +x) + "," + (this._y1 = +y);
  },
  quadraticCurveTo: function(x1, y1, x, y) {
    this._ += "Q" + (+x1) + "," + (+y1) + "," + (this._x1 = +x) + "," + (this._y1 = +y);
  },
  bezierCurveTo: function(x1, y1, x2, y2, x, y) {
    this._ += "C" + (+x1) + "," + (+y1) + "," + (+x2) + "," + (+y2) + "," + (this._x1 = +x) + "," + (this._y1 = +y);
  },
  arcTo: function(x1, y1, x2, y2, r) {
    x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;
    var x0 = this._x1,
        y0 = this._y1,
        x21 = x2 - x1,
        y21 = y2 - y1,
        x01 = x0 - x1,
        y01 = y0 - y1,
        l01_2 = x01 * x01 + y01 * y01;

    // Is the radius negative? Error.
    if (r < 0) throw new Error("negative radius: " + r);

    // Is this path empty? Move to (x1,y1).
    if (this._x1 === null) {
      this._ += "M" + (this._x1 = x1) + "," + (this._y1 = y1);
    }

    // Or, is (x1,y1) coincident with (x0,y0)? Do nothing.
    else if (!(l01_2 > epsilon));

    // Or, are (x0,y0), (x1,y1) and (x2,y2) collinear?
    // Equivalently, is (x1,y1) coincident with (x2,y2)?
    // Or, is the radius zero? Line to (x1,y1).
    else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon) || !r) {
      this._ += "L" + (this._x1 = x1) + "," + (this._y1 = y1);
    }

    // Otherwise, draw an arc!
    else {
      var x20 = x2 - x0,
          y20 = y2 - y0,
          l21_2 = x21 * x21 + y21 * y21,
          l20_2 = x20 * x20 + y20 * y20,
          l21 = Math.sqrt(l21_2),
          l01 = Math.sqrt(l01_2),
          l = r * Math.tan((pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2),
          t01 = l / l01,
          t21 = l / l21;

      // If the start tangent is not coincident with (x0,y0), line to.
      if (Math.abs(t01 - 1) > epsilon) {
        this._ += "L" + (x1 + t01 * x01) + "," + (y1 + t01 * y01);
      }

      this._ += "A" + r + "," + r + ",0,0," + (+(y01 * x20 > x01 * y20)) + "," + (this._x1 = x1 + t21 * x21) + "," + (this._y1 = y1 + t21 * y21);
    }
  },
  arc: function(x, y, r, a0, a1, ccw) {
    x = +x, y = +y, r = +r;
    var dx = r * Math.cos(a0),
        dy = r * Math.sin(a0),
        x0 = x + dx,
        y0 = y + dy,
        cw = 1 ^ ccw,
        da = ccw ? a0 - a1 : a1 - a0;

    // Is the radius negative? Error.
    if (r < 0) throw new Error("negative radius: " + r);

    // Is this path empty? Move to (x0,y0).
    if (this._x1 === null) {
      this._ += "M" + x0 + "," + y0;
    }

    // Or, is (x0,y0) not coincident with the previous point? Line to (x0,y0).
    else if (Math.abs(this._x1 - x0) > epsilon || Math.abs(this._y1 - y0) > epsilon) {
      this._ += "L" + x0 + "," + y0;
    }

    // Is this arc empty? We’re done.
    if (!r) return;

    // Does the angle go the wrong way? Flip the direction.
    if (da < 0) da = da % tau + tau;

    // Is this a complete circle? Draw two arcs to complete the circle.
    if (da > tauEpsilon) {
      this._ += "A" + r + "," + r + ",0,1," + cw + "," + (x - dx) + "," + (y - dy) + "A" + r + "," + r + ",0,1," + cw + "," + (this._x1 = x0) + "," + (this._y1 = y0);
    }

    // Is this arc non-empty? Draw an arc!
    else if (da > epsilon) {
      this._ += "A" + r + "," + r + ",0," + (+(da >= pi)) + "," + cw + "," + (this._x1 = x + r * Math.cos(a1)) + "," + (this._y1 = y + r * Math.sin(a1));
    }
  },
  rect: function(x, y, w, h) {
    this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y) + "h" + (+w) + "v" + (+h) + "h" + (-w) + "Z";
  },
  toString: function() {
    return this._;
  }
};

function constant(x) {
  return function constant() {
    return x;
  };
}

var abs = Math.abs;
var atan2 = Math.atan2;
var picasso_esm_cos = Math.cos;
var picasso_esm_max = Math.max;
var picasso_esm_min = Math.min;
var picasso_esm_sin = Math.sin;
var sqrt = Math.sqrt;

var epsilon$1 = 1e-12;
var pi$1 = Math.PI;
var halfPi = pi$1 / 2;
var tau$1 = 2 * pi$1;

function acos(x) {
  return x > 1 ? 0 : x < -1 ? pi$1 : Math.acos(x);
}

function asin(x) {
  return x >= 1 ? halfPi : x <= -1 ? -halfPi : Math.asin(x);
}

function arcInnerRadius(d) {
  return d.innerRadius;
}

function arcOuterRadius(d) {
  return d.outerRadius;
}

function arcStartAngle(d) {
  return d.startAngle;
}

function arcEndAngle(d) {
  return d.endAngle;
}

function arcPadAngle(d) {
  return d && d.padAngle; // Note: optional!
}

function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  var x10 = x1 - x0, y10 = y1 - y0,
      x32 = x3 - x2, y32 = y3 - y2,
      t = y32 * x10 - x32 * y10;
  if (t * t < epsilon$1) return;
  t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t;
  return [x0 + t * x10, y0 + t * y10];
}

// Compute perpendicular offset line of length rc.
// http://mathworld.wolfram.com/Circle-LineIntersection.html
function cornerTangents(x0, y0, x1, y1, r1, rc, cw) {
  var x01 = x0 - x1,
      y01 = y0 - y1,
      lo = (cw ? rc : -rc) / sqrt(x01 * x01 + y01 * y01),
      ox = lo * y01,
      oy = -lo * x01,
      x11 = x0 + ox,
      y11 = y0 + oy,
      x10 = x1 + ox,
      y10 = y1 + oy,
      x00 = (x11 + x10) / 2,
      y00 = (y11 + y10) / 2,
      dx = x10 - x11,
      dy = y10 - y11,
      d2 = dx * dx + dy * dy,
      r = r1 - rc,
      D = x11 * y10 - x10 * y11,
      d = (dy < 0 ? -1 : 1) * sqrt(picasso_esm_max(0, r * r * d2 - D * D)),
      cx0 = (D * dy - dx * d) / d2,
      cy0 = (-D * dx - dy * d) / d2,
      cx1 = (D * dy + dx * d) / d2,
      cy1 = (-D * dx + dy * d) / d2,
      dx0 = cx0 - x00,
      dy0 = cy0 - y00,
      dx1 = cx1 - x00,
      dy1 = cy1 - y00;

  // Pick the closer of the two intersection points.
  // TODO Is there a faster way to determine which intersection to use?
  if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;

  return {
    cx: cx0,
    cy: cy0,
    x01: -ox,
    y01: -oy,
    x11: cx0 * (r1 / r - 1),
    y11: cy0 * (r1 / r - 1)
  };
}

function arc() {
  var innerRadius = arcInnerRadius,
      outerRadius = arcOuterRadius,
      cornerRadius = constant(0),
      padRadius = null,
      startAngle = arcStartAngle,
      endAngle = arcEndAngle,
      padAngle = arcPadAngle,
      context = null;

  function arc() {
    var buffer,
        r,
        r0 = +innerRadius.apply(this, arguments),
        r1 = +outerRadius.apply(this, arguments),
        a0 = startAngle.apply(this, arguments) - halfPi,
        a1 = endAngle.apply(this, arguments) - halfPi,
        da = abs(a1 - a0),
        cw = a1 > a0;

    if (!context) context = buffer = picasso_esm_path();

    // Ensure that the outer radius is always larger than the inner radius.
    if (r1 < r0) r = r1, r1 = r0, r0 = r;

    // Is it a point?
    if (!(r1 > epsilon$1)) context.moveTo(0, 0);

    // Or is it a circle or annulus?
    else if (da > tau$1 - epsilon$1) {
      context.moveTo(r1 * picasso_esm_cos(a0), r1 * picasso_esm_sin(a0));
      context.arc(0, 0, r1, a0, a1, !cw);
      if (r0 > epsilon$1) {
        context.moveTo(r0 * picasso_esm_cos(a1), r0 * picasso_esm_sin(a1));
        context.arc(0, 0, r0, a1, a0, cw);
      }
    }

    // Or is it a circular or annular sector?
    else {
      var a01 = a0,
          a11 = a1,
          a00 = a0,
          a10 = a1,
          da0 = da,
          da1 = da,
          ap = padAngle.apply(this, arguments) / 2,
          rp = (ap > epsilon$1) && (padRadius ? +padRadius.apply(this, arguments) : sqrt(r0 * r0 + r1 * r1)),
          rc = picasso_esm_min(abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments)),
          rc0 = rc,
          rc1 = rc,
          t0,
          t1;

      // Apply padding? Note that since r1 ≥ r0, da1 ≥ da0.
      if (rp > epsilon$1) {
        var p0 = asin(rp / r0 * picasso_esm_sin(ap)),
            p1 = asin(rp / r1 * picasso_esm_sin(ap));
        if ((da0 -= p0 * 2) > epsilon$1) p0 *= (cw ? 1 : -1), a00 += p0, a10 -= p0;
        else da0 = 0, a00 = a10 = (a0 + a1) / 2;
        if ((da1 -= p1 * 2) > epsilon$1) p1 *= (cw ? 1 : -1), a01 += p1, a11 -= p1;
        else da1 = 0, a01 = a11 = (a0 + a1) / 2;
      }

      var x01 = r1 * picasso_esm_cos(a01),
          y01 = r1 * picasso_esm_sin(a01),
          x10 = r0 * picasso_esm_cos(a10),
          y10 = r0 * picasso_esm_sin(a10);

      // Apply rounded corners?
      if (rc > epsilon$1) {
        var x11 = r1 * picasso_esm_cos(a11),
            y11 = r1 * picasso_esm_sin(a11),
            x00 = r0 * picasso_esm_cos(a00),
            y00 = r0 * picasso_esm_sin(a00),
            oc;

        // Restrict the corner radius according to the sector angle.
        if (da < pi$1 && (oc = intersect(x01, y01, x00, y00, x11, y11, x10, y10))) {
          var ax = x01 - oc[0],
              ay = y01 - oc[1],
              bx = x11 - oc[0],
              by = y11 - oc[1],
              kc = 1 / picasso_esm_sin(acos((ax * bx + ay * by) / (sqrt(ax * ax + ay * ay) * sqrt(bx * bx + by * by))) / 2),
              lc = sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
          rc0 = picasso_esm_min(rc, (r0 - lc) / (kc - 1));
          rc1 = picasso_esm_min(rc, (r1 - lc) / (kc + 1));
        }
      }

      // Is the sector collapsed to a line?
      if (!(da1 > epsilon$1)) context.moveTo(x01, y01);

      // Does the sector’s outer ring have rounded corners?
      else if (rc1 > epsilon$1) {
        t0 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw);
        t1 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw);

        context.moveTo(t0.cx + t0.x01, t0.cy + t0.y01);

        // Have the corners merged?
        if (rc1 < rc) context.arc(t0.cx, t0.cy, rc1, atan2(t0.y01, t0.x01), atan2(t1.y01, t1.x01), !cw);

        // Otherwise, draw the two corners and the ring.
        else {
          context.arc(t0.cx, t0.cy, rc1, atan2(t0.y01, t0.x01), atan2(t0.y11, t0.x11), !cw);
          context.arc(0, 0, r1, atan2(t0.cy + t0.y11, t0.cx + t0.x11), atan2(t1.cy + t1.y11, t1.cx + t1.x11), !cw);
          context.arc(t1.cx, t1.cy, rc1, atan2(t1.y11, t1.x11), atan2(t1.y01, t1.x01), !cw);
        }
      }

      // Or is the outer ring just a circular arc?
      else context.moveTo(x01, y01), context.arc(0, 0, r1, a01, a11, !cw);

      // Is there no inner ring, and it’s a circular sector?
      // Or perhaps it’s an annular sector collapsed due to padding?
      if (!(r0 > epsilon$1) || !(da0 > epsilon$1)) context.lineTo(x10, y10);

      // Does the sector’s inner ring (or point) have rounded corners?
      else if (rc0 > epsilon$1) {
        t0 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw);
        t1 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw);

        context.lineTo(t0.cx + t0.x01, t0.cy + t0.y01);

        // Have the corners merged?
        if (rc0 < rc) context.arc(t0.cx, t0.cy, rc0, atan2(t0.y01, t0.x01), atan2(t1.y01, t1.x01), !cw);

        // Otherwise, draw the two corners and the ring.
        else {
          context.arc(t0.cx, t0.cy, rc0, atan2(t0.y01, t0.x01), atan2(t0.y11, t0.x11), !cw);
          context.arc(0, 0, r0, atan2(t0.cy + t0.y11, t0.cx + t0.x11), atan2(t1.cy + t1.y11, t1.cx + t1.x11), cw);
          context.arc(t1.cx, t1.cy, rc0, atan2(t1.y11, t1.x11), atan2(t1.y01, t1.x01), !cw);
        }
      }

      // Or is the inner ring just a circular arc?
      else context.arc(0, 0, r0, a10, a00, cw);
    }

    context.closePath();

    if (buffer) return context = null, buffer + "" || null;
  }

  arc.centroid = function() {
    var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2,
        a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - pi$1 / 2;
    return [picasso_esm_cos(a) * r, picasso_esm_sin(a) * r];
  };

  arc.innerRadius = function(_) {
    return arguments.length ? (innerRadius = typeof _ === "function" ? _ : constant(+_), arc) : innerRadius;
  };

  arc.outerRadius = function(_) {
    return arguments.length ? (outerRadius = typeof _ === "function" ? _ : constant(+_), arc) : outerRadius;
  };

  arc.cornerRadius = function(_) {
    return arguments.length ? (cornerRadius = typeof _ === "function" ? _ : constant(+_), arc) : cornerRadius;
  };

  arc.padRadius = function(_) {
    return arguments.length ? (padRadius = _ == null ? null : typeof _ === "function" ? _ : constant(+_), arc) : padRadius;
  };

  arc.startAngle = function(_) {
    return arguments.length ? (startAngle = typeof _ === "function" ? _ : constant(+_), arc) : startAngle;
  };

  arc.endAngle = function(_) {
    return arguments.length ? (endAngle = typeof _ === "function" ? _ : constant(+_), arc) : endAngle;
  };

  arc.padAngle = function(_) {
    return arguments.length ? (padAngle = typeof _ === "function" ? _ : constant(+_), arc) : padAngle;
  };

  arc.context = function(_) {
    return arguments.length ? ((context = _ == null ? null : _), arc) : context;
  };

  return arc;
}

function picasso_esm_Linear(context) {
  this._context = context;
}

picasso_esm_Linear.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; // proceed
      default: this._context.lineTo(x, y); break;
    }
  }
};

function curveLinear(context) {
  return new picasso_esm_Linear(context);
}

function picasso_esm_x(p) {
  return p[0];
}

function picasso_esm_y(p) {
  return p[1];
}

function line() {
  var x$1 = picasso_esm_x,
      y$1 = picasso_esm_y,
      defined = constant(true),
      context = null,
      curve = curveLinear,
      output = null;

  function line(data) {
    var i,
        n = data.length,
        d,
        defined0 = false,
        buffer;

    if (context == null) output = curve(buffer = picasso_esm_path());

    for (i = 0; i <= n; ++i) {
      if (!(i < n && defined(d = data[i], i, data)) === defined0) {
        if (defined0 = !defined0) output.lineStart();
        else output.lineEnd();
      }
      if (defined0) output.point(+x$1(d, i, data), +y$1(d, i, data));
    }

    if (buffer) return output = null, buffer + "" || null;
  }

  line.x = function(_) {
    return arguments.length ? (x$1 = typeof _ === "function" ? _ : constant(+_), line) : x$1;
  };

  line.y = function(_) {
    return arguments.length ? (y$1 = typeof _ === "function" ? _ : constant(+_), line) : y$1;
  };

  line.defined = function(_) {
    return arguments.length ? (defined = typeof _ === "function" ? _ : constant(!!_), line) : defined;
  };

  line.curve = function(_) {
    return arguments.length ? (curve = _, context != null && (output = curve(context)), line) : curve;
  };

  line.context = function(_) {
    return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), line) : context;
  };

  return line;
}

function picasso_esm_area() {
  var x0 = picasso_esm_x,
      x1 = null,
      y0 = constant(0),
      y1 = picasso_esm_y,
      defined = constant(true),
      context = null,
      curve = curveLinear,
      output = null;

  function area(data) {
    var i,
        j,
        k,
        n = data.length,
        d,
        defined0 = false,
        buffer,
        x0z = new Array(n),
        y0z = new Array(n);

    if (context == null) output = curve(buffer = picasso_esm_path());

    for (i = 0; i <= n; ++i) {
      if (!(i < n && defined(d = data[i], i, data)) === defined0) {
        if (defined0 = !defined0) {
          j = i;
          output.areaStart();
          output.lineStart();
        } else {
          output.lineEnd();
          output.lineStart();
          for (k = i - 1; k >= j; --k) {
            output.point(x0z[k], y0z[k]);
          }
          output.lineEnd();
          output.areaEnd();
        }
      }
      if (defined0) {
        x0z[i] = +x0(d, i, data), y0z[i] = +y0(d, i, data);
        output.point(x1 ? +x1(d, i, data) : x0z[i], y1 ? +y1(d, i, data) : y0z[i]);
      }
    }

    if (buffer) return output = null, buffer + "" || null;
  }

  function arealine() {
    return line().defined(defined).curve(curve).context(context);
  }

  area.x = function(_) {
    return arguments.length ? (x0 = typeof _ === "function" ? _ : constant(+_), x1 = null, area) : x0;
  };

  area.x0 = function(_) {
    return arguments.length ? (x0 = typeof _ === "function" ? _ : constant(+_), area) : x0;
  };

  area.x1 = function(_) {
    return arguments.length ? (x1 = _ == null ? null : typeof _ === "function" ? _ : constant(+_), area) : x1;
  };

  area.y = function(_) {
    return arguments.length ? (y0 = typeof _ === "function" ? _ : constant(+_), y1 = null, area) : y0;
  };

  area.y0 = function(_) {
    return arguments.length ? (y0 = typeof _ === "function" ? _ : constant(+_), area) : y0;
  };

  area.y1 = function(_) {
    return arguments.length ? (y1 = _ == null ? null : typeof _ === "function" ? _ : constant(+_), area) : y1;
  };

  area.lineX0 =
  area.lineY0 = function() {
    return arealine().x(x0).y(y0);
  };

  area.lineY1 = function() {
    return arealine().x(x0).y(y1);
  };

  area.lineX1 = function() {
    return arealine().x(x1).y(y0);
  };

  area.defined = function(_) {
    return arguments.length ? (defined = typeof _ === "function" ? _ : constant(!!_), area) : defined;
  };

  area.curve = function(_) {
    return arguments.length ? (curve = _, context != null && (output = curve(context)), area) : curve;
  };

  area.context = function(_) {
    return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), area) : context;
  };

  return area;
}

function descending(a, b) {
  return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
}

function identity(d) {
  return d;
}

function picasso_esm_pie() {
  var value = identity,
      sortValues = descending,
      sort = null,
      startAngle = constant(0),
      endAngle = constant(tau$1),
      padAngle = constant(0);

  function pie(data) {
    var i,
        n = data.length,
        j,
        k,
        sum = 0,
        index = new Array(n),
        arcs = new Array(n),
        a0 = +startAngle.apply(this, arguments),
        da = Math.min(tau$1, Math.max(-tau$1, endAngle.apply(this, arguments) - a0)),
        a1,
        p = Math.min(Math.abs(da) / n, padAngle.apply(this, arguments)),
        pa = p * (da < 0 ? -1 : 1),
        v;

    for (i = 0; i < n; ++i) {
      if ((v = arcs[index[i] = i] = +value(data[i], i, data)) > 0) {
        sum += v;
      }
    }

    // Optionally sort the arcs by previously-computed values or by data.
    if (sortValues != null) index.sort(function(i, j) { return sortValues(arcs[i], arcs[j]); });
    else if (sort != null) index.sort(function(i, j) { return sort(data[i], data[j]); });

    // Compute the arcs! They are stored in the original data's order.
    for (i = 0, k = sum ? (da - n * pa) / sum : 0; i < n; ++i, a0 = a1) {
      j = index[i], v = arcs[j], a1 = a0 + (v > 0 ? v * k : 0) + pa, arcs[j] = {
        data: data[j],
        index: i,
        value: v,
        startAngle: a0,
        endAngle: a1,
        padAngle: p
      };
    }

    return arcs;
  }

  pie.value = function(_) {
    return arguments.length ? (value = typeof _ === "function" ? _ : constant(+_), pie) : value;
  };

  pie.sortValues = function(_) {
    return arguments.length ? (sortValues = _, sort = null, pie) : sortValues;
  };

  pie.sort = function(_) {
    return arguments.length ? (sort = _, sortValues = null, pie) : sort;
  };

  pie.startAngle = function(_) {
    return arguments.length ? (startAngle = typeof _ === "function" ? _ : constant(+_), pie) : startAngle;
  };

  pie.endAngle = function(_) {
    return arguments.length ? (endAngle = typeof _ === "function" ? _ : constant(+_), pie) : endAngle;
  };

  pie.padAngle = function(_) {
    return arguments.length ? (padAngle = typeof _ === "function" ? _ : constant(+_), pie) : padAngle;
  };

  return pie;
}

var slice = Array.prototype.slice;

function picasso_esm_point(that, x, y) {
  that._context.bezierCurveTo(
    (2 * that._x0 + that._x1) / 3,
    (2 * that._y0 + that._y1) / 3,
    (that._x0 + 2 * that._x1) / 3,
    (that._y0 + 2 * that._y1) / 3,
    (that._x0 + 4 * that._x1 + x) / 6,
    (that._y0 + 4 * that._y1 + y) / 6
  );
}

function Basis(context) {
  this._context = context;
}

Basis.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 =
    this._y0 = this._y1 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 3: picasso_esm_point(this, this._x1, this._y1); // proceed
      case 2: this._context.lineTo(this._x1, this._y1); break;
    }
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; break;
      case 2: this._point = 3; this._context.lineTo((5 * this._x0 + this._x1) / 6, (5 * this._y0 + this._y1) / 6); // proceed
      default: picasso_esm_point(this, x, y); break;
    }
    this._x0 = this._x1, this._x1 = x;
    this._y0 = this._y1, this._y1 = y;
  }
};

function curveBasis(context) {
  return new Basis(context);
}

function point$1(that, x, y) {
  that._context.bezierCurveTo(
    that._x1 + that._k * (that._x2 - that._x0),
    that._y1 + that._k * (that._y2 - that._y0),
    that._x2 + that._k * (that._x1 - x),
    that._y2 + that._k * (that._y1 - y),
    that._x2,
    that._y2
  );
}

function Cardinal(context, tension) {
  this._context = context;
  this._k = (1 - tension) / 6;
}

Cardinal.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._x2 =
    this._y0 = this._y1 = this._y2 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 2: this._context.lineTo(this._x2, this._y2); break;
      case 3: point$1(this, this._x1, this._y1); break;
    }
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; this._x1 = x, this._y1 = y; break;
      case 2: this._point = 3; // proceed
      default: point$1(this, x, y); break;
    }
    this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  }
};

var curveCardinal = (function custom(tension) {

  function cardinal(context) {
    return new Cardinal(context, tension);
  }

  cardinal.tension = function(tension) {
    return custom(+tension);
  };

  return cardinal;
})(0);

function point$2(that, x, y) {
  var x1 = that._x1,
      y1 = that._y1,
      x2 = that._x2,
      y2 = that._y2;

  if (that._l01_a > epsilon$1) {
    var a = 2 * that._l01_2a + 3 * that._l01_a * that._l12_a + that._l12_2a,
        n = 3 * that._l01_a * (that._l01_a + that._l12_a);
    x1 = (x1 * a - that._x0 * that._l12_2a + that._x2 * that._l01_2a) / n;
    y1 = (y1 * a - that._y0 * that._l12_2a + that._y2 * that._l01_2a) / n;
  }

  if (that._l23_a > epsilon$1) {
    var b = 2 * that._l23_2a + 3 * that._l23_a * that._l12_a + that._l12_2a,
        m = 3 * that._l23_a * (that._l23_a + that._l12_a);
    x2 = (x2 * b + that._x1 * that._l23_2a - x * that._l12_2a) / m;
    y2 = (y2 * b + that._y1 * that._l23_2a - y * that._l12_2a) / m;
  }

  that._context.bezierCurveTo(x1, y1, x2, y2, that._x2, that._y2);
}

function CatmullRom(context, alpha) {
  this._context = context;
  this._alpha = alpha;
}

CatmullRom.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._x2 =
    this._y0 = this._y1 = this._y2 = NaN;
    this._l01_a = this._l12_a = this._l23_a =
    this._l01_2a = this._l12_2a = this._l23_2a =
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 2: this._context.lineTo(this._x2, this._y2); break;
      case 3: this.point(this._x2, this._y2); break;
    }
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;

    if (this._point) {
      var x23 = this._x2 - x,
          y23 = this._y2 - y;
      this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
    }

    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; break;
      case 2: this._point = 3; // proceed
      default: point$2(this, x, y); break;
    }

    this._l01_a = this._l12_a, this._l12_a = this._l23_a;
    this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
    this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
  }
};

var curveCatmullRom = (function custom(alpha) {

  function catmullRom(context) {
    return alpha ? new CatmullRom(context, alpha) : new Cardinal(context, 0);
  }

  catmullRom.alpha = function(alpha) {
    return custom(+alpha);
  };

  return catmullRom;
})(0.5);

function picasso_esm_sign(x) {
  return x < 0 ? -1 : 1;
}

// Calculate the slopes of the tangents (Hermite-type interpolation) based on
// the following paper: Steffen, M. 1990. A Simple Method for Monotonic
// Interpolation in One Dimension. Astronomy and Astrophysics, Vol. 239, NO.
// NOV(II), P. 443, 1990.
function slope3(that, x2, y2) {
  var h0 = that._x1 - that._x0,
      h1 = x2 - that._x1,
      s0 = (that._y1 - that._y0) / (h0 || h1 < 0 && -0),
      s1 = (y2 - that._y1) / (h1 || h0 < 0 && -0),
      p = (s0 * h1 + s1 * h0) / (h0 + h1);
  return (picasso_esm_sign(s0) + picasso_esm_sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0;
}

// Calculate a one-sided slope.
function slope2(that, t) {
  var h = that._x1 - that._x0;
  return h ? (3 * (that._y1 - that._y0) / h - t) / 2 : t;
}

// According to https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Representations
// "you can express cubic Hermite interpolation in terms of cubic Bézier curves
// with respect to the four values p0, p0 + m0 / 3, p1 - m1 / 3, p1".
function point$3(that, t0, t1) {
  var x0 = that._x0,
      y0 = that._y0,
      x1 = that._x1,
      y1 = that._y1,
      dx = (x1 - x0) / 3;
  that._context.bezierCurveTo(x0 + dx, y0 + dx * t0, x1 - dx, y1 - dx * t1, x1, y1);
}

function MonotoneX(context) {
  this._context = context;
}

MonotoneX.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 =
    this._y0 = this._y1 =
    this._t0 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 2: this._context.lineTo(this._x1, this._y1); break;
      case 3: point$3(this, this._t0, slope2(this, this._t0)); break;
    }
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x, y) {
    var t1 = NaN;

    x = +x, y = +y;
    if (x === this._x1 && y === this._y1) return; // Ignore coincident points.
    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; break;
      case 2: this._point = 3; point$3(this, slope2(this, t1 = slope3(this, x, y)), t1); break;
      default: point$3(this, this._t0, t1 = slope3(this, x, y)); break;
    }

    this._x0 = this._x1, this._x1 = x;
    this._y0 = this._y1, this._y1 = y;
    this._t0 = t1;
  }
};

function MonotoneY(context) {
  this._context = new ReflectContext(context);
}

(MonotoneY.prototype = Object.create(MonotoneX.prototype)).point = function(x, y) {
  MonotoneX.prototype.point.call(this, y, x);
};

function ReflectContext(context) {
  this._context = context;
}

ReflectContext.prototype = {
  moveTo: function(x, y) { this._context.moveTo(y, x); },
  closePath: function() { this._context.closePath(); },
  lineTo: function(x, y) { this._context.lineTo(y, x); },
  bezierCurveTo: function(x1, y1, x2, y2, x, y) { this._context.bezierCurveTo(y1, x1, y2, x2, y, x); }
};

function monotoneX(context) {
  return new MonotoneX(context);
}

function monotoneY(context) {
  return new MonotoneY(context);
}

function Natural(context) {
  this._context = context;
}

Natural.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x = [];
    this._y = [];
  },
  lineEnd: function() {
    var x = this._x,
        y = this._y,
        n = x.length;

    if (n) {
      this._line ? this._context.lineTo(x[0], y[0]) : this._context.moveTo(x[0], y[0]);
      if (n === 2) {
        this._context.lineTo(x[1], y[1]);
      } else {
        var px = controlPoints(x),
            py = controlPoints(y);
        for (var i0 = 0, i1 = 1; i1 < n; ++i0, ++i1) {
          this._context.bezierCurveTo(px[0][i0], py[0][i0], px[1][i0], py[1][i0], x[i1], y[i1]);
        }
      }
    }

    if (this._line || (this._line !== 0 && n === 1)) this._context.closePath();
    this._line = 1 - this._line;
    this._x = this._y = null;
  },
  point: function(x, y) {
    this._x.push(+x);
    this._y.push(+y);
  }
};

// See https://www.particleincell.com/2012/bezier-splines/ for derivation.
function controlPoints(x) {
  var i,
      n = x.length - 1,
      m,
      a = new Array(n),
      b = new Array(n),
      r = new Array(n);
  a[0] = 0, b[0] = 2, r[0] = x[0] + 2 * x[1];
  for (i = 1; i < n - 1; ++i) a[i] = 1, b[i] = 4, r[i] = 4 * x[i] + 2 * x[i + 1];
  a[n - 1] = 2, b[n - 1] = 7, r[n - 1] = 8 * x[n - 1] + x[n];
  for (i = 1; i < n; ++i) m = a[i] / b[i - 1], b[i] -= m, r[i] -= m * r[i - 1];
  a[n - 1] = r[n - 1] / b[n - 1];
  for (i = n - 2; i >= 0; --i) a[i] = (r[i] - a[i + 1]) / b[i];
  b[n - 1] = (x[n] + a[n - 1]) / 2;
  for (i = 0; i < n - 1; ++i) b[i] = 2 * x[i + 1] - a[i + 1];
  return [a, b];
}

function curveNatural(context) {
  return new Natural(context);
}

function Step(context, t) {
  this._context = context;
  this._t = t;
}

Step.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x = this._y = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    if (0 < this._t && this._t < 1 && this._point === 2) this._context.lineTo(this._x, this._y);
    if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
    if (this._line >= 0) this._t = 1 - this._t, this._line = 1 - this._line;
  },
  point: function(x, y) {
    x = +x, y = +y;
    switch (this._point) {
      case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
      case 1: this._point = 2; // proceed
      default: {
        if (this._t <= 0) {
          this._context.lineTo(this._x, y);
          this._context.lineTo(x, y);
        } else {
          var x1 = this._x * (1 - this._t) + x * this._t;
          this._context.lineTo(x1, this._y);
          this._context.lineTo(x1, y);
        }
        break;
      }
    }
    this._x = x, this._y = y;
  }
};

function curveStep(context) {
  return new Step(context, 0.5);
}

function stepBefore(context) {
  return new Step(context, 0);
}

function stepAfter(context) {
  return new Step(context, 1);
}

function stackOffsetNone(series, order) {
  if (!((n = series.length) > 1)) return;
  for (var i = 1, j, s0, s1 = series[order[0]], n, m = s1.length; i < n; ++i) {
    s0 = s1, s1 = series[order[i]];
    for (j = 0; j < m; ++j) {
      s1[j][1] += s1[j][0] = isNaN(s0[j][1]) ? s0[j][0] : s0[j][1];
    }
  }
}

function stackOrderNone(series) {
  var n = series.length, o = new Array(n);
  while (--n >= 0) o[n] = n;
  return o;
}

function stackValue(d, key) {
  return d[key];
}

function stack() {
  var keys = constant([]),
      order = stackOrderNone,
      offset = stackOffsetNone,
      value = stackValue;

  function stack(data) {
    var kz = keys.apply(this, arguments),
        i,
        m = data.length,
        n = kz.length,
        sz = new Array(n),
        oz;

    for (i = 0; i < n; ++i) {
      for (var ki = kz[i], si = sz[i] = new Array(m), j = 0, sij; j < m; ++j) {
        si[j] = sij = [0, +value(data[j], ki, j, data)];
        sij.data = data[j];
      }
      si.key = ki;
    }

    for (i = 0, oz = order(sz); i < n; ++i) {
      sz[oz[i]].index = i;
    }

    offset(sz, oz);
    return sz;
  }

  stack.keys = function(_) {
    return arguments.length ? (keys = typeof _ === "function" ? _ : constant(slice.call(_)), stack) : keys;
  };

  stack.value = function(_) {
    return arguments.length ? (value = typeof _ === "function" ? _ : constant(+_), stack) : value;
  };

  stack.order = function(_) {
    return arguments.length ? (order = _ == null ? stackOrderNone : typeof _ === "function" ? _ : constant(slice.call(_)), stack) : order;
  };

  stack.offset = function(_) {
    return arguments.length ? (offset = _ == null ? stackOffsetNone : _, stack) : offset;
  };

  return stack;
}

function stackOffsetExpand(series, order) {
  if (!((n = series.length) > 0)) return;
  for (var i, n, j = 0, m = series[0].length, y; j < m; ++j) {
    for (y = i = 0; i < n; ++i) y += series[i][j][1] || 0;
    if (y) for (i = 0; i < n; ++i) series[i][j][1] /= y;
  }
  stackOffsetNone(series, order);
}

function stackOffsetDiverging(series, order) {
  if (!((n = series.length) > 0)) return;
  for (var i, j = 0, d, dy, yp, yn, n, m = series[order[0]].length; j < m; ++j) {
    for (yp = yn = 0, i = 0; i < n; ++i) {
      if ((dy = (d = series[order[i]][j])[1] - d[0]) >= 0) {
        d[0] = yp, d[1] = yp += dy;
      } else if (dy < 0) {
        d[1] = yn, d[0] = yn += dy;
      } else {
        d[0] = yp;
      }
    }
  }
}

function stackOffsetSilhouette(series, order) {
  if (!((n = series.length) > 0)) return;
  for (var j = 0, s0 = series[order[0]], n, m = s0.length; j < m; ++j) {
    for (var i = 0, y = 0; i < n; ++i) y += series[i][j][1] || 0;
    s0[j][1] += s0[j][0] = -y / 2;
  }
  stackOffsetNone(series, order);
}

function stackOffsetWiggle(series, order) {
  if (!((n = series.length) > 0) || !((m = (s0 = series[order[0]]).length) > 0)) return;
  for (var y = 0, j = 1, s0, m, n; j < m; ++j) {
    for (var i = 0, s1 = 0, s2 = 0; i < n; ++i) {
      var si = series[order[i]],
          sij0 = si[j][1] || 0,
          sij1 = si[j - 1][1] || 0,
          s3 = (sij0 - sij1) / 2;
      for (var k = 0; k < i; ++k) {
        var sk = series[order[k]],
            skj0 = sk[j][1] || 0,
            skj1 = sk[j - 1][1] || 0;
        s3 += skj0 - skj1;
      }
      s1 += sij0, s2 += s3 * sij0;
    }
    s0[j - 1][1] += s0[j - 1][0] = y;
    if (s1) y -= s2 / s1;
  }
  s0[j - 1][1] += s0[j - 1][0] = y;
  stackOffsetNone(series, order);
}

function appearance(series) {
  var peaks = series.map(peak);
  return stackOrderNone(series).sort(function(a, b) { return peaks[a] - peaks[b]; });
}

function peak(series) {
  var i = -1, j = 0, n = series.length, vi, vj = -Infinity;
  while (++i < n) if ((vi = +series[i][1]) > vj) vj = vi, j = i;
  return j;
}

function stackOrderAscending(series) {
  var sums = series.map(picasso_esm_sum);
  return stackOrderNone(series).sort(function(a, b) { return sums[a] - sums[b]; });
}

function picasso_esm_sum(series) {
  var s = 0, i = -1, n = series.length, v;
  while (++i < n) if (v = +series[i][1]) s += v;
  return s;
}

function stackOrderInsideOut(series) {
  var n = series.length,
      i,
      j,
      sums = series.map(picasso_esm_sum),
      order = appearance(series),
      top = 0,
      bottom = 0,
      tops = [],
      bottoms = [];

  for (i = 0; i < n; ++i) {
    j = order[i];
    if (top < bottom) {
      top += sums[j];
      tops.push(j);
    } else {
      bottom += sums[j];
      bottoms.push(j);
    }
  }

  return bottoms.reverse().concat(tops);
}

function stackOrderReverse(series) {
  return stackOrderNone(series).reverse();
}

function registryFactory(parentRegistry) {
  var registerName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'unspecified';
  var logger = arguments.length > 2 ? arguments[2] : undefined;
  var defaultValue;
  var reg = {};
  var parent = parentRegistry || {
    get: function get() {
      return undefined;
    },
    has: function has() {
      return false;
    },
    default: function _default() {
      return undefined;
    }
  };
  defaultValue = parent.default();
  /**
   * @private
   * @param {string} key
   * @param {any} value
   * @throws {TypeError} Key must be a non-empty string
   * @returns {boolean} False if the given key already exists, true otherwise
   * @example
   * var r = registry();
   * r.add( "marker", function(args) {
   *   return new markers[args.type](args);
   * });
   *
   */

  function add(key, value) {
    if (!key || typeof key !== 'string') {
      throw new TypeError('Invalid argument: key must be a non-empty string');
    }

    if (key in reg) {
      return false;
    }

    reg[key] = value;
    return true;
  }

  function get(key) {
    return reg[key] || parent.get(key);
  }

  function has(key) {
    return !!reg[key] || parent.has(key);
  }

  function remove(key) {
    var d = reg[key];
    delete reg[key];
    return d;
  }

  function getKeys() {
    return Object.keys(reg);
  }

  function getValues() {
    return Object.keys(reg).map(function (key) {
      return reg[key];
    });
  }

  function deflt(d) {
    if (typeof d !== 'undefined') {
      defaultValue = d;
    }

    return defaultValue;
  }
  /**
   * @alias registry
   * @interface
   * @param {string} key
   * @param {any} value
   */


  function registry(key, value) {
    if (typeof value !== 'undefined') {
      return add(key, value);
    }

    var ret = get(key);

    if (logger && typeof ret === 'undefined') {
      logger.warn("".concat(key, " does not exist in ").concat(registerName, " registry"));
    }

    return ret || get(defaultValue);
  }

  registry.add = add;
  registry.get = get;
  registry.has = has;
  registry.remove = remove;
  registry.getKeys = getKeys;
  registry.getValues = getValues;
  registry.default = deflt;
  registry.register = add; // deprecated

  return registry;
}

// Computes the decimal coefficient and exponent of the specified number x with
// significant digits p, where x is positive and p is in [1, 21] or undefined.
// For example, formatDecimal(1.23) returns ["123", 0].
function formatDecimal(x, p) {
  if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; // NaN, ±Infinity
  var i, coefficient = x.slice(0, i);

  // The string returned by toExponential either has the form \d\.\d+e[-+]\d+
  // (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3).
  return [
    coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
    +x.slice(i + 1)
  ];
}

function picasso_esm_exponent(x) {
  return x = formatDecimal(Math.abs(x)), x ? x[1] : NaN;
}

function formatGroup(grouping, thousands) {
  return function(value, width) {
    var i = value.length,
        t = [],
        j = 0,
        g = grouping[0],
        length = 0;

    while (i > 0 && g > 0) {
      if (length + g + 1 > width) g = Math.max(1, width - length);
      t.push(value.substring(i -= g, i + g));
      if ((length += g + 1) > width) break;
      g = grouping[j = (j + 1) % grouping.length];
    }

    return t.reverse().join(thousands);
  };
}

function formatNumerals(numerals) {
  return function(value) {
    return value.replace(/[0-9]/g, function(i) {
      return numerals[+i];
    });
  };
}

// [[fill]align][sign][symbol][0][width][,][.precision][~][type]
var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;

function formatSpecifier(specifier) {
  if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier);
  var match;
  return new FormatSpecifier({
    fill: match[1],
    align: match[2],
    sign: match[3],
    symbol: match[4],
    zero: match[5],
    width: match[6],
    comma: match[7],
    precision: match[8] && match[8].slice(1),
    trim: match[9],
    type: match[10]
  });
}

formatSpecifier.prototype = FormatSpecifier.prototype; // instanceof

function FormatSpecifier(specifier) {
  this.fill = specifier.fill === undefined ? " " : specifier.fill + "";
  this.align = specifier.align === undefined ? ">" : specifier.align + "";
  this.sign = specifier.sign === undefined ? "-" : specifier.sign + "";
  this.symbol = specifier.symbol === undefined ? "" : specifier.symbol + "";
  this.zero = !!specifier.zero;
  this.width = specifier.width === undefined ? undefined : +specifier.width;
  this.comma = !!specifier.comma;
  this.precision = specifier.precision === undefined ? undefined : +specifier.precision;
  this.trim = !!specifier.trim;
  this.type = specifier.type === undefined ? "" : specifier.type + "";
}

FormatSpecifier.prototype.toString = function() {
  return this.fill
      + this.align
      + this.sign
      + this.symbol
      + (this.zero ? "0" : "")
      + (this.width === undefined ? "" : Math.max(1, this.width | 0))
      + (this.comma ? "," : "")
      + (this.precision === undefined ? "" : "." + Math.max(0, this.precision | 0))
      + (this.trim ? "~" : "")
      + this.type;
};

// Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.
function formatTrim(s) {
  out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
    switch (s[i]) {
      case ".": i0 = i1 = i; break;
      case "0": if (i0 === 0) i0 = i; i1 = i; break;
      default: if (i0 > 0) { if (!+s[i]) break out; i0 = 0; } break;
    }
  }
  return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
}

var prefixExponent;

function formatPrefixAuto(x, p) {
  var d = formatDecimal(x, p);
  if (!d) return x + "";
  var coefficient = d[0],
      exponent = d[1],
      i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,
      n = coefficient.length;
  return i === n ? coefficient
      : i > n ? coefficient + new Array(i - n + 1).join("0")
      : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i)
      : "0." + new Array(1 - i).join("0") + formatDecimal(x, Math.max(0, p + i - 1))[0]; // less than 1y!
}

function formatRounded(x, p) {
  var d = formatDecimal(x, p);
  if (!d) return x + "";
  var coefficient = d[0],
      exponent = d[1];
  return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient
      : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1)
      : coefficient + new Array(exponent - coefficient.length + 2).join("0");
}

var formatTypes = {
  "%": function(x, p) { return (x * 100).toFixed(p); },
  "b": function(x) { return Math.round(x).toString(2); },
  "c": function(x) { return x + ""; },
  "d": function(x) { return Math.round(x).toString(10); },
  "e": function(x, p) { return x.toExponential(p); },
  "f": function(x, p) { return x.toFixed(p); },
  "g": function(x, p) { return x.toPrecision(p); },
  "o": function(x) { return Math.round(x).toString(8); },
  "p": function(x, p) { return formatRounded(x * 100, p); },
  "r": formatRounded,
  "s": formatPrefixAuto,
  "X": function(x) { return Math.round(x).toString(16).toUpperCase(); },
  "x": function(x) { return Math.round(x).toString(16); }
};

function identity$1(x) {
  return x;
}

var picasso_esm_map = Array.prototype.map,
    prefixes = ["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];

function formatLocale(locale) {
  var group = locale.grouping === undefined || locale.thousands === undefined ? identity$1 : formatGroup(picasso_esm_map.call(locale.grouping, Number), locale.thousands + ""),
      currencyPrefix = locale.currency === undefined ? "" : locale.currency[0] + "",
      currencySuffix = locale.currency === undefined ? "" : locale.currency[1] + "",
      decimal = locale.decimal === undefined ? "." : locale.decimal + "",
      numerals = locale.numerals === undefined ? identity$1 : formatNumerals(picasso_esm_map.call(locale.numerals, String)),
      percent = locale.percent === undefined ? "%" : locale.percent + "",
      minus = locale.minus === undefined ? "-" : locale.minus + "",
      nan = locale.nan === undefined ? "NaN" : locale.nan + "";

  function newFormat(specifier) {
    specifier = formatSpecifier(specifier);

    var fill = specifier.fill,
        align = specifier.align,
        sign = specifier.sign,
        symbol = specifier.symbol,
        zero = specifier.zero,
        width = specifier.width,
        comma = specifier.comma,
        precision = specifier.precision,
        trim = specifier.trim,
        type = specifier.type;

    // The "n" type is an alias for ",g".
    if (type === "n") comma = true, type = "g";

    // The "" type, and any invalid type, is an alias for ".12~g".
    else if (!formatTypes[type]) precision === undefined && (precision = 12), trim = true, type = "g";

    // If zero fill is specified, padding goes after sign and before digits.
    if (zero || (fill === "0" && align === "=")) zero = true, fill = "0", align = "=";

    // Compute the prefix and suffix.
    // For SI-prefix, the suffix is lazily computed.
    var prefix = symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "",
        suffix = symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent : "";

    // What format function should we use?
    // Is this an integer type?
    // Can this type generate exponential notation?
    var formatType = formatTypes[type],
        maybeSuffix = /[defgprs%]/.test(type);

    // Set the default precision if not specified,
    // or clamp the specified precision to the supported range.
    // For significant precision, it must be in [1, 21].
    // For fixed precision, it must be in [0, 20].
    precision = precision === undefined ? 6
        : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))
        : Math.max(0, Math.min(20, precision));

    function format(value) {
      var valuePrefix = prefix,
          valueSuffix = suffix,
          i, n, c;

      if (type === "c") {
        valueSuffix = formatType(value) + valueSuffix;
        value = "";
      } else {
        value = +value;

        // Perform the initial formatting.
        var valueNegative = value < 0;
        value = isNaN(value) ? nan : formatType(Math.abs(value), precision);

        // Trim insignificant zeros.
        if (trim) value = formatTrim(value);

        // If a negative value rounds to zero during formatting, treat as positive.
        if (valueNegative && +value === 0) valueNegative = false;

        // Compute the prefix and suffix.
        valuePrefix = (valueNegative ? (sign === "(" ? sign : minus) : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;

        valueSuffix = (type === "s" ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");

        // Break the formatted value into the integer “value” part that can be
        // grouped, and fractional or exponential “suffix” part that is not.
        if (maybeSuffix) {
          i = -1, n = value.length;
          while (++i < n) {
            if (c = value.charCodeAt(i), 48 > c || c > 57) {
              valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
              value = value.slice(0, i);
              break;
            }
          }
        }
      }

      // If the fill character is not "0", grouping is applied before padding.
      if (comma && !zero) value = group(value, Infinity);

      // Compute the padding.
      var length = valuePrefix.length + value.length + valueSuffix.length,
          padding = length < width ? new Array(width - length + 1).join(fill) : "";

      // If the fill character is "0", grouping is applied after padding.
      if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";

      // Reconstruct the final output based on the desired alignment.
      switch (align) {
        case "<": value = valuePrefix + value + valueSuffix + padding; break;
        case "=": value = valuePrefix + padding + value + valueSuffix; break;
        case "^": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;
        default: value = padding + valuePrefix + value + valueSuffix; break;
      }

      return numerals(value);
    }

    format.toString = function() {
      return specifier + "";
    };

    return format;
  }

  function formatPrefix(specifier, value) {
    var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)),
        e = Math.max(-8, Math.min(8, Math.floor(picasso_esm_exponent(value) / 3))) * 3,
        k = Math.pow(10, -e),
        prefix = prefixes[8 + e / 3];
    return function(value) {
      return f(k * value) + prefix;
    };
  }

  return {
    format: newFormat,
    formatPrefix: formatPrefix
  };
}

var picasso_esm_locale;
var picasso_esm_format;
var picasso_esm_formatPrefix;

defaultLocale({
  decimal: ".",
  thousands: ",",
  grouping: [3],
  currency: ["$", ""],
  minus: "-"
});

function defaultLocale(definition) {
  picasso_esm_locale = formatLocale(definition);
  picasso_esm_format = picasso_esm_locale.format;
  picasso_esm_formatPrefix = picasso_esm_locale.formatPrefix;
  return picasso_esm_locale;
}

function picasso_esm_formatter(pattern, thousand, decimal) {
  var locale, d3format;
  /**
   * Format a value according to the specified pattern created at construct
   * @private
   *
   * @param  {Number} value   The number to be formatted
   * @return {String}         [description]
   */

  function format(value) {
    return d3format(value);
  }
  /**
    * Set the locale for the formatter
    *
    * @param  {Object} args   Locale object for formatting
    * @return {Undefined}      Returns nothing
    */


  format.locale = function localeFn(settings) {
    locale = formatLocale(settings);
    d3format = locale.format(pattern);
    return this;
  };
  /**
   * Resets the formatter using format.locale
   * @ignore
   */


  function reset() {
    format.locale({
      decimal: decimal || '.',
      thousands: thousand || ',',
      grouping: [3],
      currency: ['$', '']
    });
  }

  reset();
  /**
    * Format a value according to a specific pattern
    * that is not the one specified in the constructor
    *
    * @param  {String} p   Pattern
    * @param  {Number} v   Value
    * @param  {String} t   Thousand
    * @param  {String} d   Decimal
    * @return {String}     Formatted value
    */

  format.format = function formatFn(p, v, t, d) {
    if (t || d) {
      thousand = t;
      decimal = d;
      reset();
    }

    return locale.format(p)(v);
  };
  /**
   * Change the pattern on existing formatter
   *
   * @param  {String} p     Pattern (optional)
   * @return {String}       Returns the pattern
   */


  format.pattern = function patternFn(p) {
    if (p) {
      pattern = p;
      d3format = locale.format(p);
    }

    return pattern;
  };

  return format;
}

var t0 = new Date,
    picasso_esm_t1 = new Date;

function newInterval(floori, offseti, count, field) {

  function interval(date) {
    return floori(date = new Date(+date)), date;
  }

  interval.floor = interval;

  interval.ceil = function(date) {
    return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date;
  };

  interval.round = function(date) {
    var d0 = interval(date),
        d1 = interval.ceil(date);
    return date - d0 < d1 - date ? d0 : d1;
  };

  interval.offset = function(date, step) {
    return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date;
  };

  interval.range = function(start, stop, step) {
    var range = [], previous;
    start = interval.ceil(start);
    step = step == null ? 1 : Math.floor(step);
    if (!(start < stop) || !(step > 0)) return range; // also handles Invalid Date
    do range.push(previous = new Date(+start)), offseti(start, step), floori(start);
    while (previous < start && start < stop);
    return range;
  };

  interval.filter = function(test) {
    return newInterval(function(date) {
      if (date >= date) while (floori(date), !test(date)) date.setTime(date - 1);
    }, function(date, step) {
      if (date >= date) {
        if (step < 0) while (++step <= 0) {
          while (offseti(date, -1), !test(date)) {} // eslint-disable-line no-empty
        } else while (--step >= 0) {
          while (offseti(date, +1), !test(date)) {} // eslint-disable-line no-empty
        }
      }
    });
  };

  if (count) {
    interval.count = function(start, end) {
      t0.setTime(+start), picasso_esm_t1.setTime(+end);
      floori(t0), floori(picasso_esm_t1);
      return Math.floor(count(t0, picasso_esm_t1));
    };

    interval.every = function(step) {
      step = Math.floor(step);
      return !isFinite(step) || !(step > 0) ? null
          : !(step > 1) ? interval
          : interval.filter(field
              ? function(d) { return field(d) % step === 0; }
              : function(d) { return interval.count(0, d) % step === 0; });
    };
  }

  return interval;
}

var millisecond = newInterval(function() {
  // noop
}, function(date, step) {
  date.setTime(+date + step);
}, function(start, end) {
  return end - start;
});

// An optimized implementation for this simple case.
millisecond.every = function(k) {
  k = Math.floor(k);
  if (!isFinite(k) || !(k > 0)) return null;
  if (!(k > 1)) return millisecond;
  return newInterval(function(date) {
    date.setTime(Math.floor(date / k) * k);
  }, function(date, step) {
    date.setTime(+date + step * k);
  }, function(start, end) {
    return (end - start) / k;
  });
};

var durationSecond = 1e3;
var durationMinute = 6e4;
var durationHour = 36e5;
var durationDay = 864e5;
var durationWeek = 6048e5;

var second = newInterval(function(date) {
  date.setTime(date - date.getMilliseconds());
}, function(date, step) {
  date.setTime(+date + step * durationSecond);
}, function(start, end) {
  return (end - start) / durationSecond;
}, function(date) {
  return date.getUTCSeconds();
});

var minute = newInterval(function(date) {
  date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond);
}, function(date, step) {
  date.setTime(+date + step * durationMinute);
}, function(start, end) {
  return (end - start) / durationMinute;
}, function(date) {
  return date.getMinutes();
});

var hour = newInterval(function(date) {
  date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond - date.getMinutes() * durationMinute);
}, function(date, step) {
  date.setTime(+date + step * durationHour);
}, function(start, end) {
  return (end - start) / durationHour;
}, function(date) {
  return date.getHours();
});

var day = newInterval(function(date) {
  date.setHours(0, 0, 0, 0);
}, function(date, step) {
  date.setDate(date.getDate() + step);
}, function(start, end) {
  return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay;
}, function(date) {
  return date.getDate() - 1;
});

function weekday(i) {
  return newInterval(function(date) {
    date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7);
    date.setHours(0, 0, 0, 0);
  }, function(date, step) {
    date.setDate(date.getDate() + step * 7);
  }, function(start, end) {
    return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek;
  });
}

var sunday = weekday(0);
var monday = weekday(1);
var tuesday = weekday(2);
var wednesday = weekday(3);
var thursday = weekday(4);
var friday = weekday(5);
var saturday = weekday(6);

var month = newInterval(function(date) {
  date.setDate(1);
  date.setHours(0, 0, 0, 0);
}, function(date, step) {
  date.setMonth(date.getMonth() + step);
}, function(start, end) {
  return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;
}, function(date) {
  return date.getMonth();
});

var year = newInterval(function(date) {
  date.setMonth(0, 1);
  date.setHours(0, 0, 0, 0);
}, function(date, step) {
  date.setFullYear(date.getFullYear() + step);
}, function(start, end) {
  return end.getFullYear() - start.getFullYear();
}, function(date) {
  return date.getFullYear();
});

// An optimized implementation for this simple case.
year.every = function(k) {
  return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date) {
    date.setFullYear(Math.floor(date.getFullYear() / k) * k);
    date.setMonth(0, 1);
    date.setHours(0, 0, 0, 0);
  }, function(date, step) {
    date.setFullYear(date.getFullYear() + step * k);
  });
};

var utcMinute = newInterval(function(date) {
  date.setUTCSeconds(0, 0);
}, function(date, step) {
  date.setTime(+date + step * durationMinute);
}, function(start, end) {
  return (end - start) / durationMinute;
}, function(date) {
  return date.getUTCMinutes();
});

var utcHour = newInterval(function(date) {
  date.setUTCMinutes(0, 0, 0);
}, function(date, step) {
  date.setTime(+date + step * durationHour);
}, function(start, end) {
  return (end - start) / durationHour;
}, function(date) {
  return date.getUTCHours();
});

var utcDay = newInterval(function(date) {
  date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
  date.setUTCDate(date.getUTCDate() + step);
}, function(start, end) {
  return (end - start) / durationDay;
}, function(date) {
  return date.getUTCDate() - 1;
});

function utcWeekday(i) {
  return newInterval(function(date) {
    date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7);
    date.setUTCHours(0, 0, 0, 0);
  }, function(date, step) {
    date.setUTCDate(date.getUTCDate() + step * 7);
  }, function(start, end) {
    return (end - start) / durationWeek;
  });
}

var utcSunday = utcWeekday(0);
var utcMonday = utcWeekday(1);
var utcTuesday = utcWeekday(2);
var utcWednesday = utcWeekday(3);
var utcThursday = utcWeekday(4);
var utcFriday = utcWeekday(5);
var utcSaturday = utcWeekday(6);

var utcMonth = newInterval(function(date) {
  date.setUTCDate(1);
  date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
  date.setUTCMonth(date.getUTCMonth() + step);
}, function(start, end) {
  return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;
}, function(date) {
  return date.getUTCMonth();
});

var utcYear = newInterval(function(date) {
  date.setUTCMonth(0, 1);
  date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
  date.setUTCFullYear(date.getUTCFullYear() + step);
}, function(start, end) {
  return end.getUTCFullYear() - start.getUTCFullYear();
}, function(date) {
  return date.getUTCFullYear();
});

// An optimized implementation for this simple case.
utcYear.every = function(k) {
  return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date) {
    date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k);
    date.setUTCMonth(0, 1);
    date.setUTCHours(0, 0, 0, 0);
  }, function(date, step) {
    date.setUTCFullYear(date.getUTCFullYear() + step * k);
  });
};

function localDate(d) {
  if (0 <= d.y && d.y < 100) {
    var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
    date.setFullYear(d.y);
    return date;
  }
  return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);
}

function utcDate(d) {
  if (0 <= d.y && d.y < 100) {
    var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
    date.setUTCFullYear(d.y);
    return date;
  }
  return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
}

function newYear(y) {
  return {y: y, m: 0, d: 1, H: 0, M: 0, S: 0, L: 0};
}

function formatLocale$1(locale) {
  var locale_dateTime = locale.dateTime,
      locale_date = locale.date,
      locale_time = locale.time,
      locale_periods = locale.periods,
      locale_weekdays = locale.days,
      locale_shortWeekdays = locale.shortDays,
      locale_months = locale.months,
      locale_shortMonths = locale.shortMonths;

  var periodRe = formatRe(locale_periods),
      periodLookup = formatLookup(locale_periods),
      weekdayRe = formatRe(locale_weekdays),
      weekdayLookup = formatLookup(locale_weekdays),
      shortWeekdayRe = formatRe(locale_shortWeekdays),
      shortWeekdayLookup = formatLookup(locale_shortWeekdays),
      monthRe = formatRe(locale_months),
      monthLookup = formatLookup(locale_months),
      shortMonthRe = formatRe(locale_shortMonths),
      shortMonthLookup = formatLookup(locale_shortMonths);

  var formats = {
    "a": formatShortWeekday,
    "A": formatWeekday,
    "b": formatShortMonth,
    "B": formatMonth,
    "c": null,
    "d": formatDayOfMonth,
    "e": formatDayOfMonth,
    "f": formatMicroseconds,
    "H": formatHour24,
    "I": formatHour12,
    "j": formatDayOfYear,
    "L": formatMilliseconds,
    "m": formatMonthNumber,
    "M": formatMinutes,
    "p": formatPeriod,
    "Q": formatUnixTimestamp,
    "s": formatUnixTimestampSeconds,
    "S": formatSeconds,
    "u": formatWeekdayNumberMonday,
    "U": formatWeekNumberSunday,
    "V": formatWeekNumberISO,
    "w": formatWeekdayNumberSunday,
    "W": formatWeekNumberMonday,
    "x": null,
    "X": null,
    "y": formatYear,
    "Y": formatFullYear,
    "Z": formatZone,
    "%": formatLiteralPercent
  };

  var utcFormats = {
    "a": formatUTCShortWeekday,
    "A": formatUTCWeekday,
    "b": formatUTCShortMonth,
    "B": formatUTCMonth,
    "c": null,
    "d": formatUTCDayOfMonth,
    "e": formatUTCDayOfMonth,
    "f": formatUTCMicroseconds,
    "H": formatUTCHour24,
    "I": formatUTCHour12,
    "j": formatUTCDayOfYear,
    "L": formatUTCMilliseconds,
    "m": formatUTCMonthNumber,
    "M": formatUTCMinutes,
    "p": formatUTCPeriod,
    "Q": formatUnixTimestamp,
    "s": formatUnixTimestampSeconds,
    "S": formatUTCSeconds,
    "u": formatUTCWeekdayNumberMonday,
    "U": formatUTCWeekNumberSunday,
    "V": formatUTCWeekNumberISO,
    "w": formatUTCWeekdayNumberSunday,
    "W": formatUTCWeekNumberMonday,
    "x": null,
    "X": null,
    "y": formatUTCYear,
    "Y": formatUTCFullYear,
    "Z": formatUTCZone,
    "%": formatLiteralPercent
  };

  var parses = {
    "a": parseShortWeekday,
    "A": parseWeekday,
    "b": parseShortMonth,
    "B": parseMonth,
    "c": parseLocaleDateTime,
    "d": parseDayOfMonth,
    "e": parseDayOfMonth,
    "f": parseMicroseconds,
    "H": parseHour24,
    "I": parseHour24,
    "j": parseDayOfYear,
    "L": parseMilliseconds,
    "m": parseMonthNumber,
    "M": parseMinutes,
    "p": parsePeriod,
    "Q": parseUnixTimestamp,
    "s": parseUnixTimestampSeconds,
    "S": parseSeconds,
    "u": parseWeekdayNumberMonday,
    "U": parseWeekNumberSunday,
    "V": parseWeekNumberISO,
    "w": parseWeekdayNumberSunday,
    "W": parseWeekNumberMonday,
    "x": parseLocaleDate,
    "X": parseLocaleTime,
    "y": parseYear,
    "Y": parseFullYear,
    "Z": parseZone,
    "%": parseLiteralPercent
  };

  // These recursive directive definitions must be deferred.
  formats.x = newFormat(locale_date, formats);
  formats.X = newFormat(locale_time, formats);
  formats.c = newFormat(locale_dateTime, formats);
  utcFormats.x = newFormat(locale_date, utcFormats);
  utcFormats.X = newFormat(locale_time, utcFormats);
  utcFormats.c = newFormat(locale_dateTime, utcFormats);

  function newFormat(specifier, formats) {
    return function(date) {
      var string = [],
          i = -1,
          j = 0,
          n = specifier.length,
          c,
          pad,
          format;

      if (!(date instanceof Date)) date = new Date(+date);

      while (++i < n) {
        if (specifier.charCodeAt(i) === 37) {
          string.push(specifier.slice(j, i));
          if ((pad = pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i);
          else pad = c === "e" ? " " : "0";
          if (format = formats[c]) c = format(date, pad);
          string.push(c);
          j = i + 1;
        }
      }

      string.push(specifier.slice(j, i));
      return string.join("");
    };
  }

  function newParse(specifier, newDate) {
    return function(string) {
      var d = newYear(1900),
          i = parseSpecifier(d, specifier, string += "", 0),
          week, day$1;
      if (i != string.length) return null;

      // If a UNIX timestamp is specified, return it.
      if ("Q" in d) return new Date(d.Q);

      // The am-pm flag is 0 for AM, and 1 for PM.
      if ("p" in d) d.H = d.H % 12 + d.p * 12;

      // Convert day-of-week and week-of-year to day-of-year.
      if ("V" in d) {
        if (d.V < 1 || d.V > 53) return null;
        if (!("w" in d)) d.w = 1;
        if ("Z" in d) {
          week = utcDate(newYear(d.y)), day$1 = week.getUTCDay();
          week = day$1 > 4 || day$1 === 0 ? utcMonday.ceil(week) : utcMonday(week);
          week = utcDay.offset(week, (d.V - 1) * 7);
          d.y = week.getUTCFullYear();
          d.m = week.getUTCMonth();
          d.d = week.getUTCDate() + (d.w + 6) % 7;
        } else {
          week = newDate(newYear(d.y)), day$1 = week.getDay();
          week = day$1 > 4 || day$1 === 0 ? monday.ceil(week) : monday(week);
          week = day.offset(week, (d.V - 1) * 7);
          d.y = week.getFullYear();
          d.m = week.getMonth();
          d.d = week.getDate() + (d.w + 6) % 7;
        }
      } else if ("W" in d || "U" in d) {
        if (!("w" in d)) d.w = "u" in d ? d.u % 7 : "W" in d ? 1 : 0;
        day$1 = "Z" in d ? utcDate(newYear(d.y)).getUTCDay() : newDate(newYear(d.y)).getDay();
        d.m = 0;
        d.d = "W" in d ? (d.w + 6) % 7 + d.W * 7 - (day$1 + 5) % 7 : d.w + d.U * 7 - (day$1 + 6) % 7;
      }

      // If a time zone is specified, all fields are interpreted as UTC and then
      // offset according to the specified time zone.
      if ("Z" in d) {
        d.H += d.Z / 100 | 0;
        d.M += d.Z % 100;
        return utcDate(d);
      }

      // Otherwise, all fields are in local time.
      return newDate(d);
    };
  }

  function parseSpecifier(d, specifier, string, j) {
    var i = 0,
        n = specifier.length,
        m = string.length,
        c,
        parse;

    while (i < n) {
      if (j >= m) return -1;
      c = specifier.charCodeAt(i++);
      if (c === 37) {
        c = specifier.charAt(i++);
        parse = parses[c in pads ? specifier.charAt(i++) : c];
        if (!parse || ((j = parse(d, string, j)) < 0)) return -1;
      } else if (c != string.charCodeAt(j++)) {
        return -1;
      }
    }

    return j;
  }

  function parsePeriod(d, string, i) {
    var n = periodRe.exec(string.slice(i));
    return n ? (d.p = periodLookup[n[0].toLowerCase()], i + n[0].length) : -1;
  }

  function parseShortWeekday(d, string, i) {
    var n = shortWeekdayRe.exec(string.slice(i));
    return n ? (d.w = shortWeekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;
  }

  function parseWeekday(d, string, i) {
    var n = weekdayRe.exec(string.slice(i));
    return n ? (d.w = weekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;
  }

  function parseShortMonth(d, string, i) {
    var n = shortMonthRe.exec(string.slice(i));
    return n ? (d.m = shortMonthLookup[n[0].toLowerCase()], i + n[0].length) : -1;
  }

  function parseMonth(d, string, i) {
    var n = monthRe.exec(string.slice(i));
    return n ? (d.m = monthLookup[n[0].toLowerCase()], i + n[0].length) : -1;
  }

  function parseLocaleDateTime(d, string, i) {
    return parseSpecifier(d, locale_dateTime, string, i);
  }

  function parseLocaleDate(d, string, i) {
    return parseSpecifier(d, locale_date, string, i);
  }

  function parseLocaleTime(d, string, i) {
    return parseSpecifier(d, locale_time, string, i);
  }

  function formatShortWeekday(d) {
    return locale_shortWeekdays[d.getDay()];
  }

  function formatWeekday(d) {
    return locale_weekdays[d.getDay()];
  }

  function formatShortMonth(d) {
    return locale_shortMonths[d.getMonth()];
  }

  function formatMonth(d) {
    return locale_months[d.getMonth()];
  }

  function formatPeriod(d) {
    return locale_periods[+(d.getHours() >= 12)];
  }

  function formatUTCShortWeekday(d) {
    return locale_shortWeekdays[d.getUTCDay()];
  }

  function formatUTCWeekday(d) {
    return locale_weekdays[d.getUTCDay()];
  }

  function formatUTCShortMonth(d) {
    return locale_shortMonths[d.getUTCMonth()];
  }

  function formatUTCMonth(d) {
    return locale_months[d.getUTCMonth()];
  }

  function formatUTCPeriod(d) {
    return locale_periods[+(d.getUTCHours() >= 12)];
  }

  return {
    format: function(specifier) {
      var f = newFormat(specifier += "", formats);
      f.toString = function() { return specifier; };
      return f;
    },
    parse: function(specifier) {
      var p = newParse(specifier += "", localDate);
      p.toString = function() { return specifier; };
      return p;
    },
    utcFormat: function(specifier) {
      var f = newFormat(specifier += "", utcFormats);
      f.toString = function() { return specifier; };
      return f;
    },
    utcParse: function(specifier) {
      var p = newParse(specifier, utcDate);
      p.toString = function() { return specifier; };
      return p;
    }
  };
}

var pads = {"-": "", "_": " ", "0": "0"},
    numberRe = /^\s*\d+/, // note: ignores next directive
    percentRe = /^%/,
    requoteRe = /[\\^$*+?|[\]().{}]/g;

function pad(value, fill, width) {
  var sign = value < 0 ? "-" : "",
      string = (sign ? -value : value) + "",
      length = string.length;
  return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);
}

function requote(s) {
  return s.replace(requoteRe, "\\$&");
}

function formatRe(names) {
  return new RegExp("^(?:" + names.map(requote).join("|") + ")", "i");
}

function formatLookup(names) {
  var map = {}, i = -1, n = names.length;
  while (++i < n) map[names[i].toLowerCase()] = i;
  return map;
}

function parseWeekdayNumberSunday(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 1));
  return n ? (d.w = +n[0], i + n[0].length) : -1;
}

function parseWeekdayNumberMonday(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 1));
  return n ? (d.u = +n[0], i + n[0].length) : -1;
}

function parseWeekNumberSunday(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.U = +n[0], i + n[0].length) : -1;
}

function parseWeekNumberISO(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.V = +n[0], i + n[0].length) : -1;
}

function parseWeekNumberMonday(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.W = +n[0], i + n[0].length) : -1;
}

function parseFullYear(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 4));
  return n ? (d.y = +n[0], i + n[0].length) : -1;
}

function parseYear(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1;
}

function parseZone(d, string, i) {
  var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string.slice(i, i + 6));
  return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1;
}

function parseMonthNumber(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.m = n[0] - 1, i + n[0].length) : -1;
}

function parseDayOfMonth(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.d = +n[0], i + n[0].length) : -1;
}

function parseDayOfYear(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 3));
  return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;
}

function parseHour24(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.H = +n[0], i + n[0].length) : -1;
}

function parseMinutes(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.M = +n[0], i + n[0].length) : -1;
}

function parseSeconds(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.S = +n[0], i + n[0].length) : -1;
}

function parseMilliseconds(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 3));
  return n ? (d.L = +n[0], i + n[0].length) : -1;
}

function parseMicroseconds(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 6));
  return n ? (d.L = Math.floor(n[0] / 1000), i + n[0].length) : -1;
}

function parseLiteralPercent(d, string, i) {
  var n = percentRe.exec(string.slice(i, i + 1));
  return n ? i + n[0].length : -1;
}

function parseUnixTimestamp(d, string, i) {
  var n = numberRe.exec(string.slice(i));
  return n ? (d.Q = +n[0], i + n[0].length) : -1;
}

function parseUnixTimestampSeconds(d, string, i) {
  var n = numberRe.exec(string.slice(i));
  return n ? (d.Q = (+n[0]) * 1000, i + n[0].length) : -1;
}

function formatDayOfMonth(d, p) {
  return pad(d.getDate(), p, 2);
}

function formatHour24(d, p) {
  return pad(d.getHours(), p, 2);
}

function formatHour12(d, p) {
  return pad(d.getHours() % 12 || 12, p, 2);
}

function formatDayOfYear(d, p) {
  return pad(1 + day.count(year(d), d), p, 3);
}

function formatMilliseconds(d, p) {
  return pad(d.getMilliseconds(), p, 3);
}

function formatMicroseconds(d, p) {
  return formatMilliseconds(d, p) + "000";
}

function formatMonthNumber(d, p) {
  return pad(d.getMonth() + 1, p, 2);
}

function formatMinutes(d, p) {
  return pad(d.getMinutes(), p, 2);
}

function formatSeconds(d, p) {
  return pad(d.getSeconds(), p, 2);
}

function formatWeekdayNumberMonday(d) {
  var day = d.getDay();
  return day === 0 ? 7 : day;
}

function formatWeekNumberSunday(d, p) {
  return pad(sunday.count(year(d), d), p, 2);
}

function formatWeekNumberISO(d, p) {
  var day = d.getDay();
  d = (day >= 4 || day === 0) ? thursday(d) : thursday.ceil(d);
  return pad(thursday.count(year(d), d) + (year(d).getDay() === 4), p, 2);
}

function formatWeekdayNumberSunday(d) {
  return d.getDay();
}

function formatWeekNumberMonday(d, p) {
  return pad(monday.count(year(d), d), p, 2);
}

function formatYear(d, p) {
  return pad(d.getFullYear() % 100, p, 2);
}

function formatFullYear(d, p) {
  return pad(d.getFullYear() % 10000, p, 4);
}

function formatZone(d) {
  var z = d.getTimezoneOffset();
  return (z > 0 ? "-" : (z *= -1, "+"))
      + pad(z / 60 | 0, "0", 2)
      + pad(z % 60, "0", 2);
}

function formatUTCDayOfMonth(d, p) {
  return pad(d.getUTCDate(), p, 2);
}

function formatUTCHour24(d, p) {
  return pad(d.getUTCHours(), p, 2);
}

function formatUTCHour12(d, p) {
  return pad(d.getUTCHours() % 12 || 12, p, 2);
}

function formatUTCDayOfYear(d, p) {
  return pad(1 + utcDay.count(utcYear(d), d), p, 3);
}

function formatUTCMilliseconds(d, p) {
  return pad(d.getUTCMilliseconds(), p, 3);
}

function formatUTCMicroseconds(d, p) {
  return formatUTCMilliseconds(d, p) + "000";
}

function formatUTCMonthNumber(d, p) {
  return pad(d.getUTCMonth() + 1, p, 2);
}

function formatUTCMinutes(d, p) {
  return pad(d.getUTCMinutes(), p, 2);
}

function formatUTCSeconds(d, p) {
  return pad(d.getUTCSeconds(), p, 2);
}

function formatUTCWeekdayNumberMonday(d) {
  var dow = d.getUTCDay();
  return dow === 0 ? 7 : dow;
}

function formatUTCWeekNumberSunday(d, p) {
  return pad(utcSunday.count(utcYear(d), d), p, 2);
}

function formatUTCWeekNumberISO(d, p) {
  var day = d.getUTCDay();
  d = (day >= 4 || day === 0) ? utcThursday(d) : utcThursday.ceil(d);
  return pad(utcThursday.count(utcYear(d), d) + (utcYear(d).getUTCDay() === 4), p, 2);
}

function formatUTCWeekdayNumberSunday(d) {
  return d.getUTCDay();
}

function formatUTCWeekNumberMonday(d, p) {
  return pad(utcMonday.count(utcYear(d), d), p, 2);
}

function formatUTCYear(d, p) {
  return pad(d.getUTCFullYear() % 100, p, 2);
}

function formatUTCFullYear(d, p) {
  return pad(d.getUTCFullYear() % 10000, p, 4);
}

function formatUTCZone() {
  return "+0000";
}

function formatLiteralPercent() {
  return "%";
}

function formatUnixTimestamp(d) {
  return +d;
}

function formatUnixTimestampSeconds(d) {
  return Math.floor(+d / 1000);
}

var locale$1;
var timeFormat;
var timeParse;
var utcFormat;
var utcParse;

defaultLocale$1({
  dateTime: "%x, %X",
  date: "%-m/%-d/%Y",
  time: "%-I:%M:%S %p",
  periods: ["AM", "PM"],
  days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
  shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
});

function defaultLocale$1(definition) {
  locale$1 = formatLocale$1(definition);
  timeFormat = locale$1.format;
  timeParse = locale$1.parse;
  utcFormat = locale$1.utcFormat;
  utcParse = locale$1.utcParse;
  return locale$1;
}

var isoSpecifier = "%Y-%m-%dT%H:%M:%S.%LZ";

function formatIsoNative(date) {
  return date.toISOString();
}

var formatIso = Date.prototype.toISOString
    ? formatIsoNative
    : utcFormat(isoSpecifier);

function parseIsoNative(string) {
  var date = new Date(string);
  return isNaN(date) ? null : date;
}

var parseIso = +new Date("2000-01-01T00:00:00.000Z")
    ? parseIsoNative
    : utcParse(isoSpecifier);

function formatter$1(pattern) {
  // eslint-disable-line import/prefer-default-export
  var locale = formatLocale$1({
    dateTime: '%x, %X',
    date: '%-m/%-d/%Y',
    time: '%-I:%M:%S %p',
    periods: ['AM', 'PM'],
    days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
    shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  });
  var d3format = locale.format(pattern);
  /**
   * Format a value according to the specified pattern created at construct
   *
   * @param  {Date} value   The number to be formatted
   * @return {String}         [description]
   * @private
   */

  function format(value) {
    return d3format(value);
  }
  /**
    * Format a value according to a specific pattern
    * that is not the one specified in the constructor
    *
    * @param  {String} p   Pattern
    * @param  {Date} v   Value
    * @return {String}     Formatted value
    */


  format.format = function formatFn(p, v) {
    return locale.format(p)(v);
  };
  /**
   * Set the locale for the formatter
   *
   * @param  {Object} args   Locale object for formatting
   * @return {Undefined}      Returns nothing
   */


  format.locale = function localeFn() {
    locale = formatLocale$1.apply(void 0, arguments);
    d3format = locale.format(pattern);
    return this;
  };
  /**
   * Parse a string to a date according to a pattern
   *
   * @param  {String} p   Pattern
   * @param  {String} v   Value
   * @return {Date}     Date
   */


  format.parse = function parse(p, v) {
    return locale.parse(p)(v);
  };
  /**
   * Returns a parser that parses strings to date according to the pattern
   *
   * @param  {String} p   Pattern
   * @return {Function}   Parser
   */


  format.parsePattern = function parsePattern(p) {
    return locale.parse(p);
  };

  return format;
}

var formatterRegistry = registryFactory();
formatterRegistry('d3-number', picasso_esm_formatter);
formatterRegistry('d3-time', formatter$1);

/* eslint no-return-assign: 0 */

var getFormatter = function getFormatter(data) {
  if (typeof data.formatter === 'function') {
    return data.formatter();
  }

  var f = data.formatter || {};
  return formatterRegistry(f.type || 'd3-number')(f.format || '');
};

var accessors = {
  id: function id(data) {
    return "".concat(data.source, "/").concat(data.key || data.title);
  },
  key: function key(data) {
    return String(data.key || data.title);
  },
  tags: function tags(data) {
    return data.tags;
  },
  min: function min(data) {
    return data.min;
  },
  max: function max(data) {
    return data.max;
  },
  type: function type(data) {
    return data.type;
  },
  title: function title(data) {
    return String(data.title);
  },
  values: function values(data) {
    return data.values;
  },
  value: function value(v) {
    return v;
  },
  label: function label(v) {
    return v;
  },
  formatter: function formatter(data) {
    return getFormatter(data);
  }
};
/**
 * Create a new field with default settings
 * @ignore
 * @return {field} Data field
 */

function picasso_esm_field(data) {
  var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
      _ref$id = _ref.id,
      _id = _ref$id === void 0 ? accessors.id : _ref$id,
      _ref$key = _ref.key,
      _key = _ref$key === void 0 ? accessors.key : _ref$key,
      _ref$min = _ref.min,
      _min = _ref$min === void 0 ? accessors.min : _ref$min,
      _ref$max = _ref.max,
      _max = _ref$max === void 0 ? accessors.max : _ref$max,
      _ref$type = _ref.type,
      _type = _ref$type === void 0 ? accessors.type : _ref$type,
      _ref$tags = _ref.tags,
      _tags = _ref$tags === void 0 ? accessors.tags : _ref$tags,
      _ref$title = _ref.title,
      _title = _ref$title === void 0 ? accessors.title : _ref$title,
      _ref$values = _ref.values,
      values = _ref$values === void 0 ? accessors.values : _ref$values,
      _ref$value = _ref.value,
      value = _ref$value === void 0 ? accessors.value : _ref$value,
      _ref$label = _ref.label,
      label = _ref$label === void 0 ? accessors.label : _ref$label,
      _ref$formatter = _ref.formatter,
      _formatter = _ref$formatter === void 0 ? accessors.formatter : _ref$formatter;

  /**
   * @alias field
   */
  var f = {
    /**
     * Returns this field's id
     * @returns {string}
     */
    id: function id() {
      return _id(data);
    },

    /**
     * Returns this field's key
     * @returns {string}
     */
    key: function key() {
      return _key(data);
    },

    /**
     * Returns the input data
     * @returns {any}
     */
    raw: function raw() {
      return data;
    },

    /**
     * Returns the tags.
     * @return {Array<string>}
     */
    tags: function tags() {
      return _tags(data);
    },

    /**
     * Returns this field's type: 'dimension' or 'measure'.
     * @return {string}
     */
    type: function type() {
      return _type(data);
    },

    /**
     * Returns the min value of this field.
     * @return {number}
     */
    min: function min() {
      return _min(data);
    },

    /**
     * Returns the max value of this field.
     * @return {number}
     */
    max: function max() {
      return _max(data);
    },

    /**
     * Returns this field's title.
     * @return {string}
     */
    title: function title() {
      return _title(data);
    },

    /**
     * Returns the values of this field.
     * @return {Array<datum-extract>}
     */
    items: function items() {
      return values(data);
    },

    /**
     * Returns a formatter adapted to the content of this field.
     */
    formatter: function formatter() {
      return _formatter(data);
    },
    value: value,
    label: label
  };
  return f;
}

var OFFSETS = {
  diverging: stackOffsetDiverging,
  none: stackOffsetNone,
  silhouette: stackOffsetSilhouette,
  expand: stackOffsetExpand,
  wiggle: stackOffsetWiggle
};
var ORDERS = {
  ascending: stackOrderAscending,
  insideout: stackOrderInsideOut,
  none: stackOrderNone,
  reverse: stackOrderReverse
};

function stacked(data, config, ds) {
  var stackIds = {};
  var stackFn = config.stackKey;
  var valueFn = config.value;
  var startProp = config.startProp || 'start';
  var endProp = config.endProp || 'end';
  var offset = config.offset || 'none';
  var order = config.order || 'none';
  var valueRef = config.valueRef || '';
  var maxStackCount = 0;
  var valueFields = {};

  for (var i = 0; i < data.items.length; i++) {
    var p = data.items[i];
    var sourceField = valueRef ? p[valueRef] : null;

    if (sourceField && sourceField.source) {
      var ff = "".concat(sourceField.source.key || '', "/").concat(sourceField.source.field);

      if (!valueFields[ff]) {
        valueFields[ff] = sourceField.source;
      }
    }

    var sid = stackFn(p);
    stackIds[sid] = stackIds[sid] || {
      items: []
    };
    stackIds[sid].items.push(p);
    maxStackCount = Math.max(maxStackCount, stackIds[sid].items.length);
  }

  var keys = Array.apply(null, {
    length: maxStackCount
  }).map(Number.call, Number); // eslint-disable-line

  var matrix = Object.keys(stackIds).map(function (sid) {
    return stackIds[sid].items;
  });
  var d3Stack = stack().keys(keys).value(function (s, key) {
    return s[key] ? valueFn(s[key]) : 0;
  }).order(ORDERS[order]).offset(OFFSETS[offset]);
  var series = d3Stack(matrix);
  var values = [];

  for (var _i = 0; _i < series.length; _i++) {
    var serie = series[_i];

    for (var s = 0; s < serie.length; s++) {
      var range = serie[s];
      var item = serie[s].data[serie.key];

      if (!item) {
        continue;
      }

      item[startProp] = {
        value: range[0]
      };
      item[endProp] = {
        value: range[1]
      };
      values.push(range[0], range[1]);
    }
  }

  var stackedFields = Object.keys(valueFields).map(function (f) {
    var dSource = ds(valueFields[f].key);
    return dSource ? dSource.field(valueFields[f].field) : null;
  }).filter(function (f) {
    return !!f;
  });
  var field$1 = picasso_esm_field({
    title: stackedFields.map(function (f) {
      return f.title();
    }).join(', '),
    min: Math.min.apply(Math, values),
    max: Math.max.apply(Math, values),
    type: 'measure',
    formatter: stackedFields[0] ? stackedFields[0].formatter : undefined
  });
  data.fields.push(field$1);
}

function extract(dataConfig) {
  var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var extracted = {// items: [],
    // fields: [],
    // source: null,
    // value: null,
    // label: null,
    // children: null,
    // root: null,
    // graph: null
  };
  var logger = opts.logger;

  if (Array.isArray(dataConfig)) {
    // if data is an array, assume it's manual data input -> normalize
    extracted.items = dataConfig.map(function (v) {
      return {
        value: v,
        label: String(v)
      };
    });
  } else if (dataConfig) {
    if ('collection' in dataConfig) {
      extracted = _objectSpread2({}, data.collection(dataConfig.collection));
    } else {
      var source = data.dataset ? data.dataset(dataConfig.source) : null;

      var valueFn = dataConfig.value || function (d) {
        return d;
      };

      var labelFn = dataConfig.label || function (d) {
        return d;
      };

      if (dataConfig.groupBy || dataConfig.mapTo) {
        // DEPRECATION
        logger.warn('Deprecated "data" configuration', dataConfig);
        extracted.items = [];
      } else if (dataConfig.hierarchy) {
        extracted.root = source.hierarchy ? source.hierarchy(dataConfig.hierarchy) : null;
        extracted.fields = source.fields();
      } else if (dataConfig.items) {
        extracted.items = dataConfig.items.map(function (v) {
          return {
            value: valueFn(v),
            label: String(labelFn(v))
          };
        });
      } else if (dataConfig.extract) {
        var extractionsConfigs = Array.isArray(dataConfig.extract) ? dataConfig.extract : [dataConfig.extract];
        extracted.items = [];
        var sourceFields = [];
        extractionsConfigs.forEach(function (cfg) {
          var _extracted$items;

          var s = cfg.source ? data.dataset(cfg.source) : source;

          if (!s) {
            return;
          }

          (_extracted$items = extracted.items).push.apply(_extracted$items, _toConsumableArray$1(s.extract(cfg)));

          if (typeof cfg.field !== 'undefined') {
            sourceFields.push(s.field(cfg.field));
          }
        });

        if (sourceFields.length) {
          extracted.fields = sourceFields;
        }

        if (dataConfig.amend && Array.isArray(dataConfig.amend)) {
          var _extracted$items2;

          (_extracted$items2 = extracted.items).push.apply(_extracted$items2, _toConsumableArray$1(dataConfig.amend));
        }
      } else if (typeof dataConfig.field !== 'undefined' && source) {
        var f = source.field(dataConfig.field);

        if (f) {
          if (!extracted.fields) {
            extracted.fields = [];
          }

          extracted.fields.push(f);

          if (!('value' in dataConfig)) {
            valueFn = f.value || function (v) {
              return v;
            };

            labelFn = f.label || function (v) {
              return v;
            };

            extracted.value = valueFn;
          }

          extracted.items = f.items().map(function (v) {
            return {
              value: valueFn(v),
              label: String(labelFn(v)),
              source: {
                field: dataConfig.field
              }
            };
          }); // TODO - add source: { key: dataConfig.source, field: dataConfig.field, data: v }
        }
      } else if (dataConfig.fields) {
        dataConfig.fields.forEach(function (obj) {
          var s = _typeof(obj) === 'object' && obj.source ? data.dataset(obj.source) : source;

          if (!s) {
            return;
          }

          var f;

          if (_typeof(obj) === 'object' && typeof obj.field !== 'undefined') {
            f = s.field(obj.field);
          } else {
            f = s.field(obj);
          }

          if (f) {
            if (!extracted.fields) {
              extracted.fields = [];
            }

            extracted.fields.push(f);
          }
        });
      }

      if (extracted.items && dataConfig.map) {
        extracted.items = extracted.items.map(dataConfig.map);
      }
    }

    if (dataConfig && dataConfig.stack) {
      stacked(extracted, dataConfig.stack, data.dataset);
    }
  }

  if (dataConfig && !Array.isArray(dataConfig) && typeof dataConfig.filter === 'function' && extracted.items) {
    extracted.items = extracted.items.filter(dataConfig.filter);
  }

  if (dataConfig && !Array.isArray(dataConfig) && typeof dataConfig.sort === 'function' && extracted.items) {
    extracted.items = extracted.items.sort(dataConfig.sort);
  }

  return extracted;
}

function picasso_esm_create(config, d, opts) {
  var extractor = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : extract;
  var collections = {};
  (config || []).forEach(function (cfg) {
    if (!cfg.key) {
      throw new Error('Data collection is missing "key" property');
    }

    if (_typeof(cfg.data) === 'object' && 'collection' in cfg.data) {
      throw new Error('Data config for collections may not reference other collections');
    }

    collections[cfg.key] = function () {
      return extractor(cfg.data, d, opts);
    };
  });

  var fn = function fn(key) {
    var k;
    var cfg;

    if (typeof key === 'string') {
      k = key;
    } else if (_typeof(key) === 'object') {
      k = key.key;
      cfg = key;
    }

    if (!(k in collections)) {
      throw new Error("Unknown data collection: ".concat(k));
    }

    if (typeof collections[k] === 'function') {
      collections[k] = collections[k]();
    }

    var coll = collections[k];

    if (cfg) {
      if (cfg.fields && cfg.fields.filter) {
        var filtered = coll.fields.filter(cfg.fields.filter);

        if (coll.fields.length !== filtered.length) {
          coll = extend(coll, {
            fields: filtered
          });
        }
      }
    }

    return coll;
  };

  return fn;
}

function create$1(options, data, deps) {
  var extractor = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : extract;

  if (options.data) {
    var d = extractor(options.data, data, deps);

    if (d && d.fields && d.fields[0]) {
      // TODO Have some magic to handle and merge formatters from multiple sources
      return d.fields[0].formatter();
    }
  }

  var formatterType;

  if (options.formatter) {
    formatterType = "".concat(options.formatter, "-").concat(options.type || 'number');
  } else {
    formatterType = options.type || 'd3-number';
  }

  if (deps.formatter.has(formatterType)) {
    var f = deps.formatter.get(formatterType)(options.format || '');
    return f;
  }

  throw new Error("Formatter of type '".concat(formatterType, "' was not found"));
}
function collection(formattersConfig, data, deps) {
  var fn = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : create$1;
  var formatters = {};
  return {
    get: function get(def) {
      var key;

      if (typeof def === 'string' && formattersConfig[def]) {
        key = def;
      } else if (_typeof(def) === 'object' && 'formatter' in def && formattersConfig[def.formatter]) {
        key = def.formatter;
      } else if (_typeof(def) === 'object' && 'type' in def && formattersConfig[def.type]) {
        key = def.type;
      }

      if (key) {
        formatters[key] = formatters[key] || fn(formattersConfig[key], data, deps);
        return formatters[key];
      }

      return fn(def || {}, data, deps);
    },
    all: function all() {
      Object.keys(formattersConfig).forEach(this.get);
      return formatters;
    }
  };
}

function ascending(a, b) {
  return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

function bisector(compare) {
  if (compare.length === 1) compare = ascendingComparator(compare);
  return {
    left: function(a, x, lo, hi) {
      if (lo == null) lo = 0;
      if (hi == null) hi = a.length;
      while (lo < hi) {
        var mid = lo + hi >>> 1;
        if (compare(a[mid], x) < 0) lo = mid + 1;
        else hi = mid;
      }
      return lo;
    },
    right: function(a, x, lo, hi) {
      if (lo == null) lo = 0;
      if (hi == null) hi = a.length;
      while (lo < hi) {
        var mid = lo + hi >>> 1;
        if (compare(a[mid], x) > 0) hi = mid;
        else lo = mid + 1;
      }
      return lo;
    }
  };
}

function ascendingComparator(f) {
  return function(d, x) {
    return ascending(f(d), x);
  };
}

var ascendingBisect = bisector(ascending);
var bisectRight = ascendingBisect.right;

function sequence(start, stop, step) {
  start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;

  var i = -1,
      n = Math.max(0, Math.ceil((stop - start) / step)) | 0,
      range = new Array(n);

  while (++i < n) {
    range[i] = start + i * step;
  }

  return range;
}

var e10 = Math.sqrt(50),
    e5 = Math.sqrt(10),
    e2 = Math.sqrt(2);

function ticks(start, stop, count) {
  var reverse,
      i = -1,
      n,
      ticks,
      step;

  stop = +stop, start = +start, count = +count;
  if (start === stop && count > 0) return [start];
  if (reverse = stop < start) n = start, start = stop, stop = n;
  if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];

  if (step > 0) {
    start = Math.ceil(start / step);
    stop = Math.floor(stop / step);
    ticks = new Array(n = Math.ceil(stop - start + 1));
    while (++i < n) ticks[i] = (start + i) * step;
  } else {
    start = Math.floor(start * step);
    stop = Math.ceil(stop * step);
    ticks = new Array(n = Math.ceil(start - stop + 1));
    while (++i < n) ticks[i] = (start - i) / step;
  }

  if (reverse) ticks.reverse();

  return ticks;
}

function tickIncrement(start, stop, count) {
  var step = (stop - start) / Math.max(0, count),
      power = Math.floor(Math.log(step) / Math.LN10),
      error = step / Math.pow(10, power);
  return power >= 0
      ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)
      : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);
}

function tickStep(start, stop, count) {
  var step0 = Math.abs(stop - start) / Math.max(0, count),
      step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),
      error = step0 / step1;
  if (error >= e10) step1 *= 10;
  else if (error >= e5) step1 *= 5;
  else if (error >= e2) step1 *= 2;
  return stop < start ? -step1 : step1;
}

function initRange(domain, range) {
  switch (arguments.length) {
    case 0: break;
    case 1: this.range(domain); break;
    default: this.range(range).domain(domain); break;
  }
  return this;
}

var picasso_esm_prefix = "$";

function Map() {}

Map.prototype = map$1.prototype = {
  constructor: Map,
  has: function(key) {
    return (picasso_esm_prefix + key) in this;
  },
  get: function(key) {
    return this[picasso_esm_prefix + key];
  },
  set: function(key, value) {
    this[picasso_esm_prefix + key] = value;
    return this;
  },
  remove: function(key) {
    var property = picasso_esm_prefix + key;
    return property in this && delete this[property];
  },
  clear: function() {
    for (var property in this) if (property[0] === picasso_esm_prefix) delete this[property];
  },
  keys: function() {
    var keys = [];
    for (var property in this) if (property[0] === picasso_esm_prefix) keys.push(property.slice(1));
    return keys;
  },
  values: function() {
    var values = [];
    for (var property in this) if (property[0] === picasso_esm_prefix) values.push(this[property]);
    return values;
  },
  entries: function() {
    var entries = [];
    for (var property in this) if (property[0] === picasso_esm_prefix) entries.push({key: property.slice(1), value: this[property]});
    return entries;
  },
  size: function() {
    var size = 0;
    for (var property in this) if (property[0] === picasso_esm_prefix) ++size;
    return size;
  },
  empty: function() {
    for (var property in this) if (property[0] === picasso_esm_prefix) return false;
    return true;
  },
  each: function(f) {
    for (var property in this) if (property[0] === picasso_esm_prefix) f(this[property], property.slice(1), this);
  }
};

function map$1(object, f) {
  var map = new Map;

  // Copy constructor.
  if (object instanceof Map) object.each(function(value, key) { map.set(key, value); });

  // Index array by numeric index or specified key function.
  else if (Array.isArray(object)) {
    var i = -1,
        n = object.length,
        o;

    if (f == null) while (++i < n) map.set(i, object[i]);
    else while (++i < n) map.set(f(o = object[i], i, object), o);
  }

  // Convert object to map.
  else if (object) for (var key in object) map.set(key, object[key]);

  return map;
}

function picasso_esm_Set() {}

var proto = map$1.prototype;

picasso_esm_Set.prototype = picasso_esm_set.prototype = {
  constructor: picasso_esm_Set,
  has: proto.has,
  add: function(value) {
    value += "";
    this[picasso_esm_prefix + value] = value;
    return this;
  },
  remove: proto.remove,
  clear: proto.clear,
  values: proto.keys,
  size: proto.size,
  empty: proto.empty,
  each: proto.each
};

function picasso_esm_set(object, f) {
  var set = new picasso_esm_Set;

  // Copy constructor.
  if (object instanceof picasso_esm_Set) object.each(function(value) { set.add(value); });

  // Otherwise, assume it’s an array.
  else if (object) {
    var i = -1, n = object.length;
    if (f == null) while (++i < n) set.add(object[i]);
    else while (++i < n) set.add(f(object[i], i, object));
  }

  return set;
}

var picasso_esm_array = Array.prototype;

var map$2 = picasso_esm_array.map;
var slice$1 = picasso_esm_array.slice;

var implicit = {name: "implicit"};

function ordinal() {
  var index = map$1(),
      domain = [],
      range = [],
      unknown = implicit;

  function scale(d) {
    var key = d + "", i = index.get(key);
    if (!i) {
      if (unknown !== implicit) return unknown;
      index.set(key, i = domain.push(d));
    }
    return range[(i - 1) % range.length];
  }

  scale.domain = function(_) {
    if (!arguments.length) return domain.slice();
    domain = [], index = map$1();
    var i = -1, n = _.length, d, key;
    while (++i < n) if (!index.has(key = (d = _[i]) + "")) index.set(key, domain.push(d));
    return scale;
  };

  scale.range = function(_) {
    return arguments.length ? (range = slice$1.call(_), scale) : range.slice();
  };

  scale.unknown = function(_) {
    return arguments.length ? (unknown = _, scale) : unknown;
  };

  scale.copy = function() {
    return ordinal(domain, range).unknown(unknown);
  };

  initRange.apply(scale, arguments);

  return scale;
}

function band() {
  var scale = ordinal().unknown(undefined),
      domain = scale.domain,
      ordinalRange = scale.range,
      range = [0, 1],
      step,
      bandwidth,
      round = false,
      paddingInner = 0,
      paddingOuter = 0,
      align = 0.5;

  delete scale.unknown;

  function rescale() {
    var n = domain().length,
        reverse = range[1] < range[0],
        start = range[reverse - 0],
        stop = range[1 - reverse];
    step = (stop - start) / Math.max(1, n - paddingInner + paddingOuter * 2);
    if (round) step = Math.floor(step);
    start += (stop - start - step * (n - paddingInner)) * align;
    bandwidth = step * (1 - paddingInner);
    if (round) start = Math.round(start), bandwidth = Math.round(bandwidth);
    var values = sequence(n).map(function(i) { return start + step * i; });
    return ordinalRange(reverse ? values.reverse() : values);
  }

  scale.domain = function(_) {
    return arguments.length ? (domain(_), rescale()) : domain();
  };

  scale.range = function(_) {
    return arguments.length ? (range = [+_[0], +_[1]], rescale()) : range.slice();
  };

  scale.rangeRound = function(_) {
    return range = [+_[0], +_[1]], round = true, rescale();
  };

  scale.bandwidth = function() {
    return bandwidth;
  };

  scale.step = function() {
    return step;
  };

  scale.round = function(_) {
    return arguments.length ? (round = !!_, rescale()) : round;
  };

  scale.padding = function(_) {
    return arguments.length ? (paddingInner = Math.min(1, paddingOuter = +_), rescale()) : paddingInner;
  };

  scale.paddingInner = function(_) {
    return arguments.length ? (paddingInner = Math.min(1, _), rescale()) : paddingInner;
  };

  scale.paddingOuter = function(_) {
    return arguments.length ? (paddingOuter = +_, rescale()) : paddingOuter;
  };

  scale.align = function(_) {
    return arguments.length ? (align = Math.max(0, Math.min(1, _)), rescale()) : align;
  };

  scale.copy = function() {
    return band(domain(), range)
        .round(round)
        .paddingInner(paddingInner)
        .paddingOuter(paddingOuter)
        .align(align);
  };

  return initRange.apply(rescale(), arguments);
}

function define(constructor, factory, prototype) {
  constructor.prototype = factory.prototype = prototype;
  prototype.constructor = constructor;
}

function extend$1(parent, definition) {
  var prototype = Object.create(parent.prototype);
  for (var key in definition) prototype[key] = definition[key];
  return prototype;
}

function Color() {}

var darker = 0.7;
var brighter = 1 / darker;

var reI = "\\s*([+-]?\\d+)\\s*",
    reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",
    reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",
    reHex3 = /^#([0-9a-f]{3})$/,
    reHex6 = /^#([0-9a-f]{6})$/,
    reRgbInteger = new RegExp("^rgb\\(" + [reI, reI, reI] + "\\)$"),
    reRgbPercent = new RegExp("^rgb\\(" + [reP, reP, reP] + "\\)$"),
    reRgbaInteger = new RegExp("^rgba\\(" + [reI, reI, reI, reN] + "\\)$"),
    reRgbaPercent = new RegExp("^rgba\\(" + [reP, reP, reP, reN] + "\\)$"),
    reHslPercent = new RegExp("^hsl\\(" + [reN, reP, reP] + "\\)$"),
    reHslaPercent = new RegExp("^hsla\\(" + [reN, reP, reP, reN] + "\\)$");

var named = {
  aliceblue: 0xf0f8ff,
  antiquewhite: 0xfaebd7,
  aqua: 0x00ffff,
  aquamarine: 0x7fffd4,
  azure: 0xf0ffff,
  beige: 0xf5f5dc,
  bisque: 0xffe4c4,
  black: 0x000000,
  blanchedalmond: 0xffebcd,
  blue: 0x0000ff,
  blueviolet: 0x8a2be2,
  brown: 0xa52a2a,
  burlywood: 0xdeb887,
  cadetblue: 0x5f9ea0,
  chartreuse: 0x7fff00,
  chocolate: 0xd2691e,
  coral: 0xff7f50,
  cornflowerblue: 0x6495ed,
  cornsilk: 0xfff8dc,
  crimson: 0xdc143c,
  cyan: 0x00ffff,
  darkblue: 0x00008b,
  darkcyan: 0x008b8b,
  darkgoldenrod: 0xb8860b,
  darkgray: 0xa9a9a9,
  darkgreen: 0x006400,
  darkgrey: 0xa9a9a9,
  darkkhaki: 0xbdb76b,
  darkmagenta: 0x8b008b,
  darkolivegreen: 0x556b2f,
  darkorange: 0xff8c00,
  darkorchid: 0x9932cc,
  darkred: 0x8b0000,
  darksalmon: 0xe9967a,
  darkseagreen: 0x8fbc8f,
  darkslateblue: 0x483d8b,
  darkslategray: 0x2f4f4f,
  darkslategrey: 0x2f4f4f,
  darkturquoise: 0x00ced1,
  darkviolet: 0x9400d3,
  deeppink: 0xff1493,
  deepskyblue: 0x00bfff,
  dimgray: 0x696969,
  dimgrey: 0x696969,
  dodgerblue: 0x1e90ff,
  firebrick: 0xb22222,
  floralwhite: 0xfffaf0,
  forestgreen: 0x228b22,
  fuchsia: 0xff00ff,
  gainsboro: 0xdcdcdc,
  ghostwhite: 0xf8f8ff,
  gold: 0xffd700,
  goldenrod: 0xdaa520,
  gray: 0x808080,
  green: 0x008000,
  greenyellow: 0xadff2f,
  grey: 0x808080,
  honeydew: 0xf0fff0,
  hotpink: 0xff69b4,
  indianred: 0xcd5c5c,
  indigo: 0x4b0082,
  ivory: 0xfffff0,
  khaki: 0xf0e68c,
  lavender: 0xe6e6fa,
  lavenderblush: 0xfff0f5,
  lawngreen: 0x7cfc00,
  lemonchiffon: 0xfffacd,
  lightblue: 0xadd8e6,
  lightcoral: 0xf08080,
  lightcyan: 0xe0ffff,
  lightgoldenrodyellow: 0xfafad2,
  lightgray: 0xd3d3d3,
  lightgreen: 0x90ee90,
  lightgrey: 0xd3d3d3,
  lightpink: 0xffb6c1,
  lightsalmon: 0xffa07a,
  lightseagreen: 0x20b2aa,
  lightskyblue: 0x87cefa,
  lightslategray: 0x778899,
  lightslategrey: 0x778899,
  lightsteelblue: 0xb0c4de,
  lightyellow: 0xffffe0,
  lime: 0x00ff00,
  limegreen: 0x32cd32,
  linen: 0xfaf0e6,
  magenta: 0xff00ff,
  maroon: 0x800000,
  mediumaquamarine: 0x66cdaa,
  mediumblue: 0x0000cd,
  mediumorchid: 0xba55d3,
  mediumpurple: 0x9370db,
  mediumseagreen: 0x3cb371,
  mediumslateblue: 0x7b68ee,
  mediumspringgreen: 0x00fa9a,
  mediumturquoise: 0x48d1cc,
  mediumvioletred: 0xc71585,
  midnightblue: 0x191970,
  mintcream: 0xf5fffa,
  mistyrose: 0xffe4e1,
  moccasin: 0xffe4b5,
  navajowhite: 0xffdead,
  navy: 0x000080,
  oldlace: 0xfdf5e6,
  olive: 0x808000,
  olivedrab: 0x6b8e23,
  orange: 0xffa500,
  orangered: 0xff4500,
  orchid: 0xda70d6,
  palegoldenrod: 0xeee8aa,
  palegreen: 0x98fb98,
  paleturquoise: 0xafeeee,
  palevioletred: 0xdb7093,
  papayawhip: 0xffefd5,
  peachpuff: 0xffdab9,
  peru: 0xcd853f,
  pink: 0xffc0cb,
  plum: 0xdda0dd,
  powderblue: 0xb0e0e6,
  purple: 0x800080,
  rebeccapurple: 0x663399,
  red: 0xff0000,
  rosybrown: 0xbc8f8f,
  royalblue: 0x4169e1,
  saddlebrown: 0x8b4513,
  salmon: 0xfa8072,
  sandybrown: 0xf4a460,
  seagreen: 0x2e8b57,
  seashell: 0xfff5ee,
  sienna: 0xa0522d,
  silver: 0xc0c0c0,
  skyblue: 0x87ceeb,
  slateblue: 0x6a5acd,
  slategray: 0x708090,
  slategrey: 0x708090,
  snow: 0xfffafa,
  springgreen: 0x00ff7f,
  steelblue: 0x4682b4,
  tan: 0xd2b48c,
  teal: 0x008080,
  thistle: 0xd8bfd8,
  tomato: 0xff6347,
  turquoise: 0x40e0d0,
  violet: 0xee82ee,
  wheat: 0xf5deb3,
  white: 0xffffff,
  whitesmoke: 0xf5f5f5,
  yellow: 0xffff00,
  yellowgreen: 0x9acd32
};

define(Color, picasso_esm_color, {
  displayable: function() {
    return this.rgb().displayable();
  },
  hex: function() {
    return this.rgb().hex();
  },
  toString: function() {
    return this.rgb() + "";
  }
});

function picasso_esm_color(format) {
  var m;
  format = (format + "").trim().toLowerCase();
  return (m = reHex3.exec(format)) ? (m = parseInt(m[1], 16), new Rgb((m >> 8 & 0xf) | (m >> 4 & 0x0f0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1)) // #f00
      : (m = reHex6.exec(format)) ? rgbn(parseInt(m[1], 16)) // #ff0000
      : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
      : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
      : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
      : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
      : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
      : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
      : named.hasOwnProperty(format) ? rgbn(named[format])
      : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0)
      : null;
}

function rgbn(n) {
  return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
}

function rgba(r, g, b, a) {
  if (a <= 0) r = g = b = NaN;
  return new Rgb(r, g, b, a);
}

function rgbConvert(o) {
  if (!(o instanceof Color)) o = picasso_esm_color(o);
  if (!o) return new Rgb;
  o = o.rgb();
  return new Rgb(o.r, o.g, o.b, o.opacity);
}

function picasso_esm_rgb(r, g, b, opacity) {
  return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
}

function Rgb(r, g, b, opacity) {
  this.r = +r;
  this.g = +g;
  this.b = +b;
  this.opacity = +opacity;
}

define(Rgb, picasso_esm_rgb, extend$1(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  rgb: function() {
    return this;
  },
  displayable: function() {
    return (0 <= this.r && this.r <= 255)
        && (0 <= this.g && this.g <= 255)
        && (0 <= this.b && this.b <= 255)
        && (0 <= this.opacity && this.opacity <= 1);
  },
  hex: function() {
    return "#" + hex(this.r) + hex(this.g) + hex(this.b);
  },
  toString: function() {
    var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
    return (a === 1 ? "rgb(" : "rgba(")
        + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", "
        + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", "
        + Math.max(0, Math.min(255, Math.round(this.b) || 0))
        + (a === 1 ? ")" : ", " + a + ")");
  }
}));

function hex(value) {
  value = Math.max(0, Math.min(255, Math.round(value) || 0));
  return (value < 16 ? "0" : "") + value.toString(16);
}

function hsla(h, s, l, a) {
  if (a <= 0) h = s = l = NaN;
  else if (l <= 0 || l >= 1) h = s = NaN;
  else if (s <= 0) h = NaN;
  return new Hsl(h, s, l, a);
}

function hslConvert(o) {
  if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Color)) o = picasso_esm_color(o);
  if (!o) return new Hsl;
  if (o instanceof Hsl) return o;
  o = o.rgb();
  var r = o.r / 255,
      g = o.g / 255,
      b = o.b / 255,
      min = Math.min(r, g, b),
      max = Math.max(r, g, b),
      h = NaN,
      s = max - min,
      l = (max + min) / 2;
  if (s) {
    if (r === max) h = (g - b) / s + (g < b) * 6;
    else if (g === max) h = (b - r) / s + 2;
    else h = (r - g) / s + 4;
    s /= l < 0.5 ? max + min : 2 - max - min;
    h *= 60;
  } else {
    s = l > 0 && l < 1 ? 0 : h;
  }
  return new Hsl(h, s, l, o.opacity);
}

function hsl(h, s, l, opacity) {
  return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
}

function Hsl(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}

define(Hsl, hsl, extend$1(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  rgb: function() {
    var h = this.h % 360 + (this.h < 0) * 360,
        s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
        l = this.l,
        m2 = l + (l < 0.5 ? l : 1 - l) * s,
        m1 = 2 * l - m2;
    return new Rgb(
      hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
      hsl2rgb(h, m1, m2),
      hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
      this.opacity
    );
  },
  displayable: function() {
    return (0 <= this.s && this.s <= 1 || isNaN(this.s))
        && (0 <= this.l && this.l <= 1)
        && (0 <= this.opacity && this.opacity <= 1);
  }
}));

/* From FvD 13.37, CSS Color Module Level 3 */
function hsl2rgb(h, m1, m2) {
  return (h < 60 ? m1 + (m2 - m1) * h / 60
      : h < 180 ? m2
      : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60
      : m1) * 255;
}

var deg2rad = Math.PI / 180;
var rad2deg = 180 / Math.PI;

// https://beta.observablehq.com/@mbostock/lab-and-rgb
var K = 18,
    Xn = 0.96422,
    Yn = 1,
    Zn = 0.82521,
    t0$1 = 4 / 29,
    t1$1 = 6 / 29,
    picasso_esm_t2 = 3 * t1$1 * t1$1,
    picasso_esm_t3 = t1$1 * t1$1 * t1$1;

function labConvert(o) {
  if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);
  if (o instanceof Hcl) {
    if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity);
    var h = o.h * deg2rad;
    return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
  }
  if (!(o instanceof Rgb)) o = rgbConvert(o);
  var r = rgb2lrgb(o.r),
      g = rgb2lrgb(o.g),
      b = rgb2lrgb(o.b),
      y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x, z;
  if (r === g && g === b) x = z = y; else {
    x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);
    z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);
  }
  return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);
}

function lab(l, a, b, opacity) {
  return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);
}

function Lab(l, a, b, opacity) {
  this.l = +l;
  this.a = +a;
  this.b = +b;
  this.opacity = +opacity;
}

define(Lab, lab, extend$1(Color, {
  brighter: function(k) {
    return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  darker: function(k) {
    return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  rgb: function() {
    var y = (this.l + 16) / 116,
        x = isNaN(this.a) ? y : y + this.a / 500,
        z = isNaN(this.b) ? y : y - this.b / 200;
    x = Xn * lab2xyz(x);
    y = Yn * lab2xyz(y);
    z = Zn * lab2xyz(z);
    return new Rgb(
      lrgb2rgb( 3.1338561 * x - 1.6168667 * y - 0.4906146 * z),
      lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z),
      lrgb2rgb( 0.0719453 * x - 0.2289914 * y + 1.4052427 * z),
      this.opacity
    );
  }
}));

function xyz2lab(t) {
  return t > picasso_esm_t3 ? Math.pow(t, 1 / 3) : t / picasso_esm_t2 + t0$1;
}

function lab2xyz(t) {
  return t > t1$1 ? t * t * t : picasso_esm_t2 * (t - t0$1);
}

function lrgb2rgb(x) {
  return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
}

function rgb2lrgb(x) {
  return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
}

function hclConvert(o) {
  if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);
  if (!(o instanceof Lab)) o = labConvert(o);
  if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0, o.l, o.opacity);
  var h = Math.atan2(o.b, o.a) * rad2deg;
  return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
}

function hcl(h, c, l, opacity) {
  return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
}

function Hcl(h, c, l, opacity) {
  this.h = +h;
  this.c = +c;
  this.l = +l;
  this.opacity = +opacity;
}

define(Hcl, hcl, extend$1(Color, {
  brighter: function(k) {
    return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);
  },
  darker: function(k) {
    return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);
  },
  rgb: function() {
    return labConvert(this).rgb();
  }
}));

var A = -0.14861,
    B = +1.78277,
    C = -0.29227,
    D = -0.90649,
    E = +1.97294,
    ED = E * D,
    EB = E * B,
    BC_DA = B * C - D * A;

function cubehelixConvert(o) {
  if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Rgb)) o = rgbConvert(o);
  var r = o.r / 255,
      g = o.g / 255,
      b = o.b / 255,
      l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB),
      bl = b - l,
      k = (E * (g - l) - C * bl) / D,
      s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1
      h = s ? Math.atan2(k, bl) * rad2deg - 120 : NaN;
  return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);
}

function cubehelix(h, s, l, opacity) {
  return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity);
}

function Cubehelix(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}

define(Cubehelix, cubehelix, extend$1(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
  },
  rgb: function() {
    var h = isNaN(this.h) ? 0 : (this.h + 120) * deg2rad,
        l = +this.l,
        a = isNaN(this.s) ? 0 : this.s * l * (1 - l),
        cosh = Math.cos(h),
        sinh = Math.sin(h);
    return new Rgb(
      255 * (l + a * (A * cosh + B * sinh)),
      255 * (l + a * (C * cosh + D * sinh)),
      255 * (l + a * (E * cosh)),
      this.opacity
    );
  }
}));

function constant$1(x) {
  return function() {
    return x;
  };
}

function linear(a, d) {
  return function(t) {
    return a + t * d;
  };
}

function exponential(a, b, y) {
  return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {
    return Math.pow(a + t * b, y);
  };
}

function gamma(y) {
  return (y = +y) === 1 ? nogamma : function(a, b) {
    return b - a ? exponential(a, b, y) : constant$1(isNaN(a) ? b : a);
  };
}

function nogamma(a, b) {
  var d = b - a;
  return d ? linear(a, d) : constant$1(isNaN(a) ? b : a);
}

var interpolateRgb = (function rgbGamma(y) {
  var color = gamma(y);

  function rgb$1(start, end) {
    var r = color((start = picasso_esm_rgb(start)).r, (end = picasso_esm_rgb(end)).r),
        g = color(start.g, end.g),
        b = color(start.b, end.b),
        opacity = nogamma(start.opacity, end.opacity);
    return function(t) {
      start.r = r(t);
      start.g = g(t);
      start.b = b(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }

  rgb$1.gamma = rgbGamma;

  return rgb$1;
})(1);

function array$1(a, b) {
  var nb = b ? b.length : 0,
      na = a ? Math.min(nb, a.length) : 0,
      x = new Array(na),
      c = new Array(nb),
      i;

  for (i = 0; i < na; ++i) x[i] = interpolateValue(a[i], b[i]);
  for (; i < nb; ++i) c[i] = b[i];

  return function(t) {
    for (i = 0; i < na; ++i) c[i] = x[i](t);
    return c;
  };
}

function date(a, b) {
  var d = new Date;
  return a = +a, b -= a, function(t) {
    return d.setTime(a + b * t), d;
  };
}

function interpolateNumber(a, b) {
  return a = +a, b -= a, function(t) {
    return a + b * t;
  };
}

function interpolateObject(a, b) {
  var i = {},
      c = {},
      k;

  if (a === null || typeof a !== "object") a = {};
  if (b === null || typeof b !== "object") b = {};

  for (k in b) {
    if (k in a) {
      i[k] = interpolateValue(a[k], b[k]);
    } else {
      c[k] = b[k];
    }
  }

  return function(t) {
    for (k in i) c[k] = i[k](t);
    return c;
  };
}

var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,
    reB = new RegExp(reA.source, "g");

function picasso_esm_zero(b) {
  return function() {
    return b;
  };
}

function one(b) {
  return function(t) {
    return b(t) + "";
  };
}

function string(a, b) {
  var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b
      am, // current match in a
      bm, // current match in b
      bs, // string preceding current number in b, if any
      i = -1, // index in s
      s = [], // string constants and placeholders
      q = []; // number interpolators

  // Coerce inputs to strings.
  a = a + "", b = b + "";

  // Interpolate pairs of numbers in a & b.
  while ((am = reA.exec(a))
      && (bm = reB.exec(b))) {
    if ((bs = bm.index) > bi) { // a string precedes the next number in b
      bs = b.slice(bi, bs);
      if (s[i]) s[i] += bs; // coalesce with previous string
      else s[++i] = bs;
    }
    if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match
      if (s[i]) s[i] += bm; // coalesce with previous string
      else s[++i] = bm;
    } else { // interpolate non-matching numbers
      s[++i] = null;
      q.push({i: i, x: interpolateNumber(am, bm)});
    }
    bi = reB.lastIndex;
  }

  // Add remains of b.
  if (bi < b.length) {
    bs = b.slice(bi);
    if (s[i]) s[i] += bs; // coalesce with previous string
    else s[++i] = bs;
  }

  // Special optimization for only a single match.
  // Otherwise, interpolate each of the numbers and rejoin the string.
  return s.length < 2 ? (q[0]
      ? one(q[0].x)
      : picasso_esm_zero(b))
      : (b = q.length, function(t) {
          for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
          return s.join("");
        });
}

function interpolateValue(a, b) {
  var t = typeof b, c;
  return b == null || t === "boolean" ? constant$1(b)
      : (t === "number" ? interpolateNumber
      : t === "string" ? ((c = picasso_esm_color(b)) ? (b = c, interpolateRgb) : string)
      : b instanceof picasso_esm_color ? interpolateRgb
      : b instanceof Date ? date
      : Array.isArray(b) ? array$1
      : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? interpolateObject
      : interpolateNumber)(a, b);
}

function interpolateRound(a, b) {
  return a = +a, b -= a, function(t) {
    return Math.round(a + b * t);
  };
}

function constant$2(x) {
  return function() {
    return x;
  };
}

function number(x) {
  return +x;
}

var picasso_esm_unit = [0, 1];

function identity$2(x) {
  return x;
}

function picasso_esm_normalize(a, b) {
  return (b -= (a = +a))
      ? function(x) { return (x - a) / b; }
      : constant$2(isNaN(b) ? NaN : 0.5);
}

function clamper(domain) {
  var a = domain[0], b = domain[domain.length - 1], t;
  if (a > b) t = a, a = b, b = t;
  return function(x) { return Math.max(a, Math.min(b, x)); };
}

// normalize(a, b)(x) takes a domain value x in [a,b] and returns the corresponding parameter t in [0,1].
// interpolate(a, b)(t) takes a parameter t in [0,1] and returns the corresponding range value x in [a,b].
function bimap(domain, range, interpolate) {
  var d0 = domain[0], d1 = domain[1], r0 = range[0], r1 = range[1];
  if (d1 < d0) d0 = picasso_esm_normalize(d1, d0), r0 = interpolate(r1, r0);
  else d0 = picasso_esm_normalize(d0, d1), r0 = interpolate(r0, r1);
  return function(x) { return r0(d0(x)); };
}

function polymap(domain, range, interpolate) {
  var j = Math.min(domain.length, range.length) - 1,
      d = new Array(j),
      r = new Array(j),
      i = -1;

  // Reverse descending domains.
  if (domain[j] < domain[0]) {
    domain = domain.slice().reverse();
    range = range.slice().reverse();
  }

  while (++i < j) {
    d[i] = picasso_esm_normalize(domain[i], domain[i + 1]);
    r[i] = interpolate(range[i], range[i + 1]);
  }

  return function(x) {
    var i = bisectRight(domain, x, 1, j) - 1;
    return r[i](d[i](x));
  };
}

function copy(source, target) {
  return target
      .domain(source.domain())
      .range(source.range())
      .interpolate(source.interpolate())
      .clamp(source.clamp())
      .unknown(source.unknown());
}

function transformer() {
  var domain = picasso_esm_unit,
      range = picasso_esm_unit,
      interpolate = interpolateValue,
      transform,
      untransform,
      unknown,
      clamp = identity$2,
      piecewise,
      output,
      input;

  function rescale() {
    piecewise = Math.min(domain.length, range.length) > 2 ? polymap : bimap;
    output = input = null;
    return scale;
  }

  function scale(x) {
    return isNaN(x = +x) ? unknown : (output || (output = piecewise(domain.map(transform), range, interpolate)))(transform(clamp(x)));
  }

  scale.invert = function(y) {
    return clamp(untransform((input || (input = piecewise(range, domain.map(transform), interpolateNumber)))(y)));
  };

  scale.domain = function(_) {
    return arguments.length ? (domain = map$2.call(_, number), clamp === identity$2 || (clamp = clamper(domain)), rescale()) : domain.slice();
  };

  scale.range = function(_) {
    return arguments.length ? (range = slice$1.call(_), rescale()) : range.slice();
  };

  scale.rangeRound = function(_) {
    return range = slice$1.call(_), interpolate = interpolateRound, rescale();
  };

  scale.clamp = function(_) {
    return arguments.length ? (clamp = _ ? clamper(domain) : identity$2, scale) : clamp !== identity$2;
  };

  scale.interpolate = function(_) {
    return arguments.length ? (interpolate = _, rescale()) : interpolate;
  };

  scale.unknown = function(_) {
    return arguments.length ? (unknown = _, scale) : unknown;
  };

  return function(t, u) {
    transform = t, untransform = u;
    return rescale();
  };
}

function continuous(transform, untransform) {
  return transformer()(transform, untransform);
}

// Computes the decimal coefficient and exponent of the specified number x with
// significant digits p, where x is positive and p is in [1, 21] or undefined.
// For example, formatDecimal(1.23) returns ["123", 0].
function formatDecimal$1(x, p) {
  if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; // NaN, ±Infinity
  var i, coefficient = x.slice(0, i);

  // The string returned by toExponential either has the form \d\.\d+e[-+]\d+
  // (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3).
  return [
    coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
    +x.slice(i + 1)
  ];
}

function exponent$1(x) {
  return x = formatDecimal$1(Math.abs(x)), x ? x[1] : NaN;
}

function formatGroup$1(grouping, thousands) {
  return function(value, width) {
    var i = value.length,
        t = [],
        j = 0,
        g = grouping[0],
        length = 0;

    while (i > 0 && g > 0) {
      if (length + g + 1 > width) g = Math.max(1, width - length);
      t.push(value.substring(i -= g, i + g));
      if ((length += g + 1) > width) break;
      g = grouping[j = (j + 1) % grouping.length];
    }

    return t.reverse().join(thousands);
  };
}

function formatNumerals$1(numerals) {
  return function(value) {
    return value.replace(/[0-9]/g, function(i) {
      return numerals[+i];
    });
  };
}

// [[fill]align][sign][symbol][0][width][,][.precision][~][type]
var re$1 = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;

function formatSpecifier$1(specifier) {
  return new FormatSpecifier$1(specifier);
}

formatSpecifier$1.prototype = FormatSpecifier$1.prototype; // instanceof

function FormatSpecifier$1(specifier) {
  if (!(match = re$1.exec(specifier))) throw new Error("invalid format: " + specifier);
  var match;
  this.fill = match[1] || " ";
  this.align = match[2] || ">";
  this.sign = match[3] || "-";
  this.symbol = match[4] || "";
  this.zero = !!match[5];
  this.width = match[6] && +match[6];
  this.comma = !!match[7];
  this.precision = match[8] && +match[8].slice(1);
  this.trim = !!match[9];
  this.type = match[10] || "";
}

FormatSpecifier$1.prototype.toString = function() {
  return this.fill
      + this.align
      + this.sign
      + this.symbol
      + (this.zero ? "0" : "")
      + (this.width == null ? "" : Math.max(1, this.width | 0))
      + (this.comma ? "," : "")
      + (this.precision == null ? "" : "." + Math.max(0, this.precision | 0))
      + (this.trim ? "~" : "")
      + this.type;
};

// Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.
function formatTrim$1(s) {
  out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
    switch (s[i]) {
      case ".": i0 = i1 = i; break;
      case "0": if (i0 === 0) i0 = i; i1 = i; break;
      default: if (i0 > 0) { if (!+s[i]) break out; i0 = 0; } break;
    }
  }
  return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
}

var prefixExponent$1;

function formatPrefixAuto$1(x, p) {
  var d = formatDecimal$1(x, p);
  if (!d) return x + "";
  var coefficient = d[0],
      exponent = d[1],
      i = exponent - (prefixExponent$1 = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,
      n = coefficient.length;
  return i === n ? coefficient
      : i > n ? coefficient + new Array(i - n + 1).join("0")
      : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i)
      : "0." + new Array(1 - i).join("0") + formatDecimal$1(x, Math.max(0, p + i - 1))[0]; // less than 1y!
}

function formatRounded$1(x, p) {
  var d = formatDecimal$1(x, p);
  if (!d) return x + "";
  var coefficient = d[0],
      exponent = d[1];
  return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient
      : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1)
      : coefficient + new Array(exponent - coefficient.length + 2).join("0");
}

var formatTypes$1 = {
  "%": function(x, p) { return (x * 100).toFixed(p); },
  "b": function(x) { return Math.round(x).toString(2); },
  "c": function(x) { return x + ""; },
  "d": function(x) { return Math.round(x).toString(10); },
  "e": function(x, p) { return x.toExponential(p); },
  "f": function(x, p) { return x.toFixed(p); },
  "g": function(x, p) { return x.toPrecision(p); },
  "o": function(x) { return Math.round(x).toString(8); },
  "p": function(x, p) { return formatRounded$1(x * 100, p); },
  "r": formatRounded$1,
  "s": formatPrefixAuto$1,
  "X": function(x) { return Math.round(x).toString(16).toUpperCase(); },
  "x": function(x) { return Math.round(x).toString(16); }
};

function identity$3(x) {
  return x;
}

var prefixes$1 = ["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];

function formatLocale$2(locale) {
  var group = locale.grouping && locale.thousands ? formatGroup$1(locale.grouping, locale.thousands) : identity$3,
      currency = locale.currency,
      decimal = locale.decimal,
      numerals = locale.numerals ? formatNumerals$1(locale.numerals) : identity$3,
      percent = locale.percent || "%";

  function newFormat(specifier) {
    specifier = formatSpecifier$1(specifier);

    var fill = specifier.fill,
        align = specifier.align,
        sign = specifier.sign,
        symbol = specifier.symbol,
        zero = specifier.zero,
        width = specifier.width,
        comma = specifier.comma,
        precision = specifier.precision,
        trim = specifier.trim,
        type = specifier.type;

    // The "n" type is an alias for ",g".
    if (type === "n") comma = true, type = "g";

    // The "" type, and any invalid type, is an alias for ".12~g".
    else if (!formatTypes$1[type]) precision == null && (precision = 12), trim = true, type = "g";

    // If zero fill is specified, padding goes after sign and before digits.
    if (zero || (fill === "0" && align === "=")) zero = true, fill = "0", align = "=";

    // Compute the prefix and suffix.
    // For SI-prefix, the suffix is lazily computed.
    var prefix = symbol === "$" ? currency[0] : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "",
        suffix = symbol === "$" ? currency[1] : /[%p]/.test(type) ? percent : "";

    // What format function should we use?
    // Is this an integer type?
    // Can this type generate exponential notation?
    var formatType = formatTypes$1[type],
        maybeSuffix = /[defgprs%]/.test(type);

    // Set the default precision if not specified,
    // or clamp the specified precision to the supported range.
    // For significant precision, it must be in [1, 21].
    // For fixed precision, it must be in [0, 20].
    precision = precision == null ? 6
        : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))
        : Math.max(0, Math.min(20, precision));

    function format(value) {
      var valuePrefix = prefix,
          valueSuffix = suffix,
          i, n, c;

      if (type === "c") {
        valueSuffix = formatType(value) + valueSuffix;
        value = "";
      } else {
        value = +value;

        // Perform the initial formatting.
        var valueNegative = value < 0;
        value = formatType(Math.abs(value), precision);

        // Trim insignificant zeros.
        if (trim) value = formatTrim$1(value);

        // If a negative value rounds to zero during formatting, treat as positive.
        if (valueNegative && +value === 0) valueNegative = false;

        // Compute the prefix and suffix.
        valuePrefix = (valueNegative ? (sign === "(" ? sign : "-") : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
        valueSuffix = (type === "s" ? prefixes$1[8 + prefixExponent$1 / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");

        // Break the formatted value into the integer “value” part that can be
        // grouped, and fractional or exponential “suffix” part that is not.
        if (maybeSuffix) {
          i = -1, n = value.length;
          while (++i < n) {
            if (c = value.charCodeAt(i), 48 > c || c > 57) {
              valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
              value = value.slice(0, i);
              break;
            }
          }
        }
      }

      // If the fill character is not "0", grouping is applied before padding.
      if (comma && !zero) value = group(value, Infinity);

      // Compute the padding.
      var length = valuePrefix.length + value.length + valueSuffix.length,
          padding = length < width ? new Array(width - length + 1).join(fill) : "";

      // If the fill character is "0", grouping is applied after padding.
      if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";

      // Reconstruct the final output based on the desired alignment.
      switch (align) {
        case "<": value = valuePrefix + value + valueSuffix + padding; break;
        case "=": value = valuePrefix + padding + value + valueSuffix; break;
        case "^": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;
        default: value = padding + valuePrefix + value + valueSuffix; break;
      }

      return numerals(value);
    }

    format.toString = function() {
      return specifier + "";
    };

    return format;
  }

  function formatPrefix(specifier, value) {
    var f = newFormat((specifier = formatSpecifier$1(specifier), specifier.type = "f", specifier)),
        e = Math.max(-8, Math.min(8, Math.floor(exponent$1(value) / 3))) * 3,
        k = Math.pow(10, -e),
        prefix = prefixes$1[8 + e / 3];
    return function(value) {
      return f(k * value) + prefix;
    };
  }

  return {
    format: newFormat,
    formatPrefix: formatPrefix
  };
}

var locale$2;
var format$1;
var formatPrefix$1;

defaultLocale$2({
  decimal: ".",
  thousands: ",",
  grouping: [3],
  currency: ["$", ""]
});

function defaultLocale$2(definition) {
  locale$2 = formatLocale$2(definition);
  format$1 = locale$2.format;
  formatPrefix$1 = locale$2.formatPrefix;
  return locale$2;
}

function precisionFixed(step) {
  return Math.max(0, -exponent$1(Math.abs(step)));
}

function precisionPrefix(step, value) {
  return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent$1(value) / 3))) * 3 - exponent$1(Math.abs(step)));
}

function precisionRound(step, max) {
  step = Math.abs(step), max = Math.abs(max) - step;
  return Math.max(0, exponent$1(max) - exponent$1(step)) + 1;
}

function tickFormat(start, stop, count, specifier) {
  var step = tickStep(start, stop, count),
      precision;
  specifier = formatSpecifier$1(specifier == null ? ",f" : specifier);
  switch (specifier.type) {
    case "s": {
      var value = Math.max(Math.abs(start), Math.abs(stop));
      if (specifier.precision == null && !isNaN(precision = precisionPrefix(step, value))) specifier.precision = precision;
      return formatPrefix$1(specifier, value);
    }
    case "":
    case "e":
    case "g":
    case "p":
    case "r": {
      if (specifier.precision == null && !isNaN(precision = precisionRound(step, Math.max(Math.abs(start), Math.abs(stop))))) specifier.precision = precision - (specifier.type === "e");
      break;
    }
    case "f":
    case "%": {
      if (specifier.precision == null && !isNaN(precision = precisionFixed(step))) specifier.precision = precision - (specifier.type === "%") * 2;
      break;
    }
  }
  return format$1(specifier);
}

function linearish(scale) {
  var domain = scale.domain;

  scale.ticks = function(count) {
    var d = domain();
    return ticks(d[0], d[d.length - 1], count == null ? 10 : count);
  };

  scale.tickFormat = function(count, specifier) {
    var d = domain();
    return tickFormat(d[0], d[d.length - 1], count == null ? 10 : count, specifier);
  };

  scale.nice = function(count) {
    if (count == null) count = 10;

    var d = domain(),
        i0 = 0,
        i1 = d.length - 1,
        start = d[i0],
        stop = d[i1],
        step;

    if (stop < start) {
      step = start, start = stop, stop = step;
      step = i0, i0 = i1, i1 = step;
    }

    step = tickIncrement(start, stop, count);

    if (step > 0) {
      start = Math.floor(start / step) * step;
      stop = Math.ceil(stop / step) * step;
      step = tickIncrement(start, stop, count);
    } else if (step < 0) {
      start = Math.ceil(start * step) / step;
      stop = Math.floor(stop * step) / step;
      step = tickIncrement(start, stop, count);
    }

    if (step > 0) {
      d[i0] = Math.floor(start / step) * step;
      d[i1] = Math.ceil(stop / step) * step;
      domain(d);
    } else if (step < 0) {
      d[i0] = Math.ceil(start * step) / step;
      d[i1] = Math.floor(stop * step) / step;
      domain(d);
    }

    return scale;
  };

  return scale;
}

function linear$1() {
  var scale = continuous(identity$2, identity$2);

  scale.copy = function() {
    return copy(scale, linear$1());
  };

  initRange.apply(scale, arguments);

  return linearish(scale);
}

function threshold() {
  var domain = [0.5],
      range = [0, 1],
      unknown,
      n = 1;

  function scale(x) {
    return x <= x ? range[bisectRight(domain, x, 0, n)] : unknown;
  }

  scale.domain = function(_) {
    return arguments.length ? (domain = slice$1.call(_), n = Math.min(domain.length, range.length - 1), scale) : domain.slice();
  };

  scale.range = function(_) {
    return arguments.length ? (range = slice$1.call(_), n = Math.min(domain.length, range.length - 1), scale) : range.slice();
  };

  scale.invertExtent = function(y) {
    var i = range.indexOf(y);
    return [domain[i - 1], domain[i]];
  };

  scale.unknown = function(_) {
    return arguments.length ? (unknown = _, scale) : unknown;
  };

  scale.copy = function() {
    return threshold()
        .domain(domain)
        .range(range)
        .unknown(unknown);
  };

  return initRange.apply(scale, arguments);
}

function applyFormat(formatter) {
  return typeof formatter === 'undefined' ? function (t) {
    return t;
  } : function (t) {
    return formatter(t);
  };
}

function picasso_esm_clamp(val) {
  return Math.max(0, Math.min(1, val));
}

function isObject(obj) {
  return _typeof(obj) === 'object';
}

function minorTicksGenerator(count, start, end) {
  var r = Math.abs(start - end);
  var interval = r / (count + 1);
  var ticks = [];

  for (var i = 1; i <= count; i++) {
    var v = i * interval;
    ticks.push(start < end ? start + v : start - v);
  }

  return ticks;
}

function appendMinorTicks(majorTicks, minorCount, scale) {
  if (majorTicks.length === 1) {
    return majorTicks;
  }

  var ticks = majorTicks.concat([]);

  for (var i = 0; i < majorTicks.length; i++) {
    var start = majorTicks[i];
    var end = majorTicks[i + 1];

    if (i === 0 && start !== scale.start()) {
      // Before and after first major tick
      ticks.push.apply(ticks, _toConsumableArray$1(minorTicksGenerator(minorCount, start, end)));
      start -= end - start;
      end = majorTicks[i];
      ticks.push.apply(ticks, _toConsumableArray$1(minorTicksGenerator(minorCount, start, end)));
    } else if (i === majorTicks.length - 1 && end !== scale.end()) {
      // After last major tick
      end = start + (start - majorTicks[i - 1]);
      ticks.push.apply(ticks, _toConsumableArray$1(minorTicksGenerator(minorCount, start, end)));
    } else {
      ticks.push.apply(ticks, _toConsumableArray$1(minorTicksGenerator(minorCount, start, end)));
    }
  }

  return ticks.filter(function (t) {
    return t >= scale.min() && t <= scale.max();
  });
}
/**
* Generate ticks based on a distance, for each 100th unit, one additional tick may be added
* @private
* @param  {Number} distance       Distance between each tick
* @param  {Number} scale         The scale instance
* @param  {Number} [minorCount=0]     Number of tick added between each distance
* @param  {Number} [unitDivider=100]   Number to divide distance with
* @return {Array}               Array of ticks
*/


function looseDistanceBasedGenerator(_ref) {
  var distance = _ref.distance,
      scale = _ref.scale,
      _ref$minorCount = _ref.minorCount,
      minorCount = _ref$minorCount === void 0 ? 0 : _ref$minorCount,
      _ref$unitDivider = _ref.unitDivider,
      unitDivider = _ref$unitDivider === void 0 ? 100 : _ref$unitDivider,
      _ref$formatter = _ref.formatter,
      formatter = _ref$formatter === void 0 ? undefined : _ref$formatter;
  var step = !notNumber(unitDivider) && !notNumber(distance) ? Math.max(distance / unitDivider, 2) : 2;
  var count = Math.min(1000, Math.round(step)); // safe guard against huge numbers

  var majorTicks = scale.ticks(count);

  if (majorTicks.length <= 1) {
    majorTicks = scale.ticks(count + 1);
  }

  var ticks = minorCount > 0 ? appendMinorTicks(majorTicks, minorCount, scale) : majorTicks;
  ticks.sort(function (a, b) {
    return a - b;
  });
  var ticksFormatted = ticks.map(applyFormat(formatter));
  return ticks.map(function (tick, i) {
    var position = scale(tick);
    return {
      position: position,
      start: position,
      end: position,
      label: ticksFormatted[i],
      value: tick,
      isMinor: majorTicks.indexOf(tick) === -1
    };
  });
}
/**
* Generate ticks based on a distance, for each 100th unit, one additional tick may be added.
* Will attempt to round the bounds of domain to even values and generate ticks hitting the domain bounds.
* @private
* @param  {Number} distance       Distance between each tick
* @param  {Number} scale         The scale instance
* @param  {Number} [minorCount=0]     Number of tick added between each distance
* @param  {Number} [unitDivider=100]   Number to divide distance with
* @return {Array}               Array of ticks
*/

function tightDistanceBasedGenerator(_ref2) {
  var distance = _ref2.distance,
      scale = _ref2.scale,
      _ref2$minorCount = _ref2.minorCount,
      minorCount = _ref2$minorCount === void 0 ? 0 : _ref2$minorCount,
      _ref2$unitDivider = _ref2.unitDivider,
      unitDivider = _ref2$unitDivider === void 0 ? 100 : _ref2$unitDivider,
      _ref2$formatter = _ref2.formatter,
      formatter = _ref2$formatter === void 0 ? undefined : _ref2$formatter;
  var step = !notNumber(unitDivider) && !notNumber(distance) ? Math.max(distance / unitDivider, 2) : 2;
  var count = Math.min(1000, Math.round(step)); // safe guard against huge numbers

  var n = count > 10 ? 10 : count;
  scale.nice(n);
  var majorTicks = scale.ticks(count);
  var ticks = minorCount > 0 ? appendMinorTicks(majorTicks, minorCount, scale) : majorTicks;
  ticks.sort(function (a, b) {
    return a - b;
  });
  var ticksFormatted = ticks.map(applyFormat(formatter));
  return ticks.map(function (tick, i) {
    var position = scale(tick);
    return {
      position: position,
      start: position,
      end: position,
      label: ticksFormatted[i],
      value: tick,
      isMinor: majorTicks.indexOf(tick) === -1
    };
  });
}

function ticksByCount(_ref3) {
  var count = _ref3.count,
      minorCount = _ref3.minorCount,
      scale = _ref3.scale,
      formatter = _ref3.formatter;
  return scale.ticks((count - 1) * minorCount + count).map(function (tick, i) {
    var position = scale(tick);
    return {
      position: position,
      start: position,
      end: position,
      label: formatter(tick),
      isMinor: i % (minorCount + 1) !== 0,
      value: tick
    };
  });
}

function ticksByValue(_ref4) {
  var values = _ref4.values,
      scale = _ref4.scale,
      _ref4$formatter = _ref4.formatter,
      formatter = _ref4$formatter === void 0 ? function (v) {
    return v;
  } : _ref4$formatter;
  return values.sort(function (a, b) {
    return (isObject(a) ? a.value : a) - (isObject(b) ? b.value : b);
  }).filter(function (v, i, ary) {
    var val = isObject(v) ? v.value : v;
    return val <= scale.max() && val >= scale.min() && ary.indexOf(v) === i;
  }).map(function (v) {
    var isObj = isObject(v);
    var value = isObj ? v.value : v;
    var position = scale(value);
    return {
      position: position,
      value: value,
      label: isObj && typeof v.label !== 'undefined' ? v.label : formatter(value),
      isMinor: isObj ? !!v.isMinor : false,
      start: isObj && !isNaN(v.start) ? picasso_esm_clamp(scale(v.start)) : position,
      // TODOHandle end < start?
      end: isObj && !isNaN(v.end) ? picasso_esm_clamp(scale(v.end)) : position // TODO Handle start > end?

    };
  });
}

function forceTicksAtBounds(ticks, scale, formatter) {
  var ticksP = ticks.map(function (t) {
    return t.position;
  });
  var range = scale.range();

  if (ticksP.indexOf(range[0]) === -1) {
    ticks.splice(0, 0, {
      position: range[0],
      start: range[0],
      end: range[0],
      label: formatter(scale.start()),
      isMinor: false,
      value: scale.start()
    });
  } else if (ticks[0] && ticks[0].isMinor) {
    ticks[0].isMinor = false; // Convert to major tick
  }

  var lastTick = ticks[ticks.length - 1];

  if (ticksP.indexOf(range[1]) === -1) {
    ticks.push({
      position: range[1],
      start: range[1],
      end: range[1],
      label: formatter(scale.end()),
      isMinor: false,
      value: scale.end()
    });
  } else if (lastTick && lastTick.isMinor) {
    lastTick.isMinor = false; // Convert to major tick
  }
}

function generateContinuousTicks(_ref5) {
  var settings = _ref5.settings,
      scale = _ref5.scale,
      distance = _ref5.distance,
      _ref5$formatter = _ref5.formatter,
      formatter = _ref5$formatter === void 0 ? function (val) {
    return val;
  } : _ref5$formatter;
  var ticks;
  var minorCount = settings.minorTicks && !notNumber(settings.minorTicks.count) ? Math.min(100, settings.minorTicks.count) : 0;

  if (Array.isArray(settings.ticks.values)) {
    var values = settings.ticks.values.filter(function (v) {
      return _typeof(v) === 'object' ? !notNumber(v.value) : !notNumber(v);
    });
    ticks = ticksByValue({
      values: values,
      scale: scale.copy(),
      formatter: formatter
    });
  } else if (!notNumber(settings.ticks.count)) {
    var count = Math.min(1000, settings.ticks.count);
    ticks = ticksByCount({
      count: count,
      minorCount: minorCount,
      scale: scale.copy(),
      formatter: formatter
    });
  } else {
    var tickGen = settings.ticks.tight ? tightDistanceBasedGenerator : looseDistanceBasedGenerator;
    ticks = tickGen({
      distance: distance,
      minorCount: minorCount,
      unitDivider: settings.ticks.distance,
      scale: scale,
      formatter: formatter
    });

    if (settings.ticks.forceBounds) {
      forceTicksAtBounds(ticks, scale, formatter);
    }
  }

  return ticks;
}
function generateDiscreteTicks(_ref6) {
  var scale = _ref6.scale;
  var domain = scale.domain();
  var values = domain;
  var dataItems = scale.data().items;
  var labels = scale.labels ? scale.labels() : values;
  var bandwidth = scale.bandwidth();
  return values.map(function (d, i) {
    var start = scale(d);
    return {
      position: start + bandwidth / 2,
      label: "".concat(labels[i]),
      data: dataItems ? dataItems[i] : undefined,
      start: start,
      end: start + bandwidth
    };
  });
}

function resolveSettings$1() {
  var settings = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var defaultSettings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var stngs = {};
  Object.keys(defaultSettings).forEach(function (key) {
    var type = _typeof(settings[key]);

    if (type === 'function') {
      stngs[key] = settings[key](context);
    } else if (type === 'undefined') {
      stngs[key] = defaultSettings[key];
    } else {
      stngs[key] = settings[key];
    }
  });
  return stngs;
}

var DEFAULT_SETTINGS = {
  min: NaN,
  max: NaN,
  expand: NaN,
  include: [],
  invert: false
};
var DEFAULT_TICKS_SETTINGS = {
  tight: false,
  forceBounds: false,
  values: undefined,
  count: NaN,
  distance: 100
};
var DEFAULT_MINORTICKS_SETTINGS = {
  count: NaN
};
/**
 * @typedef {object} scale--linear
 * @property {string} [type='linear']
 * @property {number} [expand] - Expand the output range
 * @property {boolean} [invert=false] - Invert the output range
 * @property {number[]} [include] - Include specified numbers in the output range
 * @property {object} [ticks]
 * @property {boolean} [ticks.tight = false]
 * @property {boolean} [ticks.forceBounds = false]
 * @property {number} [ticks.distance = 100]  - Approximate distance between each tick
 * @property {number[]|object[]} [ticks.values] - If set, ticks are no longer generated but instead equal to this set
 * @property {number} [ticks.count]
 * @property {object} [minorTicks]
 * @property {number} [minorTicks.count = 3]
 * @property {number} [min] - Set an explicit minimum value
 * @property {number} [max] - Set an explicit maximum value
 */

function getMinMax$1(settings, fields) {
  var min = +settings.min;
  var max = +settings.max;
  var fieldMin = 0;
  var fieldMax = 1;

  if (fields && fields[0]) {
    var minValues = fields.map(function (m) {
      return m.min();
    }).filter(function (v) {
      return !isNaN(v);
    });
    var maxValues = fields.map(function (m) {
      return m.max();
    }).filter(function (v) {
      return !isNaN(v);
    });
    fieldMin = minValues.length ? Math.min.apply(Math, _toConsumableArray$1(minValues)) : Number.NaN;
    fieldMax = maxValues.length ? Math.max.apply(Math, _toConsumableArray$1(maxValues)) : Number.NaN;

    if (isNaN(fieldMin) || isNaN(fieldMax)) {
      fieldMin = -1;
      fieldMax = 1;
    } else if (fieldMin === fieldMax && fieldMin === 0) {
      fieldMin = -1;
      fieldMax = 1;
    } else if (fieldMin === fieldMax && fieldMin) {
      fieldMin -= Math.abs(fieldMin * 0.1);
      fieldMax += Math.abs(fieldMax * 0.1);
    } else if (!isNaN(settings.expand)) {
      var range = fieldMax - fieldMin;
      fieldMin -= range * settings.expand;
      fieldMax += range * settings.expand;
    }

    if (Array.isArray(settings.include)) {
      var i = settings.include.filter(function (n) {
        return !isNaN(n);
      });
      fieldMin = Math.min.apply(Math, _toConsumableArray$1(i).concat([fieldMin]));
      fieldMax = Math.max.apply(Math, _toConsumableArray$1(i).concat([fieldMax]));
    }
  }

  return {
    mini: !isNaN(min) ? min : fieldMin,
    maxi: !isNaN(max) ? max : fieldMax
  };
}

function initNormScale(normScale, scale) {
  if (normScale.instance) {
    return;
  }

  normScale.instance = scale.copy();
  normScale.instance.domain([scale.start(), scale.end()]);
  normScale.instance.clamp(true);
  normScale.instance.range(normScale.invert ? [1, 0] : [0, 1]);
}
/**
 * @alias scaleLinear
 * @private
 * @param { object } settings
 * @param { field[] } [fields]
 * @return { linear }
 */


function scaleLinear() {
  var settings = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var resources = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var d3Scale = linear$1();
  var normScale = {
    instance: null,
    invert: false
  };
  var ctx = {
    data: data,
    resources: resources
  };
  var stgns = resolveSettings$1(settings, DEFAULT_SETTINGS, ctx);
  stgns.ticks = resolveSettings$1(settings.ticks, DEFAULT_TICKS_SETTINGS, ctx);
  stgns.minorTicks = resolveSettings$1(settings.minorTicks, DEFAULT_MINORTICKS_SETTINGS, ctx);
  var tickCache;
  /**
   * @alias linear
   * @private
   * @param { Object } value
   * @return { number }
   */

  function fn(v) {
    if (notNumber(v)) {
      return NaN;
    }

    return d3Scale(v);
  }

  fn.data = function () {
    return data;
  };
  /**
   * {@link https://github.com/d3/d3-scale#continuous_invert }
   * @param { number } value The inverted value
   * @return { number } The inverted scaled value
   */


  fn.invert = function invert(value) {
    return d3Scale.invert(value);
  };
  /**
   * {@link https://github.com/d3/d3-scale#continuous_rangeRound }
   * @param { number[] } values Range values
   * @return { linear } The instance this method was called on
   */


  fn.rangeRound = function rangeRound(values) {
    d3Scale.rangeRound(values);
    return fn;
  };
  /**
   * {@link https://github.com/d3/d3-scale#continuous_clamp }
   * @param { boolean } [ value=true ] TRUE if clamping should be enabled
   * @return { linear } The instance this method was called on
   */


  fn.clamp = function clamp() {
    var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
    d3Scale.clamp(value);
    return fn;
  };
  /**
   * Get cached ticks (if any)
   * @return { number | undefined }
   */


  fn.cachedTicks = function fnCachedTicks() {
    return tickCache;
  };
  /**
   * Clear the tick cache
   * @return {number | undefined}
   */


  fn.clearTicksCache = function fnClearTicks() {
    tickCache = undefined;
    return this;
  };
  /**
   * {@link https://github.com/d3/d3-scale#continuous_ticks }
   * @param { Object } input Number of ticks to generate or an object passed to tick generator
   * @return { number[] | Object } Array of ticks or any type the custom tick generator returns
   */


  fn.ticks = function ticks(input) {
    if (input !== null && _typeof(input) === 'object') {
      input.settings = input.settings || {}; // TODO Discontinue support for custom ticks settings as argument

      input.settings = extend(true, {}, stgns, input.settings);
      input.scale = fn;
      tickCache = generateContinuousTicks(input);
      return tickCache;
    }

    tickCache = d3Scale.ticks(input);
    return tickCache;
  };
  /**
   * {@link https://github.com/d3/d3-scale#continuous_nice }
   * @param { number } count
   * @return { linear } The instance this method was called on
   */


  fn.nice = function nice(count) {
    d3Scale.nice(count);
    return fn;
  }; // TODO Support this?


  fn.tickFormat = function tickFormat(count, format) {
    return d3Scale.tickFormat(count, format);
  }; // TODO Support this?


  fn.interpolate = function interpolate(func) {
    d3Scale.interpolate(func);
    return fn;
  };
  /**
   * @param { number[] } [values] Set or Get domain values
   * @return { linear | Number[] } The instance this method was called on if a parameter is provided, otherwise the current domain is returned
   */


  fn.domain = function domain(values) {
    if (arguments.length) {
      d3Scale.domain(values);

      if (normScale.instance) {
        normScale.instance.domain([fn.start(), fn.end()]);
      }

      return fn;
    }

    return d3Scale.domain();
  };
  /**
   * @param { number[] } [values] Set or Get range values
   * @return { linear | number[] } The instance this method was called on if a parameter is provided, otherwise the current range is returned
   */


  fn.range = function range(values) {
    if (arguments.length) {
      d3Scale.range(values);
      return fn;
    }

    return d3Scale.range();
  };
  /**
   * Get the first value of the domain
   * @return { number }
   */


  fn.start = function start() {
    return fn.domain()[0];
  };
  /**
   * Get the last value of the domain
   * @return { number }
   */


  fn.end = function end() {
    return fn.domain()[this.domain().length - 1];
  };
  /**
   * Get the minimum value of the domain
   * @return { number }
   */


  fn.min = function min() {
    return Math.min(this.start(), this.end());
  };
  /**
   * Get the maximum value of the domain
   * @return { number }
   */


  fn.max = function max() {
    return Math.max(this.start(), this.end());
  };
  /**
   * Divides the domain and range into uniform segments, based on start and end value
   * @param  { number } segments The number of segments
   * @return { function } The instance this method was called on
   * @example
   * let s = linear();
   * s.domain([0, 10]);
   * s.range([0, 1]);
   * s.classify( 2 );
   * s.domain(); // [10, 5, 5, 0]
   * s.range(); // [0.75, 0.75, 0.25, 0.25]
   */


  fn.classify = function classify(segments) {
    var valueRange = (fn.start() - fn.end()) / segments,
        domain = [fn.end()],
        range = [],
        samplePos = valueRange / 2;

    for (var i = 0; i < segments; i++) {
      var lastVal = domain[domain.length - 1] || 0,
          calIntervalPos = lastVal + valueRange,
          calSamplePos = lastVal + samplePos,
          sampleColValue = fn(calSamplePos);
      domain.push.apply(domain, [calIntervalPos, calIntervalPos]);
      range.push.apply(range, [sampleColValue, sampleColValue]);
    }

    domain.pop();
    fn.domain(domain);
    fn.range(range);
    return fn;
  };

  fn.copy = function copy() {
    var cop = scaleLinear(settings, data, resources);
    cop.domain(fn.domain());
    cop.range(fn.range());
    cop.clamp(d3Scale.clamp());
    return cop;
  };
  /**
   * @param {number} d - A domain value
   * @return {number} A normalized range output given in range 0-1
   * @example
   * const scale = scaleLinear().domain([0, 10]).range([0, 10000]);
   * scale.norm(5); // Returns 0.5
   * scale(5); // Returns 5000
   *
   * scale.domain([0, 2, 10]);
   * scale.norm(5); // Returns 0.5
   */


  fn.norm = function norm(d) {
    initNormScale(normScale, fn);
    return normScale.instance(d);
  };
  /**
   * @param {number} d - A normalized value in range 0-1
   * @return {number} A corresponding domain value
   * @example
   * const scale = scaleLinear().domain([0, 10]).range([0, 10000]);
   * scale.normInvert(0.5); // Returns 5
   * scale.invert(5000); // Returns 5
   */


  fn.normInvert = function norm(t) {
    initNormScale(normScale, fn);
    return normScale.instance.invert(t);
  };

  var _getMinMax = getMinMax$1(stgns, data ? data.fields : []),
      mini = _getMinMax.mini,
      maxi = _getMinMax.maxi;

  fn.domain([mini, maxi]);
  fn.range(stgns.invert ? [1, 0] : [0, 1]);
  normScale.invert = stgns.invert;
  return fn;
}

var DEFAULT_SETTINGS$1 = {
  padding: 0,
  paddingInner: NaN,
  paddingOuter: NaN,
  align: 0.5,
  invert: false,
  maxPxStep: NaN,
  range: [0, 1]
};
/**
 * @typedef {object} scale--band
 * @property {string} [type='band']
 * @property {number} [padding] - {@link https://github.com/d3/d3-scale#band_padding}
 * @property {number} [paddingInner] - {@link https://github.com/d3/d3-scale#band_paddingInner}
 * @property {number} [paddingOuter] - {@link https://github.com/d3/d3-scale#band_paddingOuter}
 * @property {number} [align] - {@link https://github.com/d3/d3-scale#band_align}
 * @property {boolean} [invert=false] - Invert the output range
 * @property {number} [maxPxStep] - Explicitly limit the bandwidth to a pixel value
 * @property {function} [label] - Callback label function, applied on each datum
 * @property {function} [value] - Callback value function, applied on each datum
 * @property {array<number>|function} [range=[0, 1]] - Set range explicitly (ignored when maxPxStep takes effect)
 */

/**
 * @alias scaleBand
 * @memberof picasso
 * @private
 * @param { Object } settings
 * @param { fields[] } [fields]
 * @param { dataset } [dataset]
 * @return { band }
 */

function scaleBand() {
  var settings = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var resources = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

  /**
   * An augmented {@link https://github.com/d3/d3-scale#_band|d3 band scale}
   * @alias band
   * @private
   * @kind function
   * @param { Object } value
   * @return { number }
   */
  var band$1 = band();
  var ctx = {
    data: data,
    resources: resources
  };
  var stgns = resolveSettings$1(settings, DEFAULT_SETTINGS$1, ctx);
  var items = data.items || [];
  var domainToDataMapping = {};
  var values = [];
  var labels = []; // I would like to define this outside of scaleBand but it cause the documentation to be in the wrong order

  function augmentScaleBand(band, settings) {
    // eslint-disable-line no-shadow
    band.data = function () {
      return data;
    };

    band.datum = function (domainValue) {
      return items[domainToDataMapping[domainValue]];
    };
    /**
     * Get the first value of the domain
     * @return { number }
     */


    band.start = function start() {
      return band.domain()[0];
    };
    /**
     * Get the last value of the domain
     * @return { number }
     */


    band.end = function end() {
      return band.domain()[band.domain().length - 1];
    };

    band.labels = function () {
      return labels;
    };
    /**
     * Generate discrete ticks
     * @return {Object[]} Array of ticks
     */


    band.ticks = function ticks() {
      var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      input.scale = band;
      return generateDiscreteTicks(input, settings.trackBy || 'label');
    };
  }

  augmentScaleBand(band$1, settings);
  /**
   * if required creates a new scale with a restricted range
   * so that step size is at most maxPxStep
   * otherwise it returns itself
   * @param { number } size
   * @return { band }
   */

  band$1.pxScale = function pxScale(size) {
    var max = stgns.maxPxStep;

    if (isNaN(max)) {
      return band$1;
    }

    var n = band$1.domain().length;
    var sizeRelativeToStep = Math.max(1, n - band$1.paddingInner() + 2 * band$1.paddingOuter());

    if (sizeRelativeToStep * max >= size) {
      return band$1;
    }

    var newBand = band$1.copy();
    newBand.type = band$1.type;
    augmentScaleBand(newBand, settings);
    var t = sizeRelativeToStep * max / size;
    var offset = (1 - t) * band$1.align();
    newBand.range(stgns.invert ? [t + offset, offset] : [offset, t + offset]);
    return newBand;
  };

  var valueFn = typeof settings.value === 'function' ? settings.value : function (d) {
    return d.datum.value;
  };
  var labelFn = typeof settings.label === 'function' ? settings.label : function (d) {
    return d.datum.label;
  };

  for (var i = 0; i < items.length; i++) {
    var arg = extend({
      datum: items[i]
    }, ctx);
    var v = valueFn(arg, i);

    if (values.indexOf(v) === -1) {
      values.push(v);
      labels.push(labelFn(arg, i));
      domainToDataMapping[v] = i;
    }
  }

  band$1.domain(values);
  band$1.range(stgns.invert ? stgns.range.slice().reverse() : stgns.range);
  band$1.padding(isNaN(stgns.padding) ? 0 : stgns.padding);

  if (!isNaN(stgns.paddingInner)) {
    band$1.paddingInner(stgns.paddingInner);
  }

  if (!isNaN(stgns.paddingOuter)) {
    band$1.paddingOuter(stgns.paddingOuter);
  }

  band$1.align(isNaN(stgns.align) ? 0.5 : stgns.align);
  return band$1;
}

var DEFAULT_TICKS_SETTINGS$1 = {
  depth: 0
};

function keyGen(node, valueFn, ctx) {
  return node.ancestors().map(function (a) {
    return valueFn(extend({
      datum: a.data
    }, ctx));
  }).reverse().slice(1) // Delete root node
  .toString();
}

function flattenTree(rootNode, settings, ctx) {
  var ticksDepth = settings.ticks.depth;
  var valueFn = settings.value;
  var labelFn = settings.label;
  var values = [];
  var labels = [];
  var items = {};
  var ticks = [];
  var expando = 0;

  if (!rootNode) {
    return {
      values: values,
      labels: labels,
      items: items,
      ticks: ticks
    };
  }

  rootNode.eachAfter(function (node) {
    if (node.depth > 0) {
      var key = keyGen(node, valueFn, ctx);
      var leaves = node.leaves() || [node]; // If leaf node returns itself

      var value = valueFn(extend({
        datum: node.data
      }, ctx));
      var label = labelFn(extend({
        datum: node.data
      }, ctx));
      var isBranch = Array.isArray(node.children);
      var item = {
        key: key,
        count: leaves.length,
        value: value,
        label: label,
        leftEdge: keyGen(leaves[0], valueFn, ctx),
        rightEdge: keyGen(leaves[Math.max(leaves.length - 1, 0)], valueFn, ctx),
        node: node // isTick: ticksDepth === null ? !isBranch : node.depth === ticksDepth

      };

      if (isBranch) {
        values.push("SPACER_".concat(expando, "_SPACER"));
        expando++;
      } else {
        values.push(key);
        labels.push(label);
      }

      if (ticksDepth <= 0 && !isBranch || node.depth === ticksDepth) {
        ticks.push(item);
      }

      items[key] = item;
    }
  });
  var spill = rootNode.height - 1;

  if (spill > 0) {
    values.splice(-spill);
  }

  return {
    values: values,
    labels: labels,
    items: items,
    ticks: ticks
  };
}
/**
 * @typedef {object} scale-hBand.settings
 * @private
 * @property {number} [padding=0] - Exposes {@link https://github.com/d3/d3-scale#band_padding}
 * @property {boolean} [paddingOuter=0] - Exposes {@link https://github.com/d3/d3-scale#band_paddingOuter}
 * @property {number[]} [paddingInner=0] - Exposes {@link https://github.com/d3/d3-scale#band_paddingInner}
 * @property {object} [align=0.5] - Exposes {@link https://github.com/d3/d3-scale#band_align}
 * @property {boolean} [invert=false] - Invert the output range
 */

/**
  * Hierarchical band scale, that is an augmented band scale, that takes hierarchical data as input
 * @alias scaleHierarchicalBand
 * @private
 * @param { Object } settings
 * @param { fields[] } [fields]
 * @param { dataset } [dataset] - With a root property that is an instance of D3.js Hierarchy
 * @return { h-band }
 */


function scaleHierarchicalBand() {
  var settings = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var resources = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var ctx = {
    data: data,
    resources: resources
  };
  var stgns = resolveSettings$1(settings, DEFAULT_SETTINGS$1, ctx);
  stgns.ticks = resolveSettings$1(settings.ticks, DEFAULT_TICKS_SETTINGS$1, ctx);
  stgns.value = typeof settings.value === 'function' ? settings.value : function (d) {
    return d.datum.value;
  };
  stgns.label = typeof settings.label === 'function' ? settings.label : function (d) {
    return d.datum.value;
  };
  var bandInstance = scaleBand(stgns);

  var _flattenTree = flattenTree(data.root, stgns, ctx),
      values = _flattenTree.values,
      labels = _flattenTree.labels,
      items = _flattenTree.items,
      ticks = _flattenTree.ticks;
  /**
   * @alias h-band
   * @private
   * @kind function
   * @param { Object[] } value - Array where each value is a reference to a node, going from depth 1 to n.
   * @return { number }
   */


  var hBand = function fn(val) {
    var strVal = String(val);
    var item = items[strVal];

    if (item) {
      return bandInstance(stgns.invert ? item.rightEdge : item.leftEdge);
    }

    return bandInstance(strVal);
  };

  extend(true, hBand, bandInstance);
  /**
   * Wrapped {@link https://github.com/d3/d3-scale#band_bandwidth}
   * @param { Object[] } [val] - Array where each value is a reference to a node, going from depth 1 to n. If omitted, bandwidth for the leaf nodes is return.
   * @return { number }
   */

  hBand.bandwidth = function bandwidth(val) {
    var item = items[String(val)];
    var bw = bandInstance.bandwidth();

    if (item && !item.isLeaf) {
      var left = hBand(item.leftEdge);
      var right = hBand(item.rightEdge);
      return Math.abs(left - right) + bw;
    }

    return bw;
  };
  /**
   * Wrapped {@link https://github.com/d3/d3-scale#band_step}
   * @param { Object[] } [val] - Array where each value is a reference to a node, going from depth 1 to n. If omitted, step size for the leaf nodes is return.
   * @return { number }
   */


  hBand.step = function step(val) {
    var item = items[String(val)];
    var leafCount = item ? item.count : 1;
    var stepSize = bandInstance.step();
    stepSize *= leafCount;
    return stepSize;
  };
  /**
   * @return { dataset }
   */


  hBand.data = function () {
    return data;
  };
  /**
   * Return datum for a given node
   * @param { Object[] } val - Array where each value is a reference to a node, going from depth 1 to n.
   * @return { Object } The datum
   */


  hBand.datum = function (val) {
    var item = items[String(val)];

    if (item) {
      return item.node.data;
    }

    return null;
  };

  hBand.copy = function () {
    return scaleHierarchicalBand(settings, data, resources);
  };
  /**
   * @return { Object[] } Labels for each leaf node
   */


  hBand.labels = function () {
    return labels;
  };
  /**
   * Generate discrete ticks
   * @return { Object[] } Ticks for each leaf node
   */


  hBand.ticks = function () {
    // eslint-disable-line arrow-body-style
    return ticks.map(function (item) {
      var start = hBand(item.key);
      var bandwidth = hBand.bandwidth(item.key);
      return {
        position: start + bandwidth / 2,
        label: item.label,
        data: item.node.data,
        start: start,
        end: start + bandwidth
      };
    });
  };

  var orgPxScale = bandInstance.pxScale;

  hBand.pxScale = function pxScale(size) {
    bandInstance = orgPxScale(size);
    return hBand;
  };

  hBand.domain(values);
  return hBand;
}

var minAccessor = function minAccessor(v) {
  return v.min();
};

var maxAccessor = function maxAccessor(v) {
  return v.max();
};
/**
 * Calculate the min/max value based on various inputs.
 *
 * Provided min/max setting takes presedence over all other inputs. If not provided, the respective values are calculated
 * from the given arr input, where each item in the array is expected to have a min/max accessor.
 *
 * @private
 * @param {object} [settings]
 * @param {number} [settings.min] The minimum value. Defaults to 0 if not provided.
 * @param {number} [settings.max] The maximum value. Defaults to 1 if not provided.
 * @param {object} [arr]
 * @returns { object[] } An array containing the min and max values.
 *
 * @example
 * minmax(); // [0, 1]
 *
 * minmax({}, [
 * { min: () => 13, max: () => 15 },
 * { min: () => NaN, max: () => 17 },
 * ]); // [13, 17]
 *
 * minmax({ min: -5, max: 4 }, [
 * { min: () => -20, max: () => 15 },
 * ]); // [-5, 4]
 */


function minmax(settings, arr) {
  // const definedMin = settings && typeof settings.min !== 'undefined';
  // const definedMax = settings && typeof settings.max !== 'undefined';
  var definedMin = settings && !isNaN(settings.min);
  var definedMax = settings && !isNaN(settings.max);
  var min = definedMin ? +settings.min : 0;
  var max = definedMax ? +settings.max : 1;

  if (arr && arr.length) {
    if (!definedMin) {
      var arrMin = arr.map(minAccessor).filter(isNumber);
      min = arrMin.length ? Math.min.apply(Math, _toConsumableArray$1(arrMin)) : min;
    }

    if (!definedMax) {
      var arrMax = arr.map(maxAccessor).filter(isNumber);
      max = arrMax.length ? Math.max.apply(Math, _toConsumableArray$1(arrMax)) : max;
    }
  }

  return [min, max];
}

var DEFAULT_SETTINGS$2 = {
  domain: [],
  range: [],
  invert: false,
  min: NaN,
  max: NaN
};

function generateDomain(range, min, max) {
  var len = range.length;

  if (len === 2) {
    return [min, max];
  }

  var domain = [];
  var part = (max - min) / (len - 1);
  domain.push(min);

  for (var i = 1; i < len - 1; i++) {
    domain.push(min + part * i);
  }

  domain.push(max);
  return domain;
}
/**
 * @typedef {object} scale--sequential-color
 * @property {string} [type='sequential-color']
 * @property {string[]} [range] - CSS color values of the output range
 * @property {boolean} [invert=false] - Invert range
 * @property {number} [min] - Set an explicit minimum value
 * @property {number} [max] - Set an explicit maximum value
 */

/**
 * @alias scaleSequentialColor
 * @private
 * @param { Object } [settings] Settings for this scale. If both range and domain are specified, they have to fulfill range.length === domain.length, otherwise they will be overriden.
 * @param { number[] } [settings.domain] Numeric values indicating stop limits between start and end values.
 * @param { color[] } [settings.range] CSS color values indicating stop colors between start and end values.
 * @param { field[] } [fields] Fields to dynamically calculate the domain extent.
 * @return { sequentialColor }
 *
 * @example
 * picasso.scaleSequentialColor({
 *  range: ['red', '#fc6', 'green'],
 *  domain: [-40, 0, 100]
 * });
 */


function scaleSequentialColor() {
  var settings = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var resources = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var s = scaleLinear(settings, data, resources).clamp(true).interpolate(interpolateRgb);
  var stgns = resolveSettings$1(settings, DEFAULT_SETTINGS$2, {
    data: data,
    resources: resources
  });
  var isDomain = Array.isArray(stgns.domain) && stgns.domain.length;
  var isRange = Array.isArray(stgns.range) && stgns.range.length;
  /**
   * @alias sequentialColor
   * @private
   * @kind function
   * @param { Object } v Object containing a 'value' property
   * @return { string } The blended color
   */

  var fn = s;
  extend(true, fn, s);

  var _minmax = minmax(stgns, data ? data.fields : []),
      _minmax2 = picasso_esm_slicedToArray(_minmax, 2),
      min = _minmax2[0],
      max = _minmax2[1];

  var num = isDomain ? stgns.domain.length : -1;
  var DEFAULT_COLORS = resources.theme ? resources.theme.palette('sequential', num > 0 ? num : 2) : [];
  var range = isRange ? stgns.range : DEFAULT_COLORS;
  fn.range(stgns.invert ? range.slice().reverse() : range.slice());
  fn.domain(isDomain ? stgns.domain : generateDomain(fn.range(), min, max));
  return fn;
}

var DEFAULT_SETTINGS$3 = {
  domain: [],
  range: [],
  invert: false,
  min: NaN,
  max: NaN,
  nice: false
};

function generateDomain$1(range, min, max) {
  var len = range.length;

  if (len === 2) {
    return [min + (max - min) / 2];
  }

  var domain = [];
  var part = (max - min) / len;

  for (var i = 1; i < len; i++) {
    domain.push(min + part * i);
  }

  return domain;
}

function getBreaks(domain) {
  var ret = [];

  for (var i = 0; i < domain.length - 1; i++) {
    ret.push((domain[i] + domain[i + 1]) / 2);
  }

  return ret;
}

function generateRange(domain, colors, min, max) {
  min = domain[0];
  max = domain && domain.length >= 2 ? domain[domain.length - 1] : max;
  var seq = scaleSequentialColor().domain([min, max]).range(colors);
  var values = [min].concat(_toConsumableArray$1(getBreaks(domain)), [max]);
  return values.map(function (v) {
    return seq(v);
  });
}

function generateNiceDomain(range, min, max) {
  var numPoints = range.length === 2 ? 10 : Math.max(1, range.length);
  var lin = linear$1().domain([min, max]).nice(numPoints);
  var domain = lin.ticks(numPoints);

  if (!range || !range.length) {
    return domain;
  } // remove values from endpoints


  var num = Math.max(0, range.length - 1);

  while (domain.length > num) {
    if (domain[0] - min <= max - domain[domain.length - 1]) {
      domain.shift();
    } else {
      domain.pop();
    }
  }

  return domain;
}
/**
 * @typedef {object} scale--threshold-color
 * @property {string} [type='threshold-color']
 * @property {number[]} [domain] Values defining the thresholds
 * @property {string[]} [range] - CSS color values of the output range
 * @property {boolean} [invert=false] - Invert range
 * @property {number} [min] - Set an explicit minimum value
 * @property {number} [max] - Set an explicit maximum value
 * @property {boolean} [nice=false] If set to true, will generate 'nice' domain values. Ignored if domain is set.
 */

/**
 * @alias scaleThresholdColor
 * @private
 * @param { object } [settings] Settings for this scale. If both domain and range are specified, they have to fulfill domain.length === range.length + 1,  otherwise they will be overriden.
 * @param { number[] } [settings.domain] Values defining the thresholds.
 * @param { color[] } [settings.range] CSS color values of the output range.
 * @param { boolean } [settings.nice=false] If set to true, will generate 'nice' domain values. Ignored if domain is set.
 * @param { number } [settings.min] Minimum value to generate domain extent from. Ignored if domain is set.
 * @param { number } [settings.max] Maximum value to generate domain extend from. Ignored if domain is set.
 * @param { field[] } [fields] Fields to dynamically calculate the domain extent from. Ignored if min/max are set.
 * @return { thresholdColor }
 *
 * @example
 * let t = threshold({
 *   range: ['black', 'white'],
 *   domain: [25,50,75],
 *   max: 100,
 *   min: 0
 * });
 * t.domain(); // [25,50,75]
 * t.range(); // Generates from colors and domain: ['rgb(0,0,0)','rgb(85,85,85)','rgb(170,170,170)','rgb(255,255,255)']
 */


function scaleThresholdColor() {
  var settings = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var resources = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var d3Scale = threshold();
  var stgns = resolveSettings$1(settings, DEFAULT_SETTINGS$3, {
    data: data,
    resources: resources
  });
  var isDomain = Array.isArray(stgns.domain) && stgns.domain.length;
  var isRange = Array.isArray(stgns.range) && stgns.range.length;
  /**
   * @alias thresholdColor
   * @private
   * @param { object } v Object literal containing a 'value' property.
   * @return { string } A CSS color from the scale's range.
   */

  function fn(v) {
    if (notNumber(v)) {
      return NaN;
    }

    return d3Scale(v);
  }

  Object.keys(d3Scale).forEach(function (key) {
    return fn[key] = d3Scale[key];
  });
  var fields = data.fields;

  var _minmax = minmax(stgns, fields),
      _minmax2 = picasso_esm_slicedToArray(_minmax, 2),
      min = _minmax2[0],
      max = _minmax2[1];

  var num = isDomain ? stgns.domain.length : -1;
  var DEFAULT_COLORS = resources.theme ? resources.theme.palette('sequential', num > 0 ? num : 2) : [];
  var range = isRange ? stgns.range : DEFAULT_COLORS;
  var domain = [];

  if (isDomain) {
    domain = stgns.domain;
  } else if (stgns.nice) {
    domain = generateNiceDomain(range, min, max);
  } else {
    domain = [min + (max - min) / 2];
  }

  if (range.length > domain.length + 1) {
    // Generate limits from range
    domain = generateDomain$1(range, min, max);
  } else if (range.length < domain.length + 1) {
    // Generate additional colors
    range = generateRange(domain, range, min, max);
  }

  fn.data = function () {
    return data;
  };

  fn.range(stgns.invert ? range.slice().reverse() : range);
  fn.domain(domain);
  return fn;
}

var DEFAULT_SETTINGS$4 = {
  domain: [],
  range: []
};
/**
 * @alias scaleOrdinal
 * @private
 * @param { Object } settings
 * @param { field[] } [fields]
 * @param { dataset } data
 * @return { ordinal }
 */

function ordinal$1() {
  var settings = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var resources = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

  /**
   * An augmented {@link https://github.com/d3/d3-scale#_ordinal|d3 ordinal scale}
   * @private
   * @alias ordinal
   * @param { Object }
   * @return { number }
   */
  var fn = ordinal();
  var ctx = {
    data: data,
    resources: resources
  };
  var stgns = resolveSettings$1(settings, DEFAULT_SETTINGS$4, ctx);
  var valueFn = typeof settings.value === 'function' ? settings.value : function (d) {
    return d.datum.value;
  };
  var labelFn = typeof settings.label === 'function' ? settings.label : function (d) {
    return d.datum.label;
  };
  var items = data.items || [];
  var domainToDataMapping = {};
  var values = [];
  var labels = [];

  for (var i = 0; i < items.length; i++) {
    var arg = extend({
      datum: items[i]
    }, ctx);
    var v = valueFn(arg, i);

    if (values.indexOf(v) === -1) {
      values.push(v);
      labels.push(labelFn(arg, i));
      domainToDataMapping[v] = i;
    }
  }

  fn.data = function () {
    return data;
  };

  fn.labels = function () {
    return labels;
  };

  fn.label = function (domainValue) {
    return labels[values.indexOf(domainValue)];
  };

  fn.datum = function (domainValue) {
    return items[domainToDataMapping[domainValue]];
  };

  fn.range(stgns.range);

  if (Array.isArray(stgns.domain) && stgns.domain.length) {
    fn.domain(stgns.domain);
  } else {
    fn.domain(values);
  }

  return fn;
}

var DEFAULT_SETTINGS$5 = {
  domain: [],
  range: [],
  unknown: undefined
};
var DEFAULT_EXPLICIT_SETTINGS = {
  domain: [],
  range: [],
  override: false
};
/**
 * @typedef {object} scale--categorical-color
 * @property {string} [type='categorical-color']
 * @property {string[]} [range=false] - CSS color values of the output range
 * @property {string} [unknown] - {@link https://github.com/d3/d3-scale#ordinal_unknown}
 * @property {object} [explicit] - Explicitly bind values to an output
 * @property {object[]} [explicit.domain[]] - Values to bind
 * @property {string[]} [explicit.range[]] - Output range
 */

/**
 * An ordinal scale with the output range set to default colors, as defined by *scaleCategorical.range*
 * @alias scaleCategorical
 * @private
 * @param { Object } settings
 * @param { field[] } [fields]
 * @param { dataset } [dataset]
 * @return { ordinal }
 */

function scaleCategorical() {
  var settings = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var resources = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var s = ordinal$1(settings, data, resources);
  var theme = resources.theme;
  var stgns = resolveSettings$1(settings, DEFAULT_SETTINGS$5, {
    data: data,
    resources: resources
  });
  stgns.explicit = resolveSettings$1(settings.explicit, DEFAULT_EXPLICIT_SETTINGS, {
    data: data,
    resources: resources
  });
  var range;

  if (!Array.isArray(stgns.range) || stgns.range.length === 0) {
    range = theme ? theme.palette('categorical', s.domain().length).slice() : [];
  } else {
    range = stgns.range.slice();
  }

  if (stgns.unknown) {
    s.unknown(stgns.unknown);
  } else if (theme && theme.palette('unknown')) {
    var un = theme.palette('unknown');
    s.unknown(un[0]);
  }

  if (Array.isArray(stgns.explicit.domain) && stgns.explicit.domain.length) {
    var domain = s.domain().slice();
    var explicitDomain = stgns.explicit.domain;
    var explicitRange = Array.isArray(stgns.explicit.range) ? stgns.explicit.range : []; // duplicate range values to cover entire domain

    var numCopies = Math.floor(domain.length / range.length);

    for (var i = 1; i < numCopies + 1; i *= 2) {
      range = range.concat(range);
    }

    if (stgns.explicit.override) {
      for (var _i = 0; _i < explicitDomain.length; _i++) {
        var index = domain.indexOf(explicitDomain[_i]);

        if (index > -1) {
          range[index] = explicitRange[_i];
        }
      }
    } else {
      // inject explicit colors
      var order = explicitDomain.map(function (d, i) {
        return [domain.indexOf(d), d, explicitRange[i]];
      }).sort(function (a, b) {
        return a[0] - b[0];
      });
      order.forEach(function (v) {
        var idx = domain.indexOf(v[1]);

        if (idx !== -1) {
          range.splice(idx, 0, v[2]);
        }
      });
    } // cutoff excess range values


    range.length = domain.length;
  }

  s.range(range);
  return s;
}

var scaleRegistry = registryFactory();
scaleRegistry('linear', scaleLinear);
scaleRegistry('band', scaleBand);
scaleRegistry('h-band', scaleHierarchicalBand);
scaleRegistry('sequential-color', scaleSequentialColor);
scaleRegistry('threshold-color', scaleThresholdColor);
scaleRegistry('categorical-color', scaleCategorical);

function getTypeFromMeta(fields) {
  var types = fields.map(function (field) {
    return field.type() === 'dimension' ? 'band' : 'linear';
  });
  return types.indexOf('linear') !== -1 ? 'linear' : 'band';
}

function deduceScaleTypeFromData(data) {
  if (data.root) {
    return 'h-band';
  }

  if (data.fields && data.fields[0]) {
    return getTypeFromMeta(data.fields);
  }

  return 'linear';
}

function create$2(options, d, deps) {
  var dataSourceConfig = options.data;

  if (options.source) {
    // DEPRECATION
    deps.logger.warn('Deprecated: Scale data source configuration');
    dataSourceConfig = {
      extract: []
    };
    (Array.isArray(options.source) ? options.source : [options.source]).forEach(function (source) {
      dataSourceConfig.extract.push({
        field: source
      });
    });
  }

  var data = extract(dataSourceConfig, d, deps);
  var type = options.type || deduceScaleTypeFromData(data);
  var s;

  if (type === 'color') {
    if (data.fields && data.fields[0] && data.fields[0].type() === 'dimension') {
      type = 'categorical-color';
    } else {
      type = 'sequential-color';
    }
  }

  if (deps.scale.has(type)) {
    s = deps.scale.get(type);
    s = s(options, data, {
      theme: deps.theme,
      logger: deps.logger
    });
    s.type = type;
  }

  return s;
}
function collection$1(scalesConfig, data, deps) {
  var fn = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : create$2;
  var scales = {};
  return {
    get: function get(def) {
      var key;

      if (typeof def === 'string' && scalesConfig[def]) {
        key = def;
      } else if (_typeof(def) === 'object' && 'scale' in def && scalesConfig[def.scale]) {
        key = def.scale;
      }

      if (key) {
        scales[key] = scales[key] || fn(scalesConfig[key], data, deps);
        return scales[key];
      }

      return fn(def, data, deps);
    },
    all: function all() {
      Object.keys(scalesConfig).forEach(this.get);
      return scales;
    }
  };
}

/**
 * Utility functions
 */

var util = {};

util.isObject = function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
};

util.isNumber = function isNumber(arg) {
  return typeof arg === 'number';
};

util.isUndefined = function isUndefined(arg) {
  return arg === void 0;
};

util.isFunction = function isFunction(arg){
  return typeof arg === 'function';
};


/**
 * EventEmitter class
 */

function EventEmitter() {
  EventEmitter.init.call(this);
}
var nodeEventEmitter = EventEmitter;

// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;

EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;

// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;

EventEmitter.init = function() {
  this._events = this._events || {};
  this._maxListeners = this._maxListeners || undefined;
};

// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
  if (!util.isNumber(n) || n < 0 || isNaN(n))
    throw TypeError('n must be a positive number');
  this._maxListeners = n;
  return this;
};

EventEmitter.prototype.emit = function(type) {
  var er, handler, len, args, i, listeners;

  if (!this._events)
    this._events = {};

  // If there is no 'error' event listener then throw.
  if (type === 'error' && !this._events.error) {
    er = arguments[1];
    if (er instanceof Error) {
      throw er; // Unhandled 'error' event
    } else {
      throw Error('Uncaught, unspecified "error" event.');
    }
    return false;
  }

  handler = this._events[type];

  if (util.isUndefined(handler))
    return false;

  if (util.isFunction(handler)) {
    switch (arguments.length) {
      // fast cases
      case 1:
        handler.call(this);
        break;
      case 2:
        handler.call(this, arguments[1]);
        break;
      case 3:
        handler.call(this, arguments[1], arguments[2]);
        break;
      // slower
      default:
        len = arguments.length;
        args = new Array(len - 1);
        for (i = 1; i < len; i++)
          args[i - 1] = arguments[i];
        handler.apply(this, args);
    }
  } else if (util.isObject(handler)) {
    len = arguments.length;
    args = new Array(len - 1);
    for (i = 1; i < len; i++)
      args[i - 1] = arguments[i];

    listeners = handler.slice();
    len = listeners.length;
    for (i = 0; i < len; i++)
      listeners[i].apply(this, args);
  }

  return true;
};

EventEmitter.prototype.addListener = function(type, listener) {
  var m;

  if (!util.isFunction(listener))
    throw TypeError('listener must be a function');

  if (!this._events)
    this._events = {};

  // To avoid recursion in the case that type === "newListener"! Before
  // adding it to the listeners, first emit "newListener".
  if (this._events.newListener)
    this.emit('newListener', type,
              util.isFunction(listener.listener) ?
              listener.listener : listener);

  if (!this._events[type])
    // Optimize the case of one listener. Don't need the extra array object.
    this._events[type] = listener;
  else if (util.isObject(this._events[type]))
    // If we've already got an array, just append.
    this._events[type].push(listener);
  else
    // Adding the second element, need to change to array.
    this._events[type] = [this._events[type], listener];

  // Check for listener leak
  if (util.isObject(this._events[type]) && !this._events[type].warned) {
    var m;
    if (!util.isUndefined(this._maxListeners)) {
      m = this._maxListeners;
    } else {
      m = EventEmitter.defaultMaxListeners;
    }

    if (m && m > 0 && this._events[type].length > m) {
      this._events[type].warned = true;

      if (util.isFunction(console.error)) {
        console.error('(node) warning: possible EventEmitter memory ' +
                      'leak detected. %d listeners added. ' +
                      'Use emitter.setMaxListeners() to increase limit.',
                      this._events[type].length);
      }
      if (util.isFunction(console.trace))
        console.trace();
    }
  }

  return this;
};

EventEmitter.prototype.on = EventEmitter.prototype.addListener;

EventEmitter.prototype.once = function(type, listener) {
  if (!util.isFunction(listener))
    throw TypeError('listener must be a function');

  var fired = false;

  function g() {
    this.removeListener(type, g);

    if (!fired) {
      fired = true;
      listener.apply(this, arguments);
    }
  }

  g.listener = listener;
  this.on(type, g);

  return this;
};

// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
  var list, position, length, i;

  if (!util.isFunction(listener))
    throw TypeError('listener must be a function');

  if (!this._events || !this._events[type])
    return this;

  list = this._events[type];
  length = list.length;
  position = -1;

  if (list === listener ||
      (util.isFunction(list.listener) && list.listener === listener)) {
    delete this._events[type];
    if (this._events.removeListener)
      this.emit('removeListener', type, listener);

  } else if (util.isObject(list)) {
    for (i = length; i-- > 0;) {
      if (list[i] === listener ||
          (list[i].listener && list[i].listener === listener)) {
        position = i;
        break;
      }
    }

    if (position < 0)
      return this;

    if (list.length === 1) {
      list.length = 0;
      delete this._events[type];
    } else {
      list.splice(position, 1);
    }

    if (this._events.removeListener)
      this.emit('removeListener', type, listener);
  }

  return this;
};

EventEmitter.prototype.removeAllListeners = function(type) {
  var key, listeners;

  if (!this._events)
    return this;

  // not listening for removeListener, no need to emit
  if (!this._events.removeListener) {
    if (arguments.length === 0)
      this._events = {};
    else if (this._events[type])
      delete this._events[type];
    return this;
  }

  // emit removeListener for all listeners on all events
  if (arguments.length === 0) {
    for (key in this._events) {
      if (key === 'removeListener') continue;
      this.removeAllListeners(key);
    }
    this.removeAllListeners('removeListener');
    this._events = {};
    return this;
  }

  listeners = this._events[type];

  if (util.isFunction(listeners)) {
    this.removeListener(type, listeners);
  } else if (Array.isArray(listeners)) {
    // LIFO order
    while (listeners.length)
      this.removeListener(type, listeners[listeners.length - 1]);
  }
  delete this._events[type];

  return this;
};

EventEmitter.prototype.listeners = function(type) {
  var ret;
  if (!this._events || !this._events[type])
    ret = [];
  else if (util.isFunction(this._events[type]))
    ret = [this._events[type]];
  else
    ret = this._events[type].slice();
  return ret;
};

EventEmitter.listenerCount = function(emitter, type) {
  var ret;
  if (!emitter._events || !emitter._events[type])
    ret = 0;
  else if (util.isFunction(emitter._events[type]))
    ret = 1;
  else
    ret = emitter._events[type].length;
  return ret;
};

var EventEmitter$1 = {
  /**
   * Function used to add event handling to objects passed in.
   * @private
   * @param {Object} obj Object instance that will get event handling.
   */
  mixin: function mixin(obj) {
    Object.keys(nodeEventEmitter.prototype).forEach(function (key) {
      obj[key] = nodeEventEmitter.prototype[key];
    });
    nodeEventEmitter.init(obj);
    return obj;
  }
};

function scrollApi() {
  var min = 0;
  var max = 0;
  var start = 0;
  var viewSize = 0;
  start = start || min;
  /**
   * The scroll api
   * @private
   * @alias scroll
   */

  var s = {
    /**
     * Move the current scroll
     * @param {number} value
     * @emits update
     */
    move: function move(value) {
      this.moveTo(start + value);
    },

    /**
     * Change the current scroll to a specific value
     * @param {number} value
     * @emits update
     */
    moveTo: function moveTo(value) {
      var newStart = Math.max(min, Math.min(max - viewSize, value));

      if (start !== newStart) {
        start = newStart;
        s.emit('update');
      }
    },

    /**
     * Update scroll settings
     * @param {number} [settings.min]
     * @param {number} [settings.max]
     * @param {number} [settings.viewSize]
     * @emits update
     */
    update: function update(settings) {
      var triggerUpdate = false;
      var _settings$min = settings.min;
      min = _settings$min === void 0 ? min : _settings$min;
      var _settings$max = settings.max;
      max = _settings$max === void 0 ? max : _settings$max;

      if (settings.viewSize !== undefined && settings.viewSize !== viewSize) {
        viewSize = settings.viewSize;
        triggerUpdate = true;
      } // update scroll to be within the new bounds


      var newStart = Math.max(min, Math.min(max - viewSize, start));

      if (start !== newStart) {
        start = newStart;
        triggerUpdate = true;
      }

      if (triggerUpdate) {
        s.emit('update');
      }
    },

    /**
     * Get the current scroll state
     * @return {object} with min, max, start & viewSize
     */
    getState: function getState() {
      return {
        min: min,
        max: max,
        start: start,
        viewSize: viewSize
      };
    }
  };
  EventEmitter$1.mixin(s);
  return s;
}

function createOrUpdate(options, oldApi) {
  var min = options.min || 0;
  var max = options.max || 0;
  var viewSize = options.viewSize || 0;
  var s = oldApi || scrollApi();
  s.update({
    min: min,
    max: max,
    viewSize: viewSize
  });
  return s;
}
function builder(obj, oldScrollApis) {
  var scrollApis = {};

  for (var n in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, n)) {
      scrollApis[n] = createOrUpdate(obj[n], oldScrollApis ? oldScrollApis[n] : null);
    }
  }

  return scrollApis;
}
function getOrCreateScrollApi(v, scrollApis) {
  if (!scrollApis[v]) {
    scrollApis[v] = scrollApi();
  }

  return scrollApis[v];
}

function lessThanOrEqual(value, limit) {
  return value <= limit;
}

function lessThan(value, limit) {
  return value < limit;
}

function picasso_esm_index(boundaries, point, after) {
  var i = 0;

  while (i < boundaries.length && point > boundaries[i]) {
    ++i;
  }

  if (boundaries[i] === point && after) {
    ++i;
  }

  return i;
}

function contains(boundaries, point, minCondition, maxCondition) {
  var len = boundaries.length;

  for (var i = 1; i < len; i += 2) {
    if (minCondition(boundaries[i - 1], point) && maxCondition(point, boundaries[i])) {
      return true;
    }
  }

  return false;
}

function rangeCollection() {
  var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var maxCondition;
  var minCondition;
  var boundaries = [];

  function fn() {}

  fn.configure = function () {
    var c = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var _c$includeMax = c.includeMax,
        includeMax = _c$includeMax === void 0 ? true : _c$includeMax,
        _c$includeMin = c.includeMin,
        includeMin = _c$includeMin === void 0 ? true : _c$includeMin;
    maxCondition = includeMax ? lessThanOrEqual : lessThan;
    minCondition = includeMin ? lessThanOrEqual : lessThan;
  };

  fn.add = function (_ref) {
    var _boundaries;

    var min = _ref.min,
        max = _ref.max;
    var i0 = picasso_esm_index(boundaries, min);
    var i1 = picasso_esm_index(boundaries, max, true);
    var args = [i0, i1 - i0];

    if (i0 % 2 === 0) {
      args.push(min);
    }

    if (i1 % 2 === 0) {
      args.push(max);
    }

    var before = boundaries.join(',');

    (_boundaries = boundaries).splice.apply(_boundaries, args);

    var after = boundaries.join(',');
    return before !== after;
  };

  fn.remove = function (_ref2) {
    var _boundaries2;

    var min = _ref2.min,
        max = _ref2.max;
    var i0 = picasso_esm_index(boundaries, min);
    var i1 = picasso_esm_index(boundaries, max, true);
    var args = [i0, i1 - i0];

    if (i0 % 2 === 1) {
      args.push(min);
    }

    if (i1 % 2 === 1) {
      args.push(max);
    }

    var before = boundaries.join(',');

    (_boundaries2 = boundaries).splice.apply(_boundaries2, args);

    var after = boundaries.join(',');
    return before !== after;
  };

  fn.set = function (range) {
    var before = boundaries.join(',');
    boundaries = [];

    if (Array.isArray(range)) {
      range.forEach(fn.add);
    } else {
      fn.add(range);
    }

    var after = boundaries.join(',');
    return before !== after;
  };

  fn.clear = function () {
    var before = boundaries.length > 0;
    boundaries = [];
    return before;
  };

  fn.containsValue = function (value) {
    return contains(boundaries, value, minCondition, maxCondition);
  };

  fn.containsRange = function (_ref3) {
    var min = _ref3.min,
        max = _ref3.max;
    var i0 = picasso_esm_index(boundaries, min, true);
    var i1 = picasso_esm_index(boundaries, max);
    return i0 === i1 && i1 % 2 === 1;
  };

  fn.toggle = function (range) {
    if (fn.containsRange(range)) {
      return fn.remove(range);
    }

    return fn.add(range);
  };

  fn.ranges = function () {
    var collection = [];

    for (var i = 1; i < boundaries.length; i += 2) {
      collection.push({
        min: boundaries[i - 1],
        max: boundaries[i]
      });
    }

    return collection;
  };

  fn.configure(config);
  return fn;
}

function valueCollection() {
  var values = [];

  function vc() {}

  vc.add = function (value) {
    if (values.indexOf(value) === -1) {
      values.push(value);
      return true;
    }

    return false;
  };

  vc.remove = function (value) {
    var idx = values.indexOf(value);

    if (idx !== -1) {
      values.splice(idx, 1);
      return true;
    }

    return false;
  };

  vc.contains = function (value) {
    return values.indexOf(value) !== -1;
  };

  vc.values = function () {
    return values.slice();
  };

  vc.clear = function () {
    return values = [];
  };

  vc.toString = function () {
    return values.join(';');
  };

  return vc;
}

/**
 * @typedef {object} brush-config
 * @property {Array<brush-config--ranges>} [ranges] - Range configurations
 */

/**
 * @typedef {object}
 * @alias brush-config--ranges
 */

var DEFAULT_RANGE_CONFIG = {
  /**
   * An identifier that represents the data source of the value
   * @type {string=}
   */
  key: undefined,

  /**
   * Whether or not the minimum value of a range should be included when determening if a value is brushed.
   * @type {boolean=} */
  includeMin: true,

  /**
   * Whether or not the maximum value of a range should be included when determening if a value is brushed.
   * @type {boolean=} */
  includeMax: true
};

function add(_ref) {
  var items = _ref.items,
      collection = _ref.collection,
      vc = _ref.vc;
  var changedMap = {};
  var changed = [];
  var key;
  var values;

  for (var i = 0, num = items.length; i < num; i++) {
    key = items[i].key;

    if (!collection[key]) {
      collection[key] = vc();
    }

    values = items[i].values || [items[i].value];

    for (var vi = 0; vi < values.length; vi++) {
      if (collection[key].add(values[vi])) {
        changedMap[key] = changedMap[key] || [];
        changedMap[key].push(values[vi]);
      }
    }
  }

  var keys = Object.keys(changedMap);

  for (var _i = 0, _num = keys.length; _i < _num; _i++) {
    key = keys[_i];
    changed.push({
      id: key,
      values: changedMap[key]
    });
  }

  return changed;
}

function picasso_esm_remove(_ref2) {
  var items = _ref2.items,
      collection = _ref2.collection;
  var changedMap = {};
  var changed = [];
  var key;
  var values;

  for (var i = 0, num = items.length; i < num; i++) {
    key = items[i].key;

    if (!collection[key]) {
      continue;
    }

    values = items[i].values || [items[i].value];

    for (var vi = 0; vi < values.length; vi++) {
      if (collection[key].remove(values[vi])) {
        changedMap[key] = changedMap[key] || [];
        changedMap[key].push(values[vi]);
      }
    }
  }

  var keys = Object.keys(changedMap);

  for (var _i2 = 0, _num2 = keys.length; _i2 < _num2; _i2++) {
    key = keys[_i2];
    changed.push({
      id: key,
      values: changedMap[key]
    });
  }

  return changed;
}

function collectUnique(items) {
  var filteredSet = {};
  var key;
  var values;

  for (var i = 0, num = items.length; i < num; i++) {
    key = items[i].key;
    values = items[i].values || [items[i].value];

    if (!filteredSet[key]) {
      filteredSet[key] = [];
    }

    for (var vi = 0; vi < values.length; vi++) {
      var idx = filteredSet[key].indexOf(values[vi]);

      if (idx === -1) {
        filteredSet[key].push(values[vi]);
      }
    }
  }

  return filteredSet;
}

function createValueCollection(_ref3) {
  var key = _ref3.key,
      collection = _ref3.collection,
      obj = _ref3.obj,
      fn = _ref3.fn,
      value = _ref3.value;

  if (!collection[key]) {
    collection[key] = fn();
  }

  obj[key] = obj[key] || [];
  obj[key].push(value);
  collection[key].add(value);
}

function toggle(_ref4) {
  var items = _ref4.items,
      values = _ref4.values,
      vc = _ref4.vc;
  var addedMap = {};
  var removedMap = {};
  var added = [];
  var removed = [];
  var filteredSet = collectUnique(items);
  var key;
  var value;
  var fs;
  var setKeys = Object.keys(filteredSet);

  for (var i = 0, num = setKeys.length; i < num; i++) {
    key = setKeys[i];
    fs = filteredSet[key];

    for (var k = 0, len = fs.length; k < len; k++) {
      value = fs[k];

      if (!values[key] || !values[key].contains(value)) {
        createValueCollection({
          key: key,
          value: value,
          collection: values,
          obj: addedMap,
          fn: vc
        });
      } else if (values[key] && values[key].contains(value)) {
        removedMap[key] = removedMap[key] || [];
        removedMap[key].push(value);
        values[key].remove(value);
      }
    }
  }

  var addedKeys = Object.keys(addedMap);

  for (var _i3 = 0, _num3 = addedKeys.length; _i3 < _num3; _i3++) {
    key = addedKeys[_i3];
    added.push({
      id: key,
      values: addedMap[key]
    });
  }

  var removedKeys = Object.keys(removedMap);

  for (var _i4 = 0, _num4 = removedKeys.length; _i4 < _num4; _i4++) {
    key = removedKeys[_i4];
    removed.push({
      id: key,
      values: removedMap[key]
    });
  }

  return [added, removed];
}

function picasso_esm_diff(old, current) {
  var changed = [];
  var keys = Object.keys(old);
  var key;
  var changedValues;

  var filterFn = function filterFn(v) {
    return current[key].indexOf(v) === -1;
  };

  for (var i = 0, num = keys.length; i < num; i++) {
    key = keys[i];

    if (!current[key]) {
      changed.push({
        id: key,
        values: old[key]
      });
    } else {
      changedValues = old[key].filter(filterFn);

      if (changedValues.length) {
        changed.push({
          id: key,
          values: changedValues
        });
      }
    }
  }

  return changed;
}

function set$1(_ref5) {
  var items = _ref5.items,
      vCollection = _ref5.vCollection,
      vc = _ref5.vc;
  var addedMap = {};
  var filteredSet = collectUnique(items);
  var added = [];
  var removed = [];
  var key;
  var oldMap = {};
  var vcKeys = Object.keys(vCollection);

  for (var i = 0, num = vcKeys.length; i < num; i++) {
    key = vcKeys[i];
    oldMap[key] = vCollection[key].values().slice();
    delete vCollection[key];
  }

  var createValueCollectionFn = function createValueCollectionFn(value) {
    if (!vCollection[key] || !vCollection[key].contains(value)) {
      createValueCollection({
        key: key,
        value: value,
        collection: vCollection,
        obj: addedMap,
        fn: vc
      });
    }
  };

  var fsKeys = Object.keys(filteredSet);

  for (var _i5 = 0, _num5 = fsKeys.length; _i5 < _num5; _i5++) {
    key = fsKeys[_i5];
    filteredSet[key].forEach(createValueCollectionFn);
  }

  removed = picasso_esm_diff(oldMap, addedMap);
  added = picasso_esm_diff(addedMap, oldMap);
  return [added, removed];
}

function applyAliases(items, aliases) {
  if (!Object.keys(aliases).length) {
    return items;
  }

  var len = items.length;
  var its = Array(len);

  for (var i = 0; i < len; i++) {
    its[i] = items[i].key in aliases ? extend({}, items[i], {
      key: aliases[items[i].key]
    }) : items[i];
  }

  return its;
}

function intercept(handlers, items, aliases) {
  var its = applyAliases(items, aliases);
  return handlers && handlers.length ? handlers.reduce(function (value, interceptor) {
    return interceptor(value);
  }, its) : its;
}

function toCamelCase(s) {
  return s.replace(/(-[a-z])/g, function ($1) {
    return $1.toUpperCase().replace('-', '');
  });
}

function toSnakeCase(s) {
  return s.replace(/([A-Z])/g, function ($1) {
    return "-".concat($1.toLowerCase());
  });
}

function updateRange(items, action, _ref6) {
  var ranges = _ref6.ranges,
      interceptors = _ref6.interceptors,
      rc = _ref6.rc,
      aliases = _ref6.aliases,
      rangeConfig = _ref6.rangeConfig;
  var inter = "".concat(action, "Ranges");
  var its = intercept(interceptors[inter], items, aliases);
  var changed = false;
  its.forEach(function (item) {
    var key = item.key;

    if (!ranges[key]) {
      ranges[key] = rc(rangeConfig.sources[key] || rangeConfig.default);
    }

    if (action === 'set') {
      changed = ranges[key][action](item.ranges || item.range) || changed;
    } else {
      var rangeValues = item.ranges || [item.range];

      for (var i = 0; i < rangeValues.length; i++) {
        changed = ranges[key][action](rangeValues[i]) || changed;
      }
    }
  });
  return changed;
}

function brush() {
  var _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref7$vc = _ref7.vc,
      vc = _ref7$vc === void 0 ? valueCollection : _ref7$vc,
      _ref7$rc = _ref7.rc,
      rc = _ref7$rc === void 0 ? rangeCollection : _ref7$rc;

  var activated = false;
  var ranges = {};
  var values = {};
  var aliases = {};
  var rangeConfig = {
    sources: {},
    default: extend({}, DEFAULT_RANGE_CONFIG)
  };
  var interceptors = {
    addValues: [],
    removeValues: [],
    toggleValues: [],
    setValues: [],
    addRanges: [],
    setRanges: [],
    removeRanges: [],
    toggleRanges: []
  };

  var getState = function getState() {
    var state = {
      values: {},
      ranges: {}
    };
    Object.keys(values).forEach(function (key) {
      state.values[key] = values[key].values();
    });
    Object.keys(ranges).forEach(function (key) {
      state.ranges[key] = ranges[key].ranges();
    });
    return state;
  };

  var links = {
    ls: [],
    clear: function clear() {
      this.ls.forEach(function (b) {
        return b.clear();
      });
    },
    start: function start() {
      this.ls.forEach(function (b) {
        return b.start();
      });
    },
    end: function end() {
      this.ls.forEach(function (b) {
        return b.end();
      });
    },
    update: function update() {
      var s = getState();
      this.ls.forEach(function (b) {
        return b._state(s);
      });
    },
    updateValues: function updateValues() {
      var s = getState();
      this.ls.forEach(function (b) {
        return b._state({
          values: s.values
        });
      });
    },
    updateRanges: function updateRanges() {
      var s = getState();
      this.ls.forEach(function (b) {
        return b._state({
          ranges: s.ranges
        });
      });
    }
  };
  /**
   * A brush context
   * @alias brush
   * @interface
   */

  var fn = {};
  /**
   * Triggered when this brush is activated
   * @event brush#start
   * @type {string}
   */

  /**
   * Triggered when this brush is updated
   * @event brush#update
   * @type {string}
   * @param {Array<object>} added - The added items
   * @param {Array<object>} removed - The removed items
   */

  /**
   * Triggered when this brush is deactivated
   * @event brush#end
   * @type {string}
   */

  /**
    * Configure the brush instance.
    *
    * @param {brush-config} config
    * @example
    * brushInstance.configure({
    *   ranges: [
    *     { key: 'some key', includeMax: false },
    *     { includeMax: true, includeMin: true },
    *   ]
    * })
    */

  fn.configure = function () {
    var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

    if (Array.isArray(config.ranges) && config.ranges.length) {
      rangeConfig = {
        sources: {},
        default: extend({}, DEFAULT_RANGE_CONFIG)
      };
      config.ranges.forEach(function (cfg) {
        var c = {};
        Object.keys(DEFAULT_RANGE_CONFIG).filter(function (attr) {
          return attr !== 'key';
        }).forEach(function (attr) {
          c[attr] = typeof cfg[attr] !== 'undefined' ? cfg[attr] : DEFAULT_RANGE_CONFIG[attr];
        });

        if (typeof cfg.key !== 'undefined') {
          rangeConfig.sources[cfg.key] = c;
        } else {
          rangeConfig.default = c;
        }
      });
      Object.keys(ranges).forEach(function (key) {
        return ranges[key].configure(rangeConfig.sources[key] || rangeConfig.default);
      }); // TODO only emit update if config has changed

      fn.emit('update', [], []);
    }
  };
  /**
   * Link this brush to another brush instance.
   *
   * When linked, the `target` will receive updates whenever this brush changes.
   * @param {brush} target - The brush instance to link to
   */


  fn.link = function (target) {
    if (fn === target) {
      throw new Error('Can\'t link to self');
    }

    links.ls.push(target);

    target._state(getState());
  };

  fn._state = function (s) {
    if (!s) {
      return getState();
    }

    if (s.values) {
      var arr = [];
      Object.keys(s.values).forEach(function (key) {
        if (!values[key] || s.values[key].join(';') !== values[key].toString()) {
          arr.push({
            key: key,
            values: s.values[key]
          });
        }
      });
      Object.keys(values).forEach(function (key) {
        if (!s.values[key]) {
          arr.push({
            key: key,
            values: []
          });
        }
      });

      if (arr.length) {
        fn.setValues(arr);
      }
    }

    if (s.ranges) {
      var _arr = [];
      Object.keys(s.ranges).forEach(function (key) {
        if (!ranges[key] || s.ranges[key].join(';') !== ranges[key].toString()) {
          _arr.push({
            key: key,
            ranges: s.ranges[key]
          });
        }
      });
      Object.keys(ranges).forEach(function (key) {
        if (!s.ranges[key]) {
          _arr.push({
            key: key,
            ranges: []
          });
        }
      });

      if (_arr.length) {
        fn.setRanges(_arr);
      }
    }

    return undefined;
  };
  /**
   * Starts this brush context
   *
   * Starts this brush context and emits a 'start' event if it is not already started.
   * @emits brush#start
   */


  fn.start = function () {
    if (!activated) {
      activated = true;
      fn.emit('start');
      links.start();
    }
  };
  /**
   * Ends this brush context
   *
   * Ends this brush context and emits an 'end' event if it is not already ended.
   * @emits brush#end
   */


  fn.end = function () {
    if (!activated) {
      return;
    }

    activated = false;
    ranges = {};
    values = {};
    fn.emit('end');
    links.end();
  };
  /**
   * Checks if this brush is activated
   *
   * Returns true if started, false otherwise
   * @return {boolean}
   */


  fn.isActive = function () {
    return activated;
  };
  /**
   * Clears this brush context
   */


  fn.clear = function () {
    var removed = fn.brushes().filter(function (b) {
      return b.type === 'value' && b.brush.values().length;
    }).map(function (b) {
      return {
        id: b.id,
        values: b.brush.values()
      };
    });
    var hasChanged = Object.keys(ranges).length > 0 || removed.length;
    ranges = {};
    values = {};

    if (hasChanged) {
      fn.emit('update', [], removed); // TODO - do not emit update if state hasn't changed

      links.clear();
    }
  };
  /**
   * Returns all brushes within this context
   * @return {object}
   */


  fn.brushes = function () {
    var result = [];
    result = result.concat(Object.keys(ranges).map(function (key) {
      return {
        type: 'range',
        id: key,
        brush: ranges[key]
      };
    }));
    result = result.concat(Object.keys(values).map(function (key) {
      return {
        type: 'value',
        id: key,
        brush: values[key]
      };
    }));
    return result;
  };
  /**
   * Adds a primitive value to this brush context
   *
   * If this brush context is not started, a 'start' event is emitted.
   * If the state of the brush changes, ie. if the added value does not already exist, an 'update' event is emitted.
   *
   * @param {string} key  An identifier that represents the data source of the value
   * @param {string|number} value The value to add
   * @emits brush#start
   * @emits brush#update
   * @example
   * brush.addValue('countries', 'Sweden');
   * brush.addValue('/qHyperCube/qDimensionInfo/0', 3);
   */


  fn.addValue = function (key, value) {
    fn.addValues([{
      key: key,
      value: value
    }]);
  };
  /**
   * @param {object[]} items Items to add
   */


  fn.addValues = function (items) {
    var its = intercept(interceptors.addValues, items, aliases);
    var added = add({
      vc: vc,
      collection: values,
      items: its
    });
    fn.emit('add-values', its);

    if (added.length) {
      if (!activated) {
        activated = true;
        fn.emit('start');
      }

      fn.emit('update', added, []);
      links.updateValues();
    }
  };
  /**
   * @param {object[]} items Items to set
   */


  fn.setValues = function (items) {
    var its = intercept(interceptors.setValues, items, aliases);
    var changed = set$1({
      items: its,
      vCollection: values,
      vc: vc
    });
    fn.emit('set-values', its);

    if (changed[0].length > 0 || changed[1].length > 0) {
      if (!activated) {
        activated = true;
        fn.emit('start');
      }

      fn.emit('update', changed[0], changed[1]);
      links.updateValues();
    }
  };
  /**
   * Removes a primitive values from this brush context
   *
   * If the state of the brush changes, ie. if the removed value does exist, an 'update' event is emitted.
   *
   * @param  {string} key  An identifier that represents the data source of the value
   * @param  {string|number} value The value to remove
   * @example
   * brush.removeValue('countries', 'Sweden');
   */


  fn.removeValue = function (key, value) {
    fn.removeValues([{
      key: key,
      value: value
    }]);
  };
  /**
   * @param {object[]} items Items to remove
   */


  fn.removeValues = function (items) {
    var its = intercept(interceptors.removeValues, items, aliases);
    var removed = picasso_esm_remove({
      collection: values,
      items: its
    });
    fn.emit('remove-values', its);

    if (removed.length) {
      fn.emit('update', [], removed);
      links.updateValues(); // TODO - emit 'end' event if there are no remaining active brushes
    }
  };
  /**
   * Add and remove values in a single operation
   * almost the same as calling addValues and removeValues but only triggers one 'update' event
   *
   * If the state of the brush changes, an 'update' event is emitted.
   *
   * @param {object[]} addItems Items to add
   * @param {object[]} removeItems Items to remove
   */


  fn.addAndRemoveValues = function (addItems, removeItems) {
    var addIts = intercept(interceptors.addValues, addItems, aliases);
    var removeIts = intercept(interceptors.removeValues, removeItems, aliases);
    var added = add({
      vc: vc,
      collection: values,
      items: addIts
    });
    var removed = picasso_esm_remove({
      collection: values,
      items: removeIts
    });
    fn.emit('add-values', addIts);
    fn.emit('remove-values', removeIts);

    if (added.length || removed.length) {
      if (!activated) {
        activated = true;
        fn.emit('start');
      }

      fn.emit('update', added, removed);
      links.updateValues();
    }
  };
  /**
   * Toggles a primitive value in this brush context
   *
   * If the given value exist in this brush context, it will be removed. If it does not exist it will be added.
   *
   * @param  {string} key  An identifier that represents the data source of the value
   * @param  {string|number} value The value to toggle
   * @example
   * brush.toggleValue('countries', 'Sweden');
   */


  fn.toggleValue = function (key, value) {
    fn.toggleValues([{
      key: key,
      value: value
    }]);
  };
  /**
   * @param {object[]} items Items to toggle
   */


  fn.toggleValues = function (items) {
    var its = intercept(interceptors.toggleValues, items, aliases);
    var toggled = toggle({
      items: its,
      values: values,
      vc: vc
    });
    fn.emit('toggle-values', its);

    if (toggled[0].length > 0 || toggled[1].length > 0) {
      if (!activated) {
        activated = true;
        fn.emit('start');
      }

      fn.emit('update', toggled[0], toggled[1]);
      links.updateValues();
    }
  };
  /**
   * Checks if a certain value exists in this brush context
   *
   * Returns true if the values exists for the provided key, returns false otherwise.
   *
   * @param  {string} key  An identifier that represents the data source of the value
   * @param  {string|number} value The value to check for
   * @return {boolean}
   * @example
   * brush.addValue('countries', 'Sweden');
   * brush.containsValue('countries', 'Sweden'); // true
   * brush.toggleValue('countries', 'Sweden'); // remove 'Sweden'
   * brush.containsValue('countries', 'Sweden'); // false
   */


  fn.containsValue = function (key, value) {
    var k = aliases[key] || key;

    if (!values[k]) {
      return false;
    }

    return values[k].contains(value);
  };
  /**
   * Adds a numeric range to this brush context
   *
   * @param {string} key - An identifier that represents the data source of the range
   * @param {object} range - The range to add to this brush
   * @param {number} range.min - Min value of the range
   * @param {number} range.max - Max value of the range
   * @example
   * brush.addRange('Sales', { min: 20, max: 50 });
   */


  fn.addRange = function (key, range) {
    fn.addRanges([{
      key: key,
      range: range
    }]);
  };
  /**
   * @see {brush.addRange}
   * @param {object[]} items - Items containing the ranges to remove
   * @param {string} items[].key
   * @param {object} items[].range
   */


  fn.addRanges = function (items) {
    var changed = updateRange(items, 'add', {
      ranges: ranges,
      rc: rc,
      interceptors: interceptors,
      aliases: aliases,
      rangeConfig: rangeConfig
    });

    if (!changed) {
      return;
    }

    if (!activated) {
      activated = true;
      fn.emit('start');
    }

    fn.emit('update', [], []);
    links.updateRanges();
  };
  /**
   * Removes a numeric range from this brush context
   *
   * @param {string} key - An identifier that represents the data source of the range
   * @param {object} range - The range to remove from this brush
   * @param {number} range.min - Min value of the range
   * @param {number} range.max - Max value of the range
   */


  fn.removeRange = function (key, range) {
    fn.removeRanges([{
      key: key,
      range: range
    }]);
  };
  /**
   * @see {brush.removeRange}
   * @param {object[]} items - Items containing the ranges to remove
   */


  fn.removeRanges = function (items) {
    var changed = updateRange(items, 'remove', {
      ranges: ranges,
      rc: rc,
      interceptors: interceptors,
      aliases: aliases,
      rangeConfig: rangeConfig
    });

    if (!changed) {
      return;
    }

    if (!activated) {
      activated = true;
      fn.emit('start');
    }

    fn.emit('update', [], []);
    links.updateRanges();
  };
  /**
   * Sets a numeric range to this brush context
   *
   * Overwrites any active ranges identified by `key`
   *
   * @param {string} key - An identifier that represents the data source of the range
   * @param {object} range - The range to set on this brush
   * @param {number} range.min - Min value of the range
   * @param {number} range.max - Max value of the range
   */


  fn.setRange = function (key, range) {
    fn.setRanges([{
      key: key,
      range: range
    }]);
  };
  /**
   * @see {brush.setRange}
   * @param {object[]} items - Items containing the ranges to set
   */


  fn.setRanges = function (items) {
    var changed = updateRange(items, 'set', {
      ranges: ranges,
      rc: rc,
      interceptors: interceptors,
      aliases: aliases,
      rangeConfig: rangeConfig
    });

    if (!changed) {
      return;
    }

    if (!activated) {
      activated = true;
      fn.emit('start');
    }

    fn.emit('update', [], []);
    links.updateRanges();
  };
  /**
   * Toggles a numeric range in this brush context
   *
   * Removes the range if it's already contained within the given identifier,
   * otherwise the given range is added to the brush.
   *
   * @param {string} key - An identifier that represents the data source of the range
   * @param {object} range - The range to toggle in this brush
   * @param {number} range.min - Min value of the range
   * @param {number} range.max - Max value of the range
   */


  fn.toggleRange = function (key, range) {
    fn.toggleRanges([{
      key: key,
      range: range
    }]);
  };
  /**
   * @see {brush.toggleRange}
   * @param {object[]} items - Items containing the ranges to toggle
   */


  fn.toggleRanges = function (items) {
    var changed = updateRange(items, 'toggle', {
      ranges: ranges,
      rc: rc,
      interceptors: interceptors,
      aliases: aliases,
      rangeConfig: rangeConfig
    });

    if (!changed) {
      return;
    }

    if (!activated) {
      activated = true;
      fn.emit('start');
    }

    fn.emit('update', [], []);
    links.updateRanges();
  };
  /**
   * Checks if a value is contained within a range in this brush context
   *
   * Returns true if the values exists for the provided key, returns false otherwise.
   *
   * @param  {string} key - An identifier that represents the data source of the value
   * @param  {number} value - The value to check for
   * @return {boolean}
   * @example
   * brush.addRange('Sales', { min: 10, max: 50 });
   * brush.containsRangeValue('Sales', 30); // true
   * brush.containsRangeValue('Sales', 5); // false
   */


  fn.containsRangeValue = function (key, value) {
    var k = aliases[key] || key;

    if (!ranges[k]) {
      return false;
    }

    return ranges[k].containsValue(value);
  };
  /**
   * Checks if a range segment is contained within this brush context
   *
   * Returns true if the range segment exists for the provided key, returns false otherwise.
   *
   * @param {string} key - An identifier that represents the data source of the value
   * @param {object} range - The range to check for
   * @param {number} range.min - Min value of the range
   * @param {number} range.max - Max value of the range
   * @return {boolean}
   * @example
   * brush.addRange('Sales', { min: 10, max: 50 });
   * brush.containsRange('Sales', { min: 15, max: 20 }); // true - the range segment is fully contained within [10, 50]
   * brush.containsRange('Sales', { min: 5, max: 20 }); // false - part of the range segment is outside [10, 50]
   * brush.containsRange('Sales', { min: 30, max: 80 }); // false - part of the range segment is outside [10, 50]
   */


  fn.containsRange = function (key, range) {
    var k = aliases[key] || key;

    if (!ranges[k]) {
      return false;
    }

    return ranges[k].containsRange(range);
  };

  fn.containsMappedData = function (d, props, mode) {
    var status = [];
    var keys = Object.keys(d);
    var key;
    var item;
    var source;
    var value;

    for (var i = 0, num = keys.length; i < num; i++) {
      key = keys[i];

      if (key === 'value') {
        item = d;
        status[i] = {
          key: '',
          i: i,
          bool: false
        };
      } else if (key === 'source') {
        continue;
      } else {
        item = d[key];
        status[i] = {
          key: key,
          i: i,
          bool: false
        };
      }

      source = item.source && item.source.field;

      if (typeof source === 'undefined') {
        continue;
      }

      if (typeof item.source.key !== 'undefined') {
        source = "".concat(item.source.key, "/").concat(source);
      }

      if (source in aliases) {
        source = aliases[source];
      }

      value = item.value;

      if (ranges[source]) {
        status[i].bool = Array.isArray(value) ? ranges[source].containsRange({
          min: value[0],
          max: value[1]
        }) : ranges[source].containsValue(value);
      } else if (values[source] && values[source].contains(value)) {
        status[i].bool = true;
      }
    }

    if (props) {
      status = status.filter(function (b) {
        return props.indexOf(b.key) !== -1;
      });

      if (mode === 'and') {
        return !!status.length && !status.some(function (s) {
          return s.bool === false;
        });
      }

      if (mode === 'xor') {
        return !!status.length && status.some(function (s) {
          return s.bool;
        }) && status.some(function (s) {
          return s.bool === false;
        });
      } // !mode || mode === 'or'


      return status.some(function (s) {
        return s.bool;
      });
    }

    return status.some(function (s) {
      return s.bool;
    });
  };
  /**
   * Adds an event interceptor
   *
   * @param {string} name Name of the event to intercept
   * @param {function} ic Handler to call before event is triggered
   * @example
   * brush.intercept('add-values', items => {
   *  console.log('about to add the following items', items);
   *  return items;
   * });
   */


  fn.intercept = function (name, ic) {
    var s = toCamelCase(name);

    if (!interceptors[s]) {
      return;
    }

    interceptors[s].push(ic);
  };
  /**
   * Removes an interceptor
   *
   * @param {string} name Name of the event to intercept
   * @param {function} ic Handler to remove
   */


  fn.removeInterceptor = function (name, ic) {
    var s = toCamelCase(name);

    if (!interceptors[s]) {
      return;
    }

    var idx = interceptors[s].indexOf(ic);

    if (idx !== -1) {
      interceptors[s].splice(idx, 1);
    }
  };
  /**
   * Removes all interceptors
   *
   * @param {string} [name] Name of the event to remove interceptors for. If not provided, removes all interceptors.
   */


  fn.removeAllInterceptors = function (name) {
    var toRemove = [];

    if (name) {
      var s = toCamelCase(name);

      if (interceptors[s] && interceptors[s].length) {
        toRemove.push({
          name: name,
          handlers: interceptors[s]
        });
      }
    } else {
      Object.keys(interceptors).forEach(function (n) {
        if (interceptors[n].length) {
          toRemove.push({
            name: toSnakeCase(n),
            handlers: interceptors[n]
          });
        }
      });
    }

    toRemove.forEach(function (ic) {
      var interceptorHandlers = ic.handlers.slice();
      interceptorHandlers.forEach(function (handler) {
        return fn.removeInterceptor(ic.name, handler);
      });
    });
  };
  /**
   * Adds an alias to the given key
   *
   * @param {string} key - Value to be replaced
   * @param {string} alias - Value to replace key with
   * @example
   * brush.addKeyAlias('BadFieldName', 'Region');
   * brush.addValue('BadFieldName', 'Sweden'); // 'BadFieldName' will be stored as 'Region'
   * brush.containsValue('Region', 'Sweden'); // true
   * brush.containsValue('BadFieldName', 'Sweden'); // true
   */


  fn.addKeyAlias = function (key, alias) {
    aliases[key] = alias;
  };
  /**
   * Removes an alias
   *
   * This will only remove the key to alias mapping for new manipulations of the brush,
   * no changes will be made to the current state of this brush.
   *
   * @param {string} key - Value to remove as alias
   * @example
   * brush.removeKeyAlias('BadFieldName');
   */


  fn.removeKeyAlias = function (key) {
    delete aliases[key];
  };

  EventEmitter$1.mixin(fn);
  return fn;
}

var reg = registryFactory();

function cubicInOut(t) {
  return ((t *= 2) <= 1 ? t * t * t : (t -= 2) * t * t + 2) / 2;
}

var tau$2 = 2 * Math.PI,
    amplitude = 1,
    period = 0.3;

var elasticOut = (function custom(a, p) {
  var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau$2);

  function elasticOut(t) {
    return 1 - a * Math.pow(2, -10 * (t = +t)) * Math.sin((t + s) / p);
  }

  elasticOut.amplitude = function(a) { return custom(a, p * tau$2); };
  elasticOut.period = function(p) { return custom(a, p); };

  return elasticOut;
})(amplitude, period);

/* globals window */

function nodeId(node, i) {
  if (node.data) {
    return node.data.value;
  }

  if (node.type === 'text') {
    return node.text;
  }

  return i;
}

function picasso_esm_tween(_ref, _ref2, config) {
  var old = _ref.old,
      current = _ref.current;
  var renderer = _ref2.renderer;
  var ticker; // let staticNodes = [];

  var toBeUpdated = [];
  var entered = {
    nodes: [],
    ips: []
  };
  var exited = {
    nodes: [],
    ips: []
  };
  var updated = {
    nodes: [],
    ips: []
  };
  var stages = [];
  var trackBy = config.trackBy || nodeId;
  var tweener = {
    start: function start() {
      var ids = {};
      old.forEach(function (node, i) {
        var id = trackBy(node, i);
        ids[id] = node;
      });
      current.forEach(function (node, i) {
        var id = trackBy(node, i);

        if (ids[id]) {
          updated.ips.push(interpolateObject(ids[id], node));
          updated.nodes.push(node);
          toBeUpdated.push(ids[id]);
          ids[id] = false;
        } else {
          entered.nodes.push(node);
          entered.ips.push(interpolateObject({
            r: 0.001,
            opacity: 0
          }, node));
        }
      });
      Object.keys(ids).forEach(function (key) {
        if (ids[key]) {
          exited.nodes.push(ids[key]);
          exited.ips.push(interpolateObject(ids[key], extend({}, ids[key], {
            r: 0.0001,
            opacity: 0
          })));
        }
      });

      if (exited.ips.length) {
        stages.push({
          easing: cubicInOut,
          duration: 200,
          tweens: exited.ips,
          nodes: [].concat(toBeUpdated)
        });
      }

      if (updated.ips.length) {
        stages.push({
          easing: cubicInOut,
          duration: 400,
          tweens: updated.ips,
          nodes: []
        });
      }

      if (entered.ips.length) {
        stages.push({
          easing: elasticOut,
          duration: 1200,
          tweens: entered.ips,
          nodes: _toConsumableArray$1(updated.nodes)
        });
      } // console.log(stages);


      if (stages.length) {
        stages[0].started = Date.now();

        if (typeof window !== 'undefined') {
          ticker = window.requestAnimationFrame(tweener.tick);
        }
      }
    },
    tick: function tick() {
      var currentStage = stages[0];

      if (!currentStage) {
        tweener.stop();
      }

      if (!currentStage.started) {
        currentStage.started = Date.now();
      }

      var t = (Date.now() - currentStage.started) / currentStage.duration;
      var currentNodes = [];
      var tweenedNodes = currentStage.tweens.map(function (ip) {
        return ip(currentStage.easing(Math.min(1, t)));
      });
      currentNodes.push.apply(currentNodes, _toConsumableArray$1(tweenedNodes));
      currentNodes.push.apply(currentNodes, _toConsumableArray$1(currentStage.nodes)); // currentNodes.push(...staticNodes);
      // stages.slice(1).forEach(stage => currentNodes.push(...stage.nodes));

      renderer.render(currentNodes);

      if (t >= 1) {
        // staticNodes.push(...currentStage.nodes);
        stages.shift();

        if (!stages.length) {
          tweener.stop();
        }
      }

      if (ticker) {
        ticker = window.requestAnimationFrame(tweener.tick);
      }
    },
    stop: function stop() {
      if (ticker) {
        window.cancelAnimationFrame(ticker);
        ticker = false;
      }
    }
  };
  return tweener;
}

var GLOBAL_DEFAULTS = {
  fontFamily: 'Arial',
  fontSize: '13px',
  color: '#595959',
  backgroundColor: '#ffffff',
  stroke: '#000000',
  strokeWidth: 0,
  $fill: '#333333'
};
var REF_RX = /^\$/;

function isPrimitive(x) {
  var type = _typeof(x);

  return type !== 'object' && type !== 'function' && type !== 'undefined';
}
/**
 * @callback datum-accessor
 * @param {datum-extract} d
 */

/**
 * @typedef {object} datum-config
 * @property {string} [scale]
 * @property {datum-accessor} fn
 * @property {string} ref - A reference to a datum-extract property
 */

/**
 * @typedef {string|datum-config|datum-accessor} datum-string
 */

/**
 * @typedef {number|datum-config|datum-accessor} datum-number
 */

/**
 * @typedef {boolean|datum-config|datum-accessor} datum-boolean
 */

/**
 * Normalizes property settings
 *
 * @ignore
 * @export
 * @param {any} settings
 * @param {any} defaults
 * @param {any} chart
 * @returns {any}
 */


function normalizeSettings(settings, defaults, chart) {
  var composition = extend({}, settings);
  var defs = extend({}, defaults);
  Object.keys(composition).forEach(function (key) {
    defs[key] = {};
    var v = composition[key];

    var vType = _typeof(v);

    if (typeof v === 'function') {
      defs[key].fn = v;
    } else if (isPrimitive(v)) {
      var defaultValue = defaults[key];

      if (typeof defaultValue === 'string' && REF_RX.test(defaultValue)) {
        defaultValue = GLOBAL_DEFAULTS[defaultValue];
      }

      var defaultType = _typeof(defaultValue);

      if (defaultType === 'undefined') {
        // if property has no default, assign provided value
        defs[key] = v;
      } else {
        // assign provided value if it's of same type as default, otherwise use default
        defs[key] = defaultType === vType ? v : defaultValue;
      }
    } else if (v && _typeof(v) === 'object') {
      if (typeof v.fn === 'function') {
        defs[key].fn = v.fn;
      }

      if (typeof v.scale !== 'undefined') {
        defs[key].scale = chart.scale(v.scale);
      }

      if (typeof v.ref === 'string') {
        defs[key].ref = v.ref;
      }
    }
  });
  Object.keys(defaults).forEach(function (key) {
    if (key in composition) {
      // don't process same props again
      return;
    }

    var v = defaults[key];

    var defaultType = _typeof(v);

    if (defaultType === 'string' && REF_RX.test(v)) {
      defs[key] = GLOBAL_DEFAULTS[v];
    } else {
      defs[key] = v;
    }
  });
  return defs;
}
function resolveForItem(context, normalized, idx) {
  var ret = {};
  var keys = Object.keys(normalized);
  var len = keys.length;
  var fallbackData = context.datum;
  var datum = context.datum;

  for (var i = 0; i < len; i++) {
    var key = keys[i];
    var normalizedProp = normalized[key];
    var exists = _typeof(datum) === 'object' && typeof normalizedProp !== 'undefined';
    var hasExplicitDataProp = exists && typeof normalizedProp.ref === 'string';
    var hasImplicitDataProp = exists && key in datum;
    var propData = hasExplicitDataProp ? datum[normalizedProp.ref] : hasImplicitDataProp ? datum[key] : fallbackData; // eslint-disable-line

    if (isPrimitive(normalizedProp)) {
      ret[key] = normalizedProp;
    } else if (exists && normalizedProp.fn) {
      // callback function
      if (normalizedProp.scale) {
        context.scale = normalizedProp.scale;
      }

      ret[key] = normalizedProp.fn.call(null, context, idx);
    } else if (exists && normalizedProp.scale && propData) {
      ret[key] = normalizedProp.scale(propData.value);

      if (normalizedProp.scale.bandwidth) {
        ret[key] += normalizedProp.scale.bandwidth() / 2;
      }
    } else if (hasExplicitDataProp && propData) {
      ret[key] = propData.value;
    } else if (normalizedProp.fn) {
      ret[key] = normalizedProp.fn.call(null, context, idx);
    } else {
      ret[key] = normalizedProp;
    }
  }

  return ret;
}

function updateScaleSize(object, path, size) {
  var o = object[path];

  if (o && o.scale && o.scale.pxScale) {
    o.scale = o.scale.pxScale(size);
  } else if (o && o.pxScale) {
    object[path] = o.pxScale(size);
  }
}
function scaleWithSize(scale, size) {
  return scale.pxScale ? scale.pxScale(size) : scale;
}

var externals = {
  normalizeSettings: normalizeSettings,
  resolveForItem: resolveForItem,
  updateScaleSize: updateScaleSize
};
function settingsResolver (resources) {
  var deps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : externals;
  var cache = {};

  function resolve(_ref) {
    var data = _ref.data,
        settings = _ref.settings,
        _ref$defaults = _ref.defaults,
        defaults = _ref$defaults === void 0 ? {} : _ref$defaults,
        scaled = _ref.scaled;
    var norm = cache.norm = deps.normalizeSettings(settings, defaults, resources.chart);
    var res = {
      scale: resources.chart.scale,
      formatter: resources.chart.formatter
    };

    if (scaled) {
      Object.keys(scaled).forEach(function (key) {
        if (norm[key]) {
          deps.updateScaleSize(norm, key, scaled[key]);
        }
      });
    }

    var resolved = [];

    if (data && Array.isArray(data.items)) {
      var context;

      for (var i = 0, len = data.items.length; i < len; i++) {
        context = {
          datum: data.items[i],
          data: data,
          resources: res
        };
        var obj = deps.resolveForItem(context, cache.norm, i);
        obj.data = data.items[i];
        resolved.push(obj);
      }
    } else {
      var _context = {
        data: data,
        resources: res
      };

      var _obj = deps.resolveForItem(_context, cache.norm, -1);

      return {
        settings: cache.norm,
        item: _obj
      };
    }

    return {
      settings: cache.norm,
      items: resolved
    };
  }

  return {
    resolve: resolve
  };
}

/**
 * Flatten the array of nodes by removing any containers as they do not support styling, thus unable to brush them.
 * @param {array} nodes
 * @ignore
 */

function reduceToLeafNodes() {
  var nodes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  return nodes.reduce(function (ary, node) {
    if (Array.isArray(node.children)) {
      ary.push.apply(ary, _toConsumableArray$1(reduceToLeafNodes(node.children)));
      return ary;
    }

    ary.push(node);
    return ary;
  }, []);
}
function styler(obj, _ref) {
  var context = _ref.context,
      data = _ref.data,
      style = _ref.style,
      filter = _ref.filter,
      mode = _ref.mode;
  var brusher = obj.chart.brush(context);
  var dataProps = data;
  var active = style.active || {};
  var inactive = style.inactive || {};
  var styleProps = [];
  Object.keys(active).forEach(function (key) {
    styleProps.push(key);
  });
  Object.keys(inactive).forEach(function (key) {
    if (styleProps.indexOf(key) === -1) {
      styleProps.push(key);
    }
  });
  var activeNodes = [];
  var globalActivation = false; // track when we need to loop through all nodes, not just the active ones

  var getNodes = function getNodes() {
    var nodes = reduceToLeafNodes(obj.nodes);

    if (typeof filter === 'function') {
      nodes = nodes.filter(filter);
    }

    return nodes;
  };

  var update = function update() {
    // TODO - render nodes only once, i.e. don't render for each brush, update nodes for all brushes and then render
    var nodes = getNodes();
    var len = nodes.length;
    var nodeData;
    var globalChanged = false;

    var _loop = function _loop(i) {
      // TODO - update only added and removed nodes
      nodeData = nodes[i].data;

      if (!nodeData) {
        return "continue";
      }

      if (!nodes[i].__style) {
        nodes[i].__style = {};
        styleProps.forEach(function (s) {
          nodes[i].__style[s] = nodes[i][s]; // store original value
        });
      }

      var isActive = brusher.containsMappedData(nodeData, dataProps, mode);
      var activeIdx = activeNodes.indexOf(nodes[i]);
      var changed = false;

      if (isActive && activeIdx === -1) {
        // activated
        activeNodes.push(nodes[i]);
        changed = true;
      } else if (!isActive && activeIdx !== -1) {
        // was active
        activeNodes.splice(activeIdx, 1);
        changed = true;
      }

      if (changed || globalActivation) {
        var original = extend({}, nodes[i], nodes[i].__style);
        styleProps.forEach(function (s) {
          if (isActive && s in active) {
            nodes[i][s] = typeof active[s] === 'function' ? active[s].call(null, original) : active[s];
          } else if (!isActive && s in inactive) {
            nodes[i][s] = typeof inactive[s] === 'function' ? inactive[s].call(null, original) : inactive[s];
          } else {
            nodes[i][s] = nodes[i].__style[s];
          }
        });
        globalChanged = true;
      }
    };

    for (var i = 0; i < len; i++) {
      var _ret = _loop(i);

      if (_ret === "continue") continue;
    }

    globalActivation = false;
    return globalChanged;
  };

  var onStart = function onStart() {
    var nodes = getNodes();
    var len = nodes.length;

    var _loop2 = function _loop2(i) {
      if (!nodes[i].data) {
        return "continue";
      }

      nodes[i].__style = nodes[i].__style || {};
      styleProps.forEach(function (s) {
        nodes[i].__style[s] = nodes[i][s]; // store original value

        if (s in inactive) {
          nodes[i][s] = typeof inactive[s] === 'function' ? inactive[s].call(null, nodes[i]) : inactive[s];
        }
      });
    };

    for (var i = 0; i < len; i++) {
      var _ret2 = _loop2(i);

      if (_ret2 === "continue") continue;
    }

    globalActivation = true;
    activeNodes.length = 0;
    obj.renderer.render(obj.nodes);
  };

  var onEnd = function onEnd() {
    var nodes = getNodes();
    var len = nodes.length;

    var _loop3 = function _loop3(i) {
      if (nodes[i].__style) {
        Object.keys(nodes[i].__style).forEach(function (s) {
          nodes[i][s] = nodes[i].__style[s];
        });
        nodes[i].__style = undefined;
      }
    };

    for (var i = 0; i < len; i++) {
      _loop3(i);
    }

    activeNodes.length = 0;
    obj.renderer.render(obj.nodes);
  };

  var onUpdate = function onUpdate()
  /* added, removed */
  {
    var changed = update();

    if (changed) {
      obj.renderer.render(obj.nodes);
    }
  };

  var externalUpdate = function externalUpdate() {
    activeNodes.length = 0;
    globalActivation = true;
    update();
  };

  brusher.on('start', onStart);
  brusher.on('end', onEnd);
  brusher.on('update', onUpdate);

  function cleanUp() {
    brusher.removeListener('start', onStart);
    brusher.removeListener('end', onEnd);
    brusher.removeListener('update', onUpdate);
  }

  return {
    isActive: function isActive() {
      return brusher.isActive();
    },
    update: externalUpdate,
    cleanUp: cleanUp
  };
}
function brushDataPoints(_ref2) {
  var dataPoints = _ref2.dataPoints,
      action = _ref2.action,
      chart = _ref2.chart,
      trigger = _ref2.trigger;

  if (!trigger) {
    return;
  }

  var dataProps = trigger.data || [''];
  var rangeBrush = {
    items: [],
    actionFn: 'toggleRanges'
  };
  var valueBrush = {
    items: [],
    actionFn: 'toggleValues'
  };

  if (['add', 'remove', 'set', 'toggle'].indexOf(action) !== -1) {
    rangeBrush.actionFn = "".concat(action, "Ranges");
    valueBrush.actionFn = "".concat(action, "Values");
  }

  var _loop4 = function _loop4(i) {
    var dataPoint = dataPoints[i];

    if (!dataPoint) {
      return "continue";
    }

    dataProps.forEach(function (p) {
      var d = dataPoint && !p ? dataPoint : dataPoint[p];

      if (d) {
        var it = {
          key: d.source.field
        };

        if (typeof d.source.key !== 'undefined') {
          it.key = "".concat(d.source.key, "/").concat(d.source.field);
        }

        if (Array.isArray(d.value)) {
          it.range = {
            min: d.value[0],
            max: d.value[1]
          };
          rangeBrush.items.push(it);
        } else {
          it.value = d.value;
          valueBrush.items.push(it);
        }
      }
    });
  };

  for (var i = 0; i < dataPoints.length; i++) {
    var _ret3 = _loop4(i);

    if (_ret3 === "continue") continue;
  }

  trigger.contexts.forEach(function (c) {
    if (rangeBrush.items.length) {
      chart.brush(c)[rangeBrush.actionFn](rangeBrush.items);
    } else {
      chart.brush(c)[valueBrush.actionFn](valueBrush.items); // call action even if there are items to potentially clear what is currently in the brush
    }
  });
}
function brushFromSceneNodes(_ref3) {
  var nodes = _ref3.nodes,
      action = _ref3.action,
      chart = _ref3.chart,
      trigger = _ref3.trigger;
  var dataPoints = [];

  for (var i = 0; i < nodes.length; i++) {
    var node = nodes[i];
    var nodeData = node.data;

    if (nodeData !== null) {
      dataPoints.push(nodeData);
    }
  }

  brushDataPoints({
    dataPoints: dataPoints,
    action: action,
    chart: chart,
    trigger: trigger
  });
}
function resolveEvent(_ref4) {
  var collisions = _ref4.collisions,
      t = _ref4.t,
      config = _ref4.config,
      action = _ref4.action;
  var brushCollisions = [];
  var resolved = false;

  if (collisions.length > 0) {
    brushCollisions = collisions;
    resolved = true;

    if (t.propagation === 'stop') {
      brushCollisions = [collisions[collisions.length - 1]];
    }
  }

  var nodes = brushCollisions.map(function (c) {
    return c.node;
  });
  brushFromSceneNodes({
    nodes: nodes,
    action: action,
    chart: config.chart,
    data: config.data,
    trigger: t
  });
  return resolved;
}

function touchSingleContactPoint(e, rect) {
  if (e.changedTouches.length !== 1) {
    return null;
  }

  return {
    x: e.changedTouches[0].clientX - rect.left,
    y: e.changedTouches[0].clientY - rect.top
  };
}

function singleContactPoint(e, rect) {
  return {
    x: e.clientX - rect.left,
    y: e.clientY - rect.top
  };
}

function resolveCollisions(e, t, renderer) {
  var rect = renderer.element().getBoundingClientRect();
  var p = isTouchEvent(e) ? touchSingleContactPoint(e, rect) : singleContactPoint(e, rect);

  if (p === null || p.x < 0 || p.y < 0 || p.x > rect.width || p.y > rect.height) {
    // TODO include radius in this check?
    return [];
  }

  if (t.touchRadius > 0 && isTouchEvent(e)) {
    p = {
      cx: p.x,
      cy: p.y,
      r: t.touchRadius // TODO Use touch event radius/width value (Need to handle dpi scaling as well)

    };
  }

  return renderer.itemsAt(p);
}

function resolveAction(action, e, def) {
  if (action) {
    if (typeof action === 'function') {
      return action(e);
    }

    return action;
  }

  return def;
}

function resolveTapEvent(_ref5) {
  var e = _ref5.e,
      t = _ref5.t,
      config = _ref5.config;
  var collisions = resolveCollisions(e, t, config.renderer);
  return resolveEvent({
    collisions: collisions,
    t: t,
    config: config,
    action: resolveAction(t.action, e, 'toggle')
  });
}
function resolveOverEvent(_ref6) {
  var e = _ref6.e,
      t = _ref6.t,
      config = _ref6.config;
  var collisions = resolveCollisions(e, t, config.renderer);
  return resolveEvent({
    collisions: collisions,
    t: t,
    config: config,
    action: resolveAction(t.action, e, 'set')
  });
}

/**
 * A list of supported attributes in lower camelCase notation mapped to corresponding kebab-case notation.
 * The kebab-case notations are a sub-set of SVG attributes (https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute).
 * @ignore
 */
var mappedAttributes = {
  fill: 'fill',
  stroke: 'stroke',
  opacity: 'opacity',
  strokeWidth: 'stroke-width',
  strokeLinejoin: 'stroke-linejoin',
  fontFamily: 'font-family',
  fontSize: 'font-size',
  baseline: 'dominant-baseline',
  // Special case where we have defined our own attribute name
  dominantBaseline: 'dominant-baseline',
  anchor: 'text-anchor',
  // Special case where we have defined our own attribute name
  textAnchor: 'text-anchor',
  maxWidth: 'maxWidth',
  transform: 'transform',
  strokeDasharray: 'stroke-dasharray',
  id: 'id'
};
/**
 * Takes a target object and assign each supported attribute from a source object to that target.
 * Each supported attributes is converted to a mapped kebab-case notation.
 * @ignore
 *
 * @param {object} target - Target object on which to assign mapped attribute values
 * @param {object} source - Source object
 */

function assignMappedAttribute(target, source) {
  Object.keys(mappedAttributes).forEach(function (key) {
    var sourceValue = source[key];

    if (typeof sourceValue !== 'undefined') {
      var mappedKey = mappedAttributes[key];
      target[mappedKey] = sourceValue;
    }
  });
}

/**
 * @extends symbol-config
 * @typedef {object} symbol--circle
 */
function circle(options) {
  return {
    type: 'circle',
    fill: 'black',
    cx: options.x,
    cy: options.y,
    r: options.size / 2
  };
}

function pointsToPath(points) {
  var close = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  var d = '';

  for (var i = 0; i < points.length; i++) {
    var p = points[i];

    if (i === 0) {
      d += "M".concat(p.x, " ").concat(p.y);
    } else {
      d += "L".concat(p.x, " ").concat(p.y);
    }

    d += ' ';
  }

  if (close) {
    d += 'Z';
  }

  return d;
}

/**
 * @extends symbol-config
 * @typedef {object} symbol--diamond
 */

function diamond(options) {
  var size = options.size;
  var left = options.x - size / 2;
  var top = options.y - size / 2;
  var points = [{
    x: left,
    y: top + size / 2
  }, {
    x: left + size / 2,
    y: top
  }, {
    x: left + size,
    y: top + size / 2
  }, {
    x: left + size / 2,
    y: top + size
  }, {
    x: left,
    y: top + size / 2
  }];
  return {
    type: 'path',
    fill: 'black',
    d: pointsToPath(points)
  };
}

function generateCrossPoints(x, y, size, barWidth) {
  var r = size / 2;
  var innerLeft = x - barWidth / 2;
  var innerTop = y - barWidth / 2;
  var left = x - r;
  var top = y - r;
  return [{
    x: innerLeft,
    y: innerTop
  }, // Top
  {
    x: innerLeft,
    y: top
  }, {
    x: innerLeft + barWidth,
    y: top
  }, {
    x: innerLeft + barWidth,
    y: innerTop
  }, // Right
  {
    x: left + size,
    y: innerTop
  }, {
    x: left + size,
    y: innerTop + barWidth
  }, {
    x: innerLeft + barWidth,
    y: innerTop + barWidth
  }, // Bottom
  {
    x: innerLeft + barWidth,
    y: top + size
  }, {
    x: innerLeft,
    y: top + size
  }, {
    x: innerLeft,
    y: innerTop + barWidth
  }, // Left
  {
    x: left,
    y: innerTop + barWidth
  }, {
    x: left,
    y: innerTop
  }];
}
/**
 * @extends symbol-config
 * @typedef {object} symbol--cross
 * @property {number} [width] - Width of the diagonals
 */

function cross(options) {
  var x = options.x;
  var y = options.y;
  var r = options.size / 2;
  var width = isNaN(options.width) ? r / 2 : options.width;
  var barWidth = Math.min(width, r);
  var points = generateCrossPoints(x, y, options.size, barWidth);
  return {
    type: 'path',
    fill: 'black',
    d: pointsToPath(points)
  };
}

/**
 * Get x1, y1, x2, y2 point from angle
 * Source: {@link https://codepen.io/NV/pen/jcnmK}
 * @private
 *
 * @param  {number} angle Radians
 * @return {object}       Point with x1, y2, x2, y2.
 */
function angleToPoints(angle) {
  var segment = Math.floor(angle / Math.PI * 2) + 2;
  var diagonal = (0.5 * segment + 0.25) * Math.PI;
  var op = Math.cos(Math.abs(diagonal - angle)) * Math.sqrt(2);
  var x = op * Math.cos(angle);
  var y = op * Math.sin(angle);
  return {
    x1: x < 0 ? 1 : 0,
    y1: y < 0 ? 1 : 0,
    x2: x >= 0 ? x : x + 1,
    y2: y >= 0 ? y : y + 1
  };
}
/**
 * Turns degrees into radians
 * @private
 *
 * @param  {number} degrees Degrees
 * @return {number}         Radians
 */

function toRadians(d) {
  return -d / 180 * Math.PI;
}
/**
 * Get x1, y1, x2, y2 point from degree
 * @private
 *
 * @param  {number} d Degree
 * @return {object}   Point with x1, y2, x2, y2.
 */

function degreesToPoints(d) {
  return angleToPoints(toRadians(d));
}

function add$1(v1, v2) {
  return {
    x: v1.x + v2.x,
    y: v1.y + v2.y
  };
}
function sub(v1, v2) {
  return {
    x: v1.x - v2.x,
    y: v1.y - v2.y
  };
}
function scalarMultiply(v, s) {
  return {
    x: v.x * s,
    y: v.y * s
  };
}
function distanceX(v1, v2) {
  return v1.x - v2.x;
}
function distanceY(v1, v2) {
  return v1.y - v2.y;
}
function sqrDistance(v1, v2) {
  return Math.pow(distanceX(v1, v2), 2) + Math.pow(distanceY(v1, v2), 2);
}
function distance(v1, v2) {
  return Math.sqrt(sqrDistance(v1, v2));
}
function dot(v1, v2) {
  return v1.x * v2.x + v1.y * v2.y;
}
function projectOnto(v1, v2) {
  var m = dot(v1, v2) / dot(v2, v2) || 1;
  return {
    x: v2.x * m,
    y: v2.y * m
  };
}
function rotate(v, radians) {
  var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
    x: 0,
    y: 0
  };
  var cos = Math.cos(radians);
  var sin = Math.sin(radians);
  var t1 = sub(v, origin);
  var t2 = {
    x: cos * t1.x - sin * t1.y,
    y: sin * t1.x + cos * t1.y
  };
  return add$1(t2, origin);
}

/**
 * @extends symbol-config
 * @typedef {object} symbol--saltire
 * @property {number} [width] - Width of the diagonals
 */

function saltire(options) {
  var radians = toRadians(45);
  var r = options.size / 2;
  var width = isNaN(options.width) ? r / 2 : options.width;
  var barWidth = Math.min(width, r);
  var adjustedSize = options.size; // Adjust for the barwidth and rotation angle, so that the visual part is always inside the symbol area

  var h = Math.sin(Math.asin(-radians)) * (barWidth / 2);
  var c = r / Math.sin(-radians);
  adjustedSize += (c - r) * 2;
  adjustedSize -= h * 2;
  var centroid = {
    x: options.x,
    y: options.y
  };
  var points = generateCrossPoints(options.x, options.y, adjustedSize, barWidth).map(function (p) {
    return rotate(p, radians, centroid);
  });
  return {
    type: 'path',
    fill: 'black',
    d: pointsToPath(points)
  };
}

/**
 * @extends symbol-config
 * @typedef {object} symbol--square
 */
function picasso_esm_square(options) {
  var size = options.size;
  return {
    type: 'rect',
    fill: 'black',
    x: options.x - size / 2,
    y: options.y - size / 2,
    width: size,
    height: size
  };
}

var DIRECTION_TO_ANGLE = {
  up: 0,
  down: 180,
  left: 90,
  right: -90
};
/**
 * @extends symbol-config
 * @typedef {object} symbol--triangle
 * @property {string} [direction='up'] - Direction of the triangle ('up'|'down'|'left'|'right')
 */

function triangle(options) {
  var size = options.size;
  var p = {
    x: options.x,
    y: options.y
  };
  var directionAngle = DIRECTION_TO_ANGLE[options.direction] || 0;
  var halfSize = size / 2;
  var left = options.x - halfSize;
  var top = options.y - halfSize;
  var points = [{
    x: left,
    y: top + size
  }, {
    x: left + halfSize,
    y: top
  }, {
    x: left + size,
    y: top + size
  }, {
    x: left,
    y: top + size
  }];
  var radians = toRadians(directionAngle);
  points = points.map(function (pp) {
    return rotate(pp, radians, p);
  });
  return {
    type: 'path',
    fill: 'black',
    d: pointsToPath(points)
  };
}

function createRectCollider(_ref) {
  var x = _ref.x,
      y = _ref.y,
      size = _ref.size;
  var r = size / 2;
  return {
    type: 'rect',
    x: x - r,
    y: y - r,
    width: size,
    height: size
  };
}
/**
 * @extends symbol-config
 * @typedef {object} symbol--line
 * @property {string} [direction='horizontal'] - Direction of line ('horizontal'|'vertical').
 */


function line$1(options) {
  var isVertical = options.direction === 'vertical';
  var r = options.size / 2;
  var x = options.x;
  var y = options.y;
  return {
    type: 'line',
    stroke: 'black',
    strokeWidth: 1,
    x1: x - (isVertical ? 0 : r),
    y1: y - (isVertical ? r : 0),
    x2: x + (isVertical ? 0 : r),
    y2: y + (isVertical ? r : 0),
    collider: createRectCollider(options) // TODO Use visual collider?

  };
}

/**
 * @extends symbol-config
 * @typedef {object} symbol--star
 * @property {number} [points=5] - Number of points on the star
 * @property {number} [startAngle=90] - Start drawing angle
 * @property {number} [innerRadius=size/2] - Size of the star core. My not exceed size of symbol.
 */

function star(options) {
  var size = options.size;
  var points = [];
  var outerRadius = size / 2;
  var drawPoints = options.points || 5;
  var innerRadius = Math.min(options.innerRadius || size / 2, size) / 2;
  var startAngle = isNaN(options.startAngle) ? 90 : options.startAngle;
  var angle = 360 / drawPoints;

  for (var i = 1; i <= drawPoints; i++) {
    var pAngle = angle * i + startAngle;
    var radians = toRadians(pAngle);
    var innerRadians = toRadians(pAngle + angle / 2);
    var y = Math.sin(radians);
    var x = Math.cos(radians);
    var iy = Math.sin(innerRadians);
    var ix = Math.cos(innerRadians);
    points.push({
      x: options.x + x * outerRadius,
      y: options.y + y * outerRadius
    });
    points.push({
      x: options.x + ix * innerRadius,
      y: options.y + iy * innerRadius
    });
  }

  return {
    type: 'path',
    fill: 'black',
    d: pointsToPath(points)
  };
}

/**
 * @extends symbol-config
 * @typedef {object} symbol--n-polygon
 * @property {object} [sides=6] - Number of sides on the regular polygon
 * @property {object} [startAngle=0] - Start drawing angle
 */

function nPolygon(options) {
  var points = [];
  var radius = options.size / 2;
  var drawPoints = Math.max(isNaN(options.sides) ? 6 : options.sides, 3);
  var angle = 360 / drawPoints;
  var startAngle = isNaN(options.startAngle) ? 0 : options.startAngle;

  for (var i = 1; i <= drawPoints; i++) {
    var radians = toRadians(angle * i + startAngle);
    var y = Math.sin(radians);
    var x = Math.cos(radians);
    points.push({
      x: options.x + x * radius,
      y: options.y + y * radius
    });
  }

  return {
    type: 'path',
    fill: 'black',
    d: pointsToPath(points)
  };
}

/**
 * @extends symbol-config
 * @typedef {object} symbol--bar
 * @property {string} [direction='horizontal'] - Direction of bar ('horizontal'|'vertical').
 */

function picasso_esm_bar(options) {
  var p = {
    x: options.x,
    y: options.y
  };
  var isVertical = options.direction === 'vertical';
  var r = options.size / 2;
  var width = r / 2;
  var halfWidth = width / 2;
  var points = [{
    x: p.x - r,
    y: p.y + halfWidth
  }, {
    x: p.x - r,
    y: p.y - halfWidth
  }, {
    x: p.x + r,
    y: p.y - halfWidth
  }, {
    x: p.x + r,
    y: p.y + halfWidth
  }];

  if (isVertical) {
    var radians = toRadians(90);
    points = points.map(function (pp) {
      return rotate(pp, radians, p);
    });
  }

  var rect = pointsToRect(points);
  rect.type = 'rect';
  rect.fill = 'black';
  return rect;
}

var parentReg = registryFactory();
parentReg.add('circle', circle);
parentReg.add('diamond', diamond);
parentReg.add('saltire', saltire);
parentReg.add('square', picasso_esm_square);
parentReg.add('triangle', triangle);
parentReg.add('line', line$1);
parentReg.add('star', star);
parentReg.add('n-polygon', nPolygon);
parentReg.add('cross', cross);
parentReg.add('bar', picasso_esm_bar);

function applyOpts(obj) {
  var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  Object.keys(opts).forEach(function (key) {
    if (typeof mappedAttributes[key] !== 'undefined' && key !== 'transform') {
      obj[key] = opts[key];
    }
  });
}
/**
 * Factory function for symbols.
 * Options object is passed to symbols function.
 * @private
 * @param {symbol--bar|symbol--circle|symbol--cross|symbol--diamond|symbol--line|symbol--n-polygon|symbol--saltire|symbol--square|symbol--star|symbol--triangle} options - Options definition may contain any of the supported display-object attributes
 * @returns {object} A node definition
 */


var create$3 = function create() {
  var reg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : parentReg;
  return function () {
    var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    // TODO handle reserverd properties x, y, size, data, etc..
    var fn = reg.get(options.type);

    if (fn) {
      var s = fn(options);
      applyOpts(s, options);

      if (typeof options.data !== 'undefined') {
        s.data = options.data;
      }

      return s;
    }

    return fn;
  };
};
/**
 * Mandatory symbol config
 * @typedef {object} symbol-config
 * @property {object} options - Options definition may contain any of the supported display-object attributes
 * @property {string} options.type - Type of symbol
 * @property {number} options.x - x-coordinate
 * @property {number} options.y - y-coordinate
 * @property {number} options.size
 * @property {object} [options.data]
 */

var isReservedProperty = function isReservedProperty(prop) {
  return ['on', 'preferredSize', 'created', 'beforeMount', 'mounted', 'resize', 'beforeUpdate', 'updated', 'beforeRender', 'render', 'beforeUnmount', 'beforeDestroy', 'destroyed', 'defaultSettings', 'data', 'settings', 'formatter', 'scale', 'chart', 'dockConfig', 'mediator', 'style', 'resolver', 'registries', '_DO_NOT_USE_getInfo', 'symbol', 'isVisible'].some(function (name) {
    return name === prop;
  });
};

function prepareContext(ctx, definition, opts) {
  var _definition$require = definition.require,
      require = _definition$require === void 0 ? [] : _definition$require;

  var mediatorSettings = definition.mediator || {};
  var settings = opts.settings,
      formatter = opts.formatter,
      scale = opts.scale,
      data = opts.data,
      renderer = opts.renderer,
      chart = opts.chart,
      dockConfig = opts.dockConfig,
      mediator = opts.mediator,
      instance = opts.instance,
      rect = opts.rect,
      style = opts.style,
      registries = opts.registries,
      resolver = opts.resolver,
      update = opts.update,
      _DO_NOT_USE_getInfo = opts._DO_NOT_USE_getInfo,
      symbol = opts.symbol,
      isVisible = opts.isVisible;

  ctx.emit = function () {};

  if (isVisible) {
    ctx.isVisible = isVisible;
  } // TODO add setters and log warnings / errors to console


  Object.defineProperty(ctx, 'settings', {
    get: settings
  });
  Object.defineProperty(ctx, 'data', {
    get: data
  });
  Object.defineProperty(ctx, 'formatter', {
    get: formatter
  });
  Object.defineProperty(ctx, 'scale', {
    get: scale
  });
  Object.defineProperty(ctx, 'mediator', {
    get: mediator
  });
  Object.defineProperty(ctx, 'style', {
    get: style
  });
  Object.defineProperty(ctx, 'registries', {
    get: registries
  });

  if (rect) {
    Object.defineProperty(ctx, 'rect', {
      get: rect
    });
  } // TODO _DO_NOT_USE_getInfo is a temporary solution to expose info from a component
  // It should replace ASAP with a proper solution.
  // The only component activaly in need of it is the legend-cat


  if (_DO_NOT_USE_getInfo) {
    ctx._DO_NOT_USE_getInfo = _DO_NOT_USE_getInfo;
  }

  Object.keys(definition).forEach(function (key) {
    if (!isReservedProperty(key)) {
      // Add non-lifecycle methods to the context
      if (typeof definition[key] === 'function') {
        ctx[key] = definition[key].bind(ctx);
      } else {
        ctx[key] = definition[key];
      }
    }
  }); // Add properties to context

  require.forEach(function (req) {
    if (req === 'renderer') {
      Object.defineProperty(ctx, 'renderer', {
        get: renderer
      });
    } else if (req === 'chart') {
      Object.defineProperty(ctx, 'chart', {
        get: chart
      });
    } else if (req === 'dockConfig') {
      Object.defineProperty(ctx, 'dockConfig', {
        get: dockConfig
      });
    } else if (req === 'instance') {
      Object.defineProperty(ctx, 'instance', {
        get: instance
      });
    } else if (req === 'update' && update) {
      Object.defineProperty(ctx, 'update', {
        get: update
      });
    } else if (req === 'resolver') {
      Object.defineProperty(ctx, 'resolver', {
        get: resolver
      });
    } else if (req === 'symbol') {
      Object.defineProperty(ctx, 'symbol', {
        get: symbol
      });
    }
  });

  Object.keys(mediatorSettings).forEach(function (eventName) {
    ctx.mediator.on(eventName, mediatorSettings[eventName].bind(ctx));
  });
}

function createDockDefinition(settings, preferredSize, logger) {
  var getLayoutProperty = function getLayoutProperty(propName) {
    if (settings[propName]) {
      logger.warn("Deprecation Warning the ".concat(propName, " property should be moved into layout: {} property")); // eslint-disable-line no-console

      return settings[propName];
    }

    return settings.layout ? settings.layout[propName] : undefined;
  };

  var def = {};
  def.displayOrder = getLayoutProperty('displayOrder');
  def.dock = getLayoutProperty('dock');
  def.prioOrder = getLayoutProperty('prioOrder');
  def.minimumLayoutMode = getLayoutProperty('minimumLayoutMode'); // move layout properties to layout object

  settings.layout = settings.layout || {};
  settings.layout.displayOrder = typeof def.displayOrder !== 'undefined' ? def.displayOrder : settings.layout.displayOrder;
  settings.layout.prioOrder = typeof def.prioOrder !== 'undefined' ? def.prioOrder : settings.layout.prioOrder;
  settings.layout.dock = def.dock || settings.layout.dock;
  settings.layout.minimumLayoutMode = def.minimumLayoutMode || settings.layout.minimumLayoutMode; // not directly a dock layout property

  def.show = settings.show;
  def.preferredSize = preferredSize;
  return def;
}

function setUpEmitter(ctx, emitter, settings) {
  // Object.defineProperty(ctx, 'emitter', )
  Object.keys(settings.on || {}).forEach(function (event) {
    ctx.eventListeners = ctx.eventListeners || [];
    var listener = settings.on[event].bind(ctx);
    ctx.eventListeners.push({
      event: event,
      listener: listener
    });
    emitter.on(event, listener);
  });

  ctx.emit = function (name) {
    for (var _len = arguments.length, event = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      event[_key - 1] = arguments[_key];
    }

    return emitter.emit.apply(emitter, [name].concat(event));
  };
}

function tearDownEmitter(ctx, emitter) {
  if (ctx.eventListeners) {
    ctx.eventListeners.forEach(function (_ref) {
      var event = _ref.event,
          listener = _ref.listener;
      emitter.removeListener(event, listener);
    });
    ctx.eventListeners.length = 0;
  }

  ctx.emit = function () {};
} // First render
// preferredSize -> resize -> beforeRender -> render -> mounted
// Normal update
// beforeUpdate -> preferredSize -> resize -> beforeRender -> render -> updated
// Update without relayout
// beforeUpdate -> beforeRender -> render -> updated
// TODO support es6 classes


function componentFactory(definition) {
  var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

  var _definition$defaultSe = definition.defaultSettings,
      defaultSettings = _definition$defaultSe === void 0 ? {} : _definition$defaultSe,
      _definition$_DO_NOT_U = definition._DO_NOT_USE_getInfo,
      _DO_NOT_USE_getInfo = _definition$_DO_NOT_U === void 0 ? function () {
    return {};
  } : _definition$_DO_NOT_U;

  var _chart = context.chart,
      container = context.container,
      _mediator = context.mediator,
      _registries = context.registries,
      theme = context.theme,
      renderer = context.renderer;
  var emitter = EventEmitter$1.mixin({});
  var config = context.settings || {};

  var _settings = extend(true, {}, defaultSettings, config);

  var _data = [];

  var _scale;

  var _formatter;

  var element;
  var size;

  var _style;

  var _resolver = settingsResolver({
    chart: _chart
  });

  var _isVisible = false;
  var brushArgs = {
    nodes: [],
    chart: _chart,
    config: _settings.brush || {},
    renderer: null
  };
  var brushTriggers = {
    tap: [],
    over: []
  };
  var brushStylers = [];
  var definitionContext = {};
  var instanceContext = extend({}, config); // Create a callback that calls lifecycle functions in the definition and config (if they exist).

  function createCallback(method) {
    var defaultMethod = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {};
    var canBeValue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
    return function cb() {
      var inDefinition = typeof definition[method] !== 'undefined';
      var inConfig = typeof config[method] !== 'undefined';
      var returnValue;

      for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }

      if (inDefinition) {
        if (typeof definition[method] === 'function') {
          var _definition$method;

          returnValue = (_definition$method = definition[method]).call.apply(_definition$method, [definitionContext].concat(args));
        } else if (canBeValue) {
          returnValue = definition[method];
        }
      }

      if (inConfig) {
        if (typeof config[method] === 'function') {
          var _config$method;

          returnValue = (_config$method = config[method]).call.apply(_config$method, [instanceContext].concat(args));
        } else if (canBeValue) {
          returnValue = config[method];
        }
      }

      if (!inDefinition && !inConfig) {
        returnValue = defaultMethod.call.apply(defaultMethod, [definitionContext].concat(args));
      }

      return returnValue;
    };
  }

  var preferredSize = createCallback('preferredSize', function () {
    return 0;
  }, true);
  var resize = createCallback('resize', function (_ref2) {
    var inner = _ref2.inner;
    return inner;
  });
  var created = createCallback('created');
  var beforeMount = createCallback('beforeMount');
  var mounted = createCallback('mounted');
  var beforeUnmount = createCallback('beforeUnmount');
  var beforeUpdate = createCallback('beforeUpdate');
  var updated = createCallback('updated');
  var beforeRender = createCallback('beforeRender');
  var beforeDestroy = createCallback('beforeDestroy');
  var destroyed = createCallback('destroyed');
  var render = definition.render; // Do not allow overriding of this function

  var addBrushStylers = function addBrushStylers() {
    if (_settings.brush) {
      (_settings.brush.consume || []).forEach(function (b) {
        if (b.context && b.style) {
          brushStylers.push(styler(brushArgs, b));
        }
      });
    }
  };

  var addBrushTriggers = function addBrushTriggers() {
    if (_settings.brush) {
      (_settings.brush.trigger || []).forEach(function (t) {
        if (t.on === 'over') {
          brushTriggers.over.push(t);
        } else {
          brushTriggers.tap.push(t);
        }
      });
    }
  };

  Object.defineProperty(brushArgs, 'data', {
    get: function get() {
      return _data;
    }
  });
  var rendString = _settings.renderer || definition.renderer;
  var rend = rendString ? renderer || _registries.renderer(rendString)() : renderer || _registries.renderer()();
  brushArgs.renderer = rend;
  var dockConfigCallbackContext = {
    resources: _chart.logger ? {
      logger: _chart.logger()
    } : {}
  };

  var _dockConfig = dockConfig(createDockDefinition(_settings, preferredSize, _chart.logger()), dockConfigCallbackContext);

  var appendComponentMeta = function appendComponentMeta(node) {
    node.key = _settings.key;
    node.element = rend.element();
  };

  var fn = function fn() {};

  fn.dockConfig = function () {
    return _dockConfig;
  }; // Set new settings - will trigger mapping of data and creation of scale / formatter.


  fn.set = function () {
    var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

    if (opts.settings) {
      config = opts.settings;
      _settings = extend(true, {}, defaultSettings, opts.settings);
      _dockConfig = dockConfig(createDockDefinition(_settings, preferredSize, _chart.logger()), dockConfigCallbackContext);
    }

    if (_settings.scale) {
      _scale = _chart.scale(_settings.scale);
    }

    if (_settings.data) {
      _data = extract(_settings.data, {
        dataset: _chart.dataset,
        collection: _chart.dataCollection
      }, {
        logger: _chart.logger()
      }, _chart.dataCollection);
    } else if (_scale) {
      _data = _scale.data();
    } else {
      _data = [];
    }

    if (typeof _settings.formatter === 'string') {
      _formatter = _chart.formatter(_settings.formatter);
    } else if (_typeof(_settings.formatter) === 'object') {
      _formatter = _chart.formatter(_settings.formatter);
    } else if (_scale && _scale.data().fields) {
      _formatter = _scale.data().fields[0].formatter();
    }

    _style = theme.style(_settings.style || {});
  };

  fn.resize = function () {
    var inner = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var outer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var newSize = resize({
      inner: inner,
      outer: outer
    });

    if (newSize) {
      size = rend.size(newSize);
    } else {
      size = rend.size(inner);
    }

    instanceContext.rect = extend(true, {
      computedPhysical: size.computedPhysical,
      computedOuter: outer.computed || outer,
      computedInner: inner.computed || inner
    }, inner);
    size = extend(true, {
      computedOuter: outer.computed || outer,
      computedInner: inner.computed || inner
    }, size);
  };

  fn.getRect = function () {
    return instanceContext.rect;
  };

  var getRenderArgs = function getRenderArgs() {
    var renderArgs = rend.renderArgs ? rend.renderArgs.slice(0) : [];
    renderArgs.push({
      data: _data
    });
    return renderArgs;
  };

  fn.beforeMount = beforeMount;

  fn.beforeRender = function () {
    beforeRender({
      size: size
    });
  };

  var currentNodes;

  fn.render = function () {
    var nodes = brushArgs.nodes = render.call.apply(render, [definitionContext].concat(_toConsumableArray$1(getRenderArgs())));
    rend.render(nodes);
    currentNodes = nodes;
  };

  fn.hide = function () {
    fn.unmount();
    rend.size({
      x: 0,
      y: 0,
      width: 0,
      height: 0
    });
    rend.clear();
  };

  fn.beforeUpdate = function () {
    beforeUpdate({
      settings: _settings,
      data: _data
    });
  };

  var currentTween;

  fn.update = function () {
    if (currentTween) {
      currentTween.stop();
    }

    var nodes = brushArgs.nodes = render.call.apply(render, [definitionContext].concat(_toConsumableArray$1(getRenderArgs()))); // Reset brush stylers and triggers

    brushStylers.forEach(function (b) {
      return b.cleanUp();
    });
    brushStylers.length = 0;
    brushTriggers.tap = [];
    brushTriggers.over = [];

    if (_settings.brush) {
      addBrushStylers();
      addBrushTriggers();
    }

    brushStylers.forEach(function (bs) {
      if (bs.isActive()) {
        bs.update();
      }
    });

    if (currentNodes && _settings.animations && _settings.animations.enabled) {
      currentTween = picasso_esm_tween({
        old: currentNodes,
        current: nodes
      }, {
        renderer: rend
      }, _settings.animations);
      currentTween.start();
    } else {
      rend.render(nodes);
    }

    currentNodes = nodes;

    if (rend.setKey && typeof config.key === 'string') {
      rend.setKey(config.key);
    }
  };

  fn.updated = updated;

  fn.destroy = function () {
    fn.unmount();
    beforeDestroy(element);
    rend.destroy();
    destroyed();
    element = null;
  };
  /**
   * Update active nodes. For now this can be used as a way update and apply brushing on nodes.
   * Ex: if a component have changed the nodes since its initial render.
   * @param {Nodes[]} nodes
   * @deprecated
   * @ignore
   */


  var updateNodes = function updateNodes(nodes) {
    brushArgs.nodes = nodes;
    brushStylers.forEach(function (bs) {
      if (bs.isActive()) {
        bs.update();
      }
    });
    rend.render(nodes);
  }; // Set contexts, note that the definition and instance need different contexts (for example if they have different 'require' props)


  prepareContext(definitionContext, definition, {
    settings: function settings() {
      return _settings;
    },
    data: function data() {
      return _data;
    },
    scale: function scale() {
      return _scale;
    },
    formatter: function formatter() {
      return _formatter;
    },
    renderer: function renderer() {
      return rend;
    },
    chart: function chart() {
      return _chart;
    },
    dockConfig: function dockConfig() {
      return _dockConfig;
    },
    mediator: function mediator() {
      return _mediator;
    },
    instance: function instance() {
      return instanceContext;
    },
    rect: function rect() {
      return instanceContext.rect;
    },
    style: function style() {
      return _style;
    },
    update: function update() {
      return updateNodes;
    },
    registries: function registries() {
      return _registries;
    },
    resolver: function resolver() {
      return _resolver;
    },
    symbol: function symbol() {
      return create$3(_registries.symbol);
    }
  });
  prepareContext(instanceContext, config, {
    settings: function settings() {
      return _settings;
    },
    data: function data() {
      return _data;
    },
    scale: function scale() {
      return _scale;
    },
    formatter: function formatter() {
      return _formatter;
    },
    renderer: function renderer() {
      return rend;
    },
    chart: function chart() {
      return _chart;
    },
    dockConfig: function dockConfig() {
      return _dockConfig;
    },
    mediator: function mediator() {
      return _mediator;
    },
    style: function style() {
      return _style;
    },
    _DO_NOT_USE_getInfo: _DO_NOT_USE_getInfo.bind(definitionContext),
    isVisible: function isVisible() {
      return _isVisible;
    }
  });

  fn.getBrushedShapes = function getBrushedShapes(brushCtx, mode, props) {
    var shapes = [];

    if (_settings.brush && _settings.brush.consume) {
      var brusher = _chart.brush(brushCtx);

      var sceneNodes = rend.findShapes('*');

      _settings.brush.consume.filter(function (t) {
        return t.context === brushCtx;
      }).forEach(function (consume) {
        for (var i = 0; i < sceneNodes.length; i++) {
          var node = sceneNodes[i];

          if (node.data && brusher.containsMappedData(node.data, props || consume.data, mode)) {
            appendComponentMeta(node);
            shapes.push(node);
            sceneNodes.splice(i, 1);
            i--;
          }
        }
      });
    }

    return shapes;
  };

  fn.findShapes = function (selector) {
    var shapes = rend.findShapes(selector);

    for (var i = 0, num = shapes.length; i < num; i++) {
      appendComponentMeta(shapes[i]);
    }

    return shapes;
  };

  fn.shapesAt = function (shape) {
    var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var items = rend.itemsAt(shape);
    var shapes;

    if (opts && opts.propagation === 'stop' && items.length > 0) {
      shapes = [items.pop().node];
    } else {
      shapes = items.map(function (i) {
        return i.node;
      });
    }

    for (var i = 0, num = shapes.length; i < num; i++) {
      appendComponentMeta(shapes[i]);
    }

    return shapes;
  };

  fn.brushFromShapes = function (shapes) {
    var trigger = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    trigger.contexts = Array.isArray(trigger.contexts) ? trigger.contexts : [];
    var action = trigger.action || 'toggle';
    brushFromSceneNodes({
      nodes: shapes,
      action: action,
      trigger: trigger,
      chart: _chart,
      data: brushArgs.data
    });
  };

  fn.mount = function () {
    element = rend.element && rend.element() ? element : rend.appendTo(container);

    if (rend.setKey && typeof config.key === 'string') {
      rend.setKey(config.key);
    }

    if (_settings.brush) {
      addBrushStylers();
      addBrushTriggers();
    }

    setUpEmitter(instanceContext, emitter, config);
    setUpEmitter(definitionContext, emitter, definition);
    _isVisible = true;
  };

  fn.mounted = function () {
    return mounted(element);
  };

  fn.unmount = function () {
    [instanceContext, definitionContext].forEach(function (ctx) {
      tearDownEmitter(ctx, emitter);
    });
    brushTriggers.tap = [];
    brushTriggers.over = [];
    brushStylers.forEach(function (bs) {
      bs.cleanUp();
    });
    brushStylers.length = 0;
    beforeUnmount();
    _isVisible = false;
  };

  fn.onBrushTap = function (e) {
    brushTriggers.tap.forEach(function (t) {
      if (resolveTapEvent({
        e: e,
        t: t,
        config: brushArgs
      }) && t.globalPropagation === 'stop') {
        _chart.toggleBrushing(true);
      }
    });
  };

  fn.onBrushOver = function (e) {
    brushTriggers.over.forEach(function (t) {
      if (resolveOverEvent({
        e: e,
        t: t,
        config: brushArgs
      }) && t.globalPropagation === 'stop') {
        _chart.toggleBrushing(true);
      }
    });
  };
  /**
   * Expose definition on instance
   * @private
   * @experimental
   */


  fn.def = definitionContext;
  /**
   * Expose instanceCtx on "instance"
   * @private
   * @experimental
   */

  fn.ctx = instanceContext;

  fn.renderer = function () {
    return rend;
  };

  fn.set({
    settings: config
  });
  created();
  return fn;
}

function mediator() {
  var instance = {};
  EventEmitter$1.mixin(instance);
  return instance;
}

var EPSILON = 1e-12;
function closestPointToLine(start, end, p) {
  var startToPoint = sub(p, start);
  var startToEnd = sub(end, start);
  var pointOnLine = add$1(projectOnto(startToPoint, startToEnd), start);
  return pointOnLine;
}
function isPointOnLine(start, end, p) {
  return distance(start, p) + distance(end, p) - distance(start, end) < EPSILON;
}
/**
 * Check if rectangle a is located inside rectangle b or if they are the same rectangle.
 * @param {rect} a - An rect containing (x,y) coordinates, width and height. The origin is assumed to be top left.
 * @param {rect} b - An rect containing (x,y) coordinates, width and height. The origin is assumed to be top left.
 * @ignore
 */

function rectContainsRect(a, b) {
  return a.x >= b.x && a.x + a.width <= b.x + b.width && a.y >= b.y && a.y + a.height <= b.y + b.height;
}

function lineHasNoLength(line) {
  return line.x1 === line.x2 && line.y1 === line.y2;
}

function rectHasNoSize(rect) {
  return rect.width <= 0 || rect.height <= 0;
}

function circleHasNoSize(circle) {
  return circle.r <= 0;
}

function toFewEdges(polygon) {
  return polygon.edges.length <= 2;
}
/**
   * Test if a Circle contains a point. If so, returns true and false otherwise.
   * Circle muse have a radius greater then 0.
   * @private
   * @param {object} circle
   * @param {number} circle.cx - center x-coordinate
   * @param {number} circle.cy - center y-coordinate
   * @param {number} circle.r - circle radius
   * @param {object} point
   * @param {number} point.x - x-coordinate
   * @param {number} point.y - y-coordinate
   * @return {boolean} true if circle contains point
   */


function testCirclePoint(circle, point) {
  if (circleHasNoSize(circle)) {
    return false;
  }

  var center = {
    x: circle.cx,
    y: circle.cy
  };
  var sqrDist = sqrDistance(center, point);

  if (sqrDist <= Math.pow(circle.r, 2)) {
    return true;
  }

  return false;
}
/**
   * Test if a Circle collide with a rectangle. If so, returns true and false otherwise.
   * Circle muse have a radius greater then 0.
   * Rectangle must have a width and height greather then 0.
   * @private
   * @param {object} circle
   * @param {number} circle.cx - center x-coordinate
   * @param {number} circle.cy - center y-coordinate
   * @param {number} circle.r - circle radius
   * @param {object} rect
   * @param {number} rect.x - x-coordinate
   * @param {number} rect.y - y-coordinate
   * @param {number} rect.width - width
   * @param {number} rect.height - height
   * @return {boolean} true if circle collide with rectangle
  */

function testCircleRect(circle, rect) {
  if (rectHasNoSize(rect) || circleHasNoSize(circle)) {
    return false;
  }

  var rX = rect.width / 2;
  var rY = rect.height / 2;
  var rcX = rect.x + rX;
  var rcY = rect.y + rY;
  var r = circle.r;
  var cx = circle.cx;
  var cy = circle.cy;
  var dX = Math.abs(cx - rcX);
  var dY = Math.abs(cy - rcY);

  if (dX > rX + r || dY > rY + r) {
    return false;
  }

  if (dX <= rX || dY <= rY) {
    return true;
  }

  var sqrDist = Math.pow(dX - rX, 2) + Math.pow(dY - rY, 2);
  return sqrDist <= Math.pow(r, 2);
}
/**
   * Test if a Circle collide with a line segment. If so, returns true and false otherwise.
   * Circle muse have a radius greater then 0.
   * Line must have a length greater then 0.
   * @private
   * @param {object} circle
   * @param {number} circle.cx - center x-coordinate
   * @param {number} circle.cy - center y-coordinate
   * @param {number} circle.r - circle radius
   * @param {object} line
   * @param {number} line.x1 - x-coordinate
   * @param {number} line.y1 - y-coordinate
   * @param {number} line.x1 - x-coordinate
   * @param {number} line.y1 - y-coordinate
   * @return {boolean} true if circle collide with line
  */

function testCircleLine(circle, line) {
  if (circleHasNoSize(circle) || lineHasNoLength(line)) {
    return false;
  }

  var _lineToPoints = lineToPoints(line),
      _lineToPoints2 = picasso_esm_slicedToArray(_lineToPoints, 2),
      p1 = _lineToPoints2[0],
      p2 = _lineToPoints2[1];

  if (testCirclePoint(circle, p1) || testCirclePoint(circle, p2)) {
    return true;
  }

  var center = {
    x: circle.cx,
    y: circle.cy
  };
  var pointOnLine = closestPointToLine(p1, p2, center);
  var dist = sqrDistance(pointOnLine, center);
  return dist <= Math.pow(circle.r, 2) && isPointOnLine(p1, p2, pointOnLine);
}
/**
   * Test if a Circle collide with another Circle. If so, returns true and false otherwise.
   * Both circles muse have a radius greater then 0.
   * @private
   * @param {object} circle
   * @param {number} circle.cx - center x-coordinate
   * @param {number} circle.cy - center y-coordinate
   * @param {number} circle.r - circle radius
   * @param {object} circle
   * @param {number} circle.cx - center x-coordinate
   * @param {number} circle.cy - center y-coordinate
   * @param {number} circle.r - circle radius
   * @return {boolean} true if circle collide with circle
  */

function testCircleCircle(circle1, circle2) {
  if (circleHasNoSize(circle1) || circleHasNoSize(circle2)) {
    return false;
  }

  var dx = circle1.cx - circle2.cx;
  var dy = circle1.cy - circle2.cy;
  var sqrDist = Math.pow(dx, 2) + Math.pow(dy, 2);

  if (sqrDist <= Math.pow(circle1.r + circle2.r, 2)) {
    return true;
  }

  return false;
}
/**
   * Test if a Circle collide with Polygon. If so, returns true and false otherwise.
   * Circle muse have a radius greater then 0.
   * Polygon must contain at least 2 vertices
   * @private
   * @param {object} circle
   * @param {number} circle.cx - center x-coordinate
   * @param {number} circle.cy - center y-coordinate
   * @param {number} circle.r - circle radius
   * @param {object} polygon
   * @param {Array} polygon.vertices - Array of vertices
   * @param {object} polygon.vertices.vertex
   * @param {number} polygon.vertices.vertex.x - x-coordinate
   * @param {number} polygon.vertices.vertex.y - y-coordinate
   * @param {Array} polygon.edges - Array of edges
   * @param {Array} polygon.edges.edge - Array of points
   * @param {object} polygon.edges.edge.point
   * @param {number} polygon.edges.edge.point.x - x-coordinate
   * @param {number} polygon.edges.edge.point.y - y-coordinate
   * @return {boolean} true if circle collide with polygon
  */

function testCirclePolygon(circle, polygon) {
  // TODO handle polygon that is a straight line, current impl will interrept it is a true, if radius is extended onto any of the edges
  if (toFewEdges(polygon) || circleHasNoSize(circle)) {
    return false;
  }

  var center = {
    x: circle.cx,
    y: circle.cy
  };

  if (testPolygonPoint(polygon, center)) {
    return true;
  }

  var num = polygon.edges.length;

  for (var i = 0; i < num; i++) {
    var edge = pointsToLine(polygon.edges[i]);

    if (testCircleLine(circle, edge)) {
      return true;
    }
  }

  return false;
}
/**
   * Test if a Polygon contains a Point. If so, returns true and false otherwise.
   * Polygon must contain at least 2 vertices
   * @private
   * @param {object} polygon
   * @param {Array} polygon.vertices - Array of vertices
   * @param {object} polygon.vertices.vertex
   * @param {number} polygon.vertices.vertex.x - x-coordinate
   * @param {number} polygon.vertices.vertex.y - y-coordinate
   * @param {Array} polygon.edges - Array of edges
   * @param {Array} polygon.edges.edge - Array of points
   * @param {object} polygon.edges.edge.point
   * @param {number} polygon.edges.edge.point.x - x-coordinate
   * @param {number} polygon.edges.edge.point.y - y-coordinate
   * @param {object} point
   * @param {number} point.x - x-coordinate
   * @param {number} point.y - y-coordinate
   * @return {boolean} true if polygon conatins point
  */

function testPolygonPoint(polygon, point) {
  // TODO handle polygon that is a straight line, current impl gives a non-deterministic output, that is depending on number of vertices
  if (toFewEdges(polygon) || !testRectPoint(polygon.boundingRect(), point)) {
    return false;
  }

  var even = true;
  var num = polygon.vertices.length;
  var rayStart = {
    x: polygon.xMin - 1,
    y: point.y
  };

  for (var i = 0; i < num - 1; i++) {
    var edge = pointsToLine(polygon.edges[i]);

    if (!(edge.y1 < point.y && edge.y2 < point.y) && !(edge.y1 > point.y && edge.y2 > point.y)) {
      // filterout any edges that does not cross the ray
      even = testLineLine(edge, pointsToLine([rayStart, point])) ? !even : even;
    }
  }

  return !even;
}
/**
   * Test if a Polygon collider with a line. If so, returns true and false otherwise.
   * Polygon must contain at least 3 edges.
   * Line must have length greater then 0.
   * @private
   * @param {object} polygon
   * @param {Array} polygon.vertices - Array of vertices
   * @param {object} polygon.vertices.vertex
   * @param {number} polygon.vertices.vertex.x - x-coordinate
   * @param {number} polygon.vertices.vertex.y - y-coordinate
   * @param {Array} polygon.edges - Array of edges
   * @param {Array} polygon.edges.edge - Array of points
   * @param {object} polygon.edges.edge.point
   * @param {number} polygon.edges.edge.point.x - x-coordinate
   * @param {number} polygon.edges.edge.point.y - y-coordinate
   * @param {object} line
   * @param {number} line.x1 - x-coordinate
   * @param {number} line.y1 - y-coordinate
   * @param {number} line.x1 - x-coordinate
   * @param {number} line.y1 - y-coordinate
   * @return {boolean} true if polygon collider with line
  */

function testPolygonLine(polygon, line) {
  // TODO handle polygon that is a straight line, current impl gives a non-deterministic output, that is depending on number of vertices
  if (toFewEdges(polygon)) {
    return false;
  }

  for (var i = 0, num = polygon.edges.length; i < num; i++) {
    var edge = pointsToLine(polygon.edges[i]);

    if (testLineLine(line, edge)) {
      return true;
    }
  }

  var _lineToPoints3 = lineToPoints(line),
      _lineToPoints4 = picasso_esm_slicedToArray(_lineToPoints3, 2),
      p1 = _lineToPoints4[0],
      p2 = _lineToPoints4[1];

  return testPolygonPoint(polygon, p1) || testPolygonPoint(polygon, p2);
}
/**
   * Test if a Polygon collider with a rectangle. If so, returns true and false otherwise.
   * Polygon must contain at least 3 edges.
   * Rectangle must width and height greater then 0.
   * @private
   * @param {object} polygon
   * @param {Array} polygon.vertices - Array of vertices
   * @param {object} polygon.vertices.vertex
   * @param {number} polygon.vertices.vertex.x - x-coordinate
   * @param {number} polygon.vertices.vertex.y - y-coordinate
   * @param {Array} polygon.edges - Array of edges
   * @param {Array} polygon.edges.edge - Array of points
   * @param {object} polygon.edges.edge.point
   * @param {number} polygon.edges.edge.point.x - x-coordinate
   * @param {number} polygon.edges.edge.point.y - y-coordinate
   * @param {object} rect
   * @param {number} rect.x - x-coordinate
   * @param {number} rect.y - y-coordinate
   * @param {number} rect.width - width
   * @param {number} rect.height - height
   * @return {boolean} true if polygon collider with rect
  */

function testPolygonRect(polygon, rect) {
  // TODO handle polygon that is a straight line, current impl gives a non-deterministic output, that is depending on number of vertices
  if (toFewEdges(polygon)) {
    return false;
  }

  for (var i = 0, num = polygon.edges.length; i < num; i++) {
    var edge = pointsToLine(polygon.edges[i]);

    if (testRectLine(rect, edge)) {
      return true;
    }
  }

  var _rectToPoints = rectToPoints(rect),
      _rectToPoints2 = picasso_esm_slicedToArray(_rectToPoints, 4),
      p1 = _rectToPoints2[0],
      p2 = _rectToPoints2[1],
      p3 = _rectToPoints2[2],
      p4 = _rectToPoints2[3];

  return testPolygonPoint(polygon, p1) || testPolygonPoint(polygon, p2) || testPolygonPoint(polygon, p3) || testPolygonPoint(polygon, p4);
}
/**
   * Test if a Rectangle collide with another rectangle. If so, returns true and false otherwise.
   * Both rectangles must have a width and height greather then 0.
   * @private
   * @param {object} rect
   * @param {number} rect.x - x-coordinate
   * @param {number} rect.y - y-coordinate
   * @param {number} rect.width - width
   * @param {number} rect.height - height
   * @param {object} rect
   * @param {number} rect.x - x-coordinate
   * @param {number} rect.y - y-coordinate
   * @param {number} rect.width - width
   * @param {number} rect.height - height
   * @return {boolean} true if rectangle collide with rectangle
  */

function testRectRect(rect1, rect2) {
  if (rectHasNoSize(rect1) || rectHasNoSize(rect2)) {
    return false;
  }

  return rect1.x <= rect2.x + rect2.width && rect2.x <= rect1.x + rect1.width && rect1.y <= rect2.y + rect2.height && rect2.y <= rect1.y + rect1.height;
}
/**
   * Test if a Rectangle contains a Point. If so, returns true and false otherwise.
   * Rectangle must have a width and height greather then 0.
   * @private
   * @param {object} rect
   * @param {number} rect.x - x-coordinate
   * @param {number} rect.y - y-coordinate
   * @param {number} rect.width - width
   * @param {number} rect.height - height
   * @param {object} point
   * @param {number} point.x - x-coordinate
   * @param {number} point.y - y-coordinate
   * @return {boolean} true if rectangle contains point
  */

function testRectPoint(rect, point) {
  if (rectHasNoSize(rect)) {
    return false;
  }

  return point.x >= rect.x && point.x <= rect.x + rect.width && point.y >= rect.y && point.y <= rect.y + rect.height;
}
/**
   * Test if a Rectangle collider with a line. If so, returns true and false otherwise.
   * Rectangle must have a width and height greather then 0.
   * Line must have length greater then 0.
   * @private
   * @param {object} rect
   * @param {number} rect.x - x-coordinate
   * @param {number} rect.y - y-coordinate
   * @param {number} rect.width - width
   * @param {number} rect.height - height
   * @param {object} line
   * @param {number} line.x1 - x-coordinate
   * @param {number} line.y1 - y-coordinate
   * @param {number} line.x1 - x-coordinate
   * @param {number} line.y1 - y-coordinate
   * @return {boolean} true if rectangle collide with line
  */

function testRectLine(rect, line) {
  if (lineHasNoLength(line) || rectHasNoSize(rect)) {
    return false;
  }

  var _lineToPoints5 = lineToPoints(line),
      _lineToPoints6 = picasso_esm_slicedToArray(_lineToPoints5, 2),
      p1 = _lineToPoints6[0],
      p2 = _lineToPoints6[1];

  if (testRectPoint(rect, p1) || testRectPoint(rect, p2)) {
    return true;
  }

  var rectEdges = rectToPoints(rect);
  var num = rectEdges.length;

  for (var i = 0; i < num; i++) {
    var edge = pointsToLine([rectEdges[i], rectEdges[i !== 3 ? i + 1 : 0]]);

    if (testLineLine(edge, line)) {
      return true;
    }
  }

  return false;
}
/**
   * Test if a Line collider with another line. If so, returns true and false otherwise.
   * Both lines must have length greater then 0.
   * @private
   * @param {object} line
   * @param {number} line.x1 - x-coordinate
   * @param {number} line.y1 - y-coordinate
   * @param {number} line.x1 - x-coordinate
   * @param {number} line.y1 - y-coordinate
   * @param {object} line
   * @param {number} line.x1 - x-coordinate
   * @param {number} line.y1 - y-coordinate
   * @param {number} line.x1 - x-coordinate
   * @param {number} line.y1 - y-coordinate
   * @return {boolean} true if line collide with line
  */

function testLineLine(line1, line2) {
  var _lineToPoints7 = lineToPoints(line1),
      _lineToPoints8 = picasso_esm_slicedToArray(_lineToPoints7, 2),
      p1 = _lineToPoints8[0],
      p2 = _lineToPoints8[1];

  var _lineToPoints9 = lineToPoints(line2),
      _lineToPoints10 = picasso_esm_slicedToArray(_lineToPoints9, 2),
      p3 = _lineToPoints10[0],
      p4 = _lineToPoints10[1];

  var dx1 = distanceX(p2, p1);
  var dy1 = distanceY(p2, p1);
  var dx2 = distanceX(p4, p3);
  var dy2 = distanceY(p4, p3);
  var dx3 = distanceX(p1, p3);
  var dy3 = distanceY(p1, p3);
  var ub = dy2 * dx1 - dx2 * dy1;
  var uat = dx2 * dy3 - dy2 * dx3;
  var ubt = dx1 * dy3 - dy1 * dx3;
  var t1;
  var t2;

  if (dx1 === 0 && dy1 === 0) {
    // Line segment has no length
    return false;
  }

  if (dx2 === 0 && dy2 === 0) {
    // Line segment has no length
    return false;
  }

  if (ub === 0) {
    if (uat === 0 && ubt === 0) {
      // COINCIDENT;
      if (dx1 === 0) {
        if (dy1 === 0) {
          // p1 = p2
          return p1.x === p2.x && p1.y === p2.y;
        }

        t1 = distanceY(p3, p1) / dy1;
        t2 = distanceY(p4, p1) / dy1;
      } else {
        t1 = (p3.x - p1.x) / dx1;
        t2 = (p4.x - p1.x) / dx1;
      }

      if (t1 < 0 && t2 < 0 || t1 > 1 && t2 > 1) {
        return false;
      }

      return true;
    }

    return false; // PARALLEL;
  }

  var ua = uat / ub;
  ub = ubt / ub;

  if (ua >= 0.0 && ua <= 1.0 && ub >= 0.0 && ub <= 1.0) {
    return true;
  }

  return false;
}
/**
   * Test if a Line contains a Point. If so, returns true and false otherwise.
   * Line must have length greater then 0.
   * @private
   * @param {object} line
   * @param {number} line.x1 - x-coordinate
   * @param {number} line.y1 - y-coordinate
   * @param {number} line.x1 - x-coordinate
   * @param {number} line.y1 - y-coordinate
   * @param {object} point
   * @param {number} point.x - x-coordinate
   * @param {number} point.y - y-coordinate
   * @return {boolean} true if line contains point
  */

function testLinePoint(line, point) {
  if (lineHasNoLength(line)) {
    return false;
  }

  var _lineToPoints11 = lineToPoints(line),
      _lineToPoints12 = picasso_esm_slicedToArray(_lineToPoints11, 2),
      p1 = _lineToPoints12[0],
      p2 = _lineToPoints12[1];

  return isPointOnLine(p1, p2, point);
}

var VARIABLE_RX = /^\$/;
var EXTEND = '@extend';

function throwCyclical(s) {
  throw new Error("Cyclical reference for \"".concat(s, "\""));
}

function picasso_esm_res(style, references, path) {
  if (typeof style === 'string') {
    var value = references[style];

    if (path.indexOf(style) !== -1) {
      throwCyclical(style);
    }

    if (VARIABLE_RX.test(value)) {
      path.push(style);
      return picasso_esm_res(value, references, path);
    }

    return value;
  }

  var computed = style;
  var refs = extend(true, {}, references, style);
  var s = {};

  if (style[EXTEND]) {
    var extendFrom = style[EXTEND];

    if (path.indexOf(extendFrom) !== -1) {
      throwCyclical(extendFrom);
    }

    var pext = path.slice();
    pext.push(extendFrom);
    computed = extend(true, {}, picasso_esm_res(refs[extendFrom], references, pext), style);
  }

  Object.keys(computed).forEach(function (key) {
    var p = path.slice();

    if (key === EXTEND || VARIABLE_RX.test(key)) {
      return;
    }

    s[key] = computed[key];
    var value = s[key];

    if (VARIABLE_RX.test(value) && value in refs) {
      if (path.indexOf(value) !== -1) {
        throwCyclical(value);
      }

      p.push(value);
      value = refs[value];

      if (_typeof(value) === 'object') {
        s[key] = picasso_esm_res(value, refs, p);
      } else if (VARIABLE_RX.test(value) && value in refs) {
        s[key] = picasso_esm_res(value, refs, p);
      } else {
        s[key] = value;
      }
    } else if (_typeof(value) === 'object') {
      s[key] = picasso_esm_res(value, refs, p);
    }
  });
  return s;
}
/**
 * Resolve style references
 * @private
 * @param {style-object} style
 * @param {style-object} references
 * @returns {object} The resolved style
 * @example
 * resolve({
 *   label: '$label--big'
 * }, {
 *   '$size--m': '12px',
 *   '$label--big': {
 *     fontFamily: 'Arial',
 *     fontSize: '$size--m'
 *   }
 * }); // { label: { fontFamily: 'Arial', fontSize: '12px' } }
 */


function picasso_esm_resolve(style, references) {
  return picasso_esm_res(style, references, []);
}

function themeFn() {
  var style = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var palettes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  var pals = {};
  var internalStyle = style;

  var setPalettes = function setPalettes(p) {
    p.forEach(function (palette) {
      var pal = Array.isArray(palette.colors[0]) ? palette.colors : [palette.colors];
      pals[palette.key] = {
        colors: pal,
        sizes: pal.map(function (colors) {
          return colors ? colors.length : 0;
        })
      };
    });
  };

  var getPalette = function getPalette(key, num) {
    var palette = pals[key];

    if (!palette) {
      return [];
    }

    var sizes = palette.sizes; // find the first color set containing at least 'num' colors

    for (var i = 0; i < sizes.length; i++) {
      if (num <= sizes[i]) {
        return palette.colors[i];
      }
    }

    return palette.colors[sizes.length - 1];
  };
  /**
   * Theme API
   * @private
   * @experimental
   */


  var theme = {
    /**
     * Get an array of colors
     * @param {string} name - Name of the color palette
     * @param {number} [num] - The minimum number of colors to get from the palette
     */
    palette: function palette(name, num) {
      return getPalette(name, num);
    },
    setPalettes: setPalettes,

    /**
     * Resolve style references
     * @param {style-object} s - Object containing style
     */
    style: function style(s) {
      return picasso_esm_resolve(s, internalStyle);
    },

    /**
     * Set custom style
     * @param {style-object} s - Object containing style
     */
    setStyle: function setStyle(s) {
      internalStyle = extend({}, style, s);
    }
  };
  setPalettes(palettes);
  return theme;
}

/**
 * @typedef {object} component-settings
 * @property {string} type - Component type (ex: axis, point, ...)
 * @property {function} [preferredSize] - Function returning the preferred size
 * @property {function} [created]
 * @property {function} [beforeMount]
 * @property {function} [mounted]
 * @property {function} [beforeUpdate]
 * @property {function} [updated]
 * @property {function} [beforeRender]
 * @property {function} [beforeDestroy]
 * @property {function} [destroyed]
 * @property {brush-setting} [brush] see [brushing](./brushing.md)
 * @property {object} [layout] Layout settings
 * @property {number} [layout.displayOrder = 0]
 * @property {number} [layout.prioOrder = 0]
 * @property {string | {width: string, height: string}} [layout.minimumLayoutMode] Refer to layout sizes defined by layoutModes in `strategy`
 * @property {string} [layout.dock] left, right, top or bottom
 * @property {boolean} [show = true] If the component should be rendered
 * @property {string} [scale] Named scale. Will be provided to the component if it ask for it.
 * @property {string} [formatter] Named formatter. Fallback to create formatter from scale. Will be provided to the component if it ask for it.
 */

function addComponentDelta(shape, containerBounds, componentBounds) {
  var dx = containerBounds.left - componentBounds.left;
  var dy = containerBounds.top - componentBounds.top;
  var type = getShapeType(shape);
  var deltaShape = extend(true, {}, shape);

  switch (type) {
    case 'circle':
      deltaShape.cx += dx;
      deltaShape.cy += dy;
      break;

    case 'polygon':
      for (var i = 0, num = deltaShape.vertices.length; i < num; i++) {
        var v = deltaShape.vertices[i];
        v.x += dx;
        v.y += dy;
      }

      break;

    case 'line':
      deltaShape.x1 += dx;
      deltaShape.y1 += dy;
      deltaShape.x2 += dx;
      deltaShape.y2 += dy;
      break;

    case 'point':
    case 'rect':
      deltaShape.x += dx;
      deltaShape.y += dy;
      break;

    default:
      break;
  }

  return deltaShape;
}

var moveToPosition = function moveToPosition(element, comp, index) {
  var el = comp.instance.renderer().element();

  if (isNaN(index) || !el || !element || !element.children) {
    return;
  }

  var nodes = element.children;
  var i = Math.max(0, index);
  var node = nodes[i];

  if (el === node) {
    return;
  }

  var additionalEl = comp.instance.def.additionalElements && comp.instance.def.additionalElements().filter(Boolean);

  if (element.insertBefore && typeof node !== 'undefined') {
    element.insertBefore(el, node);

    if (additionalEl) {
      additionalEl.forEach(function (ae) {
        element.insertBefore(ae, el);
      });
    }
  } else {
    if (additionalEl) {
      additionalEl.forEach(function (ae) {
        element.appendChild(ae, el);
      });
    }

    element.appendChild(el);
  }
};

function orderComponents(element, visibleComponents, order) {
  var elToIdx = [];
  var numElements = 0;
  var ordered = order ? visibleComponents.slice().sort(function (a, b) {
    return order[visibleComponents.indexOf(a)] - order[visibleComponents.indexOf(b)];
  }) : visibleComponents;
  ordered.forEach(function (comp) {
    elToIdx.push(numElements); // assume each component has at least one element

    numElements++; // check additional elements

    var additionalEl = comp.instance.def.additionalElements && comp.instance.def.additionalElements();

    if (additionalEl) {
      numElements += additionalEl.length;
    }
  });
  ordered.forEach(function (comp, i) {
    return moveToPosition(element, comp, elToIdx[i]);
  });
}

function chartFn(definition, context) {
  /**
   * @typedef {object} chart-definition
   */
  var element = definition.element,
      _definition$data = definition.data,
      data = _definition$data === void 0 ? [] : _definition$data,
      _definition$settings = definition.settings,
      settings = _definition$settings === void 0 ? {} : _definition$settings,
      _definition$on = definition.on,
      on = _definition$on === void 0 ? {} : _definition$on;
  var registries = context.registries;
  var logger = context.logger;
  var theme = themeFn(context.style, context.palettes);
  var listeners = [];
  /**
   * @alias chart
   * @interface
   */

  var instance = extend({}, definition);
  var mediator$1 = mediator();
  var currentComponents = []; // Augmented components

  var visibleComponents = [];
  var currentScales = null; // Built scales

  var currentFormatters = null; // Built formatters

  var currentScrollApis = null; // Build scroll apis

  var currentInteractions = [];

  var dataset = function dataset() {};

  var dataCollection = function dataCollection() {};

  var brushes = {};
  var stopBrushing = false;

  var createComponent = function createComponent(compSettings, container) {
    if (!registries.component.has(compSettings.type)) {
      logger.warn("Unknown component: ".concat(compSettings.type));
      return false;
    }

    var componentDefinition = registries.component(compSettings.type);
    var compInstance = componentFactory(componentDefinition, {
      settings: compSettings,
      chart: instance,
      mediator: mediator$1,
      registries: registries,
      theme: theme,
      container: container
    });
    return {
      instance: compInstance,
      settings: extend(true, {}, compSettings),
      key: compSettings.key,
      hasKey: typeof compSettings.key !== 'undefined'
    };
  }; // Create a callback that calls lifecycle functions in the definition and config (if they exist).


  function createCallback(method) {
    var defaultMethod = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {};
    return function cb() {
      var inDefinition = typeof definition[method] === 'function';
      var returnValue;

      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      if (inDefinition) {
        var _definition$method;

        returnValue = (_definition$method = definition[method]).call.apply(_definition$method, [instance].concat(args));
      } else {
        returnValue = defaultMethod.call.apply(defaultMethod, [instance].concat(args));
      }

      return returnValue;
    };
  }

  var findComponent = function findComponent(componentInstance) {
    for (var i = 0; i < currentComponents.length; i++) {
      if (currentComponents[i].instance === componentInstance) {
        return currentComponents[i];
      }
    }

    return null;
  };

  var findComponentIndexByKey = function findComponentIndexByKey(key) {
    for (var i = 0; i < currentComponents.length; i++) {
      var currComp = currentComponents[i];

      if (currComp.hasKey && currComp.key === key) {
        return i;
      }
    }

    return -1;
  };

  function getElementRect(el) {
    if (typeof el.getBoundingClientRect === 'function') {
      var _el$getBoundingClient = el.getBoundingClientRect(),
          width = _el$getBoundingClient.width,
          height = _el$getBoundingClient.height;

      return {
        x: 0,
        y: 0,
        width: width,
        height: height
      };
    }

    return {
      x: 0,
      y: 0,
      width: 0,
      height: 0
    };
  }

  var layout = function layout(components) {
    var vcomponents = components.map(function (c) {
      var dockConfig = c.instance.dockConfig();
      return {
        instance: c.instance,
        resize: c.instance.resize,
        preferredSize: dockConfig.computePreferredSize.bind(dockConfig),
        settings: c.settings,
        layoutComponents: function layoutComponents() {}
      };
    });
    var layoutSettings;

    if (settings.dockLayout) {
      logger.warn('Deprecation Warning: "dockLayout" property should be renamed to "strategy"');
      layoutSettings = settings.dockLayout;
    } else {
      layoutSettings = settings.strategy;
    }

    var dockLayout$1 = dockLayout(layoutSettings);
    var rect = getElementRect(element);

    var _dockLayout$layout = dockLayout$1.layout(rect, vcomponents),
        visible = _dockLayout$layout.visible,
        hidden = _dockLayout$layout.hidden,
        order = _dockLayout$layout.order;

    return {
      visible: visible.map(function (v) {
        return findComponent(v.instance);
      }),
      hidden: hidden.map(function (h) {
        return findComponent(h.instance);
      }),
      order: order
    };
  };

  var created = createCallback('created');
  var beforeMount = createCallback('beforeMount');
  var mounted = createCallback('mounted');
  var beforeUpdate = createCallback('beforeUpdate');
  var updated = createCallback('updated');
  var beforeRender = createCallback('beforeRender');
  var beforeDestroy = createCallback('beforeDestroy');
  var destroyed = createCallback('destroyed');

  var set = function set(_data, _settings) {
    var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
        partialData = _ref.partialData;

    var _settings$formatters = _settings.formatters,
        formatters = _settings$formatters === void 0 ? {} : _settings$formatters,
        _settings$scales = _settings.scales,
        scales = _settings$scales === void 0 ? {} : _settings$scales,
        _settings$scroll = _settings.scroll,
        scroll = _settings$scroll === void 0 ? {} : _settings$scroll;
    dataset = datasets(_data, {
      logger: logger,
      types: registries.data
    });

    if (!partialData) {
      Object.keys(brushes).forEach(function (b) {
        return brushes[b].clear();
      });
    }

    if (_settings.palettes) {
      theme.setPalettes(_settings.palettes);
    }

    if (_settings.style) {
      theme.setStyle(_settings.style);
    }

    dataCollection = picasso_esm_create(_settings.collections, {
      dataset: dataset
    }, {
      logger: logger
    });
    var deps = {
      theme: theme,
      logger: logger
    };
    currentScales = collection$1(scales, {
      dataset: dataset,
      collection: dataCollection
    }, _objectSpread2({}, deps, {
      scale: registries.scale
    }));
    currentFormatters = collection(formatters, {
      dataset: dataset,
      collection: dataCollection
    }, _objectSpread2({}, deps, {
      formatter: registries.formatter
    }));
    currentScrollApis = builder(scroll, currentScrollApis);
  };

  var render = function render() {
    var _settings2 = settings,
        _settings2$components = _settings2.components,
        components = _settings2$components === void 0 ? [] : _settings2$components;
    beforeRender();
    set(data, settings);
    currentComponents = components.map(function (compSettings) {
      return createComponent(compSettings, element);
    }).filter(function (c) {
      return !!c;
    });

    var _layout = layout(currentComponents),
        visible = _layout.visible,
        hidden = _layout.hidden,
        order = _layout.order;

    visibleComponents = visible;
    hidden.forEach(function (comp) {
      comp.instance.hide();
      comp.visible = false;
    });
    visible.forEach(function (comp) {
      return comp.instance.beforeMount();
    });
    visible.forEach(function (comp) {
      return comp.instance.mount();
    });
    visible.forEach(function (comp) {
      return comp.instance.beforeRender();
    });
    visible.forEach(function (comp) {
      return comp.instance.render();
    });
    visible.forEach(function (comp) {
      return comp.instance.mounted();
    });
    visible.forEach(function (comp) {
      comp.visible = true;
    });
    orderComponents(element, visibleComponents, order);
  };

  function setInteractions() {
    var interactions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    var current = {};
    var newKeys = interactions.filter(function (it) {
      return !!it.key;
    }).map(function (it) {
      return it.key;
    });
    currentInteractions.forEach(function (cit) {
      if (cit.key && newKeys.indexOf(cit.key) !== -1) {
        // keep old instance
        current[cit.key] = cit;
      } else {
        cit.destroy();
      }
    });
    currentInteractions = interactions.map(function (intSettings) {
      var intDefinition = intSettings.key && current[intSettings.key] ? current[intSettings.key] : registries.interaction(intSettings.type)(instance, mediator$1, element);
      intDefinition.set(intSettings);
      return intDefinition;
    });
  }

  var componentsFromPoint = function componentsFromPoint(p) {
    var br = element.getBoundingClientRect();
    var x = 'clientX' in p ? p.clientX : p.x;
    var y = 'clientY' in p ? p.clientY : p.y;
    var tp = {
      x: x - br.left,
      y: y - br.top
    };
    var ret = [];
    visibleComponents.forEach(function (c) {
      var r = c.instance.getRect(); // Do test on physical rect and use computed rect if available, otherwise fallback to computing a new rect for legacy support

      if (testRectPoint(r.computedPhysical ? r.computedPhysical : {
        x: r.margin.left + r.x * r.scaleRatio.x,
        y: r.margin.top + r.y * r.scaleRatio.y,
        width: r.width * r.scaleRatio.x,
        height: r.height * r.scaleRatio.y
      }, tp)) {
        ret.push(c);
      }
    });
    return ret;
  };

  var addDefaultEventListeners = function addDefaultEventListeners() {
    if (listeners.length || !element) {
      return;
    }

    Object.keys(on).forEach(function (key) {
      var listener = on[key].bind(instance);
      element.addEventListener(key, listener);
      listeners.push({
        key: key,
        listener: listener
      });
    });
    var eventInfo = {};

    var onTapDown = function onTapDown(e) {
      if (e.touches) {
        eventInfo.x = e.touches[0].clientX;
        eventInfo.y = e.touches[0].clientY;
        eventInfo.multiTouch = e.touches.length > 1;
      } else {
        eventInfo.x = e.clientX;
        eventInfo.y = e.clientY;
        eventInfo.multiTouch = false;
      }

      eventInfo.time = Date.now();
      eventInfo.comps = componentsFromPoint(eventInfo);
    };

    var onBrushTap = function onBrushTap(e) {
      var comps = eventInfo.comps || componentsFromPoint(e);

      if (comps.every(function (c) {
        return c.instance.def.disableTriggers;
      })) {
        return;
      }

      if (e.type === 'touchend') {
        e.preventDefault();
      }

      if (!isValidTapEvent(e, eventInfo)) {
        return;
      }

      for (var i = comps.length - 1; i >= 0; i--) {
        var comp = comps[i];
        comp.instance.onBrushTap(e);

        if (stopBrushing) {
          stopBrushing = false;
          break;
        }
      }
    };

    var onBrushOver = function onBrushOver(e) {
      var comps = componentsFromPoint(e);

      for (var i = comps.length - 1; i >= 0; i--) {
        var comp = comps[i];
        comp.instance.onBrushOver(e);

        if (stopBrushing) {
          stopBrushing = false;
          break;
        }
      }
    };

    var brushEventList = [];
    brushEventList.push({
      key: 'mousedown',
      listener: onTapDown
    });
    brushEventList.push({
      key: 'mouseup',
      listener: onBrushTap
    });

    if (detectTouchSupport(element)) {
      brushEventList.push({
        key: 'touchstart',
        listener: onTapDown
      });
      brushEventList.push({
        key: 'touchend',
        listener: onBrushTap
      });
    }

    brushEventList.push({
      key: 'mousemove',
      listener: onBrushOver
    });
    brushEventList.forEach(function (event) {
      element.addEventListener(event.key, event.listener);
      listeners.push(event);
    });
  };

  var removeDefaultEventListeners = function removeDefaultEventListeners() {
    listeners.forEach(function (_ref2) {
      var key = _ref2.key,
          listener = _ref2.listener;
      return element.removeEventListener(key, listener);
    });
    listeners.length = 0;
  }; // Browser only


  var mount = function mount() {
    element.innerHTML = '';
    render();
    addDefaultEventListeners();
    setInteractions(settings.interactions);
  };

  var unmount = function unmount() {
    removeDefaultEventListeners();
    setInteractions();
  };
  /**
   * Update the chart with new settings and / or data
   * @param {chart-definition} [chart] - Chart definition
   */


  instance.update = function () {
    var newProps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var partialData = newProps.partialData,
        _newProps$excludeFrom = newProps.excludeFromUpdate,
        excludeFromUpdate = _newProps$excludeFrom === void 0 ? [] : _newProps$excludeFrom;
    var visibleOrder;

    if (newProps.data) {
      data = newProps.data;
    }

    if (newProps.settings) {
      settings = newProps.settings;
      setInteractions(newProps.settings.interactions);
    }

    beforeUpdate();
    set(data, settings, {
      partialData: partialData
    });
    var _settings3 = settings,
        formatters = _settings3.formatters,
        scales = _settings3.scales,
        _settings3$components = _settings3.components,
        components = _settings3$components === void 0 ? [] : _settings3$components;

    var _loop = function _loop(i) {
      var currComp = currentComponents[i]; // TODO warn when there is no key

      if (!components.some(function (c) {
        return currComp.hasKey && currComp.key === c.key;
      })) {
        // Component is removed
        currentComponents.splice(i, 1);
        currComp.instance.destroy();
      }
    };

    for (var i = currentComponents.length - 1; i >= 0; i--) {
      _loop(i);
    } // Let the "components" array determine order of components


    currentComponents = components.map(function (comp) {
      var idx = findComponentIndexByKey(comp.key); // Component should not be updated

      if (excludeFromUpdate.indexOf(comp.key) > -1) {
        return currentComponents[idx];
      }

      if (idx === -1) {
        // Component is added
        return createComponent(comp, element);
      } // Component is (potentially) updated


      currentComponents[idx].updateWith = {
        formatters: formatters,
        scales: scales,
        data: data,
        settings: comp
      };
      return currentComponents[idx];
    }).filter(function (c) {
      return !!c;
    });
    currentComponents.forEach(function (comp) {
      if (comp.updateWith) {
        comp.instance.set(comp.updateWith);
      }
    });
    currentComponents.forEach(function (comp) {
      if (comp.updateWith) {
        comp.instance.beforeUpdate();
      }
    });
    var toUpdate = [];
    var toRender = [];
    var toRenderOrUpdate;

    if (partialData) {
      currentComponents.forEach(function (comp) {
        if (comp.updateWith && comp.visible) {
          toUpdate.push(comp);
        }
      });
      toRenderOrUpdate = toUpdate;
    } else {
      var _layout2 = layout(currentComponents),
          visible = _layout2.visible,
          hidden = _layout2.hidden,
          order = _layout2.order; // Relayout


      visibleComponents = visible;
      toRenderOrUpdate = visible;
      visibleOrder = order;
      visible.forEach(function (comp) {
        if (comp.updateWith && comp.visible) {
          toUpdate.push(comp);
        } else {
          toRender.push(comp);
        }
      });
      hidden.forEach(function (comp) {
        comp.instance.hide();
        comp.visible = false;
        delete comp.updateWith;
      });
    }

    toRender.forEach(function (comp) {
      return comp.instance.beforeMount();
    });
    toRender.forEach(function (comp) {
      return comp.instance.mount();
    });
    toRenderOrUpdate.forEach(function (comp) {
      return comp.instance.beforeRender();
    });
    toRenderOrUpdate.forEach(function (comp) {
      if (comp.updateWith && comp.visible) {
        comp.instance.update();
      } else {
        comp.instance.render();
      }
    }); // Ensure that displayOrder is keept, only do so on re-layout update.
    // Which is only the case if partialData is false.

    if (!partialData) {
      orderComponents(element, visibleComponents, visibleOrder);
    }

    toRender.forEach(function (comp) {
      return comp.instance.mounted();
    });
    toUpdate.forEach(function (comp) {
      return comp.instance.updated();
    });
    visibleComponents.forEach(function (comp) {
      delete comp.updateWith;
      comp.visible = true;
    });
    updated();
  };
  /**
   * Destroy the chart instance.
   */


  instance.destroy = function () {
    beforeDestroy();
    currentComponents.forEach(function (comp) {
      return comp.instance.destroy();
    });
    currentComponents = [];
    unmount();
    delete instance.update;
    delete instance.destroy;
    destroyed();
  };
  /**
   * Get all shapes associated with the provided context
   * @param {string} context The brush context
   * @param {string} mode Property comparasion mode.
   * @param {Array<string>} props Which specific data properties to compare
   * @param {string} key Which component to get shapes from. Default gives shapes from all components.
   * @return {Array<object>} Array of objects containing shape and parent element
   */


  instance.getAffectedShapes = function (ctx) {
    var mode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'and';
    var props = arguments.length > 2 ? arguments[2] : undefined;
    var key = arguments.length > 3 ? arguments[3] : undefined;
    var shapes = [];
    currentComponents.filter(function (comp) {
      return key === undefined || key === null || comp.key === key;
    }).forEach(function (comp) {
      shapes.push.apply(shapes, _toConsumableArray$1(comp.instance.getBrushedShapes(ctx, mode, props)));
    });
    return shapes;
  };
  /**
   * Get all nodes matching the provided selector
   * @param {string} selector CSS selector [type, attribute, universal, class]
   * @returns {Array<SceneNode>} Array of objects containing matching nodes
   *
   * @example
   * chart.findShapes('Circle') // [<CircleNode>, <CircleNode>]
   * chart.findShapes('Circle[fill="red"][stroke!="black"]') // [CircleNode, CircleNode]
   * chart.findShapes('Container Rect') // [Rect, Rect]
   */


  instance.findShapes = function (selector) {
    var shapes = [];
    visibleComponents.forEach(function (c) {
      shapes.push.apply(shapes, _toConsumableArray$1(c.instance.findShapes(selector)));
    });
    return shapes;
  };
  /**
   * Get components overlapping a point.
   * @param {point} p - Point with x- and y-cooridnate. The coordinate is relative to the browser viewport.
   * @returns {Array<component-context>} Array of component contexts
   */


  instance.componentsFromPoint = function (p) {
    return componentsFromPoint(p).map(function (comp) {
      return comp.instance.ctx;
    });
  };
  /**
   * Get all nodes colliding with a geometrical shape (circle, line, rectangle, point, polygon).
   *
   * The input shape is identified based on the geometrical attributes in the following order: circle => line => rectangle => point => polygon.
   * Note that not all nodes on a scene have collision detection enabled.
   * @param {line|rect|point|circle} shape - A geometrical shape. Coordinates are relative to the top-left corner of the chart instance container.
   * @param {object} opts - Options
   * @param {object[]} [opts.components] - Array of components to include in the lookup. If no components are specified, all components will be included.
   * @param {string} [opts.components[].component.key] - Component key
   * @param {string} [opts.components[].component.propagation] - if set to `stop`, will start lookup on top visible shape and propagate downwards until a shape is found.
   * @param {string} [opts.propagation] - if set to `stop`, will start lookup on top visible component and propagate downwards until a component has at least a match.
   * @returns {Array<SceneNode>} Array of objects containing colliding nodes
   *
   * @example
   * chart.shapesAt(
   *  {
   *    x: 0,
   *    y: 0,
   *    width: 100,
   *    height: 100
   *  },
   *  {
   *    components: [
   *      { key: 'key1', propagation: 'stop' },
   *      { key: 'key2' }
   *    ],
   *    propagation: 'stop'
   *  }
   * );
   */


  instance.shapesAt = function (shape) {
    var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    var result = [];
    var containerBounds = element.getBoundingClientRect();
    var comps = visibleComponents; // Assume that visibleComponents is ordererd according to displayOrder

    if (Array.isArray(opts.components) && opts.components.length > 0) {
      var compKeys = opts.components.map(function (c) {
        return c.key;
      });
      comps = visibleComponents.filter(function (c) {
        return compKeys.indexOf(c.key) !== -1;
      }).map(function (c) {
        return {
          instance: c.instance,
          opts: opts.components[compKeys.indexOf(c.key)]
        };
      });
    }

    for (var i = comps.length - 1; i >= 0; i--) {
      var c = comps[i];
      var componentBounds = c.instance.renderer().element().getBoundingClientRect();
      var deltaShape = addComponentDelta(shape, containerBounds, componentBounds);
      var shapes = c.instance.shapesAt(deltaShape, c.opts);
      var stopPropagation = shapes.length > 0 && opts.propagation === 'stop';
      result.push.apply(result, _toConsumableArray$1(shapes));

      if (result.length > 0 && stopPropagation) {
        return result;
      }
    }

    return result;
  };
  /**
   * Brush data by providing a collection of data bound shapes.
   * @param {SceneNode[]} shapes - An array of data bound shapes.
   * @param {object} config - Options
   * @param {Array<object>} opts.components - Array of components to include in the lookup.
   * @param {string} [opts.components.component.key] - Component key
   * @param {Array<string>} [opts.components.component.contexts] - Name of the brushing contexts to affect
   * @param {Array<string>} [opts.components.component.data] - The mapped data properties to add to the brush
   * @param {string} [opts.components.component.action] - Type of action to respond with
   *
   * @example
   * const shapes = chartInstance.shapesAt(...);
   * const config = {
   *  components:[
   *    {
   *      key: 'key1',
   *      contexts: ['myContext'],
   *      data: [''],
   *      action: 'add'
   *    }
   *  ]
   * };
   * chartInstance.brushFromShapes(shapes, config);
   */


  instance.brushFromShapes = function (shapes) {
    var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
      components: []
    };

    var _loop2 = function _loop2(i) {
      var iKey = config.components[i].key;
      visibleComponents.filter(function (c) {
        return iKey === c.key;
      }).forEach(function (c) {
        var compShapes = shapes.filter(function (shape) {
          return shape.key === c.key;
        });
        c.instance.brushFromShapes(compShapes, config.components[i]);
      });
    };

    for (var i = 0; i < config.components.length; i++) {
      _loop2(i);
    }
  };
  /**
   * @param {string} name - Name of scroll api
   * @returns {scroll}
   */


  instance.scroll = function scroll() {
    var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'default';
    return getOrCreateScrollApi(name, currentScrollApis);
  };
  /**
   * Get
   * @param {string} key - Get the dataset identified by `key`
   * @returns {dataset}
   */


  instance.dataset = function (key) {
    return dataset(key);
  };

  instance.dataCollection = function (key) {
    return dataCollection(key);
  };
  /**
   * Get all registered scales
   * @returns {Object<string,scale>}
   */


  instance.scales = function scales() {
    return currentScales.all();
  };
  /**
   * Get all registered formatters
   * @returns {Object<string,formatter>}
   */


  instance.formatters = function formatters() {
    return currentFormatters.all();
  };
  /**
   * Get or create brush context for this chart
   * @param {string} name - Name of the brush context. If no match is found, a new brush context is created and returned.
   * @returns {brush}
   */


  instance.brush = function brushFn() {
    var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'default';

    if (!brushes[name]) {
      brushes[name] = brush();
    }

    return brushes[name];
  };
  /**
   * Get or create a scale for this chart
   * @param {string|object} v - Scale reference or scale options
   * @returns {scale}
   * @example
   * instance.scale('nameOfMyScale'); // Fetch an existing scale by name
   * instance.scale({ scale: 'nameOfMyScale' }); // Fetch an existing scale by name
   * instance.scale({ source: '0/1', type: 'linear' }); // Create a new scale
   */


  instance.scale = function scale(v) {
    return currentScales.get(v);
  };
  /**
   * Get or create a formatter for this chart
   * @param {string|object} v - Formatter reference or formatter options
   * @returns {formatter}
   * @example
   * instance.formatter('nameOfMyFormatter'); // Fetch an existing formatter by name
   * instance.formatter({ formatter: 'nameOfMyFormatter' }); // Fetch an existing formatter by name
   * instance.formatter({ type: 'q' }); // Fetch an existing formatter by type
   * instance.formatter({
   *  formatter: 'd3',
   *  type: 'number',
   *  format: '1.0.%'
   * }); // Create a new formatter
   */


  instance.formatter = function formatter(v) {
    return currentFormatters.get(v);
  };
  /**
   * @param {boolean} [val] - Toggle brushing on or off. If value is omitted, a toggle action is applied to the current state.
   */


  instance.toggleBrushing = function toggleBrushing(val) {
    if (typeof val !== 'undefined') {
      stopBrushing = val;
    } else {
      stopBrushing = !stopBrushing;
    }
  };
  /**
   * Get a component context
   * @param {string} key - Component key
   * @returns {component-context} Component context
   */


  instance.component = function (key) {
    var idx = findComponentIndexByKey(key);

    if (idx !== -1) {
      return currentComponents[idx].instance.ctx;
    }

    return undefined;
  };

  instance.logger = function () {
    return logger;
  };

  instance.theme = function () {
    return theme;
  };
  /**
   * Get the all interactions instances
   * @name chart.interactions
   * @type {object}
   * @example
   * chart.interactions.instances; // Array of all interaction instances
   * chart.interactions.on(); // Toggle on all interactions instances
   * chart.interactions.off(); // Toggle off all interactions instances
   */


  Object.defineProperty(instance, 'interactions', {
    get: function get() {
      return (
        /** @lends chart.interactions */
        {
          /** @type Array<interaction> */
          instances: currentInteractions,

          /** Enable all interaction instances */
          on: function on() {
            addDefaultEventListeners();
            currentInteractions.forEach(function (i) {
              return i.on();
            });
          },

          /** Disable all interaction instances */
          off: function off() {
            removeDefaultEventListeners();
            currentInteractions.forEach(function (i) {
              return i.off();
            });
          }
        }
      );
    }
  });
  created();

  if (element) {
    beforeMount();
    mount();
    mounted(element);
    instance.element = element;
  }

  return instance;
}

var rendererRegistry = function rendererRegistry(reg) {
  var f = registryFactory(reg);

  f.prio = function (p) {
    return p ? f.default(p[0]) : [f.default()];
  };

  f.types = function () {
    return f.getKeys();
  };

  return f;
};

var componentRegistry = registryFactory();

function findField(query, _ref) {
  var cache = _ref.cache;

  if (typeof query === 'number') {
    return cache.fields[query];
  } // Find by key first


  for (var i = 0; i < cache.fields.length; i++) {
    if (cache.fields[i].key() === query) {
      return cache.fields[i];
    }
  } // find by title


  for (var _i = 0; _i < cache.fields.length; _i++) {
    if (cache.fields[_i].title() === query) {
      return cache.fields[_i];
    }
  }

  return null;
}
var filters = {
  numeric: function numeric(values) {
    return values.filter(function (v) {
      return typeof v === 'number' && !isNaN(v);
    });
  }
};
var unfilteredReducers = {
  sum: function sum(values) {
    return values.reduce(function (a, b) {
      return a + b;
    }, 0);
  }
}; // function isPrimitive(x) {
//   const type = typeof x;
//   return (type !== 'object' && type !== 'function');
// }

/**
 * [reducers description]
 * @type {Object}
 * @private
 */

var reducers = {
  first: function first(values) {
    return values[0];
  },
  last: function last(values) {
    return values[values.length - 1];
  },
  min: function min(values) {
    var filtered = filters.numeric(values);
    return !filtered.length ? NaN : Math.min.apply(null, filtered);
  },
  max: function max(values) {
    var filtered = filters.numeric(values);
    return !filtered.length ? NaN : Math.max.apply(null, filtered);
  },
  sum: function sum(values) {
    var filtered = filters.numeric(values);
    return !filtered.length ? NaN : filtered.reduce(function (a, b) {
      return a + b;
    }, 0);
  },
  avg: function avg(values) {
    var filtered = filters.numeric(values);
    var len = filtered.length;
    return !len ? NaN : unfilteredReducers.sum(filtered) / len;
  }
};

function normalizeProperties(cfg, dataset, dataProperties, main) {
  // console.log('======', cfg, main, dataset);
  var props = {};
  var mainField = main.field || (typeof cfg.field !== 'undefined' ? dataset.field(cfg.field) : null);
  Object.keys(dataProperties).forEach(function (key) {
    var pConfig = dataProperties[key];
    var prop = props[key] = {};

    if (['number', 'string', 'boolean'].indexOf(_typeof(pConfig)) !== -1) {
      prop.type = 'primitive';
      prop.value = pConfig;
    } else if (typeof pConfig === 'function') {
      prop.type = 'function';
      prop.value = pConfig;
      prop.label = pConfig;
      prop.field = mainField;
    } else if (_typeof(pConfig) === 'object') {
      if (pConfig.fields) {
        prop.fields = pConfig.fields.map(function (ff) {
          return normalizeProperties(cfg, dataset, {
            main: ff
          }, main).main;
        });
      } else if (typeof pConfig.field !== 'undefined') {
        prop.type = 'field';
        prop.field = dataset.field(pConfig.field);
        prop.value = prop.field.value;
        prop.label = prop.field.label;
      } else if (mainField) {
        prop.value = mainField.value;
        prop.label = mainField.label;
        prop.field = mainField;
      }

      if (typeof pConfig.filter === 'function') {
        prop.filter = pConfig.filter;
      }

      if (typeof pConfig.value !== 'undefined') {
        prop.value = pConfig.value;
      }

      if (typeof pConfig.label !== 'undefined') {
        prop.label = pConfig.label;
      }

      if (typeof pConfig.reduce === 'function') {
        prop.reduce = pConfig.reduce;
      } else if (pConfig.reduce) {
        prop.reduce = reducers[pConfig.reduce];
      } else if (prop.field && prop.field.reduce) {
        prop.reduce = typeof prop.field.reduce === 'string' ? reducers[prop.field.reduce] : prop.field.reduce;
      }

      if (typeof pConfig.reduceLabel === 'function') {
        prop.reduceLabel = pConfig.reduceLabel;
      } else if (pConfig.reduceLabel) {
        prop.reduceLabel = reducers[pConfig.reduceLabel];
      } else if (prop.field && prop.field.reduceLabel) {
        prop.reduceLabel = typeof prop.field.reduceLabel === 'string' ? reducers[prop.field.reduceLabel] : prop.field.reduceLabel;
      }
    }
  });
  return props;
}
/*
example of configuration input
cfg = {
  field: 'State', // the 'top level' values are extracted from field state
  value: d => d.qText, // the value of the output
  props: { // additional data properties ammended to each item
    a: 3, // constant value
    b: d => d.qElemNumber, // function will receive the original field value
    c: {
      field: 'Country', // reference to another field
      value: d => d.qText // extract the qText value from the referenced field
    },
    d: {
      value: d => d.qRow //  extract qRow from field 'State'
    }
  }
}

// output
[{
  value: 'CA', source: { field: 'State' },
  a: { value: 3 },
  b: { value: 26, source: 'State' },
  c: { value: 'USA', source: 'Country' },
  d: { value: 131, source: 'State' }
},
...]
*/


function getPropsInfo(cfg, dataset) {
  // console.log('222', cfg);
  var _normalizeProperties = normalizeProperties(cfg, dataset, {
    main: {
      value: cfg.value,
      label: cfg.label,
      reduce: cfg.reduce,
      filter: cfg.filter
    }
  }, {}),
      main = _normalizeProperties.main;

  var props = normalizeProperties(cfg, dataset, cfg.props || {}, main);
  return {
    props: props,
    main: main
  };
}

function collectItems(items, cfg, formatter, prop) {
  var values = Array(items.length);
  var labels = Array(items.length);
  var it;

  for (var i = 0; i < items.length; i++) {
    it = prop ? items[i][prop] : items[i];
    values[i] = it.value;
    labels[i] = it.label;
  }

  var reduce = cfg.reduce;
  var reduceLabel = cfg.reduceLabel;
  var v = reduce ? reduce(values) : values;
  var b = reduceLabel ? reduceLabel(labels, v) : formatter ? formatter(v) : String(v); // eslint-disable-line no-nested-ternary
  // // ret[prop].label = String(propsFormatters[prop](ret[prop].value));

  var ret = {
    value: v,
    label: b
  };

  if (prop && items[0][prop].source) {
    ret.source = items[0][prop].source;
    return ret;
  }

  if (!prop && items[0].source) {
    ret.source = items[0].source;
    return ret;
  }

  return ret;
} // collect items that have been grouped and reduce per group and property


function collect(trackedItems, _ref2) {
  var main = _ref2.main,
      propsArr = _ref2.propsArr,
      props = _ref2.props;
  var dataItems = [];
  var mainFormatter = main.field.formatter(); // || (v => v);

  var propsFormatters = {};
  propsArr.forEach(function (prop) {
    propsFormatters[prop] = props[prop].field ? props[prop].field.formatter() : function (v) {
      return v;
    };
  });
  dataItems.push.apply(dataItems, _toConsumableArray$1(trackedItems.map(function (t) {
    var ret = collectItems(t.items, main, mainFormatter);
    propsArr.forEach(function (prop) {
      ret[prop] = collectItems(t.items, props[prop], propsFormatters[prop], prop);
    });
    return ret;
  })));
  return dataItems;
}
function picasso_esm_track(_ref3) {
  var cfg = _ref3.cfg,
      itemData = _ref3.itemData,
      obj = _ref3.obj,
      target = _ref3.target,
      tracker = _ref3.tracker,
      trackType = _ref3.trackType;
  var trackId = trackType === 'function' ? cfg.trackBy(itemData) : itemData[cfg.trackBy];
  var trackedItem = tracker[trackId];

  if (!trackedItem) {
    trackedItem = tracker[trackId] = {
      items: [],
      id: trackId
    };
    target.push(trackedItem);
  }

  trackedItem.items.push(obj);
}

function datumExtract(propCfg, cell, _ref) {
  var key = _ref.key;
  var datum = {
    value: typeof propCfg.value === 'function' ? propCfg.value(cell) : typeof propCfg.value !== 'undefined' ? propCfg.value : cell // eslint-disable-line no-nested-ternary

  };
  datum.label = typeof propCfg.label === 'function' ? propCfg.label(cell) : typeof propCfg.label !== 'undefined' ? String(propCfg.label) : String(datum.value); // eslint-disable-line no-nested-ternary

  if (propCfg.field) {
    datum.source = {
      key: key,
      field: propCfg.field.key()
    };
  }

  return datum;
}

function extract$1(config, dataset) {
  var cfgs = Array.isArray(config) ? config : [config];
  var dataItems = [];
  cfgs.forEach(function (cfg) {
    if (typeof cfg.field !== 'undefined') {
      (function () {
        var f = dataset.field(cfg.field);
        var sourceKey = dataset.key();

        if (!f) {
          throw Error("Field '".concat(cfg.field, "' not found"));
        }

        var _getPropsInfo = getPropsInfo(cfg, dataset),
            props = _getPropsInfo.props,
            main = _getPropsInfo.main;

        var propsArr = Object.keys(props);
        var track$1 = !!cfg.trackBy;

        var trackType = _typeof(cfg.trackBy);

        var tracker = {};
        var trackedItems = [];
        var items = f.items();
        var mapped = [];

        var _loop = function _loop(idx) {
          var mainCell = items[idx];
          var exclude = main.filter && !main.filter(mainCell);

          if (exclude) {
            return "continue";
          }

          var ret = datumExtract(main, mainCell, {
            key: sourceKey
          }); // loop through all props that need to be mapped and
          // assign 'value' and 'source' to each property

          propsArr.forEach(function (prop) {
            var p = props[prop];
            var propCell = p.field ? p.field.items()[idx] : mainCell;
            ret[prop] = datumExtract(p, propCell, {
              key: sourceKey
            });
          }); // collect items based on the trackBy value
          // items with the same trackBy value are placed in an array and reduced later

          if (track$1) {
            picasso_esm_track({
              cfg: cfg,
              itemData: mainCell,
              obj: ret,
              target: trackedItems,
              tracker: tracker,
              trackType: trackType
            });
          }

          mapped.push(ret);
        };

        for (var idx = 0; idx < items.length; idx++) {
          var _ret = _loop(idx);

          if (_ret === "continue") continue;
        } // reduce if items have been grouped


        if (track$1) {
          dataItems.push.apply(dataItems, _toConsumableArray$1(collect(trackedItems, {
            main: main,
            propsArr: propsArr,
            props: props
          })));
        } else {
          dataItems.push.apply(dataItems, mapped);
        }
      })();
    }
  });
  return dataItems;
}

var filters$1 = {
  numeric: function numeric(values) {
    return values.filter(function (v) {
      return typeof v === 'number' && !isNaN(v);
    });
  }
};

function createFields(_ref) {
  var source = _ref.source,
      data = _ref.data,
      cache = _ref.cache,
      config = _ref.config;
  var headers;
  var content = data;
  var parse = config && config.parse;

  if (Array.isArray(data[0])) {
    // assume 2d matrix of data
    if (parse && parse.headers === false) {
      headers = data[0].map(function (v, i) {
        return i;
      });
    } else {
      headers = data[0];
      content = data.slice(1);
    }
  } else {
    headers = Object.keys(data[0]);
  }

  var rowFn = !!parse && typeof parse.row === 'function' && parse.row;
  var flds = headers;

  if (parse && typeof parse.fields === 'function') {
    flds = parse.fields(flds.slice());
  } else {
    flds = headers.map(function (h) {
      return {
        key: h,
        title: h
      };
    });
  }

  var fieldValues;

  if (Array.isArray(data[0])) {
    fieldValues = flds.map(function () {
      return [];
    });
  } else {
    fieldValues = {};
    flds.forEach(function (f) {
      fieldValues[f.key] = [];
    });
  }

  for (var r = 0; r < content.length; r++) {
    var row = rowFn ? rowFn(content[r], r, flds) : content[r];

    if (!row) {
      continue;
    }

    if (Array.isArray(row)) {
      for (var c = 0; c < flds.length; c++) {
        fieldValues[c].push(row[c]);
      }
    } else {
      for (var _c = 0; _c < flds.length; _c++) {
        fieldValues[flds[_c].key].push(row[flds[_c].key]);
      }
    }
  }

  var fv = Array.isArray(fieldValues) ? function (i) {
    return fieldValues[i];
  } : function (i) {
    return fieldValues[flds[i].key];
  };

  for (var _c2 = 0; _c2 < flds.length; _c2++) {
    var values = fv(_c2);
    var numericValues = filters$1.numeric(values);
    var isMeasure = numericValues.length > 0;
    var type = isMeasure ? 'measure' : 'dimension';
    var min = isMeasure ? Math.min.apply(Math, _toConsumableArray$1(numericValues)) : NaN;
    var max = isMeasure ? Math.max.apply(Math, _toConsumableArray$1(numericValues)) : NaN;
    cache.fields.push(picasso_esm_field(extend({
      source: source,
      key: _c2,
      title: flds[_c2].title,
      values: values,
      min: min,
      max: max,
      type: type
    }, flds[_c2]), {
      value: flds[_c2].value,
      label: flds[_c2].label
    }));
  }
}

var dsv = function dsv(_ref2) {
  var data = _ref2.data,
      config = _ref2.config;
  var rows = data.split('\n');
  var row0 = rows[0];
  var row1 = rows[1];
  var delimiter = ',';

  if (config && config.parse && config.parse.delimiter) {
    delimiter = config.parse.delimiter;
  } else if (row0) {
    // guess delimiter
    var guesses = [/,/, /\t/, /;/];

    for (var i = 0; i < guesses.length; i++) {
      var d = guesses[i];

      if (row0 && row1) {
        if (d.test(row0) && d.test(row1) && row0.split(d).length === row1.split(d).length) {
          delimiter = d;
          break;
        }
      } else if (d.test(row0)) {
        delimiter = d;
      }
    }
  }

  return rows.map(function (row) {
    return row.split(delimiter);
  });
};

var parseData = function parseData(_ref3) {
  var key = _ref3.key,
      data = _ref3.data,
      cache = _ref3.cache,
      config = _ref3.config;

  if (!data) {
    return;
  }

  var dd = data;

  if (typeof dd === 'string') {
    // assume dsv
    dd = dsv({
      data: data,
      config: config
    });
  }

  if (!Array.isArray(dd)) {
    return; // warn?
  }

  createFields({
    data: dd,
    cache: cache,
    source: key,
    config: config
  });
};
/**
 * Create a new dataset with default settings
 * @private
 * @return {dataset}
 */


function ds() {
  var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _key = _ref4.key,
      data = _ref4.data,
      config = _ref4.config;

  var cache = {
    fields: []
  };
  /**
   * @alias dataset
   * @interface
   */

  var dataset = {
    /**
     * Get the key identifying this dataset
     * @returns {string}
     */
    key: function key() {
      return _key;
    },

    /**
     * Get the raw data
     * @returns {any}
     */
    raw: function raw() {
      return data;
    },

    /**
     * Find a field within this dataset
     * @param {string} query - The field to find
     * @returns {field}
     */
    field: function field(query) {
      return findField(query, {
        cache: cache,
        matrix: data
      });
    },

    /**
     * Get all fields within this dataset
     * @returns {Array<field>}
     */
    fields: function fields() {
      return cache.fields.slice();
    },

    /**
     * Extract data items from this dataset
     * @param {data-extract-config} config
     * @returns {Array<datum-extract>}
     */
    extract: function extract(cfg) {
      return extract$1(cfg, dataset);
    },

    /**
     * @returns {null}
     */
    hierarchy: function hierarchy() {
      return null;
    }
  };
  parseData({
    key: _key,
    data: data,
    config: config,
    cache: cache
  });
  return dataset;
}

ds.util = {
  normalizeConfig: getPropsInfo,
  collect: collect,
  track: picasso_esm_track
};
/**
 * @typedef {object} data-extract-config
 * @property {string} field - The field to extract data from
 * @property {data-extract-config~valueFn} [value] - The field value accessor
 * @property {data-extract-config~labelFn} [label] - The field label accessor
 * @property {data-extract-config~trackByFn} [trackBy] - Track by value accessor
 * @property {data-extract-config~reduceFn} [reduce] - Reducer function
 * @property {data-extract-config~reduceLabelFn} [reduceLabel] - Label reducer function
 * @property {data-extract-config~filterFn} [filter] - Filter function
 * @property {object} [props] - Additional properties to add to the extracted item
 */

/**
 * @callback data-extract-config~valueFn
 * @param {any} cell The field cell
 * @returns {any}
 */

/**
 * @callback data-extract-config~labelFn
 * @param {any} cell The field cell
 * @returns {string}
 */

/**
 * @callback data-extract-config~filterFn
 * @param {any} cell The field cell
 * @returns {boolean}
 */

/**
 * @callback data-extract-config~trackByFn
 * @param {any} cell The field cell
 * @returns {any}
 */

/**
 * @callback data-extract-config~reduceFn
 * @param {any[]} values The collected values to reduce
 * @returns {any}
 */

/**
 * @callback data-extract-config~reduceLabelFn
 * @param {any[]} labels The collected labels to reduce
 * @param {any} value Reduced value
 * @returns {string}
 */

/**
 * @typedef {object} datum-extract
 * @property {any} value - The extracted value
 * @property {string} label - The extracted value as a string
 * @property {object} source - The data source of the extracted data
 * @property {string} source.key - The data-source key
 * @property {string} source.field - The source field
 */

var dataRegistry = registryFactory();
dataRegistry.default('matrix');
dataRegistry('matrix', ds);
dataRegistry('default', ds); // deprecated

/**
 * Manages event handlers for native events
 * @private
 */
function picasso_esm_native(chart, mediator, element) {
  var instance = {
    chart: chart,
    mediator: mediator,
    element: element
  };
  var nativeEvents = [];
  var settings;
  var itKey;
  var isOn = true;
  /**
   * Set default settings
   * @private
   */

  function setDefaultSettings(newSettings) {
    itKey = newSettings.key;
    settings = newSettings;
    settings.events = settings.events || [];

    if (settings.enable === undefined) {
      settings.enable = true;
    }
  }
  /**
   * Add native events based on settings
   * @private
   */


  function addEvents() {
    if (typeof settings.enable === 'function') {
      settings.enable = settings.enable.bind(instance)();
    }

    if (!settings.enable) {
      return; // interaction is disabled
    }

    Object.keys(settings.events).forEach(function (key) {
      var listener = settings.events[key].bind(instance);
      element.addEventListener(key, listener);
      nativeEvents.push({
        key: key,
        listener: listener
      });
    });
  }
  /**
   * Removes all added native events
   * @private
   */


  function removeAddedEvents() {
    // remove added native events
    nativeEvents.forEach(function (_ref) {
      var key = _ref.key,
          listener = _ref.listener;
      element.removeEventListener(key, listener);
    });
    nativeEvents = [];
  }

  return {
    /**
     * Getter for the key.
     * @private
     */
    get key() {
      return itKey;
    },

    /**
     * Updates this with new settings
     * @private
     * @param {object} newSettings
     * @param {string} [newSettings.type] - The interaction type. Is 'native' for this component
     * @param {boolean|function} [newSettings.enable=true] - Should the interactions defined here be enabled or not.
     * This is only run when adding event handlers. In effect at startup, update or during on/off.
     * It does not run during every event loop.
     * @param {array} [newSettings.gestures] - The keys in this object is the names of native events
     * that should be added to the chart element and they should all point to function which
     * will be the corresponding event handler.
     */
    set: function set(newSettings) {
      setDefaultSettings(newSettings);
      removeAddedEvents();

      if (isOn) {
        addEvents();
      }
    },

    /**
     * Turns off interactions
     * @private
     */
    off: function off() {
      isOn = false;
      removeAddedEvents();
    },

    /**
     * Turns off interactions
     * @private
     */
    on: function on() {
      isOn = true;

      if (nativeEvents.length === 0) {
        addEvents();
      }
    },

    /**
     * Destroys and unbinds all event handlers
     * @private
     */
    destroy: function destroy() {
      removeAddedEvents();
      instance = null;
      settings = null;
    }
  };
}

var reg$1 = registryFactory();
reg$1('native', picasso_esm_native);

/**
 * Short-hand for max(min())
 *
 * @param {number} min Minimum allowed value
 * @param {number} max Maximum allowed value
 * @param {number} value The actual value to cap
 * @ignore
 */
function picasso_esm_cap(min, max, value) {
  return Math.max(min, Math.min(max, value));
}
/**
 * Resolve a diff, i.e. resolveDiff(0.2, 0.6, 1, 100) = 20
 *
 * @param {object} params parameters
 * @param {number} params.start Normalized start value
 * @param {number} params.end Normalized end value
 * @param {number} params.minPx The minimum number of pixels
 * @param {number} params.maxPx Maximum number of pixels, i.e. the width or height
 * @ignore
 */

function resolveDiff(_ref) {
  var start = _ref.start,
      end = _ref.end,
      _ref$minPx = _ref.minPx,
      minPx = _ref$minPx === void 0 ? 0.1 : _ref$minPx,
      _ref$maxPx = _ref.maxPx,
      maxPx = _ref$maxPx === void 0 ? 1 : _ref$maxPx;
  var high = Math.max(start, end);
  var low = Math.min(start, end);
  var highModified = picasso_esm_cap(-0.1, 1.2, high);
  var lowModified = picasso_esm_cap(-0.1, 1.2, low);
  var wantedDiff = highModified * maxPx - lowModified * maxPx;
  var actualDiff = Math.max(minPx, wantedDiff);
  var startModifier = (actualDiff - wantedDiff) / 2;
  var actualLow = lowModified * maxPx - startModifier;
  return {
    actualDiff: actualDiff,
    startModifier: startModifier,
    actualLow: actualLow
  };
}

/**
 * Out of bounds shape
 * @param {object} params parameters
 * @param {object} params.item Resolved styling item from box component with item.major
 * @param {number} params.value 0 or 1 depending on where to render the oob shape
 * @param {number} params.boxWidth Un-calculated box width in relative/normalized format
 * @param {number} params.boxPadding Un-calculated box padding in relative/normalized format
 * @param {number} params.rendWidth The pixel width of the area to render upon
 * @param {number} params.rendHeight The pixel height of the area to render upon
 * @param {boolean} params.flipXY Wether or not to flip X and Y coordinates together with Width and Height
 * @param {function} params.symbol Symbol library function from component
 * @ignore
 */

function oob(_ref) {
  var _extend;

  var item = _ref.item,
      value = _ref.value,
      boxCenter = _ref.boxCenter,
      rendWidth = _ref.rendWidth,
      rendHeight = _ref.rendHeight,
      flipXY = _ref.flipXY,
      symbol = _ref.symbol;
  var x = 'x';
  var y = 'y';
  var calcwidth = rendWidth;
  var calcheight = rendHeight;
  var startAngle = value < 0.5 ? 90 : -90;

  if (flipXY) {
    x = 'y';
    y = 'x';
    calcwidth = rendHeight;
    calcheight = rendWidth;
    startAngle = value < 0.5 ? 180 : 0;
  }

  return symbol(extend({}, item.oob, (_extend = {}, dist_picasso_esm_defineProperty(_extend, x, boxCenter * calcwidth), dist_picasso_esm_defineProperty(_extend, y, Math.max(item.oob.size / 2, Math.min(value * calcheight, calcheight - item.oob.size / 2))), dist_picasso_esm_defineProperty(_extend, "startAngle", startAngle), _extend)));
}
/**
 * Box shape calculation function
 * @param {object} params parameters
 * @param {object} params.item Resolved styling item from box component with item.major
 * @param {number} params.boxWidth Un-calculated box width in relative/normalized format
 * @param {number} params.boxPadding Un-calculated box padding in relative/normalized format
 * @param {number} params.rendWidth The pixel width of the area to render upon
 * @param {number} params.rendHeight The pixel height of the area to render upon
 * @param {boolean} params.flipXY wether or not to flip X and Y coordinates together with Width and Height
 * @ignore
 */

function picasso_esm_box(_ref2) {
  var _extend2;

  var item = _ref2.item,
      boxWidth = _ref2.boxWidth,
      boxPadding = _ref2.boxPadding,
      rendWidth = _ref2.rendWidth,
      rendHeight = _ref2.rendHeight,
      flipXY = _ref2.flipXY;
  var x = 'x';
  var y = 'y';
  var width = 'width';
  var height = 'height';
  var calcwidth = rendWidth;
  var calcheight = rendHeight;

  if (flipXY) {
    x = 'y';
    y = 'x';
    width = 'height';
    height = 'width';
    calcwidth = rendHeight;
    calcheight = rendWidth;
  }

  var _resolveDiff = resolveDiff({
    start: item.start,
    end: item.end,
    minPx: item.box.minHeightPx,
    maxPx: calcheight
  }),
      actualDiff = _resolveDiff.actualDiff,
      actualLow = _resolveDiff.actualLow;

  return extend({}, item.box, (_extend2 = {
    type: 'rect'
  }, dist_picasso_esm_defineProperty(_extend2, x, (boxPadding + item.major) * calcwidth), dist_picasso_esm_defineProperty(_extend2, y, actualLow), dist_picasso_esm_defineProperty(_extend2, height, actualDiff), dist_picasso_esm_defineProperty(_extend2, width, boxWidth * calcwidth), dist_picasso_esm_defineProperty(_extend2, "data", item.data || {}), dist_picasso_esm_defineProperty(_extend2, "collider", {
    type: null
  }), _extend2));
}
/**
 * A vertical line shape (for start - min, end - max values)
 * @param {object} params parameters
 * @param {object} params.item Resolved styling item from box component with item.major
 * @param {number} params.from Normalized from value
 * @param {number} params.to Normalized to value
 * @param {number} params.boxCenter Center coordinate for the box
 * @param {number} params.rendWidth The pixel width of the area to render upon
 * @param {number} params.rendHeight The pixel height of the area to render upon
 * @param {boolean} params.flipXY wether or not to flip X and Y coordinates together with Width and Height
 * @ignore
 */

function verticalLine(_ref3) {
  var _extend3;

  var item = _ref3.item,
      from = _ref3.from,
      to = _ref3.to,
      boxCenter = _ref3.boxCenter,
      rendWidth = _ref3.rendWidth,
      rendHeight = _ref3.rendHeight,
      flipXY = _ref3.flipXY;
  var x1 = 'x1';
  var y1 = 'y1';
  var x2 = 'x2';
  var y2 = 'y2';
  var calcwidth = rendWidth;
  var calcheight = rendHeight;

  if (flipXY) {
    x1 = 'y1';
    y1 = 'x1';
    x2 = 'y2';
    y2 = 'x2';
    calcwidth = rendHeight;
    calcheight = rendWidth;
  }

  return extend({}, item.line, (_extend3 = {
    type: 'line'
  }, dist_picasso_esm_defineProperty(_extend3, y2, Math.floor(from * calcheight)), dist_picasso_esm_defineProperty(_extend3, x1, boxCenter * calcwidth), dist_picasso_esm_defineProperty(_extend3, y1, Math.floor(to * calcheight)), dist_picasso_esm_defineProperty(_extend3, x2, boxCenter * calcwidth), dist_picasso_esm_defineProperty(_extend3, "data", item.data || {}), dist_picasso_esm_defineProperty(_extend3, "collider", {
    type: null
  }), _extend3));
}
/**
 * A horizontal line shape (for median and whiskers)
 * @param {object} params parameters
 * @param {object} params.item Resolved styling item from box component with item.major
 * @param {string} params.key Which key to use as style base in the item object
 * @param {number} params.position At which "height" (X) to position the horizontal line
 * @param {number} params.width Width of the horizontal line (i.e. box width or a multiple of it)
 * @param {number} params.boxCenter Center coordinate for the box
 * @param {number} params.rendWidth The pixel width of the area to render upon
 * @param {number} params.rendHeight The pixel height of the area to render upon
 * @param {boolean} params.flipXY wether or not to flip X and Y coordinates together with Width and Height
 * @ignore
 */

function horizontalLine(_ref4) {
  var _extend4;

  var item = _ref4.item,
      key = _ref4.key,
      position = _ref4.position,
      width = _ref4.width,
      boxCenter = _ref4.boxCenter,
      rendWidth = _ref4.rendWidth,
      rendHeight = _ref4.rendHeight,
      flipXY = _ref4.flipXY;
  var x1 = 'x1';
  var y1 = 'y1';
  var x2 = 'x2';
  var y2 = 'y2';
  var calcwidth = rendWidth;
  var calcheight = rendHeight;

  if (flipXY) {
    x1 = 'y1';
    y1 = 'x1';
    x2 = 'y2';
    y2 = 'x2';
    calcwidth = rendHeight;
    calcheight = rendWidth;
  }

  var halfWidth = width / 2;
  return extend({
    type: 'line'
  }, item[key], (_extend4 = {}, dist_picasso_esm_defineProperty(_extend4, y1, Math.floor(position * calcheight)), dist_picasso_esm_defineProperty(_extend4, x1, (boxCenter - halfWidth) * calcwidth), dist_picasso_esm_defineProperty(_extend4, y2, Math.floor(position * calcheight)), dist_picasso_esm_defineProperty(_extend4, x2, (boxCenter + halfWidth) * calcwidth), dist_picasso_esm_defineProperty(_extend4, "r", halfWidth * calcwidth), dist_picasso_esm_defineProperty(_extend4, "cx", boxCenter * calcwidth), dist_picasso_esm_defineProperty(_extend4, "cy", position * calcheight), dist_picasso_esm_defineProperty(_extend4, "width", width * calcwidth), dist_picasso_esm_defineProperty(_extend4, "data", item.data || {}), dist_picasso_esm_defineProperty(_extend4, "collider", {
    type: null
  }), _extend4));
}
/**
 * A horizontal line shape (for median and whiskers)
 * @param {number} bandwidth The current bandwidth for this item
 * @param {object} item A resolved style item to render with major and box width variables, minWidthPx and maxWidthPx
 * @param {number} maxMajorWidth The actual maximum major width
 * @ignore
 */

function getBoxWidth(bandwidth, item, maxMajorWidth) {
  var _item$box = item.box,
      width = _item$box.width,
      maxWidthPx = _item$box.maxWidthPx,
      minWidthPx = _item$box.minWidthPx;
  var sign = bandwidth >= 0 ? 1 : -1;
  var boxWidth = Math.min(sign * bandwidth * width, isNaN(maxWidthPx) ? maxMajorWidth : maxWidthPx / maxMajorWidth);
  boxWidth = isNaN(minWidthPx) ? boxWidth : Math.max(minWidthPx / maxMajorWidth, boxWidth);
  return boxWidth * sign;
}

function buildShapes(_ref) {
  var width = _ref.width,
      height = _ref.height,
      flipXY = _ref.flipXY,
      resolved = _ref.resolved,
      keys = _ref.keys,
      symbol = _ref.symbol;
  // if (!settings || !settings.major || !settings.major.scale || !settings.minor || !settings.minor.scale) {
  //   return [];
  // }
  var output = [];
  var majorItems = resolved.major.items;

  if (!majorItems.length) {
    return output;
  }

  var rendWidth = width;
  var rendHeight = height;
  var maxMajorWidth = flipXY ? height : width;
  var majorSettings = resolved.major.settings;
  var minorProps = ['start', 'end', 'min', 'max', 'med'].filter(function (prop) {
    return typeof resolved.minor.settings[prop] !== 'undefined';
  });
  var numMinorProps = minorProps.length;
  var nonOobKeys = keys.filter(function (key) {
    return key !== 'oob';
  });
  var children;
  var major;
  var minorItem;
  var boxWidth;
  var boxPadding;
  var boxCenter;
  var isLowerOutOfBounds;
  var isHigherOutOfBounds;
  var isOutOfBounds;
  var numKeys = keys ? keys.length : 0;
  var numNonOobKeys = nonOobKeys ? nonOobKeys.length : 0;

  function addBox() {
    /* THE BOX */
    if (minorItem.box && isNumber(minorItem.start) && isNumber(minorItem.end)) {
      children.push(picasso_esm_box({
        item: minorItem,
        boxWidth: boxWidth,
        boxPadding: boxPadding,
        rendWidth: rendWidth,
        rendHeight: rendHeight,
        flipXY: flipXY
      }));
    }
  }

  function addLine() {
    /* LINES MIN - START, END - MAX */
    if (isNumber(minorItem.min) && isNumber(minorItem.start)) {
      children.push(verticalLine({
        item: minorItem,
        from: minorItem.min,
        to: minorItem.start,
        boxCenter: boxCenter,
        rendWidth: rendWidth,
        rendHeight: rendHeight,
        flipXY: flipXY
      }));
    }

    if (isNumber(minorItem.max) && isNumber(minorItem.end)) {
      children.push(verticalLine({
        item: minorItem,
        from: minorItem.max,
        to: minorItem.end,
        boxCenter: boxCenter,
        rendWidth: rendWidth,
        rendHeight: rendHeight,
        flipXY: flipXY
      }));
    }
  }

  function addMedian() {
    /* MEDIAN */
    if (minorItem.median && isNumber(minorItem.med)) {
      children.push(horizontalLine({
        item: minorItem,
        key: 'median',
        position: minorItem.med,
        width: boxWidth,
        boxCenter: boxCenter,
        rendWidth: rendWidth,
        rendHeight: rendHeight,
        flipXY: flipXY
      }));
    }
  }

  function addWhisker() {
    /* WHISKERS */
    if (minorItem.whisker) {
      var whiskerWidth = boxWidth * minorItem.whisker.width;

      if (isNumber(minorItem.min)) {
        children.push(horizontalLine({
          item: minorItem,
          key: 'whisker',
          position: minorItem.min,
          width: whiskerWidth,
          boxCenter: boxCenter,
          rendWidth: rendWidth,
          rendHeight: rendHeight,
          flipXY: flipXY
        }));
      }

      if (isNumber(minorItem.max)) {
        children.push(horizontalLine({
          item: minorItem,
          key: 'whisker',
          position: minorItem.max,
          width: whiskerWidth,
          boxCenter: boxCenter,
          rendWidth: rendWidth,
          rendHeight: rendHeight,
          flipXY: flipXY
        }));
      }
    }
  }

  function addOutOfBounds() {
    /* OUT OF BOUNDS */
    if (isLowerOutOfBounds) {
      children.push(oob({
        item: minorItem,
        value: 0,
        boxCenter: boxCenter,
        rendWidth: rendWidth,
        rendHeight: rendHeight,
        flipXY: flipXY,
        symbol: symbol
      }));
    } else if (isHigherOutOfBounds) {
      children.push(oob({
        item: minorItem,
        value: 1,
        boxCenter: boxCenter,
        rendWidth: rendWidth,
        rendHeight: rendHeight,
        flipXY: flipXY,
        symbol: symbol
      }));
    }
  }

  var addMarkerList = {
    box: addBox,
    line: addLine,
    median: addMedian,
    whisker: addWhisker
  };

  function checkOutOfBounds() {
    var value;
    var max = -Number.MAX_VALUE;
    var min = Number.MAX_VALUE;

    for (var n = 0; n < numMinorProps; n++) {
      value = minorItem[minorProps[n]];

      if (isNumber(value)) {
        if (max < value) {
          max = value;
        }

        if (min > value) {
          min = value;
        }
      }
    }

    isLowerOutOfBounds = max < 0 && max !== -Number.MAX_VALUE;
    isHigherOutOfBounds = min > 1 && min !== Number.MAX_VALUE;
    isOutOfBounds = isLowerOutOfBounds || isHigherOutOfBounds;
  }

  for (var i = 0, len = majorItems.length; i < len; i++) {
    children = [];
    major = null;
    var majorItem = majorItems[i];
    var d = majorItem.data;
    var majorVal = null;
    var majorEndVal = null;

    if (typeof majorSettings.binStart !== 'undefined') {
      // if start and end is defined
      majorVal = majorItem.binStart;
      majorEndVal = majorItem.binEnd;
      major = majorSettings.binStart.scale;
    } else {
      major = majorSettings.major.scale;
      majorVal = major ? majorItem.major : 0;
    }

    var bandwidth = 0;

    if (!major) {
      bandwidth = 1;
    } else if (major.bandwidth) {
      bandwidth = major.bandwidth();
      majorVal -= bandwidth / 2;
    } else {
      bandwidth = majorEndVal - majorVal;
    }

    minorItem = extend({}, {
      major: majorVal,
      majorEnd: majorEndVal
    }, resolved.minor.items[i]);

    for (var j = 0; j < numKeys; j++) {
      minorItem[keys[j]] = resolved[keys[j]].items[i];
    }

    boxWidth = getBoxWidth(bandwidth, minorItem, maxMajorWidth);
    boxPadding = (bandwidth - boxWidth) / 2;
    boxCenter = boxPadding + minorItem.major + boxWidth / 2;
    checkOutOfBounds();

    if (!isOutOfBounds) {
      for (var k = 0; k < numNonOobKeys; k++) {
        if (minorItem[nonOobKeys[k]] && minorItem[nonOobKeys[k]].show === false) {
          continue;
        }

        addMarkerList[nonOobKeys[k]]();
      }
    } else if (minorItem.oob) {
      addOutOfBounds();
    }

    var container = {
      type: 'container',
      data: d,
      collider: {
        type: 'bounds'
      },
      children: children
    };
    output.push(container);
  }

  return output;
}

/**
 * Resolve a complex object using the built-in resolver from this.resolver in component
 * @ignore
 */

function complexResolver(_ref) {
  var keys = _ref.keys,
      data = _ref.data,
      defaultSettings = _ref.defaultSettings,
      style = _ref.style,
      settings = _ref.settings,
      width = _ref.width,
      height = _ref.height,
      resolver = _ref.resolver;
  var defaults = extend(true, {}, defaultSettings || {}, style || {});
  var scaled = {
    major: settings.orientation === 'horizontal' ? height : width,
    minor: settings.orientation === 'horizontal' ? width : height
  };
  var majorSettings = settings.major;
  var majorResolved;

  if (_typeof(majorSettings) === 'object' && _typeof(majorSettings.ref) === 'object' && typeof majorSettings.ref.start !== 'undefined' && typeof majorSettings.ref.end !== 'undefined') {
    // temporary backwards compatibility
    majorResolved = resolver.resolve({
      data: data,
      defaults: {
        start: 0,
        end: 1
      },
      scaled: scaled,
      settings: extend(true, {}, {
        binStart: {
          scale: settings.major.scale,
          ref: settings.major.ref.start
        },
        binEnd: {
          scale: settings.major.scale,
          ref: settings.major.ref.end
        }
      })
    });
  } else if (_typeof(majorSettings) === 'object' && typeof majorSettings.binStart !== 'undefined' && typeof majorSettings.binEnd !== 'undefined') {
    majorResolved = resolver.resolve({
      data: data,
      defaults: {
        start: 0,
        end: 1
      },
      scaled: scaled,
      settings: extend(true, {}, {
        binStart: {
          scale: settings.major.scale,
          ref: 'binStart'
        },
        binEnd: {
          scale: settings.major.scale,
          ref: 'binEnd'
        }
      }, settings.major)
    });
  } else {
    majorResolved = resolver.resolve({
      data: data,
      scaled: scaled,
      defaults: {
        major: 0.5
      },
      settings: {
        major: settings.major
      }
    });
  }

  var minorSettings = settings.minor || {};
  var defaultMinorSettings = {};
  ['start', 'end', 'min', 'max', 'med'].forEach(function (prop) {
    if (minorSettings[prop] || data.items && data.items.length && data.items[0][prop]) {
      defaultMinorSettings[prop] = {
        scale: minorSettings.scale,
        ref: prop
      };
    }
  });
  var minorResolved = resolver.resolve({
    data: data,
    defaults: {
      start: 0,
      end: 1
    },
    scaled: scaled,
    settings: extend(true, {}, defaultMinorSettings, minorSettings)
  });
  var key;
  var ext = {
    major: majorResolved,
    minor: minorResolved
  };

  for (var ki = 0, len = keys.length; ki < len; ki++) {
    if (!settings[key] || settings[key].show !== false) {
      key = keys[ki];
      ext[key] = resolver.resolve({
        data: data,
        defaults: defaults[key],
        settings: settings[key],
        scaled: scaled
      });
    }
  }

  return ext;
}

var DEFAULT_DATA_SETTINGS = {
  oob: {
    show: true,
    type: 'n-polygon',
    fill: '#999',
    stroke: '#000',
    strokeWidth: 0,
    size: 10,
    sides: 3,
    startAngle: -90
  },
  box: {
    show: true,
    fill: '#fff',
    stroke: '#000',
    strokeWidth: 1,
    strokeLinejoin: 'miter',
    width: 1,
    maxWidthPx: undefined,
    minWidthPx: 1,
    minHeightPx: 1
  },
  line: {
    show: true,
    stroke: '#000',
    strokeWidth: 1
  },
  median: {
    show: true,
    stroke: '#000',
    strokeWidth: 1
  },
  whisker: {
    show: true,
    stroke: '#000',
    strokeWidth: 1,
    fill: '',
    type: 'line',
    width: 1
  }
};
var dataKeys = Object.keys(DEFAULT_DATA_SETTINGS);
var picasso_esm_component = {
  require: ['chart', 'resolver', 'symbol'],
  defaultSettings: {
    settings: {},
    data: {},
    style: {
      box: '$shape',
      line: '$shape-guide',
      whisker: '$shape-guide',
      median: '$shape-guide--inverted'
    }
  },
  created: function created() {
    this.state = {};
  },
  render: function render(_ref) {
    var _this = this;

    var data = _ref.data;
    var _this$rect = this.rect,
        width = _this$rect.width,
        height = _this$rect.height;
    var flipXY = this.settings.settings.orientation === 'horizontal';
    var style = this.style,
        resolver = this.resolver,
        symbol = this.symbol;
    var keys = dataKeys.filter(function (key) {
      return !_this.settings.settings[key] || _this.settings.settings[key].show !== false;
    });
    var defaultSettings = {};
    keys.forEach(function (key) {
      return defaultSettings[key] = DEFAULT_DATA_SETTINGS[key];
    });
    var resolved = complexResolver({
      keys: keys,
      data: data,
      defaultSettings: defaultSettings,
      style: style,
      settings: this.settings.settings,
      width: width,
      height: height,
      resolver: resolver
    });
    var settings = resolved.settings,
        items = resolved.items;
    var shapes = buildShapes({
      items: items,
      settings: settings,
      width: width,
      height: height,
      flipXY: flipXY,
      resolved: resolved,
      keys: keys,
      symbol: symbol
    });
    return shapes;
  }
};

function box$1(picasso) {
  picasso.component('box', picasso_esm_component);
  picasso.component('box-marker', picasso_esm_component); // temporary backwards compatibility - DEPRECATED
}
/**
 * @typedef {object} component--box
 * @property {string} type - "box"
 * @property {component--box~data} data Box data
 * @property {component--box~settings} settings Box settings
 * @example
 * {
 *   type: "box",
 *   data: {
 *    mapTo: {
 *      min: { source: "/qHyperCube/qMeasureInfo/0" },
 *      start: { source: "/qHyperCube/qMeasureInfo/1" },
 *      med: { source: "/qHyperCube/qMeasureInfo/2" },
 *      end: { source: "/qHyperCube/qMeasureInfo/3" },
 *      max: { source: "/qHyperCube/qMeasureInfo/4" },
 *    },
 *    groupBy: {
 *      source: "/qHyperCube/qDimensionInfo/0"
 *    }
 *  },
 *  settings: {
 *    major: {
 *      scale: { source: "/qHyperCube/qDimensionInfo/0" }
 *    },
 *    minor: {
 *      scale: { source: ["/qHyperCube/qMeasureInfo/0",
 *               "/qHyperCube/qMeasureInfo/1",
 *               "/qHyperCube/qMeasureInfo/2",
 *               "/qHyperCube/qMeasureInfo/3",
 *               "/qHyperCube/qMeasureInfo/4"] }
 *    }
 *  }
 * }
 */

/**
 * @typedef {object} component--box~settings
 * @property {object} major
 * @property {string} major.scale The scale to use along the major (dimension) axis
 * @property {string|component--box~settings~majorReference} [major.ref='self'] Reference to the data property along the major axis
 * @property {object} minor
 * @property {string} minor.scale The scale to use along the minor (measure) axis
 * @property {string} [orientation='vertical'] Which orientation to use (vertical or horizontal)
 * @property {object} [box] Visual properties for the box shape in the box marker
 * @property {boolean} [box.show=true] Boolean for showing the box shape
 * @property {string} [box.fill='#fff']
 * @property {string} [box.stroke='#000']
 * @property {number} [box.strokeWidth=1]
 * @property {string} [box.strokeLinejoin='miter']
 * @property {number} [box.width=1]
 * @property {number} [box.maxWidthPx=100] Maximum width of the box in pixels (not applicable when using major start and end)
 * @property {number} [box.minWidthPx=1] Minimum width of the box in pixels (not applicable when using major start and end)
 * @property {number} [box.minHeightPx=1] Minimum height of the box shape
 * @property {object} [line] Visual properties for lines between min-start, end-max.
 * @property {boolean} [line.show=true]
 * @property {string} [line.stroke='#000']
 * @property {number} [line.strokeWidth=1]
 * @property {object} [whisker] All the visual properties for whiskers at min and max.
 * @property {boolean} [whisker.show=true]
 * @property {string} [whisker.stroke='#000']
 * @property {number} [whisker.strokeWidth=1]
 * @property {number} [whisker.width=1]
 * @property {object} [median] Visual properties for the median
 * @property {boolean} [median.show=true]
 * @property {string} [median.stroke='#000']
 * @property {number} [median.strokeWidth=1]
 * @property {object} [oob] EXPERIMENTAL: Out of bounds symbol utilizing the symbol API
 * @property {boolean} [oob.show=true]
 * @property {string} [oob.type='n-polygon'] Type of the symbol to be used
 * @property {string} [oob.fill='#999'] Fill color of the symbol
 * @property {string} [oob.stroke='#000'] Stroke color
 * @property {number} [oob.strokeWidth=0] Stroke width
 * @property {number} [oob.size=10] Size/width of the symbol in pixels
 * @property {number} [oob.sides=3] Number of sides for a n-polygon (3 for triangle)
 */

/**
 * @typedef {object} component--box~settings~majorReference
 * @property {string} start Reference to the data property of the start value along the major axis
 * @property {string} end Reference to the data property of the end value along the major axis
 */

/**
 * @typedef {object} component--box~data
 * @property {number} [min] Min
 * @property {number} [max] Max
 * @property {number} [start] Start of box
 * @property {number} [end] End of box
 * @property {number} [med] Median
 */

var DEFAULT_ERROR_SETTINGS = {
  errorShape: {
    shape: 'saltire',
    width: 2,
    size: 0.5,
    fill: '#333',
    stroke: '#333',
    strokeWidth: 0
  }
};
/**
  * @typedef {object}
  * @alias component--point.settings
  */

var DEFAULT_DATA_SETTINGS$1 = {
  /** Type of shape
   * @type {datum-string=} */
  shape: 'circle',
  label: '',

  /** Fill color
   * @type {datum-string=} */
  fill: '#333',

  /** Stroke color
   * @type {datum-string=} */
  stroke: '#ccc',

  /** Stroke width
   * @type {datum-number=} */
  strokeWidth: 0,

  /** Stroke line join
   * @type {string=} */
  strokeLinejoin: 'miter',

  /** Opacity of shape
   * @type {datum-number=} */
  opacity: 1,

  /** Normalized x coordinate
   * @type {datum-number=} */
  x: 0.5,

  /** Normalized y coordinate
   * @type {datum-number=} */
  y: 0.5,

  /** Normalized size of shape
   * @type {datum-number=} */
  size: 1,
  strokeDasharray: ''
};
/**
  * @typedef {object}
  * @alias component--point.settings.sizeLimits
  */

var SIZE_LIMITS = {
  /** Maximum size of shape, in pixels
   * @type {number=} */
  maxPx: 10000,

  /** Minimum size of shape, in pixels
   * @type {number=} */
  minPx: 1,

  /** Maximum size relative linear scale extent
   * @type {number=} */
  maxRelExtent: 0.1,

  /** Minimum size relative linear scale extent
   * @type {number=} */
  minRelExtent: 0.01,

  /** Maximum size relative discrete scale banwidth
   * @type {number=} */
  maxRelDiscrete: 1,

  /** Minimum size relative discrete scale banwidth
   * @type {number=} */
  minRelDiscrete: 0.1
};

function getPxSpaceFromScale(s, space) {
  if (s && typeof s.bandwidth === 'function') {
    // some kind of ordinal scale
    return {
      isBandwidth: true,
      value: Math.max(1, s.bandwidth() * space)
    };
  }

  return {
    isBandwidth: false,
    value: Math.max(1, space)
  };
}

function getPointSizeLimits(x, y, width, height, limits) {
  var xSpacePx = getPxSpaceFromScale(x ? x.scale : undefined, width);
  var ySpacePx = getPxSpaceFromScale(y ? y.scale : undefined, height);
  var maxSizePx = Math.min(xSpacePx.value * limits[xSpacePx.isBandwidth ? 'maxRelDiscrete' : 'maxRelExtent'], ySpacePx.value * limits[ySpacePx.isBandwidth ? 'maxRelDiscrete' : 'maxRelExtent']);
  var minSizePx = Math.min(xSpacePx.value * limits[xSpacePx.isBandwidth ? 'minRelDiscrete' : 'minRelExtent'], ySpacePx.value * limits[ySpacePx.isBandwidth ? 'minRelDiscrete' : 'minRelExtent']);
  var min = Math.max(1, Math.floor(minSizePx));
  var max = Math.max(1, Math.floor(maxSizePx));
  return {
    min: min,
    max: max,
    maxGlobal: limits.maxPx,
    minGlobal: limits.minPx
  };
}

function createDisplayPoints(dataPoints, _ref, pointSize, shapeFn) {
  var width = _ref.width,
      height = _ref.height;
  return dataPoints.filter(function (p) {
    return !isNaN(p.x + p.y);
  }).map(function (p) {
    var s = notNumber(p.size) ? DEFAULT_ERROR_SETTINGS.errorShape : p;
    var size = pointSize.min + s.size * (pointSize.max - pointSize.min);
    var shapeSpec = {
      type: s.shape === 'rect' ? 'square' : s.shape,
      label: p.label,
      x: p.x * width,
      y: p.y * height,
      fill: s.fill,
      size: Math.min(pointSize.maxGlobal, Math.max(pointSize.minGlobal, size)),
      stroke: s.stroke,
      strokeWidth: s.strokeWidth,
      strokeDasharray: s.strokeDasharray,
      opacity: s.opacity
    };

    if (s === p.errorShape) {
      shapeSpec.width = s.width;
    }

    var shape = shapeFn(shapeSpec);
    shape.data = p.data;
    return shape;
  });
}

var component$1 = {
  require: ['chart', 'resolver', 'symbol'],
  defaultSettings: {
    settings: {},
    data: {},
    animations: {
      enabled: false,
      trackBy: function trackBy(node) {
        return node.data.value;
      }
    },
    style: {
      item: '$shape'
    }
  },
  render: function render(_ref2) {
    var data = _ref2.data;
    var resolved = this.resolver.resolve({
      data: data,
      defaults: extend({}, DEFAULT_DATA_SETTINGS$1, this.style.item),
      settings: this.settings.settings,
      scaled: {
        x: this.rect.width,
        y: this.rect.height
      }
    });
    var _this$rect = this.rect,
        width = _this$rect.width,
        height = _this$rect.height;
    var limits = extend({}, SIZE_LIMITS, this.settings.settings.sizeLimits);
    var points = resolved.items;
    var pointSize = getPointSizeLimits(resolved.settings.x, resolved.settings.y, width, height, limits);
    return createDisplayPoints(points, this.rect, pointSize, this.settings.shapeFn || this.symbol);
  }
};

/**
 * @typedef {object} component--point
 */

/**
 * @type {string}
 * @memberof component--point
 */

var picasso_esm_type = 'point';
function pointMarker(picasso) {
  picasso.component(picasso_esm_type, component$1);
  picasso.component('point-marker', component$1); // temporary backwards compatibility - DEPRECATED
}

/**
 * @typedef {object}
 * @alias component--pie-settings
 */

var DEFAULT_DATA_SETTINGS$2 = {
  /** Start angle of the pie, in radians
   * @type {number=} */
  startAngle: 0,

  /** End angle of the pie, in radians
   * @type {number=} */
  endAngle: 2 * Math.PI,

  /**
   * @typedef {object}
   */
  slice: {
    label: '',

    /** Absolute value of the slice's arc length
     * @type {number=} */
    arc: 1,

    /** Visibility of the slice
     * @type {boolean=} */
    show: true,

    /** Fill color of the slice
     * @type {string=} */
    fill: '#333',

    /** Stroke color of the slice
     * @type {string=} */
    stroke: '#ccc',

    /** Stroke width of the slice
     * @type {number=} */
    strokeWidth: 1,

    /** Stroke line join
     * @type {string=} */
    strokeLinejoin: 'round',

    /** Opacity of the slice
     * @type {number=} */
    opacity: 1,

    /** Inner radius of the slice
     * @type {number=} */
    innerRadius: 0,

    /** Outer radius of the slice
     * @type {number=} */
    outerRadius: 0.8,

    /** Corner radius of the slice, in pixels
     * @type {number=} */
    cornerRadius: 0,

    /** Radial offset of the slice
     * @type {number=} */
    offset: 0
  }
};
/**
 * @typedef {object} component--pie
 * @property {string} [type='pie']
 * @example
 * {
 *   type: 'pie',
 *   data: {
 *     extract: {
 *       field: 'Region',
 *       props: {
 *         num: { field: 'Population' }
 *       }
 *     }
 *   },
 *   settings: {
 *     startAngle: Math.PI / 2,
 *     endAngle: -Math.PI / 2,
 *     slice: {
 *       arc: { ref: 'num' },
 *       fill: 'green',
 *       stroke: 'red',
 *       strokeWidth: 2,
 *       strokeLinejoin: 'round',
 *       innerRadius: 0.6,
 *       outerRadius 0.8,
 *       opacity: 0.8,
 *       offset: 0.2
 *     }
 *   }
 * }
 */

function offsetSlice(centroid, offset, outerRadius, innerRadius) {
  var _centroid = picasso_esm_slicedToArray(centroid, 2),
      vx = _centroid[0],
      vy = _centroid[1];

  var vlen = Math.sqrt(vx * vx + vy * vy);
  vx /= vlen;
  vy /= vlen;
  var diff = outerRadius - innerRadius;
  return {
    x: vx * offset * diff,
    y: vy * offset * diff
  };
}

function createDisplayPies(arcData, _ref, slices, sum) {
  var x = _ref.x,
      y = _ref.y,
      width = _ref.width,
      height = _ref.height;
  var arcGen = arc();
  var center = {
    x: x + width / 2,
    y: y + height / 2
  };
  var innerRadius = Math.min(width, height) / 2;
  var outerRadius = Math.min(width, height) / 2;
  var cornerRadius = outerRadius / 100;
  return arcData.map(function (a, i) {
    var slice = slices[i];
    slice.type = 'path';
    var or = outerRadius * slice.outerRadius;
    var ir = innerRadius * slice.innerRadius;
    arcGen.innerRadius(ir);
    arcGen.outerRadius(or);
    arcGen.cornerRadius(cornerRadius * slice.cornerRadius);
    slice.d = arcGen(a);
    var centroid = arcGen.centroid(a);
    var offset = slice.offset ? offsetSlice(centroid, slice.offset, or, ir) : {
      x: 0,
      y: 0
    };
    slice.transform = "translate(".concat(offset.x, ", ").concat(offset.y, ") translate(").concat(center.x, ", ").concat(center.y, ")");
    slice.desc = {
      share: a.value / sum,
      slice: {
        start: a.startAngle,
        end: a.endAngle,
        innerRadius: ir,
        outerRadius: or,
        offset: {
          x: center.x + offset.x,
          y: center.y + offset.y
        }
      }
    };
    return slice;
  });
}

function arcValue(stngs, item) {
  if (stngs.slice && 'arc' in stngs.slice) {
    return item.arc;
  }

  return item.data.value;
}
var pieComponent = {
  require: ['chart', 'resolver'],
  defaultSettings: {
    settings: {
      startAngle: 0,
      endAngle: 2 * Math.PI,
      padAngle: 0,
      slice: {}
    },
    style: {
      slice: '$shape'
    },
    data: {}
  },
  render: function render(_ref2) {
    var data = _ref2.data;
    var arcValues = [];
    var slices = [];
    var stngs = this.settings.settings;

    var _this$resolver$resolv = this.resolver.resolve({
      data: data,
      defaults: extend({}, DEFAULT_DATA_SETTINGS$2.slice, this.style.slice),
      settings: stngs.slice
    }),
        items = _this$resolver$resolv.items;

    var sum = 0;

    for (var i = 0, len = items.length; i < len; i++) {
      var val = arcValue(stngs, items[i]);

      if (val > 0 && items[i].outerRadius >= items[i].innerRadius) {
        arcValues.push(val);
        slices.push(items[i]);
        sum += val;
      }
    }

    var pieGen = picasso_esm_pie().sortValues(null);
    pieGen.startAngle(stngs.startAngle);
    pieGen.endAngle(stngs.endAngle);
    pieGen.padAngle(stngs.padAngle);
    var arcData = pieGen(arcValues);
    return createDisplayPies(arcData, extend({}, this.rect, {
      x: 0,
      y: 0
    }), slices, sum);
  }
};

function pie$1(picasso) {
  picasso.component('pie', pieComponent);
}

/**
 * Create a crispifier
 * @ignore
 *
 * @param  {Object} [crispMap] Optional crispmap if you need custom crisping.
 * @return {Function}          crispItem function
 *
 * @example
 * import { crispifierFactory } from "core/crispifier";
 *
 * let crispify = crispifierFactory(customCrispMap);
 *
 * // For a single item
 * crispify(myItem);
 *
 * // For multiple items
 * crispify.multiple(myArrayOfItems);
 */
function crispifierFactory(crispMap) {
  // Define the crispMap
  if (crispMap === undefined) {
    crispMap = {};
    crispMap.line = {
      append: ['x1', 'x2', 'y1', 'y2'],
      round: [],
      condition: function condition(item) {
        return item.x1 === item.x2 || item.y1 === item.y2;
      },
      conditionAppend: function conditionAppend(item) {
        return item.strokeWidth % 2 !== 0;
      }
    };
    crispMap.rect = {
      append: ['x', 'y'],
      round: ['width', 'height'],
      condition: function condition() {
        return true;
      },
      conditionAppend: function conditionAppend(item) {
        return item.strokeWidth % 2 !== 0;
      }
    };
  } // Re-map the crispmap


  Object.keys(crispMap).forEach(function (type) {
    var self = crispMap[type];
    self.items = [];
    self.append.forEach(function (toAppend) {
      self.items.push({
        key: toAppend,
        type: 'append'
      });
    });
    self.round.forEach(function (toAppend) {
      self.items.push({
        key: toAppend,
        type: 'round'
      });
    });
  });
  /**
   * Crispify a single item
   * @ignore
   * @param  {Object} item  Item with renderer variables such as X, Y, and type.
   * @return {Undefined}    Returns nothing, modifies the original item instead
   */

  function crispItem(item) {
    if (crispMap[item.type] && crispMap[item.type].condition(item)) {
      var self = crispMap[item.type];
      var doAppend = self.conditionAppend === undefined || self.conditionAppend(item);
      self.items.forEach(function (i) {
        var rounded = Math.round(item[i.key]);
        var diff = item[i.key] - rounded;
        item[i.key] = rounded;

        if (doAppend && i.type === 'append') {
          if (diff > 0) {
            item[i.key] += 0.5;
          } else {
            item[i.key] -= 0.5;
          }
        }
      });
    }
  }
  /**
   * Crispify multiple items
   * @ignore
   *
   * @param  {Array} items  Array of objects to crispify
   * @return {Undefined}    Returns nothing, modifies the original item instead
   */


  crispItem.multiple = function (items) {
    return items.forEach(function (item) {
      return crispItem(item);
    });
  };

  return crispItem;
}
var crispifier = crispifierFactory();

var Transposer =
/*#__PURE__*/
function () {
  /**
   * @private
   */
  function Transposer() {
    _classCallCheck$1(this, Transposer);

    this.reset();
    this.push.apply(this, arguments);
  }
  /**
   * Evaluate a key for a transposed coordinate
   *
   * @param  {String} key   Key
   * @return {String}         Actual key
   */


  _createClass$1(Transposer, [{
    key: "transposeCoordinate",

    /**
     * Transpose a coordinate according to this.flipXY and
     * the available rendering area
     *
     * @param  {String} key        The key of the coordinate to transpose
     * @param  {Number} coordinate The coordinate
     * @return {Number}            The actual location of the coordinate
     */
    value: function transposeCoordinate(key, coordinate, flipXY) {
      if (typeof coordinate === 'number' && isFinite(coordinate)) {
        var firstChar = key.substring(0, 1);

        if (firstChar === 'x' || key === 'cx') {
          return coordinate * this.width;
        }

        if (key === 'width') {
          return coordinate * this.width;
        }

        if (key === 'r') {
          return coordinate * (!flipXY ? this.width : this.height);
        }

        if (firstChar === 'y' || key === 'cy') {
          return coordinate * this.height;
        }

        if (key === 'height') {
          return coordinate * this.height;
        }
      }

      return coordinate;
    }
    /**
     * Push an item into the storage of the transposer
     *
     * @param  {Object} items An item to be drawed
     * @return {Object}       Can be chained
     */

  }, {
    key: "push",
    value: function push() {
      var _this$storage;

      (_this$storage = this.storage).push.apply(_this$storage, arguments);

      return this;
    }
  }, {
    key: "processItem",
    value: function processItem(item) {
      var newItem = {};
      var flipXY = typeof item.flipXY !== 'undefined' ? item.flipXY : this.flipXY;
      var crisp = typeof item.crisp !== 'undefined' ? item.crisp : this.crisp;

      if (item.fn && typeof item.fn === 'function') {
        var width = flipXY ? this.height : this.width;
        var height = flipXY ? this.width : this.height;
        item = item.fn({
          width: width,
          height: height,
          flipXY: flipXY
        });
        var objectKeys = Object.keys(item);

        for (var ki = 0, kl = objectKeys.length; ki < kl; ki++) {
          var key = objectKeys[ki];
          var nkey = Transposer.evaluateKey(key, flipXY);
          newItem[nkey] = item[key];
        }
      } else {
        var _objectKeys = Object.keys(item);

        for (var _ki = 0, _kl = _objectKeys.length; _ki < _kl; _ki++) {
          var _key = _objectKeys[_ki];

          var _nkey = Transposer.evaluateKey(_key, flipXY);

          var nval = this.transposeCoordinate(_nkey, item[_key], flipXY);
          newItem[_nkey] = nval;
        }
      }

      if (crisp) {
        crispifier(newItem);
      }

      return newItem;
    }
    /**
     * Get the output of the transposer
     *
     * @return {Array}   Array of objects
     */

  }, {
    key: "output",
    value: function output() {
      var items = [];

      for (var i = 0, l = this.storage.length; i < l; i++) {
        var newItem = this.processItem(this.storage[i]);
        items.push(newItem);
      }

      return items;
    }
    /**
     * Reset the transposer
     *
     * @return {Undefined}  Does not return anything
     */

  }, {
    key: "reset",
    value: function reset() {
      this.storage = [];
      this.flipXY = false;
      this.crisp = false;
      this.width = 0;
      this.height = 0;
    }
  }], [{
    key: "evaluateKey",
    value: function evaluateKey(key, flipXY) {
      if (flipXY) {
        var firstChar = key.substring(0, 1);
        var rest = key.substring(1);

        if (firstChar === 'x') {
          return "y".concat(rest);
        }

        if (firstChar === 'y') {
          return "x".concat(rest);
        }

        if (key === 'cx') {
          return 'cy';
        }

        if (key === 'cy') {
          return 'cx';
        }

        if (key === 'width') {
          return 'height';
        }

        if (key === 'height') {
          return 'width';
        }
      }

      return key;
    }
  }]);

  return Transposer;
}();

function transposer() {
  for (var _len = arguments.length, items = new Array(_len), _key2 = 0; _key2 < _len; _key2++) {
    items[_key2] = arguments[_key2];
  }

  return _construct(Transposer, items);
}

/**
 * Generate array of lines (ticks) from scale
 *
 * @param {object} scale - A scale supplied by the chart
 * @param {object} settings - The settings object from the grid line component
 * @param {object} rect - The rect containing width and height to renderer in
 * @returns {array} - Returns an array of ticks
 * @ignore
 */

function lineGen(scale, distance) {
  if (!scale || !distance) {
    return [];
  }

  return scale.cachedTicks && scale.cachedTicks() || scale.ticks({
    distance: distance
  });
}

var gridLineComponent = {
  created: function created() {},
  require: ['chart', 'renderer', 'resolver'],
  defaultSettings: {
    layout: {
      displayOrder: 0
    },
    style: {
      // Theming style
      ticks: '$guide-line',
      minorTicks: '$guide-line--minor'
    }
  },
  beforeRender: function beforeRender() {
    this.blueprint = transposer();
    this.blueprint.width = this.rect.width;
    this.blueprint.height = this.rect.height;
    this.blueprint.x = this.rect.x;
    this.blueprint.y = this.rect.y;
    this.blueprint.crisp = true;
  },
  render: function render() {
    var _this = this;

    // Setup scales
    this.x = this.settings.x ? this.chart.scale(this.settings.x) : null;
    this.y = this.settings.y ? this.chart.scale(this.settings.y) : null;
    updateScaleSize(this, 'x', this.rect.width);
    updateScaleSize(this, 'y', this.rect.height); // Return an empty array to abort rendering when no scales are available to renderer

    if (!this.x && !this.y) {
      return [];
    }

    this.settings.ticks = extend({
      show: true
    }, this.style.ticks, this.settings.ticks || {});
    this.settings.minorTicks = extend({
      show: false
    }, this.style.minorTicks, this.settings.minorTicks || {}); // Setup lines for X and Y

    this.lines = {
      x: [],
      y: []
    }; // Use the lineGen function to generate appropriate ticks

    this.lines.x = lineGen(this.x, this.rect.width);
    this.lines.y = lineGen(this.y, this.rect.height); // Set all Y lines to flipXY by default
    // This makes the transposer flip them individually

    this.lines.y = this.lines.y.map(function (i) {
      return extend(i, {
        flipXY: true
      });
    });

    var addTicks = function addTicks(_ref) {
      var dir = _ref.dir,
          isMinor = _ref.isMinor;

      var items = _this.lines[dir].filter(function (tick) {
        return !!tick.isMinor === isMinor;
      });

      var settings = isMinor ? _this.settings.minorTicks : _this.settings.ticks;

      var ticks = _this.resolver.resolve({
        settings: settings,
        data: {
          items: items,
          dir: dir
        }
      }).items;

      ticks.forEach(function (style) {
        var p = style.data; // If the style's show is falsy, don't renderer this item (to respect axis settings).

        if (style.show) {
          // Use the transposer to handle actual positioning
          _this.blueprint.push({
            type: 'line',
            x1: p.position,
            y1: 0,
            x2: p.position,
            y2: 1,
            stroke: style.stroke || 'black',
            strokeWidth: typeof style.strokeWidth !== 'undefined' ? style.strokeWidth : 1,
            strokeDasharray: typeof style.strokeDasharray !== 'undefined' ? style.strokeDasharray : undefined,
            flipXY: p.flipXY || false // This flips individual points (Y-lines)

          });
        }
      });
    };

    addTicks({
      dir: 'x',
      isMinor: false
    });
    addTicks({
      dir: 'x',
      isMinor: true
    });
    addTicks({
      dir: 'y',
      isMinor: false
    });
    addTicks({
      dir: 'y',
      isMinor: true
    });
    return this.blueprint.output();
  }
};

/**
 * @typedef {object} component--grid-line-settings
 * @property {object} x
 * @property {string} x.scale - The scale to use along x
 * @property {object} y
 * @property {string} y.scale - The scale to use along y
 * @property {object} [ticks]
 * @property {boolean} [ticks.show=true]
 * @property {string} [ticks.stroke='black']
 * @property {number} [ticks.strokeWidth='1']
 * @property {string} [ticks.strokeDasharray]
 * @property {object} [minorTicks]
 * @property {boolean} [minorTicks.show=true]
 * @property {string} [minorTicks.stroke='black']
 * @property {number} [minorTicks.strokeWidth='1']
 * @property {string} [minorTicks.strokeDasharray]
 */

function gridLine(picasso) {
  picasso.component('grid-line', gridLineComponent);
}

/**
 * Return a D property for a SVG path to get a direction marker
 *
 * @param {number} x - X coordinate
 * @param {number} y - Y coordinate
 * @param {number} r - Radius
 * @param {string} [d='bottom'] - Direction
 * @returns {string} - Finished D property
 * @ignore
 */
function directionMarker(x, y, r) {
  var d = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'bottom';
  r *= 0.8;

  if (d === 'left' || d === 'right') {
    var right = d === 'right';
    return "\n      M ".concat(x, " ").concat(y - r, "\n      A ").concat(r * 1.25, " ").concat(r * 1.25, ", 0, 1, ").concat(right ? 0 : 1, ", ").concat(x, " ").concat(y + r, "\n      L ").concat(right ? x + r : x - r, " ").concat(y, " Z\n    ");
  }

  var bottom = d === 'bottom';
  return "\n    M ".concat(x - r, " ").concat(y, "\n    A ").concat(r * 1.25, " ").concat(r * 1.25, ", 0, 1, ").concat(bottom ? 1 : 0, ", ").concat(x + r, " ").concat(y, "\n    L ").concat(x, " ").concat(bottom ? y + r : y - r, " Z\n  ");
}

function directionTriangle(x, y, r) {
  var d = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'bottom';
  r *= 0.75;

  if (d === 'left' || d === 'right') {
    var right = d === 'right';
    x += right ? r * 1.5 : -(r * 1.5);
    return "\n      M ".concat(x, " ").concat(y - r, "\n      L ").concat(x, " ").concat(y + r, "\n      L ").concat(right ? x + r : x - r, " ").concat(y, " Z\n    ");
  }

  var bottom = d === 'bottom';
  y += bottom ? r * 1.5 : -(r * 1.5);
  return "\n    M ".concat(x - r, " ").concat(y, "\n    L ").concat(x + r, " ").concat(y, "\n    L ").concat(x, " ").concat(bottom ? y + r : y - r, " Z\n  ");
}
/**
 * Handle out of bound shapes
 * Does not return anything, modifies "items" property instead (should be re-considered)
 *
 * @param {object} oob - Out of bounds object from parent
 * @param {object} settings - Settings object from parent
 * @param {object[]} items - Array of all items (for collision detection)
 * @ignore
 */


function oobManager(_ref) {
  var blueprint = _ref.blueprint,
      oob = _ref.oob,
      settings = _ref.settings,
      items = _ref.items;
  var oobKeys = Object.keys(oob);
  var style = settings.style.oob || {};

  var _loop = function _loop(i, len) {
    var key = oobKeys[i];
    var value = oob[key];

    if (value.length > 0) {
      var position = key.charAt(1);
      var flipXY = key.charAt(0) === 'y';
      var xPadding = style.padding.x + style.width;
      var yPadding = style.padding.y + style.width;
      var direction = 'bottom';

      if (flipXY) {
        direction = position === '1' ? 'bottom' : 'top';
      } else {
        direction = position === '1' ? 'right' : 'left';
      }

      var indicator = blueprint.processItem({
        fn: function fn(_ref2) {
          var width = _ref2.width,
              height = _ref2.height;

          /* eslint no-loop-func: 0 */
          var x = position * width + (position === '1' ? -xPadding : xPadding);
          var y = flipXY ? yPadding : height - yPadding;

          if (style.type === 'arc') {
            return {
              type: 'path',
              d: directionMarker(flipXY ? y : x, flipXY ? x : y, style.width, direction),
              x: x,
              y: y,
              stroke: style.stroke,
              fill: style.fill,
              strokeWidth: style.strokeWidth || 0
            };
          }

          return {
            type: 'circle',
            cx: x,
            cy: y,
            r: style.width,
            stroke: style.stroke,
            fill: style.fill,
            strokeWidth: style.strokeWidth || 0,
            opacity: style.opacity,
            data: value
          };
        },
        flipXY: flipXY
      });
      var x = indicator.cx || indicator.x;
      var y = indicator.cy || indicator.y;
      var text = {
        type: 'text',
        text: value.length || '',
        x: x - style.width * 0.4,
        y: y + style.width * 0.4,
        fontFamily: style.text.fontFamily,
        fontSize: "".concat(style.width * 1.3, "px"),
        stroke: style.text.stroke,
        fill: style.text.fill,
        strokeWidth: style.text.strokeWidth || 0,
        opacity: style.text.opacity
      };
      var triangle = {
        type: 'path',
        d: directionTriangle(x, y, style.width, direction),
        x: x,
        y: y,
        stroke: style.triangle.stroke,
        fill: style.triangle.fill,
        strokeWidth: style.triangle.strokeWidth || 0,
        opacity: style.triangle.opacity
      };
      items.push(indicator, text, triangle);
    }
  };

  for (var i = 0, len = oobKeys.length; i < len; i++) {
    _loop(i);
  }
}

function refLabelDefaultSettings() {
  return {
    fill: '#000',
    fontFamily: 'Arial',
    fontSize: '12px',
    opacity: 1,
    maxWidth: 1,
    maxWidthPx: 9999,
    padding: 5,
    background: {
      fill: '#fff',
      stroke: 'transparent',
      strokeWidth: 0,
      opacity: 0.5
    }
  };
}
/**
 * Converts a numerical OR string value to a normalized value
 *
 * @param {string|number} align -Description how to align (Numerical from 0-1 or 'top', 'left', 'center', 'middle', 'bottom' or 'right')
 * @returns {number} - Normalized value 0...1
 * @ignore
 */

function alignmentToNumber(align) {
  if (typeof align === 'undefined') {
    return 0;
  }

  if (typeof align === 'number' && isFinite(align)) {
    return align;
  }

  if (typeof align === 'string') {
    switch (align) {
      case 'center':
      case 'middle':
        return 0.5;

      case 'bottom':
      case 'right':
        return 1;

      case 'top':
      case 'left':
      default:
        return 0;
    }
  }

  return 0;
}
/**
 * Create line and label (if applicable)
 * Does not return anything, modifies "items" property instead (should be re-considered)
 *
 * @param {object} p - Current point
 * @param {object} style - Applicable line styling
 * @param {object} settings - Settings object derived from parent
 * @param {object[]} items - Array of all items (for collision detection)
 * @ignore
 */

function createLineWithLabel(_ref) {
  var chart = _ref.chart,
      blueprint = _ref.blueprint,
      renderer = _ref.renderer,
      p = _ref.p,
      settings = _ref.settings,
      items = _ref.items;
  var doesNotCollide = true;
  var line = false;
  var rect = false;
  var label = false;
  var value = false;
  var style = extend(true, {}, settings.style.line, p.line || {}); // Use the transposer to handle actual positioning

  line = blueprint.processItem({
    type: 'line',
    x1: p.position,
    y1: 0,
    x2: p.position,
    y2: 1,
    stroke: style.stroke || 'black',
    strokeWidth: style.strokeWidth || 1,
    flipXY: p.flipXY || false // This flips individual points (Y-lines)

  });

  if (p.label) {
    var item = extend(true, refLabelDefaultSettings(), settings.style.label || {}, {
      fill: style.stroke
    }, p.label);
    var formatter;
    var measuredValue = {
      width: 0,
      height: 0
    };
    var valueString = '';

    if (typeof p.formatter === 'string') {
      formatter = chart.formatter(p.formatter);
    } else if (_typeof(p.formatter) === 'object') {
      formatter = chart.formatter(p.formatter);
    } else if (typeof p.scale !== 'undefined' && p.scale.data) {
      // TODO - Add support for array as source into formatter
      var scaleData = p.scale.data() && p.scale.data().fields;
      formatter = scaleData && scaleData[0] ? scaleData[0].formatter() : null;
    }

    if (formatter) {
      valueString = " (".concat(formatter(p.value), ")");
    } else if (p.scale) {
      valueString = " (".concat(p.value, ")");
    }

    if (valueString) {
      measuredValue = renderer.measureText({
        text: valueString,
        fontFamily: item.fontFamily,
        fontSize: item.fontSize
      });
    } // Measure the label text


    var measuredLabel = renderer.measureText({
      text: item.text || '',
      fontFamily: item.fontFamily,
      fontSize: item.fontSize
    });
    var measured = {
      width: measuredLabel.width + measuredValue.width,
      height: Math.max(measuredLabel.height, measuredValue.height)
    };
    var labelPadding = item.padding; // let anchor = item.anchor === 'end' ? 'end' : 'start';

    var align = alignmentToNumber(p.flipXY ? item.vAlign : item.align);
    var vAlign = alignmentToNumber(p.flipXY ? item.align : item.vAlign);
    var calcWidth = Math.min(1 + measured.width + labelPadding * 2, item.maxWidth * blueprint.width, item.maxWidthPx);
    var calcHeight = measured.height + labelPadding * 2;
    var rectWidth = p.flipXY ? calcHeight : calcWidth;
    var rectHeight = p.flipXY ? calcWidth : calcHeight;
    rect = blueprint.processItem({
      fn: function fn(_ref2) {
        var width = _ref2.width,
            height = _ref2.height;
        var x = p.position * width - (p.flipXY ? calcHeight : calcWidth) * (1 - align);
        x = p.flipXY ? x : Math.max(x, 0);
        var y = Math.max(Math.abs(vAlign * height - rectHeight * vAlign), 0);
        return {
          type: 'rect',
          x: x,
          y: y,
          width: p.flipXY ? rectWidth : Math.min(rectWidth, blueprint.width - x),
          height: rectHeight,
          stroke: item.background.stroke,
          strokeWidth: item.background.strokeWidth,
          fill: item.background.fill,
          opacity: item.background.opacity
        };
      },
      flipXY: p.flipXY || false // This flips individual points (Y-lines)

    });

    if (rect.x < -1 || rect.x + rect.width > blueprint.width + 1 || rect.y < -1 || rect.y + rect.height > blueprint.height + 1) {
      // do not create labels if out of bounds
      rect = undefined;
    } else {
      // Labels are just basic objects attached to a corner of a rect,
      // and this rect needs to already be processed
      // so there is no blueprint.processItem required here
      label = {
        type: 'text',
        text: item.text || '',
        fill: item.fill,
        opacity: item.opacity,
        fontFamily: item.fontFamily,
        fontSize: item.fontSize,
        x: rect.x + labelPadding,
        y: rect.y + rect.height / 2 + measured.height / 3,
        maxWidth: rect.width - labelPadding * 2 - measuredValue.width,
        anchor: 'start'
      };

      if (valueString) {
        value = {
          type: 'text',
          text: valueString || '',
          fill: item.fill,
          opacity: item.opacity,
          fontFamily: item.fontFamily,
          fontSize: item.fontSize,
          x: label.x + 3 + (rect.width - (measuredValue.width + labelPadding * 2)),
          y: label.y
        };
      } // Detect collisions with other labels/rects or lines


      for (var i = 0, len = items.length; i < len; i++) {
        var curItem = items[i];

        if (curItem.type === 'rect') {
          // We only detect rects here, since rects are always behind labels,
          // and we wouldn't want to measure text one more time
          if (testRectRect(rect, curItem)) {
            doesNotCollide = false;
          }
        } else if (curItem.type === 'line') {
          // This will only collide when flipXY are the same for both objects,
          // So it only collides on objects on the same "axis"
          if (p.flipXY === curItem.flipXY && testRectLine(rect, curItem)) {
            doesNotCollide = false;
          }
        }
      }
    }
  } // Always push the line,
  // but this is done after collision detection,
  // because otherwise it would collide with it's own line


  items.push(line); // Only push rect & label if we haven't collided and both are defined

  if (doesNotCollide && rect && label) {
    items.push(rect, label);

    if (value) {
      items.push(value);
    }
  }
}

function createOobData(line) {
  var data = {
    value: line.value
  };

  if (line.label) {
    data.label = line.label.text;
  }

  return data;
}

function filterUndefinedValue(line) {
  return typeof line.value !== 'undefined';
}
/**
 * @typedef {object} component--ref-line
 * @experimental
 * @property {refline-generic-style} [style=refline-generic-style] - x coordinate
 * @property {object} lines - X & Y Lines
 * @property {reflines-x[]} [lines.x=refline-line[]] - lines along X
 * @property {reflines-y[]} [lines.y=refline-line[]] - lines along Y
 */

/**
 * @typedef {object} component--ref-line.style
 * @property {refline-oob-style} [oob=component--ref-line.style.oob] - Style for out of bounds object (oob)
 * @property {refline-line} [line=refline-line] - Generic style for lines
 * @property {refline-line-label} [label=refline-line-label] - Generic style for labels
 */

/**
 * @typedef {object} component--ref-line.style.oob
 * @property {boolean} [show=true] - Show out of bounds items
 * @property {string} [type=undefined] - EXPERIMENTAL:  Set this to 'arc' for an experimental out of bounds shape (only works with SVG)
 * @property {number} [width=10] - Width of the out of bounds object
 * @property {string} [fill='#1A1A1A'] - Fill color of the OOB object
 * @property {string} [stroke='transparent'] - Stroke of the OOB object
 * @property {number} [strokeWidth=0] - Stroke width of the OOB object
 * @property {number} [opacity=1] - Opacity of the OOB object
 * @property {refline-generic-text} [text=refline-generic-text] - Text configuration for out of bounds
 * @property {refline-generic-object} [triangle=refline-generic-object] - The triangle in OOB
 * @property {object} [padding] - Padding on X
 * @property {number} [padding.x=28] - Padding on X
 * @property {number} [padding.y=5] - Padding on X
 */

/**
 * @typedef {object} component--ref-line.generic-text
 * @property {string} [text=''] - Text (if applicable)
 * @property {string} [fontSize='12px'] - Font size (if applicable)
 * @property {string} [fontFamily='Arial'] - Font family
 * @property {string} [fill='#fff'] - Fill color
 * @property {string} [stroke='transparent'] - Stroke
 * @property {number} [strokeWidth=0] - Stroke width
 * @property {number} [opacity=1] - Opacity
 */

/**
 * @typedef {object} component--ref-line.line
 * @property {number} value - The value of the reference line. If a scale is specified, it is applied.
 * @property {Scale} [scale=undefined] - Scale to use (if undefined will use normalized value 0-1)
 * @property {refline-generic-object} [line=refline-generic-object] - The style of the line
 * @property {refline-line-label} [label=refline-line-label] - The label style of the line
 */

/**
 * @typedef {object} component--ref-line.line-label
 * @property {number} padding=5 - Padding inside the label
 * @property {string} [text=''] - Text
 * @property {string} [fontSize='12px'] - Font size
 * @property {string} [fontFamily='Arial'] - Font family
 * @property {string} [stroke='transparent'] - Stroke
 * @property {number} [strokeWidth=0] - Stroke width
 * @property {number} [opacity=1] - Opacity
 * @property {number|string} [align=0] - Alignment property left to right (0 = left, 1 = right). Also supports string ('left', 'center', 'middle', 'right')
 * @property {number|string} [vAlign=0] - Alignment property top to bottom (0 = top, 1 = bottom). Also supports string ('top', 'center', 'middle', 'bottom')
 * @property {number} [maxWidth=1] - The maximum relative width to the width of the rendering area (see maxWidthPx below aswell)
 * @property {number} [maxWidthPx=9999] - The maximum width in pixels.
 * @property {refline-line-label-background} [background=refline-line-label-background] - The background style (rect behind text)
 */

/**
 * @example
 * // Labels will be rendered with the maximum size of the smallest value of maxWidth and maxWidthPx size, so you may specify maxWidth 0.8 but maxWidthPx 100 and will never be over 100px and never over 80% of the renderable area.
 */

/**
 * @typedef {object} component--ref-line.line-label-background
 * @property {string} [fill='#fff'] - Fill color
 * @property {string} [stroke='transparent'] - Stroke
 * @property {number} [strokeWidth=0] - Stroke width
 * @property {number} [opacity=0.5] - Opacity
 */

/**
 * @typedef {object} component--ref-line.generic-object
 * @property {string} [fill='#fff'] - Fill color
 * @property {string} [stroke='transparent'] - Stroke
 * @property {number} [strokeWidth=0] - Stroke width
 * @property {number} [opacity=1] - Opacity
 */


var refLineComponent = {
  require: ['chart', 'renderer'],
  defaultSettings: {
    layout: {
      displayOrder: 0
    },
    style: {
      oob: {
        show: true,
        width: 10,
        fill: '#1A1A1A',
        stroke: 'transparent',
        strokeWidth: 0,
        opacity: 1,
        text: {
          fontFamily: 'Arial',
          stroke: 'transparent',
          fill: '#fff',
          strokeWidth: 0,
          opacity: 1
        },
        triangle: {
          fill: '#4D4D4D',
          stroke: 'transparent',
          strokeWidth: 0,
          opacity: 1
        },
        padding: {
          x: 28,
          y: 5
        }
      },
      line: {
        stroke: '#000'
      },
      label: {
        strokeWidth: 0
      }
    }
  },
  preferredSize: function preferredSize() {
    return 30;
  },
  beforeRender: function beforeRender() {
    this.blueprint = transposer();
    this.blueprint.width = this.rect.width;
    this.blueprint.height = this.rect.height;
    this.blueprint.x = this.rect.x;
    this.blueprint.y = this.rect.y;
    this.blueprint.crisp = true;
  },
  render: function render() {
    var _this = this;

    var settings = this.settings; // Setup lines for X and Y

    this.lines = {
      x: [],
      y: []
    };
    this.lines.x = settings.lines && settings.lines.x || [];
    this.lines.y = settings.lines && settings.lines.y || [];

    if (this.lines.x.length === 0 && this.lines.y.length === 0) {
      return [];
    }

    var oob = {
      x0: [],
      x1: [],
      y0: [],
      y1: []
    }; // Convert a value to an actual position using the scale

    this.lines.x = this.lines.x.filter(filterUndefinedValue).map(function (line) {
      if (line.scale) {
        var scale = _this.chart.scale(line.scale);

        return extend(line, {
          scale: scale,
          position: scale(line.value)
        });
      }

      return extend(line, {
        position: line.value
      });
    }); // Set all Y lines to flipXY by default
    // This makes the transposer flip them individually

    this.lines.y = this.lines.y.filter(filterUndefinedValue).map(function (line) {
      if (line.scale) {
        var scale = _this.chart.scale(line.scale);

        return extend(line, {
          scale: scale,
          position: scale(line.value),
          flipXY: true
        });
      }

      return extend(line, {
        position: line.value,
        flipXY: true
      });
    }); // Move out of bounds lines (OOB) to separate rendering

    this.lines.x = this.lines.x.filter(function (line) {
      if (line.position < 0 || line.position > 1) {
        oob["x".concat(line.position > 1 ? 1 : 0)].push(createOobData(line));
        return false;
      }

      return true;
    });
    this.lines.y = this.lines.y.filter(function (line) {
      if (line.position < 0 || line.position > 1) {
        oob["y".concat(line.position > 1 ? 1 : 0)].push(createOobData(line));
        return false;
      }

      return true;
    });
    var items = []; // Loop through all X and Y lines

    [].concat(_toConsumableArray$1(this.lines.x), _toConsumableArray$1(this.lines.y)).forEach(function (p) {
      var show = p.show === true || typeof p.show === 'undefined';

      if (show) {
        // Create line with labels
        createLineWithLabel({
          chart: _this.chart,
          blueprint: _this.blueprint,
          renderer: _this.renderer,
          p: p,
          settings: settings,
          items: items
        });
      }
    }); // Handle out of bounds

    if (settings.style.oob.show) {
      oobManager({
        blueprint: this.blueprint,
        oob: oob,
        settings: settings,
        items: items
      });
    }

    return items;
  }
};

function refLine(picasso) {
  picasso.component('ref-line', refLineComponent);
}

function appendStyle(struct, buildOpts) {
  extend(struct, buildOpts.style);
  var halfWidth = struct.strokeWidth / 2;

  if (buildOpts.align === 'top') {
    struct.y1 -= halfWidth;
    struct.y2 -= halfWidth;
  } else if (buildOpts.align === 'bottom') {
    struct.y1 += halfWidth;
    struct.y2 += halfWidth;
  } else if (buildOpts.align === 'left') {
    struct.x1 -= halfWidth;
    struct.x2 -= halfWidth;
  } else if (buildOpts.align === 'right') {
    struct.x1 += halfWidth;
    struct.x2 += halfWidth;
  }
}

function buildLine(buildOpts) {
  var struct = {
    type: 'line',
    x1: 0,
    x2: 0,
    y1: 0,
    y2: 0,
    collider: {
      type: null
    }
  };

  if (buildOpts.align === 'top' || buildOpts.align === 'bottom') {
    struct.x1 = buildOpts.innerRect.x - buildOpts.outerRect.x;
    struct.x2 = buildOpts.innerRect.width + buildOpts.innerRect.x;
    struct.y1 = struct.y2 = buildOpts.align === 'top' ? buildOpts.innerRect.height - buildOpts.padding : buildOpts.padding;
  } else {
    struct.x1 = struct.x2 = buildOpts.align === 'left' ? buildOpts.innerRect.width - buildOpts.padding : buildOpts.padding;
    struct.y1 = buildOpts.innerRect.y - buildOpts.outerRect.y;
    struct.y2 = buildOpts.innerRect.height + buildOpts.innerRect.y;
  }

  appendStyle(struct, buildOpts);
  return struct;
}

function checkText(text) {
  return typeof text === 'string' || typeof text === 'number' ? text : '-';
}

function appendStyle$1(struct, buildOpts) {
  ['fill', 'fontSize', 'fontFamily'].forEach(function (style) {
    struct[style] = buildOpts.style[style];
  });
}

function clampEnds(struct, buildOpts) {
  if (buildOpts.tilted || buildOpts.stepSize) {
    return;
  }

  if (buildOpts.align === 'top' || buildOpts.align === 'bottom') {
    var leftBoundary = 0;
    var rightBoundary = buildOpts.outerRect.width;
    var textWidth = Math.min(buildOpts.maxWidth / 2, buildOpts.textRect.width / 2);
    var leftTextBoundary = struct.x - textWidth;
    var rightTextBoundary = struct.x + textWidth;

    if (leftTextBoundary < leftBoundary) {
      struct.anchor = 'start';
      struct.x = buildOpts.innerRect.x - buildOpts.outerRect.x;
    } else if (rightTextBoundary > rightBoundary) {
      struct.anchor = 'end';
      struct.x = buildOpts.innerRect.width + buildOpts.innerRect.x;
    }
  } else {
    var topBoundary = 0;
    var bottomBoundary = buildOpts.outerRect.height;
    var textHeight = buildOpts.maxHeight / 2;
    var topTextBoundary = struct.y - textHeight;
    var bottomTextBoundary = struct.y + textHeight;

    if (topTextBoundary < topBoundary) {
      struct.y = buildOpts.innerRect.y - buildOpts.outerRect.y;
      struct.baseline = 'text-before-edge';
    } else if (bottomTextBoundary > bottomBoundary) {
      struct.y = buildOpts.innerRect.height + (buildOpts.innerRect.y - buildOpts.outerRect.y);
      struct.baseline = 'text-after-edge';
    }
  }
}

function appendPadding(struct, buildOpts) {
  if (buildOpts.align === 'top') {
    struct.y -= buildOpts.padding;
  } else if (buildOpts.align === 'bottom') {
    struct.y += buildOpts.padding + buildOpts.maxHeight;
  } else if (buildOpts.align === 'left') {
    struct.x -= buildOpts.padding;
  } else if (buildOpts.align === 'right') {
    struct.x += buildOpts.padding;
  }
}

function appendTilting(struct, buildOpts) {
  if (buildOpts.tilted) {
    var r = -buildOpts.angle;
    var radians = r * (Math.PI / 180);

    if (buildOpts.align === 'bottom') {
      struct.x -= buildOpts.maxHeight * Math.sin(radians) / 2;
      struct.y -= buildOpts.maxHeight;
      struct.y += buildOpts.maxHeight * Math.cos(radians) / 2;
    } else {
      struct.x -= buildOpts.maxHeight * Math.sin(radians) / 3;
    }

    struct.transform = "rotate(".concat(r, ", ").concat(struct.x, ", ").concat(struct.y, ")");
    struct.anchor = buildOpts.align === 'bottom' === buildOpts.angle < 0 ? 'start' : 'end'; // adjustForEnds

    var textWidth = Math.cos(radians) * buildOpts.maxWidth;

    if (buildOpts.align === 'bottom' === buildOpts.angle < 0) {
      // right
      var rightBoundary = buildOpts.outerRect.width - buildOpts.paddingEnd;
      var rightTextBoundary = struct.x + textWidth;

      if (rightTextBoundary > rightBoundary) {
        struct.maxWidth = (rightBoundary - struct.x - 10) / Math.cos(radians);
      }
    } else {
      // left
      var leftBoundary = buildOpts.paddingEnd;
      var leftTextBoundary = struct.x - textWidth;

      if (leftTextBoundary < leftBoundary) {
        struct.maxWidth = (struct.x - leftBoundary - 10) / Math.cos(radians);
      }
    }
  }
}

function bandwidthCollider(tick, struct, buildOpts) {
  if (buildOpts.align === 'bottom' || buildOpts.align === 'top') {
    var tickCenter = tick.position * buildOpts.innerRect.width;
    var leftBoundary = tickCenter + (buildOpts.innerRect.x - buildOpts.outerRect.x - buildOpts.stepSize / 2);
    struct.collider = {
      type: 'rect',
      x: leftBoundary,
      y: 0,
      width: leftBoundary < 0 ? buildOpts.stepSize + leftBoundary : buildOpts.stepSize,
      // Adjust collider so that it doesnt extend onto neighbor collider
      height: buildOpts.innerRect.height
    };
  } else {
    var _tickCenter = tick.position * buildOpts.innerRect.height;

    var topBoundary = _tickCenter + (buildOpts.innerRect.y - buildOpts.outerRect.y - buildOpts.stepSize / 2);
    struct.collider = {
      type: 'rect',
      x: 0,
      y: topBoundary,
      width: buildOpts.innerRect.width,
      height: topBoundary < 0 ? buildOpts.stepSize + topBoundary : buildOpts.stepSize // Adjust collider so that it doesnt extend onto neighbor collider

    };
  } // Clip edges of the collider, should not extend beyoned the outerRect


  var collider = struct.collider;
  collider.x = Math.max(collider.x, 0);
  collider.y = Math.max(collider.y, 0);
  var widthClip = collider.x + collider.width - (buildOpts.outerRect.x + buildOpts.outerRect.width);
  collider.width = widthClip > 0 ? collider.width - widthClip : collider.width;
  var heightClip = collider.y + collider.height - (buildOpts.outerRect.y + buildOpts.outerRect.height);
  collider.height = heightClip > 0 ? collider.height - heightClip : collider.height;
}

function boundsCollider(tick, struct) {
  struct.collider = {
    type: 'polygon',
    vertices: [{
      x: struct.boundingRect.x,
      y: struct.boundingRect.y
    }, {
      x: struct.boundingRect.x + struct.boundingRect.width,
      y: struct.boundingRect.y
    }, {
      x: struct.boundingRect.x + struct.boundingRect.width,
      y: struct.boundingRect.y + struct.boundingRect.height
    }, {
      x: struct.boundingRect.x,
      y: struct.boundingRect.y + struct.boundingRect.height
    }]
  };
}

function tiltedCollider(tick, struct, buildOpts) {
  var radians = buildOpts.angle * (Math.PI / 180);
  var halfWidth = Math.max(buildOpts.stepSize / 2, struct.boundingRect.height / 2); // Handle if bandwidth is zero

  var startAnchor = struct.anchor === 'start';
  var em = struct.anchor === 'end' && radians < 0;
  var sp = struct.anchor === 'start' && radians >= 0;
  var y = struct.boundingRect.y + (sp || em ? struct.boundingRect.height : 0); // Generate starting points at bandwidth boundaries

  var points = [{
    x: struct.x - halfWidth,
    y: y
  }, {
    x: struct.x + halfWidth,
    y: y
  }].map(function (p) {
    return rotate(p, radians, {
      x: struct.x,
      y: struct.y
    });
  }); // Rotate around center point to counteract labels rotation
  // Append points to wrap polygon around label

  var margin = 10; // extend slightly to handle single char labels better

  var leftPoint = {
    x: startAnchor ? struct.boundingRect.x + struct.boundingRect.width + margin : struct.boundingRect.x - margin,
    y: struct.boundingRect.y + struct.boundingRect.height
  };
  var rightPoint = {
    x: startAnchor ? struct.boundingRect.x + struct.boundingRect.width + margin : struct.boundingRect.x - margin,
    y: struct.boundingRect.y
  };
  var orderedPoints = radians >= 0 ? [leftPoint, rightPoint] : [rightPoint, leftPoint];
  points.push.apply(points, orderedPoints);
  struct.collider = {
    type: 'polygon',
    vertices: points
  };
}

function appendCollider(tick, struct, buildOpts) {
  if (buildOpts.layered || !buildOpts.stepSize) {
    boundsCollider(tick, struct);
  } else if (buildOpts.tilted) {
    tiltedCollider(tick, struct, buildOpts);
  } else {
    bandwidthCollider(tick, struct, buildOpts);
  }
}

function appendBounds(struct, buildOpts) {
  struct.boundingRect = buildOpts.textBounds(struct);
}

function wiggle(buildOpts, isVertical) {
  var a = isNaN(buildOpts.style.align) ? 0.5 : Math.min(Math.max(buildOpts.style.align, 0), 1);
  var w = 0;

  if (buildOpts.tilted) {
    w = buildOpts.stepSize * a;
  } else {
    var size = isVertical ? buildOpts.textRect.height : buildOpts.textRect.width;
    w = Math.max(0, buildOpts.stepSize - size) * a;
  }

  return w;
}

function buildNode(tick, buildOpts) {
  var struct = {
    type: 'text',
    text: checkText(tick.label),
    x: 0,
    y: 0,
    maxWidth: buildOpts.maxWidth,
    maxHeight: buildOpts.maxHeight
  };

  if (buildOpts.align === 'top' || buildOpts.align === 'bottom') {
    struct.x = tick.start * buildOpts.innerRect.width + (buildOpts.innerRect.x - buildOpts.outerRect.x) + wiggle(buildOpts, false);
    struct.y = buildOpts.align === 'top' ? buildOpts.innerRect.height : 0;
    struct.anchor = buildOpts.stepSize ? 'start' : 'middle';
    struct.x += isNaN(buildOpts.style.offset) ? 0 : +buildOpts.style.offset;
  } else {
    struct.y = tick.start * buildOpts.innerRect.height + (buildOpts.innerRect.y - buildOpts.outerRect.y) + wiggle(buildOpts, true);
    struct.x = buildOpts.align === 'left' ? buildOpts.innerRect.width : 0;
    struct.anchor = buildOpts.align === 'left' ? 'end' : 'start';
    struct.baseline = buildOpts.stepSize ? 'text-before-edge' : 'central';
    struct.y += isNaN(buildOpts.style.offset) ? 0 : +buildOpts.style.offset;
  }

  appendStyle$1(struct, buildOpts);
  clampEnds(struct, buildOpts);
  appendPadding(struct, buildOpts);
  appendTilting(struct, buildOpts);
  appendBounds(struct, buildOpts);
  appendCollider(tick, struct, buildOpts);
  return struct;
}

function appendStyle$2(struct, buildOpts) {
  extend(struct, buildOpts.style);
}

function appendPadding$1(struct, buildOpts) {
  if (buildOpts.align === 'top') {
    struct.y1 -= buildOpts.padding;
    struct.y2 -= buildOpts.padding;
  } else if (buildOpts.align === 'bottom') {
    struct.y1 += buildOpts.padding;
    struct.y2 += buildOpts.padding;
  } else if (buildOpts.align === 'left') {
    struct.x1 -= buildOpts.padding;
    struct.x2 -= buildOpts.padding;
  } else if (buildOpts.align === 'right') {
    struct.x1 += buildOpts.padding;
    struct.x2 += buildOpts.padding;
  }
}

function adjustForEnds(struct, buildOpts) {
  var halfWidth = struct.strokeWidth / 2;

  if (struct.x1 === buildOpts.innerRect.width) {
    // outer end tick
    struct.x1 -= halfWidth;
    struct.x2 -= halfWidth;
  } else if (struct.x1 === 0) {
    // outer start tick
    struct.x1 += halfWidth;
    struct.x2 += halfWidth;
  } else if (struct.y1 === buildOpts.innerRect.height) {
    struct.y1 -= halfWidth;
    struct.y2 -= halfWidth;
  } else if (struct.y1 === 0) {
    struct.y1 += halfWidth;
    struct.y2 += halfWidth;
  }
}

function buildNode$1(tick, buildOpts) {
  var struct = {
    type: 'line',
    x1: 0,
    x2: 0,
    y1: 0,
    y2: 0,
    collider: {
      type: null
    }
  };

  if (buildOpts.align === 'top' || buildOpts.align === 'bottom') {
    struct.x1 = struct.x2 = tick.position * buildOpts.innerRect.width + (buildOpts.innerRect.x - buildOpts.outerRect.x);
    struct.y1 = buildOpts.align === 'top' ? buildOpts.innerRect.height : 0;
    struct.y2 = buildOpts.align === 'top' ? struct.y1 - buildOpts.tickSize : struct.y1 + buildOpts.tickSize;
  } else {
    struct.y1 = struct.y2 = tick.position * buildOpts.innerRect.height + (buildOpts.innerRect.y - buildOpts.outerRect.y);
    struct.x1 = buildOpts.align === 'left' ? buildOpts.innerRect.width : 0;
    struct.x2 = buildOpts.align === 'left' ? struct.x1 - buildOpts.tickSize : struct.x1 + buildOpts.tickSize;
  }

  appendStyle$2(struct, buildOpts);
  appendPadding$1(struct, buildOpts);
  adjustForEnds(struct, buildOpts);
  return struct;
}

function isMajorTick(tick) {
  return !tick.isMinor && tick.position >= 0 && tick.position <= 1;
}

function isVerticalLabelOverlapping(_ref) {
  var majorTicks = _ref.majorTicks,
      measureText = _ref.measureText,
      rect = _ref.rect;
  var size = rect.height;
  var textHeight = measureText('M').height;

  if (majorTicks.length < 2) {
    return false;
  }

  var d = size * Math.abs(majorTicks[0].position - majorTicks[1].position);

  if (d < textHeight) {
    return true;
  }

  return false;
}

function isHorizontalLabelOverlapping(_ref2) {
  var majorTicks = _ref2.majorTicks,
      measureText = _ref2.measureText,
      rect = _ref2.rect,
      state = _ref2.state;

  /*
   * Currently isn't any good way of doing a accurate measurement on size available (bandWidth * width) for labels.
   * It's a lifecycle limitation as components docked either left or right can affect the width available after the calculation is done.
   * <number of components docked left/right> * <width of components> => Less accurate ===> Can result in only ellips char rendered as labels.
   */
  var m = state.labels.activeMode === 'layered' ? 2 : 1;
  var size = rect.width;
  var tickSize = majorTicks.map(function (tick) {
    return tick.label;
  }).map(function (l) {
    return "".concat(l.slice(0, 1)).concat(l.length > 1 ? '…' : '');
  }) // Measure the size of 1 chars + the ellips char.
  .map(measureText).map(function (r) {
    return r.width;
  });

  for (var i = 0; i < majorTicks.length; ++i) {
    var tick = majorTicks[i];
    var d1 = m * size * Math.abs(tick.start - tick.end);
    var d2 = tickSize[i];

    if (d1 < d2) {
      return true;
    }
  }

  return false;
}

function shouldAutoTilt(_ref3) {
  var majorTicks = _ref3.majorTicks,
      measure = _ref3.measure,
      rect = _ref3.rect,
      state = _ref3.state,
      settings = _ref3.settings;
  var glyphCount = settings.labels.maxGlyphCount;
  var m = state.labels.activeMode === 'layered' ? 2 : 1;
  var magicSizeRatioMultipler = settings.labels.tiltThreshold ? settings.labels.tiltThreshold : 0.7; // So that if less the 70% of labels are visible, toggle on tilt or use variable tiltThreshold

  var ellipsCharSize = measure('…').width; // include ellipsed char in calc as it's generally large then the char it replaces

  var size = rect.width;
  var maxLabelWidth = 0;
  var d1 = 0;

  if (!isNaN(glyphCount)) {
    var minBandwidth = majorTicks.reduce(function (prev, curr) {
      return Math.min(Math.abs(curr.start - curr.end), prev);
    }, Infinity);
    d1 = m * size * minBandwidth;
    maxLabelWidth = measure('M').width * magicSizeRatioMultipler * glyphCount;

    if (maxLabelWidth + ellipsCharSize > d1) {
      return true;
    }
  } else {
    for (var i = 0; i < majorTicks.length; i++) {
      var tick = majorTicks[i];
      var label = tick.label;
      var width = measure(label).width * (label.length > 1 ? magicSizeRatioMultipler : 1);
      d1 = m * size * Math.abs(tick.start - tick.end);

      if (width + ellipsCharSize > d1) {
        return true;
      }
    }
  }

  return false;
}

function isTiltedLabelOverlapping(_ref4) {
  var majorTicks = _ref4.majorTicks,
      measureText = _ref4.measureText,
      rect = _ref4.rect,
      bleedSize = _ref4.bleedSize,
      angle = _ref4.angle;

  if (majorTicks.length < 2) {
    return false;
  }

  if (angle === 0) {
    return true; // TODO 0 angle should be considered non-tilted
  }

  var absAngle = Math.abs(angle);
  var size = rect.width - bleedSize;
  var stepSize = size * Math.abs(majorTicks[0].position - majorTicks[1].position);
  var textHeight = measureText('M').height;
  var reciprocal = 1 / stepSize; // 1 === Math.sin(90 * (Math.PI / 180))

  var distanceBetweenLabels = Math.sin(absAngle * (Math.PI / 180)) / reciprocal;
  return textHeight > distanceBetweenLabels;
}

function isToLarge(_ref5) {
  var rect = _ref5.rect,
      state = _ref5.state,
      majorTicks = _ref5.majorTicks,
      measure = _ref5.measure,
      horizontal = _ref5.horizontal;

  if (horizontal) {
    return isHorizontalLabelOverlapping({
      majorTicks: majorTicks,
      measureText: measure,
      rect: rect,
      state: state
    });
  }

  return isVerticalLabelOverlapping({
    majorTicks: majorTicks,
    measureText: measure,
    rect: rect,
    state: state
  });
}

function getClampedValue(_ref6) {
  var value = _ref6.value,
      maxValue = _ref6.maxValue,
      minValue = _ref6.minValue,
      range = _ref6.range,
      modifier = _ref6.modifier;

  if (!isNaN(range) && !isNaN(modifier)) {
    value = range * modifier;
  }

  if (value > maxValue) {
    value = maxValue;
  }

  if (value < minValue) {
    value = minValue;
  }

  return value;
}
function getSize(_ref7) {
  var isDiscrete = _ref7.isDiscrete,
      rect = _ref7.rect,
      formatter = _ref7.formatter,
      measureText = _ref7.measureText,
      scale = _ref7.scale,
      settings = _ref7.settings,
      state = _ref7.state;
  var size = 0;
  var edgeBleed = {
    left: 0,
    top: 0,
    right: 0,
    bottom: 0
  };
  var _settings$labels = settings.labels,
      maxValue = _settings$labels.maxLengthPx,
      minValue = _settings$labels.minLengthPx;

  if (settings.labels.show) {
    var align = settings.align;
    var horizontal = align === 'top' || align === 'bottom';
    var distance = horizontal ? rect.width : rect.height;
    var majorTicks = scale.ticks({
      settings: settings,
      distance: distance,
      formatter: formatter
    }).filter(isMajorTick);

    var measure = function measure(text) {
      var m = measureText({
        text: text,
        fontSize: settings.labels.fontSize,
        fontFamily: settings.labels.fontFamily
      });
      m.width = getClampedValue({
        value: m.width,
        maxValue: maxValue,
        minValue: minValue
      });
      return m;
    };

    if (isDiscrete && horizontal && settings.labels.mode === 'auto') {
      if (shouldAutoTilt({
        majorTicks: majorTicks,
        measure: measure,
        rect: rect,
        state: state,
        settings: settings
      })) {
        state.labels.activeMode = 'tilted';
      } else {
        state.labels.activeMode = 'horizontal';
      }
    }

    if (!settings.labels.filterOverlapping && state.labels.activeMode !== 'tilted' && isToLarge({
      rect: rect,
      state: state,
      majorTicks: majorTicks,
      measure: measure,
      horizontal: horizontal
    })) {
      var toLargeSize = Math.max(rect.width, rect.height); // used to hide the axis

      return {
        size: toLargeSize,
        isToLarge: true
      };
    }

    var sizeFromTextRect;

    if (state.labels.activeMode === 'tilted') {
      var radians = Math.abs(settings.labels.tiltAngle) * (Math.PI / 180); // angle in radians

      sizeFromTextRect = function sizeFromTextRect(r) {
        return getClampedValue({
          value: r.width,
          maxValue: maxValue,
          minValue: minValue
        }) * Math.sin(radians) + r.height * Math.cos(radians);
      };
    } else if (horizontal) {
      sizeFromTextRect = function sizeFromTextRect(r) {
        return r.height;
      };
    } else {
      sizeFromTextRect = function sizeFromTextRect(r) {
        return getClampedValue({
          value: r.width,
          maxValue: maxValue,
          minValue: minValue
        });
      };
    }

    var labels;

    if (horizontal && state.labels.activeMode !== 'tilted') {
      labels = ['M'];
    } else if (!isNaN(settings.labels.maxGlyphCount)) {
      var label = '';

      for (var i = 0; i < settings.labels.maxGlyphCount; i++) {
        label += 'M';
      }

      labels = [label];
    } else {
      labels = majorTicks.map(function (tick) {
        return tick.label;
      });
    }

    var tickMeasures = labels.map(measure);
    var labelSizes = tickMeasures.map(sizeFromTextRect);
    var textSize = Math.max.apply(Math, _toConsumableArray$1(labelSizes).concat([0]));
    size += textSize;
    size += settings.labels.margin;

    if (state.labels.activeMode === 'layered') {
      size *= 2;
    }

    if (state.labels.activeMode === 'tilted') {
      var extendLeft = settings.align === 'bottom' === settings.labels.tiltAngle >= 0;

      var _radians = Math.abs(settings.labels.tiltAngle) * (Math.PI / 180); // angle in radians


      var h = measureText('M').height;
      var maxWidth = (textSize - h * Math.cos(_radians)) / Math.sin(_radians);

      var labelWidth = function labelWidth(r) {
        return Math.min(maxWidth, r.width) * Math.cos(_radians) + r.height;
      };

      var adjustByPosition = function adjustByPosition(s, i) {
        var pos = majorTicks[i] ? majorTicks[i].position : 0;

        if (extendLeft) {
          return s - pos * rect.width;
        }

        return s - (1 - pos) * rect.width;
      };

      var bleedSize = Math.min(settings.labels.maxEdgeBleed, Math.max.apply(Math, _toConsumableArray$1(tickMeasures.map(labelWidth).map(adjustByPosition)).concat([0]))) + settings.paddingEnd;
      var bleedDir = extendLeft ? 'left' : 'right';
      edgeBleed[bleedDir] = bleedSize;

      if (!settings.labels.filterOverlapping && isTiltedLabelOverlapping({
        majorTicks: majorTicks,
        measureText: measureText,
        rect: rect,
        bleedSize: bleedSize,
        angle: settings.labels.tiltAngle
      })) {
        return {
          size: Math.max(rect.width, rect.height),
          isToLarge: true
        };
      }
    }
  }

  return {
    size: size,
    edgeBleed: edgeBleed
  };
}

var PADDING = 2;

var tickDistance = function tickDistance(rect, start, end) {
  return rect.width * Math.abs(start.position - end.position);
};

var getLeftEdgeWidth = function getLeftEdgeWidth(_ref) {
  var innerRect = _ref.innerRect,
      outerRect = _ref.outerRect,
      tick = _ref.tick,
      nextWidth = _ref.nextWidth;
  var leftEdgeBleed = innerRect.x - outerRect.x;
  var left = innerRect.width * tick.position + leftEdgeBleed;
  var minDubble = Math.min(nextWidth, left) * 2;
  var minWidth = tick.position === 0 ? innerRect.width / 2 - PADDING : 0;
  return Math.max(nextWidth, minDubble, minWidth);
};

var getRightEdgeWidth = function getRightEdgeWidth(_ref2) {
  var innerRect = _ref2.innerRect,
      outerRect = _ref2.outerRect,
      tick = _ref2.tick,
      prevWidth = _ref2.prevWidth;
  var leftEdgeBleed = innerRect.x - outerRect.x;
  var rightEdgeBleed = outerRect.width - innerRect.width - leftEdgeBleed;
  var right = innerRect.width - innerRect.width * tick.position + rightEdgeBleed;
  var minDubble = Math.min(prevWidth, right) * 2;
  var minWidth = tick.position === 1 ? innerRect.width / 2 - PADDING : 0;
  return Math.max(prevWidth, minDubble, minWidth);
};

function getHorizontalWidth(_ref3) {
  var layered = _ref3.layered,
      major = _ref3.major,
      innerRect = _ref3.innerRect,
      outerRect = _ref3.outerRect,
      tick = _ref3.tick,
      index = _ref3.index;
  var step = layered ? 2 : 1;
  var prev = major[index - step];
  var next = major[index + step];
  var prevWidth = prev ? tickDistance(innerRect, tick, prev) / 2 - PADDING : Infinity;
  var nextWidth = next ? tickDistance(innerRect, tick, next) / 2 - PADDING : Infinity;

  if (major.length < 2) {
    return innerRect.width;
  }

  if (!prev) {
    return getLeftEdgeWidth({
      innerRect: innerRect,
      outerRect: outerRect,
      tick: tick,
      nextWidth: nextWidth
    });
  }

  if (!next) {
    return getRightEdgeWidth({
      innerRect: innerRect,
      outerRect: outerRect,
      tick: tick,
      prevWidth: prevWidth
    });
  }

  return Math.min(prevWidth, nextWidth) * 2;
}

function tickSpacing(settings) {
  var spacing = 0;
  spacing += settings.paddingStart;
  spacing += settings.line.show ? settings.line.strokeWidth : 0;
  spacing += settings.ticks.show ? settings.ticks.margin : 0;
  return spacing;
}

function tickMinorSpacing(settings) {
  return settings.line.strokeWidth + settings.minorTicks.margin;
}

function labelsSpacing(settings) {
  var spacing = 0;
  spacing += settings.ticks.show ? settings.ticks.tickSize : 0;
  spacing += tickSpacing(settings) + settings.labels.margin;
  return spacing;
}

function calcActualTextRect(_ref) {
  var style = _ref.style,
      measureText = _ref.measureText,
      tick = _ref.tick;
  return measureText({
    text: tick.label,
    fontSize: style.fontSize,
    fontFamily: style.fontFamily
  });
}

function majorTicks(ticks) {
  return ticks.filter(function (t) {
    return !t.isMinor;
  });
}

function minorTicks(ticks) {
  return ticks.filter(function (t) {
    return t.isMinor;
  });
}

function tickBuilder(ticks, buildOpts) {
  return ticks.map(function (tick) {
    return buildNode$1(tick, buildOpts);
  });
}

function tickBandwidth(scale, tick) {
  return tick ? Math.abs(tick.end - tick.start) : scale.bandwidth();
}

function labelBuilder(ticks, buildOpts, resolveTickOpts) {
  return ticks.map(function (tick, idx) {
    resolveTickOpts(tick, idx);
    var label = buildNode(tick, buildOpts);
    label.data = tick.data;
    return label;
  });
}

function layeredLabelBuilder(ticks, buildOpts, settings, resolveTickOpts) {
  var padding = buildOpts.padding;
  var spacing = labelsSpacing(settings);
  return ticks.map(function (tick, idx) {
    resolveTickOpts(tick, idx);
    var padding2 = spacing + buildOpts.maxHeight + settings.labels.margin;
    buildOpts.layer = idx % 2;
    buildOpts.padding = idx % 2 === 0 ? padding : padding2;
    var label = buildNode(tick, buildOpts);
    label.data = tick.data;
    return label;
  });
}

function filterOverlappingLabels(labels, ticks, buildOpts) {
  var isOverlapping = function isOverlapping(i, k) {
    var rect1 = expandRect(1, labels[i].boundingRect);
    var rect2 = expandRect(1, labels[k].boundingRect);
    return testRectRect(rect1, rect2);
  };

  if (buildOpts && buildOpts.tilted) {
    var absAngle = Math.abs(buildOpts.angle);

    isOverlapping = function isOverlapping(i, k) {
      var stepSize = Math.abs(labels[i].x - labels[k].x);
      var reciprocal = 1 / stepSize;
      var distanceBetweenLabels = Math.sin(absAngle * (Math.PI / 180)) / reciprocal;
      return labels[i].boundingRect.height > distanceBetweenLabels;
    };
  }

  for (var i = 0; i <= labels.length - 1; i++) {
    for (var k = i + 1; k <= Math.min(i + 5, i + (labels.length - 1)); k++) {
      // TODO Find a better way to handle exteme/layered labels then to iterare over ~5 next labels
      if (labels[i] && labels[k] && isOverlapping(i, k)) {
        if (k === labels.length - 1) {
          // On collition with last label, remove current label instead
          labels.splice(i, 1);

          if (ticks) {
            ticks.splice(i, 1);
          }
        } else {
          labels.splice(k, 1);

          if (ticks) {
            ticks.splice(k, 1);
          }
        }

        k--;
        i--;
      }
    }
  }
}

function discreteCalcMaxTextRect(_ref2) {
  var textMetrics = _ref2.textMetrics,
      settings = _ref2.settings,
      innerRect = _ref2.innerRect,
      scale = _ref2.scale,
      tilted = _ref2.tilted,
      layered = _ref2.layered,
      tick = _ref2.tick;
  var h = textMetrics.height;
  var bandwidth = tickBandwidth(scale, tick);
  var textRect = {
    width: 0,
    height: h
  };

  if (settings.align === 'left' || settings.align === 'right') {
    textRect.width = innerRect.width - labelsSpacing(settings) - settings.paddingEnd;
  } else if (layered) {
    textRect.width = bandwidth * innerRect.width * 2;
  } else if (tilted) {
    var radians = Math.abs(settings.labels.tiltAngle) * (Math.PI / 180);
    textRect.width = (innerRect.height - labelsSpacing(settings) - settings.paddingEnd - h * Math.cos(radians)) / Math.sin(radians);
  } else {
    textRect.width = bandwidth * innerRect.width;
  }

  textRect.width = getClampedValue({
    value: textRect.width,
    maxValue: settings.labels.maxLengthPx,
    minValue: settings.labels.minLengthPx
  });
  return textRect;
}

function continuousCalcMaxTextRect(_ref3) {
  var textMetrics = _ref3.textMetrics,
      settings = _ref3.settings,
      innerRect = _ref3.innerRect,
      outerRect = _ref3.outerRect,
      tilted = _ref3.tilted,
      layered = _ref3.layered,
      tick = _ref3.tick,
      index = _ref3.index,
      major = _ref3.major;
  var h = textMetrics.height;
  var textRect = {
    width: 0,
    height: h
  };

  if (settings.align === 'left' || settings.align === 'right') {
    textRect.width = innerRect.width - labelsSpacing(settings) - settings.paddingEnd;
  } else if (tilted) {
    var radians = Math.abs(settings.labels.tiltAngle) * (Math.PI / 180);
    textRect.width = (innerRect.height - labelsSpacing(settings) - settings.paddingEnd - h * Math.cos(radians)) / Math.sin(radians);
  } else {
    textRect.width = getHorizontalWidth({
      layered: layered,
      major: major,
      innerRect: innerRect,
      outerRect: outerRect,
      tick: tick,
      index: index
    });
  }

  textRect.width = getClampedValue({
    value: textRect.width,
    maxValue: settings.labels.maxLengthPx,
    minValue: settings.labels.minLengthPx
  });
  return textRect;
}

function getStepSizeFn(_ref4) {
  var innerRect = _ref4.innerRect,
      scale = _ref4.scale,
      settings = _ref4.settings,
      tick = _ref4.tick;
  var size = settings.align === 'top' || settings.align === 'bottom' ? innerRect.width : innerRect.height;
  var bandwidth = tickBandwidth(scale, tick);
  return size * bandwidth;
}

function nodeBuilder(isDiscrete) {
  var resolveLabelRect;

  function continuous() {
    resolveLabelRect = continuousCalcMaxTextRect;
    return continuous;
  }

  function discrete() {
    resolveLabelRect = discreteCalcMaxTextRect;
    return discrete;
  }

  function build(_ref5) {
    var settings = _ref5.settings,
        scale = _ref5.scale,
        innerRect = _ref5.innerRect,
        outerRect = _ref5.outerRect,
        measureText = _ref5.measureText,
        ticks = _ref5.ticks,
        state = _ref5.state,
        textBounds = _ref5.textBounds;
    var nodes = [];
    var major = majorTicks(ticks);
    var minor = minorTicks(ticks);
    var buildOpts = {
      innerRect: innerRect,
      align: settings.align,
      outerRect: outerRect
    };
    var tilted = state.labels.activeMode === 'tilted';
    var layered = state.labels.activeMode === 'layered';
    var majorTickNodes;

    if (settings.line.show) {
      buildOpts.style = settings.line;
      buildOpts.padding = settings.paddingStart;
      nodes.push(buildLine(buildOpts));
    }

    if (settings.ticks.show) {
      buildOpts.style = settings.ticks;
      buildOpts.tickSize = settings.ticks.tickSize;
      buildOpts.padding = tickSpacing(settings);
      majorTickNodes = tickBuilder(major, buildOpts);
    }

    if (settings.labels.show) {
      var padding = labelsSpacing(settings);
      buildOpts.style = settings.labels;
      buildOpts.padding = padding;
      buildOpts.tilted = tilted;
      buildOpts.layered = layered;
      buildOpts.angle = settings.labels.tiltAngle;
      buildOpts.paddingEnd = settings.paddingEnd;
      buildOpts.textBounds = textBounds;

      var resolveTickOpts = function resolveTickOpts(tick, index) {
        buildOpts.textRect = calcActualTextRect({
          tick: tick,
          measureText: measureText,
          style: buildOpts.style
        });
        var maxSize = resolveLabelRect({
          textMetrics: buildOpts.textRect,
          settings: settings,
          innerRect: innerRect,
          outerRect: outerRect,
          scale: scale,
          tilted: tilted,
          layered: layered,
          tick: tick,
          major: major,
          index: index
        });
        buildOpts.maxWidth = maxSize.width;
        buildOpts.maxHeight = maxSize.height;
        buildOpts.stepSize = getStepSizeFn({
          innerRect: innerRect,
          scale: scale,
          ticks: ticks,
          settings: settings,
          tick: tick
        });
      };

      var labelNodes = [];

      if (layered && (settings.align === 'top' || settings.align === 'bottom')) {
        labelNodes = layeredLabelBuilder(major, buildOpts, settings, resolveTickOpts);
      } else {
        labelNodes = labelBuilder(major, buildOpts, resolveTickOpts);
      } // Remove labels (and paired tick) that are overlapping


      if (settings.labels.filterOverlapping) {
        filterOverlappingLabels(labelNodes, majorTickNodes, buildOpts);
      }

      nodes.push.apply(nodes, _toConsumableArray$1(labelNodes));
    }

    if (settings.minorTicks && settings.minorTicks.show && minor.length > 0) {
      buildOpts.style = settings.minorTicks;
      buildOpts.tickSize = settings.minorTicks.tickSize;
      buildOpts.padding = tickMinorSpacing(settings);
      nodes.push.apply(nodes, _toConsumableArray$1(tickBuilder(minor, buildOpts)));
    }

    if (majorTickNodes) {
      nodes.push.apply(nodes, _toConsumableArray$1(majorTickNodes));
    }

    return nodes;
  }

  continuous.build = build;
  discrete.build = build;
  return isDiscrete ? discrete() : continuous();
}

// const DEFAULT_LAYOUT_SETTINGS = { // TODO create dis and con specific settings
//   anchor: 'auto', // TODO re-name from align..
//   // orientation: 'auto', // TODO impl. v/h/auto
//   // direction: 'auto', // TODO impl. left/right/top/bottom/auto
//   padding: { // TODO use dock layout margin instead..
//     start: 0,
//     end: 10
//   },
//   maxGlyphCount: NaN,
//   maxEdgeBleed: Infinity
//   // labelMode: 'auto' // TODO move here? auto, horizontal, layered
// };

/**
 * Discrete axis settings
 * @typedef {object}
 * @alias component--axis-discrete
 */
var DEFAULT_DISCRETE_SETTINGS = {
  /**
   * @typedef {object}
   */
  labels: {
    /** Toggle labels on/off
    * @type {boolean=} */
    show: true,

    /** Tilting angle in degrees. Capped between -90 and 90. Only applicable when labels are in `tilted` mode.
    * @type {number=} */
    tiltAngle: 40,

    /** Threshold for toggle of tilted labels. Capped between 0 and 1. For example, if it is set to 0.7, then tilted labels will be toggled if less than 70% of the labels are visible.
    * @type {number=}
    * @experimental */
    tiltThreshold: 0.7,

    /** Control the amount of space (in pixels) that labes can occupy outside their docking area. Only applicable when labels are in `tilted` mode.
    * @type {number=} */
    maxEdgeBleed: Infinity,

    /** Space in pixels between the tick and label.
    * @type {number=} */
    margin: 4,

    /** Max length of labels in pixels
    * @type {number=} */
    maxLengthPx: 150,

    /** Min length of labels in pixels. Labels will always at least require this much space
    * @type {number=} */
    minLengthPx: 0,

    /** Control how labels arrange themself. Availabe modes are `auto`, `horizontal`, `layered` and `tilted`. When set to `auto` the axis determines the best possible layout in the current context.
    * @type {string=} */
    mode: 'auto',

    /** When only a sub-set of data is available, ex. when paging. This property can be used to let the axis estimate how much space the labels will consume, allowing it to give a consistent space estimate over the entire dataset when paging.
    * @type {number=} */
    maxGlyphCount: NaN,

    /** Align act as a slider for the text bounding rect over the item bandwidth, given that the item have a bandwidth. Except when labels are tilted, then the align is a pure align that shifts the position of the label anchoring point.
    * @type {number=} */
    align: 0.5,

    /** Offset in pixels along the axis direction.
    * @type {number=} */
    offset: 0,

    /**
     * Toggle whether labels should be filtered if they are overlapping. Filtering may be applied in a non-sequential order.
     * If labels are overlapping and this setting is toggled off, the axis will automatically hide.
     * @type {boolean=}
     */
    filterOverlapping: false
  },

  /**
   * @typedef {object}
   */
  ticks: {
    /** Toggle ticks on/off
    * @type {boolean=} */
    show: false,

    /** Space in pixels between the ticks and the line.
    * @type {number=} */
    margin: 0,

    /** Size of the ticks in pixels.
    * @type {number=} */
    tickSize: 4
  },

  /**
   * @typedef {object}
   */
  line: {
    /** Toggle line on/off
    * @type {boolean=} */
    show: false
  },

  /** Padding in direction perpendicular to the axis
    * @type {number=} */
  paddingStart: 0,

  /** Padding in direction perpendicular to the axis
    * @type {number=} */
  paddingEnd: 10,

  /** Set the anchoring point of the axis. Avaialable options are `auto/left/right/bottom/top`. In `auto` the axis determines the best option. The options are restricted based on the axis orientation, a vertical axis may only anchor on `left` or `right`
    * @type {string=} */
  align: 'auto'
};
/**
 * Continuous axis settings
 * @typedef {object}
 * @alias component--axis-continuous
 */

var DEFAULT_CONTINUOUS_SETTINGS = {
  /**
   * @typedef {object}
   */
  labels: {
    /** Toggle labels on/off
    * @type {boolean=} */
    show: true,

    /** Space in pixels between the tick and label.
    * @type {number=} */
    margin: 4,

    /** Max length of labels in pixels
    * @type {number=} */
    maxLengthPx: 150,

    /** Min length of labels in pixels. Labels will always at least require this much space
    * @type {number=} */
    minLengthPx: 0,

    /** Align act as a slider for the text bounding rect over the item bandwidth, given that the item have a bandwidth.
    * @type {number=} */
    align: 0.5,

    /** Offset in pixels along the axis direction.
    * @type {number=} */
    offset: 0,

    /**
     * Toggle whether labels should be filtered if they are overlapping. Filtering may be applied in a non-sequential order.
     * If labels are overlapping and this setting is toggled off, the axis will automatically hide.
     * @type {boolean=}
     */
    filterOverlapping: true
  },

  /**
   * @typedef {object}
   */
  ticks: {
    /** Toggle ticks on/off
    * @type {boolean=} */
    show: true,

    /** Space in pixels between the ticks and the line.
    * @type {number=} */
    margin: 0,

    /** Size of the ticks in pixels.
    * @type {number=} */
    tickSize: 8
  },

  /**
   * @typedef {object}
   */
  minorTicks: {
    /** Toggle minor-ticks on/off
    * @type {boolean=} */
    show: false,

    /** Size of the ticks in pixels.
    * @type {number=} */
    tickSize: 3,

    /** Space in pixels between the ticks and the line.
    * @type {number=} */
    margin: 0
  },

  /**
   * @typedef {object}
   */
  line: {
    /** Toggle line on/off
    * @type {boolean=} */
    show: true
  },

  /** Padding in direction perpendicular to the axis
    * @type {number=} */
  paddingStart: 0,

  /** Padding in direction perpendicular to the axis
    * @type {number=} */
  paddingEnd: 10,

  /** Set the anchoring point of the axis. Avaialable options are `auto/left/right/bottom/top`. In `auto` the axis determines the best option. The options are restricted based on the axis orientation, a vertical axis may only anchor on `left` or `right`
    * @type {string=} */
  align: 'auto'
};

function calcRequiredSize(_ref) {
  var isDiscrete = _ref.isDiscrete,
      rect = _ref.rect,
      formatter = _ref.formatter,
      measureText = _ref.measureText,
      scale = _ref.scale,
      settings = _ref.settings,
      state = _ref.state;
  var size = 0;

  var _getLabelSize = getSize({
    isDiscrete: isDiscrete,
    rect: rect,
    formatter: formatter,
    measureText: measureText,
    scale: scale,
    settings: settings,
    state: state
  }),
      labelSize = _getLabelSize.size,
      edgeBleed = _getLabelSize.edgeBleed,
      isToLarge = _getLabelSize.isToLarge;

  size += labelSize;

  if (isToLarge) {
    return {
      size: size
    };
  }

  if (settings.ticks.show) {
    size += settings.ticks.margin;
    size += settings.ticks.tickSize;
  }

  if (settings.minorTicks && settings.minorTicks.show) {
    var minorTicksSize = settings.minorTicks.margin + settings.minorTicks.tickSize;

    if (minorTicksSize > size) {
      size = minorTicksSize;
    }
  }

  if (settings.line.show) {
    size += settings.line.strokeWidth;
  }

  size += settings.paddingStart;
  size += settings.paddingEnd;
  return {
    size: size,
    edgeBleed: edgeBleed
  };
}

function alignTransform(_ref) {
  var align = _ref.align,
      inner = _ref.inner;

  if (align === 'left') {
    return {
      x: inner.width + inner.x
    };
  }

  if (align === 'right' || align === 'bottom') {
    return inner;
  }

  return {
    y: inner.y + inner.height
  };
}

function resolveAlign(align, dock) {
  var horizontal = ['top', 'bottom'];
  var vertical = ['left', 'right'];

  if (horizontal.indexOf(align) !== -1 && vertical.indexOf(dock) === -1) {
    return align;
  }

  if (vertical.indexOf(align) !== -1 && horizontal.indexOf(dock) === -1) {
    return align;
  }

  return dock; // Invalid align, return current dock as default
}
/**
 * @ignore
 * @param {object} context - The component context
 */


function resolveLocalSettings(_ref2) {
  var state = _ref2.state,
      style = _ref2.style,
      settings = _ref2.settings;
  var defaultStgns = extend(true, {}, state.isDiscrete ? DEFAULT_DISCRETE_SETTINGS : DEFAULT_CONTINUOUS_SETTINGS, style);
  var localStgns = extend(true, {}, defaultStgns, settings.settings);
  var dock = settings.layout.dock || state.defaultDock;
  localStgns.dock = dock;
  localStgns.align = resolveAlign(settings.settings.align, dock);
  localStgns.labels.tiltAngle = Math.max(-90, Math.min(localStgns.labels.tiltAngle, 90));
  return localStgns;
}

function updateActiveMode(state, settings, isDiscrete) {
  var mode = settings.labels.mode;

  if (!isDiscrete || !state.isHorizontal) {
    return 'horizontal';
  }

  if (mode === 'auto') {
    return state.labels.activeMode;
  }

  if (['layered', 'tilted'].indexOf(settings.labels.mode) !== -1 && ['top', 'bottom'].indexOf(settings.dock) !== -1) {
    return mode;
  }

  return 'horizontal';
}

var axisComponent = {
  require: ['chart', 'renderer', 'dockConfig'],
  defaultSettings: {
    layout: {
      displayOrder: 0,
      prioOrder: 0
    },
    settings: {},
    style: {
      labels: '$label',
      ticks: '$guide-line',
      minorTicks: '$guide-line--minor',
      line: '$guide-line'
    }
  },
  created: function created() {
    // State is a representation of properties that are private to this component defintion and may be modified by only in this context.
    this.state = {
      isDiscrete: !!this.scale.bandwidth,
      isHorizontal: false,
      labels: {
        activeMode: 'horizontal'
      },
      ticks: [],
      innerRect: {
        width: 0,
        height: 0,
        x: 0,
        y: 0
      },
      outerRect: {
        width: 0,
        height: 0,
        x: 0,
        y: 0
      },
      defaultDock: undefined,
      concreteNodeBuilder: undefined,
      settings: undefined
    };

    if (this.state.isDiscrete) {
      this.state.defaultDock = 'bottom';
    } else {
      this.state.defaultDock = 'left';
    }

    this.setState(this.settings);
  },
  setState: function setState() {
    this.state.isDiscrete = !!this.scale.bandwidth;
    this.state.settings = resolveLocalSettings(this);
    this.state.concreteNodeBuilder = nodeBuilder(this.state.isDiscrete);
    this.dockConfig.dock(this.state.settings.dock); // Override the dock setting (TODO should be removed)

    this.state.isHorizontal = this.state.settings.align === 'top' || this.state.settings.align === 'bottom';
    this.state.labels.activeMode = updateActiveMode(this.state, this.state.settings, this.state.isDiscrete);
  },
  preferredSize: function preferredSize(opts) {
    var formatter = this.formatter,
        state = this.state,
        scale = this.scale;
    var distance = this.state.isHorizontal ? opts.inner.width : opts.inner.height;
    this.state.pxScale = scaleWithSize(scale, distance);
    var reqSize = calcRequiredSize({
      isDiscrete: this.state.isDiscrete,
      rect: opts.inner,
      formatter: formatter,
      measureText: this.renderer.measureText,
      scale: this.state.pxScale,
      settings: this.state.settings,
      state: state
    });
    return reqSize;
  },
  beforeUpdate: function beforeUpdate() {
    var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var settings = opts.settings;
    this.setState(settings);
  },
  resize: function resize(opts) {
    var inner = opts.inner,
        outer = opts.outer;
    var extendedInner = extend({}, inner, alignTransform({
      align: this.state.settings.align,
      inner: inner
    }));
    var finalOuter = outer || extendedInner;
    extend(this.state.innerRect, extendedInner);
    extend(this.state.outerRect, finalOuter);
    return outer;
  },
  beforeRender: function beforeRender() {
    var scale = this.scale,
        formatter = this.formatter;
    var distance = this.state.isHorizontal ? this.state.innerRect.width : this.state.innerRect.height;
    this.state.pxScale = scaleWithSize(scale, distance);
    this.state.ticks = this.state.pxScale.ticks({
      distance: distance,
      formatter: formatter
    }).filter(function (t) {
      return t.position >= 0 && t.position <= 1;
    });
  },
  render: function render() {
    var state = this.state;
    var nodes = [];
    nodes.push.apply(nodes, _toConsumableArray$1(this.state.concreteNodeBuilder.build({
      settings: this.state.settings,
      scale: this.state.pxScale,
      innerRect: this.state.innerRect,
      outerRect: this.state.outerRect,
      measureText: this.renderer.measureText,
      textBounds: this.renderer.textBounds,
      ticks: this.state.ticks,
      state: state
    })));
    crispifier.multiple(nodes);
    return nodes;
  }
};

/**
 * @typedef {object} component--axis
 */

/**
 * @type {string}
 * @memberof component--axis
 */

var type$1 = 'axis';
function picasso_esm_axis(picasso) {
  picasso.component(type$1, axisComponent);
}

function parseTitle(text, join, scale) {
  var title = '';

  if (typeof text === 'function') {
    title = text();
  } else if (typeof text === 'string') {
    title = text;
  } else if (scale) {
    var data = scale.data();
    var titles = (data.fields || []).map(function (field) {
      return field.title();
    });
    title = titles.join(join);
  }

  return title;
}

function getTextAnchor(dock, anchor) {
  var val = 'middle';

  if (dock === 'left') {
    if (anchor === 'top') {
      val = 'end';
    } else if (anchor === 'bottom') {
      val = 'start';
    }
  } else if (dock === 'right') {
    if (anchor === 'top') {
      val = 'start';
    } else if (anchor === 'bottom') {
      val = 'end';
    }
  } else if (anchor === 'left') {
    val = 'start';
  } else if (anchor === 'right') {
    val = 'end';
  }

  return val;
}

function generateTitle(_ref) {
  var title = _ref.title,
      definitionSettings = _ref.definitionSettings,
      dock = _ref.dock,
      rect = _ref.rect,
      measureText = _ref.measureText,
      style = _ref.style;
  var struct = {
    type: 'text',
    text: title,
    x: 0,
    y: 0,
    dx: 0,
    dy: 0,
    anchor: getTextAnchor(dock, definitionSettings.anchor),
    baseline: 'alphabetical'
  };
  extend(struct, style.text);
  var textRect = measureText(struct);

  if (dock === 'top' || dock === 'bottom') {
    var x = rect.width / 2;

    if (definitionSettings.anchor === 'left') {
      x = definitionSettings.paddingLeft || 0;
    } else if (definitionSettings.anchor === 'right') {
      x = rect.width - (definitionSettings.paddingRight || 0);
    }

    struct.x = x;
    struct.y = dock === 'top' ? rect.height - definitionSettings.paddingStart : definitionSettings.paddingStart + textRect.height;
    struct.dy = dock === 'top' ? -(textRect.height / 6) : -(textRect.height / 3);
    struct.maxWidth = rect.width * 0.8;
  } else {
    var y = rect.height / 2;

    if (definitionSettings.anchor === 'top') {
      y = definitionSettings.paddingStart;
    } else if (definitionSettings.anchor === 'bottom') {
      y = rect.height - definitionSettings.paddingStart;
    }

    struct.y = y;
    struct.x = dock === 'left' ? rect.width - definitionSettings.paddingStart : definitionSettings.paddingStart;
    struct.dx = dock === 'left' ? -(textRect.height / 3) : textRect.height / 3;
    var rotation = dock === 'left' ? 270 : 90;
    struct.transform = "rotate(".concat(rotation, ", ").concat(struct.x + struct.dx, ", ").concat(struct.y + struct.dy, ")");
    struct.maxWidth = rect.height * 0.8;
  }

  if (!isNaN(definitionSettings.maxLengthPx)) {
    struct.maxWidth = Math.min(struct.maxWidth, definitionSettings.maxLengthPx);
  }

  return struct;
}
/**
 * @typedef {object} component--text
 * @property {string} [type='text']
 * @property {string|function} text
 * @property {component--text-settings} settings - Text settings
 * @example
 * {
 *  type: 'text',
 *  text: 'my title',
 *  dock: 'left',
 *  settings: {
 *    anchor: 'left',
 *    style: {
 *      fill: 'red'
 *    }
 *  }
 * }
 */

/**
 * @typedef {object} component--text-settings
 * @property {number} [paddingStart=5]
 * @property {number} [paddingEnd=5]
 * @property {number} [paddingLeft=0]
 * @property {number} [paddingRight=0]
 * @property {string} [anchor='center'] - Where to v- or h-align the text. Supports `left`, `right`, `top`, `bottom` and `center`
 * @property {string} [join=', '] - String to add when joining titles from multiple sources
 * @property {number} [maxLengthPx] - Limit the text length to this value in pixels
 */


var textComponent = {
  require: ['renderer', 'chart'],
  defaultSettings: {
    layout: {
      dock: 'bottom',
      displayOrder: 0,
      prioOrder: 0
    },
    settings: {
      paddingStart: 5,
      paddingEnd: 5,
      paddingLeft: 0,
      paddingRight: 0,
      anchor: 'center',
      join: ', ',
      maxLengthPx: NaN
    },
    style: {
      text: '$title'
    }
  },
  created: function created() {
    this.definitionSettings = this.settings.settings;
    var text = this.settings.text;
    var join = this.definitionSettings.join;
    this.title = parseTitle(text, join, this.scale);
  },
  preferredSize: function preferredSize() {
    var height = this.renderer.measureText({
      text: this.title,
      fontSize: this.style.text.fontSize,
      fontFamily: this.style.text.fontFamily
    }).height;
    return height + this.definitionSettings.paddingStart + this.definitionSettings.paddingEnd;
  },
  render: function render() {
    var title = this.title,
        definitionSettings = this.definitionSettings,
        rect = this.rect;
    var nodes = [];
    nodes.push(generateTitle({
      title: title,
      dock: this.settings.layout.dock,
      definitionSettings: definitionSettings,
      rect: rect,
      measureText: this.renderer.measureText,
      style: this.style
    }));
    return nodes;
  },
  beforeUpdate: function beforeUpdate(opts) {
    if (opts.settings) {
      extend(this.settings, opts.settings);
      this.definitionSettings = opts.settings.settings;
    }

    var text = this.settings.text;
    var join = this.definitionSettings.join;
    this.title = parseTitle(text, join, this.scale);
  }
};

function picasso_esm_text(picasso) {
  picasso.component('text', textComponent);
}

/**
 * @typedef {object} component--scrollbar
 * @private
 */

/**
 * @typedef {object} component--scrollbar.settings
 * @property {boolean} [backgroundColor = '#eee']
 * @property {boolean} [thumbColor = '#ccc']
 * @property {boolean} [width = 16]
 */
function picasso_esm_start(_scrollbar, pos) {
  var dock = _scrollbar.settings.layout.dock;
  var invert = _scrollbar.settings.settings.invert;
  var horizontal = dock === 'top' || dock === 'bottom';
  var lengthAttr = horizontal ? 'width' : 'height';
  var length = _scrollbar.rect[lengthAttr];

  var scroll = _scrollbar.chart.scroll(_scrollbar.settings.scroll);

  var currentMove;
  {
    // local scope to allow reuse of variable names later
    var offset = pos[horizontal ? 'x' : 'y'];

    if (invert) {
      offset = length - offset;
    }

    var scrollState = scroll.getState();
    currentMove = {
      startOffset: offset,
      startScroll: scrollState.start,
      swipe: false
    }; // Detect swipe start outsize the thumb & change startScroll to jump the scroll there.

    var scrollPoint = offset / length * (scrollState.max - scrollState.min) + scrollState.min;

    if (scrollPoint < scrollState.start) {
      currentMove.startScroll = scrollPoint;
    } else if (scrollPoint > scrollState.start + scrollState.viewSize) {
      currentMove.startScroll = scrollPoint - scrollState.viewSize;
    }
  }

  var update = function update(p) {
    var offset = p[horizontal ? 'x' : 'y'];

    if (invert) {
      offset = length - offset;
    }

    if (!currentMove.swipe) {
      if (Math.abs(currentMove.startOffset - offset) <= 1) {
        return;
      }

      currentMove.swipe = true;
    }

    var scrollState = scroll.getState();
    var scrollMove = (offset - currentMove.startOffset) / length * (scrollState.max - scrollState.min);
    var scrollStart = currentMove.startScroll + scrollMove;
    scroll.moveTo(scrollStart);
  };

  var end = function end(p) {
    var offset = p[horizontal ? 'x' : 'y'];

    if (invert) {
      offset = length - offset;
    }

    var scrollState = scroll.getState();

    if (currentMove.swipe) {
      var scrollMove = (offset - currentMove.startOffset) / length * (scrollState.max - scrollState.min);
      var scrollStart = currentMove.startScroll + scrollMove;
      scroll.moveTo(scrollStart);
    } else {
      var scrollCenter = offset / length * (scrollState.max - scrollState.min) + scrollState.min;

      var _scrollStart = scrollCenter - scrollState.viewSize / 2;

      scroll.moveTo(_scrollStart);
    }
  };

  return {
    update: update,
    end: end
  };
}

function getLocalPos(event, renderer) {
  var containerRect = renderer.element().getBoundingClientRect();
  return {
    x: event.center.x - containerRect.left,
    y: event.center.y - containerRect.top
  };
}

var scrollbarComponent = {
  require: ['chart', 'renderer'],
  on: {
    panStart: function panStart(event) {
      var pos = getLocalPos(event, this.renderer);
      var startPos = {
        x: pos.x - event.deltaX,
        y: pos.y - event.deltaY
      };
      this.currentMove = picasso_esm_start(this, startPos);
      this.currentMove.update(pos);
    },
    panMove: function panMove(event) {
      if (!this.currentMove) {
        return;
      }

      var pos = getLocalPos(event, this.renderer);
      this.currentMove.update(pos);
    },
    panEnd: function panEnd(event) {
      if (!this.currentMove) {
        return;
      }

      var pos = getLocalPos(event, this.renderer);
      this.currentMove.end(pos);
      this.currentMove = null;
    },
    panCancel: function panCancel() {
      this.currentMove = null;
    },
    tap: function tap(event) {
      var pos = getLocalPos(event, this.renderer);
      var move = picasso_esm_start(this, pos);
      move.end(pos);
    }
  },
  defaultSettings: {
    settings: {
      backgroundColor: '#eee',
      thumbColor: '#ccc',
      width: 16 // 32 for touch

    }
  },
  preferredSize: function preferredSize(rect) {
    var scrollState = this.chart.scroll(this.settings.scroll).getState(); // hide the scrollbar if it is not possible to scroll

    if (scrollState.viewSize >= scrollState.max - scrollState.min) {
      var toLargeSize = Math.max(rect.width, rect.height);
      return toLargeSize;
    }

    return this.settings.settings.width;
  },
  render: function render(h) {
    var _style;

    var dock = this.settings.layout.dock;
    var invert = this.settings.settings.invert;
    var horizontal = dock === 'top' || dock === 'bottom';
    var lengthAttr = horizontal ? 'width' : 'height';
    var _rect = this.rect;
    var length = _rect[lengthAttr];
    var scrollState = this.chart.scroll(this.settings.scroll).getState();
    var thumbStart = length * (scrollState.start - scrollState.min) / (scrollState.max - scrollState.min);
    var thumbRange = length * scrollState.viewSize / (scrollState.max - scrollState.min);

    if (invert) {
      thumbStart = length - thumbStart - thumbRange;
    }

    return h('div', {
      style: {
        position: 'relative',
        width: '100%',
        height: '100%',
        background: this.settings.settings.backgroundColor,
        pointerEvents: 'auto'
      }
    }, [].concat(h('div', {
      class: 'scroller',
      style: (_style = {
        position: 'absolute'
      }, dist_picasso_esm_defineProperty(_style, horizontal ? 'left' : 'top', "".concat(thumbStart, "px")), dist_picasso_esm_defineProperty(_style, horizontal ? 'top' : 'left', '25%'), dist_picasso_esm_defineProperty(_style, horizontal ? 'height' : 'width', '50%'), dist_picasso_esm_defineProperty(_style, lengthAttr, "".concat(Math.max(1, thumbRange), "px")), dist_picasso_esm_defineProperty(_style, "background", this.settings.settings.thumbColor), _style)
    })));
  },
  renderer: 'dom'
};
function scrollbar(picasso) {
  picasso.component('scrollbar', scrollbarComponent);
}

var TARGET_SIZE = 5;
var VERTICAL = 0;
var HORIZONTAL = 1;

function buildLine$1(_ref) {
  var h = _ref.h,
      isVertical = _ref.isVertical,
      value = _ref.value,
      pos = _ref.pos,
      align = _ref.align,
      borderHit = _ref.borderHit,
      state = _ref.state,
      idx = _ref.idx;
  var isAlignStart = align !== 'end';
  var alignStart = {
    left: '0',
    top: '0'
  };
  var alignEnd = {
    right: '0',
    bottom: '0'
  };
  var alignStyle = isAlignStart ? alignStart : alignEnd;
  var start = 0;
  var width = '100%';
  var height = '100%';

  if (state.targetRect && state.settings.bubbles.align === 'start') {
    width = "".concat(state.targetRect.x + state.targetRect.width, "px");
    height = "".concat(state.targetRect.y + state.targetRect.height, "px");
  } else if (state.targetRect && state.settings.bubbles.align === 'end') {
    start = isVertical ? state.targetRect.x : state.targetRect.y;
    width = "".concat(state.rect.width - start, "px");
    height = "".concat(state.rect.height - start, "px");
  }

  if (!isAlignStart) {
    pos -= borderHit;
  } // edge


  return h('div', {
    onmouseover: function onmouseover(e) {
      e.srcElement.children[0].style.backgroundColor = '#000';
      e.srcElement.children[0].style[isVertical ? 'height' : 'width'] = '2px';
    },
    onmouseout: function onmouseout(e) {
      e.srcElement.children[0].style.backgroundColor = state.style.line.stroke;
      e.srcElement.children[0].style[isVertical ? 'height' : 'width'] = '1px';
    },
    'data-value': value,
    'data-key': [state.key, 'edge', idx].join('-'),
    style: {
      cursor: isVertical ? 'ns-resize' : 'ew-resize',
      position: 'absolute',
      left: isVertical ? "".concat(start, "px") : "".concat(pos, "px"),
      top: isVertical ? "".concat(pos, "px") : "".concat(start, "px"),
      height: isVertical ? "".concat(borderHit, "px") : height,
      width: isVertical ? width : "".concat(borderHit, "px"),
      pointerEvents: 'auto'
    }
  }, [// line
  h('div', {
    style: extend({
      backgroundColor: state.style.line.stroke,
      position: 'absolute',
      height: isVertical ? "".concat(1, "px") : '100%',
      width: isVertical ? '100%' : "".concat(1, "px"),
      pointerEvents: 'none'
    }, alignStyle)
  })]);
}

function buildBubble(_ref2) {
  var _style;

  var h = _ref2.h,
      isVertical = _ref2.isVertical,
      label = _ref2.label,
      otherValue = _ref2.otherValue,
      rangeIdx = _ref2.rangeIdx,
      idx = _ref2.idx,
      pos = _ref2.pos,
      align = _ref2.align,
      state = _ref2.state,
      value = _ref2.value;
  var isAlignStart = align !== 'end';
  var isOutside = state.settings.bubbles.placement === 'outside';
  var outside = 'none';
  var bubbleDock;

  if (isVertical) {
    bubbleDock = isAlignStart ? 'left' : 'right';

    if (isOutside) {
      outside = isAlignStart ? 'translate(-100%,  0px)' : 'translate(100%,  0px)';
    }
  } else {
    bubbleDock = isAlignStart ? 'top' : 'bottom';

    if (isOutside) {
      outside = isAlignStart ? 'translate(0px, -100%)' : 'translate(0px,  100%)';
    }
  }

  var inEdit = state.edit && state.edit.rangeIdx === rangeIdx && state.edit.bubbleIdx === idx;
  var bubbleStyle = {
    position: 'relative',
    borderRadius: "".concat(state.style.bubble.borderRadius, "px"),
    border: "".concat(state.style.bubble.strokeWidth, "px solid ").concat(state.style.bubble.stroke),
    backgroundColor: state.style.bubble.fill,
    color: state.style.bubble.color,
    fontFamily: state.style.bubble.fontFamily,
    fontSize: state.style.bubble.fontSize,
    padding: '4px 8px',
    textAlign: 'center',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
    maxWidth: '150px',
    minWidth: '50px',
    minHeight: '1em',
    pointerEvents: 'auto',
    transform: isVertical ? 'translate(0,-50%)' : 'translate(-50%,0)',
    cursor: isVertical ? 'ns-resize' : 'ew-resize'
  };
  var currentBorderColor = state.style.bubble.stroke;
  var bubble = inEdit ? h('input', {
    type: 'text',
    value: value,
    style: _objectSpread2({}, bubbleStyle, {
      textAlign: 'start',
      textOverflow: '',
      fontSize: '13px' // TODO - make it styleable

    }),
    onkeyup: function onkeyup(e) {
      if (e.key === 'Enter') {
        e.preventDefault();
        e.stopPropagation();
        var newValue = parseFloat(e.target.value);

        if (isNaN(newValue)) {
          currentBorderColor = 'rgba(230, 78, 78, 0.6)';
          e.target.style.border = "".concat(state.style.bubble.strokeWidth, "px solid ").concat(currentBorderColor);
        } else {
          state.onEditConfirmed(rangeIdx, newValue, otherValue);
        }
      } else if (e.key === 'Escape') {
        e.preventDefault();
        e.stopPropagation();
        state.onEditCanceled();
      }
    }
  }) : h('div', {
    'data-key': [state.key, 'bubble', rangeIdx].join('-'),
    'data-other-value': otherValue,
    'data-idx': rangeIdx,
    'data-bidx': idx,
    style: bubbleStyle
  }, [label]); // bubble wrapper

  return h('div', {
    style: (_style = {
      position: 'absolute'
    }, dist_picasso_esm_defineProperty(_style, bubbleDock, '0'), dist_picasso_esm_defineProperty(_style, isVertical ? 'top' : 'left', "".concat(pos, "px")), dist_picasso_esm_defineProperty(_style, "transform", outside), _style)
  }, [// bubble
  bubble]);
}

function buildArea(_ref3) {
  var h = _ref3.h,
      isVertical = _ref3.isVertical,
      top = _ref3.top,
      height = _ref3.height,
      color = _ref3.color,
      on = _ref3.on,
      opacity = _ref3.opacity;
  return h('div', extend({
    style: {
      backgroundColor: color,
      opacity: opacity,
      position: 'absolute',
      left: isVertical ? 0 : "".concat(top, "px"),
      top: isVertical ? "".concat(top, "px") : 0,
      height: isVertical ? "".concat(height, "px") : '100%',
      width: isVertical ? '100%' : "".concat(height, "px"),
      pointerEvents: 'auto'
    }
  }, on), []);
}

function buildRange(_ref4) {
  var borderHit = _ref4.borderHit,
      els = _ref4.els,
      isVertical = _ref4.isVertical,
      state = _ref4.state,
      vStart = _ref4.vStart,
      vEnd = _ref4.vEnd,
      idx = _ref4.idx;
  var targetOffset = 0;

  if (state.targetRect) {
    targetOffset = isVertical ? state.targetRect.y : state.targetRect.x;
  }

  var hasScale = !!state.scale;
  var start = hasScale ? state.scale.norm(vStart) * state.size : vStart;
  var end = hasScale ? state.scale.norm(vEnd) * state.size : vEnd;
  var height = Math.abs(start - end);
  var top = Math.min(start, end) + targetOffset;
  var bottom = top + height;

  if (state.targetRect) {
    var target = state.targetFillRect || state.targetRect;
    var targetSize = isVertical ? target.height : target.width;
    var targetStart = hasScale ? state.scale.norm(vStart) * targetSize : vStart;
    var targetEnd = hasScale ? state.scale.norm(vEnd) * targetSize : vEnd;
    var targetHeight = Math.abs(targetStart - targetEnd);
    var targetTop = Math.min(targetStart, targetEnd);
    var targetArea = {
      h: state.h,
      isVertical: isVertical,
      top: targetTop,
      height: targetHeight,
      color: state.style.target.fill,
      opacity: state.style.target.opacity
    };

    if (state.style.target.opacity < 0.8) {
      targetArea.on = {
        onmouseover: function onmouseover(e) {
          e.srcElement.style.opacity = state.style.target.opacity + 0.1;
        },
        onmouseout: function onmouseout(e) {
          e.srcElement.style.opacity = state.style.target.opacity;
        }
      };
    }

    els.push(state.h('div', {
      style: {
        position: 'absolute',
        left: "".concat(target.x, "px"),
        top: "".concat(target.y, "px"),
        height: "".concat(target.height, "px"),
        width: "".concat(target.width, "px")
      }
    }, [buildArea(targetArea)]));
  } // active range area
  // els.push(buildArea({
  //   h: state.h,
  //   isVertical,
  //   top,
  //   height,
  //   color: state.settings.fill
  // }));


  var valStart = start < end ? vStart : vEnd;
  var valEnd = start < end ? vEnd : vStart;

  var _ref5 = hasScale ? state.scale.domain() : [Math.min(vStart, vEnd), Math.max(vStart, vEnd)],
      _ref6 = picasso_esm_slicedToArray(_ref5, 2),
      min = _ref6[0],
      max = _ref6[1];

  var isStartVisible = valStart + 1e-5 >= min && valStart - 1e-5 <= max; // accept minor floating point difference

  var isEndVisible = valEnd - 1e-5 <= max && valEnd + 1e-5 >= min;

  if (isStartVisible) {
    els.push(buildLine$1({
      h: state.h,
      isVertical: isVertical,
      borderHit: borderHit,
      value: valStart,
      pos: top,
      align: 'start',
      state: state,
      idx: idx
    }));
  }

  if (isEndVisible) {
    els.push(buildLine$1({
      h: state.h,
      isVertical: isVertical,
      borderHit: borderHit,
      value: valEnd,
      pos: bottom,
      align: 'end',
      state: state,
      idx: idx
    }));
  }

  var bubbles = state.settings.bubbles;

  if (bubbles && bubbles.show) {
    var fontSize = bubbles.fontSize;
    var fontFamily = bubbles.fontFamily;
    var fill = bubbles.fill;
    var style = {
      fontSize: fontSize,
      fontFamily: fontFamily,
      color: fill
    };
    var range = [vStart, vEnd];

    if (isStartVisible) {
      els.push(buildBubble({
        h: state.h,
        isVertical: isVertical,
        align: bubbles.align,
        style: style,
        rangeIdx: idx,
        idx: 0,
        otherValue: valEnd,
        value: valStart,
        label: "".concat(state.format(valStart, range)),
        pos: top,
        state: state
      }));
    }

    if (isEndVisible) {
      els.push(buildBubble({
        h: state.h,
        isVertical: isVertical,
        align: bubbles.align,
        style: style,
        rangeIdx: idx,
        idx: 1,
        otherValue: valStart,
        value: valEnd,
        label: "".concat(state.format(valEnd, range)),
        pos: bottom,
        state: state
      }));
    }
  }
}
function getMoveDelta(state) {
  var posDelta = state.active.limitHigh - state.active.end;
  var negDelta = state.active.limitLow - state.active.start;
  var delta = state.current - state.start;

  if (delta < 0) {
    delta = Math.max(delta, negDelta);
  } else {
    delta = Math.min(delta, posDelta);
  }

  return delta;
}
function nodes(state) {
  var els = [];
  var isVertical = state.direction === VERTICAL;

  if (Array.isArray(state.ranges)) {
    // add all other ranges
    state.ranges.forEach(function (r, i) {
      if (!state.active || i !== state.active.idx) {
        buildRange({
          borderHit: TARGET_SIZE,
          els: els,
          isVertical: isVertical,
          state: state,
          vStart: Math.min(r.min, r.max),
          vEnd: Math.max(r.min, r.max),
          idx: i
        });
      }
    });
  }

  if (state.active) {
    // add active range
    var vStart = state.start;
    var vEnd = state.current;

    if (state.active.idx !== -1) {
      if (state.active.mode === 'foo') {
        vStart = Math.min(state.active.start, state.active.end);
        vEnd = Math.max(state.active.start, state.active.end);
      } else if (state.active.mode === 'modify') {
        vStart = Math.min(state.start, state.current);
        vEnd = Math.max(state.start, state.current);
      } else {
        var delta = getMoveDelta(state);
        vStart = state.active.start + delta;
        vEnd = state.active.end + delta;
      }
    }

    buildRange({
      borderHit: TARGET_SIZE,
      els: els,
      isVertical: isVertical,
      state: state,
      vStart: vStart,
      vEnd: vEnd,
      idx: state.active.idx
    });
  }

  return els;
}

function rangelimits(state) {
  return {
    min: state.scale.min(),
    max: state.scale.max()
  };
}

function areaLimits(state) {
  return {
    min: 0,
    max: state.direction ? state.rect.width : state.rect.height
  };
}

function findActive(state, value, limits) {
  var rs = state.ranges;
  var i;
  var activeIdx = -1;

  for (i = 0; i < rs.length; i++) {
    if (rs[i].min <= value && value <= rs[i].max) {
      activeIdx = i;
      limits.min = i ? rs[i - 1].max : limits.min;
      limits.max = i + 1 < rs.length ? rs[i + 1].min : limits.max;
      break;
    } else if (value < rs[i].min) {
      limits.max = rs[i].min;
      limits.min = i ? rs[i - 1].max : limits.min;
      break;
    }
  }

  if (activeIdx === -1 && rs.length && i >= rs.length) {
    limits.min = rs[rs.length - 1].max;
  }

  var activeRange;

  if (activeIdx !== -1) {
    activeRange = {
      idx: activeIdx,
      start: rs[activeIdx].min,
      end: rs[activeIdx].max,
      limitLow: limits.min,
      limitHigh: limits.max,
      mode: 'foo'
    };
  }

  state.active = activeRange;
}

function startArea(_ref) {
  var state = _ref.state,
      e = _ref.e,
      renderer = _ref.renderer,
      ranges = _ref.ranges,
      targetSize = _ref.targetSize;

  if (state.started) {
    return;
  }

  var x = e.center.x - e.deltaX;
  var y = e.center.y - e.deltaY;
  var target = document.elementFromPoint(x, y);

  if (!renderer.element().contains(target)) {
    target = null;
  }

  var tempState = {
    started: true
  };
  state.offset = renderer.element().getBoundingClientRect();
  state.ranges = ranges(state);
  var relX = x - state.offset.left; // coordinate relative renderer

  var relY = y - state.offset.top;
  var startPoint = e.center[state.cssCoord.coord] - e[state.cssCoord.pos] - state.offset[state.cssCoord.offset];
  var relStart = e.center[state.cssCoord.coord] - state.offset[state.cssCoord.offset];
  var v = relStart;
  var vStart = startPoint;
  tempState.start = startPoint;
  tempState.current = relStart;
  var rs = state.ranges;
  var limits = areaLimits(state);
  var i;
  var activeIdx = -1;

  if (target && target.hasAttribute('data-idx')) {
    activeIdx = parseInt(target.getAttribute('data-idx'), 10);
    limits.min = activeIdx > 0 ? rs[activeIdx - 1].max : limits.min;
    limits.max = activeIdx + 1 < rs.length ? rs[activeIdx + 1].min : limits.max;
  } else {
    for (i = 0; i < rs.length; i++) {
      if (rs[i].min <= vStart && vStart <= rs[i].max) {
        activeIdx = i;
        limits.min = i ? rs[i - 1].max : limits.min;
        limits.max = i + 1 < rs.length ? rs[i + 1].min : limits.max;
        break;
      } else if (vStart < rs[i].min) {
        limits.max = rs[i].min;
        limits.min = i ? rs[i - 1].max : limits.min;
        break;
      }
    }

    if (activeIdx === -1 && rs.length && i >= rs.length) {
      limits.min = rs[rs.length - 1].max;
    }
  }

  if (activeIdx === -1 && !state.multi) {
    tempState.ranges = [];
    limits.min = 0;
    limits.max = state.direction ? state.rect.width : state.rect.height;
  }

  var activeRange;

  if (activeIdx !== -1) {
    activeRange = {
      idx: activeIdx,
      start: rs[activeIdx].min,
      end: rs[activeIdx].max,
      limitLow: limits.min,
      limitHigh: limits.max,
      mode: 'move'
    };

    if (target && target.hasAttribute('data-other-value')) {
      tempState.start = parseFloat(target.getAttribute('data-other-value'));
      activeRange.mode = 'modify';
    } else {
      var pxStart = activeRange.start;
      var pxEnd = activeRange.end;

      if (Math.abs(startPoint - pxStart) <= targetSize) {
        tempState.start = activeRange.end;
        activeRange.mode = 'modify';
      } else if (Math.abs(startPoint - pxEnd) <= targetSize) {
        tempState.start = activeRange.start;
        activeRange.mode = 'modify';
      }
    }
  } else {
    activeRange = {
      idx: -1,
      start: vStart,
      end: v,
      limitLow: limits.min,
      limitHigh: limits.max,
      mode: 'current'
    };
  }

  tempState.active = activeRange;

  if (activeRange.mode !== 'modify' && state.targetRect && !testRectPoint(state.targetRect, {
    x: relX,
    y: relY
  })) ; else {
    Object.keys(tempState).forEach(function (key) {
      return state[key] = tempState[key];
    });
  }
}
function start$1(_ref2) {
  var state = _ref2.state,
      e = _ref2.e,
      renderer = _ref2.renderer,
      ranges = _ref2.ranges,
      targetSize = _ref2.targetSize;

  if (state.started) {
    return;
  }

  state.edit = null;
  var x = e.center.x - e.deltaX;
  var y = e.center.y - e.deltaY;
  var target = document.elementFromPoint(x, y);

  if (!renderer.element().contains(target)) {
    target = null;
  }

  var tempState = {
    started: true
  };
  state.offset = extend({}, renderer.element().getBoundingClientRect());
  var relX = x - state.offset.left; // coordinate relative renderer

  var relY = y - state.offset.top;
  state.offset.left += state.targetRect ? state.targetRect.x : 0; // make offset relative to targetRect

  state.offset.top += state.targetRect ? state.targetRect.y : 0;
  state.ranges = ranges(state, state.fauxBrushInstance || state.brushInstance);
  var startPoint = e.center[state.cssCoord.coord] - e[state.cssCoord.pos] - state.offset[state.cssCoord.offset];
  var relStart = e.center[state.cssCoord.coord] - state.offset[state.cssCoord.offset];
  tempState.current = state.scale.normInvert(relStart / state.size);
  tempState.start = state.scale.normInvert(startPoint / state.size);
  var rs = state.ranges;
  var limits = rangelimits(state);
  var i;
  var activeIdx = -1;

  if (target && target.hasAttribute('data-idx')) {
    activeIdx = parseInt(target.getAttribute('data-idx'), 10);
    limits.min = activeIdx > 0 ? rs[activeIdx - 1].max : limits.min;
    limits.max = activeIdx + 1 < rs.length ? rs[activeIdx + 1].min : limits.max;
  } else {
    for (i = 0; i < rs.length; i++) {
      if (rs[i].min <= tempState.start && tempState.start <= rs[i].max) {
        activeIdx = i;
        limits.min = i ? rs[i - 1].max : limits.min;
        limits.max = i + 1 < rs.length ? rs[i + 1].min : limits.max;
        break;
      } else if (tempState.start < rs[i].min) {
        limits.max = rs[i].min;
        limits.min = i ? rs[i - 1].max : limits.min;
        break;
      }
    }

    if (activeIdx === -1 && rs.length && i >= rs.length) {
      limits.min = rs[rs.length - 1].max;
    }
  }

  if (activeIdx === -1 && !state.multi) {
    tempState.ranges = [];
    limits.min = state.scale.min();
    limits.max = state.scale.max();
  }

  var activeRange;

  if (activeIdx !== -1) {
    activeRange = {
      idx: activeIdx,
      start: rs[activeIdx].min,
      end: rs[activeIdx].max,
      limitLow: limits.min,
      limitHigh: limits.max,
      mode: 'move'
    };

    if (target && target.hasAttribute('data-other-value')) {
      tempState.start = parseFloat(target.getAttribute('data-other-value'));
      activeRange.mode = 'modify';
    } else {
      var pxStart = state.scale.norm(activeRange.start) * state.size;
      var pxEnd = state.scale.norm(activeRange.end) * state.size;

      if (Math.abs(startPoint - pxStart) <= targetSize) {
        tempState.start = activeRange.end;
        activeRange.mode = 'modify';
      } else if (Math.abs(startPoint - pxEnd) <= targetSize) {
        tempState.start = activeRange.start;
        activeRange.mode = 'modify';
      }
    }
  } else {
    activeRange = {
      idx: -1,
      start: tempState.start,
      end: tempState.current,
      limitLow: limits.min,
      limitHigh: limits.max,
      mode: 'current'
    };
  }

  tempState.active = activeRange;

  if (activeRange.mode !== 'modify' && state.targetRect && !testRectPoint(state.targetRect, {
    x: relX,
    y: relY
  })) ; else {
    Object.keys(tempState).forEach(function (key) {
      return state[key] = tempState[key];
    });
  }
}
function picasso_esm_end(state, ranges) {
  state.started = false;
  state.ranges = ranges(state, state.fauxBrushInstance || state.brushInstance);
  var limits = rangelimits(state);
  findActive(state, state.current, limits);
}
function endArea(state, ranges) {
  state.started = false;
  state.ranges = ranges(state);
  var limits = areaLimits(state);
  findActive(state, state.current, limits);
}
function move(state, e) {
  var relY = e.center[state.cssCoord.coord] - state.offset[state.cssCoord.offset];
  var rel = relY / state.size;
  var v = state.scale.normInvert(rel);
  state.current = Math.max(Math.min(v, state.active.limitHigh), state.active.limitLow);
}
function moveArea(state, e) {
  var rel = e.center[state.cssCoord.coord] - state.offset[state.cssCoord.offset];
  state.current = Math.max(Math.min(rel, state.active.limitHigh), state.active.limitLow);
}

function _render(state) {
  state.renderer.render(nodes(state));
}

function ranges(state, brush) {
  if (!brush || !brush.isActive()) {
    return [];
  }

  var sourceData = state.scale.data();
  var sourceFields = sourceData ? sourceData.fields || [] : [];
  var sources = sourceFields.map(function (field) {
    return field.id();
  });
  var rangeBrush = brush.brushes().filter(function (f) {
    return f.type === 'range' && sources.indexOf(f.id) !== -1;
  })[0];

  if (!rangeBrush) {
    return [];
  }

  return rangeBrush.brush.ranges();
}

function setRanges(state) {
  var rs = state.ranges.map(function (r) {
    return {
      min: r.min,
      max: r.max
    };
  });

  if (state.active.idx !== -1) {
    if (state.active.mode === 'modify') {
      rs[state.active.idx].min = Math.min(state.start, state.current);
      rs[state.active.idx].max = Math.max(state.start, state.current);
    } else {
      var delta = getMoveDelta(state);
      rs[state.active.idx].min += delta;
      rs[state.active.idx].max += delta;
    }
  } else {
    rs.push({
      min: Math.min(state.start, state.current),
      max: Math.max(state.start, state.current)
    });
  }

  var scaleData = state.scale.data();

  if (scaleData && scaleData.fields) {
    scaleData.fields.forEach(function (field) {
      if (state.fauxBrushInstance) {
        var ordRS = ranges(state, state.fauxBrushInstance);
        var oldValues = state.findValues(ordRS);
        var values = state.findValues(rs);
        var addedValues = values.filter(function (v) {
          return oldValues.indexOf(v) === -1;
        });
        var removedValues = oldValues.filter(function (v) {
          return values.indexOf(v) === -1;
        });
        var addItems = addedValues.map(function (v) {
          return {
            key: field.id(),
            value: v
          };
        });
        var removeItems = removedValues.map(function (v) {
          return {
            key: field.id(),
            value: v
          };
        });
        state.brushInstance.addAndRemoveValues(addItems, removeItems);
        state.fauxBrushInstance.setRange(field.id(), rs);
      } else {
        state.brushInstance.setRange(field.id(), rs);
      }
    });
  }
}

function setEditedRanges(state, idx, startValue, endValue) {
  var rs = state.ranges.map(function (r) {
    return {
      min: r.min,
      max: r.max
    };
  });
  var limitMin = state.scale.min();
  var limitMax = state.scale.max();
  rs[idx] = {
    min: Math.max(limitMin, Math.min(startValue, endValue)),
    max: Math.min(limitMax, Math.max(startValue, endValue))
  };
  state.ranges[idx] = _objectSpread2({}, rs[idx]);
  var scaleData = state.scale.data();

  if (scaleData && scaleData.fields) {
    scaleData.fields.forEach(function (field) {
      if (!state.fauxBrushInstance) {
        state.brushInstance.setRange(field.id(), rs);
      }
    });
  }
}

function picasso_esm_findClosest(value, scale) {
  var name;
  var minDist = Infinity;
  var domain = scale.domain();
  var halfBandwidth = scale.bandwidth() / 2;

  for (var i = 0; i < domain.length; ++i) {
    var d = Math.abs(value - halfBandwidth - scale(domain[i]));

    if (d < minDist) {
      minDist = d;
      name = domain[i];
    }
  }

  return name;
}

function findClosestLabel(value, scale) {
  var ticks = scale.ticks();
  var idx = scale.domain().indexOf(picasso_esm_findClosest(value, scale));
  return idx !== -1 ? ticks[idx].label : '-';
}

function rangesOverlap(r1, r2) {
  return Math.min.apply(Math, _toConsumableArray$1(r1)) <= Math.max.apply(Math, _toConsumableArray$1(r2)) && Math.max.apply(Math, _toConsumableArray$1(r1)) >= Math.min.apply(Math, _toConsumableArray$1(r2));
}

function findValues(rangesValues, scale) {
  var domain = scale.domain();
  var scaleRange = scale.range();
  var values = [];
  rangesValues.forEach(function (range) {
    if (!rangesOverlap(scaleRange, [range.min, range.max])) {
      return;
    }

    var startIdx = domain.indexOf(picasso_esm_findClosest(range.min, scale));
    var endIdx = domain.indexOf(picasso_esm_findClosest(range.max, scale));
    values.push.apply(values, domain.slice(Math.min(startIdx, endIdx), Math.max(startIdx, endIdx) + 1));
    /* eslint prefer-spread:0 */
  });
  return values;
}

function resolveNodeBounds(targetNodes) {
  var points = targetNodes.reduce(function (ary, node) {
    ary.push.apply(ary, _toConsumableArray$1(rectToPoints(node.bounds)));
    return ary;
  }, []);
  return pointsToRect(points);
}

function resolveTarget(ctx) {
  var resolved = {
    targetRect: null,
    targetFillRect: null,
    scale: null,
    size: null
  };
  var stngs = ctx.settings.settings;
  var targets = stngs.target && (stngs.target.components || (stngs.target.component ? [stngs.target.component] : [])).map(function (c) {
    return ctx.chart.component(c);
  }).filter(function (c) {
    return !!c && !!c.rect;
  });
  var targetNodes = stngs.target && stngs.target.selector ? ctx.chart.findShapes(stngs.target.selector) : [];
  var targetFillNodes = stngs.target && stngs.target.fillSelector ? ctx.chart.findShapes(stngs.target.fillSelector) : [];

  if (targetNodes.length > 0) {
    var bounds = resolveNodeBounds(targetNodes);
    resolved.size = bounds[ctx.state.direction === VERTICAL ? 'height' : 'width'];
    resolved.scale = scaleWithSize(ctx.chart.scale(stngs.scale), resolved.size);
    resolved.targetRect = bounds;

    if (targetFillNodes.length > 0) {
      var fillBounds = resolveNodeBounds(targetFillNodes);
      resolved.targetFillRect = fillBounds;
    }
  } else if (targets && targets.length > 0) {
    var targetRect = targets.slice(1).reduce(function (prev, curr) {
      return {
        x0: Math.min(prev.x0, curr.rect.computedInner.x),
        y0: Math.min(prev.y0, curr.rect.computedInner.y),
        x1: Math.max(prev.x1, curr.rect.computedInner.x + curr.rect.computedInner.width),
        y1: Math.max(prev.y1, curr.rect.computedInner.y + curr.rect.computedInner.height)
      };
    }, {
      x0: targets[0].rect.computedInner.x,
      y0: targets[0].rect.computedInner.y,
      x1: targets[0].rect.computedInner.x + targets[0].rect.computedInner.width,
      y1: targets[0].rect.computedInner.y + targets[0].rect.computedInner.height
    });
    resolved.targetRect = {
      x: targetRect.x0 - ctx.state.rect.x,
      y: targetRect.y0 - ctx.state.rect.y,
      width: targetRect.x1 - targetRect.x0,
      height: targetRect.y1 - targetRect.y0
    };
  }

  return resolved;
}
/**
 * @typedef {object} component--brush-range-settings
 * @property {string|object} brush - Brush context to apply changes to
 * @property {string} scale - Scale to extract data from
 * @property {string} [direction=vertical] - Rendering direction [horizontal|vertical]
 * @property {object} [bubbles]
 * @property {boolean} [bubbles.show=true] - True to show label bubble, false otherwise
 * @property {string} [bubbles.align=start] - Where to anchor bubble [start|end]
 * @property {function} [bubbles.label] - Callback function for the labels
 * @property {object} [target]
 * @property {string} [target.component] - Render matching overlay on target component. @deprecated Use `components` instead
 * @property {string[]} [target.components] - Render matching overlay on target components
 * @property {string} [target.selector] - Instead of targeting a component, target one or more shapes
 * @property {string} [target.fillSelector] - Target a subset of the selector as fill area. Only applicable if `selector` property is set
 */

/**
 * @typedef {object} component--brush-range-style
 * @property {object} [bubble]
 * @property {string} [bubble.fontSize]
 * @property {string} [bubble.fontFamily]
 * @property {string} [bubble.fill]
 * @property {string} [bubble.color]
 * @property {string} [bubble.stroke]
 * @property {number} [bubble.strokeWidth]
 * @property {number} [bubble.borderRadius]
 * @property {object} [line]
 * @property {string} [line.stroke]
 * @property {number} [line.strokeWidth]
 * @property {object} [target]
 * @property {string} [target.fill]
 * @property {number} [target.strokeWidth]
 * @property {number} [target.opacity]
 */


var brushRangeComponent = {
  require: ['chart', 'settings', 'renderer'],
  defaultSettings: {
    settings: {
      bubbles: {
        show: true,
        align: 'start'
      }
    },
    style: {
      bubble: '$label-overlay',
      line: '$shape-guide--inverted',
      target: '$selection-area-target'
    }
  },
  renderer: 'dom',
  on: {
    rangeStart: function rangeStart(e) {
      this.start(e);
    },
    rangeMove: function rangeMove(e) {
      this.move(e);
    },
    rangeEnd: function rangeEnd(e) {
      this.end(e);
    },
    rangeClear: function rangeClear(e) {
      this.clear(e);
    },
    bubbleStart: function bubbleStart(e) {
      this.bubbleStart(e);
    }
  },
  created: function created() {
    this.state = {
      key: this.settings.key || 'brush-range'
    };
  },
  beforeRender: function beforeRender(opts) {
    this.state.rect = opts.size.computedInner;
  },
  renderRanges: function renderRanges() {
    if (!this.state.started) {
      this.state.ranges = ranges(this.state, this.state.brushInstance);
      this.state.active = null;

      _render(this.state);
    }
  },
  render: function render(h) {
    var _this = this;

    var stngs = this.settings.settings;
    this.state.direction = stngs.direction === 'vertical' ? VERTICAL : HORIZONTAL;
    var offset = this.renderer.element().getBoundingClientRect();
    var size = this.state.rect[this.state.direction === VERTICAL ? 'height' : 'width'];
    var scale = scaleWithSize(this.chart.scale(stngs.scale), size);
    var target = resolveTarget(this);
    scale = target.scale ? target.scale : scale;
    this.state.targetRect = target.targetRect;
    this.state.targetFillRect = target.targetFillRect;
    this.state.size = target.size === null ? size : target.size;
    this.state.settings = stngs;
    this.state.style = this.style;
    this.state.offset = offset;
    this.state.brush = _typeof(stngs.brush) === 'object' ? stngs.brush.context : stngs.brush;
    this.state.brushInstance = this.chart.brush(this.state.brush);
    this.state.renderer = this.renderer;
    this.state.multi = !!stngs.multiple;
    this.state.h = h;

    this.state.onEditConfirmed = function (rangeIdx, value, otherValue) {
      _this.state.edit = null;
      setEditedRanges(_this.state, rangeIdx, value, otherValue);

      _this.emit('bubbleEnd');

      _render(_this.state);
    };

    this.state.onEditCanceled = function () {
      _this.state.edit = null;

      _render(_this.state);
    };

    this.state.cssCoord = {
      offset: this.state.direction === VERTICAL ? 'top' : 'left',
      coord: this.state.direction === VERTICAL ? 'y' : 'x',
      pos: this.state.direction === VERTICAL ? 'deltaY' : 'deltaX'
    };
    this.state.format = typeof stngs.bubbles.label === 'function' ? function (v, r) {
      return stngs.bubbles.label.call(undefined, {
        datum: v,
        data: r,
        scale: scale,
        resources: {
          scale: _this.chart.scale,
          formatter: _this.chart.formatter
        }
      });
    } : false;

    if (!{}.hasOwnProperty.call(scale, 'norm')) {
      // Non-linear scale if norm method is unavailable
      this.state.editable = false;
      this.state.scale = scaleLinear();
      this.state.scale.data = scale.data;

      if (!this.state.format) {
        this.state.format = function (v, r) {
          if (!rangesOverlap(scale.range(), r)) {
            return '-';
          }

          return findClosestLabel(v, scale);
        };
      }

      this.state.fauxBrushInstance = brush();

      this.state.findValues = function (valueRanges) {
        return findValues(valueRanges, scale);
      };
    } else {
      this.state.editable = true;
      this.state.observeBrush = _typeof(stngs.brush) === 'object' ? stngs.brush.observe : false;
      this.state.fauxBrushInstance = null;
      this.state.findValues = null;
      this.state.scale = scale;
      var scaleData = this.state.scale.data();

      if (!this.state.format && scaleData && scaleData.fields && scaleData.fields[0]) {
        this.state.format = scaleData.fields[0].formatter();
      }
    }

    this.state.ranges = ranges(this.state, this.state.brushInstance);
    return this.state.observeBrush || this.state.sourcedFromThisComponent ? [nodes(this.state)] : [];
  },
  mounted: function mounted() {
    if (this.state.observeBrush && this.state.brushInstance) {
      this.state.brushInstance.on('update', this.renderRanges);
    }
  },
  beforeDestroy: function beforeDestroy() {
    if (this.state.observeBrush && this.state.brushInstance) {
      this.state.brushInstance.removeListener('update', this.renderRanges);
    }
  },
  start: function start(e) {
    start$1({
      e: e,
      state: this.state,
      renderer: this.renderer,
      ranges: ranges,
      targetSize: TARGET_SIZE
    });
  },
  end: function end$1() {
    if (!this.state.started) {
      return;
    }

    picasso_esm_end(this.state, ranges);

    _render(this.state);

    this.state.sourcedFromThisComponent = true;
    this.state.active = null;
  },
  move: function move$1(e) {
    if (!this.state.started) {
      return;
    }

    move(this.state, e);

    setRanges(this.state);

    _render(this.state);
  },
  clear: function clear() {
    if (this.state.fauxBrushInstance) {
      this.state.fauxBrushInstance.clear();
    }

    this.state.renderer.render([]);
    this.state.started = false;
    this.state.active = null;
    this.state.sourcedFromThisComponent = false;
  },
  bubbleStart: function bubbleStart(e) {
    if (!this.state.editable) {
      return;
    }

    var ee = e.srcEvent || e;
    var target = ee.target;
    var ed = {
      rangeIdx: parseInt(target.getAttribute('data-idx'), 10),
      bubbleIdx: parseInt(target.getAttribute('data-bidx'), 10)
    };

    if (isNaN(ed.rangeIdx) || JSON.stringify(ed) === JSON.stringify(this.state.edit)) {
      return;
    }

    this.state.edit = ed;
    ee.stopPropagation();
    ee.stopImmediatePropagation();
    ee.preventDefault();
    var wrapper = target.parentNode;

    _render(this.state);

    var inputEl = wrapper.querySelector('input');
    inputEl.focus();
    inputEl.select();
  }
};

function picasso_esm_render(state) {
  state.renderer.render(nodes(state));
}

function ranges$1(state) {
  return state.rc.ranges();
}

function shapesFromRange(state, brushRange) {
  var shapeAt = {
    x: state.direction ? brushRange.min + state.rect.x : state.rect.x,
    y: state.direction ? state.rect.y : brushRange.min + state.rect.y,
    width: state.direction ? brushRange.max - brushRange.min : state.rect.width + state.rect.x,
    height: state.direction ? state.rect.height + state.rect.y : brushRange.max - brushRange.min
  };
  return state.chart.shapesAt(shapeAt, state.settings.brush);
}

function brushFromShape(state, newShapes) {
  state.chart.brushFromShapes(newShapes, state.settings.brush);
}

function setRanges$1(state) {
  var rs = state.ranges.map(function (r) {
    return {
      min: r.min,
      max: r.max
    };
  });

  if (state.active.idx !== -1) {
    if (state.active.mode === 'modify') {
      rs[state.active.idx].min = Math.min(state.start, state.current);
      rs[state.active.idx].max = Math.max(state.start, state.current);
    } else {
      var delta = getMoveDelta(state);
      rs[state.active.idx].min = state.active.start + delta;
      rs[state.active.idx].max = state.active.end + delta;
    }
  } else {
    rs.push({
      min: Math.min(state.start, state.current),
      max: Math.max(state.start, state.current)
    });
  }

  state.rc.set(rs);
  var shapes = [];
  rs.forEach(function (range) {
    shapes.push.apply(shapes, _toConsumableArray$1(shapesFromRange(state, range)));
  });
  brushFromShape(state, shapes);
}

function getBubbleLabel(state, value, range) {
  var min = Math.min.apply(Math, _toConsumableArray$1(range));
  var max = Math.max.apply(Math, _toConsumableArray$1(range));
  var shapeAt = {
    x: state.direction ? min + state.rect.x : state.rect.x,
    y: state.direction ? state.rect.y : min + state.rect.y,
    width: state.direction ? max - min : state.rect.width + state.rect.x,
    height: state.direction ? state.rect.height + state.rect.y : max - min
  };
  var shapes = state.chart.shapesAt(shapeAt, state.settings.brush);

  if (shapes.length === 0) {
    return '-';
  }

  var labelShape = shapes.reduce(function (s0, s1) {
    // Min value
    var bounds0 = s0.bounds;
    var bounds1 = s1.bounds;

    if (value === min) {
      if (bounds0[state.cssCoord.coord] <= bounds1[state.cssCoord.coord]) {
        return s0;
      }

      return s1;
    } // Max value


    if (bounds0[state.cssCoord.coord] + bounds0[state.cssCoord.area] >= bounds1[state.cssCoord.coord] + bounds1[state.cssCoord.area]) {
      return s0;
    }

    return s1;
  });
  var compConfig = state.settings.brush.components.reduce(function (c0, c1) {
    return c0.key === labelShape.key ? c0 : c1;
  });

  if (typeof state.settings.bubbles.label === 'function') {
    return state.settings.bubbles.label(labelShape.data);
  }

  if (Array.isArray(compConfig.data) && compConfig.data.length) {
    return labelShape.data[compConfig.data[0]].label;
  }

  return labelShape.data && labelShape.data.label ? labelShape.data.label : '-';
}
/**
 * @typedef {object} component--brush-area-dir-settings
 * @property {object} brush
 * @property {array} brush.components
 * @property {object} brush.components[].key - Component key
 * @property {object} brush.components[].contexts[] - Brush context to apply changes to
 * @property {object} [brush.components[].data] - Data reference
 * @property {object} [brush.components[].action] - Type of brush action
 * @property {string} [direction=vertical] - Rendering direction [horizontal|vertical]
 * @property {object} [bubbles]
 * @property {boolean} [bubbles.show=true] - True to show label bubble, false otherwise
 * @property {string} [bubbles.align=start] - Where to anchor bubble [start|end]
 * @property {function} [bubbles.label] - Callback function for the labels
 * @property {object} [target]
 * @property {string} [target.component] - Render matching overlay on target component. @deprecated Use `components` instead
 * @property {string[]} [target.components] - Render matching overlay on target components
 */

/**
 * @typedef {object} component--brush-area-dir-style
 * @property {object} [bubble]
 * @property {string} [bubble.fontSize]
 * @property {string} [bubble.fontFamily]
 * @property {string} [bubble.fill]
 * @property {string} [bubble.color]
 * @property {string} [bubble.stroke]
 * @property {number} [bubble.strokeWidth]
 * @property {number} [bubble.borderRadius]
 * @property {object} [line]
 * @property {string} [line.stroke]
 * @property {number} [line.strokeWidth]
 * @property {object} [target]
 * @property {string} [target.fill]
 * @property {number} [target.strokeWidth]
 * @property {number} [target.opacity]
 */


var brushAreaDirectionalComponent = {
  require: ['chart', 'settings', 'renderer'],
  defaultSettings: {
    settings: {
      bubbles: {
        show: true,
        align: 'start'
      }
    },
    style: {
      bubble: '$label-overlay',
      line: '$shape-guide--inverted',
      target: '$selection-area-target'
    }
  },
  renderer: 'dom',
  on: {
    areaStart: function areaStart(e) {
      this.start(e);
    },
    areaMove: function areaMove(e) {
      this.move(e);
    },
    areaEnd: function areaEnd(e) {
      this.end(e);
    },
    areaClear: function areaClear(e) {
      this.clear(e);
    }
  },
  created: function created() {
    this.state = {
      key: this.settings.key || 'brush-area-dir'
    };
  },
  render: function render(h) {
    var _this = this;

    this.state.rect = this.rect;
    var stngs = this.settings.settings;
    var direction = stngs.direction === 'vertical' ? VERTICAL : HORIZONTAL;
    var size = this.state.rect[direction === VERTICAL ? 'height' : 'width'];
    var offset = this.renderer.element().getBoundingClientRect();
    var targets = (stngs.target ? stngs.target.components || [stngs.target.component] : []).map(function (c) {
      return _this.chart.component(c);
    }).filter(function (c) {
      return !!c && !!c.rect;
    });
    var targetRect = targets[0] ? targets.slice(1).reduce(function (prev, curr) {
      return {
        x0: Math.min(prev.x0, curr.rect.x),
        y0: Math.min(prev.y0, curr.rect.y),
        x1: Math.max(prev.x1, curr.rect.x + curr.rect.width),
        y1: Math.max(prev.y1, curr.rect.y + curr.rect.height)
      };
    }, {
      x0: targets[0].rect.x,
      y0: targets[0].rect.y,
      x1: targets[0].rect.x + targets[0].rect.width,
      y1: targets[0].rect.y + targets[0].rect.height
    }) : null;
    this.state.targetRect = targetRect ? {
      x: targetRect.x0 - this.rect.x,
      y: targetRect.y0 - this.rect.y,
      width: targetRect.x1 - targetRect.x0,
      height: targetRect.y1 - targetRect.y0
    } : null;
    this.state.style = this.style;
    this.state.chart = this.chart;
    this.state.direction = direction;
    this.state.settings = stngs;
    this.state.offset = offset;
    this.state.rc = rangeCollection();
    this.state.renderer = this.renderer;
    this.state.multi = !!stngs.multiple;
    this.state.h = h;
    this.state.size = size;
    this.state.cssCoord = {
      offset: this.state.direction === VERTICAL ? 'top' : 'left',
      coord: this.state.direction === VERTICAL ? 'y' : 'x',
      pos: this.state.direction === VERTICAL ? 'deltaY' : 'deltaX',
      area: this.state.direction === VERTICAL ? 'height' : 'width'
    };

    this.state.format = function getFormat(v, r) {
      return getBubbleLabel(this, v, r);
    };

    return [];
  },
  start: function start(e) {
    startArea({
      e: e,
      state: this.state,
      renderer: this.renderer,
      ranges: ranges$1,
      targetSize: TARGET_SIZE
    });
  },
  end: function end() {
    if (!this.state.started) {
      return;
    }

    endArea(this.state, ranges$1);
    picasso_esm_render(this.state);
  },
  move: function move(e) {
    if (!this.state.started) {
      return;
    }

    moveArea(this.state, e);
    setRanges$1(this.state);
    picasso_esm_render(this.state);
  },
  clear: function clear() {
    if (this.state.rc) {
      this.state.rc.clear();
    }

    this.state.renderer.render([]);
  }
};

function rangeBrush(picasso) {
  picasso.component('brush-range', brushRangeComponent);
  picasso.component('brush-area-dir', brushAreaDirectionalComponent);
}

var FILL = '#ccc';
var OPACITY = 1;

function ranges$2(state) {
  var brush = state.brush;

  if (!brush || !brush.isActive()) {
    return [];
  }

  var sourceData = state.scale.data();
  var sourceFields = sourceData ? sourceData.fields || [] : [];
  var sources = sourceFields.map(function (field) {
    return field.id();
  });
  var rangeBrush = brush.brushes().filter(function (f) {
    return f.type === 'range' && sources.indexOf(f.id) !== -1;
  })[0];

  if (!rangeBrush) {
    return [];
  }

  return rangeBrush.brush.ranges();
}

function shapes(state) {
  var isVertical = state.direction === 'vertical';
  var size = state.rect[isVertical ? 'height' : 'width'];
  var otherSize = state.rect[isVertical ? 'width' : 'height'];
  return ranges$2(state).map(function (range) {
    var start = state.scale(range.min) * size;
    var end = state.scale(range.max) * size;
    var low = Math.min(start, end);
    var s = Math.abs(start - end);
    return {
      type: 'rect',
      fill: state.fill,
      opacity: state.opacity,
      x: isVertical ? 0 : low,
      width: isVertical ? otherSize : s,
      y: isVertical ? low : 0,
      height: isVertical ? s : otherSize
    };
  });
}

function onStart(state) {
  state.renderer.render(shapes(state));
}

function onUpdate(state) {
  state.renderer.render(shapes(state));
}

function onEnd(state) {
  state.renderer.render(shapes(state));
}

function setup(state, brush, scale, renderer) {
  state.brush = brush;

  if (!brush) {
    return;
  }

  function start() {
    onStart(state);
  }

  function update() {
    onUpdate(state);
  }

  function end() {
    onEnd(state);
  }

  brush.on('start', start);
  brush.on('update', update);
  brush.on('end', end);
  state.start = start;
  state.update = update;
  state.end = end;
  state.brush = brush;
  state.scale = scale;
  state.renderer = renderer;
}

function picasso_esm_teardown(state) {
  if (state.brush) {
    state.brush.removeListener('start', state.start);
    state.brush.removeListener('update', state.update);
    state.brush.removeListener('end', state.end);
  }

  state.start = undefined;
  state.update = undefined;
  state.end = undefined;
  state.brush = undefined;
  state.scale = undefined;
  state.renderer = undefined;
}
/**
 * @typedef {object} component--range
 */

/**
 * @typedef {object} component--range.settings
 * @property {string} brush - Name of brush instance
 * @property {string} scale - Name of a scale
 * @property {string} [direction='horizontal'] - Direction of the brush
 * @property {string} [fill='#ccc'] - Fill color
 * @property {number} [opacity=1] - Layer opacity
 */


var rangeComponent = {
  require: ['chart', 'settings', 'renderer'],
  defaultSettings: {
    settings: {}
  },
  preferredSize: function preferredSize() {
    return 50;
  },
  created: function created() {
    this.state = {};
  },
  render: function render() {
    var stngs = this.settings.settings;
    var brush = this.chart.brush(stngs.brush);
    var direction = stngs.direction || 'horizontal';
    var distance = direction === 'horizontal' ? this.rect.width : this.rect.height;
    var scale = scaleWithSize(this.chart.scale(stngs.scale), distance);
    picasso_esm_teardown(this.state);
    setup(this.state, brush, scale, this.renderer);
    this.state.rect = this.rect;
    this.state.fill = stngs.fill || FILL;
    this.state.opacity = typeof stngs.opacity !== 'undefined' ? stngs.opacity : OPACITY;
    this.state.direction = direction;
    return shapes(this.state);
  },
  beforeDestroy: function beforeDestroy() {
    picasso_esm_teardown(this.state);
  }
};

function rangeBrush$1(picasso) {
  picasso.component('range', rangeComponent);
}

function getPoint(rendererBounds, event) {
  var eventOffsetX = event.center.x;
  var eventOffsetY = event.center.y;
  return {
    x: eventOffsetX - rendererBounds.left,
    y: eventOffsetY - rendererBounds.top
  }; // return {
  //   x: Math.min(Math.max(eventOffsetX - rendererBounds.left, 0), rendererBounds.width),
  //   y: Math.min(Math.max(eventOffsetY - rendererBounds.top, 0), rendererBounds.height)
  // };
}

function withinThreshold(p, state, settings) {
  var startPoint = state.points[0];
  var sqrDist = sqrDistance(p, startPoint);
  return sqrDist < Math.pow(settings.settings.snapIndicator.threshold, 2);
}

function appendToPath(state, p) {
  if (state.path.d == null) {
    state.path.d = "M".concat(p.x, " ").concat(p.y, " ");
  } else {
    state.path.d += "L".concat(p.x, " ").concat(p.y, " ");
  }

  state.points.push(p);
}

function render$1(state, renderer) {
  var nodes = [state.startPoint, state.path, state.snapIndicator].filter(function (node) {
    return node.visible;
  });
  renderer.render(nodes);
}

function setSnapIndictor(_ref) {
  var state = _ref.state,
      _ref$start = _ref.start,
      start = _ref$start === void 0 ? null : _ref$start,
      _ref$end = _ref.end,
      end = _ref$end === void 0 ? null : _ref$end;

  if (start !== null) {
    state.snapIndicator.x1 = start.x;
    state.snapIndicator.y1 = start.y;
  }

  if (end !== null) {
    state.snapIndicator.x2 = end.x;
    state.snapIndicator.y2 = end.y;
  }
}

function showSnapIndicator(state, show) {
  state.snapIndicator.visible = show;
}

function setStartPoint(state, p) {
  state.startPoint.cx = p.x;
  state.startPoint.cy = p.y;
}

function getComponentDelta(chart, rendererBounds) {
  var chartBounds = chart.element.getBoundingClientRect();
  return {
    x: rendererBounds.left - chartBounds.left,
    y: rendererBounds.top - chartBounds.top
  };
}

function doLineBrush(state, chart) {
  if (state.active) {
    var p1 = state.points[state.points.length - 2];
    var p2 = state.points[state.points.length - 1];
    state.lineBrushShape.x1 = p1.x + state.componentDelta.x;
    state.lineBrushShape.y1 = p1.y + state.componentDelta.y;
    state.lineBrushShape.x2 = p2.x + state.componentDelta.x;
    state.lineBrushShape.y2 = p2.y + state.componentDelta.y;
    var shapes = chart.shapesAt(state.lineBrushShape, {
      components: state.brushConfig
    });
    chart.brushFromShapes(shapes, {
      components: state.brushConfig
    });
  }
}

function doPolygonBrush(state, chart) {
  if (state.active) {
    var dx = state.componentDelta.x;
    var dy = state.componentDelta.y;
    var vertices = state.points.map(function (p) {
      return {
        x: p.x + dx,
        y: p.y + dy
      };
    });
    var shapes = chart.shapesAt({
      vertices: vertices
    }, {
      components: state.brushConfig
    });
    chart.brushFromShapes(shapes, {
      components: state.brushConfig
    });
  }
}

function initPath(stgns) {
  return {
    visible: true,
    type: 'path',
    d: null,
    fill: stgns.fill,
    stroke: stgns.stroke,
    strokeWidth: stgns.strokeWidth,
    opacity: stgns.opacity,
    strokeDasharray: stgns.strokeDasharray,
    collider: {
      type: null
    }
  };
}

function initSnapIndicator(stgns) {
  return {
    visible: false,
    type: 'line',
    x1: 0,
    y1: 0,
    x2: 0,
    y2: 0,
    strokeDasharray: stgns.strokeDasharray,
    stroke: stgns.stroke,
    strokeWidth: stgns.strokeWidth,
    opacity: stgns.opacity,
    collider: {
      type: null
    }
  };
}

function initStartPoint(stgns) {
  return {
    visible: true,
    type: 'circle',
    cx: 0,
    cy: 0,
    r: stgns.r,
    fill: stgns.fill,
    opacity: stgns.opacity,
    stroke: stgns.stroke,
    strokeWidth: stgns.strokeWidth,
    collider: {
      type: null
    }
  };
}

function getBrushConfig(settings) {
  return settings.settings.brush.components.map(function (b) {
    return {
      key: b.key,
      contexts: b.contexts || ['lassoBrush'],
      data: b.data || [''],
      action: b.action || 'add'
    };
  });
}

function endBrush(state, chart) {
  state.brushConfig.forEach(function (config) {
    config.contexts.forEach(function (context) {
      chart.brush(context).end();
    });
  });
}

function resetState() {
  return {
    points: [],
    active: false,
    path: null,
    snapIndicator: null,
    startPoint: null,
    rendererBounds: null,
    componentDelta: null,
    brushConfig: null,
    lineBrushShape: {
      x1: 0,
      y1: 0,
      x2: 0,
      y2: 0
    } // Keep a single shape instance to avoid instantiating a new object on each lookup

  };
}
/**
 * @typedef {object} component--brush-lasso
 */

/**
 * @typedef {object} component--brush-lasso-settings
 * @property {object} [lasso] - Lasso style settings
 * @property {string} [lasso.fill='transparent']
 * @property {string} [lasso.stroke='black']
 * @property {number} [lasso.strokeWidth=2]
 * @property {number} [lasso.opacity=0.7]
 * @property {number} [lasso.strokeDasharray]
 * @property {object} [snapIndicator] - Snap indicator settings
 * @property {number} [snapIndicator.threshold=75] - The distance in pixel to show the snap indicator, if less then threshold the indicator is dispalyed
 * @property {string} [snapIndicator.strokeDasharray='5, 5']
 * @property {string} [snapIndicator.stroke='black']
 * @property {number} [snapIndicator.strokeWidth=2]
 * @property {number} [snapIndicator.opacity=0.5]
 * @property {object} [startPoint] - Start point style settings
 * @property {number} [startPoint.r=10] - Circle radius
 * @property {string} [startPoint.stroke='green']
 * @property {number} [startPoint.strokeWidth=1]
 * @property {number} [startPoint.opacity=1]
 * @property {object} [brush]
 * @property {object[]} brush.components - Array of components to brush on.
 * @property {string} [brush.components[].component.key] - Component key
 * @property {string[]} [brush.components[].component.contexts=['brushLasso']] - Name of the brushing contexts to affect
 * @property {string[]} [brush.components[].component.data=['']] - The mapped data properties to add to the brush
 * @property {string} [brush.components[].component.action='add'] - Type of action to respond with
 */


var brushLassoComponent = {
  require: ['chart', 'renderer', 'settings'],
  defaultSettings: {
    layout: {
      displayOrder: 0
    },
    settings: {
      brush: {
        components: []
      },
      snapIndicator: {
        threshold: 75,
        strokeDasharray: '5, 5',
        stroke: 'black',
        strokeWidth: 2,
        opacity: 0.5
      },
      lasso: {
        fill: 'transparent',
        stroke: 'black',
        strokeWidth: 2,
        opacity: 0.7,
        strokeDasharray: '20, 10'
      },
      startPoint: {
        r: 10,
        fill: 'green',
        stroke: 'black',
        strokeWidth: 1,
        opacity: 1
      }
    }
  },
  on: {
    lassoStart: function lassoStart(e) {
      this.start(e);
    },
    lassoEnd: function lassoEnd(e) {
      this.end(e);
    },
    lassoMove: function lassoMove(e) {
      this.move(e);
    },
    lassoCancel: function lassoCancel() {
      this.cancel();
    }
  },
  created: function created() {
    this.state = resetState();
  },
  start: function start(e) {
    this.state.active = true;
    this.state.path = initPath(this.settings.settings.lasso);
    this.state.snapIndicator = initSnapIndicator(this.settings.settings.snapIndicator);
    this.state.startPoint = initStartPoint(this.settings.settings.startPoint);
    this.state.rendererBounds = this.renderer.element().getBoundingClientRect();
    this.state.componentDelta = getComponentDelta(this.chart, this.state.rendererBounds);
    this.state.brushConfig = getBrushConfig(this.settings);
    var p = getPoint(this.state.rendererBounds, e);
    appendToPath(this.state, p);
    setSnapIndictor({
      state: this.state,
      start: p
    });
    setStartPoint(this.state, p);
  },
  move: function move(e) {
    if (!this.state.active) {
      return;
    }

    var p = getPoint(this.state.rendererBounds, e);

    if (withinThreshold(p, this.state, this.settings)) {
      showSnapIndicator(this.state, true);
    } else {
      showSnapIndicator(this.state, false);
    }

    appendToPath(this.state, p);
    setSnapIndictor({
      state: this.state,
      end: p
    });
    render$1(this.state, this.renderer);
    doLineBrush(this.state, this.chart);
  },
  end: function end(e) {
    if (!this.state.active) {
      return;
    }

    showSnapIndicator(this.state, false);
    var p = getPoint(this.state.rendererBounds, e);
    var shouldSnap = withinThreshold(p, this.state, this.settings);

    if (shouldSnap) {
      doPolygonBrush(this.state, this.chart);
    }

    this.state = resetState();
    this.renderer.render([]);
  },
  cancel: function cancel() {
    if (!this.state.active) {
      return;
    }

    endBrush(this.state, this.chart);
    this.state = resetState();
    this.renderer.render([]);
  },
  render: function render() {// Do nothing
  }
};

function lassoBrush(picasso) {
  picasso.component('brush-lasso', brushLassoComponent);
}

/**
 * Using the basic example found here: https://en.wikipedia.org/wiki/Binary_search_algorithm
 *
 * Finds the first node that may intersect the label.
 * @private
 */

function binaryLeftSearch(labelBounds, ary, coord, side, extractBounds) {
  var left = 0;
  var right = ary.length - 1;
  var bounds;

  while (left < right) {
    var m = Math.floor((left + right) / 2);
    bounds = extractBounds(ary[m]);

    if (bounds[coord] + bounds[side] < labelBounds[coord]) {
      // label is on right side
      left = m + 1;
    } else {
      // label is on the left side
      right = m;
    }
  }

  return left;
}
/**
 * The purpose of this module is to act as a filtering function to remove any labels
 * that meets one of the following criterias:
 * -- The label is not fully inside the container, such that it would be fully or partially clipped if rendered
 * -- The label overlaps another label
 * -- The label overlaps another bar which is not the bar the label is originating from
 *
 * Assumes that the nodes are sorted from left/top to right/down, as that allows
 * some optimizations to be performed.
 * @private
 * @returns {function} Filter function, returns false if label be removed and true otherwise
 */

function filterOverlappingLabels$1(_ref) {
  var orientation = _ref.orientation,
      targetNodes = _ref.targetNodes,
      labels = _ref.labels,
      container = _ref.container;
  var findLeft = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : binaryLeftSearch;
  var renderLabels = [];
  var coord = orientation === 'v' ? 'x' : 'y';
  var side = orientation === 'v' ? 'width' : 'height';

  var getTextBounds = function getTextBounds(item) {
    return item.textBounds;
  };

  var getNodeBounds = function getNodeBounds(item) {
    return item.node.localBounds;
  };

  return function (doNotUse, labelIndex) {
    var _labels$labelIndex = labels[labelIndex],
        labelBounds = _labels$labelIndex.textBounds,
        labelNode = _labels$labelIndex.node; // ### Test if label is not fully inside container based on the orientation ###

    if (labelBounds[coord] < container[coord] || labelBounds[coord] + labelBounds[side] > container[coord] + container[side]) {
      return false;
    } // ### Test label to label collision ###


    var leftStartLabel = findLeft(labelBounds, renderLabels, coord, side, getTextBounds);

    for (var i = leftStartLabel; i < renderLabels.length; i++) {
      if (testRectRect(labelBounds, renderLabels[i].textBounds)) {
        return false;
      }
    } // ### Test label to node collision ###


    var leftStartNode = findLeft(labelBounds, targetNodes, coord, side, getNodeBounds);
    var labelRightBoundary = labelBounds[coord] + labelBounds[side];

    for (var _i = leftStartNode; _i < targetNodes.length; _i++) {
      var node = targetNodes[_i].node; // Do not test beyond this node, as they are assumed to not collide with the label

      if (labelRightBoundary < node.localBounds[coord]) {
        break;
      }

      if (testRectRect(labelBounds, node.localBounds) && labelNode !== node) {
        return false;
      }
    } // No collision occured, allow the label to be rendered


    renderLabels.push(labels[labelIndex]);
    return true;
  };
}

var PADDING$1 = 4; // const DOUBLE_PADDING = PADDING * 2;

function cbContext(node, chart) {
  return {
    node: node,
    data: node.data,
    scale: chart.scale,
    formatter: chart.formatter,
    dataset: chart.dataset
  };
}

function isValidText(text) {
  var type = _typeof(text);

  return (type === 'string' || type === 'number') && text !== '';
}

function toBackground(label) {
  return _objectSpread2({
    type: 'rect',
    rx: 2,
    ry: 2,
    fill: label.backgroundColor
  }, label.backgroundBounds);
}

function isTextWidthInRectWidth(rect, label, rotate) {
  return rotate ? rect.width >= label.height : rect.width >= label.width;
}

function isTextHeightInRectHeight(rect, label, rotate) {
  return rotate ? rect.height >= label.width : rect.height >= label.height;
}

function isGoodPlacement(orientation, rect, label, fitsHorizontally, overflow) {
  var fitWidth;
  var fitHeight;

  if (orientation === 'v') {
    fitWidth = fitsHorizontally || overflow || isTextWidthInRectWidth(rect, label, true);
    fitHeight = isTextHeightInRectHeight(rect, label, !fitsHorizontally);
  } else {
    fitWidth = isTextWidthInRectWidth(rect, label);
    fitHeight = overflow || isTextHeightInRectHeight(rect, label, false);
  }

  return fitWidth && fitHeight;
}

function isTextInRect(rect, label, opts) {
  return isTextWidthInRectWidth(rect, label, opts.rotate) && isTextHeightInRectHeight(rect, label, opts.rotate);
}
function placeSegmentInSegment(majorSegmentPosition, majorSegmentSize, minorSegmentSize, align) {
  var majorSegmentCenter = majorSegmentPosition + majorSegmentSize * 0.5;
  var offset = (align - 0.5) * (majorSegmentSize - minorSegmentSize);
  var minorSegmentCenter = majorSegmentCenter + offset;
  var minorSegmentPosition = minorSegmentCenter - minorSegmentSize * 0.5;
  return minorSegmentPosition;
}
function placeTextInRect(rect, text, opts) {
  var label = {
    type: 'text',
    text: text,
    maxWidth: opts.rotate ? rect.height : rect.width,
    x: 0,
    y: rect.y,
    dx: 0,
    dy: 0,
    fill: opts.fill,
    anchor: opts.rotate ? 'end' : 'start',
    baseline: 'central',
    fontSize: "".concat(opts.fontSize, "px"),
    fontFamily: opts.fontFamily
  };
  var textMetrics = opts.textMetrics;

  if (!opts.overflow && !isTextInRect(rect, textMetrics, opts)) {
    return false;
  }

  var baseLineOffset = textMetrics.height * 0.5;

  if (opts.rotate) {
    label.x = placeSegmentInSegment(rect.x, rect.width, textMetrics.height, opts.align) + baseLineOffset;
    label.y = placeSegmentInSegment(rect.y, rect.height, textMetrics.width, opts.justify);
    label.transform = "rotate(-90, ".concat(label.x + label.dx, ", ").concat(label.y + label.dy, ")");
  } else {
    label.x = placeSegmentInSegment(rect.x, rect.width, textMetrics.width, opts.align);
    label.y = placeSegmentInSegment(rect.y, rect.height, textMetrics.height, opts.justify) + baseLineOffset;
  }

  return label;
}

function limitBounds(bounds, view) {
  var minY = Math.max(0, Math.min(bounds.y, view.height));
  var maxY = Math.max(0, Math.min(bounds.y + bounds.height, view.height));
  var minX = Math.max(0, Math.min(bounds.x, view.width));
  var maxX = Math.max(0, Math.min(bounds.x + bounds.width, view.width));
  bounds.x = minX;
  bounds.width = maxX - minX;
  bounds.y = minY;
  bounds.height = maxY - minY;
}

function pad$1(bounds) {
  var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var _padding$top = padding.top,
      top = _padding$top === void 0 ? PADDING$1 : _padding$top,
      _padding$bottom = padding.bottom,
      bottom = _padding$bottom === void 0 ? PADDING$1 : _padding$bottom,
      _padding$left = padding.left,
      left = _padding$left === void 0 ? PADDING$1 : _padding$left,
      _padding$right = padding.right,
      right = _padding$right === void 0 ? PADDING$1 : _padding$right;
  bounds.x += left;
  bounds.width -= left + right;
  bounds.y += top;
  bounds.height -= top + bottom;
}

function getBarRect(_ref) {
  var bar = _ref.bar,
      view = _ref.view,
      direction = _ref.direction,
      position = _ref.position,
      _ref$padding = _ref.padding,
      padding = _ref$padding === void 0 ? PADDING$1 : _ref$padding;
  var bounds = {};
  extend(bounds, bar);

  if (!position || position === 'inside') ; else if (direction === 'up' || direction === 'down') {
    var start = Math.max(0, Math.min(bar.y, view.height));
    var end = Math.max(0, Math.min(bar.y + bar.height, view.height));

    if (position === 'outside' && direction === 'up' || position === 'opposite' && direction === 'down') {
      bounds.y = 0;
      bounds.height = start;
    } else if (position === 'outside' && direction === 'down' || position === 'opposite' && direction === 'up') {
      bounds.y = end;
      bounds.height = view.height - end;
    }
  } else {
    var _start = Math.max(0, Math.min(bar.x, view.width));

    var _end = Math.max(0, Math.min(bar.x + bar.width, view.width));

    if (position === 'outside' && direction === 'left' || position === 'opposite' && direction === 'right') {
      bounds.x = 0;
      bounds.width = _start;
    } else if (position === 'outside' && direction === 'right' || position === 'opposite' && direction === 'left') {
      bounds.x = _end;
      bounds.width = view.width - _end;
    }
  }

  limitBounds(bounds, view);
  pad$1(bounds, padding);
  return bounds;
}
function findBestPlacement(_ref2) {
  var direction = _ref2.direction,
      fitsHorizontally = _ref2.fitsHorizontally,
      measured = _ref2.measured,
      node = _ref2.node,
      orientation = _ref2.orientation,
      placementSettings = _ref2.placementSettings,
      rect = _ref2.rect;
  var barRect = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : getBarRect;
  var largest;
  var bounds;
  var placement;
  var testBounds;
  var p;
  var boundaries = [];
  var dimension = orientation === 'h' ? 'width' : 'height';

  for (p = 0; p < placementSettings.length; p++) {
    placement = placementSettings[p];
    testBounds = barRect({
      bar: node.localBounds,
      view: rect,
      direction: direction,
      position: placement.position,
      padding: placement.padding
    });
    boundaries.push(testBounds);
    largest = !p || testBounds[dimension] > largest[dimension] ? testBounds : largest;

    if (isGoodPlacement(orientation, testBounds, measured, fitsHorizontally, placement.overflow)) {
      bounds = testBounds;
      break;
    }
  } // fallback strategy - place the text in the largest rectangle


  if (!bounds) {
    bounds = largest;
    p = boundaries.indexOf(bounds);
  }

  placement = placementSettings[p];
  return {
    bounds: bounds,
    placement: placement
  };
}

function approxTextBounds(label, textMetrics, rotated, rect) {
  var padding = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  var _padding$top2 = padding.top,
      top = _padding$top2 === void 0 ? PADDING$1 : _padding$top2,
      _padding$bottom2 = padding.bottom,
      bottom = _padding$bottom2 === void 0 ? PADDING$1 : _padding$bottom2,
      _padding$left2 = padding.left,
      left = _padding$left2 === void 0 ? PADDING$1 : _padding$left2,
      _padding$right2 = padding.right,
      right = _padding$right2 === void 0 ? PADDING$1 : _padding$right2;
  var x0 = label.x + label.dx;
  var y0 = label.y + label.dy;
  var height = rotated ? Math.min(textMetrics.width, rect.height) : Math.min(textMetrics.height, rect.width);
  var width = rotated ? Math.min(textMetrics.height, rect.height) : Math.min(textMetrics.width, rect.width);
  var offset = textMetrics.height * 0.5;
  var PADDING_OFFSET = 1e-9; // Needed to support a case when multiple bars are on the same location

  var x = rotated ? x0 - offset : x0;
  var y = rotated ? y0 : y0 - offset;
  var bounds = {
    x: x - left - PADDING_OFFSET,
    y: y - top - PADDING_OFFSET,
    width: width + (left + right) - PADDING_OFFSET,
    height: height + (top + bottom) - PADDING_OFFSET
  };
  return bounds;
}

function placeInBars(_ref3) {
  var chart = _ref3.chart,
      targetNodes = _ref3.targetNodes,
      rect = _ref3.rect,
      fitsHorizontally = _ref3.fitsHorizontally,
      collectiveOrientation = _ref3.collectiveOrientation;
  var findPlacement = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : findBestPlacement;
  var placer = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : placeTextInRect;
  var postFilter = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : filterOverlappingLabels$1;
  var labels = [];
  var postFilterContext = {
    container: rect,
    targetNodes: targetNodes,
    labels: [],
    orientation: collectiveOrientation
  };
  var label;
  var target;
  var node;
  var text;
  var justify;
  var bounds;
  var fill;
  var measured;
  var direction;
  var lblStngs;
  var placement;
  var placements;
  var arg;
  var orientation;

  for (var i = 0, len = targetNodes.length; i < len; i++) {
    bounds = null;
    target = targetNodes[i];
    node = target.node;
    arg = cbContext(node, chart);
    direction = target.direction;
    orientation = direction === 'left' || direction === 'right' ? 'h' : 'v';

    for (var j = 0; j < target.texts.length; j++) {
      text = target.texts[j];

      if (!isValidText(text)) {
        continue;
      }

      lblStngs = target.labelSettings[j];
      measured = target.measurements[j];
      placements = lblStngs.placements;
      var bestPlacement = findPlacement({
        direction: direction,
        fitsHorizontally: fitsHorizontally,
        lblStngs: lblStngs,
        measured: measured,
        node: node,
        orientation: orientation,
        placements: placements,
        placementSettings: target.placementSettings[j],
        rect: rect
      });
      bounds = bestPlacement.bounds;
      placement = bestPlacement.placement;

      if (bounds && placement) {
        justify = placement.justify;
        fill = typeof placement.fill === 'function' ? placement.fill(arg, i) : placement.fill;
        var linkData = typeof lblStngs.linkData === 'function' ? lblStngs.linkData(arg, i) : undefined;
        var overflow = typeof placement.overflow === 'function' ? placement.overflow(arg, i) : placement.overflow;

        if (direction === 'up') {
          justify = 1 - justify;
        }

        if (placement.position === 'opposite') {
          justify = 1 - justify;
        }

        if (direction === 'left') {
          justify = 1 - justify;
        }

        var isRotated = !(collectiveOrientation === 'h' || fitsHorizontally);
        label = placer(bounds, text, {
          fill: fill,
          justify: orientation === 'h' ? placement.align : justify,
          align: orientation === 'h' ? justify : placement.align,
          fontSize: lblStngs.fontSize,
          fontFamily: lblStngs.fontFamily,
          textMetrics: measured,
          rotate: isRotated,
          overflow: !!overflow
        });

        if (label) {
          if (typeof linkData !== 'undefined') {
            label.data = linkData;
          }

          if (_typeof(placement.background) === 'object') {
            label.backgroundColor = typeof placement.background.fill === 'function' ? placement.background.fill(arg, i) : placement.background.fill;

            if (typeof label.backgroundColor !== 'undefined') {
              label.backgroundBounds = approxTextBounds(label, measured, isRotated, bounds, placement.background.padding);
            }
          }

          labels.push(label);
          postFilterContext.labels.push({
            node: node,
            textBounds: approxTextBounds(label, measured, isRotated, bounds, placement.padding)
          });
        }
      }
    }
  }

  var filteredLabels = labels.filter(postFilter(postFilterContext));
  var backgrounds = filteredLabels.filter(function (lb) {
    return typeof lb.backgroundBounds !== 'undefined';
  }).map(toBackground);
  return [].concat(_toConsumableArray$1(backgrounds), _toConsumableArray$1(filteredLabels));
}
function precalculate(_ref4) {
  var nodes = _ref4.nodes,
      rect = _ref4.rect,
      chart = _ref4.chart,
      labelSettings = _ref4.labelSettings,
      placementSettings = _ref4.placementSettings,
      settings = _ref4.settings,
      renderer = _ref4.renderer;
  var labelStruct = {};
  var targetNodes = [];
  var target;
  var fitsHorizontally = true;
  var hasHorizontalDirection = false;
  var node;
  var text;
  var bounds;
  var measured;
  var lblStng;
  var direction;

  for (var i = 0; i < nodes.length; i++) {
    node = nodes[i];
    bounds = node.localBounds;

    if (!testRectRect(bounds, rect)) {
      continue;
    }

    var arg = cbContext(node, chart);
    target = {
      node: node,
      texts: [],
      measurements: [],
      labelSettings: [],
      placementSettings: [] // direction: 'up'

    };

    for (var j = 0; j < labelSettings.length; j++) {
      lblStng = labelSettings[j];
      text = typeof lblStng.label === 'function' ? lblStng.label(arg, i) : undefined;

      if (!isValidText(text)) {
        continue; // eslint-ignore-line
      }

      direction = typeof settings.direction === 'function' ? settings.direction(arg, i) : settings.direction || 'up';
      hasHorizontalDirection = hasHorizontalDirection || direction === 'left' || direction === 'right';
      labelStruct.fontFamily = lblStng.fontFamily;
      labelStruct.fontSize = "".concat(lblStng.fontSize, "px");
      labelStruct.text = text;
      measured = renderer.measureText(labelStruct);
      target.measurements.push(measured);
      target.texts.push(text);
      target.labelSettings.push(lblStng);
      target.placementSettings.push(placementSettings[j]);
      target.direction = direction;
      fitsHorizontally = fitsHorizontally && measured.width <= bounds.width - PADDING$1 * 2;
    }

    targetNodes.push(target);
  }

  return {
    targetNodes: targetNodes,
    fitsHorizontally: fitsHorizontally,
    hasHorizontalDirection: hasHorizontalDirection
  };
}
/**
 * @typedef {object} component--labels~label-strategy
 *
 */

/**
 * @typedef {object} component--labels~label-strategy.settings
 * @property {string|function} [direction='up'] - The direction in which the bars are growing: 'up', 'down', 'right' or 'left'.
 * @property {string} [fontFamily='Arial']
 * @property {number} [fontSize=12]
 * @property {Array<object>} labels
 * @property {string|function} labels[].label - The text value
 * @property {function} labels[].linkData - Link data to the label
 * @property {Array<object>} labels[].placements
 * @property {string} labels[].placements[].position - 'inside' | 'outside' | 'opposite'
 * @property {number} [labels[].placements[].justify=0] - Placement of the label along the direction of the bar
 * @property {number} [labels[].placements[].align=0.5] - Placement of the label along the perpendicular direction of the bar
 * @property {string} [labels[].placements[].fill='#333'] - Color of the label
 * @property {boolean} [labels[].placements[].overflow=false] - True if the label is allowed to overflow the bar
 * @property {object} labels[].placements[].padding - Padding between the label and the bar
 * @property {number} [labels[].placements[].padding.top=4] - Padding-top between the label and the bar
 * @property {number} [labels[].placements[].padding.bottom=4] - Padding-bottom between the label and the bar
 * @property {number} [labels[].placements[].padding.left=4] - Padding-left between the label and the bar
 * @property {number} [labels[].placements[].padding.right=4] - Padding-right between the label and the bar
 * @property {object} labels[].placements[].background - Background of the label
 * @property {string|function} labels[].placements[].background.fill - Background color of the label
 * @property {object} labels[].placements[].background.padding - Padding between the label and the background
 * @property {number} [labels[].placements[].background.padding.top=4] - Padding-top between the label and the background
 * @property {number} [labels[].placements[].background.padding.bottom=4] - Padding-bottom between the label and the background
 * @property {number} [labels[].placements[].background.padding.left=4] - Padding-left between the label and the background
 * @property {number} [labels[].placements[].background.padding.right=4] - Padding-right between the label and the background
 */

function bars(_ref5) {
  var settings = _ref5.settings,
      chart = _ref5.chart,
      nodes = _ref5.nodes,
      rect = _ref5.rect,
      renderer = _ref5.renderer,
      style = _ref5.style;
  var placer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : placeInBars;
  var defaults = extend({
    fontSize: 12,
    fontFamily: 'Arial',
    align: 0.5,
    justify: 0,
    fill: '#333'
  }, style.label);
  defaults.fontSize = parseInt(defaults.fontSize, 10);
  var labelSettings = settings.labels.map(function (labelSetting) {
    return extend({}, defaults, settings, labelSetting);
  });
  var placementSettings = settings.labels.map(function (labelSetting) {
    return labelSetting.placements.map(function (placement) {
      return extend({}, defaults, settings, labelSetting, placement);
    });
  });

  var _precalculate = precalculate({
    nodes: nodes,
    chart: chart,
    renderer: renderer,
    settings: settings,
    rect: rect,
    labelSettings: labelSettings,
    placementSettings: placementSettings
  }),
      fitsHorizontally = _precalculate.fitsHorizontally,
      hasHorizontalDirection = _precalculate.hasHorizontalDirection,
      targetNodes = _precalculate.targetNodes;

  var coord = hasHorizontalDirection ? 'y' : 'x';
  var side = hasHorizontalDirection ? 'height' : 'width';
  targetNodes.sort(function (a, b) {
    return a.node.localBounds[coord] + a.node.localBounds[side] - (b.node.localBounds[coord] + b.node.localBounds[side]);
  });
  return placer({
    chart: chart,
    targetNodes: targetNodes,
    stngs: settings,
    rect: rect,
    fitsHorizontally: fitsHorizontally,
    collectiveOrientation: hasHorizontalDirection ? 'h' : 'v'
  });
}

var LABEL_OVERLAP_THRESHOLD_X = 4;

function normalize$1(angle) {
  var PI2 = Math.PI * 2;
  return (angle % PI2 + PI2) % PI2; // normalize
}

function pad$2(bounds, padding) {
  bounds.x += padding;
  bounds.width -= padding * 2;
  bounds.y += padding;
  bounds.height -= padding * 2;
}

function getTopLeftBounds(bounds) {
  var x = bounds.x;
  var y = bounds.y - bounds.height / 2;
  return {
    x: x,
    y: y,
    width: bounds.width,
    height: bounds.height
  };
} // assume 0 <= angle < (PI / 2)


function getLineCircleIntersection(radius, offset, angle) {
  var x = offset.x,
      y = offset.y;

  if (x * x + y * y > radius * radius) {
    return null;
  }

  var dx = Math.sin(angle);
  var dy = Math.cos(angle);
  var D = x * dy - y * dx;
  var d = radius * radius - D * D;

  if (d < 0) {
    return null;
  }

  var sqrtD = Math.sqrt(d);
  return {
    x: D * dy + dx * sqrtD,
    y: -(D * dx) + dy * sqrtD
  };
} // assume 0 <= angle < (PI * 2)


function getRectFromCircleIntersection(_ref) {
  var radius = _ref.radius,
      size = _ref.size,
      angle = _ref.angle;
  var width = size.width,
      height = size.height;
  var lineOffset = {
    x: width / 2,
    y: height / 2
  };
  var section = Math.floor(angle / (Math.PI / 2));
  var intersection;
  var offset;

  switch (section) {
    case 0:
      intersection = getLineCircleIntersection(radius, lineOffset, angle);

      if (!intersection) {
        return null;
      }

      intersection.y *= -1;
      offset = {
        x: -width,
        y: 0
      };
      break;

    case 1:
      intersection = getLineCircleIntersection(radius, lineOffset, Math.PI - angle);

      if (!intersection) {
        return null;
      }

      offset = {
        x: -width,
        y: -height
      };
      break;

    case 2:
      intersection = getLineCircleIntersection(radius, lineOffset, angle - Math.PI);

      if (!intersection) {
        return null;
      }

      intersection.x *= -1;
      offset = {
        x: 0,
        y: -height
      };
      break;

    case 3:
      intersection = getLineCircleIntersection(radius, lineOffset, 2 * Math.PI - angle);

      if (!intersection) {
        return null;
      }

      intersection.x *= -1;
      intersection.y *= -1;
      offset = {
        x: 0,
        y: 0
      };
      break;

    default:
      throw new Error('invalid angle');
  }

  var bounds = {
    x: intersection.x + offset.x,
    y: intersection.y + offset.y,
    width: width,
    height: height
  };
  return bounds;
}

function getHorizontalInsideSliceRect(_ref2) {
  var slice = _ref2.slice,
      padding = _ref2.padding,
      measured = _ref2.measured,
      store = _ref2.store;
  var start = slice.start,
      end = slice.end,
      outerRadius = slice.outerRadius;
  var middle = normalize$1((start + end) / 2);
  var size = {
    width: measured.width + padding * 2,
    height: measured.height + padding * 2
  };
  var bounds = getRectFromCircleIntersection({
    radius: outerRadius,
    size: size,
    angle: middle
  });

  if (!bounds) {
    return null;
  }

  bounds.baseline = 'top';
  pad$2(bounds, padding);

  if (store.insideLabelBounds.some(function (rect) {
    return testRectRect(rect, bounds);
  })) {
    return null;
  }

  store.insideLabelBounds.push({
    x: bounds.x - LABEL_OVERLAP_THRESHOLD_X,
    y: bounds.y,
    width: bounds.width + LABEL_OVERLAP_THRESHOLD_X * 2,
    height: bounds.height
  }); // Copy as bounds is mutated else where

  return bounds;
}

function getHorizontalIntoSliceRect(_ref3) {
  var slice = _ref3.slice,
      padding = _ref3.padding,
      measured = _ref3.measured;
  var start = slice.start,
      end = slice.end,
      innerRadius = slice.innerRadius,
      outerRadius = slice.outerRadius;
  var middle = normalize$1((start + end) / 2);
  var size = {
    width: measured.width + padding * 2,
    height: measured.height + padding * 2
  };
  var bounds = getRectFromCircleIntersection({
    radius: outerRadius,
    size: size,
    angle: middle
  });

  if (!bounds) {
    return null;
  }

  bounds.baseline = 'top';
  var startLine = {
    x1: 0,
    y1: 0,
    x2: Math.sin(start) * outerRadius,
    y2: -Math.cos(start) * outerRadius
  };

  if (testRectLine(bounds, startLine)) {
    return null;
  }

  var endLine = {
    x1: 0,
    y1: 0,
    x2: Math.sin(end) * outerRadius,
    y2: -Math.cos(end) * outerRadius
  };

  if (testRectLine(bounds, endLine)) {
    return null;
  }

  var circle = {
    cx: 0,
    cy: 0,
    r: innerRadius
  };

  if (testCircleRect(circle, bounds)) {
    return null;
  }

  pad$2(bounds, padding);
  return bounds;
} // TODO: this case can support a justify setting


function getRotatedInsideSliceRect(_ref4) {
  var slice = _ref4.slice,
      measured = _ref4.measured,
      padding = _ref4.padding;
  var start = slice.start,
      end = slice.end,
      innerRadius = slice.innerRadius,
      outerRadius = slice.outerRadius;
  var maxWidth = outerRadius - innerRadius - padding * 2;
  var size = end - start;

  if (size < Math.PI) {
    var x = (measured.height / 2 + padding) / Math.tan(size / 2);

    if (x > innerRadius) {
      maxWidth = outerRadius - x - padding * 2;
    }
  }

  if (maxWidth < 0 || maxWidth < measured.minReqWidth) {
    return null;
  }

  var middle = normalize$1((start + end) / 2);
  var r = outerRadius - padding;
  var bounds = {
    x: Math.sin(middle) * r,
    y: -Math.cos(middle) * r,
    width: maxWidth,
    height: measured.height
  };

  if (middle < Math.PI) {
    bounds.angle = middle - Math.PI / 2;
    bounds.anchor = 'end';
  } else {
    bounds.angle = middle + Math.PI / 2;
    bounds.anchor = 'start';
  }

  return bounds;
}

function getRotatedOusideSliceRect(_ref5) {
  var slice = _ref5.slice,
      measured = _ref5.measured,
      padding = _ref5.padding,
      view = _ref5.view;
  var start = slice.start,
      end = slice.end,
      outerRadius = slice.outerRadius,
      offset = slice.offset;
  var r = outerRadius + padding;
  var size = end - start;

  if (size < Math.PI) {
    var minR = (measured.height / 2 + padding) / Math.tan(size / 2);

    if (minR > r) {
      return null;
    }
  }

  var middle = normalize$1((start + end) / 2);
  var x = Math.sin(middle) * r;
  var y = -Math.cos(middle) * r;
  var maxWidth = measured.width;
  var v = middle % Math.PI;

  if (v > Math.PI / 2) {
    v = Math.PI - v;
  }

  if (Math.cos(v) > 0.001) {
    var edge = y < 0 ? view.y : view.y + view.height;
    var d = Math.abs(edge - offset.y);
    var w = d / Math.cos(v) - Math.tan(v) * (measured.height / 2) - padding * 2 - outerRadius;

    if (w < maxWidth) {
      maxWidth = w;
    }
  }

  if (Math.sin(v) > 0.001) {
    var _edge = x < 0 ? view.x : view.x + view.width;

    var _d = Math.abs(_edge - offset.x);

    var _w = _d / Math.sin(v) - measured.height / 2 / Math.tan(v) - padding * 2 - outerRadius;

    if (_w < maxWidth) {
      maxWidth = _w;
    }
  }

  if (maxWidth <= 0 || maxWidth < measured.minReqWidth) {
    return null;
  }

  var bounds = {
    x: x,
    y: y,
    width: maxWidth,
    height: measured.height
  };

  if (middle < Math.PI) {
    bounds.angle = middle - Math.PI / 2;
    bounds.anchor = 'start';
  } else {
    bounds.angle = middle + Math.PI / 2;
    bounds.anchor = 'end';
  }

  return bounds;
}

function outOfSpace(context, section, view) {
  switch (section) {
    case 0:
      return context.q1maxY < 0;

    case 1:
      return context.q2minY > view.height;

    case 2:
      return context.q3minY > view.height;

    case 3:
      return context.q4maxY < 0;

    default:
      return true;
  }
}

function adjustBounds(bounds, context, slice) {
  var LINE_PADDING = 2;
  var LIMIT = 1;
  var start = slice.start,
      end = slice.end,
      offset = slice.offset,
      outerRadius = slice.outerRadius;
  var middle = normalize$1((start + end) / 2);
  var section = Math.floor(middle / (Math.PI / 2));

  switch (section) {
    case 0:
      if (context.q1maxY !== undefined) {
        var y = Math.min(bounds.y, context.q1maxY - bounds.height);
        var dy = bounds.y - y;
        bounds.y = y;

        if (dy > LIMIT) {
          var r = outerRadius + LINE_PADDING;
          bounds.line = {
            type: 'line',
            x1: bounds.x - LINE_PADDING,
            y1: bounds.y + LINE_PADDING,
            x2: offset.x + Math.sin(middle) * r,
            y2: offset.y - Math.cos(middle) * r,
            strokeWidth: 1
          };
        }
      }

      break;

    case 1:
      if (context.q2minY !== undefined) {
        var _y = Math.max(bounds.y, context.q2minY);

        var _dy = _y - bounds.y;

        bounds.y = _y;

        if (_dy > LIMIT) {
          var _r = outerRadius + LINE_PADDING;

          bounds.line = {
            type: 'line',
            x1: bounds.x - LINE_PADDING,
            y1: bounds.y - LINE_PADDING,
            x2: offset.x + Math.sin(middle) * _r,
            y2: offset.y - Math.cos(middle) * _r,
            strokeWidth: 1
          };
        }
      }

      break;

    case 2:
      if (context.q3minY !== undefined) {
        var _y2 = Math.max(bounds.y, context.q3minY);

        var _dy2 = _y2 - bounds.y;

        bounds.y = _y2;

        if (_dy2 > LIMIT) {
          var _r2 = outerRadius + LINE_PADDING;

          bounds.line = {
            type: 'line',
            x1: bounds.x + LINE_PADDING,
            y1: bounds.y - LINE_PADDING,
            x2: offset.x + Math.sin(middle) * _r2,
            y2: offset.y - Math.cos(middle) * _r2,
            strokeWidth: 1
          };
        }
      }

      break;

    case 3:
      if (context.q4maxY !== undefined) {
        var _y3 = Math.min(bounds.y, context.q4maxY - bounds.height);

        var _dy3 = bounds.y - _y3;

        bounds.y = _y3;

        if (_dy3 > LIMIT) {
          var _r3 = outerRadius + LINE_PADDING;

          bounds.line = {
            type: 'line',
            x1: bounds.x + LINE_PADDING,
            y1: bounds.y + LINE_PADDING,
            x2: offset.x + Math.sin(middle) * _r3,
            y2: offset.y - Math.cos(middle) * _r3,
            strokeWidth: 1
          };
        }
      }

      break;

    default:
      break;
  }
}

function updateContext(_ref6) {
  var context = _ref6.context,
      node = _ref6.node,
      bounds = _ref6.bounds;
  var PADDING = 2;
  var _node$desc$slice = node.desc.slice,
      start = _node$desc$slice.start,
      end = _node$desc$slice.end;
  var middle = normalize$1((start + end) / 2);
  var section = Math.floor(middle / (Math.PI / 2));

  switch (section) {
    case 0:
      context.q1maxY = bounds.y - PADDING;

      if (context.q2minY === undefined) {
        context.q2minY = bounds.y + bounds.height + PADDING;
      }

      break;

    case 1:
      context.q2minY = bounds.y + bounds.height + PADDING;
      break;

    case 2:
      context.q3minY = bounds.y + bounds.height + PADDING;
      break;

    case 3:
      context.q4maxY = bounds.y - PADDING;

      if (context.q3minY === undefined) {
        context.q3minY = bounds.y + bounds.height + PADDING;
      }

      break;

    default:
      break;
  }
}

function getHorizontalOusideSliceRect(_ref7) {
  var slice = _ref7.slice,
      measured = _ref7.measured,
      padding = _ref7.padding,
      view = _ref7.view,
      context = _ref7.context;
  var start = slice.start,
      end = slice.end,
      outerRadius = slice.outerRadius,
      offset = slice.offset;
  var middle = normalize$1((start + end) / 2);
  var section = Math.floor(middle / (Math.PI / 2));

  if (outOfSpace(context, section, view)) {
    return null;
  }

  var r = outerRadius + padding + measured.height / 2;
  var x = Math.sin(middle) * r;
  var y = -Math.cos(middle) * r;
  var maxWidth = measured.width;

  if (middle < Math.PI) {
    var w = Math.abs(view.x + view.width - (x + offset.x));

    if (w < maxWidth) {
      maxWidth = w;
    }
  } else {
    var _w2 = Math.abs(view.x - (x + offset.x));

    if (_w2 < maxWidth) {
      maxWidth = _w2;
    }
  }

  if (maxWidth < measured.minReqWidth) {
    return null;
  }

  var bounds = {
    x: x,
    y: y,
    width: maxWidth,
    height: measured.height
  };

  if (middle < Math.PI) {
    bounds.anchor = 'start';
  } else {
    bounds.anchor = 'end';
  }

  return bounds;
}

function cbContext$1(node, chart) {
  return {
    node: node,
    data: node.data,
    scale: chart.scale,
    formatter: chart.formatter,
    dataset: chart.dataset
  };
}

function placeTextOnPoint(rect, text, opts) {
  var label = {
    type: 'text',
    text: text,
    maxWidth: rect.width,
    x: rect.x,
    y: rect.y + (rect.baseline === 'top' ? rect.height / 2 : 0),
    fill: opts.fill,
    anchor: rect.anchor || 'start',
    baseline: 'middle',
    fontSize: "".concat(opts.fontSize, "px"),
    fontFamily: opts.fontFamily
  };

  if (!isNaN(rect.angle)) {
    var angle = rect.angle * (360 / (Math.PI * 2));
    label.transform = "rotate(".concat(angle, ", ").concat(label.x, ", ").concat(label.y, ")");
  }

  return label;
}

function getSliceRect(_ref8) {
  var slice = _ref8.slice,
      direction = _ref8.direction,
      position = _ref8.position,
      padding = _ref8.padding,
      measured = _ref8.measured,
      view = _ref8.view,
      context = _ref8.context,
      store = _ref8.store;
  var start = slice.start,
      end = slice.end,
      innerRadius = slice.innerRadius,
      offset = slice.offset;
  var bounds;
  var s;

  switch (position) {
    case 'into':
      if (direction === 'rotate') {
        bounds = getRotatedInsideSliceRect({
          slice: slice,
          measured: measured,
          padding: padding
        });
      } else {
        bounds = getHorizontalIntoSliceRect({
          slice: slice,
          measured: measured,
          padding: padding
        });
      }

      break;

    case 'inside':
      s = {
        start: start,
        end: end,
        innerRadius: 0,
        outerRadius: innerRadius
      };

      if (direction === 'rotate') {
        bounds = getRotatedInsideSliceRect({
          slice: s,
          measured: measured,
          padding: padding
        });
      } else {
        bounds = getHorizontalInsideSliceRect({
          slice: s,
          measured: measured,
          padding: padding,
          store: store
        });
      }

      break;

    case 'outside':
      if (direction === 'rotate') {
        bounds = getRotatedOusideSliceRect({
          slice: slice,
          measured: measured,
          padding: padding,
          view: view
        });
      } else {
        bounds = getHorizontalOusideSliceRect({
          slice: slice,
          measured: measured,
          padding: padding,
          view: view,
          context: context
        });
      }

      break;

    default:
      throw new Error('not implemented');
  }

  if (bounds) {
    bounds.x += offset.x;
    bounds.y += offset.y;

    if (position === 'outside' && direction !== 'rotate') {
      adjustBounds(bounds, context, slice);
    }
  }

  return bounds;
}

function findBestPlacement$1(_ref9) {
  var context = _ref9.context,
      direction = _ref9.direction,
      measured = _ref9.measured,
      node = _ref9.node,
      placementSettings = _ref9.placementSettings,
      rect = _ref9.rect,
      store = _ref9.store;
  var sliceRect = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : getSliceRect;

  for (var p = 0; p < placementSettings.length; p++) {
    var placement = placementSettings[p];
    var bounds = sliceRect({
      context: context,
      slice: node.desc.slice,
      view: rect,
      direction: direction,
      position: placement.position,
      measured: measured,
      padding: placement.padding,
      store: store
    });

    if (!bounds) {
      continue;
    }

    return {
      bounds: bounds,
      placement: placement
    };
  }

  return {
    bounds: null,
    placement: null
  };
}
/*
 * Sorts the nodes so that
 *   in each quarter sort nodes from the center (in y) outwards
 *   first quarter before the second
 *   forth quarter before the third
 */


function sortNodes(nodes) {
  var q1 = [];
  var q2 = [];
  var q3 = [];
  var q4 = [];

  for (var i = 0; i < nodes.length; ++i) {
    var _nodes$i$desc$slice = nodes[i].desc.slice,
        start = _nodes$i$desc$slice.start,
        end = _nodes$i$desc$slice.end;
    var middle = normalize$1((start + end) / 2);
    var section = Math.floor(middle / (Math.PI / 2));

    switch (section) {
      case 0:
        q1.push(nodes[i]);
        break;

      case 1:
        q2.push(nodes[i]);
        break;

      case 2:
        q3.push(nodes[i]);
        break;

      case 3:
        q4.push(nodes[i]);
        break;

      default:
        break;
    }
  }

  var sortFn = function sortFn(a, b) {
    var middleA = normalize$1((a.desc.slice.start + a.desc.slice.end) / 2);
    var middleB = normalize$1((b.desc.slice.start + b.desc.slice.end) / 2);
    return middleA - middleB;
  };

  var reverseSortFn = function reverseSortFn(a, b) {
    return sortFn(b, a);
  };

  q1.sort(reverseSortFn);
  q2.sort(sortFn);
  q3.sort(reverseSortFn);
  q4.sort(sortFn);
  return q1.concat(q2, q4, q3);
}

function measureText(text, stgns, renderer) {
  var fontFamily = stgns.fontFamily;
  var fontSize = "".concat(stgns.fontSize, "px");
  var metrics = renderer.measureText({
    text: text,
    fontFamily: fontFamily,
    fontSize: fontSize
  });
  metrics.minReqWidth = Math.min(metrics.width, renderer.measureText({
    text: "".concat(text[0], "\u2026"),
    fontFamily: fontFamily,
    fontSize: fontSize
  }).width);
  return metrics;
}
/**
 * @typedef {object} component--labels~slices-label-strategy
 *
 */

/**
 * @typedef {object} component--labels~slices-label-strategy.settings
 * @property {string|function} [direction='horizontal'] - The direction of the text: 'horizontal' or 'rotate'.
 * @property {string} [fontFamily='Arial']
 * @property {number} [fontSize=12]
 * @property {Array<object>} labels
 * @property {string|function} labels[].label - The text value
 * @property {function} labels[].linkData - Link data to the label
 * @property {Array<object>} labels[].placements
 * @property {string} [labels[].placements[].position='into'] - 'inside' | 'into' | 'outside' (outside is not implmented yet)
 * @property {string} [labels[].placements[].fill='#333'] - Color of the label
 */


function slices(_ref10) {
  var settings = _ref10.settings,
      chart = _ref10.chart,
      nodes = _ref10.nodes,
      rect = _ref10.rect,
      renderer = _ref10.renderer,
      style = _ref10.style;
  var findPlacement = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : findBestPlacement$1;
  var placer = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : placeTextOnPoint;
  var defaults = extend({
    fontSize: 12,
    fontFamily: 'Arial',
    fill: '#333',
    padding: 4,
    position: 'into'
  }, style.label);
  defaults.fontSize = parseInt(defaults.fontSize, 10);
  var labelSettings = settings.labels.map(function (labelSetting) {
    return extend({}, defaults, settings, labelSetting);
  });
  var placementSettings = settings.labels.map(function (labelSetting) {
    return labelSetting.placements.map(function (placement) {
      return extend({}, defaults, settings, labelSetting, placement);
    });
  });
  var labels = [];
  var store = {
    insideLabelBounds: []
  };
  nodes = sortNodes(nodes);
  var context = {};

  for (var i = 0, len = nodes.length; i < len; i++) {
    var node = nodes[i];
    var arg = cbContext$1(node, chart);

    for (var j = 0; j < labelSettings.length; j++) {
      var lblStngs = labelSettings[j];
      var text = typeof lblStngs.label === 'function' ? lblStngs.label(arg, i) : '';

      if (!text) {
        continue;
      }

      var direction = typeof lblStngs.direction === 'function' ? lblStngs.direction(arg, i) : lblStngs.direction || 'horizontal';
      var linkData = typeof lblStngs.linkData === 'function' ? lblStngs.linkData(arg, i) : undefined;
      var measured = measureText(text, lblStngs, renderer);
      var bestPlacement = findPlacement({
        context: context,
        direction: direction,
        lblStngs: lblStngs,
        measured: measured,
        node: node,
        placementSettings: placementSettings[j],
        rect: rect,
        store: store
      });
      var bounds = bestPlacement.bounds;
      var placement = bestPlacement.placement;

      if (bounds && placement) {
        if (placement.position === 'outside' && direction !== 'rotate') {
          updateContext({
            context: context,
            node: node,
            bounds: bounds
          });
          var topLeftBounds = getTopLeftBounds(bounds);

          if (!rectContainsRect(topLeftBounds, rect)) {
            continue;
          }
        }

        var fill = typeof placement.fill === 'function' ? placement.fill(arg, i) : placement.fill;
        var label = placer(bounds, text, {
          fill: fill,
          fontSize: lblStngs.fontSize,
          fontFamily: lblStngs.fontFamily,
          textMetrics: measured
        });

        if (label) {
          if (typeof linkData !== 'undefined') {
            label.data = linkData;
          }

          labels.push(label);

          if (bounds.line) {
            bounds.line.stroke = fill;
            labels.push(bounds.line);
          }
        }
      }
    }
  }

  return labels;
}

var LINEBREAK_REGEX = /\n+|\r+|\r\n/;
var WHITESPACE_REGEX = /\s/;
var HYPHEN_REGEX = /[a-zA-Z\u00C0-\u00F6\u00F8-\u00FF\u00AD]/;
var NO_BREAK = 0;
var MANDATORY = 1;
var BREAK_ALLOWED = 2;
function includesLineBreak(c) {
  if (typeof c === 'string') {
    return c.search(LINEBREAK_REGEX) !== -1;
  }

  return String(c).search(LINEBREAK_REGEX) !== -1;
}

function includesWhiteSpace(c) {
  return c.search(WHITESPACE_REGEX) !== -1;
}

function hyphenationAllowed(c) {
  /* Latin character set. Excluding numbers, sign and symbol characters, but including soft hyphen */
  return c.search(HYPHEN_REGEX) !== -1;
}

function resolveBreakOpportunity(chunk, i, chunks, mandatory, noBreakAllowed) {
  if (mandatory.some(function (fn) {
    return fn(chunk, i, chunks);
  })) {
    return MANDATORY;
  }

  if (noBreakAllowed.some(function (fn) {
    return fn(chunk, i, chunks);
  })) {
    return NO_BREAK;
  }

  return BREAK_ALLOWED;
}

function cleanEmptyChunks(chunks) {
  if (chunks[0] === '') {
    chunks.shift();
  }

  if (chunks[chunks.length - 1] === '') {
    chunks.pop();
  }
}

function clamp$1(val, min, max) {
  return Math.max(min, Math.min(max, val));
}

function stringTokenizer() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      string = _ref.string,
      _ref$separator = _ref.separator,
      separator = _ref$separator === void 0 ? '' : _ref$separator,
      _ref$reverse = _ref.reverse,
      reverse = _ref$reverse === void 0 ? false : _ref$reverse,
      _ref$measureText = _ref.measureText,
      measureText = _ref$measureText === void 0 ? function (text) {
    return {
      width: text.length,
      height: 1
    };
  } : _ref$measureText,
      _ref$mandatoryBreakId = _ref.mandatoryBreakIdentifiers,
      mandatoryBreakIdentifiers = _ref$mandatoryBreakId === void 0 ? [includesLineBreak] : _ref$mandatoryBreakId,
      _ref$noBreakAllowedId = _ref.noBreakAllowedIdentifiers,
      noBreakAllowedIdentifiers = _ref$noBreakAllowedId === void 0 ? [] : _ref$noBreakAllowedId,
      _ref$suppressIdentifi = _ref.suppressIdentifier,
      suppressIdentifier = _ref$suppressIdentifi === void 0 ? [includesWhiteSpace, includesLineBreak, function (chunk) {
    return chunk === '';
  }] : _ref$suppressIdentifi,
      _ref$hyphenationIdent = _ref.hyphenationIdentifiers,
      hyphenationIdentifiers = _ref$hyphenationIdent === void 0 ? [hyphenationAllowed] : _ref$hyphenationIdent;

  var chunks = String(string).split(separator);
  cleanEmptyChunks(chunks);
  var length = chunks.length;
  var isNotDone = reverse ? function (p) {
    return p >= 0;
  } : function (p) {
    return p < length;
  };
  var position = reverse ? length : -1; // Set init position 1 step before or after to make first next call go to first position

  function peek(peekAt) {
    var i = clamp$1(peekAt, 0, length - 1);
    var chunk = chunks[i];
    var textMeasure = measureText(chunk);
    var opportunity = resolveBreakOpportunity(chunk, i, chunks, mandatoryBreakIdentifiers, noBreakAllowedIdentifiers);
    return {
      index: i,
      value: chunk,
      breakOpportunity: opportunity,
      suppress: suppressIdentifier.some(function (fn) {
        return fn(chunk, i, chunks);
      }),
      hyphenation: hyphenationIdentifiers.some(function (fn) {
        return fn(chunk, i, chunks);
      }),
      width: textMeasure.width,
      height: textMeasure.height,
      done: false
    };
  }

  function next(jumpToPosition) {
    if (isNaN(jumpToPosition)) {
      if (reverse) {
        position--;
      } else {
        position++;
      }
    } else {
      position = clamp$1(jumpToPosition, 0, length - 1);
    }

    if (isNotDone(position)) {
      return peek(position);
    }

    return {
      done: true
    };
  }

  return {
    next: next,
    peek: peek,
    length: length
  };
}

var HYPHENS_CHAR = "\u2010";
var ELLIPSIS_CHAR = '…';

var BASE = 24;
var PAD = 4;
var BUMP = 1e-12;
var DEFAULT_FONT_HEIGHT = 16;
var DEFAULT_LINE_HEIGHT = 1.2;
var TEXT_REGEX = /^\s*\d+(\.\d+)?px\s*$/i;

function isValidFontSize(val) {
  var type = _typeof(val);

  if (type === 'string') {
    return TEXT_REGEX.test(val);
  }

  return false;
}

function fontSizeToHeight(fontSize) {
  if (isValidFontSize(fontSize)) {
    var size = parseFloat(fontSize);
    var m = PAD * Math.ceil((size + BUMP) / BASE);
    return size + m;
  }

  return DEFAULT_FONT_HEIGHT;
}
function fontSizeToLineHeight(node) {
  var fontSize = node['font-size'] || node.fontSize;

  if (isValidFontSize(fontSize)) {
    return parseFloat(fontSize) * Math.max(isNaN(node.lineHeight) ? DEFAULT_LINE_HEIGHT : node.lineHeight, 0);
  }

  return DEFAULT_FONT_HEIGHT * DEFAULT_LINE_HEIGHT;
}

function resolveMaxAllowedLines(node) {
  var maxHeight = node.maxHeight;
  var maxLines = Math.max(node.maxLines, 1) || Infinity;

  if (isNaN(maxHeight)) {
    return maxLines;
  }

  var computedLineHeight = fontSizeToLineHeight(node);
  return Math.max(1, Math.min(Math.floor(maxHeight / computedLineHeight), maxLines));
}

function initState(node, measureText) {
  return {
    lines: [],
    line: '',
    width: 0,
    maxLines: resolveMaxAllowedLines(node),
    maxWidth: node.maxWidth,
    hyphens: {
      enabled: node.hyphens === 'auto',
      char: HYPHENS_CHAR,
      metrics: measureText(HYPHENS_CHAR)
    }
  };
}

function newLine(state) {
  state.lines.push(state.line);
  state.line = '';
  state.width = 0;
}

function appendToLine(state, token) {
  state.line += token.value;
  state.width += token.width;
}

function insertHyphenAndJump(state, token, iterator) {
  if (token.width > state.maxWidth) {
    return token;
  }

  var startIndex = token.index;

  for (var i = 1; i < 5; i++) {
    var pairToken = iterator.peek(token.index - 1);

    if (!token.hyphenation || !pairToken.hyphenation || token.index === 0) {
      return token;
    }

    if (state.width + state.hyphens.metrics.width <= state.maxWidth) {
      state.line += state.hyphens.char;
      return token;
    }

    if (state.line.length === 1) {
      return token;
    }

    token = iterator.next(startIndex - i);
    state.line = state.line.slice(0, -1);
    state.width -= token.width;
  }

  return token;
}

function breakSequence(state, token, measureText) {
  var charTokenIterator = stringTokenizer({
    string: token.value,
    measureText: measureText
  });

  while (state.lines.length < state.maxLines) {
    var charToken = charTokenIterator.next();

    if (charToken.done) {
      break;
    } else if (state.width + charToken.width > state.maxWidth && charToken.breakOpportunity === BREAK_ALLOWED && state.line.length > 0) {
      charToken = state.hyphens.enabled ? insertHyphenAndJump(state, charToken, charTokenIterator) : charToken;
      newLine(state);
      appendToLine(state, charToken);
    } else {
      appendToLine(state, charToken);
    }
  }
}

function breakAll(node, measureText) {
  var text = node.text;
  var iterator = stringTokenizer({
    string: text,
    separator: '',
    measureText: measureText,
    noBreakAllowedIdentifiers: [function (chunk, i) {
      return i === 0;
    }]
  });
  var state = initState(node, measureText);
  var reduced = true;

  while (state.lines.length < state.maxLines) {
    var token = iterator.next();

    if (token.done) {
      newLine(state);
      reduced = false;
      break;
    } else if (token.breakOpportunity === MANDATORY) {
      newLine(state);
    } else if (state.width + token.width > state.maxWidth && token.breakOpportunity === BREAK_ALLOWED) {
      if (token.suppress) {
        // Token is suppressable and can be ignored
        state.width += token.width;
      } else {
        token = state.hyphens.enabled ? insertHyphenAndJump(state, token, iterator) : token;
        newLine(state);
        appendToLine(state, token);
      }
    } else {
      appendToLine(state, token);
    }
  }

  return {
    lines: state.lines,
    reduced: reduced
  };
}
function breakWord(node, measureText) {
  var text = node.text;
  var iterator = stringTokenizer({
    string: text,
    separator: /(\s|-|\u2010)/,
    measureText: measureText
  });
  var state = initState(node, measureText);
  var reduced = true;

  while (state.lines.length < state.maxLines) {
    var token = iterator.next();

    if (token.done) {
      newLine(state);
      reduced = false;
      break;
    } else if (token.breakOpportunity === MANDATORY) {
      newLine(state);
    } else if (state.width + token.width > state.maxWidth && token.breakOpportunity === BREAK_ALLOWED) {
      if (token.suppress) {
        // Token is suppressable and can be ignored
        newLine(state);
      } else if (token.width > state.maxWidth) {
        // Single sequence is wider then maxWidth, break sequence into multiple lines
        breakSequence(state, token, measureText);
      } else {
        newLine(state);
        appendToLine(state, token);
      }
    } else {
      appendToLine(state, token);
    }
  }

  return {
    lines: state.lines,
    reduced: reduced
  };
}

function generateLineNodes(result, item, halfLead, height) {
  var container = {
    type: 'container',
    children: []
  };

  if (typeof item.id !== 'undefined') {
    // TODO also inherit data attribute and more?
    container.id = item.id;
  }

  var currentY = 0;
  result.lines.forEach(function (line, i) {
    var node = extend({}, item);
    node.text = line;
    node._lineBreak = true; // Flag node as processed to avoid duplicate linebreak run

    currentY += halfLead; // leading height above

    if (result.reduced && i === result.lines.length - 1) {
      node.text += ELLIPSIS_CHAR;
    } else {
      delete node.maxWidth;
    }

    node.dy = isNaN(node.dy) ? currentY : node.dy + currentY;
    currentY += height;
    currentY += halfLead; // Leading height below

    container.children.push(node);
  });
  return container;
}

function shouldLineBreak(item) {
  // If type text and not already broken into lines
  return item.type === 'text' && !item._lineBreak;
}

function wrappedMeasureText(node, measureText) {
  return function (text) {
    return measureText({
      text: text,
      fontSize: node.fontSize,
      fontFamily: node.fontFamily
    });
  };
}

function resolveLineBreakAlgorithm(node) {
  var WORDBREAK = {
    'break-all': breakAll,
    'break-word': breakWord
  };
  return WORDBREAK[node.wordBreak];
}
/**
 * Apply wordBreak rules to text nodes.
 * @ignore
 * @param {function} measureText
 * @returns {function} Event function to convert a text node into multiple nodes
 */

function onLineBreak(measureText) {
  return function (state) {
    var item = state.node;

    if (shouldLineBreak(item)) {
      var wordBreakFn = resolveLineBreakAlgorithm(item);

      if (!wordBreakFn) {
        return;
      }

      var tm = measureText(item);

      if (tm.width > item.maxWidth || includesLineBreak(item.text)) {
        var diff = fontSizeToLineHeight(item) - tm.height;
        var halfLead = diff / 2;
        var result = wordBreakFn(item, wrappedMeasureText(item, measureText));
        state.node = generateLineNodes(result, item, halfLead, tm.height); // Convert node to container
      }
    }
  };
}

function ellipsText(_ref, measureText) {
  var text = _ref.text,
      fontSize = _ref['font-size'],
      fontFamily = _ref['font-family'],
      maxWidth = _ref.maxWidth;
  // eslint-disable-line import/prefer-default-export
  text = typeof text === 'string' ? text : "".concat(text);

  if (maxWidth === undefined) {
    return text;
  }

  var textWidth = measureText({
    text: text,
    fontSize: fontSize,
    fontFamily: fontFamily
  }).width;

  if (textWidth <= maxWidth) {
    return text;
  }

  var min = 0;
  var max = text.length - 1;

  while (min <= max) {
    var reduceIndex = Math.floor((min + max) / 2);
    var reduceText = text.substr(0, reduceIndex) + ELLIPSIS_CHAR;
    textWidth = measureText({
      text: reduceText,
      fontSize: fontSize,
      fontFamily: fontFamily
    }).width;

    if (textWidth <= maxWidth) {
      min = reduceIndex + 1;
    } else {
      // textWidth > maxWidth
      max = reduceIndex - 1;
    }
  }

  return text.substr(0, max) + ELLIPSIS_CHAR;
}

/**
 * Currently some browsers, IE11 and Edge confirmed, doesn't support the dominant-baseline svg-attribute and
 * the browser that does, have different implementations. Thus giving an unpredictable result when rendering'
 * text and predicting it's position (ex. in collision detection).
 *
 * To supplement and the aid in aligning/positioning text with various items, this function can be used
 * to follow a common heuristic across supported renderers.
 * @ignore
 * @param {object} textNode
 * @param {string|number} [textNode['font-size']=0] - String in px format or number
 * @param {string} [textNode['dominant-baseline']] - If baseline is omitted dominant-baseline is used
 * @param {string} [textNode.baseline]
 * @returns {number} Delta-y required to adjust for baseline
 */
function baselineHeuristic(textNode) {
  var baseline = textNode.baseline || textNode['dominant-baseline'];
  var dy = 0;
  var fontSize = parseInt(textNode.fontSize || textNode['font-size'], 10) || 0;

  switch (baseline) {
    case 'hanging':
      dy = fontSize * 0.75;
      break;

    case 'text-before-edge':
      dy = fontSize * 0.85;
      break;

    case 'middle':
      dy = fontSize * 0.25;
      break;

    case 'central':
      dy = fontSize * 0.35;
      break;

    case 'mathemetical':
      dy = fontSize / 2;
      break;

    case 'text-after-edge':
    case 'ideographic':
      dy = -fontSize * 0.2;
      break;

    default:
      dy = 0;
      break;
  }

  return dy;
}

var heightCache = {};
var widthCache = {};
var contextCache = {
  fontSize: undefined,
  fontFamily: undefined
};
var picasso_esm_context;

function setContext() {
  picasso_esm_context = picasso_esm_context || document.createElement('canvas').getContext('2d');
}

function setFont(fontSize, fontFamily) {
  if (contextCache.fontSize === fontSize && contextCache.fontFamily === fontFamily) {
    return;
  }

  picasso_esm_context.font = fontSize + ' ' + fontFamily; // eslint-disable-line

  contextCache.fontSize = fontSize;
  contextCache.fontFamily = fontFamily;
}

function measureTextWidth(text, fontSize, fontFamily) {
  var key = text + fontSize + fontFamily;

  if (typeof widthCache[key] !== 'number') {
    setContext();
    setFont(fontSize, fontFamily);
    widthCache[key] = picasso_esm_context.measureText(text).width;
  }

  return widthCache[key];
}

function measureTextHeight(fontSize) {
  if (typeof heightCache[fontSize] !== 'number') {
    heightCache[fontSize] = fontSizeToHeight(fontSize);
  }

  return heightCache[fontSize];
}
/**
 * @private
 * @param {object} opts
 * @param {string} opts.text - Text to measure
 * @param {string} opts.fontSize - Font size with a unit definition, ex. 'px' or 'em'
 * @param {string} opts.fontFamily - Font family
 * @return {object} Width and height of text in pixels
 * @example
 * measureText({
 *  text: 'my text',
 *  fontSize: '12px',
 *  fontFamily: 'Arial'
 * }); // returns { width: 20, height: 12 }
 */


function measureText$1(_ref) {
  var text = _ref.text,
      fontSize = _ref.fontSize,
      fontFamily = _ref.fontFamily;
  var w = measureTextWidth(text, fontSize, fontFamily);
  var h = measureTextHeight(fontSize);
  return {
    width: w,
    height: h
  };
}
/**
 * Calculates the bounding rectangle of a text node.
 * The bounding rectangle is a approximate of the "em square" seen here (http://www.w3resource.com/html5-canvas/html5-canvas-text.php)
 * @ignore
 * @param {object} attrs - Text node definition
 * @param {number} [attrs.x] - X-coordinate
 * @param {number} [attrs.y] - Y-coordinate
 * @param {number} [attrs.dx] - Delta x-coordinate
 * @param {number} [attrs.dy] - Delta y-coordinate
 * @param {string} [attrs.anchor] - Text anchor
 * @param {number} [attrs.maxWidth] - Maximum allowed text width
 * @return {object} The bounding rectangle
 */

function calcTextBounds(attrs) {
  var measureFn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : measureText$1;
  var fontSize = attrs['font-size'] || attrs.fontSize;
  var fontFamily = attrs['font-family'] || attrs.fontFamily;
  var textMeasure = measureFn({
    text: attrs.text,
    fontFamily: fontFamily,
    fontSize: fontSize
  });
  var calWidth = Math.min(attrs.maxWidth || textMeasure.width, textMeasure.width); // Use actual value if max is not set

  var x = attrs.x || 0;
  var y = attrs.y || 0;
  var dx = attrs.dx || 0;
  var dy = (attrs.dy || 0) + baselineHeuristic(attrs);
  var boundingRect = {
    x: 0,
    y: y + dy - textMeasure.height * 0.75,
    // Magic number for alphabetical baseline
    width: calWidth,
    height: textMeasure.height
  };
  var anchor = attrs['text-anchor'] || attrs.anchor;

  if (anchor === 'middle') {
    boundingRect.x = x + dx - calWidth / 2;
  } else if (anchor === 'end') {
    boundingRect.x = x + dx - calWidth;
  } else {
    boundingRect.x = x + dx;
  }

  return boundingRect;
}
/**
 * Calculates the bounding rectangle of a text node. Including any line breaks.
 * @ignore
 * @param {object} node
 * @param {string} node.text - Text to measure
 * @param {number} [node.x=0] - X-coordinate
 * @param {number} [node.y=0] - Y-coordinate
 * @param {number} [node.dx=0] - Delta x-coordinate
 * @param {number} [node.dy=0] - Delta y-coordinate
 * @param {string} [node.anchor='start'] - Text anchor
 * @param {string} [node.fontSize] - Font size
 * @param {string} [node.fontFamily] - Font family
 * @param {string} [node['font-size']] - Font size
 * @param {string} [node['font-family']] - Font family
 * @param {string} [node.wordBreak] - Word-break option
 * @param {number} [node.maxWidth] - Maximum allowed text width
 * @param {number} [node.maxHeight] - Maximum allowed text height. If both maxLines and maxHeight are set, the property that results in the fewest number of lines is used
 * @param {number} [node.maxLines] - Maximum number of lines allowed.
 * @param {number} [node.lineHeight=1.2] - Line height
 * @param {function} [measureFn] - Optional text measure function
 * @return {object} The bounding rectangle
 */


function textBounds(node) {
  var measureFn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : measureText$1;
  var lineBreakFn = resolveLineBreakAlgorithm(node);
  var fontSize = node['font-size'] || node.fontSize;
  var fontFamily = node['font-family'] || node.fontFamily;
  var tm = measureFn({
    text: node.text,
    fontFamily: fontFamily,
    fontSize: fontSize
  });

  if (lineBreakFn && (tm.width > node.maxWidth || includesLineBreak(node.text))) {
    var resolvedLineBreaks = lineBreakFn(node, function (text) {
      return measureFn({
        text: text,
        fontFamily: fontFamily,
        fontSize: fontSize
      });
    });
    var nodeCopy = extend({}, node);
    var maxWidth = 0;
    var widestLine = '';

    for (var i = 0, len = resolvedLineBreaks.lines.length; i < len; i++) {
      var line = resolvedLineBreaks.lines[i];
      line += i === len - 1 && resolvedLineBreaks.reduced ? ELLIPSIS_CHAR : '';
      var width = measureFn({
        text: line,
        fontSize: fontSize,
        fontFamily: fontFamily
      }).width;

      if (width >= maxWidth) {
        maxWidth = width;
        widestLine = line;
      }
    }

    nodeCopy.text = widestLine;
    var bounds = calcTextBounds(nodeCopy, measureFn);
    bounds.height = fontSizeToLineHeight(node) * resolvedLineBreaks.lines.length;
    return bounds;
  }

  return calcTextBounds(node, measureFn);
}

var LINE_HEIGHT = 1.2;
var CIRCLE_FACTOR = 0.9;

function cbContext$2(node, chart) {
  return {
    node: node,
    data: node.data,
    scale: chart.scale,
    formatter: chart.formatter,
    dataset: chart.dataset
  };
}

function placeTextInRect$1(rect, text, opts) {
  var label = {
    type: 'text',
    text: text,
    maxWidth: rect.width,
    x: 0,
    y: rect.y,
    dx: 0,
    dy: 0,
    fill: opts.fill,
    anchor: 'start',
    baseline: 'alphabetical',
    fontSize: "".concat(opts.fontSize, "px"),
    fontFamily: opts.fontFamily
  };
  var textMetrics = opts.textMetrics;

  if (rect.width < opts.fontSize) {
    return false;
  }

  var wiggleWidth = Math.max(0, rect.width - textMetrics.width);
  label.x = rect.x + opts.align * wiggleWidth;
  label.y = rect.y + textMetrics.height / LINE_HEIGHT;
  return label;
}

function getRectFromCircle(_ref) {
  var cx = _ref.cx,
      cy = _ref.cy,
      r = _ref.r;
  return {
    type: 'circle',
    bounds: {
      cx: cx,
      cy: cy,
      r: r
    }
  };
}

function getSliceBounds(slice) {
  var EPSILON = 1e-12;
  var start = slice.start,
      end = slice.end,
      innerRadius = slice.innerRadius,
      outerRadius = slice.outerRadius,
      offset = slice.offset;

  if (Math.abs(start + 2 * Math.PI - end) > EPSILON) {
    return {
      type: null,
      bounds: null
    };
  }

  var r = innerRadius !== 0 ? innerRadius : outerRadius;
  return getRectFromCircle({
    cx: offset.x,
    cy: offset.y,
    r: r
  });
}

function getBounds(node) {
  if (node.desc && node.desc.slice) {
    return getSliceBounds(node.desc.slice);
  }

  if (node.type === 'circle') {
    return getRectFromCircle(node.attrs);
  }

  if (node.type === 'rect') {
    return {
      type: 'rect',
      bounds: node.bounds
    };
  } // defualt to node.bounds ?


  return {
    type: null,
    bounds: null
  };
}
/**
 * @typedef {object} component--labels~rows-label-strategy
 *
 */

/**
 * @typedef {object} component--labels~rows-label-strategy.settings
 * @property {string} [fontFamily='Arial']
 * @property {number} [fontSize=12]
 * @property {number} [justify=0.5]
 * @property {number} [padding=4]
 * @property {Array<object>} labels
 * @property {string|function} labels[].label - The text value
 * @property {function} labels[].linkData - Link data to the label
 * @property {number} [labels[].align=0.5]
 * @property {string|function} [labels[].fill='#333']
 */


function picasso_esm_rows(_ref2) {
  var settings = _ref2.settings,
      chart = _ref2.chart,
      nodes = _ref2.nodes,
      renderer = _ref2.renderer,
      style = _ref2.style;
  var placer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : placeTextInRect$1;
  var defaults = extend({
    fontSize: 12,
    fontFamily: 'Arial',
    fill: '#333',
    padding: 4,
    align: 0.5,
    justify: 0.5
  }, style.label);
  defaults.fontSize = parseInt(defaults.fontSize, 10);
  var rowSettings = extend({}, defaults, settings);
  var labelSettings = settings.labels.map(function (labelSetting) {
    return extend({}, rowSettings, labelSetting);
  });
  var labelStruct = {};
  var labels = [];

  for (var i = 0, len = nodes.length; i < len; i++) {
    var node = nodes[i];
    var arg = cbContext$2(node, chart);

    var _getBounds = getBounds(node),
        type = _getBounds.type,
        bounds = _getBounds.bounds;

    if (!bounds) {
      continue;
    }

    var totalHeight = 0;
    var measurements = [];
    var texts = [];
    var maxHeight = type === 'circle' ? 2 * bounds.r * CIRCLE_FACTOR : bounds.height;
    totalHeight += rowSettings.padding;
    var j = void 0;

    for (j = 0; j < labelSettings.length; j++) {
      var lblStngs = labelSettings[j];
      var text = typeof lblStngs.label === 'function' ? lblStngs.label(arg, i) : '';
      labelStruct.fontFamily = lblStngs.fontFamily;
      labelStruct.fontSize = "".concat(lblStngs.fontSize, "px");
      labelStruct.text = text;
      var measured = renderer.measureText(labelStruct);
      totalHeight += measured.height + lblStngs.padding;

      if (totalHeight > maxHeight) {
        break;
      }

      texts.push(text);
      measurements.push(measured);
    }

    var labelCount = j;
    var wiggleHeight = Math.max(0, maxHeight - totalHeight);
    var currentY = void 0;

    if (type === 'circle') {
      currentY = bounds.cy - bounds.r * CIRCLE_FACTOR;
    } else {
      currentY = bounds.y;
    }

    currentY += rowSettings.justify * wiggleHeight + rowSettings.padding;

    for (j = 0; j < labelCount; j++) {
      var _lblStngs = labelSettings[j];
      var rect = void 0;

      if (type === 'circle') {
        var maxYDistToCenter = Math.max(Math.abs(currentY - bounds.cy), Math.abs(currentY + measurements[j].height - bounds.cy));
        var halfWidth = Math.sqrt(bounds.r * bounds.r - maxYDistToCenter * maxYDistToCenter);
        rect = {
          x: bounds.cx - halfWidth + rowSettings.padding,
          y: currentY,
          width: 2 * halfWidth - 2 * rowSettings.padding,
          height: measurements[j].height
        };
      } else {
        rect = {
          x: bounds.x + rowSettings.padding,
          y: currentY,
          width: bounds.width - 2 * rowSettings.padding,
          height: measurements[j].height
        };
      }

      currentY += measurements[j].height + rowSettings.padding;
      var fill = typeof _lblStngs.fill === 'function' ? _lblStngs.fill(arg, i) : _lblStngs.fill;
      var linkData = typeof _lblStngs.linkData === 'function' ? _lblStngs.linkData(arg, i) : undefined;
      var label = placer(rect, texts[j], {
        fill: fill,
        align: _lblStngs.align,
        fontSize: _lblStngs.fontSize,
        fontFamily: _lblStngs.fontFamily,
        textMetrics: measurements[j]
      });

      if (label) {
        if (label.text && label.text !== ELLIPSIS_CHAR) {
          var ellipsed = ellipsText(label, renderer.measureText);

          if (ELLIPSIS_CHAR === ellipsed) {
            // don't include label if it's only an ellipsis
            continue;
          }

          label.ellipsed = ellipsed;
        }

        if (typeof linkData !== 'undefined') {
          label.data = linkData;
        }

        labels.push(label);
      }
    }
  }

  return labels;
}

var strategies = {
  bar: bars,
  slice: slices,
  rows: picasso_esm_rows
};

/**
 * @typedef {object} component--labels
 * @property {string} [type='labels']
 */

/**
 * @typedef {object} component--labels.settings
 * @property {Array<object>} sources
 * @property {string} sources[].component
 * @property {string} sources[].selector
 * @property {component--labels~label-strategy} sources[].strategy
 */

function strategy(_ref, fn) {
  var chart = _ref.chart,
      source = _ref.source,
      rect = _ref.rect,
      renderer = _ref.renderer,
      style = _ref.style;
  var component = chart.component(source.component);

  if (!component) {
    return [];
  }

  var nodes = chart.findShapes(source.selector).filter(function (n) {
    return n.key === source.component;
  });
  return fn({
    chart: chart,
    settings: source.strategy.settings,
    nodes: nodes,
    rect: {
      x: 0,
      y: 0,
      width: rect.width,
      height: rect.height
    },
    renderer: renderer,
    style: style
  });
}
var labelsComponent = {
  require: ['chart', 'renderer', 'settings'],
  defaultSettings: {
    settings: {},
    style: {
      label: '$label'
    }
  },
  render: function render() {
    var _this = this;

    var stngs = this.settings.settings;
    var labels = [];
    (stngs.sources || []).forEach(function (source) {
      if (source.strategy && strategies[source.strategy.type] && source.component) {
        labels.push.apply(labels, _toConsumableArray$1(strategy({
          chart: _this.chart,
          rect: _this.rect,
          renderer: _this.renderer,
          source: source,
          style: _this.style
        }, strategies[source.strategy.type])));
      }
    });
    return labels;
  }
};

function picasso_esm_labels(picasso) {
  picasso.component('labels', labelsComponent);
}

/**
 * @typedef {object}
 * @alias component--legend-cat.settings
 */

var DEFAULT_SETTINGS$6 = {
  /**
   * @typedef {object=}
   */
  layout: {
    /**
     * Maximum number of columns (vertical) or rows (horizontal)
     * @type {number=}
     */
    size: 1,

    /**
     * Layout direction. Either `'ltr'` or `'rtl'`
     * @type {string=}
     */
    direction: 'ltr',

    /** Initial scroll offset
     * @type {number=} */
    scrollOffset: 0
  },

  /**
   * Settings applied per item
   * @typedef {object=}
   */
  item: {
    /** Whether to show the current item
     * @type {boolean=} */
    show: true,
    justify: 0.5,
    align: 0.5,

    /**
     * @typedef {object=} */
    label: {
      fontSize: '12px',
      fontFamily: 'Arial',
      fill: '#595959',

      /** Word break rule, how to apply line break if label text overflows its maxWidth property. Either `'break-word'` or `'break-all'`
       * @type {string=} */
      wordBreak: 'none',

      /** Max number of lines allowed if label is broken into multiple lines (only applicable with wordBreak)
       * @type {number=} */
      maxLines: 2,

      /** Maximum width of label, in px
       * @type {number=} */
      maxWidth: 136,
      lineHeight: 1.2
    },

    /**
     * @typedef {object=} */
    shape: {
      /**
       * @type {string=} */
      type: 'square',

      /**
       * @type {number=} */
      size: 12
    }
  },

  /**
   * @typedef {object=} */
  title: {
    /** Whether to show the title
     * @type {boolean=} */
    show: true,

    /** Title text. Defaults to the title of the provided data field
     * @type {string=} */
    text: undefined,

    /** Horizontal alignment of the text. Allowed values are `'start'`, `'middle'` and `'end'`
     * @type {string}
     */
    anchor: 'start',
    fontSize: '16px',
    fontFamily: 'Arial',
    fill: '#595959',

    /** Word break rule, how to apply line break if label text overflows its maxWidth property. Either `'break-word'` or `'break-all'`
     * @type {string=} */
    wordBreak: 'none',

    /** Max number of lines allowed if label is broken into multiple lines, is only appled when `wordBreak` is not set to `'none'`
     * @type {number=} */
    maxLines: 2,

    /** Maximum width of title, in px
     * @type {number=} */
    maxWidth: 156,
    lineHeight: 1.25
  },

  /**
   * @typedef {object=} */
  navigation: {
    /**
     * @typedef {object=} */
    button: {
      /**
       * @type {object<string, boolean>=} */
      class: undefined,

      /**
       * @type {function} */
      content: undefined
    },

    /** Whether the button should be disabled or not
     * @type {boolean=} */
    disabled: false
  }
};
/**
 * Resolve settings based on input, defaults, and data
 *
 * @ignore
 * @param {legendComponent} comp - The component instance
 */

function resolveSettings$2(comp) {
  var domain = comp.scale.domain();
  var data = {
    items: []
  };
  var dock = comp.settings.layout.dock;

  if (comp.scale.type === 'threshold-color') {
    var fields = comp.scale.data().fields;
    var sourceField = fields[0];

    var formatter = function formatter(v) {
      return String(v);
    };

    if (comp.settings.formatter) {
      formatter = comp.chart.formatter(comp.settings.formatter);
    } else if (sourceField) {
      formatter = sourceField.formatter();
    }

    for (var i = 0; i < domain.length - 1; i++) {
      var it = {
        value: domain[i],
        label: "".concat(formatter(domain[i]), " - < ").concat(formatter(domain[i + 1]))
      };

      if (sourceField) {
        it.source = {
          field: sourceField.id()
        };
      }

      data.items.push(it);
    }

    var orientation = dock === 'top' || dock === 'bottom' ? 'horizontal' : 'vertical';

    if (orientation === 'vertical') {
      data.items.reverse();
    }
  } else {
    var _labels = comp.scale.labels ? comp.scale.labels() : null;

    data.items = domain.map(function (d, idx) {
      var datum = comp.scale.datum ? extend({}, comp.scale.datum(d)) : {
        value: d
      };
      datum.value = d;

      if (comp.scale.label) {
        datum.label = comp.scale.label(d);
      } else if (_labels) {
        datum.label = _labels[idx];
      }

      return datum;
    });
  }

  var title = comp.resolver.resolve({
    data: {
      fields: comp.scale.data().fields
    },
    defaults: extend(true, {}, DEFAULT_SETTINGS$6.title, comp.style.title),
    settings: comp.settings.settings.title
  });
  var layout = comp.resolver.resolve({
    data: {
      fields: comp.scale.data().fields
    },
    defaults: DEFAULT_SETTINGS$6.layout,
    settings: comp.settings.settings.layout
  });
  var labels = comp.resolver.resolve({
    data: data,
    defaults: extend(true, {}, DEFAULT_SETTINGS$6.item.label, comp.style.item.label),
    settings: (comp.settings.settings.item || {}).label
  });
  var shapeSettings = extend(true, {}, (comp.settings.settings.item || {}).shape);

  if (typeof shapeSettings.fill === 'undefined' && comp.settings.scale) {
    shapeSettings.fill = {
      scale: comp.settings.scale
    };
  }

  var symbols = comp.resolver.resolve({
    data: data,
    defaults: extend(true, {}, DEFAULT_SETTINGS$6.item.shape, comp.style.item.shape),
    settings: shapeSettings
  });
  var items = comp.resolver.resolve({
    data: data,
    defaults: extend(true, {}, {
      show: DEFAULT_SETTINGS$6.item.show
    }),
    settings: {
      show: (comp.settings.settings.item || {}).show
    }
  });

  function range(item, i) {
    var v = item.data.value;
    var next = domain[i + 1];
    item.data.value = [v, next];
  }

  if (comp.scale.type === 'threshold-color') {
    var _orientation = dock === 'top' || dock === 'bottom' ? 'horizontal' : 'vertical';

    if (_orientation === 'vertical') {
      items.items.reverse().forEach(range);
      items.items.reverse();
    } else {
      items.items.forEach(range);
    }
  }

  return {
    title: title,
    labels: labels,
    symbols: symbols,
    items: items,
    layout: layout
  };
}

/* eslint no-mixed-operators:0 */

function placeTextInRect$2(rect, label, opts) {
  var textMetrics = opts.textMetrics;

  if (rect.height < textMetrics.height) {
    return false;
  }

  var wiggleWidth = Math.max(0, rect.width - textMetrics.width);
  label.baseline = 'text-before-edge';
  var wiggleHeight = Math.max(0, rect.height - textMetrics.height);
  label.x = rect.x + opts.align * wiggleWidth;
  label.y = rect.y + opts.justify * wiggleHeight + parseInt(label.fontSize, 10) * 0.175; // 0.175 - basline offset

  return label;
}

function wiggleSymbol(container, size, opts) {
  var wiggleWidth = Math.max(0, container.width - size);
  var wiggleHeight = Math.max(0, container.height - size);
  return {
    x: container.x + size / 2 + opts.align * wiggleWidth,
    y: container.y + size / 2 + opts.justify * wiggleHeight
  };
}

function createRenderItem(_ref) {
  var _ref$x = _ref.x,
      x = _ref$x === void 0 ? 0 : _ref$x,
      y = _ref.y,
      item = _ref.item,
      globalMetrics = _ref.globalMetrics,
      createSymbol = _ref.createSymbol,
      _ref$direction = _ref.direction,
      direction = _ref$direction === void 0 ? 'ltr' : _ref$direction;
  var label = item.label.displayObject;
  var labelBounds = item.label.bounds;
  var symbolItem = item.symbol.meta;
  var rtl = direction === 'rtl';
  var labelRect = {
    x: rtl ? x + globalMetrics.maxLabelBounds.width : x + globalMetrics.maxSymbolSize + globalMetrics.spacing,
    y: y,
    width: globalMetrics.maxLabelBounds.width,
    height: Math.max(globalMetrics.maxSymbolSize, globalMetrics.maxLabelBounds.height)
  };
  var wiggled = wiggleSymbol({
    x: rtl ? x + globalMetrics.maxLabelBounds.width + globalMetrics.spacing : x,
    y: y,
    width: globalMetrics.maxSymbolSize,
    height: labelRect.height
  }, symbolItem.size, {
    align: typeof symbolItem.align === 'undefined' ? 0.5 : symbolItem.align,
    justify: typeof symbolItem.justify === 'undefined' ? 0.5 : symbolItem.justify
  });
  var symbol = createSymbol(extend({}, symbolItem, wiggled));
  delete symbol.collider;
  label.anchor = rtl ? 'end' : 'start';
  placeTextInRect$2(labelRect, label, {
    textMetrics: labelBounds,
    fontSize: parseInt(label.fontSize, 10),
    align: 0.0,
    justify: 0.5
  });
  var container = {
    type: 'container',
    data: item.label.displayObject.data,
    children: [symbol, label],
    collider: {
      type: 'rect',
      x: x,
      y: y,
      width: globalMetrics.maxItemBounds.width,
      height: globalMetrics.maxItemBounds.height
    }
  };
  return {
    item: container,
    metrics: labelRect
  };
}

function _getItemsToRender(_ref2, rect, _ref3) {
  var viewRect = _ref2.viewRect;
  var itemized = _ref3.itemized,
      _ref3$create = _ref3.create,
      create = _ref3$create === void 0 ? createRenderItem : _ref3$create,
      parallels = _ref3.parallels,
      createSymbol = _ref3.createSymbol;
  var direction = itemized.layout.direction;
  var globalMetrics = itemized.globalMetrics;
  var legendItems = itemized.items;
  var isHorizontal = itemized.layout.orientation === 'horizontal';
  var s = 0;
  var renderItems = [];
  var fixedHeight = globalMetrics.maxItemBounds.height;
  var fixedWidth = globalMetrics.maxItemBounds.width;
  var rowHeight = itemized.layout.margin.vertical + fixedHeight;
  var columnWidth = itemized.layout.margin.horizontal + fixedWidth;
  var x = rect.x;
  var y = rect.y;
  var shift = viewRect.x - rect.x;

  for (var i = 0; i < legendItems.length; i++) {
    var renderItem = create({
      y: y,
      x: direction === 'rtl' ? viewRect.x + shift + viewRect.width - fixedWidth - (x - rect.x) : x,
      item: legendItems[i],
      globalMetrics: globalMetrics,
      direction: direction,
      createSymbol: createSymbol
    });

    if (isHorizontal && x >= viewRect.x - fixedWidth || !isHorizontal && y >= viewRect.y - fixedHeight) {
      renderItems.push(renderItem.item);
    }

    s++;

    if (s >= parallels) {
      s = 0;

      if (isHorizontal) {
        x += columnWidth; // next column

        y = rect.y; // reset y to first row
      } else {
        y += rowHeight; // next row

        x = rect.x; // reset x to first column
      }
    } else if (isHorizontal) {
      y += rowHeight; // next row
    } else {
      x += columnWidth; // next column
    }

    if (!isHorizontal && y > viewRect.y + viewRect.height) {
      break;
    } else if (isHorizontal && x > viewRect.x + viewRect.width) {
      break;
    }
  }

  return renderItems;
}

function _itemize(_ref4, renderer) {
  var resolved = _ref4.resolved,
      dock = _ref4.dock;
  var label;
  var items = [];
  var item;
  var sourceItems = resolved.items.items;
  var sourceSymbols = resolved.symbols.items;
  var sourceLabels = resolved.labels.items;
  var maxSymbolSize = 0;
  var maxLabelWidth = 0;
  var maxLabelHeight = 0;

  for (var i = 0; i < sourceItems.length; i++) {
    if (sourceItems[i].show === false) {
      continue;
    }

    var text = typeof sourceLabels[i].text !== 'undefined' ? sourceLabels[i].text : sourceLabels[i].data.label || '';
    label = extend({}, sourceLabels[i], {
      // create the displayObject here in order to measure it
      type: 'text',
      fontSize: "".concat(parseInt(sourceLabels[i].fontSize, 10), "px"),
      text: text,
      title: text
    });
    item = {
      symbol: {
        // can't create a displayObject here due to need to wiggle the center position of the symbol later on,
        // just store the object needed later on
        meta: sourceSymbols[i]
      },
      label: {
        displayObject: label,
        bounds: renderer.textBounds(label)
      }
    };
    items.push(item);
    maxSymbolSize = Math.max(sourceSymbols[i].size, maxSymbolSize);
    maxLabelWidth = Math.max(item.label.bounds.width, maxLabelWidth);
    maxLabelHeight = Math.max(item.label.bounds.height, maxLabelHeight);
  }

  return {
    items: items,
    globalMetrics: {
      spacing: 8,
      maxSymbolSize: maxSymbolSize,
      maxItemBounds: {
        height: Math.max(maxSymbolSize, maxLabelHeight),
        width: maxSymbolSize + 8 + maxLabelWidth
      },
      maxLabelBounds: {
        width: maxLabelWidth,
        height: maxLabelHeight
      }
    },
    layout: {
      margin: {
        vertical: typeof resolved.layout.item.vertical !== 'undefined' ? resolved.layout.item.vertical : 4,
        horizontal: typeof resolved.layout.item.horizontal !== 'undefined' ? resolved.layout.item.horizontal : 4
      },
      mode: resolved.layout.item.mode,
      size: resolved.layout.item.size,
      orientation: dock === 'top' || dock === 'bottom' ? 'horizontal' : 'vertical',
      direction: resolved.layout.item.direction,
      scrollOffset: resolved.layout.item.scrollOffset
    }
  };
}

function _extent(itemized, parallels) {
  var count = itemized.items.length;
  var size = Math.ceil(count / parallels);
  var property = itemized.layout.orientation === 'horizontal' ? 'width' : 'height';
  var margin = property === 'width' ? 'horizontal' : 'vertical';
  return itemized.globalMetrics.maxItemBounds[property] * size + (size - 1) * itemized.layout.margin[margin];
}

function _spread(itemized, parallels) {
  var size = parallels;
  var property = itemized.layout.orientation === 'horizontal' ? 'height' : 'width';
  var margin = property === 'width' ? 'horizontal' : 'vertical';
  return itemized.globalMetrics.maxItemBounds[property] * size + // expected vertical size of items
  (size - 1) * itemized.layout.margin[margin]; // expected spacing between items
}

function _parallelize(availableExtent, availableSpread, itemized) {
  var count = itemized.items.length;
  var extentProperty = itemized.layout.orientation === 'horizontal' ? 'width' : 'height';
  var margin = extentProperty === 'width' ? 'horizontal' : 'vertical';
  var extentInPx = itemized.globalMetrics.maxItemBounds[extentProperty] * count + (count - 1) * itemized.layout.margin[margin];
  var numNeeded = Math.ceil(extentInPx / availableExtent);

  if (availableSpread != null) {
    var spreadProperty = itemized.layout.orientation === 'horizontal' ? 'height' : 'width';
    var numAllowed = Math.floor(availableSpread / (4 + itemized.globalMetrics.maxItemBounds[spreadProperty]));
    numNeeded = Math.min(numNeeded, numAllowed);
  }

  var numInput = isNaN(itemized.layout.size) ? 1 : itemized.layout.size;
  return Math.max(1, Math.min(numNeeded, numInput));
}
function itemRendererFactory (legend, _ref5) {
  var _ref5$onScroll = _ref5.onScroll,
      onScroll = _ref5$onScroll === void 0 ? function () {} : _ref5$onScroll;
  var itemized;
  var parallels;
  var viewRect;
  var containerRect;
  var _offset = null;
  var overflow = 0;
  var api = {
    itemize: function itemize(obj) {
      itemized = _itemize(obj, legend.renderer);
      _offset = !isNaN(itemized.layout.scrollOffset) ? itemized.layout.scrollOffset : _offset; // Set the initial offset
    },
    getItemsToRender: function getItemsToRender(obj) {
      viewRect = obj.viewRect;
      overflow = api.getContentOverflow(viewRect);
      var ext = api.extent();
      _offset = Math.max(0, Math.min(_offset, overflow));
      containerRect = extend({}, viewRect);
      var offsetProperty = api.orientation() === 'horizontal' ? 'x' : 'y';
      containerRect[offsetProperty] -= _offset;
      containerRect[offsetProperty === 'x' ? 'width' : 'height'] = ext;
      return _getItemsToRender(obj, containerRect, {
        itemized: itemized,
        parallels: parallels,
        createSymbol: legend.symbol
      });
    },
    parallelize: function parallelize(availableExtent, availableSpread) {
      parallels = _parallelize(availableExtent, availableSpread, itemized);
      return parallels;
    },
    hasContentOverflow: function hasContentOverflow() {
      var property = itemized.layout.orientation === 'horizontal' ? 'width' : 'height';
      return _extent(itemized, parallels) > viewRect[property];
    },
    getContentOverflow: function getContentOverflow() {
      var rect = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : viewRect;
      var property = itemized.layout.orientation === 'horizontal' ? 'width' : 'height';
      return Math.max(0, _extent(itemized, parallels) - rect[property]);
    },
    getNextSize: function getNextSize() {
      // TODO - calculate the actual size to next item to ensure alignment
      var property = itemized.layout.orientation === 'horizontal' ? 'width' : 'height';
      var margin = property === 'width' ? 'horizontal' : 'vertical';
      return itemized.globalMetrics.maxItemBounds[property] + itemized.layout.margin[margin];
    },
    getPrevSize: function getPrevSize() {
      // TODO - calculate the actual size to next item to ensure alignment
      var property = itemized.layout.orientation === 'horizontal' ? 'width' : 'height';
      var margin = property === 'width' ? 'horizontal' : 'vertical';
      return itemized.globalMetrics.maxItemBounds[property] + itemized.layout.margin[margin];
    },
    hasNext: function hasNext() {
      if (api.orientation() === 'horizontal') {
        return viewRect.x + viewRect.width < containerRect.x + containerRect.width;
      }

      return viewRect.y + viewRect.height < containerRect.y + containerRect.height;
    },
    hasPrev: function hasPrev() {
      if (api.orientation() === 'horizontal') {
        return containerRect.x < viewRect.x;
      }

      return containerRect.y < viewRect.y;
    },
    next: function next() {
      api.scroll(-api.getNextSize());
    },
    prev: function prev() {
      api.scroll(api.getPrevSize());
    },
    scroll: function scroll(delta) {
      var current = Math.max(0, Math.min(overflow, _offset - delta));

      if (current === _offset) {
        return;
      }

      _offset = current;
      onScroll();
    },
    offset: function offset() {
      return _offset;
    },
    orientation: function orientation() {
      return itemized.layout.orientation;
    },
    direction: function direction() {
      return itemized.layout.direction;
    },
    extent: function extent() {
      return _extent(itemized, parallels);
    },
    // total amount of space along orientation
    spread: function spread() {
      return _spread(itemized, parallels);
    } // total amount of space perpendicular to orientation

  };
  return api;
}

/**
 * Concatenate object keys into a space separated string. Use for transforming a 'class name map' into a class string
 * @private
 * @param  {Object} classMap Object with class names as keys and true or false values depending on if they should be in the returned class string or not
 * @return {String} Space separated string with class names
 */
function classString(classMap) {
  return Object.keys(classMap).filter(function (className) {
    return classMap[className];
  }).join(' ');
}

var DIR = {
  up: "\u25B2",
  right: "\u25B6",
  down: "\u25BC",
  left: "\u25C0"
};

function _itemize$1(_ref) {
  var dock = _ref.dock,
      navigation = _ref.navigation;
  return {
    layout: {
      orientation: dock === 'top' || dock === 'bottom' ? 'vertical' : 'horizontal'
    },
    navigation: navigation
  };
}

function btn(h, _ref2) {
  var size = _ref2.size,
      isActive = _ref2.isActive,
      direction = _ref2.direction,
      nav = _ref2.nav,
      attrs = _ref2.attrs;
  var c = {};
  var content = '';

  if (nav && nav.button) {
    if (typeof nav.button.class === 'function') {
      c = nav.button.class({
        direction: direction
      });
    } else if (nav.button.class) {
      c = nav.button.class;
    }

    if (typeof nav.button.content === 'function') {
      content = nav.button.content(h, {
        direction: direction
      });
    }
  }

  var style = {
    width: "".concat(size, "px"),
    minWidth: "".concat(size, "px"),
    height: "".concat(size, "px")
  };

  if (!Object.keys(c).length) {
    // if no classes are set, add some basic styling
    style.border = '0';
    style.background = 'none';
  }

  var attrsMerged = attrs;

  if (!isActive || nav && nav.disabled) {
    attrsMerged.disabled = 'disabled';
  }

  return h('button', extend({
    class: classString(c),
    style: style
  }, attrsMerged), [content || h('span', {
    style: {
      pointerEvents: 'none'
    }
  }, [DIR[direction]])]);
}

function _render$1(renderer, _ref3, itemized, legend) {
  var rect = _ref3.rect,
      itemRenderer = _ref3.itemRenderer;

  if (!renderer || !renderer.renderArgs) {
    return;
  }

  renderer.size(rect);
  var h = renderer.renderArgs[0];
  var isVertical = itemized.layout.orientation === 'vertical'; // orientation of the navigation (not the legend)

  var isRtl = itemRenderer.direction() === 'rtl';
  var hasNext = itemRenderer.hasNext();
  var hasPrev = itemRenderer.hasPrev();

  if (!hasPrev && !hasNext) {
    renderer.render([]);
    return;
  }

  var buttonSize = 32;
  var order = isVertical ? ['right', 'left'] : ['down', 'up'];

  if (isRtl && isVertical) {
    order.reverse();
  }

  var nodes = [h('div', {
    style: {
      position: 'relative',
      display: 'flex',
      'flex-direction': isVertical ? 'column' : 'row',
      'justify-content': 'center',
      height: '100%',
      pointerEvents: 'auto'
    },
    dir: isRtl && !isVertical ? 'rtl' : 'ltr'
  }, [btn(h, {
    size: buttonSize,
    isActive: hasNext,
    direction: order[0],
    attrs: {
      'data-action': 'next',
      'data-component-key': legend.settings.key
    },
    nav: itemized.navigation
  }), btn(h, {
    size: buttonSize,
    isActive: hasPrev,
    direction: order[1],
    attrs: {
      'data-action': 'prev',
      'data-component-key': legend.settings.key
    },
    nav: itemized.navigation
  })])];
  renderer.render(nodes);
}

function navigationRendererFactory (legend) {
  var itemized;
  var nav = {
    itemize: function itemize(obj) {
      itemized = _itemize$1(obj);
    },
    render: function render(obj) {
      return _render$1(nav.renderer, obj, itemized, legend);
    },
    extent: function extent() {
      return 32;
    },
    spread: function spread() {
      return 64;
    }
  };
  return nav;
}

function _itemize$2(_ref, legend) {
  var resolved = _ref.resolved;

  if (resolved.title.item.show === false) {
    return null;
  }

  var t = extend({}, resolved.title.item, {
    type: 'text'
  });

  if (resolved.layout.item.direction === 'rtl') {
    if (!t.anchor || t.anchor === 'start') {
      t.anchor = 'end';
    } else if (t.anchor === 'end') {
      t.anchor = 'start';
    }
  }

  if (typeof resolved.title.settings.text === 'undefined') {
    var fields = legend.scale.data().fields;
    t.text = fields && fields[0] ? fields[0].title() : '';
  }

  return {
    displayObject: t,
    bounds: legend.renderer.textBounds(t)
  };
}

function _render$2(_ref2, renderer, itemized) {
  var rect = _ref2.rect;

  if (!renderer) {
    return;
  }

  var nodes = [];
  renderer.size(rect);

  if (itemized) {
    var align = {
      start: 0,
      end: rect.width,
      middle: rect.width / 2
    };
    nodes.push(extend({}, itemized.displayObject, {
      x: align[itemized.displayObject.anchor] || 0,
      y: 0,
      baseline: 'text-before-edge',
      title: itemized.displayObject.text
    }));
  }

  renderer.render(nodes);
}

function titleRendererFactory (legend) {
  var itemized;
  var api = {
    itemize: function itemize(obj) {
      itemized = _itemize$2(obj, legend);
    },
    render: function render(obj) {
      _render$2(obj, api.renderer, itemized);
    },
    spread: function spread() {
      return itemized ? itemized.bounds.height : 0;
    },
    extent: function extent() {
      return itemized ? itemized.bounds.width : 0;
    }
  };
  return api;
}

/* eslint no-mixed-operators:0 */

function picasso_esm_layout(rect, display, orientation, _ref) {
  var itemRenderer = _ref.itemRenderer,
      navigationRenderer = _ref.navigationRenderer,
      titleRenderer = _ref.titleRenderer,
      _ref$isPreliminary = _ref.isPreliminary,
      isPreliminary = _ref$isPreliminary === void 0 ? false : _ref$isPreliminary;
  var title;
  var content;
  var navigation;
  var preferredSize = 0;
  var paddedRect = {
    x: display.spacing,
    y: display.spacing,
    width: rect.width - 2 * display.spacing,
    height: rect.height - 2 * display.spacing
  };
  title = {
    x: paddedRect.x,
    y: paddedRect.y,
    width: paddedRect.width,
    height: titleRenderer.spread()
  };

  if (orientation === 'horizontal') {
    // const titleAtTop = false;
    // if (titleAtTop) { // this might be a nicer layout sometimes
    //   // |------------------|
    //   // |title             |
    //   // |------------|-----|
    //   // |content     | nav |
    //   // |------------|-----|
    //   // available space for items without navigation UI
    //   const availableExtentForItems = paddedRect.width;
    //   const availableSpreadForItems = paddedRect.height - (title.y + title.height) + 8;
    //   const isRtl = itemRenderer.direction() === 'rtl';
    //   itemRenderer.parallelize(availableExtentForItems, isPreliminary ? undefined : availableSpreadForItems);
    //   const navigationSize = itemRenderer.extent() > availableExtentForItems ? navigationRenderer.extent() : 0;
    //   content = {
    //     x: paddedRect.x,
    //     y: title.y + title.height,
    //     width: paddedRect.width - navigationSize,
    //     height: availableSpreadForItems
    //   };
    //   navigation = {
    //     x: content.x + content.width,
    //     y: title.y + title.height,
    //     width: navigationSize,
    //     height: paddedRect.height - (title.y + title.height) + 8
    //   };
    //   if (isRtl) { // switch navigation and content
    //     navigation.x = content.x;
    //     content.x = navigation.x + navigation.width;
    //     // totalContent.x = navigation.x;
    //   }
    //   preferredSize = title.height + Math.max(navigationRenderer.spread(), itemRenderer.spread());
    // } else {
    // |-----|------------|-----|
    // |title|content     | nav |
    // |-----|------------|-----|
    title = {
      x: paddedRect.x,
      y: paddedRect.y,
      width: titleRenderer.extent(),
      height: titleRenderer.spread()
    }; // available space for items without navigation UI

    var availableExtentForItems = paddedRect.width - title.width - (title.width ? display.spacing : 0);
    var availableSpreadForItems = paddedRect.height;
    itemRenderer.parallelize(availableExtentForItems, isPreliminary ? undefined : availableSpreadForItems);
    var navigationSize = itemRenderer.extent() > availableExtentForItems ? navigationRenderer.extent() : 0;
    var spread = itemRenderer.spread();
    var navigationSpread = navigationSize ? navigationRenderer.spread() : 0;
    content = {
      x: title.x + title.width + (title.width ? display.spacing : 0),
      y: paddedRect.y + Math.max(0, (navigationSpread - spread) / 2),
      width: paddedRect.width - navigationSize - title.width - (navigationSize ? display.spacing : 0) - (title.width ? display.spacing : 0),
      height: availableSpreadForItems
    };
    navigation = {
      x: content.x + content.width + (navigationSize ? display.spacing : 0),
      y: paddedRect.y,
      width: navigationSize,
      height: paddedRect.height
    };
    title.y = content.y;
    var isRtl = itemRenderer.direction() === 'rtl';

    if (isRtl) {
      // switch title, content and navigation
      navigation.x = paddedRect.x;
      content.x = navigation.x + navigation.width + (navigation.width ? display.spacing : 0);
      title.x = content.x + content.width + (title.width ? display.spacing : 0);
    }

    preferredSize = Math.max(title.height, navigationSpread, itemRenderer.spread()); // }
  } else {
    // |------------|
    // |title       |
    // |------------|
    // |content     |
    // |------------|
    // |navigation  |
    // |------------|
    var _availableExtentForItems = paddedRect.height - title.height - (title.height ? display.spacing : 0);

    var _availableSpreadForItems = paddedRect.width;
    itemRenderer.parallelize(_availableExtentForItems, isPreliminary ? undefined : _availableSpreadForItems);

    var _navigationSize = itemRenderer.extent() > _availableExtentForItems ? navigationRenderer.extent() : 0;

    navigation = {
      x: paddedRect.x,
      y: paddedRect.y + paddedRect.height - _navigationSize,
      width: paddedRect.width,
      height: _navigationSize
    };
    content = {
      x: paddedRect.x,
      y: title.y + title.height + (title.height ? display.spacing : 0),
      width: paddedRect.width,
      height: paddedRect.height - title.height - (title.height ? display.spacing : 0) - navigation.height - (navigation.height ? display.spacing : 0)
    };
    preferredSize = Math.max(titleRenderer.extent(), _navigationSize ? navigationRenderer.spread() : 0, itemRenderer.spread());
  }

  content = extend({}, rect, {
    x: rect.x + content.x,
    y: rect.y + content.y,
    width: content.width,
    height: content.height
  });
  navigation.x += rect.x;
  navigation.y += rect.y;
  title.x += rect.x;
  title.y += rect.y;
  return {
    title: extend({}, rect, title),
    content: extend({}, rect, content),
    navigation: extend({}, rect, navigation),
    orientation: orientation,
    preferredSize: preferredSize
  };
}

function picasso_esm_update(comp) {
  comp.state.resolved = resolveSettings$2(comp);
  comp.titleRenderer.itemize({
    resolved: comp.state.resolved,
    dock: comp.settings.layout.dock || 'center'
  });
  comp.itemRenderer.itemize({
    resolved: comp.state.resolved,
    dock: comp.settings.layout.dock || 'center'
  });
  comp.navigationRenderer.itemize({
    resolved: comp.state.resolved,
    dock: comp.settings.layout.dock || 'center',
    navigation: comp.settings.settings.navigation
  });
  comp.state.display = {
    spacing: 8
  };
}

function _preferredSize(comp, size) {
  var s = 0;
  var dock = comp.settings.layout.dock || 'center';
  var orientation = dock === 'top' || dock === 'bottom' ? 'horizontal' : 'vertical';
  var d = comp.state.display;
  var tempLayout = picasso_esm_layout(size.inner, d, orientation, {
    itemRenderer: comp.itemRenderer,
    navigationRenderer: comp.navigationRenderer,
    titleRenderer: comp.titleRenderer,
    isPreliminary: true
  });
  s += d.spacing; // start padding in both vertical and horizontal mode

  s += tempLayout.preferredSize;
  s += d.spacing; // end padding in both vertical and horizontal mode

  return s;
}

function _render$3(legend) {
  var rect = legend.rect,
      settings = legend.settings,
      state = legend.state,
      itemRenderer = legend.itemRenderer,
      navigationRenderer = legend.navigationRenderer,
      titleRenderer = legend.titleRenderer;
  var dock = settings.layout.dock;
  var orientation = dock === 'top' || dock === 'bottom' ? 'horizontal' : 'vertical';
  var l = picasso_esm_layout(rect, state.display, orientation, {
    itemRenderer: itemRenderer,
    navigationRenderer: navigationRenderer,
    titleRenderer: titleRenderer
  });
  legend.renderer.size(l.content); // l.content.x = 0;
  // l.content.y = 0;
  // l.navigation.x += rect.x;
  // l.navigation.y += rect.y;
  // l.title.x += rect.x;
  // l.title.y += rect.y;

  var contentItems = itemRenderer.getItemsToRender({
    viewRect: extend({}, l.content, {
      x: 0,
      y: 0
    })
  });
  navigationRenderer.render({
    rect: l.navigation,
    itemRenderer: itemRenderer
  });
  titleRenderer.render({
    rect: l.title
  });
  legend.state.views = {
    layout: l
  };
  return contentItems;
}

var component$2 = {
  require: ['chart', 'settings', 'renderer', 'update', 'resolver', 'registries', 'symbol'],
  defaultSettings: {
    settings: {},
    style: {
      item: {
        label: '$label',
        shape: '$shape'
      },
      title: '$title'
    }
  },
  mounted: function mounted(renderElement) {
    if (renderElement && renderElement.parentNode) {
      this.navigationRenderer.renderer.appendTo(renderElement.parentNode);
      this.titleRenderer.renderer.appendTo(renderElement.parentNode);
      renderElement.parentNode.insertBefore(this.navigationRenderer.renderer.element(), renderElement);
      renderElement.parentNode.insertBefore(this.titleRenderer.renderer.element(), renderElement);
    }

    this.navigationRenderer.render({
      rect: this.state.views.layout.navigation,
      itemRenderer: this.itemRenderer
    });
    this.titleRenderer.render({
      rect: this.state.views.layout.title
    });
  },
  beforeUnmount: function beforeUnmount() {
    this.navigationRenderer.renderer.clear();
    this.titleRenderer.renderer.clear();
  },
  on: {
    panstart: function panstart() {
      if (this.state.interaction.started) {
        return;
      }

      var contentOverflow = this.itemRenderer.getContentOverflow();

      if (!contentOverflow) {
        return;
      }

      this.state.interaction.started = true;
      this.state.interaction.delta = 0;
    },
    panmove: function panmove(e) {
      if (!this.state.interaction.started) {
        return;
      }

      var delta = this.itemRenderer.orientation() === 'horizontal' ? (this.itemRenderer.direction() === 'rtl' ? -1 : 1) * e.deltaX : e.deltaY;
      this.itemRenderer.scroll(delta - this.state.interaction.delta);
      this.state.interaction.delta = delta;
    },
    panend: function panend() {
      this.state.interaction.started = false;
    },
    scroll: function scroll(delta) {
      this.itemRenderer.scroll(-delta);
    },
    next: function next() {
      this.itemRenderer.next();
    },
    prev: function prev() {
      this.itemRenderer.prev();
    }
  },
  created: function created() {
    var _this = this;

    this.state = {
      interaction: {}
    };

    this.onScroll = function () {
      var items = _render$3(_this);

      _this.update(items);
    };

    this.itemRenderer = itemRendererFactory(this, {
      onScroll: this.onScroll
    });
    this.navigationRenderer = navigationRendererFactory(this);
    this.titleRenderer = titleRendererFactory(this);
    this.navigationRenderer.renderer = this.registries.renderer('dom')();
    this.titleRenderer.renderer = this.registries.renderer(this.settings.renderer)();
    picasso_esm_update(this);
  },
  preferredSize: function preferredSize(obj) {
    return _preferredSize(this, obj);
  },
  beforeUpdate: function beforeUpdate() {
    picasso_esm_update(this);
  },
  render: function render() {
    return _render$3(this);
  },
  beforeDestroy: function beforeDestroy() {
    this.navigationRenderer.renderer.destroy();
    this.titleRenderer.renderer.destroy();
  },
  additionalElements: function additionalElements() {
    return [this.titleRenderer.renderer.element(), this.navigationRenderer.renderer.element()];
  },
  _DO_NOT_USE_getInfo: function _DO_NOT_USE_getInfo() {
    return {
      offset: this.itemRenderer.offset()
    };
  }
};

/**
 * @typedef {object} component--legend-cat
 * @property {string} scale
 */

/**
 * @type {string}
 * @memberof component--legend-cat
 */

var type$2 = 'legend-cat';
function categoricalLegend(picasso) {
  picasso.component(type$2, component$2);
}

function applyAlignJustify(ctx, node) {
  var wiggle = 0;
  var cmd = {
    type: ctx.state.isVertical ? 'justify' : 'align',
    coord: ctx.state.isVertical ? 'y' : 'x',
    pos: ctx.state.isVertical ? 'height' : 'width',
    fn: ctx.state.isVertical ? 'requiredHeight' : 'requiredWidth'
  };
  wiggle = ctx.state.rect[cmd.pos] - ctx.state.legend.length() - ctx.state.title[cmd.fn]();
  wiggle *= Math.min(1, Math.max(ctx.stgns[cmd.type], 0));
  node[cmd.coord] += wiggle;
}

function generateStopNodes(ctx) {
  var fillScale = ctx.state.legend.fillScale;
  var majorScale = ctx.state.legend.majorScale;
  var stops = fillScale.domain().map(function (d) {
    return {
      type: 'stop',
      color: fillScale(d),
      offset: Math.min(1, Math.max(0, majorScale.norm(d)))
    };
  });
  return stops.sort(function (a, b) {
    return a.offset - b.offset;
  });
}
function createTitleNode(ctx) {
  var state = ctx.state;
  var settings = ctx.stgns;
  var isTickLeft = state.ticks.anchor === 'left';
  var isTickTop = state.ticks.anchor === 'top';
  var x = state.rect.x;
  var y = state.rect.y;
  var textAnchor = 'start';

  if (state.title.anchor === 'left') {
    x += state.title.requiredWidth() - settings.title.padding;
    y += state.title.textMetrics.height;
    y += isTickTop ? state.rect.height - state.title.textBounds.height : 0;
    textAnchor = 'end';
  } else if (state.title.anchor === 'right') {
    x += state.legend.length();
    x += settings.title.padding;
    y += state.title.textMetrics.height;
    y += isTickTop ? state.rect.height - state.title.textBounds.height : 0;
  } else if (state.title.anchor === 'top') {
    x += isTickLeft ? state.rect.width : 0;
    y += state.title.textMetrics.height;
    textAnchor = isTickLeft ? 'end' : 'start';
  }

  var node = {
    tag: 'legend-title',
    type: 'text',
    x: x,
    y: Math.min(y, state.rect.y + state.rect.height),
    text: settings.title.text,
    fill: settings.title.fill,
    fontSize: settings.title.fontSize,
    fontFamily: settings.title.fontFamily,
    maxWidth: settings.title.maxLengthPx,
    maxLines: settings.title.maxLines,
    wordBreak: settings.title.wordBreak,
    hyphens: settings.title.hyphens,
    lineHeight: settings.title.lineHeight,
    anchor: textAnchor,
    title: settings.title.text
  };
  applyAlignJustify(ctx, node);
  return node;
}
function createLegendRectNode(ctx, stops) {
  var state = ctx.state;
  var settings = ctx.stgns;
  var container = state.rect;
  var x = container.x;
  var y = container.y;
  var width = state.isVertical ? settings.size : state.legend.length();
  var height = state.isVertical ? state.legend.length() : settings.size;

  if (state.ticks.anchor === 'left') {
    x += state.rect.width - settings.size;
  } else if (state.ticks.anchor === 'top') {
    y += state.rect.height - settings.size;
  }

  if (state.title.anchor === 'top') {
    y += state.title.requiredHeight();
  } else if (state.title.anchor === 'left') {
    x += state.title.requiredWidth();
  }

  var node = {
    type: 'rect',
    x: x,
    y: y,
    width: width,
    height: height,
    fill: {
      type: 'gradient',
      stops: stops,
      degree: state.isVertical ? 90 : 180
    }
  };
  applyAlignJustify(ctx, node);
  return node;
}
function createTickNodes(ctx, legendNode) {
  var state = ctx.state;
  var settings = ctx.stgns;
  var anchor = 'start';
  var rangeSelectorRect = {
    type: 'rect',
    x: legendNode.x,
    y: legendNode.y,
    width: state.isVertical ? 0 : legendNode.width,
    height: state.isVertical ? legendNode.height : 0,
    fill: 'transparent'
  };
  var nodes = state.ticks.values.map(function (tick) {
    var x = 0;
    var y = 0;
    var dx = 0;
    var dy = 0;
    var baseline = 'alphabetical';

    if (state.isVertical) {
      y = legendNode.y + legendNode.height * tick.pos;
      baseline = tick.pos === 0 ? 'text-before-edge' : 'text-after-edge';
    } else {
      x = legendNode.x + legendNode.width * tick.pos;
    }

    if (state.ticks.anchor === 'right') {
      x = legendNode.x + settings.size + settings.tick.padding;
      rangeSelectorRect.x = legendNode.x + legendNode.width;
    } else if (state.ticks.anchor === 'left') {
      x = legendNode.x - settings.tick.padding;
      anchor = 'end';
    } else if (state.ticks.anchor === 'top') {
      y = legendNode.y - settings.tick.padding;
      dy -= tick.textMetrics.height * 0.25;
      anchor = tick.pos === 0 ? 'start' : 'end';
    } else if (state.ticks.anchor === 'bottom') {
      y = legendNode.y + legendNode.height + settings.tick.padding;
      dy = tick.textMetrics.height * 0.8;
      anchor = tick.pos === 0 ? 'start' : 'end';
      rangeSelectorRect.y = legendNode.y + legendNode.height;
    }

    var node = {
      type: 'text',
      x: x,
      y: y,
      dx: dx,
      dy: dy,
      text: tick.label,
      fontSize: settings.tick.fontSize,
      fontFamily: settings.tick.fontFamily,
      fill: settings.tick.fill,
      maxWidth: state.isVertical ? settings.tick.maxLengthPx : Math.min(settings.tick.maxLengthPx, state.legend.length() / 2),
      anchor: anchor,
      textBoundsFn: ctx.renderer.textBounds,
      title: tick.label,
      baseline: baseline
    };
    return node;
  });
  return {
    type: 'container',
    id: 'legend-seq-ticks',
    children: [].concat(_toConsumableArray$1(nodes), [rangeSelectorRect])
  };
}

function resolveAnchor(dock, anchor, map) {
  var mapped = map[dock];

  if (_typeof(mapped) === 'object') {
    if (mapped.valid.indexOf(anchor) !== -1) {
      return anchor;
    }

    return mapped.default;
  }

  return map.default;
}

function resolveTickAnchor(settings) {
  var dock = settings.layout.dock;
  var anchor = settings.settings.tick.anchor;
  var dockAnchorMap = {
    left: {
      valid: ['left', 'right'],
      default: 'left'
    },
    right: {
      valid: ['left', 'right'],
      default: 'right'
    },
    top: {
      valid: ['top', 'bottom'],
      default: 'top'
    },
    bottom: {
      valid: ['top', 'bottom'],
      default: 'bottom'
    },
    default: 'right'
  };
  return resolveAnchor(dock, anchor, dockAnchorMap);
}

function resolveTitleAnchor(settings) {
  var dockAnchorMap = {
    left: {
      valid: ['top'],
      default: 'top'
    },
    right: {
      valid: ['top'],
      default: 'top'
    },
    top: {
      valid: ['left', 'right'],
      default: 'left'
    },
    bottom: {
      valid: ['left', 'right'],
      default: 'left'
    },
    default: 'top'
  };
  var dock = settings.layout.dock;
  var anchor = settings.settings.title.anchor;
  return resolveAnchor(dock, anchor, dockAnchorMap);
}

function initRect(ctx, size) {
  var rect = {
    x: 0,
    y: 0,
    width: 0,
    height: 0
  };
  var padding = ctx.stgns.padding;
  rect.x = padding.left;
  rect.y = padding.top;
  rect.width = size.width - padding.left - padding.right;
  rect.height = size.height - padding.top - padding.bottom;
  return rect;
}

function getTicks(ctx, majorScale) {
  var values = majorScale.domain();
  var labels = values;
  var labelFn = ctx.stgns.tick.label;

  if (!labelFn && ctx.formatter) {
    labelFn = ctx.formatter;
  } else if (!labelFn && majorScale.data().fields) {
    labelFn = majorScale.data().fields[0].formatter();
  }

  if (typeof labelFn === 'function') {
    labels = values.map(labelFn).map(String);
  }

  var ticks = values.map(function (value, i) {
    var label = labels[i];
    return {
      value: value,
      label: label,
      pos: majorScale.norm(parseFloat(value, 10)),
      textMetrics: ctx.renderer.measureText({
        text: label,
        fontSize: ctx.stgns.tick.fontSize,
        fontFamily: ctx.stgns.tick.fontFamily
      })
    };
  });
  return ticks;
}

function initState$1(ctx) {
  var isVertical = ctx.settings.layout.dock !== 'top' && ctx.settings.layout.dock !== 'bottom';
  var titleStgns = ctx.stgns.title;
  var fillScale = ctx.chart.scale(ctx.stgns.fill);
  var majorScale = ctx.chart.scale(ctx.stgns.major);
  var tickValues = getTicks(ctx, majorScale);
  var tickAnchor = resolveTickAnchor(ctx.settings);

  if (typeof titleStgns.text === 'undefined') {
    var fields = majorScale.data().fields;
    titleStgns.text = fields && fields[0] ? fields[0].title() : '';
  }

  var titleTextMetrics = ctx.renderer.measureText({
    text: titleStgns.text,
    fontSize: titleStgns.fontSize,
    fontFamily: titleStgns.fontFamily
  });
  var titleTextBounds = ctx.renderer.textBounds({
    text: titleStgns.text,
    fontSize: titleStgns.fontSize,
    fontFamily: titleStgns.fontFamily,
    maxLines: titleStgns.maxLines,
    maxWidth: titleStgns.maxLengthPx,
    wordBreak: titleStgns.wordBreak,
    hyphens: titleStgns.hyphens,
    lineHeight: titleStgns.lineHeight
  });
  var state = {
    isVertical: isVertical,
    nodes: [],
    title: {
      anchor: resolveTitleAnchor(ctx.settings),
      textMetrics: titleTextMetrics,
      textBounds: titleTextBounds,
      requiredWidth: function requiredWidth() {
        if (!titleStgns.show) {
          return 0;
        }

        var w = titleTextBounds.width;
        var mw = titleStgns.maxLengthPx;

        if (!isVertical) {
          w += titleStgns.padding;
          mw += titleStgns.padding;
        }

        return Math.min(w, mw, state.rect.width);
      },
      requiredHeight: function requiredHeight() {
        if (!titleStgns.show) {
          return 0;
        }

        var h = titleTextBounds.height;

        if (isVertical) {
          h += titleStgns.padding;
        }

        return Math.min(h, state.rect.height);
      }
    },
    ticks: {
      values: tickValues,
      anchor: tickAnchor,
      length: Math.min(Math.max.apply(Math, _toConsumableArray$1(tickValues.map(function (t) {
        return t.textMetrics.width;
      }))), ctx.stgns.tick.maxLengthPx),
      requiredHeight: function requiredHeight() {
        return tickAnchor === 'top' ? Math.max.apply(Math, _toConsumableArray$1(state.ticks.values.map(function (t) {
          return t.textMetrics.height;
        }))) + ctx.stgns.tick.padding : 0;
      },
      height: Math.max.apply(Math, _toConsumableArray$1(tickValues.map(function (t) {
        return t.textMetrics.height;
      })))
    },
    legend: {
      fillScale: fillScale,
      majorScale: majorScale,
      length: function length() {
        var pos = isVertical ? 'height' : 'width';
        var fnPos = isVertical ? 'requiredHeight' : 'requiredWidth';
        var len = Math.min(state.rect[pos], state.rect[pos] * ctx.stgns.length) - state.title[fnPos]();
        return Math.max(0, Math.min(len, ctx.stgns.maxLengthPx));
      }
    }
  };
  return state;
}
/**
 * @typedef {object} component--legend-seq
 * @property {string} fill - Reference to definition of sequential color scale
 * @property {string} major - Reference to definition of linear scale
 * @property {number} [size=15] - Size in pixels of the legend, if vertical is the width and height otherwise
 * @property {number} [length=1] - A value in the range 0-1 indicating the length of the legend node
 * @property {number} [maxLengthPx=250] - Max length in pixels
 * @property {number} [align=0.5] - A value in the range 0-1 indicating horizontal alignment of the legend's content. 0 aligns to the left, 1 to the right.
 * @property {number} [justify=0] - A value in the range 0-1 indicating vertical alignment of the legend's content. 0 aligns to the top, 1 to the bottom.
 * @property {object} [padding]
 * @property {number} [padding.left=5]
 * @property {number} [padding.right=5]
 * @property {number} [padding.top=5]
 * @property {number} [padding.bottom=5]
 * @property {object} [tick]
 * @property {function} [tick.label] - Function applied to all tick values, returned values are used as labels
 * @property {string} [tick.fill='#595959']
 * @property {string} [tick.fontSize='12px']
 * @property {string} [tick.fontFamily='Arial']
 * @property {number} [tick.maxLengthPx=150] - Max length in pixels
 * @property {string} [tick.anchor='right'] - Where to anchor the tick in relation to the legend node, supported values are [top, bottom, left and right]
 * @property {number} [tick.padding=5] - padding in pixels to the legend node
 * @property {object} [title] - Title settings
 * @property {boolean} [title.show=true] - Toggle title on/off
 * @property {string} [title.text=''] - Title text. Defaults to the title of the provided data field
 * @property {string} [title.fill='#595959']
 * @property {string} [title.fontSize='12px']
 * @property {string} [title.fontFamily='Arial']
 * @property {number} [title.maxLengthPx=100] - Max length in pixels
 * @property {number} [title.padding=5] - padding in pixels to the legend node
 * @property {string} [title.anchor='top'] - Where to anchor the title in relation to the legend node, supported values are [top, left and right]
 * @property {string} [title.wordBreak='none'] - How overflowing title is handled, if it should insert line breaks at word boundries (break-word) or character boundries (break-all)
 * @property {string} [title.hyphens='auto'] - How words should be hyphenated when text wraps across multiple lines (only applicable with wordBreak)
 * @property {number} [title.maxLines=2] - Number of allowed lines if title contains line breaks (only applicable with wordBreak)
 * @property {number} [title.lineHeight=1.2] - A multiplier defining the distance between lines (only applicable with wordBreak)
 */


var legendDef = {
  require: ['chart', 'settings', 'renderer'],
  defaultSettings: {
    layout: {
      displayOrder: 0,
      dock: 'right'
    },
    settings: {
      size: 15,
      length: 0.5,
      maxLengthPx: 250,
      align: 0.5,
      justify: 0,
      padding: {
        left: 5,
        right: 5,
        top: 5,
        bottom: 5
      },
      tick: {
        label: null,
        fill: '#595959',
        fontSize: '12px',
        fontFamily: 'Arial',
        maxLengthPx: 100,
        anchor: null,
        // Use default based on dock
        padding: 5
      },
      title: {
        show: true,
        text: undefined,
        fill: '#595959',
        fontSize: '12px',
        fontFamily: 'Arial',
        maxLengthPx: 100,
        padding: 5,
        maxLines: 2,
        wordBreak: 'none',
        lineHeight: 1.2,
        hyphens: 'auto',
        anchor: null // Use default based on dock

      }
    }
  },
  preferredSize: function preferredSize(opts) {
    var state = this.state;
    state.rect = initRect(this, opts.inner); // Init with size of legend

    var prefSize = this.stgns.size; // Append paddings

    var paddings = state.isVertical ? this.stgns.padding.left + this.stgns.padding.right : this.stgns.padding.top + this.stgns.padding.bottom;
    prefSize += paddings; // Append tick size

    var maxSize = Math.max(opts.inner.width, opts.inner.height);

    if (state.ticks.anchor === 'left' || state.ticks.anchor === 'right') {
      var tHeight = state.ticks.values.reduce(function (sum, t) {
        return sum + t.textMetrics.height;
      }, 0);

      if (tHeight > this.state.legend.length()) {
        return maxSize;
      }

      prefSize += state.ticks.length;
    } else {
      var tWidth = state.ticks.length;

      if (tWidth > this.state.legend.length()) {
        return maxSize;
      }

      prefSize += Math.max.apply(Math, _toConsumableArray$1(state.ticks.values.map(function (t) {
        return t.textMetrics.height;
      })));
    }

    prefSize += this.stgns.tick.padding; // Append or use title size

    if (this.stgns.title.show) {
      if (state.title.anchor === 'left' || state.title.anchor === 'right') {
        prefSize = Math.max(state.title.textBounds.height + paddings, prefSize);
      } else {
        prefSize = Math.max(prefSize, state.title.requiredWidth() + paddings);
      }
    }

    this.state.preferredSize = prefSize;
    return prefSize;
  },
  created: function created() {
    this.stgns = this.settings.settings;
    this.state = initState$1(this);
  },
  beforeUpdate: function beforeUpdate(opts) {
    this.stgns = opts.settings.settings;
    this.state = initState$1(this);
  },
  beforeRender: function beforeRender(opts) {
    this.state.nodes = [];
    this.state.rect = initRect(this, opts.size);

    if (this.stgns.title.show) {
      var titleNode = createTitleNode(this);
      this.state.nodes.push(titleNode);
    }

    var stopNodes = generateStopNodes(this);
    var rectNode = createLegendRectNode(this, stopNodes);
    var tickNodes = createTickNodes(this, rectNode);
    var targetNode = {
      // The target node enables range selection component to limit its range to a specific area
      id: 'legend-seq-target',
      type: 'container',
      children: [rectNode, tickNodes]
    };
    this.state.nodes.push(targetNode);
  },
  render: function render() {
    return this.state.nodes;
  }
};

function sequentialLegend(picasso) {
  picasso.component('legend-seq', legendDef);
}

var CURVES = {
  step: curveStep,
  stepAfter: stepAfter,
  stepBefore: stepBefore,
  linear: curveLinear,
  basis: curveBasis,
  cardinal: curveCardinal.tension(0),
  catmullRom: curveCatmullRom,
  monotonex: monotoneX,
  monotoney: monotoneY,
  natural: curveNatural
};
/**
 * @callback component--line~layerSort
 * @param {object} a
 * @param {string} a.id
 * @param {Array<datum-extract>} a.data
 * @param {object} b
 * @param {string} b.id
 * @param {Array<datum-extract>} b.data
 */

/**
 * @typedef {object}
 * @alias component--line-settings
 */

var SETTINGS = {
  /**
   * @typedef {object}
   */
  coordinates: {
    /**
     * @type {number} */
    minor: 0.5,

    /**
     * @type {number} */
    major: 0.5,

    /**
     * @type {number=} */
    layerId: 0
  },

  /**
   * @type {boolean=} */
  connect: false,

  /**
   * @type {string=} */
  orientation: 'horizontal',

  /**
   * @typedef {object} */
  layers: {
    /**
     * @type {string=} */
    curve: 'linear',

    /**
     * @type {boolean=} */
    show: true,

    /**
     * @type {component--line~layerSort=} */
    sort: undefined,

    /**
     * @typedef {object} */
    line: {
      /**
       * @type {string=} */
      stroke: '#ccc',

      /**
       * @type {number=} */
      strokeWidth: 1,

      /**
       * @type {string=} */
      strokeLinejoin: 'miter',

      /**
       * @type {string=} */
      strokeDasharray: undefined,

      /**
       * @type {number=} */
      opacity: 1,

      /**
       * @type {boolean=} */
      show: true
    },

    /**
     * @typedef {object} */
    area: {
      /**
       * @type {string=} */
      fill: '#ccc',

      /**
       * @type {number=} */
      opacity: 0.8,

      /**
       * @type {boolean=} */
      show: true
    }
  }
};
/**
 * @type {datum-boolean=}
 * @memberof component--line-settings.coordinates
 * @name defined
 * @default true
 */

function createDisplayLayer(points, _ref) {
  var generator = _ref.generator,
      item = _ref.item,
      data = _ref.data;
  var fill = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
  var path = generator(points);
  var d = {
    type: 'path',
    d: path,
    opacity: item.opacity,
    stroke: item.stroke,
    strokeWidth: item.strokeWidth,
    strokeLinejoin: item.strokeLinejoin,
    fill: fill || item.fill,
    data: data
  };

  if (item.strokeDasharray) {
    d.strokeDasharray = item.strokeDasharray;
  }

  return d;
}

function createDisplayLayers(layers, _ref2) {
  var width = _ref2.width,
      height = _ref2.height,
      missingMinor0 = _ref2.missingMinor0,
      stngs = _ref2.stngs;
  var nodes = [];
  var layerStngs = stngs.layers || {};
  layers.forEach(function (layer) {
    var lineObj = layer.lineObj,
        layerObj = layer.layerObj,
        areaObj = layer.areaObj,
        points = layer.points;
    var areaGenerator = picasso_esm_area();
    var defined = stngs.coordinates ? stngs.coordinates.defined : null;
    var lineGenerator;
    var secondaryLineGenerator;
    var minor = {
      size: height,
      p: 'y'
    };
    var major = {
      size: width,
      p: 'x'
    };

    if (stngs.orientation === 'vertical') {
      var temp = extend(true, {}, major);
      major = extend(true, {}, minor);
      minor = extend(true, {}, temp);
    }

    areaGenerator[major.p](function (d) {
      return d.major * major.size;
    }) // eslint-disable-line no-unexpected-multiline
    ["".concat(minor.p, "1")](function (d) {
      return d.minor * minor.size;
    }) // eslint-disable-line no-unexpected-multiline
    ["".concat(minor.p, "0")](function (d) {
      return d.minor0 * minor.size;
    }) // eslint-disable-line no-unexpected-multiline
    .curve(CURVES[layerObj.curve === 'monotone' ? "monotone".concat(major.p) : layerObj.curve]);

    if (defined) {
      areaGenerator.defined(function (d) {
        return !d.dummy && typeof d.minor === 'number' && !isNaN(d.minor) && d.defined;
      });
    } else {
      areaGenerator.defined(function (d) {
        return !d.dummy && typeof d.minor === 'number' && !isNaN(d.minor);
      });
    }

    var filteredPoints = stngs.connect ? points.filter(areaGenerator.defined()) : points;
    lineGenerator = areaGenerator["line".concat(minor.p.toUpperCase(), "1")]();
    secondaryLineGenerator = areaGenerator["line".concat(minor.p.toUpperCase(), "0")](); // area layer

    if (layerStngs.area && areaObj.show !== false) {
      nodes.push(createDisplayLayer(filteredPoints, {
        data: layer.consumableData,
        item: areaObj,
        generator: areaGenerator
      }));
    } // main line layer


    if (lineObj && lineObj.show !== false) {
      nodes.push(createDisplayLayer(filteredPoints, {
        data: layer.consumableData,
        item: lineObj,
        generator: lineGenerator
      }, 'none')); // secondary line layer, used only when rendering area

      if (!missingMinor0 && layerStngs.area && areaObj.show !== false) {
        nodes.push(createDisplayLayer(filteredPoints, {
          data: layer.consumableData,
          item: lineObj,
          generator: secondaryLineGenerator
        }, 'none'));
      }
    }
  });
  return nodes;
}

function resolve$1(_ref3) {
  var data = _ref3.data,
      stngs = _ref3.stngs,
      rect = _ref3.rect,
      resolver = _ref3.resolver,
      style = _ref3.style,
      domain = _ref3.domain;
  var width = rect.width,
      height = rect.height;
  var coordinates = resolver.resolve({
    data: data,
    defaults: SETTINGS.coordinates,
    settings: stngs.coordinates || {},
    scaled: {
      major: stngs.orientation === 'vertical' ? height : width,
      minor: stngs.orientation === 'vertical' ? width : height
    }
  }); // there are two cases when a line should be interrupted:
  // 1. When the minor value is undefined (this case is easily handled by the lineGenerator.defined).
  // 2. When a line is moving over a domain that may not coincide with the domain on the major scale.
  // For the second case, dummy points need to be injected in order to create values which will cause gaps as they fulfill the first case.
  // These dummy points need to be injected only when: the domain is discrete, connect !== false and multiple layers are defined

  var injectDummy = !stngs.connect && domain.length > 2 && (typeof stngs.coordinates.layerId === 'function' || _typeof(stngs.coordinates.layerId) === 'object'); // collect points into layers

  var layerIds = {};
  var numLines = 0;

  for (var i = 0; i < coordinates.items.length; i++) {
    var p = coordinates.items[i];
    var lid = p.layerId;

    if (injectDummy) {
      // inject dummy if the previous point on the major domain is not the same as the prev point on the line's domain.
      // this works only if a datum's value property is the same primitive as in the domain.
      var lastItem = layerIds[lid] ? layerIds[lid].items[layerIds[lid].items.length - 1] : null;
      var lastOrderIdx = lastItem ? domain.indexOf(lastItem.data.major ? lastItem.data.major.value : lastItem.data.value) : null;

      if (lastItem && domain.indexOf(p.data.major ? p.data.major.value : p.data.value) - 1 !== lastOrderIdx) {
        layerIds[lid].items.push({
          dummy: true
        });
      }
    }

    layerIds[lid] = layerIds[lid] || {
      order: numLines++,
      id: lid,
      items: [],
      dataItems: [],
      consumableData: {}
    };
    layerIds[lid].dataItems.push(p.data);
    layerIds[lid].items.push(p);
  }

  var metaLayers = Object.keys(layerIds).map(function (lid) {
    layerIds[lid].consumableData = _objectSpread2({
      points: layerIds[lid].dataItems
    }, layerIds[lid].dataItems[0]);
    return layerIds[lid];
  });
  var layersData = {
    items: metaLayers.map(function (layer) {
      return layer.consumableData;
    })
  };
  var layerStngs = stngs.layers || {};
  var layersResolved = resolver.resolve({
    data: layersData,
    defaults: {
      curve: SETTINGS.layers.curve,
      show: SETTINGS.layers.show
    },
    settings: {
      curve: layerStngs.curve,
      show: layerStngs.show
    }
  });
  var linesResolved = resolver.resolve({
    data: layersData,
    defaults: extend({}, SETTINGS.layers.line, style.line),
    settings: layerStngs.line
  });
  var areasResolved = resolver.resolve({
    data: layersData,
    defaults: extend({}, SETTINGS.layers.area, style.area),
    settings: layerStngs.area
  });
  return {
    coordinates: coordinates,
    metaLayers: metaLayers,
    layers: layersResolved,
    lines: linesResolved,
    areas: areasResolved
  };
}

function calculateVisibleLayers(opts) {
  var _resolve = resolve$1(opts),
      metaLayers = _resolve.metaLayers,
      coordinates = _resolve.coordinates,
      layers = _resolve.layers,
      lines = _resolve.lines,
      areas = _resolve.areas;

  var visibleLayers = [];
  metaLayers.forEach(function (layer, ix) {
    var layerObj = layers.items[ix];

    if (layerObj.show === false) {
      return;
    } // layerObj.points = [];


    layerObj.datum = layerObj.data;
    layerObj.data = [];
    layerObj.id = layer.id;
    var values = [];
    var points = [];
    var point;
    var pData;

    for (var i = 0; i < layer.items.length; i++) {
      point = layer.items[i];
      pData = point.data;

      if (!point.dummy) {
        if (isNaN(point.major)) {
          continue;
        }

        if (opts.missingMinor0) {
          point.minor0 = coordinates.settings.minor.scale ? coordinates.settings.minor.scale(pData.minor0 ? pData.minor0.value : 0) : 0;
        }

        if (!isNaN(point.minor)) {
          values.push(point.minor);
        }

        layerObj.data.push(point.data);
      }

      points.push(point);
    }

    var median = values.sort(function (a, b) {
      return a - b;
    })[Math.floor((values.length - 1) / 2)];
    visibleLayers.push({
      layerObj: layerObj,
      lineObj: lines.items[ix],
      areaObj: areas.items[ix],
      median: median,
      points: points,
      consumableData: layer.consumableData
    });
  });
  return visibleLayers;
}

var lineMarkerComponent = {
  require: ['chart', 'resolver'],
  defaultSettings: {
    style: {
      area: '$shape',
      line: '$shape-outline'
    }
  },
  created: function created() {},
  render: function render(_ref4) {
    var data = _ref4.data;
    // console.log("DATA", data);
    var _this$rect = this.rect,
        width = _this$rect.width,
        height = _this$rect.height;
    this.stngs = this.settings.settings || {};
    var missingMinor0 = !this.stngs.coordinates || typeof this.stngs.coordinates.minor0 === 'undefined';
    var visibleLayers = calculateVisibleLayers({
      data: data,
      stngs: this.stngs,
      rect: this.rect,
      resolver: this.resolver,
      style: this.style,
      missingMinor0: missingMinor0,
      domain: this.stngs.coordinates && this.stngs.coordinates.major && this.stngs.coordinates.major.scale ? this.chart.scale(this.stngs.coordinates.major.scale).domain() : []
    });

    if (this.stngs.layers && this.stngs.layers.sort) {
      var sortable = visibleLayers.map(function (v) {
        return {
          id: v.layerObj.id,
          data: v.layerObj.data
        };
      }).sort(this.stngs.layers.sort).map(function (s) {
        return s.id;
      });
      visibleLayers.sort(function (a, b) {
        return sortable.indexOf(a.layerObj.id) - sortable.indexOf(b.layerObj.id);
      });
    } else {
      visibleLayers.sort(function (a, b) {
        return a.median - b.median;
      });
    } // generate visuals


    return createDisplayLayers(visibleLayers, {
      width: width,
      height: height,
      missingMinor0: missingMinor0,
      stngs: this.stngs
    });
  }
};

/**
 * @typedef {object} component--line
 */

/**
 * @type {string}
 * @memberof component--line
 */

var type$3 = 'line';
function line$2(picasso) {
  picasso.component(type$3, lineMarkerComponent);
}

/**
 * @typedef {object} component--brush-area-brush
 * @property {string} key - Component key
 * @property {string[]} [contexts] - Name of the brushing contexts to affect
 * @property {string[]} [data] - The mapped data properties to add to the brush
 * @property {string} [action='set'] - Type of action to respond with
 */

/**
  * @typedef {object}
  * @alias component--brush-area-settings
  */

var DEFAULT_SETTINGS$7 = {
  /**
   * @type {object}
   */
  brush: {
    /**
    * @type {Array<component--brush-area-brush>}
    */
    components: []
  }
};
/**
 * Transform the incoming event into point in the local coordinate system. That is the coordinate system of the component.
 * @private
 * @param {object} ctx - Context
 * @param {object} event - Incoming event, either native event or hammer event
 * @param {boolean} clamp - True to clamp the point inside the component bounds
 * @returns {point}
 */

function getLocalPoint(ctx, event) {
  var clamp = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  var x;
  var y;

  if (_typeof(event.center) === 'object') {
    x = event.center.x;
    y = event.center.y;
  } else {
    x = event.clientX;
    y = event.clientY;
  }

  var localX = x - ctx.state.boundingRect.left;
  var localY = y - ctx.state.boundingRect.top;
  return {
    x: clamp ? Math.max(0, Math.min(localX, ctx.rect.width)) : localX,
    y: clamp ? Math.max(0, Math.min(localY, ctx.rect.height)) : localY
  };
}
/**
 * Transform a local point into a point in the chart coordinate system.
 * @private
 * @param {object} ctx - Context
 * @param {object} p - Point to transform
 * @returns {point}
 */


function localToChartPoint(ctx, p) {
  return {
    x: p.x + ctx.rect.x,
    y: p.y + ctx.rect.y
  };
}
/**
 * Extract and apply default brush configuration.
 * @private
 * @param {object} settings
 * @returns {object[]} An Array of brush configurations
 */


function getBrushConfig$1(settings) {
  return settings.settings.brush.components.map(function (b) {
    return {
      key: b.key,
      contexts: b.contexts,
      data: b.data,
      action: b.action || 'set'
    };
  });
}
/**
 * End all active brush contexts.
 * @private
 * @param {oject} state
 * @param {object} chart - Chart instance
 */


function doEndBrush(state, chart) {
  state.brushConfig.forEach(function (config) {
    if (Array.isArray(config.contexts)) {
      config.contexts.forEach(function (context) {
        chart.brush(context).end();
      });
    }
  });
}
/**
 * Convert two points into a rectangle.
 * @private
 * @param {point} p0
 * @param {point} p1
 * @returns {rect}
 */


function toRect(p0, p1) {
  var xMin = Math.min(p0.x, p1.x);
  var yMin = Math.min(p0.y, p1.y);
  var xMax = Math.max(p0.x, p1.x);
  var yMax = Math.max(p0.y, p1.y);
  return {
    x: xMin,
    y: yMin,
    width: xMax - xMin,
    height: yMax - yMin
  };
}
/**
 * Perform a brush on the given area.
 * @private
 * @param {object} ctx
 */


function doAreaBrush(ctx) {
  if (ctx.state.active) {
    var start = localToChartPoint(ctx, ctx.state.start);
    var end = localToChartPoint(ctx, ctx.state.end);
    var shapes = ctx.chart.shapesAt(toRect(start, end), {
      components: ctx.state.brushConfig
    });
    ctx.chart.brushFromShapes(shapes, {
      components: ctx.state.brushConfig
    });
  }
}

function render$2(ctx) {
  ctx.renderer.render([extend({
    type: 'rect'
  }, toRect(ctx.state.start, ctx.state.end), ctx.style.area)]);
}

function resetState$1() {
  return {
    start: {
      x: 0,
      y: 0
    },
    end: {
      x: 0,
      y: 0
    },
    active: false
  };
}

var picasso_esm_definition = {
  require: ['chart', 'renderer'],
  defaultSettings: {
    layout: {
      displayOrder: 99
    },
    settings: DEFAULT_SETTINGS$7,
    style: {
      area: '$selection-area-target'
    }
  },
  on: {
    areaStart: function areaStart(e) {
      this.start(e);
    },
    areaMove: function areaMove(e) {
      this.move(e);
    },
    areaEnd: function areaEnd(e) {
      this.end(e);
    },
    areaCancel: function areaCancel() {
      this.cancel();
    }
  },
  created: function created() {
    this.state = resetState$1();
  },
  preferredSize: function preferredSize() {
    return 0;
  },
  render: function render() {},
  start: function start(e) {
    this.state.boundingRect = this.renderer.element().getBoundingClientRect();
    var p = getLocalPoint(this, e, false); // Require event to be inside the component bounds

    if (!testRectPoint({
      x: 0,
      y: 0,
      width: this.rect.width,
      height: this.rect.height
    }, p)) {
      return;
    }

    this.state.brushConfig = getBrushConfig$1(this.settings);
    this.state.start = getLocalPoint(this, e);
    this.state.active = true;
  },
  move: function move(e) {
    if (!this.state.active) {
      return;
    }

    this.state.end = getLocalPoint(this, e);
    doAreaBrush(this);
    render$2(this);
  },
  end: function end() {
    if (!this.state.active) {
      return;
    }

    this.state = resetState$1();
    this.renderer.render([]);
  },
  cancel: function cancel() {
    if (!this.state.active) {
      return;
    }

    doEndBrush(this.state, this.chart);
    this.state = resetState$1();
    this.renderer.render([]);
  }
};

function areaBrush(picasso) {
  picasso.component('brush-area', picasso_esm_definition);
}

function extractor(nodes, _ref) {
  var chart = _ref.chart,
      scale = _ref.scale,
      props = _ref.props,
      h = _ref.h;
  var dataCtx = {
    resources: {
      dataset: chart.dataset,
      scale: chart.scale,
      formatter: chart.formatter
    },
    scale: scale,
    h: h
  };
  var data = [];
  nodes.forEach(function (node) {
    if (typeof props.extract === 'function') {
      var ctx = extend({
        node: node
      }, dataCtx);
      data.push(props.extract(ctx));
    }
  });
  return data;
}

function resolveClasses(props, opts) {
  return {
    tooltip: typeof props.tooltipClass === 'function' ? props.tooltipClass({
      dock: opts.dock
    }) : props.tooltipClass,
    content: typeof props.contentClass === 'function' ? props.contentClass({
      dock: opts.dock
    }) : props.contentClass,
    arrow: typeof props.arrowClass === 'function' ? props.arrowClass({
      dock: opts.dock
    }) : props.arrowClass
  };
}

function resolveContent(h, data, style, props) {
  return props.content({
    h: h,
    style: style,
    data: data
  });
}

function render$3(data, placement, _ref) {
  var renderer = _ref.renderer,
      style = _ref.style,
      props = _ref.props,
      h = _ref.h;
  var classes = resolveClasses(props, placement);
  var content = resolveContent(h, data, style, props);
  var tooltipDefaultStyle = {
    position: 'relative',
    display: 'inline-block'
  };
  var tooltipNode = h("div", {
    dir: props.direction,
    class: classString(extend({
      'pic-tooltip': true
    }, classes.tooltip)),
    style: extend(tooltipDefaultStyle, placement.computedTooltipStyle)
  }, h("div", {
    style: style.content,
    class: classString(extend({
      'pic-tooltip-content': true
    }, classes.content))
  }, content), h("div", {
    class: classString(extend({
      'pic-tooltip-arrow': true
    }, classes.arrow)),
    style: extend({}, style.arrow, style["arrow-".concat(placement.dock)], placement.computedArrowStyle)
  }));
  renderer.render(tooltipNode);
  return renderer.element().children[0];
}

// Successfull flow: pending -> active -> fulfilled (only with duration)
// Cancelled flow: pending -> active -> cancelled
// Rejected flow: pending -> rejected
// Debounced flow: pending -> debounced -> pending -> [rejected|fulfilled]
function dispatcherState() {
  var fn = function fn() {};

  var on = {
    pending: [],
    debounced: [],
    active: [],
    cancelled: [],
    rejected: [],
    fulfilled: []
  };
  var state;

  fn.set = function (s) {
    state = s;
    on[state].forEach(function (event) {
      return event(s);
    });
  };

  fn.on = function (key, event) {
    if (Array.isArray(key)) {
      key.forEach(function (k) {
        return on[k].push(event);
      });
    } else {
      on[key].push(event);
    }
  };

  fn.destroy = function () {
    Object.keys(on).forEach(function (key) {
      on[key].length = 0;
    });
  }; // fn.on(['pending', 'debounced', 'active', 'cancelled', 'rejected', 'fulfilled'], (e) => {
  //   console.log(e);
  // });


  return fn;
}

function timeSpanDispatcher(_ref) {
  var defaultDuration = _ref.defaultDuration,
      defaultDelay = _ref.defaultDelay;
  var actionId = null;
  var fulfilledId = null;
  var isActive = false;
  var state = dispatcherState();

  var fn = function fn() {};

  var fulfilled = function fulfilled() {
    actionId = null;
    fulfilledId = null;
    isActive = false;
    state.set('fulfilled');
  };

  fn.invoke = function (action) {
    var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultDuration;
    var delay = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultDelay;

    if (actionId) {
      clearTimeout(actionId);
      state.set('debounced');
    }

    state.set('pending');
    actionId = setTimeout(function () {
      action();
      isActive = true;
      actionId = null;
      state.set('active');
    }, delay);

    if (duration > 0) {
      if (fulfilledId) {
        clearTimeout(fulfilledId);
      }

      fulfilledId = setTimeout(fulfilled, duration + Math.max(delay, 0));
    }
  };

  fn.clear = function () {
    if (isActive) {
      state.set('cancelled');
    } else if (actionId) {
      clearTimeout(actionId);
      state.set('rejected');
    }

    if (fulfilledId) {
      clearTimeout(fulfilledId);
    }

    actionId = null;
    fulfilledId = null;
    isActive = false;
  };

  fn.on = function (key, event) {
    state.on(key, event);
  };

  fn.destroy = function () {
    fn.clear();
    state.destroy();
  };

  return fn;
}

function getDockTransform() {
  var offset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  return {
    left: "translate(-100%,-50%) translateX(".concat(-offset, "px)"),
    right: "translate(".concat(offset, "px, -50%)"),
    top: "translate(-50%, -100%) translateY(".concat(-offset, "px)"),
    bottom: "translate(-50%, ".concat(offset, "px)")
  };
}

function getDockOffset(width, height) {
  var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  return {
    left: {
      x: -width - offset,
      y: -height / 2
    },
    right: {
      x: offset,
      y: -height / 2
    },
    top: {
      x: -width / 2,
      y: -height - offset
    },
    bottom: {
      x: -width / 2,
      y: offset
    }
  };
}

function getComputedArrowStyle(offset) {
  return {
    left: {
      left: '100%',
      top: "calc(50% - ".concat(offset, "px)"),
      borderWidth: "".concat(offset, "px")
    },
    right: {
      left: "".concat(-offset * 2, "px"),
      top: "calc(50% - ".concat(offset, "px)"),
      borderWidth: "".concat(offset, "px")
    },
    top: {
      left: "calc(50% - ".concat(offset, "px)"),
      top: '100%',
      borderWidth: "".concat(offset, "px")
    },
    bottom: {
      left: "calc(50% - ".concat(offset, "px)"),
      top: "".concat(-offset * 2, "px"),
      borderWidth: "".concat(offset, "px")
    }
  };
}

function isInsideArea(area, vx, vy, width, height, offset) {
  var rect = {
    x: vx + offset.x,
    y: vy + offset.y,
    width: width,
    height: height
  };

  if (rect.x < 0 || rect.y < 0) {
    return false;
  }

  if (rect.x + rect.width > area.width || rect.y + rect.height > area.height) {
    return false;
  }

  return true;
}
/**
 * @param {vx} vx X-coordinate realative to the area
 * @param {vy} vy Y-coordinate realative to the area
 */


function calcOffset(_ref) {
  var area = _ref.area,
      vx = _ref.vx,
      vy = _ref.vy,
      width = _ref.width,
      height = _ref.height,
      offset = _ref.offset;
  var rect = {
    x: vx + offset.x,
    y: vy + offset.y,
    width: width,
    height: height
  };
  var offsetX = rect.x < 0 ? -rect.x : 0;
  var offsetY = rect.y < 0 ? -rect.y : 0;
  offsetX += rect.x + rect.width > area.width ? -(rect.x + rect.width - area.width) : 0;
  offsetY += rect.y + rect.height > area.height ? -(rect.y + rect.height - area.height) : 0;
  return {
    x: offsetX,
    y: offsetY
  };
}

function alignToBounds(_ref2) {
  var resources = _ref2.resources,
      nodes = _ref2.nodes,
      pointer = _ref2.pointer,
      elmWidth = _ref2.width,
      elmHeight = _ref2.height,
      options = _ref2.options;
  var targetBounds = pointer.targetBounds;

  var _resources$getNodeBou = resources.getNodeBoundsRelativeToTarget(nodes[0]),
      x = _resources$getNodeBou.x,
      y = _resources$getNodeBou.y,
      width = _resources$getNodeBou.width,
      height = _resources$getNodeBou.height;

  var docks = {
    left: {
      x: x,
      y: y + height / 2
    },
    right: {
      x: x + width,
      y: y + height / 2
    },
    top: {
      x: x + width / 2,
      y: y
    },
    bottom: {
      x: x + width / 2,
      y: y + height
    }
  }; // Check if explicit dock

  var dockTransforms = getDockTransform(options.offset);
  var transform = dockTransforms[options.dock];

  if (transform) {
    return {
      computedTooltipStyle: {
        left: "".concat(docks[options.dock].x, "px"),
        top: "".concat(docks[options.dock].y, "px"),
        transform: transform
      },
      computedArrowStyle: getComputedArrowStyle(options.offset)[options.dock],
      dock: options.dock
    };
  }

  var area = {
    width: options.area === 'target' ? targetBounds.width : window.innerWidth,
    height: options.area === 'target' ? targetBounds.height : window.innerHeight
  };
  var dockOffsets = getDockOffset(elmWidth, elmHeight, options.offset);
  var dockOrder = ['top', 'left', 'right', 'bottom'];

  for (var i = 0; i < dockOrder.length; i += 1) {
    var dock = dockOrder[i];
    var vx = options.area === 'target' ? docks[dock].x : targetBounds.left + docks[dock].x;
    var vy = options.area === 'target' ? docks[dock].y : targetBounds.top + docks[dock].y;

    if (isInsideArea(area, vx, vy, elmWidth, elmHeight, dockOffsets[dock])) {
      return {
        computedTooltipStyle: {
          left: "".concat(docks[dock].x, "px"),
          top: "".concat(docks[dock].y, "px"),
          transform: dockTransforms[dock]
        },
        computedArrowStyle: getComputedArrowStyle(options.offset)[dock],
        dock: dock
      };
    }
  }

  return {
    computedTooltipStyle: {
      left: "".concat(docks.top.x, "px"),
      top: "".concat(docks.top.y, "px"),
      transform: dockTransforms.top
    },
    computedArrowStyle: getComputedArrowStyle(options.offset).top,
    dock: 'top'
  };
}

function alignToPoint(_ref3) {
  var options = _ref3.options,
      pointer = _ref3.pointer,
      width = _ref3.width,
      height = _ref3.height,
      dockOrder = _ref3.dockOrder,
      x = _ref3.x,
      y = _ref3.y;
  var targetBounds = pointer.targetBounds; // Check if explicit dock

  var dockTransforms = getDockTransform(options.offset);
  var transform = dockTransforms[options.dock];

  if (transform) {
    return {
      computedTooltipStyle: {
        left: "".concat(x, "px"),
        top: "".concat(y, "px"),
        transform: transform
      },
      computedArrowStyle: getComputedArrowStyle(options.offset)[options.dock],
      dock: options.dock
    };
  }

  var area = {
    width: options.area === 'target' ? targetBounds.width : window.innerWidth,
    height: options.area === 'target' ? targetBounds.height : window.innerHeight
  };
  var dockOffsets = getDockOffset(width, height, options.offset);
  var results = [];
  var edgeMargin = 20;
  var vx = options.area === 'target' ? x : targetBounds.left + x;
  var vy = options.area === 'target' ? y : targetBounds.top + y;

  for (var i = 0; i < dockOrder.length; i += 1) {
    var dock = dockOrder[i];
    var offset = calcOffset({
      area: area,
      vx: vx,
      vy: vy,
      width: width,
      height: height,
      offset: dockOffsets[dock]
    });
    var computedTooltipStyle = {
      left: "".concat(x, "px"),
      top: "".concat(y, "px"),
      transform: dockTransforms[dock]
    };
    var computedArrowStyle = getComputedArrowStyle(options.offset)[dock];

    if (offset.x !== 0) {
      computedTooltipStyle.width = "".concat(width - edgeMargin - Math.abs(offset.x), "px");

      if (dock === 'top' || dock === 'bottom') {
        computedTooltipStyle.left = "".concat(x + offset.x, "px");
        computedArrowStyle.left = "calc(50% ".concat(offset.x > 0 ? '-' : '+', " ").concat(Math.abs(offset.x), "px)");
      }
    }

    var result = {
      computedTooltipStyle: computedTooltipStyle,
      computedArrowStyle: computedArrowStyle,
      dock: dock,
      rect: {
        width: width,
        height: height
      }
    };

    if (offset.x === 0 && offset.y === 0) {
      return result;
    }

    result.offset = offset;
    results.push(result);
  }

  results.sort(function (a, b) {
    return Math.abs(a.offset.x) - Math.abs(b.offset.x);
  });
  return results[0];
}

function alignToPointer(_ref4) {
  var options = _ref4.options,
      pointer = _ref4.pointer,
      width = _ref4.width,
      height = _ref4.height;
  var x = pointer.x,
      y = pointer.y;
  return alignToPoint({
    x: x,
    y: y,
    pointer: pointer,
    width: width,
    height: height,
    options: options,
    dockOrder: ['top', 'left', 'right', 'bottom']
  });
}

function alignToSlice(_ref5) {
  var options = _ref5.options,
      pointer = _ref5.pointer,
      width = _ref5.width,
      height = _ref5.height,
      nodes = _ref5.nodes,
      resources = _ref5.resources;
  var node = nodes[0];
  var dx = pointer.dx,
      dy = pointer.dy;
  var componentBounds = resources.getComponentBoundsFromNode(node); // cx and cy relative to targetBounds

  var center = {
    x: dx + componentBounds.x + componentBounds.width / 2,
    y: dy + componentBounds.y + componentBounds.height / 2
  };
  var _node$desc$slice = node.desc.slice,
      start = _node$desc$slice.start,
      end = _node$desc$slice.end,
      outerRadius = _node$desc$slice.outerRadius; // Node origin is at 12 o clock, clockwise, but Math uses 3 a clock, so it's transformed to origin at 3 a clock

  var middle = (start + end) / 2 - Math.PI / 2;
  var PI2 = Math.PI * 2;
  var radians = (middle % PI2 + PI2) % PI2;
  var dockOrder = ['top', 'left', 'right', 'bottom'];

  if (options.dock === 'auto') {
    if (radians <= Math.PI / 4 || radians >= Math.PI * 7 / 4) {
      dockOrder = ['right', 'top', 'bottom', 'left'];
    } else if (radians <= Math.PI * 3 / 4) {
      dockOrder = ['bottom', 'left', 'right', 'top'];
    } else if (radians <= Math.PI * 5 / 4) {
      dockOrder = ['left', 'top', 'bottom', 'right'];
    } else {
      dockOrder = ['top', 'left', 'right', 'bottom'];
    }
  }

  return alignToPoint({
    x: center.x + outerRadius * componentBounds.scaleRatio.x * Math.cos(radians),
    y: center.y + outerRadius * componentBounds.scaleRatio.y * Math.sin(radians),
    pointer: pointer,
    width: width,
    height: height,
    options: options,
    dockOrder: dockOrder
  });
}

function _getComponentBoundsFromNode(node, pointer, chart) {
  var comp = node.key ? chart.component(node.key) : chart.componentsFromPoint({
    x: pointer.clientX,
    y: pointer.clientY
  })[0];

  if (!comp) {
    return {
      x: 0,
      y: 0,
      width: 0,
      height: 0,
      scaleRatio: {
        x: 1,
        y: 1
      }
    };
  }

  var componentSize = comp.rect;
  return extend({
    scaleRatio: componentSize.scaleRatio
  }, componentSize.computedInner);
}

function _getNodeBoundsRelativeToTarget(node, pointer, chart) {
  var componentBounds = _getComponentBoundsFromNode(node, pointer, chart);

  var bounds = node.bounds;
  return {
    x: componentBounds.x + pointer.dx + bounds.x,
    y: componentBounds.y + pointer.dy + bounds.y,
    width: bounds.width,
    height: bounds.height
  };
}

var STRATEGIES = {
  bounds: alignToBounds,
  pointer: alignToPointer,
  slice: alignToSlice
};
function picasso_esm_placement(_ref6, _ref7) {
  var width = _ref6.width,
      height = _ref6.height;
  var chart = _ref7.chart,
      state = _ref7.state,
      props = _ref7.props;
  var propCtx = {
    resources: {
      formatter: chart.formatter,
      scale: chart.scale,
      component: chart.component,
      getComponentBoundsFromNode: function getComponentBoundsFromNode(node) {
        return _getComponentBoundsFromNode(node, state.pointer, chart);
      },
      getNodeBoundsRelativeToTarget: function getNodeBoundsRelativeToTarget(node) {
        return _getNodeBoundsRelativeToTarget(node, state.pointer, chart);
      }
    },
    nodes: state.activeNodes,
    pointer: state.pointer,
    width: width,
    height: height
  };

  var type = _typeof(props.placement);

  if (type === 'object' && typeof props.placement.fn === 'function') {
    // Custom placement strategy function
    return props.placement.fn(propCtx);
  }

  var opts = {
    type: 'pointer',
    offset: 8,
    dock: 'auto',
    area: 'viewport'
  };

  if (type === 'function') {
    // Custom placement function
    opts = extend(opts, props.placement(propCtx));
  }

  if (type === 'object' && STRATEGIES[props.placement.type]) {
    // Predefined placement function with options
    opts = extend(opts, props.placement);
  } else if (type === 'string' && STRATEGIES[props.placement]) {
    // Predefined placement function without options
    opts = extend(opts, {
      type: props.placement
    });
  }

  propCtx.options = opts;
  var plcm = STRATEGIES[opts.type](propCtx);

  var _propCtx$resources$ge = propCtx.resources.getComponentBoundsFromNode(propCtx.nodes[0]),
      minX = _propCtx$resources$ge.x,
      minY = _propCtx$resources$ge.y,
      maxX = _propCtx$resources$ge.width,
      maxY = _propCtx$resources$ge.height;

  minX += propCtx.pointer.dx;
  maxX += minX;
  minY += propCtx.pointer.dy;
  maxY += minY; // Clamp tooltip position

  plcm.computedTooltipStyle.left = "".concat(Math.min(Math.max(0, minX, parseFloat(plcm.computedTooltipStyle.left)), maxX), "px");
  plcm.computedTooltipStyle.top = "".concat(Math.min(Math.max(0, minY, parseFloat(plcm.computedTooltipStyle.top)), maxY), "px");
  return plcm;
}

var picasso_esm_instance;
function picasso_esm_setActive(action) {
  picasso_esm_instance = action;
}
function removeActive(action) {
  if (picasso_esm_instance === action) {
    picasso_esm_instance = null;
    return true;
  }

  return false;
}
function cancelActive(a) {
  if (picasso_esm_instance && picasso_esm_instance !== a) {
    picasso_esm_instance();
  }
}
function remove$1() {
  picasso_esm_instance = null;
}

/**
 * @typedef {object}
 * @alias component--tooltip.settings
 */

var DEFAULT_SETTINGS$8 = {
  /**
   * How long the tooltip is visible, in milliseconds
   * @type {number=}
   */
  duration: 8000,

  /**
   * Delay before the tooltip is rendered, in milliseconds
   * @type {number=}
   */
  delay: 500,

  /**
   * Reduce incoming nodes to only a set of applicable nodes. Is called as a part of the `show` event.
   * @type {function=}
   * @returns {array} An array of nodes
   */
  filter: function filter(nodes) {
    return nodes.filter(function (node) {
      return node.data && typeof node.data.value !== 'undefined';
    });
  },

  /**
   * Extract data from a node.
   * @type {function=}
   * @returns {object} An array of data
   */
  extract: function extract(ctx) {
    return ctx.node.data.value;
  },

  /**
   * Content generator. Extracted data is available in the `data` property, where each value in the area is the extracted datum from a node.
   * @type {function=}
   * @returns {object[]} Array of h objects
   */
  content: function content(_ref) {
    var h = _ref.h,
        data = _ref.data;
    return data.map(function (datum) {
      return h('div', {}, datum);
    });
  },

  /**
   * Comparison function. If evaluted to true, the incoming nodes in the `show` event are ignored. If evaluated to false, any active tooltip is cleared and a new tooltip is queued.
   *
   * The function gets two parameters, the first is the currently active set of nodes, if any, and the second is the incoming set of nodes. By default the two set of nodes are considered equal if their data attributes are the same.
   * @type {function=}
   * @returns {boolean}
   */
  isEqual: function isEqual(prev, curr) {
    return prev.length && prev.length === curr.length && prev.every(function (p, i) {
      return curr[i] && JSON.stringify(p.data) === JSON.stringify(curr[i].data);
    });
  },

  /**
   * @typedef {object=}
   */
  placement: {
    /**
     * Available types: [pointer | bounds | slice]
     * @type {string=}
     */
    type: 'pointer',

    /**
     * Docking position of the tooltip. Available positions: [left | right | top | bottom | auto]
     * @type {string=}
     */
    dock: 'auto',

    /**
     * Distance from the content area to the tooltip position, in px.
     * @type {number=}
     */
    offset: 8,

    /**
     * Specify the limiting area, where target is the component area unless the appendTo property is set, in which case it referes to the appendTo element. Viewport is the browser viewport.
     *
     * Available options are: [viewport | target]
     * @type {number=}
     */
    area: 'viewport'
  },

  /**
   * Set tooltip class.
  * @type {object<string, boolean>=}
  */
  tooltipClass: {},

  /**
   * Set content class.
  * @type {object<string, boolean>=}
  */
  contentClass: {},

  /**
   * Set arrow class.
  * @type {object<string, boolean>=}
  */
  arrowClass: {},

  /**
   * Content direction [ltr | rtl]
   * @type {string=}
   */
  direction: 'ltr',

  /**
   * Explicitly set a target element. This allows the tooltip to attach itself outside the picasso container.
   * @type {HTMLElement=}
   */
  appendTo: undefined,

  /**
   * Component lifecycle hook. Called before the tooltip is displayed.
   * @type {function=}
   */
  beforeShow: undefined,

  /**
   * Component lifecycle hook. Called after the tooltip have been displayed.
   * @type {function=}
   */
  afterShow: undefined,

  /**
   * Component lifecycle hook. Called before the tooltip is hidden.
   * @type {function=}
   */
  beforeHide: undefined,

  /**
   * Component lifecycle hook. Called when the toolip is hidden. By default this deletes the tooltip element.
   * @type {function=}
   */
  onHide: undefined,

  /**
   * Component lifecycle hook. Called after the tooltip is hidden.
   * @type {function=}
   */
  afterHide: undefined
};
var DEFAULT_STYLE = {
  tooltip: {},
  content: {
    backgroundColor: '$gray-25',
    color: '$font-color--inverted',
    fontFamily: '$font-family',
    fontSize: '$font-size',
    lineHeight: '$line-height',
    borderRadius: '4px',
    padding: '8px',
    opacity: 0.9
  },
  arrow: {
    position: 'absolute',
    width: '0px',
    height: '0px',
    borderStyle: 'solid',
    color: '$gray-25',
    opacity: 0.9
  },
  'arrow-bottom': {
    borderTopColor: 'transparent',
    borderLeftColor: 'transparent',
    borderRightColor: 'transparent'
  },
  'arrow-top': {
    borderBottomColor: 'transparent',
    borderLeftColor: 'transparent',
    borderRightColor: 'transparent'
  },
  'arrow-right': {
    borderTopColor: 'transparent',
    borderLeftColor: 'transparent',
    borderBottomColor: 'transparent'
  },
  'arrow-left': {
    borderTopColor: 'transparent',
    borderBottomColor: 'transparent',
    borderRightColor: 'transparent'
  }
};

function toPoint(event, _ref2) {
  var chart = _ref2.chart,
      state = _ref2.state;
  var x = 0;
  var y = 0;

  if (event.center) {
    x += event.center.x;
    y += event.center.y;
  } else {
    x += event.clientX;
    y += event.clientY;
  } // TODO Don't do getBoundingClientRect lookup here. It's performance heavy.


  var chartBounds = chart.element.getBoundingClientRect();
  var targetBounds = state.targetElement.getBoundingClientRect();
  var clientX = x;
  var clientY = y;
  var dx = chartBounds.left - targetBounds.left;
  var dy = chartBounds.top - targetBounds.top;
  var cx = x - chartBounds.left;
  var cy = y - chartBounds.top;
  x -= targetBounds.left;
  y -= targetBounds.top;
  return {
    x: x,
    // Target point relative to the target bounds
    y: y,
    dx: dx,
    // Delta from target bounds to the chart bounds
    dy: dy,
    cx: cx,
    // Target point relative to the chart bounds
    cy: cy,
    clientX: clientX,
    clientY: clientY,
    targetBounds: targetBounds,
    // Target bounding rect
    chartBounds: chartBounds // Chart bounding rect

  };
}

var component$3 = {
  require: ['chart', 'renderer'],
  defaultSettings: {
    settings: DEFAULT_SETTINGS$8,
    style: DEFAULT_STYLE
  },
  renderer: 'dom',
  on: {
    hide: function hide() {
      this.hide();
    },
    show: function show(event) {
      var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      this.show(event, opts);
    },
    prevent: function prevent(p) {
      this.prevent(p);
    }
  },
  hide: function hide() {
    this.dispatcher.clear();
    this.state.activeNodes = [];
    this.state.pointer = {};
  },
  show: function show(event) {
    var _this = this;

    var _ref3 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
        nodes = _ref3.nodes,
        duration = _ref3.duration,
        delay = _ref3.delay;

    if (this.state.prevent) {
      return;
    } // Set pointer here to always expose latest pointer to invokeRenderer


    this.state.pointer = toPoint(event, this);
    var fNodes;

    if (Array.isArray(nodes)) {
      fNodes = this.props.filter(nodes);
    } else {
      fNodes = this.props.filter(this.chart.shapesAt({
        x: this.state.pointer.cx,
        y: this.state.pointer.cy
      }));
    }

    if (this.props.isEqual(this.state.activeNodes, fNodes)) {
      return;
    }

    this.dispatcher.clear();
    this.state.activeNodes = fNodes;

    if (this.state.activeNodes.length) {
      this.dispatcher.invoke(function () {
        return _this.invokeRenderer(_this.state.activeNodes);
      }, duration, delay);
    }
  },
  prevent: function prevent(p) {
    this.state.prevent = !!p;
  },
  init: function init(settings) {
    var _this2 = this;

    this.state = {
      activeNodes: [],
      pointer: {},
      targetElement: null,
      prevent: false
    };
    this.props = settings.settings;
    this.dispatcher = timeSpanDispatcher({
      defaultDuration: this.props.duration,
      defaultDelay: this.props.delay
    });
    var instanceId = this.dispatcher.clear;
    this.dispatcher.on('pending', function () {
      // Cancel only if the active is another instance
      cancelActive(instanceId);
      picasso_esm_setActive(instanceId);

      if (typeof _this2.props.beforeShow === 'function') {
        _this2.props.beforeShow.call(undefined, {
          resources: {
            formatter: _this2.chart.formatter,
            scale: _this2.chart.scale
          }
        });
      }
    });
    this.dispatcher.on(['cancelled', 'fulfilled'], function () {
      var listenerCtx = {
        resources: {
          formatter: _this2.chart.formatter,
          scale: _this2.chart.scale
        }
      };

      if (typeof _this2.props.beforeHide === 'function') {
        _this2.props.beforeHide.call(undefined, extend({
          element: _this2.state.tooltipElm
        }, listenerCtx));
      }

      if (typeof _this2.props.onHide === 'function') {
        _this2.props.onHide.call(undefined, extend({
          element: _this2.state.tooltipElm
        }, listenerCtx));
      } else {
        _this2.renderer.clear([]); // Hide tooltip

      }

      if (typeof _this2.props.afterHide === 'function') {
        _this2.props.afterHide.call(undefined, listenerCtx);
      }

      removeActive(instanceId);
      _this2.state.tooltipElm = undefined;
    });
    this.dispatcher.on('active', function () {
      if (typeof _this2.props.afterShow === 'function') {
        _this2.props.afterShow.call(undefined, {
          element: _this2.state.tooltipElm,
          resources: {
            formatter: _this2.chart.formatter,
            scale: _this2.chart.scale
          }
        });
      }
    });
  },
  created: function created() {
    this.init(this.settings);
  },
  beforeUpdate: function beforeUpdate(_ref4) {
    var settings = _ref4.settings;

    if (this.dispatcher) {
      this.dispatcher.destroy();
      remove$1();
    }

    this.init(settings);
  },
  render: function render(h) {
    this.h = h;
    return []; // Nothing to render initially.
  },
  beforeDestroy: function beforeDestroy() {
    this.dispatcher.destroy();
    remove$1();
  },
  appendTo: function appendTo() {
    if (this.props.appendTo) {
      this.state.targetElement = typeof this.props.appendTo === 'function' ? this.props.appendTo({
        resources: {
          formatter: this.chart.formatter,
          scale: this.chart.scale
        }
      }) : this.props.appendTo;

      var _this$state$targetEle = this.state.targetElement.getBoundingClientRect(),
          width = _this$state$targetEle.width,
          height = _this$state$targetEle.height;

      this.renderer.destroy();
      this.renderer.size({
        width: width,
        height: height
      });
      this.renderer.appendTo(this.state.targetElement);
    } else {
      this.state.targetElement = this.renderer.element();
    }
  },
  mounted: function mounted() {
    this.appendTo();
  },
  updated: function updated() {
    // Append here to, otherwise the picasso displayOrder logic screw things up
    this.appendTo();
  },
  invokeRenderer: function invokeRenderer(nodes) {
    var items = extractor(nodes, this);
    var pseudoElement = render$3(items, {
      style: {
        left: '0px',
        top: '0px',
        visibility: 'hidden'
      }
    }, this);
    var pos = picasso_esm_placement(pseudoElement.getBoundingClientRect(), this);
    this.state.tooltipElm = render$3(items, pos, this);
  }
};

/**
 * @typedef {object} component--tooltip
 */

/**
 * @type {string}
 * @memberof component--tooltip
 */

var type$4 = 'tooltip';
function addTooltip(picasso) {
  picasso.component(type$4, component$3);
}

var debugColliderDef = {
  require: ['renderer', 'chart'],
  defaultSettings: {
    settings: {
      target: '',
      selector: '*',
      fill: 'rgba(0, 255, 0, 0.1)',
      stroke: 'lime',
      opacity: 1,
      useOuterRect: false
    }
  },
  on: {
    update: function update() {
      this.draw();
    }
  },
  draw: function draw() {
    var _this = this;

    var shapes = this.chart.findShapes(this.props.selector).filter(function (s) {
      return s.key === _this.props.target;
    }); // Find all shapes

    var colliders = shapes.filter(function (s) {
      return s.collider;
    }).map(function (s) {
      return s.collider;
    });
    colliders.forEach(function (c) {
      c.fill = _this.props.fill;
      c.stroke = _this.props.stroke;
      c.opacity = _this.props.opacity;
      c.collider = {
        type: null
      };
    });
    this.renderer.render(colliders);
  },
  created: function created() {
    this.props = this.settings.settings;
  },
  resize: function resize(_ref) {
    var outer = _ref.outer,
        inner = _ref.inner;

    if (this.props.useOuterRect) {
      return outer;
    }

    return inner;
  },
  render: function render() {},
  mounted: function mounted() {
    this.draw();
  },
  updated: function updated() {
    this.props = this.settings.settings;
    this.draw();
  }
};

var PI_X2 = Math.PI * 2;
/**
 * Implementation of F.6.5 https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
 * @ignore
 * @param {number} rx - Arc x-radius
 * @param {number} ry - Arc y-radius
 * @param {number} rotation - Arc rotation in degrees (0-360)
 * @param {boolean} largeArcFlag
 * @param {boolean} sweepFlag
 * @param {number} endX - X-coordinate for end of arc
 * @param {number} endY - Y-coordinate for end of arc
 * @param {number} startX - X-coordinate for start of arc
 * @param {number} startY - Y-coordinate for start of arc
 * @returns {object}
 */

function arcToCenter(rx, ry, rotation, largeArcFlag, sweepFlag, endX, endY, startX, startY) {
  var startAngle;
  var endAngle;
  var sweepAngle;
  var cx;
  var cy;
  var radiusRatio;
  var rad = toRadians(rotation % 360); // F.6.5.1

  var cos = Math.cos(rad);
  var sin = Math.sin(rad);
  var hdx = (startX - endX) / 2;
  var hdy = (startY - endY) / 2;
  var x1d = cos * hdx + sin * hdy;
  var y1d = cos * hdy - sin * hdx; // F.6.6

  rx = Math.abs(rx);
  ry = Math.abs(ry);
  radiusRatio = Math.pow(x1d, 2) / Math.pow(rx, 2) + Math.pow(y1d, 2) / Math.pow(ry, 2);

  if (radiusRatio > 1) {
    radiusRatio = Math.sqrt(radiusRatio);
    rx *= radiusRatio;
    ry *= radiusRatio;
  } // F.6.5.2


  var rxry = rx * ry;
  var rxy1d = rx * y1d;
  var ryx1d = ry * x1d;
  var den = Math.pow(rxy1d, 2) + Math.pow(ryx1d, 2);
  var num = Math.pow(rxry, 2) - den;
  var frac = Math.sqrt(Math.max(num / den, 0));

  if (largeArcFlag === sweepFlag) {
    frac = -frac;
  }

  var cxd = frac * (rxy1d / ry);
  var cyd = frac * -(ryx1d / rx); // F.6.5.3

  var mx = (startX + endX) / 2;
  var my = (startY + endY) / 2;
  cx = cos * cxd - sin * cyd + mx;
  cy = sin * cxd + cos * cyd + my; // F.6.5.6 clockwise angle

  var ux = (x1d - cxd) / rx;
  var uy = (y1d - cyd) / ry;
  var vx = (-x1d - cxd) / rx;
  var vy = (-y1d - cyd) / ry;
  startAngle = Math.atan2(uy, ux);
  startAngle += startAngle < 0 ? PI_X2 : 0;
  endAngle = Math.atan2(vy, vx);
  endAngle += endAngle < 0 ? PI_X2 : 0;
  sweepAngle = endAngle - startAngle;

  if (!sweepFlag && startAngle < endAngle) {
    sweepAngle -= PI_X2;
  } else if (sweepFlag && endAngle < startAngle) {
    sweepAngle += PI_X2;
  }

  sweepAngle %= PI_X2;
  return {
    startAngle: startAngle,
    sweepAngle: sweepAngle,
    cx: cx,
    cy: cy,
    rx: rx,
    ry: ry
  };
}

/**
 * Measure the flatnass of a cubic bezier curve
 * @ignore
 * @param {point} s - Start point
 * @param {point} cp1 - First control point
 * @param {point} cp2 - Second control point
 * @param {point} e - End point
 */
function flatness(s, cp1, cp2, e) {
  var ux = Math.abs(s.x + cp2.x - (cp1.x + cp1.x));
  var uy = Math.abs(s.y + cp2.y - (cp1.y + cp1.y));
  var vx = Math.abs(cp1.x + e.x - (cp2.x + cp2.x));
  var vy = Math.abs(cp1.y + e.y - (cp2.y + cp2.y));
  return ux + uy + vx + vy;
}

function mid(p0, p1) {
  return {
    x: (p0.x + p1.x) / 2,
    y: (p0.y + p1.y) / 2
  };
}

function picasso_esm_interpolate(t, s, cp1, cp2, e) {
  var td = 1 - t;
  var t0 = Math.pow(td, 3) * s;
  var t1 = 3 * Math.pow(td, 2) * t * cp1;
  var t2 = 3 * td * Math.pow(t, 2) * cp2;
  var t3 = Math.pow(t, 3) * e;
  return t0 + t1 + t2 + t3;
}
/**
 * Recursive subdivision of a curve using de Casteljau algorithm.
 * Splits the curve into multiple line segments where each segments is choosen based on a level of flatness.
 * @ignore
 * @param {point} s - Start point
 * @param {point} cp1 - First control point
 * @param {point} cp2 - Second control point
 * @param {point} e - End point
 * @param {array} points - Initial set of points
 * @returns {point[]} Array of points
 */


function toPoints(s, cp1, cp2, e) {
  var points = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : [];

  if (flatness(s, cp1, cp2, e) <= 10) {
    // Poor man's Set
    if (points.indexOf(s) === -1) {
      points.push(s);
    }

    if (points.indexOf(e) === -1) {
      points.push(e);
    }

    return points;
  }

  var t = 0.5;
  var m0 = mid(s, cp1);
  var m1 = mid(cp1, cp2);
  var m2 = mid(cp2, e);
  var b = {
    // Split curve at point
    x: picasso_esm_interpolate(t, s.x, cp1.x, cp2.x, e.x),
    y: picasso_esm_interpolate(t, s.y, cp1.y, cp2.y, e.y)
  };
  var q0 = mid(m0, m1); // New cp2 for left curve

  var q1 = mid(m1, m2); // New cp1 for right curve

  toPoints(s, m0, q0, b, points); // left curve

  toPoints(b, q1, m2, e, points); // Right curve

  return points;
}

function toCubic(s, cp, e) {
  var cp1x = s.x + 2 / 3 * (cp.x - s.x);
  var cp1y = s.y + 2 / 3 * (cp.y - s.y);
  var cp2x = e.x + 2 / 3 * (cp.x - e.x);
  var cp2y = e.y + 2 / 3 * (cp.y - e.y);
  var cp1 = {
    x: cp1x,
    y: cp1y
  };
  var cp2 = {
    x: cp2x,
    y: cp2y
  };
  return {
    cp1: cp1,
    cp2: cp2
  };
}
/**
 * Recursive subdivision of a curve using de Casteljau algorithm.
 * Splits the curve into multiple line segments where each segments is choosen based on a level of flatness.
 * @ignore
 * @param {point} s - Start point
 * @param {point} cp - Control point
 * @param {point} e - End point
 * @returns {point[]} Array of points
 */


function toPoints$1(s, cp, e) {
  var _toCubic = toCubic(s, cp, e),
      cp1 = _toCubic.cp1,
      cp2 = _toCubic.cp2;

  return toPoints(s, cp1, cp2, e);
}

var EPSILON$1 = 1e-12;

function removeDuplicates(points) {
  for (var i = 0; i < points.length - 1; i++) {
    var p0 = points[i];
    var p1 = points[i + 1];

    if (Math.abs(p0.x - p1.x) < EPSILON$1 && Math.abs(p0.y - p1.y) < EPSILON$1) {
      points.splice(i, 1);
      i--;
    }
  }
}
/**
 * Transform an arc to a set of points a long the arc.
 * Specifiction F.6 (https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes)
 * @ignore
 * @param {array} s - Segments
 * @param {number} startX - X-coordinate for start of arc
 * @param {number} startY - Y-coordinate for start of arc
 */


function arcToPoints(s, startX, startY) {
  var points = [];
  var largeArcFlag = !!s[4]; // F.6.3

  var sweepFlag = !!s[5]; // F.6.3

  var rotation = s[3];
  var endX = s[6];
  var endY = s[7];
  var rx = s[1];
  var ry = s[2];
  var cx;
  var cy;
  var sweepAngle;
  var startAngle;

  if (s[0] === 'a') {
    endX += startX;
    endY += startY;
  } // F.6.2


  if (startX === endY && startY === endY) {
    return points;
  } // Given no radius, threat as lineTo command


  if (!rx || !ry) {
    points.push({
      x: endX,
      y: endY
    });
    return points;
  }

  var _arcToCenter = arcToCenter(rx, ry, rotation, largeArcFlag, sweepFlag, endX, endY, startX, startY);

  cx = _arcToCenter.cx;
  cy = _arcToCenter.cy;
  rx = _arcToCenter.rx;
  ry = _arcToCenter.ry;
  sweepAngle = _arcToCenter.sweepAngle;
  startAngle = _arcToCenter.startAngle;
  // Approximation of perimeter
  var p = Math.abs(sweepAngle * Math.sqrt((Math.pow(rx, 2) + Math.pow(ry, 2)) / 2)); // Generate a point every 10th pixel. Scaling of the node should probably be included in this calculation

  var res = Math.ceil(p / 10);
  var resAngle = sweepAngle / res;

  for (var k = 1; k <= res; k++) {
    var deltaAngle = resAngle * k;
    var radians = (startAngle + deltaAngle) % PI_X2;
    var cos = Math.cos(radians);
    var sin = Math.sin(radians); // F.6.3 https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes

    points.push({
      x: cx + cos * rx + -sin * cos,
      y: cy + sin * ry + cos * sin
    });
  } // points.push({ x: cx, y: cy });


  return points;
}
/**
 * Converts a SVG path data string into a set of points.
 * @ignore
 * @param {string} path
 * @returns {Array<point[]>} Array of points
 */


function pathToPoints(path) {
  var commands = src_2(path);
  var segments = [];
  var points = [];
  var x = 0; // Current point

  var y = 0;
  var cpx = null; // Last control point on a cubic curve

  var cpy = null;
  var qcpx = null; // Last control point on a quad curve

  var qcpy = null;

  for (var i = 0; i < commands.length; ++i) {
    var cmd = commands[i];
    var pathType = cmd[0]; // Reset control point if command is not cubic

    if (pathType !== 'S' && pathType !== 's' && pathType !== 'C' && pathType !== 'c') {
      cpx = null;
      cpy = null;
    }

    if (pathType !== 'T' && pathType !== 't' && pathType !== 'Q' && pathType !== 'q') {
      qcpx = null;
      qcpy = null;
    }

    switch (pathType) {
      case 'm':
        if (points.length) {
          segments.push(points.splice(0));
        }

      // Fall through

      case 'l':
        // eslint-disable-line no-fallthrough
        x += cmd[1];
        y += cmd[2];
        points.push({
          x: x,
          y: y
        });
        break;

      case 'M':
        if (points.length) {
          segments.push(points.splice(0));
        }

      // Fall through

      case 'L':
        // eslint-disable-line no-fallthrough
        x = cmd[1];
        y = cmd[2];
        points.push({
          x: x,
          y: y
        });
        break;

      case 'H':
        x = cmd[1];
        points.push({
          x: x,
          y: y
        });
        break;

      case 'h':
        x += cmd[1];
        points.push({
          x: x,
          y: y
        });
        break;

      case 'V':
        y = cmd[1];
        points.push({
          x: x,
          y: y
        });
        break;

      case 'v':
        y += cmd[1];
        points.push({
          x: x,
          y: y
        });
        break;

      case 'a':
        points.push.apply(points, _toConsumableArray$1(arcToPoints(cmd, x, y)));
        x += cmd[6];
        y += cmd[7];
        break;

      case 'A':
        points.push.apply(points, _toConsumableArray$1(arcToPoints(cmd, x, y)));
        x = cmd[6];
        y = cmd[7];
        break;

      case 'c':
        points.push.apply(points, _toConsumableArray$1(toPoints({
          x: x,
          y: y
        }, {
          x: cmd[1] + x,
          y: cmd[2] + y
        }, {
          x: cmd[3] + x,
          y: cmd[4] + y
        }, {
          x: cmd[5] + x,
          y: cmd[6] + y
        })));
        cpx = cmd[3] + x; // Last control point

        cpy = cmd[4] + y;
        x += cmd[5];
        y += cmd[6];
        break;

      case 'C':
        points.push.apply(points, _toConsumableArray$1(toPoints({
          x: x,
          y: y
        }, {
          x: cmd[1],
          y: cmd[2]
        }, {
          x: cmd[3],
          y: cmd[4]
        }, {
          x: cmd[5],
          y: cmd[6]
        })));
        cpx = cmd[3]; // Last control point

        cpy = cmd[4];
        x = cmd[5];
        y = cmd[6];
        break;

      case 's':
        if (cpx === null || cpx === null) {
          cpx = x;
          cpy = y;
        }

        points.push.apply(points, _toConsumableArray$1(toPoints({
          x: x,
          y: y
        }, {
          x: 2 * x - cpx,
          y: 2 * y - cpy
        }, {
          x: cmd[1] + x,
          y: cmd[2] + y
        }, {
          x: cmd[3] + x,
          y: cmd[4] + y
        })));
        cpx = cmd[1] + x; // last control point

        cpy = cmd[2] + y;
        x += cmd[3];
        y += cmd[4];
        break;

      case 'S':
        if (cpx === null || cpx === null) {
          cpx = x;
          cpy = y;
        }

        points.push.apply(points, _toConsumableArray$1(toPoints({
          x: x,
          y: y
        }, {
          x: 2 * x - cpx,
          y: 2 * y - cpy
        }, {
          x: cmd[1],
          y: cmd[2]
        }, {
          x: cmd[3],
          y: cmd[4]
        })));
        cpx = cmd[1]; // last control point

        cpy = cmd[2];
        x = cmd[3];
        y = cmd[4];
        break;

      case 'Q':
        points.push.apply(points, _toConsumableArray$1(toPoints$1({
          x: x,
          y: y
        }, {
          x: cmd[1],
          y: cmd[2]
        }, {
          x: cmd[3],
          y: cmd[4]
        })));
        qcpx = cmd[1]; // last control point

        qcpy = cmd[2];
        x = cmd[3];
        y = cmd[4];
        break;

      case 'q':
        points.push.apply(points, _toConsumableArray$1(toPoints$1({
          x: x,
          y: y
        }, {
          x: cmd[1] + x,
          y: cmd[2] + y
        }, {
          x: cmd[3] + x,
          y: cmd[4] + y
        })));
        qcpx = cmd[1] + x; // last control point

        qcpy = cmd[2] + y;
        x += cmd[3];
        y += cmd[4];
        break;

      case 'T':
        if (qcpx === null || qcpx === null) {
          qcpx = x;
          qcpy = y;
        }

        qcpx = 2 * x - qcpx; // last control point

        qcpy = 2 * y - qcpy;
        points.push.apply(points, _toConsumableArray$1(toPoints$1({
          x: x,
          y: y
        }, {
          x: qcpx,
          y: qcpy
        }, {
          x: cmd[1],
          y: cmd[2]
        })));
        x = cmd[1];
        y = cmd[2];
        break;

      case 't':
        if (qcpx === null || qcpx === null) {
          qcpx = x;
          qcpy = y;
        }

        qcpx = 2 * x - qcpx; // last control point

        qcpy = 2 * y - qcpy;
        points.push.apply(points, _toConsumableArray$1(toPoints$1({
          x: x,
          y: y
        }, {
          x: qcpx,
          y: qcpy
        }, {
          x: cmd[1] + x,
          y: cmd[2] + y
        })));
        x += cmd[1];
        y += cmd[2];
        break;

      case 'z':
      case 'Z':
        if (points.length) {
          points.push({
            x: points[0].x,
            y: points[0].y
          });
        }

        break;

      default: // Do nothing

    }
  }

  removeDuplicates(points);
  segments.push(points.splice(0));
  return segments;
}

var debugPathToPointsDef = {
  require: ['renderer', 'chart'],
  defaultSettings: {
    settings: {
      target: '',
      fill: 'transparent',
      stroke: 'lime',
      opacity: 1,
      radius: 2,
      useOuterRect: false
    }
  },
  on: {
    update: function update() {
      this.draw();
    }
  },
  draw: function draw() {
    var _this = this;

    var shapes = this.chart.findShapes('path').filter(function (s) {
      return s.key === _this.props.target;
    }); // Find all shapes

    var circles = [];
    shapes.forEach(function (s) {
      pathToPoints(s.attrs.d).forEach(function (segment) {
        segment.forEach(function (p) {
          circles.push({
            type: 'circle',
            cx: p.x,
            cy: p.y,
            r: _this.props.radius,
            fill: _this.props.fill,
            stroke: _this.props.stroke,
            opacity: _this.props.opacity,
            collider: {
              type: null
            }
          });
        });
      });
    });
    this.renderer.render(circles);
  },
  created: function created() {
    this.props = this.settings.settings;
  },
  resize: function resize(_ref) {
    var outer = _ref.outer,
        inner = _ref.inner;

    if (this.props.useOuterRect) {
      return outer;
    }

    return inner;
  },
  render: function render() {},
  mounted: function mounted() {
    this.draw();
  },
  updated: function updated() {
    this.props = this.settings.settings;
    this.draw();
  }
};

function debugCollider(picasso) {
  picasso.component('debug-collider', debugColliderDef);
}
function debugPathToPoints(picasso) {
  picasso.component('debug-path-to-points', debugPathToPointsDef);
}

var components = [box$1, pointMarker, pie$1, gridLine, refLine, picasso_esm_axis, picasso_esm_text, scrollbar, rangeBrush, rangeBrush$1, lassoBrush, picasso_esm_labels, categoricalLegend, sequentialLegend, line$2, areaBrush, addTooltip, debugCollider, debugPathToPoints];

var Node =
/*#__PURE__*/
function () {
  /**
   * @private
   */
  function Node(type) {
    _classCallCheck$1(this, Node);

    this._parent = null;
    this._children = [];
    this._ancestors = null;
    this.type = type;
    this.data = null;
  }
  /**
   * Detaches this node from its parent, if such exists.
   * @returns {Node}
   */


  _createClass$1(Node, [{
    key: "detach",
    value: function detach() {
      if (this._parent) {
        this._parent.removeChild(this);
      }

      return this;
    }
    /**
     * Parent of this node.
     * @readonly
     * @type {Node}
     */

  }, {
    key: "equals",

    /**
     *
     * @returns {Boolean}
     */
    value: function equals(n) {
      var children = this.children;
      var nChildren = n.children;

      if (children.length !== nChildren.length) {
        return false;
      } // Requires deterministic child order


      for (var i = 0; i < children.length; i++) {
        if (!children[i].equals(nChildren[i])) {
          return false;
        }
      }

      return true;
    }
  }, {
    key: "toJSON",
    value: function toJSON() {
      return {
        type: this.type,
        children: this.children.map(function (ch) {
          return ch.toJSON();
        })
      };
    }
  }, {
    key: "parent",
    get: function get() {
      return this._parent;
    }
    /**
     * Checks whether this node is a branch.
     *
     * True if this node has children, false otherwise.
     * @readonly
     * @type {Boolean}
     */

  }, {
    key: "isBranch",
    get: function get() {
      return this._children && this._children.length;
    }
    /**
     * Children of this node.
     * @readonly
     * @type {Node[]}
     */

  }, {
    key: "children",
    get: function get() {
      return this._children;
    }
    /**
     * Ancestors of this node, including parent.
     * @readonly
     * @type {Node[]}
     */

  }, {
    key: "ancestors",
    get: function get() {
      if (!this._ancestors) {
        this._ancestors = [];

        if (this.parent) {
          var _this$_ancestors;

          (_this$_ancestors = this._ancestors).push.apply(_this$_ancestors, [this.parent].concat(_toConsumableArray$1(this.parent.ancestors)));
        }
      }

      return this._ancestors;
    }
    /**
     * Descendants of this node.
     * @readonly
     * @type {Node[]}
     */

  }, {
    key: "descendants",
    get: function get() {
      var r = [];
      var len = this.children.length;
      var i;
      var c;

      for (i = 0, len; i < len; i++) {
        c = this.children[i];
        r.push(c);

        if (c.children.length) {
          r.push.apply(r, _toConsumableArray$1(c.descendants));
        }
      }

      return r;
    }
  }]);

  return Node;
}();

/**
 * Construct a new GeoRect instance
 * @private
 */

var GeoRect =
/*#__PURE__*/
function () {
  function GeoRect() {
    var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        _ref$x = _ref.x,
        x = _ref$x === void 0 ? 0 : _ref$x,
        _ref$y = _ref.y,
        y = _ref$y === void 0 ? 0 : _ref$y,
        _ref$width = _ref.width,
        width = _ref$width === void 0 ? 0 : _ref$width,
        _ref$height = _ref.height,
        height = _ref$height === void 0 ? 0 : _ref$height,
        _ref$minWidth = _ref.minWidth,
        minWidth = _ref$minWidth === void 0 ? 0 : _ref$minWidth,
        _ref$minHeight = _ref.minHeight,
        minHeight = _ref$minHeight === void 0 ? 0 : _ref$minHeight;

    _classCallCheck$1(this, GeoRect);

    this.set({
      x: x,
      y: y,
      width: width,
      height: height,
      minWidth: minWidth,
      minHeight: minHeight
    });
  }

  _createClass$1(GeoRect, [{
    key: "set",
    value: function set() {
      var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref2$x = _ref2.x,
          x = _ref2$x === void 0 ? 0 : _ref2$x,
          _ref2$y = _ref2.y,
          y = _ref2$y === void 0 ? 0 : _ref2$y,
          _ref2$width = _ref2.width,
          width = _ref2$width === void 0 ? 0 : _ref2$width,
          _ref2$height = _ref2.height,
          height = _ref2$height === void 0 ? 0 : _ref2$height,
          _ref2$minWidth = _ref2.minWidth,
          minWidth = _ref2$minWidth === void 0 ? 0 : _ref2$minWidth,
          _ref2$minHeight = _ref2.minHeight,
          minHeight = _ref2$minHeight === void 0 ? 0 : _ref2$minHeight;

      this.type = 'rect';

      if (width >= 0) {
        this.x = x;
        this.width = Math.max(width, minWidth);
      } else {
        this.x = x + Math.min(width, -minWidth);
        this.width = -Math.min(width, -minWidth);
      }

      if (height >= 0) {
        this.y = y;
        this.height = Math.max(height, minHeight);
      } else {
        this.y = y + Math.min(height, -minHeight);
        this.height = -Math.min(height, -minHeight);
      }
    }
    /**
     * @param {point} p
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "containsPoint",
    value: function containsPoint(p) {
      return testRectPoint(this, p);
    }
    /**
     * @param {point[]} points - Line start and end point as an array of points
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsLine",
    value: function intersectsLine(points) {
      var line = pointsToLine(points);
      return testRectLine(this, line);
    }
    /**
     * @param {point[]} points - Rect vertices as an array of points
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsRect",
    value: function intersectsRect(points) {
      var rect = pointsToRect(points);
      return testRectRect(this, rect);
    }
    /**
     * @param {circle} c
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsCircle",
    value: function intersectsCircle(c) {
      return testCircleRect(c, this);
    }
    /**
     * @param {GeoPolygon} polygon
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsPolygon",
    value: function intersectsPolygon(polygon) {
      return testPolygonRect(polygon, this);
    }
    /**
     * Get the points
     * @returns {point[]}
     */

  }, {
    key: "points",
    value: function points() {
      return [{
        x: this.x,
        y: this.y
      }, {
        x: this.x + this.width,
        y: this.y
      }, {
        x: this.x + this.width,
        y: this.y + this.height
      }, {
        x: this.x,
        y: this.y + this.height
      }];
    }
  }]);

  return GeoRect;
}();

function create$4() {
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }

  return _construct(GeoRect, args);
}

/**
 * Construct a new GeoCircle instance
 * @private
 */

var GeoCircle =
/*#__PURE__*/
function () {
  function GeoCircle() {
    var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        _ref$cx = _ref.cx,
        cx = _ref$cx === void 0 ? 0 : _ref$cx,
        _ref$cy = _ref.cy,
        cy = _ref$cy === void 0 ? 0 : _ref$cy,
        _ref$r = _ref.r,
        r = _ref$r === void 0 ? 0 : _ref$r,
        _ref$minRadius = _ref.minRadius,
        minRadius = _ref$minRadius === void 0 ? 0 : _ref$minRadius;

    _classCallCheck$1(this, GeoCircle);

    this.set({
      cx: cx,
      cy: cy,
      r: r,
      minRadius: minRadius
    });
  }

  _createClass$1(GeoCircle, [{
    key: "set",
    value: function set() {
      var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref2$cx = _ref2.cx,
          cx = _ref2$cx === void 0 ? 0 : _ref2$cx,
          _ref2$cy = _ref2.cy,
          cy = _ref2$cy === void 0 ? 0 : _ref2$cy,
          _ref2$r = _ref2.r,
          r = _ref2$r === void 0 ? 0 : _ref2$r,
          _ref2$minRadius = _ref2.minRadius,
          minRadius = _ref2$minRadius === void 0 ? 0 : _ref2$minRadius;

      this.type = 'circle';
      this.cx = cx;
      this.cy = cy;
      this.r = Math.max(r, minRadius);
      this.vector = {
        x: this.cx,
        y: this.cy
      };
    }
    /**
     * @param {point} p
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "containsPoint",
    value: function containsPoint(p) {
      return testCirclePoint(this, p);
    }
    /**
     * @param {point[]} points - Line start and end point as an array of points
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsLine",
    value: function intersectsLine(points) {
      var line = pointsToLine(points);
      return testCircleLine(this, line);
    }
    /**
     * @param {point[]} points - Rect vertices as an array of points
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsRect",
    value: function intersectsRect(points) {
      var rect = pointsToRect(points);
      return testCircleRect(this, rect);
    }
    /**
     * @param {circle} c
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsCircle",
    value: function intersectsCircle(c) {
      return testCircleCircle(this, c);
    }
    /**
     * @param {GeoPolygon} polygon
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsPolygon",
    value: function intersectsPolygon(polygon) {
      return testCirclePolygon(this, polygon);
    }
    /**
     * Get the points
     * @returns {point[]}
     */

  }, {
    key: "points",
    value: function points() {
      return [{
        x: this.cx,
        y: this.cy
      }];
    }
  }]);

  return GeoCircle;
}();

function create$5() {
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }

  return _construct(GeoCircle, args);
}

/**
 * Construct a new GeoLine instance
 * @private
 */

var GeoLine =
/*#__PURE__*/
function () {
  function GeoLine() {
    var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        _ref$x = _ref.x1,
        x1 = _ref$x === void 0 ? 0 : _ref$x,
        _ref$y = _ref.y1,
        y1 = _ref$y === void 0 ? 0 : _ref$y,
        _ref$x2 = _ref.x2,
        x2 = _ref$x2 === void 0 ? 0 : _ref$x2,
        _ref$y2 = _ref.y2,
        y2 = _ref$y2 === void 0 ? 0 : _ref$y2,
        _ref$tolerance = _ref.tolerance,
        tolerance = _ref$tolerance === void 0 ? 0 : _ref$tolerance;

    _classCallCheck$1(this, GeoLine);

    this.set({
      x1: x1,
      y1: y1,
      x2: x2,
      y2: y2,
      tolerance: tolerance
    });
  }

  _createClass$1(GeoLine, [{
    key: "set",
    value: function set() {
      var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref2$x = _ref2.x1,
          x1 = _ref2$x === void 0 ? 0 : _ref2$x,
          _ref2$y = _ref2.y1,
          y1 = _ref2$y === void 0 ? 0 : _ref2$y,
          _ref2$x2 = _ref2.x2,
          x2 = _ref2$x2 === void 0 ? 0 : _ref2$x2,
          _ref2$y2 = _ref2.y2,
          y2 = _ref2$y2 === void 0 ? 0 : _ref2$y2,
          _ref2$tolerance = _ref2.tolerance,
          tolerance = _ref2$tolerance === void 0 ? 0 : _ref2$tolerance;

      this.type = 'line';
      this.x1 = x1;
      this.y1 = y1;
      this.x2 = x2;
      this.y2 = y2;
      this.tolerance = Math.max(0, Math.round(tolerance));
      this.vectors = this.points();
      this.zeroSize = x1 === x2 && y1 === y2;
    }
    /**
     * @param {point} p
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "containsPoint",
    value: function containsPoint(p) {
      if (this.tolerance > 0) {
        var c = {
          cx: p.x,
          cy: p.y,
          r: this.tolerance
        };
        return testCircleLine(c, this);
      }

      return testLinePoint(this, p);
    }
    /**
     * @param {point[]} points - Line start and end point as an array of points
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsLine",
    value: function intersectsLine(points) {
      var line = pointsToLine(points);
      return testLineLine(this, line);
    }
    /**
     * @param {point[]} points - Rect vertices as an array of points
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsRect",
    value: function intersectsRect(points) {
      var rect = pointsToRect(points);
      return testRectLine(rect, this);
    }
    /**
     * @param {circle} c
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsCircle",
    value: function intersectsCircle(c) {
      return testCircleLine(c, this);
    }
    /**
     * @param {GeoPolygon} polygon
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsPolygon",
    value: function intersectsPolygon(polygon) {
      return testPolygonLine(polygon, this);
    }
    /**
     * Get the points
     * @returns {point[]}
     */

  }, {
    key: "points",
    value: function points() {
      return [{
        x: this.x1,
        y: this.y1
      }, {
        x: this.x2,
        y: this.y2
      }];
    }
  }]);

  return GeoLine;
}();

function create$6() {
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }

  return _construct(GeoLine, args);
}

function picasso_esm_close(vertices) {
  var first = vertices[0];
  var last = vertices[vertices.length - 1];

  if (first.x !== last.x || first.y !== last.y) {
    vertices.push(first);
  }
}

function removeDuplicates$1(vertices) {
  for (var i = 0; i < vertices.length - 1; i++) {
    var v0 = vertices[i];
    var v1 = vertices[i + 1];

    if (v0.x === v1.x && v0.y === v1.y) {
      vertices.splice(i, 1);
      i--;
    }
  }
}
/**
 * Construct a new GeoPolygon instance
 * @private
 */


var GeoPolygon =
/*#__PURE__*/
function () {
  function GeoPolygon() {
    var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        _ref$vertices = _ref.vertices,
        vertices = _ref$vertices === void 0 ? [] : _ref$vertices;

    _classCallCheck$1(this, GeoPolygon);

    this.set({
      vertices: vertices
    });
  }
  /**
   * Set the vertices.
   * If vertices doesn't close the polygon, a closing vertice is appended.
   * @param {object} input An object with a vertices property
   * @param {point[]} [input.vertices=[]] Vertices are represented as an array of points.
   */


  _createClass$1(GeoPolygon, [{
    key: "set",
    value: function set() {
      var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref2$vertices = _ref2.vertices,
          vertices = _ref2$vertices === void 0 ? [] : _ref2$vertices;

      this.type = 'polygon';
      this.vertices = vertices.slice();
      this.edges = [];
      removeDuplicates$1(this.vertices);

      if (this.vertices.length <= 2) {
        return;
      }

      picasso_esm_close(this.vertices);
      this.xMin = NaN;
      this.yMin = NaN;
      this.xMax = NaN;
      this.yMax = NaN;

      for (var i = 0; i < this.vertices.length; i++) {
        if (i < this.vertices.length - 1) {
          this.edges.push([this.vertices[i], this.vertices[i + 1]]);
        }

        this.xMin = isNaN(this.xMin) ? this.vertices[i].x : Math.min(this.xMin, this.vertices[i].x);
        this.xMax = isNaN(this.xMax) ? this.vertices[i].x : Math.max(this.xMax, this.vertices[i].x);
        this.yMin = isNaN(this.yMin) ? this.vertices[i].y : Math.min(this.yMin, this.vertices[i].y);
        this.yMax = isNaN(this.yMax) ? this.vertices[i].y : Math.max(this.yMax, this.vertices[i].y);
      }

      this._bounds = null;
      this._boundingRect = null;
    }
    /**
     * Check if a point is inside the area of the polygon.
     * Supports convex, concave and self-intersecting polygons (filled area).
     * @param {point} point
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "containsPoint",
    value: function containsPoint(point) {
      return testPolygonPoint(this, point);
    }
    /**
     * Check if circle is inside the area of the polygon.
     * Supports convex, concave and self-intersecting polygons (filled area).
     * @param {circle} circle
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsCircle",
    value: function intersectsCircle(circle) {
      return testCirclePolygon(circle, this);
    }
    /**
     * @param {point[]} points - Line start and end point as an array of points
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsLine",
    value: function intersectsLine(points) {
      return testPolygonLine(this, pointsToLine(points));
    }
    /**
     * @param {point[]} points - Rect vertices as an array of points
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsRect",
    value: function intersectsRect(points) {
      return testPolygonRect(this, pointsToRect(points));
    }
    /**
     * Check if polygon intersects another polygon.
     * Supports convex, concave and self-intersecting polygons (filled area).
     * @param {GeoPolygon} polygon
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsPolygon",
    value: function intersectsPolygon(polygon) {
      // This is a unoptimized solution and should be replaced by a more efficient algorithm.
      if (!testRectRect(this.boundingRect(), polygon.boundingRect())) {
        return false;
      }

      var intersects = false;

      for (var i = 0, len = this.edges.length; i < len; i++) {
        intersects = testPolygonLine(polygon, pointsToLine(this.edges[i]));

        if (intersects === true) {
          break;
        }
      }

      return intersects;
    }
    /**
     * Get the points
     * @returns {point[]}
     */

  }, {
    key: "points",
    value: function points() {
      return this.vertices;
    }
    /**
     * Get the bounds of the polygon, as an array of points
     * @returns {point[]}
     */

  }, {
    key: "bounds",
    value: function bounds() {
      if (!this._bounds) {
        this._bounds = [{
          x: this.xMin,
          y: this.yMin
        }, {
          x: this.xMax,
          y: this.yMin
        }, {
          x: this.xMax,
          y: this.yMax
        }, {
          x: this.xMin,
          y: this.yMax
        }];
      }

      return this._bounds;
    }
    /**
     * Get the bounding rect of the polygon
     * @returns {rect}
     */

  }, {
    key: "boundingRect",
    value: function boundingRect() {
      if (!this._boundingRect) {
        this._boundingRect = {
          x: this.xMin,
          y: this.yMin,
          width: this.xMax - this.xMin,
          height: this.yMax - this.yMin
        };
      }

      return this._boundingRect;
    }
  }]);

  return GeoPolygon;
}();
/**
* Construct a new GeoPolygon instance
* @param {object} input An object with a vertices property
* @param {point[]} [input.vertices=[]] Vertices are represented as an array of points.
* @returns {GeoPolygon} GeoPolygon instance
* @private
*/


function create$7() {
  for (var _len = arguments.length, a = new Array(_len), _key = 0; _key < _len; _key++) {
    a[_key] = arguments[_key];
  }

  return _construct(GeoPolygon, a);
}

function pointsAreNotEqual(p0, p1) {
  return p0.x !== p1.x || p0.y !== p1.y;
}
/**
 * Construct a new GeoPolyline instance
 * @private
 */


var GeoPolyline =
/*#__PURE__*/
function () {
  function GeoPolyline() {
    var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        _ref$points = _ref.points,
        points = _ref$points === void 0 ? [] : _ref$points;

    _classCallCheck$1(this, GeoPolyline);

    this.set({
      points: points
    });
  }

  _createClass$1(GeoPolyline, [{
    key: "set",
    value: function set() {
      var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref2$points = _ref2.points,
          points = _ref2$points === void 0 ? [] : _ref2$points;

      this.type = 'polyline';
      this.segments = [];
      this._points = points.slice();

      if (this._points.length > 1) {
        for (var i = 0, len = this._points.length - 1; i < len; i++) {
          if (pointsAreNotEqual(this._points[i], this._points[i + 1])) {
            this.segments.push({
              x1: this._points[i].x,
              y1: this._points[i].y,
              x2: this._points[i + 1].x,
              y2: this._points[i + 1].y
            });
          }
        }
      }
    }
    /**
     * @param {point} point
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "containsPoint",
    value: function containsPoint(point) {
      return this.segments.some(function (line) {
        return testLinePoint(line, point);
      });
    }
    /**
     * @param {circle} circle
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsCircle",
    value: function intersectsCircle(circle) {
      return this.segments.some(function (line) {
        return testCircleLine(circle, line);
      });
    }
    /**
     * @param {point[]} points - Line start and end point as an array of points
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsLine",
    value: function intersectsLine(points) {
      var testLine = pointsToLine(points);
      return this.segments.some(function (line) {
        return testLineLine(line, testLine);
      });
    }
    /**
     * @param {point[]} points - Rect vertices as an array of points
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsRect",
    value: function intersectsRect(points) {
      var rect = pointsToRect(points);
      return this.segments.some(function (line) {
        return testRectLine(rect, line);
      });
    }
    /**
     * @param {GeoPolygon} polygon
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsPolygon",
    value: function intersectsPolygon(polygon) {
      // This is a unoptimized solution and should be replaced by a more efficient algorithm.
      return this.segments.some(function (line) {
        return testPolygonLine(polygon, line);
      });
    }
    /**
     * Get the points
     * @returns {point[]}
     */

  }, {
    key: "points",
    value: function points() {
      return this._points;
    }
  }]);

  return GeoPolyline;
}();

function create$8() {
  for (var _len = arguments.length, a = new Array(_len), _key = 0; _key < _len; _key++) {
    a[_key] = arguments[_key];
  }

  return _construct(GeoPolyline, a);
}

var reg$2 = registryFactory();
reg$2.add('rect', create$4);
reg$2.add('circle', create$5);
reg$2.add('line', create$6);
reg$2.add('polygon', create$7);
reg$2.add('polyline', create$8);
function create$9(type, input) {
  // eslint-disable-line import/prefer-default-export
  return reg$2.get(type)(input);
}
/**
 * @typedef {object} rect
 * @property {number} x - X-coordinate
 * @property {number} y - Y-coordinate
 * @property {number} width - Width
 * @property {number} height - Height
 */

/**
 * @typedef {object} line
 * @property {number} x1 - Start x-coordinate
 * @property {number} y1 - Start y-coordinate
 * @property {number} x2 - End x-coordinate
 * @property {number} y2 - End y-coordinate
 */

/**
 * @typedef {object} point
 * @property {number} x - X-coordinate
 * @property {number} y - Y-coordinate
 */

/**
 * @typedef {object} circle
 * @property {number} cx - Center x-coordinate
 * @property {number} cy - Center y-coordinate
 * @property {number} r - Circle radius
 */

/**
 * @typedef {object} polygon
 * @property {Array<point>} points - Array of connected points
 */

/**
 * @typedef {object} polyline
 * @property {Array<point>} points - Array of connected points
 */

/**
 * @typedef {object} path
 * @property {string} d - Path definition
 */

/**
 * Construct a new GeometryCollection instance
 * @private
  */

var GeometryCollection =
/*#__PURE__*/
function () {
  function GeometryCollection() {
    var collection = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];

    _classCallCheck$1(this, GeometryCollection);

    this.set(collection);
  }

  _createClass$1(GeometryCollection, [{
    key: "set",
    value: function set() {
      var _this = this;

      var collection = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      this.geometries = [];
      collection.forEach(function (geo) {
        var geoInstance = create$9(geo.type, geo);

        if (geoInstance) {
          _this.geometries.push(geoInstance);
        }
      });
    }
    /**
     * @param {point} p
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "containsPoint",
    value: function containsPoint(p) {
      return this.geometries.some(function (geo) {
        return geo.containsPoint(p);
      });
    }
    /**
     * @param {point[]} points - Line start and end point as an array of points
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsLine",
    value: function intersectsLine(points) {
      return this.geometries.some(function (geo) {
        return geo.intersectsLine(points);
      });
    }
    /**
     * @param {point[]} points - Rect vertices as an array of points
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsRect",
    value: function intersectsRect(points) {
      return this.geometries.some(function (geo) {
        return geo.intersectsRect(points);
      });
    }
    /**
     * @param {circle} c
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsCircle",
    value: function intersectsCircle(c) {
      return this.geometries.some(function (geo) {
        return geo.intersectsCircle(c);
      });
    }
    /**
     * @param {GeoPolygon} polygon
     * @returns {boolean} True if there is an intersection, false otherwise
     */

  }, {
    key: "intersectsPolygon",
    value: function intersectsPolygon(polygon) {
      return this.geometries.some(function (geo) {
        return geo.intersectsPolygon(polygon);
      });
    }
  }]);

  return GeometryCollection;
}();

function create$a() {
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }

  return _construct(GeometryCollection, args);
}

var Matrix =
/*#__PURE__*/
function () {
  /**
   * Creates a matrix with identity values.
   * @private
   */
  function Matrix() {
    _classCallCheck$1(this, Matrix);

    this._elements = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
    this._stack = [];
  }
  /**
   * Creates a new matrix with a copy of the current values.
   */


  _createClass$1(Matrix, [{
    key: "clone",
    value: function clone() {
      var mt = new Matrix();
      return mt.multiply(this);
    }
    /**
    * Sets the matrix values
    * @param {Number[][]} arr A 3x3 array.
    */

  }, {
    key: "set",
    value: function set(arr) {
      this._elements = arr;
      return this;
    }
    /**
    * Saves the current matrix values to a stack.
    */

  }, {
    key: "save",
    value: function save() {
      this._stack.push(this.elements);

      return this;
    }
    /**
    * Sets the current matrix values to the last ones saved on to the stack.
    */

  }, {
    key: "restore",
    value: function restore() {
      if (this._stack.length) {
        this._elements = this._stack.pop(); // TODO - use a copy instead
      }

      return this;
    }
    /**
    * Adds a scalar value to each element in the matrix.
    * @param {Number} value
    */

  }, {
    key: "add",
    value: function add(value) {
      // assume scalar
      var i, j;

      for (i = 0; i < this._elements.length; i++) {
        for (j = 0; j < this._elements[i].length; j++) {
          this._elements[i][j] += value;
        }
      }

      return this;
    }
    /**
    * Translates the current matrix along the x and y axis.
    * @param {Number} x
    * @param {Number} y
    */

  }, {
    key: "translate",
    value: function translate(x, y) {
      this.multiply([[1, 0, x], [0, 1, y], [0, 0, 1]]);
      return this;
    }
    /**
    * Rotates the current matrix.
    * @param {Number} radianAngle Angle in radians.
    */

  }, {
    key: "rotate",
    value: function rotate(radianAngle) {
      var cos = Math.cos(-radianAngle),
          sin = Math.sin(-radianAngle);
      this.multiply([[cos, sin, 0], [-sin, cos, 0], [0, 0, 1]]);
      return this;
    }
    /**
    *
    * If value is a number; multiplies each element in the matrix by the given value.
    * If value is a matrix; multiplies the two matrices.
    * @param {Number|Array|Matrix} value
    */

  }, {
    key: "multiply",
    value: function multiply(value) {
      var i, j, m, k;

      if (value instanceof Matrix) {
        value = value._elements;
      }

      if (Array.isArray(value)) {
        // matrix multiplication
        m = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];

        for (i = 0; i < this._elements.length; i++) {
          // row
          for (j = 0; j < this._elements[i].length; j++) {
            // column
            for (k = 0; k < 3; k++) {
              // row
              m[i][j] += this._elements[i][k] * value[k][j];
            }
          }
        }

        this._elements = m;
      } else {
        // scalar multiplication
        for (i = 0; i < this._elements.length; i++) {
          for (j = 0; j < this._elements[i].length; j++) {
            this._elements[i][j] *= value;
          }
        }
      }

      return this;
    }
    /**
    * Scales the matrix along x and y axis.
    * @param {Number} x The value to scale the matrix with along the x direction
    * @param {Number} [y=x] The value to scale the matrix with along the y direction.
    */

  }, {
    key: "scale",
    value: function scale(x) {
      var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : x;
      // if ( arguments.length < 2 || typeof y === "undefined" ) {
      //  y = x;
      // }
      this.multiply([[x, 0, 0], [0, y, 0], [0, 0, 1]]);
      return this;
    }
    /**
     * Multiples the matrix with the supplied transformation values
     * @param {Number} a Horizontal scaling
     * @param {Number} b Horizontal skewing
     * @param {Number} c Vertical skewing
     * @param {Number} d Vertical scaling
     * @param {Number} e Horizontal moving
     * @param {Number} f Vertical scaling
     */

  }, {
    key: "transform",
    value: function transform(a, b, c, d, e, f) {
      this.multiply([[a, c, e], [b, d, f], [0, 0, 1]]);
      return this;
    }
    /**
    * Gets the value of the determinant.
    * @return {Number}
    */

  }, {
    key: "determinant",
    value: function determinant() {
      var a = this._elements[0][0],
          b = this._elements[0][1],
          c = this._elements[0][2],
          d = this._elements[1][0],
          e = this._elements[1][1],
          f = this._elements[1][2],
          g = this._elements[2][0],
          h = this._elements[2][1],
          i = this._elements[2][2],
          p = 0;
      p = a * e * i + b * f * g + c * d * h - c * e * g - b * d * i - a * f * h;
      return p;
    }
    /**
    * Inverts the matrix.
    */

  }, {
    key: "invert",
    value: function invert() {
      var dt = this.determinant(),
          a = this._elements[0][0],
          b = this._elements[0][1],
          c = this._elements[0][2],
          d = this._elements[1][0],
          e = this._elements[1][1],
          f = this._elements[1][2],
          g = this._elements[2][0],
          h = this._elements[2][1],
          k = this._elements[2][2];
      this._elements = [[e * k - f * h, c * h - b * k, b * f - c * e], [f * g - d * k, a * k - c * g, c * d - a * f], [d * h - e * g, g * b - a * h, a * e - b * d]];
      this.multiply(1 / dt); // TODO - handle when dt === 0 ?

      return this;
    }
    /**
    * Transposes the elements of the matrix.
    */

  }, {
    key: "transpose",
    value: function transpose() {
      var m = Object.create(this._elements); // ?

      this._elements = [[m[0][0], m[1][0], m[2][0]], [m[0][1], m[1][1], m[2][1]], [m[0][2], m[1][2], m[2][2]]];
      return this;
    }
    /**
    * Resets the inner elements of the matrix to identity values.
    */

  }, {
    key: "identity",
    value: function identity() {
      this._elements = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
      return this;
    }
  }, {
    key: "toString",
    value: function toString() {
      return "".concat(this._elements.map(function (r) {
        return r.join('\t');
      }).join('\n'));
    }
  }, {
    key: "isIdentity",
    value: function isIdentity() {
      var m = this._elements;
      return m[0][0] === 1 && m[0][1] === 0 && m[0][2] === 0 && m[1][0] === 0 && m[1][1] === 1 && m[1][2] === 0 && m[2][0] === 0 && m[2][1] === 0 && m[2][2] === 1;
    }
    /**
     * Transforms the given point by this matrix and returns a new point
     */

  }, {
    key: "transformPoint",
    value: function transformPoint(p) {
      var vec = [p.x, p.y, 1],
          i,
          j,
          e = this._elements,
          m = [0, 0, 0];

      for (i = 0; i < this._elements.length; i++) {
        // row
        for (j = 0; j < this._elements[i].length; j++) {
          // column
          m[i] += vec[j] * e[i][j];
        }
      }

      return {
        x: m[0],
        y: m[1]
      };
    }
    /**
     * Transforms the given points by this matrix and returns the new points
     */

  }, {
    key: "transformPoints",
    value: function transformPoints(array) {
      var vec,
          i,
          j,
          k,
          m,
          e = this._elements,
          ret = [];

      for (k = 0; k < array.length; k++) {
        vec = [array[k].x, array[k].y, 1];
        m = [0, 0, 0];

        for (i = 0; i < this._elements.length; i++) {
          // row
          for (j = 0; j < this._elements[i].length; j++) {
            // column
            m[i] += vec[j] * e[i][j];
          }
        }

        ret.push({
          x: m[0],
          y: m[1]
        });
      }

      return ret;
    }
  }, {
    key: "elements",
    get: function get() {
      var m = this._elements;
      return [[m[0][0], m[0][1], m[0][2]], [m[1][0], m[1][1], m[1][2]], [m[2][0], m[2][1], m[2][2]]];
    }
  }]);

  return Matrix;
}();

var transformRegEx = /(translate|scale|rotate|matrix)\(([0-9,.eE+-\s]+)(?:,|\s?)+\)/g;

function parseTransform(transform) {
  var m,
      commands = [];

  while ((m = transformRegEx.exec(transform)) !== null) {
    // eslint-disable-line no-cond-assign
    var argsStr = m[2].trim();
    var args = argsStr.indexOf(',') === -1 ? argsStr.split(' ') : argsStr.split(',');
    commands.push({
      cmd: m[1],
      args: args.filter(function (a) {
        return a.trim().length > 0;
      }).map(function (a) {
        return Number(a);
      })
    });
  }

  return commands;
}

function resolveRotateCmd(matrix, transform) {
  var radians = transform.args[0] * (Math.PI / 180);

  if (transform.args.length > 2) {
    var x = transform.args[1];
    var y = transform.args[2];
    matrix.translate(x, y);
    matrix.rotate(radians);
    matrix.translate(-x, -y);
  } else if (transform.args.length === 1) {
    matrix.rotate(radians);
  }
}

function resolveScaleCmd(matrix, transform) {
  var x = transform.args[0];
  var y = isNaN(transform.args[1]) ? transform.args[0] : transform.args[1];
  matrix.scale(x, y);
}

function resolveTranslateCmd(matrix, transform) {
  var x = transform.args[0];
  var y = isNaN(transform.args[1]) ? 0 : transform.args[1];
  matrix.translate(x, y);
}

function resolveMatrixCmd(matrix, transform) {
  if (transform.args.length >= 6) {
    matrix.transform.apply(matrix, _toConsumableArray$1(transform.args));
  }
}

function resolveTransform(t, matrix) {
  var transforms = parseTransform(t);
  var transform;

  for (var i = 0, len = transforms.length; i < len; i++) {
    transform = transforms[i];

    if (transform.cmd === 'rotate') {
      resolveRotateCmd(matrix, transform);
    } else if (transform.cmd === 'scale') {
      resolveScaleCmd(matrix, transform);
    } else if (transform.cmd === 'matrix') {
      resolveMatrixCmd(matrix, transform);
    } else if (transform.cmd === 'translate') {
      resolveTranslateCmd(matrix, transform);
    }
  }
}

/* eslint-disable no-useless-escape */
var SELECTOR_MAPS = {
  type: /^\w[\w-]+/,
  attr: /^\[\w(?:[\w\._-]+)?(?:[!]?=['\"][\w\s*#_-]*['\"])?\]/,
  universal: /^(\*)/,
  tag: /^\.(\w+)/
};
var FILTERS = {
  type: function type(c, objects) {
    // eslint-disable-line arrow-body-style
    return objects.filter(function (o) {
      var type = o.type;

      if (type) {
        return type.toLowerCase() === c.toLowerCase();
      }

      return false;
    });
  },
  attr: function attr(_attr, operator, value, objects) {
    // eslint-disable-line arrow-body-style
    return objects.filter(function (o) {
      var v = o.attrs[_attr];

      if (!operator) {
        // TODO handle undefined differently for != operator? As display object may very well have a default rendering color
        return typeof v !== 'undefined';
      }

      if (typeof v === 'undefined') {
        return false;
      }

      switch (operator) {
        case '=':
          return value === String(v);

        case '!=':
          return value !== String(v);

        default:
          return false;
      }
    });
  },
  universal: function universal(objects) {
    return objects;
  },
  tag: function tag(selector, objects) {
    // eslint-disable-line arrow-body-style
    return objects.filter(function (o) {
      var tag = o.tag;

      if (tag) {
        return tag.trim().split(/\s+/).indexOf(selector.replace('.', '')) !== -1;
      }

      return false;
    });
  }
};
/**
* Filters out objects of given type and value
* @ignore
* @example
* filter(
*   {type:'type', value:'Circle'},
*   [new Circle(), new Rectangle()]
* )
* // [Circle]
* @param {Object} token
* @param {Array} objects
* @returns {Object[]} Objects that fulfill the type and value
*/

function picasso_esm_filter(token, objects) {
  if (!objects || !objects.length || !token || typeof FILTERS[token.type] !== 'function') {
    return [];
  }

  switch (token.type) {
    case 'type':
      return FILTERS[token.type](token.value, objects);

    case 'attr':
      return FILTERS[token.type](token.attribute, token.operator, token.attributeValue, objects);

    case 'universal':
      return FILTERS[token.type](objects);

    case 'tag':
      return FILTERS[token.type](token.value, objects);

    default:
      return [];
  }
}
/**
* Tokenizes a string into supported selectors
* @ignore
*
* @example
* tokenize("Circle[color='red']")
*
* @param {String} s
*/

function tokenize(s) {
  var groups = [];
  var sub;
  var info;
  var match;
  var validSelector;
  s.split(/\s*,\s*/).forEach(function (group) {
    group = group.trim();
    sub = [];

    var selectorMapsIterator = function selectorMapsIterator(key) {
      match = group.match(SELECTOR_MAPS[key]);

      if (match) {
        validSelector = true;
        group = group.slice(match[0].length);
        info = {
          type: key,
          value: match[0]
        };

        if (key === 'attr') {
          // extract parts of attribute from e.g. [color='red'] => (color, =, red)
          match = match[0].match(/\[(\w[\w\._-]+)?(?:([!]?=)['\"]([\w\s#_-]*)['\"])?\]/);
          info.attribute = match[1];
          info.operator = match[2];
          info.attributeValue = match[3];
        }

        sub.push(info);
      }
    };

    while (group) {
      validSelector = false;
      match = group.match(/^\s*([>+~]|\s)\s*/);

      if (match) {
        validSelector = true;
        sub.push({
          type: ' ',
          value: match[0]
        });
        group = group.slice(match[0].length);
      }

      Object.keys(SELECTOR_MAPS).forEach(selectorMapsIterator);

      if (sub && sub.length && groups.indexOf(sub) < 0) {
        groups.push(sub);
      }

      if (!validSelector) {
        break;
      }
    }
  });
  return groups;
}

function find(s, object) {
  var result = [];
  var groupResults = [];
  var groups;
  var descendants;

  if (object.isBranch) {
    groups = tokenize(s);
    descendants = object.descendants;
    var tokens;

    var _loop = function _loop(gi, glen) {
      tokens = groups[gi];
      var levels = [];
      var filtered = descendants.slice();
      var hasRemainder = false;
      tokens.reverse().forEach(function (token) {
        if (token.type === ' ') {
          levels.push(filtered);
          filtered = descendants.slice();
          hasRemainder = false;
          return;
        }

        filtered = picasso_esm_filter(token, filtered);
        hasRemainder = true;
      });

      if (hasRemainder) {
        levels.push(filtered);
      }

      var selected = levels[0].filter(function (node) {
        var ancestor = node.parent;
        var idx;

        for (var _i = 1; _i < levels.length; _i++) {
          idx = levels[_i].indexOf(ancestor);

          while (ancestor && idx < 0) {
            ancestor = ancestor.parent;
            idx = levels[_i].indexOf(ancestor);
          }

          if (idx < 0) {
            return false;
          }
        }

        return true;
      });
      groupResults.push(selected);
    };

    for (var gi = 0, glen = groups.length; gi < glen; gi++) {
      _loop(gi, glen);
    }

    for (var i = 0, len = groupResults.length; i < len; i++) {
      for (var ni = 0, nlen = groupResults[i].length; ni < nlen; ni++) {
        if (result.indexOf(groupResults[i][ni]) < 0) {
          result.push(groupResults[i][ni]);
        }
      }
    }
  }

  return result || [];
}

var nodeSelector = {
  find: find
};

function appendDpi(points, dpi) {
  for (var i = 0, len = points.length; i < len; i++) {
    points[i].x /= dpi;
    points[i].y /= dpi;
  }
}

function geometryToDef(geometry, dpi, mvm) {
  var type = geometry.type;
  var points = mvm ? mvm.transformPoints(geometry.points()) : geometry.points();
  appendDpi(points, dpi);
  var def = null;

  if (type === 'rect' || type === 'bounds') {
    def = pointsToRect(points);
    def.type = type;
  } else if (type === 'circle') {
    def = pointsToCircle(points, geometry.r);
    def.type = type;
  } else if (type === 'line') {
    def = pointsToLine(points);
    def.type = type;
  } else if (type === 'polygon' || type === 'polyline') {
    var path = pointsToPath(points, type === 'polygon');
    def = {
      type: 'path',
      d: path
    };
  }

  return def;
}
/**
 * @ignore
 * @returns {object} Returns a node definition of the collider
 */


function colliderToShape(node, dpi) {
  if (node.collider) {
    var mvm = node.modelViewMatrix;
    var isCollection = node.colliderType === 'collection';

    if (isCollection) {
      var children = node.collider.geometries.map(function (geometry) {
        return geometryToDef(geometry, dpi, mvm);
      });
      return {
        type: 'container',
        children: children
      };
    }

    return geometryToDef(node.collider, dpi, mvm);
  }

  return null;
}
/**
 * Read-only object representing a node on the scene.
 */


var SceneNode =
/*#__PURE__*/
function () {
  function SceneNode(node) {
    var _this = this;

    _classCallCheck$1(this, SceneNode);

    this._bounds = function () {
      var includeTransform = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;

      var _ref = node.boundingRect ? node.boundingRect(includeTransform) : {
        x: 0,
        y: 0,
        width: 0,
        height: 0
      },
          x = _ref.x,
          y = _ref.y,
          width = _ref.width,
          height = _ref.height;

      return {
        x: x,
        y: y,
        width: width,
        height: height
      };
    };

    this._attrs = node.attrs;
    this._type = node.type;
    this._data = node.data;
    this._dpi = node.stage ? node.stage.dpi : 1;

    this._collider = function () {
      return colliderToShape(node, _this._dpi);
    };

    this._desc = node.desc;
    this._tag = node.tag;

    this._children = function () {
      return node.children.map(function (n) {
        return new SceneNode(n);
      });
    };

    this._parent = function () {
      return node.parent ? new SceneNode(node.parent) : null;
    };

    this._cache = {
      elementBoundingRect: null
    };

    this._getElementBoundingRect = function () {
      if (!_this._cache.elementBoundingRect && _this.element) {
        _this._cache.elementBoundingRect = _this.element.getBoundingClientRect();
      }

      return _this._cache.elementBoundingRect || {
        left: 0,
        top: 0
      };
    };
  }
  /**
   * Get child nodes
   * @type {SceneNode[]}
   */


  _createClass$1(SceneNode, [{
    key: "boundsRelativeTo",

    /**
     * Bounding rectangle of the node, relative a target.
     *
     * If target is an HTMLElement, the bounds are relative to the HTMLElement.
     * Any other target type will return the bounds relative to the viewport of the browser.
     *
     * @param {HTMLElement|any} target
     * @param {boolean} includeTransform - Whether to include any applied transforms on the node
     * @returns {rect}
     * @example
     *
     * node.boundsRelativeTo($('div'));
     * node.boundsRelativeTo('viewport');
     */
    value: function boundsRelativeTo(target) {
      var includeTransform = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

      var type = _typeof(target);

      var bounds = includeTransform ? this.bounds : this.localBounds;

      var selfRect = this._getElementBoundingRect();

      var dx = selfRect.left;
      var dy = selfRect.top;

      if (type === 'object' && target !== null && typeof target.getBoundingClientRect === 'function') {
        var _target$getBoundingCl = target.getBoundingClientRect(),
            _target$getBoundingCl2 = _target$getBoundingCl.left,
            left = _target$getBoundingCl2 === void 0 ? 0 : _target$getBoundingCl2,
            _target$getBoundingCl3 = _target$getBoundingCl.top,
            top = _target$getBoundingCl3 === void 0 ? 0 : _target$getBoundingCl3;

        dx -= left;
        dy -= top;
      }

      bounds.x += dx;
      bounds.y += dy;
      return bounds;
    }
    /**
     * Collider of the node. Transform on the node has been applied to the collider shape, if any, but excluding scaling transform related to devicePixelRatio.
     * Origin is in the top-left corner of the scene element.
     *
     * If node has no collider, null is returned.
     * @type {line|rect|circle|path}
     */

  }, {
    key: "children",
    get: function get() {
      return this._children();
    }
    /**
     * Get parent node
     * @type {SceneNode}
     */

  }, {
    key: "parent",
    get: function get() {
      return this._parent();
    }
    /**
     * Node type
     * @type {string}
     */

  }, {
    key: "type",
    get: function get() {
      return this._type;
    }
    /**
     * Get the associated data
     * @type {any}
     */

  }, {
    key: "data",
    get: function get() {
      return this._data;
    }
    /**
     * Node attributes
     * @type {object}
     */

  }, {
    key: "attrs",
    get: function get() {
      return this._attrs;
    }
    /**
     * Element the scene is attached to
     * @type {HTMLElement}
     * @private
     */

  }, {
    key: "element",
    set: function set(e) {
      this._cache.elementBoundingRect = null;
      this._element = e;
    }
    /**
     * Element the scene is attached to
     * @type {HTMLElement}
     */
    ,
    get: function get() {
      return this._element;
    }
    /**
    * Key of the component this shape belongs to
    * @type {string}
    * @private
    */

  }, {
    key: "key",
    set: function set(k) {
      this._key = k;
    }
    /**
    * Key of the component this shape belongs to
    * @type {string}
    */
    ,
    get: function get() {
      return this._key;
    }
    /**
     * Bounding rectangle of the node. After any transform has been applied, if any, but excluding scaling transform related to devicePixelRatio.
     * Origin is in the top-left corner of the scene element.
     * @type {rect}
     */

  }, {
    key: "bounds",
    get: function get() {
      var bounds = this._bounds();

      bounds.x /= this._dpi;
      bounds.y /= this._dpi;
      bounds.width /= this._dpi;
      bounds.height /= this._dpi;
      return bounds;
    }
    /**
     * Bounding rectangle of the node withing it's local coordinate system.
     * Origin is in the top-left corner of the scene element.
     * @type {rect}
     */

  }, {
    key: "localBounds",
    get: function get() {
      var bounds = this._bounds(false);

      return bounds;
    }
  }, {
    key: "collider",
    get: function get() {
      return this._collider();
    }
    /**
     * Node description
     * @type {object}
     */

  }, {
    key: "desc",
    get: function get() {
      return this._desc;
    }
    /**
     * Node tag
     * @type {string}
     */

  }, {
    key: "tag",
    get: function get() {
      return this._tag;
    }
  }]);

  return SceneNode;
}();

function create$b() {
  for (var _len = arguments.length, a = new Array(_len), _key = 0; _key < _len; _key++) {
    a[_key] = arguments[_key];
  }

  return _construct(SceneNode, a);
}

var Collision =
/*#__PURE__*/
function () {
  function Collision(node) {
    _classCallCheck$1(this, Collision);

    this._node = create$b(node);
    this._parent = null;
    this._input = null;
  }

  _createClass$1(Collision, [{
    key: "node",
    get: function get() {
      return this._node;
    }
  }, {
    key: "parent",
    set: function set(p) {
      this._parent = p;
    },
    get: function get() {
      return this._parent;
    }
  }, {
    key: "input",
    set: function set(i) {
      this._input = i;
    },
    get: function get() {
      return this._input;
    }
  }]);

  return Collision;
}();
function create$c() {
  for (var _len = arguments.length, a = new Array(_len), _key = 0; _key < _len; _key++) {
    a[_key] = arguments[_key];
  }

  return _construct(Collision, a);
}

function appendParentNode(node, collision) {
  var p = node.parent;

  if (p && p.type !== 'stage') {
    collision.parent = create$c(p);
    var pp = p.parent;

    if (pp && pp.type !== 'stage') {
      appendParentNode(pp, collision.parent);
    }
  }
}

function appendInputShape(shape, collisions) {
  for (var i = 0, len = collisions.length; i < len; i++) {
    collisions[i].input = shape;
  }
}

function resolveFrontChildCollision(node, type, input) {
  var num = node.descendants.length;

  for (var i = num - 1; i >= 0; i--) {
    var desc = node.descendants[i];

    if (desc.collider === null) {
      continue;
    }

    if (desc.collider[type](input)) {
      var collision = create$c(desc);
      appendParentNode(desc, collision);
      return collision;
    }
  }

  return null;
}

function resolveGeometryCollision(node, type, input) {
  if (node.collider[type](input)) {
    var c = create$c(node);
    appendParentNode(node, c);
    return c;
  }

  return null;
}

function inverseTransform(node, input) {
  var transformedInput = {};

  if (node.modelViewMatrix) {
    if (Array.isArray(input)) {
      // Rect or Line
      transformedInput = node.inverseModelViewMatrix.transformPoints(input);
    } else if (!isNaN(input.r)) {
      // Circle
      var p = {
        x: input.cx,
        y: input.cy
      };

      var _node$inverseModelVie = node.inverseModelViewMatrix.transformPoint(p);

      transformedInput.cx = _node$inverseModelVie.x;
      transformedInput.cy = _node$inverseModelVie.y;
      transformedInput.r = input.r;
    } else if (Array.isArray(input.vertices)) {
      // Polygon
      transformedInput.vertices = node.inverseModelViewMatrix.transformPoints(input.vertices);
    } else {
      // Point
      transformedInput = node.inverseModelViewMatrix.transformPoint(input);
    }
  } else {
    transformedInput = input;
  }

  if (Array.isArray(transformedInput.vertices)) {
    transformedInput = create$7(transformedInput); // TODO Shouldn't have to do this here, currently its beacause a collision algorithm optimization, i.e. caching of polygon bounds
  }

  return transformedInput;
}

function resolveCollision(node, intersectionType, input) {
  if (node.colliderType === null) {
    return null;
  }

  var transformedInput = inverseTransform(node, input);

  if (node.colliderType === 'frontChild') {
    return resolveFrontChildCollision(node, intersectionType, transformedInput);
  }

  return resolveGeometryCollision(node, intersectionType, transformedInput);
}

function findAllCollisions(nodes, intersectionType, ary, input) {
  var num = nodes.length;

  for (var i = 0; i < num; i++) {
    var node = nodes[i];
    var collision = resolveCollision(node, intersectionType, input);

    if (collision) {
      ary.push(collision);
    } // Only traverse children if no match is found on parent and it doesnt have any custom collider


    if (node.children && !collision && !node.collider) {
      findAllCollisions(node.children, intersectionType, ary, input);
    }
  }
}

function hasCollision(nodes, intersectionType, input) {
  var num = nodes.length;

  for (var i = 0; i < num; i++) {
    var node = nodes[i];
    var collision = resolveCollision(node, intersectionType, input);

    if (collision !== null) {
      return true;
    }

    if (node.children && !node.collider) {
      return hasCollision(node.children, intersectionType, input);
    }
  }

  return false;
}

function resolveShape(shape) {
  var ratio = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  var type = getShapeType(shape);
  var _shape = {};

  switch (type) {
    case 'circle':
      _shape.cx = shape.cx * ratio;
      _shape.cy = shape.cy * ratio;
      _shape.r = shape.r;
      return ['intersectsCircle', _shape];

    case 'rect':
      _shape = rectToPoints(shape).map(function (p) {
        return scalarMultiply(p, ratio);
      });
      return ['intersectsRect', _shape];

    case 'line':
      _shape = lineToPoints(shape).map(function (p) {
        return scalarMultiply(p, ratio);
      });
      return ['intersectsLine', _shape];

    case 'point':
      _shape = scalarMultiply(shape, ratio);
      return ['containsPoint', _shape];

    case 'polygon':
      _shape.vertices = shape.vertices.map(function (vertex) {
        return scalarMultiply(vertex, ratio);
      });
      return ['intersectsPolygon', _shape];

    default:
      return [];
  }
}

function resolveCollionsOnNode(node, shape) {
  var _resolveShape = resolveShape(shape, node.dpi),
      _resolveShape2 = picasso_esm_slicedToArray(_resolveShape, 2),
      intersectionType = _resolveShape2[0],
      _shape = _resolveShape2[1];

  var collisions = [];

  if (intersectionType) {
    findAllCollisions([node], intersectionType, collisions, _shape);
    appendInputShape(shape, collisions);
  }

  return collisions;
}
function hasCollisionOnNode(node, shape) {
  var _resolveShape3 = resolveShape(shape, node.dpi),
      _resolveShape4 = picasso_esm_slicedToArray(_resolveShape3, 2),
      intersectionType = _resolveShape4[0],
      _shape = _resolveShape4[1];

  return hasCollision([node], intersectionType, _shape);
}

/**
 * @typedef {object} node-def
 * @property {string} type
 * @property {string|gradient-def|pattern-def} [fill] - {@link https://www.w3.org/TR/fill-stroke-3/#fill-shorthand}
 * @property {string|gradient-def|pattern-def} [stroke] - {@link https://www.w3.org/TR/fill-stroke-3/#propdef-stroke}
 * @property {number} [strokeWidth] - {@link https://www.w3.org/TR/fill-stroke-3/#propdef-stroke-width}
 * @property {string|number[]} [strokeDasharray] - {@link https://www.w3.org/TR/fill-stroke-3/#propdef-stroke-dasharray}
 * @property {number} [opacity] - {@link https://www.w3.org/TR/css-color-4/#propdef-opacity}
 * @property {string} [transform] - {@link https://www.w3.org/TR/SVG/coords.html#TransformAttribute}
 * @property {object} [data] - Data object, may contain any properties
 * @property {object} [desc] - Meta-data object, may contain any properties
 * @property {string} [tag] - White-space seperated list of tags
 * @property {string} [id] - Unique identifier of the node
 * @property {object} [collider]
 */

var DisplayObject =
/*#__PURE__*/
function (_Node) {
  picasso_esm_inherits(DisplayObject, _Node);

  function DisplayObject(type) {
    var _this;

    _classCallCheck$1(this, DisplayObject);

    _this = picasso_esm_possibleConstructorReturn(this, _getPrototypeOf(DisplayObject).call(this, type));
    _this._stage = null;
    _this._collider = {
      type: null,
      definition: null,
      fn: null
    };
    _this._attrs = {};
    _this._node = null;
    return _this;
  }

  _createClass$1(DisplayObject, [{
    key: "set",
    value: function set() {
      var v = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      this.node = v;
      var data = v.data,
          desc = v.desc,
          tag = v.tag,
          strokeReference = v.strokeReference,
          fillReference = v.fillReference;
      assignMappedAttribute(this.attrs, v);

      if (typeof data !== 'undefined') {
        this.data = data;
      }

      if (_typeof(desc) === 'object') {
        this.desc = extend(true, {}, desc);
      }

      if (typeof tag === 'string') {
        this.tag = tag;
      }

      if (typeof strokeReference === 'string') {
        this.strokeReference = strokeReference;
      }

      if (typeof fillReference === 'string') {
        this.fillReference = fillReference;
      }
    }
  }, {
    key: "findShapes",
    value: function findShapes(selector) {
      return nodeSelector.find(selector, this).map(function (node) {
        return create$b(node);
      });
    }
  }, {
    key: "getItemsFrom",
    value: function getItemsFrom(shape) {
      return resolveCollionsOnNode(this, shape);
    }
  }, {
    key: "containsPoint",
    value: function containsPoint(p) {
      return hasCollisionOnNode(this, p);
    }
  }, {
    key: "intersectsLine",
    value: function intersectsLine(line) {
      return hasCollisionOnNode(this, line);
    }
  }, {
    key: "intersectsRect",
    value: function intersectsRect(rect) {
      return hasCollisionOnNode(this, rect);
    }
  }, {
    key: "intersectsCircle",
    value: function intersectsCircle(circle) {
      return hasCollisionOnNode(this, circle);
    }
  }, {
    key: "intersectsPolygon",
    value: function intersectsPolygon(polygon) {
      return hasCollisionOnNode(this, polygon);
    }
  }, {
    key: "resolveLocalTransform",
    value: function resolveLocalTransform() {
      var m = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Matrix();

      if (typeof this.attrs.transform !== 'undefined') {
        resolveTransform(this.attrs.transform, m);
      }

      this.modelViewMatrix = m.clone();
    }
  }, {
    key: "resolveGlobalTransform",
    value: function resolveGlobalTransform() {
      var m = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Matrix();
      var a = this.ancestors;

      if (a.length > 0) {
        for (var i = a.length - 1; i >= 0; i--) {
          a[i].resolveLocalTransform(m);
          m = a[i].modelViewMatrix;
        }
      }

      this.resolveLocalTransform(m);
    }
    /**
     * Returns the value of attribute a.
     * @private
     * @param a
     * @returns {*} The value of attribute a.
     */

  }, {
    key: "attr",
    value: function attr(a) {
      return this.attrs[a];
    }
  }, {
    key: "equals",
    value: function equals(d) {
      var attrs = this.attrs;
      var attrKeys = Object.keys(attrs);
      var dAttrs = d.attrs;
      var dAttrKeys = Object.keys(dAttrs);

      if (attrKeys.length !== dAttrKeys.length) {
        return false;
      }

      for (var i = 0; i < attrKeys.length; i++) {
        var key = attrKeys[i];

        if (!Object.hasOwnProperty.call(dAttrs, key)) {
          return false;
        }

        if (attrs[key] !== dAttrs[key]) {
          return false;
        }
      }

      return picasso_esm_get(_getPrototypeOf(DisplayObject.prototype), "equals", this).call(this, d);
    }
  }, {
    key: "toJSON",
    value: function toJSON() {
      var json = picasso_esm_get(_getPrototypeOf(DisplayObject.prototype), "toJSON", this).call(this);

      json.attrs = this.attrs;
      return json;
    }
  }, {
    key: "attrs",
    get: function get() {
      return this._attrs;
    }
  }, {
    key: "stage",
    get: function get() {
      if (this._parent && !this._stage) {
        // lazy evaluation
        this._stage = this._parent.stage;
      } else if (!this._parent && this._stage !== this) {
        this._stage = null;
      }

      return this._stage;
    }
  }, {
    key: "modelViewMatrix",
    set: function set(m) {
      this._mvm = m;
      this._imvm = null;
    },
    get: function get() {
      return this._mvm;
    }
  }, {
    key: "inverseModelViewMatrix",
    get: function get() {
      this._imvm = this._imvm ? this._imvm : this._mvm.clone().invert();
      return this._imvm;
    }
  }, {
    key: "node",
    set: function set(n) {
      this._node = n;
    },
    get: function get() {
      return this._node;
    }
  }, {
    key: "collider",
    set: function set(definition) {
      var type = Array.isArray(definition) ? 'collection' : definition && definition.type;

      if (typeof type !== 'string') {
        // Non string type definition resets the collider
        this._collider.type = null;
        this._collider.definition = null;
        this._collider.fn = null;
        return;
      } // Check if a collider of the same type is already defined, if so, do an update


      if (this._collider !== null && this._collider.type === type && this._collider.fn !== null) {
        this._collider.fn.set(definition);

        this._collider.definition = definition;
        return;
      } // Store the definition so that it can be lazy evaluated


      this._collider.type = type;
      this._collider.definition = definition;
    },
    get: function get() {
      // Resolve geometry function from cache
      if (this._collider.fn !== null) {
        return this._collider.fn;
      } // Resolve geometry function and store it in cache


      switch (this._collider.type) {
        case 'collection':
          this._collider.fn = create$a(this._collider.definition);
          break;

        case 'frontChild':
          // TODO Deprecate
          // Front child is not resolved by a function on this node, but instead on one of its child nodes
          return true;

        case 'bounds':
          this._collider.fn = create$9('rect', this.boundingRect());
          break;

        case 'line':
        case 'rect':
        case 'circle':
        case 'polygon':
        case 'polyline':
          this._collider.fn = create$9(this._collider.type, this._collider.definition);
          break;

        default:
          return null;
      }

      return this._collider.fn;
    }
  }, {
    key: "colliderType",
    get: function get() {
      return this._collider.type;
    }
  }]);

  return DisplayObject;
}(Node);

var NodeContainer =
/*#__PURE__*/
function (_Node) {
  picasso_esm_inherits(NodeContainer, _Node);

  function NodeContainer() {
    _classCallCheck$1(this, NodeContainer);

    return picasso_esm_possibleConstructorReturn(this, _getPrototypeOf(NodeContainer).apply(this, arguments));
  }

  _createClass$1(NodeContainer, [{
    key: "addChild",
    value: function addChild(c) {
      if (!c || !(c instanceof Node)) {
        throw new TypeError("Expecting a Node as argument, but got ".concat(c));
      }

      if (c === this) {
        throw new Error('Can not add itself as child!');
      }

      if (c._children && c._children.length && this.ancestors.indexOf(c) >= 0) {
        throw new Error('Can not add an ancestor as child!');
      }

      if (c._parent && c._parent !== this) {
        c._parent.removeChild(c);
      }

      this._children.push(c);

      c._parent = this;
      c._ancestors = null;
      return this;
    }
  }, {
    key: "addChildren",
    value: function addChildren(children) {
      var i,
          num = children ? children.length : 0;

      for (i = 0; i < num; i++) {
        this.addChild(children[i]);
      }

      return this;
    }
    /**
     * Removes given child node from this node.
     * @private
     * @param {Node} c
     * @returns {Node} This object, for chaining purposes.
     */

  }, {
    key: "removeChild",
    value: function removeChild(c) {
      var indx = this._children.indexOf(c);

      if (indx >= 0) {
        this._children.splice(indx, 1);

        c._parent = null;
        c._ancestors = null;
      }

      return this;
    }
  }, {
    key: "removeChildren",
    value: function removeChildren(children) {
      var i, num;

      if (!this._children) {
        return this;
      }

      if (children) {
        num = children.length;

        for (i = 0; i < num; i++) {
          this.removeChild(children[i]);
        }
      } else {
        while (this._children.length) {
          this.removeChild(this._children[0]);
        }
      }

      return this;
    }
  }]);

  return NodeContainer;
}(Node);

/**
 * @extends node-def
 * @typedef {object} node--container-def
 * @property {node-def[]} children - Array of child nodes
 */

var NC = NodeContainer.prototype;

var Container =
/*#__PURE__*/
function (_DisplayObject) {
  picasso_esm_inherits(Container, _DisplayObject);

  function Container() {
    var _this;

    var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

    _classCallCheck$1(this, Container);

    var _s$type = s.type,
        type = _s$type === void 0 ? 'container' : _s$type;
    _this = picasso_esm_possibleConstructorReturn(this, _getPrototypeOf(Container).call(this, type));

    _this.set(s);

    return _this;
  }

  _createClass$1(Container, [{
    key: "set",
    value: function set() {
      var v = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      picasso_esm_get(_getPrototypeOf(Container.prototype), "set", this).call(this, v);

      var collider = v.collider;
      var opts = extend({
        type: null
      }, collider);
      this.collider = opts;
      this.__boundingRect = {
        true: null,
        false: null
      };
      this.__bounds = {
        true: null,
        false: null
      };
    }
  }, {
    key: "appendChildRect",
    value: function appendChildRect(child, includeTransform) {
      if (typeof child.bounds !== 'undefined') {
        var rect = this.__boundingRect[includeTransform] || {};

        var _child$bounds = child.bounds(includeTransform),
            _child$bounds2 = picasso_esm_slicedToArray(_child$bounds, 3),
            p0 = _child$bounds2[0],
            p2 = _child$bounds2[2];

        var xMin = p0.x,
            yMin = p0.y;
        var xMax = p2.x,
            yMax = p2.y;

        var _xMax = isNaN(rect.width) ? xMax : Math.max(xMax, rect.width + rect.x);

        var _yMax = isNaN(rect.height) ? yMax : Math.max(yMax, rect.height + rect.y);

        rect.x = isNaN(rect.x) ? xMin : Math.min(xMin, rect.x);
        rect.y = isNaN(rect.y) ? yMin : Math.min(yMin, rect.y);
        rect.width = _xMax - rect.x;
        rect.height = _yMax - rect.y;
        this.__boundingRect[includeTransform] = rect;
      }
    }
  }, {
    key: "boundingRect",
    value: function boundingRect() {
      var includeTransform = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (this.__boundingRect[includeTransform] !== null) {
        return this.__boundingRect[includeTransform];
      }

      var num = this.children.length;

      for (var i = 0; i < num; i++) {
        this.appendChildRect(this.children[i], includeTransform);
      }

      this.__boundingRect[includeTransform] = extend({
        x: 0,
        y: 0,
        width: 0,
        height: 0
      }, this.__boundingRect[includeTransform]);
      return this.__boundingRect[includeTransform];
    }
  }, {
    key: "bounds",
    value: function bounds() {
      var includeTransform = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (this.__bounds[includeTransform] !== null) {
        return this.__bounds[includeTransform];
      }

      var rect = this.boundingRect(includeTransform);
      this.__bounds[includeTransform] = [{
        x: rect.x,
        y: rect.y
      }, {
        x: rect.x + rect.width,
        y: rect.y
      }, {
        x: rect.x + rect.width,
        y: rect.y + rect.height
      }, {
        x: rect.x,
        y: rect.y + rect.height
      }];
      return this.__bounds[includeTransform];
    }
  }, {
    key: "addChild",
    value: function addChild(c) {
      var r = NC.addChild.call(this, c);

      if (this._collider && this._collider.type === 'bounds') {
        this.appendChildRect(c, true);
        var opts = extend({
          type: 'bounds',
          x: 0,
          y: 0,
          width: 0,
          height: 0
        }, this.__boundingRect.true);
        this.collider = opts;
      }

      return r;
    }
  }, {
    key: "addChildren",
    value: function addChildren(children) {
      var r = NC.addChildren.call(this, children);
      var num = children.length;

      if (this._collider && this._collider.type === 'bounds' && num > 0) {
        for (var i = 0; i < num; i++) {
          this.appendChildRect(children[i], true);
        }

        var opts = extend({
          type: 'bounds',
          x: 0,
          y: 0,
          width: 0,
          height: 0
        }, this.__boundingRect.true);
        this.collider = opts;
      }

      return r;
    }
  }, {
    key: "removeChild",
    value: function removeChild(c) {
      c._stage = null;
      var desc = c.descendants,
          num = desc ? desc.length : 0,
          i; // remove reference to stage from all descendants

      for (i = 0; i < num; i++) {
        desc[i]._stage = null;
      }

      NC.removeChild.call(this, c);

      if (this._collider && this._collider.type === 'bounds') {
        this.__boundingRect = {
          true: null,
          false: null
        };
        this.__bounds = {
          true: null,
          false: null
        };
        var opts = extend(this.boundingRect(true), {
          type: 'bounds'
        });
        this.collider = opts;
      }

      return this;
    }
  }, {
    key: "removeChildren",
    value: function removeChildren(children) {
      NC.removeChildren.call(this, children);

      if (this._collider && this._collider.type === 'bounds') {
        this.__boundingRect = {
          true: null,
          false: null
        };
        this.__bounds = {
          true: null,
          false: null
        };
        var opts = extend(this.boundingRect(true), {
          type: 'bounds'
        });
        this.collider = opts;
      }

      return this;
    }
  }]);

  return Container;
}(DisplayObject);
function create$d() {
  for (var _len = arguments.length, s = new Array(_len), _key = 0; _key < _len; _key++) {
    s[_key] = arguments[_key];
  }

  return _construct(Container, s);
}

var Stage =
/*#__PURE__*/
function (_Container) {
  picasso_esm_inherits(Stage, _Container);

  function Stage(dpi) {
    var _this;

    _classCallCheck$1(this, Stage);

    _this = picasso_esm_possibleConstructorReturn(this, _getPrototypeOf(Stage).call(this, 'stage'));
    _this._stage = picasso_esm_assertThisInitialized(_this);
    _this._dpiRatio = dpi || 1;
    return _this;
  }

  _createClass$1(Stage, [{
    key: "dpi",
    get: function get() {
      return this._dpiRatio;
    }
  }]);

  return Stage;
}(Container);
function create$e() {
  for (var _len = arguments.length, a = new Array(_len), _key = 0; _key < _len; _key++) {
    a[_key] = arguments[_key];
  }

  return _construct(Stage, a);
}

/**
 * @typedef {object} gradient-def
 * @property {string} type
 * @property {object[]} stops
 * @property {string} [stops[].type=linearGradient] - radialGradient|linearGradient
 * @property {string} stops[].color - {@link https://www.w3.org/TR/SVG/types.html#DataTypeColor}
 * @property {string} [stops[].opacity=1] - {@link https://www.w3.org/TR/css-color-4/#propdef-opacity}
 * @property {number} stops[].offset - {@link https://www.w3.org/TR/SVG/pservers.html#StopElementOffsetAttribute}
 * @property {number} [degree] - Gradient rotation angle
 */

/**
 * @typedef {object} node--gradient-item-def
 * @property {string} id - Gradient identifier
 * @property {number} x1 - {@link https://www.w3.org/TR/SVG/pservers.html#LinearGradientElementX1Attribute}
 * @property {number} y1 - {@link https://www.w3.org/TR/SVG/pservers.html#LinearGradientElementY1Attribute}
 * @property {number} x2 - {@link https://www.w3.org/TR/SVG/pservers.html#LinearGradientElementX2Attribute}
 * @property {number} y2 - {@link https://www.w3.org/TR/SVG/pservers.html#LinearGradientElementY2Attribute}
 * @property {number} offset - {@link https://www.w3.org/TR/SVG/pservers.html#StopElementOffsetAttribute}
 * @property {object} style - {@link https://www.w3.org/TR/SVG/styling.html#StyleAttribute}
 */

var NC$1 = NodeContainer.prototype;
var allowedAttrs = ['x1', 'x2', 'y1', 'y2', 'id', 'offset', 'style'];

var GradientItem =
/*#__PURE__*/
function (_DisplayObject) {
  picasso_esm_inherits(GradientItem, _DisplayObject);

  function GradientItem() {
    var _this;

    var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

    _classCallCheck$1(this, GradientItem);

    var _s$type = s.type,
        type = _s$type === void 0 ? 'container' : _s$type;
    _this = picasso_esm_possibleConstructorReturn(this, _getPrototypeOf(GradientItem).call(this, type));

    _this.set(s);

    _this._boundingRect = {};
    return _this;
  }

  _createClass$1(GradientItem, [{
    key: "set",
    value: function set() {
      var v = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      picasso_esm_get(_getPrototypeOf(GradientItem.prototype), "set", this).call(this, v);

      var attrs = this.attrs;
      var attrKey = '';

      for (var i = 0, len = allowedAttrs.length; i !== len; i++) {
        attrKey = allowedAttrs[i];

        if (typeof v[attrKey] !== 'undefined') {
          attrs[attrKey] = v[attrKey];
        }
      }
    }
  }, {
    key: "addChild",
    value: function addChild(c) {
      var r = NC$1.addChild.call(this, c);
      return r;
    }
  }, {
    key: "addChildren",
    value: function addChildren(children) {
      var r = NC$1.addChildren.call(this, children);
      return r;
    }
  }, {
    key: "removeChild",
    value: function removeChild(c) {
      c._stage = null;
      var desc = c.descendants,
          num = desc ? desc.length : 0,
          i; // remove reference to stage from all descendants

      for (i = 0; i < num; i++) {
        desc[i]._stage = null;
      }

      NC$1.removeChild.call(this, c);
      return this;
    }
  }, {
    key: "removeChildren",
    value: function removeChildren(children) {
      NC$1.removeChildren.call(this, children);
      return this;
    }
  }]);

  return GradientItem;
}(DisplayObject);
function create$f() {
  for (var _len = arguments.length, s = new Array(_len), _key = 0; _key < _len; _key++) {
    s[_key] = arguments[_key];
  }

  return _construct(GradientItem, s);
}

/**
 * @experimental
 * @typedef {object} pattern-def
 * @property {'pattern'} type
 * @property {string} fill
 * @property {number} width
 * @property {number} height
 * @property {object[]} shapes
 * @example
 * Stripe pattern
 * ```js
 * {
 *   type: 'pattern',
 *   fill: 'red',
 *   width: 4,
 *   height: 4,
 *   shapes: [
 *     { type: 'rect', x: 3, y: 0, width: 1, height: 1 },
 *     { type: 'rect', x: 2, y: 1, width: 1, height: 1 },
 *     { type: 'rect', x: 1, y: 2, width: 1, height: 1 },
 *     { type: 'rect', x: 0, y: 3, width: 1, height: 1 },
 *   ]
 * }
 * ```
 */

var NC$2 = NodeContainer.prototype;
var allowedAttrs$1 = ['patternUnits', 'x', 'y', 'width', 'height', 'id'];

var PatternItem =
/*#__PURE__*/
function (_DisplayObject) {
  picasso_esm_inherits(PatternItem, _DisplayObject);

  function PatternItem() {
    var _this;

    var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

    _classCallCheck$1(this, PatternItem);

    var _s$type = s.type,
        type = _s$type === void 0 ? 'container' : _s$type;
    _this = picasso_esm_possibleConstructorReturn(this, _getPrototypeOf(PatternItem).call(this, type));

    _this.set(s);

    _this._boundingRect = {};
    return _this;
  }

  _createClass$1(PatternItem, [{
    key: "set",
    value: function set() {
      var v = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      picasso_esm_get(_getPrototypeOf(PatternItem.prototype), "set", this).call(this, v);

      var attrs = this.attrs;
      var attrKey = '';

      for (var i = 0, len = allowedAttrs$1.length; i !== len; i++) {
        attrKey = allowedAttrs$1[i];

        if (typeof v[attrKey] !== 'undefined') {
          attrs[attrKey] = v[attrKey];
        }
      }
    }
  }, {
    key: "addChild",
    value: function addChild(c) {
      var r = NC$2.addChild.call(this, c);
      return r;
    }
  }, {
    key: "addChildren",
    value: function addChildren(children) {
      var r = NC$2.addChildren.call(this, children);
      return r;
    }
  }, {
    key: "removeChild",
    value: function removeChild(c) {
      c._stage = null;
      var desc = c.descendants,
          num = desc ? desc.length : 0,
          i; // remove reference to stage from all descendants

      for (i = 0; i < num; i++) {
        desc[i]._stage = null;
      }

      NC$2.removeChild.call(this, c);
      return this;
    }
  }, {
    key: "removeChildren",
    value: function removeChildren(children) {
      NC$2.removeChildren.call(this, children);
      return this;
    }
  }]);

  return PatternItem;
}(DisplayObject);
function create$g() {
  for (var _len = arguments.length, s = new Array(_len), _key = 0; _key < _len; _key++) {
    s[_key] = arguments[_key];
  }

  return _construct(PatternItem, s);
}

/**
 * @extends node-def
 * @typedef {object} node--rect-def
 * @property {number} x - {@link https://www.w3.org/TR/SVG/shapes.html#RectElementXAttribute}
 * @property {number} y - {@link https://www.w3.org/TR/SVG/shapes.html#RectElementYAttribute}
 * @property {number} width - {@link https://www.w3.org/TR/SVG/shapes.html#RectElementWidthAttribute}
 * @property {number} height- {@link https://www.w3.org/TR/SVG/shapes.html#RectElementHeightAttribute}
 */

var Rect =
/*#__PURE__*/
function (_DisplayObject) {
  picasso_esm_inherits(Rect, _DisplayObject);

  function Rect() {
    var _this2;

    var _this;

    _classCallCheck$1(this, Rect);

    _this = picasso_esm_possibleConstructorReturn(this, _getPrototypeOf(Rect).call(this, 'rect'));

    (_this2 = _this).set.apply(_this2, arguments);

    return _this;
  }

  _createClass$1(Rect, [{
    key: "set",
    value: function set() {
      var v = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var _v$x = v.x,
          x = _v$x === void 0 ? 0 : _v$x,
          _v$y = v.y,
          y = _v$y === void 0 ? 0 : _v$y,
          _v$width = v.width,
          width = _v$width === void 0 ? 0 : _v$width,
          _v$height = v.height,
          height = _v$height === void 0 ? 0 : _v$height,
          _v$rx = v.rx,
          rx = _v$rx === void 0 ? 0 : _v$rx,
          _v$ry = v.ry,
          ry = _v$ry === void 0 ? 0 : _v$ry,
          collider = v.collider;
      var opts = extend({
        type: 'rect',
        x: x,
        y: y,
        width: width,
        height: height
      }, collider);

      picasso_esm_get(_getPrototypeOf(Rect.prototype), "set", this).call(this, v);

      if (width >= 0) {
        this.attrs.x = x;
        this.attrs.width = width;
      } else {
        this.attrs.x = x + width;
        this.attrs.width = -width;
      }

      if (height >= 0) {
        this.attrs.y = y;
        this.attrs.height = height;
      } else {
        this.attrs.y = y + height;
        this.attrs.height = -height;
      }

      if (rx > 0) {
        this.attrs.rx = rx;
      }

      if (ry > 0) {
        this.attrs.ry = ry;
      }

      this.collider = opts;
      this.__boundingRect = {
        true: null,
        false: null
      };
      this.__bounds = {
        true: null,
        false: null
      };
    }
  }, {
    key: "boundingRect",
    value: function boundingRect() {
      var includeTransform = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (this.__boundingRect[includeTransform] !== null) {
        return this.__boundingRect[includeTransform];
      }

      var p = rectToPoints(this.attrs);
      var pt = includeTransform && this.modelViewMatrix ? this.modelViewMatrix.transformPoints(p) : p;

      var _getMinMax = getMinMax(pt),
          _getMinMax2 = picasso_esm_slicedToArray(_getMinMax, 4),
          xMin = _getMinMax2[0],
          yMin = _getMinMax2[1],
          xMax = _getMinMax2[2],
          yMax = _getMinMax2[3];

      this.__boundingRect[includeTransform] = {
        x: xMin,
        y: yMin,
        width: xMax - xMin,
        height: yMax - yMin
      };
      return this.__boundingRect[includeTransform];
    }
  }, {
    key: "bounds",
    value: function bounds() {
      var includeTransform = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (this.__bounds[includeTransform] !== null) {
        return this.__bounds[includeTransform];
      }

      var rect = this.boundingRect(includeTransform);
      this.__bounds[includeTransform] = [{
        x: rect.x,
        y: rect.y
      }, {
        x: rect.x + rect.width,
        y: rect.y
      }, {
        x: rect.x + rect.width,
        y: rect.y + rect.height
      }, {
        x: rect.x,
        y: rect.y + rect.height
      }];
      return this.__bounds[includeTransform];
    }
  }]);

  return Rect;
}(DisplayObject);
function create$h() {
  for (var _len = arguments.length, s = new Array(_len), _key = 0; _key < _len; _key++) {
    s[_key] = arguments[_key];
  }

  return _construct(Rect, s);
}

/**
 * @extends node-def
 * @typedef {object} node--circle-def
 * @property {number} cx - {@link https://www.w3.org/TR/SVG/shapes.html#CircleElementCXAttribute}
 * @property {number} cy - {@link https://www.w3.org/TR/SVG/shapes.html#CircleElementCYAttribute}
 * @property {number} r - {@link https://www.w3.org/TR/SVG/shapes.html#CircleElementRAttribute}
 */

var Circle =
/*#__PURE__*/
function (_DisplayObject) {
  picasso_esm_inherits(Circle, _DisplayObject);

  function Circle() {
    var _this2;

    var _this;

    _classCallCheck$1(this, Circle);

    _this = picasso_esm_possibleConstructorReturn(this, _getPrototypeOf(Circle).call(this, 'circle'));

    (_this2 = _this).set.apply(_this2, arguments);

    return _this;
  }

  _createClass$1(Circle, [{
    key: "set",
    value: function set() {
      var v = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var _v$cx = v.cx,
          cx = _v$cx === void 0 ? 0 : _v$cx,
          _v$cy = v.cy,
          cy = _v$cy === void 0 ? 0 : _v$cy,
          _v$r = v.r,
          r = _v$r === void 0 ? 0 : _v$r,
          collider = v.collider;
      var opts = extend({
        type: 'circle',
        cx: cx,
        cy: cy,
        r: r
      }, collider);

      picasso_esm_get(_getPrototypeOf(Circle.prototype), "set", this).call(this, v);

      this.attrs.cx = cx;
      this.attrs.cy = cy;
      this.attrs.r = r;
      this.collider = opts;
      this.__boundingRect = {
        true: null,
        false: null
      };
      this.__bounds = {
        true: null,
        false: null
      };
    }
  }, {
    key: "boundingRect",
    value: function boundingRect() {
      var includeTransform = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (this.__boundingRect[includeTransform] !== null) {
        return this.__boundingRect[includeTransform];
      } // TODO Handle Circle bounds correctly for a circle transformed to an non axis aligned ellipse/circle
      // Current solution only rotate the bounds, giving a larger boundingRect if rotated


      var p = this.bounds(includeTransform);
      this.__boundingRect[includeTransform] = {
        x: p[0].x,
        y: p[0].y,
        width: p[2].x - p[0].x,
        height: p[2].y - p[0].y
      };
      return this.__boundingRect[includeTransform];
    }
  }, {
    key: "bounds",
    value: function bounds() {
      var includeTransform = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (this.__bounds[includeTransform] !== null) {
        return this.__bounds[includeTransform];
      } // TODO Handle Circle bounds correctly for a circle transformed to an non axis aligned ellipse/circle


      var _this$attrs = this.attrs,
          cx = _this$attrs.cx,
          cy = _this$attrs.cy,
          rX = _this$attrs.r,
          rY = _this$attrs.r;
      var x = cx - rX;
      var y = cy - rY;
      var w = rX * 2;
      var h = rY * 2;
      var p = [{
        x: x,
        y: y
      }, {
        x: x + w,
        y: y
      }, {
        x: x + w,
        y: y + h
      }, {
        x: x,
        y: y + h
      }];

      if (includeTransform && this.modelViewMatrix) {
        p = this.modelViewMatrix.transformPoints(p);

        var _getMinMax = getMinMax(p),
            _getMinMax2 = picasso_esm_slicedToArray(_getMinMax, 4),
            xMin = _getMinMax2[0],
            yMin = _getMinMax2[1],
            xMax = _getMinMax2[2],
            yMax = _getMinMax2[3];

        w = xMax - xMin;
        h = yMax - yMin;
        this.__bounds[includeTransform] = [{
          x: xMin,
          y: yMin
        }, {
          x: xMin + w,
          y: yMin
        }, {
          x: xMin + w,
          y: yMin + h
        }, {
          x: xMin,
          y: yMin + h
        }];
      } else {
        this.__bounds[includeTransform] = p;
      }

      return this.__bounds[includeTransform];
    }
  }]);

  return Circle;
}(DisplayObject);
function create$i() {
  for (var _len = arguments.length, s = new Array(_len), _key = 0; _key < _len; _key++) {
    s[_key] = arguments[_key];
  }

  return _construct(Circle, s);
}

/**
 * @extends node-def
 * @typedef {object} node--line-def
 * @property {number} x1 - {@link https://www.w3.org/TR/SVG/shapes.html#LineElementX1Attribute}
 * @property {number} y1 - {@link https://www.w3.org/TR/SVG/shapes.html#LineElementY1Attribute}
 * @property {number} x2 - {@link https://www.w3.org/TR/SVG/shapes.html#LineElementX2Attribute}
 * @property {number} y2 - {@link https://www.w3.org/TR/SVG/shapes.html#LineElementY2Attribute}
 */

var Line =
/*#__PURE__*/
function (_DisplayObject) {
  picasso_esm_inherits(Line, _DisplayObject);

  function Line() {
    var _this2;

    var _this;

    _classCallCheck$1(this, Line);

    _this = picasso_esm_possibleConstructorReturn(this, _getPrototypeOf(Line).call(this, 'line'));

    (_this2 = _this).set.apply(_this2, arguments);

    return _this;
  }

  _createClass$1(Line, [{
    key: "set",
    value: function set() {
      var v = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var _v$x = v.x1,
          x1 = _v$x === void 0 ? 0 : _v$x,
          _v$y = v.y1,
          y1 = _v$y === void 0 ? 0 : _v$y,
          _v$x2 = v.x2,
          x2 = _v$x2 === void 0 ? 0 : _v$x2,
          _v$y2 = v.y2,
          y2 = _v$y2 === void 0 ? 0 : _v$y2,
          collider = v.collider;

      picasso_esm_get(_getPrototypeOf(Line.prototype), "set", this).call(this, v);

      this.attrs.x1 = x1;
      this.attrs.y1 = y1;
      this.attrs.x2 = x2;
      this.attrs.y2 = y2;
      var defaultCollider = {
        type: 'line',
        x1: x1,
        y1: y1,
        x2: x2,
        y2: y2
      };
      this.collider = extend(defaultCollider, collider);
      this.__boundingRect = {
        true: null,
        false: null
      };
      this.__bounds = {
        true: null,
        false: null
      };
    }
  }, {
    key: "boundingRect",
    value: function boundingRect() {
      var includeTransform = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (this.__boundingRect[includeTransform] !== null) {
        return this.__boundingRect[includeTransform];
      }

      var p = lineToPoints(this.attrs);

      if (includeTransform && this.modelViewMatrix) {
        p = this.modelViewMatrix.transformPoints(p);
      }

      var _getMinMax = getMinMax(p),
          _getMinMax2 = picasso_esm_slicedToArray(_getMinMax, 4),
          xMin = _getMinMax2[0],
          yMin = _getMinMax2[1],
          xMax = _getMinMax2[2],
          yMax = _getMinMax2[3];

      var hasSize = xMin !== xMax || yMin !== yMax;
      this.__boundingRect[includeTransform] = {
        x: xMin,
        y: yMin,
        width: hasSize ? Math.max(1, xMax - xMin) : 0,
        height: hasSize ? Math.max(1, yMax - yMin) : 0
      };
      return this.__boundingRect[includeTransform];
    }
  }, {
    key: "bounds",
    value: function bounds() {
      var includeTransform = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (this.__bounds[includeTransform] !== null) {
        return this.__bounds[includeTransform];
      }

      var rect = this.boundingRect(includeTransform);
      this.__bounds[includeTransform] = [{
        x: rect.x,
        y: rect.y
      }, {
        x: rect.x + rect.width,
        y: rect.y
      }, {
        x: rect.x + rect.width,
        y: rect.y + rect.height
      }, {
        x: rect.x,
        y: rect.y + rect.height
      }];
      return this.__bounds[includeTransform];
    }
  }]);

  return Line;
}(DisplayObject);
function create$j() {
  for (var _len = arguments.length, s = new Array(_len), _key = 0; _key < _len; _key++) {
    s[_key] = arguments[_key];
  }

  return _construct(Line, s);
}

var PI_2 = Math.PI / 2;

function lineAngle(p0, p1) {
  var t = Math.atan2(p1.y - p0.y, p1.x - p0.x);
  return t < 0 ? t + Math.PI * 2 : t;
} // TODO Find a more accurate method to find the open and closed points


function rotatePoint$1(p, angle, radius) {
  return {
    x: p.x + Math.cos(angle) * radius,
    y: p.y + Math.sin(angle) * radius
  };
}

function polylineToPolygonCollider(points, radius) {
  var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var open = [];
  var close = []; // TODO handle case if points.length === 2

  if (opts.forceOrientation === 'h') {
    var start = points[0].x < points[1].x ? -1 : 1;
    var end = points[points.length - 1].x > points[points.length - 2].x ? 1 : -1;
    points.unshift({
      x: points[0].x + start,
      y: points[0].y
    });
    points.push({
      x: points[points.length - 1].x + end,
      y: points[points.length - 1].y
    });
  } else if (opts.forceOrientation === 'v') {
    var _start = points[0].y < points[1].y ? -1 : 1;

    var _end = points[points.length - 1].y > points[points.length - 2].y ? 1 : -1;

    points.unshift({
      x: points[0].x,
      y: points[0].y + _start
    });
    points.push({
      x: points[points.length - 1].x,
      y: points[points.length - 1].y + _end
    });
  }

  var len = points.length - 1;

  for (var i = 1; i < len; i++) {
    var prev = points[i - 1];
    var curr = points[i];
    var next = points[i + 1];
    var currToPrev = lineAngle(curr, prev);
    var currToNext = lineAngle(curr, next);
    var openAngle = (currToPrev + currToNext) / 2;
    var closeAngle = openAngle + Math.PI;
    var maxAngle = Math.max(openAngle, closeAngle);
    var minAngle = Math.min(openAngle, closeAngle);
    var openClose = currToPrev > currToNext;

    if (i === 1) {
      var prevToCurr = lineAngle(prev, curr);
      open.push(rotatePoint$1(prev, prevToCurr - PI_2, radius));
      close.unshift(rotatePoint$1(prev, prevToCurr + PI_2, radius));
    }

    var opened = openClose ? maxAngle : minAngle;
    var closed = openClose ? minAngle : maxAngle;
    open.push(rotatePoint$1(curr, opened, radius));
    close.unshift(rotatePoint$1(curr, closed, radius));

    if (i === len - 1) {
      var nextToCurr = lineAngle(next, curr);
      open.push(rotatePoint$1(next, nextToCurr + PI_2, radius));
      close.unshift(rotatePoint$1(next, nextToCurr - PI_2, radius));
    }
  }

  return {
    type: 'polygon',
    vertices: [].concat(open, close)
  };
}

function flatten2d(ary) {
  var newAry = [];
  var a;
  var len = ary.length;

  for (var i = 0; i < len; i++) {
    a = ary[i];

    for (var k = 0; k < a.length; k++) {
      newAry.push(a[k]);
    }
  }

  return newAry;
}

var EPSILON$2 = 1e-12;
/**
 * @extends node-def
 * @typedef {object} node--path-def
 * @property {string} d - {@link https://www.w3.org/TR/SVG/paths.html#DAttribute}
 */

function isClosed(points) {
  if (points.length < 2) {
    return false;
  }

  var p0 = points[0];
  var p1 = points[points.length - 1];
  return Math.abs(p0.x - p1.x) < EPSILON$2 && Math.abs(p0.y - p1.y) < EPSILON$2;
}

var Path$1 =
/*#__PURE__*/
function (_DisplayObject) {
  picasso_esm_inherits(Path, _DisplayObject);

  function Path() {
    var _this2;

    var _this;

    _classCallCheck$1(this, Path);

    _this = picasso_esm_possibleConstructorReturn(this, _getPrototypeOf(Path).call(this, 'path'));

    (_this2 = _this).set.apply(_this2, arguments);

    return _this;
  }

  _createClass$1(Path, [{
    key: "set",
    value: function set() {
      var _this3 = this;

      var v = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      picasso_esm_get(_getPrototypeOf(Path.prototype), "set", this).call(this, v);

      this.segments = [];
      this.points = [];
      this.attrs.d = v.d;

      if (Array.isArray(v.collider) || _typeof(v.collider) === 'object' && typeof v.collider.type !== 'undefined') {
        this.collider = v.collider;
      } else if (v.d) {
        this.segments = pathToPoints(v.d);
        this.segments.forEach(function (segment) {
          if (segment.length <= 1) ; else if (isClosed(segment)) {
            _this3.collider = extend({
              type: 'polygon',
              vertices: segment
            }, v.collider);
          } else if (_typeof(v.collider) === 'object' && v.collider.visual) {
            var size = _this3.attrs['stroke-width'] / 2;
            _this3.collider = polylineToPolygonCollider(segment, size, v.collider);
          } else {
            _this3.collider = extend({
              type: 'polyline',
              points: segment
            }, v.collider);
          }
        });
      }

      this.__boundingRect = {
        true: null,
        false: null
      };
      this.__bounds = {
        true: null,
        false: null
      };
    }
  }, {
    key: "boundingRect",
    value: function boundingRect() {
      var includeTransform = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (this.__boundingRect[includeTransform] !== null) {
        return this.__boundingRect[includeTransform];
      }

      if (!this.points.length) {
        this.segments = this.segments.length ? this.segments : pathToPoints(this.attrs.d);
        this.points = flatten2d(this.segments);
      }

      var pt = includeTransform && this.modelViewMatrix ? this.modelViewMatrix.transformPoints(this.points) : this.points;

      var _getMinMax = getMinMax(pt),
          _getMinMax2 = picasso_esm_slicedToArray(_getMinMax, 4),
          xMin = _getMinMax2[0],
          yMin = _getMinMax2[1],
          xMax = _getMinMax2[2],
          yMax = _getMinMax2[3];

      this.__boundingRect[includeTransform] = {
        x: xMin || 0,
        y: yMin || 0,
        width: xMax - xMin || 0,
        height: yMax - yMin || 0
      };
      return this.__boundingRect[includeTransform];
    }
  }, {
    key: "bounds",
    value: function bounds() {
      var includeTransform = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (this.__bounds[includeTransform] !== null) {
        return this.__bounds[includeTransform];
      }

      var rect = this.boundingRect(includeTransform);
      this.__bounds[includeTransform] = [{
        x: rect.x,
        y: rect.y
      }, {
        x: rect.x + rect.width,
        y: rect.y
      }, {
        x: rect.x + rect.width,
        y: rect.y + rect.height
      }, {
        x: rect.x,
        y: rect.y + rect.height
      }];
      return this.__bounds[includeTransform];
    }
  }]);

  return Path;
}(DisplayObject);
function create$k() {
  for (var _len = arguments.length, s = new Array(_len), _key = 0; _key < _len; _key++) {
    s[_key] = arguments[_key];
  }

  return _construct(Path$1, s);
}

function hasData(_ref) {
  var data = _ref.data,
      _boundingRect = _ref._boundingRect,
      _textBoundsFn = _ref._textBoundsFn;
  return typeof data !== 'undefined' && data !== null && (_boundingRect || _textBoundsFn);
}
/**
 * @extends node-def
 * @typedef {object} node--text-def
 * @property {string} text
 * @property {number} x - {@link https://www.w3.org/TR/SVG/text.html#TextElementXAttribute}
 * @property {number} y - {@link https://www.w3.org/TR/SVG/text.html#TextElementYAttribute}
 * @property {number} [dx] - {@link https://www.w3.org/TR/SVG/text.html#TextElementDXAttribute}
 * @property {number} [dy] - {@link https://www.w3.org/TR/SVG/text.html#TextElementDYAttribute}
 * @property {string} [fontSize] - {@link https://www.w3.org/TR/SVG/text.html#FontPropertiesUsedBySVG}
 * @property {string} [fontFamily] - {@link https://www.w3.org/TR/SVG/text.html#FontPropertiesUsedBySVG}
 * @property {rect} [boundingRect] - Explicitly set the bounding rectangle of the node. Has predence over textBoundsFn
 * @property {function} [textBoundsFn] - Implicitly set the bounding rectangle of the node, the function must return an object with x, y, width and height attributes
 * @property {string} [baseline] - Alias for dominantBaseline
 * @property {string} [dominantBaseline] - {@link https://www.w3.org/TR/SVG/text.html#BaselineAlignmentProperties}
 * @property {string} [anchor] - Alias for textAnchor
 * @property {string} [textAnchor] - {@link https://www.w3.org/TR/SVG/text.html#TextAnchorProperty}
 * @property {string} [wordBreak] - Word-break option
 * @property {number} [maxWidth] - Maximum allowed text width
 * @property {number} [maxHeight] - Maximum allowed text height. If both maxLines and maxHeight are set, the property that results in the fewest number of lines is used
 * @property {number} [maxLines] - Maximum number of lines allowed
 * @property {number} [lineHeight=1.2] - Line height
 */


var Text =
/*#__PURE__*/
function (_DisplayObject) {
  picasso_esm_inherits(Text, _DisplayObject);

  function Text() {
    var _this2;

    var _this;

    _classCallCheck$1(this, Text);

    _this = picasso_esm_possibleConstructorReturn(this, _getPrototypeOf(Text).call(this, 'text'));

    (_this2 = _this).set.apply(_this2, arguments);

    return _this;
  }

  _createClass$1(Text, [{
    key: "set",
    value: function set() {
      var v = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var _v$x = v.x,
          x = _v$x === void 0 ? 0 : _v$x,
          _v$y = v.y,
          y = _v$y === void 0 ? 0 : _v$y,
          _v$dx = v.dx,
          dx = _v$dx === void 0 ? 0 : _v$dx,
          _v$dy = v.dy,
          dy = _v$dy === void 0 ? 0 : _v$dy,
          textBoundsFn = v.textBoundsFn,
          text = v.text,
          title = v.title,
          collider = v.collider,
          boundingRect = v.boundingRect,
          ellipsed = v.ellipsed;

      picasso_esm_get(_getPrototypeOf(Text.prototype), "set", this).call(this, v);

      this.attrs.x = x;
      this.attrs.y = y;
      this.attrs.dx = dx;
      this.attrs.dy = dy;
      this.attrs.text = text;

      if (typeof title !== 'undefined') {
        this.attrs.title = String(title);
      }

      if (_typeof(boundingRect) === 'object') {
        this._textBoundsFn = function () {
          return boundingRect;
        };
      } else if (typeof textBoundsFn === 'function') {
        this._textBoundsFn = textBoundsFn;
      }

      if (typeof ellipsed === 'string') {
        this.ellipsed = ellipsed;
      }

      this.collider = extend({
        type: hasData(this) ? 'bounds' : null
      }, collider);
      this.__boundingRect = {
        true: null,
        false: null
      };
      this.__bounds = {
        true: null,
        false: null
      };
    }
  }, {
    key: "boundingRect",
    value: function boundingRect() {
      var includeTransform = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (this.__boundingRect[includeTransform] !== null) {
        return this.__boundingRect[includeTransform];
      }

      var rect;

      if (typeof this._textBoundsFn === 'function') {
        rect = this._textBoundsFn(this.attrs);
      } else {
        return {
          x: 0,
          y: 0,
          width: 0,
          height: 0
        };
      }

      var p = rectToPoints(rect);
      var pt = includeTransform && this.modelViewMatrix ? this.modelViewMatrix.transformPoints(p) : p;

      var _getMinMax = getMinMax(pt),
          _getMinMax2 = picasso_esm_slicedToArray(_getMinMax, 4),
          xMin = _getMinMax2[0],
          yMin = _getMinMax2[1],
          xMax = _getMinMax2[2],
          yMax = _getMinMax2[3];

      this.__boundingRect[includeTransform] = {
        x: xMin,
        y: yMin,
        width: xMax - xMin,
        height: yMax - yMin
      };
      return this.__boundingRect[includeTransform];
    }
  }, {
    key: "bounds",
    value: function bounds() {
      var includeTransform = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      if (this.__bounds[includeTransform] !== null) {
        return this.__bounds[includeTransform];
      }

      var rect = this.boundingRect(includeTransform);
      this.__bounds[includeTransform] = [{
        x: rect.x,
        y: rect.y
      }, {
        x: rect.x + rect.width,
        y: rect.y
      }, {
        x: rect.x + rect.width,
        y: rect.y + rect.height
      }, {
        x: rect.x,
        y: rect.y + rect.height
      }];
      return this.__bounds[includeTransform];
    }
  }]);

  return Text;
}(DisplayObject);
function create$l() {
  for (var _len = arguments.length, s = new Array(_len), _key = 0; _key < _len; _key++) {
    s[_key] = arguments[_key];
  }

  return _construct(Text, s);
}

var reg$3 = registryFactory();
reg$3.add('rect', create$h);
reg$3.add('circle', create$i);
reg$3.add('text', create$l);
reg$3.add('line', create$j);
reg$3.add('path', create$k);
reg$3.add('stage', create$e);
reg$3.add('container', create$d);
reg$3.add('defs', create$d);
reg$3.add('linearGradient', create$f);
reg$3.add('radialGradient', create$f);
reg$3.add('stop', create$f);
reg$3.add('pattern', create$g);
function create$m(type, input) {
  // eslint-disable-line import/prefer-default-export
  return reg$3.get(type)(input);
}

/**
 * Creates a context. Input an array of strings that should be inherited by the context.
 * @private
 *
 * @param  {Array}  [whitelist=[]]  An array of whitelisted string keys to inherit
 * @return {Function}               A context function
 */

function contextFactory() {
  var whitelist = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var states = [{}];
  /**
   * Returns the current context as an object. The object is mutable.
   * @private
   *
   * @return {Object}   Current context
   */

  function context() {
    // Returns the current context, the last in the stack.
    var item = states[states.length - 1];
    return item;
  }
  /**
   * Call context.save() to save the current context and move down the stack.
   *
   * @param  {Object} [item={}]   Optional item to save.
   * @return {Object}             The current context, just as context()
   */


  context.save = function save() {
    var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var current = context();
    var obj = {};
    var key = ''; // Only inherit whitelisted properties

    for (var i = 0; i < whitelist.length; i++) {
      key = whitelist[i];

      if (typeof current[key] !== 'undefined') {
        obj[key] = current[key];
      }
    } // Extend the new object with the saved item


    extend(obj, item); // Push it to the stack

    states.push(obj); // Return the new current context

    return context();
  };
  /**
   * Restore the previous context. Returns the context.
   *
   * @return {Undefined}   Returns nothing
   */


  context.restore = function restore() {
    // Remove the last element from the stack
    states.splice(states.length - 1, 1);
  };

  return context;
}

var styleContext = contextFactory(['stroke', 'fill', 'strokeWidth', 'opacity', 'fontFamily', 'fontSize', 'baseline']);

function doEvent(state, listeners) {
  if (!Array.isArray(listeners)) {
    return;
  }

  for (var i = 0, len = listeners.length; i < len; i++) {
    listeners[i](state);
  }
}

function updateState(state, index, nodes) {
  state.node = nodes[index];
  state.index = index;
}

function traverse(items, parent, matrix, on) {
  var disabled = false;
  var state = {
    siblings: items,
    node: null,
    index: 0
  };

  for (var i = 0, len = items.length; i < len; i++) {
    updateState(state, i, items);
    doEvent(state, on.create);
    disabled = typeof state.node.disabled === 'function' ? state.node.disabled() : state.node.disabled;

    if (disabled) {
      continue;
    } // Save the current style context to be able to inherit styles


    state.node = styleContext.save(state.node);
    var displayNode = create$m(state.node.type, state.node);

    if (displayNode) {
      if (state.node.transform) {
        matrix.save();
        resolveTransform(state.node.transform, matrix);
      }

      if (!matrix.isIdentity()) {
        displayNode.modelViewMatrix = matrix.clone();
      }

      parent.addChild(displayNode);

      if (state.node.children) {
        traverse(state.node.children, displayNode, matrix, on);
      }

      if (state.node.transform) {
        matrix.restore();
      }
    } // Revert to previous style context


    styleContext.restore();
  }
}

function picasso_esm_scene(_ref) {
  var items = _ref.items,
      stage = _ref.stage,
      dpi = _ref.dpi,
      _ref$on = _ref.on,
      on = _ref$on === void 0 ? {} : _ref$on;

  if (!stage) {
    stage = create$m('stage', dpi);
  }

  traverse(items, stage, new Matrix(), on);
  return stage;
}

/**
 * Get or create a gradient
 * @ignore
 * @param  {Object} g        Canvas 2d context
 * @param  {Object} node    Current node (for width/height properties)
 * @param  {Object} gradient The gradient properties
 * @return {Object}          A canvas compatible radial or linear gradient object
 */

function createCanvasGradient(g, node, gradient) {
  var orientation = gradient.orientation,
      degree = gradient.degree,
      _gradient$stops = gradient.stops,
      stops = _gradient$stops === void 0 ? [] : _gradient$stops;
  var newGradient = null;

  if (orientation === 'radial') {
    var bounds = node.boundingRect();
    newGradient = g.createRadialGradient(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2, 1e-5, bounds.x + bounds.width / 2, bounds.y + bounds.height / 2, Math.max(bounds.width, bounds.height) / 2);
  } else {
    var points = degreesToPoints(degree);
    ['x1', 'x2', 'y1', 'y2'].forEach(function (c) {
      if (c in gradient) {
        points[c] = gradient[c];
      }
    });

    var _bounds = node.boundingRect();

    newGradient = g.createLinearGradient(_bounds.x + points.x1 * _bounds.width, _bounds.y + points.y1 * _bounds.height, _bounds.x + points.x2 * _bounds.width, _bounds.y + points.y2 * _bounds.height);
  }

  for (var i = 0, len = stops.length; i < len; i++) {
    var stop = stops[i];
    newGradient.addColorStop(stop.offset, stop.color);
  }

  return newGradient;
}

function getPattern(pattern, dummyCanvas, ctx) {
  dummyCanvas.width = pattern.width;
  dummyCanvas.height = pattern.height;
  ctx.save();
  ctx.fillStyle = pattern.fill;
  pattern.shapes.forEach(function (s) {
    switch (s.type) {
      case 'rect':
        ctx.rect(s.x, s.y, s.width, s.height);
        break;

      default:
        break;
    }
  });
  ctx.fill();
  ctx.restore();
  return ctx.createPattern(dummyCanvas, 'repeat');
}

function patternizer(document) {
  var dummyCanvas = document.createElement('canvas');
  var ctx = dummyCanvas.getContext('2d');
  var cache = {};
  return {
    create: function create(pattern) {
      var key = pattern.key;

      if (key) {
        cache[key] = cache[key] || getPattern(pattern, dummyCanvas, ctx);
        return cache[key];
      }

      return getPattern(pattern, dummyCanvas, ctx);
    },
    clear: function clear() {
      cache = {};
    }
  };
}

/**
 * @typedef {object} renderer-container-def
 * @property {number} [x] - x-coordinate
 * @property {number} [y] - y-coordinate
 * @property {number} [width] - Width
 * @property {number} [height] - Height
 * @property {object} [scaleRatio]
 * @property {number} [scaleRatio.x] - Scale ratio on x-axis
 * @property {number} [scaleRatio.y] - Scale ratio on y-axis
 * @property {object} [margin]
 * @property {number} [margin.left] - Left margin
 * @property {number} [margin.top] - Top margin
 */

/**
 * Create the renderer box
 * @private
 * @param {renderer-container-def} [opts]
 * @returns {renderer-container-def} A svg renderer instance
 */
function createRendererBox() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      x = _ref.x,
      y = _ref.y,
      width = _ref.width,
      height = _ref.height,
      scaleRatio = _ref.scaleRatio,
      margin = _ref.margin,
      edgeBleed = _ref.edgeBleed;

  var box = {
    x: 0,
    y: 0,
    width: 0,
    height: 0,
    scaleRatio: {
      x: 1,
      y: 1
    },
    margin: {
      left: 0,
      top: 0
    },
    edgeBleed: {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0,
      bool: false
    }
  };
  box.x = isNaN(x) ? box.x : x;
  box.y = isNaN(y) ? box.y : y;
  box.width = isNaN(width) ? box.width : width;
  box.height = isNaN(height) ? box.height : height;

  if (typeof scaleRatio !== 'undefined') {
    box.scaleRatio.x = isNaN(scaleRatio.x) ? box.scaleRatio.x : scaleRatio.x;
    box.scaleRatio.y = isNaN(scaleRatio.y) ? box.scaleRatio.y : scaleRatio.y;
  }

  if (typeof margin !== 'undefined') {
    box.margin.left = isNaN(margin.left) ? 0 : margin.left;
    box.margin.top = isNaN(margin.top) ? 0 : margin.top;
  }

  if (_typeof(edgeBleed) === 'object') {
    ['left', 'right', 'top', 'bottom'].forEach(function (prop) {
      if (!isNaN(edgeBleed[prop]) && edgeBleed[prop] > 0) {
        box.edgeBleed[prop] = edgeBleed[prop];
        box.edgeBleed.bool = true;
      }
    });
  }

  box.computedPhysical = {
    x: Math.round(box.margin.left + (box.x - box.edgeBleed.left) * box.scaleRatio.x),
    y: Math.round(box.margin.top + (box.y - box.edgeBleed.top) * box.scaleRatio.y),
    width: Math.round((box.width + box.edgeBleed.left + box.edgeBleed.right) * box.scaleRatio.x),
    height: Math.round((box.height + box.edgeBleed.top + box.edgeBleed.bottom) * box.scaleRatio.y)
  };
  return box;
}

/**
 * Base renderer factory
 * @private
 */

function create$n() {
  /**
  * @interface
  * @alias renderer
  */
  var renderer = {
    /**
    * Get the element this renderer is attached to
    * @returns {HTMLElement}
    */
    element: function element() {},

    /**
     * Get the root element of the renderer
     * @returns {HTMLElement}
     */
    root: function root() {},

    /**
    * @param {HTMLElement} element - Element to attach renderer to
    * @returns {HTMLElement} Root element of the renderer
    */
    appendTo: function appendTo() {},

    /**
     * @param {node-def[]} nodes - Nodes to render
     * @returns {boolean} True if the nodes where rendered, otherwise false
     */
    render: function render() {
      return false;
    },

    /**
     * Get nodes renderer at area
     * @param {point|circle|rect|line|polygon} geometry - Get nodes that intersects with geometry
     * @returns {SceneNode[]}
     */
    itemsAt: function itemsAt() {
      return [];
    },

    /**
     * Get all nodes matching the provided selector
     * @param {string} selector CSS selector [type, attribute, universal, class]
     * @returns {SceneNode[]} Array of objects containing matching nodes
     */
    findShapes: function findShapes() {
      return [];
    },

    /**
     * Clear all child elements from the renderer root element
     * @returns {renderer} The renderer instance
     */
    clear: function clear() {},

    /**
     * Remove the renderer root element from its parent element
     */
    destory: function destory() {},

    /**
     * Set or Get the size definition of the renderer container.
     * @param {renderer-container-def} [opts] - Size definition
     * @returns {renderer-container-def} The current size definition
     */
    size: function size() {},

    /**
     * @function
     * @param {object} opts
     * @param {string} opts.text - Text to measure
     * @param {string} opts.fontSize - {@link https://www.w3.org/TR/SVG/text.html#FontPropertiesUsedBySVG}
     * @param {string} opts.fontFamily - {@link https://www.w3.org/TR/SVG/text.html#FontPropertiesUsedBySVG}
     * @returns {object} Width and height of text
     * @example
     * measureText({
     *  text: 'my text',
     *  fontSize: '12px',
     *  fontFamily: 'Arial'
     * }); // returns { width: 20, height: 12 }
     */
    measureText: measureText$1,

    /**
     * Calculates the bounding rectangle of a text node. Including any potential line breaks.
     * @function
     * @param {node--text-def} node
     * @return {rect} The bounding rectangle
     */
    textBounds: textBounds,
    setKey: function setKey(key) {
      renderer.element().setAttribute('data-key', key);
    }
  };
  return renderer;
}

function hasData$1(data) {
  return typeof data !== 'undefined' && data !== null;
}

function injectTextBoundsFn(renderer) {
  return function (_ref) {
    var node = _ref.node;

    if (node.type === 'text' && hasData$1(node.data) && !node.textBoundsFn) {
      node.textBoundsFn = renderer.textBounds;
    }
  };
}

var reg$4 = registryFactory();

function toLineDash(p) {
  if (Array.isArray(p)) {
    return p;
  }

  if (typeof p === 'string') {
    if (p.indexOf(',') !== -1) {
      return p.split(',');
    }

    return p.split(' ');
  }

  return [];
}

function dpiScale(g) {
  var dpr = typeof window === 'undefined' ? 1 : window.devicePixelRatio || 1;
  var backingStorePixelRatio = g.webkitBackingStorePixelRatio || g.mozBackingStorePixelRatio || g.msBackingStorePixelRatio || g.oBackingStorePixelRatio || g.backingStorePixelRatio || 1;
  return dpr / backingStorePixelRatio;
}

function resolveMatrix(p, g) {
  g.setTransform(p[0][0], p[1][0], p[0][1], p[1][1], p[0][2], p[1][2]);
}

function applyContext(g, s, shapeToCanvasMap) {
  var computed = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  var computedKeys = Object.keys(computed);

  for (var i = 0, len = shapeToCanvasMap.length; i < len; i++) {
    var cmd = shapeToCanvasMap[i];
    var shapeCmd = cmd[0];
    var canvasCmd = cmd[1];
    var convertCmd = cmd[2];

    if (shapeCmd in s.attrs && !(canvasCmd in computed) && g[canvasCmd] !== s.attrs[shapeCmd]) {
      var val = convertCmd ? convertCmd(s.attrs[shapeCmd]) : s.attrs[shapeCmd];

      if (typeof g[canvasCmd] === 'function') {
        g[canvasCmd](val);
      } else {
        g[canvasCmd] = val;
      }
    }
  }

  for (var _i = 0, _len = computedKeys.length; _i < _len; _i++) {
    var key = computedKeys[_i];
    g[key] = computed[key];
  }
}

function renderShapes(shapes, g, shapeToCanvasMap, deps) {
  for (var i = 0, len = shapes.length; i < len; i++) {
    var shape = shapes[i];
    var computed = {};
    g.save();

    if (shape.attrs && (shape.attrs.fill || shape.attrs.stroke)) {
      if (shape.attrs.fill && _typeof(shape.attrs.fill) === 'object' && shape.attrs.fill.type === 'gradient') {
        computed.fillStyle = createCanvasGradient(g, shape, shape.attrs.fill);
      } else if (shape.attrs.fill && _typeof(shape.attrs.fill) === 'object' && shape.attrs.fill.type === 'pattern') {
        computed.fillStyle = deps.patterns.create(shape.attrs.fill);
      }

      if (shape.attrs.stroke && _typeof(shape.attrs.stroke) === 'object' && shape.attrs.stroke.type === 'gradient') {
        computed.strokeStyle = createCanvasGradient(g, shape, shape.attrs.stroke);
      } else if (shape.attrs.stroke && _typeof(shape.attrs.stroke) === 'object' && shape.attrs.stroke.type === 'pattern') {
        computed.strokeStyle = deps.patterns.create(shape.attrs.stroke);
      }
    }

    applyContext(g, shape, shapeToCanvasMap, computed);

    if (shape.modelViewMatrix) {
      resolveMatrix(shape.modelViewMatrix.elements, g);
    }

    if (reg$4.has(shape.type)) {
      reg$4.get(shape.type)(shape.attrs, {
        g: g,
        doFill: 'fill' in shape.attrs && shape.attrs.fill !== 'none',
        doStroke: 'stroke' in shape.attrs && shape.attrs['stroke-width'] !== 0,
        ellipsed: shape.ellipsed
      });
    }

    if (shape.children) {
      renderShapes(shape.children, g, shapeToCanvasMap, deps);
    }

    g.restore();
  }
}
/**
 * Create a new canvas renderer
 * @typedef {function} canvasRendererFactory
 * @param {function} sceneFn - Scene factory
 * @returns {renderer} A canvas renderer instance
 */


function picasso_esm_renderer() {
  var sceneFn = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : picasso_esm_scene;
  var el;
  var scene$1;
  var hasChangedRect = false;
  var rect = createRendererBox();
  var shapeToCanvasMap = [['fill', 'fillStyle'], ['stroke', 'strokeStyle'], ['opacity', 'globalAlpha'], ['globalAlpha', 'globalAlpha'], ['stroke-width', 'lineWidth'], ['stroke-linejoin', 'lineJoin'], ['stroke-dasharray', 'setLineDash', toLineDash]];
  var patterns;
  var canvasRenderer = create$n();

  canvasRenderer.element = function () {
    return el;
  };

  canvasRenderer.root = function () {
    return el;
  };

  canvasRenderer.appendTo = function (element) {
    if (!el) {
      el = element.ownerDocument.createElement('canvas');
      el.style.position = 'absolute';
      el.style['-webkit-font-smoothing'] = 'antialiased';
      el.style['-moz-osx-font-smoothing'] = 'antialiased';
      el.style.pointerEvents = 'none';
    }

    element.appendChild(el);
    return el;
  };

  canvasRenderer.render = function (shapes) {
    if (!el) {
      return false;
    }

    if (!patterns) {
      patterns = patternizer(el.ownerDocument);
    }

    var g = el.getContext('2d');
    var dpiRatio = dpiScale(g);
    var scaleX = rect.scaleRatio.x;
    var scaleY = rect.scaleRatio.y;

    if (hasChangedRect) {
      el.style.left = "".concat(rect.computedPhysical.x, "px");
      el.style.top = "".concat(rect.computedPhysical.y, "px");
      el.style.width = "".concat(rect.computedPhysical.width, "px");
      el.style.height = "".concat(rect.computedPhysical.height, "px");
      el.width = Math.round(rect.computedPhysical.width * dpiRatio);
      el.height = Math.round(rect.computedPhysical.height * dpiRatio);
    }

    var sceneContainer = {
      type: 'container',
      children: shapes,
      transform: rect.edgeBleed.bool ? "translate(".concat(rect.edgeBleed.left * dpiRatio * scaleX, ", ").concat(rect.edgeBleed.top * dpiRatio * scaleY, ")") : ''
    };

    if (dpiRatio !== 1 || scaleX !== 1 || scaleY !== 1) {
      sceneContainer.transform += "scale(".concat(dpiRatio * scaleX, ", ").concat(dpiRatio * scaleY, ")");
    }

    var newScene = sceneFn({
      items: [sceneContainer],
      dpi: dpiRatio,
      on: {
        create: [onLineBreak(canvasRenderer.measureText), injectTextBoundsFn(canvasRenderer)]
      }
    });
    var hasChangedScene = scene$1 ? !newScene.equals(scene$1) : true;
    patterns.clear();
    var doRender = hasChangedRect || hasChangedScene;

    if (doRender) {
      canvasRenderer.clear();
      renderShapes(newScene.children, g, shapeToCanvasMap, {
        patterns: patterns
      });
    }

    hasChangedRect = false;
    scene$1 = newScene;
    return doRender;
  };

  canvasRenderer.itemsAt = function (input) {
    return scene$1 ? scene$1.getItemsFrom(input) : [];
  };

  canvasRenderer.findShapes = function (selector) {
    return scene$1 ? scene$1.findShapes(selector) : [];
  };

  canvasRenderer.clear = function () {
    if (el) {
      el.width = el.width; // eslint-disable-line
    }

    scene$1 = null;
    return canvasRenderer;
  };

  canvasRenderer.size = function (opts) {
    if (opts) {
      var newRect = createRendererBox(opts);

      if (JSON.stringify(rect) !== JSON.stringify(newRect)) {
        hasChangedRect = true;
        rect = newRect;
      }
    }

    return rect;
  };

  canvasRenderer.destroy = function () {
    if (el) {
      if (el.parentElement) {
        el.parentElement.removeChild(el);
      }

      el = null;
    }

    scene$1 = null;
  };

  return canvasRenderer;
}
function register(type, renderFn) {
  reg$4.add(type, renderFn);
}

function clampRadius(max, value) {
  return Math.max(0, Math.min(max, value));
}
/**
 * Implementation details follow rx/ry restrictions from https://svgwg.org/svg2-draft/geometry.html#RX
 *
 * Using Quadratic Bézier curve it's not possible accurately represent a circle or ellipse but should for the case of a rounded rectangle be sufficent.
 * @private
 */


function quadraticRoundedRect(g, x, y, width, height, rx, ry) {
  rx = clampRadius(width / 2, rx > 0 ? rx : ry);
  ry = clampRadius(height / 2, ry > 0 ? ry : rx);
  g.moveTo(x, y + ry);
  g.lineTo(x, y + height - ry);
  g.quadraticCurveTo(x, y + height, x + rx, y + height);
  g.lineTo(x + width - rx, y + height);
  g.quadraticCurveTo(x + width, y + height, x + width, y + height - ry);
  g.lineTo(x + width, y + ry);
  g.quadraticCurveTo(x + width, y, x + width - rx, y);
  g.lineTo(x + rx, y);
  g.quadraticCurveTo(x, y, x, y + ry);
}

function render$4(rect, _ref) {
  var g = _ref.g,
      doFill = _ref.doFill,
      doStroke = _ref.doStroke;
  g.beginPath();

  if (rect.rx > 0 || rect.ry > 0) {
    quadraticRoundedRect(g, rect.x, rect.y, rect.width, rect.height, rect.rx, rect.ry);
  } else {
    g.rect(rect.x, rect.y, rect.width, rect.height);
  }

  if (doFill) {
    g.fill();
  }

  if (doStroke) {
    g.stroke();
  }
}

function render$5(circle, _ref) {
  var g = _ref.g,
      doFill = _ref.doFill,
      doStroke = _ref.doStroke;
  g.beginPath();
  g.moveTo(circle.cx + circle.r, circle.cy);
  g.arc(circle.cx, circle.cy, circle.r, 0, Math.PI * 2, false);

  if (doFill) {
    g.fill();
  }

  if (doStroke) {
    g.stroke();
  }
}

function render$6(line, _ref) {
  var g = _ref.g,
      doStroke = _ref.doStroke;
  g.beginPath();
  g.moveTo(line.x1, line.y1);
  g.lineTo(line.x2, line.y2);

  if (doStroke) {
    g.stroke();
  }
}

/* eslint no-misleading-character-class: 0 */
// Source: https://en.wikipedia.org/wiki/Bi-directional_text and http://www.unicode.org/Public/6.0.0/ucd/UnicodeData.txt
// 3 types of strong direction characters: L (strong left-to-right), R(strong right-to-left, Hebrew) and AL(strong right-to-left, Arabic language)
var rangesOfLChars = "[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0-\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376-\u037D\u0386\u0388-\u03F5\u03F7-\u0482\u048A-\u0589\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u097F\u0982-\u09B9\u09BD-\u09C0\u09C7-\u09CC\u09CE-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u0A03-\u0A39\u0A3E-\u0A40\u0A59-\u0A6F\u0A72-\u0A74\u0A83-\u0AB9\u0ABD-\u0AC0\u0AC9-\u0ACC\u0AD0-\u0AE1\u0AE6-\u0AEF\u0B02-\u0B39\u0B3D-\u0B3E\u0B40\u0B47-\u0B4C\u0B57-\u0B61\u0B66-\u0B77\u0B83-\u0BBF\u0BC1-\u0BCC\u0BD0-\u0BF2\u0C01-\u0C3D\u0C41-\u0C44\u0C58-\u0C61\u0C66-\u0C6F\u0C7F-\u0CB9\u0CBD-\u0CCB\u0CD5-\u0CE1\u0CE6-\u0D40\u0D46-\u0D4C\u0D4E-\u0D61\u0D66-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0E30\u0E32-\u0E33\u0E40-\u0E46\u0E4F-\u0EB0\u0EB2-\u0EB3\u0EBD-\u0EC6\u0ED0-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u102C\u1031\u1038\u103B-\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083-\u1084\u1087-\u108C\u108E-\u109C\u109E-\u135A\u1360-\u138F\u13A0-\u13F4\u1401-\u167F\u1681-\u169A\u16A0-\u1711\u1720-\u1731\u1735-\u1751\u1760-\u1770\u1780-\u17B6\u17BE-\u17C5\u17C7-\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u18A8\u18AA-\u191C\u1923-\u1926\u1929-\u1931\u1933-\u1938\u1946-\u19DA\u1A00-\u1A16\u1A19-\u1A55\u1A57\u1A61\u1A63-\u1A64\u1A6D-\u1A72\u1A80-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B6A\u1B74-\u1B7C\u1B82-\u1BA1\u1BA6-\u1BA7\u1BAA-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2-\u1C2B\u1C34-\u1C35\u1C3B-\u1C7F\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1DBF\u1E00-\u1FBC\u1FBE\u1FC2-\u1FCC\u1FD0-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FFC\u200E\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E-\u214F\u2160-\u2188\u2336-\u237A\u2395\u249C-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2CE4\u2CEB-\u2CEE\u2D00-\u2D70\u2D80-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u31BA\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DB5\u4E00-\uA48C\uA4D0-\uA60C\uA610-\uA66E\uA680-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA925\uA92E-\uA946\uA952-\uA97C\uA983-\uA9B2\uA9B4-\uA9B5\uA9BA-\uA9BB\uA9BD-\uAA28\uAA2F-\uAA30\uAA33-\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D-\uAAAF\uAAB1\uAAB5-\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2-\uABE4\uABE6-\uABE7\uABE9-\uABEC\uABF0-\uFB17\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFDC]";
var rangesOfRChars = "[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05F4\u07C0-\u07EA\u07F4-\u07F5\u07FA-\u0815\u081A\u0824\u0828\u0830-\u0858\u085E\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB4F]";
var rangesOfALChars = "[\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5-\u06E6\u06EE-\u06EF\u06FA-\u070D\u0710\u0712-\u072F\u074D-\u07A5\u07B1\uFB50-\uFD3D\uFD50-\uFDFC\uFE70-\uFEFC]"; // let rangesOfNChars = '[\u0009-\u000D\u001C-\u0022\u0026-\u002A\u003B-\u0040\u005B-\u0060\u007B-\u007E\u0085\u00A1\u00A6-\u00A9\u00AB-\u00AC\u00AE-\u00AF\u00B4\u00B6-\u00B8\u00BB-\u00BF\u00D7\u00F7\u02B9-\u02BA\u02C2-\u02CF\u02D2-\u02DF\u02E5-\u02ED\u02EF-\u02FF\u0374-\u0375\u037E-\u0385\u0387\u03F6\u058A\u0606-\u0607\u060E-\u060F\u06DE\u06E9\u07F6-\u07F9\u0BF3-\u0BF8\u0BFA\u0C78-\u0C7E\u0F3A-\u0F3D\u1390-\u1399\u1400\u1680\u169B-\u169C\u17F0-\u180A\u180E\u1940-\u1945\u19DE-\u19FF\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD-\u200A\u2010-\u2029\u2035-\u2043\u2045-\u205F\u207C-\u207E\u208C-\u208E\u2100-\u2101\u2103-\u2106\u2108-\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u213A-\u213B\u2140-\u2144\u214A-\u214D\u2150-\u215F\u2189-\u2211\u2214-\u2335\u237B-\u2394\u2396-\u2487\u24EA-\u26AB\u26AD-\u27FF\u2900-\u2B59\u2CE5-\u2CEA\u2CF9-\u2CFF\u2E00-\u3004\u3008-\u3020\u3030\u3036-\u3037\u303D-\u303F\u309B-\u309C\u30A0\u30FB\u31C0-\u31E3\u321D-\u321E\u3250-\u325F\u327C-\u327E\u32B1-\u32BF\u32CC-\u32CF\u3377-\u337A\u33DE-\u33DF\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA60D-\uA60F\uA673\uA67E-\uA67F\uA700-\uA721\uA788\uA828-\uA82B\uA874-\uA877\uFD3E-\uFD3F\uFDFD\uFE10-\uFE19\uFE30-\uFE4F\uFE51\uFE54\uFE56-\uFE5E\uFE60-\uFE61\uFE64-\uFE68\uFE6B\uFF01-\uFF02\uFF06-\uFF0A\uFF1B-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\uFFE2-\uFFE4\uFFE8-\uFFFD]';

var rangesOfLRgExp = new RegExp(rangesOfLChars);
var rangesOfRRgExp = new RegExp(rangesOfRChars);
var rangesOfALRgExp = new RegExp(rangesOfALChars); // let rangesOfNRgExp = new RegExp(rangesOfNChars);
// let lrm = String.fromCharCode(8206); // left-to-right marker
// let rlm = String.fromCharCode(8207); // right-to-left marker

function isLtrChar(c) {
  return rangesOfLRgExp.test(c);
}

function isRtlChar(c) {
  return rangesOfRRgExp.test(c) || rangesOfALRgExp.test(c);
}

function detectTextDirection(s) {
  var n = s ? s.length : 0,
      i,
      c;

  for (i = 0; i < n; i++) {
    c = s[i];

    if (isLtrChar(c)) {
      return 'ltr';
    }

    if (isRtlChar(c)) {
      return 'rtl';
    }
  }

  return 'ltr';
}
var textAnchorRTLMap = {
  start: 'end',
  end: 'start',
  center: 'center',
  middle: 'middle'
};
/* let flippedTextAnchor = true;
let detected = false;
export function detectRtlSvgSupport(ns, ownerDoc) {
  if (!detected) {
    const body = ownerDoc.body;
    if (body) {
      const rtlTestSVG = ownerDoc.createElementNS(ns, 'svg');
      const textNode = ownerDoc.createElementNS(ns, 'text');
      const group = ownerDoc.createElementNS(ns, 'g');

      rtlTestSVG.setAttribute('xmlns', ns);
      rtlTestSVG.setAttribute('style', 'position: absolute; width: 100px; height: 100px; top: -100px; left: 0px');

      textNode.setAttribute('text-anchor', 'start');
      textNode.setAttribute('direction', 'rtl');
      textNode.setAttribute('font-size', '14px');
      textNode.setAttribute('x', 50);
      textNode.setAttribute('y', 50);
      textNode.textContent = 'ثعبان';

      group.appendChild(textNode);
      rtlTestSVG.appendChild(group);
      body.appendChild(rtlTestSVG);

      flippedTextAnchor = textNode.getBoundingClientRect().left < 50;
      body.removeChild(rtlTestSVG);
    }
  }
  detected = true;
} */

function flipTextAnchor(value, dir) {
  if (dir === 'rtl') {
    return textAnchorRTLMap[value];
  }

  return value;
}

function render$7(t, _ref) {
  var g = _ref.g,
      ellipsed = _ref.ellipsed;
  var text = ellipsed || ellipsText(t, measureText$1);
  g.font = "".concat(t['font-size'], " ").concat(t['font-family']);
  var dir = detectTextDirection(t.text);

  if (g.canvas.dir !== dir) {
    g.canvas.dir = dir;
  }

  var textAnchor = t['text-anchor'] === 'middle' ? 'center' : t['text-anchor'];
  var textAlign = flipTextAnchor(textAnchor, g.canvas.dir);

  if (textAlign && g.textAlign !== textAlign) {
    g.textAlign = textAlign;
  }

  var bdy = baselineHeuristic(t);
  g.fillText(text, t.x + t.dx, t.y + t.dy + bdy);
}

function render$8(path, _ref) {
  var g = _ref.g,
      doStroke = _ref.doStroke,
      doFill = _ref.doFill;
  var p = new Path2D(path.d);

  if (doFill) {
    g.fill(p);
  }

  if (doStroke) {
    g.stroke(p);
  }
}

register('rect', render$4);
register('circle', render$5);
register('line', render$6);
register('path', render$8);
register('text', render$7);
function rendererComponent(picasso) {
  picasso.renderer('canvas', picasso_esm_renderer);
}

function diff$1(from, to) {
  var added = [];
  var items;
  var removed = [];
  var updatedNew = [];
  var updatedOld = [];
  var fromIds;
  var toIds;

  var idMapper = function idMapper(a) {
    return a.id;
  };

  var nodeMapper = function nodeMapper(node, i) {
    var id;

    if (_typeof(node) === 'object') {
      if ('id' in node) {
        id = node.id;
      } else {
        id = i;
      }
    } else {
      id = node;
    }

    return {
      content: node,
      id: "".concat(id, "__").concat(node.type || '')
    };
  };

  if (!from.isTree) {
    from = from.map(nodeMapper);
  }

  to = to.map(nodeMapper);
  fromIds = from.map(idMapper);
  toIds = to.map(idMapper); // TODO - handle duplicate values
  // added = to.filter( v => fromIds.indexOf( v.id ) < 0 );
  // updatedNew = to.filter( v => fromIds.indexOf( v.id ) >= 0 );
  // removed = from.filter( v => toIds.indexOf( v.id ) < 0 );
  // updatedOld = from.filter( v => toIds.indexOf( v.id ) >= 0 );

  for (var i = 0, len = to.length; i < len; i++) {
    var idx = fromIds.indexOf(to[i].id);

    if (idx === -1) {
      added.push(to[i]);
    } else {
      updatedNew.push(to[i]);
    }
  }

  for (var _i = 0, _len = from.length; _i < _len; _i++) {
    var _idx = toIds.indexOf(from[_i].id);

    if (_idx === -1) {
      removed.push(from[_i]);
    } else {
      updatedOld.push(from[_i]);
    }
  }

  for (var _i2 = 0, _len2 = added.length; _i2 < _len2; _i2++) {
    if (added[_i2].content.children) {
      added[_i2].diff = diff$1([], added[_i2].content.children);
      added[_i2].children = added[_i2].diff.updatedNew.concat(added[_i2].diff.added);
      added[_i2].children.isTree = true;
    }
  }

  for (var _i3 = 0, _len3 = updatedNew.length; _i3 < _len3; _i3++) {
    updatedNew[_i3].diff = diff$1(updatedOld[_i3].children || [], updatedNew[_i3].content.children || []);
    updatedNew[_i3].object = updatedOld[_i3].object;
    updatedNew[_i3].children = updatedNew[_i3].diff.items;
  }

  items = updatedNew.concat(added);
  added.isTree = true;
  removed.isTree = true;
  updatedNew.isTree = true;
  updatedOld.isTree = true;
  items.isTree = true;
  return {
    added: added,
    updatedNew: updatedNew,
    updatedOld: updatedOld,
    removed: removed,
    items: items
  };
}

function createNodes(nodes, parent, create) {
  for (var i = 0, len = nodes.length; i < len; i++) {
    nodes[i].object = create(nodes[i].content.type, parent);
  }
}

function destroyNodes(nodes, destroy) {
  for (var i = 0, len = nodes.length; i < len; i++) {
    if (nodes[i].object !== null && typeof nodes[i].object !== 'undefined') {
      destroy(nodes[i].object);
      nodes[i].object = null;
    }
  }
}

function updateNodes(nodes, creator, maintainer, destroyer) {
  var item;

  for (var i = 0, len = nodes.length; i < len; i++) {
    item = nodes[i];

    if (item.object !== null && typeof item.object !== 'undefined') {
      maintainer(item.object, item.content);

      if (item.diff) {
        createNodes(item.diff.added, item.object, creator);
        destroyNodes(item.diff.removed, destroyer);
        updateNodes(item.diff.items, creator, maintainer, destroyer);
      }
    }
  }
}

function createTree(oldItems, newItems, root, creator, maintainer, destroyer) {
  var d = diff$1(oldItems, newItems);
  createNodes(d.added, root, creator);
  destroyNodes(d.removed, destroyer);
  updateNodes(d.items, creator, maintainer, destroyer);
  return d.items;
}

var svgNs = 'http://www.w3.org/2000/svg';

var creator = function creator(type, parent) {
  if (!type || typeof type !== 'string') {
    throw new Error("Invalid type: ".concat(type));
  }

  var el = parent.ownerDocument.createElementNS(svgNs, type === 'container' ? 'g' : type);
  parent.appendChild(el);
  return el;
};

var destroyer = function destroyer(el) {
  if (el.parentNode) {
    el.parentNode.removeChild(el);
  }
};

var maintainer = function maintainer(element, item) {
  for (var attr in item.attrs) {
    if (attr === 'stroke' && item.strokeReference) {
      element.setAttribute('stroke', item.strokeReference);
    } else if (attr === 'fill' && item.fillReference) {
      element.setAttribute('fill', item.fillReference);
    } else if (attr === 'text') {
      element.setAttribute('style', 'white-space: pre');
      element.textContent = item.ellipsed || ellipsText(item.attrs, measureText$1);
      var dir = detectTextDirection(item.attrs.text);

      if (dir === 'rtl') {
        element.setAttribute('direction', 'rtl');
        element.setAttribute('dir', 'rtl');
        element.setAttribute('text-anchor', flipTextAnchor(element.getAttribute('text-anchor'), dir));
      }
    } else if (item.type === 'text' && (attr === 'dy' || attr === 'dominant-baseline')) {
      var dy = +element.getAttribute(attr) || 0;
      var val = 0;

      if (attr === 'dominant-baseline') {
        val = baselineHeuristic(item.attrs);
      } else {
        val = item.attrs[attr];
      }

      element.setAttribute('dy', val + dy);
    } else if (item.type === 'text' && attr === 'title' && item.attrs.title) {
      var t = element.ownerDocument.createElementNS(svgNs, 'title');
      t.textContent = item.attrs.title;
      element.appendChild(t);
    } else {
      element.setAttribute(attr, item.attrs[attr]);
    }
  }

  if (typeof item.data === 'string' || typeof item.data === 'number' || typeof item.data === 'boolean') {
    element.setAttribute('data', item.data);
  } else if (_typeof(item.data) === 'object' && item.data !== null) {
    for (var d in item.data) {
      if (typeof item.data[d] === 'string' || typeof item.data[d] === 'number' || typeof item.data[d] === 'boolean') {
        element.setAttribute("data-".concat(d), item.data[d]);
      }
    }
  }
};

var TreeItemRenderer =
/*#__PURE__*/
function () {
  /**
   * Constructor
   * @private
   * @param  {TreeCreator} treeCreator - Function used to create the DOM tree..
   * @param  {SVGCreator} nodeCreator - Function used to create nodes.
   * @param  {SVGMaintainer} nodeMaintainer - Function used to update nodes.
   * @param  {SVGDestroyer} nodeDestroyer - Function used to destroy nodes.
   */
  function TreeItemRenderer(treeCreator, nodeCreator, nodeMaintainer, nodeDestroyer) {
    _classCallCheck$1(this, TreeItemRenderer);

    this.create = treeCreator;
    this.nodeCreator = nodeCreator;
    this.nodeMaintainer = nodeMaintainer;
    this.nodeDestroyer = nodeDestroyer;
  }

  _createClass$1(TreeItemRenderer, [{
    key: "render",
    value: function render(newItems, root) {
      return this.create([], newItems, root, this.nodeCreator, this.nodeMaintainer, this.nodeDestroyer);
    }
  }]);

  return TreeItemRenderer;
}();

function tree() {
  return new TreeItemRenderer(createTree, creator, maintainer, destroyer);
}
/**
 * Create an SVGElement and attach to parent.
 * @private
 * @callback SVGCreator
 * @param {String} type - The type of element to create.
 * @param {SVGElement} parent - The parent element to append the new element to.
 * @return {SVGElement} The created element
 */

/**
 * Update the element with content from item.
 * @private
 * @callback SVGMaintainer
 * @param {SVGElement} el - The element to update
 * @param {Object} item - The object to use as input for the update
 */

/**
 * Detach element from its parent.
 * @private
 * @callback SVGDestroyer
 * @param {SVGElement} el - Element to destroy.
 */

/**
 * Create, update and destroy nodes.
 * @private
 * @callback TreeCreator
 * @param {Object[]} existing - The existing items in the tree.
 * @param {Object[]} active - The new items to create the tree from.
 * @param {SVGCreator} creator - Function used to create nodes.
 * @param {SVGMaintainer} maintainer - Function used to update nodes.
 * @param {SVGDestroyer} destroyer - Function used to destroy nodes.
 */

/* eslint import/prefer-default-export: 0 */

/**
 * Hash an object
 * Modified version of Java's HashCode function
 * Source: {@link http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/}
 * @ignore
 *
 * @param  {Object} item Item to hash
 * @return {String}      Unique hash id
 */
function hashObject(item) {
  var hash = 0;
  var i;
  var chr;
  var len;
  item = JSON.stringify(item);

  if (item.length === 0) {
    return hash;
  }

  for (i = 0, len = item.length; i < len; i++) {
    chr = item.charCodeAt(i);
    hash = (hash << 5) - hash + chr;
    hash &= hash; // Convert to 32bit integer
  }

  return hash;
}

function gradienter(bucket) {
  var hasher = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : hashObject;
  var cache = {};
  var uid = Date.now();
  var p = {
    getOrCreateGradient: function getOrCreateGradient() {
      var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var attr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'fill';
      var url = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
      var gradientHash = hasher(item[attr]);
      var gradientId = "picasso-gradient-".concat(uid, "-").concat(gradientHash);

      if (!cache[gradientHash]) {
        var _item$attr = item[attr],
            orientation = _item$attr.orientation,
            degree = _item$attr.degree,
            _item$attr$stops = _item$attr.stops,
            stops = _item$attr$stops === void 0 ? [] : _item$attr$stops;
        var gradient = {};

        if (degree === undefined) {
          degree = 90;
        } // Default to linear


        if (orientation === 'radial') {
          gradient.type = 'radialGradient';
        } else {
          gradient = degreesToPoints(degree);
          ['x1', 'x2', 'y1', 'y2'].forEach(function (c) {
            if (c in item[attr]) {
              gradient[c] = item[attr][c];
            }
          });
          gradient.type = 'linearGradient';
        }

        gradient.id = gradientId;
        gradient.children = stops.map(function (_ref) {
          var offset = _ref.offset,
              color = _ref.color,
              opacity = _ref.opacity;
          return {
            type: 'stop',
            offset: "".concat(offset * 100, "%"),
            style: "stop-color:".concat(color, ";stop-opacity:").concat(typeof opacity !== 'undefined' ? opacity : 1)
          };
        });
        bucket.push(gradient);
        cache[gradientHash] = gradientId;
      }

      return "url('".concat(url, "#").concat(gradientId, "')");
    },
    onCreate: function onCreate(state) {
      var url = '';

      if (typeof window !== 'undefined') {
        url = window.location.href.split('#')[0];
      }

      var item = state.node;

      if (item.fill && _typeof(item.fill) === 'object' && item.fill.type === 'gradient') {
        item.fillReference = p.getOrCreateGradient(item, 'fill', url);
      }

      if (item.stroke && _typeof(item.stroke) === 'object' && item.stroke.type === 'gradient') {
        item.strokeReference = p.getOrCreateGradient(item, 'stroke', url);
      }
    },
    clear: function clear() {
      cache = {};
    }
  };
  return p;
}

function patternizer$1(bucket) {
  var hasher = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : hashObject;
  var cache = {};
  var uid = Date.now();
  var p = {
    onCreate: function onCreate(state) {
      var inputs = {};

      if (state.node && _typeof(state.node.fill) === 'object' && state.node.fill.type === 'pattern' && state.node.fill.shapes) {
        inputs.fill = state.node.fill;
      }

      if (state.node && _typeof(state.node.stroke) === 'object' && state.node.stroke.type === 'pattern' && state.node.stroke.shapes) {
        inputs.stroke = state.node.stroke;
      }

      Object.keys(inputs).forEach(function (key) {
        var url = '';
        var input = inputs[key];
        var patternHash = hasher(input);
        var pnid = "picasso-pattern-".concat(uid, "-").concat(patternHash);

        if (typeof window !== 'undefined') {
          url = window.location.href.split('#')[0];
        }

        if (!cache[patternHash]) {
          var pn = {
            patternUnits: 'userSpaceOnUse',
            x: 0,
            y: 0,
            width: input.width,
            height: input.height,
            type: 'pattern',
            id: pnid,
            children: [],
            fill: input.fill
          };
          input.shapes.forEach(function (s) {
            pn.children.push(s);
          });
          bucket.push(pn);
          cache[patternHash] = true;
        }

        state.node["".concat(key, "Reference")] = "url('".concat(url, "#").concat(pnid, "')");
      });
    },
    clear: function clear() {
      cache = {};
    }
  };
  return p;
}

/**
 * Create a new svg renderer
 * @typedef {function} svgRendererFactory
 * @param {function} treeFactory - Node tree factory
 * @param {string} ns - Namespace definition
 * @param {function} sceneFn - Scene factory
 * @returns {renderer} A svg renderer instance
 */

function renderer$1() {
  var treeFn = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : tree;
  var ns = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : svgNs;
  var sceneFn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : picasso_esm_scene;
  var tree$1 = treeFn();
  var el;
  var group;
  var hasChangedRect = false;
  var rect = createRendererBox();
  var scene$1;
  var svg = create$n();
  var defs = {
    type: 'defs',
    children: []
  };
  var patterns = patternizer$1(defs.children);
  var gradients = gradienter(defs.children);

  svg.element = function () {
    return el;
  };

  svg.root = function () {
    return group;
  };

  svg.appendTo = function (element) {
    if (!el) {
      el = element.ownerDocument.createElementNS(ns, 'svg');
      el.style.position = 'absolute';
      el.style['-webkit-font-smoothing'] = 'antialiased';
      el.style['-moz-osx-font-smoothing'] = 'antialiased';
      el.style.pointerEvents = 'none';
      el.setAttribute('xmlns', ns);
      group = element.ownerDocument.createElementNS(ns, 'g');
      group.style.pointerEvents = 'auto';
      el.appendChild(group);
    }

    element.appendChild(el);
    return el;
  };

  svg.render = function (nodes) {
    if (!el) {
      return false;
    }

    var scaleX = rect.scaleRatio.x;
    var scaleY = rect.scaleRatio.y;

    if (hasChangedRect) {
      el.style.left = "".concat(rect.computedPhysical.x, "px");
      el.style.top = "".concat(rect.computedPhysical.y, "px");
      el.setAttribute('width', rect.computedPhysical.width);
      el.setAttribute('height', rect.computedPhysical.height);
    }

    gradients.clear();
    patterns.clear();
    defs.children.length = 0;
    var sceneContainer = {
      type: 'container',
      children: Array.isArray(nodes) ? [].concat(_toConsumableArray$1(nodes), [defs]) : nodes,
      transform: rect.edgeBleed.bool ? "translate(".concat(rect.edgeBleed.left * scaleX, ", ").concat(rect.edgeBleed.top * scaleY, ")") : ''
    };

    if (scaleX !== 1 || scaleY !== 1) {
      sceneContainer.transform += "scale(".concat(scaleX, ", ").concat(scaleY, ")");
    }

    var newScene = sceneFn({
      items: [sceneContainer],
      on: {
        create: [function (state) {
          state.node.fillReference = undefined;
          state.node.strokeReference = undefined;
        }, gradients.onCreate, patterns.onCreate, onLineBreak(svg.measureText), injectTextBoundsFn(svg)]
      }
    });
    var hasChangedScene = scene$1 ? !newScene.equals(scene$1) : true;
    var doRender = hasChangedRect || hasChangedScene;

    if (doRender) {
      svg.clear();
      tree$1.render(newScene.children, group);
    }

    hasChangedRect = false;
    scene$1 = newScene;
    return doRender;
  };

  svg.itemsAt = function (input) {
    return scene$1 ? scene$1.getItemsFrom(input) : [];
  };

  svg.findShapes = function (selector) {
    return scene$1 ? scene$1.findShapes(selector) : [];
  };

  svg.clear = function () {
    if (!group) {
      return svg;
    }

    scene$1 = null;
    var g = group.cloneNode(false);
    el.replaceChild(g, group);
    group = g;
    return svg;
  };

  svg.destroy = function () {
    // parentElement is not supported in IE11 for SVGElement.
    if (el && el.parentNode) {
      el.parentNode.removeChild(el);
    }

    el = null;
    group = null;
  };

  svg.size = function (opts) {
    if (opts) {
      var newRect = createRendererBox(opts);

      if (JSON.stringify(rect) !== JSON.stringify(newRect)) {
        hasChangedRect = true;
        rect = newRect;
      }
    }

    return rect;
  };

  return svg;
}
function rendererComponent$1(picasso) {
  picasso.renderer('svg', renderer$1);
}

var VNode = function VNode() {};

var picasso_esm_options = {};

var stack$1 = [];

var EMPTY_CHILDREN = [];

function picasso_esm_h(nodeName, attributes) {
	var children = EMPTY_CHILDREN,
	    lastSimple,
	    child,
	    simple,
	    i;
	for (i = arguments.length; i-- > 2;) {
		stack$1.push(arguments[i]);
	}
	if (attributes && attributes.children != null) {
		if (!stack$1.length) stack$1.push(attributes.children);
		delete attributes.children;
	}
	while (stack$1.length) {
		if ((child = stack$1.pop()) && child.pop !== undefined) {
			for (i = child.length; i--;) {
				stack$1.push(child[i]);
			}
		} else {
			if (typeof child === 'boolean') child = null;

			if (simple = typeof nodeName !== 'function') {
				if (child == null) child = '';else if (typeof child === 'number') child = String(child);else if (typeof child !== 'string') simple = false;
			}

			if (simple && lastSimple) {
				children[children.length - 1] += child;
			} else if (children === EMPTY_CHILDREN) {
				children = [child];
			} else {
				children.push(child);
			}

			lastSimple = simple;
		}
	}

	var p = new VNode();
	p.nodeName = nodeName;
	p.children = children;
	p.attributes = attributes == null ? undefined : attributes;
	p.key = attributes == null ? undefined : attributes.key;

	return p;
}

function extend$2(obj, props) {
  for (var i in props) {
    obj[i] = props[i];
  }return obj;
}

function applyRef(ref, value) {
  if (ref) {
    if (typeof ref == 'function') ref(value);else ref.current = value;
  }
}

var picasso_esm_defer = typeof Promise == 'function' ? Promise.resolve().then.bind(Promise.resolve()) : setTimeout;

var IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i;

var picasso_esm_items = [];

function enqueueRender(component) {
	if (!component._dirty && (component._dirty = true) && picasso_esm_items.push(component) == 1) {
		( picasso_esm_defer)(rerender);
	}
}

function rerender() {
	var p;
	while (p = picasso_esm_items.pop()) {
		if (p._dirty) renderComponent(p);
	}
}

function isSameNodeType(node, vnode, hydrating) {
	if (typeof vnode === 'string' || typeof vnode === 'number') {
		return node.splitText !== undefined;
	}
	if (typeof vnode.nodeName === 'string') {
		return !node._componentConstructor && isNamedNode(node, vnode.nodeName);
	}
	return hydrating || node._componentConstructor === vnode.nodeName;
}

function isNamedNode(node, nodeName) {
	return node.normalizedNodeName === nodeName || node.nodeName.toLowerCase() === nodeName.toLowerCase();
}

function getNodeProps(vnode) {
	var props = extend$2({}, vnode.attributes);
	props.children = vnode.children;

	var defaultProps = vnode.nodeName.defaultProps;
	if (defaultProps !== undefined) {
		for (var i in defaultProps) {
			if (props[i] === undefined) {
				props[i] = defaultProps[i];
			}
		}
	}

	return props;
}

function createNode(nodeName, isSvg) {
	var node = isSvg ? document.createElementNS('http://www.w3.org/2000/svg', nodeName) : document.createElement(nodeName);
	node.normalizedNodeName = nodeName;
	return node;
}

function removeNode(node) {
	var parentNode = node.parentNode;
	if (parentNode) parentNode.removeChild(node);
}

function setAccessor(node, name, old, value, isSvg) {
	if (name === 'className') name = 'class';

	if (name === 'key') ; else if (name === 'ref') {
		applyRef(old, null);
		applyRef(value, node);
	} else if (name === 'class' && !isSvg) {
		node.className = value || '';
	} else if (name === 'style') {
		if (!value || typeof value === 'string' || typeof old === 'string') {
			node.style.cssText = value || '';
		}
		if (value && typeof value === 'object') {
			if (typeof old !== 'string') {
				for (var i in old) {
					if (!(i in value)) node.style[i] = '';
				}
			}
			for (var i in value) {
				node.style[i] = typeof value[i] === 'number' && IS_NON_DIMENSIONAL.test(i) === false ? value[i] + 'px' : value[i];
			}
		}
	} else if (name === 'dangerouslySetInnerHTML') {
		if (value) node.innerHTML = value.__html || '';
	} else if (name[0] == 'o' && name[1] == 'n') {
		var useCapture = name !== (name = name.replace(/Capture$/, ''));
		name = name.toLowerCase().substring(2);
		if (value) {
			if (!old) node.addEventListener(name, eventProxy, useCapture);
		} else {
			node.removeEventListener(name, eventProxy, useCapture);
		}
		(node._listeners || (node._listeners = {}))[name] = value;
	} else if (name !== 'list' && name !== 'type' && !isSvg && name in node) {
		try {
			node[name] = value == null ? '' : value;
		} catch (e) {}
		if ((value == null || value === false) && name != 'spellcheck') node.removeAttribute(name);
	} else {
		var ns = isSvg && name !== (name = name.replace(/^xlink:?/, ''));

		if (value == null || value === false) {
			if (ns) node.removeAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase());else node.removeAttribute(name);
		} else if (typeof value !== 'function') {
			if (ns) node.setAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase(), value);else node.setAttribute(name, value);
		}
	}
}

function eventProxy(e) {
	return this._listeners[e.type]( e);
}

var mounts = [];

var diffLevel = 0;

var isSvgMode = false;

var hydrating = false;

function flushMounts() {
	var c;
	while (c = mounts.shift()) {
		if (c.componentDidMount) c.componentDidMount();
	}
}

function diff$2(dom, vnode, context, mountAll, parent, componentRoot) {
	if (!diffLevel++) {
		isSvgMode = parent != null && parent.ownerSVGElement !== undefined;

		hydrating = dom != null && !('__preactattr_' in dom);
	}

	var ret = idiff(dom, vnode, context, mountAll, componentRoot);

	if (parent && ret.parentNode !== parent) parent.appendChild(ret);

	if (! --diffLevel) {
		hydrating = false;

		if (!componentRoot) flushMounts();
	}

	return ret;
}

function idiff(dom, vnode, context, mountAll, componentRoot) {
	var out = dom,
	    prevSvgMode = isSvgMode;

	if (vnode == null || typeof vnode === 'boolean') vnode = '';

	if (typeof vnode === 'string' || typeof vnode === 'number') {
		if (dom && dom.splitText !== undefined && dom.parentNode && (!dom._component || componentRoot)) {
			if (dom.nodeValue != vnode) {
				dom.nodeValue = vnode;
			}
		} else {
			out = document.createTextNode(vnode);
			if (dom) {
				if (dom.parentNode) dom.parentNode.replaceChild(out, dom);
				recollectNodeTree(dom, true);
			}
		}

		out['__preactattr_'] = true;

		return out;
	}

	var vnodeName = vnode.nodeName;
	if (typeof vnodeName === 'function') {
		return buildComponentFromVNode(dom, vnode, context, mountAll);
	}

	isSvgMode = vnodeName === 'svg' ? true : vnodeName === 'foreignObject' ? false : isSvgMode;

	vnodeName = String(vnodeName);
	if (!dom || !isNamedNode(dom, vnodeName)) {
		out = createNode(vnodeName, isSvgMode);

		if (dom) {
			while (dom.firstChild) {
				out.appendChild(dom.firstChild);
			}
			if (dom.parentNode) dom.parentNode.replaceChild(out, dom);

			recollectNodeTree(dom, true);
		}
	}

	var fc = out.firstChild,
	    props = out['__preactattr_'],
	    vchildren = vnode.children;

	if (props == null) {
		props = out['__preactattr_'] = {};
		for (var a = out.attributes, i = a.length; i--;) {
			props[a[i].name] = a[i].value;
		}
	}

	if (!hydrating && vchildren && vchildren.length === 1 && typeof vchildren[0] === 'string' && fc != null && fc.splitText !== undefined && fc.nextSibling == null) {
		if (fc.nodeValue != vchildren[0]) {
			fc.nodeValue = vchildren[0];
		}
	} else if (vchildren && vchildren.length || fc != null) {
			innerDiffNode(out, vchildren, context, mountAll, hydrating || props.dangerouslySetInnerHTML != null);
		}

	diffAttributes(out, vnode.attributes, props);

	isSvgMode = prevSvgMode;

	return out;
}

function innerDiffNode(dom, vchildren, context, mountAll, isHydrating) {
	var originalChildren = dom.childNodes,
	    children = [],
	    keyed = {},
	    keyedLen = 0,
	    min = 0,
	    len = originalChildren.length,
	    childrenLen = 0,
	    vlen = vchildren ? vchildren.length : 0,
	    j,
	    c,
	    f,
	    vchild,
	    child;

	if (len !== 0) {
		for (var i = 0; i < len; i++) {
			var _child = originalChildren[i],
			    props = _child['__preactattr_'],
			    key = vlen && props ? _child._component ? _child._component.__key : props.key : null;
			if (key != null) {
				keyedLen++;
				keyed[key] = _child;
			} else if (props || (_child.splitText !== undefined ? isHydrating ? _child.nodeValue.trim() : true : isHydrating)) {
				children[childrenLen++] = _child;
			}
		}
	}

	if (vlen !== 0) {
		for (var i = 0; i < vlen; i++) {
			vchild = vchildren[i];
			child = null;

			var key = vchild.key;
			if (key != null) {
				if (keyedLen && keyed[key] !== undefined) {
					child = keyed[key];
					keyed[key] = undefined;
					keyedLen--;
				}
			} else if (min < childrenLen) {
					for (j = min; j < childrenLen; j++) {
						if (children[j] !== undefined && isSameNodeType(c = children[j], vchild, isHydrating)) {
							child = c;
							children[j] = undefined;
							if (j === childrenLen - 1) childrenLen--;
							if (j === min) min++;
							break;
						}
					}
				}

			child = idiff(child, vchild, context, mountAll);

			f = originalChildren[i];
			if (child && child !== dom && child !== f) {
				if (f == null) {
					dom.appendChild(child);
				} else if (child === f.nextSibling) {
					removeNode(f);
				} else {
					dom.insertBefore(child, f);
				}
			}
		}
	}

	if (keyedLen) {
		for (var i in keyed) {
			if (keyed[i] !== undefined) recollectNodeTree(keyed[i], false);
		}
	}

	while (min <= childrenLen) {
		if ((child = children[childrenLen--]) !== undefined) recollectNodeTree(child, false);
	}
}

function recollectNodeTree(node, unmountOnly) {
	var component = node._component;
	if (component) {
		unmountComponent(component);
	} else {
		if (node['__preactattr_'] != null) applyRef(node['__preactattr_'].ref, null);

		if (unmountOnly === false || node['__preactattr_'] == null) {
			removeNode(node);
		}

		removeChildren(node);
	}
}

function removeChildren(node) {
	node = node.lastChild;
	while (node) {
		var next = node.previousSibling;
		recollectNodeTree(node, true);
		node = next;
	}
}

function diffAttributes(dom, attrs, old) {
	var name;

	for (name in old) {
		if (!(attrs && attrs[name] != null) && old[name] != null) {
			setAccessor(dom, name, old[name], old[name] = undefined, isSvgMode);
		}
	}

	for (name in attrs) {
		if (name !== 'children' && name !== 'innerHTML' && (!(name in old) || attrs[name] !== (name === 'value' || name === 'checked' ? dom[name] : old[name]))) {
			setAccessor(dom, name, old[name], old[name] = attrs[name], isSvgMode);
		}
	}
}

var recyclerComponents = [];

function createComponent(Ctor, props, context) {
	var inst,
	    i = recyclerComponents.length;

	if (Ctor.prototype && Ctor.prototype.render) {
		inst = new Ctor(props, context);
		picasso_esm_Component.call(inst, props, context);
	} else {
		inst = new picasso_esm_Component(props, context);
		inst.constructor = Ctor;
		inst.render = doRender;
	}

	while (i--) {
		if (recyclerComponents[i].constructor === Ctor) {
			inst.nextBase = recyclerComponents[i].nextBase;
			recyclerComponents.splice(i, 1);
			return inst;
		}
	}

	return inst;
}

function doRender(props, state, context) {
	return this.constructor(props, context);
}

function setComponentProps(component, props, renderMode, context, mountAll) {
	if (component._disable) return;
	component._disable = true;

	component.__ref = props.ref;
	component.__key = props.key;
	delete props.ref;
	delete props.key;

	if (typeof component.constructor.getDerivedStateFromProps === 'undefined') {
		if (!component.base || mountAll) {
			if (component.componentWillMount) component.componentWillMount();
		} else if (component.componentWillReceiveProps) {
			component.componentWillReceiveProps(props, context);
		}
	}

	if (context && context !== component.context) {
		if (!component.prevContext) component.prevContext = component.context;
		component.context = context;
	}

	if (!component.prevProps) component.prevProps = component.props;
	component.props = props;

	component._disable = false;

	if (renderMode !== 0) {
		if (renderMode === 1 || picasso_esm_options.syncComponentUpdates !== false || !component.base) {
			renderComponent(component, 1, mountAll);
		} else {
			enqueueRender(component);
		}
	}

	applyRef(component.__ref, component);
}

function renderComponent(component, renderMode, mountAll, isChild) {
	if (component._disable) return;

	var props = component.props,
	    state = component.state,
	    context = component.context,
	    previousProps = component.prevProps || props,
	    previousState = component.prevState || state,
	    previousContext = component.prevContext || context,
	    isUpdate = component.base,
	    nextBase = component.nextBase,
	    initialBase = isUpdate || nextBase,
	    initialChildComponent = component._component,
	    skip = false,
	    snapshot = previousContext,
	    rendered,
	    inst,
	    cbase;

	if (component.constructor.getDerivedStateFromProps) {
		state = extend$2(extend$2({}, state), component.constructor.getDerivedStateFromProps(props, state));
		component.state = state;
	}

	if (isUpdate) {
		component.props = previousProps;
		component.state = previousState;
		component.context = previousContext;
		if (renderMode !== 2 && component.shouldComponentUpdate && component.shouldComponentUpdate(props, state, context) === false) {
			skip = true;
		} else if (component.componentWillUpdate) {
			component.componentWillUpdate(props, state, context);
		}
		component.props = props;
		component.state = state;
		component.context = context;
	}

	component.prevProps = component.prevState = component.prevContext = component.nextBase = null;
	component._dirty = false;

	if (!skip) {
		rendered = component.render(props, state, context);

		if (component.getChildContext) {
			context = extend$2(extend$2({}, context), component.getChildContext());
		}

		if (isUpdate && component.getSnapshotBeforeUpdate) {
			snapshot = component.getSnapshotBeforeUpdate(previousProps, previousState);
		}

		var childComponent = rendered && rendered.nodeName,
		    toUnmount,
		    base;

		if (typeof childComponent === 'function') {

			var childProps = getNodeProps(rendered);
			inst = initialChildComponent;

			if (inst && inst.constructor === childComponent && childProps.key == inst.__key) {
				setComponentProps(inst, childProps, 1, context, false);
			} else {
				toUnmount = inst;

				component._component = inst = createComponent(childComponent, childProps, context);
				inst.nextBase = inst.nextBase || nextBase;
				inst._parentComponent = component;
				setComponentProps(inst, childProps, 0, context, false);
				renderComponent(inst, 1, mountAll, true);
			}

			base = inst.base;
		} else {
			cbase = initialBase;

			toUnmount = initialChildComponent;
			if (toUnmount) {
				cbase = component._component = null;
			}

			if (initialBase || renderMode === 1) {
				if (cbase) cbase._component = null;
				base = diff$2(cbase, rendered, context, mountAll || !isUpdate, initialBase && initialBase.parentNode, true);
			}
		}

		if (initialBase && base !== initialBase && inst !== initialChildComponent) {
			var baseParent = initialBase.parentNode;
			if (baseParent && base !== baseParent) {
				baseParent.replaceChild(base, initialBase);

				if (!toUnmount) {
					initialBase._component = null;
					recollectNodeTree(initialBase, false);
				}
			}
		}

		if (toUnmount) {
			unmountComponent(toUnmount);
		}

		component.base = base;
		if (base && !isChild) {
			var componentRef = component,
			    t = component;
			while (t = t._parentComponent) {
				(componentRef = t).base = base;
			}
			base._component = componentRef;
			base._componentConstructor = componentRef.constructor;
		}
	}

	if (!isUpdate || mountAll) {
		mounts.push(component);
	} else if (!skip) {

		if (component.componentDidUpdate) {
			component.componentDidUpdate(previousProps, previousState, snapshot);
		}
	}

	while (component._renderCallbacks.length) {
		component._renderCallbacks.pop().call(component);
	}if (!diffLevel && !isChild) flushMounts();
}

function buildComponentFromVNode(dom, vnode, context, mountAll) {
	var c = dom && dom._component,
	    originalComponent = c,
	    oldDom = dom,
	    isDirectOwner = c && dom._componentConstructor === vnode.nodeName,
	    isOwner = isDirectOwner,
	    props = getNodeProps(vnode);
	while (c && !isOwner && (c = c._parentComponent)) {
		isOwner = c.constructor === vnode.nodeName;
	}

	if (c && isOwner && (!mountAll || c._component)) {
		setComponentProps(c, props, 3, context, mountAll);
		dom = c.base;
	} else {
		if (originalComponent && !isDirectOwner) {
			unmountComponent(originalComponent);
			dom = oldDom = null;
		}

		c = createComponent(vnode.nodeName, props, context);
		if (dom && !c.nextBase) {
			c.nextBase = dom;

			oldDom = null;
		}
		setComponentProps(c, props, 1, context, mountAll);
		dom = c.base;

		if (oldDom && dom !== oldDom) {
			oldDom._component = null;
			recollectNodeTree(oldDom, false);
		}
	}

	return dom;
}

function unmountComponent(component) {

	var base = component.base;

	component._disable = true;

	if (component.componentWillUnmount) component.componentWillUnmount();

	component.base = null;

	var inner = component._component;
	if (inner) {
		unmountComponent(inner);
	} else if (base) {
		if (base['__preactattr_'] != null) applyRef(base['__preactattr_'].ref, null);

		component.nextBase = base;

		removeNode(base);
		recyclerComponents.push(component);

		removeChildren(base);
	}

	applyRef(component.__ref, null);
}

function picasso_esm_Component(props, context) {
	this._dirty = true;

	this.context = context;

	this.props = props;

	this.state = this.state || {};

	this._renderCallbacks = [];
}

extend$2(picasso_esm_Component.prototype, {
	setState: function setState(state, callback) {
		if (!this.prevState) this.prevState = this.state;
		this.state = extend$2(extend$2({}, this.state), typeof state === 'function' ? state(this.state, this.props) : state);
		if (callback) this._renderCallbacks.push(callback);
		enqueueRender(this);
	},
	forceUpdate: function forceUpdate(callback) {
		if (callback) this._renderCallbacks.push(callback);
		renderComponent(this, 2);
	},
	render: function render() {}
});

function render$9(vnode, parent, merge) {
  return diff$2(merge, vnode, {}, false, parent, false);
}

function renderer$2() {
  var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var _opts$createElement = opts.createElement,
      createElement = _opts$createElement === void 0 ? document.createElement.bind(document) : _opts$createElement;
  var el;
  var rect = createRendererBox();
  var dNode;
  var dom = create$n();

  dom.element = function () {
    return el;
  };

  dom.root = function () {
    return el;
  };

  dom.appendTo = function (element) {
    if (!el) {
      el = createElement('div');
      el.style.position = 'absolute';
      el.style['-webkit-font-smoothing'] = 'antialiased';
      el.style['-moz-osx-font-smoothing'] = 'antialiased';
      el.style.pointerEvents = 'none';
    }

    element.appendChild(el);
    return el;
  };

  dom.render = function (nodes) {
    if (!el) {
      return false;
    }

    el.style.left = "".concat(rect.computedPhysical.x, "px");
    el.style.top = "".concat(rect.computedPhysical.y, "px");
    el.style.width = "".concat(rect.computedPhysical.width, "px");
    el.style.height = "".concat(rect.computedPhysical.height, "px");
    var vNode;

    if (Array.isArray(nodes)) {
      vNode = picasso_esm_h("div", null, nodes);
    } else {
      vNode = nodes;
    }

    dNode = render$9(vNode, el, dNode);
    return true;
  };

  dom.renderArgs = [picasso_esm_h]; // Arguments to render functions using the DOM renderer

  dom.clear = function () {
    if (el) {
      var first = el.firstChild;

      while (first) {
        el.removeChild(first);
        first = el.firstChild;
      }

      dNode = null;
    }

    return dom;
  };

  dom.destroy = function () {
    if (el && el.parentElement) {
      el.parentElement.removeChild(el);
    }

    el = null;
    dNode = null;
  };

  dom.size = function (inner) {
    if (inner) {
      rect = createRendererBox(inner);
    }

    return rect;
  };

  return dom;
}

function rendererComponent$2(picasso) {
  picasso.renderer('dom', renderer$2);
}

var renderers = [rendererComponent$1, rendererComponent, rendererComponent$2];

var scales = [];

var LOG_LEVEL = {
  OFF: 0,
  ERROR: 1,
  WARN: 2,
  INFO: 3,
  DEBUG: 4
};

var loggerFn = function loggerFn() {
  var _LOG_FN;

  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$level = _ref.level,
      level = _ref$level === void 0 ? LOG_LEVEL.OFF : _ref$level,
      _ref$pipe = _ref.pipe,
      pipe = _ref$pipe === void 0 ? console : _ref$pipe;

  var currentlevel = level;
  var LOG_FN = (_LOG_FN = {}, dist_picasso_esm_defineProperty(_LOG_FN, LOG_LEVEL.OFF, function () {}), dist_picasso_esm_defineProperty(_LOG_FN, LOG_LEVEL.ERROR, function () {
    return pipe.error.apply(pipe, arguments);
  }), dist_picasso_esm_defineProperty(_LOG_FN, LOG_LEVEL.WARN, function () {
    return pipe.warn.apply(pipe, arguments);
  }), dist_picasso_esm_defineProperty(_LOG_FN, LOG_LEVEL.INFO, function () {
    return pipe.info.apply(pipe, arguments);
  }), dist_picasso_esm_defineProperty(_LOG_FN, LOG_LEVEL.DEBUG, function () {
    return pipe.log.apply(pipe, arguments);
  }), _LOG_FN);

  var log = function log(lev) {
    if (!lev || currentlevel < lev) {
      return;
    }

    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args[_key - 1] = arguments[_key];
    }

    (LOG_FN[lev] || LOG_FN[LOG_LEVEL.DEBUG]).apply(void 0, args);
  };
  /**
   * @typedef {object} logger
   * @private
   */


  return (
    /** @lends logger */
    {
      /**
       * Log a message
       * @param {number} lev - The log level
       * @param {...any} args
       * @kind function
       */
      log: log,

      /**
       * Log an error message
       * @param {...any} args
       */
      error: function error() {
        for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
          args[_key2] = arguments[_key2];
        }

        return log.apply(void 0, [LOG_LEVEL.ERROR].concat(args));
      },

      /**
       * Log a warning message
       * @param {...any} args
       */
      warn: function warn() {
        for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
          args[_key3] = arguments[_key3];
        }

        return log.apply(void 0, [LOG_LEVEL.WARN].concat(args));
      },

      /**
       * Log an info message
       * @param {...any} args
       */
      info: function info() {
        for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
          args[_key4] = arguments[_key4];
        }

        return log.apply(void 0, [LOG_LEVEL.INFO].concat(args));
      },

      /**
       * Log a debug message
       * @param {...any} args
       */
      debug: function debug() {
        for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
          args[_key5] = arguments[_key5];
        }

        return log.apply(void 0, [LOG_LEVEL.DEBUG].concat(args));
      },

      /**
       * Set the current log level
       * @param {number} lev - The log level
       */
      level: function level(lev) {
        if (typeof lev === 'number') {
          currentlevel = lev;
        }

        return currentlevel;
      },
      LOG_LEVEL: LOG_LEVEL
    }
  );
};

var palettes = [{
  key: 'categorical',
  colors: [['#a54343', '#d76c6c', '#ec983d', '#ecc43d', '#f9ec86', '#cbe989', '#70ba6e', '#578b60', '#79d69f', '#26a0a7', '#138185', '#65d3da'] // breeze colors
  ]
}, {
  key: 'diverging',
  colors: [['#3d52a1', '#3a89c9', '#77b7e5', '#b4ddf7', '#e6f5fe', '#ffe3aa', '#f9bd7e', '#ed875e', '#d24d3e', '#ae1c3e']]
}, {
  key: 'sequential',
  colors: [['rgb(180,221,212)', 'rgb(34, 83, 90)']]
}];
/* eslint quote-props: 0 */

var picasso_esm_style = {
  // -- FOUNDATION --
  // fonts
  '$font-family': "'Source Sans Pro', Arial, sans-serif",
  '$font-size': '12px',
  '$line-height': '16px',
  '$font-size--l': '16px',
  // base grays
  '$gray-100': '#ffffff',
  '$gray-98': '#f9f9f9',
  '$gray-95': '#f2f2f2',
  '$gray-90': '#e6e6e6',
  '$gray-35': '#595959',
  '$gray-30': '#4d4d4d',
  '$gray-25': '#404040',
  '$gray-20': '#333333',
  // borders
  '$border-95': 'rgba(255, 255, 255, 0.05)',
  '$border-90': 'rgba(255, 255, 255, 0.1)',
  '$border-80': 'rgba(255, 255, 255, 0.2)',
  '$border-20': 'rgba(0, 0, 0, 0.2)',
  '$border-10': 'rgba(0, 0, 0, 0.1)',
  '$border-5': 'rgba(0, 0, 0, 0.05)',
  // primary colors
  '$primary-blue': '#3F8AB3',
  '$primary-green': '#6CB33F',
  '$primary-red': '#DC423F',
  '$primary-orange': '#EF960F',
  // spacing
  '$spacing--s': 4,
  '$spacing': 8,
  '$spacing--l': 12,
  // -------------------------
  // -- ALIASES --
  '$font-color': '$gray-35',
  '$font-color--inverted': '$gray-90',
  '$guide-color': '$gray-90',
  '$guide-color--inverted': '$gray-35',
  '$border': '$border-80',
  '$border--inverted': '$border-10',
  // -------------------------
  // -- MIXINS --
  // data points
  '$shape': {
    // data shape
    fill: '$primary-blue',
    strokeWidth: 1,
    stroke: '$border'
  },
  '$shape-outline': {
    // data shape which usually does not have a fill, e.g. the line in a linechart
    stroke: '$primary-blue',
    strokeWidth: 2
  },
  '$shape-guide': {
    // lines that somehow belongs to a data shape, e.g. whiskers in a boxplot
    stroke: '$guide-color',
    strokeWidth: 1
  },
  '$shape-guide--inverted': {
    '@extend': '$shape-guide',
    stroke: '$guide-color--inverted'
  },
  '$label': {
    fontSize: '$font-size',
    fontFamily: '$font-family',
    fill: '$font-color'
  },
  '$label--inverted': {
    '$extend': '$label',
    fill: '$font-color--inverted'
  },
  // user interface
  '$label-overlay': {
    // e.g. selection range bubble
    fontSize: '$font-size--l',
    fontFamily: '$font-family',
    fill: '$gray-100',
    // background fill
    color: '$font-color',
    stroke: '$guide-color--inverted',
    strokeWidth: 1,
    borderRadius: 4
  },
  '$title': {
    '@extend': '$label',
    fontSize: '$font-size--l'
  },
  '$guide-line': {
    strokeWidth: 1,
    stroke: '$guide-color'
  },
  '$guide-line--minor': {
    strokeWidth: 1,
    stroke: '$gray-95' // needs alias

  },
  '$padding--s': {
    left: '$spacing--s',
    right: '$spacing--s',
    top: '$spacing--s',
    bottom: '$spacing--s'
  },
  '$padding': {
    left: '$spacing',
    right: '$spacing',
    top: '$spacing',
    bottom: '$spacing'
  },
  '$selection-area-target': {
    fill: '$primary-green',
    strokeWidth: 0,
    opacity: 0.2
  }
};

function usePlugin(plugin) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var api = arguments.length > 2 ? arguments[2] : undefined;
  plugin(api, options);
}

function picasso_esm_pic() {
  var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var registries = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var logger = loggerFn(config.logger);
  /**
   * @lends picassojs
   */

  var regis = {
    // -- registries --

    /**
     * Component registry
     * @type {registry}
     */
    component: registryFactory(registries.component, 'component', logger),

    /**
     * Data registry
     * @type {registry}
     */
    data: registryFactory(registries.data, 'data', logger),

    /**
     * Formatter registry
     * @type {registry}
     */
    formatter: registryFactory(registries.formatter, 'formatter', logger),

    /**
     * Interaction registry
     * @type {registry}
     */
    interaction: registryFactory(registries.interaction, 'interaction', logger),

    /**
     * Renderer registry
     * @type {registry}
     */
    renderer: rendererRegistry(registries.renderer),

    /**
     * Scale registry
     * @type {registry}
     */
    scale: registryFactory(registries.scale, 'scale', logger),

    /**
     * Symbol registry
     * @type {registry}
     * @private
     */
    symbol: registryFactory(registries.symbol, 'symbol', logger),
    // -- misc --

    /**
     * log some some stuff
     * @type {logger}
     * @private
     */
    logger: logger
  };

  if (config.renderer && config.renderer.prio) {
    regis.renderer.default(config.renderer.prio[0]);
  }
  /**
   * picasso.js entry point
   * @experimental
   * @entry
   * @alias picassojs
   * @param {object} cfg
   * @param {object} cfg.renderer
   * @param {Array<string>} cfg.renderer.prio
   * @param {object} cfg.logger
   * @param {number} cfg.logger.level
   * @param {object} cfg.style
   * @param {Array<object>} cfg.palettes
   * @returns {picassojs}
   */


  function picassojs() {
    var cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var cc = {
      palettes: config.palettes.concat(cfg.palettes || []),
      style: extend({}, config.style, cfg.style),
      logger: cfg.logger || config.logger,
      renderer: cfg.renderer || config.renderer
    };
    return picasso_esm_pic(cc, regis);
  }
  /**
   * @callback picassojs~plugin
   * @param {picassojs~registries} registries
   * @param {object} options
   */

  /**
   * @param {picassojs~plugin} plugin
   * @param {object} [options]
   */


  picassojs.use = function (plugin) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    return usePlugin(plugin, options, regis);
  };
  /**
   * @param {chart-definition} definition
   * @returns {chart}
   */


  picassojs.chart = function (definition) {
    return chartFn(definition, {
      registries: regis,
      logger: logger,
      style: config.style,
      palettes: config.palettes
    });
  };

  picassojs.config = function () {
    return config;
  };

  Object.keys(regis).forEach(function (key) {
    picassojs[key] = regis[key];
  });
  /**
   * picasso.js version
   * @type {string}
   */

  picassojs.version = about.version;
  return picassojs;
}

var picasso_esm_p = picasso_esm_pic({
  renderer: {
    prio: ['svg', 'canvas']
  },
  logger: {
    level: 0
  },
  style: picasso_esm_style,
  palettes: palettes
}, {
  component: componentRegistry,
  data: dataRegistry,
  formatter: formatterRegistry,
  interaction: reg$1,
  renderer: rendererRegistry(),
  scale: scaleRegistry,
  symbol: parentReg
});
components.forEach(picasso_esm_p.use);
renderers.forEach(picasso_esm_p.use);
scales.forEach(picasso_esm_p.use);

/* harmony default export */ var picasso_esm = (picasso_esm_p);
//# sourceMappingURL=picasso.esm.js.map

// EXTERNAL MODULE: ./node_modules/picasso-plugin-hammer/dist/picasso-hammer.esm.js
var picasso_hammer_esm = __webpack_require__(72);

// EXTERNAL MODULE: ./node_modules/picasso-plugin-q/dist/picasso-q.esm.js
var picasso_q_esm = __webpack_require__(73);

// CONCATENATED MODULE: ./node_modules/d3-ease/src/linear.js
function linear_linear(t) {
  return +t;
}

// CONCATENATED MODULE: ./node_modules/d3-ease/src/quad.js
function quadIn(t) {
  return t * t;
}

function quadOut(t) {
  return t * (2 - t);
}

function quadInOut(t) {
  return ((t *= 2) <= 1 ? t * t : --t * (2 - t) + 1) / 2;
}

// CONCATENATED MODULE: ./node_modules/d3-ease/src/cubic.js
function cubicIn(t) {
  return t * t * t;
}

function cubicOut(t) {
  return --t * t * t + 1;
}

function cubic_cubicInOut(t) {
  return ((t *= 2) <= 1 ? t * t * t : (t -= 2) * t * t + 2) / 2;
}

// CONCATENATED MODULE: ./node_modules/d3-ease/src/poly.js
var poly_exponent = 3;

var polyIn = (function custom(e) {
  e = +e;

  function polyIn(t) {
    return Math.pow(t, e);
  }

  polyIn.exponent = custom;

  return polyIn;
})(poly_exponent);

var polyOut = (function custom(e) {
  e = +e;

  function polyOut(t) {
    return 1 - Math.pow(1 - t, e);
  }

  polyOut.exponent = custom;

  return polyOut;
})(poly_exponent);

var polyInOut = (function custom(e) {
  e = +e;

  function polyInOut(t) {
    return ((t *= 2) <= 1 ? Math.pow(t, e) : 2 - Math.pow(2 - t, e)) / 2;
  }

  polyInOut.exponent = custom;

  return polyInOut;
})(poly_exponent);

// CONCATENATED MODULE: ./node_modules/d3-ease/src/sin.js
var sin_pi = Math.PI,
    sin_halfPi = sin_pi / 2;

function sinIn(t) {
  return 1 - Math.cos(t * sin_halfPi);
}

function sinOut(t) {
  return Math.sin(t * sin_halfPi);
}

function sinInOut(t) {
  return (1 - Math.cos(sin_pi * t)) / 2;
}

// CONCATENATED MODULE: ./node_modules/d3-ease/src/exp.js
function expIn(t) {
  return Math.pow(2, 10 * t - 10);
}

function expOut(t) {
  return 1 - Math.pow(2, -10 * t);
}

function expInOut(t) {
  return ((t *= 2) <= 1 ? Math.pow(2, 10 * t - 10) : 2 - Math.pow(2, 10 - 10 * t)) / 2;
}

// CONCATENATED MODULE: ./node_modules/d3-ease/src/circle.js
function circleIn(t) {
  return 1 - Math.sqrt(1 - t * t);
}

function circleOut(t) {
  return Math.sqrt(1 - --t * t);
}

function circleInOut(t) {
  return ((t *= 2) <= 1 ? 1 - Math.sqrt(1 - t * t) : Math.sqrt(1 - (t -= 2) * t) + 1) / 2;
}

// CONCATENATED MODULE: ./node_modules/d3-ease/src/bounce.js
var b1 = 4 / 11,
    b2 = 6 / 11,
    b3 = 8 / 11,
    b4 = 3 / 4,
    b5 = 9 / 11,
    b6 = 10 / 11,
    b7 = 15 / 16,
    b8 = 21 / 22,
    b9 = 63 / 64,
    b0 = 1 / b1 / b1;

function bounceIn(t) {
  return 1 - bounceOut(1 - t);
}

function bounceOut(t) {
  return (t = +t) < b1 ? b0 * t * t : t < b3 ? b0 * (t -= b2) * t + b4 : t < b6 ? b0 * (t -= b5) * t + b7 : b0 * (t -= b8) * t + b9;
}

function bounceInOut(t) {
  return ((t *= 2) <= 1 ? 1 - bounceOut(1 - t) : bounceOut(t - 1) + 1) / 2;
}

// CONCATENATED MODULE: ./node_modules/d3-ease/src/back.js
var overshoot = 1.70158;

var backIn = (function custom(s) {
  s = +s;

  function backIn(t) {
    return t * t * ((s + 1) * t - s);
  }

  backIn.overshoot = custom;

  return backIn;
})(overshoot);

var backOut = (function custom(s) {
  s = +s;

  function backOut(t) {
    return --t * t * ((s + 1) * t + s) + 1;
  }

  backOut.overshoot = custom;

  return backOut;
})(overshoot);

var backInOut = (function custom(s) {
  s = +s;

  function backInOut(t) {
    return ((t *= 2) < 1 ? t * t * ((s + 1) * t - s) : (t -= 2) * t * ((s + 1) * t + s) + 2) / 2;
  }

  backInOut.overshoot = custom;

  return backInOut;
})(overshoot);

// CONCATENATED MODULE: ./node_modules/d3-ease/src/elastic.js
var elastic_tau = 2 * Math.PI,
    elastic_amplitude = 1,
    elastic_period = 0.3;

var elasticIn = (function custom(a, p) {
  var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= elastic_tau);

  function elasticIn(t) {
    return a * Math.pow(2, 10 * --t) * Math.sin((s - t) / p);
  }

  elasticIn.amplitude = function(a) { return custom(a, p * elastic_tau); };
  elasticIn.period = function(p) { return custom(a, p); };

  return elasticIn;
})(elastic_amplitude, elastic_period);

var elastic_elasticOut = (function custom(a, p) {
  var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= elastic_tau);

  function elasticOut(t) {
    return 1 - a * Math.pow(2, -10 * (t = +t)) * Math.sin((t + s) / p);
  }

  elasticOut.amplitude = function(a) { return custom(a, p * elastic_tau); };
  elasticOut.period = function(p) { return custom(a, p); };

  return elasticOut;
})(elastic_amplitude, elastic_period);

var elasticInOut = (function custom(a, p) {
  var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= elastic_tau);

  function elasticInOut(t) {
    return ((t = t * 2 - 1) < 0
        ? a * Math.pow(2, 10 * t) * Math.sin((s - t) / p)
        : 2 - a * Math.pow(2, -10 * t) * Math.sin((s + t) / p)) / 2;
  }

  elasticInOut.amplitude = function(a) { return custom(a, p * elastic_tau); };
  elasticInOut.period = function(p) { return custom(a, p); };

  return elasticInOut;
})(elastic_amplitude, elastic_period);

// CONCATENATED MODULE: ./node_modules/d3-ease/src/index.js




















// CONCATENATED MODULE: ./node_modules/d3-timer/src/timer.js
var timer_frame = 0, // is an animation frame pending?
    timer_timeout = 0, // is a timeout pending?
    timer_interval = 0, // are any timers active?
    pokeDelay = 1000, // how frequently we check for clock skew
    taskHead,
    taskTail,
    clockLast = 0,
    clockNow = 0,
    clockSkew = 0,
    clock = typeof performance === "object" && performance.now ? performance : Date,
    setFrame = typeof window === "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f) { setTimeout(f, 17); };

function now() {
  return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew);
}

function clearNow() {
  clockNow = 0;
}

function Timer() {
  this._call =
  this._time =
  this._next = null;
}

Timer.prototype = timer_timer.prototype = {
  constructor: Timer,
  restart: function(callback, delay, time) {
    if (typeof callback !== "function") throw new TypeError("callback is not a function");
    time = (time == null ? now() : +time) + (delay == null ? 0 : +delay);
    if (!this._next && taskTail !== this) {
      if (taskTail) taskTail._next = this;
      else taskHead = this;
      taskTail = this;
    }
    this._call = callback;
    this._time = time;
    sleep();
  },
  stop: function() {
    if (this._call) {
      this._call = null;
      this._time = Infinity;
      sleep();
    }
  }
};

function timer_timer(callback, delay, time) {
  var t = new Timer;
  t.restart(callback, delay, time);
  return t;
}

function timerFlush() {
  now(); // Get the current time, if not already set.
  ++timer_frame; // Pretend we’ve set an alarm, if we haven’t already.
  var t = taskHead, e;
  while (t) {
    if ((e = clockNow - t._time) >= 0) t._call.call(null, e);
    t = t._next;
  }
  --timer_frame;
}

function wake() {
  clockNow = (clockLast = clock.now()) + clockSkew;
  timer_frame = timer_timeout = 0;
  try {
    timerFlush();
  } finally {
    timer_frame = 0;
    nap();
    clockNow = 0;
  }
}

function poke() {
  var now = clock.now(), delay = now - clockLast;
  if (delay > pokeDelay) clockSkew -= delay, clockLast = now;
}

function nap() {
  var t0, t1 = taskHead, t2, time = Infinity;
  while (t1) {
    if (t1._call) {
      if (time > t1._time) time = t1._time;
      t0 = t1, t1 = t1._next;
    } else {
      t2 = t1._next, t1._next = null;
      t1 = t0 ? t0._next = t2 : taskHead = t2;
    }
  }
  taskTail = t0;
  sleep(time);
}

function sleep(time) {
  if (timer_frame) return; // Soonest alarm already set, or will be.
  if (timer_timeout) timer_timeout = clearTimeout(timer_timeout);
  var delay = time - clockNow; // Strictly less than if we recomputed clockNow.
  if (delay > 24) {
    if (time < Infinity) timer_timeout = setTimeout(wake, time - clock.now() - clockSkew);
    if (timer_interval) timer_interval = clearInterval(timer_interval);
  } else {
    if (!timer_interval) clockLast = clock.now(), timer_interval = setInterval(poke, pokeDelay);
    timer_frame = 1, setFrame(wake);
  }
}

// CONCATENATED MODULE: ./node_modules/d3-color/src/define.js
/* harmony default export */ var src_define = (function(constructor, factory, prototype) {
  constructor.prototype = factory.prototype = prototype;
  prototype.constructor = constructor;
});

function define_extend(parent, definition) {
  var prototype = Object.create(parent.prototype);
  for (var key in definition) prototype[key] = definition[key];
  return prototype;
}

// CONCATENATED MODULE: ./node_modules/d3-color/src/color.js


function color_Color() {}

var color_darker = 0.7;
var color_brighter = 1 / color_darker;

var color_reI = "\\s*([+-]?\\d+)\\s*",
    color_reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",
    color_reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",
    reHex = /^#([0-9a-f]{3,8})$/,
    color_reRgbInteger = new RegExp("^rgb\\(" + [color_reI, color_reI, color_reI] + "\\)$"),
    color_reRgbPercent = new RegExp("^rgb\\(" + [color_reP, color_reP, color_reP] + "\\)$"),
    color_reRgbaInteger = new RegExp("^rgba\\(" + [color_reI, color_reI, color_reI, color_reN] + "\\)$"),
    color_reRgbaPercent = new RegExp("^rgba\\(" + [color_reP, color_reP, color_reP, color_reN] + "\\)$"),
    color_reHslPercent = new RegExp("^hsl\\(" + [color_reN, color_reP, color_reP] + "\\)$"),
    color_reHslaPercent = new RegExp("^hsla\\(" + [color_reN, color_reP, color_reP, color_reN] + "\\)$");

var color_named = {
  aliceblue: 0xf0f8ff,
  antiquewhite: 0xfaebd7,
  aqua: 0x00ffff,
  aquamarine: 0x7fffd4,
  azure: 0xf0ffff,
  beige: 0xf5f5dc,
  bisque: 0xffe4c4,
  black: 0x000000,
  blanchedalmond: 0xffebcd,
  blue: 0x0000ff,
  blueviolet: 0x8a2be2,
  brown: 0xa52a2a,
  burlywood: 0xdeb887,
  cadetblue: 0x5f9ea0,
  chartreuse: 0x7fff00,
  chocolate: 0xd2691e,
  coral: 0xff7f50,
  cornflowerblue: 0x6495ed,
  cornsilk: 0xfff8dc,
  crimson: 0xdc143c,
  cyan: 0x00ffff,
  darkblue: 0x00008b,
  darkcyan: 0x008b8b,
  darkgoldenrod: 0xb8860b,
  darkgray: 0xa9a9a9,
  darkgreen: 0x006400,
  darkgrey: 0xa9a9a9,
  darkkhaki: 0xbdb76b,
  darkmagenta: 0x8b008b,
  darkolivegreen: 0x556b2f,
  darkorange: 0xff8c00,
  darkorchid: 0x9932cc,
  darkred: 0x8b0000,
  darksalmon: 0xe9967a,
  darkseagreen: 0x8fbc8f,
  darkslateblue: 0x483d8b,
  darkslategray: 0x2f4f4f,
  darkslategrey: 0x2f4f4f,
  darkturquoise: 0x00ced1,
  darkviolet: 0x9400d3,
  deeppink: 0xff1493,
  deepskyblue: 0x00bfff,
  dimgray: 0x696969,
  dimgrey: 0x696969,
  dodgerblue: 0x1e90ff,
  firebrick: 0xb22222,
  floralwhite: 0xfffaf0,
  forestgreen: 0x228b22,
  fuchsia: 0xff00ff,
  gainsboro: 0xdcdcdc,
  ghostwhite: 0xf8f8ff,
  gold: 0xffd700,
  goldenrod: 0xdaa520,
  gray: 0x808080,
  green: 0x008000,
  greenyellow: 0xadff2f,
  grey: 0x808080,
  honeydew: 0xf0fff0,
  hotpink: 0xff69b4,
  indianred: 0xcd5c5c,
  indigo: 0x4b0082,
  ivory: 0xfffff0,
  khaki: 0xf0e68c,
  lavender: 0xe6e6fa,
  lavenderblush: 0xfff0f5,
  lawngreen: 0x7cfc00,
  lemonchiffon: 0xfffacd,
  lightblue: 0xadd8e6,
  lightcoral: 0xf08080,
  lightcyan: 0xe0ffff,
  lightgoldenrodyellow: 0xfafad2,
  lightgray: 0xd3d3d3,
  lightgreen: 0x90ee90,
  lightgrey: 0xd3d3d3,
  lightpink: 0xffb6c1,
  lightsalmon: 0xffa07a,
  lightseagreen: 0x20b2aa,
  lightskyblue: 0x87cefa,
  lightslategray: 0x778899,
  lightslategrey: 0x778899,
  lightsteelblue: 0xb0c4de,
  lightyellow: 0xffffe0,
  lime: 0x00ff00,
  limegreen: 0x32cd32,
  linen: 0xfaf0e6,
  magenta: 0xff00ff,
  maroon: 0x800000,
  mediumaquamarine: 0x66cdaa,
  mediumblue: 0x0000cd,
  mediumorchid: 0xba55d3,
  mediumpurple: 0x9370db,
  mediumseagreen: 0x3cb371,
  mediumslateblue: 0x7b68ee,
  mediumspringgreen: 0x00fa9a,
  mediumturquoise: 0x48d1cc,
  mediumvioletred: 0xc71585,
  midnightblue: 0x191970,
  mintcream: 0xf5fffa,
  mistyrose: 0xffe4e1,
  moccasin: 0xffe4b5,
  navajowhite: 0xffdead,
  navy: 0x000080,
  oldlace: 0xfdf5e6,
  olive: 0x808000,
  olivedrab: 0x6b8e23,
  orange: 0xffa500,
  orangered: 0xff4500,
  orchid: 0xda70d6,
  palegoldenrod: 0xeee8aa,
  palegreen: 0x98fb98,
  paleturquoise: 0xafeeee,
  palevioletred: 0xdb7093,
  papayawhip: 0xffefd5,
  peachpuff: 0xffdab9,
  peru: 0xcd853f,
  pink: 0xffc0cb,
  plum: 0xdda0dd,
  powderblue: 0xb0e0e6,
  purple: 0x800080,
  rebeccapurple: 0x663399,
  red: 0xff0000,
  rosybrown: 0xbc8f8f,
  royalblue: 0x4169e1,
  saddlebrown: 0x8b4513,
  salmon: 0xfa8072,
  sandybrown: 0xf4a460,
  seagreen: 0x2e8b57,
  seashell: 0xfff5ee,
  sienna: 0xa0522d,
  silver: 0xc0c0c0,
  skyblue: 0x87ceeb,
  slateblue: 0x6a5acd,
  slategray: 0x708090,
  slategrey: 0x708090,
  snow: 0xfffafa,
  springgreen: 0x00ff7f,
  steelblue: 0x4682b4,
  tan: 0xd2b48c,
  teal: 0x008080,
  thistle: 0xd8bfd8,
  tomato: 0xff6347,
  turquoise: 0x40e0d0,
  violet: 0xee82ee,
  wheat: 0xf5deb3,
  white: 0xffffff,
  whitesmoke: 0xf5f5f5,
  yellow: 0xffff00,
  yellowgreen: 0x9acd32
};

src_define(color_Color, color_color, {
  copy: function(channels) {
    return Object.assign(new this.constructor, this, channels);
  },
  displayable: function() {
    return this.rgb().displayable();
  },
  hex: color_formatHex, // Deprecated! Use color.formatHex.
  formatHex: color_formatHex,
  formatHsl: color_formatHsl,
  formatRgb: color_formatRgb,
  toString: color_formatRgb
});

function color_formatHex() {
  return this.rgb().formatHex();
}

function color_formatHsl() {
  return color_hslConvert(this).formatHsl();
}

function color_formatRgb() {
  return this.rgb().formatRgb();
}

function color_color(format) {
  var m, l;
  format = (format + "").trim().toLowerCase();
  return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? color_rgbn(m) // #ff0000
      : l === 3 ? new color_Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00
      : l === 8 ? new color_Rgb(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000
      : l === 4 ? new color_Rgb((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000
      : null) // invalid hex
      : (m = color_reRgbInteger.exec(format)) ? new color_Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
      : (m = color_reRgbPercent.exec(format)) ? new color_Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
      : (m = color_reRgbaInteger.exec(format)) ? color_rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
      : (m = color_reRgbaPercent.exec(format)) ? color_rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
      : (m = color_reHslPercent.exec(format)) ? color_hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
      : (m = color_reHslaPercent.exec(format)) ? color_hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
      : color_named.hasOwnProperty(format) ? color_rgbn(color_named[format]) // eslint-disable-line no-prototype-builtins
      : format === "transparent" ? new color_Rgb(NaN, NaN, NaN, 0)
      : null;
}

function color_rgbn(n) {
  return new color_Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
}

function color_rgba(r, g, b, a) {
  if (a <= 0) r = g = b = NaN;
  return new color_Rgb(r, g, b, a);
}

function color_rgbConvert(o) {
  if (!(o instanceof color_Color)) o = color_color(o);
  if (!o) return new color_Rgb;
  o = o.rgb();
  return new color_Rgb(o.r, o.g, o.b, o.opacity);
}

function color_rgb(r, g, b, opacity) {
  return arguments.length === 1 ? color_rgbConvert(r) : new color_Rgb(r, g, b, opacity == null ? 1 : opacity);
}

function color_Rgb(r, g, b, opacity) {
  this.r = +r;
  this.g = +g;
  this.b = +b;
  this.opacity = +opacity;
}

src_define(color_Rgb, color_rgb, define_extend(color_Color, {
  brighter: function(k) {
    k = k == null ? color_brighter : Math.pow(color_brighter, k);
    return new color_Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? color_darker : Math.pow(color_darker, k);
    return new color_Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  rgb: function() {
    return this;
  },
  displayable: function() {
    return (-0.5 <= this.r && this.r < 255.5)
        && (-0.5 <= this.g && this.g < 255.5)
        && (-0.5 <= this.b && this.b < 255.5)
        && (0 <= this.opacity && this.opacity <= 1);
  },
  hex: rgb_formatHex, // Deprecated! Use color.formatHex.
  formatHex: rgb_formatHex,
  formatRgb: rgb_formatRgb,
  toString: rgb_formatRgb
}));

function rgb_formatHex() {
  return "#" + color_hex(this.r) + color_hex(this.g) + color_hex(this.b);
}

function rgb_formatRgb() {
  var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
  return (a === 1 ? "rgb(" : "rgba(")
      + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", "
      + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", "
      + Math.max(0, Math.min(255, Math.round(this.b) || 0))
      + (a === 1 ? ")" : ", " + a + ")");
}

function color_hex(value) {
  value = Math.max(0, Math.min(255, Math.round(value) || 0));
  return (value < 16 ? "0" : "") + value.toString(16);
}

function color_hsla(h, s, l, a) {
  if (a <= 0) h = s = l = NaN;
  else if (l <= 0 || l >= 1) h = s = NaN;
  else if (s <= 0) h = NaN;
  return new color_Hsl(h, s, l, a);
}

function color_hslConvert(o) {
  if (o instanceof color_Hsl) return new color_Hsl(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof color_Color)) o = color_color(o);
  if (!o) return new color_Hsl;
  if (o instanceof color_Hsl) return o;
  o = o.rgb();
  var r = o.r / 255,
      g = o.g / 255,
      b = o.b / 255,
      min = Math.min(r, g, b),
      max = Math.max(r, g, b),
      h = NaN,
      s = max - min,
      l = (max + min) / 2;
  if (s) {
    if (r === max) h = (g - b) / s + (g < b) * 6;
    else if (g === max) h = (b - r) / s + 2;
    else h = (r - g) / s + 4;
    s /= l < 0.5 ? max + min : 2 - max - min;
    h *= 60;
  } else {
    s = l > 0 && l < 1 ? 0 : h;
  }
  return new color_Hsl(h, s, l, o.opacity);
}

function color_hsl(h, s, l, opacity) {
  return arguments.length === 1 ? color_hslConvert(h) : new color_Hsl(h, s, l, opacity == null ? 1 : opacity);
}

function color_Hsl(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}

src_define(color_Hsl, color_hsl, define_extend(color_Color, {
  brighter: function(k) {
    k = k == null ? color_brighter : Math.pow(color_brighter, k);
    return new color_Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? color_darker : Math.pow(color_darker, k);
    return new color_Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  rgb: function() {
    var h = this.h % 360 + (this.h < 0) * 360,
        s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
        l = this.l,
        m2 = l + (l < 0.5 ? l : 1 - l) * s,
        m1 = 2 * l - m2;
    return new color_Rgb(
      color_hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
      color_hsl2rgb(h, m1, m2),
      color_hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
      this.opacity
    );
  },
  displayable: function() {
    return (0 <= this.s && this.s <= 1 || isNaN(this.s))
        && (0 <= this.l && this.l <= 1)
        && (0 <= this.opacity && this.opacity <= 1);
  },
  formatHsl: function() {
    var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
    return (a === 1 ? "hsl(" : "hsla(")
        + (this.h || 0) + ", "
        + (this.s || 0) * 100 + "%, "
        + (this.l || 0) * 100 + "%"
        + (a === 1 ? ")" : ", " + a + ")");
  }
}));

/* From FvD 13.37, CSS Color Module Level 3 */
function color_hsl2rgb(h, m1, m2) {
  return (h < 60 ? m1 + (m2 - m1) * h / 60
      : h < 180 ? m2
      : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60
      : m1) * 255;
}

// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/basis.js
function basis(t1, v0, v1, v2, v3) {
  var t2 = t1 * t1, t3 = t2 * t1;
  return ((1 - 3 * t1 + 3 * t2 - t3) * v0
      + (4 - 6 * t2 + 3 * t3) * v1
      + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2
      + t3 * v3) / 6;
}

/* harmony default export */ var src_basis = (function(values) {
  var n = values.length - 1;
  return function(t) {
    var i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n),
        v1 = values[i],
        v2 = values[i + 1],
        v0 = i > 0 ? values[i - 1] : 2 * v1 - v2,
        v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;
    return basis((t - i / n) * n, v0, v1, v2, v3);
  };
});

// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/basisClosed.js


/* harmony default export */ var basisClosed = (function(values) {
  var n = values.length;
  return function(t) {
    var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n),
        v0 = values[(i + n - 1) % n],
        v1 = values[i % n],
        v2 = values[(i + 1) % n],
        v3 = values[(i + 2) % n];
    return basis((t - i / n) * n, v0, v1, v2, v3);
  };
});

// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/constant.js
/* harmony default export */ var src_constant = (function(x) {
  return function() {
    return x;
  };
});

// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/color.js


function color_linear(a, d) {
  return function(t) {
    return a + t * d;
  };
}

function color_exponential(a, b, y) {
  return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {
    return Math.pow(a + t * b, y);
  };
}

function hue(a, b) {
  var d = b - a;
  return d ? color_linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : src_constant(isNaN(a) ? b : a);
}

function color_gamma(y) {
  return (y = +y) === 1 ? color_nogamma : function(a, b) {
    return b - a ? color_exponential(a, b, y) : src_constant(isNaN(a) ? b : a);
  };
}

function color_nogamma(a, b) {
  var d = b - a;
  return d ? color_linear(a, d) : src_constant(isNaN(a) ? b : a);
}

// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/rgb.js





/* harmony default export */ var src_rgb = ((function rgbGamma(y) {
  var color = color_gamma(y);

  function rgb(start, end) {
    var r = color((start = color_rgb(start)).r, (end = color_rgb(end)).r),
        g = color(start.g, end.g),
        b = color(start.b, end.b),
        opacity = color_nogamma(start.opacity, end.opacity);
    return function(t) {
      start.r = r(t);
      start.g = g(t);
      start.b = b(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }

  rgb.gamma = rgbGamma;

  return rgb;
})(1));

function rgbSpline(spline) {
  return function(colors) {
    var n = colors.length,
        r = new Array(n),
        g = new Array(n),
        b = new Array(n),
        i, color;
    for (i = 0; i < n; ++i) {
      color = color_rgb(colors[i]);
      r[i] = color.r || 0;
      g[i] = color.g || 0;
      b[i] = color.b || 0;
    }
    r = spline(r);
    g = spline(g);
    b = spline(b);
    color.opacity = 1;
    return function(t) {
      color.r = r(t);
      color.g = g(t);
      color.b = b(t);
      return color + "";
    };
  };
}

var rgbBasis = rgbSpline(src_basis);
var rgbBasisClosed = rgbSpline(basisClosed);

// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/numberArray.js
/* harmony default export */ var numberArray = (function(a, b) {
  if (!b) b = [];
  var n = a ? Math.min(b.length, a.length) : 0,
      c = b.slice(),
      i;
  return function(t) {
    for (i = 0; i < n; ++i) c[i] = a[i] * (1 - t) + b[i] * t;
    return c;
  };
});

function isNumberArray(x) {
  return ArrayBuffer.isView(x) && !(x instanceof DataView);
}

// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/array.js



/* harmony default export */ var src_array = (function(a, b) {
  return (isNumberArray(b) ? numberArray : genericArray)(a, b);
});

function genericArray(a, b) {
  var nb = b ? b.length : 0,
      na = a ? Math.min(nb, a.length) : 0,
      x = new Array(na),
      c = new Array(nb),
      i;

  for (i = 0; i < na; ++i) x[i] = src_value(a[i], b[i]);
  for (; i < nb; ++i) c[i] = b[i];

  return function(t) {
    for (i = 0; i < na; ++i) c[i] = x[i](t);
    return c;
  };
}

// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/date.js
/* harmony default export */ var src_date = (function(a, b) {
  var d = new Date;
  return a = +a, b = +b, function(t) {
    return d.setTime(a * (1 - t) + b * t), d;
  };
});

// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/number.js
/* harmony default export */ var src_number = (function(a, b) {
  return a = +a, b = +b, function(t) {
    return a * (1 - t) + b * t;
  };
});

// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/object.js


/* harmony default export */ var object = (function(a, b) {
  var i = {},
      c = {},
      k;

  if (a === null || typeof a !== "object") a = {};
  if (b === null || typeof b !== "object") b = {};

  for (k in b) {
    if (k in a) {
      i[k] = src_value(a[k], b[k]);
    } else {
      c[k] = b[k];
    }
  }

  return function(t) {
    for (k in i) c[k] = i[k](t);
    return c;
  };
});

// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/string.js


var string_reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,
    string_reB = new RegExp(string_reA.source, "g");

function string_zero(b) {
  return function() {
    return b;
  };
}

function string_one(b) {
  return function(t) {
    return b(t) + "";
  };
}

/* harmony default export */ var src_string = (function(a, b) {
  var bi = string_reA.lastIndex = string_reB.lastIndex = 0, // scan index for next number in b
      am, // current match in a
      bm, // current match in b
      bs, // string preceding current number in b, if any
      i = -1, // index in s
      s = [], // string constants and placeholders
      q = []; // number interpolators

  // Coerce inputs to strings.
  a = a + "", b = b + "";

  // Interpolate pairs of numbers in a & b.
  while ((am = string_reA.exec(a))
      && (bm = string_reB.exec(b))) {
    if ((bs = bm.index) > bi) { // a string precedes the next number in b
      bs = b.slice(bi, bs);
      if (s[i]) s[i] += bs; // coalesce with previous string
      else s[++i] = bs;
    }
    if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match
      if (s[i]) s[i] += bm; // coalesce with previous string
      else s[++i] = bm;
    } else { // interpolate non-matching numbers
      s[++i] = null;
      q.push({i: i, x: src_number(am, bm)});
    }
    bi = string_reB.lastIndex;
  }

  // Add remains of b.
  if (bi < b.length) {
    bs = b.slice(bi);
    if (s[i]) s[i] += bs; // coalesce with previous string
    else s[++i] = bs;
  }

  // Special optimization for only a single match.
  // Otherwise, interpolate each of the numbers and rejoin the string.
  return s.length < 2 ? (q[0]
      ? string_one(q[0].x)
      : string_zero(b))
      : (b = q.length, function(t) {
          for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
          return s.join("");
        });
});

// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/value.js










/* harmony default export */ var src_value = (function(a, b) {
  var t = typeof b, c;
  return b == null || t === "boolean" ? src_constant(b)
      : (t === "number" ? src_number
      : t === "string" ? ((c = color_color(b)) ? (b = c, src_rgb) : src_string)
      : b instanceof color_color ? src_rgb
      : b instanceof Date ? src_date
      : isNumberArray(b) ? numberArray
      : Array.isArray(b) ? genericArray
      : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object
      : src_number)(a, b);
});

// CONCATENATED MODULE: ./node_modules/d3-format/src/formatDecimal.js
// Computes the decimal coefficient and exponent of the specified number x with
// significant digits p, where x is positive and p is in [1, 21] or undefined.
// For example, formatDecimal(1.23) returns ["123", 0].
/* harmony default export */ var src_formatDecimal = (function(x, p) {
  if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; // NaN, ±Infinity
  var i, coefficient = x.slice(0, i);

  // The string returned by toExponential either has the form \d\.\d+e[-+]\d+
  // (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3).
  return [
    coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
    +x.slice(i + 1)
  ];
});

// CONCATENATED MODULE: ./node_modules/d3-format/src/exponent.js


/* harmony default export */ var src_exponent = (function(x) {
  return x = src_formatDecimal(Math.abs(x)), x ? x[1] : NaN;
});

// CONCATENATED MODULE: ./node_modules/d3-format/src/formatGroup.js
/* harmony default export */ var src_formatGroup = (function(grouping, thousands) {
  return function(value, width) {
    var i = value.length,
        t = [],
        j = 0,
        g = grouping[0],
        length = 0;

    while (i > 0 && g > 0) {
      if (length + g + 1 > width) g = Math.max(1, width - length);
      t.push(value.substring(i -= g, i + g));
      if ((length += g + 1) > width) break;
      g = grouping[j = (j + 1) % grouping.length];
    }

    return t.reverse().join(thousands);
  };
});

// CONCATENATED MODULE: ./node_modules/d3-format/src/formatNumerals.js
/* harmony default export */ var src_formatNumerals = (function(numerals) {
  return function(value) {
    return value.replace(/[0-9]/g, function(i) {
      return numerals[+i];
    });
  };
});

// CONCATENATED MODULE: ./node_modules/d3-format/src/formatSpecifier.js
// [[fill]align][sign][symbol][0][width][,][.precision][~][type]
var formatSpecifier_re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;

function formatSpecifier_formatSpecifier(specifier) {
  if (!(match = formatSpecifier_re.exec(specifier))) throw new Error("invalid format: " + specifier);
  var match;
  return new formatSpecifier_FormatSpecifier({
    fill: match[1],
    align: match[2],
    sign: match[3],
    symbol: match[4],
    zero: match[5],
    width: match[6],
    comma: match[7],
    precision: match[8] && match[8].slice(1),
    trim: match[9],
    type: match[10]
  });
}

formatSpecifier_formatSpecifier.prototype = formatSpecifier_FormatSpecifier.prototype; // instanceof

function formatSpecifier_FormatSpecifier(specifier) {
  this.fill = specifier.fill === undefined ? " " : specifier.fill + "";
  this.align = specifier.align === undefined ? ">" : specifier.align + "";
  this.sign = specifier.sign === undefined ? "-" : specifier.sign + "";
  this.symbol = specifier.symbol === undefined ? "" : specifier.symbol + "";
  this.zero = !!specifier.zero;
  this.width = specifier.width === undefined ? undefined : +specifier.width;
  this.comma = !!specifier.comma;
  this.precision = specifier.precision === undefined ? undefined : +specifier.precision;
  this.trim = !!specifier.trim;
  this.type = specifier.type === undefined ? "" : specifier.type + "";
}

formatSpecifier_FormatSpecifier.prototype.toString = function() {
  return this.fill
      + this.align
      + this.sign
      + this.symbol
      + (this.zero ? "0" : "")
      + (this.width === undefined ? "" : Math.max(1, this.width | 0))
      + (this.comma ? "," : "")
      + (this.precision === undefined ? "" : "." + Math.max(0, this.precision | 0))
      + (this.trim ? "~" : "")
      + this.type;
};

// CONCATENATED MODULE: ./node_modules/d3-format/src/formatTrim.js
// Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.
/* harmony default export */ var src_formatTrim = (function(s) {
  out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
    switch (s[i]) {
      case ".": i0 = i1 = i; break;
      case "0": if (i0 === 0) i0 = i; i1 = i; break;
      default: if (!+s[i]) break out; if (i0 > 0) i0 = 0; break;
    }
  }
  return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
});

// CONCATENATED MODULE: ./node_modules/d3-format/src/formatPrefixAuto.js


var formatPrefixAuto_prefixExponent;

/* harmony default export */ var src_formatPrefixAuto = (function(x, p) {
  var d = src_formatDecimal(x, p);
  if (!d) return x + "";
  var coefficient = d[0],
      exponent = d[1],
      i = exponent - (formatPrefixAuto_prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,
      n = coefficient.length;
  return i === n ? coefficient
      : i > n ? coefficient + new Array(i - n + 1).join("0")
      : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i)
      : "0." + new Array(1 - i).join("0") + src_formatDecimal(x, Math.max(0, p + i - 1))[0]; // less than 1y!
});

// CONCATENATED MODULE: ./node_modules/d3-format/src/formatRounded.js


/* harmony default export */ var src_formatRounded = (function(x, p) {
  var d = src_formatDecimal(x, p);
  if (!d) return x + "";
  var coefficient = d[0],
      exponent = d[1];
  return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient
      : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1)
      : coefficient + new Array(exponent - coefficient.length + 2).join("0");
});

// CONCATENATED MODULE: ./node_modules/d3-format/src/formatTypes.js



/* harmony default export */ var src_formatTypes = ({
  "%": function(x, p) { return (x * 100).toFixed(p); },
  "b": function(x) { return Math.round(x).toString(2); },
  "c": function(x) { return x + ""; },
  "d": function(x) { return Math.round(x).toString(10); },
  "e": function(x, p) { return x.toExponential(p); },
  "f": function(x, p) { return x.toFixed(p); },
  "g": function(x, p) { return x.toPrecision(p); },
  "o": function(x) { return Math.round(x).toString(8); },
  "p": function(x, p) { return src_formatRounded(x * 100, p); },
  "r": src_formatRounded,
  "s": src_formatPrefixAuto,
  "X": function(x) { return Math.round(x).toString(16).toUpperCase(); },
  "x": function(x) { return Math.round(x).toString(16); }
});

// CONCATENATED MODULE: ./node_modules/d3-format/src/identity.js
/* harmony default export */ var src_identity = (function(x) {
  return x;
});

// CONCATENATED MODULE: ./node_modules/d3-format/src/locale.js









var locale_map = Array.prototype.map,
    locale_prefixes = ["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];

/* harmony default export */ var src_locale = (function(locale) {
  var group = locale.grouping === undefined || locale.thousands === undefined ? src_identity : src_formatGroup(locale_map.call(locale.grouping, Number), locale.thousands + ""),
      currencyPrefix = locale.currency === undefined ? "" : locale.currency[0] + "",
      currencySuffix = locale.currency === undefined ? "" : locale.currency[1] + "",
      decimal = locale.decimal === undefined ? "." : locale.decimal + "",
      numerals = locale.numerals === undefined ? src_identity : src_formatNumerals(locale_map.call(locale.numerals, String)),
      percent = locale.percent === undefined ? "%" : locale.percent + "",
      minus = locale.minus === undefined ? "-" : locale.minus + "",
      nan = locale.nan === undefined ? "NaN" : locale.nan + "";

  function newFormat(specifier) {
    specifier = formatSpecifier_formatSpecifier(specifier);

    var fill = specifier.fill,
        align = specifier.align,
        sign = specifier.sign,
        symbol = specifier.symbol,
        zero = specifier.zero,
        width = specifier.width,
        comma = specifier.comma,
        precision = specifier.precision,
        trim = specifier.trim,
        type = specifier.type;

    // The "n" type is an alias for ",g".
    if (type === "n") comma = true, type = "g";

    // The "" type, and any invalid type, is an alias for ".12~g".
    else if (!src_formatTypes[type]) precision === undefined && (precision = 12), trim = true, type = "g";

    // If zero fill is specified, padding goes after sign and before digits.
    if (zero || (fill === "0" && align === "=")) zero = true, fill = "0", align = "=";

    // Compute the prefix and suffix.
    // For SI-prefix, the suffix is lazily computed.
    var prefix = symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "",
        suffix = symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent : "";

    // What format function should we use?
    // Is this an integer type?
    // Can this type generate exponential notation?
    var formatType = src_formatTypes[type],
        maybeSuffix = /[defgprs%]/.test(type);

    // Set the default precision if not specified,
    // or clamp the specified precision to the supported range.
    // For significant precision, it must be in [1, 21].
    // For fixed precision, it must be in [0, 20].
    precision = precision === undefined ? 6
        : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))
        : Math.max(0, Math.min(20, precision));

    function format(value) {
      var valuePrefix = prefix,
          valueSuffix = suffix,
          i, n, c;

      if (type === "c") {
        valueSuffix = formatType(value) + valueSuffix;
        value = "";
      } else {
        value = +value;

        // Perform the initial formatting.
        var valueNegative = value < 0;
        value = isNaN(value) ? nan : formatType(Math.abs(value), precision);

        // Trim insignificant zeros.
        if (trim) value = src_formatTrim(value);

        // If a negative value rounds to zero during formatting, treat as positive.
        if (valueNegative && +value === 0) valueNegative = false;

        // Compute the prefix and suffix.
        valuePrefix = (valueNegative ? (sign === "(" ? sign : minus) : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;

        valueSuffix = (type === "s" ? locale_prefixes[8 + formatPrefixAuto_prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");

        // Break the formatted value into the integer “value” part that can be
        // grouped, and fractional or exponential “suffix” part that is not.
        if (maybeSuffix) {
          i = -1, n = value.length;
          while (++i < n) {
            if (c = value.charCodeAt(i), 48 > c || c > 57) {
              valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
              value = value.slice(0, i);
              break;
            }
          }
        }
      }

      // If the fill character is not "0", grouping is applied before padding.
      if (comma && !zero) value = group(value, Infinity);

      // Compute the padding.
      var length = valuePrefix.length + value.length + valueSuffix.length,
          padding = length < width ? new Array(width - length + 1).join(fill) : "";

      // If the fill character is "0", grouping is applied after padding.
      if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";

      // Reconstruct the final output based on the desired alignment.
      switch (align) {
        case "<": value = valuePrefix + value + valueSuffix + padding; break;
        case "=": value = valuePrefix + padding + value + valueSuffix; break;
        case "^": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;
        default: value = padding + valuePrefix + value + valueSuffix; break;
      }

      return numerals(value);
    }

    format.toString = function() {
      return specifier + "";
    };

    return format;
  }

  function formatPrefix(specifier, value) {
    var f = newFormat((specifier = formatSpecifier_formatSpecifier(specifier), specifier.type = "f", specifier)),
        e = Math.max(-8, Math.min(8, Math.floor(src_exponent(value) / 3))) * 3,
        k = Math.pow(10, -e),
        prefix = locale_prefixes[8 + e / 3];
    return function(value) {
      return f(k * value) + prefix;
    };
  }

  return {
    format: newFormat,
    formatPrefix: formatPrefix
  };
});

// CONCATENATED MODULE: ./node_modules/d3-format/src/defaultLocale.js


var defaultLocale_locale;
var defaultLocale_format;
var defaultLocale_formatPrefix;

defaultLocale_defaultLocale({
  decimal: ".",
  thousands: ",",
  grouping: [3],
  currency: ["$", ""],
  minus: "-"
});

function defaultLocale_defaultLocale(definition) {
  defaultLocale_locale = src_locale(definition);
  defaultLocale_format = defaultLocale_locale.format;
  defaultLocale_formatPrefix = defaultLocale_locale.formatPrefix;
  return defaultLocale_locale;
}

// EXTERNAL MODULE: ./node_modules/resize-observer-polyfill/dist/ResizeObserver.es.js
var ResizeObserver_es = __webpack_require__(74);

// EXTERNAL MODULE: ./node_modules/@material-ui/icons/Clear.js
var Clear = __webpack_require__(75);
var Clear_default = /*#__PURE__*/__webpack_require__.n(Clear);

// CONCATENATED MODULE: ./src/components/QdtModal/QdtSelectionModal.jsx





var QdtSelectionModal_styles = {
  root: {
    position: 'absolute',
    top: -40,
    // right: 0,
    width: '100%',
    borderTop: '1px solid #CCCCCC',
    borderLeft: '1px solid #CCCCCC',
    borderRight: '1px solid #CCCCCC',
    textAlign: 'right',
    padding: 5
  },
  cancelButton: {
    color: '#FFFFFF',
    backgroundColor: '#dc423f',
    border: 0,
    padding: '5px 15px',
    borderRadius: 3,
    marginRight: 10
  },
  confirmButton: {
    color: '#FFFFFF',
    backgroundColor: '#009845',
    border: 0,
    padding: '5px 15px',
    borderRadius: 3
  }
};

var QdtSelectionModal_QdtSelectionModal = function QdtSelectionModal(_ref) {
  var isOpen = _ref.isOpen,
      onCancelSelections = _ref.onCancelSelections,
      onConfirmSelections = _ref.onConfirmSelections;
  return react_default.a.createElement("div", {
    style: QdtSelectionModal_styles.root
  }, isOpen && react_default.a.createElement("div", null, react_default.a.createElement(esm_IconButton_IconButton, {
    style: QdtSelectionModal_styles.cancelButton,
    size: "small",
    onClick: onCancelSelections
  }, react_default.a.createElement(Clear_default.a, {
    fontSize: "inherit"
  })), react_default.a.createElement(esm_IconButton_IconButton, {
    style: QdtSelectionModal_styles.confirmButton,
    size: "small",
    onClick: onConfirmSelections
  }, react_default.a.createElement(Check_default.a, {
    fontSize: "inherit"
  }))));
};

QdtSelectionModal_QdtSelectionModal.propTypes = {
  isOpen: prop_types_default.a.bool.isRequired,
  onCancelSelections: prop_types_default.a.func.isRequired,
  onConfirmSelections: prop_types_default.a.func.isRequired
};
QdtSelectionModal_QdtSelectionModal.defaultProps = {};
/* harmony default export */ var QdtModal_QdtSelectionModal = (QdtSelectionModal_QdtSelectionModal);
// CONCATENATED MODULE: ./src/components/QdtPicasso/components/domPointLabel.js

/* harmony default export */ var components_domPointLabel = ({
  require: ['resolver'],
  renderer: 'dom',
  defaultSettings: {
    settings: {}
  },
  beforeRender: function beforeRender(options) {
    this.size = options.size;
  },
  generatePoints: function generatePoints(data) {
    var _this = this;

    var visible = [];
    return data.items.map(function (row) {
      var left = _this.size.width * row.x - data.settings.width / 2;
      var top = _this.size.height * row.y - data.settings.height / 2 - data.settings.offset;
      var display = 'inline';
      var p = {
        w: data.settings.width,
        h: data.settings.height
      }; // Collision detection

      if (visible.length) {
        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = visible[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var n = _step.value;

            // eslint-disable-line no-restricted-syntax
            if (left < n.left + p.w && left + p.w > n.left && top < n.top + p.h && p.h + top > n.top) {
              display = 'none';
              break;
            }
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator["return"] != null) {
              _iterator["return"]();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }
      }

      if (display === 'inline') visible = [].concat(toConsumableArray_default()(visible), [{
        left: left,
        top: top
      }]);
      var style = {
        position: 'absolute',
        left: "".concat(left, "px"),
        top: "".concat(top, "px"),
        'font-size': data.settings.fontSize ? data.settings.fontSize : '10px',
        color: data.settings.color ? data.settings.color : '#000000',
        width: "".concat(data.settings.width, "px"),
        'text-align': 'center',
        display: display
      };

      var res = _this.h('div', {
        attrs: {
          "class": 'domLabel'
        },
        style: style
      }, row.data.label);

      return res;
    });
  },
  render: function render(h, _ref) {
    var data = _ref.data;
    this.h = h; // snabbdom reference

    var resolved = this.resolver.resolve({
      data: data,
      settings: this.settings.settings,
      scaled: {
        x: this.size.width,
        y: this.size.height
      }
    });
    return this.generatePoints(resolved);
  }
});
// CONCATENATED MODULE: ./src/components/QdtPicasso/components/domPointImage.js
/* harmony default export */ var domPointImage = ({
  require: ['resolver'],
  renderer: 'dom',
  defaultSettings: {
    settings: {}
  },
  beforeRender: function beforeRender(options) {
    this.size = options.size;
  },
  generatePoints: function generatePoints(data) {
    var _this = this;

    return data.items.map(function (row) {
      var style = {
        position: 'absolute',
        left: "".concat(_this.size.width * row.x - data.settings.width / 2, "px"),
        top: "".concat(_this.size.height * row.y - data.settings.height / 2 - 10, "px"),
        // extra 10px for the text
        'text-align': 'center',
        'font-size': '10px',
        color: data.settings.color,
        'background-image': "url(\"".concat(data.settings.image, "\")"),
        'background-repeat': 'no-repeat',
        'background-position': 'center bottom',
        width: "".concat(data.settings.width, "px"),
        height: "".concat(data.settings.height + 12, "px") // extra 12px for the text

      };

      var res = _this.h('div', {
        attrs: {
          "class": 'domPointImage'
        },
        style: style
      });

      return res;
    });
  },
  render: function render(h, _ref) {
    var data = _ref.data;
    this.h = h; // snabbdom reference

    var resolved = this.resolver.resolve({
      data: data,
      settings: this.settings.settings,
      scaled: {
        x: this.size.width,
        y: this.size.height
      }
    });
    return this.generatePoints(resolved);
  }
});
// CONCATENATED MODULE: ./src/components/QdtPicasso/QdtPicasso.jsx

















picasso_esm.component('domPointLabel', components_domPointLabel);
picasso_esm.component('domPointImage', domPointImage);
picasso_esm.use(picasso_hammer_esm["a" /* default */]);
picasso_esm.use(picasso_q_esm["a" /* default */]); // Custom formatter to change G to B (US Billions)

var QdtPicasso_formatterGtoB = function formatterGtoB() {
  return function (value) {
    return defaultLocale_format('.1s')(value).replace(/G/, 'B');
  };
}; // .1s for no decimal on Billions


picasso_esm.formatter('formatterGtoB', QdtPicasso_formatterGtoB);
var QdtPicasso = react_default.a.forwardRef(function (_ref, ref) {
  var model = _ref.model,
      layout = _ref.layout,
      optionsProp = _ref.options;
  var defaultOptions = {
    prio: 'canvas',
    settings: {
      formatters: {
        formatterGtoB: {
          type: 'formatterGtoB'
        }
      }
    },
    transition: {
      duration: 1000,
      easing: 'easeCubic'
    },
    width: '100%',
    height: '100%'
  };
  var options = Object(merge["a" /* default */])(defaultOptions, optionsProp);
  var elementNode = Object(react["useRef"])(null);
  var pic = Object(react["useRef"])(null);
  var transition = Object(react["useRef"])(null);
  var tweenLayout = Object(react["useRef"])(null);
  var staleLayout = Object(react["useRef"])(layout);
  var staleOptions = Object(react["useRef"])(options);

  var _useState = Object(react["useState"])(false),
      _useState2 = slicedToArray_default()(_useState, 2),
      selectionModalOpen = _useState2[0],
      setSelectionModalOpen = _useState2[1];

  ref.current = {
    node: elementNode.current,
    pic: pic.current
  }; //eslint-disable-line

  var stopTransition = Object(react["useCallback"])(function () {
    transition.current.stop();
    transition.current = null;
    staleLayout.current = layout;
    staleOptions.current = options;
  }, [layout, options]);
  var create = Object(react["useCallback"])(function () {
    if (!layout.qHyperCube) return;
    pic.current = picasso_esm({
      renderer: {
        prio: [options.prio]
      }
    }).chart({
      element: elementNode.current,
      data: [{
        type: 'q',
        key: 'qHyperCube',
        data: layout.qHyperCube
      }],
      settings: options.settings
    });
    pic.current.brush('select').on('start', function () {
      model.beginSelections(['/qHyperCubeDef']);
      setSelectionModalOpen(true);
    });
    pic.current.brush('select').on('update', function (added, removed) {
      var qValues = [].concat(toConsumableArray_default()(added), toConsumableArray_default()(removed)).map(function (v) {
        return v.values[0];
      });
      model.selectHyperCubeValues('/qHyperCubeDef', 0, qValues, true);
    });
    staleLayout.current = layout;
    staleOptions.current = options;
  }, [layout, model, options]);
  var update = Object(react["useCallback"])(function () {
    if (transition.current) {
      stopTransition();
      staleLayout.current = tweenLayout.current;
    }

    if (!layout.qHyperCube) return;
    var duration = options.transition.duration;
    var ease = src_namespaceObject[options.transition.easing];
    transition.current = timer_timer(function (elapsed) {
      var t = Math.min(1, ease(elapsed / duration));
      tweenLayout.current = src_value(staleLayout.current, layout)(t);
      pic.current.update({
        data: [{
          type: 'q',
          key: 'qHyperCube',
          data: tweenLayout.current.qHyperCube
        }],
        settings: options.settings
      });

      if (t === 1) {
        stopTransition();
      }
    });
  }, [layout, options.settings, options.transition, stopTransition]);

  var handleCancelSelections = function handleCancelSelections() {
    pic.current.brush('select').end();
    model.endSelections(false);
    setSelectionModalOpen(false);
  };

  var handleConfirmSelections = function handleConfirmSelections() {
    pic.current.brush('select').end();
    model.endSelections(true);
    setSelectionModalOpen(false);
  };

  Object(react["useEffect"])(function () {
    if (!pic.current) create();
    if (pic.current && !selectionModalOpen && (!deep_equal_default()(staleLayout.current, layout) || JSON.stringify(staleOptions.current) !== JSON.stringify(options))) update();
    ref.current = {
      node: elementNode.current,
      pic: pic.current
    }; //eslint-disable-line
  }, [create, update, layout, options, ref, selectionModalOpen]);
  Object(react["useEffect"])(function () {
    var ro = new ResizeObserver_es["a" /* default */](function () {
      if (pic.current) pic.current.update();
    });
    ro.observe(elementNode.current);
  }, []);
  return react_default.a.createElement("div", {
    style: {
      width: options.width,
      height: options.height
    }
  }, react_default.a.createElement("div", {
    ref: elementNode,
    style: {
      width: options.width,
      height: options.height,
      border: selectionModalOpen ? '1px solid #CCCCCC' : 0
    }
  }), react_default.a.createElement(QdtModal_QdtSelectionModal, {
    style: {
      width: options.width
    },
    isOpen: selectionModalOpen,
    onCancelSelections: handleCancelSelections,
    onConfirmSelections: handleConfirmSelections
  }));
});
QdtPicasso.propTypes = {
  layout: prop_types_default.a.object,
  model: prop_types_default.a.object,
  options: prop_types_default.a.object
};
QdtPicasso.defaultProps = {
  layout: null,
  model: null,
  options: {}
};
/* harmony default export */ var QdtPicasso_QdtPicasso = (QdtPicasso);
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/components/axis.js
// https://picassojs.com/docs/component-axis.html



var axis_axis = function axis() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$theme = _ref.theme,
      themeProp = _ref$theme === void 0 ? {} : _ref$theme,
      _ref$properties = _ref.properties,
      propertiesProp = _ref$properties === void 0 ? {} : _ref$properties,
      _ref$scale = _ref.scale,
      scale = _ref$scale === void 0 ? 'x' : _ref$scale,
      _ref$formatter = _ref.formatter,
      formatter = _ref$formatter === void 0 ? null : _ref$formatter;

  var theme = Object(merge["a" /* default */])(Light, themeProp); //eslint-disable-line

  var defaultProperties = {
    type: 'axis',
    key: "".concat(scale, "-axis"),
    scale: scale,
    dock: scale === 'x' && 'bottom' || scale === 'y' && 'left' || null,
    settings: {
      labels: {
        show: true,
        mode: 'auto',
        align: 0.5,
        justify: 0
      },
      ticks: {
        show: true,
        margin: 0,
        tickSize: 4
      },
      line: {
        show: true
      },
      paddingStart: 0,
      paddingEnd: 10,
      align: 'auto'
    },
    formatter: 'formatterGtoB'
  };
  if (formatter) defaultProperties.formatter = formatter;
  var properties = Object(merge["a" /* default */])(defaultProperties, propertiesProp);
  return properties;
};

/* harmony default export */ var components_axis = (axis_axis);
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/components/box.js



var box_box = function box() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$theme = _ref.theme,
      themeProp = _ref$theme === void 0 ? {} : _ref$theme,
      _ref$properties = _ref.properties,
      propertiesProp = _ref$properties === void 0 ? {} : _ref$properties,
      _ref$orientation = _ref.orientation,
      orientation = _ref$orientation === void 0 ? 'vertical' : _ref$orientation;

  var theme = Object(merge["a" /* default */])(Light, themeProp); //eslint-disable-line

  var majorScale = orientation === 'vertical' && 'x' || orientation === 'horizontal' && 'y' || null;
  var minorScale = orientation === 'vertical' && 'y' || orientation === 'horizontal' && 'x' || null;
  var defaultProperties = {
    type: 'box',
    key: 'bars',
    displayOrder: 1,
    data: {
      extract: {
        field: 'qDimensionInfo/0',
        props: {
          start: 0,
          end: {
            field: 'qMeasureInfo/0'
          }
        }
      }
    },
    settings: {
      major: {
        scale: majorScale
      },
      minor: {
        scale: minorScale,
        ref: 'end'
      },
      orientation: orientation,
      box: {
        fill: theme.palette.primary.main,
        stroke: theme.palette.primary.light,
        strokeWidth: 1,
        width: 1
      }
    },
    brush: {
      trigger: [{
        on: 'tap',
        contexts: ['select']
      }],
      consume: [{
        context: 'select',
        style: {
          active: {
            opacity: 1
          },
          inactive: {
            opacity: 0.5
          }
        }
      }]
    }
  };
  var properties = Object(merge["a" /* default */])(defaultProperties, propertiesProp);
  return properties;
};

/* harmony default export */ var components_box = (box_box);
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/components/point.js



var point_point = function point() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$theme = _ref.theme,
      themeProp = _ref$theme === void 0 ? {} : _ref$theme,
      _ref$properties = _ref.properties,
      propertiesProp = _ref$properties === void 0 ? {} : _ref$properties;

  var theme = Object(merge["a" /* default */])(Light, themeProp); //eslint-disable-line

  var defaultProperties = {
    type: 'point',
    key: 'point',
    displayOrder: 1,
    data: {
      extract: {
        field: 'qDimensionInfo/0',
        props: {
          x: {
            field: 'qDimensionInfo/0'
          },
          y: {
            field: 'qMeasureInfo/0'
          },
          num: {
            field: 'qMeasureInfo/0'
          }
        }
      }
    },
    settings: {
      x: {
        scale: 'x'
      },
      y: {
        scale: 'y'
      },
      shape: 'circle',
      size: 0.2,
      strokeWidth: 1,
      stroke: theme.palette.primary.light,
      opacity: 1,
      fill: theme.palette.primary.main
    },
    brush: {
      trigger: [{
        on: 'tap',
        contexts: ['select']
      }],
      consume: [{
        context: 'select',
        style: {
          active: {
            opacity: 1
          },
          inactive: {
            opacity: 0.5
          }
        }
      }]
    }
  };
  var properties = Object(merge["a" /* default */])(defaultProperties, propertiesProp);
  return properties;
};

/* harmony default export */ var components_point = (point_point);
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/components/lineArea.js



var lineArea_lineArea = function lineArea() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$theme = _ref.theme,
      themeProp = _ref$theme === void 0 ? {} : _ref$theme,
      _ref$properties = _ref.properties,
      propertiesProp = _ref$properties === void 0 ? {} : _ref$properties,
      _ref$showLine = _ref.showLine,
      showLine = _ref$showLine === void 0 ? true : _ref$showLine,
      _ref$showArea = _ref.showArea,
      showArea = _ref$showArea === void 0 ? true : _ref$showArea;

  var theme = Object(merge["a" /* default */])(Light, themeProp); //eslint-disable-line

  var defaultProperties = {
    type: 'line',
    key: 'line',
    displayOrder: 1,
    data: {
      extract: {
        field: 'qDimensionInfo/0',
        props: {
          y: {
            field: 'qMeasureInfo/0'
          }
        }
      }
    },
    settings: {
      coordinates: {
        major: {
          scale: 'x'
        },
        minor: {
          scale: 'y',
          ref: 'y'
        },
        minor0: {
          scale: 'y',
          fn: function fn(d) {
            return d.scale(0);
          }
        }
      },
      orientation: 'horizontal',
      layers: {
        curve: 'linear',
        show: true,
        line: {
          show: showLine,
          opacity: 1,
          stroke: theme.palette.primary.main,
          strokeWidth: 2
        },
        area: {
          show: showArea,
          fill: theme.palette.primary.main,
          opacity: 0.8
        }
      }
    }
  };
  var properties = Object(merge["a" /* default */])(defaultProperties, propertiesProp);
  return properties;
};

/* harmony default export */ var components_lineArea = (lineArea_lineArea);
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/components/grid.js
// https://picassojs.com/docs/component-grid-line.html



var grid_grid = function grid() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$theme = _ref.theme,
      themeProp = _ref$theme === void 0 ? {} : _ref$theme,
      _ref$properties = _ref.properties,
      propertiesProp = _ref$properties === void 0 ? {} : _ref$properties,
      _ref$x = _ref.x,
      x = _ref$x === void 0 ? true : _ref$x,
      _ref$y = _ref.y,
      y = _ref$y === void 0 ? true : _ref$y;

  var theme = Object(merge["a" /* default */])(Light, themeProp); //eslint-disable-line

  var defaultProperties = {
    type: 'grid-line'
  };

  if (x) {
    defaultProperties.x = {
      scale: 'x'
    };
  }

  if (y) {
    defaultProperties.y = {
      scale: 'y'
    };
  }

  var properties = Object(merge["a" /* default */])(defaultProperties, propertiesProp);
  return properties;
};

/* harmony default export */ var components_grid = (grid_grid);
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/components/labels.js




var labels_labels = function labels() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$theme = _ref.theme,
      themeProp = _ref$theme === void 0 ? {} : _ref$theme,
      _ref$properties = _ref.properties,
      propertiesProp = _ref$properties === void 0 ? {} : _ref$properties,
      _ref$type = _ref.type,
      type = _ref$type === void 0 ? 'bar' : _ref$type,
      _ref$component = _ref.component,
      component = _ref$component === void 0 ? 'bars' : _ref$component,
      _ref$orientation = _ref.orientation,
      orientation = _ref$orientation === void 0 ? 'vertical' : _ref$orientation,
      _ref$format = _ref.format,
      formatSpec = _ref$format === void 0 ? '.2s' : _ref$format,
      _ref$labels = _ref.labels,
      labelsProp = _ref$labels === void 0 ? null : _ref$labels;

  var theme = Object(merge["a" /* default */])(Light, themeProp); //eslint-disable-line

  var defaultProperties = {
    type: 'labels',
    displayOrder: 2,
    settings: {
      sources: [{
        component: component,
        selector: type === 'bar' ? 'rect' : 'path',
        strategy: {
          type: type,
          settings: {
            direction: function direction(_ref2) {
              var data = _ref2.data;
              return type === 'bar' && orientation === 'vertical' && (data && data.end.value > data.start.value ? 'up' : 'down') || type === 'bar' && orientation === 'horizontal' && (data && data.end.value > data.start.value ? 'right' : 'left') || type === 'rows' && (data && data.end.value > data.start.value ? 'right' : 'left') || type === 'slice' && 'rotated';
            },
            align: 0.5,
            justify: 0,
            fontSize: 9,
            labels: labelsProp || [{
              label: function label(_ref3) {
                var data = _ref3.data;

                if (type === 'bar') {
                  if (data.series) {
                    return defaultLocale_format(formatSpec)(data.end.value - data.start.value);
                  }

                  return defaultLocale_format(formatSpec)(data.end.value);
                }

                if (type === 'slice') {
                  return defaultLocale_format(formatSpec)(data.num.label);
                }

                return defaultLocale_format(formatSpec)(data.value);
              },
              placements: [{
                position: 'inside',
                fill: '#FFFFFF',
                justify: 1
              }, {
                position: 'outside',
                fill: '#666666',
                justify: 0
              }]
            }]
          }
        }
      }]
    }
  };
  var properties = Object(merge["a" /* default */])(defaultProperties, propertiesProp);
  return properties;
};

/* harmony default export */ var components_labels = (labels_labels);
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/components/range.js



var range_range = function range() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$theme = _ref.theme,
      themeProp = _ref$theme === void 0 ? {} : _ref$theme,
      _ref$properties = _ref.properties,
      propertiesProp = _ref$properties === void 0 ? {} : _ref$properties,
      _ref$scale = _ref.scale,
      scale = _ref$scale === void 0 ? 'x' : _ref$scale;

  var theme = Object(merge["a" /* default */])(Light, themeProp); //eslint-disable-line

  var defaultProperties = {
    key: 'x-range',
    type: 'brush-range',
    settings: {
      brush: 'select',
      direction: 'horizontal',
      scale: 'x',
      target: {
        component: 'x-axis'
      },
      bubbles: {
        align: 'end'
      }
    }
  };

  if (scale === 'y') {
    defaultProperties.key = 'y-range';
    defaultProperties.settings.direction = 'vertical';
    defaultProperties.settings.scale = 'y';
    defaultProperties.settings.target.component = 'y-axis';
  }

  var properties = Object(merge["a" /* default */])(defaultProperties, propertiesProp);
  return properties;
};

/* harmony default export */ var components_range = (range_range);
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/components/tooltip.js




var tooltip_tooltip = function tooltip() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$theme = _ref.theme,
      themeProp = _ref$theme === void 0 ? {} : _ref$theme,
      _ref$properties = _ref.properties,
      propertiesProp = _ref$properties === void 0 ? {} : _ref$properties,
      _ref$format = _ref.format,
      formatSpec = _ref$format === void 0 ? '.2s' : _ref$format;

  var theme = Object(merge["a" /* default */])(Light, themeProp); //eslint-disable-line

  var defaultProperties = {
    key: 'tooltip',
    type: 'tooltip',
    displayOrder: 10,
    settings: {
      filter: function filter(nodes) {
        return nodes.filter(function (node) {
          return ['bars', 'range', 'point', 'point2', 'pie', 'rects'].includes(node.key);
        });
      },
      extract: function extract(_ref2) {
        var node = _ref2.node;
        var data = node.data,
            key = node.key,
            attrs = node.attrs;
        return {
          data: data,
          key: key,
          attrs: attrs
        };
      },
      content: function content(_ref3) {
        var h = _ref3.h,
            data = _ref3.data;
        var html = '';

        switch (data[0].key) {
          // line, dots
          case 'point':
          case 'point2':
            html = h('div.qdt-tooltip-header', {}, [h('div.qdt-tooltip-header-title', {}, "".concat(data[0].data.label, ": ")), h('div.qdt-tooltip-header-measure', {}, "".concat(defaultLocale_format('.2s')(data[0].data.y.label).replace(/G/, 'B')))]);
            break;
          // Pie

          case 'pie':
            html = h('div.qdt-tooltip-header', {}, [h('div.qdt-tooltip-header-title', {}, "".concat(data[0].data.label, ": ")), h('div.qdt-tooltip-header-measure', {}, "".concat(defaultLocale_format(formatSpec)(data[0].data.num.label)))]);
            break;
          // Barcharts, Gauge

          case 'bars':
          default:
            if (data[0].data.series) {
              // Stacked
              html = h('div.qdt-tooltip-header', {}, [h('div.qdt-tooltip-header-title', {
                align: 'center',
                style: {
                  'border-bottom': '1px solid rgba(255,255,255,0.2)',
                  'padding-bottom': '5px',
                  display: 'block'
                }
              }, "".concat(data[0].data.series.label)), h('div.qdt-tooltip-header-measure', {
                align: 'center',
                style: {
                  'padding-top': '5px'
                }
              }, "".concat(data[0].data.label, ": ").concat(defaultLocale_format(formatSpec)(data[0].data.end.value - data[0].data.start.value)))]);
            } else {
              html = h('div.qdt-tooltip-header', {}, [h('div.qdt-tooltip-header-title', {}, "".concat(data[0].data.label, ": ")), h('div.qdt-tooltip-header-measure', {}, "".concat(defaultLocale_format(formatSpec)(data[0].data.end.label).replace(/G/, 'B')))]);
            }

            break;
        }

        return h('div', {
          display: 'table'
        }, html);
      },
      afterShow: function afterShow(_ref4) {
        var element = _ref4.element;
        var e = element;
        e.children[0].style.opacity = 1;
        e.children[1].style.opacity = 1;
      },
      onHide: function onHide(_ref5) {
        var element = _ref5.element;
        var e = element;
        e.children[0].style.opacity = 0;
        e.children[1].style.opacity = 0;
      },
      placement: {
        type: 'pointer',
        area: 'target'
      }
    },
    style: {
      content: {
        'border-spacing': '4px',
        opacity: 0,
        transition: 'opacity 150ms ease-in'
      },
      arrow: {
        opacity: 0,
        transition: 'opacity 150ms ease-in'
      }
    } // formatter: 'formatterGtoB',

  };
  var properties = Object(merge["a" /* default */])(defaultProperties, propertiesProp);
  return properties;
};

/* harmony default export */ var components_tooltip = (tooltip_tooltip);
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/components/legend.js
// https://picassojs.com/docs/component-legend-cat.html



var legend_legend = function legend() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$theme = _ref.theme,
      themeProp = _ref$theme === void 0 ? {} : _ref$theme,
      _ref$properties = _ref.properties,
      propertiesProp = _ref$properties === void 0 ? {} : _ref$properties;

  var theme = Object(merge["a" /* default */])(Light, themeProp); //eslint-disable-line

  var defaultProperties = {
    type: 'legend-cat',
    key: 'legend',
    dock: 'right',
    scale: 'c',
    settings: {
      layout: {
        size: 4,
        direction: 'ltr',
        scrollOffset: 0
      },
      item: {
        show: true,
        label: {
          wordBreak: 'none',
          maxLines: 2,
          maxWidth: 136
        },
        shape: {
          type: 'square',
          size: 12
        }
      },
      title: {
        show: true,
        anchor: 'start',
        wordBreak: 'none',
        maxLines: 2,
        maxWidth: 156
      }
    },
    brush: {
      trigger: [{
        on: 'tap',
        contexts: ['select']
      }],
      consume: [{
        context: 'select',
        style: {
          active: {
            opacity: 1
          },
          inactive: {
            opacity: 0.5
          }
        }
      }]
    }
  };
  var properties = Object(merge["a" /* default */])(defaultProperties, propertiesProp);
  return properties;
};

/* harmony default export */ var components_legend = (legend_legend);
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/components/index.js
// export { default as axis } from './axis';
// export { default as box } from './box';
// export { default as grid } from './grid';
// export { default as labels } from './labels';
// export { default as range } from './range';
// export { default as tooltip } from './tooltip';
// export { default as domPointLabel } from './domPointLabel';
// export { default as legend } from './legend';
// // export { default as line } from './line';
// export { default as pie } from './pie';
// export { default as point } from './point';









/* harmony default export */ var settings_components = ({
  axis: components_axis,
  box: components_box,
  point: components_point,
  lineArea: components_lineArea,
  grid: components_grid,
  labels: components_labels,
  range: components_range,
  tooltip: components_tooltip,
  legend: components_legend
});
// CONCATENATED MODULE: ./src/components/QdtViz/QdtViz.jsx




/**
 * @name QdtViz
 * @param {object} app - Qlik Capability Api App
 * @param {options} object - Options
 * https://help.qlik.com/en-US/sense-developer/April2020/Subsystems/APIs/Content/Sense_ClientAPIs/CapabilityAPIs/VisualizationAPI/VisualizationAPI.htm
*/





var QdtViz_QdtViz = function QdtViz(_ref) {
  var app = _ref.app,
      optionsProp = _ref.options;
  var defaultOptions = {
    multiple: false,
    noSelections: false,
    noInteraction: false,
    type: 'barchart',
    cols: [],
    options: {},
    height: 400
  };
  var options = Object(merge["a" /* default */])(defaultOptions, optionsProp);
  var elementRef = Object(react["useRef"])(null);

  var _useState = Object(react["useState"])(null),
      _useState2 = slicedToArray_default()(_useState, 2),
      qViz = _useState2[0],
      setQViz = _useState2[1];

  var create =
  /*#__PURE__*/
  function () {
    var _ref2 = asyncToGenerator_default()(
    /*#__PURE__*/
    regenerator_default.a.mark(function _callee() {
      var qVizPromise, _qViz;

      return regenerator_default.a.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (options.id && options.id === 'CurrentSelections') {
                qVizPromise = app.getObject(elementRef.current, 'CurrentSelections');
                options.height = 50;
              } else if (options.id) {
                qVizPromise = app.visualization.get(options.id);
              } else {
                qVizPromise = app.visualization.create(options.type, options.cols, options.options);
              } // const qVizPromise = (options.id) ? app.visualization.get(options.id) : app.visualization.create(options.type, options.cols, options.options); // eslint-disable-line max-len


              _context.next = 3;
              return qVizPromise;

            case 3:
              _qViz = _context.sent;
              if (options.id && options.id !== 'CurrentSelections') _qViz.setOptions(options);
              _context.next = 7;
              return setQViz(_qViz);

            case 7:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function create() {
      return _ref2.apply(this, arguments);
    };
  }();

  var show = function show() {
    qViz.show(elementRef.current, {
      noSelections: options.noSelections,
      noInteraction: options.noInteraction
    });
  };

  var close = function close() {
    qViz.close();
  };

  var resize = function resize() {
    qViz.resize();
  };

  Object(react["useEffect"])(function () {
    asyncToGenerator_default()(
    /*#__PURE__*/
    regenerator_default.a.mark(function _callee2() {
      return regenerator_default.a.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              if (qViz) {
                _context2.next = 3;
                break;
              }

              _context2.next = 3;
              return create();

            case 3:
              if (qViz && options.id !== 'CurrentSelections') show();
              window.addEventListener('resize', resize);

            case 5:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }))();

    return function () {
      if (qViz) close();
      window.removeEventListener('resize', resize);
    };
  }, [close, create, options.id, qViz, resize, show]);
  return react_default.a.createElement("div", {
    ref: elementRef,
    style: {
      height: options.height
    }
  });
};

QdtViz_QdtViz.propTypes = {
  app: prop_types_default.a.object,
  options: prop_types_default.a.object
};
QdtViz_QdtViz.defaultProps = {
  app: null,
  options: {}
};
/* harmony default export */ var components_QdtViz_QdtViz = (function (_ref4) {
  var element = _ref4.element,
      app = _ref4.app,
      options = _ref4.options;
  react_dom_default.a.unmountComponentAtNode(element);
  react_dom_default.a.render(react_default.a.createElement(QdtViz_QdtViz, {
    app: app,
    options: options
  }), element);
}); // export default QdtSelect;
// EXTERNAL MODULE: ./src/components/QdtPicasso/settings/interactions/rangePan.js
var rangePan = __webpack_require__(19);

// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/interactions/tooltipHover.js


var tooltipHover_tooltipHover = function tooltipHover() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$properties = _ref.properties,
      propertiesProp = _ref$properties === void 0 ? {} : _ref$properties;

  var defaultProperties = {
    type: 'native',
    events: {
      mousemove: function mousemove(e) {
        this.chart.component('tooltip').emit('show', e);
      },
      mouseleave: function mouseleave() {
        this.chart.component('tooltip').emit('hide');
      }
    }
  };
  var properties = Object(merge["a" /* default */])(defaultProperties, propertiesProp);
  return properties;
};

/* harmony default export */ var interactions_tooltipHover = (tooltipHover_tooltipHover);
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/utils/formatters.js

picasso_esm.formatter('abs', function () {
  return function (v) {
    return Math.abs(v);
  };
});
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/barchart.js
















var barchart_BarChart = function BarChart() {
  var _scales;

  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$theme = _ref.theme,
      themeProp = _ref$theme === void 0 ? {} : _ref$theme,
      _ref$properties = _ref.properties,
      propertiesProp = _ref$properties === void 0 ? {} : _ref$properties,
      _ref$orientation = _ref.orientation,
      orientation = _ref$orientation === void 0 ? 'vertical' : _ref$orientation,
      _ref$type = _ref.type,
      type = _ref$type === void 0 ? 'standard' : _ref$type,
      _ref$xAxis = _ref.xAxis,
      xAxisProp = _ref$xAxis === void 0 ? {} : _ref$xAxis,
      _ref$yAxis = _ref.yAxis,
      yAxisProp = _ref$yAxis === void 0 ? {} : _ref$yAxis,
      _ref$grid = _ref.grid,
      gridProp = _ref$grid === void 0 ? {} : _ref$grid,
      _ref$box = _ref.box,
      boxProp = _ref$box === void 0 ? {} : _ref$box,
      _ref$labels = _ref.labels,
      labelsProp = _ref$labels === void 0 ? {} : _ref$labels,
      _ref$legend = _ref.legend,
      legendProp = _ref$legend === void 0 ? {} : _ref$legend,
      _ref$range = _ref.range,
      rangeProp = _ref$range === void 0 ? {} : _ref$range,
      _ref$tooltip = _ref.tooltip,
      tooltipProp = _ref$tooltip === void 0 ? {} : _ref$tooltip;

  var theme = Object(merge["a" /* default */])(Light, themeProp);
  var majorScale = orientation === 'vertical' && 'x' || orientation === 'horizontal' && 'y' || null;
  var minorScale = orientation === 'vertical' && 'y' || orientation === 'horizontal' && 'x' || null;
  var defaultProperties = {
    scales: (_scales = {}, defineProperty_default()(_scales, majorScale, {
      data: {
        extract: {
          field: 'qDimensionInfo/0'
        }
      },
      padding: 0.2
    }), defineProperty_default()(_scales, minorScale, {
      data: {
        field: 'qMeasureInfo/0'
      },
      include: [0],
      invert: orientation === 'vertical'
    }), _scales),
    components: [],
    interactions: []
  };

  if (type === 'standard') {
    if (xAxisProp) defaultProperties.components.push(components_axis(Object(merge["a" /* default */])({
      scale: 'x'
    }, xAxisProp)));
    if (yAxisProp) defaultProperties.components.push(components_axis(Object(merge["a" /* default */])({
      scale: 'y'
    }, yAxisProp)));

    if (gridProp) {
      defaultProperties.components.push(components_grid(Object(merge["a" /* default */])({
        x: orientation === 'horizontal',
        y: orientation === 'vertical'
      }, gridProp)));
    }

    if (boxProp) {
      defaultProperties.components.push(components_box(Object(merge["a" /* default */])({
        orientation: orientation
      }, boxProp)));
    }

    if (labelsProp) defaultProperties.components.push(components_labels(Object(merge["a" /* default */])({
      orientation: orientation
    }, labelsProp)));

    if (rangeProp) {
      defaultProperties.components.push(components_range(Object(merge["a" /* default */])({
        scale: majorScale
      }, rangeProp)));
      defaultProperties.interactions.push(Object(rangePan["a" /* default */])({
        scale: majorScale
      }));
    }

    if (tooltipProp) {
      defaultProperties.components.push(components_tooltip(Object(merge["a" /* default */])({}, tooltipProp)));
      defaultProperties.interactions.push(interactions_tooltipHover());
    }
  }

  if (type === 'stacked') {
    defaultProperties.collections = [{
      key: 'stacked',
      data: {
        extract: {
          field: 'qDimensionInfo/0',
          value: function value(d) {
            return d.qText;
          },
          // qElemNumber
          props: {
            series: {
              field: 'qDimensionInfo/1',
              value: function value(d) {
                return d.qText;
              }
            },
            end: {
              field: 'qMeasureInfo/0'
            },
            qElemNumber: {
              value: function value(d) {
                return d.qElemNumber;
              }
            }
          }
        },
        stack: {
          stackKey: function stackKey(d) {
            return d.value;
          },
          value: function value(d) {
            return d.end.value;
          }
        }
      }
    }];
    defaultProperties.scales[majorScale].data = {
      extract: {
        field: 'qDimensionInfo/0',
        value: function value(d) {
          return d.qText;
        }
      }
    };
    defaultProperties.scales[minorScale].data = {
      collection: {
        key: 'stacked'
      }
    };
    defaultProperties.scales.color = {
      data: {
        extract: {
          field: 'qDimensionInfo/1',
          value: function value(d) {
            return d.qText;
          }
        }
      },
      range: Object.values(theme.palette).map(function (color) {
        return color.main;
      }),
      type: 'color'
    };
    if (xAxisProp) defaultProperties.components.push(components_axis(Object(merge["a" /* default */])({
      scale: 'x'
    }, xAxisProp)));
    if (yAxisProp) defaultProperties.components.push(components_axis(Object(merge["a" /* default */])({
      scale: 'y'
    }, yAxisProp)));

    if (gridProp) {
      defaultProperties.components.push(components_grid(Object(merge["a" /* default */])({
        x: orientation === 'horizontal',
        y: orientation === 'vertical'
      }, gridProp)));
    }

    if (boxProp) {
      defaultProperties.components.push(components_box(Object(merge["a" /* default */])({
        orientation: orientation,
        properties: {
          data: {
            collection: 'stacked'
          },
          settings: {
            box: {
              fill: {
                scale: 'color',
                ref: 'series'
              },
              strokeWidth: 0
            }
          },
          brush: {
            trigger: [{
              on: 'tap',
              contexts: ['select'],
              data: ['qElemNumber']
            }]
          }
        }
      }, boxProp)));
    }

    if (labelsProp) defaultProperties.components.push(components_labels(Object(merge["a" /* default */])({
      orientation: orientation
    }, labelsProp)));
    if (legendProp) defaultProperties.components.push(components_legend(Object(merge["a" /* default */])({
      properties: {
        scale: 'color'
      }
    }, legendProp)));

    if (rangeProp) {
      defaultProperties.components.push(components_range(Object(merge["a" /* default */])({
        scale: majorScale
      }, rangeProp)));
      defaultProperties.interactions.push(Object(rangePan["a" /* default */])({
        scale: majorScale
      }));
    }

    if (tooltipProp) {
      defaultProperties.components.push(components_tooltip(Object(merge["a" /* default */])({}, tooltipProp)));
      defaultProperties.interactions.push(interactions_tooltipHover());
    }
  }

  if (type === 'gauge') {
    console.log(defaultProperties);
  }

  if (type === 'group') {
    /* define group barchart */
  }

  if (type === 'butterfly') {
    defaultProperties.scales[minorScale] = {
      data: {
        fields: ['qMeasureInfo/0', 'qMeasureInfo/1']
      },
      expand: 0.1,
      min: function min(_ref2) {
        var data = _ref2.data;
        return -Math.max.apply(Math, toConsumableArray_default()(data.fields.map(function (f) {
          return f.max();
        }))) * 1.1;
      }
    };
    defaultProperties.scales.color = {
      range: [theme.palette.primary.main, theme.palette.secondary.main],
      type: 'color'
    };
    if (xAxisProp) defaultProperties.components.push(components_axis(Object(merge["a" /* default */])({
      scale: 'x',
      formatter: {
        type: 'abs'
      }
    }, xAxisProp)));
    if (yAxisProp) defaultProperties.components.push(components_axis(Object(merge["a" /* default */])({
      scale: 'y'
    }, yAxisProp)));

    if (gridProp) {
      defaultProperties.components.push(components_grid(Object(merge["a" /* default */])({
        x: orientation === 'horizontal',
        y: orientation === 'vertical'
      }, gridProp)));
    }

    if (boxProp) {
      defaultProperties.components.push(components_box(Object(merge["a" /* default */])({
        orientation: orientation,
        properties: {
          settings: {
            minor: {
              start: function start(d) {
                return d.resources.scale(minorScale)(0);
              },
              end: function end(d) {
                return d.resources.scale(minorScale)(d.datum.end.value * -1);
              }
            },
            box: {
              fill: function fill(d) {
                return d.resources.scale('color')(0);
              }
            }
          }
        }
      }, boxProp)));
      defaultProperties.components.push(components_box(Object(merge["a" /* default */])({
        orientation: orientation,
        properties: {
          data: {
            extract: {
              props: {
                end: {
                  field: 'qMeasureInfo/1'
                }
              }
            }
          },
          settings: {
            minor: {
              start: function start(d) {
                return d.resources.scale(minorScale)(0);
              },
              end: function end(d) {
                return d.resources.scale(minorScale)(d.datum.end.value);
              }
            },
            box: {
              fill: function fill(d) {
                return d.resources.scale('color')(1);
              }
            }
          }
        }
      }, boxProp)));
    }

    if (labelsProp) defaultProperties.components.push(components_labels(Object(merge["a" /* default */])({
      orientation: orientation
    }, labelsProp)));

    if (rangeProp) {
      defaultProperties.components.push(components_range(Object(merge["a" /* default */])({
        scale: majorScale
      }, rangeProp)));
      defaultProperties.interactions.push(Object(rangePan["a" /* default */])({
        scale: majorScale
      }));
    }

    if (tooltipProp) {
      defaultProperties.components.push(components_tooltip(Object(merge["a" /* default */])({}, tooltipProp)));
      defaultProperties.interactions.push(interactions_tooltipHover());
    }
  }

  if (type === 'rank') {
    defaultProperties.scales[majorScale].data.extract.props = {
      rank: {
        field: 'qMeasureInfo/1'
      }
    };

    defaultProperties.scales[majorScale].data.sort = function (a, b) {
      return a.rank.value - b.rank.value;
    };

    defaultProperties.scales[minorScale].expand = 0.5;
    defaultProperties.scales.color = {
      data: {
        extract: {
          field: 'qMeasureInfo/1'
        }
      },
      range: [theme.palette.primary.main, theme.palette.secondary.main],
      type: 'color'
    };

    if (gridProp) {
      defaultProperties.components.push(components_grid(Object(merge["a" /* default */])({
        x: orientation === 'horizontal',
        y: orientation === 'vertical'
      }, gridProp)));
    }

    defaultProperties.components.push(components_box({
      orientation: orientation,
      properties: {
        data: {
          extract: {
            props: {
              rank: {
                field: 'qMeasureInfo/1'
              }
            }
          }
        },
        settings: {
          major: {
            fn: function fn(d) {
              return d.datum.rank.value * d.scale.step() - d.scale.paddingOuter() * d.scale.bandwidth() - 0.5 * d.scale.bandwidth();
            }
          },
          box: {
            fill: {
              scale: 'color',
              fn: function fn(d) {
                return d.scale(d.datum.rank.value);
              }
            },
            strokeWidth: 0,
            width: 0.25
          }
        }
      }
    })); // defaultProperties.components.push(
    //   box({
    //     orientation,
    //     properties: {
    //       key: 'end-bars',
    //       data: {
    //         extract: {
    //           props: {
    //             start: { field: 'qMeasureInfo/0' },
    //             end: { field: 'qMeasureInfo/0' },
    //             rank: { field: 'qMeasureInfo/1' },
    //           },
    //         },
    //       },
    //       settings: {
    //         major: {
    //           fn: (d) => (d.datum.rank.value * d.scale.step()) - (d.scale.paddingOuter() * d.scale.bandwidth()) - (0.5 * d.scale.bandwidth()),
    //         },
    //         box: {
    //           fill: { scale: 'c', fn: (d) => d.scale(d.datum.rank.value) },
    //           width: 0.6,
    //           minHeightPx: 3,
    //         },
    //       },
    //     },
    //   }),
    // );

    defaultProperties.components.push(components_box({
      orientation: orientation,
      properties: {
        key: 'label-bars',
        data: {
          extract: {
            props: {
              rank: {
                field: 'qMeasureInfo/1'
              }
            }
          }
        },
        settings: {
          major: {
            fn: function fn(d) {
              return d.datum.rank.value * d.scale.step() - d.scale.paddingOuter() * d.scale.bandwidth() - 0.5 * d.scale.bandwidth();
            }
          },
          box: {
            opacity: 0,
            width: 1
          }
        }
      }
    }));
    var valueLabels = components_labels({
      orientation: orientation,
      component: 'label-bars',
      labels: [{
        placements: [{
          position: 'outside',
          fill: '#666'
        }],
        label: function label(node) {
          return defaultLocale_format('$.3s')(node.data.end.value).replace(/G/, 'B');
        }
      }]
    });
    valueLabels.settings.sources[0].strategy.settings.fontSize = 12;
    valueLabels.settings.sources[0].strategy.settings.padding = {
      top: 0,
      right: 0,
      bottom: 0,
      left: 6
    };
    defaultProperties.components.push(valueLabels);
    var axisLabels = components_labels({
      orientation: orientation,
      component: 'label-bars',
      labels: [{
        placements: [{
          position: 'opposite',
          fill: '#666'
        }],
        label: function label(node) {
          return node.data.label;
        }
      }]
    });
    axisLabels.settings.sources[0].strategy.settings.fontSize = 14;
    axisLabels.settings.sources[0].strategy.settings.padding = {
      top: 0,
      right: 8,
      bottom: 0,
      left: 0
    };
    defaultProperties.components.push(axisLabels);
  }

  if (type === 'mekko') {
    /* define merimekko */
  }

  var properties = Object(merge["a" /* default */])(defaultProperties, propertiesProp);
  return properties;
};

/* harmony default export */ var barchart = (barchart_BarChart);
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/lineChart.js
/* eslint-disable */











var lineChart_lineChart = function lineChart() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$theme = _ref.theme,
      themeProp = _ref$theme === void 0 ? {} : _ref$theme,
      _ref$properties = _ref.properties,
      propertiesProp = _ref$properties === void 0 ? {} : _ref$properties,
      _ref$type = _ref.type,
      type = _ref$type === void 0 ? 'standard' : _ref$type,
      _ref$showArea = _ref.showArea,
      showArea = _ref$showArea === void 0 ? false : _ref$showArea,
      _ref$xAxis = _ref.xAxis,
      xAxisProp = _ref$xAxis === void 0 ? {} : _ref$xAxis,
      _ref$yAxis = _ref.yAxis,
      yAxisProp = _ref$yAxis === void 0 ? {} : _ref$yAxis,
      _ref$grid = _ref.grid,
      gridProp = _ref$grid === void 0 ? {} : _ref$grid,
      _ref$lineArea = _ref.lineArea,
      lineAreaProp = _ref$lineArea === void 0 ? {} : _ref$lineArea,
      _ref$point = _ref.point,
      pointProp = _ref$point === void 0 ? {} : _ref$point,
      _ref$range = _ref.range,
      rangeProp = _ref$range === void 0 ? {} : _ref$range,
      _ref$tooltip = _ref.tooltip,
      tooltipProp = _ref$tooltip === void 0 ? {} : _ref$tooltip;

  var theme = Object(merge["a" /* default */])(Light, themeProp); //eslint-disable-line

  var defaultProperties = {
    scales: {
      x: {
        data: {
          extract: {
            field: 'qDimensionInfo/0'
          }
        },
        expand: 0.01
      },
      y: {
        data: {
          field: 'qMeasureInfo/0'
        },
        include: [0],
        invert: true,
        expand: 0.015
      }
    },
    components: [],
    interactions: []
  };

  if (type === 'standard') {
    if (xAxisProp) defaultProperties.components.push(components_axis(Object(merge["a" /* default */])({
      scale: 'x'
    }, xAxisProp)));
    if (yAxisProp) defaultProperties.components.push(components_axis(Object(merge["a" /* default */])({
      scale: 'y'
    }, yAxisProp)));
    if (gridProp) defaultProperties.components.push(components_grid(Object(merge["a" /* default */])({
      x: false,
      y: true
    }, gridProp)));
    if (lineAreaProp) defaultProperties.components.push(components_lineArea(Object(merge["a" /* default */])({
      showArea: showArea
    }, lineAreaProp)));
    if (pointProp) defaultProperties.components.push(components_point(Object(merge["a" /* default */])({}, pointProp)));

    if (rangeProp) {
      defaultProperties.components.push(components_range(Object(merge["a" /* default */])({}, rangeProp)));
      defaultProperties.interactions.push(Object(rangePan["a" /* default */])());
    }

    if (tooltipProp) {
      defaultProperties.components.push(components_tooltip(Object(merge["a" /* default */])({}, tooltipProp)));
      defaultProperties.interactions.push(interactions_tooltipHover());
    }
  }

  if (type === 'multi') {
    defaultProperties.scales.color = {
      data: {
        extract: {
          field: 'qDimensionInfo/1'
        }
      },
      range: Object.values(theme.palette).map(function (color) {
        return color.main;
      }),
      type: 'color'
    };
    if (xAxisProp) defaultProperties.components.push(components_axis(Object(merge["a" /* default */])({
      scale: 'x'
    }, xAxisProp)));
    if (yAxisProp) defaultProperties.components.push(components_axis(Object(merge["a" /* default */])({
      scale: 'y'
    }, yAxisProp)));
    if (gridProp) defaultProperties.components.push(components_grid(Object(merge["a" /* default */])({
      x: false,
      y: true
    }, gridProp)));
    if (lineAreaProp) defaultProperties.components.push(components_lineArea(Object(merge["a" /* default */])({
      showArea: showArea,
      properties: {
        data: {
          extract: {
            props: {
              series: {
                field: 'qDimensionInfo/1'
              }
            }
          }
        },
        settings: {
          coordinates: {
            layerId: {
              ref: 'series'
            }
          },
          layers: {
            line: {
              stroke: {
                scale: 'color',
                ref: 'series'
              }
            },
            area: {
              fill: {
                scale: 'color',
                ref: 'series'
              }
            }
          }
        }
      }
    }, lineAreaProp)));

    if (pointProp) {
      defaultProperties.components.push(components_point(Object(merge["a" /* default */])({}, pointProp)));
      defaultProperties.scales.x;
    }

    if (rangeProp) {
      defaultProperties.components.push(components_range(Object(merge["a" /* default */])({}, rangeProp)));
      defaultProperties.interactions.push(Object(rangePan["a" /* default */])());
    }

    if (tooltipProp) {
      defaultProperties.components.push(components_tooltip(Object(merge["a" /* default */])({}, tooltipProp)));
      defaultProperties.interactions.push(interactions_tooltipHover());
    }
  }

  if (type === 'stacked') {
    defaultProperties.collections = [{
      key: 'stacked',
      data: {
        extract: {
          field: 'qDimensionInfo/0',
          props: {
            series: {
              field: 'qDimensionInfo/1'
            },
            end: {
              field: 'qMeasureInfo/0'
            }
          }
        },
        stack: {
          stackKey: function stackKey(d) {
            return d.value;
          },
          value: function value(d) {
            return d.end.value;
          }
        }
      }
    }];
    defaultProperties.scales.y.data = {
      collection: {
        key: 'stacked'
      }
    };
    defaultProperties.scales.color = {
      data: {
        extract: {
          field: 'qDimensionInfo/1'
        }
      },
      range: Object.values(theme.palette).map(function (color) {
        return color.main;
      }),
      type: 'color'
    };
    if (xAxisProp) defaultProperties.components.push(components_axis(Object(merge["a" /* default */])({
      scale: 'x'
    }, xAxisProp)));
    if (yAxisProp) defaultProperties.components.push(components_axis(Object(merge["a" /* default */])({
      scale: 'y'
    }, yAxisProp)));
    if (gridProp) defaultProperties.components.push(components_grid(Object(merge["a" /* default */])({
      x: false,
      y: true
    }, gridProp)));
    if (lineAreaProp) defaultProperties.components.push(components_lineArea(Object(merge["a" /* default */])({
      showArea: showArea,
      properties: {
        data: {
          collection: 'stacked'
        },
        settings: {
          coordinates: {
            minor: {
              scale: 'y',
              ref: 'end'
            },
            minor0: {
              scale: 'y',
              ref: 'start'
            },
            layerId: {
              ref: 'series'
            }
          },
          layers: {
            line: {
              stroke: {
                scale: 'color',
                ref: 'series'
              }
            },
            area: {
              fill: {
                scale: 'color',
                ref: 'series'
              }
            }
          }
        }
      }
    }, lineAreaProp)));
    if (pointProp) defaultProperties.components.push(components_point(Object(merge["a" /* default */])({}, pointProp)));

    if (rangeProp) {
      defaultProperties.components.push(components_range(Object(merge["a" /* default */])({}, rangeProp)));
      defaultProperties.interactions.push(Object(rangePan["a" /* default */])());
    }

    if (tooltipProp) {
      defaultProperties.components.push(components_tooltip(Object(merge["a" /* default */])({}, tooltipProp)));
      defaultProperties.interactions.push(interactions_tooltipHover());
    }
  }

  if (type === 'rangeArea') {
    defaultProperties.scales.y.data = {
      fields: ['qMeasureInfo/0', 'qMeasureInfo/1']
    };
    if (xAxisProp) defaultProperties.components.push(components_axis(Object(merge["a" /* default */])({
      scale: 'x'
    }, xAxisProp)));
    if (yAxisProp) defaultProperties.components.push(components_axis(Object(merge["a" /* default */])({
      scale: 'y'
    }, yAxisProp)));
    if (gridProp) defaultProperties.components.push(components_grid(Object(merge["a" /* default */])({
      x: false,
      y: true
    }, gridProp)));
    defaultProperties.components.push(components_lineArea({
      showArea: true,
      properties: {
        data: {
          extract: {
            props: {
              y0: {
                field: 'qMeasureInfo/0'
              },
              y: {
                field: 'qMeasureInfo/1'
              }
            }
          }
        },
        settings: {
          coordinates: {
            minor0: {
              scale: 'y',
              ref: 'y0'
            }
          }
        }
      }
    })); //  defaultProperties.components.push(point({
    //   properties: {
    //     data: {
    //       extract: {
    //         props: {
    //           y: { field: 'qMeasureInfo/1' },
    //           num: { field: 'qMeasureInfo/1' },
    //         },
    //       },
    //     },
    //   },
    // }));

    defaultProperties.components.push(components_lineArea({
      showArea: false,
      properties: {
        key: 'line2',
        data: {
          extract: {
            props: {
              y: {
                field: 'qMeasureInfo/0'
              }
            }
          }
        },
        settings: {
          paddingStart: 10,
          layers: {
            area: {
              show: false
            },
            line: {
              stroke: theme.palette.secondary.main
            }
          }
        }
      }
    })); // defaultProperties.components.push(point({
    //   properties: {
    //     key: 'point2',
    //     data: {
    //       extract: {
    //         props: {
    //           y: { field: 'qMeasureInfo/0' },
    //           num: { field: 'qMeasureInfo/0' },
    //         },
    //       },
    //     },
    //     settings: {
    //       fill: theme.palette.secondary.main,
    //       stroke: theme.palette.secondary.main,
    //     },
    //   },
    // }));

    if (rangeProp) {
      defaultProperties.components.push(components_range(Object(merge["a" /* default */])({}, rangeProp)));
      defaultProperties.interactions.push(Object(rangePan["a" /* default */])());
    }

    if (tooltipProp) {
      defaultProperties.components.push(components_tooltip(Object(merge["a" /* default */])({}, tooltipProp)));
      defaultProperties.interactions.push(interactions_tooltipHover());
    }
  }

  var properties = Object(merge["a" /* default */])(defaultProperties, propertiesProp);
  return properties;
};

/* harmony default export */ var settings_lineChart = (lineChart_lineChart);
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/components/pie.js



var pie_pie = function pie() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$theme = _ref.theme,
      themeProp = _ref$theme === void 0 ? {} : _ref$theme,
      _ref$properties = _ref.properties,
      propertiesProp = _ref$properties === void 0 ? {} : _ref$properties;

  var theme = Object(merge["a" /* default */])(Light, themeProp); //eslint-disable-line

  var defaultProperties = {
    key: 'pie',
    type: 'pie',
    displayOrder: 1,
    data: {
      extract: {
        field: 'qDimensionInfo/0',
        props: {
          num: {
            field: 'qMeasureInfo/0'
          }
        }
      }
    },
    settings: {
      slice: {
        arc: {
          ref: 'num'
        },
        fill: {
          scale: 'c'
        },
        outerRadius: function outerRadius() {
          return 0.9;
        },
        strokeWidth: 1,
        stroke: 'rgba(255, 255, 255, 0.5)'
      }
    },
    brush: {
      trigger: [{
        on: 'tap',
        // action: 'toggle',
        contexts: ['select'] // data: ['qDimension'],
        // propagation: 'stop',
        // globalPropagation: 'stop',
        // touchRadius: 24,

      }],
      consume: [{
        context: 'select',
        style: {
          active: {
            opacity: 1
          },
          inactive: {
            opacity: 0.4
          }
        }
      }]
    }
  };
  var properties = Object(merge["a" /* default */])(defaultProperties, propertiesProp);
  return properties;
};

/* harmony default export */ var components_pie = (pie_pie);
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/pieChart.js






var pieChart_pieChart = function pieChart() {
  return {
    scales: {
      c: {
        data: {
          extract: {
            field: 'qDimensionInfo/0'
          }
        },
        type: 'color'
      }
    },
    components: [components_legend(), components_tooltip(), components_pie(), components_labels({
      component: 'pie',
      selector: 'path',
      type: 'slice',
      direction: 'horizontal'
    })],
    interactions: [interactions_tooltipHover()]
  };
};

/* harmony default export */ var settings_pieChart = (pieChart_pieChart);
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/components/domPointLabel.js



var domPointLabel_domPointLabel = function domPointLabel() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$theme = _ref.theme,
      themeProp = _ref$theme === void 0 ? {} : _ref$theme,
      _ref$properties = _ref.properties,
      propertiesProp = _ref$properties === void 0 ? {} : _ref$properties;

  var theme = Object(merge["a" /* default */])(Light, themeProp); //eslint-disable-line

  var defaultProperties = {
    key: 'domPointLabel',
    type: 'domPointLabel',
    displayOrder: 1,
    data: {
      extract: {
        field: 'qDimensionInfo/0',
        props: {
          x: {
            field: 'qMeasureInfo/1'
          },
          y: {
            field: 'qMeasureInfo/0'
          }
        }
      }
    },
    settings: {
      x: {
        scale: 'x'
      },
      y: {
        scale: 'y'
      },
      fontSize: '10px',
      color: '#000000',
      offset: 30,
      width: 50,
      height: 10
    }
  };
  var properties = Object(merge["a" /* default */])(defaultProperties, propertiesProp);
  return properties;
};

/* harmony default export */ var settings_components_domPointLabel = (domPointLabel_domPointLabel);
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/interactions/legendClick.js


var legendClick_legendClick = function legendClick() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$properties = _ref.properties,
      propertiesProp = _ref$properties === void 0 ? {} : _ref$properties;

  var defaultProperties = {
    type: 'native',
    events: {
      click: function click(e) {
        if (e.srcElement.dataset.componentKey && e.srcElement.dataset.action) {
          this.chart.component(e.srcElement.dataset.componentKey).emit(e.srcElement.dataset.action);
        }
      }
    }
  };
  var properties = Object(merge["a" /* default */])(defaultProperties, propertiesProp);
  return properties;
};

/* harmony default export */ var interactions_legendClick = (legendClick_legendClick);
// CONCATENATED MODULE: ./src/components/QdtPicasso/settings/scatterPlot.js












var scatterPlot_ScatterPlot = function ScatterPlot() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$theme = _ref.theme,
      themeProp = _ref$theme === void 0 ? {} : _ref$theme,
      _ref$properties = _ref.properties,
      propertiesProp = _ref$properties === void 0 ? {} : _ref$properties,
      _ref$point = _ref.point,
      pointProp = _ref$point === void 0 ? {} : _ref$point,
      _ref$pointImage = _ref.pointImage,
      pointImageProp = _ref$pointImage === void 0 ? null : _ref$pointImage,
      _ref$labels = _ref.labels,
      labelsProp = _ref$labels === void 0 ? {} : _ref$labels,
      _ref$legend = _ref.legend,
      legendProp = _ref$legend === void 0 ? {} : _ref$legend,
      _ref$tooltip = _ref.tooltip,
      tooltipProp = _ref$tooltip === void 0 ? {} : _ref$tooltip,
      _ref$range = _ref.range,
      rangeProp = _ref$range === void 0 ? {} : _ref$range;

  var theme = Object(merge["a" /* default */])(Light, themeProp); //eslint-disable-line

  var defaultProperties = {
    scales: {
      x: {
        data: {
          field: 'qMeasureInfo/1'
        },
        expand: 0.1
      },
      y: {
        data: {
          field: 'qMeasureInfo/0'
        },
        expand: 0.2,
        invert: true
      },
      c: {
        data: {
          extract: {
            field: 'qDimensionInfo/0'
          }
        },
        // range: theme.palette,
        type: 'color'
      }
    },
    components: [components_axis(), components_axis({
      scale: 'y'
    })],
    interactions: []
  };
  defaultProperties.components.push(components_point(Object(merge["a" /* default */])({
    properties: {
      displayOrder: 3,
      data: {
        extract: {
          props: {
            x: {
              field: 'qMeasureInfo/1'
            },
            group: {
              field: 'qDimensionInfo/0'
            }
          }
        }
      },
      settings: {
        stroke: {
          scale: 'c',
          ref: 'group'
        },
        fill: {
          scale: 'c',
          ref: 'group'
        }
      }
    }
  }, pointProp)));

  if (pointImageProp) {
    defaultProperties.components.push(components_point(Object(merge["a" /* default */])({
      properties: {
        type: 'domPointImage',
        key: 'point2',
        displayOrder: 4,
        data: {
          extract: {
            props: {
              x: {
                field: 'qMeasureInfo/1'
              },
              group: {
                field: 'qDimensionInfo/0'
              }
            }
          }
        },
        settings: {
          image: 'https://webapps.qlik.com/qdt-components/plain-html/emoji_smiley.png',
          width: 32,
          height: 32
        }
      }
    }, pointImageProp)));
  }

  if (labelsProp) {
    defaultProperties.components.push(settings_components_domPointLabel(Object(merge["a" /* default */])({
      properties: {
        displayOrder: 5
      }
    }, labelsProp)));
  }

  if (legendProp) {
    defaultProperties.components.push(components_legend(Object(merge["a" /* default */])({
      properties: {
        displayOrder: 6
      }
    }, legendProp)));
    defaultProperties.interactions.push(interactions_legendClick());
  }

  if (tooltipProp) {
    defaultProperties.components.push(components_tooltip(Object(merge["a" /* default */])({}, tooltipProp)));
    defaultProperties.interactions.push(interactions_tooltipHover());
  }

  if (rangeProp) {
    defaultProperties.components.push(components_range());
    defaultProperties.components.push(components_range({
      scale: 'y'
    }));
    defaultProperties.interactions.push(Object(rangePan["a" /* default */])());
    defaultProperties.interactions.push(Object(rangePan["a" /* default */])({
      scale: 'y'
    }));
  }

  var properties = Object(merge["a" /* default */])(defaultProperties, propertiesProp);
  return properties;
};

/* harmony default export */ var scatterPlot = (scatterPlot_ScatterPlot);
// CONCATENATED MODULE: ./src/index.jsx
/* concated harmony reexport qdtNova */__webpack_require__.d(__webpack_exports__, "qdtNova", function() { return qdtNova; });
/* concated harmony reexport qdtEnigma */__webpack_require__.d(__webpack_exports__, "qdtEnigma", function() { return src_qdtEnigma; });
/* concated harmony reexport qdtCapabilityApp */__webpack_require__.d(__webpack_exports__, "qdtCapabilityApp", function() { return qdtCapabilityApp; });
/* concated harmony reexport qdtCompose */__webpack_require__.d(__webpack_exports__, "qdtCompose", function() { return qdtCompose; });
/* concated harmony reexport QdtTheme */__webpack_require__.d(__webpack_exports__, "QdtTheme", function() { return themes; });
/* concated harmony reexport useThree */__webpack_require__.d(__webpack_exports__, "useThree", function() { return hooks_useThree; });
/* concated harmony reexport QdtButton */__webpack_require__.d(__webpack_exports__, "QdtButton", function() { return components_QdtButton_QdtButton; });
/* concated harmony reexport QdtKpi */__webpack_require__.d(__webpack_exports__, "QdtKpi", function() { return components_QdtKpi_QdtKpi; });
/* concated harmony reexport QdtSelect */__webpack_require__.d(__webpack_exports__, "QdtSelect", function() { return components_QdtSelect_QdtSelect; });
/* concated harmony reexport QdtSelectSimple */__webpack_require__.d(__webpack_exports__, "QdtSelectSimple", function() { return QdtSelectSimple; });
/* concated harmony reexport QdtList */__webpack_require__.d(__webpack_exports__, "QdtList", function() { return components_QdtList_QdtList; });
/* concated harmony reexport QdtTable */__webpack_require__.d(__webpack_exports__, "QdtTable", function() { return components_QdtTable_QdtTable; });
/* concated harmony reexport QdtSequencer */__webpack_require__.d(__webpack_exports__, "QdtSequencer", function() { return components_QdtSequencer_QdtSequencer; });
/* concated harmony reexport QdtSlider */__webpack_require__.d(__webpack_exports__, "QdtSlider", function() { return components_QdtSlider_QdtSlider; });
/* concated harmony reexport QdtMapBox */__webpack_require__.d(__webpack_exports__, "QdtMapBox", function() { return QdtMapbox_QdtMapBox; });
/* concated harmony reexport QdtSelections */__webpack_require__.d(__webpack_exports__, "QdtSelections", function() { return components_QdtSelections_QdtSelections; });
/* concated harmony reexport QdtSearch */__webpack_require__.d(__webpack_exports__, "QdtSearch", function() { return components_QdtSearch_QdtSearch; });
/* concated harmony reexport QdtThree */__webpack_require__.d(__webpack_exports__, "QdtThree", function() { return components_QdtThree_QdtThree; });
/* concated harmony reexport QdtPicasso */__webpack_require__.d(__webpack_exports__, "QdtPicasso", function() { return QdtPicasso_QdtPicasso; });
/* concated harmony reexport QdtPicassoComponents */__webpack_require__.d(__webpack_exports__, "QdtPicassoComponents", function() { return settings_components; });
/* concated harmony reexport QdtViz */__webpack_require__.d(__webpack_exports__, "QdtViz", function() { return components_QdtViz_QdtViz; });
/* concated harmony reexport useSessionObject */__webpack_require__.d(__webpack_exports__, "useSessionObject", function() { return hooks_useSessionObject; });
/* concated harmony reexport useBarChartSettings */__webpack_require__.d(__webpack_exports__, "useBarChartSettings", function() { return barchart; });
/* concated harmony reexport useLineChartSettings */__webpack_require__.d(__webpack_exports__, "useLineChartSettings", function() { return settings_lineChart; });
/* concated harmony reexport usePieChartSettings */__webpack_require__.d(__webpack_exports__, "usePieChartSettings", function() { return settings_pieChart; });
/* concated harmony reexport useScatterPlotSettings */__webpack_require__.d(__webpack_exports__, "useScatterPlotSettings", function() { return scatterPlot; });



























/***/ }),
/* 130 */,
/* 131 */,
/* 132 */,
/* 133 */,
/* 134 */,
/* 135 */,
/* 136 */,
/* 137 */,
/* 138 */,
/* 139 */,
/* 140 */,
/* 141 */,
/* 142 */,
/* 143 */,
/* 144 */,
/* 145 */,
/* 146 */,
/* 147 */,
/* 148 */,
/* 149 */,
/* 150 */,
/* 151 */,
/* 152 */,
/* 153 */,
/* 154 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return useTheme; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _ThemeContext__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(36);


function useTheme() {
  return react__WEBPACK_IMPORTED_MODULE_0___default.a.useContext(_ThemeContext__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"]);
}

/***/ }),
/* 155 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* eslint-disable no-restricted-syntax */
function getThemeProps(params) {
  var theme = params.theme,
      name = params.name,
      props = params.props;

  if (!theme || !theme.props || !theme.props[name]) {
    return props;
  } // Resolve default props, code borrow from React source.
  // https://github.com/facebook/react/blob/15a8f031838a553e41c0b66eb1bcf1da8448104d/packages/react/src/ReactElement.js#L221


  var defaultProps = theme.props[name];
  var propName;

  for (propName in defaultProps) {
    if (props[propName] === undefined) {
      props[propName] = defaultProps[propName];
    }
  }

  return props;
}

/* harmony default export */ __webpack_exports__["a"] = (getThemeProps);

/***/ }),
/* 156 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);



function mergeClasses() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var baseClasses = options.baseClasses,
      newClasses = options.newClasses,
      Component = options.Component;

  if (!newClasses) {
    return baseClasses;
  }

  var nextClasses = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])({}, baseClasses);

  if (false) {}

  Object.keys(newClasses).forEach(function (key) {
    if (false) {}

    if (newClasses[key]) {
      nextClasses[key] = "".concat(baseClasses[key], " ").concat(newClasses[key]);
    }
  });
  return nextClasses;
}

/* harmony default export */ __webpack_exports__["a"] = (mergeClasses);

/***/ }),
/* 157 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXTERNAL MODULE: ./node_modules/@material-ui/styles/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js + 1 modules
var objectWithoutProperties = __webpack_require__(24);

// EXTERNAL MODULE: ./node_modules/@material-ui/styles/node_modules/@babel/runtime/helpers/esm/extends.js
var esm_extends = __webpack_require__(17);

// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__(0);
var react_default = /*#__PURE__*/__webpack_require__.n(react);

// CONCATENATED MODULE: ./node_modules/jss/node_modules/@babel/runtime/helpers/esm/extends.js
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);
}
// CONCATENATED MODULE: ./node_modules/is-in-browser/dist/module.js
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var isBrowser = (typeof window === "undefined" ? "undefined" : _typeof(window)) === "object" && (typeof document === "undefined" ? "undefined" : _typeof(document)) === 'object' && document.nodeType === 9;

/* harmony default export */ var dist_module = (isBrowser);

// CONCATENATED MODULE: ./node_modules/tiny-warning/dist/tiny-warning.esm.js
var isProduction = "production" === 'production';
function warning(condition, message) {
  if (!isProduction) {
    if (condition) {
      return;
    }

    var text = "Warning: " + message;

    if (typeof console !== 'undefined') {
      console.warn(text);
    }

    try {
      throw Error(text);
    } catch (x) {}
  }
}

/* harmony default export */ var tiny_warning_esm = (warning);

// CONCATENATED MODULE: ./node_modules/jss/node_modules/@babel/runtime/helpers/esm/createClass.js
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);
  }
}

function _createClass(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties(Constructor, staticProps);
  return Constructor;
}
// CONCATENATED MODULE: ./node_modules/jss/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js
function _inheritsLoose(subClass, superClass) {
  subClass.prototype = Object.create(superClass.prototype);
  subClass.prototype.constructor = subClass;
  subClass.__proto__ = superClass;
}
// CONCATENATED MODULE: ./node_modules/jss/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js
function _assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return self;
}
// CONCATENATED MODULE: ./node_modules/jss/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js
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;
}
// CONCATENATED MODULE: ./node_modules/jss/dist/jss.esm.js








var plainObjectConstrurctor = {}.constructor;
function cloneStyle(style) {
  if (style == null || typeof style !== 'object') return style;
  if (Array.isArray(style)) return style.map(cloneStyle);
  if (style.constructor !== plainObjectConstrurctor) return style;
  var newStyle = {};

  for (var name in style) {
    newStyle[name] = cloneStyle(style[name]);
  }

  return newStyle;
}

/**
 * Create a rule instance.
 */

function createRule(name, decl, options) {
  if (name === void 0) {
    name = 'unnamed';
  }

  var jss = options.jss;
  var declCopy = cloneStyle(decl);
  var rule = jss.plugins.onCreateRule(name, declCopy, options);
  if (rule) return rule; // It is an at-rule and it has no instance.

  if (name[0] === '@') {
     false ? undefined : void 0;
  }

  return null;
}

var join = function join(value, by) {
  var result = '';

  for (var i = 0; i < value.length; i++) {
    // Remove !important from the value, it will be readded later.
    if (value[i] === '!important') break;
    if (result) result += by;
    result += value[i];
  }

  return result;
};
/**
 * Converts array values to string.
 *
 * `margin: [['5px', '10px']]` > `margin: 5px 10px;`
 * `border: ['1px', '2px']` > `border: 1px, 2px;`
 * `margin: [['5px', '10px'], '!important']` > `margin: 5px 10px !important;`
 * `color: ['red', !important]` > `color: red !important;`
 */


function toCssValue(value, ignoreImportant) {
  if (ignoreImportant === void 0) {
    ignoreImportant = false;
  }

  if (!Array.isArray(value)) return value;
  var cssValue = ''; // Support space separated values via `[['5px', '10px']]`.

  if (Array.isArray(value[0])) {
    for (var i = 0; i < value.length; i++) {
      if (value[i] === '!important') break;
      if (cssValue) cssValue += ', ';
      cssValue += join(value[i], ' ');
    }
  } else cssValue = join(value, ', '); // Add !important, because it was ignored.


  if (!ignoreImportant && value[value.length - 1] === '!important') {
    cssValue += ' !important';
  }

  return cssValue;
}

/**
 * Indent a string.
 * http://jsperf.com/array-join-vs-for
 */
function indentStr(str, indent) {
  var result = '';

  for (var index = 0; index < indent; index++) {
    result += '  ';
  }

  return result + str;
}
/**
 * Converts a Rule to CSS string.
 */


function toCss(selector, style, options) {
  if (options === void 0) {
    options = {};
  }

  var result = '';
  if (!style) return result;
  var _options = options,
      _options$indent = _options.indent,
      indent = _options$indent === void 0 ? 0 : _options$indent;
  var fallbacks = style.fallbacks;
  if (selector) indent++; // Apply fallbacks first.

  if (fallbacks) {
    // Array syntax {fallbacks: [{prop: value}]}
    if (Array.isArray(fallbacks)) {
      for (var index = 0; index < fallbacks.length; index++) {
        var fallback = fallbacks[index];

        for (var prop in fallback) {
          var value = fallback[prop];

          if (value != null) {
            if (result) result += '\n';
            result += "" + indentStr(prop + ": " + toCssValue(value) + ";", indent);
          }
        }
      }
    } else {
      // Object syntax {fallbacks: {prop: value}}
      for (var _prop in fallbacks) {
        var _value = fallbacks[_prop];

        if (_value != null) {
          if (result) result += '\n';
          result += "" + indentStr(_prop + ": " + toCssValue(_value) + ";", indent);
        }
      }
    }
  }

  for (var _prop2 in style) {
    var _value2 = style[_prop2];

    if (_value2 != null && _prop2 !== 'fallbacks') {
      if (result) result += '\n';
      result += "" + indentStr(_prop2 + ": " + toCssValue(_value2) + ";", indent);
    }
  } // Allow empty style in this case, because properties will be added dynamically.


  if (!result && !options.allowEmpty) return result; // When rule is being stringified before selector was defined.

  if (!selector) return result;
  indent--;
  if (result) result = "\n" + result + "\n";
  return indentStr(selector + " {" + result, indent) + indentStr('}', indent);
}

var escapeRegex = /([[\].#*$><+~=|^:(),"'`\s])/g;
var nativeEscape = typeof CSS !== 'undefined' && CSS.escape;
var jss_esm_escape = (function (str) {
  return nativeEscape ? nativeEscape(str) : str.replace(escapeRegex, '\\$1');
});

var BaseStyleRule =
/*#__PURE__*/
function () {
  function BaseStyleRule(key, style, options) {
    this.type = 'style';
    this.key = void 0;
    this.isProcessed = false;
    this.style = void 0;
    this.renderer = void 0;
    this.renderable = void 0;
    this.options = void 0;
    var sheet = options.sheet,
        Renderer = options.Renderer;
    this.key = key;
    this.options = options;
    this.style = style;
    if (sheet) this.renderer = sheet.renderer;else if (Renderer) this.renderer = new Renderer();
  }
  /**
   * Get or set a style property.
   */


  var _proto = BaseStyleRule.prototype;

  _proto.prop = function prop(name, value, options) {
    // It's a getter.
    if (value === undefined) return this.style[name]; // Don't do anything if the value has not changed.

    var force = options ? options.force : false;
    if (!force && this.style[name] === value) return this;
    var newValue = value;

    if (!options || options.process !== false) {
      newValue = this.options.jss.plugins.onChangeValue(value, name, this);
    }

    var isEmpty = newValue == null || newValue === false;
    var isDefined = name in this.style; // Value is empty and wasn't defined before.

    if (isEmpty && !isDefined && !force) return this; // We are going to remove this value.

    var remove = isEmpty && isDefined;
    if (remove) delete this.style[name];else this.style[name] = newValue; // Renderable is defined if StyleSheet option `link` is true.

    if (this.renderable && this.renderer) {
      if (remove) this.renderer.removeProperty(this.renderable, name);else this.renderer.setProperty(this.renderable, name, newValue);
      return this;
    }

    var sheet = this.options.sheet;

    if (sheet && sheet.attached) {
       false ? undefined : void 0;
    }

    return this;
  };

  return BaseStyleRule;
}();
var jss_esm_StyleRule =
/*#__PURE__*/
function (_BaseStyleRule) {
  _inheritsLoose(StyleRule, _BaseStyleRule);

  function StyleRule(key, style, options) {
    var _this;

    _this = _BaseStyleRule.call(this, key, style, options) || this;
    _this.selectorText = void 0;
    _this.id = void 0;
    _this.renderable = void 0;
    var selector = options.selector,
        scoped = options.scoped,
        sheet = options.sheet,
        generateId = options.generateId;

    if (selector) {
      _this.selectorText = selector;
    } else if (scoped !== false) {
      _this.id = generateId(_assertThisInitialized(_assertThisInitialized(_this)), sheet);
      _this.selectorText = "." + jss_esm_escape(_this.id);
    }

    return _this;
  }
  /**
   * Set selector string.
   * Attention: use this with caution. Most browsers didn't implement
   * selectorText setter, so this may result in rerendering of entire Style Sheet.
   */


  var _proto2 = StyleRule.prototype;

  /**
   * Apply rule to an element inline.
   */
  _proto2.applyTo = function applyTo(renderable) {
    var renderer = this.renderer;

    if (renderer) {
      var json = this.toJSON();

      for (var prop in json) {
        renderer.setProperty(renderable, prop, json[prop]);
      }
    }

    return this;
  }
  /**
   * Returns JSON representation of the rule.
   * Fallbacks are not supported.
   * Useful for inline styles.
   */
  ;

  _proto2.toJSON = function toJSON() {
    var json = {};

    for (var prop in this.style) {
      var value = this.style[prop];
      if (typeof value !== 'object') json[prop] = value;else if (Array.isArray(value)) json[prop] = toCssValue(value);
    }

    return json;
  }
  /**
   * Generates a CSS string.
   */
  ;

  _proto2.toString = function toString(options) {
    var sheet = this.options.sheet;
    var link = sheet ? sheet.options.link : false;
    var opts = link ? _extends({}, options, {
      allowEmpty: true
    }) : options;
    return toCss(this.selectorText, this.style, opts);
  };

  _createClass(StyleRule, [{
    key: "selector",
    set: function set(selector) {
      if (selector === this.selectorText) return;
      this.selectorText = selector;
      var renderer = this.renderer,
          renderable = this.renderable;
      if (!renderable || !renderer) return;
      var hasChanged = renderer.setSelector(renderable, selector); // If selector setter is not implemented, rerender the rule.

      if (!hasChanged) {
        renderer.replaceRule(renderable, this);
      }
    }
    /**
     * Get selector string.
     */
    ,
    get: function get() {
      return this.selectorText;
    }
  }]);

  return StyleRule;
}(BaseStyleRule);
var pluginStyleRule = {
  onCreateRule: function onCreateRule(name, style, options) {
    if (name[0] === '@' || options.parent && options.parent.type === 'keyframes') {
      return null;
    }

    return new jss_esm_StyleRule(name, style, options);
  }
};

var defaultToStringOptions = {
  indent: 1,
  children: true
};
var atRegExp = /@([\w-]+)/;
/**
 * Conditional rule for @media, @supports
 */

var jss_esm_ConditionalRule =
/*#__PURE__*/
function () {
  function ConditionalRule(key, styles, options) {
    this.type = 'conditional';
    this.at = void 0;
    this.key = void 0;
    this.query = void 0;
    this.rules = void 0;
    this.options = void 0;
    this.isProcessed = false;
    this.renderable = void 0;
    this.key = key; // Key might contain a unique suffix in case the `name` passed by user was duplicate.

    this.query = options.name;
    var atMatch = key.match(atRegExp);
    this.at = atMatch ? atMatch[1] : 'unknown';
    this.options = options;
    this.rules = new jss_esm_RuleList(_extends({}, options, {
      parent: this
    }));

    for (var name in styles) {
      this.rules.add(name, styles[name]);
    }

    this.rules.process();
  }
  /**
   * Get a rule.
   */


  var _proto = ConditionalRule.prototype;

  _proto.getRule = function getRule(name) {
    return this.rules.get(name);
  }
  /**
   * Get index of a rule.
   */
  ;

  _proto.indexOf = function indexOf(rule) {
    return this.rules.indexOf(rule);
  }
  /**
   * Create and register rule, run plugins.
   */
  ;

  _proto.addRule = function addRule(name, style, options) {
    var rule = this.rules.add(name, style, options);
    if (!rule) return null;
    this.options.jss.plugins.onProcessRule(rule);
    return rule;
  }
  /**
   * Generates a CSS string.
   */
  ;

  _proto.toString = function toString(options) {
    if (options === void 0) {
      options = defaultToStringOptions;
    }

    if (options.indent == null) options.indent = defaultToStringOptions.indent;
    if (options.children == null) options.children = defaultToStringOptions.children;

    if (options.children === false) {
      return this.query + " {}";
    }

    var children = this.rules.toString(options);
    return children ? this.query + " {\n" + children + "\n}" : '';
  };

  return ConditionalRule;
}();
var keyRegExp = /@media|@supports\s+/;
var pluginConditionalRule = {
  onCreateRule: function onCreateRule(key, styles, options) {
    return keyRegExp.test(key) ? new jss_esm_ConditionalRule(key, styles, options) : null;
  }
};

var defaultToStringOptions$1 = {
  indent: 1,
  children: true
};
var nameRegExp = /@keyframes\s+([\w-]+)/;
/**
 * Rule for @keyframes
 */

var jss_esm_KeyframesRule =
/*#__PURE__*/
function () {
  function KeyframesRule(key, frames, options) {
    this.type = 'keyframes';
    this.at = '@keyframes';
    this.key = void 0;
    this.name = void 0;
    this.id = void 0;
    this.rules = void 0;
    this.options = void 0;
    this.isProcessed = false;
    this.renderable = void 0;
    var nameMatch = key.match(nameRegExp);

    if (nameMatch && nameMatch[1]) {
      this.name = nameMatch[1];
    } else {
      this.name = 'noname';
       false ? undefined : void 0;
    }

    this.key = this.type + "-" + this.name;
    this.options = options;
    var scoped = options.scoped,
        sheet = options.sheet,
        generateId = options.generateId;
    this.id = scoped === false ? this.name : jss_esm_escape(generateId(this, sheet));
    this.rules = new jss_esm_RuleList(_extends({}, options, {
      parent: this
    }));

    for (var name in frames) {
      this.rules.add(name, frames[name], _extends({}, options, {
        parent: this
      }));
    }

    this.rules.process();
  }
  /**
   * Generates a CSS string.
   */


  var _proto = KeyframesRule.prototype;

  _proto.toString = function toString(options) {
    if (options === void 0) {
      options = defaultToStringOptions$1;
    }

    if (options.indent == null) options.indent = defaultToStringOptions$1.indent;
    if (options.children == null) options.children = defaultToStringOptions$1.children;

    if (options.children === false) {
      return this.at + " " + this.id + " {}";
    }

    var children = this.rules.toString(options);
    if (children) children = "\n" + children + "\n";
    return this.at + " " + this.id + " {" + children + "}";
  };

  return KeyframesRule;
}();
var keyRegExp$1 = /@keyframes\s+/;
var refRegExp = /\$([\w-]+)/g;

var findReferencedKeyframe = function findReferencedKeyframe(val, keyframes) {
  if (typeof val === 'string') {
    return val.replace(refRegExp, function (match, name) {
      if (name in keyframes) {
        return keyframes[name];
      }

       false ? undefined : void 0;
      return match;
    });
  }

  return val;
};
/**
 * Replace the reference for a animation name.
 */


var jss_esm_replaceRef = function replaceRef(style, prop, keyframes) {
  var value = style[prop];
  var refKeyframe = findReferencedKeyframe(value, keyframes);

  if (refKeyframe !== value) {
    style[prop] = refKeyframe;
  }
};

var jss_esm_plugin = {
  onCreateRule: function onCreateRule(key, frames, options) {
    return typeof key === 'string' && keyRegExp$1.test(key) ? new jss_esm_KeyframesRule(key, frames, options) : null;
  },
  // Animation name ref replacer.
  onProcessStyle: function onProcessStyle(style, rule, sheet) {
    if (rule.type !== 'style' || !sheet) return style;
    if ('animation-name' in style) jss_esm_replaceRef(style, 'animation-name', sheet.keyframes);
    if ('animation' in style) jss_esm_replaceRef(style, 'animation', sheet.keyframes);
    return style;
  },
  onChangeValue: function onChangeValue(val, prop, rule) {
    var sheet = rule.options.sheet;

    if (!sheet) {
      return val;
    }

    switch (prop) {
      case 'animation':
        return findReferencedKeyframe(val, sheet.keyframes);

      case 'animation-name':
        return findReferencedKeyframe(val, sheet.keyframes);

      default:
        return val;
    }
  }
};

var jss_esm_KeyframeRule =
/*#__PURE__*/
function (_BaseStyleRule) {
  _inheritsLoose(KeyframeRule, _BaseStyleRule);

  function KeyframeRule() {
    var _this;

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _BaseStyleRule.call.apply(_BaseStyleRule, [this].concat(args)) || this;
    _this.renderable = void 0;
    return _this;
  }

  var _proto = KeyframeRule.prototype;

  /**
   * Generates a CSS string.
   */
  _proto.toString = function toString(options) {
    var sheet = this.options.sheet;
    var link = sheet ? sheet.options.link : false;
    var opts = link ? _extends({}, options, {
      allowEmpty: true
    }) : options;
    return toCss(this.key, this.style, opts);
  };

  return KeyframeRule;
}(BaseStyleRule);
var pluginKeyframeRule = {
  onCreateRule: function onCreateRule(key, style, options) {
    if (options.parent && options.parent.type === 'keyframes') {
      return new jss_esm_KeyframeRule(key, style, options);
    }

    return null;
  }
};

var FontFaceRule =
/*#__PURE__*/
function () {
  function FontFaceRule(key, style, options) {
    this.type = 'font-face';
    this.at = '@font-face';
    this.key = void 0;
    this.style = void 0;
    this.options = void 0;
    this.isProcessed = false;
    this.renderable = void 0;
    this.key = key;
    this.style = style;
    this.options = options;
  }
  /**
   * Generates a CSS string.
   */


  var _proto = FontFaceRule.prototype;

  _proto.toString = function toString(options) {
    if (Array.isArray(this.style)) {
      var str = '';

      for (var index = 0; index < this.style.length; index++) {
        str += toCss(this.key, this.style[index]);
        if (this.style[index + 1]) str += '\n';
      }

      return str;
    }

    return toCss(this.key, this.style, options);
  };

  return FontFaceRule;
}();
var pluginFontFaceRule = {
  onCreateRule: function onCreateRule(key, style, options) {
    return key === '@font-face' ? new FontFaceRule(key, style, options) : null;
  }
};

var ViewportRule =
/*#__PURE__*/
function () {
  function ViewportRule(key, style, options) {
    this.type = 'viewport';
    this.at = '@viewport';
    this.key = void 0;
    this.style = void 0;
    this.options = void 0;
    this.isProcessed = false;
    this.renderable = void 0;
    this.key = key;
    this.style = style;
    this.options = options;
  }
  /**
   * Generates a CSS string.
   */


  var _proto = ViewportRule.prototype;

  _proto.toString = function toString(options) {
    return toCss(this.key, this.style, options);
  };

  return ViewportRule;
}();
var pluginViewportRule = {
  onCreateRule: function onCreateRule(key, style, options) {
    return key === '@viewport' || key === '@-ms-viewport' ? new ViewportRule(key, style, options) : null;
  }
};

var SimpleRule =
/*#__PURE__*/
function () {
  function SimpleRule(key, value, options) {
    this.type = 'simple';
    this.key = void 0;
    this.value = void 0;
    this.options = void 0;
    this.isProcessed = false;
    this.renderable = void 0;
    this.key = key;
    this.value = value;
    this.options = options;
  }
  /**
   * Generates a CSS string.
   */
  // eslint-disable-next-line no-unused-vars


  var _proto = SimpleRule.prototype;

  _proto.toString = function toString(options) {
    if (Array.isArray(this.value)) {
      var str = '';

      for (var index = 0; index < this.value.length; index++) {
        str += this.key + " " + this.value[index] + ";";
        if (this.value[index + 1]) str += '\n';
      }

      return str;
    }

    return this.key + " " + this.value + ";";
  };

  return SimpleRule;
}();
var keysMap = {
  '@charset': true,
  '@import': true,
  '@namespace': true
};
var pluginSimpleRule = {
  onCreateRule: function onCreateRule(key, value, options) {
    return key in keysMap ? new SimpleRule(key, value, options) : null;
  }
};

var plugins = [pluginStyleRule, pluginConditionalRule, jss_esm_plugin, pluginKeyframeRule, pluginFontFaceRule, pluginViewportRule, pluginSimpleRule];

var defaultUpdateOptions = {
  process: true
};
var forceUpdateOptions = {
  force: true,
  process: true
  /**
   * Contains rules objects and allows adding/removing etc.
   * Is used for e.g. by `StyleSheet` or `ConditionalRule`.
   */

};

var jss_esm_RuleList =
/*#__PURE__*/
function () {
  // Rules registry for access by .get() method.
  // It contains the same rule registered by name and by selector.
  // Original styles object.
  // Used to ensure correct rules order.
  function RuleList(options) {
    this.map = {};
    this.raw = {};
    this.index = [];
    this.counter = 0;
    this.options = void 0;
    this.classes = void 0;
    this.keyframes = void 0;
    this.options = options;
    this.classes = options.classes;
    this.keyframes = options.keyframes;
  }
  /**
   * Create and register rule.
   *
   * Will not render after Style Sheet was rendered the first time.
   */


  var _proto = RuleList.prototype;

  _proto.add = function add(name, decl, ruleOptions) {
    var _this$options = this.options,
        parent = _this$options.parent,
        sheet = _this$options.sheet,
        jss = _this$options.jss,
        Renderer = _this$options.Renderer,
        generateId = _this$options.generateId,
        scoped = _this$options.scoped;

    var options = _extends({
      classes: this.classes,
      parent: parent,
      sheet: sheet,
      jss: jss,
      Renderer: Renderer,
      generateId: generateId,
      scoped: scoped,
      name: name
    }, ruleOptions); // When user uses .createStyleSheet(), duplicate names are not possible, but
    // `sheet.addRule()` opens the door for any duplicate rule name. When this happens
    // we need to make the key unique within this RuleList instance scope.


    var key = name;

    if (name in this.raw) {
      key = name + "-d" + this.counter++;
    } // We need to save the original decl before creating the rule
    // because cache plugin needs to use it as a key to return a cached rule.


    this.raw[key] = decl;

    if (key in this.classes) {
      // E.g. rules inside of @media container
      options.selector = "." + jss_esm_escape(this.classes[key]);
    }

    var rule = createRule(key, decl, options);
    if (!rule) return null;
    this.register(rule);
    var index = options.index === undefined ? this.index.length : options.index;
    this.index.splice(index, 0, rule);
    return rule;
  }
  /**
   * Get a rule.
   */
  ;

  _proto.get = function get(name) {
    return this.map[name];
  }
  /**
   * Delete a rule.
   */
  ;

  _proto.remove = function remove(rule) {
    this.unregister(rule);
    delete this.raw[rule.key];
    this.index.splice(this.index.indexOf(rule), 1);
  }
  /**
   * Get index of a rule.
   */
  ;

  _proto.indexOf = function indexOf(rule) {
    return this.index.indexOf(rule);
  }
  /**
   * Run `onProcessRule()` plugins on every rule.
   */
  ;

  _proto.process = function process() {
    var plugins$$1 = this.options.jss.plugins; // We need to clone array because if we modify the index somewhere else during a loop
    // we end up with very hard-to-track-down side effects.

    this.index.slice(0).forEach(plugins$$1.onProcessRule, plugins$$1);
  }
  /**
   * Register a rule in `.map`, `.classes` and `.keyframes` maps.
   */
  ;

  _proto.register = function register(rule) {
    this.map[rule.key] = rule;

    if (rule instanceof jss_esm_StyleRule) {
      this.map[rule.selector] = rule;
      if (rule.id) this.classes[rule.key] = rule.id;
    } else if (rule instanceof jss_esm_KeyframesRule && this.keyframes) {
      this.keyframes[rule.name] = rule.id;
    }
  }
  /**
   * Unregister a rule.
   */
  ;

  _proto.unregister = function unregister(rule) {
    delete this.map[rule.key];

    if (rule instanceof jss_esm_StyleRule) {
      delete this.map[rule.selector];
      delete this.classes[rule.key];
    } else if (rule instanceof jss_esm_KeyframesRule) {
      delete this.keyframes[rule.name];
    }
  }
  /**
   * Update the function values with a new data.
   */
  ;

  _proto.update = function update() {
    var name;
    var data;
    var options;

    if (typeof (arguments.length <= 0 ? undefined : arguments[0]) === 'string') {
      name = arguments.length <= 0 ? undefined : arguments[0]; // $FlowFixMe

      data = arguments.length <= 1 ? undefined : arguments[1]; // $FlowFixMe

      options = arguments.length <= 2 ? undefined : arguments[2];
    } else {
      data = arguments.length <= 0 ? undefined : arguments[0]; // $FlowFixMe

      options = arguments.length <= 1 ? undefined : arguments[1];
      name = null;
    }

    if (name) {
      this.updateOne(this.map[name], data, options);
    } else {
      for (var index = 0; index < this.index.length; index++) {
        this.updateOne(this.index[index], data, options);
      }
    }
  }
  /**
   * Execute plugins, update rule props.
   */
  ;

  _proto.updateOne = function updateOne(rule, data, options) {
    if (options === void 0) {
      options = defaultUpdateOptions;
    }

    var _this$options2 = this.options,
        plugins$$1 = _this$options2.jss.plugins,
        sheet = _this$options2.sheet; // It is a rules container like for e.g. ConditionalRule.

    if (rule.rules instanceof RuleList) {
      rule.rules.update(data, options);
      return;
    }

    var styleRule = rule;
    var style = styleRule.style;
    plugins$$1.onUpdate(data, rule, sheet, options); // We rely on a new `style` ref in case it was mutated during onUpdate hook.

    if (options.process && style && style !== styleRule.style) {
      // We need to run the plugins in case new `style` relies on syntax plugins.
      plugins$$1.onProcessStyle(styleRule.style, styleRule, sheet); // Update and add props.

      for (var prop in styleRule.style) {
        var nextValue = styleRule.style[prop];
        var prevValue = style[prop]; // We need to use `force: true` because `rule.style` has been updated during onUpdate hook, so `rule.prop()` will not update the CSSOM rule.
        // We do this comparison to avoid unneeded `rule.prop()` calls, since we have the old `style` object here.

        if (nextValue !== prevValue) {
          styleRule.prop(prop, nextValue, forceUpdateOptions);
        }
      } // Remove props.


      for (var _prop in style) {
        var _nextValue = styleRule.style[_prop];
        var _prevValue = style[_prop]; // We need to use `force: true` because `rule.style` has been updated during onUpdate hook, so `rule.prop()` will not update the CSSOM rule.
        // We do this comparison to avoid unneeded `rule.prop()` calls, since we have the old `style` object here.

        if (_nextValue == null && _nextValue !== _prevValue) {
          styleRule.prop(_prop, null, forceUpdateOptions);
        }
      }
    }
  }
  /**
   * Convert rules to a CSS string.
   */
  ;

  _proto.toString = function toString(options) {
    var str = '';
    var sheet = this.options.sheet;
    var link = sheet ? sheet.options.link : false;

    for (var index = 0; index < this.index.length; index++) {
      var rule = this.index[index];
      var css = rule.toString(options); // No need to render an empty rule.

      if (!css && !link) continue;
      if (str) str += '\n';
      str += css;
    }

    return str;
  };

  return RuleList;
}();

var jss_esm_StyleSheet =
/*#__PURE__*/
function () {
  function StyleSheet(styles, options) {
    this.options = void 0;
    this.deployed = void 0;
    this.attached = void 0;
    this.rules = void 0;
    this.renderer = void 0;
    this.classes = void 0;
    this.keyframes = void 0;
    this.queue = void 0;
    this.attached = false;
    this.deployed = false;
    this.classes = {};
    this.keyframes = {};
    this.options = _extends({}, options, {
      sheet: this,
      parent: this,
      classes: this.classes,
      keyframes: this.keyframes
    });

    if (options.Renderer) {
      this.renderer = new options.Renderer(this);
    }

    this.rules = new jss_esm_RuleList(this.options);

    for (var name in styles) {
      this.rules.add(name, styles[name]);
    }

    this.rules.process();
  }
  /**
   * Attach renderable to the render tree.
   */


  var _proto = StyleSheet.prototype;

  _proto.attach = function attach() {
    if (this.attached) return this;
    if (this.renderer) this.renderer.attach();
    this.attached = true; // Order is important, because we can't use insertRule API if style element is not attached.

    if (!this.deployed) this.deploy();
    return this;
  }
  /**
   * Remove renderable from render tree.
   */
  ;

  _proto.detach = function detach() {
    if (!this.attached) return this;
    if (this.renderer) this.renderer.detach();
    this.attached = false;
    return this;
  }
  /**
   * Add a rule to the current stylesheet.
   * Will insert a rule also after the stylesheet has been rendered first time.
   */
  ;

  _proto.addRule = function addRule(name, decl, options) {
    var queue = this.queue; // Plugins can create rules.
    // In order to preserve the right order, we need to queue all `.addRule` calls,
    // which happen after the first `rules.add()` call.

    if (this.attached && !queue) this.queue = [];
    var rule = this.rules.add(name, decl, options);
    if (!rule) return null;
    this.options.jss.plugins.onProcessRule(rule);

    if (this.attached) {
      if (!this.deployed) return rule; // Don't insert rule directly if there is no stringified version yet.
      // It will be inserted all together when .attach is called.

      if (queue) queue.push(rule);else {
        this.insertRule(rule);

        if (this.queue) {
          this.queue.forEach(this.insertRule, this);
          this.queue = undefined;
        }
      }
      return rule;
    } // We can't add rules to a detached style node.
    // We will redeploy the sheet once user will attach it.


    this.deployed = false;
    return rule;
  }
  /**
   * Insert rule into the StyleSheet
   */
  ;

  _proto.insertRule = function insertRule(rule) {
    if (this.renderer) {
      this.renderer.insertRule(rule);
    }
  }
  /**
   * Create and add rules.
   * Will render also after Style Sheet was rendered the first time.
   */
  ;

  _proto.addRules = function addRules(styles, options) {
    var added = [];

    for (var name in styles) {
      var rule = this.addRule(name, styles[name], options);
      if (rule) added.push(rule);
    }

    return added;
  }
  /**
   * Get a rule by name.
   */
  ;

  _proto.getRule = function getRule(name) {
    return this.rules.get(name);
  }
  /**
   * Delete a rule by name.
   * Returns `true`: if rule has been deleted from the DOM.
   */
  ;

  _proto.deleteRule = function deleteRule(name) {
    var rule = typeof name === 'object' ? name : this.rules.get(name);
    if (!rule) return false;
    this.rules.remove(rule);

    if (this.attached && rule.renderable && this.renderer) {
      return this.renderer.deleteRule(rule.renderable);
    }

    return true;
  }
  /**
   * Get index of a rule.
   */
  ;

  _proto.indexOf = function indexOf(rule) {
    return this.rules.indexOf(rule);
  }
  /**
   * Deploy pure CSS string to a renderable.
   */
  ;

  _proto.deploy = function deploy() {
    if (this.renderer) this.renderer.deploy();
    this.deployed = true;
    return this;
  }
  /**
   * Update the function values with a new data.
   */
  ;

  _proto.update = function update() {
    var _this$rules;

    (_this$rules = this.rules).update.apply(_this$rules, arguments);

    return this;
  }
  /**
   * Updates a single rule.
   */
  ;

  _proto.updateOne = function updateOne(rule, data, options) {
    this.rules.updateOne(rule, data, options);
    return this;
  }
  /**
   * Convert rules to a CSS string.
   */
  ;

  _proto.toString = function toString(options) {
    return this.rules.toString(options);
  };

  return StyleSheet;
}();

var PluginsRegistry =
/*#__PURE__*/
function () {
  function PluginsRegistry() {
    this.plugins = {
      internal: [],
      external: []
    };
    this.registry = void 0;
  }

  var _proto = PluginsRegistry.prototype;

  /**
   * Call `onCreateRule` hooks and return an object if returned by a hook.
   */
  _proto.onCreateRule = function onCreateRule(name, decl, options) {
    for (var i = 0; i < this.registry.onCreateRule.length; i++) {
      var rule = this.registry.onCreateRule[i](name, decl, options);
      if (rule) return rule;
    }

    return null;
  }
  /**
   * Call `onProcessRule` hooks.
   */
  ;

  _proto.onProcessRule = function onProcessRule(rule) {
    if (rule.isProcessed) return;
    var sheet = rule.options.sheet;

    for (var i = 0; i < this.registry.onProcessRule.length; i++) {
      this.registry.onProcessRule[i](rule, sheet);
    }

    if (rule.style) this.onProcessStyle(rule.style, rule, sheet);
    rule.isProcessed = true;
  }
  /**
   * Call `onProcessStyle` hooks.
   */
  ;

  _proto.onProcessStyle = function onProcessStyle(style, rule, sheet) {
    for (var i = 0; i < this.registry.onProcessStyle.length; i++) {
      // $FlowFixMe
      rule.style = this.registry.onProcessStyle[i](rule.style, rule, sheet);
    }
  }
  /**
   * Call `onProcessSheet` hooks.
   */
  ;

  _proto.onProcessSheet = function onProcessSheet(sheet) {
    for (var i = 0; i < this.registry.onProcessSheet.length; i++) {
      this.registry.onProcessSheet[i](sheet);
    }
  }
  /**
   * Call `onUpdate` hooks.
   */
  ;

  _proto.onUpdate = function onUpdate(data, rule, sheet, options) {
    for (var i = 0; i < this.registry.onUpdate.length; i++) {
      this.registry.onUpdate[i](data, rule, sheet, options);
    }
  }
  /**
   * Call `onChangeValue` hooks.
   */
  ;

  _proto.onChangeValue = function onChangeValue(value, prop, rule) {
    var processedValue = value;

    for (var i = 0; i < this.registry.onChangeValue.length; i++) {
      processedValue = this.registry.onChangeValue[i](processedValue, prop, rule);
    }

    return processedValue;
  }
  /**
   * Register a plugin.
   */
  ;

  _proto.use = function use(newPlugin, options) {
    if (options === void 0) {
      options = {
        queue: 'external'
      };
    }

    var plugins = this.plugins[options.queue]; // Avoids applying same plugin twice, at least based on ref.

    if (plugins.indexOf(newPlugin) !== -1) {
      return;
    }

    plugins.push(newPlugin);
    this.registry = [].concat(this.plugins.external, this.plugins.internal).reduce(function (registry, plugin) {
      for (var name in plugin) {
        if (name in registry) {
          registry[name].push(plugin[name]);
        } else {
           false ? undefined : void 0;
        }
      }

      return registry;
    }, {
      onCreateRule: [],
      onProcessRule: [],
      onProcessStyle: [],
      onProcessSheet: [],
      onChangeValue: [],
      onUpdate: []
    });
  };

  return PluginsRegistry;
}();

/**
 * Sheets registry to access them all at one place.
 */
var jss_esm_SheetsRegistry =
/*#__PURE__*/
function () {
  function SheetsRegistry() {
    this.registry = [];
  }

  var _proto = SheetsRegistry.prototype;

  /**
   * Register a Style Sheet.
   */
  _proto.add = function add(sheet) {
    var registry = this.registry;
    var index = sheet.options.index;
    if (registry.indexOf(sheet) !== -1) return;

    if (registry.length === 0 || index >= this.index) {
      registry.push(sheet);
      return;
    } // Find a position.


    for (var i = 0; i < registry.length; i++) {
      if (registry[i].options.index > index) {
        registry.splice(i, 0, sheet);
        return;
      }
    }
  }
  /**
   * Reset the registry.
   */
  ;

  _proto.reset = function reset() {
    this.registry = [];
  }
  /**
   * Remove a Style Sheet.
   */
  ;

  _proto.remove = function remove(sheet) {
    var index = this.registry.indexOf(sheet);
    this.registry.splice(index, 1);
  }
  /**
   * Convert all attached sheets to a CSS string.
   */
  ;

  _proto.toString = function toString(_temp) {
    var _ref = _temp === void 0 ? {} : _temp,
        attached = _ref.attached,
        options = _objectWithoutPropertiesLoose(_ref, ["attached"]);

    var css = '';

    for (var i = 0; i < this.registry.length; i++) {
      var sheet = this.registry[i];

      if (attached != null && sheet.attached !== attached) {
        continue;
      }

      if (css) css += '\n';
      css += sheet.toString(options);
    }

    return css;
  };

  _createClass(SheetsRegistry, [{
    key: "index",

    /**
     * Current highest index number.
     */
    get: function get() {
      return this.registry.length === 0 ? 0 : this.registry[this.registry.length - 1].options.index;
    }
  }]);

  return SheetsRegistry;
}();

/**
 * This is a global sheets registry. Only DomRenderer will add sheets to it.
 * On the server one should use an own SheetsRegistry instance and add the
 * sheets to it, because you need to make sure to create a new registry for
 * each request in order to not leak sheets across requests.
 */

var sheets = new jss_esm_SheetsRegistry();

/* eslint-disable */
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var globalThis = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();

var ns = '2f1acc6c3a606b082e5eef5e54414ffb';
if (globalThis[ns] == null) globalThis[ns] = 0; // Bundle may contain multiple JSS versions at the same time. In order to identify
// the current version with just one short number and use it for classes generation
// we use a counter. Also it is more accurate, because user can manually reevaluate
// the module.

var moduleId = globalThis[ns]++;

var maxRules = 1e10;

/**
 * Returns a function which generates unique class names based on counters.
 * When new generator function is created, rule counter is reseted.
 * We need to reset the rule counter for SSR for each request.
 */
var createGenerateId = function createGenerateId(options) {
  if (options === void 0) {
    options = {};
  }

  var ruleCounter = 0;
  return function (rule, sheet) {
    ruleCounter += 1;

    if (ruleCounter > maxRules) {
       false ? undefined : void 0;
    }

    var jssId = '';
    var prefix = '';

    if (sheet) {
      if (sheet.options.classNamePrefix) {
        prefix = sheet.options.classNamePrefix;
      }

      if (sheet.options.jss.id != null) {
        jssId = String(sheet.options.jss.id);
      }
    }

    if (options.minify) {
      // Using "c" because a number can't be the first char in a class name.
      return "" + (prefix || 'c') + moduleId + jssId + ruleCounter;
    }

    return prefix + rule.key + "-" + moduleId + (jssId ? "-" + jssId : '') + "-" + ruleCounter;
  };
};

/**
 * Cache the value from the first time a function is called.
 */
var memoize = function memoize(fn) {
  var value;
  return function () {
    if (!value) value = fn();
    return value;
  };
};
/**
 * Get a style property value.
 */


function getPropertyValue(cssRule, prop) {
  try {
    // Support CSSTOM.
    if (cssRule.attributeStyleMap) {
      return cssRule.attributeStyleMap.get(prop);
    }

    return cssRule.style.getPropertyValue(prop);
  } catch (err) {
    // IE may throw if property is unknown.
    return '';
  }
}
/**
 * Set a style property.
 */


function setProperty(cssRule, prop, value) {
  try {
    var cssValue = value;

    if (Array.isArray(value)) {
      cssValue = toCssValue(value, true);

      if (value[value.length - 1] === '!important') {
        cssRule.style.setProperty(prop, cssValue, 'important');
        return true;
      }
    } // Support CSSTOM.


    if (cssRule.attributeStyleMap) {
      cssRule.attributeStyleMap.set(prop, cssValue);
    } else {
      cssRule.style.setProperty(prop, cssValue);
    }
  } catch (err) {
    // IE may throw if property is unknown.
    return false;
  }

  return true;
}
/**
 * Remove a style property.
 */


function removeProperty(cssRule, prop) {
  try {
    // Support CSSTOM.
    if (cssRule.attributeStyleMap) {
      cssRule.attributeStyleMap.delete(prop);
    } else {
      cssRule.style.removeProperty(prop);
    }
  } catch (err) {
     false ? undefined : void 0;
  }
}
/**
 * Set the selector.
 */


function setSelector(cssRule, selectorText) {
  cssRule.selectorText = selectorText; // Return false if setter was not successful.
  // Currently works in chrome only.

  return cssRule.selectorText === selectorText;
}
/**
 * Gets the `head` element upon the first call and caches it.
 * We assume it can't be null.
 */


var getHead = memoize(function () {
  return document.querySelector('head');
});
/**
 * Find attached sheet with an index higher than the passed one.
 */

function findHigherSheet(registry, options) {
  for (var i = 0; i < registry.length; i++) {
    var sheet = registry[i];

    if (sheet.attached && sheet.options.index > options.index && sheet.options.insertionPoint === options.insertionPoint) {
      return sheet;
    }
  }

  return null;
}
/**
 * Find attached sheet with the highest index.
 */


function findHighestSheet(registry, options) {
  for (var i = registry.length - 1; i >= 0; i--) {
    var sheet = registry[i];

    if (sheet.attached && sheet.options.insertionPoint === options.insertionPoint) {
      return sheet;
    }
  }

  return null;
}
/**
 * Find a comment with "jss" inside.
 */


function findCommentNode(text) {
  var head = getHead();

  for (var i = 0; i < head.childNodes.length; i++) {
    var node = head.childNodes[i];

    if (node.nodeType === 8 && node.nodeValue.trim() === text) {
      return node;
    }
  }

  return null;
}

/**
 * Find a node before which we can insert the sheet.
 */
function findPrevNode(options) {
  var registry = sheets.registry;

  if (registry.length > 0) {
    // Try to insert before the next higher sheet.
    var sheet = findHigherSheet(registry, options);

    if (sheet && sheet.renderer) {
      return {
        parent: sheet.renderer.element.parentNode,
        node: sheet.renderer.element
      };
    } // Otherwise insert after the last attached.


    sheet = findHighestSheet(registry, options);

    if (sheet && sheet.renderer) {
      return {
        parent: sheet.renderer.element.parentNode,
        node: sheet.renderer.element.nextSibling
      };
    }
  } // Try to find a comment placeholder if registry is empty.


  var insertionPoint = options.insertionPoint;

  if (insertionPoint && typeof insertionPoint === 'string') {
    var comment = findCommentNode(insertionPoint);

    if (comment) {
      return {
        parent: comment.parentNode,
        node: comment.nextSibling
      };
    } // If user specifies an insertion point and it can't be found in the document -
    // bad specificity issues may appear.


     false ? undefined : void 0;
  }

  return false;
}
/**
 * Insert style element into the DOM.
 */


function insertStyle(style, options) {
  var insertionPoint = options.insertionPoint;
  var nextNode = findPrevNode(options);

  if (nextNode !== false && nextNode.parent) {
    nextNode.parent.insertBefore(style, nextNode.node);
    return;
  } // Works with iframes and any node types.


  if (insertionPoint && typeof insertionPoint.nodeType === 'number') {
    // https://stackoverflow.com/questions/41328728/force-casting-in-flow
    var insertionPointElement = insertionPoint;
    var parentNode = insertionPointElement.parentNode;
    if (parentNode) parentNode.insertBefore(style, insertionPointElement.nextSibling);else  false ? undefined : void 0;
    return;
  }

  getHead().appendChild(style);
}
/**
 * Read jss nonce setting from the page if the user has set it.
 */


var getNonce = memoize(function () {
  var node = document.querySelector('meta[property="csp-nonce"]');
  return node ? node.getAttribute('content') : null;
});

var _insertRule = function insertRule(container, rule, index) {
  var maxIndex = container.cssRules.length; // In case previous insertion fails, passed index might be wrong

  if (index === undefined || index > maxIndex) {
    // eslint-disable-next-line no-param-reassign
    index = maxIndex;
  }

  try {
    if ('insertRule' in container) {
      var c = container;
      c.insertRule(rule, index);
    } // Keyframes rule.
    else if ('appendRule' in container) {
        var _c = container;

        _c.appendRule(rule);
      }
  } catch (err) {
     false ? undefined : void 0;
    return false;
  }

  return container.cssRules[index];
};

var createStyle = function createStyle() {
  var el = document.createElement('style'); // Without it, IE will have a broken source order specificity if we
  // insert rules after we insert the style tag.
  // It seems to kick-off the source order specificity algorithm.

  el.textContent = '\n';
  return el;
};

var DomRenderer =
/*#__PURE__*/
function () {
  // HTMLStyleElement needs fixing https://github.com/facebook/flow/issues/2696
  function DomRenderer(sheet) {
    this.getPropertyValue = getPropertyValue;
    this.setProperty = setProperty;
    this.removeProperty = removeProperty;
    this.setSelector = setSelector;
    this.element = void 0;
    this.sheet = void 0;
    this.hasInsertedRules = false;
    // There is no sheet when the renderer is used from a standalone StyleRule.
    if (sheet) sheets.add(sheet);
    this.sheet = sheet;

    var _ref = this.sheet ? this.sheet.options : {},
        media = _ref.media,
        meta = _ref.meta,
        element = _ref.element;

    this.element = element || createStyle();
    this.element.setAttribute('data-jss', '');
    if (media) this.element.setAttribute('media', media);
    if (meta) this.element.setAttribute('data-meta', meta);
    var nonce = getNonce();
    if (nonce) this.element.setAttribute('nonce', nonce);
  }
  /**
   * Insert style element into render tree.
   */


  var _proto = DomRenderer.prototype;

  _proto.attach = function attach() {
    // In the case the element node is external and it is already in the DOM.
    if (this.element.parentNode || !this.sheet) return;
    insertStyle(this.element, this.sheet.options); // When rules are inserted using `insertRule` API, after `sheet.detach().attach()`
    // most browsers create a new CSSStyleSheet, except of all IEs.

    var deployed = Boolean(this.sheet && this.sheet.deployed);

    if (this.hasInsertedRules && deployed) {
      this.hasInsertedRules = false;
      this.deploy();
    }
  }
  /**
   * Remove style element from render tree.
   */
  ;

  _proto.detach = function detach() {
    var parentNode = this.element.parentNode;
    if (parentNode) parentNode.removeChild(this.element);
  }
  /**
   * Inject CSS string into element.
   */
  ;

  _proto.deploy = function deploy() {
    var sheet = this.sheet;
    if (!sheet) return;

    if (sheet.options.link) {
      this.insertRules(sheet.rules);
      return;
    }

    this.element.textContent = "\n" + sheet.toString() + "\n";
  }
  /**
   * Insert RuleList into an element.
   */
  ;

  _proto.insertRules = function insertRules(rules, nativeParent) {
    for (var i = 0; i < rules.index.length; i++) {
      this.insertRule(rules.index[i], i, nativeParent);
    }
  }
  /**
   * Insert a rule into element.
   */
  ;

  _proto.insertRule = function insertRule(rule, index, nativeParent) {
    if (nativeParent === void 0) {
      nativeParent = this.element.sheet;
    }

    if (rule.rules) {
      var parent = rule;
      var latestNativeParent = nativeParent;

      if (rule.type === 'conditional' || rule.type === 'keyframes') {
        // We need to render the container without children first.
        latestNativeParent = _insertRule(nativeParent, parent.toString({
          children: false
        }), index);

        if (latestNativeParent === false) {
          return false;
        }
      }

      this.insertRules(parent.rules, latestNativeParent);
      return latestNativeParent;
    } // IE keeps the CSSStyleSheet after style node has been reattached,
    // so we need to check if the `renderable` reference the right style sheet and not
    // rerender those rules.


    if (rule.renderable && rule.renderable.parentStyleSheet === this.element.sheet) {
      return rule.renderable;
    }

    var ruleStr = rule.toString();
    if (!ruleStr) return false;

    var nativeRule = _insertRule(nativeParent, ruleStr, index);

    if (nativeRule === false) {
      return false;
    }

    this.hasInsertedRules = true;
    rule.renderable = nativeRule;
    return nativeRule;
  }
  /**
   * Delete a rule.
   */
  ;

  _proto.deleteRule = function deleteRule(cssRule) {
    var sheet = this.element.sheet;
    var index = this.indexOf(cssRule);
    if (index === -1) return false;
    sheet.deleteRule(index);
    return true;
  }
  /**
   * Get index of a CSS Rule.
   */
  ;

  _proto.indexOf = function indexOf(cssRule) {
    var cssRules = this.element.sheet.cssRules;

    for (var index = 0; index < cssRules.length; index++) {
      if (cssRule === cssRules[index]) return index;
    }

    return -1;
  }
  /**
   * Generate a new CSS rule and replace the existing one.
   *
   * Only used for some old browsers because they can't set a selector.
   */
  ;

  _proto.replaceRule = function replaceRule(cssRule, rule) {
    var index = this.indexOf(cssRule);
    if (index === -1) return false;
    this.element.sheet.deleteRule(index);
    return this.insertRule(rule, index);
  }
  /**
   * Get all rules elements.
   */
  ;

  _proto.getRules = function getRules() {
    return this.element.sheet.cssRules;
  };

  return DomRenderer;
}();

var instanceCounter = 0;

var jss_esm_Jss =
/*#__PURE__*/
function () {
  function Jss(options) {
    this.id = instanceCounter++;
    this.version = "10.0.4";
    this.plugins = new PluginsRegistry();
    this.options = {
      id: {
        minify: false
      },
      createGenerateId: createGenerateId,
      Renderer: dist_module ? DomRenderer : null,
      plugins: []
    };
    this.generateId = createGenerateId({
      minify: false
    });

    for (var i = 0; i < plugins.length; i++) {
      this.plugins.use(plugins[i], {
        queue: 'internal'
      });
    }

    this.setup(options);
  }
  /**
   * Prepares various options, applies plugins.
   * Should not be used twice on the same instance, because there is no plugins
   * deduplication logic.
   */


  var _proto = Jss.prototype;

  _proto.setup = function setup(options) {
    if (options === void 0) {
      options = {};
    }

    if (options.createGenerateId) {
      this.options.createGenerateId = options.createGenerateId;
    }

    if (options.id) {
      this.options.id = _extends({}, this.options.id, options.id);
    }

    if (options.createGenerateId || options.id) {
      this.generateId = this.options.createGenerateId(this.options.id);
    }

    if (options.insertionPoint != null) this.options.insertionPoint = options.insertionPoint;

    if ('Renderer' in options) {
      this.options.Renderer = options.Renderer;
    } // eslint-disable-next-line prefer-spread


    if (options.plugins) this.use.apply(this, options.plugins);
    return this;
  }
  /**
   * Create a Style Sheet.
   */
  ;

  _proto.createStyleSheet = function createStyleSheet(styles, options) {
    if (options === void 0) {
      options = {};
    }

    var _options = options,
        index = _options.index;

    if (typeof index !== 'number') {
      index = sheets.index === 0 ? 0 : sheets.index + 1;
    }

    var sheet = new jss_esm_StyleSheet(styles, _extends({}, options, {
      jss: this,
      generateId: options.generateId || this.generateId,
      insertionPoint: this.options.insertionPoint,
      Renderer: this.options.Renderer,
      index: index
    }));
    this.plugins.onProcessSheet(sheet);
    return sheet;
  }
  /**
   * Detach the Style Sheet and remove it from the registry.
   */
  ;

  _proto.removeStyleSheet = function removeStyleSheet(sheet) {
    sheet.detach();
    sheets.remove(sheet);
    return this;
  }
  /**
   * Create a rule without a Style Sheet.
   * [Deprecated] will be removed in the next major version.
   */
  ;

  _proto.createRule = function createRule$$1(name, style, options) {
    if (style === void 0) {
      style = {};
    }

    if (options === void 0) {
      options = {};
    }

    // Enable rule without name for inline styles.
    if (typeof name === 'object') {
      return this.createRule(undefined, name, style);
    }

    var ruleOptions = _extends({}, options, {
      name: name,
      jss: this,
      Renderer: this.options.Renderer
    });

    if (!ruleOptions.generateId) ruleOptions.generateId = this.generateId;
    if (!ruleOptions.classes) ruleOptions.classes = {};
    if (!ruleOptions.keyframes) ruleOptions.keyframes = {};

    var rule = createRule(name, style, ruleOptions);

    if (rule) this.plugins.onProcessRule(rule);
    return rule;
  }
  /**
   * Register plugin. Passed function will be invoked with a rule instance.
   */
  ;

  _proto.use = function use() {
    var _this = this;

    for (var _len = arguments.length, plugins$$1 = new Array(_len), _key = 0; _key < _len; _key++) {
      plugins$$1[_key] = arguments[_key];
    }

    plugins$$1.forEach(function (plugin) {
      _this.plugins.use(plugin);
    });
    return this;
  };

  return Jss;
}();

/**
 * Extracts a styles object with only props that contain function values.
 */
function getDynamicStyles(styles) {
  var to = null;

  for (var key in styles) {
    var value = styles[key];
    var type = typeof value;

    if (type === 'function') {
      if (!to) to = {};
      to[key] = value;
    } else if (type === 'object' && value !== null && !Array.isArray(value)) {
      var extracted = getDynamicStyles(value);

      if (extracted) {
        if (!to) to = {};
        to[key] = extracted;
      }
    }
  }

  return to;
}

/**
 * SheetsManager is like a WeakMap which is designed to count StyleSheet
 * instances and attach/detach automatically.
 */
var jss_esm_SheetsManager =
/*#__PURE__*/
function () {
  function SheetsManager() {
    this.length = 0;
    this.sheets = new WeakMap();
  }

  var _proto = SheetsManager.prototype;

  _proto.get = function get(key) {
    var entry = this.sheets.get(key);
    return entry && entry.sheet;
  };

  _proto.add = function add(key, sheet) {
    if (this.sheets.has(key)) return;
    this.length++;
    this.sheets.set(key, {
      sheet: sheet,
      refs: 0
    });
  };

  _proto.manage = function manage(key) {
    var entry = this.sheets.get(key);

    if (entry) {
      if (entry.refs === 0) {
        entry.sheet.attach();
      }

      entry.refs++;
      return entry.sheet;
    }

    tiny_warning_esm(false, "[JSS] SheetsManager: can't find sheet to manage");
    return undefined;
  };

  _proto.unmanage = function unmanage(key) {
    var entry = this.sheets.get(key);

    if (entry) {
      if (entry.refs > 0) {
        entry.refs--;
        if (entry.refs === 0) entry.sheet.detach();
      }
    } else {
      tiny_warning_esm(false, "SheetsManager: can't find sheet to unmanage");
    }
  };

  _createClass(SheetsManager, [{
    key: "size",
    get: function get() {
      return this.length;
    }
  }]);

  return SheetsManager;
}();

/**
 * A better abstraction over CSS.
 *
 * @copyright Oleg Isonen (Slobodskoi) / Isonen 2014-present
 * @website https://github.com/cssinjs/jss
 * @license MIT
 */

/**
 * Export a constant indicating if this browser has CSSTOM support.
 * https://developers.google.com/web/updates/2018/03/cssom
 */
var hasCSSTOMSupport = typeof CSS !== 'undefined' && CSS && 'number' in CSS;
/**
 * Creates a new instance of Jss.
 */

var jss_esm_create = function create(options) {
  return new jss_esm_Jss(options);
};
/**
 * A global Jss instance.
 */

var jss_esm_index = jss_esm_create();

/* harmony default export */ var jss_esm = (jss_esm_index);


// EXTERNAL MODULE: ./node_modules/@material-ui/styles/esm/mergeClasses/mergeClasses.js
var mergeClasses = __webpack_require__(156);

// CONCATENATED MODULE: ./node_modules/@material-ui/styles/esm/makeStyles/multiKeyStore.js
// Used https://github.com/thinkloop/multi-key-cache as inspiration
var multiKeyStore = {
  set: function set(cache, key1, key2, value) {
    var subCache = cache.get(key1);

    if (!subCache) {
      subCache = new Map();
      cache.set(key1, subCache);
    }

    subCache.set(key2, value);
  },
  get: function get(cache, key1, key2) {
    var subCache = cache.get(key1);
    return subCache ? subCache.get(key2) : undefined;
  },
  delete: function _delete(cache, key1, key2) {
    var subCache = cache.get(key1);
    subCache.delete(key2);
  }
};
/* harmony default export */ var makeStyles_multiKeyStore = (multiKeyStore);
// EXTERNAL MODULE: ./node_modules/@material-ui/styles/esm/useTheme/useTheme.js
var useTheme = __webpack_require__(154);

// EXTERNAL MODULE: ./node_modules/prop-types/index.js
var prop_types = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/@material-ui/styles/esm/ThemeProvider/nested.js
var nested = __webpack_require__(37);

// CONCATENATED MODULE: ./node_modules/@material-ui/styles/esm/createGenerateClassName/createGenerateClassName.js

/**
 * This is the list of the style rule name we use as drop in replacement for the built-in
 * pseudo classes (:checked, :disabled, :focused, etc.).
 *
 * Why do they exist in the first place?
 * These classes are used at a specificity of 2.
 * It allows them to override previously definied styles as well as
 * being untouched by simple user overrides.
 */

var pseudoClasses = ['checked', 'disabled', 'error', 'focused', 'focusVisible', 'required', 'expanded', 'selected']; // Returns a function which generates unique class names based on counters.
// When new generator function is created, rule counter is reset.
// We need to reset the rule counter for SSR for each request.
//
// It's inspired by
// https://github.com/cssinjs/jss/blob/4e6a05dd3f7b6572fdd3ab216861d9e446c20331/src/utils/createGenerateClassName.js

function createGenerateClassName() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var _options$disableGloba = options.disableGlobal,
      disableGlobal = _options$disableGloba === void 0 ? false : _options$disableGloba,
      _options$productionPr = options.productionPrefix,
      productionPrefix = _options$productionPr === void 0 ? 'jss' : _options$productionPr,
      _options$seed = options.seed,
      seed = _options$seed === void 0 ? '' : _options$seed;
  var seedPrefix = seed === '' ? '' : "".concat(seed, "-");
  var ruleCounter = 0;
  return function (rule, styleSheet) {
    ruleCounter += 1;

    if (false) {}

    var name = styleSheet.options.name; // Is a global static MUI style?

    if (name && name.indexOf('Mui') === 0 && !styleSheet.options.link && !disableGlobal) {
      // We can use a shorthand class name, we never use the keys to style the components.
      if (pseudoClasses.indexOf(rule.key) !== -1) {
        return "Mui-".concat(rule.key);
      }

      var prefix = "".concat(seedPrefix).concat(name, "-").concat(rule.key);

      if (!styleSheet.options.theme[nested["a" /* default */]] || seed !== '') {
        return prefix;
      }

      return "".concat(prefix, "-").concat(ruleCounter);
    }

    if (true) {
      return "".concat(seedPrefix).concat(productionPrefix).concat(ruleCounter);
    }

    var suffix = "".concat(rule.key, "-").concat(ruleCounter); // Help with debuggability.

    if (styleSheet.options.classNamePrefix) {
      return "".concat(seedPrefix).concat(styleSheet.options.classNamePrefix, "-").concat(suffix);
    }

    return "".concat(seedPrefix).concat(suffix);
  };
}
// CONCATENATED MODULE: ./node_modules/jss-plugin-rule-value-function/dist/jss-plugin-rule-value-function.esm.js


var now = Date.now();
var fnValuesNs = "fnValues" + now;
var fnRuleNs = "fnStyle" + ++now;
function functionPlugin() {
  return {
    onCreateRule: function onCreateRule(name, decl, options) {
      if (typeof decl !== 'function') return null;
      var rule = createRule(name, {}, options);
      rule[fnRuleNs] = decl;
      return rule;
    },
    onProcessStyle: function onProcessStyle(style, rule) {
      // We need to extract function values from the declaration, so that we can keep core unaware of them.
      // We need to do that only once.
      // We don't need to extract functions on each style update, since this can happen only once.
      // We don't support function values inside of function rules.
      if (fnValuesNs in rule || fnRuleNs in rule) return style;
      var fnValues = {};

      for (var prop in style) {
        var value = style[prop];
        if (typeof value !== 'function') continue;
        delete style[prop];
        fnValues[prop] = value;
      } // $FlowFixMe


      rule[fnValuesNs] = fnValues;
      return style;
    },
    onUpdate: function onUpdate(data, rule, sheet, options) {
      var styleRule = rule;
      var fnRule = styleRule[fnRuleNs]; // If we have a style function, the entire rule is dynamic and style object
      // will be returned from that function.

      if (fnRule) {
        // Empty object will remove all currently defined props
        // in case function rule returns a falsy value.
        styleRule.style = fnRule(data) || {};
      }

      var fnValues = styleRule[fnValuesNs]; // If we have a fn values map, it is a rule with function values.

      if (fnValues) {
        for (var prop in fnValues) {
          styleRule.prop(prop, fnValues[prop](data), options);
        }
      }
    }
  };
}

/* harmony default export */ var jss_plugin_rule_value_function_esm = (functionPlugin);

// CONCATENATED MODULE: ./node_modules/jss-plugin-global/node_modules/@babel/runtime/helpers/esm/extends.js
function extends_extends() {
  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_extends.apply(this, arguments);
}
// CONCATENATED MODULE: ./node_modules/jss-plugin-global/dist/jss-plugin-global.esm.js



var at = '@global';
var atPrefix = '@global ';

var jss_plugin_global_esm_GlobalContainerRule =
/*#__PURE__*/
function () {
  function GlobalContainerRule(key, styles, options) {
    this.type = 'global';
    this.at = at;
    this.rules = void 0;
    this.options = void 0;
    this.key = void 0;
    this.isProcessed = false;
    this.key = key;
    this.options = options;
    this.rules = new jss_esm_RuleList(extends_extends({}, options, {
      parent: this
    }));

    for (var selector in styles) {
      this.rules.add(selector, styles[selector]);
    }

    this.rules.process();
  }
  /**
   * Get a rule.
   */


  var _proto = GlobalContainerRule.prototype;

  _proto.getRule = function getRule(name) {
    return this.rules.get(name);
  }
  /**
   * Create and register rule, run plugins.
   */
  ;

  _proto.addRule = function addRule(name, style, options) {
    var rule = this.rules.add(name, style, options);
    this.options.jss.plugins.onProcessRule(rule);
    return rule;
  }
  /**
   * Get index of a rule.
   */
  ;

  _proto.indexOf = function indexOf(rule) {
    return this.rules.indexOf(rule);
  }
  /**
   * Generates a CSS string.
   */
  ;

  _proto.toString = function toString() {
    return this.rules.toString();
  };

  return GlobalContainerRule;
}();

var jss_plugin_global_esm_GlobalPrefixedRule =
/*#__PURE__*/
function () {
  function GlobalPrefixedRule(key, style, options) {
    this.type = 'global';
    this.at = at;
    this.options = void 0;
    this.rule = void 0;
    this.isProcessed = false;
    this.key = void 0;
    this.key = key;
    this.options = options;
    var selector = key.substr(atPrefix.length);
    this.rule = options.jss.createRule(selector, style, extends_extends({}, options, {
      parent: this
    }));
  }

  var _proto2 = GlobalPrefixedRule.prototype;

  _proto2.toString = function toString(options) {
    return this.rule ? this.rule.toString(options) : '';
  };

  return GlobalPrefixedRule;
}();

var separatorRegExp = /\s*,\s*/g;

function addScope(selector, scope) {
  var parts = selector.split(separatorRegExp);
  var scoped = '';

  for (var i = 0; i < parts.length; i++) {
    scoped += scope + " " + parts[i].trim();
    if (parts[i + 1]) scoped += ', ';
  }

  return scoped;
}

function handleNestedGlobalContainerRule(rule) {
  var options = rule.options,
      style = rule.style;
  var rules = style ? style[at] : null;
  if (!rules) return;

  for (var name in rules) {
    options.sheet.addRule(name, rules[name], extends_extends({}, options, {
      selector: addScope(name, rule.selector)
    }));
  }

  delete style[at];
}

function handlePrefixedGlobalRule(rule) {
  var options = rule.options,
      style = rule.style;

  for (var prop in style) {
    if (prop[0] !== '@' || prop.substr(0, at.length) !== at) continue;
    var selector = addScope(prop.substr(at.length), rule.selector);
    options.sheet.addRule(selector, style[prop], extends_extends({}, options, {
      selector: selector
    }));
    delete style[prop];
  }
}
/**
 * Convert nested rules to separate, remove them from original styles.
 *
 * @param {Rule} rule
 * @api public
 */


function jssGlobal() {
  function onCreateRule(name, styles, options) {
    if (!name) return null;

    if (name === at) {
      return new jss_plugin_global_esm_GlobalContainerRule(name, styles, options);
    }

    if (name[0] === '@' && name.substr(0, atPrefix.length) === atPrefix) {
      return new jss_plugin_global_esm_GlobalPrefixedRule(name, styles, options);
    }

    var parent = options.parent;

    if (parent) {
      if (parent.type === 'global' || parent.options.parent && parent.options.parent.type === 'global') {
        options.scoped = false;
      }
    }

    if (options.scoped === false) {
      options.selector = name;
    }

    return null;
  }

  function onProcessRule(rule) {
    if (rule.type !== 'style') return;
    handleNestedGlobalContainerRule(rule);
    handlePrefixedGlobalRule(rule);
  }

  return {
    onCreateRule: onCreateRule,
    onProcessRule: onProcessRule
  };
}

/* harmony default export */ var jss_plugin_global_esm = (jssGlobal);

// CONCATENATED MODULE: ./node_modules/jss-plugin-nested/node_modules/@babel/runtime/helpers/esm/extends.js
function esm_extends_extends() {
  esm_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 esm_extends_extends.apply(this, arguments);
}
// CONCATENATED MODULE: ./node_modules/jss-plugin-nested/dist/jss-plugin-nested.esm.js



var jss_plugin_nested_esm_separatorRegExp = /\s*,\s*/g;
var parentRegExp = /&/g;
var jss_plugin_nested_esm_refRegExp = /\$([\w-]+)/g;
/**
 * Convert nested rules to separate, remove them from original styles.
 *
 * @param {Rule} rule
 * @api public
 */

function jssNested() {
  // Get a function to be used for $ref replacement.
  function getReplaceRef(container, sheet) {
    return function (match, key) {
      var rule = container.getRule(key) || sheet && sheet.getRule(key);

      if (rule) {
        rule = rule;
        return rule.selector;
      }

       false ? undefined : void 0;
      return key;
    };
  }

  function replaceParentRefs(nestedProp, parentProp) {
    var parentSelectors = parentProp.split(jss_plugin_nested_esm_separatorRegExp);
    var nestedSelectors = nestedProp.split(jss_plugin_nested_esm_separatorRegExp);
    var result = '';

    for (var i = 0; i < parentSelectors.length; i++) {
      var parent = parentSelectors[i];

      for (var j = 0; j < nestedSelectors.length; j++) {
        var nested = nestedSelectors[j];
        if (result) result += ', '; // Replace all & by the parent or prefix & with the parent.

        result += nested.indexOf('&') !== -1 ? nested.replace(parentRegExp, parent) : parent + " " + nested;
      }
    }

    return result;
  }

  function getOptions(rule, container, prevOptions) {
    // Options has been already created, now we only increase index.
    if (prevOptions) return esm_extends_extends({}, prevOptions, {
      index: prevOptions.index + 1
    });
    var nestingLevel = rule.options.nestingLevel;
    nestingLevel = nestingLevel === undefined ? 1 : nestingLevel + 1;

    var options = esm_extends_extends({}, rule.options, {
      nestingLevel: nestingLevel,
      index: container.indexOf(rule) + 1 // We don't need the parent name to be set options for chlid.

    });

    delete options.name;
    return options;
  }

  function onProcessStyle(style, rule, sheet) {
    if (rule.type !== 'style') return style;
    var styleRule = rule;
    var container = styleRule.options.parent;
    var options;
    var replaceRef;

    for (var prop in style) {
      var isNested = prop.indexOf('&') !== -1;
      var isNestedConditional = prop[0] === '@';
      if (!isNested && !isNestedConditional) continue;
      options = getOptions(styleRule, container, options);

      if (isNested) {
        var selector = replaceParentRefs(prop, styleRule.selector); // Lazily create the ref replacer function just once for
        // all nested rules within the sheet.

        if (!replaceRef) replaceRef = getReplaceRef(container, sheet); // Replace all $refs.

        selector = selector.replace(jss_plugin_nested_esm_refRegExp, replaceRef);
        container.addRule(selector, style[prop], esm_extends_extends({}, options, {
          selector: selector
        }));
      } else if (isNestedConditional) {
        // Place conditional right after the parent rule to ensure right ordering.
        container.addRule(prop, {}, options) // Flow expects more options but they aren't required
        // And flow doesn't know this will always be a StyleRule which has the addRule method
        // $FlowFixMe
        .addRule(styleRule.key, style[prop], {
          selector: styleRule.selector
        });
      }

      delete style[prop];
    }

    return style;
  }

  return {
    onProcessStyle: onProcessStyle
  };
}

/* harmony default export */ var jss_plugin_nested_esm = (jssNested);

// CONCATENATED MODULE: ./node_modules/hyphenate-style-name/index.js
/* eslint-disable no-var, prefer-template */
var uppercasePattern = /[A-Z]/g
var msPattern = /^ms-/
var cache = {}

function toHyphenLower(match) {
  return '-' + match.toLowerCase()
}

function hyphenateStyleName(name) {
  if (cache.hasOwnProperty(name)) {
    return cache[name]
  }

  var hName = name.replace(uppercasePattern, toHyphenLower)
  return (cache[name] = msPattern.test(hName) ? '-' + hName : hName)
}

/* harmony default export */ var hyphenate_style_name = (hyphenateStyleName);

// CONCATENATED MODULE: ./node_modules/jss-plugin-camel-case/dist/jss-plugin-camel-case.esm.js


/**
 * Convert camel cased property names to dash separated.
 *
 * @param {Object} style
 * @return {Object}
 */

function convertCase(style) {
  var converted = {};

  for (var prop in style) {
    var key = prop.indexOf('--') === 0 ? prop : hyphenate_style_name(prop);
    converted[key] = style[prop];
  }

  if (style.fallbacks) {
    if (Array.isArray(style.fallbacks)) converted.fallbacks = style.fallbacks.map(convertCase);else converted.fallbacks = convertCase(style.fallbacks);
  }

  return converted;
}
/**
 * Allow camel cased property names by converting them back to dasherized.
 *
 * @param {Rule} rule
 */


function camelCase() {
  function onProcessStyle(style) {
    if (Array.isArray(style)) {
      // Handle rules like @font-face, which can have multiple styles in an array
      for (var index = 0; index < style.length; index++) {
        style[index] = convertCase(style[index]);
      }

      return style;
    }

    return convertCase(style);
  }

  function onChangeValue(value, prop, rule) {
    if (prop.indexOf('--') === 0) {
      return value;
    }

    var hyphenatedProp = hyphenate_style_name(prop); // There was no camel case in place

    if (prop === hyphenatedProp) return value;
    rule.prop(hyphenatedProp, value); // Core will ignore that property value we set the proper one above.

    return null;
  }

  return {
    onProcessStyle: onProcessStyle,
    onChangeValue: onChangeValue
  };
}

/* harmony default export */ var jss_plugin_camel_case_esm = (camelCase);

// CONCATENATED MODULE: ./node_modules/jss-plugin-default-unit/dist/jss-plugin-default-unit.esm.js


var px = hasCSSTOMSupport && CSS ? CSS.px : 'px';
var ms = hasCSSTOMSupport && CSS ? CSS.ms : 'ms';
var percent = hasCSSTOMSupport && CSS ? CSS.percent : '%';
/**
 * Generated jss-plugin-default-unit CSS property units
 *
 * @type object
 */

var defaultUnits = {
  // Animation properties
  'animation-delay': ms,
  'animation-duration': ms,
  // Background properties
  'background-position': px,
  'background-position-x': px,
  'background-position-y': px,
  'background-size': px,
  // Border Properties
  border: px,
  'border-bottom': px,
  'border-bottom-left-radius': px,
  'border-bottom-right-radius': px,
  'border-bottom-width': px,
  'border-left': px,
  'border-left-width': px,
  'border-radius': px,
  'border-right': px,
  'border-right-width': px,
  'border-top': px,
  'border-top-left-radius': px,
  'border-top-right-radius': px,
  'border-top-width': px,
  'border-width': px,
  // Margin properties
  margin: px,
  'margin-bottom': px,
  'margin-left': px,
  'margin-right': px,
  'margin-top': px,
  // Padding properties
  padding: px,
  'padding-bottom': px,
  'padding-left': px,
  'padding-right': px,
  'padding-top': px,
  // Mask properties
  'mask-position-x': px,
  'mask-position-y': px,
  'mask-size': px,
  // Width and height properties
  height: px,
  width: px,
  'min-height': px,
  'max-height': px,
  'min-width': px,
  'max-width': px,
  // Position properties
  bottom: px,
  left: px,
  top: px,
  right: px,
  // Shadow properties
  'box-shadow': px,
  'text-shadow': px,
  // Column properties
  'column-gap': px,
  'column-rule': px,
  'column-rule-width': px,
  'column-width': px,
  // Font and text properties
  'font-size': px,
  'font-size-delta': px,
  'letter-spacing': px,
  'text-indent': px,
  'text-stroke': px,
  'text-stroke-width': px,
  'word-spacing': px,
  // Motion properties
  motion: px,
  'motion-offset': px,
  // Outline properties
  outline: px,
  'outline-offset': px,
  'outline-width': px,
  // Perspective properties
  perspective: px,
  'perspective-origin-x': percent,
  'perspective-origin-y': percent,
  // Transform properties
  'transform-origin': percent,
  'transform-origin-x': percent,
  'transform-origin-y': percent,
  'transform-origin-z': percent,
  // Transition properties
  'transition-delay': ms,
  'transition-duration': ms,
  // Alignment properties
  'vertical-align': px,
  'flex-basis': px,
  // Some random properties
  'shape-margin': px,
  size: px,
  // Grid properties
  grid: px,
  'grid-gap': px,
  'grid-row-gap': px,
  'grid-column-gap': px,
  'grid-template-rows': px,
  'grid-template-columns': px,
  'grid-auto-rows': px,
  'grid-auto-columns': px,
  // Not existing properties.
  // Used to avoid issues with jss-plugin-expand integration.
  'box-shadow-x': px,
  'box-shadow-y': px,
  'box-shadow-blur': px,
  'box-shadow-spread': px,
  'font-line-height': px,
  'text-shadow-x': px,
  'text-shadow-y': px,
  'text-shadow-blur': px
};

/**
 * Clones the object and adds a camel cased property version.
 */
function addCamelCasedVersion(obj) {
  var regExp = /(-[a-z])/g;

  var replace = function replace(str) {
    return str[1].toUpperCase();
  };

  var newObj = {};

  for (var _key in obj) {
    newObj[_key] = obj[_key];
    newObj[_key.replace(regExp, replace)] = obj[_key];
  }

  return newObj;
}

var units = addCamelCasedVersion(defaultUnits);
/**
 * Recursive deep style passing function
 */

function iterate(prop, value, options) {
  if (!value) return value;

  if (Array.isArray(value)) {
    for (var i = 0; i < value.length; i++) {
      value[i] = iterate(prop, value[i], options);
    }
  } else if (typeof value === 'object') {
    if (prop === 'fallbacks') {
      for (var innerProp in value) {
        value[innerProp] = iterate(innerProp, value[innerProp], options);
      }
    } else {
      for (var _innerProp in value) {
        value[_innerProp] = iterate(prop + "-" + _innerProp, value[_innerProp], options);
      }
    }
  } else if (typeof value === 'number') {
    if (options[prop]) {
      return "" + value + options[prop];
    }

    if (units[prop]) {
      return typeof units[prop] === 'function' ? units[prop](value).toString() : "" + value + units[prop];
    }

    return value.toString();
  }

  return value;
}
/**
 * Add unit to numeric values.
 */


function defaultUnit(options) {
  if (options === void 0) {
    options = {};
  }

  var camelCasedOptions = addCamelCasedVersion(options);

  function onProcessStyle(style, rule) {
    if (rule.type !== 'style') return style;

    for (var prop in style) {
      style[prop] = iterate(prop, style[prop], camelCasedOptions);
    }

    return style;
  }

  function onChangeValue(value, prop) {
    return iterate(prop, value, camelCasedOptions);
  }

  return {
    onProcessStyle: onProcessStyle,
    onChangeValue: onChangeValue
  };
}

/* harmony default export */ var jss_plugin_default_unit_esm = (defaultUnit);

// CONCATENATED MODULE: ./node_modules/css-vendor/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js
function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) {
    for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
      arr2[i] = arr[i];
    }

    return arr2;
  }
}
// CONCATENATED MODULE: ./node_modules/css-vendor/node_modules/@babel/runtime/helpers/esm/iterableToArray.js
function _iterableToArray(iter) {
  if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
// CONCATENATED MODULE: ./node_modules/css-vendor/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js
function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance");
}
// CONCATENATED MODULE: ./node_modules/css-vendor/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js



function _toConsumableArray(arr) {
  return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
// CONCATENATED MODULE: ./node_modules/css-vendor/dist/css-vendor.esm.js



// Export javascript style and css style vendor prefixes.
var js = '';
var css_vendor_esm_css = '';
var vendor = '';
var browser = '';
var isTouch = dist_module && 'ontouchstart' in document.documentElement; // We should not do anything if required serverside.

if (dist_module) {
  // Order matters. We need to check Webkit the last one because
  // other vendors use to add Webkit prefixes to some properties
  var jsCssMap = {
    Moz: '-moz-',
    ms: '-ms-',
    O: '-o-',
    Webkit: '-webkit-'
  };

  var _document$createEleme = document.createElement('p'),
      css_vendor_esm_style = _document$createEleme.style;

  var testProp = 'Transform';

  for (var css_vendor_esm_key in jsCssMap) {
    if (css_vendor_esm_key + testProp in css_vendor_esm_style) {
      js = css_vendor_esm_key;
      css_vendor_esm_css = jsCssMap[css_vendor_esm_key];
      break;
    }
  } // Correctly detect the Edge browser.


  if (js === 'Webkit' && 'msHyphens' in css_vendor_esm_style) {
    js = 'ms';
    css_vendor_esm_css = jsCssMap.ms;
    browser = 'edge';
  } // Correctly detect the Safari browser.


  if (js === 'Webkit' && '-apple-trailing-word' in css_vendor_esm_style) {
    vendor = 'apple';
  }
}
/**
 * Vendor prefix string for the current browser.
 *
 * @type {{js: String, css: String, vendor: String, browser: String}}
 * @api public
 */


var css_vendor_esm_prefix = {
  js: js,
  css: css_vendor_esm_css,
  vendor: vendor,
  browser: browser,
  isTouch: isTouch
};

/**
 * Test if a keyframe at-rule should be prefixed or not
 *
 * @param {String} vendor prefix string for the current browser.
 * @return {String}
 * @api public
 */

function supportedKeyframes(key) {
  // Keyframes is already prefixed. e.g. key = '@-webkit-keyframes a'
  if (key[1] === '-') return key; // No need to prefix IE/Edge. Older browsers will ignore unsupported rules.
  // https://caniuse.com/#search=keyframes

  if (css_vendor_esm_prefix.js === 'ms') return key;
  return "@" + css_vendor_esm_prefix.css + "keyframes" + key.substr(10);
}

// https://caniuse.com/#search=appearance

var appearence = {
  noPrefill: ['appearance'],
  supportedProperty: function supportedProperty(prop) {
    if (prop !== 'appearance') return false;
    if (css_vendor_esm_prefix.js === 'ms') return "-webkit-" + prop;
    return css_vendor_esm_prefix.css + prop;
  }
};

// https://caniuse.com/#search=color-adjust

var colorAdjust = {
  noPrefill: ['color-adjust'],
  supportedProperty: function supportedProperty(prop) {
    if (prop !== 'color-adjust') return false;
    if (css_vendor_esm_prefix.js === 'Webkit') return css_vendor_esm_prefix.css + "print-" + prop;
    return prop;
  }
};

var regExp = /[-\s]+(.)?/g;
/**
 * Replaces the letter with the capital letter
 *
 * @param {String} match
 * @param {String} c
 * @return {String}
 * @api private
 */

function toUpper(match, c) {
  return c ? c.toUpperCase() : '';
}
/**
 * Convert dash separated strings to camel-cased.
 *
 * @param {String} str
 * @return {String}
 * @api private
 */


function camelize(str) {
  return str.replace(regExp, toUpper);
}

/**
 * Convert dash separated strings to pascal cased.
 *
 * @param {String} str
 * @return {String}
 * @api private
 */

function pascalize(str) {
  return camelize("-" + str);
}

// but we can use a longhand property instead.
// https://caniuse.com/#search=mask

var mask = {
  noPrefill: ['mask'],
  supportedProperty: function supportedProperty(prop, style) {
    if (!/^mask/.test(prop)) return false;

    if (css_vendor_esm_prefix.js === 'Webkit') {
      var longhand = 'mask-image';

      if (camelize(longhand) in style) {
        return prop;
      }

      if (css_vendor_esm_prefix.js + pascalize(longhand) in style) {
        return css_vendor_esm_prefix.css + prop;
      }
    }

    return prop;
  }
};

// https://caniuse.com/#search=text-orientation

var textOrientation = {
  noPrefill: ['text-orientation'],
  supportedProperty: function supportedProperty(prop) {
    if (prop !== 'text-orientation') return false;

    if (css_vendor_esm_prefix.vendor === 'apple' && !css_vendor_esm_prefix.isTouch) {
      return css_vendor_esm_prefix.css + prop;
    }

    return prop;
  }
};

// https://caniuse.com/#search=transform

var transform = {
  noPrefill: ['transform'],
  supportedProperty: function supportedProperty(prop, style, options) {
    if (prop !== 'transform') return false;

    if (options.transform) {
      return prop;
    }

    return css_vendor_esm_prefix.css + prop;
  }
};

// https://caniuse.com/#search=transition

var transition = {
  noPrefill: ['transition'],
  supportedProperty: function supportedProperty(prop, style, options) {
    if (prop !== 'transition') return false;

    if (options.transition) {
      return prop;
    }

    return css_vendor_esm_prefix.css + prop;
  }
};

// https://caniuse.com/#search=writing-mode

var writingMode = {
  noPrefill: ['writing-mode'],
  supportedProperty: function supportedProperty(prop) {
    if (prop !== 'writing-mode') return false;

    if (css_vendor_esm_prefix.js === 'Webkit' || css_vendor_esm_prefix.js === 'ms') {
      return css_vendor_esm_prefix.css + prop;
    }

    return prop;
  }
};

// https://caniuse.com/#search=user-select

var userSelect = {
  noPrefill: ['user-select'],
  supportedProperty: function supportedProperty(prop) {
    if (prop !== 'user-select') return false;

    if (css_vendor_esm_prefix.js === 'Moz' || css_vendor_esm_prefix.js === 'ms' || css_vendor_esm_prefix.vendor === 'apple') {
      return css_vendor_esm_prefix.css + prop;
    }

    return prop;
  }
};

// https://caniuse.com/#search=multicolumn
// https://github.com/postcss/autoprefixer/issues/491
// https://github.com/postcss/autoprefixer/issues/177

var breakPropsOld = {
  supportedProperty: function supportedProperty(prop, style) {
    if (!/^break-/.test(prop)) return false;

    if (css_vendor_esm_prefix.js === 'Webkit') {
      var jsProp = "WebkitColumn" + pascalize(prop);
      return jsProp in style ? css_vendor_esm_prefix.css + "column-" + prop : false;
    }

    if (css_vendor_esm_prefix.js === 'Moz') {
      var _jsProp = "page" + pascalize(prop);

      return _jsProp in style ? "page-" + prop : false;
    }

    return false;
  }
};

// See https://github.com/postcss/autoprefixer/issues/324.

var inlineLogicalOld = {
  supportedProperty: function supportedProperty(prop, style) {
    if (!/^(border|margin|padding)-inline/.test(prop)) return false;
    if (css_vendor_esm_prefix.js === 'Moz') return prop;
    var newProp = prop.replace('-inline', '');
    return css_vendor_esm_prefix.js + pascalize(newProp) in style ? css_vendor_esm_prefix.css + newProp : false;
  }
};

// Camelization is required because we can't test using.
// CSS syntax for e.g. in FF.

var unprefixed = {
  supportedProperty: function supportedProperty(prop, style) {
    return camelize(prop) in style ? prop : false;
  }
};

var prefixed = {
  supportedProperty: function supportedProperty(prop, style) {
    var pascalized = pascalize(prop); // Return custom CSS variable without prefixing.

    if (prop[0] === '-') return prop; // Return already prefixed value without prefixing.

    if (prop[0] === '-' && prop[1] === '-') return prop;
    if (css_vendor_esm_prefix.js + pascalized in style) return css_vendor_esm_prefix.css + prop; // Try webkit fallback.

    if (css_vendor_esm_prefix.js !== 'Webkit' && "Webkit" + pascalized in style) return "-webkit-" + prop;
    return false;
  }
};

// https://caniuse.com/#search=scroll-snap

var scrollSnap = {
  supportedProperty: function supportedProperty(prop) {
    if (prop.substring(0, 11) !== 'scroll-snap') return false;

    if (css_vendor_esm_prefix.js === 'ms') {
      return "" + css_vendor_esm_prefix.css + prop;
    }

    return prop;
  }
};

// https://caniuse.com/#search=overscroll-behavior

var overscrollBehavior = {
  supportedProperty: function supportedProperty(prop) {
    if (prop !== 'overscroll-behavior') return false;

    if (css_vendor_esm_prefix.js === 'ms') {
      return css_vendor_esm_prefix.css + "scroll-chaining";
    }

    return prop;
  }
};

var propMap = {
  'flex-grow': 'flex-positive',
  'flex-shrink': 'flex-negative',
  'flex-basis': 'flex-preferred-size',
  'justify-content': 'flex-pack',
  order: 'flex-order',
  'align-items': 'flex-align',
  'align-content': 'flex-line-pack' // 'align-self' is handled by 'align-self' plugin.

}; // Support old flex spec from 2012.

var flex2012 = {
  supportedProperty: function supportedProperty(prop, style) {
    var newProp = propMap[prop];
    if (!newProp) return false;
    return css_vendor_esm_prefix.js + pascalize(newProp) in style ? css_vendor_esm_prefix.css + newProp : false;
  }
};

var propMap$1 = {
  flex: 'box-flex',
  'flex-grow': 'box-flex',
  'flex-direction': ['box-orient', 'box-direction'],
  order: 'box-ordinal-group',
  'align-items': 'box-align',
  'flex-flow': ['box-orient', 'box-direction'],
  'justify-content': 'box-pack'
};
var propKeys = Object.keys(propMap$1);

var prefixCss = function prefixCss(p) {
  return css_vendor_esm_prefix.css + p;
}; // Support old flex spec from 2009.


var flex2009 = {
  supportedProperty: function supportedProperty(prop, style, _ref) {
    var multiple = _ref.multiple;

    if (propKeys.indexOf(prop) > -1) {
      var newProp = propMap$1[prop];

      if (!Array.isArray(newProp)) {
        return css_vendor_esm_prefix.js + pascalize(newProp) in style ? css_vendor_esm_prefix.css + newProp : false;
      }

      if (!multiple) return false;

      for (var i = 0; i < newProp.length; i++) {
        if (!(css_vendor_esm_prefix.js + pascalize(newProp[0]) in style)) {
          return false;
        }
      }

      return newProp.map(prefixCss);
    }

    return false;
  }
};

// plugins = [
//   ...plugins,
//    breakPropsOld,
//    inlineLogicalOld,
//    unprefixed,
//    prefixed,
//    scrollSnap,
//    flex2012,
//    flex2009
// ]
// Plugins without 'noPrefill' value, going last.
// 'flex-*' plugins should be at the bottom.
// 'flex2009' going after 'flex2012'.
// 'prefixed' going after 'unprefixed'

var css_vendor_esm_plugins = [appearence, colorAdjust, mask, textOrientation, transform, transition, writingMode, userSelect, breakPropsOld, inlineLogicalOld, unprefixed, prefixed, scrollSnap, overscrollBehavior, flex2012, flex2009];
var propertyDetectors = css_vendor_esm_plugins.filter(function (p) {
  return p.supportedProperty;
}).map(function (p) {
  return p.supportedProperty;
});
var noPrefill = css_vendor_esm_plugins.filter(function (p) {
  return p.noPrefill;
}).reduce(function (a, p) {
  a.push.apply(a, _toConsumableArray(p.noPrefill));
  return a;
}, []);

var el;
var css_vendor_esm_cache = {};

if (dist_module) {
  el = document.createElement('p'); // We test every property on vendor prefix requirement.
  // Once tested, result is cached. It gives us up to 70% perf boost.
  // http://jsperf.com/element-style-object-access-vs-plain-object
  //
  // Prefill cache with known css properties to reduce amount of
  // properties we need to feature test at runtime.
  // http://davidwalsh.name/vendor-prefix

  var computed = window.getComputedStyle(document.documentElement, '');

  for (var key$1 in computed) {
    // eslint-disable-next-line no-restricted-globals
    if (!isNaN(key$1)) css_vendor_esm_cache[computed[key$1]] = computed[key$1];
  } // Properties that cannot be correctly detected using the
  // cache prefill method.


  noPrefill.forEach(function (x) {
    return delete css_vendor_esm_cache[x];
  });
}
/**
 * Test if a property is supported, returns supported property with vendor
 * prefix if required. Returns `false` if not supported.
 *
 * @param {String} prop dash separated
 * @param {Object} [options]
 * @return {String|Boolean}
 * @api public
 */


function supportedProperty(prop, options) {
  if (options === void 0) {
    options = {};
  }

  // For server-side rendering.
  if (!el) return prop; // Remove cache for benchmark tests or return property from the cache.

  if ( true && css_vendor_esm_cache[prop] != null) {
    return css_vendor_esm_cache[prop];
  } // Check if 'transition' or 'transform' natively supported in browser.


  if (prop === 'transition' || prop === 'transform') {
    options[prop] = prop in el.style;
  } // Find a plugin for current prefix property.


  for (var i = 0; i < propertyDetectors.length; i++) {
    css_vendor_esm_cache[prop] = propertyDetectors[i](prop, el.style, options); // Break loop, if value found.

    if (css_vendor_esm_cache[prop]) break;
  } // Reset styles for current property.
  // Firefox can even throw an error for invalid properties, e.g., "0".


  try {
    el.style[prop] = '';
  } catch (err) {
    return false;
  }

  return css_vendor_esm_cache[prop];
}

var cache$1 = {};
var transitionProperties = {
  transition: 1,
  'transition-property': 1,
  '-webkit-transition': 1,
  '-webkit-transition-property': 1
};
var transPropsRegExp = /(^\s*[\w-]+)|, (\s*[\w-]+)(?![^()]*\))/g;
var el$1;
/**
 * Returns prefixed value transition/transform if needed.
 *
 * @param {String} match
 * @param {String} p1
 * @param {String} p2
 * @return {String}
 * @api private
 */

function prefixTransitionCallback(match, p1, p2) {
  if (p1 === 'var') return 'var';
  if (p1 === 'all') return 'all';
  if (p2 === 'all') return ', all';
  var prefixedValue = p1 ? supportedProperty(p1) : ", " + supportedProperty(p2);
  if (!prefixedValue) return p1 || p2;
  return prefixedValue;
}

if (dist_module) el$1 = document.createElement('p');
/**
 * Returns prefixed value if needed. Returns `false` if value is not supported.
 *
 * @param {String} property
 * @param {String} value
 * @return {String|Boolean}
 * @api public
 */

function supportedValue(property, value) {
  // For server-side rendering.
  var prefixedValue = value;
  if (!el$1 || property === 'content') return value; // It is a string or a number as a string like '1'.
  // We want only prefixable values here.
  // eslint-disable-next-line no-restricted-globals

  if (typeof prefixedValue !== 'string' || !isNaN(parseInt(prefixedValue, 10))) {
    return prefixedValue;
  } // Create cache key for current value.


  var cacheKey = property + prefixedValue; // Remove cache for benchmark tests or return value from cache.

  if ( true && cache$1[cacheKey] != null) {
    return cache$1[cacheKey];
  } // IE can even throw an error in some cases, for e.g. style.content = 'bar'.


  try {
    // Test value as it is.
    el$1.style[property] = prefixedValue;
  } catch (err) {
    // Return false if value not supported.
    cache$1[cacheKey] = false;
    return false;
  } // If 'transition' or 'transition-property' property.


  if (transitionProperties[property]) {
    prefixedValue = prefixedValue.replace(transPropsRegExp, prefixTransitionCallback);
  } else if (el$1.style[property] === '') {
    // Value with a vendor prefix.
    prefixedValue = css_vendor_esm_prefix.css + prefixedValue; // Hardcode test to convert "flex" to "-ms-flexbox" for IE10.

    if (prefixedValue === '-ms-flex') el$1.style[property] = '-ms-flexbox'; // Test prefixed value.

    el$1.style[property] = prefixedValue; // Return false if value not supported.

    if (el$1.style[property] === '') {
      cache$1[cacheKey] = false;
      return false;
    }
  } // Reset styles for current property.


  el$1.style[property] = ''; // Write current value to cache.

  cache$1[cacheKey] = prefixedValue;
  return cache$1[cacheKey];
}



// CONCATENATED MODULE: ./node_modules/jss-plugin-vendor-prefixer/dist/jss-plugin-vendor-prefixer.esm.js



/**
 * Add vendor prefix to a property name when needed.
 *
 * @api public
 */

function jssVendorPrefixer() {
  function onProcessRule(rule) {
    if (rule.type === 'keyframes') {
      var atRule = rule;
      atRule.at = supportedKeyframes(atRule.at);
    }
  }

  function prefixStyle(style) {
    for (var prop in style) {
      var value = style[prop];

      if (prop === 'fallbacks' && Array.isArray(value)) {
        style[prop] = value.map(prefixStyle);
        continue;
      }

      var changeProp = false;
      var supportedProp = supportedProperty(prop);
      if (supportedProp && supportedProp !== prop) changeProp = true;
      var changeValue = false;
      var supportedValue$$1 = supportedValue(supportedProp, toCssValue(value));
      if (supportedValue$$1 && supportedValue$$1 !== value) changeValue = true;

      if (changeProp || changeValue) {
        if (changeProp) delete style[prop];
        style[supportedProp || prop] = supportedValue$$1 || value;
      }
    }

    return style;
  }

  function onProcessStyle(style, rule) {
    if (rule.type !== 'style') return style;
    return prefixStyle(style);
  }

  function onChangeValue(value, prop) {
    return supportedValue(prop, toCssValue(value)) || value;
  }

  return {
    onProcessRule: onProcessRule,
    onProcessStyle: onProcessStyle,
    onChangeValue: onChangeValue
  };
}

/* harmony default export */ var jss_plugin_vendor_prefixer_esm = (jssVendorPrefixer);

// CONCATENATED MODULE: ./node_modules/jss-plugin-props-sort/dist/jss-plugin-props-sort.esm.js
/**
 * Sort props by length.
 */
function jssPropsSort() {
  var sort = function sort(prop0, prop1) {
    if (prop0.length === prop1.length) {
      return prop0 > prop1 ? 1 : -1;
    }

    return prop0.length - prop1.length;
  };

  return {
    onProcessStyle: function onProcessStyle(style, rule) {
      if (rule.type !== 'style') return style;
      var newStyle = {};
      var props = Object.keys(style).sort(sort);

      for (var i = 0; i < props.length; i++) {
        newStyle[props[i]] = style[props[i]];
      }

      return newStyle;
    }
  };
}

/* harmony default export */ var jss_plugin_props_sort_esm = (jssPropsSort);

// CONCATENATED MODULE: ./node_modules/@material-ui/styles/esm/jssPreset/jssPreset.js






 // Subset of jss-preset-default with only the plugins the Material-UI components are using.

function jssPreset() {
  return {
    plugins: [jss_plugin_rule_value_function_esm(), jss_plugin_global_esm(), jss_plugin_nested_esm(), jss_plugin_camel_case_esm(), jss_plugin_default_unit_esm(), // Disable the vendor prefixer server-side, it does nothing.
    // This way, we can get a performance boost.
    // In the documentation, we are using `autoprefixer` to solve this problem.
    typeof window === 'undefined' ? null : jss_plugin_vendor_prefixer_esm(), jss_plugin_props_sort_esm()]
  };
}

/* harmony default export */ var jssPreset_jssPreset = (jssPreset);
// CONCATENATED MODULE: ./node_modules/@material-ui/styles/esm/StylesProvider/StylesProvider.js







 // Default JSS instance.

var StylesProvider_jss = jss_esm_create(jssPreset_jssPreset()); // Use a singleton or the provided one by the context.
//
// The counter-based approach doesn't tolerate any mistake.
// It's much safer to use the same counter everywhere.

var generateClassName = createGenerateClassName(); // Exported for test purposes

var sheetsManager = new Map();
var defaultOptions = {
  disableGeneration: false,
  generateClassName: generateClassName,
  jss: StylesProvider_jss,
  sheetsCache: null,
  sheetsManager: sheetsManager,
  sheetsRegistry: null
};
var StylesContext = react_default.a.createContext(defaultOptions);

if (false) {}

var injectFirstNode;

function StylesProvider(props) {
  var children = props.children,
      _props$injectFirst = props.injectFirst,
      injectFirst = _props$injectFirst === void 0 ? false : _props$injectFirst,
      _props$disableGenerat = props.disableGeneration,
      disableGeneration = _props$disableGenerat === void 0 ? false : _props$disableGenerat,
      localOptions = Object(objectWithoutProperties["a" /* default */])(props, ["children", "injectFirst", "disableGeneration"]);

  var outerOptions = react_default.a.useContext(StylesContext);

  var context = Object(esm_extends["a" /* default */])({}, outerOptions, {
    disableGeneration: disableGeneration
  }, localOptions);

  if (false) {}

  if (false) {}

  if (false) {}

  if (!context.jss.options.insertionPoint && injectFirst && typeof window !== 'undefined') {
    if (!injectFirstNode) {
      var head = document.head;
      injectFirstNode = document.createComment('mui-inject-first');
      head.insertBefore(injectFirstNode, head.firstChild);
    }

    context.jss = jss_esm_create({
      plugins: jssPreset_jssPreset().plugins,
      insertionPoint: injectFirstNode
    });
  }

  return react_default.a.createElement(StylesContext.Provider, {
    value: context
  }, children);
}

 false ? undefined : void 0;

if (false) {}

/* harmony default export */ var StylesProvider_StylesProvider = (StylesProvider);
// CONCATENATED MODULE: ./node_modules/@material-ui/styles/esm/makeStyles/indexCounter.js
/* eslint-disable import/prefer-default-export */
// Global index counter to preserve source order.
// We create the style sheet during at the creation of the component,
// children are handled after the parents, so the order of style elements would be parent->child.
// It is a problem though when a parent passes a className
// which needs to override any child's styles.
// StyleSheet of the child has a higher specificity, because of the source order.
// So our solution is to render sheets them in the reverse order child->sheet, so
// that parent has a higher specificity.
var indexCounter = -1e9;
function increment() {
  indexCounter += 1;

  if (false) {}

  return indexCounter;
}
// CONCATENATED MODULE: ./node_modules/@material-ui/styles/node_modules/@babel/runtime/helpers/esm/typeof.js
function typeof_typeof(obj) {
  "@babel/helpers - typeof";

  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    typeof_typeof = function _typeof(obj) {
      return typeof obj;
    };
  } else {
    typeof_typeof = function _typeof(obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
  }

  return typeof_typeof(obj);
}
// EXTERNAL MODULE: ./node_modules/@material-ui/utils/esm/deepmerge.js + 2 modules
var deepmerge = __webpack_require__(158);

// CONCATENATED MODULE: ./node_modules/@material-ui/styles/esm/getStylesCreator/getStylesCreator.js





function getStylesCreator(stylesOrCreator) {
  var themingEnabled = typeof stylesOrCreator === 'function';

  if (false) {}

  return {
    create: function create(theme, name) {
      var styles;

      try {
        styles = themingEnabled ? stylesOrCreator(theme) : stylesOrCreator;
      } catch (err) {
        if (false) {}

        throw err;
      }

      if (!name || !theme.overrides || !theme.overrides[name]) {
        return styles;
      }

      var overrides = theme.overrides[name];

      var stylesWithOverrides = Object(esm_extends["a" /* default */])({}, styles);

      Object.keys(overrides).forEach(function (key) {
        if (false) {}

        stylesWithOverrides[key] = Object(deepmerge["a" /* default */])(stylesWithOverrides[key], overrides[key]);
      });
      return stylesWithOverrides;
    },
    options: {}
  };
}

/* harmony default export */ var getStylesCreator_getStylesCreator = (getStylesCreator);
// CONCATENATED MODULE: ./node_modules/@material-ui/styles/esm/getStylesCreator/noopTheme.js
// We use the same empty object to ref count the styles that don't need a theme object.
var noopTheme = {};
/* harmony default export */ var getStylesCreator_noopTheme = (noopTheme);
// CONCATENATED MODULE: ./node_modules/@material-ui/styles/esm/makeStyles/makeStyles.js












function getClasses(_ref, classes, Component) {
  var state = _ref.state,
      stylesOptions = _ref.stylesOptions;

  if (stylesOptions.disableGeneration) {
    return classes || {};
  }

  if (!state.cacheClasses) {
    state.cacheClasses = {
      // Cache for the finalized classes value.
      value: null,
      // Cache for the last used classes prop pointer.
      lastProp: null,
      // Cache for the last used rendered classes pointer.
      lastJSS: {}
    };
  } // Tracks if either the rendered classes or classes prop has changed,
  // requiring the generation of a new finalized classes object.


  var generate = false;

  if (state.classes !== state.cacheClasses.lastJSS) {
    state.cacheClasses.lastJSS = state.classes;
    generate = true;
  }

  if (classes !== state.cacheClasses.lastProp) {
    state.cacheClasses.lastProp = classes;
    generate = true;
  }

  if (generate) {
    state.cacheClasses.value = Object(mergeClasses["a" /* default */])({
      baseClasses: state.cacheClasses.lastJSS,
      newClasses: classes,
      Component: Component
    });
  }

  return state.cacheClasses.value;
}

function attach(_ref2, props) {
  var state = _ref2.state,
      theme = _ref2.theme,
      stylesOptions = _ref2.stylesOptions,
      stylesCreator = _ref2.stylesCreator,
      name = _ref2.name;

  if (stylesOptions.disableGeneration) {
    return;
  }

  var sheetManager = makeStyles_multiKeyStore.get(stylesOptions.sheetsManager, stylesCreator, theme);

  if (!sheetManager) {
    sheetManager = {
      refs: 0,
      staticSheet: null,
      dynamicStyles: null
    };
    makeStyles_multiKeyStore.set(stylesOptions.sheetsManager, stylesCreator, theme, sheetManager);
  }

  var options = Object(esm_extends["a" /* default */])({}, stylesCreator.options, {}, stylesOptions, {
    theme: theme,
    flip: typeof stylesOptions.flip === 'boolean' ? stylesOptions.flip : theme.direction === 'rtl'
  });

  options.generateId = options.serverGenerateClassName || options.generateClassName;
  var sheetsRegistry = stylesOptions.sheetsRegistry;

  if (sheetManager.refs === 0) {
    var staticSheet;

    if (stylesOptions.sheetsCache) {
      staticSheet = makeStyles_multiKeyStore.get(stylesOptions.sheetsCache, stylesCreator, theme);
    }

    var styles = stylesCreator.create(theme, name);

    if (!staticSheet) {
      staticSheet = stylesOptions.jss.createStyleSheet(styles, Object(esm_extends["a" /* default */])({
        link: false
      }, options));
      staticSheet.attach();

      if (stylesOptions.sheetsCache) {
        makeStyles_multiKeyStore.set(stylesOptions.sheetsCache, stylesCreator, theme, staticSheet);
      }
    }

    if (sheetsRegistry) {
      sheetsRegistry.add(staticSheet);
    }

    sheetManager.staticSheet = staticSheet;
    sheetManager.dynamicStyles = getDynamicStyles(styles);
  }

  if (sheetManager.dynamicStyles) {
    var dynamicSheet = stylesOptions.jss.createStyleSheet(sheetManager.dynamicStyles, Object(esm_extends["a" /* default */])({
      link: true
    }, options));
    dynamicSheet.update(props);
    dynamicSheet.attach();
    state.dynamicSheet = dynamicSheet;
    state.classes = Object(mergeClasses["a" /* default */])({
      baseClasses: sheetManager.staticSheet.classes,
      newClasses: dynamicSheet.classes
    });

    if (sheetsRegistry) {
      sheetsRegistry.add(dynamicSheet);
    }
  } else {
    state.classes = sheetManager.staticSheet.classes;
  }

  sheetManager.refs += 1;
}

function update(_ref3, props) {
  var state = _ref3.state;

  if (state.dynamicSheet) {
    state.dynamicSheet.update(props);
  }
}

function detach(_ref4) {
  var state = _ref4.state,
      theme = _ref4.theme,
      stylesOptions = _ref4.stylesOptions,
      stylesCreator = _ref4.stylesCreator;

  if (stylesOptions.disableGeneration) {
    return;
  }

  var sheetManager = makeStyles_multiKeyStore.get(stylesOptions.sheetsManager, stylesCreator, theme);
  sheetManager.refs -= 1;
  var sheetsRegistry = stylesOptions.sheetsRegistry;

  if (sheetManager.refs === 0) {
    makeStyles_multiKeyStore.delete(stylesOptions.sheetsManager, stylesCreator, theme);
    stylesOptions.jss.removeStyleSheet(sheetManager.staticSheet);

    if (sheetsRegistry) {
      sheetsRegistry.remove(sheetManager.staticSheet);
    }
  }

  if (state.dynamicSheet) {
    stylesOptions.jss.removeStyleSheet(state.dynamicSheet);

    if (sheetsRegistry) {
      sheetsRegistry.remove(state.dynamicSheet);
    }
  }
}

function useSynchronousEffect(func, values) {
  var key = react_default.a.useRef([]);
  var output; // Store "generation" key. Just returns a new object every time

  var currentKey = react_default.a.useMemo(function () {
    return {};
  }, values); // eslint-disable-line react-hooks/exhaustive-deps
  // "the first render", or "memo dropped the value"

  if (key.current !== currentKey) {
    key.current = currentKey;
    output = func();
  }

  react_default.a.useEffect(function () {
    return function () {
      if (output) {
        output();
      }
    };
  }, [currentKey] // eslint-disable-line react-hooks/exhaustive-deps
  );
}

function makeStyles(stylesOrCreator) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

  var name = options.name,
      classNamePrefixOption = options.classNamePrefix,
      Component = options.Component,
      _options$defaultTheme = options.defaultTheme,
      defaultTheme = _options$defaultTheme === void 0 ? getStylesCreator_noopTheme : _options$defaultTheme,
      stylesOptions2 = Object(objectWithoutProperties["a" /* default */])(options, ["name", "classNamePrefix", "Component", "defaultTheme"]);

  var stylesCreator = getStylesCreator_getStylesCreator(stylesOrCreator);
  var classNamePrefix = name || classNamePrefixOption || 'makeStyles';
  stylesCreator.options = {
    index: increment(),
    name: name,
    meta: classNamePrefix,
    classNamePrefix: classNamePrefix
  };
  return function () {
    var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var theme = Object(useTheme["a" /* default */])() || defaultTheme;

    var stylesOptions = Object(esm_extends["a" /* default */])({}, react_default.a.useContext(StylesContext), {}, stylesOptions2);

    var instance = react_default.a.useRef();
    var shouldUpdate = react_default.a.useRef();
    useSynchronousEffect(function () {
      var current = {
        name: name,
        state: {},
        stylesCreator: stylesCreator,
        stylesOptions: stylesOptions,
        theme: theme
      };
      attach(current, props);
      shouldUpdate.current = false;
      instance.current = current;
      return function () {
        detach(current);
      };
    }, [theme, stylesCreator]);
    react_default.a.useEffect(function () {
      if (shouldUpdate.current) {
        update(instance.current, props);
      }

      shouldUpdate.current = true;
    });
    return getClasses(instance.current, props.classes, Component);
  };
}

/* harmony default export */ var makeStyles_makeStyles = __webpack_exports__["a"] = (makeStyles);

/***/ }),
/* 158 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// CONCATENATED MODULE: ./node_modules/@material-ui/utils/node_modules/@babel/runtime/helpers/esm/extends.js
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);
}
// CONCATENATED MODULE: ./node_modules/@material-ui/utils/node_modules/@babel/runtime/helpers/esm/typeof.js
function _typeof(obj) {
  "@babel/helpers - typeof";

  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof = function _typeof(obj) {
      return typeof obj;
    };
  } else {
    _typeof = function _typeof(obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
  }

  return _typeof(obj);
}
// CONCATENATED MODULE: ./node_modules/@material-ui/utils/esm/deepmerge.js
/* unused harmony export isObject */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return deepmerge; });


function isObject(item) {
  return item && _typeof(item) === 'object' && !Array.isArray(item);
}
function deepmerge(target, source) {
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
    clone: true
  };
  var output = options.clone ? _extends({}, target) : target;

  if (isObject(target) && isObject(source)) {
    Object.keys(source).forEach(function (key) {
      // Avoid prototype pollution
      if (key === '__proto__') {
        return;
      }

      if (isObject(source[key]) && key in target) {
        output[key] = deepmerge(target[key], source[key], options);
      } else {
        output[key] = source[key];
      }
    });
  }

  return output;
}

/***/ })
/******/ ]);
});
//# sourceMappingURL=qdt-components.js.map