select-collaborators.jsx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. // blur: if the dropdown isn't open, try to create a new item using inputValue
  161. if (!isOpen) {
  162. addNewItem(inputValue, false)
  163. }
  164. },
  165. onChange: e => {
  166. setInputValue(e.target.value)
  167. },
  168. onKeyDown: event => {
  169. switch (event.key) {
  170. case 'Enter':
  171. // Enter: always prevent form submission
  172. event.preventDefault()
  173. event.stopPropagation()
  174. break
  175. case 'Tab':
  176. // Tab: if the dropdown isn't open, try to create a new item using inputValue and prevent blur if successful
  177. if (!isOpen && addNewItem(inputValue)) {
  178. event.preventDefault()
  179. event.stopPropagation()
  180. }
  181. break
  182. case ',':
  183. // comma: try to create a new item using inputValue
  184. event.preventDefault()
  185. addNewItem(inputValue)
  186. break
  187. }
  188. },
  189. onPaste: event => {
  190. const data =
  191. // modern browsers
  192. event.clipboardData?.getData('text/plain') ??
  193. // IE11
  194. window.clipboardData?.getData('text')
  195. if (data) {
  196. const emails = data
  197. .split(/[\r\n,; ]+/)
  198. .filter(item => item.includes('@'))
  199. if (emails.length) {
  200. // pasted comma-separated email addresses
  201. event.preventDefault()
  202. for (const email of emails) {
  203. addNewItem(email)
  204. }
  205. }
  206. }
  207. },
  208. })
  209. )}
  210. />
  211. </div>
  212. <div className={classnames({ autocomplete: isOpen })}>
  213. <ul {...getMenuProps()} className="suggestion-list">
  214. {isOpen &&
  215. filteredOptions.map((item, index) => (
  216. <Option
  217. key={item.email}
  218. index={index}
  219. item={item}
  220. selected={index === highlightedIndex}
  221. getItemProps={getItemProps}
  222. />
  223. ))}
  224. </ul>
  225. </div>
  226. </div>
  227. </div>
  228. )
  229. }
  230. SelectCollaborators.propTypes = {
  231. loading: PropTypes.bool.isRequired,
  232. options: PropTypes.array.isRequired,
  233. placeholder: PropTypes.string,
  234. multipleSelectionProps: PropTypes.shape({
  235. getSelectedItemProps: PropTypes.func.isRequired,
  236. getDropdownProps: PropTypes.func.isRequired,
  237. addSelectedItem: PropTypes.func.isRequired,
  238. removeSelectedItem: PropTypes.func.isRequired,
  239. selectedItems: PropTypes.array.isRequired,
  240. }).isRequired,
  241. }
  242. function Option({ selected, item, getItemProps, index }) {
  243. return (
  244. <li
  245. className={classnames('suggestion-item', { selected })}
  246. {...getItemProps({ item, index })}
  247. >
  248. <Icon type="user" fw />
  249. &nbsp;
  250. {item.display}
  251. </li>
  252. )
  253. }
  254. Option.propTypes = {
  255. selected: PropTypes.bool.isRequired,
  256. item: PropTypes.shape({
  257. display: PropTypes.string.isRequired,
  258. }),
  259. index: PropTypes.number.isRequired,
  260. getItemProps: PropTypes.func.isRequired,
  261. }
  262. function SelectedItem({
  263. removeSelectedItem,
  264. selectedItem,
  265. focusInput,
  266. getSelectedItemProps,
  267. index,
  268. }) {
  269. const { t } = useTranslation()
  270. const handleClick = useCallback(
  271. event => {
  272. event.preventDefault()
  273. event.stopPropagation()
  274. removeSelectedItem(selectedItem)
  275. focusInput()
  276. },
  277. [focusInput, removeSelectedItem, selectedItem]
  278. )
  279. return (
  280. <span
  281. className="tag-item"
  282. {...getSelectedItemProps({ selectedItem, index })}
  283. >
  284. <Icon type="user" fw />
  285. <span>{selectedItem.display}</span>
  286. <button
  287. type="button"
  288. className="remove-button btn-inline-link"
  289. aria-label={t('remove')}
  290. onClick={handleClick}
  291. >
  292. <Icon type="close" fw />
  293. </button>
  294. </span>
  295. )
  296. }
  297. SelectedItem.propTypes = {
  298. focusInput: PropTypes.func.isRequired,
  299. removeSelectedItem: PropTypes.func.isRequired,
  300. selectedItem: PropTypes.shape({
  301. display: PropTypes.string.isRequired,
  302. }),
  303. getSelectedItemProps: PropTypes.func.isRequired,
  304. index: PropTypes.number.isRequired,
  305. }