import React, { useMemo } from 'react' import withDefaults from '../utils/with-defaults' import useTheme from '../use-theme' import { useSelectContext } from './select-context' import logWarning from '../utils/use-warning' import Ellipsis from '../shared/ellipsis' interface Props { value?: string disabled?: boolean className?: string divider?: boolean label?: boolean preventAllEvents?: boolean } const defaultProps = { disabled: false, divider: false, label: 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, divider, label, preventAllEvents, ...props }) => { const theme = useTheme() const { updateValue, value, disableAll } = useSelectContext() const isDisabled = useMemo(() => disabled || disableAll, [disabled, disableAll]) const isLabel = useMemo(() => label || divider, [label, divider]) if (!isLabel && identValue === undefined) { logWarning('The props "value" is required.', 'Select Option') } const selected = useMemo(() => { if (!value) return false if (typeof value === 'string') { return identValue === value } return value.includes(`${identValue}`) }, [identValue, value]) const bgColor = useMemo(() => { if (isDisabled) return theme.palette.accents_1 return selected ? theme.palette.accents_2 : theme.palette.background }, [selected, isDisabled, theme.palette]) const hoverBgColor = useMemo(() => { if (isDisabled || isLabel || selected) return bgColor return theme.palette.accents_1 }, [selected, isDisabled, theme.palette, isLabel, bgColor]) const color = useMemo(() => { if (isDisabled) return theme.palette.accents_9 return selected ? theme.palette.foreground : theme.palette.accents_10 }, [selected, isDisabled, theme.palette]) const clickHandler = (event: React.MouseEvent) => { if (preventAllEvents) return event.stopPropagation() event.nativeEvent.stopImmediatePropagation() event.preventDefault() if (isDisabled || isLabel) return updateValue && updateValue(identValue) } return ( <>
{children}
) } export default withDefaults(SelectOption, defaultProps)