local-compile-context.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. import {
  2. createContext,
  3. useCallback,
  4. useContext,
  5. useEffect,
  6. useMemo,
  7. useRef,
  8. useState,
  9. } from 'react'
  10. import PropTypes from 'prop-types'
  11. import useScopeValue from '../hooks/use-scope-value'
  12. import useScopeValueSetterOnly from '../hooks/use-scope-value-setter-only'
  13. import usePersistedState from '../hooks/use-persisted-state'
  14. import useAbortController from '../hooks/use-abort-controller'
  15. import DocumentCompiler from '../../features/pdf-preview/util/compiler'
  16. import {
  17. send,
  18. sendMBOnce,
  19. sendMBSampled,
  20. } from '../../infrastructure/event-tracking'
  21. import {
  22. buildLogEntryAnnotations,
  23. handleLogFiles,
  24. handleOutputFiles,
  25. } from '../../features/pdf-preview/util/output-files'
  26. import { useIdeContext } from './ide-context'
  27. import { useProjectContext } from './project-context'
  28. import { useEditorContext } from './editor-context'
  29. import { buildFileList } from '../../features/pdf-preview/util/file-list'
  30. import { useSplitTestContext } from './split-test-context'
  31. import { useLayoutContext } from './layout-context'
  32. export const LocalCompileContext = createContext()
  33. export const CompileContextPropTypes = {
  34. value: PropTypes.shape({
  35. autoCompile: PropTypes.bool.isRequired,
  36. clearingCache: PropTypes.bool.isRequired,
  37. clsiServerId: PropTypes.string,
  38. codeCheckFailed: PropTypes.bool.isRequired,
  39. compiling: PropTypes.bool.isRequired,
  40. deliveryLatencies: PropTypes.object.isRequired,
  41. draft: PropTypes.bool.isRequired,
  42. error: PropTypes.string,
  43. fileList: PropTypes.object,
  44. hasChanges: PropTypes.bool.isRequired,
  45. highlights: PropTypes.arrayOf(PropTypes.object),
  46. logEntries: PropTypes.object,
  47. logEntryAnnotations: PropTypes.object,
  48. pdfDownloadUrl: PropTypes.string,
  49. pdfFile: PropTypes.object,
  50. pdfUrl: PropTypes.string,
  51. pdfViewer: PropTypes.string,
  52. position: PropTypes.object,
  53. rawLog: PropTypes.string,
  54. setAutoCompile: PropTypes.func.isRequired,
  55. setDraft: PropTypes.func.isRequired,
  56. setError: PropTypes.func.isRequired,
  57. setHasLintingError: PropTypes.func.isRequired, // only for storybook
  58. setHighlights: PropTypes.func.isRequired,
  59. setPosition: PropTypes.func.isRequired,
  60. setShowCompileTimeWarning: PropTypes.func.isRequired,
  61. setShowLogs: PropTypes.func.isRequired,
  62. toggleLogs: PropTypes.func.isRequired,
  63. setStopOnFirstError: PropTypes.func.isRequired,
  64. setStopOnValidationError: PropTypes.func.isRequired,
  65. showCompileTimeWarning: PropTypes.bool.isRequired,
  66. showLogs: PropTypes.bool.isRequired,
  67. showFasterCompilesFeedbackUI: PropTypes.bool.isRequired,
  68. stopOnFirstError: PropTypes.bool.isRequired,
  69. stopOnValidationError: PropTypes.bool.isRequired,
  70. stoppedOnFirstError: PropTypes.bool.isRequired,
  71. uncompiled: PropTypes.bool,
  72. validationIssues: PropTypes.object,
  73. firstRenderDone: PropTypes.func.isRequired,
  74. cleanupCompileResult: PropTypes.func,
  75. }),
  76. }
  77. LocalCompileContext.Provider.propTypes = CompileContextPropTypes
  78. export function LocalCompileProvider({ children }) {
  79. const ide = useIdeContext()
  80. const { hasPremiumCompile, isProjectOwner } = useEditorContext()
  81. const { _id: projectId, rootDocId } = useProjectContext()
  82. const { splitTestVariants } = useSplitTestContext()
  83. const { pdfPreviewOpen } = useLayoutContext()
  84. // whether a compile is in progress
  85. const [compiling, setCompiling] = useState(false)
  86. // whether to show the compile time warning
  87. const [showCompileTimeWarning, setShowCompileTimeWarning] = useState(false)
  88. // the log entries parsed from the compile output log
  89. const [logEntries, setLogEntries] = useScopeValueSetterOnly('pdf.logEntries')
  90. // annotations for display in the editor, built from the log entries
  91. const [logEntryAnnotations, setLogEntryAnnotations] = useScopeValue(
  92. 'pdf.logEntryAnnotations'
  93. )
  94. // the PDF viewer
  95. const [pdfViewer] = useScopeValue('settings.pdfViewer')
  96. // the URL for downloading the PDF
  97. const [, setPdfDownloadUrl] = useScopeValueSetterOnly('pdf.downloadUrl')
  98. // the URL for loading the PDF in the preview pane
  99. const [, setPdfUrl] = useScopeValueSetterOnly('pdf.url')
  100. // low level details for metrics
  101. const [pdfFile, setPdfFile] = useState()
  102. useEffect(() => {
  103. setPdfDownloadUrl(pdfFile?.pdfDownloadUrl)
  104. setPdfUrl(pdfFile?.pdfUrl)
  105. }, [pdfFile, setPdfDownloadUrl, setPdfUrl])
  106. // the project is considered to be "uncompiled" if a doc has changed since the last compile started
  107. const [uncompiled, setUncompiled] = useScopeValue('pdf.uncompiled')
  108. // the id of the CLSI server which ran the compile
  109. const [clsiServerId, setClsiServerId] = useState()
  110. // data received in response to a compile request
  111. const [data, setData] = useState()
  112. // callback to be invoked for PdfJsMetrics
  113. const [firstRenderDone, setFirstRenderDone] = useState(() => () => {})
  114. // latencies of compile/pdf download/rendering
  115. const [deliveryLatencies, setDeliveryLatencies] = useState({})
  116. // whether the project has been compiled yet
  117. const [compiledOnce, setCompiledOnce] = useState(false)
  118. // whether the cache is being cleared
  119. const [clearingCache, setClearingCache] = useState(false)
  120. // whether the logs should be visible
  121. const [showLogs, setShowLogs] = useState(false)
  122. // whether the faster compiles feedback UI should be displayed
  123. const [showFasterCompilesFeedbackUI, setShowFasterCompilesFeedbackUI] =
  124. useState(false)
  125. // whether the compile dropdown arrow should be animated
  126. const [animateCompileDropdownArrow, setAnimateCompileDropdownArrow] =
  127. useState(false)
  128. const toggleLogs = useCallback(() => {
  129. setShowLogs(prev => {
  130. if (!prev) {
  131. sendMBOnce('ide-open-logs-once')
  132. }
  133. return !prev
  134. })
  135. }, [setShowLogs])
  136. // an error that occurred
  137. const [error, setError] = useState()
  138. // the list of files that can be downloaded
  139. const [fileList, setFileList] = useState()
  140. // the raw contents of the log file
  141. const [rawLog, setRawLog] = useState()
  142. // validation issues from CLSI
  143. const [validationIssues, setValidationIssues] = useState()
  144. // areas to highlight on the PDF, from synctex
  145. const [highlights, setHighlights] = useState()
  146. // scroll position of the PDF
  147. const [position, setPosition] = usePersistedState(`pdf.position.${projectId}`)
  148. // whether autocompile is switched on
  149. const [autoCompile, setAutoCompile] = usePersistedState(
  150. `autocompile_enabled:${projectId}`,
  151. false,
  152. true
  153. )
  154. // whether the compile should run in draft mode
  155. const [draft, setDraft] = usePersistedState(`draft:${projectId}`, false, true)
  156. // whether compiling should stop on first error
  157. const [stopOnFirstError, setStopOnFirstError] = usePersistedState(
  158. `stop_on_first_error:${projectId}`,
  159. false,
  160. true
  161. )
  162. // whether the last compiles stopped on first error
  163. const [stoppedOnFirstError, setStoppedOnFirstError] = useState(false)
  164. // whether compiling should be prevented if there are linting errors
  165. const [stopOnValidationError, setStopOnValidationError] = usePersistedState(
  166. `stop_on_validation_error:${projectId}`,
  167. true,
  168. true
  169. )
  170. // the Document currently open in the editor
  171. const [currentDoc] = useScopeValue('editor.sharejs_doc')
  172. // whether the editor linter found errors
  173. const [hasLintingError, setHasLintingError] = useScopeValue('hasLintingError')
  174. // whether syntax validation is enabled globally
  175. const [syntaxValidation] = useScopeValue('settings.syntaxValidation')
  176. // the timestamp that a doc was last changed or saved
  177. const [changedAt, setChangedAt] = useState(0)
  178. const { signal } = useAbortController()
  179. const cleanupCompileResult = useCallback(() => {
  180. setPdfFile(null)
  181. setLogEntries(null)
  182. setLogEntryAnnotations({})
  183. }, [setPdfFile, setLogEntries, setLogEntryAnnotations])
  184. const compilingRef = useRef(false)
  185. useEffect(() => {
  186. compilingRef.current = compiling
  187. }, [compiling])
  188. // the document compiler
  189. const [compiler] = useState(() => {
  190. return new DocumentCompiler({
  191. projectId,
  192. rootDocId,
  193. setChangedAt,
  194. setCompiling,
  195. setData,
  196. setFirstRenderDone,
  197. setDeliveryLatencies,
  198. setError,
  199. cleanupCompileResult,
  200. compilingRef,
  201. signal,
  202. })
  203. })
  204. // keep currentDoc in sync with the compiler
  205. useEffect(() => {
  206. compiler.currentDoc = currentDoc
  207. }, [compiler, currentDoc])
  208. // keep draft setting in sync with the compiler
  209. useEffect(() => {
  210. compiler.setOption('draft', draft)
  211. }, [compiler, draft])
  212. // keep stop on first error setting in sync with the compiler
  213. useEffect(() => {
  214. compiler.setOption('stopOnFirstError', stopOnFirstError)
  215. }, [compiler, stopOnFirstError])
  216. // pass the "uncompiled" value up into the scope for use outside this context provider
  217. useEffect(() => {
  218. setUncompiled(changedAt > 0)
  219. }, [setUncompiled, changedAt])
  220. // always compile the PDF once after opening the project, after the doc has loaded
  221. useEffect(() => {
  222. if (!compiledOnce && currentDoc) {
  223. setCompiledOnce(true)
  224. compiler.compile({ isAutoCompileOnLoad: true })
  225. }
  226. }, [compiledOnce, currentDoc, compiler])
  227. useEffect(() => {
  228. const compileTimeWarningEnabled =
  229. splitTestVariants['compile-time-warning'] === 'show-upgrade-prompt'
  230. if (compileTimeWarningEnabled && compiling && isProjectOwner) {
  231. const timeout = window.setTimeout(() => {
  232. setShowCompileTimeWarning(true)
  233. }, 30000)
  234. return () => {
  235. window.clearTimeout(timeout)
  236. }
  237. }
  238. }, [compiling, isProjectOwner, splitTestVariants])
  239. // handle the data returned from a compile request
  240. // note: this should _only_ run when `data` changes,
  241. // the other dependencies must all be static
  242. useEffect(() => {
  243. const abortController = new AbortController()
  244. if (data) {
  245. if (data.clsiServerId) {
  246. setClsiServerId(data.clsiServerId) // set in scope, for PdfSynctexController
  247. }
  248. setShowFasterCompilesFeedbackUI(
  249. Boolean(data.showFasterCompilesFeedbackUI)
  250. )
  251. if (data.outputFiles) {
  252. const outputFiles = new Map()
  253. for (const outputFile of data.outputFiles) {
  254. outputFiles.set(outputFile.path, outputFile)
  255. }
  256. // set the PDF context
  257. if (data.status === 'success') {
  258. setPdfFile(handleOutputFiles(outputFiles, projectId, data))
  259. }
  260. setFileList(
  261. buildFileList(outputFiles, data.clsiServerId, data.compileGroup)
  262. )
  263. // handle log files
  264. // asynchronous (TODO: cancel on new compile?)
  265. setLogEntryAnnotations(null)
  266. setLogEntries(null)
  267. setRawLog(null)
  268. handleLogFiles(outputFiles, data, abortController.signal).then(
  269. result => {
  270. setRawLog(result.log)
  271. setLogEntries(result.logEntries)
  272. setLogEntryAnnotations(
  273. buildLogEntryAnnotations(
  274. result.logEntries.all,
  275. ide.fileTreeManager
  276. )
  277. )
  278. // sample compile stats for real users
  279. if (
  280. !window.user.alphaProgram &&
  281. ['success', 'stopped-on-first-error'].includes(data.status)
  282. ) {
  283. sendMBSampled(
  284. 'compile-result',
  285. {
  286. errors: result.logEntries.errors.length,
  287. warnings: result.logEntries.warnings.length,
  288. typesetting: result.logEntries.typesetting.length,
  289. newPdfPreview: true, // TODO: is this useful?
  290. stopOnFirstError: data.options.stopOnFirstError,
  291. },
  292. 0.01
  293. )
  294. }
  295. }
  296. )
  297. }
  298. switch (data.status) {
  299. case 'success':
  300. setError(undefined)
  301. setShowLogs(false)
  302. break
  303. case 'stopped-on-first-error':
  304. setError(undefined)
  305. setShowLogs(true)
  306. break
  307. case 'clsi-maintenance':
  308. case 'compile-in-progress':
  309. case 'exited':
  310. case 'failure':
  311. case 'project-too-large':
  312. case 'rate-limited':
  313. case 'terminated':
  314. case 'too-recently-compiled':
  315. setError(data.status)
  316. break
  317. case 'timedout':
  318. setError('timedout')
  319. if (!hasPremiumCompile && isProjectOwner) {
  320. send(
  321. 'subscription-funnel',
  322. 'editor-click-feature',
  323. 'compile-timeout'
  324. )
  325. }
  326. break
  327. case 'autocompile-backoff':
  328. if (!data.options.isAutoCompileOnLoad) {
  329. setError('autocompile-disabled')
  330. setAutoCompile(false)
  331. }
  332. break
  333. case 'unavailable':
  334. setError('clsi-unavailable')
  335. break
  336. case 'validation-problems':
  337. setError('validation-problems')
  338. setValidationIssues(data.validationProblems)
  339. break
  340. default:
  341. setError('error')
  342. break
  343. }
  344. setStoppedOnFirstError(data.status === 'stopped-on-first-error')
  345. }
  346. return () => {
  347. abortController.abort()
  348. }
  349. }, [
  350. data,
  351. ide,
  352. hasPremiumCompile,
  353. isProjectOwner,
  354. projectId,
  355. setAutoCompile,
  356. setClsiServerId,
  357. setLogEntries,
  358. setLogEntryAnnotations,
  359. setPdfFile,
  360. ])
  361. // switch to logs if there's an error
  362. useEffect(() => {
  363. if (error) {
  364. setShowLogs(true)
  365. }
  366. }, [error])
  367. // whether there has been an autocompile linting error, if syntax validation is switched on
  368. const autoCompileLintingError = Boolean(
  369. autoCompile && syntaxValidation && hasLintingError
  370. )
  371. const codeCheckFailed = stopOnValidationError && autoCompileLintingError
  372. // the project is available for auto-compiling
  373. // (autocompile is enabled, the PDF preview is open, and the code check (if enabled) hasn't failed)
  374. const canAutoCompile = Boolean(
  375. autoCompile && pdfPreviewOpen && !codeCheckFailed
  376. )
  377. // show that the project has pending changes
  378. const hasChanges = Boolean(canAutoCompile && uncompiled && compiledOnce)
  379. // call the debounced autocompile function if the project is available for auto-compiling and it has changed
  380. useEffect(() => {
  381. if (canAutoCompile) {
  382. if (changedAt > 0) {
  383. compiler.debouncedAutoCompile()
  384. }
  385. } else {
  386. compiler.debouncedAutoCompile.cancel()
  387. }
  388. }, [compiler, canAutoCompile, changedAt])
  389. // cancel debounced recompile on unmount
  390. useEffect(() => {
  391. return () => {
  392. compiler.debouncedAutoCompile.cancel()
  393. }
  394. }, [compiler])
  395. // start a compile manually
  396. const startCompile = useCallback(
  397. options => {
  398. compiler.compile(options)
  399. },
  400. [compiler]
  401. )
  402. // stop a compile manually
  403. const stopCompile = useCallback(() => {
  404. compiler.stopCompile()
  405. }, [compiler])
  406. // clear the compile cache
  407. const clearCache = useCallback(() => {
  408. setClearingCache(true)
  409. return compiler
  410. .clearCache()
  411. .then(() => {
  412. setFileList(undefined)
  413. setPdfFile(undefined)
  414. })
  415. .finally(() => {
  416. setClearingCache(false)
  417. })
  418. }, [compiler])
  419. // clear the cache then run a compile, triggered by a menu item
  420. const recompileFromScratch = useCallback(() => {
  421. clearCache().then(() => {
  422. compiler.compile()
  423. })
  424. }, [clearCache, compiler])
  425. // After a compile, the compiler sets `data.options` to the options that were
  426. // used for that compile.
  427. const lastCompileOptions = useMemo(() => data?.options || {}, [data])
  428. const value = useMemo(
  429. () => ({
  430. animateCompileDropdownArrow,
  431. autoCompile,
  432. clearCache,
  433. clearingCache,
  434. clsiServerId,
  435. codeCheckFailed,
  436. compiling,
  437. deliveryLatencies,
  438. draft,
  439. error,
  440. fileList,
  441. hasChanges,
  442. highlights,
  443. lastCompileOptions,
  444. logEntryAnnotations,
  445. logEntries,
  446. pdfDownloadUrl: pdfFile?.pdfDownloadUrl,
  447. pdfFile,
  448. pdfUrl: pdfFile?.pdfUrl,
  449. pdfViewer,
  450. position,
  451. rawLog,
  452. recompileFromScratch,
  453. setAnimateCompileDropdownArrow,
  454. setAutoCompile,
  455. setCompiling,
  456. setDraft,
  457. setError,
  458. setHasLintingError, // only for stories
  459. setHighlights,
  460. setPosition,
  461. showCompileTimeWarning,
  462. setShowCompileTimeWarning,
  463. setShowLogs,
  464. toggleLogs,
  465. setStopOnFirstError,
  466. setStopOnValidationError,
  467. showLogs,
  468. showFasterCompilesFeedbackUI,
  469. startCompile,
  470. stopCompile,
  471. stopOnFirstError,
  472. stopOnValidationError,
  473. stoppedOnFirstError,
  474. uncompiled,
  475. validationIssues,
  476. firstRenderDone,
  477. setChangedAt,
  478. cleanupCompileResult,
  479. }),
  480. [
  481. animateCompileDropdownArrow,
  482. autoCompile,
  483. clearCache,
  484. clearingCache,
  485. clsiServerId,
  486. codeCheckFailed,
  487. compiling,
  488. deliveryLatencies,
  489. draft,
  490. error,
  491. fileList,
  492. hasChanges,
  493. highlights,
  494. lastCompileOptions,
  495. logEntries,
  496. logEntryAnnotations,
  497. position,
  498. pdfFile,
  499. pdfViewer,
  500. rawLog,
  501. recompileFromScratch,
  502. setAnimateCompileDropdownArrow,
  503. setAutoCompile,
  504. setDraft,
  505. setError,
  506. setHasLintingError, // only for stories
  507. setHighlights,
  508. setPosition,
  509. setShowCompileTimeWarning,
  510. setStopOnFirstError,
  511. setStopOnValidationError,
  512. showCompileTimeWarning,
  513. showLogs,
  514. showFasterCompilesFeedbackUI,
  515. startCompile,
  516. stopCompile,
  517. stopOnFirstError,
  518. stopOnValidationError,
  519. stoppedOnFirstError,
  520. uncompiled,
  521. validationIssues,
  522. firstRenderDone,
  523. setChangedAt,
  524. cleanupCompileResult,
  525. setShowLogs,
  526. toggleLogs,
  527. ]
  528. )
  529. return (
  530. <LocalCompileContext.Provider value={value}>
  531. {children}
  532. </LocalCompileContext.Provider>
  533. )
  534. }
  535. LocalCompileProvider.propTypes = {
  536. children: PropTypes.any,
  537. }
  538. export function useLocalCompileContext(propTypes) {
  539. const data = useContext(LocalCompileContext)
  540. PropTypes.checkPropTypes(
  541. propTypes,
  542. data,
  543. 'data',
  544. 'LocalCompileContext.Provider'
  545. )
  546. return data
  547. }