select-collaborators.jsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. {...getInputProps(
  172. getDropdownProps({
  173. className: classnames('input', {
  174. 'invalid-tag': !isValidInput,
  175. }),
  176. type: 'email',
  177. placeholder,
  178. size: inputValue.length
  179. ? inputValue.length + 5
  180. : placeholder.length,
  181. ref: inputRef,
  182. // preventKeyAction: showDropdown,
  183. onBlur: () => {
  184. addNewItem(inputValue, false)
  185. },
  186. onChange: e => {
  187. setInputValue(e.target.value)
  188. },
  189. onClick: () => focusInput,
  190. onKeyDown: event => {
  191. switch (event.key) {
  192. case 'Enter':
  193. // Enter: always prevent form submission
  194. event.preventDefault()
  195. event.stopPropagation()
  196. break
  197. case 'Tab':
  198. // Tab: if the dropdown isn't open, try to create a new item using inputValue and prevent blur if successful
  199. if (!isOpen && addNewItem(inputValue)) {
  200. event.preventDefault()
  201. event.stopPropagation()
  202. }
  203. break
  204. case ',':
  205. // comma: try to create a new item using inputValue
  206. event.preventDefault()
  207. addNewItem(inputValue)
  208. break
  209. }
  210. },
  211. onPaste: event => {
  212. const data =
  213. // modern browsers
  214. event.clipboardData?.getData('text/plain') ??
  215. // IE11
  216. window.clipboardData?.getData('text')
  217. if (data) {
  218. const emails = data
  219. .split(/[\r\n,; ]+/)
  220. .filter(item => item.includes('@'))
  221. if (emails.length) {
  222. // pasted comma-separated email addresses
  223. event.preventDefault()
  224. for (const email of emails) {
  225. addNewItem(email)
  226. }
  227. }
  228. }
  229. },
  230. })
  231. )}
  232. />
  233. </div>
  234. <div>
  235. <ul
  236. {...getMenuProps()}
  237. className={classnames('dropdown-menu select-dropdown-menu', {
  238. show: isOpen,
  239. })}
  240. >
  241. {isOpen &&
  242. filteredOptions.map((item, index) => (
  243. <Option
  244. key={item.email}
  245. index={index}
  246. item={item}
  247. selected={index === highlightedIndex}
  248. getItemProps={getItemProps}
  249. />
  250. ))}
  251. </ul>
  252. </div>
  253. </div>
  254. </div>
  255. )
  256. }
  257. SelectCollaborators.propTypes = {
  258. loading: PropTypes.bool.isRequired,
  259. options: PropTypes.array.isRequired,
  260. placeholder: PropTypes.string,
  261. multipleSelectionProps: PropTypes.shape({
  262. getSelectedItemProps: PropTypes.func.isRequired,
  263. getDropdownProps: PropTypes.func.isRequired,
  264. addSelectedItem: PropTypes.func.isRequired,
  265. removeSelectedItem: PropTypes.func.isRequired,
  266. selectedItems: PropTypes.array.isRequired,
  267. }).isRequired,
  268. }
  269. function Option({ selected, item, getItemProps, index }) {
  270. return (
  271. <li {...getItemProps({ item, index })}>
  272. <DropdownItem
  273. as="span"
  274. role={undefined}
  275. leadingIcon="person"
  276. className={classnames({
  277. active: selected,
  278. })}
  279. >
  280. {item.display}
  281. </DropdownItem>
  282. </li>
  283. )
  284. }
  285. Option.propTypes = {
  286. selected: PropTypes.bool.isRequired,
  287. item: PropTypes.shape({
  288. display: PropTypes.string.isRequired,
  289. }),
  290. index: PropTypes.number.isRequired,
  291. getItemProps: PropTypes.func.isRequired,
  292. }
  293. function SelectedItem({
  294. removeSelectedItem,
  295. selectedItem,
  296. focusInput,
  297. getSelectedItemProps,
  298. index,
  299. }) {
  300. const handleClick = useCallback(
  301. event => {
  302. event.preventDefault()
  303. event.stopPropagation()
  304. removeSelectedItem(selectedItem)
  305. focusInput()
  306. },
  307. [focusInput, removeSelectedItem, selectedItem]
  308. )
  309. return (
  310. <Tag
  311. prepend={<MaterialIcon type="person" />}
  312. closeBtnProps={{
  313. onClick: handleClick,
  314. }}
  315. {...getSelectedItemProps({ selectedItem, index })}
  316. >
  317. {selectedItem.display}
  318. </Tag>
  319. )
  320. }
  321. SelectedItem.propTypes = {
  322. focusInput: PropTypes.func.isRequired,
  323. removeSelectedItem: PropTypes.func.isRequired,
  324. selectedItem: PropTypes.shape({
  325. display: PropTypes.string.isRequired,
  326. }),
  327. getSelectedItemProps: PropTypes.func.isRequired,
  328. index: PropTypes.number.isRequired,
  329. }