compile-context.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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. setUncompiled(changedAt > 0)
  164. }, [setUncompiled, changedAt])
  165. // always compile the PDF once after opening the project, after the doc has loaded
  166. useEffect(() => {
  167. if (!compiledOnce && currentDoc) {
  168. setCompiledOnce(true)
  169. compiler.compile({ isAutoCompileOnLoad: true })
  170. }
  171. }, [compiledOnce, currentDoc, compiler])
  172. // handle the data returned from a compile request
  173. // note: this should _only_ run when `data` changes,
  174. // the other dependencies must all be static
  175. useEffect(() => {
  176. if (data) {
  177. if (data.clsiServerId) {
  178. setClsiServerId(data.clsiServerId) // set in scope, for PdfSynctexController
  179. }
  180. if (data.outputFiles) {
  181. handleOutputFiles(projectId, data).then(result => {
  182. setLogEntryAnnotations(
  183. buildLogEntryAnnotations(result.logEntries.all, ide.fileTreeManager)
  184. )
  185. if (data.status === 'success') {
  186. setPdfDownloadUrl(result.pdfDownloadUrl)
  187. setPdfUrl(result.pdfUrl)
  188. }
  189. setLogEntries(result.logEntries)
  190. setFileList(result.fileList)
  191. setRawLog(result.log)
  192. // sample compile stats for real users
  193. if (!window.user.alphaProgram && data.status === 'success') {
  194. sendMBSampled(
  195. 'compile-result',
  196. {
  197. errors: result.logEntries.errors.length,
  198. warnings: result.logEntries.warnings.length,
  199. typesetting: result.logEntries.typesetting.length,
  200. newPdfPreview: true, // TODO: is this useful?
  201. },
  202. 0.01
  203. )
  204. }
  205. })
  206. }
  207. switch (data.status) {
  208. case 'success':
  209. setError(undefined)
  210. setShowLogs(false)
  211. break
  212. case 'clsi-maintenance':
  213. case 'compile-in-progress':
  214. case 'exited':
  215. case 'failure':
  216. case 'project-too-large':
  217. case 'rate-limited':
  218. case 'terminated':
  219. case 'too-recently-compiled':
  220. setError(data.status)
  221. break
  222. case 'timedout':
  223. setError('timedout')
  224. if (!hasPremiumCompile && isProjectOwner) {
  225. send(
  226. 'subscription-funnel',
  227. 'editor-click-feature',
  228. 'compile-timeout'
  229. )
  230. }
  231. break
  232. case 'autocompile-backoff':
  233. if (!data.options.isAutoCompileOnLoad) {
  234. setError('autocompile-disabled')
  235. setAutoCompile(false)
  236. }
  237. break
  238. case 'unavailable':
  239. setError('clsi-unavailable')
  240. break
  241. case 'validation-problems':
  242. setError('validation-problems')
  243. setValidationIssues(data.validationProblems)
  244. break
  245. default:
  246. setError('error')
  247. break
  248. }
  249. }
  250. }, [
  251. data,
  252. ide,
  253. hasPremiumCompile,
  254. isProjectOwner,
  255. projectId,
  256. setAutoCompile,
  257. setClsiServerId,
  258. setLogEntries,
  259. setLogEntryAnnotations,
  260. setPdfDownloadUrl,
  261. setPdfUrl,
  262. ])
  263. // switch to logs if there's an error
  264. useEffect(() => {
  265. if (error) {
  266. setShowLogs(true)
  267. }
  268. }, [error])
  269. // whether there has been an autocompile linting error, if syntax validation is switched on
  270. const autoCompileLintingError = Boolean(
  271. autoCompile && syntaxValidation && hasLintingError
  272. )
  273. const codeCheckFailed = stopOnValidationError && autoCompileLintingError
  274. // the project is available for auto-compiling
  275. const canAutoCompile = Boolean(autoCompile && !codeCheckFailed)
  276. // show that the project has pending changes
  277. const hasChanges = Boolean(canAutoCompile && uncompiled && compiledOnce)
  278. // call the debounced autocompile function if the project is available for auto-compiling and it has changed
  279. useEffect(() => {
  280. if (canAutoCompile) {
  281. if (changedAt > 0) {
  282. compiler.debouncedAutoCompile()
  283. }
  284. } else {
  285. compiler.debouncedAutoCompile.cancel()
  286. }
  287. }, [compiler, canAutoCompile, changedAt])
  288. // cancel debounced recompile on unmount
  289. useEffect(() => {
  290. return () => {
  291. compiler.debouncedAutoCompile.cancel()
  292. }
  293. }, [compiler])
  294. // start a compile manually
  295. const startCompile = useCallback(
  296. options => {
  297. compiler.compile(options)
  298. },
  299. [compiler]
  300. )
  301. // stop a compile manually
  302. const stopCompile = useCallback(() => {
  303. compiler.stopCompile()
  304. }, [compiler])
  305. // clear the compile cache
  306. const clearCache = useCallback(() => {
  307. setClearingCache(true)
  308. return compiler
  309. .clearCache()
  310. .then(() => {
  311. setFileList(undefined)
  312. setPdfDownloadUrl(undefined)
  313. setPdfUrl(undefined)
  314. })
  315. .finally(() => {
  316. setClearingCache(false)
  317. })
  318. }, [compiler, setPdfDownloadUrl, setPdfUrl])
  319. // clear the cache then run a compile, triggered by a menu item
  320. const recompileFromScratch = useCallback(() => {
  321. clearCache().then(() => {
  322. compiler.compile()
  323. })
  324. }, [clearCache, compiler])
  325. const value = useMemo(
  326. () => ({
  327. autoCompile,
  328. clearCache,
  329. clearingCache,
  330. clsiServerId,
  331. codeCheckFailed,
  332. compiling,
  333. draft,
  334. error,
  335. fileList,
  336. hasChanges,
  337. highlights,
  338. logEntryAnnotations,
  339. logEntries,
  340. pdfDownloadUrl,
  341. pdfUrl,
  342. pdfViewer,
  343. position,
  344. rawLog,
  345. recompileFromScratch,
  346. setAutoCompile,
  347. setCompiling,
  348. setDraft,
  349. setError,
  350. setHasLintingError, // only for stories
  351. setHighlights,
  352. setPosition,
  353. setShowLogs,
  354. setStopOnValidationError,
  355. showLogs,
  356. startCompile,
  357. stopCompile,
  358. stopOnValidationError,
  359. uncompiled,
  360. validationIssues,
  361. firstRenderDone,
  362. setChangedAt,
  363. cleanupCompileResult,
  364. }),
  365. [
  366. autoCompile,
  367. clearCache,
  368. clearingCache,
  369. clsiServerId,
  370. codeCheckFailed,
  371. compiling,
  372. draft,
  373. error,
  374. fileList,
  375. hasChanges,
  376. highlights,
  377. logEntries,
  378. logEntryAnnotations,
  379. position,
  380. pdfDownloadUrl,
  381. pdfUrl,
  382. pdfViewer,
  383. rawLog,
  384. recompileFromScratch,
  385. setAutoCompile,
  386. setDraft,
  387. setError,
  388. setHasLintingError, // only for stories
  389. setHighlights,
  390. setPosition,
  391. setStopOnValidationError,
  392. showLogs,
  393. startCompile,
  394. stopCompile,
  395. stopOnValidationError,
  396. uncompiled,
  397. validationIssues,
  398. firstRenderDone,
  399. setChangedAt,
  400. cleanupCompileResult,
  401. ]
  402. )
  403. return (
  404. <CompileContext.Provider value={value}>{children}</CompileContext.Provider>
  405. )
  406. }
  407. CompileProvider.propTypes = {
  408. children: PropTypes.any,
  409. }
  410. export function useCompileContext(propTypes) {
  411. const data = useContext(CompileContext)
  412. PropTypes.checkPropTypes(propTypes, data, 'data', 'CompileContext.Provider')
  413. return data
  414. }