select-collaborators.tsx 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. import { useEffect, useMemo, useState, useRef, useCallback } from 'react'
  2. import { useTranslation } from 'react-i18next'
  3. import { matchSorter } from 'match-sorter'
  4. import { useCombobox, UseMultipleSelectionReturnValue } from 'downshift'
  5. import classnames from 'classnames'
  6. import MaterialIcon from '@/shared/components/material-icon'
  7. import Tag from '@/features/ui/components/bootstrap-5/tag'
  8. import { DropdownItem } from '@/features/ui/components/bootstrap-5/dropdown-menu'
  9. import { Spinner } from 'react-bootstrap'
  10. import { Contact } from '../utils/types'
  11. export type ContactItem = {
  12. email: string
  13. display: string
  14. type: string
  15. }
  16. // Unicode characters in these Unicode groups:
  17. // "General Punctuation — Spaces"
  18. // "General Punctuation — Format character" (including zero-width spaces)
  19. const matchAllSpaces =
  20. /[\u061C\u2000-\u200F\u202A-\u202E\u2060\u2066-\u2069\u2028\u2029\u202F]/g
  21. export default function SelectCollaborators({
  22. loading,
  23. options,
  24. placeholder,
  25. multipleSelectionProps,
  26. }: {
  27. loading: boolean
  28. options: Contact[]
  29. placeholder: string
  30. multipleSelectionProps: UseMultipleSelectionReturnValue<ContactItem>
  31. }) {
  32. const { t } = useTranslation()
  33. const {
  34. getSelectedItemProps,
  35. getDropdownProps,
  36. addSelectedItem,
  37. removeSelectedItem,
  38. selectedItems,
  39. } = multipleSelectionProps
  40. const [inputValue, setInputValue] = useState('')
  41. const selectedEmails = useMemo(
  42. () => selectedItems.map(item => item.email),
  43. [selectedItems]
  44. )
  45. const unselectedOptions = useMemo(
  46. () => options.filter(option => !selectedEmails.includes(option.email)),
  47. [options, selectedEmails]
  48. )
  49. const filteredOptions = useMemo(() => {
  50. if (inputValue === '') {
  51. return unselectedOptions
  52. }
  53. return matchSorter(unselectedOptions, inputValue, {
  54. keys: ['name', 'email'],
  55. threshold: matchSorter.rankings.CONTAINS,
  56. baseSort: (a, b) => {
  57. // Prefer server-side sorting for ties in the match ranking.
  58. return a.index - b.index > 0 ? 1 : -1
  59. },
  60. })
  61. }, [unselectedOptions, inputValue])
  62. const inputRef = useRef<HTMLInputElement>(null)
  63. const focusInput = useCallback(() => {
  64. if (inputRef.current) {
  65. window.setTimeout(() => {
  66. if (inputRef.current) {
  67. inputRef.current.focus()
  68. }
  69. }, 10)
  70. }
  71. }, [inputRef])
  72. const isValidInput = useMemo(() => {
  73. if (inputValue.includes('@')) {
  74. for (const selectedItem of selectedItems) {
  75. if (selectedItem.email === inputValue) {
  76. return false
  77. }
  78. }
  79. }
  80. return true
  81. }, [inputValue, selectedItems])
  82. function stateReducer(_: unknown, actionAndChanges: any) {
  83. const { type, changes } = actionAndChanges
  84. // force selected item to be null so that adding, removing, then re-adding the same collaborator is recognised as a selection change
  85. if (type === useCombobox.stateChangeTypes.InputChange) {
  86. return { ...changes, selectedItem: null }
  87. }
  88. return changes
  89. }
  90. const {
  91. isOpen,
  92. getLabelProps,
  93. getMenuProps,
  94. getInputProps,
  95. highlightedIndex,
  96. getItemProps,
  97. reset,
  98. } = useCombobox({
  99. inputValue,
  100. defaultHighlightedIndex: 0,
  101. items: filteredOptions,
  102. itemToString: item => (item && item.name) || '',
  103. stateReducer,
  104. onStateChange: ({ type, selectedItem }) => {
  105. switch (type) {
  106. // add a selected item on Enter (keypress), click or blur
  107. case useCombobox.stateChangeTypes.InputKeyDownEnter:
  108. case useCombobox.stateChangeTypes.ItemClick:
  109. case useCombobox.stateChangeTypes.InputBlur:
  110. if (selectedItem) {
  111. setInputValue('')
  112. addSelectedItem(selectedItem)
  113. }
  114. break
  115. }
  116. },
  117. })
  118. const addNewItem = useCallback(
  119. (_email: string, focus = true) => {
  120. const email = _email.replace(matchAllSpaces, '')
  121. if (
  122. isValidInput &&
  123. email.includes('@') &&
  124. !selectedEmails.includes(email)
  125. ) {
  126. addSelectedItem({
  127. email,
  128. display: email,
  129. type: 'user',
  130. })
  131. setInputValue('')
  132. reset()
  133. if (focus) {
  134. focusInput()
  135. }
  136. return true
  137. }
  138. },
  139. [addSelectedItem, selectedEmails, isValidInput, focusInput, reset]
  140. )
  141. // close and reset the menu when there are no matching items
  142. useEffect(() => {
  143. if (isOpen && filteredOptions.length === 0) {
  144. reset()
  145. }
  146. }, [reset, isOpen, filteredOptions.length])
  147. return (
  148. <div className="tags-input tags-new">
  149. {/* eslint-disable-next-line jsx-a11y/label-has-for */}
  150. <label className="small" {...getLabelProps()}>
  151. <strong>
  152. {t('add_people')}
  153. &nbsp;
  154. </strong>
  155. {loading && (
  156. <Spinner
  157. animation="border"
  158. aria-hidden="true"
  159. size="sm"
  160. role="status"
  161. />
  162. )}
  163. </label>
  164. <div className="host">
  165. {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
  166. <div className="tags form-control" onClick={focusInput}>
  167. {selectedItems.map((selectedItem, index) => (
  168. <SelectedItem
  169. key={`selected-item-${index}`}
  170. removeSelectedItem={removeSelectedItem}
  171. selectedItem={selectedItem}
  172. focusInput={focusInput}
  173. index={index}
  174. getSelectedItemProps={getSelectedItemProps}
  175. />
  176. ))}
  177. <input
  178. data-testid="collaborator-email-input"
  179. {...getInputProps(
  180. getDropdownProps({
  181. className: classnames('input', {
  182. 'invalid-tag': !isValidInput,
  183. }),
  184. type: 'email',
  185. placeholder,
  186. size: inputValue.length
  187. ? inputValue.length + 5
  188. : placeholder.length,
  189. ref: inputRef,
  190. // preventKeyAction: showDropdown,
  191. onBlur: () => {
  192. addNewItem(inputValue, false)
  193. },
  194. onChange: e => {
  195. setInputValue((e.target as HTMLInputElement).value)
  196. },
  197. onClick: () => focusInput,
  198. onKeyDown: event => {
  199. switch (event.key) {
  200. case 'Enter':
  201. // Enter: always prevent form submission
  202. event.preventDefault()
  203. event.stopPropagation()
  204. break
  205. case 'Tab':
  206. // Tab: if the dropdown isn't open, try to create a new item using inputValue and prevent blur if successful
  207. if (!isOpen && addNewItem(inputValue)) {
  208. event.preventDefault()
  209. event.stopPropagation()
  210. }
  211. break
  212. case ',':
  213. // comma: try to create a new item using inputValue
  214. event.preventDefault()
  215. addNewItem(inputValue)
  216. break
  217. }
  218. },
  219. onPaste: event => {
  220. const data =
  221. // modern browsers
  222. event.clipboardData?.getData('text/plain') ??
  223. // @ts-ignore IE11
  224. window.clipboardData?.getData('text')
  225. if (data) {
  226. const emails = data
  227. .split(/[\r\n,; ]+/)
  228. .filter(item => item.includes('@'))
  229. if (emails.length) {
  230. // pasted comma-separated email addresses
  231. event.preventDefault()
  232. for (const email of emails) {
  233. addNewItem(email)
  234. }
  235. }
  236. }
  237. },
  238. })
  239. )}
  240. />
  241. </div>
  242. <div>
  243. <ul
  244. {...getMenuProps()}
  245. className={classnames('dropdown-menu select-dropdown-menu', {
  246. show: isOpen,
  247. })}
  248. >
  249. {isOpen &&
  250. filteredOptions.map((item, index) => (
  251. <Option
  252. key={item.email}
  253. index={index}
  254. item={item}
  255. selected={index === highlightedIndex}
  256. getItemProps={getItemProps}
  257. />
  258. ))}
  259. </ul>
  260. </div>
  261. </div>
  262. </div>
  263. )
  264. }
  265. function Option({
  266. selected,
  267. item,
  268. getItemProps,
  269. index,
  270. }: {
  271. selected: boolean
  272. item: Contact
  273. getItemProps: (any: any) => any
  274. index: number
  275. }) {
  276. return (
  277. <li {...getItemProps({ item, index })}>
  278. <DropdownItem
  279. as="span"
  280. role={undefined}
  281. leadingIcon="person"
  282. className={classnames({
  283. active: selected,
  284. })}
  285. >
  286. {item.display}
  287. </DropdownItem>
  288. </li>
  289. )
  290. }
  291. function SelectedItem({
  292. removeSelectedItem,
  293. selectedItem,
  294. focusInput,
  295. getSelectedItemProps,
  296. index,
  297. }: {
  298. removeSelectedItem: (item: ContactItem) => void
  299. selectedItem: ContactItem
  300. focusInput: () => void
  301. getSelectedItemProps: (any: any) => any
  302. index: number
  303. }) {
  304. const handleClick = useCallback(
  305. (event: React.MouseEvent) => {
  306. event.preventDefault()
  307. event.stopPropagation()
  308. removeSelectedItem(selectedItem)
  309. focusInput()
  310. },
  311. [focusInput, removeSelectedItem, selectedItem]
  312. )
  313. return (
  314. <Tag
  315. prepend={<MaterialIcon type="person" />}
  316. closeBtnProps={{
  317. onClick: handleClick,
  318. }}
  319. {...getSelectedItemProps({ selectedItem, index })}
  320. >
  321. {selectedItem.display}
  322. </Tag>
  323. )
  324. }