ol-autocomplete.tsx 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. import { useCombobox } from 'downshift'
  2. import { forwardRef, useState, useMemo, Fragment } from 'react'
  3. import { useTranslation } from 'react-i18next'
  4. import classnames from 'classnames'
  5. import MiniSearch from 'minisearch'
  6. import OLButton from '@/shared/components/ol/ol-button'
  7. import OLFormControl from '@/shared/components/ol/ol-form-control'
  8. import OLFormLabel from '@/shared/components/ol/ol-form-label'
  9. import {
  10. DropdownHeader,
  11. DropdownItem,
  12. } from '@/shared/components/dropdown/dropdown-menu'
  13. import MaterialIcon from '@/shared/components/material-icon'
  14. const FUZZY_SEARCH_THRESHOLD = 0.5
  15. export type OLAutocompleteItem = {
  16. value: string
  17. label: string
  18. group?: string
  19. }
  20. export type OLAutocompleteProps = {
  21. items: OLAutocompleteItem[]
  22. onChange: (value: string) => void
  23. placeholder?: string
  24. label: string
  25. showLabel?: boolean
  26. allowCreate?: boolean | ((value: string) => boolean)
  27. disabled?: boolean
  28. createOptionPrefix?: string
  29. useFuzzySearch?: boolean
  30. inputRef?: React.ForwardedRef<HTMLInputElement>
  31. expandUp?: boolean
  32. }
  33. type OLAutocompleteDisplayItem =
  34. | {
  35. type: 'item'
  36. value: string
  37. label: string
  38. }
  39. | {
  40. type: 'create'
  41. inputValue: string
  42. }
  43. function OLAutocompleteInternal({
  44. items,
  45. onChange,
  46. placeholder,
  47. label,
  48. showLabel = false,
  49. allowCreate = true,
  50. disabled = false,
  51. createOptionPrefix = '+ Create',
  52. useFuzzySearch = false,
  53. inputRef,
  54. expandUp = false,
  55. }: OLAutocompleteProps) {
  56. const { t } = useTranslation()
  57. const searchIndex = useMemo(() => {
  58. if (!useFuzzySearch) return null
  59. const searchIndex = new MiniSearch({
  60. fields: ['label'],
  61. storeFields: ['value', 'label', 'group'],
  62. idField: 'value',
  63. })
  64. searchIndex.addAll(items)
  65. return searchIndex
  66. }, [items, useFuzzySearch])
  67. const [internalInputValue, setInternalInputValue] = useState('')
  68. const inputItems = useMemo(() => {
  69. if (!internalInputValue) {
  70. return items
  71. }
  72. if (useFuzzySearch && searchIndex) {
  73. const results = searchIndex.search(internalInputValue, {
  74. fuzzy: FUZZY_SEARCH_THRESHOLD,
  75. prefix: true,
  76. })
  77. return results.map(result => ({
  78. value: result.value,
  79. label: result.label,
  80. group: result.group,
  81. }))
  82. }
  83. return items.filter(item =>
  84. item.label.toLowerCase().includes(internalInputValue.toLowerCase())
  85. )
  86. }, [items, internalInputValue, searchIndex, useFuzzySearch])
  87. const exactMatch = inputItems.some(
  88. item => item.label.toLowerCase() === internalInputValue.toLowerCase()
  89. )
  90. const allowCreateForInput =
  91. typeof allowCreate === 'function'
  92. ? allowCreate(internalInputValue)
  93. : allowCreate
  94. const showCreateOption =
  95. allowCreateForInput && internalInputValue && !exactMatch
  96. const displayItems: OLAutocompleteDisplayItem[] = [
  97. ...inputItems.map(item => ({
  98. type: 'item' as const,
  99. value: item.value,
  100. label: item.label,
  101. })),
  102. ...(showCreateOption
  103. ? [
  104. {
  105. type: 'create' as const,
  106. inputValue: internalInputValue,
  107. },
  108. ]
  109. : []),
  110. ]
  111. const hasGroupedItems = inputItems.some(item => Boolean(item.group))
  112. const {
  113. isOpen,
  114. getLabelProps,
  115. getMenuProps,
  116. getInputProps,
  117. getItemProps,
  118. highlightedIndex,
  119. selectItem,
  120. } = useCombobox<OLAutocompleteDisplayItem>({
  121. inputValue: internalInputValue,
  122. items: displayItems,
  123. defaultHighlightedIndex: 0,
  124. itemToString: item => {
  125. if (!item) return ''
  126. return item.type === 'create' ? item.inputValue : item.label
  127. },
  128. onSelectedItemChange: ({ selectedItem }) => {
  129. if (selectedItem) {
  130. if (selectedItem.type === 'create') {
  131. onChange(selectedItem.inputValue)
  132. setInternalInputValue(selectedItem.inputValue)
  133. } else {
  134. onChange(selectedItem.value)
  135. setInternalInputValue(selectedItem.label)
  136. }
  137. }
  138. },
  139. onInputValueChange: ({ inputValue = '' }) => {
  140. setInternalInputValue(inputValue)
  141. },
  142. })
  143. const shouldShowDropdown = isOpen && displayItems.length > 0
  144. const handleClear = () => {
  145. selectItem(null)
  146. setInternalInputValue('')
  147. onChange('')
  148. }
  149. const getSearchBar = () => (
  150. <div className={classnames({ 'mb-3': !expandUp, 'mt-3': expandUp })}>
  151. <OLFormLabel
  152. {...getLabelProps()}
  153. className={showLabel ? '' : 'visually-hidden'}
  154. >
  155. {label}
  156. </OLFormLabel>
  157. <div className="position-relative">
  158. <OLFormControl
  159. {...getInputProps({
  160. ref: inputRef,
  161. })}
  162. placeholder={placeholder}
  163. disabled={disabled}
  164. />
  165. {internalInputValue && !disabled && (
  166. <OLButton
  167. variant="ghost"
  168. size="sm"
  169. className="position-absolute top-50 end-0 translate-middle-y me-1"
  170. onClick={handleClear}
  171. aria-label={t('delete')}
  172. >
  173. <MaterialIcon type="close" />
  174. </OLButton>
  175. )}
  176. </div>
  177. </div>
  178. )
  179. const getResultsList = () => (
  180. <>
  181. <ul
  182. {...getMenuProps()}
  183. className={classnames('dropdown-menu', 'select-dropdown-menu', {
  184. show: shouldShowDropdown,
  185. 'select-dropdown-menu-expand-up': expandUp,
  186. })}
  187. >
  188. {hasGroupedItems ? (
  189. <>
  190. {inputItems.map((item, index) => {
  191. const previousItem = inputItems[index - 1]
  192. const hasGroupHeader =
  193. item.group &&
  194. (!previousItem || previousItem.group !== item.group)
  195. return (
  196. <Fragment key={`${item.value}${index}`}>
  197. {hasGroupHeader && index > 0 && (
  198. <li role="separator" className="dropdown-divider" />
  199. )}
  200. {hasGroupHeader && (
  201. <li>
  202. <DropdownHeader as="span">{item.group}</DropdownHeader>
  203. </li>
  204. )}
  205. <li
  206. {...getItemProps({
  207. item: {
  208. type: 'item',
  209. value: item.value,
  210. label: item.label,
  211. },
  212. index,
  213. })}
  214. >
  215. <DropdownItem
  216. as="span"
  217. role={undefined}
  218. className={classnames({
  219. 'dropdown-item-highlighted': highlightedIndex === index,
  220. })}
  221. >
  222. {item.label}
  223. </DropdownItem>
  224. </li>
  225. </Fragment>
  226. )
  227. })}
  228. {showCreateOption && (
  229. <>
  230. <li role="separator" className="dropdown-divider" />
  231. <li
  232. {...getItemProps({
  233. item: {
  234. type: 'create',
  235. inputValue: internalInputValue,
  236. },
  237. index: displayItems.length - 1,
  238. })}
  239. >
  240. <DropdownItem
  241. as="span"
  242. role={undefined}
  243. className={classnames({
  244. 'dropdown-item-highlighted':
  245. highlightedIndex === displayItems.length - 1,
  246. })}
  247. >
  248. <span className="text-muted">{createOptionPrefix} </span>
  249. <strong>'{internalInputValue}'</strong>
  250. </DropdownItem>
  251. </li>
  252. </>
  253. )}
  254. </>
  255. ) : (
  256. displayItems.map((item, index) => {
  257. const isCreateOption = item.type === 'create'
  258. const displayValue = isCreateOption ? item.inputValue : item.label
  259. return (
  260. <li
  261. key={
  262. item.type === 'create'
  263. ? `create-${item.inputValue}-${index}`
  264. : `${item.value}${index}`
  265. }
  266. {...getItemProps({
  267. item,
  268. index,
  269. })}
  270. >
  271. <DropdownItem
  272. as="span"
  273. role={undefined}
  274. className={classnames({
  275. 'dropdown-item-highlighted': highlightedIndex === index,
  276. })}
  277. >
  278. {isCreateOption ? (
  279. <>
  280. <span className="text-muted">{createOptionPrefix} </span>
  281. <strong>'{displayValue}'</strong>
  282. </>
  283. ) : (
  284. displayValue
  285. )}
  286. </DropdownItem>
  287. </li>
  288. )
  289. })
  290. )}
  291. </ul>
  292. </>
  293. )
  294. return (
  295. <div className={classnames('dropdown', 'd-block', 'ol-autocomplete')}>
  296. {expandUp ? (
  297. <>
  298. {getResultsList()}
  299. {getSearchBar()}
  300. </>
  301. ) : (
  302. <>
  303. {getSearchBar()}
  304. {getResultsList()}
  305. </>
  306. )}
  307. </div>
  308. )
  309. }
  310. const OLAutocomplete = forwardRef<HTMLInputElement, OLAutocompleteProps>(
  311. (props, ref) => {
  312. return <OLAutocompleteInternal {...props} inputRef={ref} />
  313. }
  314. )
  315. OLAutocomplete.displayName = 'OLAutocomplete'
  316. export default OLAutocomplete