file-tree-modal-create-file.test.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. import { expect } from 'chai'
  2. import * as sinon from 'sinon'
  3. import { useEffect } from 'react'
  4. import { screen, fireEvent, cleanup, waitFor } from '@testing-library/react'
  5. import fetchMock from 'fetch-mock'
  6. import PropTypes from 'prop-types'
  7. import renderWithContext from '../../helpers/render-with-context'
  8. import FileTreeModalCreateFile from '../../../../../../frontend/js/features/file-tree/components/modals/file-tree-modal-create-file'
  9. import { useFileTreeActionable } from '../../../../../../frontend/js/features/file-tree/contexts/file-tree-actionable'
  10. import { useFileTreeData } from '../../../../../../frontend/js/shared/context/file-tree-data-context'
  11. describe('<FileTreeModalCreateFile/>', function () {
  12. beforeEach(function () {
  13. window.csrfToken = 'token'
  14. })
  15. afterEach(function () {
  16. delete window.csrfToken
  17. fetchMock.restore()
  18. cleanup()
  19. })
  20. it('handles invalid file names', async function () {
  21. renderWithContext(<OpenWithMode mode="doc" />)
  22. const submitButton = screen.getByRole('button', { name: 'Create' })
  23. const input = screen.getByLabelText('File Name')
  24. expect(input.value).to.equal('name.tex')
  25. expect(submitButton.disabled).to.be.false
  26. expect(screen.queryAllByRole('alert')).to.be.empty
  27. fireEvent.change(input, { target: { value: '' } })
  28. expect(submitButton.disabled).to.be.true
  29. screen.getByRole(
  30. (role, element) =>
  31. role === 'alert' && element.textContent.match(/File name is empty/)
  32. )
  33. await fireEvent.change(input, { target: { value: 'test.tex' } })
  34. expect(submitButton.disabled).to.be.false
  35. expect(screen.queryAllByRole('alert')).to.be.empty
  36. await fireEvent.change(input, { target: { value: 'oops/i/did/it/again' } })
  37. expect(submitButton.disabled).to.be.true
  38. screen.getByRole(
  39. (role, element) =>
  40. role === 'alert' &&
  41. element.textContent.match(/contains invalid characters/)
  42. )
  43. })
  44. it('displays an error when the file limit is reached', async function () {
  45. const rootFolder = [
  46. {
  47. _id: 'root-folder-id',
  48. name: 'rootFolder',
  49. docs: Array.from({ length: 10 }, (_, index) => ({
  50. _id: `entity-${index}`,
  51. })),
  52. fileRefs: [],
  53. folders: [],
  54. },
  55. ]
  56. renderWithContext(<OpenWithMode mode="doc" />, {
  57. contextProps: { rootFolder },
  58. })
  59. screen.getByRole(
  60. (role, element) =>
  61. role === 'alert' &&
  62. element.textContent.match(/This project has reached the \d+ file limit/)
  63. )
  64. })
  65. it('displays a warning when the file limit is nearly reached', async function () {
  66. const rootFolder = [
  67. {
  68. _id: 'root-folder-id',
  69. name: 'rootFolder',
  70. docs: Array.from({ length: 9 }, (_, index) => ({
  71. _id: `entity-${index}`,
  72. })),
  73. fileRefs: [],
  74. folders: [],
  75. },
  76. ]
  77. renderWithContext(<OpenWithMode mode="doc" />, {
  78. contextProps: { rootFolder },
  79. })
  80. screen.getByText(/This project is approaching the file limit \(\d+\/\d+\)/)
  81. })
  82. it('counts files in nested folders', async function () {
  83. const rootFolder = [
  84. {
  85. _id: 'root-folder-id',
  86. name: 'rootFolder',
  87. docs: [{ _id: 'doc-1' }],
  88. fileRefs: [],
  89. folders: [
  90. {
  91. docs: [{ _id: 'doc-2' }],
  92. fileRefs: [],
  93. folders: [
  94. {
  95. docs: [
  96. { _id: 'doc-3' },
  97. { _id: 'doc-4' },
  98. { _id: 'doc-5' },
  99. { _id: 'doc-6' },
  100. { _id: 'doc-7' },
  101. ],
  102. fileRefs: [],
  103. folders: [],
  104. },
  105. ],
  106. },
  107. ],
  108. },
  109. ]
  110. renderWithContext(<OpenWithMode mode="doc" />, {
  111. contextProps: { rootFolder },
  112. })
  113. screen.getByText(/This project is approaching the file limit \(\d+\/\d+\)/)
  114. })
  115. it('counts folders toward the limit', async function () {
  116. const rootFolder = [
  117. {
  118. _id: 'root-folder-id',
  119. name: 'rootFolder',
  120. docs: [{ _id: 'doc-1' }],
  121. fileRefs: [],
  122. folders: [
  123. { docs: [], fileRefs: [], folders: [] },
  124. { docs: [], fileRefs: [], folders: [] },
  125. { docs: [], fileRefs: [], folders: [] },
  126. { docs: [], fileRefs: [], folders: [] },
  127. { docs: [], fileRefs: [], folders: [] },
  128. { docs: [], fileRefs: [], folders: [] },
  129. { docs: [], fileRefs: [], folders: [] },
  130. { docs: [], fileRefs: [], folders: [] },
  131. ],
  132. },
  133. ]
  134. renderWithContext(<OpenWithMode mode="doc" />, {
  135. contextProps: { rootFolder },
  136. })
  137. screen.getByText(/This project is approaching the file limit \(\d+\/\d+\)/)
  138. })
  139. it('creates a new file when the form is submitted', async function () {
  140. fetchMock.post('express:/project/:projectId/doc', () => 204)
  141. renderWithContext(<OpenWithMode mode="doc" />)
  142. const input = screen.getByLabelText('File Name')
  143. await fireEvent.change(input, { target: { value: 'test.tex' } })
  144. const submitButton = screen.getByRole('button', { name: 'Create' })
  145. await fireEvent.click(submitButton)
  146. expect(
  147. fetchMock.called('express:/project/:projectId/doc', {
  148. body: {
  149. parent_folder_id: 'root-folder-id',
  150. name: 'test.tex',
  151. },
  152. })
  153. ).to.be.true
  154. })
  155. it('imports a new file from a project', async function () {
  156. fetchMock
  157. .get('path:/user/projects', {
  158. projects: [
  159. {
  160. _id: 'test-project',
  161. name: 'This Project',
  162. },
  163. {
  164. _id: 'project-1',
  165. name: 'Project One',
  166. },
  167. {
  168. _id: 'project-2',
  169. name: 'Project Two',
  170. },
  171. ],
  172. })
  173. .get('express:/project/:projectId/entities', {
  174. entities: [
  175. {
  176. path: '/foo.tex',
  177. },
  178. {
  179. path: '/bar.tex',
  180. },
  181. ],
  182. })
  183. .post('express:/project/:projectId/compile', {
  184. status: 'success',
  185. outputFiles: [
  186. {
  187. build: 'test',
  188. path: 'baz.jpg',
  189. },
  190. {
  191. build: 'test',
  192. path: 'ball.jpg',
  193. },
  194. ],
  195. })
  196. .post('express:/project/:projectId/linked_file', () => 204)
  197. renderWithContext(<OpenWithMode mode="project" />)
  198. // initial state, no project selected
  199. const projectInput = screen.getByLabelText('Select a Project')
  200. expect(projectInput.disabled).to.be.true
  201. await waitFor(() => {
  202. expect(projectInput.disabled).to.be.false
  203. })
  204. // the submit button should be disabled
  205. const submitButton = screen.getByRole('button', { name: 'Create' })
  206. expect(submitButton.disabled).to.be.true
  207. // the source file selector should be disabled
  208. const fileInput = screen.getByLabelText('Select a File')
  209. expect(fileInput.disabled).to.be.true
  210. // TODO: check for options length, excluding current project
  211. // select a project
  212. await fireEvent.change(projectInput, { target: { value: 'project-2' } }) // TODO: getByRole('option')?
  213. // wait for the source file selector to be enabled
  214. await waitFor(() => {
  215. expect(fileInput.disabled).to.be.false
  216. })
  217. expect(screen.queryByLabelText('Select a File')).not.to.be.null
  218. expect(screen.queryByLabelText('Select an Output File')).to.be.null
  219. expect(submitButton.disabled).to.be.true
  220. // TODO: check for fileInput options length, excluding current project
  221. // click on the button to toggle between source and output files
  222. const sourceTypeButton = screen.getByRole('button', {
  223. // NOTE: When changing the label, update the other tests with this label as well.
  224. name: 'select from output files',
  225. })
  226. await fireEvent.click(sourceTypeButton)
  227. // wait for the output file selector to be enabled
  228. const entityInput = screen.getByLabelText('Select an Output File')
  229. await waitFor(() => {
  230. expect(entityInput.disabled).to.be.false
  231. })
  232. expect(screen.queryByLabelText('Select a File')).to.be.null
  233. expect(screen.queryByLabelText('Select an Output File')).not.to.be.null
  234. expect(submitButton.disabled).to.be.true
  235. // TODO: check for entityInput options length, excluding current project
  236. await fireEvent.change(entityInput, { target: { value: 'ball.jpg' } }) // TODO: getByRole('option')?
  237. await waitFor(() => {
  238. expect(submitButton.disabled).to.be.false
  239. })
  240. await fireEvent.click(submitButton)
  241. expect(
  242. fetchMock.called('express:/project/:projectId/linked_file', {
  243. body: {
  244. name: 'ball.jpg',
  245. provider: 'project_output_file',
  246. parent_folder_id: 'root-folder-id',
  247. data: {
  248. source_project_id: 'project-2',
  249. source_output_file_path: 'ball.jpg',
  250. build_id: 'test',
  251. },
  252. },
  253. })
  254. ).to.be.true
  255. })
  256. describe('when the output files feature is not available', function () {
  257. const flagBefore = window.ExposedSettings.hasLinkedProjectOutputFileFeature
  258. before(function () {
  259. window.ExposedSettings.hasLinkedProjectOutputFileFeature = false
  260. })
  261. after(function () {
  262. window.ExposedSettings.hasLinkedProjectOutputFileFeature = flagBefore
  263. })
  264. it('should not show the import from output file mode', async function () {
  265. fetchMock.get('path:/user/projects', {
  266. projects: [
  267. {
  268. _id: 'test-project',
  269. name: 'This Project',
  270. },
  271. {
  272. _id: 'project-1',
  273. name: 'Project One',
  274. },
  275. {
  276. _id: 'project-2',
  277. name: 'Project Two',
  278. },
  279. ],
  280. })
  281. renderWithContext(<OpenWithMode mode="project" />)
  282. // should not show the toggle
  283. expect(
  284. screen.queryByRole('button', {
  285. name: 'select from output files',
  286. })
  287. ).to.be.null
  288. })
  289. })
  290. it('import from a URL when the form is submitted', async function () {
  291. fetchMock.post('express:/project/:projectId/linked_file', () => 204)
  292. renderWithContext(<OpenWithMode mode="url" />)
  293. const urlInput = screen.getByLabelText('URL to fetch the file from')
  294. const nameInput = screen.getByLabelText('File Name In This Project')
  295. await fireEvent.change(urlInput, {
  296. target: { value: 'https://example.com/example.tex' },
  297. })
  298. // check that the name has updated automatically
  299. expect(nameInput.value).to.equal('example.tex')
  300. await fireEvent.change(nameInput, {
  301. target: { value: 'test.tex' },
  302. })
  303. // check that the name can still be edited manually
  304. expect(nameInput.value).to.equal('test.tex')
  305. const submitButton = screen.getByRole('button', { name: 'Create' })
  306. await fireEvent.click(submitButton)
  307. expect(
  308. fetchMock.called('express:/project/:projectId/linked_file', {
  309. body: {
  310. name: 'test.tex',
  311. provider: 'url',
  312. parent_folder_id: 'root-folder-id',
  313. data: { url: 'https://example.com/example.tex' },
  314. },
  315. })
  316. ).to.be.true
  317. })
  318. it('uploads a dropped file', async function () {
  319. const xhr = sinon.useFakeXMLHttpRequest()
  320. const requests = []
  321. xhr.onCreate = request => {
  322. requests.push(request)
  323. }
  324. renderWithContext(<OpenWithMode mode="upload" />)
  325. // the submit button should not be present
  326. expect(screen.queryByRole('button', { name: 'Create' })).to.be.null
  327. const dropzone = screen.getByLabelText('File Uploader')
  328. expect(dropzone).not.to.be.null
  329. fireEvent.drop(dropzone, {
  330. dataTransfer: {
  331. files: [new File(['test'], 'test.tex', { type: 'text/plain' })],
  332. },
  333. })
  334. await waitFor(() => expect(requests).to.have.length(1))
  335. const [request] = requests
  336. expect(request.url).to.equal(
  337. '/project/123abc/upload?folder_id=root-folder-id'
  338. )
  339. expect(request.method).to.equal('POST')
  340. xhr.restore()
  341. })
  342. it('uploads a pasted file', async function () {
  343. const xhr = sinon.useFakeXMLHttpRequest()
  344. const requests = []
  345. xhr.onCreate = request => {
  346. requests.push(request)
  347. }
  348. renderWithContext(<OpenWithMode mode="upload" />)
  349. // the submit button should not be present
  350. expect(screen.queryByRole('button', { name: 'Create' })).to.be.null
  351. const dropzone = screen.getByLabelText('File Uploader')
  352. expect(dropzone).not.to.be.null
  353. fireEvent.paste(dropzone, {
  354. clipboardData: {
  355. files: [new File(['test'], 'test.tex', { type: 'text/plain' })],
  356. },
  357. })
  358. await waitFor(() => expect(requests).to.have.length(1))
  359. const [request] = requests
  360. expect(request.url).to.equal(
  361. '/project/123abc/upload?folder_id=root-folder-id'
  362. )
  363. expect(request.method).to.equal('POST')
  364. xhr.restore()
  365. })
  366. it('displays upload errors', async function () {
  367. const xhr = sinon.useFakeXMLHttpRequest()
  368. const requests = []
  369. xhr.onCreate = request => {
  370. requests.push(request)
  371. }
  372. renderWithContext(<OpenWithMode mode="upload" />)
  373. // the submit button should not be present
  374. expect(screen.queryByRole('button', { name: 'Create' })).to.be.null
  375. const dropzone = screen.getByLabelText('File Uploader')
  376. expect(dropzone).not.to.be.null
  377. fireEvent.paste(dropzone, {
  378. clipboardData: {
  379. files: [new File(['test'], 'tes!t.tex', { type: 'text/plain' })],
  380. },
  381. })
  382. await waitFor(() => expect(requests).to.have.length(1))
  383. const [request] = requests
  384. expect(request.url).to.equal(
  385. '/project/123abc/upload?folder_id=root-folder-id'
  386. )
  387. expect(request.method).to.equal('POST')
  388. request.respond(
  389. 422,
  390. { 'Content-Type': 'application/json' },
  391. '{ "success": false, "error": "invalid_filename" }'
  392. )
  393. await screen.findByText(
  394. `Upload failed: check that the file name doesn’t contain special characters, trailing/leading whitespace or more than 150 characters`
  395. )
  396. xhr.restore()
  397. })
  398. })
  399. function OpenWithMode({ mode }) {
  400. const { newFileCreateMode, startCreatingFile } = useFileTreeActionable()
  401. const { fileCount } = useFileTreeData()
  402. // eslint-disable-next-line react-hooks/exhaustive-deps
  403. useEffect(() => startCreatingFile(mode), [])
  404. if (!fileCount || !newFileCreateMode) {
  405. return null
  406. }
  407. return <FileTreeModalCreateFile />
  408. }
  409. OpenWithMode.propTypes = {
  410. mode: PropTypes.string.isRequired,
  411. }