2021-12-14 19:14:53 +00:00
|
|
|
import styles from './BoxSelector.module.css';
|
|
|
|
import { BoxSelectorItem } from './BoxSelectorItem';
|
2023-02-07 03:33:57 +00:00
|
|
|
import { BoxSelectorOption, Value } from './types';
|
2021-12-14 19:14:53 +00:00
|
|
|
|
2023-02-07 03:33:57 +00:00
|
|
|
interface IsMultiProps<T extends Value> {
|
|
|
|
isMulti: true;
|
|
|
|
value: T[];
|
|
|
|
onChange(value: T[], limitedToBE: boolean): void;
|
|
|
|
}
|
|
|
|
|
|
|
|
interface SingleProps<T extends Value> {
|
|
|
|
isMulti?: never;
|
2021-12-14 19:14:53 +00:00
|
|
|
value: T;
|
|
|
|
onChange(value: T, limitedToBE: boolean): void;
|
|
|
|
}
|
|
|
|
|
2023-02-07 03:33:57 +00:00
|
|
|
type Union<T extends Value> = IsMultiProps<T> | SingleProps<T>;
|
|
|
|
|
|
|
|
export type Props<T extends Value> = Union<T> & {
|
|
|
|
radioName: string;
|
|
|
|
options: ReadonlyArray<BoxSelectorOption<T>> | Array<BoxSelectorOption<T>>;
|
|
|
|
slim?: boolean;
|
|
|
|
};
|
|
|
|
|
|
|
|
export function BoxSelector<T extends Value>({
|
2021-12-14 19:14:53 +00:00
|
|
|
radioName,
|
|
|
|
options,
|
2023-02-07 03:33:57 +00:00
|
|
|
slim = false,
|
|
|
|
...props
|
2021-12-14 19:14:53 +00:00
|
|
|
}: Props<T>) {
|
|
|
|
return (
|
2022-08-22 08:55:48 +00:00
|
|
|
<div className="form-group">
|
|
|
|
<div className="col-sm-12">
|
2023-02-07 03:33:57 +00:00
|
|
|
<div className={styles.root} role="radiogroup">
|
2022-08-22 08:55:48 +00:00
|
|
|
{options
|
|
|
|
.filter((option) => !option.hide)
|
|
|
|
.map((option) => (
|
|
|
|
<BoxSelectorItem
|
|
|
|
key={option.id}
|
|
|
|
radioName={radioName}
|
|
|
|
option={option}
|
2023-02-07 03:33:57 +00:00
|
|
|
onSelect={handleSelect}
|
2022-08-22 08:55:48 +00:00
|
|
|
disabled={option.disabled && option.disabled()}
|
|
|
|
tooltip={option.tooltip && option.tooltip()}
|
2023-02-07 03:33:57 +00:00
|
|
|
type={props.isMulti ? 'checkbox' : 'radio'}
|
|
|
|
isSelected={isSelected}
|
|
|
|
slim={slim}
|
2022-08-22 08:55:48 +00:00
|
|
|
/>
|
|
|
|
))}
|
|
|
|
</div>
|
|
|
|
</div>
|
2021-12-14 19:14:53 +00:00
|
|
|
</div>
|
|
|
|
);
|
2023-02-07 03:33:57 +00:00
|
|
|
|
|
|
|
function handleSelect(optionValue: T, limitedToBE: boolean) {
|
|
|
|
if (props.isMulti) {
|
|
|
|
const newValue = isSelected(optionValue)
|
|
|
|
? props.value.filter((v) => v !== optionValue)
|
|
|
|
: [...props.value, optionValue];
|
|
|
|
props.onChange(newValue, limitedToBE);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (isSelected(optionValue)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
props.onChange(optionValue, limitedToBE);
|
|
|
|
}
|
|
|
|
|
|
|
|
function isSelected(optionValue: T) {
|
|
|
|
if (props.isMulti) {
|
|
|
|
return props.value.includes(optionValue);
|
|
|
|
}
|
|
|
|
|
|
|
|
return props.value === optionValue;
|
|
|
|
}
|
2021-12-14 19:14:53 +00:00
|
|
|
}
|