| 1 |
import { css } from '@patternfly/react-styles'; |
| 2 |
import styles from '@patternfly/react-styles/css/components/ToggleGroup/toggle-group'; |
| 3 |
import { ToggleGroupItemVariant, ToggleGroupItemElement } from './ToggleGroupItemElement'; |
| 4 |
|
| 5 |
export interface ToggleGroupItemProps extends Omit<React.HTMLProps<HTMLDivElement>, 'onChange'> { |
| 6 |
/** Text rendered inside the toggle group item */ |
| 7 |
text?: React.ReactNode; |
| 8 |
/** Icon rendered inside the toggle group item */ |
| 9 |
icon?: React.ReactNode; |
| 10 |
/** Sets position of the icon when text is also passed in */ |
| 11 |
iconPosition?: 'start' | 'end'; |
| 12 |
/** Additional classes added to the toggle group item */ |
| 13 |
className?: string; |
| 14 |
/** Flag indicating if the toggle group item is disabled */ |
| 15 |
isDisabled?: boolean; |
| 16 |
/** Flag indicating if the toggle group item is selected */ |
| 17 |
isSelected?: boolean; |
| 18 |
/** required when icon is used with no supporting text */ |
| 19 |
'aria-label'?: string; |
| 20 |
/** Optional id for the button within the toggle group item */ |
| 21 |
buttonId?: string; |
| 22 |
/** A callback for when the toggle group item selection changes. */ |
| 23 |
onChange?: (event: React.MouseEvent<any> | React.KeyboardEvent | MouseEvent, selected: boolean) => void; |
| 24 |
} |
| 25 |
|
| 26 |
export const ToggleGroupItem: React.FunctionComponent<ToggleGroupItemProps> = ({ |
| 27 |
text, |
| 28 |
icon, |
| 29 |
iconPosition = 'start', |
| 30 |
className, |
| 31 |
isDisabled = false, |
| 32 |
isSelected = false, |
| 33 |
'aria-label': ariaLabel, |
| 34 |
onChange = () => {}, |
| 35 |
buttonId, |
| 36 |
...props |
| 37 |
}: ToggleGroupItemProps) => { |
| 38 |
const handleChange = (event: any): void => { |
| 39 |
onChange(event, !isSelected); |
| 40 |
}; |
| 41 |
|
| 42 |
if (!ariaLabel && icon && !text) { |
| 43 |
/* eslint-disable no-console */ |
| 44 |
console.warn('An accessible aria-label is required when using the toggle group item icon variant.'); |
| 45 |
} |
| 46 |
|
| 47 |
const toggleGroupIcon = <ToggleGroupItemElement variant={ToggleGroupItemVariant.icon}>{icon}</ToggleGroupItemElement>; |
| 48 |
|
| 49 |
return ( |
| 50 |
<div className={css(styles.toggleGroupItem, className)} {...props}> |
| 51 |
<button |
| 52 |
type="button" |
| 53 |
className={css(styles.toggleGroupButton, isSelected && styles.modifiers.selected)} |
| 54 |
aria-pressed={isSelected} |
| 55 |
onClick={handleChange} |
| 56 |
aria-label={ariaLabel} |
| 57 |
disabled={isDisabled} |
| 58 |
id={buttonId} |
| 59 |
> |
| 60 |
{icon && iconPosition === 'start' && toggleGroupIcon} |
| 61 |
{text && <ToggleGroupItemElement variant={ToggleGroupItemVariant.text}>{text}</ToggleGroupItemElement>} |
| 62 |
{icon && iconPosition === 'end' && toggleGroupIcon} |
| 63 |
</button> |
| 64 |
</div> |
| 65 |
); |
| 66 |
}; |
| 67 |
ToggleGroupItem.displayName = 'ToggleGroupItem'; |