compile-context.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 { send, sendMBSampled } from '../../infrastructure/event-tracking'
  17. import {
  18. buildLogEntryAnnotations,
  19. handleLogFiles,
  20. handleOutputFiles,
  21. } from '../../features/pdf-preview/util/output-files'
  22. import { useIdeContext } from './ide-context'
  23. import { useProjectContext } from './project-context'
  24. import { useEditorContext } from './editor-context'
  25. import { buildFileList } from '../../features/pdf-preview/util/file-list'
  26. export const CompileContext = createContext()
  27. CompileContext.Provider.propTypes = {
  28. value: PropTypes.shape({
  29. autoCompile: PropTypes.bool.isRequired,
  30. clearingCache: PropTypes.bool.isRequired,
  31. clsiServerId: PropTypes.string,
  32. codeCheckFailed: PropTypes.bool.isRequired,
  33. compiling: PropTypes.bool.isRequired,
  34. draft: PropTypes.bool.isRequired,
  35. error: PropTypes.string,
  36. fileList: PropTypes.object,
  37. hasChanges: PropTypes.bool.isRequired,
  38. highlights: PropTypes.arrayOf(PropTypes.object),
  39. logEntries: PropTypes.object,
  40. logEntryAnnotations: PropTypes.object,
  41. pdfDownloadUrl: PropTypes.string,
  42. pdfUrl: PropTypes.string,
  43. pdfViewer: PropTypes.string,
  44. position: PropTypes.object,
  45. rawLog: PropTypes.string,
  46. setAutoCompile: PropTypes.func.isRequired,
  47. setDraft: PropTypes.func.isRequired,
  48. setError: PropTypes.func.isRequired,
  49. setHasLintingError: PropTypes.func.isRequired, // only for storybook
  50. setHighlights: PropTypes.func.isRequired,
  51. setPosition: PropTypes.func.isRequired,
  52. setShowLogs: PropTypes.func.isRequired,
  53. setStopOnValidationError: PropTypes.func.isRequired,
  54. showLogs: PropTypes.bool.isRequired,
  55. stopOnValidationError: PropTypes.bool.isRequired,
  56. uncompiled: PropTypes.bool,
  57. validationIssues: PropTypes.object,
  58. firstRenderDone: PropTypes.func,
  59. cleanupCompileResult: PropTypes.func,
  60. }),
  61. }
  62. export function CompileProvider({ children }) {
  63. const ide = useIdeContext()
  64. const { hasPremiumCompile, isProjectOwner } = useEditorContext()
  65. const { _id: projectId, rootDocId } = useProjectContext()
  66. // whether a compile is in progress
  67. const [compiling, setCompiling] = useState(false)
  68. // the log entries parsed from the compile output log
  69. const [logEntries, setLogEntries] = useScopeValueSetterOnly('pdf.logEntries')
  70. // annotations for display in the editor, built from the log entries
  71. const [logEntryAnnotations, setLogEntryAnnotations] = useScopeValue(
  72. 'pdf.logEntryAnnotations'
  73. )
  74. // the PDF viewer
  75. const [pdfViewer] = useScopeValue('settings.pdfViewer')
  76. // the URL for downloading the PDF
  77. const [pdfDownloadUrl, setPdfDownloadUrl] =
  78. useScopeValueSetterOnly('pdf.downloadUrl')
  79. // the URL for loading the PDF in the preview pane
  80. const [pdfUrl, setPdfUrl] = useScopeValueSetterOnly('pdf.url')
  81. // the project is considered to be "uncompiled" if a doc has changed since the last compile started
  82. const [uncompiled, setUncompiled] = useScopeValue('pdf.uncompiled')
  83. // the id of the CLSI server which ran the compile
  84. const [clsiServerId, setClsiServerId] = useState()
  85. // data received in response to a compile request
  86. const [data, setData] = useState()
  87. // callback to be invoked for PdfJsMetrics
  88. const [firstRenderDone, setFirstRenderDone] = useState()
  89. // whether the project has been compiled yet
  90. const [compiledOnce, setCompiledOnce] = useState(false)
  91. // whether the cache is being cleared
  92. const [clearingCache, setClearingCache] = useState(false)
  93. // whether the logs should be visible
  94. const [showLogs, setShowLogs] = useState(false)
  95. // an error that occurred
  96. const [error, setError] = useState()
  97. // the list of files that can be downloaded
  98. const [fileList, setFileList] = useState()
  99. // the raw contents of the log file
  100. const [rawLog, setRawLog] = useState()
  101. // validation issues from CLSI
  102. const [validationIssues, setValidationIssues] = useState()
  103. // areas to highlight on the PDF, from synctex
  104. const [highlights, setHighlights] = useState()
  105. // scroll position of the PDF
  106. const [position, setPosition] = usePersistedState(`pdf.position.${projectId}`)
  107. // whether autocompile is switched on
  108. const [autoCompile, setAutoCompile] = usePersistedState(
  109. `autocompile_enabled:${projectId}`,
  110. false,
  111. true
  112. )
  113. // whether the compile should run in draft mode
  114. const [draft, setDraft] = usePersistedState(`draft:${projectId}`, false, true)
  115. // whether compiling should be prevented if there are linting errors
  116. const [stopOnValidationError, setStopOnValidationError] = usePersistedState(
  117. `stop_on_validation_error:${projectId}`,
  118. true,
  119. true
  120. )
  121. // the Document currently open in the editor
  122. const [currentDoc] = useScopeValue('editor.sharejs_doc')
  123. // whether the editor linter found errors
  124. const [hasLintingError, setHasLintingError] = useScopeValue('hasLintingError')
  125. // whether syntax validation is enabled globally
  126. const [syntaxValidation] = useScopeValue('settings.syntaxValidation')
  127. // the timestamp that a doc was last changed or saved
  128. const [changedAt, setChangedAt] = useState(0)
  129. const { signal } = useAbortController()
  130. const cleanupCompileResult = useCallback(() => {
  131. setPdfUrl(null)
  132. setPdfDownloadUrl(null)
  133. setLogEntries(null)
  134. setLogEntryAnnotations({})
  135. }, [setPdfUrl, setPdfDownloadUrl, setLogEntries, setLogEntryAnnotations])
  136. const compilingRef = useRef(false)
  137. useEffect(() => {
  138. compilingRef.current = compiling
  139. }, [compiling])
  140. // the document compiler
  141. const [compiler] = useState(() => {
  142. return new DocumentCompiler({
  143. projectId,
  144. rootDocId,
  145. setChangedAt,
  146. setCompiling,
  147. setData,
  148. setFirstRenderDone,
  149. setError,
  150. cleanupCompileResult,
  151. compilingRef,
  152. signal,
  153. })
  154. })
  155. // keep currentDoc in sync with the compiler
  156. useEffect(() => {
  157. compiler.currentDoc = currentDoc
  158. }, [compiler, currentDoc])
  159. // keep draft setting in sync with the compiler
  160. useEffect(() => {
  161. compiler.draft = draft
  162. }, [compiler, draft])
  163. // pass the "uncompiled" value up into the scope for use outside this context provider
  164. useEffect(() => {
  165. setUncompiled(changedAt > 0)
  166. }, [setUncompiled, changedAt])
  167. // always compile the PDF once after opening the project, after the doc has loaded
  168. useEffect(() => {
  169. if (!compiledOnce && currentDoc) {
  170. setCompiledOnce(true)
  171. compiler.compile({ isAutoCompileOnLoad: true })
  172. }
  173. }, [compiledOnce, currentDoc, compiler])
  174. // handle the data returned from a compile request
  175. // note: this should _only_ run when `data` changes,
  176. // the other dependencies must all be static
  177. useEffect(() => {
  178. const abortController = new AbortController()
  179. if (data) {
  180. if (data.clsiServerId) {
  181. setClsiServerId(data.clsiServerId) // set in scope, for PdfSynctexController
  182. }
  183. if (data.outputFiles) {
  184. const outputFiles = new Map()
  185. for (const outputFile of data.outputFiles) {
  186. outputFiles.set(outputFile.path, outputFile)
  187. }
  188. // set the PDF URLs
  189. handleOutputFiles(outputFiles, projectId, data).then(result => {
  190. if (data.status === 'success') {
  191. setPdfDownloadUrl(result.pdfDownloadUrl)
  192. setPdfUrl(result.pdfUrl)
  193. }
  194. setFileList(buildFileList(outputFiles, data.clsiServerId))
  195. // handle log files
  196. // asynchronous (TODO: cancel on new compile?)
  197. setLogEntryAnnotations(null)
  198. setLogEntries(null)
  199. setRawLog(null)
  200. handleLogFiles(outputFiles, data, abortController.signal).then(
  201. result => {
  202. setRawLog(result.log)
  203. setLogEntries(result.logEntries)
  204. setLogEntryAnnotations(
  205. buildLogEntryAnnotations(
  206. result.logEntries.all,
  207. ide.fileTreeManager
  208. )
  209. )
  210. // sample compile stats for real users
  211. if (!window.user.alphaProgram && data.status === 'success') {
  212. sendMBSampled(
  213. 'compile-result',
  214. {
  215. errors: result.logEntries.errors.length,
  216. warnings: result.logEntries.warnings.length,
  217. typesetting: result.logEntries.typesetting.length,
  218. newPdfPreview: true, // TODO: is this useful?
  219. },
  220. 0.01
  221. )
  222. }
  223. }
  224. )
  225. })
  226. }
  227. switch (data.status) {
  228. case 'success':
  229. setError(undefined)
  230. setShowLogs(false)
  231. break
  232. case 'clsi-maintenance':
  233. case 'compile-in-progress':
  234. case 'exited':
  235. case 'failure':
  236. case 'project-too-large':
  237. case 'rate-limited':
  238. case 'terminated':
  239. case 'too-recently-compiled':
  240. setError(data.status)
  241. break
  242. case 'timedout':
  243. setError('timedout')
  244. if (!hasPremiumCompile && isProjectOwner) {
  245. send(
  246. 'subscription-funnel',
  247. 'editor-click-feature',
  248. 'compile-timeout'
  249. )
  250. }
  251. break
  252. case 'autocompile-backoff':
  253. if (!data.options.isAutoCompileOnLoad) {
  254. setError('autocompile-disabled')
  255. setAutoCompile(false)
  256. }
  257. break
  258. case 'unavailable':
  259. setError('clsi-unavailable')
  260. break
  261. case 'validation-problems':
  262. setError('validation-problems')
  263. setValidationIssues(data.validationProblems)
  264. break
  265. default:
  266. setError('error')
  267. break
  268. }
  269. }
  270. return () => {
  271. abortController.abort()
  272. }
  273. }, [
  274. data,
  275. ide,
  276. hasPremiumCompile,
  277. isProjectOwner,
  278. projectId,
  279. setAutoCompile,
  280. setClsiServerId,
  281. setLogEntries,
  282. setLogEntryAnnotations,
  283. setPdfDownloadUrl,
  284. setPdfUrl,
  285. ])
  286. // switch to logs if there's an error
  287. useEffect(() => {
  288. if (error) {
  289. setShowLogs(true)
  290. }
  291. }, [error])
  292. // whether there has been an autocompile linting error, if syntax validation is switched on
  293. const autoCompileLintingError = Boolean(
  294. autoCompile && syntaxValidation && hasLintingError
  295. )
  296. const codeCheckFailed = stopOnValidationError && autoCompileLintingError
  297. // the project is available for auto-compiling
  298. const canAutoCompile = Boolean(autoCompile && !codeCheckFailed)
  299. // show that the project has pending changes
  300. const hasChanges = Boolean(canAutoCompile && uncompiled && compiledOnce)
  301. // call the debounced autocompile function if the project is available for auto-compiling and it has changed
  302. useEffect(() => {
  303. if (canAutoCompile) {
  304. if (changedAt > 0) {
  305. compiler.debouncedAutoCompile()
  306. }
  307. } else {
  308. compiler.debouncedAutoCompile.cancel()
  309. }
  310. }, [compiler, canAutoCompile, changedAt])
  311. // cancel debounced recompile on unmount
  312. useEffect(() => {
  313. return () => {
  314. compiler.debouncedAutoCompile.cancel()
  315. }
  316. }, [compiler])
  317. // start a compile manually
  318. const startCompile = useCallback(
  319. options => {
  320. compiler.compile(options)
  321. },
  322. [compiler]
  323. )
  324. // stop a compile manually
  325. const stopCompile = useCallback(() => {
  326. compiler.stopCompile()
  327. }, [compiler])
  328. // clear the compile cache
  329. const clearCache = useCallback(() => {
  330. setClearingCache(true)
  331. return compiler
  332. .clearCache()
  333. .then(() => {
  334. setFileList(undefined)
  335. setPdfDownloadUrl(undefined)
  336. setPdfUrl(undefined)
  337. })
  338. .finally(() => {
  339. setClearingCache(false)
  340. })
  341. }, [compiler, setPdfDownloadUrl, setPdfUrl])
  342. // clear the cache then run a compile, triggered by a menu item
  343. const recompileFromScratch = useCallback(() => {
  344. clearCache().then(() => {
  345. compiler.compile()
  346. })
  347. }, [clearCache, compiler])
  348. const value = useMemo(
  349. () => ({
  350. autoCompile,
  351. clearCache,
  352. clearingCache,
  353. clsiServerId,
  354. codeCheckFailed,
  355. compiling,
  356. draft,
  357. error,
  358. fileList,
  359. hasChanges,
  360. highlights,
  361. logEntryAnnotations,
  362. logEntries,
  363. pdfDownloadUrl,
  364. pdfUrl,
  365. pdfViewer,
  366. position,
  367. rawLog,
  368. recompileFromScratch,
  369. setAutoCompile,
  370. setCompiling,
  371. setDraft,
  372. setError,
  373. setHasLintingError, // only for stories
  374. setHighlights,
  375. setPosition,
  376. setShowLogs,
  377. setStopOnValidationError,
  378. showLogs,
  379. startCompile,
  380. stopCompile,
  381. stopOnValidationError,
  382. uncompiled,
  383. validationIssues,
  384. firstRenderDone,
  385. setChangedAt,
  386. cleanupCompileResult,
  387. }),
  388. [
  389. autoCompile,
  390. clearCache,
  391. clearingCache,
  392. clsiServerId,
  393. codeCheckFailed,
  394. compiling,
  395. draft,
  396. error,
  397. fileList,
  398. hasChanges,
  399. highlights,
  400. logEntries,
  401. logEntryAnnotations,
  402. position,
  403. pdfDownloadUrl,
  404. pdfUrl,
  405. pdfViewer,
  406. rawLog,
  407. recompileFromScratch,
  408. setAutoCompile,
  409. setDraft,
  410. setError,
  411. setHasLintingError, // only for stories
  412. setHighlights,
  413. setPosition,
  414. setStopOnValidationError,
  415. showLogs,
  416. startCompile,
  417. stopCompile,
  418. stopOnValidationError,
  419. uncompiled,
  420. validationIssues,
  421. firstRenderDone,
  422. setChangedAt,
  423. cleanupCompileResult,
  424. ]
  425. )
  426. return (
  427. <CompileContext.Provider value={value}>{children}</CompileContext.Provider>
  428. )
  429. }
  430. CompileProvider.propTypes = {
  431. children: PropTypes.any,
  432. }
  433. export function useCompileContext(propTypes) {
  434. const data = useContext(CompileContext)
  435. PropTypes.checkPropTypes(propTypes, data, 'data', 'CompileContext.Provider')
  436. return data
  437. }