All files / src/components dropdown-button.tsx

50% Statements 28/56
32.5% Branches 13/40
42.1% Functions 8/19
50.94% Lines 27/53

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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252                                                                            10x             4x 4x   4x 4x   4x     4x 2x 2x                                               4x 2x         4x 2x 2x           4x                                                                                           10x                                                                           10x                   8x 8x   8x     8x 8x       8x 8x 8x                                           8x         8x                                              
import {
  useRef,
  useState,
  useEffect,
  useMemo,
  type ReactNode,
  type ReactElement,
  type Dispatch,
  type SetStateAction,
  type HTMLAttributes,
  useCallback,
  Fragment,
} from 'react';
import cn from 'classnames';
 
import Button, { type ButtonProps } from './button';
 
import '../styles/components/dropdown.scss';
 
export type DropdownButtonProps = {
  /**
   * Content revealed on click.
   */
  children:
    | ReactNode
    | ((showMenu: Dispatch<SetStateAction<boolean>>) => ReactNode);
  /**
   * Label to be display by the button
   */
  label: ReactNode;
  /**
   * Open on pointer over (useful for dropdowns in header)
   */
  openOnHover?: boolean;
} & Omit<ButtonProps, 'children'>;
 
// Keep it around for now as it's still used in TreeSelect
/** @deprecated */
const DropdownButton = ({
  children,
  label,
  className,
  openOnHover = false,
  ...props
}: DropdownButtonProps) => {
  const [showMenu, setShowMenu] = useState(false);
  const [size, setSize] = useState<DOMRect>();
 
  const ref = useRef<HTMLButtonElement>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);
 
  const childType = typeof children;
 
  // effect to handle a click on anything closing the dropdown
  useEffect(() => {
    Eif (!showMenu) {
      return;
    }
 
    const listener = (event: MouseEvent | TouchEvent) => {
      if (
        !ref.current ||
        ref.current?.parentElement?.contains(event.target as Node) ||
        (childType === 'function' &&
          dropdownRef.current?.contains(event.target as Node))
      ) {
        return;
      }
      setShowMenu(false);
    };
 
    window.document.addEventListener('mouseup', listener);
    window.document.addEventListener('touchend', listener);
    // eslint-disable-next-line consistent-return
    return () => {
      window.document.removeEventListener('mouseup', listener);
      window.document.removeEventListener('touchend', listener);
    };
  }, [showMenu, childType]);
 
  useEffect(() => {
    Iif (ref.current && showMenu) {
      setSize(ref.current.getBoundingClientRect());
    }
  }, [showMenu]);
 
  const style = useMemo(() => {
    Eif (!size) {
      return undefined;
    }
    const availableHeight = window.innerHeight - size.bottom;
    return { top: size.height, maxHeight: availableHeight };
  }, [size]);
 
  return (
    <div
      className="dropdown-container"
      // TODO: This code has been commented out as part of https://www.ebi.ac.uk/panda/jira/browse/TRM-25862
      // Because Safari doesn't focus when clicking on a button: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#clicking_and_focus
      // a jira has been made https://www.ebi.ac.uk/panda/jira/browse/TRM-26188 to investigate and implement ways to deal with this.
      // Will leave the code here has a marker for that task.
      // onBlur={(e) =>
      //   setShowMenu(e.currentTarget.contains(e.relatedTarget as Node))
      // }
      onPointerEnter={openOnHover ? () => setShowMenu(true) : undefined}
      onPointerLeave={openOnHover ? () => setShowMenu(false) : undefined}
    >
      <Button
        className={cn('dropdown', className)}
        onClick={() => setShowMenu((showMenu) => !showMenu)}
        ref={ref}
        {...props}
      >
        {label}
      </Button>
      <div
        className={cn('dropdown-menu', {
          'dropdown-menu-open': showMenu,
        })}
        ref={dropdownRef}
        style={style}
      >
        {showMenu &&
          (typeof children === 'function' ? children(setShowMenu) : children)}
      </div>
    </div>
  );
};
 
type ControlledDropdownProps = {
  /**
   * Element always visible used to open and close the dropdown
   */
  visibleElement: ReactElement;
  /**
   * Whether the dropdown is open or closed
   */
  expanded: boolean;
};
 
export const ControlledDropdown = ({
  visibleElement,
  expanded,
  children,
  className,
  'aria-haspopup': ariaHaspopup,
  ...props
}: ControlledDropdownProps & HTMLAttributes<HTMLDivElement>) => (
  <div
    className={cn(className, 'dropdown')}
    {...props}
    aria-expanded={expanded}
    aria-haspopup={ariaHaspopup || true}
  >
    {/* Not sure why fragments and keys are needed, but otherwise gets the
    React key warnings messages and children are rendered as array... */}
    <Fragment key="visible">{visibleElement}</Fragment>
    <Fragment key="content">
      {expanded && <div className="dropdown__content">{children}</div>}
    </Fragment>
  </div>
);
 
type DropdownProps = {
  /**
   * Prop that, when it changes, will cause the dropdown to close
   */
  propChangeToClose?: unknown;
  /**
   * Render for element always visible used to open and close the dropdown
   */
  visibleElement: (onClick: () => unknown) => ReactElement;
  /**
   * Close if a clickable element within is clicked
   */
  children: ReactNode | ((closeDropdown: () => unknown) => ReactNode);
};
 
export const Dropdown = ({
  visibleElement,
  propChangeToClose,
  className,
  'aria-haspopup': ariaHaspopup,
  children,
  ...props
}: Omit<ControlledDropdownProps, 'expanded' | 'visibleElement'> &
  DropdownProps &
  Omit<HTMLAttributes<HTMLDivElement>, 'children'>) => {
  const [expanded, setExpanded] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
 
  const close = useCallback(() => setExpanded(false), []);
 
  // Effect in order to close the dropdown when the corresponding prop changes
  useEffect(() => {
    close();
  }, [close, propChangeToClose]);
 
  // effect to handle a click on anything closing the dropdown
  useEffect(() => {
    Eif (!expanded) {
      return;
    }
 
    const listener = (event: MouseEvent | TouchEvent) => {
      if (
        !ref.current ||
        (event.target && ref.current?.contains(event.target as Node))
      ) {
        return;
      }
      close();
    };
 
    window.document.addEventListener('mouseup', listener, { passive: true });
    window.document.addEventListener('touchend', listener, { passive: true });
    // eslint-disable-next-line consistent-return
    return () => {
      window.document.removeEventListener('mouseup', listener);
      window.document.removeEventListener('touchend', listener);
    };
  }, [close, expanded]);
 
  const handleClick = useCallback(
    () => setExpanded((expanded) => !expanded),
    []
  );
 
  return (
    <div
      className={cn(className, 'dropdown')}
      {...props}
      aria-expanded={expanded}
      aria-haspopup={ariaHaspopup || true}
      ref={ref}
    >
      {/* Not sure why fragments and keys are needed, but otherwise gets the
      React key warnings messages and children are rendered as array... */}
      <Fragment key="visible">{visibleElement(handleClick)}</Fragment>
      <Fragment key="content">
        {expanded && (
          <div className="dropdown__content">
            {typeof children === 'function' ? children(close) : children}
          </div>
        )}
      </Fragment>
    </div>
  );
};
 
export default DropdownButton;