select-collaborators.js 9.2 KB

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