All files / src/collapse CollapsePanel.tsx

54.55% Statements 6/11
80% Branches 12/15
50% Functions 2/4
60% Lines 6/10

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                                                                                                7x       6x   7x 7x 7x                     7x                                          
import React, { useContext } from "react";
import classNames from "classnames";
import { CollapseContext } from "./CollapseContext";
import { Icon } from "../icon";
import { StyledProps } from "../_type";
import { useConfig } from "../_util/config-context";
import { injectValue } from "../_util/inject-value";
 
export interface CollapsePanelProps extends StyledProps {
  /**
   * 面板唯一标识
   */
  id: string;
 
  /**
   * 头部标题
   * @docType React.ReactNode | ((active: boolean) => React.ReactNode)
   */
  title?: React.ReactNode | ((active: boolean) => React.ReactNode);
 
  /**
   * 内容
   */
  children?: React.ReactNode;
 
  /**
   * **\[Deprecated\]** 请使用 `children` 代替
   * @deprecated
   */
  content?: React.ReactNode;
 
  /**
   * 展开方向
   * @default "bottom"
   * @version 2.1.0
   */
  position?: "top" | "bottom";
}
 
export function CollapsePanel({
  id,
  title,
  children,
  content = children,
  position,
  className,
  style,
}: CollapsePanelProps) {
  const { classPrefix } = useConfig();
  const {
    activeIds,
    onActive,
    icon = active => <Icon type={active ? "arrowup" : "arrowdown"} />,
    iconPosition = "left",
  } = useContext(CollapseContext);
  const active = activeIds.includes(id);
  const top = position === "top";
 
  function handleClick(event: React.MouseEvent) {
    const context = { event };
    if (active) {
      onActive(activeIds.filter(activeId => activeId !== id), context);
    } else {
      onActive([...activeIds, id], context);
    }
  }
 
  return (
    <div
      className={classNames(`${classPrefix}-accordion`, className, {
        "is-active": active,
      })}
      style={style}
    >
      {top && <div className={`${classPrefix}-accordion__body`}>{content}</div>}
      <div className={`${classPrefix}-accordion__header`} onClick={handleClick}>
        {iconPosition !== "right" && injectValue(icon)(active)}
        <span className={`${classPrefix}-accordion__header-title`}>
          {injectValue(title)(active)}
        </span>
        {iconPosition === "right" && injectValue(icon)(active)}
      </div>
      {!top && (
        <div className={`${classPrefix}-accordion__body`}>{content}</div>
      )}
    </div>
  );
}