share-project-modal.test.tsx 32 KB

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