select-collaborators.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. if (inputValue === '') {
  35. return unselectedOptions
  36. }
  37. return matchSorter(unselectedOptions, inputValue, {
  38. keys: ['name', 'email'],
  39. threshold: matchSorter.rankings.CONTAINS,
  40. baseSort: (a, b) => {
  41. // Prefer server-side sorting for ties in the match ranking.
  42. return a.index - b.index > 0 ? 1 : -1
  43. },
  44. })
  45. }, [unselectedOptions, inputValue])
  46. const inputRef = useRef(null)
  47. const focusInput = useCallback(() => {
  48. if (inputRef.current) {
  49. window.setTimeout(() => {
  50. inputRef.current.focus()
  51. }, 10)
  52. }
  53. }, [inputRef])
  54. const isValidInput = useMemo(() => {
  55. if (inputValue.includes('@')) {
  56. for (const selectedItem of selectedItems) {
  57. if (selectedItem.email === inputValue) {
  58. return false
  59. }
  60. }
  61. }
  62. return true
  63. }, [inputValue, selectedItems])
  64. const {
  65. isOpen,
  66. getLabelProps,
  67. getMenuProps,
  68. getInputProps,
  69. getComboboxProps,
  70. highlightedIndex,
  71. getItemProps,
  72. reset,
  73. } = useCombobox({
  74. inputValue,
  75. defaultHighlightedIndex: 0,
  76. items: filteredOptions,
  77. itemToString: item => item && item.name,
  78. onStateChange: ({ inputValue, type, selectedItem }) => {
  79. switch (type) {
  80. // add a selected item on Enter (keypress), click or blur
  81. case useCombobox.stateChangeTypes.InputKeyDownEnter:
  82. case useCombobox.stateChangeTypes.ItemClick:
  83. case useCombobox.stateChangeTypes.InputBlur:
  84. if (selectedItem) {
  85. setInputValue('')
  86. addSelectedItem(selectedItem)
  87. }
  88. break
  89. }
  90. },
  91. })
  92. const addNewItem = useCallback(
  93. (_email, focus = true) => {
  94. const email = _email.replace(matchAllSpaces, '')
  95. if (
  96. isValidInput &&
  97. email.includes('@') &&
  98. !selectedEmails.includes(email)
  99. ) {
  100. addSelectedItem({
  101. email,
  102. display: email,
  103. type: 'user',
  104. })
  105. setInputValue('')
  106. reset()
  107. if (focus) {
  108. focusInput()
  109. }
  110. return true
  111. }
  112. },
  113. [addSelectedItem, selectedEmails, isValidInput, focusInput, reset]
  114. )
  115. // close and reset the menu when there are no matching items
  116. useEffect(() => {
  117. if (isOpen && filteredOptions.length === 0) {
  118. reset()
  119. }
  120. }, [reset, isOpen, filteredOptions.length])
  121. return (
  122. <div className="tags-input">
  123. {/* eslint-disable-next-line jsx-a11y/label-has-for */}
  124. <label className="small" {...getLabelProps()}>
  125. <Trans i18nKey="share_with_your_collabs" />
  126. &nbsp;
  127. {loading && <Icon type="refresh" spin />}
  128. </label>
  129. <div className="host">
  130. {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
  131. <div {...getComboboxProps()} className="tags" onClick={focusInput}>
  132. {selectedItems.map((selectedItem, index) => (
  133. <SelectedItem
  134. key={`selected-item-${index}`}
  135. removeSelectedItem={removeSelectedItem}
  136. selectedItem={selectedItem}
  137. focusInput={focusInput}
  138. index={index}
  139. getSelectedItemProps={getSelectedItemProps}
  140. />
  141. ))}
  142. <input
  143. {...getInputProps(
  144. getDropdownProps({
  145. className: classnames({
  146. input: true,
  147. 'invalid-tag': !isValidInput,
  148. }),
  149. type: 'email',
  150. placeholder,
  151. size: inputValue.length
  152. ? inputValue.length + 5
  153. : placeholder.length,
  154. ref: inputRef,
  155. // preventKeyAction: showDropdown,
  156. onBlur: () => {
  157. // blur: if the dropdown isn't open, try to create a new item using inputValue
  158. if (!isOpen) {
  159. addNewItem(inputValue, false)
  160. }
  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(/\s*,\s*/)
  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" modifier="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" modifier="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" modifier="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. }