import React, { useState } from 'react' import type { ListEventType, ListProps } from './list' import ConditionalWrapper from '../ConditionalWrapper/ConditionalWrapper.tsx' import Input from '../Input/Input.tsx' import { classNames } from '../../utils/classNames' import searchIcon from '../../icons/search.svg?raw' import styles from './list.module.scss' export type Props = ListProps & { onSelect?: (event: ListEventType) => void } const List = ({ showSearchBar, showSearchBarIcon, searchBarPlaceholder, noResultsLabel = 'No results.', maxHeight, id, className, wrapperClassName, secondary, itemGroups, onSelect }: Props) => { const [searchValue, setSearchValue] = useState('') const [numberOfResults, setNumberOfResults] = useState(1) const [itemGroupsWithActive, setItemGroups] = useState(itemGroups) const classes = classNames([ styles.list, (secondary && !showSearchBar) && styles.secondary, !showSearchBar && styles.container, className ]) const wrapperClasses = classNames([ styles.container, secondary && styles.secondary, wrapperClassName ]) const style = maxHeight ? { maxHeight } as React.CSSProperties : undefined const search = (event: React.InputEvent) => { const value = (event.target as HTMLInputElement).value.toLowerCase() setSearchValue(value) setNumberOfResults( itemGroups .map(group => group.items) .flat() .filter(item => { return item.value?.toLowerCase().includes(value) || item.subText?.toLowerCase().includes(value) || item.name?.toLowerCase().includes(value) }).length ) } const select = (event: any) => { const li = event.target as HTMLLIElement setItemGroups( itemGroupsWithActive.map(group => { return { ...group, items: group.items.map(item => { return { ...item, selected: li.dataset.name === item.name } }) } }) ) onSelect?.({ ...li.dataset, list: li.parentElement } as ListEventType) } const selectByKey = (event: any) => { if (event.key === 'Enter') { select(event) } } return ( (
{showSearchBarIcon && ( )} {children}
)}>
) } export default List