select-collaborators.jsx 10 KB

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