local-compile-context.js 18 KB

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