import React, { useRef } from "react";
import { CSSTransition } from "react-transition-group";
import { TransitionProps } from "react-transition-group/Transition";
import { noop } from "../_util/noop";

export function BaseTransition({
  in: enter,
  onEnter = noop,
  onExit = noop,
  onExited = noop,
  children,
  ...props
}: TransitionProps) {
  // 离场时保持 children 不变
  const childrenRef = useRef<React.ReactNode>(null);

  return (
    <CSSTransition
      {...props}
      in={enter}
      onEnter={(...args) => {
        childrenRef.current = null;
        onEnter(...args);
      }}
      onExit={(...args) => {
        childrenRef.current = children;
        onExit(...args);
      }}
      onExited={(...args) => {
        childrenRef.current = null;
        onExited(...args);
      }}
      onExiting={() => {
        /** fix issue: https://git.woa.com/tea-design/tea2/issues/525 */
        childrenRef.current = null;
      }}
    >
      {childrenRef.current || children}
    </CSSTransition>
  );
}

BaseTransition.displayName = "BaseTransition";
