select-collaborators.jsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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 Icon from '@/shared/components/icon'
  8. import MaterialIcon from '@/shared/components/material-icon'
  9. import Tag from '@/features/ui/components/bootstrap-5/tag'
  10. import { DropdownItem } from '@/features/ui/components/bootstrap-5/dropdown-menu'
  11. import BootstrapVersionSwitcher from '@/features/ui/components/bootstrap-5/bootstrap-version-switcher'
  12. import { bsVersion } from '@/features/utils/bootstrap-5'
  13. import { Spinner } from 'react-bootstrap-5'
  14. // Unicode characters in these Unicode groups:
  15. // "General Punctuation — Spaces"
  16. // "General Punctuation — Format character" (including zero-width spaces)
  17. const matchAllSpaces =
  18. /[\u061C\u2000-\u200F\u202A-\u202E\u2060\u2066-\u2069\u2028\u2029\u202F]/g
  19. export default function SelectCollaborators({
  20. loading,
  21. options,
  22. placeholder,
  23. multipleSelectionProps,
  24. }) {
  25. const { t } = useTranslation()
  26. const {
  27. getSelectedItemProps,
  28. getDropdownProps,
  29. addSelectedItem,
  30. removeSelectedItem,
  31. selectedItems,
  32. } = multipleSelectionProps
  33. const [inputValue, setInputValue] = useState('')
  34. const selectedEmails = useMemo(
  35. () => selectedItems.map(item => item.email),
  36. [selectedItems]
  37. )
  38. const unselectedOptions = useMemo(
  39. () => options.filter(option => !selectedEmails.includes(option.email)),
  40. [options, selectedEmails]
  41. )
  42. const filteredOptions = useMemo(() => {
  43. if (inputValue === '') {
  44. return unselectedOptions
  45. }
  46. return matchSorter(unselectedOptions, inputValue, {
  47. keys: ['name', 'email'],
  48. threshold: matchSorter.rankings.CONTAINS,
  49. baseSort: (a, b) => {
  50. // Prefer server-side sorting for ties in the match ranking.
  51. return a.index - b.index > 0 ? 1 : -1
  52. },
  53. })
  54. }, [unselectedOptions, inputValue])
  55. const inputRef = useRef(null)
  56. const focusInput = useCallback(() => {
  57. if (inputRef.current) {
  58. window.setTimeout(() => {
  59. inputRef.current.focus()
  60. }, 10)
  61. }
  62. }, [inputRef])
  63. const isValidInput = useMemo(() => {
  64. if (inputValue.includes('@')) {
  65. for (const selectedItem of selectedItems) {
  66. if (selectedItem.email === inputValue) {
  67. return false
  68. }
  69. }
  70. }
  71. return true
  72. }, [inputValue, selectedItems])
  73. function stateReducer(state, actionAndChanges) {
  74. const { type, changes } = actionAndChanges
  75. // force selected item to be null so that adding, removing, then re-adding the same collaborator is recognised as a selection change
  76. if (type === useCombobox.stateChangeTypes.InputChange) {
  77. return { ...changes, selectedItem: null }
  78. }
  79. return changes
  80. }
  81. const {
  82. isOpen,
  83. getLabelProps,
  84. getMenuProps,
  85. getInputProps,
  86. getComboboxProps,
  87. highlightedIndex,
  88. getItemProps,
  89. reset,
  90. } = useCombobox({
  91. inputValue,
  92. defaultHighlightedIndex: 0,
  93. items: filteredOptions,
  94. itemToString: item => item && item.name,
  95. stateReducer,
  96. onStateChange: ({ inputValue, type, selectedItem }) => {
  97. switch (type) {
  98. // add a selected item on Enter (keypress), click or blur
  99. case useCombobox.stateChangeTypes.InputKeyDownEnter:
  100. case useCombobox.stateChangeTypes.ItemClick:
  101. case useCombobox.stateChangeTypes.InputBlur:
  102. if (selectedItem) {
  103. setInputValue('')
  104. addSelectedItem(selectedItem)
  105. }
  106. break
  107. }
  108. },
  109. })
  110. const addNewItem = useCallback(
  111. (_email, focus = true) => {
  112. const email = _email.replace(matchAllSpaces, '')
  113. if (
  114. isValidInput &&
  115. email.includes('@') &&
  116. !selectedEmails.includes(email)
  117. ) {
  118. addSelectedItem({
  119. email,
  120. display: email,
  121. type: 'user',
  122. })
  123. setInputValue('')
  124. reset()
  125. if (focus) {
  126. focusInput()
  127. }
  128. return true
  129. }
  130. },
  131. [addSelectedItem, selectedEmails, isValidInput, focusInput, reset]
  132. )
  133. // close and reset the menu when there are no matching items
  134. useEffect(() => {
  135. if (isOpen && filteredOptions.length === 0) {
  136. reset()
  137. }
  138. }, [reset, isOpen, filteredOptions.length])
  139. return (
  140. <div className="tags-input tags-new">
  141. {/* eslint-disable-next-line jsx-a11y/label-has-for */}
  142. <label className="small" {...getLabelProps()}>
  143. <strong>
  144. {t('add_people')}
  145. &nbsp;
  146. </strong>
  147. {loading && (
  148. <BootstrapVersionSwitcher
  149. bs3={<Icon type="refresh" spin />}
  150. bs5={
  151. <Spinner
  152. animation="border"
  153. aria-hidden="true"
  154. size="sm"
  155. role="status"
  156. />
  157. }
  158. />
  159. )}
  160. </label>
  161. <div className="host">
  162. {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
  163. <div
  164. {...getComboboxProps()}
  165. className="tags form-control"
  166. onClick={focusInput}
  167. >
  168. {selectedItems.map((selectedItem, index) => (
  169. <SelectedItem
  170. key={`selected-item-${index}`}
  171. removeSelectedItem={removeSelectedItem}
  172. selectedItem={selectedItem}
  173. focusInput={focusInput}
  174. index={index}
  175. getSelectedItemProps={getSelectedItemProps}
  176. />
  177. ))}
  178. <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.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. // 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. className={bsVersion({ bs3: classnames({ autocomplete: isOpen }) })}
  244. >
  245. <ul
  246. {...getMenuProps()}
  247. className={classnames(
  248. bsVersion({
  249. bs3: 'suggestion-list',
  250. bs5: classnames('dropdown-menu select-dropdown-menu', {
  251. show: isOpen,
  252. }),
  253. })
  254. )}
  255. >
  256. {isOpen &&
  257. filteredOptions.map((item, index) => (
  258. <Option
  259. key={item.email}
  260. index={index}
  261. item={item}
  262. selected={index === highlightedIndex}
  263. getItemProps={getItemProps}
  264. />
  265. ))}
  266. </ul>
  267. </div>
  268. </div>
  269. </div>
  270. )
  271. }
  272. SelectCollaborators.propTypes = {
  273. loading: PropTypes.bool.isRequired,
  274. options: PropTypes.array.isRequired,
  275. placeholder: PropTypes.string,
  276. multipleSelectionProps: PropTypes.shape({
  277. getSelectedItemProps: PropTypes.func.isRequired,
  278. getDropdownProps: PropTypes.func.isRequired,
  279. addSelectedItem: PropTypes.func.isRequired,
  280. removeSelectedItem: PropTypes.func.isRequired,
  281. selectedItems: PropTypes.array.isRequired,
  282. }).isRequired,
  283. }
  284. function Option({ selected, item, getItemProps, index }) {
  285. return (
  286. <li
  287. className={bsVersion({
  288. bs3: classnames('suggestion-item', { selected }),
  289. })}
  290. {...getItemProps({ item, index })}
  291. >
  292. <BootstrapVersionSwitcher
  293. bs3={
  294. <>
  295. <Icon type="user" fw />
  296. &nbsp;
  297. {item.display}
  298. </>
  299. }
  300. bs5={
  301. <DropdownItem
  302. as="span"
  303. role={undefined}
  304. leadingIcon="person"
  305. className={classnames({
  306. active: selected,
  307. })}
  308. >
  309. {item.display}
  310. </DropdownItem>
  311. }
  312. />
  313. </li>
  314. )
  315. }
  316. Option.propTypes = {
  317. selected: PropTypes.bool.isRequired,
  318. item: PropTypes.shape({
  319. display: PropTypes.string.isRequired,
  320. }),
  321. index: PropTypes.number.isRequired,
  322. getItemProps: PropTypes.func.isRequired,
  323. }
  324. function SelectedItem({
  325. removeSelectedItem,
  326. selectedItem,
  327. focusInput,
  328. getSelectedItemProps,
  329. index,
  330. }) {
  331. const { t } = useTranslation()
  332. const handleClick = useCallback(
  333. event => {
  334. event.preventDefault()
  335. event.stopPropagation()
  336. removeSelectedItem(selectedItem)
  337. focusInput()
  338. },
  339. [focusInput, removeSelectedItem, selectedItem]
  340. )
  341. return (
  342. <BootstrapVersionSwitcher
  343. bs3={
  344. <span
  345. className="tag-item"
  346. {...getSelectedItemProps({ selectedItem, index })}
  347. >
  348. <Icon type="user" fw />
  349. <span>{selectedItem.display}</span>
  350. <button
  351. type="button"
  352. className="remove-button btn-inline-link"
  353. aria-label={t('remove')}
  354. onClick={handleClick}
  355. >
  356. <Icon type="close" fw />
  357. </button>
  358. </span>
  359. }
  360. bs5={
  361. <Tag
  362. prepend={
  363. <BootstrapVersionSwitcher
  364. bs3={<Icon type="user" fw />}
  365. bs5={<MaterialIcon type="person" />}
  366. />
  367. }
  368. closeBtnProps={{
  369. onClick: handleClick,
  370. }}
  371. {...getSelectedItemProps({ selectedItem, index })}
  372. >
  373. {selectedItem.display}
  374. </Tag>
  375. }
  376. />
  377. )
  378. }
  379. SelectedItem.propTypes = {
  380. focusInput: PropTypes.func.isRequired,
  381. removeSelectedItem: PropTypes.func.isRequired,
  382. selectedItem: PropTypes.shape({
  383. display: PropTypes.string.isRequired,
  384. }),
  385. getSelectedItemProps: PropTypes.func.isRequired,
  386. index: PropTypes.number.isRequired,
  387. }