import React, { useMemo } from 'react' import withDefaults from '../utils/with-defaults' import useTheme from '../styles/use-theme' import { useSelectContext } from './select-context' import useWarning from '../utils/use-warning' interface Props { value: string disabled?: boolean className?: string preventAllEvents?: boolean } const defaultProps = { disabled: false, className: '', preventAllEvents: false, } type NativeAttrs = Omit, keyof Props> export type SelectOptionProps = Props & typeof defaultProps & NativeAttrs const SelectOption: React.FC> = ({ value: identValue, className, children, disabled, preventAllEvents, ...props }) => { const theme = useTheme() const { updateValue, value, disableAll } = useSelectContext() const isDisabled = useMemo(() => disabled || disableAll, [disabled, disableAll]) if (identValue === undefined) { useWarning('The props "value" is required.', 'Select Option') } const selected = useMemo(() => (value ? identValue === value : false), [identValue, value]) const bgColor = useMemo(() => { if (isDisabled) return theme.palette.accents_1 return selected ? theme.palette.accents_1 : theme.palette.background }, [selected, isDisabled, theme.palette]) const color = useMemo(() => { if (isDisabled) return theme.palette.accents_4 return selected ? theme.palette.foreground : theme.palette.accents_5 }, [selected, isDisabled, theme.palette]) const clickHandler = (event: React.MouseEvent) => { if (preventAllEvents) return event.stopPropagation() event.nativeEvent.stopImmediatePropagation() event.preventDefault() if (isDisabled) return updateValue && updateValue(identValue) } return ( <>
{children}
) } export default withDefaults(SelectOption, defaultProps)