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 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 | 1x 1x 1x 1x 1x 1x 1x 1x | import React, {
Children,
cloneElement,
CSSProperties,
FC,
isValidElement,
ReactElement,
ReactNode,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { PinDirection, RelativePortal } from "ui/layout/RelativePortal";
import { CaretDownIcon } from "ui/icons/Icons";
import { Menu, MenuItem, MenuItemProps } from "ui/menu/Menu";
import { ButtonProps } from "./Button";
import {
StyledButton,
StyledDropdownArrow,
StyledDropdownButton,
StyledDropdownMenu,
StyledDropdownSubMenu,
StyledInlineDropdownWrapper,
} from "./style";
interface DropdownButtonProps {
readonly label?: ReactNode;
readonly title?: string;
readonly children?: ReactNode;
readonly showArrow?: boolean;
readonly menuDirection?: "left" | "right";
readonly openUpwards?: boolean;
readonly offsetX?: number;
readonly offsetY?: number;
readonly style?: CSSProperties;
readonly onKeyDown?: (event: React.KeyboardEvent<HTMLElement>) => boolean;
readonly onMouseDown?: (
event: React.MouseEvent<HTMLButtonElement, MouseEvent>,
) => void;
}
const emptyArr: React.ReactNode[] = [];
export const DropdownButton: FC<DropdownButtonProps & ButtonProps> = React.memo(
({
id,
size,
variant = "normal",
label,
title,
children,
showArrow = true,
menuDirection = "left",
openUpwards,
offsetX,
offsetY,
active,
style,
onKeyDown,
onMouseDown,
}) => {
const isInitialMount = useRef(true);
const buttonRef = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
const subMenuRef = useRef<HTMLDivElement>(null);
const clickedOpen = useRef(false);
const [isOpen, setIsOpen] = useState(false);
const [menuWidth, setMenuWidth] = useState(0);
const [parentMenuIndex, setParentMenuIndex] = useState(-1);
const currentMenuIndex = useRef<number>(-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(() => {
// This function is designed to handle every click
const handleEveryClick = (event: MouseEvent) => {
// Ignore if the menu isn't open
Iif (!isOpen) {
return;
}
// Make this happen asynchronously
setTimeout(() => {
// 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();
}, 10);
};
// Add listener
document.addEventListener("click", handleEveryClick);
// Return function to remove listener
return () => document.removeEventListener("click", 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();
buttonRef.current?.focus();
}
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,
],
);
// Handle keyboard events when button has focus
const onButtonKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLButtonElement>) => {
// If keydown handler has been provided and it returns true
// override default keyboard handling and close any open menus
if (onKeyDown?.(e)) {
closeMenu();
} else {
const { key } = e;
// Ignore any keys not handled by button
Iif (!["Enter", " ", "Tab", "ArrowDown", "Escape"].includes(key)) {
return;
}
if (
(key === "Tab" || key === "ArrowDown") &&
clickedOpen.current &&
isOpen
) {
// Handle the case when the button was clicked to open menu
// Tab or ArrowDown should focus on first item
e.preventDefault();
moveFocus(0, -1);
} else if (key === "Escape") {
// Pressing escape on button focus will always close the menu
closeMenu();
} else Iif (key !== "Tab") {
e.preventDefault();
setIsOpen(true);
setParentMenuIndex(-1);
}
}
},
[closeMenu, isOpen, moveFocus, onKeyDown],
);
// When clicking button toggle open state
// and close any sub menus
const onButtonClick = useCallback(
(_e: React.MouseEvent) => {
clickedOpen.current = !isOpen;
requestAnimationFrame(() => {
setIsOpen(!isOpen);
setParentMenuIndex(-1);
});
},
[isOpen, setIsOpen],
);
// 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
if (isOpen && !clickedOpen.current) {
moveFocus(0, -1);
} else Iif (!isOpen) {
clickedOpen.current = false;
}
}, [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
useEffect(() => {
isInitialMount.current = false;
}, []);
const menuPinDirection = `${openUpwards ? "bottom" : "top"}-${
menuDirection === "left" ? "left" : "right"
}` as PinDirection;
const menu = useMemo(() => {
return (
isOpen && (
<StyledDropdownMenu $menuDirection={menuDirection}>
<RelativePortal
pin={menuPinDirection}
offsetX={offsetX}
offsetY={offsetY}
>
<Menu role="menu" ref={menuRef}>
{childrenWithProps}
</Menu>
</RelativePortal>
</StyledDropdownMenu>
)
);
}, [
childrenWithProps,
isOpen,
menuDirection,
menuPinDirection,
offsetX,
offsetY,
]);
return (
<StyledDropdownButton>
{openUpwards && menu}
<StyledButton
id={id}
title={title}
$size={size}
$variant={variant}
$active={active}
data-is-active={active}
onKeyDown={onButtonKeyDown}
onClick={onButtonClick}
tabIndex={0}
ref={buttonRef}
role={"button"}
type="button"
aria-haspopup={true}
aria-expanded={isOpen}
onMouseDown={onMouseDown}
style={{
...style,
...(showArrow && !label
? {
paddingLeft: 0,
paddingRight: 5,
}
: {}),
}}
>
{label}
{showArrow && (
<StyledDropdownArrow $openUpwards={openUpwards}>
<CaretDownIcon />
</StyledDropdownArrow>
)}
</StyledButton>
{!openUpwards && menu}
</StyledDropdownButton>
);
},
);
interface InlineDropdownWrapperProps {
children: ReactNode;
}
export const InlineDropdownWrapper = ({
children,
}: InlineDropdownWrapperProps) => (
<StyledInlineDropdownWrapper children={children} />
);
|