| 1 |
import { createContext, forwardRef, useContext, useEffect, useRef, useState } from 'react'; |
| 2 |
import styles from '@patternfly/react-styles/css/components/Menu/menu'; |
| 3 |
import { css } from '@patternfly/react-styles'; |
| 4 |
import topOffset from '@patternfly/react-tokens/dist/esm/c_menu_m_flyout__menu_top_offset'; |
| 5 |
import rightOffset from '@patternfly/react-tokens/dist/esm/c_menu_m_flyout__menu_m_left_right_offset'; |
| 6 |
import leftOffset from '@patternfly/react-tokens/dist/esm/c_menu_m_flyout__menu_left_offset'; |
| 7 |
import RhMicronsExternalLinkIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-external-link-icon'; |
| 8 |
import RhMicronsCaretLeftIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-caret-left-icon'; |
| 9 |
import RhMicronsCaretRightIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-caret-right-icon'; |
| 10 |
import CheckIcon from '@patternfly/react-icons/dist/esm/icons/check-icon'; |
| 11 |
import { Checkbox } from '../Checkbox'; |
| 12 |
import { MenuContext, MenuItemContext } from './MenuContext'; |
| 13 |
import { MenuItemAction } from './MenuItemAction'; |
| 14 |
import { Tooltip, TooltipProps } from '../Tooltip'; |
| 15 |
import { canUseDOM } from '../../helpers/util'; |
| 16 |
import { useIsomorphicLayoutEffect } from '../../helpers/useIsomorphicLayout'; |
| 17 |
import { useSSRSafeId } from '../../helpers'; |
| 18 |
|
| 19 |
export interface MenuItemProps extends Omit<React.HTMLProps<HTMLLIElement>, 'onClick'> { |
| 20 |
/** Content rendered inside the menu list item. */ |
| 21 |
children?: React.ReactNode; |
| 22 |
/** Additional classes added to the menu list item */ |
| 23 |
className?: string; |
| 24 |
/** Identifies the component in the Menu onSelect or onActionClick callback */ |
| 25 |
itemId?: any; |
| 26 |
/** Target navigation link. Should not be used if the flyout prop is defined. */ |
| 27 |
to?: string; |
| 28 |
/** Navigation link target. Only set when the to property is present. If isExternalLink is also passed in, this property will be set to "_blank". */ |
| 29 |
target?: string; |
| 30 |
/** Navigation link relationship. Only set when the to property is present. */ |
| 31 |
rel?: string; |
| 32 |
/** Navigation link download. Only set when the to property is present. */ |
| 33 |
download?: string; |
| 34 |
/** Flag indicating the item has a checkbox */ |
| 35 |
hasCheckbox?: boolean; |
| 36 |
/** Flag indicating whether the item is active */ |
| 37 |
isActive?: boolean; |
| 38 |
/** Flag indicating if the item is favorited */ |
| 39 |
isFavorited?: boolean; |
| 40 |
/** Flag indicating if the item causes a load */ |
| 41 |
isLoadButton?: boolean; |
| 42 |
/** Flag indicating a loading state */ |
| 43 |
isLoading?: boolean; |
| 44 |
/** Callback for item click */ |
| 45 |
onClick?: (event?: any) => void; |
| 46 |
/** Component used to render the menu item */ |
| 47 |
component?: React.ElementType<any> | React.ComponentType<any>; |
| 48 |
/** Render item as disabled option */ |
| 49 |
isDisabled?: boolean; |
| 50 |
/** Render item as aria-disabled option */ |
| 51 |
isAriaDisabled?: boolean; |
| 52 |
/** Props for adding a tooltip to a menu item */ |
| 53 |
tooltipProps?: TooltipProps; |
| 54 |
/** Render item with icon */ |
| 55 |
icon?: React.ReactNode; |
| 56 |
/** Render item with one or more actions */ |
| 57 |
actions?: React.ReactNode; |
| 58 |
/** Description of the menu item */ |
| 59 |
description?: React.ReactNode; |
| 60 |
/** Render an external link icon on focus or hover, and set the link's |
| 61 |
* "target" attribute to a value of "_blank". |
| 62 |
*/ |
| 63 |
isExternalLink?: boolean; |
| 64 |
/** Flag indicating if the option is selected */ |
| 65 |
isSelected?: boolean; |
| 66 |
/** Flag indicating the item is focused */ |
| 67 |
isFocused?: boolean; |
| 68 |
/** Flag indicating the item is in danger state */ |
| 69 |
isDanger?: boolean; |
| 70 |
/** Flyout menu. Should not be used if the to prop is defined. */ |
| 71 |
flyoutMenu?: React.ReactElement<any>; |
| 72 |
/** Callback function when mouse leaves trigger */ |
| 73 |
onShowFlyout?: (event?: any) => void; |
| 74 |
/** Drilldown menu of the item. Should be a Menu or DrilldownMenu type. */ |
| 75 |
drilldownMenu?: React.ReactNode | (() => React.ReactNode); |
| 76 |
/** Sub menu direction */ |
| 77 |
direction?: 'down' | 'up'; |
| 78 |
/** True if item is on current selection path */ |
| 79 |
isOnPath?: boolean; |
| 80 |
/** Adds an accessible name to the menu item. */ |
| 81 |
'aria-label'?: string; |
| 82 |
/** @hide Forwarded ref */ |
| 83 |
innerRef?: React.Ref<HTMLAnchorElement | HTMLButtonElement>; |
| 84 |
/** Sets the id attribute on the menu item component. */ |
| 85 |
id?: string; |
| 86 |
} |
| 87 |
|
| 88 |
const FlyoutContext = createContext({ |
| 89 |
direction: 'right' as 'left' | 'right' |
| 90 |
}); |
| 91 |
|
| 92 |
const MenuItemBase: React.FunctionComponent<MenuItemProps> = ({ |
| 93 |
children, |
| 94 |
className, |
| 95 |
itemId = null, |
| 96 |
to, |
| 97 |
hasCheckbox = false, |
| 98 |
isActive = null, |
| 99 |
isFavorited = null, |
| 100 |
isLoadButton = false, |
| 101 |
isLoading = false, |
| 102 |
flyoutMenu, |
| 103 |
direction, |
| 104 |
description = null as string, |
| 105 |
onClick = () => {}, |
| 106 |
component = 'button', |
| 107 |
isDisabled = false, |
| 108 |
isAriaDisabled = false, |
| 109 |
isExternalLink = false, |
| 110 |
isSelected = null, |
| 111 |
isFocused, |
| 112 |
isDanger = false, |
| 113 |
icon, |
| 114 |
actions, |
| 115 |
onShowFlyout, |
| 116 |
drilldownMenu, |
| 117 |
isOnPath, |
| 118 |
innerRef, |
| 119 |
id, |
| 120 |
'aria-label': ariaLabel, |
| 121 |
tooltipProps, |
| 122 |
rel, |
| 123 |
target, |
| 124 |
download, |
| 125 |
...props |
| 126 |
}: MenuItemProps) => { |
| 127 |
const { |
| 128 |
menuId, |
| 129 |
parentMenu, |
| 130 |
onSelect, |
| 131 |
onActionClick, |
| 132 |
activeItemId, |
| 133 |
selected, |
| 134 |
drilldownItemPath, |
| 135 |
onDrillIn, |
| 136 |
onDrillOut, |
| 137 |
flyoutRef, |
| 138 |
setFlyoutRef, |
| 139 |
disableHover, |
| 140 |
role: menuRole |
| 141 |
} = useContext(MenuContext); |
| 142 |
let Component = (to ? 'a' : component) as any; |
| 143 |
if (hasCheckbox && !to) { |
| 144 |
Component = 'label' as any; |
| 145 |
} |
| 146 |
const [flyoutTarget, setFlyoutTarget] = useState(null); |
| 147 |
const flyoutContext = useContext(FlyoutContext); |
| 148 |
const [flyoutXDirection, setFlyoutXDirection] = useState(flyoutContext.direction); |
| 149 |
const ref = useRef<HTMLLIElement>(undefined); |
| 150 |
const privateRef = useRef(undefined); |
| 151 |
const innerComponentRef = innerRef || privateRef; |
| 152 |
const flyoutVisible = ref === flyoutRef; |
| 153 |
|
| 154 |
const randomId = useSSRSafeId(); |
| 155 |
const hasFlyout = flyoutMenu !== undefined; |
| 156 |
const showFlyout = (show: boolean) => { |
| 157 |
if (!flyoutVisible && show) { |
| 158 |
setFlyoutRef(ref); |
| 159 |
} else if (flyoutVisible && !show) { |
| 160 |
setFlyoutRef(null); |
| 161 |
} |
| 162 |
onShowFlyout && show && onShowFlyout(); |
| 163 |
}; |
| 164 |
|
| 165 |
useIsomorphicLayoutEffect(() => { |
| 166 |
if (hasFlyout && ref.current && canUseDOM) { |
| 167 |
const flyoutMenu = ref.current.lastElementChild as HTMLElement; |
| 168 |
if (flyoutMenu && flyoutMenu.classList.contains(styles.menu)) { |
| 169 |
const origin = ref.current.getClientRects()[0]; |
| 170 |
const rect = flyoutMenu.getClientRects()[0]; |
| 171 |
if (origin && rect) { |
| 172 |
const spaceLeftLeft = origin.x - rect.width; |
| 173 |
const spaceLeftRight = window.innerWidth - origin.x - origin.width - rect.width; |
| 174 |
let xDir = flyoutXDirection as 'left' | 'right' | 'none'; |
| 175 |
if (spaceLeftRight < 0 && xDir !== 'left') { |
| 176 |
setFlyoutXDirection('left'); |
| 177 |
xDir = 'left'; |
| 178 |
} else if (spaceLeftLeft < 0 && xDir !== 'right') { |
| 179 |
setFlyoutXDirection('right'); |
| 180 |
xDir = 'right'; |
| 181 |
} |
| 182 |
let xOffset = 0; |
| 183 |
if (spaceLeftLeft < 0 && spaceLeftRight < 0) { |
| 184 |
xOffset = xDir === 'right' ? -spaceLeftRight : -spaceLeftLeft; |
| 185 |
} |
| 186 |
if (xDir === 'left') { |
| 187 |
flyoutMenu.classList.add(styles.modifiers.left); |
| 188 |
flyoutMenu.style.setProperty(rightOffset.name, `-${xOffset}px`); |
| 189 |
} else { |
| 190 |
flyoutMenu.style.setProperty(leftOffset.name, `-${xOffset}px`); |
| 191 |
} |
| 192 |
|
| 193 |
const spaceLeftBot = window.innerHeight - origin.y - rect.height; |
| 194 |
const spaceLeftTop = window.innerHeight - rect.height; |
| 195 |
if (spaceLeftTop < 0 && spaceLeftBot < 0) { |
| 196 |
// working idea: page can usually scroll down, but not up |
| 197 |
// TODO: proper scroll buttons |
| 198 |
} else if (spaceLeftBot < 0) { |
| 199 |
flyoutMenu.style.setProperty(topOffset.name, `${spaceLeftBot}px`); |
| 200 |
} |
| 201 |
} |
| 202 |
} |
| 203 |
} |
| 204 |
}, [flyoutVisible, flyoutMenu]); |
| 205 |
|
| 206 |
useEffect(() => { |
| 207 |
setFlyoutXDirection(flyoutContext.direction); |
| 208 |
}, [flyoutContext]); |
| 209 |
|
| 210 |
useEffect(() => { |
| 211 |
if (flyoutTarget) { |
| 212 |
if (flyoutVisible) { |
| 213 |
const flyoutMenu = (flyoutTarget as HTMLElement).nextElementSibling; |
| 214 |
const flyoutItems = Array.from(flyoutMenu?.getElementsByTagName('UL')[0]?.children || []).filter( |
| 215 |
(el) => !(el.classList.contains('pf-m-disabled') || el.classList.contains(styles.divider)) |
| 216 |
); |
| 217 |
(flyoutItems[0]?.firstChild as HTMLElement)?.focus(); |
| 218 |
} else { |
| 219 |
flyoutTarget.focus(); |
| 220 |
} |
| 221 |
} |
| 222 |
}, [flyoutVisible, flyoutTarget]); |
| 223 |
|
| 224 |
const handleFlyout = (event: React.KeyboardEvent | React.MouseEvent) => { |
| 225 |
const key = (event as React.KeyboardEvent).key; |
| 226 |
const target = event.target; |
| 227 |
const type = event.type; |
| 228 |
|
| 229 |
if (key === ' ' || key === 'Enter' || key === 'ArrowRight' || type === 'click') { |
| 230 |
event.stopPropagation(); |
| 231 |
event.preventDefault(); |
| 232 |
if (!flyoutVisible) { |
| 233 |
showFlyout(true); |
| 234 |
setFlyoutTarget(target as HTMLElement); |
| 235 |
} |
| 236 |
} |
| 237 |
|
| 238 |
if (key === 'Escape' || key === 'ArrowLeft') { |
| 239 |
if (flyoutVisible) { |
| 240 |
event.stopPropagation(); |
| 241 |
showFlyout(false); |
| 242 |
} |
| 243 |
} |
| 244 |
}; |
| 245 |
|
| 246 |
const onItemSelect = (event: any, onSelect: any) => { |
| 247 |
if (!isAriaDisabled) { |
| 248 |
// Trigger callback for Menu onSelect |
| 249 |
onSelect && onSelect(event, itemId); |
| 250 |
// Trigger callback for item onClick |
| 251 |
onClick && onClick(event); |
| 252 |
} |
| 253 |
}; |
| 254 |
const _isOnPath = (isOnPath && isOnPath) || (drilldownItemPath && drilldownItemPath.includes(itemId)) || false; |
| 255 |
let drill: (event: React.KeyboardEvent | React.MouseEvent) => void; |
| 256 |
if (direction) { |
| 257 |
if (direction === 'down') { |
| 258 |
drill = (event) => |
| 259 |
onDrillIn && |
| 260 |
onDrillIn( |
| 261 |
event, |
| 262 |
menuId, |
| 263 |
typeof drilldownMenu === 'function' |
| 264 |
? (drilldownMenu() as any).props.id |
| 265 |
: (drilldownMenu as React.ReactElement<any>).props.id, |
| 266 |
itemId |
| 267 |
); |
| 268 |
} else { |
| 269 |
drill = (event) => onDrillOut && onDrillOut(event, parentMenu, itemId); |
| 270 |
} |
| 271 |
} |
| 272 |
let additionalProps = {} as any; |
| 273 |
if (Component === 'a') { |
| 274 |
additionalProps = { |
| 275 |
href: to, |
| 276 |
'aria-disabled': isDisabled || isAriaDisabled ? true : null, |
| 277 |
// prevent invalid 'disabled' attribute on <a> tags |
| 278 |
disabled: null, |
| 279 |
target: isExternalLink ? '_blank' : target, |
| 280 |
rel, |
| 281 |
download |
| 282 |
}; |
| 283 |
} else if (Component === 'button') { |
| 284 |
additionalProps = { |
| 285 |
type: 'button', |
| 286 |
'aria-disabled': isAriaDisabled ? true : null |
| 287 |
}; |
| 288 |
} |
| 289 |
|
| 290 |
if (isOnPath) { |
| 291 |
additionalProps['aria-expanded'] = true; |
| 292 |
} else if (hasFlyout) { |
| 293 |
additionalProps['aria-haspopup'] = 'menu'; |
| 294 |
additionalProps['aria-expanded'] = flyoutVisible; |
| 295 |
} |
| 296 |
const getAriaCurrent = () => { |
| 297 |
if (isActive !== null) { |
| 298 |
if (isActive) { |
| 299 |
return 'page'; |
| 300 |
} else { |
| 301 |
return null; |
| 302 |
} |
| 303 |
} else if (itemId !== null && activeItemId !== null) { |
| 304 |
return itemId === activeItemId; |
| 305 |
} |
| 306 |
return null; |
| 307 |
}; |
| 308 |
const getIsSelected = () => { |
| 309 |
if (isSelected !== null) { |
| 310 |
return isSelected; |
| 311 |
} else if (selected !== null && itemId !== null) { |
| 312 |
return (Array.isArray(selected) && selected.includes(itemId)) || itemId === selected; |
| 313 |
} |
| 314 |
return false; |
| 315 |
}; |
| 316 |
const onMouseOver = () => { |
| 317 |
if (disableHover) { |
| 318 |
return; |
| 319 |
} |
| 320 |
if (hasFlyout) { |
| 321 |
showFlyout(true); |
| 322 |
} else { |
| 323 |
setFlyoutRef(null); |
| 324 |
} |
| 325 |
}; |
| 326 |
|
| 327 |
useEffect(() => { |
| 328 |
if (isFocused && ref.current) { |
| 329 |
const itemEl = ref.current; |
| 330 |
const parentListEl = itemEl.parentElement; |
| 331 |
|
| 332 |
if (parentListEl) { |
| 333 |
const isAboveTop = itemEl.offsetTop - parentListEl.offsetTop < parentListEl.scrollTop; |
| 334 |
const isBelowBottom = itemEl.offsetTop - parentListEl.offsetTop + itemEl.clientHeight; |
| 335 |
|
| 336 |
if (isAboveTop || isBelowBottom) { |
| 337 |
itemEl.scrollIntoView({ behavior: 'auto', block: 'nearest' }); |
| 338 |
} |
| 339 |
} |
| 340 |
} |
| 341 |
}, [isFocused]); |
| 342 |
|
| 343 |
const isSelectMenu = menuRole === 'listbox'; |
| 344 |
|
| 345 |
const renderItem = ( |
| 346 |
<> |
| 347 |
<Component |
| 348 |
id={id} |
| 349 |
tabIndex={-1} |
| 350 |
className={css(styles.menuItem, getIsSelected() && !hasCheckbox && styles.modifiers.selected, className)} |
| 351 |
aria-current={getAriaCurrent()} |
| 352 |
{...(!hasCheckbox && { disabled: isDisabled, 'aria-label': ariaLabel })} |
| 353 |
{...(!hasCheckbox && !flyoutMenu && { role: isSelectMenu ? 'option' : 'menuitem' })} |
| 354 |
{...(!hasCheckbox && !flyoutMenu && isSelectMenu && { 'aria-selected': getIsSelected() })} |
| 355 |
ref={innerComponentRef} |
| 356 |
{...(!hasCheckbox && { |
| 357 |
onClick: (event: React.KeyboardEvent | React.MouseEvent) => { |
| 358 |
if (!isAriaDisabled) { |
| 359 |
onItemSelect(event, onSelect); |
| 360 |
drill && drill(event); |
| 361 |
flyoutMenu && handleFlyout(event); |
| 362 |
} else { |
| 363 |
event.preventDefault(); |
| 364 |
} |
| 365 |
} |
| 366 |
})} |
| 367 |
{...(hasCheckbox && { htmlFor: randomId })} |
| 368 |
{...additionalProps} |
| 369 |
> |
| 370 |
<span className={css(styles.menuItemMain)}> |
| 371 |
{direction === 'up' && ( |
| 372 |
<span className={css(styles.menuItemToggleIcon)}> |
| 373 |
<RhMicronsCaretLeftIcon /> |
| 374 |
</span> |
| 375 |
)} |
| 376 |
{icon && <span className={css(styles.menuItemIcon)}>{icon}</span>} |
| 377 |
{hasCheckbox && ( |
| 378 |
<span className={css(styles.menuItemCheck)}> |
| 379 |
<Checkbox |
| 380 |
id={randomId} |
| 381 |
component="span" |
| 382 |
isChecked={isSelected || false} |
| 383 |
onChange={(event) => onItemSelect(event, onSelect)} |
| 384 |
isDisabled={isDisabled} |
| 385 |
aria-disabled={isAriaDisabled} |
| 386 |
/> |
| 387 |
</span> |
| 388 |
)} |
| 389 |
<span className={css(styles.menuItemText)}>{children}</span> |
| 390 |
{isExternalLink && ( |
| 391 |
<span className={css(styles.menuItemExternalIcon)}> |
| 392 |
<RhMicronsExternalLinkIcon /> |
| 393 |
</span> |
| 394 |
)} |
| 395 |
{(flyoutMenu || direction === 'down') && ( |
| 396 |
<span className={css(styles.menuItemToggleIcon)}> |
| 397 |
<RhMicronsCaretRightIcon /> |
| 398 |
</span> |
| 399 |
)} |
| 400 |
{getIsSelected() && ( |
| 401 |
<span className={css(styles.menuItemSelectIcon)}> |
| 402 |
<CheckIcon /> |
| 403 |
</span> |
| 404 |
)} |
| 405 |
</span> |
| 406 |
{description && direction !== 'up' && ( |
| 407 |
<span className={css(styles.menuItemDescription)}> |
| 408 |
<span>{description}</span> |
| 409 |
</span> |
| 410 |
)} |
| 411 |
</Component> |
| 412 |
{flyoutVisible && ( |
| 413 |
<MenuContext.Provider value={{ disableHover }}> |
| 414 |
<FlyoutContext.Provider value={{ direction: flyoutXDirection }}>{flyoutMenu}</FlyoutContext.Provider> |
| 415 |
</MenuContext.Provider> |
| 416 |
)} |
| 417 |
{typeof drilldownMenu === 'function' ? drilldownMenu() : drilldownMenu} |
| 418 |
<MenuItemContext.Provider value={{ itemId, isDisabled }}> |
| 419 |
{actions} |
| 420 |
{isFavorited !== null && ( |
| 421 |
<MenuItemAction |
| 422 |
icon="favorites" |
| 423 |
isFavorited={isFavorited} |
| 424 |
aria-label={isFavorited ? 'starred' : 'not starred'} |
| 425 |
onClick={(event) => onActionClick(event, itemId)} |
| 426 |
tabIndex={-1} |
| 427 |
actionId="fav" |
| 428 |
/> |
| 429 |
)} |
| 430 |
</MenuItemContext.Provider> |
| 431 |
</> |
| 432 |
); |
| 433 |
|
| 434 |
return ( |
| 435 |
<> |
| 436 |
<li |
| 437 |
className={css( |
| 438 |
styles.menuListItem, |
| 439 |
isDisabled && styles.modifiers.disabled, |
| 440 |
isAriaDisabled && styles.modifiers.ariaDisabled, |
| 441 |
_isOnPath && styles.modifiers.currentPath, |
| 442 |
isLoadButton && styles.modifiers.load, |
| 443 |
isLoading && styles.modifiers.loading, |
| 444 |
isFocused && 'pf-m-focus', |
| 445 |
isDanger && styles.modifiers.danger, |
| 446 |
className |
| 447 |
)} |
| 448 |
onMouseOver={() => { |
| 449 |
if (!isAriaDisabled) { |
| 450 |
onMouseOver(); |
| 451 |
} |
| 452 |
}} |
| 453 |
{...(flyoutMenu && !isAriaDisabled && { onKeyDown: handleFlyout })} |
| 454 |
ref={ref} |
| 455 |
role={!hasCheckbox ? 'none' : 'menuitem'} |
| 456 |
{...(hasCheckbox && { 'aria-label': ariaLabel })} |
| 457 |
{...props} |
| 458 |
> |
| 459 |
{renderItem} |
| 460 |
</li> |
| 461 |
{tooltipProps && <Tooltip {...tooltipProps} triggerRef={innerComponentRef as any} />} |
| 462 |
</> |
| 463 |
); |
| 464 |
}; |
| 465 |
|
| 466 |
export const MenuItem = forwardRef((props: MenuItemProps, ref: React.Ref<any>) => ( |
| 467 |
<MenuItemBase {...props} innerRef={ref} /> |
| 468 |
)); |
| 469 |
|
| 470 |
MenuItem.displayName = 'MenuItem'; |