"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useAnimation = useAnimation;

var React = _interopRequireWildcard(require("react"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : 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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

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 _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_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 _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function useAnimation(config) {
  var refs = React.useRef(new Set());
  var parameters = React.useRef(new WeakMap());
  var entryAnimations = React.useRef(new WeakMap());
  var exitAnimations = React.useRef(new WeakMap());
  var isAnimationSupported = React.useRef(true);

  var _React$useState = React.useState('initial'),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      phase = _React$useState2[0],
      setPhase = _React$useState2[1];

  var configRef = React.useRef(config); // We only need the most updated value. Equivalent of using useEffectEvent.

  React.useEffect(function () {
    configRef.current = config;
  }, [config]);
  var register = React.useCallback(function () {
    var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
      index: refs.current.size
    };
    return {
      ref: function ref(el) {
        if (el) {
          parameters.current.set(el, options);
          refs.current.add(el);
        }
      }
    };
  }, []);
  React.useEffect(function () {
    var elements = refs.current; // Check if animation is supported on dom elements in the browser.

    isAnimationSupported.current = Object.hasOwnProperty.call(Element.prototype, 'animate');
    return function () {
      if (isAnimationSupported.current) {
        // Remove all outstanding animations and cleanup refs
        var allSnapshot = _toConsumableArray(elements).flatMap(function (ref) {
          return ref.getAnimations();
        });

        allSnapshot.forEach(function (animation) {
          return animation.cancel();
        });
      }

      elements.clear();
    };
  }, []);
  React.useEffect(function () {
    if (!isAnimationSupported.current) {
      console.warn('Web Animation API is not supported on this browser');
      return;
    } // In debug mode, we override the phase with the one provided.


    if (useAnimation.debug.phase !== null) {
      setPhase(useAnimation.debug.phase);
    }

    switch (phase) {
      case 'entry':
        {
          refs.current.forEach(function (ref) {
            var _entryAnimations$curr, _configRef$current$en;

            var _parameters$current$g = parameters.current.get(ref),
                index = _parameters$current$g.index,
                _parameters$current$g2 = _parameters$current$g.overrides,
                overrides = _parameters$current$g2 === void 0 ? {} : _parameters$current$g2;

            var entry = (_entryAnimations$curr = entryAnimations.current.get(ref)) !== null && _entryAnimations$curr !== void 0 ? _entryAnimations$curr : [];
            ref.getAnimations().forEach(function (animation) {
              return animation.cancel();
            });
            (_configRef$current$en = configRef.current.entry) === null || _configRef$current$en === void 0 ? void 0 : _configRef$current$en.forEach(function (keyframesConfig, i) {
              var id = keyframesConfig.id;
              var keyframes = keyframesConfig.keyframes,
                  _keyframesConfig$opti = keyframesConfig.options,
                  options = _keyframesConfig$opti === void 0 ? {} : _keyframesConfig$opti;
              var override = overrides[id];

              if (override) {
                keyframes = (override === null || override === void 0 ? void 0 : override.keyframes) || keyframes;
                options = _objectSpread(_objectSpread({}, options), override === null || override === void 0 ? void 0 : override.options);
              }

              var animationOptions = _objectSpread(_objectSpread({}, options), {}, {
                delay: typeof options.delay === 'function' ? options.delay(index) : options.delay,
                duration: typeof options.duration === 'function' ? options.duration(index) : options.duration
              });

              var anim = ref.animate(keyframes, animationOptions);
              anim.id = "entry ".concat(i);
              entry.push(anim);
            });
            entryAnimations.current.set(ref, entry);
          });
          break;
        }

      case 'exit':
        {
          refs.current.forEach(function (ref) {
            var _exitAnimations$curre, _configRef$current$ex;

            var _parameters$current$g3 = parameters.current.get(ref),
                index = _parameters$current$g3.index,
                _parameters$current$g4 = _parameters$current$g3.overrides,
                overrides = _parameters$current$g4 === void 0 ? {} : _parameters$current$g4;

            var exit = (_exitAnimations$curre = exitAnimations.current.get(ref)) !== null && _exitAnimations$curre !== void 0 ? _exitAnimations$curre : [];
            (_configRef$current$ex = configRef.current.exit) === null || _configRef$current$ex === void 0 ? void 0 : _configRef$current$ex.forEach(function (keyframesConfig, i) {
              var id = keyframesConfig.id;
              var keyframes = keyframesConfig.keyframes,
                  _keyframesConfig$opti2 = keyframesConfig.options,
                  options = _keyframesConfig$opti2 === void 0 ? {} : _keyframesConfig$opti2;
              var override = overrides[id];

              if (override) {
                keyframes = (override === null || override === void 0 ? void 0 : override.keyframes) || keyframes;
                options = _objectSpread(_objectSpread({}, options), override === null || override === void 0 ? void 0 : override.options);
              }

              var animationOptions = _objectSpread(_objectSpread({}, options), {}, {
                delay: typeof options.delay === 'function' ? options.delay(index) : options.delay,
                duration: typeof options.duration === 'function' ? options.duration(index) : options.duration
              });

              var anim = ref.animate(keyframes, animationOptions);
              anim.id = "exit ".concat(i);
              exit.push(anim);
            });
            exitAnimations.current.set(ref, exit);
          }); // Snapshot all animations  from the whole run that need to be removed.

          var allSnapshot = _toConsumableArray(refs.current).flatMap(function (ref) {
            return ref.getAnimations();
          }); // Detect when all exit animations on all registered elements finish


          var exitSnapshot = _toConsumableArray(refs.current).flatMap(function (ref) {
            return exitAnimations.current.get(ref);
          });

          Promise.allSettled(exitSnapshot.map(function (animation) {
            return animation.finished;
          })).then(function () {
            allSnapshot.forEach(function (animation) {
              return animation.cancel();
            });
            refs.current.forEach(function (ref) {
              entryAnimations.current.set(ref, []);
              exitAnimations.current.set(ref, []);
            });
            setPhase(function (phase) {
              return phase === 'exit' ? 'finished' : phase;
            });
          });
          break;
        }

      default:
        break;
    } // In debug mode, we need to manually pause all animations at the desired time.


    if (useAnimation.debug.phase !== null) {
      var _allSnapshot = _toConsumableArray(refs.current).flatMap(function (ref) {
        return ref.getAnimations();
      });

      _allSnapshot.forEach(function (animation) {
        animation.currentTime = useAnimation.debug.time;
        animation.pause();
      });
    }

    console.log('phase', phase);
  }, [phase]);
  return {
    register: register,
    phase: phase,
    setPhase: setPhase
  };
}

var debug = {
  phase: null,
  time: 0
};
useAnimation.debug = debug;