import { _ as _extends$1 } from '../extends-C4cduGrv.js';
import { a as _objectWithoutPropertiesLoose, _ as _objectWithoutProperties$2 } from '../objectWithoutProperties-TXwlfNxG.js';
import * as React from 'react';
import React__default, { useRef, useImperativeHandle, useEffect, useState, useCallback, forwardRef } from 'react';
import { _ as _createClass, a as _inherits$1, b as _classCallCheck$1, c as _assertThisInitialized, d as _getPrototypeOf, e as _possibleConstructorReturn$1 } from '../createClass-DT8Y0mhp.js';
import * as ReactDOM from 'react-dom';
import { render } from 'react-dom';
import { _ as _defineProperty } from '../defineProperty-CEd-kZQW.js';
import { _ as _toConsumableArray } from '../toConsumableArray-dKQYsfpV.js';
import { _ as _slicedToArray } from '../slicedToArray-BB-AwwkK.js';
import { _ as _typeof } from '../typeof-CgC7Bq6K.js';
import { object, func, oneOfType, node, string } from 'prop-types';
import VisuallyHidden from '@reach/visually-hidden';
import Toast from '../toast/index.js';
import '../setPrototypeOf-Bchah3-D.js';
import '../index-qSfOyGhk.js';
import '../toast/assets/close.js';
import '../toast/assets/success.js';
import '../toast/assets/error.js';
import '../toast/assets/info.js';
import '../button/index.js';
import '../ck-icon/index.js';
import 'classnames';
import '../ck-icon/assets/icon-map/index.js';
import '../icon/index.js';
import '@fortawesome/react-fontawesome';
import '../icon/icons.js';
import '../icon/library.js';
import '@fortawesome/fontawesome-svg-core';
import '@fortawesome/pro-solid-svg-icons';
import '@fortawesome/pro-light-svg-icons';
import '@fortawesome/free-brands-svg-icons';
import '../floating-ui.react-cWPyyUrN.js';
import '../button/button-group.js';

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike  ) { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }

function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var is = {
  arr: Array.isArray,
  obj: function obj(a) {
    return Object.prototype.toString.call(a) === '[object Object]';
  },
  fun: function fun(a) {
    return typeof a === 'function';
  },
  str: function str(a) {
    return typeof a === 'string';
  },
  num: function num(a) {
    return typeof a === 'number';
  },
  und: function und(a) {
    return a === void 0;
  },
  nul: function nul(a) {
    return a === null;
  },
  set: function set(a) {
    return a instanceof Set;
  },
  map: function map(a) {
    return a instanceof Map;
  },
  equ: function equ(a, b) {
    if (_typeof(a) !== _typeof(b)) return false;
    if (is.str(a) || is.num(a)) return a === b;
    if (is.obj(a) && is.obj(b) && Object.keys(a).length + Object.keys(b).length === 0) return true;
    var i;

    for (i in a) {
      if (!(i in b)) return false;
    }

    for (i in b) {
      if (a[i] !== b[i]) return false;
    }

    return is.und(i) ? a === b : true;
  }
};

function merge(target, lowercase) {

  return function (object) {
    return (is.arr(object) ? object : Object.keys(object)).reduce(function (acc, element) {
      var key = element;
      acc[key] = target(key);
      return acc;
    }, target);
  };
}

function useForceUpdate() {
  var _useState = useState(false),
      f = _useState[1];

  var forceUpdate = useCallback(function () {
    return f(function (v) {
      return !v;
    });
  }, []);
  return forceUpdate;
}

function withDefault(value, defaultValue) {
  return is.und(value) || is.nul(value) ? defaultValue : value;
}

function toArray(a) {
  return !is.und(a) ? is.arr(a) ? a : [a] : [];
}

function callProp(obj) {
  for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }

  return is.fun(obj) ? obj.apply(void 0, args) : obj;
}

function getForwardProps(props) {
  props.to;
      props.from;
      props.config;
      props.onStart;
      props.onRest;
      props.onFrame;
      props.children;
      props.reset;
      props.reverse;
      props.force;
      props.immediate;
      props.delay;
      props.attach;
      props.destroyed;
      props.interpolateTo;
      props.ref;
      props.lazy;
      var forward = _objectWithoutPropertiesLoose(props, ["to", "from", "config", "onStart", "onRest", "onFrame", "children", "reset", "reverse", "force", "immediate", "delay", "attach", "destroyed", "interpolateTo", "ref", "lazy"]);

  return forward;
}

function interpolateTo(props) {
  var forward = getForwardProps(props);
  if (is.und(forward)) return _extends$1({
    to: forward
  }, props);
  var rest = Object.keys(props).reduce(function (a, k) {
    return !is.und(forward[k]) ? a : _extends$1({}, a, _defineProperty({}, k, props[k]));
  }, {});
  return _extends$1({
    to: forward
  }, rest);
}

function handleRef(ref, forward) {
  if (forward) {
    // If it's a function, assume it's a ref callback
    if (is.fun(forward)) forward(ref);else if (is.obj(forward)) {
      forward.current = ref;
    }
  }

  return ref;
}

var Animated = /*#__PURE__*/function () {
  function Animated() {
    _classCallCheck$1(this, Animated);

    this.payload = void 0;
    this.children = [];
  }

  _createClass(Animated, [{
    key: "getAnimatedValue",
    value: function getAnimatedValue() {
      return this.getValue();
    }
  }, {
    key: "getPayload",
    value: function getPayload() {
      return this.payload || this;
    }
  }, {
    key: "attach",
    value: function attach() {}
  }, {
    key: "detach",
    value: function detach() {}
  }, {
    key: "getChildren",
    value: function getChildren() {
      return this.children;
    }
  }, {
    key: "addChild",
    value: function addChild(child) {
      if (this.children.length === 0) this.attach();
      this.children.push(child);
    }
  }, {
    key: "removeChild",
    value: function removeChild(child) {
      var index = this.children.indexOf(child);
      this.children.splice(index, 1);
      if (this.children.length === 0) this.detach();
    }
  }]);

  return Animated;
}();

var AnimatedArray = /*#__PURE__*/function (_Animated) {
  _inherits$1(AnimatedArray, _Animated);

  var _super = _createSuper$1(AnimatedArray);

  function AnimatedArray() {
    var _this2;

    _classCallCheck$1(this, AnimatedArray);

    _this2 = _super.apply(this, arguments);
    _this2.payload = [];

    _this2.attach = function () {
      return _this2.payload.forEach(function (p) {
        return p instanceof Animated && p.addChild(_assertThisInitialized(_this2));
      });
    };

    _this2.detach = function () {
      return _this2.payload.forEach(function (p) {
        return p instanceof Animated && p.removeChild(_assertThisInitialized(_this2));
      });
    };

    return _this2;
  }

  return AnimatedArray;
}(Animated);

var AnimatedObject = /*#__PURE__*/function (_Animated2) {
  _inherits$1(AnimatedObject, _Animated2);

  var _super2 = _createSuper$1(AnimatedObject);

  function AnimatedObject() {
    var _this3;

    _classCallCheck$1(this, AnimatedObject);

    _this3 = _super2.apply(this, arguments);
    _this3.payload = {};

    _this3.attach = function () {
      return Object.values(_this3.payload).forEach(function (s) {
        return s instanceof Animated && s.addChild(_assertThisInitialized(_this3));
      });
    };

    _this3.detach = function () {
      return Object.values(_this3.payload).forEach(function (s) {
        return s instanceof Animated && s.removeChild(_assertThisInitialized(_this3));
      });
    };

    return _this3;
  }

  _createClass(AnimatedObject, [{
    key: "getValue",
    value: function getValue(animated) {
      if (animated === void 0) {
        animated = false;
      }

      var payload = {};

      for (var key in this.payload) {
        var value = this.payload[key];
        if (animated && !(value instanceof Animated)) continue;
        payload[key] = value instanceof Animated ? value[animated ? 'getAnimatedValue' : 'getValue']() : value;
      }

      return payload;
    }
  }, {
    key: "getAnimatedValue",
    value: function getAnimatedValue() {
      return this.getValue(true);
    }
  }]);

  return AnimatedObject;
}(Animated);

var applyAnimatedValues;

function injectApplyAnimatedValues(fn, transform) {
  applyAnimatedValues = {
    fn: fn,
    transform: transform
  };
}

var colorNames;

function injectColorNames(names) {
  colorNames = names;
}

var requestFrame = function requestFrame(cb) {
  return typeof window !== 'undefined' ? window.requestAnimationFrame(cb) : -1;
};

var interpolation;

function injectStringInterpolator(fn) {
  interpolation = fn;
}

var now = function now() {
  return Date.now();
};

var animatedApi = function animatedApi(node) {
  return node.current;
};

var createAnimatedStyle;

function injectCreateAnimatedStyle(factory) {
  createAnimatedStyle = factory;
}
/**
 * Wraps the `style` property with `AnimatedStyle`.
 */

var AnimatedProps = /*#__PURE__*/function (_AnimatedObject) {
  _inherits$1(AnimatedProps, _AnimatedObject);

  var _super3 = _createSuper$1(AnimatedProps);

  function AnimatedProps(props, callback) {
    var _this4;

    _classCallCheck$1(this, AnimatedProps);

    _this4 = _super3.call(this);
    _this4.update = void 0;
    _this4.payload = !props.style ? props : _extends$1({}, props, {
      style: createAnimatedStyle(props.style)
    });
    _this4.update = callback;

    _this4.attach();

    return _this4;
  }

  return AnimatedProps;
}(AnimatedObject);

var isFunctionComponent = function isFunctionComponent(val) {
  return is.fun(val) && !(val.prototype instanceof React__default.Component);
};

var createAnimatedComponent = function createAnimatedComponent(Component) {
  var AnimatedComponent = /*#__PURE__*/forwardRef(function (props, ref) {
    var forceUpdate = useForceUpdate();
    var mounted = useRef(true);
    var propsAnimated = useRef(null);
    var node = useRef(null);
    var attachProps = useCallback(function (props) {
      var oldPropsAnimated = propsAnimated.current;

      var callback = function callback() {
        var didUpdate = false;

        if (node.current) {
          didUpdate = applyAnimatedValues.fn(node.current, propsAnimated.current.getAnimatedValue());
        }

        if (!node.current || didUpdate === false) {
          // If no referenced node has been found, or the update target didn't have a
          // native-responder, then forceUpdate the animation ...
          forceUpdate();
        }
      };

      propsAnimated.current = new AnimatedProps(props, callback);
      oldPropsAnimated && oldPropsAnimated.detach();
    }, []);
    useEffect(function () {
      return function () {
        mounted.current = false;
        propsAnimated.current && propsAnimated.current.detach();
      };
    }, []);
    useImperativeHandle(ref, function () {
      return animatedApi(node);
    });
    attachProps(props);

    var _getValue = propsAnimated.current.getValue();
        _getValue.scrollTop;
        _getValue.scrollLeft;
        var animatedProps = _objectWithoutPropertiesLoose(_getValue, ["scrollTop", "scrollLeft"]); // Functions cannot have refs, see:
    // See: https://github.com/react-spring/react-spring/issues/569


    var refFn = isFunctionComponent(Component) ? undefined : function (childRef) {
      return node.current = handleRef(childRef, ref);
    };
    return /*#__PURE__*/React__default.createElement(Component, _extends$1({}, animatedProps, {
      ref: refFn
    }));
  });
  return AnimatedComponent;
};

var active = false;
var controllers = new Set();

var update = function update() {
  if (!active) return false;
  var time = now();

  var _iterator = _createForOfIteratorHelper(controllers),
      _step;

  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var controller = _step.value;
      var isActive = false;

      for (var configIdx = 0; configIdx < controller.configs.length; configIdx++) {
        var _config = controller.configs[configIdx];
        var endOfAnimation = void 0,
            lastTime = void 0;

        for (var valIdx = 0; valIdx < _config.animatedValues.length; valIdx++) {
          var animation = _config.animatedValues[valIdx]; // If an animation is done, skip, until all of them conclude

          if (animation.done) continue;
          var from = _config.fromValues[valIdx];
          var to = _config.toValues[valIdx];
          var position = animation.lastPosition;
          var isAnimated = to instanceof Animated;
          var velocity = Array.isArray(_config.initialVelocity) ? _config.initialVelocity[valIdx] : _config.initialVelocity;
          if (isAnimated) to = to.getValue(); // Conclude animation if it's either immediate, or from-values match end-state

          if (_config.immediate) {
            animation.setValue(to);
            animation.done = true;
            continue;
          } // Break animation when string values are involved


          if (typeof from === 'string' || typeof to === 'string') {
            animation.setValue(to);
            animation.done = true;
            continue;
          }

          if (_config.duration !== void 0) {
            /** Duration easing */
            position = from + _config.easing((time - animation.startTime) / _config.duration) * (to - from);
            endOfAnimation = time >= animation.startTime + _config.duration;
          } else if (_config.decay) {
            /** Decay easing */
            position = from + velocity / (1 - 0.998) * (1 - Math.exp(-(1 - 0.998) * (time - animation.startTime)));
            endOfAnimation = Math.abs(animation.lastPosition - position) < 0.1;
            if (endOfAnimation) to = position;
          } else {
            /** Spring easing */
            lastTime = animation.lastTime !== void 0 ? animation.lastTime : time;
            velocity = animation.lastVelocity !== void 0 ? animation.lastVelocity : _config.initialVelocity; // If we lost a lot of frames just jump to the end.

            if (time > lastTime + 64) lastTime = time; // http://gafferongames.com/game-physics/fix-your-timestep/

            var numSteps = Math.floor(time - lastTime);

            for (var i = 0; i < numSteps; ++i) {
              var force = -_config.tension * (position - to);
              var damping = -_config.friction * velocity;
              var acceleration = (force + damping) / _config.mass;
              velocity = velocity + acceleration * 1 / 1000;
              position = position + velocity * 1 / 1000;
            } // Conditions for stopping the spring animation


            var isOvershooting = _config.clamp && _config.tension !== 0 ? from < to ? position > to : position < to : false;

            var isVelocity = Math.abs(velocity) <= _config.precision;

            var isDisplacement = _config.tension !== 0 ? Math.abs(to - position) <= _config.precision : true;
            endOfAnimation = isOvershooting || isVelocity && isDisplacement;
            animation.lastVelocity = velocity;
            animation.lastTime = time;
          } // Trails aren't done until their parents conclude


          if (isAnimated && !_config.toValues[valIdx].done) endOfAnimation = false;

          if (endOfAnimation) {
            // Ensure that we end up with a round value
            if (animation.value !== to) position = to;
            animation.done = true;
          } else isActive = true;

          animation.setValue(position);
          animation.lastPosition = position;
        } // Keep track of updated values only when necessary


        if (controller.props.onFrame) controller.values[_config.name] = _config.interpolation.getValue();
      } // Update callbacks in the end of the frame


      if (controller.props.onFrame) controller.props.onFrame(controller.values); // Either call onEnd or next frame

      if (!isActive) {
        controllers["delete"](controller);
        controller.stop(true);
      }
    } // Loop over as long as there are controllers ...

  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }

  if (controllers.size) {
    requestFrame(update);
  } else {
    active = false;
  }

  return active;
};

var _start = function start(controller) {
  if (!controllers.has(controller)) controllers.add(controller);

  if (!active) {
    active = true;
    requestFrame(update);
  }
};

var stop = function stop(controller) {
  if (controllers.has(controller)) controllers["delete"](controller);
};

function createInterpolator(range, output, extrapolate) {
  if (typeof range === 'function') {
    return range;
  }

  if (Array.isArray(range)) {
    return createInterpolator({
      range: range,
      output: output,
      extrapolate: extrapolate
    });
  }

  if (interpolation && typeof range.output[0] === 'string') {
    return interpolation(range);
  }

  var config = range;
  var outputRange = config.output;
  var inputRange = config.range || [0, 1];
  var extrapolateLeft = config.extrapolateLeft || config.extrapolate || 'extend';
  var extrapolateRight = config.extrapolateRight || config.extrapolate || 'extend';

  var easing = config.easing || function (t) {
    return t;
  };

  return function (input) {
    var range = findRange(input, inputRange);
    return interpolate(input, inputRange[range], inputRange[range + 1], outputRange[range], outputRange[range + 1], easing, extrapolateLeft, extrapolateRight, config.map);
  };
}

function interpolate(input, inputMin, inputMax, outputMin, outputMax, easing, extrapolateLeft, extrapolateRight, map) {
  var result = map ? map(input) : input; // Extrapolate

  if (result < inputMin) {
    if (extrapolateLeft === 'identity') return result;else if (extrapolateLeft === 'clamp') result = inputMin;
  }

  if (result > inputMax) {
    if (extrapolateRight === 'identity') return result;else if (extrapolateRight === 'clamp') result = inputMax;
  }

  if (outputMin === outputMax) return outputMin;
  if (inputMin === inputMax) return input <= inputMin ? outputMin : outputMax; // Input Range

  if (inputMin === -Infinity) result = -result;else if (inputMax === Infinity) result = result - inputMin;else result = (result - inputMin) / (inputMax - inputMin); // Easing

  result = easing(result); // Output Range

  if (outputMin === -Infinity) result = -result;else if (outputMax === Infinity) result = result + outputMin;else result = result * (outputMax - outputMin) + outputMin;
  return result;
}

function findRange(input, inputRange) {
  for (var i = 1; i < inputRange.length - 1; ++i) {
    if (inputRange[i] >= input) break;
  }

  return i - 1;
}

var AnimatedInterpolation = /*#__PURE__*/function (_AnimatedArray) {
  _inherits$1(AnimatedInterpolation, _AnimatedArray);

  var _super4 = _createSuper$1(AnimatedInterpolation);

  function AnimatedInterpolation(parents, range, output, extrapolate) {
    var _this5;

    _classCallCheck$1(this, AnimatedInterpolation);

    _this5 = _super4.call(this);
    _this5.calc = void 0;
    _this5.payload = parents instanceof AnimatedArray && !(parents instanceof AnimatedInterpolation) ? parents.getPayload() : Array.isArray(parents) ? parents : [parents];
    _this5.calc = createInterpolator(range, output, extrapolate);
    return _this5;
  }

  _createClass(AnimatedInterpolation, [{
    key: "getValue",
    value: function getValue() {
      return this.calc.apply(this, _toConsumableArray(this.payload.map(function (value) {
        return value.getValue();
      })));
    }
  }, {
    key: "updateConfig",
    value: function updateConfig(range, output, extrapolate) {
      this.calc = createInterpolator(range, output, extrapolate);
    }
  }, {
    key: "interpolate",
    value: function interpolate(range, output, extrapolate) {
      return new AnimatedInterpolation(this, range, output, extrapolate);
    }
  }]);

  return AnimatedInterpolation;
}(AnimatedArray);
/**
 * Animated works by building a directed acyclic graph of dependencies
 * transparently when you render your Animated components.
 *
 *               new Animated.Value(0)
 *     .interpolate()        .interpolate()    new Animated.Value(1)
 *         opacity               translateY      scale
 *          style                         transform
 *         View#234                         style
 *                                         View#123
 *
 * A) Top Down phase
 * When an AnimatedValue is updated, we recursively go down through this
 * graph in order to find leaf nodes: the views that we flag as needing
 * an update.
 *
 * B) Bottom Up phase
 * When a view is flagged as needing an update, we recursively go back up
 * in order to build the new value that it needs. The reason why we need
 * this two-phases process is to deal with composite props such as
 * transform which can receive values from multiple parents.
 */


function addAnimatedStyles(node, styles) {
  if ('update' in node) {
    styles.add(node);
  } else {
    node.getChildren().forEach(function (child) {
      return addAnimatedStyles(child, styles);
    });
  }
}

var AnimatedValue = /*#__PURE__*/function (_Animated3) {
  _inherits$1(AnimatedValue, _Animated3);

  var _super5 = _createSuper$1(AnimatedValue);

  function AnimatedValue(_value) {
    var _this6;

    _classCallCheck$1(this, AnimatedValue);

    var _this;

    _this6 = _super5.call(this);
    _this = _assertThisInitialized(_this6);
    _this6.animatedStyles = new Set();
    _this6.value = void 0;
    _this6.startPosition = void 0;
    _this6.lastPosition = void 0;
    _this6.lastVelocity = void 0;
    _this6.startTime = void 0;
    _this6.lastTime = void 0;
    _this6.done = false;

    _this6.setValue = function (value, flush) {
      if (flush === void 0) {
        flush = true;
      }

      _this.value = value;
      if (flush) _this.flush();
    };

    _this6.value = _value;
    _this6.startPosition = _value;
    _this6.lastPosition = _value;
    return _this6;
  }

  _createClass(AnimatedValue, [{
    key: "flush",
    value: function flush() {
      if (this.animatedStyles.size === 0) {
        addAnimatedStyles(this, this.animatedStyles);
      }

      this.animatedStyles.forEach(function (animatedStyle) {
        return animatedStyle.update();
      });
    }
  }, {
    key: "clearStyles",
    value: function clearStyles() {
      this.animatedStyles.clear();
    }
  }, {
    key: "getValue",
    value: function getValue() {
      return this.value;
    }
  }, {
    key: "interpolate",
    value: function interpolate(range, output, extrapolate) {
      return new AnimatedInterpolation(this, range, output, extrapolate);
    }
  }]);

  return AnimatedValue;
}(Animated);

var AnimatedValueArray = /*#__PURE__*/function (_AnimatedArray2) {
  _inherits$1(AnimatedValueArray, _AnimatedArray2);

  var _super6 = _createSuper$1(AnimatedValueArray);

  function AnimatedValueArray(values) {
    var _this7;

    _classCallCheck$1(this, AnimatedValueArray);

    _this7 = _super6.call(this);
    _this7.payload = values.map(function (n) {
      return new AnimatedValue(n);
    });
    return _this7;
  }

  _createClass(AnimatedValueArray, [{
    key: "setValue",
    value: function setValue(value, flush) {
      var _this8 = this;

      if (flush === void 0) {
        flush = true;
      }

      if (Array.isArray(value)) {
        if (value.length === this.payload.length) {
          value.forEach(function (v, i) {
            return _this8.payload[i].setValue(v, flush);
          });
        }
      } else {
        this.payload.forEach(function (p) {
          return p.setValue(value, flush);
        });
      }
    }
  }, {
    key: "getValue",
    value: function getValue() {
      return this.payload.map(function (v) {
        return v.getValue();
      });
    }
  }, {
    key: "interpolate",
    value: function interpolate(range, output) {
      return new AnimatedInterpolation(this, range, output);
    }
  }]);

  return AnimatedValueArray;
}(AnimatedArray);

var G = 0;

var Controller = /*#__PURE__*/function () {
  function Controller() {
    var _this9 = this;

    _classCallCheck$1(this, Controller);

    this.id = void 0;
    this.idle = true;
    this.hasChanged = false;
    this.guid = 0;
    this.local = 0;
    this.props = {};
    this.merged = {};
    this.animations = {};
    this.interpolations = {};
    this.values = {};
    this.configs = [];
    this.listeners = [];
    this.queue = [];
    this.localQueue = void 0;

    this.getValues = function () {
      return _this9.interpolations;
    };

    this.id = G++;
  }
  /** update(props)
   *  This function filters input props and creates an array of tasks which are executed in .start()
   *  Each task is allowed to carry a delay, which means it can execute asnychroneously */


  _createClass(Controller, [{
    key: "update",
    value: function update(args) {
      //this._id = n + this.id
      if (!args) return this; // Extract delay and the to-prop from props

      var _ref = interpolateTo(args),
          _ref$delay = _ref.delay,
          delay = _ref$delay === void 0 ? 0 : _ref$delay,
          to = _ref.to,
          props = _objectWithoutPropertiesLoose(_ref, ["delay", "to"]);

      if (is.arr(to) || is.fun(to)) {
        // If config is either a function or an array queue it up as is
        this.queue.push(_extends$1({}, props, {
          delay: delay,
          to: to
        }));
      } else if (to) {
        // Otherwise go through each key since it could be delayed individually
        var ops = {};
        Object.entries(to).forEach(function (_ref2) {
          var k = _ref2[0],
              v = _ref2[1]; // Fetch delay and create an entry, consisting of the to-props, the delay, and basic props

          var entry = _extends$1({
            to: _defineProperty({}, k, v),
            delay: callProp(delay, k)
          }, props);

          var previous = ops[entry.delay] && ops[entry.delay].to;
          ops[entry.delay] = _extends$1({}, ops[entry.delay], entry, {
            to: _extends$1({}, previous, entry.to)
          });
        });
        this.queue = Object.values(ops);
      } // Sort queue, so that async calls go last


      this.queue = this.queue.sort(function (a, b) {
        return a.delay - b.delay;
      }); // Diff the reduced props immediately (they'll contain the from-prop and some config)

      this.diff(props);
      return this;
    }
    /** start(onEnd)
     *  This function either executes a queue, if present, or starts the frameloop, which animates */

  }, {
    key: "start",
    value: function start(onEnd) {
      var _this10 = this;

      // If a queue is present we must excecute it
      if (this.queue.length) {
        this.idle = false; // Updates can interrupt trailing queues, in that case we just merge values

        if (this.localQueue) {
          this.localQueue.forEach(function (_ref3) {
            var _ref3$from = _ref3.from,
                from = _ref3$from === void 0 ? {} : _ref3$from,
                _ref3$to = _ref3.to,
                to = _ref3$to === void 0 ? {} : _ref3$to;
            if (is.obj(from)) _this10.merged = _extends$1({}, from, _this10.merged);
            if (is.obj(to)) _this10.merged = _extends$1({}, _this10.merged, to);
          });
        } // The guid helps us tracking frames, a new queue over an old one means an override
        // We discard async calls in that caseÍ


        var local = this.local = ++this.guid;
        var queue = this.localQueue = this.queue;
        this.queue = []; // Go through each entry and execute it

        queue.forEach(function (_ref4, index) {
          var delay = _ref4.delay,
              props = _objectWithoutPropertiesLoose(_ref4, ["delay"]);

          var cb = function cb(finished) {
            if (index === queue.length - 1 && local === _this10.guid && finished) {
              _this10.idle = true;
              if (_this10.props.onRest) _this10.props.onRest(_this10.merged);
            }

            if (onEnd) onEnd();
          }; // Entries can be delayed, ansyc or immediate


          var async = is.arr(props.to) || is.fun(props.to);

          if (delay) {
            setTimeout(function () {
              if (local === _this10.guid) {
                if (async) _this10.runAsync(props, cb);else _this10.diff(props).start(cb);
              }
            }, delay);
          } else if (async) _this10.runAsync(props, cb);else _this10.diff(props).start(cb);
        });
      } // Otherwise we kick of the frameloop
      else {
          if (is.fun(onEnd)) this.listeners.push(onEnd);
          if (this.props.onStart) this.props.onStart();

          _start(this);
        }

      return this;
    }
  }, {
    key: "stop",
    value: function stop(finished) {
      this.listeners.forEach(function (onEnd) {
        return onEnd(finished);
      });
      this.listeners = [];
      return this;
    }
    /** Pause sets onEnd listeners free, but also removes the controller from the frameloop */

  }, {
    key: "pause",
    value: function pause(finished) {
      this.stop(true);
      if (finished) stop(this);
      return this;
    }
  }, {
    key: "runAsync",
    value: function runAsync(_ref5, onEnd) {
      var _this11 = this;

      var _this = this;

      _ref5.delay;
          var props = _objectWithoutPropertiesLoose(_ref5, ["delay"]);

      var local = this.local; // If "to" is either a function or an array it will be processed async, therefor "to" should be empty right now
      // If the view relies on certain values "from" has to be present

      var queue = Promise.resolve(undefined);

      if (is.arr(props.to)) {
        var _loop = function _loop(i) {
          var index = i;

          var fresh = _extends$1({}, props, interpolateTo(props.to[index]));

          if (is.arr(fresh.config)) fresh.config = fresh.config[index];
          queue = queue.then(function () {
            //this.stop()
            if (local === _this11.guid) return new Promise(function (r) {
              return _this11.diff(fresh).start(r);
            });
          });
        };

        for (var i = 0; i < props.to.length; i++) {
          _loop(i);
        }
      } else if (is.fun(props.to)) {
        var index = 0;
        var last;
        queue = queue.then(function () {
          return props.to( // next(props)
          function (p) {
            var fresh = _extends$1({}, props, interpolateTo(p));

            if (is.arr(fresh.config)) fresh.config = fresh.config[index];
            index++; //this.stop()

            if (local === _this11.guid) return last = new Promise(function (r) {
              return _this11.diff(fresh).start(r);
            });
            return;
          }, // cancel()
          function (finished) {
            if (finished === void 0) {
              finished = true;
            }

            return _this.stop(finished);
          }).then(function () {
            return last;
          });
        });
      }

      queue.then(onEnd);
    }
  }, {
    key: "diff",
    value: function diff(props) {
      var _this12 = this;

      this.props = _extends$1({}, this.props, props);
      var _this$props = this.props,
          _this$props$from = _this$props.from,
          from = _this$props$from === void 0 ? {} : _this$props$from,
          _this$props$to = _this$props.to,
          to = _this$props$to === void 0 ? {} : _this$props$to,
          _this$props$config = _this$props.config,
          config = _this$props$config === void 0 ? {} : _this$props$config,
          reverse = _this$props.reverse,
          attach = _this$props.attach,
          reset = _this$props.reset,
          immediate = _this$props.immediate; // Reverse values when requested

      if (reverse) {
        var _ref6 = [to, from];
        from = _ref6[0];
        to = _ref6[1];
      } // This will collect all props that were ever set, reset merged props when necessary


      this.merged = _extends$1({}, from, this.merged, to);
      this.hasChanged = false; // Attachment handling, trailed springs can "attach" themselves to a previous spring

      var target = attach && attach(this); // Reduces input { name: value } pairs into animated values

      this.animations = Object.entries(this.merged).reduce(function (acc, _ref7) {
        var name = _ref7[0],
            value = _ref7[1]; // Issue cached entries, except on reset

        var entry = acc[name] || {}; // Figure out what the value is supposed to be

        var isNumber = is.num(value);
        var isString = is.str(value) && !value.startsWith('#') && !/\d/.test(value) && !colorNames[value];
        var isArray = is.arr(value);
        var isInterpolation = !isNumber && !isArray && !isString;
        var fromValue = !is.und(from[name]) ? from[name] : value;
        var toValue = isNumber || isArray ? value : isString ? value : 1;
        var toConfig = callProp(config, name);
        if (target) toValue = target.animations[name].parent;
        var parent = entry.parent,
            interpolation$$1 = entry.interpolation,
            toValues = toArray(target ? toValue.getPayload() : toValue),
            animatedValues;
        var newValue = value;
        if (isInterpolation) newValue = interpolation({
          range: [0, 1],
          output: [value, value]
        })(1);
        var currentValue = interpolation$$1 && interpolation$$1.getValue(); // Change detection flags

        var isFirst = is.und(parent);
        var isActive = !isFirst && entry.animatedValues.some(function (v) {
          return !v.done;
        });
        var currentValueDiffersFromGoal = !is.equ(newValue, currentValue);
        var hasNewGoal = !is.equ(newValue, entry.previous);
        var hasNewConfig = !is.equ(toConfig, entry.config); // Change animation props when props indicate a new goal (new value differs from previous one)
        // and current values differ from it. Config changes trigger a new update as well (though probably shouldn't?)

        if (reset || hasNewGoal && currentValueDiffersFromGoal || hasNewConfig) {
          // Convert regular values into animated values, ALWAYS re-use if possible
          if (isNumber || isString) parent = interpolation$$1 = entry.parent || new AnimatedValue(fromValue);else if (isArray) parent = interpolation$$1 = entry.parent || new AnimatedValueArray(fromValue);else if (isInterpolation) {
            var prev = entry.interpolation && entry.interpolation.calc(entry.parent.value);
            prev = prev !== void 0 && !reset ? prev : fromValue;

            if (entry.parent) {
              parent = entry.parent;
              parent.setValue(0, false);
            } else parent = new AnimatedValue(0);

            var range = {
              output: [prev, value]
            };

            if (entry.interpolation) {
              interpolation$$1 = entry.interpolation;
              entry.interpolation.updateConfig(range);
            } else interpolation$$1 = parent.interpolate(range);
          }
          toValues = toArray(target ? toValue.getPayload() : toValue);
          animatedValues = toArray(parent.getPayload());
          if (reset && !isInterpolation) parent.setValue(fromValue, false);
          _this12.hasChanged = true; // Reset animated values

          animatedValues.forEach(function (value) {
            value.startPosition = value.value;
            value.lastPosition = value.value;
            value.lastVelocity = isActive ? value.lastVelocity : undefined;
            value.lastTime = isActive ? value.lastTime : undefined;
            value.startTime = now();
            value.done = false;
            value.animatedStyles.clear();
          }); // Set immediate values

          if (callProp(immediate, name)) {
            parent.setValue(isInterpolation ? toValue : value, false);
          }

          return _extends$1({}, acc, _defineProperty({}, name, _extends$1({}, entry, {
            name: name,
            parent: parent,
            interpolation: interpolation$$1,
            animatedValues: animatedValues,
            toValues: toValues,
            previous: newValue,
            config: toConfig,
            fromValues: toArray(parent.getValue()),
            immediate: callProp(immediate, name),
            initialVelocity: withDefault(toConfig.velocity, 0),
            clamp: withDefault(toConfig.clamp, false),
            precision: withDefault(toConfig.precision, 0.01),
            tension: withDefault(toConfig.tension, 170),
            friction: withDefault(toConfig.friction, 26),
            mass: withDefault(toConfig.mass, 1),
            duration: toConfig.duration,
            easing: withDefault(toConfig.easing, function (t) {
              return t;
            }),
            decay: toConfig.decay
          })));
        } else {
          if (!currentValueDiffersFromGoal) {
            // So ... the current target value (newValue) appears to be different from the previous value,
            // which normally constitutes an update, but the actual value (currentValue) matches the target!
            // In order to resolve this without causing an animation update we silently flag the animation as done,
            // which it technically is. Interpolations also needs a config update with their target set to 1.
            if (isInterpolation) {
              parent.setValue(1, false);
              interpolation$$1.updateConfig({
                output: [newValue, newValue]
              });
            }

            parent.done = true;
            _this12.hasChanged = true;
            return _extends$1({}, acc, _defineProperty({}, name, _extends$1({}, acc[name], {
              previous: newValue
            })));
          }

          return acc;
        }
      }, this.animations);

      if (this.hasChanged) {
        // Make animations available to frameloop
        this.configs = Object.values(this.animations);
        this.values = {};
        this.interpolations = {};

        for (var key in this.animations) {
          this.interpolations[key] = this.animations[key].interpolation;
          this.values[key] = this.animations[key].interpolation.getValue();
        }
      }

      return this;
    }
  }, {
    key: "destroy",
    value: function destroy() {
      this.stop();
      this.props = {};
      this.merged = {};
      this.animations = {};
      this.interpolations = {};
      this.values = {};
      this.configs = [];
      this.local = 0;
    }
  }]);

  return Controller;
}();
/** API
 * const transitions = useTransition(items, itemKeys, { ... })
 * const [transitions, update] = useTransition(items, itemKeys, () => ({ ... }))
 */


var guid = 0;
var ENTER = 'enter';
var LEAVE = 'leave';
var UPDATE = 'update';

var mapKeys = function mapKeys(items, keys) {
  return (typeof keys === 'function' ? items.map(keys) : toArray(keys)).map(String);
};

var get = function get(props) {
  var items = props.items,
      _props$keys = props.keys,
      keys = _props$keys === void 0 ? function (item) {
    return item;
  } : _props$keys,
      rest = _objectWithoutPropertiesLoose(props, ["items", "keys"]);

  items = toArray(items !== void 0 ? items : null);
  return _extends$1({
    items: items,
    keys: mapKeys(items, keys)
  }, rest);
};

function useTransition(input, keyTransform, config) {
  var props = _extends$1({
    items: input,
    keys: function (i) {
      return i;
    }
  }, config);

  var _get = get(props),
      _get$lazy = _get.lazy,
      lazy = _get$lazy === void 0 ? false : _get$lazy;
      _get.unique;
      var _get$reset = _get.reset,
      reset = _get$reset === void 0 ? false : _get$reset;
      _get.enter;
      _get.leave;
      _get.update;
      var onDestroyed = _get.onDestroyed;
      _get.keys;
      _get.items;
      var onFrame = _get.onFrame,
      _onRest = _get.onRest,
      onStart = _get.onStart,
      ref = _get.ref,
      extra = _objectWithoutPropertiesLoose(_get, ["lazy", "unique", "reset", "enter", "leave", "update", "onDestroyed", "keys", "items", "onFrame", "onRest", "onStart", "ref"]);

  var forceUpdate = useForceUpdate();
  var mounted = useRef(false);
  var state = useRef({
    mounted: false,
    first: true,
    deleted: [],
    current: {},
    transitions: [],
    prevProps: {},
    paused: !!props.ref,
    instances: !mounted.current && new Map(),
    forceUpdate: forceUpdate
  });
  useImperativeHandle(props.ref, function () {
    return {
      start: function start() {
        return Promise.all(Array.from(state.current.instances).map(function (_ref) {
          var c = _ref[1];
          return new Promise(function (r) {
            return c.start(r);
          });
        }));
      },
      stop: function stop(finished) {
        return Array.from(state.current.instances).forEach(function (_ref2) {
          var c = _ref2[1];
          return c.stop(finished);
        });
      },

      get controllers() {
        return Array.from(state.current.instances).map(function (_ref3) {
          var c = _ref3[1];
          return c;
        });
      }

    };
  }); // Update state

  state.current = diffItems(state.current, props);

  if (state.current.changed) {
    // Update state
    state.current.transitions.forEach(function (transition) {
      var slot = transition.slot,
          from = transition.from,
          to = transition.to,
          config = transition.config,
          trail = transition.trail,
          key = transition.key,
          item = transition.item;
      if (!state.current.instances.has(key)) state.current.instances.set(key, new Controller()); // update the map object

      var ctrl = state.current.instances.get(key);

      var newProps = _extends$1({}, extra, {
        to: to,
        from: from,
        config: config,
        ref: ref,
        onRest: function onRest(values) {
          if (state.current.mounted) {
            if (transition.destroyed) {
              // If no ref is given delete destroyed items immediately
              if (!ref && !lazy) cleanUp(state, key);
              if (onDestroyed) onDestroyed(item);
            } // A transition comes to rest once all its springs conclude


            var curInstances = Array.from(state.current.instances);

            var _active = curInstances.some(function (_ref4) {
              var c = _ref4[1];
              return !c.idle;
            });

            if (!_active && (ref || lazy) && state.current.deleted.length > 0) cleanUp(state);
            if (_onRest) _onRest(item, slot, values);
          }
        },
        onStart: onStart && function () {
          return onStart(item, slot);
        },
        onFrame: onFrame && function (values) {
          return onFrame(item, slot, values);
        },
        delay: trail,
        reset: reset && slot === ENTER // Update controller

      });

      ctrl.update(newProps);
      if (!state.current.paused) ctrl.start();
    });
  }

  useEffect(function () {
    state.current.mounted = mounted.current = true;
    return function () {
      state.current.mounted = mounted.current = false;
      Array.from(state.current.instances).map(function (_ref5) {
        var c = _ref5[1];
        return c.destroy();
      });
      state.current.instances.clear();
    };
  }, []);
  return state.current.transitions.map(function (_ref6) {
    var item = _ref6.item,
        slot = _ref6.slot,
        key = _ref6.key;
    return {
      item: item,
      key: key,
      state: slot,
      props: state.current.instances.get(key).getValues()
    };
  });
}

function cleanUp(state, filterKey) {
  var deleted = state.current.deleted;

  var _iterator2 = _createForOfIteratorHelper(deleted),
      _step2;

  try {
    var _loop2 = function _loop2() {
      var _ref7 = _step2.value;
      var key = _ref7.key;

      var filter = function filter(t) {
        return t.key !== key;
      };

      if (is.und(filterKey) || filterKey === key) {
        state.current.instances["delete"](key);
        state.current.transitions = state.current.transitions.filter(filter);
        state.current.deleted = state.current.deleted.filter(filter);
      }
    };

    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      _loop2();
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }

  state.current.forceUpdate();
}

function diffItems(_ref8, props) {
  var first = _ref8.first,
      prevProps = _ref8.prevProps,
      state = _objectWithoutPropertiesLoose(_ref8, ["first", "prevProps"]);

  var _get2 = get(props),
      items = _get2.items,
      keys = _get2.keys,
      initial = _get2.initial,
      from = _get2.from,
      enter = _get2.enter,
      leave = _get2.leave,
      update = _get2.update,
      _get2$trail = _get2.trail,
      trail = _get2$trail === void 0 ? 0 : _get2$trail,
      unique = _get2.unique,
      config = _get2.config,
      _get2$order = _get2.order,
      order = _get2$order === void 0 ? [ENTER, LEAVE, UPDATE] : _get2$order;

  var _get3 = get(prevProps),
      _keys = _get3.keys,
      _items = _get3.items;

  var current = _extends$1({}, state.current);

  var deleted = _toConsumableArray(state.deleted); // Compare next keys with current keys


  var currentKeys = Object.keys(current);
  var currentSet = new Set(currentKeys);
  var nextSet = new Set(keys);
  var added = keys.filter(function (item) {
    return !currentSet.has(item);
  });
  var removed = state.transitions.filter(function (item) {
    return !item.destroyed && !nextSet.has(item.originalKey);
  }).map(function (i) {
    return i.originalKey;
  });
  var updated = keys.filter(function (item) {
    return currentSet.has(item);
  });
  var delay = -trail;

  while (order.length) {
    var changeType = order.shift();

    switch (changeType) {
      case ENTER:
        {
          added.forEach(function (key, index) {
            // In unique mode, remove fading out transitions if their key comes in again
            if (unique && deleted.find(function (d) {
              return d.originalKey === key;
            })) deleted = deleted.filter(function (t) {
              return t.originalKey !== key;
            });
            var keyIndex = keys.indexOf(key);
            var item = items[keyIndex];
            var slot = first && initial !== void 0 ? 'initial' : ENTER;
            current[key] = {
              slot: slot,
              originalKey: key,
              key: unique ? String(key) : guid++,
              item: item,
              trail: delay = delay + trail,
              config: callProp(config, item, slot),
              from: callProp(first ? initial !== void 0 ? initial || {} : from : from, item),
              to: callProp(enter, item)
            };
          });
          break;
        }

      case LEAVE:
        {
          removed.forEach(function (key) {
            var keyIndex = _keys.indexOf(key);

            var item = _items[keyIndex];
            var slot = LEAVE;
            deleted.unshift(_extends$1({}, current[key], {
              slot: slot,
              destroyed: true,
              left: _keys[Math.max(0, keyIndex - 1)],
              right: _keys[Math.min(_keys.length, keyIndex + 1)],
              trail: delay = delay + trail,
              config: callProp(config, item, slot),
              to: callProp(leave, item)
            }));
            delete current[key];
          });
          break;
        }

      case UPDATE:
        {
          updated.forEach(function (key) {
            var keyIndex = keys.indexOf(key);
            var item = items[keyIndex];
            var slot = UPDATE;
            current[key] = _extends$1({}, current[key], {
              item: item,
              slot: slot,
              trail: delay = delay + trail,
              config: callProp(config, item, slot),
              to: callProp(update, item)
            });
          });
          break;
        }
    }
  }

  var out = keys.map(function (key) {
    return current[key];
  }); // This tries to restore order for deleted items by finding their last known siblings
  // only using the left sibling to keep order placement consistent for all deleted items

  deleted.forEach(function (_ref9) {
    var left = _ref9.left;
        _ref9.right;
        var item = _objectWithoutPropertiesLoose(_ref9, ["left", "right"]);

    var pos; // Was it the element on the left, if yes, move there ...

    if ((pos = out.findIndex(function (t) {
      return t.originalKey === left;
    })) !== -1) pos += 1; // And if nothing else helps, move it to the start ¯\_(ツ)_/¯

    pos = Math.max(0, pos);
    out = [].concat(_toConsumableArray(out.slice(0, pos)), [item], _toConsumableArray(out.slice(pos)));
  });
  return _extends$1({}, state, {
    changed: added.length || removed.length || updated.length,
    first: first && added.length === 0,
    transitions: out,
    current: current,
    deleted: deleted,
    prevProps: props
  });
}

var AnimatedStyle = /*#__PURE__*/function (_AnimatedObject2) {
  _inherits$1(AnimatedStyle, _AnimatedObject2);

  var _super7 = _createSuper$1(AnimatedStyle);

  function AnimatedStyle(style) {
    var _this13;

    _classCallCheck$1(this, AnimatedStyle);

    if (style === void 0) {
      style = {};
    }

    _this13 = _super7.call(this);

    if (style.transform && !(style.transform instanceof Animated)) {
      style = applyAnimatedValues.transform(style);
    }

    _this13.payload = style;
    return _this13;
  }

  return AnimatedStyle;
}(AnimatedObject); // http://www.w3.org/TR/css3-color/#svg-color


var colors = {
  transparent: 0x00000000,
  aliceblue: 0xf0f8ffff,
  antiquewhite: 0xfaebd7ff,
  aqua: 0x00ffffff,
  aquamarine: 0x7fffd4ff,
  azure: 0xf0ffffff,
  beige: 0xf5f5dcff,
  bisque: 0xffe4c4ff,
  black: 0x000000ff,
  blanchedalmond: 0xffebcdff,
  blue: 0x0000ffff,
  blueviolet: 0x8a2be2ff,
  brown: 0xa52a2aff,
  burlywood: 0xdeb887ff,
  burntsienna: 0xea7e5dff,
  cadetblue: 0x5f9ea0ff,
  chartreuse: 0x7fff00ff,
  chocolate: 0xd2691eff,
  coral: 0xff7f50ff,
  cornflowerblue: 0x6495edff,
  cornsilk: 0xfff8dcff,
  crimson: 0xdc143cff,
  cyan: 0x00ffffff,
  darkblue: 0x00008bff,
  darkcyan: 0x008b8bff,
  darkgoldenrod: 0xb8860bff,
  darkgray: 0xa9a9a9ff,
  darkgreen: 0x006400ff,
  darkgrey: 0xa9a9a9ff,
  darkkhaki: 0xbdb76bff,
  darkmagenta: 0x8b008bff,
  darkolivegreen: 0x556b2fff,
  darkorange: 0xff8c00ff,
  darkorchid: 0x9932ccff,
  darkred: 0x8b0000ff,
  darksalmon: 0xe9967aff,
  darkseagreen: 0x8fbc8fff,
  darkslateblue: 0x483d8bff,
  darkslategray: 0x2f4f4fff,
  darkslategrey: 0x2f4f4fff,
  darkturquoise: 0x00ced1ff,
  darkviolet: 0x9400d3ff,
  deeppink: 0xff1493ff,
  deepskyblue: 0x00bfffff,
  dimgray: 0x696969ff,
  dimgrey: 0x696969ff,
  dodgerblue: 0x1e90ffff,
  firebrick: 0xb22222ff,
  floralwhite: 0xfffaf0ff,
  forestgreen: 0x228b22ff,
  fuchsia: 0xff00ffff,
  gainsboro: 0xdcdcdcff,
  ghostwhite: 0xf8f8ffff,
  gold: 0xffd700ff,
  goldenrod: 0xdaa520ff,
  gray: 0x808080ff,
  green: 0x008000ff,
  greenyellow: 0xadff2fff,
  grey: 0x808080ff,
  honeydew: 0xf0fff0ff,
  hotpink: 0xff69b4ff,
  indianred: 0xcd5c5cff,
  indigo: 0x4b0082ff,
  ivory: 0xfffff0ff,
  khaki: 0xf0e68cff,
  lavender: 0xe6e6faff,
  lavenderblush: 0xfff0f5ff,
  lawngreen: 0x7cfc00ff,
  lemonchiffon: 0xfffacdff,
  lightblue: 0xadd8e6ff,
  lightcoral: 0xf08080ff,
  lightcyan: 0xe0ffffff,
  lightgoldenrodyellow: 0xfafad2ff,
  lightgray: 0xd3d3d3ff,
  lightgreen: 0x90ee90ff,
  lightgrey: 0xd3d3d3ff,
  lightpink: 0xffb6c1ff,
  lightsalmon: 0xffa07aff,
  lightseagreen: 0x20b2aaff,
  lightskyblue: 0x87cefaff,
  lightslategray: 0x778899ff,
  lightslategrey: 0x778899ff,
  lightsteelblue: 0xb0c4deff,
  lightyellow: 0xffffe0ff,
  lime: 0x00ff00ff,
  limegreen: 0x32cd32ff,
  linen: 0xfaf0e6ff,
  magenta: 0xff00ffff,
  maroon: 0x800000ff,
  mediumaquamarine: 0x66cdaaff,
  mediumblue: 0x0000cdff,
  mediumorchid: 0xba55d3ff,
  mediumpurple: 0x9370dbff,
  mediumseagreen: 0x3cb371ff,
  mediumslateblue: 0x7b68eeff,
  mediumspringgreen: 0x00fa9aff,
  mediumturquoise: 0x48d1ccff,
  mediumvioletred: 0xc71585ff,
  midnightblue: 0x191970ff,
  mintcream: 0xf5fffaff,
  mistyrose: 0xffe4e1ff,
  moccasin: 0xffe4b5ff,
  navajowhite: 0xffdeadff,
  navy: 0x000080ff,
  oldlace: 0xfdf5e6ff,
  olive: 0x808000ff,
  olivedrab: 0x6b8e23ff,
  orange: 0xffa500ff,
  orangered: 0xff4500ff,
  orchid: 0xda70d6ff,
  palegoldenrod: 0xeee8aaff,
  palegreen: 0x98fb98ff,
  paleturquoise: 0xafeeeeff,
  palevioletred: 0xdb7093ff,
  papayawhip: 0xffefd5ff,
  peachpuff: 0xffdab9ff,
  peru: 0xcd853fff,
  pink: 0xffc0cbff,
  plum: 0xdda0ddff,
  powderblue: 0xb0e0e6ff,
  purple: 0x800080ff,
  rebeccapurple: 0x663399ff,
  red: 0xff0000ff,
  rosybrown: 0xbc8f8fff,
  royalblue: 0x4169e1ff,
  saddlebrown: 0x8b4513ff,
  salmon: 0xfa8072ff,
  sandybrown: 0xf4a460ff,
  seagreen: 0x2e8b57ff,
  seashell: 0xfff5eeff,
  sienna: 0xa0522dff,
  silver: 0xc0c0c0ff,
  skyblue: 0x87ceebff,
  slateblue: 0x6a5acdff,
  slategray: 0x708090ff,
  slategrey: 0x708090ff,
  snow: 0xfffafaff,
  springgreen: 0x00ff7fff,
  steelblue: 0x4682b4ff,
  tan: 0xd2b48cff,
  teal: 0x008080ff,
  thistle: 0xd8bfd8ff,
  tomato: 0xff6347ff,
  turquoise: 0x40e0d0ff,
  violet: 0xee82eeff,
  wheat: 0xf5deb3ff,
  white: 0xffffffff,
  whitesmoke: 0xf5f5f5ff,
  yellow: 0xffff00ff,
  yellowgreen: 0x9acd32ff
}; // const INTEGER = '[-+]?\\d+';

var NUMBER = '[-+]?\\d*\\.?\\d+';
var PERCENTAGE = NUMBER + '%';

function call() {
  for (var _len = arguments.length, parts = new Array(_len), _key = 0; _key < _len; _key++) {
    parts[_key] = arguments[_key];
  }

  return '\\(\\s*(' + parts.join(')\\s*,\\s*(') + ')\\s*\\)';
}

var rgb = new RegExp('rgb' + call(NUMBER, NUMBER, NUMBER));
var rgba = new RegExp('rgba' + call(NUMBER, NUMBER, NUMBER, NUMBER));
var hsl = new RegExp('hsl' + call(NUMBER, PERCENTAGE, PERCENTAGE));
var hsla = new RegExp('hsla' + call(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER));
var hex3 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
var hex4 = /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/;
var hex6 = /^#([0-9a-fA-F]{6})$/;
var hex8 = /^#([0-9a-fA-F]{8})$/;
/*
https://github.com/react-community/normalize-css-color

BSD 3-Clause License

Copyright (c) 2016, React Community
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

function normalizeColor(color) {
  var match;

  if (typeof color === 'number') {
    return color >>> 0 === color && color >= 0 && color <= 0xffffffff ? color : null;
  } // Ordered based on occurrences on Facebook codebase


  if (match = hex6.exec(color)) return parseInt(match[1] + 'ff', 16) >>> 0;
  if (colors.hasOwnProperty(color)) return colors[color];

  if (match = rgb.exec(color)) {
    return (parse255(match[1]) << 24 | // r
    parse255(match[2]) << 16 | // g
    parse255(match[3]) << 8 | // b
    0x000000ff) >>> // a
    0;
  }

  if (match = rgba.exec(color)) {
    return (parse255(match[1]) << 24 | // r
    parse255(match[2]) << 16 | // g
    parse255(match[3]) << 8 | // b
    parse1(match[4])) >>> // a
    0;
  }

  if (match = hex3.exec(color)) {
    return parseInt(match[1] + match[1] + // r
    match[2] + match[2] + // g
    match[3] + match[3] + // b
    'ff', // a
    16) >>> 0;
  } // https://drafts.csswg.org/css-color-4/#hex-notation


  if (match = hex8.exec(color)) return parseInt(match[1], 16) >>> 0;

  if (match = hex4.exec(color)) {
    return parseInt(match[1] + match[1] + // r
    match[2] + match[2] + // g
    match[3] + match[3] + // b
    match[4] + match[4], // a
    16) >>> 0;
  }

  if (match = hsl.exec(color)) {
    return (hslToRgb(parse360(match[1]), // h
    parsePercentage(match[2]), // s
    parsePercentage(match[3]) // l
    ) | 0x000000ff) >>> // a
    0;
  }

  if (match = hsla.exec(color)) {
    return (hslToRgb(parse360(match[1]), // h
    parsePercentage(match[2]), // s
    parsePercentage(match[3]) // l
    ) | parse1(match[4])) >>> // a
    0;
  }

  return null;
}

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) * (2 / 3 - t) * 6;
  return p;
}

function hslToRgb(h, s, l) {
  var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  var p = 2 * l - q;
  var r = hue2rgb(p, q, h + 1 / 3);
  var g = hue2rgb(p, q, h);
  var b = hue2rgb(p, q, h - 1 / 3);
  return Math.round(r * 255) << 24 | Math.round(g * 255) << 16 | Math.round(b * 255) << 8;
}

function parse255(str) {
  var _int = parseInt(str, 10);

  if (_int < 0) return 0;
  if (_int > 255) return 255;
  return _int;
}

function parse360(str) {
  var _int2 = parseFloat(str);

  return (_int2 % 360 + 360) % 360 / 360;
}

function parse1(str) {
  var num = parseFloat(str);
  if (num < 0) return 0;
  if (num > 1) return 255;
  return Math.round(num * 255);
}

function parsePercentage(str) {
  // parseFloat conveniently ignores the final %
  var _int3 = parseFloat(str);

  if (_int3 < 0) return 0;
  if (_int3 > 100) return 1;
  return _int3 / 100;
}

function colorToRgba(input) {
  var int32Color = normalizeColor(input);
  if (int32Color === null) return input;
  int32Color = int32Color || 0;
  var r = (int32Color & 0xff000000) >>> 24;
  var g = (int32Color & 0x00ff0000) >>> 16;
  var b = (int32Color & 0x0000ff00) >>> 8;
  var a = (int32Color & 0x000000ff) / 255;
  return "rgba(".concat(r, ", ").concat(g, ", ").concat(b, ", ").concat(a, ")");
} // Problem: https://github.com/animatedjs/animated/pull/102
// Solution: https://stackoverflow.com/questions/638565/parsing-scientific-notation-sensibly/658662


var stringShapeRegex = /[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; // Covers rgb, rgba, hsl, hsla
// Taken from https://gist.github.com/olmokramer/82ccce673f86db7cda5e

var colorRegex = /(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))/gi; // Covers color names (transparent, blue, etc.)

var colorNamesRegex = new RegExp("(".concat(Object.keys(colors).join('|'), ")"), 'g');
/**
 * Supports string shapes by extracting numbers so new values can be computed,
 * and recombines those values into new strings of the same shape.  Supports
 * things like:
 *
 *   rgba(123, 42, 99, 0.36)           // colors
 *   -45deg                            // values with units
 *   0 2px 2px 0px rgba(0, 0, 0, 0.12) // box shadows
 */

var createStringInterpolator = function createStringInterpolator(config) {
  // Replace colors with rgba
  var outputRange = config.output.map(function (rangeValue) {
    return rangeValue.replace(colorRegex, colorToRgba);
  }).map(function (rangeValue) {
    return rangeValue.replace(colorNamesRegex, colorToRgba);
  });
  var outputRanges = outputRange[0].match(stringShapeRegex).map(function () {
    return [];
  });
  outputRange.forEach(function (value) {
    value.match(stringShapeRegex).forEach(function (number, i) {
      return outputRanges[i].push(+number);
    });
  });
  var interpolations = outputRange[0].match(stringShapeRegex).map(function (_value, i) {
    return createInterpolator(_extends$1({}, config, {
      output: outputRanges[i]
    }));
  });
  return function (input) {
    var i = 0;
    return outputRange[0] // 'rgba(0, 100, 200, 0)'
    // ->
    // 'rgba(${interpolations[0](input)}, ${interpolations[1](input)}, ...'
    .replace(stringShapeRegex, function () {
      return interpolations[i++](input);
    }) // rgba requires that the r,g,b are integers.... so we want to round them, but we *dont* want to
    // round the opacity (4th column).
    .replace(/rgba\(([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+), ([0-9\.-]+)\)/gi, function (_, p1, p2, p3, p4) {
      return "rgba(".concat(Math.round(p1), ", ").concat(Math.round(p2), ", ").concat(Math.round(p3), ", ").concat(p4, ")");
    });
  };
};

var isUnitlessNumber = {
  animationIterationCount: true,
  borderImageOutset: true,
  borderImageSlice: true,
  borderImageWidth: true,
  boxFlex: true,
  boxFlexGroup: true,
  boxOrdinalGroup: true,
  columnCount: true,
  columns: true,
  flex: true,
  flexGrow: true,
  flexPositive: true,
  flexShrink: true,
  flexNegative: true,
  flexOrder: true,
  gridRow: true,
  gridRowEnd: true,
  gridRowSpan: true,
  gridRowStart: true,
  gridColumn: true,
  gridColumnEnd: true,
  gridColumnSpan: true,
  gridColumnStart: true,
  fontWeight: true,
  lineClamp: true,
  lineHeight: true,
  opacity: true,
  order: true,
  orphans: true,
  tabSize: true,
  widows: true,
  zIndex: true,
  zoom: true,
  // SVG-related properties
  fillOpacity: true,
  floodOpacity: true,
  stopOpacity: true,
  strokeDasharray: true,
  strokeDashoffset: true,
  strokeMiterlimit: true,
  strokeOpacity: true,
  strokeWidth: true
};

var prefixKey = function prefixKey(prefix, key) {
  return prefix + key.charAt(0).toUpperCase() + key.substring(1);
};

var prefixes = ['Webkit', 'Ms', 'Moz', 'O'];
isUnitlessNumber = Object.keys(isUnitlessNumber).reduce(function (acc, prop) {
  prefixes.forEach(function (prefix) {
    return acc[prefixKey(prefix, prop)] = acc[prop];
  });
  return acc;
}, isUnitlessNumber);

function dangerousStyleValue(name, value, isCustomProperty) {
  if (value == null || typeof value === 'boolean' || value === '') return '';
  if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers

  return ('' + value).trim();
}

var attributeCache = {};
injectCreateAnimatedStyle(function (style) {
  return new AnimatedStyle(style);
});
injectStringInterpolator(createStringInterpolator);
injectColorNames(colors);
injectApplyAnimatedValues(function (instance, props) {
  if (instance.nodeType && instance.setAttribute !== undefined) {
    var style = props.style,
        children = props.children,
        scrollTop = props.scrollTop,
        scrollLeft = props.scrollLeft,
        attributes = _objectWithoutPropertiesLoose(props, ["style", "children", "scrollTop", "scrollLeft"]);

    var filter = instance.nodeName === 'filter' || instance.parentNode && instance.parentNode.nodeName === 'filter';
    if (scrollTop !== void 0) instance.scrollTop = scrollTop;
    if (scrollLeft !== void 0) instance.scrollLeft = scrollLeft; // Set textContent, if children is an animatable value

    if (children !== void 0) instance.textContent = children; // Set styles ...

    for (var styleName in style) {
      if (!style.hasOwnProperty(styleName)) continue;
      var isCustomProperty = styleName.indexOf('--') === 0;
      var styleValue = dangerousStyleValue(styleName, style[styleName], isCustomProperty);
      if (styleName === 'float') styleName = 'cssFloat';
      if (isCustomProperty) instance.style.setProperty(styleName, styleValue);else instance.style[styleName] = styleValue;
    } // Set attributes ...


    for (var name in attributes) {
      // Attributes are written in dash case
      var dashCase = filter ? name : attributeCache[name] || (attributeCache[name] = name.replace(/([A-Z])/g, function (n) {
        return '-' + n.toLowerCase();
      }));
      if (typeof instance.getAttribute(dashCase) !== 'undefined') instance.setAttribute(dashCase, attributes[name]);
    }

    return;
  } else return false;
}, function (style) {
  return style;
});
var domElements = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG
'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan']; // Extend animated with all the available THREE elements

var apply = merge(createAnimatedComponent);
var extendedAnimated = apply(domElements);

function _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;
}

function _objectWithoutProperties$1(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 cleanProps = function cleanProps(props) {
  props.initialState;
      props.getInitialState;
      props.refs;
      props.getRefs;
      props.didMount;
      props.didUpdate;
      props.willUnmount;
      props.getSnapshotBeforeUpdate;
      props.shouldUpdate;
      props.render;
      var rest = _objectWithoutProperties$1(props, ["initialState", "getInitialState", "refs", "getRefs", "didMount", "didUpdate", "willUnmount", "getSnapshotBeforeUpdate", "shouldUpdate", "render"]);

  return rest;
};

var Component = function (_React$Component) {
  _inherits(Component, _React$Component);

  function Component() {
    var _temp, _this, _ret;

    _classCallCheck(this, Component);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _initialiseProps.call(_this), _temp), _possibleConstructorReturn(_this, _ret);
  }

  Component.prototype.getArgs = function getArgs() {
    var state = this.state,
        props = this.props,
        setState = this._setState,
        forceUpdate = this._forceUpdate,
        refs = this._refs;
    return {
      state: state,
      props: cleanProps(props),
      refs: refs,
      setState: setState,
      forceUpdate: forceUpdate
    };
  };

  Component.prototype.componentDidMount = function componentDidMount() {
    if (this.props.didMount) this.props.didMount(this.getArgs());
  };

  Component.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {
    if (this.props.shouldUpdate) return this.props.shouldUpdate({
      props: this.props,
      state: this.state,
      nextProps: cleanProps(nextProps),
      nextState: nextState
    });else return true;
  };

  Component.prototype.componentWillUnmount = function componentWillUnmount() {
    if (this.props.willUnmount) this.props.willUnmount({
      state: this.state,
      props: cleanProps(this.props),
      refs: this._refs
    });
  };

  Component.prototype.componentDidUpdate = function componentDidUpdate(prevProps, prevState, snapshot) {
    if (this.props.didUpdate) this.props.didUpdate(Object.assign(this.getArgs(), {
      prevProps: cleanProps(prevProps),
      prevState: prevState
    }), snapshot);
  };

  Component.prototype.getSnapshotBeforeUpdate = function getSnapshotBeforeUpdate(prevProps, prevState) {
    if (this.props.getSnapshotBeforeUpdate) {
      return this.props.getSnapshotBeforeUpdate(Object.assign(this.getArgs(), {
        prevProps: cleanProps(prevProps),
        prevState: prevState
      }));
    } else {
      return null;
    }
  };

  Component.prototype.render = function render() {
    var _props = this.props,
        children = _props.children,
        render = _props.render;
    return render ? render(this.getArgs()) : typeof children === "function" ? children(this.getArgs()) : children || null;
  };

  return Component;
}(React__default.Component);

Component.defaultProps = {
  getInitialState: function getInitialState() {},
  getRefs: function getRefs() {
    return {};
  }
};

var _initialiseProps = function _initialiseProps() {
  var _this2 = this;

  this.state = this.props.initialState || this.props.getInitialState(this.props);
  this._refs = this.props.refs || this.props.getRefs(this.getArgs());

  this._setState = function () {
    return _this2.setState.apply(_this2, arguments);
  };

  this._forceUpdate = function () {
    return _this2.forceUpdate.apply(_this2, arguments);
  };
};

process.env.NODE_ENV !== "production" ? Component.propTypes = {
  initialState: object,
  getInitialState: func,
  refs: object,
  getRefs: func,
  didMount: func,
  didUpdate: func,
  willUnmount: func,
  getSnapshotBeforeUpdate: func,
  shouldUpdate: func,
  render: func,
  children: oneOfType([func, node])
} : void 0;

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;
};

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;
} // The approach here is to allow developers to render a visual <Alert> and then
// an alert (SRs don't read them on first load anyway)

var keys = {
  polite: -1,
  assertive: -1
};
var elements = {
  polite: {},
  assertive: {}
};
var liveRegions = {
  polite: null,
  assertive: null
};
var renderTimer = null;

var renderAlerts = function renderAlerts() {
  clearTimeout(renderTimer);
  renderTimer = setTimeout(function () {
    Object.keys(elements).forEach(function (type) {
      var container = liveRegions[type];

      if (container) {
        render( /*#__PURE__*/React__default.createElement(VisuallyHidden, null, /*#__PURE__*/React__default.createElement("div", {
          role: type === "assertive" ? "alert" : "status",
          "aria-live": type
        }, Object.keys(elements[type]).map(function (key) {
          return /*#__PURE__*/React__default.cloneElement(elements[type][key], {
            key: key
          });
        }))), liveRegions[type]);
      }
    });
  }, 500);
};

var createMirror = function createMirror(type) {
  var key = ++keys[type];

  var mount = function mount(element) {
    if (liveRegions[type]) {
      elements[type][key] = element;
      renderAlerts();
    } else {
      var _node = document.createElement("div");

      _node.setAttribute("data-reach-live-" + type, "true");

      liveRegions[type] = _node;
      document.body.appendChild(liveRegions[type]);
      mount(element);
    }
  };

  var update = function update(element) {
    elements[type][key] = element;
    renderAlerts();
  };

  var unmount = function unmount(element) {
    delete elements[type][key];
    renderAlerts();
  };

  return {
    mount: mount,
    update: update,
    unmount: unmount
  };
};

var Alert$1 = function Alert(_ref) {
  var children = _ref.children,
      type = _ref.type,
      props = _objectWithoutProperties(_ref, ["children", "type"]);

  var element = /*#__PURE__*/React__default.createElement("div", _extends({}, props, {
    "data-reach-alert": true
  }), children);
  return /*#__PURE__*/React__default.createElement(Component, {
    type: type,
    getRefs: function getRefs() {
      return {
        mirror: createMirror(type)
      };
    },
    didMount: function didMount(_ref2) {
      var refs = _ref2.refs;
      return refs.mirror.mount(element);
    },
    didUpdate: function didUpdate(_ref3) {
      var refs = _ref3.refs,
          prevProps = _ref3.prevProps;

      if (prevProps.type !== type) {
        refs.mirror.unmount();
        refs.mirror = createMirror(type);
        refs.mirror.mount(element);
      } else {
        refs.mirror.update(element, prevProps.type, type);
      }
    },
    willUnmount: function willUnmount(_ref4) {
      var refs = _ref4.refs;
      return refs.mirror.unmount(element);
    },
    children: element
  });
};

process.env.NODE_ENV !== "production" ? Alert$1.propTypes = {
  children: node,
  type: string
} : void 0;
Alert$1.defaultProps = {
  type: "polite"
};

var Alert = function Alert(_ref) {
  var id = _ref.id,
      title = _ref.title,
      onClose = _ref.onClose;
  return /*#__PURE__*/React.createElement("div", {
    id: id,
    className: "Toaster__alert"
  }, typeof title === "string" ? /*#__PURE__*/React.createElement("div", {
    className: "Toaster__alert_text"
  }, title) : title, onClose && /*#__PURE__*/React.createElement(Close, {
    onClose: onClose
  }));
};

var Close = function Close(_ref2) {
  var onClose = _ref2.onClose;
  return /*#__PURE__*/React.createElement("button", {
    className: "Toaster__alert_close",
    type: "button",
    "aria-label": "Close",
    onClick: onClose
  }, /*#__PURE__*/React.createElement("span", {
    "aria-hidden": "true"
  }, "\xD7"));
};

function useTimeout(callback, delay) {
  var savedCallback = React.useRef(); // Remember the latest callback.

  React.useEffect(function () {
    savedCallback.current = callback;
  }, [callback]); // Set up the interval.

  React.useEffect(function () {
    function tick() {
      if (savedCallback.current) {
        savedCallback.current();
      }
    }

    if (delay !== null) {
      var id = setTimeout(tick, delay);
      return function () {
        return clearTimeout(id);
      };
    }
  }, [delay]);
}

var getStyle = function getStyle(position) {
  var style = {
    display: "flex",
    flexDirection: "column",
    alignItems: "center"
  };

  if (position.includes("right")) {
    style.alignItems = "flex-end";
  } else if (position.includes("left")) {
    style.alignItems = "flex-start";
  }

  return style;
};

var Message = function Message(_ref) {
  var id = _ref.id,
      message = _ref.message,
      position = _ref.position,
      onRequestRemove = _ref.onRequestRemove,
      _ref$requestClose = _ref.requestClose,
      requestClose = _ref$requestClose === void 0 ? false : _ref$requestClose,
      _ref$duration = _ref.duration,
      duration = _ref$duration === void 0 ? 30000 : _ref$duration;
  var container = React.useRef(null);

  var _React$useState = React.useState(duration),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      timeout = _React$useState2[0],
      setTimeout = _React$useState2[1];

  var _React$useState3 = React.useState(true),
      _React$useState4 = _slicedToArray(_React$useState3, 2),
      localShow = _React$useState4[0],
      setLocalShow = _React$useState4[1];

  var isFromTop = position === "top-left" || position === "top-right" || position === "top";
  useTimeout(close, timeout);
  var animation = {
    config: {
      mass: 1,
      tension: 185,
      friction: 26
    },
    from: {
      opacity: 1,
      height: 0,
      transform: "translateY(".concat(isFromTop ? "-100%" : 0, ") scale(1)")
    },
    enter: function enter() {
      return function (next) {
        return next({
          opacity: 1,
          height: container.current.getBoundingClientRect().height,
          transform: "translateY(0) scale(1)"
        });
      };
    },
    leave: {
      opacity: 0,
      height: 0,
      transform: "translateY(0 scale(0.9)"
    },
    onRest: onRest
  };
  var transition = useTransition(localShow, null, animation);
  var style = React.useMemo(function () {
    return getStyle(position);
  }, [position]);

  function onMouseEnter() {
    setTimeout(null);
  }

  function onMouseLeave() {
    setTimeout(duration);
  }

  function onRest() {
    if (!localShow) {
      onRequestRemove();
    }
  }

  function close() {
    setLocalShow(false);
  }

  React.useEffect(function () {
    if (requestClose) {
      setLocalShow(false);
    }
  }, [requestClose]);

  function renderMessage() {
    if (typeof message === "string" || /*#__PURE__*/React.isValidElement(message)) {
      return /*#__PURE__*/React.createElement(Alert, {
        id: id,
        title: message,
        onClose: close
      });
    }

    if (typeof message === "function") {
      return message({
        id: id,
        onClose: close
      });
    }

    return null;
  }

  return /*#__PURE__*/React.createElement(React.Fragment, null, transition.map(function (_ref2) {
    var key = _ref2.key,
        item = _ref2.item,
        props = _ref2.props;
    return item && /*#__PURE__*/React.createElement(extendedAnimated.div, {
      key: key,
      className: "Toaster__message",
      onMouseEnter: onMouseEnter,
      onMouseLeave: onMouseLeave,
      style: Object.assign({
        opacity: props.opacity,
        height: props.height
      }, style)
    }, /*#__PURE__*/React.createElement(extendedAnimated.div, {
      style: {
        transform: props.transform,
        pointerEvents: "auto"
      },
      ref: container,
      className: "Toaster__message-wrapper"
    }, /*#__PURE__*/React.createElement(Alert$1, null, renderMessage())));
  }));
};

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$1(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var defaultState = {
  top: [],
  "top-left": [],
  "top-right": [],
  "bottom-left": [],
  bottom: [],
  "bottom-right": []
};

var ToastManager = /*#__PURE__*/function (_React$Component) {
  _inherits$1(ToastManager, _React$Component);

  var _super = _createSuper(ToastManager);

  function ToastManager(props) {
    var _this;

    _classCallCheck$1(this, ToastManager);

    _this = _super.call(this, props);
    _this.state = defaultState;

    _this.notify = function (message, options) {
      var toast = _this.createToastState(message, options);

      var position = toast.position; // prepend the toast for toasts positioned at the top of
      // the screen, otherwise append it.

      var isTop = position.includes("top");

      _this.setState(function (prev) {
        return Object.assign({}, prev, _defineProperty({}, position, isTop ? [toast].concat(_toConsumableArray(prev[position])) : [].concat(_toConsumableArray(prev[position]), [toast])));
      });

      return {
        id: toast.id,
        position: toast.position
      };
    };

    _this.closeAll = function () {
      Object.keys(_this.state).forEach(function (pos) {
        var p = pos;
        var position = _this.state[p];
        position.forEach(function (toast) {
          _this.closeToast(toast.id, p);
        });
      });
    };

    _this.createToastState = function (message, options) {
      var id = ++ToastManager.idCounter; // a bit messy, but object.position returns a number because
      // it's a method argument.

      var position = options.hasOwnProperty("position") && typeof options.position === "string" ? options.position : "top";
      return {
        id: id,
        message: message,
        position: position,
        showing: true,
        duration: typeof options.duration === "undefined" ? 5000 : options.duration,
        onRequestRemove: function onRequestRemove() {
          return _this.removeToast(String(id), position);
        },
        type: options.type
      };
    };

    _this.closeToast = function (id, position) {
      _this.setState(function (prev) {
        return Object.assign({}, prev, _defineProperty({}, position, prev[position].map(function (toast) {
          if (toast.id !== id) return toast;
          return Object.assign({}, toast, {
            requestClose: true
          });
        })));
      });
    }; // actually fully remove the toast


    _this.removeToast = function (id, position) {
      _this.setState(function (prev) {
        return Object.assign({}, prev, _defineProperty({}, position, prev[position].filter(function (toast) {
          return toast.id !== id;
        })));
      });
    };

    _this.getStyle = function (position) {
      var style = {
        maxWidth: "560px",
        position: "fixed",
        zIndex: 5500,
        pointerEvents: "none"
      };

      if (position === "top" || position === "bottom") {
        style.margin = "0 auto";
        style.textAlign = "center";
      }

      if (position.includes("top")) {
        style.top = 0;
      }

      if (position.includes("bottom")) {
        style.bottom = 0;
      }

      if (!position.includes("left")) {
        style.right = 0;
      }

      if (!position.includes("right")) {
        style.left = 0;
      }

      return style;
    };

    props.notify(_this.notify, _this.closeAll, _this.closeToast);
    return _this;
  }

  _createClass(ToastManager, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      return Object.keys(this.state).map(function (position) {
        var pos = position;
        var toasts = _this2.state[pos];
        return /*#__PURE__*/React.createElement("span", {
          key: position,
          className: "Toaster__manager-" + pos,
          style: _this2.getStyle(pos)
        }, toasts.map(function (toast) {
          return /*#__PURE__*/React.createElement(Message, Object.assign({
            position: pos,
            key: toast.id
          }, toast));
        }));
      });
    }
  }]);

  return ToastManager;
}(React.Component);
ToastManager.idCounter = 0;

var isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
var PORTAL_ID = "react-toast";

var Toaster = function Toaster() {
  var _this = this;

  _classCallCheck$1(this, Toaster);

  this.closeAll = function () {
    if (_this.removeAll) {
      _this.removeAll();
    }
  };

  this.bindNotify = function (fn, removeAll, closeToast) {
    _this.createNotification = fn;
    _this.removeAll = removeAll;
    _this.closeToast = closeToast;
  };

  this.notify = function (message) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    if (_this.createNotification) {
      return _this.createNotification(message, options);
    }
  };

  this.close = function (id, position) {
    if (_this.closeToast) {
      _this.closeToast(id, position);
    }
  };

  if (!isBrowser) {
    return;
  }

  var portalElement;
  var existingPortalElement = document.getElementById(PORTAL_ID);

  if (existingPortalElement) {
    portalElement = existingPortalElement;
  } else {
    var el = document.createElement("div");
    el.id = PORTAL_ID;
    el.className = "Toaster";

    if (document.body != null) {
      document.body.appendChild(el);
    }

    portalElement = el;
  }

  ReactDOM.render( /*#__PURE__*/React.createElement(ToastManager, {
    notify: this.bindNotify
  }), portalElement);
};

var toaster = new Toaster();

var _excluded = ["position", "duration"];
/**
 * Creates a toast, a small notification for conveying a message to the user.
 */

function useToast() {
  var create = useCallback(function (_ref) {
    var _ref$position = _ref.position,
        position = _ref$position === void 0 ? "bottom" : _ref$position,
        _ref$duration = _ref.duration,
        duration = _ref$duration === void 0 ? 5000 : _ref$duration,
        rest = _objectWithoutProperties$2(_ref, _excluded);

    var options = {
      position: position,
      duration: duration
    };
    toaster.notify(function (_ref2) {
      var onClose = _ref2.onClose;
      return /*#__PURE__*/React__default.createElement(Toast, _extends$1({
        handleClose: onClose
      }, rest));
    }, options);
  }, []);
  return create;
}

export { useToast as default };
