2023-06-12 14:27:40 +02:00
|
|
|
import React, { PropsWithChildren } from "react";
|
|
|
|
|
import { UseSelectStateChange } from "downshift";
|
|
|
|
|
import { FieldProps } from ":/components/Forms/Field";
|
|
|
|
|
import { optionToValue, SubProps } from ":/components/Forms/Select/mono-common";
|
|
|
|
|
import { SelectMonoSearchable } from ":/components/Forms/Select/mono-searchable";
|
|
|
|
|
import { SelectMonoSimple } from ":/components/Forms/Select/mono-simple";
|
|
|
|
|
|
|
|
|
|
export interface Option {
|
|
|
|
|
value?: string;
|
|
|
|
|
label: string;
|
|
|
|
|
disabled?: boolean;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export type SelectProps = PropsWithChildren &
|
|
|
|
|
FieldProps & {
|
|
|
|
|
label: string;
|
|
|
|
|
hideLabel?: boolean;
|
|
|
|
|
options: Option[];
|
|
|
|
|
searchable?: boolean;
|
|
|
|
|
name?: string;
|
|
|
|
|
defaultValue?: string | number | string[];
|
|
|
|
|
value?: string | number | string[];
|
|
|
|
|
onChange?: (event: {
|
|
|
|
|
target: { value: string | number | undefined | string[] };
|
|
|
|
|
}) => void;
|
2023-07-31 15:21:55 +02:00
|
|
|
onBlur?: (event: {
|
|
|
|
|
target: { value: string | number | undefined | string[] };
|
|
|
|
|
}) => void;
|
2023-06-12 14:27:40 +02:00
|
|
|
disabled?: boolean;
|
|
|
|
|
clearable?: boolean;
|
|
|
|
|
multi?: boolean;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const SelectMono = (props: SelectProps) => {
|
|
|
|
|
const defaultSelectedItem = props.defaultValue
|
|
|
|
|
? props.options.find(
|
2023-07-18 15:43:56 +02:00
|
|
|
(option) => optionToValue(option) === props.defaultValue,
|
2023-06-12 14:27:40 +02:00
|
|
|
)
|
|
|
|
|
: undefined;
|
|
|
|
|
|
|
|
|
|
const commonDownshiftProps: SubProps["downshiftProps"] = {
|
|
|
|
|
initialSelectedItem: defaultSelectedItem,
|
|
|
|
|
onSelectedItemChange: (e: UseSelectStateChange<Option>) => {
|
|
|
|
|
props.onChange?.({
|
|
|
|
|
target: {
|
|
|
|
|
value: e.selectedItem ? optionToValue(e.selectedItem) : undefined,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
},
|
2023-07-18 16:27:48 +02:00
|
|
|
isItemDisabled: (item) => !!item.disabled,
|
2023-06-12 14:27:40 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return props.searchable ? (
|
|
|
|
|
<SelectMonoSearchable {...props} downshiftProps={commonDownshiftProps} />
|
|
|
|
|
) : (
|
|
|
|
|
<SelectMonoSimple {...props} downshiftProps={commonDownshiftProps} />
|
|
|
|
|
);
|
|
|
|
|
};
|