import * as React from 'react'; import { useNavigate } from 'react-router-dom'; import { DropdownItemProps, MenuItem, Tooltip, MenuItemProps } from '@patternfly/react-core'; import isFunction from 'lodash/isFunction'; import isObject from 'lodash/isObject'; import AnalyticsButton from '../../../components/AnalyticsButton/AnalyticsButton'; import { Action } from './types'; export type ActionMenuItemProps = { action: Action; component?: React.ComponentType>; autoFocus?: boolean; onClick?: () => void; onEscape?: () => void; }; export const KEY_CODES = { ARROW_UP: 38, ARROW_DOWN: 40, ESCAPE_KEY: 27, TAB: 9, ENTER: 13, SPACE: 32, }; const ActionItem: React.FC< React.PropsWithChildren > = ({ action, onClick, onEscape, autoFocus, isAllowed, component }) => { const { label, icon, disabled, cta } = action; const { href, external } = cta as { href: string; external?: boolean }; const isDisabled = !isAllowed || disabled; const navigate = useNavigate(); const handleClick = React.useCallback( (event: MouseEvent) => { event.preventDefault(); if (isFunction(cta)) { cta(); } else if (isObject(cta)) { if (!cta.external) { navigate(cta.href); } } onClick && onClick(); }, [cta, navigate, onClick], ); const handleKeyDown = (event: KeyboardEvent) => { if (event.keyCode === KEY_CODES.ESCAPE_KEY) { onEscape && onEscape(); } if (event.keyCode === KEY_CODES.ENTER) { handleClick(event as unknown as MouseEvent); } }; const Component = component ?? MenuItem; const props = { icon, autoFocus, onClick: handleClick, 'data-test': label, }; const extraProps = { onKeyDown: handleKeyDown, ...(external ? { to: href, isExternalLink: external } : {}), }; return ( // @ts-expect-error MenuItemProps and DropdownItemProps `component` prop type is mismatching ( )} > {label} ); }; const ActionMenuItem: React.FC> = (props) => { const { action } = props; const item = ; return action.tooltip ? ( {item} ) : ( item ); }; export default ActionMenuItem;