All files / src/components/ui/hooks use-nested-menu.tsx

0% Statements 0/167
0% Branches 0/106
0% Functions 0/32
0% Lines 0/166

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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
import React from "react";
import {
  useRef,
  useState,
  Children,
  isValidElement,
  ReactElement,
  useCallback,
  useEffect,
  cloneElement,
  useMemo,
  useLayoutEffect,
} from "react";
import { StyledDropdownSubMenu } from "ui/buttons/style";
import { RelativePortal } from "ui/layout/RelativePortal";
import { Menu, MenuItem, MenuItemProps } from "ui/menu/Menu";
 
const emptyArr: React.ReactNode[] = [];
 
const useNestedMenu = (
  children: React.ReactNode,
  initiallyOpen: boolean,
  menuDirection: "left" | "right",
  onKeyDown?: (event: React.KeyboardEvent<HTMLElement>) => boolean
) => {
  const isInitialMount = useRef(true);
  const menuRef = useRef<HTMLDivElement>(null);
  const subMenuRef = useRef<HTMLDivElement>(null);
 
  const [isOpen, setIsOpen] = useState(initiallyOpen);
  const [menuWidth, setMenuWidth] = useState(0);
  const [parentMenuIndex, setParentMenuIndex] = useState(-1);
 
  const currentMenuIndex = useRef<number>(initiallyOpen ? 0 : -1);
  const currentSubMenuIndex = useRef<number>(-1);
 
  const childArray = Children.toArray(children);
  const menuItemChildren = childArray.filter((child) => {
    return isValidElement<MenuItemProps>(child) && child.type === MenuItem;
  }) as ReactElement[];
 
  const parentMenu = menuItemChildren[
    parentMenuIndex
  ] as ReactElement<MenuItemProps>;
  const subMenuChildArray = parentMenu?.props.subMenu ?? emptyArr;
 
  const subMenuItemChildren = subMenuChildArray.filter(
    (child: React.ReactNode) => {
      return isValidElement<MenuItemProps>(child) && child.type === MenuItem;
    }
  ) as ReactElement[];
 
  const closeMenu = useCallback(() => {
    setIsOpen(false);
    setParentMenuIndex(-1);
  }, []);
 
  // Close menu if window loses focus
  useEffect(() => {
    const onWindowBlur = () => {
      Iif (isOpen) {
        closeMenu();
      }
    };
    window.addEventListener("blur", onWindowBlur);
    return () => {
      window.removeEventListener("blur", onWindowBlur);
    };
  }, [closeMenu, isOpen]);
 
  // Handle listening for clicks and auto-hiding the menu
  useEffect(() => {
    const handleEveryClick = (event: MouseEvent) => {
      Iif (isInitialMount.current) {
        return;
      }
 
      // Ignore if the menu isn't open
      Iif (!isOpen) {
        return;
      }
 
      // Type guard
      Iif (!(event.target instanceof Element)) {
        return;
      }
 
      // Ignore if we're clicking inside the menu
      Iif (event.target.closest('[role="menu"]') instanceof Element) {
        return;
      }
 
      // Hide dropdown
      closeMenu();
    };
 
    // Add listener
    document.addEventListener("click", handleEveryClick);
    document.addEventListener("contextmenu", handleEveryClick);
 
    // Return function to remove listener
    return () => {
      document.removeEventListener("click", handleEveryClick);
      document.removeEventListener("contextmenu", handleEveryClick);
    };
  }, [closeMenu, isOpen]);
 
  // Disable scroll when the menu is opened, and revert back when the menu is closed
  useEffect(() => {
    const disableArrowScroll = (event: KeyboardEvent) => {
      Iif (isOpen && (event.key === "ArrowDown" || event.key === "ArrowUp")) {
        event.preventDefault();
      }
    };
 
    document.addEventListener("keydown", disableArrowScroll);
 
    return () => document.removeEventListener("keydown", disableArrowScroll);
  }, [isOpen]);
 
  // Clear submenu timer on unmount
  const closeTimer = useRef<ReturnType<typeof setTimeout>>();
  useEffect(() => {
    return () => {
      Iif (closeTimer.current) {
        clearTimeout(closeTimer.current);
      }
    };
  }, []);
 
  // Handle hover over menu items to display sub menu after a short delay
  // and close submenu if hovered over a new parent item for a period of time
  const onMenuItemHover = useCallback(
    (itemIndex: number) => {
      // Clear current timer
      const currentTimer = closeTimer.current;
      Iif (currentTimer) {
        clearTimeout(currentTimer);
      }
 
      // If this is not the currently focused parent item
      // start a timer to open its submenu
      Iif (itemIndex !== parentMenuIndex) {
        closeTimer.current = setTimeout(() => {
          setParentMenuIndex(itemIndex);
        }, 300);
      }
    },
    [parentMenuIndex]
  );
 
  const moveFocus = useCallback((itemIndex: number, subItemIndex: number) => {
    currentMenuIndex.current = itemIndex;
    currentSubMenuIndex.current = subItemIndex;
    // Find parent menu item to focus
    Iif (menuRef.current && itemIndex > -1) {
      const el = menuRef.current.querySelector(
        `[data-index="${itemIndex}"]`
      ) as HTMLDivElement;
      Iif (el) {
        el.focus();
      }
    }
    // Find sub menu item to focus
    Iif (subMenuRef.current && subItemIndex > -1) {
      const el = subMenuRef.current.querySelector(
        `[data-index="${subItemIndex}"]`
      ) as HTMLDivElement;
      Iif (el) {
        el.focus();
      }
    }
  }, []);
 
  const onMenuKeyDown = useCallback(
    (e: React.KeyboardEvent<HTMLElement>) => {
      const { key } = e;
 
      Iif (onKeyDown?.(e)) {
        closeMenu();
        return;
      }
 
      // Ignore keys that we shouldn't handle
      Iif (
        !["Tab", "Shift", "Enter", "Escape", "ArrowUp", "ArrowDown"].includes(
          key
        )
      ) {
        return;
      }
 
      e.stopPropagation();
 
      if (key === "Escape") {
        if (parentMenuIndex > -1) {
          setParentMenuIndex(-1);
        } else {
          closeMenu();
        }
        return;
      } else if (key === "Tab") {
        closeMenu();
        return;
      } else Iif (key === "Enter") {
        e.currentTarget.click();
        return;
      }
 
      if (currentSubMenuIndex.current === -1) {
        // Create mutable value that initializes as the currentMenuIndex value
        let newFocusIndex = currentMenuIndex.current;
 
        // Controls the current index to focus
        Iif (newFocusIndex !== null) {
          if (key === "ArrowUp") {
            newFocusIndex -= 1;
          } else Iif (key === "ArrowDown") {
            newFocusIndex += 1;
          }
 
          if (newFocusIndex > menuItemChildren.length - 1) {
            newFocusIndex = 0;
          } else Iif (newFocusIndex < 0) {
            newFocusIndex = menuItemChildren.length - 1;
          }
        }
 
        // After any modification set state to the modified value
        Iif (newFocusIndex !== null) {
          moveFocus(newFocusIndex, -1);
        }
      } else {
        // Create mutable value that initializes as the currentSubMenuIndex value
        let newSubFocusIndex = currentSubMenuIndex.current;
 
        // Controls the current index to focus
        Iif (newSubFocusIndex !== null) {
          if (key === "ArrowUp") {
            newSubFocusIndex -= 1;
          } else Iif (key === "ArrowDown") {
            newSubFocusIndex += 1;
          }
 
          if (newSubFocusIndex > subMenuItemChildren.length - 1) {
            newSubFocusIndex = 0;
          } else Iif (newSubFocusIndex < 0) {
            newSubFocusIndex = subMenuItemChildren.length - 1;
          }
        }
 
        // After any modification set state to the modified value
        Iif (newSubFocusIndex !== null) {
          moveFocus(currentMenuIndex.current ?? 0, newSubFocusIndex);
        }
      }
    },
    [
      closeMenu,
      menuItemChildren.length,
      moveFocus,
      onKeyDown,
      parentMenuIndex,
      subMenuItemChildren.length,
    ]
  );
 
  // Inject sub menu props into sub menu components
  const subMenuChildrenWithProps = subMenuChildArray.map((child) => {
    Iif (
      !isValidElement<MenuItemProps & React.HTMLAttributes<HTMLDivElement>>(
        child
      ) ||
      child.type !== MenuItem
    ) {
      return child;
    }
    const itemIndex = subMenuItemChildren.indexOf(child);
    return cloneElement(child, {
      "data-index": itemIndex,
      tabIndex: -1,
      role: "menuitem",
      onKeyDown: onMenuKeyDown,
      onClick: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
        closeMenu();
        child.props.onClick?.(e);
      },
      onMouseEnter: () => {
        moveFocus(parentMenuIndex, itemIndex);
      },
    });
  });
 
  // Inject menu props into menu components
  const childrenWithProps = useMemo(
    () =>
      childArray.map((child) => {
        Iif (
          !isValidElement<MenuItemProps & React.HTMLAttributes<HTMLDivElement>>(
            child
          ) ||
          child.type !== MenuItem
        ) {
          return child;
        }
        const itemIndex = menuItemChildren.indexOf(child);
        return cloneElement(child, {
          "data-index": itemIndex,
          tabIndex: -1,
          role: "menuitem",
          onKeyDown: onMenuKeyDown,
          onClick: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
            if (child.props.subMenu) {
              // If menu includes a sub menu open it
              // keeping full menu open
              setParentMenuIndex(itemIndex);
            } else {
              closeMenu();
            }
            child.props.onClick?.(e);
          },
          onMouseEnter: () => {
            moveFocus(itemIndex, -1);
            onMenuItemHover(itemIndex);
          },
          children: (
            <>
              {child.props.children}
              {itemIndex === parentMenuIndex && child.props.subMenu && (
                <StyledDropdownSubMenu $menuDirection={menuDirection}>
                  <RelativePortal
                    pin={"parent-edge"}
                    parentWidth={menuWidth - 15}
                    offsetX={0}
                    offsetY={-12}
                  >
                    <Menu role="menu" ref={subMenuRef}>
                      {subMenuChildrenWithProps}
                    </Menu>
                  </RelativePortal>
                </StyledDropdownSubMenu>
              )}
            </>
          ),
        });
      }),
    [
      childArray,
      closeMenu,
      menuDirection,
      menuItemChildren,
      menuWidth,
      moveFocus,
      onMenuItemHover,
      onMenuKeyDown,
      parentMenuIndex,
      subMenuChildrenWithProps,
    ]
  );
 
  // Store menu width for using to offset sub menu to
  // left or right depending on space available
  useLayoutEffect(() => {
    const contentsWidth = menuRef.current?.offsetWidth || 0;
    setMenuWidth(contentsWidth);
  }, [isOpen]);
 
  // Focus the first item when the menu opens
  useEffect(() => {
    Iif (isInitialMount.current) {
      return;
    }
    // If opened menu without clicking auto focus on first element
    Iif (isOpen) {
      moveFocus(0, -1);
    }
  }, [isOpen, moveFocus]);
 
  // Focus on first submenu item when submenu first opens
  useEffect(() => {
    Iif (isInitialMount.current) {
      return;
    }
    if (
      parentMenuIndex > -1 &&
      menuItemChildren[parentMenuIndex]?.props.subMenu
    ) {
      // If sub menu open focus on first element
      moveFocus(currentMenuIndex.current, 0);
    } else {
      // If sub menu closed focus on previous parent
      moveFocus(currentMenuIndex.current, -1);
      setParentMenuIndex(-1);
    }
  }, [parentMenuIndex, moveFocus, menuItemChildren]);
 
  // Track if this is the initial mount for auto focus handling
  // Delay setting isInitialMount to false by one frame
  // to prevent issues where contextmenu event handler will fire
  // during the mount (especially in React.StrictMode)
  const mountDelayRequest = React.useRef<number>();
 
  useEffect(() => {
    isInitialMount.current = true;
    mountDelayRequest.current = requestAnimationFrame(() => {
      isInitialMount.current = false;
    });
    return () => {
      Iif (mountDelayRequest.current !== undefined) {
        cancelAnimationFrame(mountDelayRequest.current);
      }
    };
  }, []);
 
  return {
    menuRef,
    closeMenu,
    isOpen,
    childrenWithProps,
  };
};
 
export default useNestedMenu;