local-compile-context.js 18 KB

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