select-collaborators.js 9.4 KB

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