select-collaborators.tsx 15 KB

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