import { Popover, PopoverContent } from '@radix-ui/react-popover' import { useCombobox } from 'downshift' import { Edit3Icon, XIcon } from 'lucide-react' import { listify, unique } from 'radashi' import React, { useEffect, useMemo } from 'react' import { EhBaseSelectorRoot } from '../../../ui/components/commandInput/EhBaseSelector' import { PopoverTrigger } from '~/components/ui/popover' import { useBootstrapConfig } from '~/modules/config/BootstrapConfigContext' import { cn } from '~/lib/utils' import { useEnvironmentContext } from '~/modules/environment/EnvironmentContext' import { fuzzySearch, makeFuzzySearchIndex, } from '~/modules/fuzzyMatchLogic/autoCompleteFilter' interface EhEnvSelectorProps { className?: string } export interface EhEnvSelectorItem { slug: string displayName: string } export function EhEnvSelector({ className = '' }: EhEnvSelectorProps) { const { envs } = useBootstrapConfig() const { currentEnv, setCurrentEnv } = useEnvironmentContext() const allItems = useMemo( () => listify(envs, (_, e) => { return { slug: e.slug, displayName: e.displayName, } }), [envs], ) const searchIndex = useMemo(() => { return makeFuzzySearchIndex({ entries: allItems, }) }, [allItems]) const [displayedItems, setDisplayedItems] = React.useState>(allItems) const envFilter = (needle: string) => { if (needle.trim() === '') { return allItems } const newLocal = fuzzySearch(needle, { index: searchIndex, }) console.log(needle, newLocal) return newLocal.map((e) => e.entry) } const { isOpen: comboIsOpen, getLabelProps, getMenuProps, getInputProps, getToggleButtonProps, highlightedIndex, getItemProps, selectItem, inputValue: comboInputValue, setInputValue, } = useCombobox({ onInputValueChange({ inputValue: changedInputValue, isOpen: changedIsOpen, }) { if (changedIsOpen) { const matchedIds = unique(envFilter(changedInputValue)) setDisplayedItems(matchedIds) } }, onSelectedItemChange({ selectedItem: changedSelectedItem }) { setCurrentEnv(changedSelectedItem?.slug) }, // selectedItem, items: displayedItems, itemToString(item) { return (item && item.displayName) || '' }, }) useEffect(() => { if (currentEnv) { const f = allItems.find((e) => e.slug === currentEnv.slug) if (f) { selectItem(f) } } }, [allItems, currentEnv, selectItem]) return (
{ const userHasSelectedSomeText = e.currentTarget.selectionStart !== e.currentTarget.selectionEnd if (!userHasSelectedSomeText) { // setInputValue('asdads') e.currentTarget.select() } }, onKeyUp: (e) => { if (e.key !== 'Enter') { // console.log(e.target.value) // setLastUsersInputText(e.target.value) } }, })} /> {comboInputValue.length ? ( setInputValue('')} /> ) : ( )}
e.preventDefault()} forceMount >
{displayedItems.map((item, index) => (
{item.displayName}
))} {displayedItems.length === 0 && (
'{comboInputValue}' not found. Try a different search.
)}
{/* */}
) }