compile-context.js 13 KB

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