All files / Menu Menu.tsx

98.85% Statements 86/87
91.8% Branches 56/61
100% Functions 14/14
98.5% Lines 66/67

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 186 187 1884x     4x 4x   4x 4x 4x 4x   4x     154x 151x 151x 151x 151x 151x 151x 151x 151x 151x   151x 151x 151x 151x       151x 151x     151x 151x 151x 151x                         151x 52x     151x 44x   151x 44x     151x   6x   6x     151x 5x 5x     151x 5x 1x 1x   4x 1x 1x       151x     144x                               274x 270x 266x                       144x 140x             4x     4x   4x         106x   96x           5x           5x                           4x 106x 106x     106x     4x                            
import React, { forwardRef, useCallback, useEffect, useState } from "react";
import { MenuProps, MenuStyleProps } from "./Menu.types";
import { MenuItemKeyProps, MenuItemPrivateProps } from "../MenuItem/MenuItem.types";
import styled, { css } from "styled-components";
import { usePopper } from "react-popper";
import { MenuItemProps } from "../MenuItem/MenuItem.types";
import ClickAwayListener from "../ClickAwayListener/ClickAwayListener";
import { useTheme } from "../ThemeProvider/ThemeProvider";
import { getColorPalette } from "../../helpers/helpers";
import colorTokens from "../../tokens/colors.json";
 
const Menu = forwardRef<HTMLDivElement, MenuProps>(
  (
    {
      children,
      popperStyles,
      variant = "contained",
      open = false,
      minWidth = "0",
      anchorElement,
      hideOnOutsideClick = true,
      color = colorTokens.default.primary.main,
      className,
      style,
      // Events
      onClick,
      onClose,
      "data-testid": dataTestId,
      ...props
    },
    ref
  ) => {
    const [isOpen, setIsOpen] = useState(open);
    const [popperElement, setPopperElement] = useState<HTMLDivElement | null>(
      null
    );
    const [focusVisible, setFocusVisible] = useState<number>(0);
    const theme = useTheme().theme;
    const colorPalette = getColorPalette(theme, color);
    const { styles, attributes, update } = usePopper(anchorElement, popperElement, {
      placement: (popperStyles && popperStyles.placement) ?? "bottom-start",
      modifiers: (popperStyles && popperStyles.modifiers) ?? [
        {
          name: "offset",
          options: {
            offset: [0, 2.5],
          },
        },
      ],
    });
 
    // Update popper position when anchor element changes
    useEffect(() => {
      update && update();
    }, [anchorElement, update]);
 
    useEffect(() => {
      setIsOpen(open);
    }, [open]);
    useEffect(() => {
      setFocusVisible(0);
    },[isOpen]);
 
    const _onClick = useCallback((
      e: React.MouseEvent<HTMLLIElement>,
      { title, value }: MenuItemKeyProps
    ) => {
      onClick && onClick(e, { title, value });
    },[onClick]);
 
    const _onClose = useCallback((e: MouseEvent) => {
      setIsOpen(false);
      onClose && onClose(e);
    },[onClose]);
 
    const _onKeyDown = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {
      if(e.key === "ArrowDown") {
        e.preventDefault();
        setFocusVisible((prev) => (prev + 1) % React.Children.count(children));
      }
      else if(e.key === "ArrowUp"){
        e.preventDefault();
        setFocusVisible((prev) => (prev - 1 + React.Children.count(children)) % React.Children.count(children));
      }
    },[children]);
 
    if (Array.isArray(children) && children.length === 0) return null;
 
    const MenuElement = (
      <StyledMenuContainer
        ref={setPopperElement}
        $open={isOpen}
        $minWidth={minWidth}
        $colorPalette={colorPalette}
        $color={color}
        $variant={variant}
        style={{ ...styles.popper, ...style }}
        onKeyDown={_onKeyDown}
        data-testid={dataTestId}
        className={className}
        {...attributes.popper}
        {...props}
      >
        <StyledMenu>
          {React.Children.map(children, (child, index) => {
            if (!child) return child;
            if (!React.isValidElement(child)) return child;
            return React.cloneElement(child, {
              key: index,
              ...(!child.props.color && { color: color }),
              ...(!child.props.variant && { variant: variant }),
              pvtHasFocus: focusVisible === index,
              pvtOnClick: _onClick,
            } as MenuItemProps & MenuItemPrivateProps);
          })}
        </StyledMenu>
      </StyledMenuContainer>
    );
 
    if (hideOnOutsideClick) {
      return (
        <ClickAwayListener onClickAway={_onClose}>
          {MenuElement}
        </ClickAwayListener>
      );
    }
 
    return MenuElement;
  }
);
export default Menu;
 
const variantStyleHandler = (
  variant: MenuStyleProps["$variant"],
  colorPalette: MenuStyleProps["$colorPalette"],
  color: MenuStyleProps["$color"]
) => {
  switch (variant) {
    case "contained":
      return css`
        background-color: ${colorPalette[color].accentScale[8]};
        color: ${colorPalette[color].accentContrast};
        border: 2px solid ${colorPalette[color].accentScale[8]};
      `;
    case "outlined":
      return css`
        background-color: transparent;
        color: ${colorPalette[color].accentScale[10]};
        border: 2px solid ${colorPalette[color].accentScale[5]};
      `;
    case "soft":
      return css`
        background-color: ${colorPalette[color].accentScale[2]};
        color: ${colorPalette[color].accentScale[10]};
        border: 2px solid ${colorPalette[color].accentScale[2]};
      `;
    case "neumorph":
      return css`
        background-color: ${colorPalette[color].appearance === "light" ? "#fff" : "#000"};
        color: ${colorPalette[color].accentScale[10]};
        box-shadow: 0 6px 6px rgba(0, 0, 0, .1), 6px -6px 12px rgba(0, 0, 0, 0.1);
      `;
  }
};
 
const StyledMenuContainer = styled.div<MenuStyleProps>`
  display: ${(props) => (props.$open ? "block" : "none")};
  min-width: ${(props) => props.$minWidth};
  border-radius: 0.5rem;
  padding: 0.5rem 0;
  ${props => variantStyleHandler(props.$variant, props.$colorPalette, props.$color)}
  
`;
const StyledMenu = styled.ul`
  display: flex;
  flex-direction: column;
  justify-content: center;
  box-sizing: border-box;
  width: 100%;
  list-style-type: none;
  cursor: pointer;
  padding: 0;
  margin: 0;
  user-select: none;
`;