"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.default = void 0;

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

var _classnames = _interopRequireDefault(require("classnames"));

var _useReducedMotion = _interopRequireDefault(require("../utils/useReducedMotion"));

var _useIsomorphicLayoutEffect = require("../utils/useIsomorphicLayoutEffect");

var _classNamesRegistry = require("./classNamesRegistry");

var _CSSTransitionAnimator = require("./CSSTransitionAnimator");

var predefinedEffects = _interopRequireWildcard(require("./predefinedEffects"));

var _debug = require("./debug");

var _excluded = ["active", "delay", "fillMode", "onTransitionEnd"];

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

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 _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

Transition.createEffect = predefinedEffects.createEffect;

var isFillModeBackwards = function isFillModeBackwards(mode) {
  return mode === 'backwards' || mode === 'both';
};

var isFillModeForwards = function isFillModeForwards(mode) {
  return mode === 'forwards' || mode === 'both';
}; // https://github.com/jsdom/jsdom/issues/1781


var supportsTransitions = function supportsTransitions() {
  return typeof window !== 'undefined' && typeof window.TransitionEvent !== 'undefined';
};

function BaseTransition(_ref) {
  var active = _ref.active,
      effect = _ref.effect,
      _ref$delay = _ref.delay,
      delay = _ref$delay === void 0 ? 0 : _ref$delay,
      _ref$fillMode = _ref.fillMode,
      fillMode = _ref$fillMode === void 0 ? 'none' : _ref$fillMode,
      inline = _ref.inline,
      className = _ref.className,
      children = _ref.children,
      onTransitionStart = _ref.onTransitionStart,
      onTransitionEnd = _ref.onTransitionEnd;
  var containerRef = React.useRef(null);
  var prefersReducedMotion = (0, _useReducedMotion.default)();
  var currentEffect = React.useMemo(function () {
    if (typeof effect === 'function') {
      return effect(prefersReducedMotion);
    }

    return effect;
  }, [effect, prefersReducedMotion]);
  var classNamesRegistry = React.useMemo(_classNamesRegistry.createClassNamesRegistry, []);
  var animator = React.useMemo(function () {
    return (0, _CSSTransitionAnimator.createCSSTransitionAnimator)(classNamesRegistry);
  }, [classNamesRegistry]);

  var _getDebugOptions = (0, _debug.getDebugOptions)(),
      outlines = _getDebugOptions.outlines;

  var baseClassName = (0, _classnames.default)('sg-transition', className, {
    'sg-transition--inline': inline,
    'sg-transition--outlines': outlines
  });
  (0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(function () {
    /**
     * Since the transition imperatively applies the style
     * and className to the container element, other props
     * changes that affect these element attributes should
     * also be imperative. The registry synchronizes them
     * without affecting the animation.
     */
    classNamesRegistry.register('base', baseClassName || '');
    var container = containerRef.current;

    if (container) {
      container.className = classNamesRegistry.toString();
    }
  }, [classNamesRegistry, baseClassName]);
  /**
   * Changing callbacks should not trigger transition.
   */

  var onTransitionStartRef = React.useRef();
  var onTransitionEndRef = React.useRef();
  (0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(function () {
    onTransitionStartRef.current = onTransitionStart;
    onTransitionEndRef.current = onTransitionEnd;
    animator.onFinish(function () {
      var container = containerRef.current;

      if (container && !isFillModeForwards(fillMode)) {
        animator.cleanup(container);
      }

      if (onTransitionEnd && currentEffect) {
        onTransitionEnd(currentEffect);
      }
    });
  });
  /**
   * The transition can be triggered by props that have been
   * applied to the actual DOM, and subsequent renders of the
   * virtual DOM should not produce any visual result.
   */

  var previouslyAppliedProps = React.useRef({
    active: false,
    effect: null
  });
  /**
   * The useLayoutEffect because of possible flicking
   * issues while using a regular useEffect hook.
   */

  (0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(function () {
    var _getDebugOptions2 = (0, _debug.getDebugOptions)(),
        speed = _getDebugOptions2.speed;

    var currentProps = {
      active: active,
      effect: currentEffect
    };
    var container = containerRef.current;
    var rules = getTransitionRules({
      previousProps: previouslyAppliedProps.current,
      currentProps: currentProps
    }); // no rules that trigger the transition found

    if (!container || typeof rules === 'undefined') {
      return;
    }

    if (currentEffect === null || rules === null) {
      animator.cleanup(container);
      return;
    }

    if (supportsTransitions() && isFillModeBackwards(fillMode)) {
      animator.apply(container, rules.from);
    }

    var performTransitionEffect = function performTransitionEffect() {
      if (onTransitionStartRef.current) {
        onTransitionStartRef.current(currentEffect);
      }

      if (!supportsTransitions()) {
        if (onTransitionEndRef.current) {
          onTransitionEndRef.current(currentEffect);
        }
      } else {
        animator.animate(container, rules.from, rules.to, speed);
      }
      /**
       * These props should be memoized just
       * after applying them to the actual DOM.
       */


      previouslyAppliedProps.current = currentProps;
    };
    /**
     * The parent Transition component can delay mounting
     * a child BaseTransition component when the active prop
     * changes and the child should not wait again.
     */


    var actualDelay = rules.canSkipDelay && !isFillModeBackwards(fillMode) ? 0 : delay;

    if (actualDelay > 0) {
      var timeoutId = setTimeout(performTransitionEffect, actualDelay / speed);
      return function () {
        return clearTimeout(timeoutId);
      };
    }

    performTransitionEffect();
  }, [animator, active, currentEffect, delay, fillMode]);
  var handleTransitionEnd = React.useCallback(function (event) {
    // ignores bubbling events of its own descendants
    if (event.target === event.currentTarget) {
      animator.propertyTransitionEnd();
    }
  }, [animator]);
  return /*#__PURE__*/React.createElement("div", {
    ref: containerRef,
    onTransitionEnd: supportsTransitions() ? handleTransitionEnd : undefined
  }, children);
}

function Transition(_ref2) {
  var active = _ref2.active,
      _ref2$delay = _ref2.delay,
      delay = _ref2$delay === void 0 ? 0 : _ref2$delay,
      _ref2$fillMode = _ref2.fillMode,
      fillMode = _ref2$fillMode === void 0 ? 'none' : _ref2$fillMode,
      onTransitionEnd = _ref2.onTransitionEnd,
      otherProps = _objectWithoutProperties(_ref2, _excluded);

  var canMountBaseComponent = delay === 0 || isFillModeBackwards(fillMode);

  var _React$useState = React.useState(canMountBaseComponent ? active : false),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      mounted = _React$useState2[0],
      setMounted = _React$useState2[1];

  (0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(function () {
    if (active) {
      var mountBaseComponent = function mountBaseComponent() {
        return setMounted(true);
      };

      if (canMountBaseComponent) {
        mountBaseComponent();
      } else {
        var _getDebugOptions3 = (0, _debug.getDebugOptions)(),
            speed = _getDebugOptions3.speed;

        var timeoutId = setTimeout(mountBaseComponent, delay / speed);
        return function () {
          return clearTimeout(timeoutId);
        };
      }
    }
  }, [active, delay, canMountBaseComponent]);
  var handleTransitionEnd = React.useCallback(function (effect) {
    if (!active) {
      setMounted(false);
    } // proxy the actual event


    if (onTransitionEnd) {
      onTransitionEnd(effect);
    }
  }, [active, onTransitionEnd]);
  return mounted ? /*#__PURE__*/React.createElement(BaseTransition, _extends({}, otherProps, {
    active: active,
    delay: delay,
    fillMode: fillMode,
    onTransitionEnd: handleTransitionEnd
  })) : null;
}

function getTransitionRules(_ref3) {
  var previousProps = _ref3.previousProps,
      currentProps = _ref3.currentProps;

  if (currentProps.effect === null) {
    return null;
  }

  if (previousProps.active === false && currentProps.active === true) {
    return {
      from: currentProps.effect.initial,
      to: currentProps.effect.animate,
      canSkipDelay: true
    };
  }

  if (previousProps.active === true && currentProps.active === false) {
    return {
      from: currentProps.effect.animate,
      to: currentProps.effect.exit,
      canSkipDelay: false
    };
  }

  if (previousProps.effect === null && currentProps.effect !== null) {
    return {
      from: currentProps.effect.initial,
      to: currentProps.effect.animate,
      canSkipDelay: false
    };
  }

  if (previousProps.effect !== currentProps.effect) {
    return {
      from: currentProps.effect.initial,
      to: currentProps.effect.animate,
      canSkipDelay: false
    };
  }
} // Export default when there is an assignement to the static property results in the followig bug:
// https://github.com/storybookjs/storybook/discussions/13935
// Separating function declaration from export statement solves the issue until it's fixed


var _default = Transition;
exports.default = _default;