select-collaborators.js 9.3 KB

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