| 1 |
import { forwardRef, useRef } from 'react'; |
| 2 |
import { Button, ButtonProps } from '../Button'; |
| 3 |
import { KeyTypes } from '../../helpers/constants'; |
| 4 |
import HelpIcon from '@patternfly/react-icons/dist/esm/icons/help-icon'; |
| 5 |
|
| 6 |
/** A help button to be passed to the FormGroup's labelHelp property. This should be wrapped or linked |
| 7 |
* to our Popover component. |
| 8 |
*/ |
| 9 |
export interface FormGroupLabelHelpProps extends ButtonProps { |
| 10 |
/** Adds an accessible name for the help button. */ |
| 11 |
'aria-label': string; |
| 12 |
/** Additional classes added to the help button. */ |
| 13 |
className?: string; |
| 14 |
/** @hide Forwarded ref */ |
| 15 |
innerRef?: React.Ref<HTMLSpanElement>; |
| 16 |
} |
| 17 |
|
| 18 |
const FormGroupLabelHelpBase: React.FunctionComponent<FormGroupLabelHelpProps> = ({ |
| 19 |
'aria-label': ariaLabel, |
| 20 |
className, |
| 21 |
innerRef, |
| 22 |
...props |
| 23 |
}) => { |
| 24 |
const ref = useRef<HTMLSpanElement>(null); |
| 25 |
const buttonRef = innerRef || ref; |
| 26 |
|
| 27 |
const isMutableRef = (ref: React.Ref<HTMLSpanElement>): ref is React.MutableRefObject<HTMLSpanElement> => |
| 28 |
typeof ref === 'object' && ref !== null && 'current' in ref && ref.current !== undefined; |
| 29 |
|
| 30 |
const handleKeyDown = (event: React.KeyboardEvent<HTMLSpanElement>) => { |
| 31 |
if ([KeyTypes.Space, KeyTypes.Enter].includes(event.key) && isMutableRef(buttonRef) && buttonRef.current) { |
| 32 |
event.preventDefault(); |
| 33 |
buttonRef.current.click(); |
| 34 |
} |
| 35 |
}; |
| 36 |
|
| 37 |
return ( |
| 38 |
<Button |
| 39 |
component="span" |
| 40 |
isInline |
| 41 |
ref={buttonRef} |
| 42 |
onKeyDown={handleKeyDown} |
| 43 |
aria-label={ariaLabel} |
| 44 |
className={className} |
| 45 |
variant="plain" |
| 46 |
hasNoPadding |
| 47 |
{...props} |
| 48 |
icon={<HelpIcon />} |
| 49 |
/> |
| 50 |
); |
| 51 |
}; |
| 52 |
|
| 53 |
export const FormGroupLabelHelp = forwardRef((props: FormGroupLabelHelpProps, ref: React.Ref<any>) => ( |
| 54 |
<FormGroupLabelHelpBase innerRef={ref} {...props} /> |
| 55 |
)); |
| 56 |
|
| 57 |
FormGroupLabelHelp.displayName = 'FormGroupLabelHelp'; |