select-collaborators.tsx 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. import { useEffect, useMemo, useState, useRef, useCallback } from 'react'
  2. import { useTranslation } from 'react-i18next'
  3. import { matchSorter } from 'match-sorter'
  4. import { useCombobox, UseMultipleSelectionReturnValue } from 'downshift'
  5. import classnames from 'classnames'
  6. import MaterialIcon from '@/shared/components/material-icon'
  7. import Tag from '@/shared/components/tag'
  8. import { DropdownItem } from '@/shared/components/dropdown/dropdown-menu'
  9. import { Spinner } from 'react-bootstrap'
  10. import { Contact } from '../utils/types'
  11. import OLFormLabel from '@/shared/components/ol/ol-form-label'
  12. export type ContactItem = {
  13. email: string
  14. display: string
  15. type: string
  16. }
  17. // Unicode characters in these Unicode groups:
  18. // "General Punctuation — Spaces"
  19. // "General Punctuation — Format character" (including zero-width spaces)
  20. const matchAllSpaces =
  21. /[\u061C\u2000-\u200F\u202A-\u202E\u2060\u2066-\u2069\u2028\u2029\u202F]/g
  22. export default function SelectCollaborators({
  23. loading,
  24. options,
  25. multipleSelectionProps,
  26. }: {
  27. loading: boolean
  28. options: Contact[]
  29. multipleSelectionProps: UseMultipleSelectionReturnValue<ContactItem>
  30. }) {
  31. const { t } = useTranslation()
  32. const {
  33. getSelectedItemProps,
  34. getDropdownProps,
  35. addSelectedItem,
  36. removeSelectedItem,
  37. selectedItems,
  38. } = multipleSelectionProps
  39. const [inputValue, setInputValue] = useState('')
  40. const selectedEmails = useMemo(
  41. () => selectedItems.map(item => item.email),
  42. [selectedItems]
  43. )
  44. const unselectedOptions = useMemo(
  45. () => options.filter(option => !selectedEmails.includes(option.email)),
  46. [options, selectedEmails]
  47. )
  48. const filteredOptions = useMemo(() => {
  49. if (inputValue === '') {
  50. return unselectedOptions
  51. }
  52. return matchSorter(unselectedOptions, inputValue, {
  53. keys: ['name', 'email'],
  54. threshold: matchSorter.rankings.CONTAINS,
  55. baseSort: (a, b) => {
  56. // Prefer server-side sorting for ties in the match ranking.
  57. return a.index - b.index > 0 ? 1 : -1
  58. },
  59. })
  60. }, [unselectedOptions, inputValue])
  61. const inputRef = useRef<HTMLInputElement>(null)
  62. const focusInput = useCallback(() => {
  63. if (inputRef.current) {
  64. window.setTimeout(() => {
  65. if (inputRef.current) {
  66. inputRef.current.focus()
  67. }
  68. }, 10)
  69. }
  70. }, [inputRef])
  71. const isValidInput = useMemo(() => {
  72. if (inputValue.includes('@')) {
  73. for (const selectedItem of selectedItems) {
  74. if (selectedItem.email === inputValue) {
  75. return false
  76. }
  77. }
  78. }
  79. return true
  80. }, [inputValue, selectedItems])
  81. function stateReducer(_: unknown, actionAndChanges: any) {
  82. const { type, changes } = actionAndChanges
  83. // force selected item to be null so that adding, removing, then re-adding the same collaborator is recognised as a selection change
  84. if (type === useCombobox.stateChangeTypes.InputChange) {
  85. return { ...changes, selectedItem: null }
  86. }
  87. return changes
  88. }
  89. const {
  90. isOpen,
  91. getLabelProps,
  92. getMenuProps,
  93. getInputProps,
  94. highlightedIndex,
  95. getItemProps,
  96. reset,
  97. } = useCombobox({
  98. inputValue,
  99. defaultHighlightedIndex: 0,
  100. items: filteredOptions,
  101. itemToString: item => (item && item.name) || '',
  102. stateReducer,
  103. onStateChange: ({ type, selectedItem }) => {
  104. switch (type) {
  105. // add a selected item on Enter (keypress), click or blur
  106. case useCombobox.stateChangeTypes.InputKeyDownEnter:
  107. case useCombobox.stateChangeTypes.ItemClick:
  108. case useCombobox.stateChangeTypes.InputBlur:
  109. if (selectedItem) {
  110. setInputValue('')
  111. addSelectedItem(selectedItem)
  112. }
  113. break
  114. }
  115. },
  116. })
  117. const addNewItem = useCallback(
  118. (_email: string, focus = true) => {
  119. const email = _email.replace(matchAllSpaces, '')
  120. if (
  121. isValidInput &&
  122. email.includes('@') &&
  123. !selectedEmails.includes(email)
  124. ) {
  125. addSelectedItem({
  126. email,
  127. display: email,
  128. type: 'user',
  129. })
  130. setInputValue('')
  131. reset()
  132. if (focus) {
  133. focusInput()
  134. }
  135. return true
  136. }
  137. },
  138. [addSelectedItem, selectedEmails, isValidInput, focusInput, reset]
  139. )
  140. // close and reset the menu when there are no matching items
  141. useEffect(() => {
  142. if (isOpen && filteredOptions.length === 0) {
  143. reset()
  144. }
  145. }, [reset, isOpen, filteredOptions.length])
  146. return (
  147. <div className="tags-input tags-new">
  148. {/* eslint-disable-next-line jsx-a11y/label-has-for */}
  149. <OLFormLabel className="small" {...getLabelProps()}>
  150. {t('add_email_address')}
  151. {loading && (
  152. <Spinner
  153. animation="border"
  154. aria-hidden="true"
  155. size="sm"
  156. role="status"
  157. className="ms-2"
  158. />
  159. )}
  160. </OLFormLabel>
  161. <div className="host">
  162. {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
  163. <div className="tags form-control" onClick={focusInput}>
  164. {selectedItems.map((selectedItem, index) => (
  165. <SelectedItem
  166. key={`selected-item-${index}`}
  167. removeSelectedItem={removeSelectedItem}
  168. selectedItem={selectedItem}
  169. focusInput={focusInput}
  170. index={index}
  171. getSelectedItemProps={getSelectedItemProps}
  172. />
  173. ))}
  174. <input
  175. data-testid="collaborator-email-input"
  176. aria-describedby="add-collaborator-help-text"
  177. {...getInputProps(
  178. getDropdownProps({
  179. className: classnames('input', {
  180. 'invalid-tag': !isValidInput,
  181. }),
  182. type: 'email',
  183. size: inputValue.length ? inputValue.length + 5 : 5,
  184. ref: inputRef,
  185. // preventKeyAction: showDropdown,
  186. onBlur: () => {
  187. addNewItem(inputValue, false)
  188. },
  189. onChange: e => {
  190. setInputValue((e.target as HTMLInputElement).value)
  191. },
  192. onClick: () => focusInput,
  193. onKeyDown: event => {
  194. switch (event.key) {
  195. case 'Enter':
  196. // Enter: always prevent form submission
  197. event.preventDefault()
  198. event.stopPropagation()
  199. break
  200. case 'Tab':
  201. // Tab: if the dropdown isn't open, try to create a new item using inputValue and prevent blur if successful
  202. if (!isOpen && addNewItem(inputValue)) {
  203. event.preventDefault()
  204. event.stopPropagation()
  205. }
  206. break
  207. case ',':
  208. // comma: try to create a new item using inputValue
  209. event.preventDefault()
  210. addNewItem(inputValue)
  211. break
  212. }
  213. },
  214. onPaste: event => {
  215. const data =
  216. // modern browsers
  217. event.clipboardData?.getData('text/plain') ??
  218. // @ts-ignore IE11
  219. window.clipboardData?.getData('text')
  220. if (data) {
  221. const emails = data
  222. .split(/[\r\n,; ]+/)
  223. .filter(item => item.includes('@'))
  224. if (emails.length) {
  225. // pasted comma-separated email addresses
  226. event.preventDefault()
  227. for (const email of emails) {
  228. addNewItem(email)
  229. }
  230. }
  231. }
  232. },
  233. })
  234. )}
  235. />
  236. </div>
  237. <div>
  238. <ul
  239. {...getMenuProps()}
  240. className={classnames('dropdown-menu select-dropdown-menu', {
  241. show: isOpen,
  242. })}
  243. >
  244. {isOpen &&
  245. filteredOptions.map((item, index) => (
  246. <Option
  247. key={item.email}
  248. index={index}
  249. item={item}
  250. selected={index === highlightedIndex}
  251. getItemProps={getItemProps}
  252. />
  253. ))}
  254. </ul>
  255. </div>
  256. </div>
  257. </div>
  258. )
  259. }
  260. function Option({
  261. selected,
  262. item,
  263. getItemProps,
  264. index,
  265. }: {
  266. selected: boolean
  267. item: Contact
  268. getItemProps: (any: any) => any
  269. index: number
  270. }) {
  271. return (
  272. <li {...getItemProps({ item, index })}>
  273. <DropdownItem
  274. as="span"
  275. role={undefined}
  276. leadingIcon="person"
  277. className={classnames({
  278. active: selected,
  279. })}
  280. >
  281. {item.display}
  282. </DropdownItem>
  283. </li>
  284. )
  285. }
  286. function SelectedItem({
  287. removeSelectedItem,
  288. selectedItem,
  289. focusInput,
  290. getSelectedItemProps,
  291. index,
  292. }: {
  293. removeSelectedItem: (item: ContactItem) => void
  294. selectedItem: ContactItem
  295. focusInput: () => void
  296. getSelectedItemProps: (any: any) => any
  297. index: number
  298. }) {
  299. const handleClick = useCallback(
  300. (event: React.MouseEvent) => {
  301. event.preventDefault()
  302. event.stopPropagation()
  303. removeSelectedItem(selectedItem)
  304. focusInput()
  305. },
  306. [focusInput, removeSelectedItem, selectedItem]
  307. )
  308. return (
  309. <Tag
  310. prepend={<MaterialIcon type="person" />}
  311. closeBtnProps={{
  312. onClick: handleClick,
  313. }}
  314. {...getSelectedItemProps({ selectedItem, index })}
  315. >
  316. {selectedItem.display}
  317. </Tag>
  318. )
  319. }