| 1 |
import { createRef, Fragment } from 'react'; |
| 2 |
import { Tooltip, TooltipProps } from '@patternfly/react-core/dist/esm/components/Tooltip'; |
| 3 |
import { Checkbox } from '@patternfly/react-core/dist/esm/components/Checkbox'; |
| 4 |
import { Radio } from '@patternfly/react-core/dist/esm/components/Radio'; |
| 5 |
|
| 6 |
export enum RowSelectVariant { |
| 7 |
radio = 'radio', |
| 8 |
checkbox = 'checkbox' |
| 9 |
} |
| 10 |
|
| 11 |
export interface SelectColumnProps { |
| 12 |
children?: React.ReactNode; |
| 13 |
className?: string; |
| 14 |
onSelect?: (event: React.FormEvent<HTMLInputElement>) => void; |
| 15 |
selectVariant?: RowSelectVariant; |
| 16 |
/** text to display on the tooltip */ |
| 17 |
tooltip?: React.ReactNode; |
| 18 |
/** other props to pass to the tooltip */ |
| 19 |
tooltipProps?: Omit<TooltipProps, 'content'>; |
| 20 |
/** id for the input element - required by Checkbox and Radio components */ |
| 21 |
id?: string; |
| 22 |
/** name for the input element - required by Radio component */ |
| 23 |
name?: string; |
| 24 |
/** Whether the checkbox should be in an indeterminate state */ |
| 25 |
isIndeterminate?: boolean; |
| 26 |
} |
| 27 |
|
| 28 |
export const SelectColumn: React.FunctionComponent<SelectColumnProps> = ({ |
| 29 |
children = null as React.ReactNode, |
| 30 |
// eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 31 |
className, |
| 32 |
onSelect = null as (event: React.FormEvent<HTMLInputElement>) => void, |
| 33 |
selectVariant, |
| 34 |
tooltip, |
| 35 |
tooltipProps, |
| 36 |
id, |
| 37 |
name, |
| 38 |
isIndeterminate, |
| 39 |
...props |
| 40 |
}: SelectColumnProps) => { |
| 41 |
const inputRef = createRef<any>(); |
| 42 |
|
| 43 |
const handleChange = (event: React.FormEvent<HTMLInputElement>, _checked: boolean) => { |
| 44 |
onSelect && onSelect(event); |
| 45 |
}; |
| 46 |
|
| 47 |
const commonProps = { |
| 48 |
...props, |
| 49 |
id, |
| 50 |
ref: inputRef, |
| 51 |
onChange: handleChange |
| 52 |
}; |
| 53 |
|
| 54 |
const checkboxProps = { |
| 55 |
...commonProps, |
| 56 |
...(isIndeterminate && { isChecked: null }) |
| 57 |
}; |
| 58 |
|
| 59 |
const content = ( |
| 60 |
<Fragment> |
| 61 |
{selectVariant === RowSelectVariant.checkbox ? ( |
| 62 |
<Checkbox {...checkboxProps} /> |
| 63 |
) : ( |
| 64 |
<Radio {...commonProps} name={name} /> |
| 65 |
)} |
| 66 |
{children} |
| 67 |
</Fragment> |
| 68 |
); |
| 69 |
|
| 70 |
return tooltip ? ( |
| 71 |
<Tooltip triggerRef={inputRef} content={tooltip} {...tooltipProps}> |
| 72 |
{content} |
| 73 |
</Tooltip> |
| 74 |
) : ( |
| 75 |
content |
| 76 |
); |
| 77 |
}; |
| 78 |
SelectColumn.displayName = 'SelectColumn'; |