All files / src/menu SubMenu.tsx

66.67% Statements 6/9
88.89% Branches 8/9
50% Functions 1/2
66.67% Lines 6/9

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                                                                                                          9x   9x         9x         9x 4x     9x                                                                
import React from "react";
import classNames from "classnames";
import { StyledProps } from "../_type";
import { Icon } from "../icon";
import { useDefault } from "../_util/use-default";
import { useConfig } from "../_util/config-context";
 
export interface SubMenuProps extends StyledProps {
  /**
   * 标题
   */
  title?: React.ReactNode;
 
  /**
   * 菜单折叠后标题处显示的图标 URL
   *
   * **传递一组 URL 时,第一个 URL 会作为未激活态图标,第二个 URL 会作为激活态图标**
   */
  icon?: string | [string, string];
 
  /**
   * 菜单内容(Menu.Item)
   */
  children?: React.ReactNode;
 
  /**
   * 是否默认展开
   *
   * @default false
   */
  defaultOpened?: boolean;
 
  /**
   * 是否展示
   */
  opened?: boolean;
 
  /**
   * 展开状态变化时回调
   */
  onOpenedChange?: (opened: boolean) => void;
}
 
export function SubMenu({
  title,
  icon,
  children,
  defaultOpened = false,
  opened,
  onOpenedChange,
  className,
  style,
}: SubMenuProps) {
  const { classPrefix } = useConfig();
  // eslint-disable-next-line no-param-reassign
  [opened, onOpenedChange] = useDefault(opened, defaultOpened, onOpenedChange);
 
  let defaultIcon;
  let activeIcon;
 
  Iif (typeof icon === "string") {
    defaultIcon = icon;
    activeIcon = icon;
  }
 
  if (Array.isArray(icon)) {
    [defaultIcon, activeIcon] = icon;
  }
 
  return (
    <li
      className={classNames(`${classPrefix}-menu__submenu`, className, {
        "is-selected": opened,
      })}
      style={style}
    >
      <a
        className={`${classPrefix}-menu__item`}
        onClick={() => onOpenedChange(!opened)}
      >
        {defaultIcon && (
          <img
            className={`${classPrefix}-menu__list-icon`}
            src={defaultIcon}
            alt="icon"
          />
        )}
        {activeIcon && (
          <img
            className={`${classPrefix}-menu__list-icon is-selected`}
            src={activeIcon}
            alt="icon"
          />
        )}
        <div className={`${classPrefix}-menu__text`}>{title}</div>
        <Icon type="arrowdown" />
      </a>
      <ul className={`${classPrefix}-menu__list`}>{children}</ul>
    </li>
  );
}