select-collaborators.jsx 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. highlightedIndex,
  84. getItemProps,
  85. reset,
  86. } = useCombobox({
  87. inputValue,
  88. defaultHighlightedIndex: 0,
  89. items: filteredOptions,
  90. itemToString: item => item && item.name,
  91. stateReducer,
  92. onStateChange: ({ inputValue, type, selectedItem }) => {
  93. switch (type) {
  94. // add a selected item on Enter (keypress), click or blur
  95. case useCombobox.stateChangeTypes.InputKeyDownEnter:
  96. case useCombobox.stateChangeTypes.ItemClick:
  97. case useCombobox.stateChangeTypes.InputBlur:
  98. if (selectedItem) {
  99. setInputValue('')
  100. addSelectedItem(selectedItem)
  101. }
  102. break
  103. }
  104. },
  105. })
  106. const addNewItem = useCallback(
  107. (_email, focus = true) => {
  108. const email = _email.replace(matchAllSpaces, '')
  109. if (
  110. isValidInput &&
  111. email.includes('@') &&
  112. !selectedEmails.includes(email)
  113. ) {
  114. addSelectedItem({
  115. email,
  116. display: email,
  117. type: 'user',
  118. })
  119. setInputValue('')
  120. reset()
  121. if (focus) {
  122. focusInput()
  123. }
  124. return true
  125. }
  126. },
  127. [addSelectedItem, selectedEmails, isValidInput, focusInput, reset]
  128. )
  129. // close and reset the menu when there are no matching items
  130. useEffect(() => {
  131. if (isOpen && filteredOptions.length === 0) {
  132. reset()
  133. }
  134. }, [reset, isOpen, filteredOptions.length])
  135. return (
  136. <div className="tags-input tags-new">
  137. {/* eslint-disable-next-line jsx-a11y/label-has-for */}
  138. <label className="small" {...getLabelProps()}>
  139. <strong>
  140. {t('add_people')}
  141. &nbsp;
  142. </strong>
  143. {loading && (
  144. <Spinner
  145. animation="border"
  146. aria-hidden="true"
  147. size="sm"
  148. role="status"
  149. />
  150. )}
  151. </label>
  152. <div className="host">
  153. {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
  154. <div className="tags form-control" onClick={focusInput}>
  155. {selectedItems.map((selectedItem, index) => (
  156. <SelectedItem
  157. key={`selected-item-${index}`}
  158. removeSelectedItem={removeSelectedItem}
  159. selectedItem={selectedItem}
  160. focusInput={focusInput}
  161. index={index}
  162. getSelectedItemProps={getSelectedItemProps}
  163. />
  164. ))}
  165. <input
  166. data-testid="collaborator-email-input"
  167. {...getInputProps(
  168. getDropdownProps({
  169. className: classnames('input', {
  170. 'invalid-tag': !isValidInput,
  171. }),
  172. type: 'email',
  173. placeholder,
  174. size: inputValue.length
  175. ? inputValue.length + 5
  176. : placeholder.length,
  177. ref: inputRef,
  178. // preventKeyAction: showDropdown,
  179. onBlur: () => {
  180. addNewItem(inputValue, false)
  181. },
  182. onChange: e => {
  183. setInputValue(e.target.value)
  184. },
  185. onClick: () => focusInput,
  186. onKeyDown: event => {
  187. switch (event.key) {
  188. case 'Enter':
  189. // Enter: always prevent form submission
  190. event.preventDefault()
  191. event.stopPropagation()
  192. break
  193. case 'Tab':
  194. // Tab: if the dropdown isn't open, try to create a new item using inputValue and prevent blur if successful
  195. if (!isOpen && addNewItem(inputValue)) {
  196. event.preventDefault()
  197. event.stopPropagation()
  198. }
  199. break
  200. case ',':
  201. // comma: try to create a new item using inputValue
  202. event.preventDefault()
  203. addNewItem(inputValue)
  204. break
  205. }
  206. },
  207. onPaste: event => {
  208. const data =
  209. // modern browsers
  210. event.clipboardData?.getData('text/plain') ??
  211. // IE11
  212. window.clipboardData?.getData('text')
  213. if (data) {
  214. const emails = data
  215. .split(/[\r\n,; ]+/)
  216. .filter(item => item.includes('@'))
  217. if (emails.length) {
  218. // pasted comma-separated email addresses
  219. event.preventDefault()
  220. for (const email of emails) {
  221. addNewItem(email)
  222. }
  223. }
  224. }
  225. },
  226. })
  227. )}
  228. />
  229. </div>
  230. <div>
  231. <ul
  232. {...getMenuProps()}
  233. className={classnames('dropdown-menu select-dropdown-menu', {
  234. show: isOpen,
  235. })}
  236. >
  237. {isOpen &&
  238. filteredOptions.map((item, index) => (
  239. <Option
  240. key={item.email}
  241. index={index}
  242. item={item}
  243. selected={index === highlightedIndex}
  244. getItemProps={getItemProps}
  245. />
  246. ))}
  247. </ul>
  248. </div>
  249. </div>
  250. </div>
  251. )
  252. }
  253. SelectCollaborators.propTypes = {
  254. loading: PropTypes.bool.isRequired,
  255. options: PropTypes.array.isRequired,
  256. placeholder: PropTypes.string,
  257. multipleSelectionProps: PropTypes.shape({
  258. getSelectedItemProps: PropTypes.func.isRequired,
  259. getDropdownProps: PropTypes.func.isRequired,
  260. addSelectedItem: PropTypes.func.isRequired,
  261. removeSelectedItem: PropTypes.func.isRequired,
  262. selectedItems: PropTypes.array.isRequired,
  263. }).isRequired,
  264. }
  265. function Option({ selected, item, getItemProps, index }) {
  266. return (
  267. <li {...getItemProps({ item, index })}>
  268. <DropdownItem
  269. as="span"
  270. role={undefined}
  271. leadingIcon="person"
  272. className={classnames({
  273. active: selected,
  274. })}
  275. >
  276. {item.display}
  277. </DropdownItem>
  278. </li>
  279. )
  280. }
  281. Option.propTypes = {
  282. selected: PropTypes.bool.isRequired,
  283. item: PropTypes.shape({
  284. display: PropTypes.string.isRequired,
  285. }),
  286. index: PropTypes.number.isRequired,
  287. getItemProps: PropTypes.func.isRequired,
  288. }
  289. function SelectedItem({
  290. removeSelectedItem,
  291. selectedItem,
  292. focusInput,
  293. getSelectedItemProps,
  294. index,
  295. }) {
  296. const handleClick = useCallback(
  297. event => {
  298. event.preventDefault()
  299. event.stopPropagation()
  300. removeSelectedItem(selectedItem)
  301. focusInput()
  302. },
  303. [focusInput, removeSelectedItem, selectedItem]
  304. )
  305. return (
  306. <Tag
  307. prepend={<MaterialIcon type="person" />}
  308. closeBtnProps={{
  309. onClick: handleClick,
  310. }}
  311. {...getSelectedItemProps({ selectedItem, index })}
  312. >
  313. {selectedItem.display}
  314. </Tag>
  315. )
  316. }
  317. SelectedItem.propTypes = {
  318. focusInput: PropTypes.func.isRequired,
  319. removeSelectedItem: PropTypes.func.isRequired,
  320. selectedItem: PropTypes.shape({
  321. display: PropTypes.string.isRequired,
  322. }),
  323. getSelectedItemProps: PropTypes.func.isRequired,
  324. index: PropTypes.number.isRequired,
  325. }