All files / src/alert Alert.tsx

72.73% Statements 24/33
76.47% Branches 13/17
53.85% Functions 7/13
74.19% Lines 23/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185                                                                                                                  2x                                   10x   10x               10x           10x   10x 10x 10x   10x 10x     10x           10x 10x 10x     10x 10x                                                             10x       10x 3x     7x     2x                         1x         3x                      
import React, { useState, useEffect, useRef, useCallback } from "react";
import classNames from "classnames";
import { StyledProps } from "../_type";
import { useDefault } from "../_util/use-default";
import { Icon } from "../icon";
import { FadeTransition } from "../transition";
import { useConfig } from "../_util/config-context";
import { Button } from "../button";
import { AlertNotice } from "./AlertNotice";
 
export interface AlertProps extends StyledProps {
  /**
   * 提示类型
   * @default "info"
   */
  type?: "info" | "success" | "warning" | "error";
 
  /**
   * 提示内容
   */
  children?: React.ReactNode;
 
  /**
   * 控制 Alert 是否显示,如果没传,默认显示
   * 配合 `onClose` 回调可以实现关闭效果
   */
  visible?: boolean;
 
  /**
   * 默认是否显示。如果不想自己控制 Alert 的显示状态,可以传入 defaultVisible 为 true,此时会渲染关闭图标,并且用户点击关闭时隐藏。
   * @default true
   */
  defaultVisible?: boolean;
 
  /**
   * 传入 visibile 或者 defaultVisible 都会渲染关闭图标,用户点击关闭图标时回调 onClose
   */
  onClose?: () => void;
 
  /**
   * 头部右侧渲染内容
   */
  extra?: React.ReactNode;
 
  /**
   * 隐藏图标显示
   * @default false
   */
  hideIcon?: boolean;
 
  /**
   * 轮播模式
   * @default false
   */
  carouselMode?: boolean;
}
 
const iconMap = {
  info: "infoblue",
  success: "success",
  warning: "warning",
  error: "error",
};
 
export function Alert({
  type,
  children,
  className,
  style,
  onClose,
  extra,
  hideIcon,
  carouselMode,
  ...props
}: AlertProps) {
  const { classPrefix } = useConfig();
 
  const alertClassName = classNames(
    `${classPrefix}-alert`,
    {
      [`${classPrefix}-alert--${type}`]: type,
    },
    className
  );
 
  const [visible, onVisibleChange] = useDefault(
    props.visible,
    props.defaultVisible,
    visible => !visible && onClose && onClose()
  );
 
  const isClosable = typeof visible === "boolean";
 
  const timerRef = useRef(null);
  const [currentIndex, setCurrentIndex] = useState<number>(0);
  const length = React.Children.count(children);
 
  const circulate = useCallback(() => {
    Iif (timerRef.current) {
      clearTimeout(timerRef.current);
    }
    timerRef.current = setTimeout(() => {
      setCurrentIndex(i => (i + 1) % length);
      circulate();
    }, 5000);
  }, [length]);
 
  useEffect(() => {
    circulate();
    return () => clearTimeout(timerRef.current);
  }, [circulate]);
 
  const alertElement = (children: React.ReactNode) => (
    <div className={alertClassName} style={style}>
      {!hideIcon && (
        <span className={`${classPrefix}-alert__decoration`}>
          <Icon type={iconMap[type] || "infoblue"} />
        </span>
      )}
      <div className={`${classPrefix}-alert__info`}>{children}</div>
      <div className={`${classPrefix}-alert__operational`}>
        {extra}
        {carouselMode && (
          <Dot
            classPrefix={classPrefix}
            total={length}
            currentIndex={currentIndex}
            onChange={index => {
              setCurrentIndex(index);
              circulate();
            }}
          />
        )}
        {isClosable && (
          <Button
            type="icon"
            icon="close"
            onClick={() => onVisibleChange(false)}
          />
        )}
      </div>
    </div>
  );
 
  const content = !carouselMode
    ? alertElement(children)
    : alertElement(React.Children.toArray(children)[currentIndex]);
 
  if (isClosable) {
    return <FadeTransition in={visible}>{content}</FadeTransition>;
  }
 
  return content;
}
 
Alert.Notice = AlertNotice;
 
function Dot({
  classPrefix,
  total,
  currentIndex,
  onChange,
}: {
  classPrefix: string;
  total: number;
  currentIndex: number;
  onChange: (index: number) => void;
}) {
  return (
    <div className={`${classPrefix}-alert__nav ${classPrefix}-alert__nav--dot`}>
      {Array(total)
        .fill(null)
        .map((_, i) => (
          <span
            key={i}
            className={classNames(`${classPrefix}-alert__nav-item`, {
              "is-current": currentIndex === i,
            })}
            onClick={() => onChange(i)}
          />
        ))}
    </div>
  );
}