select-collaborators.jsx 9.3 KB

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