select-collaborators.jsx 9.6 KB

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