compile-context.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. handleOutputFiles,
  20. } from '../../features/pdf-preview/util/output-files'
  21. import { useIdeContext } from './ide-context'
  22. import { useProjectContext } from './project-context'
  23. import { useEditorContext } from './editor-context'
  24. export const CompileContext = createContext()
  25. CompileContext.Provider.propTypes = {
  26. value: PropTypes.shape({
  27. autoCompile: PropTypes.bool.isRequired,
  28. clearingCache: PropTypes.bool.isRequired,
  29. clsiServerId: PropTypes.string,
  30. codeCheckFailed: PropTypes.bool.isRequired,
  31. compiling: PropTypes.bool.isRequired,
  32. draft: PropTypes.bool.isRequired,
  33. error: PropTypes.string,
  34. fileList: PropTypes.object,
  35. hasChanges: PropTypes.bool.isRequired,
  36. highlights: PropTypes.arrayOf(PropTypes.object),
  37. logEntries: PropTypes.object,
  38. logEntryAnnotations: PropTypes.object,
  39. pdfDownloadUrl: PropTypes.string,
  40. pdfUrl: PropTypes.string,
  41. pdfViewer: PropTypes.string,
  42. position: PropTypes.object,
  43. rawLog: PropTypes.string,
  44. setAutoCompile: PropTypes.func.isRequired,
  45. setDraft: PropTypes.func.isRequired,
  46. setError: PropTypes.func.isRequired,
  47. setHasLintingError: PropTypes.func.isRequired, // only for storybook
  48. setHighlights: PropTypes.func.isRequired,
  49. setPosition: PropTypes.func.isRequired,
  50. setShowLogs: PropTypes.func.isRequired,
  51. setStopOnValidationError: PropTypes.func.isRequired,
  52. showLogs: PropTypes.bool.isRequired,
  53. stopOnValidationError: PropTypes.bool.isRequired,
  54. uncompiled: PropTypes.bool,
  55. validationIssues: PropTypes.object,
  56. firstRenderDone: PropTypes.func,
  57. cleanupCompileResult: PropTypes.func,
  58. }),
  59. }
  60. export function CompileProvider({ children }) {
  61. const ide = useIdeContext()
  62. const { hasPremiumCompile, isProjectOwner } = useEditorContext()
  63. const { _id: projectId, rootDocId } = useProjectContext()
  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. const compilingRef = useRef(false)
  135. useEffect(() => {
  136. compilingRef.current = compiling
  137. }, [compiling])
  138. // the document compiler
  139. const [compiler] = useState(() => {
  140. return new DocumentCompiler({
  141. projectId,
  142. rootDocId,
  143. setChangedAt,
  144. setCompiling,
  145. setData,
  146. setFirstRenderDone,
  147. setError,
  148. cleanupCompileResult,
  149. compilingRef,
  150. signal,
  151. })
  152. })
  153. // keep currentDoc in sync with the compiler
  154. useEffect(() => {
  155. compiler.currentDoc = currentDoc
  156. }, [compiler, currentDoc])
  157. // keep draft setting in sync with the compiler
  158. useEffect(() => {
  159. compiler.draft = draft
  160. }, [compiler, draft])
  161. // pass the "uncompiled" value up into the scope for use outside this context provider
  162. useEffect(() => {
  163. if (window.showNewPdfPreview) {
  164. setUncompiled(changedAt > 0)
  165. }
  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. if (data) {
  179. if (data.clsiServerId) {
  180. setClsiServerId(data.clsiServerId) // set in scope, for PdfSynctexController
  181. }
  182. if (data.outputFiles) {
  183. handleOutputFiles(projectId, data).then(result => {
  184. setLogEntryAnnotations(
  185. buildLogEntryAnnotations(result.logEntries.all, ide.fileTreeManager)
  186. )
  187. if (data.status === 'success') {
  188. setPdfDownloadUrl(result.pdfDownloadUrl)
  189. setPdfUrl(result.pdfUrl)
  190. }
  191. setLogEntries(result.logEntries)
  192. setFileList(result.fileList)
  193. setRawLog(result.log)
  194. // sample compile stats for real users
  195. if (!window.user.alphaProgram && data.status === 'success') {
  196. sendMBSampled(
  197. 'compile-result',
  198. {
  199. errors: result.logEntries.errors.length,
  200. warnings: result.logEntries.warnings.length,
  201. typesetting: result.logEntries.typesetting.length,
  202. newPdfPreview: true, // TODO: is this useful?
  203. },
  204. 0.01
  205. )
  206. }
  207. })
  208. }
  209. switch (data.status) {
  210. case 'success':
  211. setError(undefined)
  212. setShowLogs(false)
  213. break
  214. case 'clsi-maintenance':
  215. case 'compile-in-progress':
  216. case 'exited':
  217. case 'failure':
  218. case 'project-too-large':
  219. case 'rate-limited':
  220. case 'terminated':
  221. case 'too-recently-compiled':
  222. setError(data.status)
  223. break
  224. case 'timedout':
  225. setError('timedout')
  226. if (!hasPremiumCompile && isProjectOwner) {
  227. send(
  228. 'subscription-funnel',
  229. 'editor-click-feature',
  230. 'compile-timeout'
  231. )
  232. }
  233. break
  234. case 'autocompile-backoff':
  235. if (!data.options.isAutoCompileOnLoad) {
  236. setError('autocompile-disabled')
  237. setAutoCompile(false)
  238. }
  239. break
  240. case 'unavailable':
  241. setError('clsi-unavailable')
  242. break
  243. case 'validation-problems':
  244. setError('validation-problems')
  245. setValidationIssues(data.validationProblems)
  246. break
  247. default:
  248. setError('error')
  249. break
  250. }
  251. }
  252. }, [
  253. data,
  254. ide,
  255. hasPremiumCompile,
  256. isProjectOwner,
  257. projectId,
  258. setAutoCompile,
  259. setClsiServerId,
  260. setLogEntries,
  261. setLogEntryAnnotations,
  262. setPdfDownloadUrl,
  263. setPdfUrl,
  264. ])
  265. // switch to logs if there's an error
  266. useEffect(() => {
  267. if (error) {
  268. setShowLogs(true)
  269. }
  270. }, [error])
  271. // whether there has been an autocompile linting error, if syntax validation is switched on
  272. const autoCompileLintingError = Boolean(
  273. autoCompile && syntaxValidation && hasLintingError
  274. )
  275. const codeCheckFailed = stopOnValidationError && autoCompileLintingError
  276. // the project is available for auto-compiling
  277. const canAutoCompile = Boolean(autoCompile && !codeCheckFailed)
  278. // show that the project has pending changes
  279. const hasChanges = Boolean(canAutoCompile && uncompiled && compiledOnce)
  280. // call the debounced autocompile function if the project is available for auto-compiling and it has changed
  281. useEffect(() => {
  282. if (canAutoCompile) {
  283. if (changedAt > 0) {
  284. compiler.debouncedAutoCompile()
  285. }
  286. } else {
  287. compiler.debouncedAutoCompile.cancel()
  288. }
  289. }, [compiler, canAutoCompile, changedAt])
  290. // cancel debounced recompile on unmount
  291. useEffect(() => {
  292. return () => {
  293. compiler.debouncedAutoCompile.cancel()
  294. }
  295. }, [compiler])
  296. // start a compile manually
  297. const startCompile = useCallback(
  298. options => {
  299. compiler.compile(options)
  300. },
  301. [compiler]
  302. )
  303. // stop a compile manually
  304. const stopCompile = useCallback(() => {
  305. compiler.stopCompile()
  306. }, [compiler])
  307. // clear the compile cache
  308. const clearCache = useCallback(() => {
  309. setClearingCache(true)
  310. return compiler
  311. .clearCache()
  312. .then(() => {
  313. setFileList(undefined)
  314. setPdfDownloadUrl(undefined)
  315. setPdfUrl(undefined)
  316. })
  317. .finally(() => {
  318. setClearingCache(false)
  319. })
  320. }, [compiler, setPdfDownloadUrl, setPdfUrl])
  321. // clear the cache then run a compile, triggered by a menu item
  322. const recompileFromScratch = useCallback(() => {
  323. clearCache().then(() => {
  324. compiler.compile()
  325. })
  326. }, [clearCache, compiler])
  327. const value = useMemo(
  328. () => ({
  329. autoCompile,
  330. clearCache,
  331. clearingCache,
  332. clsiServerId,
  333. codeCheckFailed,
  334. compiling,
  335. draft,
  336. error,
  337. fileList,
  338. hasChanges,
  339. highlights,
  340. logEntryAnnotations,
  341. logEntries,
  342. pdfDownloadUrl,
  343. pdfUrl,
  344. pdfViewer,
  345. position,
  346. rawLog,
  347. recompileFromScratch,
  348. setAutoCompile,
  349. setCompiling,
  350. setDraft,
  351. setError,
  352. setHasLintingError, // only for stories
  353. setHighlights,
  354. setPosition,
  355. setShowLogs,
  356. setStopOnValidationError,
  357. showLogs,
  358. startCompile,
  359. stopCompile,
  360. stopOnValidationError,
  361. uncompiled,
  362. validationIssues,
  363. firstRenderDone,
  364. setChangedAt,
  365. cleanupCompileResult,
  366. }),
  367. [
  368. autoCompile,
  369. clearCache,
  370. clearingCache,
  371. clsiServerId,
  372. codeCheckFailed,
  373. compiling,
  374. draft,
  375. error,
  376. fileList,
  377. hasChanges,
  378. highlights,
  379. logEntries,
  380. logEntryAnnotations,
  381. position,
  382. pdfDownloadUrl,
  383. pdfUrl,
  384. pdfViewer,
  385. rawLog,
  386. recompileFromScratch,
  387. setAutoCompile,
  388. setDraft,
  389. setError,
  390. setHasLintingError, // only for stories
  391. setHighlights,
  392. setPosition,
  393. setStopOnValidationError,
  394. showLogs,
  395. startCompile,
  396. stopCompile,
  397. stopOnValidationError,
  398. uncompiled,
  399. validationIssues,
  400. firstRenderDone,
  401. setChangedAt,
  402. cleanupCompileResult,
  403. ]
  404. )
  405. return (
  406. <CompileContext.Provider value={value}>{children}</CompileContext.Provider>
  407. )
  408. }
  409. CompileProvider.propTypes = {
  410. children: PropTypes.any,
  411. }
  412. export function useCompileContext(propTypes) {
  413. const data = useContext(CompileContext)
  414. PropTypes.checkPropTypes(propTypes, data, 'data', 'CompileContext.Provider')
  415. return data
  416. }