share-project-modal.test.tsx 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  1. import { expect } from 'chai'
  2. import sinon from 'sinon'
  3. import { screen, Screen, fireEvent, waitFor } from '@testing-library/react'
  4. import fetchMock, { CallLog } from 'fetch-mock'
  5. import userEvent from '@testing-library/user-event'
  6. import ShareProjectModal from '../../../../../frontend/js/features/share-project-modal/components/share-project-modal'
  7. import { renderWithEditorContext } from '../../../helpers/render-with-context'
  8. import {
  9. makeProjectProvider,
  10. projectDefaults,
  11. USER_EMAIL,
  12. USER_ID,
  13. } from '../../../helpers/editor-providers'
  14. import { location } from '@/shared/components/location'
  15. import { useProjectContext } from '@/shared/context/project-context'
  16. import {
  17. ProjectMember,
  18. ProjectMetadata,
  19. } from '@/shared/context/types/project-metadata'
  20. import { UserId } from '@ol-types/user'
  21. import { PublicAccessLevel } from '@ol-types/public-access-level'
  22. async function changePrivilegeLevel(
  23. screen: Screen,
  24. { current, next }: { current: string; next: string }
  25. ) {
  26. const select = screen.getByDisplayValue(current)
  27. fireEvent.click(select)
  28. const option = screen.getByRole('option', {
  29. name: next,
  30. })
  31. fireEvent.click(option)
  32. }
  33. const testProjectOverrides: Partial<ProjectMetadata> = {
  34. _id: 'test-project',
  35. name: 'Test Project',
  36. features: {
  37. collaborators: 10,
  38. compileGroup: 'standard',
  39. },
  40. owner: {
  41. _id: USER_ID,
  42. email: USER_EMAIL,
  43. first_name: 'Test',
  44. last_name: 'Owner',
  45. privileges: 'owner',
  46. signUpDate: new Date('2025-07-07').toISOString(),
  47. },
  48. }
  49. const shareModalProjectDefaults: ProjectMetadata = Object.assign(
  50. {},
  51. projectDefaults,
  52. testProjectOverrides
  53. )
  54. function createContextProps(projectOverrides?: Partial<ProjectMetadata>) {
  55. const project = Object.assign({}, shareModalProjectDefaults, projectOverrides)
  56. return { providers: { ProjectProvider: makeProjectProvider(project) } }
  57. }
  58. describe('<ShareProjectModal/>', function () {
  59. const contacts = [
  60. // user with edited name
  61. {
  62. type: 'user',
  63. email: 'test-user@example.com',
  64. first_name: 'Test',
  65. last_name: 'User',
  66. name: 'Test User',
  67. },
  68. // user with default name (email prefix)
  69. {
  70. type: 'user',
  71. email: 'test@example.com',
  72. first_name: 'test',
  73. },
  74. // no last name
  75. {
  76. type: 'user',
  77. first_name: 'Eratosthenes',
  78. email: 'eratosthenes@example.com',
  79. },
  80. // more users
  81. {
  82. type: 'user',
  83. first_name: 'Claudius',
  84. last_name: 'Ptolemy',
  85. email: 'ptolemy@example.com',
  86. },
  87. {
  88. type: 'user',
  89. first_name: 'Abd al-Rahman',
  90. last_name: 'Al-Sufi',
  91. email: 'al-sufi@example.com',
  92. },
  93. {
  94. type: 'user',
  95. first_name: 'Nicolaus',
  96. last_name: 'Copernicus',
  97. email: 'copernicus@example.com',
  98. },
  99. ]
  100. const modalProps = {
  101. show: true,
  102. handleHide: sinon.stub(),
  103. handleOpen: sinon.stub(),
  104. }
  105. beforeEach(function () {
  106. this.locationWrapperSandbox = sinon.createSandbox()
  107. this.locationWrapperStub = this.locationWrapperSandbox.stub(location)
  108. fetchMock.get('/user/contacts', { contacts })
  109. window.metaAttributesCache.set('ol-user', { allowedFreeTrial: true })
  110. window.metaAttributesCache.set('ol-showUpgradePrompt', true)
  111. window.metaAttributesCache.set('ol-preventCompileOnLoad', true)
  112. })
  113. afterEach(function () {
  114. this.locationWrapperSandbox.restore()
  115. fetchMock.removeRoutes().clearHistory()
  116. })
  117. it('renders the modal', async function () {
  118. renderWithEditorContext(
  119. <ShareProjectModal {...modalProps} />,
  120. createContextProps()
  121. )
  122. await screen.findByText('Share Project')
  123. })
  124. it('calls handleHide when a Close button is pressed', async function () {
  125. const handleHide = sinon.stub()
  126. renderWithEditorContext(
  127. <ShareProjectModal {...modalProps} handleHide={handleHide} />,
  128. createContextProps()
  129. )
  130. const [headerCloseButton, footerCloseButton] = await screen.findAllByRole(
  131. 'button',
  132. { name: 'Close' }
  133. )
  134. await userEvent.click(headerCloseButton)
  135. await userEvent.click(footerCloseButton)
  136. expect(handleHide.callCount).to.equal(2)
  137. })
  138. it('handles access level "private"', async function () {
  139. renderWithEditorContext(
  140. <ShareProjectModal {...modalProps} />,
  141. createContextProps({ publicAccessLevel: 'private' })
  142. )
  143. await screen.findByText('Link sharing is off')
  144. await screen.findByRole('button', { name: 'Turn on link sharing' })
  145. expect(screen.queryByText('Anyone with this link can view this project')).to
  146. .be.null
  147. expect(screen.queryByText('Anyone with this link can edit this project')).to
  148. .be.null
  149. })
  150. it('handles access level "tokenBased"', async function () {
  151. const tokens = {
  152. readAndWrite: '6862414195fwtbrtrdtskb',
  153. readAndWritePrefix: '6862414195',
  154. readOnly: 'wrnjfzkysqkr',
  155. readAndWriteHashPrefix: 'taEVki',
  156. readOnlyHashPrefix: 'j2xYbL',
  157. }
  158. fetchMock.get(`/project/${shareModalProjectDefaults._id}/tokens`, tokens)
  159. renderWithEditorContext(
  160. <ShareProjectModal {...modalProps} />,
  161. createContextProps({ publicAccessLevel: 'tokenBased' })
  162. )
  163. await screen.findByText('Link sharing is on')
  164. await screen.findByRole('button', { name: 'Turn off link sharing' })
  165. expect(screen.queryByText('Anyone with this link can view this project'))
  166. .not.to.be.null
  167. expect(screen.queryByText('Anyone with this link can edit this project'))
  168. .not.to.be.null
  169. screen.getByText(
  170. `https://www.test-overleaf.com/${tokens.readAndWrite}#${tokens.readAndWriteHashPrefix}`
  171. )
  172. screen.getByText(
  173. `https://www.test-overleaf.com/read/${tokens.readOnly}#${tokens.readOnlyHashPrefix}`
  174. )
  175. })
  176. it('handles legacy access level "readAndWrite"', async function () {
  177. renderWithEditorContext(
  178. <ShareProjectModal {...modalProps} />,
  179. createContextProps({ publicAccessLevel: 'readAndWrite' })
  180. )
  181. await screen.findByText(
  182. 'This project is public and can be edited by anyone with the URL.'
  183. )
  184. await screen.findByRole('button', { name: 'Make private' })
  185. })
  186. it('handles legacy access level "readOnly"', async function () {
  187. renderWithEditorContext(
  188. <ShareProjectModal {...modalProps} />,
  189. createContextProps({ publicAccessLevel: 'readOnly' })
  190. )
  191. await screen.findByText(
  192. 'This project is public and can be viewed but not edited by anyone with the URL'
  193. )
  194. await screen.findByRole('button', { name: 'Make private' })
  195. })
  196. it('displays actions for project-owners', async function () {
  197. fetchMock.get(`/project/${shareModalProjectDefaults._id}/tokens`, {})
  198. const invites: ProjectMember[] = [
  199. {
  200. _id: 'invited-author' as UserId,
  201. email: 'invited-author@example.com',
  202. privileges: 'readAndWrite',
  203. first_name: 'Invited',
  204. last_name: 'Author',
  205. },
  206. ]
  207. // render as project owner: actions should be present
  208. renderWithEditorContext(
  209. <ShareProjectModal {...modalProps} />,
  210. createContextProps({ publicAccessLevel: 'tokenBased', invites })
  211. )
  212. await screen.findByRole('button', { name: 'Turn off link sharing' })
  213. await screen.findByRole('button', { name: 'Resend' })
  214. })
  215. it('hides actions from non-project-owners when link sharing on', async function () {
  216. const invites: ProjectMember[] = [
  217. {
  218. _id: 'invited-author' as UserId,
  219. email: 'invited-author@example.com',
  220. privileges: 'readAndWrite',
  221. first_name: 'Invited',
  222. last_name: 'Author',
  223. },
  224. ]
  225. renderWithEditorContext(<ShareProjectModal {...modalProps} />, {
  226. ...createContextProps({ publicAccessLevel: 'tokenBased', invites }),
  227. user: {
  228. id: 'non-project-owner',
  229. email: 'non-project-owner@example.com',
  230. },
  231. })
  232. await screen.findByText(
  233. 'To change access permissions, please ask the project owner'
  234. )
  235. expect(screen.queryByRole('button', { name: 'Turn off link sharing' })).to
  236. .be.null
  237. expect(screen.queryByRole('button', { name: 'Turn on link sharing' })).to.be
  238. .null
  239. expect(screen.queryByRole('button', { name: 'Resend' })).to.be.null
  240. })
  241. it('hides actions from non-project-owners when link sharing off', async function () {
  242. const invites: ProjectMember[] = [
  243. {
  244. _id: 'invited-author' as UserId,
  245. email: 'invited-author@example.com',
  246. privileges: 'readAndWrite',
  247. first_name: 'Invited',
  248. last_name: 'Author',
  249. },
  250. ]
  251. renderWithEditorContext(<ShareProjectModal {...modalProps} />, {
  252. ...createContextProps({ publicAccessLevel: 'private', invites }),
  253. user: {
  254. id: 'non-project-owner',
  255. email: 'non-project-owner@example.com',
  256. },
  257. })
  258. await screen.findByText(
  259. 'To add more collaborators or turn on link sharing, please ask the project owner'
  260. )
  261. expect(screen.queryByRole('button', { name: 'Turn off link sharing' })).to
  262. .be.null
  263. expect(screen.queryByRole('button', { name: 'Turn on link sharing' })).to.be
  264. .null
  265. expect(screen.queryByRole('button', { name: 'Resend' })).to.be.null
  266. })
  267. it('only shows read-only token link to restricted token members', async function () {
  268. window.metaAttributesCache.set('ol-isRestrictedTokenMember', true)
  269. fetchMock.get(`/project/${shareModalProjectDefaults._id}/tokens`, {})
  270. renderWithEditorContext(<ShareProjectModal {...modalProps} />, {
  271. ...createContextProps({ publicAccessLevel: 'private' }),
  272. isRestrictedTokenMember: true,
  273. })
  274. // no buttons
  275. expect(screen.queryByRole('button', { name: 'Turn on link sharing' })).to.be
  276. .null
  277. expect(screen.queryByRole('button', { name: 'Turn off link sharing' })).to
  278. .be.null
  279. // only read-only token link
  280. await screen.findByText('Anyone with this link can view this project')
  281. expect(screen.queryByText('Anyone with this link can edit this project')).to
  282. .be.null
  283. })
  284. it('displays project members and invites', async function () {
  285. const members: ProjectMember[] = [
  286. {
  287. _id: 'member-author' as UserId,
  288. email: 'member-author@example.com',
  289. privileges: 'readAndWrite',
  290. first_name: 'Member',
  291. last_name: 'Author',
  292. },
  293. {
  294. _id: 'member-viewer' as UserId,
  295. email: 'member-viewer@example.com',
  296. privileges: 'readOnly',
  297. first_name: 'Member',
  298. last_name: 'Viewer',
  299. },
  300. ]
  301. const invites: ProjectMember[] = [
  302. {
  303. _id: 'invited-author' as UserId,
  304. email: 'invited-author@example.com',
  305. privileges: 'readAndWrite',
  306. first_name: 'Invited',
  307. last_name: 'Author',
  308. },
  309. {
  310. _id: 'invited-viewer' as UserId,
  311. email: 'invited-viewer@example.com',
  312. privileges: 'readOnly',
  313. first_name: 'Invited',
  314. last_name: 'Viewer',
  315. },
  316. ]
  317. fetchMock.get(`/project/${shareModalProjectDefaults._id}/tokens`, {})
  318. renderWithEditorContext(
  319. <ShareProjectModal {...modalProps} />,
  320. createContextProps({ publicAccessLevel: 'tokenBased', members, invites })
  321. )
  322. const projectOwnerEmail = USER_EMAIL
  323. await screen.findByText(projectOwnerEmail)
  324. expect(screen.queryAllByText(projectOwnerEmail)).to.have.length(1)
  325. expect(screen.queryAllByText('member-author@example.com')).to.have.length(1)
  326. expect(screen.queryAllByText('member-viewer@example.com')).to.have.length(1)
  327. expect(screen.queryAllByText('invited-author@example.com')).to.have.length(
  328. 1
  329. )
  330. expect(screen.queryAllByText('invited-viewer@example.com')).to.have.length(
  331. 1
  332. )
  333. expect(screen.queryAllByText('Invite not yet accepted.')).to.have.length(
  334. invites.length
  335. )
  336. expect(screen.queryAllByRole('button', { name: 'Resend' })).to.have.length(
  337. invites.length
  338. )
  339. })
  340. it('resends an invite', async function () {
  341. fetchMock.get(`/project/${shareModalProjectDefaults._id}/tokens`, {})
  342. fetchMock.postOnce(
  343. 'express:/project/:projectId/invite/:inviteId/resend',
  344. 204
  345. )
  346. const invites: ProjectMember[] = [
  347. {
  348. _id: 'invited-author' as UserId,
  349. email: 'invited-author@example.com',
  350. privileges: 'readAndWrite',
  351. first_name: 'Invited',
  352. last_name: 'Author',
  353. },
  354. ]
  355. renderWithEditorContext(
  356. <ShareProjectModal {...modalProps} />,
  357. createContextProps({ publicAccessLevel: 'tokenBased', invites })
  358. )
  359. const [, closeButton] = screen.getAllByRole('button', {
  360. name: 'Close',
  361. })
  362. const resendButton = screen.getByRole('button', { name: 'Resend' })
  363. fireEvent.click(resendButton)
  364. await waitFor(
  365. () => expect((closeButton as HTMLButtonElement).disabled).to.be.true
  366. )
  367. expect(fetchMock.callHistory.done()).to.be.true
  368. await waitFor(
  369. () => expect((closeButton as HTMLButtonElement).disabled).to.be.false
  370. )
  371. })
  372. it('revokes an invite', async function () {
  373. fetchMock.get(`/project/${shareModalProjectDefaults._id}/tokens`, {})
  374. fetchMock.deleteOnce('express:/project/:projectId/invite/:inviteId', 204)
  375. const invites: ProjectMember[] = [
  376. {
  377. _id: 'invited-author' as UserId,
  378. email: 'invited-author@example.com',
  379. privileges: 'readAndWrite',
  380. first_name: 'Invited',
  381. last_name: 'Author',
  382. },
  383. ]
  384. renderWithEditorContext(
  385. <ShareProjectModal {...modalProps} />,
  386. createContextProps({ publicAccessLevel: 'tokenBased', invites })
  387. )
  388. const [, closeButton] = screen.getAllByRole('button', {
  389. name: 'Close',
  390. })
  391. const revokeButton = screen.getByRole('button', { name: 'Revoke' })
  392. fireEvent.click(revokeButton)
  393. await waitFor(
  394. () => expect((closeButton as HTMLButtonElement).disabled).to.be.true
  395. )
  396. expect(fetchMock.callHistory.done()).to.be.true
  397. await waitFor(
  398. () => expect((closeButton as HTMLButtonElement).disabled).to.be.false
  399. )
  400. })
  401. it('changes member privileges to read + write', async function () {
  402. fetchMock.get(`/project/${shareModalProjectDefaults._id}/tokens`, {})
  403. fetchMock.putOnce('express:/project/:projectId/users/:userId', 204)
  404. const members: ProjectMember[] = [
  405. {
  406. _id: 'member-viewer' as UserId,
  407. email: 'member-viewer@example.com',
  408. privileges: 'readOnly',
  409. first_name: 'Member',
  410. last_name: 'Viewer',
  411. },
  412. ]
  413. renderWithEditorContext(
  414. <ShareProjectModal {...modalProps} />,
  415. createContextProps({ publicAccessLevel: 'tokenBased', members })
  416. )
  417. const [, closeButton] = screen.getAllByRole('button', {
  418. name: 'Close',
  419. })
  420. expect(
  421. await screen.findAllByText('member-viewer@example.com')
  422. ).to.have.length(1)
  423. await changePrivilegeLevel(screen, { current: 'Viewer', next: 'Editor' })
  424. await waitFor(
  425. () => expect((closeButton as HTMLButtonElement).disabled).to.be.true
  426. )
  427. const body = fetchMock.callHistory.calls().at(-1)?.options?.body
  428. expect(JSON.parse(body as string)).to.deep.equal({
  429. privilegeLevel: 'readAndWrite',
  430. })
  431. expect(fetchMock.callHistory.done()).to.be.true
  432. await waitFor(
  433. () => expect((closeButton as HTMLButtonElement).disabled).to.be.false
  434. )
  435. })
  436. it('removes a member from the project', async function () {
  437. fetchMock.get(`/project/${shareModalProjectDefaults._id}/tokens`, {})
  438. fetchMock.deleteOnce('express:/project/:projectId/users/:userId', 204)
  439. const members: ProjectMember[] = [
  440. {
  441. _id: 'member-viewer' as UserId,
  442. email: 'member-viewer@example.com',
  443. privileges: 'readOnly',
  444. first_name: 'Member',
  445. last_name: 'Viewer',
  446. },
  447. ]
  448. renderWithEditorContext(
  449. <ShareProjectModal {...modalProps} />,
  450. createContextProps({ publicAccessLevel: 'tokenBased', members })
  451. )
  452. expect(
  453. await screen.findAllByText('member-viewer@example.com')
  454. ).to.have.length(1)
  455. await changePrivilegeLevel(screen, {
  456. current: 'Viewer',
  457. next: 'Remove access',
  458. })
  459. const removeButton = screen.getByRole('button', {
  460. name: 'Change',
  461. })
  462. fireEvent.click(removeButton)
  463. const url = fetchMock.callHistory.calls().at(-1)?.url
  464. expect(url).to.equal(
  465. 'https://www.test-overleaf.com/project/test-project/users/member-viewer'
  466. )
  467. expect(fetchMock.callHistory.done()).to.be.true
  468. })
  469. it('changes member privileges to owner with confirmation', async function () {
  470. fetchMock.get(`/project/${shareModalProjectDefaults._id}/tokens`, {})
  471. fetchMock.postOnce('express:/project/:projectId/transfer-ownership', 204)
  472. const members: ProjectMember[] = [
  473. {
  474. _id: 'member-viewer' as UserId,
  475. email: 'member-viewer@example.com',
  476. privileges: 'readOnly',
  477. first_name: 'Member',
  478. last_name: 'Viewer',
  479. },
  480. ]
  481. renderWithEditorContext(
  482. <ShareProjectModal {...modalProps} />,
  483. createContextProps({ publicAccessLevel: 'tokenBased', members })
  484. )
  485. await screen.findByText('member-viewer@example.com')
  486. expect(screen.queryAllByText('member-viewer@example.com')).to.have.length(1)
  487. await changePrivilegeLevel(screen, {
  488. current: 'Viewer',
  489. next: 'Make owner',
  490. })
  491. screen.getByText((_, node) => {
  492. return (
  493. node !== null &&
  494. node.textContent ===
  495. 'Are you sure you want to make member-viewer@example.com the owner of Test Project?'
  496. )
  497. })
  498. const confirmButton: HTMLButtonElement = screen.getByRole('button', {
  499. name: 'Change owner',
  500. })
  501. fireEvent.click(confirmButton)
  502. await waitFor(() => expect(confirmButton.disabled).to.be.true)
  503. const body = fetchMock.callHistory.calls().at(-1)?.options?.body
  504. expect(JSON.parse(body as string)).to.deep.equal({
  505. user_id: 'member-viewer',
  506. })
  507. expect(fetchMock.callHistory.done()).to.be.true
  508. })
  509. it('sends invites to input email addresses', async function () {
  510. fetchMock.get(`/project/${shareModalProjectDefaults._id}/tokens`, {})
  511. renderWithEditorContext(
  512. <ShareProjectModal {...modalProps} />,
  513. createContextProps({ publicAccessLevel: 'tokenBased' })
  514. )
  515. const [inputElement] = await screen.findAllByLabelText('Add email address')
  516. // loading contacts
  517. await waitFor(() => {
  518. expect(fetchMock.callHistory.called('express:/user/contacts')).to.be.true
  519. })
  520. // displaying a list of matching contacts
  521. inputElement.focus()
  522. fireEvent.change(inputElement, { target: { value: 'ptolemy' } })
  523. await screen.findByText(/ptolemy@example.com/)
  524. // sending invitations
  525. fetchMock.post(
  526. 'express:/project/:projectId/invite',
  527. ({ args: [, req] }) => {
  528. const data = JSON.parse((req as { body: string }).body)
  529. if (data.email === 'a@b.c') {
  530. return {
  531. status: 400,
  532. body: { errorReason: 'invalid_email' },
  533. }
  534. }
  535. return {
  536. status: 200,
  537. body: {
  538. invite: {
  539. ...data,
  540. _id: data.email,
  541. },
  542. },
  543. }
  544. }
  545. )
  546. fireEvent.paste(inputElement, {
  547. clipboardData: {
  548. getData: () =>
  549. `test@example.com; foo@example.com
  550. bar@example.com, a@b.c`,
  551. },
  552. })
  553. const user = userEvent.setup()
  554. await user.click(screen.getByTestId('add-collaborator-select'))
  555. await user.click(screen.getByText('Viewer'))
  556. const submitButton = screen.getByRole('button', { name: 'Invite' })
  557. await userEvent.click(submitButton)
  558. let calls: CallLog[] = []
  559. await waitFor(
  560. () => {
  561. calls = fetchMock.callHistory.calls(
  562. 'express:/project/:projectId/invite'
  563. )
  564. expect(calls).to.have.length(4)
  565. },
  566. { timeout: 5000 } // allow time for delay between each request
  567. )
  568. expect((calls[0].args[1] as { body: string }).body).to.equal(
  569. JSON.stringify({ email: 'test@example.com', privileges: 'readOnly' })
  570. )
  571. expect((calls[1].args[1] as { body: string }).body).to.equal(
  572. JSON.stringify({ email: 'foo@example.com', privileges: 'readOnly' })
  573. )
  574. expect((calls[2].args[1] as { body: string }).body).to.equal(
  575. JSON.stringify({ email: 'bar@example.com', privileges: 'readOnly' })
  576. )
  577. expect((calls[3].args[1] as { body: string }).body).to.equal(
  578. JSON.stringify({ email: 'a@b.c', privileges: 'readOnly' })
  579. )
  580. // error from the last invite
  581. screen.getByText('An email address is invalid')
  582. })
  583. it('displays a message when the collaborator limit is reached', async function () {
  584. fetchMock.get(`/project/${shareModalProjectDefaults._id}/tokens`, {})
  585. fetchMock.post(
  586. '/event/paywall-prompt',
  587. {},
  588. { body: { 'paywall-type': 'project-sharing' } }
  589. )
  590. renderWithEditorContext(
  591. <ShareProjectModal {...modalProps} />,
  592. createContextProps({
  593. publicAccessLevel: 'tokenBased',
  594. features: {
  595. collaborators: 0,
  596. compileGroup: 'standard',
  597. trackChangesVisible: true,
  598. },
  599. })
  600. )
  601. await screen.findByText('Add more collaborators')
  602. const user = userEvent.setup()
  603. await user.click(screen.getByTestId('add-collaborator-select'))
  604. const editorOption = screen.getByText('Editor').closest('button')
  605. const reviewerOption = screen.getByText('Reviewer').closest('button')
  606. const viewerOption = screen.getByText('Viewer').closest('button')
  607. expect(editorOption?.classList.contains('disabled')).to.be.true
  608. expect(reviewerOption?.classList.contains('disabled')).to.be.true
  609. expect(viewerOption?.classList.contains('disabled')).to.be.false
  610. screen.getByText(
  611. /Upgrade to add more collaborators and access collaboration features like track changes and full project history/
  612. )
  613. })
  614. it('counts reviewers towards the collaborator limit', async function () {
  615. renderWithEditorContext(
  616. <ShareProjectModal {...modalProps} />,
  617. createContextProps({
  618. features: {
  619. collaborators: 1,
  620. trackChangesVisible: true,
  621. },
  622. members: [
  623. {
  624. _id: 'reviewer-id' as UserId,
  625. email: 'reviewer@example.com',
  626. privileges: 'review',
  627. first_name: 'Reviewer',
  628. last_name: 'LastName',
  629. },
  630. ],
  631. })
  632. )
  633. await screen.findByText('Add more collaborators')
  634. const user = userEvent.setup()
  635. await user.click(screen.getByTestId('add-collaborator-select'))
  636. const editorOption = screen.getByText('Editor').closest('button')
  637. const reviewerOption = screen.getByText('Reviewer').closest('button')
  638. const viewerOption = screen.getByText('Viewer').closest('button')
  639. expect(editorOption?.classList.contains('disabled')).to.be.true
  640. expect(reviewerOption?.classList.contains('disabled')).to.be.true
  641. expect(viewerOption?.classList.contains('disabled')).to.be.false
  642. screen.getByText(
  643. /Upgrade to add more collaborators and access collaboration features like track changes and full project history/
  644. )
  645. })
  646. it('handles server error responses', async function () {
  647. fetchMock.get(`/project/${shareModalProjectDefaults._id}/tokens`, {})
  648. renderWithEditorContext(
  649. <ShareProjectModal {...modalProps} />,
  650. createContextProps({
  651. publicAccessLevel: 'tokenBased',
  652. })
  653. )
  654. // loading contacts
  655. await waitFor(() => {
  656. expect(fetchMock.callHistory.called('express:/user/contacts')).to.be.true
  657. })
  658. const [inputElement] = await screen.findAllByLabelText('Add email address')
  659. const submitButton: HTMLButtonElement = screen.getByRole('button', {
  660. name: 'Invite',
  661. })
  662. const respondWithError = async function (errorReason: string) {
  663. fireEvent.focus(inputElement)
  664. fireEvent.change(inputElement, {
  665. target: { value: 'invited-author-1@example.com' },
  666. })
  667. fireEvent.blur(inputElement)
  668. fetchMock.postOnce('express:/project/:projectId/invite', {
  669. status: 400,
  670. body: { errorReason },
  671. })
  672. expect(submitButton.disabled).to.be.false
  673. await userEvent.click(submitButton)
  674. await fetchMock.callHistory.flush(true)
  675. expect(fetchMock.callHistory.done()).to.be.true
  676. }
  677. await respondWithError('cannot_invite_non_user')
  678. await screen.findByText(
  679. `Can’t send invite. Recipient must already have an Overleaf account`
  680. )
  681. await respondWithError('cannot_verify_user_not_robot')
  682. await screen.findByText(
  683. `Sorry, we could not verify that you are not a robot. Please check that Google reCAPTCHA is not being blocked by an ad blocker or firewall.`
  684. )
  685. await respondWithError('cannot_invite_self')
  686. await screen.findByText(`Can’t send invite to yourself`)
  687. await respondWithError('invalid_email')
  688. await screen.findByText(`An email address is invalid`)
  689. await respondWithError('too_many_requests')
  690. await screen.findByText(
  691. `Too many requests were received in a short space of time. Please wait for a few moments and try again.`
  692. )
  693. })
  694. it('handles switching between access levels', async function () {
  695. fetchMock.get(`/project/${shareModalProjectDefaults._id}/tokens`, {})
  696. fetchMock.post('express:/project/:projectId/settings/admin', 204)
  697. let setPublicAccessLevel = function (_: PublicAccessLevel) {}
  698. function WrappedModal() {
  699. const { updateProject } = useProjectContext()
  700. setPublicAccessLevel = (publicAccessLevel: PublicAccessLevel) => {
  701. updateProject({ publicAccessLevel })
  702. }
  703. return <ShareProjectModal {...modalProps} />
  704. }
  705. renderWithEditorContext(
  706. <WrappedModal />,
  707. createContextProps({
  708. publicAccessLevel: 'private',
  709. })
  710. )
  711. await screen.findByText('Link sharing is off')
  712. const enableButton: HTMLButtonElement = await screen.findByRole('button', {
  713. name: 'Turn on link sharing',
  714. })
  715. fireEvent.click(enableButton)
  716. await waitFor(() => expect(enableButton.disabled).to.be.true)
  717. const tokenBody = fetchMock.callHistory.calls().at(-1)?.options.body
  718. expect(JSON.parse(tokenBody as string)).to.deep.equal({
  719. publicAccessLevel: 'tokenBased',
  720. })
  721. // NOTE: the project data is usually updated via the websocket connection
  722. // but we can't do that so we're doing it via the project context, which is
  723. // exposed in a hacky way here
  724. setPublicAccessLevel('tokenBased')
  725. await screen.findByText('Link sharing is on')
  726. const disableButton: HTMLButtonElement = await screen.findByRole('button', {
  727. name: 'Turn off link sharing',
  728. })
  729. fireEvent.click(disableButton)
  730. await waitFor(() => expect(disableButton.disabled).to.be.true)
  731. const privateBody = fetchMock.callHistory.calls().at(-1)?.options.body
  732. expect(JSON.parse(privateBody as string)).to.deep.equal({
  733. publicAccessLevel: 'private',
  734. })
  735. setPublicAccessLevel('private')
  736. await screen.findByText('Link sharing is off')
  737. })
  738. it('avoids selecting unmatched contact', async function () {
  739. renderWithEditorContext(
  740. <ShareProjectModal {...modalProps} />,
  741. createContextProps()
  742. )
  743. const [inputElement] = await screen.findAllByLabelText('Add email address')
  744. // Wait for contacts to load
  745. await waitFor(() => {
  746. expect(fetchMock.callHistory.called('express:/user/contacts')).to.be.true
  747. })
  748. // Enter a prefix that matches a contact
  749. inputElement.focus()
  750. fireEvent.change(inputElement, { target: { value: 'ptolemy' } })
  751. // The matching contact should now be present and selected
  752. await screen.findByRole('option', {
  753. name: `Claudius Ptolemy <ptolemy@example.com>`,
  754. selected: true,
  755. })
  756. // Keep entering text so the contact no longer matches
  757. fireEvent.change(inputElement, {
  758. target: { value: 'ptolemy.new@example.com' },
  759. })
  760. // The matching contact should no longer be present
  761. expect(
  762. screen.queryByRole('option', {
  763. name: `Claudius Ptolemy <ptolemy@example.com>`,
  764. })
  765. ).to.be.null
  766. // No items should be added yet
  767. expect(screen.queryByRole('button', { name: 'Remove' })).to.be.null
  768. // Pressing Tab should add the entered item
  769. fireEvent.keyDown(inputElement, { key: 'Tab', code: 'Tab' })
  770. await waitFor(() => {
  771. expect(screen.getAllByRole('button', { name: /Remove/ })).to.have.length(
  772. 1
  773. )
  774. })
  775. // Blurring the input should not add another contact
  776. fireEvent.blur(inputElement)
  777. await waitFor(() => {
  778. expect(screen.getAllByRole('button', { name: /Remove/ })).to.have.length(
  779. 1
  780. )
  781. })
  782. })
  783. it('selects contact by typing the entire email and blurring the input', async function () {
  784. renderWithEditorContext(
  785. <ShareProjectModal {...modalProps} />,
  786. createContextProps()
  787. )
  788. const [inputElement] = await screen.findAllByLabelText('Add email address')
  789. // Wait for contacts to load
  790. await waitFor(() => {
  791. expect(fetchMock.callHistory.called('express:/user/contacts')).to.be.true
  792. })
  793. // Enter a prefix that matches a contact
  794. await userEvent.type(inputElement, 'ptolemy@example.com')
  795. // The matching contact should now be present and selected
  796. await screen.findByRole('option', {
  797. name: `Claudius Ptolemy <ptolemy@example.com>`,
  798. selected: true,
  799. })
  800. // No items should be added yet
  801. expect(screen.queryByRole('button', { name: /Remove/ })).to.be.null
  802. // Click anywhere on the form to blur the input
  803. await userEvent.click(screen.getByRole('dialog'))
  804. // The contact should be added
  805. await waitFor(() => {
  806. expect(screen.getAllByRole('button', { name: /Remove/ })).to.have.length(
  807. 1
  808. )
  809. })
  810. })
  811. it('selects contact by typing a partial email and selecting the suggestion', async function () {
  812. renderWithEditorContext(
  813. <ShareProjectModal {...modalProps} />,
  814. createContextProps()
  815. )
  816. const [inputElement] = await screen.findAllByLabelText('Add email address')
  817. // Wait for contacts to load
  818. await waitFor(() => {
  819. expect(fetchMock.callHistory.called('express:/user/contacts')).to.be.true
  820. })
  821. // Enter a prefix that matches a contact
  822. await userEvent.type(inputElement, 'pto')
  823. // The matching contact should now be present and selected
  824. await userEvent.click(
  825. screen.getByRole('option', {
  826. name: `Claudius Ptolemy <ptolemy@example.com>`,
  827. selected: true,
  828. })
  829. )
  830. // Click anywhere on the form to blur the input
  831. await userEvent.click(screen.getByRole('dialog'))
  832. // The contact should be added
  833. await waitFor(() => {
  834. expect(screen.getAllByRole('button', { name: /Remove/ })).to.have.length(
  835. 1
  836. )
  837. })
  838. })
  839. it('allows an email address to be selected, removed, then re-added', async function () {
  840. renderWithEditorContext(
  841. <ShareProjectModal {...modalProps} />,
  842. createContextProps()
  843. )
  844. const [inputElement] = await screen.findAllByLabelText('Add email address')
  845. // Wait for contacts to load
  846. await waitFor(() => {
  847. expect(fetchMock.callHistory.called('express:/user/contacts')).to.be.true
  848. })
  849. // Enter a prefix that matches a contact
  850. await userEvent.type(inputElement, 'pto')
  851. // Select the suggested contact
  852. await userEvent.click(
  853. screen.getByRole('option', {
  854. name: `Claudius Ptolemy <ptolemy@example.com>`,
  855. selected: true,
  856. })
  857. )
  858. // Click anywhere on the form to blur the input
  859. await userEvent.click(screen.getByRole('dialog'))
  860. // Remove the just-added collaborator
  861. await userEvent.click(screen.getByRole('button', { name: /Remove/ }))
  862. // Remove button should now be gone
  863. expect(screen.queryByRole('button', { name: /Remove/ })).to.be.null
  864. // Add the same collaborator again
  865. await userEvent.type(inputElement, 'pto')
  866. // Click the suggested contact again
  867. await userEvent.click(
  868. screen.getByRole('option', {
  869. name: `Claudius Ptolemy <ptolemy@example.com>`,
  870. selected: true,
  871. })
  872. )
  873. // Click anywhere on the form to blur the input
  874. await userEvent.click(screen.getByRole('dialog'))
  875. // The contact should be added
  876. await waitFor(() => {
  877. expect(screen.getAllByRole('button', { name: /Remove/ })).to.have.length(
  878. 1
  879. )
  880. })
  881. })
  882. })