import * as Ariakit from '@ariakit/react'; import { getClassNames } from '@websolutespa/bom-core'; import { forwardRef, ReactNode, useContext } from 'react'; import styled from 'styled-components'; import { getVariantKey } from '../../variants'; import { isEmptyValue } from '../utils/utils'; import { SelectValue } from './select-value'; import { SelectContext } from './select.context'; import { ISelectVariants, selectVariants } from './select.variants'; const SelectSelectStyle = styled(Ariakit.Select) ` ${props => getVariantKey('select', props.variant, props.variants)} `; export type SelectSelectProps = Ariakit.SelectProps & { variant?: keyof typeof selectVariants | (string & {}); variants?: ISelectVariants; before?: ReactNode; after?: ReactNode; }; export const SelectSelect = forwardRef( function SelectSelect({ children, variant, variants, before, after, className, ...props }: SelectSelectProps, ref) { const context = useContext(SelectContext); const store = Ariakit.useSelectContext(); const value = Ariakit.useStoreState(store, 'value'); if (!context) { return; } const classNames = getClassNames('select__select', { empty: isEmptyValue(value) }, className); return ( {before}
{after} {children}
); }); export function SelectSelection() { const selectContext = Ariakit.useSelectContext(); const context = useContext(SelectContext); if (!context) { return; } const state = selectContext?.getState(); const items = context.options ? context.options.map(x => ({ value: String(x.id), label: x.name, })) : (state?.items || []) .filter(x => x.element!.parentElement !== state?.anchorElement) .map((x) => ({ value: x.value, label: x.element!.innerText || x.value, })) as { value: string, label: string }[]; const value = state?.value; if (context.multiple && Array.isArray(value)) { const options = items.filter(x => value.indexOf(x.value) !== -1); if (options.length > 0) { return (
{options.map((option) => ( ))}
); } else { return context.placeholder || 'Select'; } } // console.log(context.options, state?.items, items, value); return items.find(x => x.value === value)?.label || context.placeholder || 'Select'; }