select-collaborators.tsx 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 { Contact } from '../utils/types'
  10. import OLFormLabel from '@/shared/components/ol/ol-form-label'
  11. import OLSpinner from '@/shared/components/ol/ol-spinner'
  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 && <OLSpinner size="sm" className="ms-2" />}
  152. </OLFormLabel>
  153. <div className="host">
  154. {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
  155. <div className="tags form-control" onClick={focusInput}>
  156. {selectedItems.map((selectedItem, index) => (
  157. <SelectedItem
  158. key={`selected-item-${index}`}
  159. removeSelectedItem={removeSelectedItem}
  160. selectedItem={selectedItem}
  161. focusInput={focusInput}
  162. index={index}
  163. getSelectedItemProps={getSelectedItemProps}
  164. />
  165. ))}
  166. <input
  167. data-testid="collaborator-email-input"
  168. aria-describedby="add-collaborator-help-text"
  169. {...getInputProps(
  170. getDropdownProps({
  171. className: classnames('input', {
  172. 'invalid-tag': !isValidInput,
  173. }),
  174. type: 'email',
  175. size: inputValue.length ? inputValue.length + 5 : 5,
  176. ref: inputRef,
  177. // preventKeyAction: showDropdown,
  178. onBlur: () => {
  179. addNewItem(inputValue, false)
  180. },
  181. onChange: e => {
  182. setInputValue((e.target as HTMLInputElement).value)
  183. },
  184. onClick: () => focusInput,
  185. onKeyDown: event => {
  186. switch (event.key) {
  187. case 'Enter':
  188. // Enter: always prevent form submission
  189. event.preventDefault()
  190. event.stopPropagation()
  191. break
  192. case 'Tab':
  193. // Tab: if the dropdown isn't open, try to create a new item using inputValue and prevent blur if successful
  194. if (!isOpen && addNewItem(inputValue)) {
  195. event.preventDefault()
  196. event.stopPropagation()
  197. }
  198. break
  199. case ',':
  200. // comma: try to create a new item using inputValue
  201. event.preventDefault()
  202. addNewItem(inputValue)
  203. break
  204. }
  205. },
  206. onPaste: event => {
  207. const data =
  208. // modern browsers
  209. event.clipboardData?.getData('text/plain') ??
  210. // @ts-ignore IE11
  211. window.clipboardData?.getData('text')
  212. if (data) {
  213. const emails = data
  214. .split(/[\r\n,; ]+/)
  215. .filter(item => item.includes('@'))
  216. .map(email => email.replace(matchAllSpaces, ''))
  217. if (emails.length) {
  218. // pasted comma-separated email addresses
  219. event.preventDefault()
  220. // dedupe emails in pasted content and previously-entered items
  221. const uniqueEmails = [...new Set(emails)].filter(
  222. email => !selectedEmails.includes(email)
  223. )
  224. for (const email of uniqueEmails) {
  225. addNewItem(email)
  226. }
  227. }
  228. }
  229. },
  230. })
  231. )}
  232. />
  233. </div>
  234. <div>
  235. <ul
  236. {...getMenuProps()}
  237. className={classnames('dropdown-menu select-dropdown-menu', {
  238. show: isOpen,
  239. })}
  240. >
  241. {isOpen &&
  242. filteredOptions.map((item, index) => (
  243. <Option
  244. key={item.email}
  245. index={index}
  246. item={item}
  247. selected={index === highlightedIndex}
  248. getItemProps={getItemProps}
  249. />
  250. ))}
  251. </ul>
  252. </div>
  253. </div>
  254. </div>
  255. )
  256. }
  257. function Option({
  258. selected,
  259. item,
  260. getItemProps,
  261. index,
  262. }: {
  263. selected: boolean
  264. item: Contact
  265. getItemProps: (any: any) => any
  266. index: number
  267. }) {
  268. return (
  269. <li {...getItemProps({ item, index })}>
  270. <DropdownItem
  271. as="span"
  272. role={undefined}
  273. leadingIcon="person"
  274. className={classnames({
  275. active: selected,
  276. })}
  277. >
  278. {item.display}
  279. </DropdownItem>
  280. </li>
  281. )
  282. }
  283. function SelectedItem({
  284. removeSelectedItem,
  285. selectedItem,
  286. focusInput,
  287. getSelectedItemProps,
  288. index,
  289. }: {
  290. removeSelectedItem: (item: ContactItem) => void
  291. selectedItem: ContactItem
  292. focusInput: () => void
  293. getSelectedItemProps: (any: any) => any
  294. index: number
  295. }) {
  296. const handleClick = useCallback(
  297. (event: React.MouseEvent) => {
  298. event.preventDefault()
  299. event.stopPropagation()
  300. removeSelectedItem(selectedItem)
  301. focusInput()
  302. },
  303. [focusInput, removeSelectedItem, selectedItem]
  304. )
  305. return (
  306. <Tag
  307. prepend={<MaterialIcon type="person" />}
  308. closeBtnProps={{
  309. onClick: handleClick,
  310. }}
  311. {...getSelectedItemProps({ selectedItem, index })}
  312. >
  313. {selectedItem.display}
  314. </Tag>
  315. )
  316. }