import React, { Fragment, useEffect, useRef, useState, useContext, useMemo } from 'react'; import { Listbox } from '@headlessui/react'; import { CheckIcon, Cog6ToothIcon } from '@heroicons/react/24/outline'; import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover'; export interface ISelectContextOption { key: string; label: string; disabled?: boolean; } interface ISelectContextProps { options?: ISelectContextOption[]; disable?: boolean; selectedKeys?: string[]; onSelect?: (selectedKeys: string[]) => void; className?: string; required?: boolean; children?: React.ReactNode | Iterable; } const SelectContext: React.FC = (props) => { const { options = [], disable = false, selectedKeys = [], onSelect, className = '', required } = props; const [selected, setSelected] = useState(options.filter((opt) => selectedKeys.includes(opt.key))); useEffect(() => { setSelected(options.filter((opt) => selectedKeys.includes(opt.key))); }, [options, selectedKeys]); const selectedKeysRef = useRef(selectedKeys); selectedKeysRef.current = selectedKeys; const onSelectRef = useRef(onSelect); onSelectRef.current = onSelect; useEffect(() => { const keys = selected.map((opt) => opt.key); if (keys.length !== selectedKeysRef.current.length || keys.some((key) => !selectedKeysRef.current.includes(key))) { onSelectRef.current?.(keys); } }, [selected]); if (disable) { return {props.children}; } return (
{props.children}
{options.map((option) => ( {({ selected }) => ( <> {option.label} {selected && ( )} )} ))}
); }; export default SelectContext;