select-collaborators.js 8.9 KB

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