pdf-preview.test.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. import { expect } from 'chai'
  2. import sinon from 'sinon'
  3. import fetchMock from 'fetch-mock'
  4. import { screen, fireEvent, waitFor, cleanup } from '@testing-library/react'
  5. import PdfPreview from '../../../../../frontend/js/features/pdf-preview/components/pdf-preview'
  6. import { renderWithEditorContext } from '../../../helpers/render-with-context'
  7. import nock from 'nock'
  8. import path from 'path'
  9. import fs from 'fs'
  10. import { cloneDeep } from 'lodash'
  11. const examplePDF = path.join(__dirname, '../fixtures/test-example.pdf')
  12. const corruptPDF = path.join(__dirname, '../fixtures/test-example-corrupt.pdf')
  13. const outputFiles = [
  14. {
  15. path: 'output.pdf',
  16. build: '123',
  17. url: '/build/output.pdf',
  18. type: 'pdf',
  19. },
  20. {
  21. path: 'output.bbl',
  22. build: '123',
  23. url: '/build/output.bbl',
  24. type: 'bbl',
  25. },
  26. {
  27. path: 'output.bib',
  28. build: '123',
  29. url: '/build/output.bib',
  30. type: 'bib',
  31. },
  32. {
  33. path: 'example.txt',
  34. build: '123',
  35. url: '/build/example.txt',
  36. type: 'txt',
  37. },
  38. {
  39. path: 'output.log',
  40. build: '123',
  41. url: '/build/output.log',
  42. type: 'log',
  43. },
  44. {
  45. path: 'output.blg',
  46. build: '123',
  47. url: '/build/output.blg',
  48. type: 'blg',
  49. },
  50. ]
  51. const mockCompile = (delayPromise = Promise.resolve()) =>
  52. fetchMock.post(
  53. 'express:/project/:projectId/compile',
  54. delayPromise.then(() => ({
  55. body: {
  56. status: 'success',
  57. clsiServerId: 'foo',
  58. compileGroup: 'priority',
  59. pdfDownloadDomain: 'https://clsi.test-overleaf.com',
  60. outputFiles: cloneDeep(outputFiles),
  61. },
  62. }))
  63. )
  64. const mockDelayed = fn => {
  65. let _resolve = null
  66. const delayPromise = new Promise((resolve, reject) => {
  67. _resolve = resolve
  68. })
  69. fn(delayPromise)
  70. return _resolve
  71. }
  72. const mockCompileError = status =>
  73. fetchMock.post('express:/project/:projectId/compile', {
  74. body: {
  75. status,
  76. clsiServerId: 'foo',
  77. compileGroup: 'priority',
  78. },
  79. })
  80. const mockValidationProblems = validationProblems =>
  81. fetchMock.post('express:/project/:projectId/compile', {
  82. body: {
  83. status: 'validation-problems',
  84. validationProblems,
  85. clsiServerId: 'foo',
  86. compileGroup: 'priority',
  87. },
  88. })
  89. const mockClearCache = () =>
  90. fetchMock.delete('express:/project/:projectId/output', 204)
  91. const mockValidPdf = () => {
  92. nock('https://clsi.test-overleaf.com')
  93. .get(/^\/build\/output\.pdf/)
  94. .replyWithFile(200, examplePDF)
  95. }
  96. const defaultFileResponses = {
  97. '/build/output.pdf': () => fs.createReadStream(examplePDF),
  98. '/build/output.blg': 'This is BibTeX, Version 4.0', // FIXME
  99. '/build/output.log': `
  100. The LaTeX compiler output
  101. * With a lot of details
  102. Wrapped in an HTML <pre> element with
  103. preformatted text which is to be presented exactly
  104. as written in the HTML file
  105. (whitespace included™)
  106. The text is typically rendered using a non-proportional ("monospace") font.
  107. LaTeX Font Info: External font \`cmex10' loaded for size
  108. (Font) <7> on input line 18.
  109. LaTeX Font Info: External font \`cmex10' loaded for size
  110. (Font) <5> on input line 18.
  111. ! Undefined control sequence.
  112. <recently read> \\Zlpha
  113. main.tex, line 23
  114. `,
  115. }
  116. const mockBuildFile = (responses = defaultFileResponses) => {
  117. fetchMock.get('begin:https://clsi.test-overleaf.com/', _url => {
  118. const url = new URL(_url, 'https://clsi.test-overleaf.com')
  119. if (url.pathname in responses) {
  120. return responses[url.pathname]
  121. }
  122. return 404
  123. })
  124. fetchMock.get('express:/build/:file', (_url, options, request) => {
  125. const url = new URL(_url, 'https://example.com')
  126. if (url.pathname in responses) {
  127. return responses[url.pathname]
  128. }
  129. return 404
  130. })
  131. }
  132. const storeAndFireEvent = (key, value) => {
  133. localStorage.setItem(key, value)
  134. fireEvent(window, new StorageEvent('storage', { key }))
  135. }
  136. const scope = {
  137. settings: {
  138. syntaxValidation: false,
  139. },
  140. editor: {
  141. sharejs_doc: {
  142. doc_id: 'test-doc',
  143. getSnapshot: () => 'some doc content',
  144. },
  145. },
  146. }
  147. describe('<PdfPreview/>', function () {
  148. let clock
  149. beforeEach(function () {
  150. window.showNewPdfPreview = true
  151. clock = sinon.useFakeTimers({
  152. shouldAdvanceTime: true,
  153. now: Date.now(),
  154. })
  155. nock.cleanAll()
  156. })
  157. afterEach(function () {
  158. window.showNewPdfPreview = undefined
  159. clock.runAll()
  160. clock.restore()
  161. fetchMock.reset()
  162. localStorage.clear()
  163. sinon.restore()
  164. })
  165. it('renders the PDF preview', async function () {
  166. mockCompile()
  167. mockBuildFile()
  168. mockValidPdf()
  169. renderWithEditorContext(<PdfPreview />, { scope })
  170. // wait for "compile on load" to finish
  171. await screen.findByRole('button', { name: 'Compiling…' })
  172. await screen.findByRole('button', { name: 'Recompile' })
  173. })
  174. it('runs a compile when the Recompile button is pressed', async function () {
  175. mockCompile()
  176. mockBuildFile()
  177. mockValidPdf()
  178. renderWithEditorContext(<PdfPreview />, { scope })
  179. // wait for "compile on load" to finish
  180. await screen.findByRole('button', { name: 'Compiling…' })
  181. await screen.findByRole('button', { name: 'Recompile' })
  182. mockValidPdf()
  183. // press the Recompile button => compile
  184. const button = screen.getByRole('button', { name: 'Recompile' })
  185. button.click()
  186. await screen.findByRole('button', { name: 'Compiling…' })
  187. await screen.findByRole('button', { name: 'Recompile' })
  188. expect(fetchMock.calls()).to.have.length(6)
  189. })
  190. it('runs a compile on `pdf:recompile` event', async function () {
  191. mockCompile()
  192. mockBuildFile()
  193. mockValidPdf()
  194. renderWithEditorContext(<PdfPreview />, { scope })
  195. // wait for "compile on load" to finish
  196. await screen.findByRole('button', { name: 'Compiling…' })
  197. await screen.findByRole('button', { name: 'Recompile' })
  198. mockValidPdf()
  199. fireEvent(window, new CustomEvent('pdf:recompile'))
  200. await screen.findByRole('button', { name: 'Compiling…' })
  201. await screen.findByRole('button', { name: 'Recompile' })
  202. expect(fetchMock.calls()).to.have.length(6)
  203. })
  204. it('does not compile while compiling', async function () {
  205. mockDelayed(mockCompile)
  206. renderWithEditorContext(<PdfPreview />, { scope })
  207. // trigger compiles while "compile on load" is running
  208. await screen.findByRole('button', { name: 'Compiling…' })
  209. fireEvent(window, new CustomEvent('pdf:recompile'))
  210. expect(fetchMock.calls()).to.have.length(1)
  211. })
  212. it('disables compile button while compile is running', async function () {
  213. mockCompile()
  214. mockBuildFile()
  215. mockValidPdf()
  216. renderWithEditorContext(<PdfPreview />, { scope })
  217. let button = screen.getByRole('button', { name: 'Compiling…' })
  218. expect(button.hasAttribute('disabled')).to.be.true
  219. button = await screen.findByRole('button', { name: 'Recompile' })
  220. expect(button.hasAttribute('disabled')).to.be.false
  221. })
  222. it('runs a compile on doc change if autocompile is enabled', async function () {
  223. mockCompile()
  224. mockBuildFile()
  225. mockValidPdf()
  226. renderWithEditorContext(<PdfPreview />, { scope })
  227. // wait for "compile on load" to finish
  228. await screen.findByRole('button', { name: 'Compiling…' })
  229. await screen.findByRole('button', { name: 'Recompile' })
  230. // switch on auto compile
  231. storeAndFireEvent('autocompile_enabled:project123', true)
  232. mockValidPdf()
  233. // fire a doc:changed event => compile
  234. fireEvent(window, new CustomEvent('doc:changed'))
  235. clock.tick(2000) // AUTO_COMPILE_DEBOUNCE
  236. await screen.findByRole('button', { name: 'Compiling…' })
  237. await screen.findByRole('button', { name: 'Recompile' })
  238. expect(fetchMock.calls()).to.have.length(6)
  239. })
  240. it('does not run a compile on doc change if autocompile is disabled', async function () {
  241. mockCompile()
  242. mockBuildFile()
  243. mockValidPdf()
  244. renderWithEditorContext(<PdfPreview />, { scope })
  245. // wait for "compile on load" to finish
  246. await screen.findByRole('button', { name: 'Compiling…' })
  247. await screen.findByRole('button', { name: 'Recompile' })
  248. // make sure auto compile is switched off
  249. storeAndFireEvent('autocompile_enabled:project123', false)
  250. // fire a doc:changed event => no compile
  251. fireEvent(window, new CustomEvent('doc:changed'))
  252. clock.tick(2000) // AUTO_COMPILE_DEBOUNCE
  253. screen.getByRole('button', { name: 'Recompile' })
  254. expect(fetchMock.calls()).to.have.length(3)
  255. })
  256. it('does not run a compile on doc change if autocompile is blocked by syntax check', async function () {
  257. mockCompile()
  258. mockBuildFile()
  259. mockValidPdf()
  260. renderWithEditorContext(<PdfPreview />, {
  261. scope: {
  262. ...scope,
  263. 'settings.syntaxValidation': true, // enable linting in the editor
  264. hasLintingError: true, // mock a linting error
  265. },
  266. })
  267. // wait for "compile on load" to finish
  268. await screen.findByRole('button', { name: 'Compiling…' })
  269. await screen.findByRole('button', { name: 'Recompile' })
  270. // switch on auto compile and syntax checking
  271. storeAndFireEvent('autocompile_enabled:project123', true)
  272. storeAndFireEvent('stop_on_validation_error:project123', true)
  273. // fire a doc:changed event => no compile
  274. fireEvent(window, new CustomEvent('doc:changed'))
  275. clock.tick(2000) // AUTO_COMPILE_DEBOUNCE
  276. screen.getByRole('button', { name: 'Recompile' })
  277. await screen.findByText('Code check failed')
  278. expect(fetchMock.calls()).to.have.length(3)
  279. })
  280. describe('displays error messages', function () {
  281. const compileErrorStatuses = {
  282. 'clear-cache':
  283. 'Sorry, something went wrong and your project could not be compiled. Please try again in a few moments.',
  284. 'clsi-maintenance':
  285. 'The compile servers are down for maintenance, and will be back shortly.',
  286. 'compile-in-progress':
  287. 'A previous compile is still running. Please wait a minute and try compiling again.',
  288. exited: 'Server Error',
  289. failure: 'No PDF',
  290. generic: 'Server Error',
  291. 'project-too-large': 'Project too large',
  292. 'rate-limited': 'Compile rate limit hit',
  293. terminated: 'Compilation cancelled',
  294. timedout: 'Timed out',
  295. 'too-recently-compiled':
  296. 'This project was compiled very recently, so this compile has been skipped.',
  297. unavailable:
  298. 'Sorry, the compile server for your project was temporarily unavailable. Please try again in a few moments.',
  299. foo: 'Sorry, something went wrong and your project could not be compiled. Please try again in a few moments.',
  300. }
  301. for (const [status, message] of Object.entries(compileErrorStatuses)) {
  302. it(`displays error message for '${status}' status`, async function () {
  303. cleanup()
  304. fetchMock.restore()
  305. mockCompileError(status)
  306. renderWithEditorContext(<PdfPreview />, { scope })
  307. // wait for "compile on load" to finish
  308. await screen.findByRole('button', { name: 'Compiling…' })
  309. await screen.findByRole('button', { name: 'Recompile' })
  310. screen.getByText(message)
  311. })
  312. }
  313. })
  314. it('displays expandable raw logs', async function () {
  315. mockCompile()
  316. mockBuildFile()
  317. mockValidPdf()
  318. // pretend that the content is large enough to trigger a "collapse"
  319. // (in jsdom these values are always zero)
  320. sinon.stub(HTMLElement.prototype, 'scrollHeight').value(500)
  321. sinon.stub(HTMLElement.prototype, 'scrollWidth').value(500)
  322. renderWithEditorContext(<PdfPreview />, { scope })
  323. // wait for "compile on load" to finish
  324. await screen.findByRole('button', { name: 'Compiling…' })
  325. await screen.findByRole('button', { name: 'Recompile' })
  326. const logsButton = screen.getByRole('button', { name: 'View logs' })
  327. logsButton.click()
  328. await screen.findByRole('button', { name: 'View PDF' })
  329. // expand the log
  330. const [expandButton] = screen.getAllByRole('button', { name: 'Expand' })
  331. expandButton.click()
  332. // collapse the log
  333. const [collapseButton] = screen.getAllByRole('button', { name: 'Collapse' })
  334. collapseButton.click()
  335. })
  336. it('displays error messages if there were validation problems', async function () {
  337. const validationProblems = {
  338. sizeCheck: {
  339. resources: [
  340. { path: 'foo/bar', kbSize: 76221 },
  341. { path: 'bar/baz', kbSize: 2342 },
  342. ],
  343. },
  344. mainFile: true,
  345. conflictedPaths: [
  346. {
  347. path: 'foo/bar',
  348. },
  349. {
  350. path: 'foo/baz',
  351. },
  352. ],
  353. }
  354. mockValidationProblems(validationProblems)
  355. renderWithEditorContext(<PdfPreview />, { scope })
  356. // wait for "compile on load" to finish
  357. await screen.findByRole('button', { name: 'Compiling…' })
  358. await screen.findByRole('button', { name: 'Recompile' })
  359. screen.getByText('Project too large')
  360. screen.getByText('Unknown main document')
  361. screen.getByText('Conflicting Paths Found')
  362. expect(fetchMock.called('express:/project/:projectId/compile')).to.be.true // TODO: auto_compile query param
  363. expect(fetchMock.called('begin:https://clsi.test-overleaf.com/')).to.be
  364. .false // TODO: actual path
  365. })
  366. it('sends a clear cache request when the button is pressed', async function () {
  367. mockCompile()
  368. mockBuildFile()
  369. mockValidPdf()
  370. renderWithEditorContext(<PdfPreview />, { scope })
  371. // wait for "compile on load" to finish
  372. await screen.findByRole('button', { name: 'Compiling…' })
  373. await screen.findByRole('button', { name: 'Recompile' })
  374. const logsButton = screen.getByRole('button', {
  375. name: 'View logs',
  376. })
  377. logsButton.click()
  378. const clearCacheButton = await screen.findByRole('button', {
  379. name: 'Clear cached files',
  380. })
  381. expect(clearCacheButton.hasAttribute('disabled')).to.be.false
  382. mockClearCache()
  383. // click the button
  384. clearCacheButton.click()
  385. expect(clearCacheButton.hasAttribute('disabled')).to.be.true
  386. await waitFor(() => {
  387. expect(clearCacheButton.hasAttribute('disabled')).to.be.false
  388. })
  389. expect(fetchMock.called('express:/project/:projectId/compile')).to.be.true // TODO: auto_compile query param
  390. expect(fetchMock.called('begin:https://clsi.test-overleaf.com/')).to.be.true // TODO: actual path
  391. })
  392. it('handle "recompile from scratch"', async function () {
  393. mockCompile()
  394. mockBuildFile()
  395. mockValidPdf()
  396. renderWithEditorContext(<PdfPreview />, { scope })
  397. // wait for "compile on load" to finish
  398. await screen.findByRole('button', { name: 'Compiling…' })
  399. await screen.findByRole('button', { name: 'Recompile' })
  400. // show the logs UI
  401. const logsButton = screen.getByRole('button', {
  402. name: 'View logs',
  403. })
  404. logsButton.click()
  405. const clearCacheButton = await screen.findByRole('button', {
  406. name: 'Clear cached files',
  407. })
  408. expect(clearCacheButton.hasAttribute('disabled')).to.be.false
  409. mockValidPdf()
  410. mockClearCache()
  411. const recompileFromScratch = screen.getByRole('menuitem', {
  412. name: 'Recompile from scratch',
  413. hidden: true,
  414. })
  415. recompileFromScratch.click()
  416. expect(clearCacheButton.hasAttribute('disabled')).to.be.true
  417. // wait for compile to finish
  418. await screen.findByRole('button', { name: 'Compiling…' })
  419. await screen.findByRole('button', { name: 'Recompile' })
  420. expect(fetchMock.called('express:/project/:projectId/compile')).to.be.true // TODO: auto_compile query param
  421. expect(fetchMock.called('express:/project/:projectId/output')).to.be.true
  422. expect(fetchMock.called('begin:https://clsi.test-overleaf.com/')).to.be.true // TODO: actual path
  423. })
  424. it('shows an error for an invalid URL', async function () {
  425. mockCompile()
  426. mockBuildFile()
  427. nock('https://clsi.test-overleaf.com')
  428. .get(/^\/build\/output.pdf/)
  429. .replyWithError({
  430. message: 'something awful happened',
  431. code: 'AWFUL_ERROR',
  432. })
  433. renderWithEditorContext(<PdfPreview />, { scope })
  434. await screen.findByText('Something went wrong while rendering this PDF.')
  435. expect(screen.queryByLabelText('Page 1')).to.not.exist
  436. expect(nock.isDone()).to.be.true
  437. })
  438. it('shows an error for a corrupt PDF', async function () {
  439. mockCompile()
  440. mockBuildFile()
  441. nock('https://clsi.test-overleaf.com')
  442. .get(/^\/build\/output.pdf/)
  443. .replyWithFile(200, corruptPDF)
  444. renderWithEditorContext(<PdfPreview />, { scope })
  445. await screen.findByText('Something went wrong while rendering this PDF.')
  446. expect(screen.queryByLabelText('Page 1')).to.not.exist
  447. expect(nock.isDone()).to.be.true
  448. })
  449. describe('human readable logs', function () {
  450. it('shows human readable hint for undefined reference errors', async function () {
  451. mockCompile()
  452. mockBuildFile({
  453. ...defaultFileResponses,
  454. '/build/output.log': `
  455. log This is pdfTeX, Version 3.14159265-2.6-1.40.21 (TeX Live 2020) (preloaded format=pdflatex 2020.9.10) 8 FEB 2022 16:27
  456. entering extended mode
  457. \\write18 enabled.
  458. %&-line parsing enabled.
  459. **main.tex
  460. (./main.tex
  461. LaTeX2e <2020-02-02> patch level 5
  462. LaTeX Warning: Reference \`intorduction' on page 1 undefined on input line 11.
  463. LaTeX Warning: Reference \`section1' on page 1 undefined on input line 13.
  464. [1
  465. {/usr/local/texlive/2020/texmf-var/fonts/map/pdftex/updmap/pdftex.map}] (/compi
  466. le/output.aux)
  467. LaTeX Warning: There were undefined references.
  468. )
  469. `,
  470. })
  471. mockValidPdf()
  472. renderWithEditorContext(<PdfPreview />, { scope })
  473. await screen.findByText(
  474. "Reference `intorduction' on page 1 undefined on input line 11."
  475. )
  476. await screen.findByText(
  477. "Reference `section1' on page 1 undefined on input line 13."
  478. )
  479. await screen.findByText('There were undefined references.')
  480. const hints = await screen.findAllByText(
  481. /You have referenced something which has not yet been labelled/
  482. )
  483. expect(hints.length).to.equal(3)
  484. })
  485. it('idoes not show human readable hint for undefined reference errors', async function () {
  486. mockCompile()
  487. mockBuildFile({
  488. ...defaultFileResponses,
  489. '/build/output.log': `
  490. Package rerunfilecheck Info: File \`output.out' has not changed.
  491. (rerunfilecheck) Checksum: 339DB29951BB30436898BC39909EA4FA;11265.
  492. Package rerunfilecheck Warning: File \`output.brf' has changed.
  493. (rerunfilecheck) Rerun to get bibliographical references right.
  494. Package rerunfilecheck Info: Checksums for \`output.brf':
  495. (rerunfilecheck) Before: D41D8CD98F00B204E9800998ECF8427E;0
  496. (rerunfilecheck) After: DF3260FAD3828D54C5E4E9337E97F7AF;4841.
  497. )
  498. `,
  499. })
  500. mockValidPdf()
  501. renderWithEditorContext(<PdfPreview />, { scope })
  502. await screen.findByText(
  503. /Package rerunfilecheck Warning: File `output.brf' has changed. Rerun to get bibliographical references right./
  504. )
  505. expect(
  506. screen.queryByText(
  507. /You have referenced something which has not yet been labelled/
  508. )
  509. ).to.not.exist
  510. })
  511. })
  512. })