import React, { useMemo } from 'react' import useTheme from '../use-theme' import { useSelectContext } from './select-context' import useWarning from '../utils/use-warning' import Ellipsis from '../shared/ellipsis' import useScaleable, { withScaleable } from '../use-scaleable' 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 & NativeAttrs const SelectOptionComponent: React.FC> = ({ value: identValue, className, children, disabled, divider, label, preventAllEvents, ...props }: React.PropsWithChildren & typeof defaultProps) => { const theme = useTheme() const { SCALES } = useScaleable() const { updateValue, value, disableAll } = useSelectContext() const isDisabled = useMemo(() => disabled || disableAll, [disabled, disableAll]) const isLabel = useMemo(() => label || divider, [label, divider]) if (!isLabel && identValue === undefined) { useWarning('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_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 || isLabel) return updateValue && updateValue(identValue) } return (
{children}
) } SelectOptionComponent.defaultProps = defaultProps SelectOptionComponent.displayName = 'GeistSelectOption' const SelectOption = withScaleable(SelectOptionComponent) export default SelectOption