select-collaborators.tsx 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. if (emails.length) {
  217. // pasted comma-separated email addresses
  218. event.preventDefault()
  219. for (const email of emails) {
  220. addNewItem(email)
  221. }
  222. }
  223. }
  224. },
  225. })
  226. )}
  227. />
  228. </div>
  229. <div>
  230. <ul
  231. {...getMenuProps()}
  232. className={classnames('dropdown-menu select-dropdown-menu', {
  233. show: isOpen,
  234. })}
  235. >
  236. {isOpen &&
  237. filteredOptions.map((item, index) => (
  238. <Option
  239. key={item.email}
  240. index={index}
  241. item={item}
  242. selected={index === highlightedIndex}
  243. getItemProps={getItemProps}
  244. />
  245. ))}
  246. </ul>
  247. </div>
  248. </div>
  249. </div>
  250. )
  251. }
  252. function Option({
  253. selected,
  254. item,
  255. getItemProps,
  256. index,
  257. }: {
  258. selected: boolean
  259. item: Contact
  260. getItemProps: (any: any) => any
  261. index: number
  262. }) {
  263. return (
  264. <li {...getItemProps({ item, index })}>
  265. <DropdownItem
  266. as="span"
  267. role={undefined}
  268. leadingIcon="person"
  269. className={classnames({
  270. active: selected,
  271. })}
  272. >
  273. {item.display}
  274. </DropdownItem>
  275. </li>
  276. )
  277. }
  278. function SelectedItem({
  279. removeSelectedItem,
  280. selectedItem,
  281. focusInput,
  282. getSelectedItemProps,
  283. index,
  284. }: {
  285. removeSelectedItem: (item: ContactItem) => void
  286. selectedItem: ContactItem
  287. focusInput: () => void
  288. getSelectedItemProps: (any: any) => any
  289. index: number
  290. }) {
  291. const handleClick = useCallback(
  292. (event: React.MouseEvent) => {
  293. event.preventDefault()
  294. event.stopPropagation()
  295. removeSelectedItem(selectedItem)
  296. focusInput()
  297. },
  298. [focusInput, removeSelectedItem, selectedItem]
  299. )
  300. return (
  301. <Tag
  302. prepend={<MaterialIcon type="person" />}
  303. closeBtnProps={{
  304. onClick: handleClick,
  305. }}
  306. {...getSelectedItemProps({ selectedItem, index })}
  307. >
  308. {selectedItem.display}
  309. </Tag>
  310. )
  311. }