select-collaborators.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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 { DropdownItem } from '@/shared/components/dropdown/dropdown-menu'
  8. import { Contact } from '../utils/types'
  9. import OLFormLabel from '@/shared/components/ol/ol-form-label'
  10. import OLSpinner from '@/shared/components/ol/ol-spinner'
  11. import OLFormFeedback from '@/shared/components/ol/ol-form-feedback'
  12. import OLRow from '@/shared/components/ol/ol-row'
  13. import OLCol from '@/shared/components/ol/ol-col'
  14. import OLTag from '@/shared/components/ol/ol-tag'
  15. import AddCollaboratorsSelect from '@/features/share-project-modal/components/add-collaborators-select'
  16. import { useFeatureFlag } from '@/shared/context/split-test-context'
  17. import { isValidEmail } from '@/shared/utils/email'
  18. export type ContactItem = {
  19. email: string
  20. display: string
  21. type: string
  22. }
  23. // Unicode characters in these Unicode groups:
  24. // "General Punctuation — Spaces"
  25. // "General Punctuation — Format character" (including zero-width spaces)
  26. const matchAllSpaces =
  27. /[\u061C\u2000-\u200F\u202A-\u202E\u2060\u2066-\u2069\u2028\u2029\u202F]/g
  28. const INPUT_ERRORS = {
  29. ALREADY_MEMBER: 'ALREADY_MEMBER',
  30. INVALID_FORMAT: 'INVALID_FORMAT',
  31. } as const
  32. type InputError = {
  33. key: `${InputError['email']}:${(typeof INPUT_ERRORS)[keyof typeof INPUT_ERRORS]}`
  34. email: string
  35. message: string
  36. }
  37. export default function SelectCollaborators({
  38. loading,
  39. options,
  40. multipleSelectionProps,
  41. currentMemberEmails,
  42. readOnly,
  43. size,
  44. }: {
  45. loading: boolean
  46. options: Contact[]
  47. multipleSelectionProps: UseMultipleSelectionReturnValue<ContactItem>
  48. currentMemberEmails: string[]
  49. readOnly?: boolean
  50. size?: 'lg'
  51. }) {
  52. const isSharingUpdatesEnabled = useFeatureFlag('sharing-updates')
  53. const { t } = useTranslation()
  54. const {
  55. getSelectedItemProps,
  56. getDropdownProps,
  57. addSelectedItem,
  58. removeSelectedItem,
  59. selectedItems,
  60. } = multipleSelectionProps
  61. const [inputValue, setInputValue] = useState('')
  62. const [inviteSent, setInviteSent] = useState(false)
  63. const [inputErrors, setInputErrors] = useState<InputError[]>([])
  64. const selectedEmails = useMemo(
  65. () => selectedItems.map(item => item.email),
  66. [selectedItems]
  67. )
  68. const unselectedOptions = useMemo(
  69. () => options.filter(option => !selectedEmails.includes(option.email)),
  70. [options, selectedEmails]
  71. )
  72. const filteredOptions = useMemo(() => {
  73. if (inputValue === '') {
  74. return unselectedOptions
  75. }
  76. return matchSorter(unselectedOptions, inputValue, {
  77. keys: ['name', 'email'],
  78. threshold: matchSorter.rankings.CONTAINS,
  79. baseSort: (a, b) => {
  80. // Prefer server-side sorting for ties in the match ranking.
  81. return a.index - b.index > 0 ? 1 : -1
  82. },
  83. })
  84. }, [unselectedOptions, inputValue])
  85. const inputRef = useRef<HTMLInputElement>(null)
  86. const focusInput = useCallback(() => {
  87. if (inputRef.current) {
  88. window.setTimeout(() => {
  89. if (inputRef.current) {
  90. inputRef.current.focus()
  91. }
  92. }, 10)
  93. }
  94. }, [inputRef])
  95. const isValidInput = useMemo(() => {
  96. if (inputValue.includes('@')) {
  97. for (const selectedItem of selectedItems) {
  98. if (selectedItem.email === inputValue) {
  99. return false
  100. }
  101. }
  102. }
  103. return true
  104. }, [inputValue, selectedItems])
  105. function stateReducer(_: unknown, actionAndChanges: any) {
  106. const { type, changes } = actionAndChanges
  107. // force selected item to be null so that adding, removing, then re-adding the same collaborator is recognised as a selection change
  108. if (type === useCombobox.stateChangeTypes.InputChange) {
  109. return { ...changes, selectedItem: null }
  110. }
  111. return changes
  112. }
  113. const {
  114. isOpen,
  115. getLabelProps,
  116. getMenuProps,
  117. getInputProps,
  118. highlightedIndex,
  119. getItemProps,
  120. reset,
  121. } = useCombobox({
  122. inputValue,
  123. defaultHighlightedIndex: 0,
  124. items: filteredOptions,
  125. itemToString: item => (item && item.name) || '',
  126. stateReducer,
  127. onStateChange: ({ type, selectedItem }) => {
  128. switch (type) {
  129. // add a selected item on Enter (keypress), click or blur
  130. case useCombobox.stateChangeTypes.InputKeyDownEnter:
  131. case useCombobox.stateChangeTypes.ItemClick:
  132. case useCombobox.stateChangeTypes.InputBlur:
  133. if (selectedItem) {
  134. setInputValue('')
  135. addSelectedItem(selectedItem)
  136. }
  137. break
  138. }
  139. },
  140. })
  141. const addNewItem = useCallback(
  142. (_email: string, focus = true) => {
  143. const email = _email.replace(matchAllSpaces, '')
  144. if (
  145. isValidInput &&
  146. email.includes('@') &&
  147. !selectedEmails.includes(email)
  148. ) {
  149. addSelectedItem({
  150. email,
  151. display: email,
  152. type: 'user',
  153. })
  154. setInputValue('')
  155. reset()
  156. const inputErrorsSetter = (
  157. inputErrors: InputError[],
  158. errorType: (typeof INPUT_ERRORS)[keyof typeof INPUT_ERRORS],
  159. message: InputError['message']
  160. ) => {
  161. const key = `${email}:${errorType}` as const
  162. return [
  163. ...inputErrors.filter(e => !(e.email === email && e.key === key)),
  164. {
  165. key,
  166. email,
  167. message,
  168. },
  169. ]
  170. }
  171. // Validate email format
  172. if (!isValidEmail(email)) {
  173. setInputErrors(prev =>
  174. inputErrorsSetter(
  175. prev,
  176. INPUT_ERRORS.INVALID_FORMAT,
  177. t('email_must_be_a_valid_format')
  178. )
  179. )
  180. }
  181. // Validate against existing members
  182. if (currentMemberEmails.includes(email.toLowerCase())) {
  183. setInputErrors(prev =>
  184. inputErrorsSetter(
  185. prev,
  186. INPUT_ERRORS.ALREADY_MEMBER,
  187. t('only_add_people_who_dont_yet_have_access')
  188. )
  189. )
  190. }
  191. if (focus) {
  192. focusInput()
  193. }
  194. return true
  195. }
  196. },
  197. [
  198. addSelectedItem,
  199. selectedEmails,
  200. isValidInput,
  201. focusInput,
  202. reset,
  203. currentMemberEmails,
  204. t,
  205. ]
  206. )
  207. // close and reset the menu when there are no matching items
  208. useEffect(() => {
  209. if (isOpen && filteredOptions.length === 0) {
  210. reset()
  211. }
  212. }, [reset, isOpen, filteredOptions.length])
  213. useEffect(() => {
  214. setInputErrors(prev => prev.filter(e => selectedEmails.includes(e.email)))
  215. }, [selectedEmails])
  216. return (
  217. <div className="tags-input tags-new">
  218. {isSharingUpdatesEnabled ? (
  219. // eslint-disable-next-line jsx-a11y/label-has-for
  220. <OLFormLabel {...getLabelProps()}>
  221. {t('enter_emails_separated_by_commas')}
  222. </OLFormLabel>
  223. ) : (
  224. // eslint-disable-next-line jsx-a11y/label-has-for
  225. <OLFormLabel className="small" {...getLabelProps()}>
  226. {t('add_email_address')}
  227. {loading && <OLSpinner size="sm" className="ms-2" />}
  228. </OLFormLabel>
  229. )}
  230. <OLRow
  231. className={classnames('align-items-start', {
  232. 'g-2': isSharingUpdatesEnabled,
  233. })}
  234. >
  235. <OLCol>
  236. <div className="host">
  237. {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
  238. <div
  239. className={classnames('tags form-control', {
  240. 'form-control-lg': size === 'lg',
  241. 'is-invalid':
  242. !isValidInput ||
  243. (isSharingUpdatesEnabled && inputErrors.length > 0),
  244. })}
  245. onClick={focusInput}
  246. >
  247. {selectedItems.map((selectedItem, index) => (
  248. <SelectedItem
  249. key={`selected-item-${index}`}
  250. removeSelectedItem={removeSelectedItem}
  251. selectedItem={selectedItem}
  252. focusInput={focusInput}
  253. index={index}
  254. getSelectedItemProps={getSelectedItemProps}
  255. hasIssue={inputErrors.some(
  256. ({ email }) => email === selectedItem.email
  257. )}
  258. />
  259. ))}
  260. <input
  261. data-testid="collaborator-email-input"
  262. aria-describedby={
  263. isSharingUpdatesEnabled
  264. ? undefined
  265. : 'add-collaborator-help-text'
  266. }
  267. {...getInputProps(
  268. getDropdownProps({
  269. className: classnames('input', {
  270. 'invalid-tag': !isSharingUpdatesEnabled && !isValidInput,
  271. 'is-invalid': !isSharingUpdatesEnabled && !isValidInput,
  272. }),
  273. type: 'email',
  274. size: inputValue.length ? inputValue.length + 5 : 5,
  275. ref: inputRef,
  276. // preventKeyAction: showDropdown,
  277. onBlur: () => {
  278. addNewItem(inputValue, false)
  279. },
  280. onChange: e => {
  281. setInputValue((e.target as HTMLInputElement).value)
  282. setInviteSent(false)
  283. },
  284. onClick: () => focusInput,
  285. onKeyDown: event => {
  286. switch (event.key) {
  287. case 'Enter':
  288. // Enter: always prevent form submission
  289. event.preventDefault()
  290. event.stopPropagation()
  291. break
  292. case 'Tab':
  293. // Tab: if the dropdown isn't open, try to create a new item using inputValue and prevent blur if successful
  294. if (!isOpen && addNewItem(inputValue)) {
  295. event.preventDefault()
  296. event.stopPropagation()
  297. }
  298. break
  299. case ',':
  300. // comma: try to create a new item using inputValue
  301. event.preventDefault()
  302. addNewItem(inputValue)
  303. break
  304. }
  305. },
  306. onPaste: event => {
  307. const data =
  308. // modern browsers
  309. event.clipboardData?.getData('text/plain') ??
  310. // @ts-ignore IE11
  311. window.clipboardData?.getData('text')
  312. if (data) {
  313. const emails = data
  314. .split(/[\r\n,; ]+/)
  315. .filter(item => item.includes('@'))
  316. .map(email => email.replace(matchAllSpaces, ''))
  317. if (emails.length) {
  318. // pasted comma-separated email addresses
  319. event.preventDefault()
  320. // dedupe emails in pasted content and previously-entered items
  321. const uniqueEmails = [...new Set(emails)].filter(
  322. email => !selectedEmails.includes(email)
  323. )
  324. for (const email of uniqueEmails) {
  325. addNewItem(email)
  326. }
  327. }
  328. }
  329. },
  330. })
  331. )}
  332. />
  333. </div>
  334. <div>
  335. <ul
  336. {...getMenuProps()}
  337. className={classnames('dropdown-menu select-dropdown-menu', {
  338. show: isOpen,
  339. })}
  340. >
  341. {isOpen &&
  342. filteredOptions.map((item, index) => (
  343. <Option
  344. key={item.email}
  345. index={index}
  346. item={item}
  347. selected={index === highlightedIndex}
  348. getItemProps={getItemProps}
  349. />
  350. ))}
  351. </ul>
  352. </div>
  353. </div>
  354. </OLCol>
  355. {isSharingUpdatesEnabled && (
  356. <OLCol xs="auto">
  357. <div className="add-collaborator-controls">
  358. <AddCollaboratorsSelect
  359. readOnly={readOnly}
  360. multipleSelectionProps={multipleSelectionProps}
  361. currentMemberEmails={currentMemberEmails}
  362. inputValue={inputValue}
  363. onInviteSuccess={() => setInviteSent(true)}
  364. hasErrors={inputErrors.length > 0}
  365. />
  366. </div>
  367. </OLCol>
  368. )}
  369. </OLRow>
  370. {isSharingUpdatesEnabled && (
  371. <>
  372. {inputErrors.length > 0 ? (
  373. inputErrors.length === 1 ? (
  374. <OLFormFeedback type="invalid" unfilled className="d-block">
  375. {inputErrors[0].message}
  376. </OLFormFeedback>
  377. ) : (
  378. <ul className="text-danger m-0 mt-2">
  379. {inputErrors.map(inputError => (
  380. <li key={inputError.key} className="small p-0">
  381. {inputError.message}
  382. </li>
  383. ))}
  384. </ul>
  385. )
  386. ) : null}
  387. {inputErrors.length === 0 && inviteSent && (
  388. <OLFormFeedback type="valid" unfilled className="d-block">
  389. {t('invitations_sent')}
  390. </OLFormFeedback>
  391. )}
  392. </>
  393. )}
  394. </div>
  395. )
  396. }
  397. function Option({
  398. selected,
  399. item,
  400. getItemProps,
  401. index,
  402. }: {
  403. selected: boolean
  404. item: Contact
  405. getItemProps: (any: any) => any
  406. index: number
  407. }) {
  408. const isSharingUpdatesEnabled = useFeatureFlag('sharing-updates')
  409. return (
  410. <li {...getItemProps({ item, index })}>
  411. <DropdownItem
  412. as="span"
  413. role={undefined}
  414. leadingIcon={
  415. isSharingUpdatesEnabled ? (
  416. <MaterialIcon type="person" unfilled />
  417. ) : (
  418. <MaterialIcon type="person" />
  419. )
  420. }
  421. className={classnames({
  422. active: selected,
  423. })}
  424. >
  425. {item.display}
  426. </DropdownItem>
  427. </li>
  428. )
  429. }
  430. function SelectedItem({
  431. removeSelectedItem,
  432. selectedItem,
  433. focusInput,
  434. getSelectedItemProps,
  435. index,
  436. hasIssue,
  437. }: {
  438. removeSelectedItem: (item: ContactItem) => void
  439. selectedItem: ContactItem
  440. focusInput: () => void
  441. getSelectedItemProps: (any: any) => any
  442. index: number
  443. hasIssue?: boolean
  444. }) {
  445. const isSharingUpdatesEnabled = useFeatureFlag('sharing-updates')
  446. const handleClick = useCallback(
  447. (event: React.MouseEvent) => {
  448. event.preventDefault()
  449. event.stopPropagation()
  450. removeSelectedItem(selectedItem)
  451. focusInput()
  452. },
  453. [focusInput, removeSelectedItem, selectedItem]
  454. )
  455. let prepend: React.ReactNode
  456. if (isSharingUpdatesEnabled) {
  457. if (hasIssue) {
  458. prepend = <MaterialIcon type="error" unfilled className="text-danger" />
  459. }
  460. } else {
  461. prepend = <MaterialIcon type="person" />
  462. }
  463. return (
  464. <OLTag
  465. prepend={prepend}
  466. closeBtnProps={{
  467. onClick: handleClick,
  468. }}
  469. translate="no"
  470. {...getSelectedItemProps({ selectedItem, index })}
  471. >
  472. {selectedItem.display}
  473. </OLTag>
  474. )
  475. }