select-collaborators.jsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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">
  141. {/* eslint-disable-next-line jsx-a11y/label-has-for */}
  142. <label className="small" {...getLabelProps()}>
  143. {t('share_with_your_collabs')}
  144. &nbsp;
  145. {loading && (
  146. <BootstrapVersionSwitcher
  147. bs3={<Icon type="refresh" spin />}
  148. bs5={
  149. <Spinner
  150. animation="border"
  151. aria-hidden="true"
  152. size="sm"
  153. role="status"
  154. />
  155. }
  156. />
  157. )}
  158. </label>
  159. <div className="host">
  160. {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
  161. <div
  162. {...getComboboxProps()}
  163. className="tags form-control"
  164. onClick={focusInput}
  165. >
  166. {selectedItems.map((selectedItem, index) => (
  167. <SelectedItem
  168. key={`selected-item-${index}`}
  169. removeSelectedItem={removeSelectedItem}
  170. selectedItem={selectedItem}
  171. focusInput={focusInput}
  172. index={index}
  173. getSelectedItemProps={getSelectedItemProps}
  174. />
  175. ))}
  176. <input
  177. {...getInputProps(
  178. getDropdownProps({
  179. className: classnames('input', {
  180. 'invalid-tag': !isValidInput,
  181. }),
  182. type: 'email',
  183. placeholder,
  184. size: inputValue.length
  185. ? inputValue.length + 5
  186. : placeholder.length,
  187. ref: inputRef,
  188. // preventKeyAction: showDropdown,
  189. onBlur: () => {
  190. addNewItem(inputValue, false)
  191. },
  192. onChange: e => {
  193. setInputValue(e.target.value)
  194. },
  195. onKeyDown: event => {
  196. switch (event.key) {
  197. case 'Enter':
  198. // Enter: always prevent form submission
  199. event.preventDefault()
  200. event.stopPropagation()
  201. break
  202. case 'Tab':
  203. // Tab: if the dropdown isn't open, try to create a new item using inputValue and prevent blur if successful
  204. if (!isOpen && addNewItem(inputValue)) {
  205. event.preventDefault()
  206. event.stopPropagation()
  207. }
  208. break
  209. case ',':
  210. // comma: try to create a new item using inputValue
  211. event.preventDefault()
  212. addNewItem(inputValue)
  213. break
  214. }
  215. },
  216. onPaste: event => {
  217. const data =
  218. // modern browsers
  219. event.clipboardData?.getData('text/plain') ??
  220. // IE11
  221. window.clipboardData?.getData('text')
  222. if (data) {
  223. const emails = data
  224. .split(/[\r\n,; ]+/)
  225. .filter(item => item.includes('@'))
  226. if (emails.length) {
  227. // pasted comma-separated email addresses
  228. event.preventDefault()
  229. for (const email of emails) {
  230. addNewItem(email)
  231. }
  232. }
  233. }
  234. },
  235. })
  236. )}
  237. />
  238. </div>
  239. <div
  240. className={bsVersion({ bs3: classnames({ autocomplete: isOpen }) })}
  241. >
  242. <ul
  243. {...getMenuProps()}
  244. className={classnames(
  245. bsVersion({
  246. bs3: 'suggestion-list',
  247. bs5: classnames('dropdown-menu select-dropdown-menu', {
  248. show: isOpen,
  249. }),
  250. })
  251. )}
  252. >
  253. {isOpen &&
  254. filteredOptions.map((item, index) => (
  255. <Option
  256. key={item.email}
  257. index={index}
  258. item={item}
  259. selected={index === highlightedIndex}
  260. getItemProps={getItemProps}
  261. />
  262. ))}
  263. </ul>
  264. </div>
  265. </div>
  266. </div>
  267. )
  268. }
  269. SelectCollaborators.propTypes = {
  270. loading: PropTypes.bool.isRequired,
  271. options: PropTypes.array.isRequired,
  272. placeholder: PropTypes.string,
  273. multipleSelectionProps: PropTypes.shape({
  274. getSelectedItemProps: PropTypes.func.isRequired,
  275. getDropdownProps: PropTypes.func.isRequired,
  276. addSelectedItem: PropTypes.func.isRequired,
  277. removeSelectedItem: PropTypes.func.isRequired,
  278. selectedItems: PropTypes.array.isRequired,
  279. }).isRequired,
  280. }
  281. function Option({ selected, item, getItemProps, index }) {
  282. return (
  283. <li
  284. className={bsVersion({
  285. bs3: classnames('suggestion-item', { selected }),
  286. })}
  287. {...getItemProps({ item, index })}
  288. >
  289. <BootstrapVersionSwitcher
  290. bs3={
  291. <>
  292. <Icon type="user" fw />
  293. &nbsp;
  294. {item.display}
  295. </>
  296. }
  297. bs5={
  298. <DropdownItem
  299. as="span"
  300. role={undefined}
  301. leadingIcon="person"
  302. className={classnames({
  303. active: selected,
  304. })}
  305. >
  306. {item.display}
  307. </DropdownItem>
  308. }
  309. />
  310. </li>
  311. )
  312. }
  313. Option.propTypes = {
  314. selected: PropTypes.bool.isRequired,
  315. item: PropTypes.shape({
  316. display: PropTypes.string.isRequired,
  317. }),
  318. index: PropTypes.number.isRequired,
  319. getItemProps: PropTypes.func.isRequired,
  320. }
  321. function SelectedItem({
  322. removeSelectedItem,
  323. selectedItem,
  324. focusInput,
  325. getSelectedItemProps,
  326. index,
  327. }) {
  328. const { t } = useTranslation()
  329. const handleClick = useCallback(
  330. event => {
  331. event.preventDefault()
  332. event.stopPropagation()
  333. removeSelectedItem(selectedItem)
  334. focusInput()
  335. },
  336. [focusInput, removeSelectedItem, selectedItem]
  337. )
  338. return (
  339. <BootstrapVersionSwitcher
  340. bs3={
  341. <span
  342. className="tag-item"
  343. {...getSelectedItemProps({ selectedItem, index })}
  344. >
  345. <Icon type="user" fw />
  346. <span>{selectedItem.display}</span>
  347. <button
  348. type="button"
  349. className="remove-button btn-inline-link"
  350. aria-label={t('remove')}
  351. onClick={handleClick}
  352. >
  353. <Icon type="close" fw />
  354. </button>
  355. </span>
  356. }
  357. bs5={
  358. <Tag
  359. prepend={
  360. <BootstrapVersionSwitcher
  361. bs3={<Icon type="user" fw />}
  362. bs5={<MaterialIcon type="person" />}
  363. />
  364. }
  365. closeBtnProps={{
  366. onClick: handleClick,
  367. }}
  368. {...getSelectedItemProps({ selectedItem, index })}
  369. >
  370. {selectedItem.display}
  371. </Tag>
  372. }
  373. />
  374. )
  375. }
  376. SelectedItem.propTypes = {
  377. focusInput: PropTypes.func.isRequired,
  378. removeSelectedItem: PropTypes.func.isRequired,
  379. selectedItem: PropTypes.shape({
  380. display: PropTypes.string.isRequired,
  381. }),
  382. getSelectedItemProps: PropTypes.func.isRequired,
  383. index: PropTypes.number.isRequired,
  384. }