compile-context.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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 {
  16. send,
  17. sendMB,
  18. sendMBSampled,
  19. } from '../../infrastructure/event-tracking'
  20. import {
  21. buildLogEntryAnnotations,
  22. handleOutputFiles,
  23. } from '../../features/pdf-preview/util/output-files'
  24. import { useIdeContext } from './ide-context'
  25. import { useProjectContext } from './project-context'
  26. import { useEditorContext } from './editor-context'
  27. export const CompileContext = createContext()
  28. CompileContext.Provider.propTypes = {
  29. value: PropTypes.shape({
  30. autoCompile: PropTypes.bool.isRequired,
  31. clearingCache: PropTypes.bool.isRequired,
  32. clsiServerId: PropTypes.string,
  33. codeCheckFailed: PropTypes.bool.isRequired,
  34. compiling: PropTypes.bool.isRequired,
  35. draft: PropTypes.bool.isRequired,
  36. error: PropTypes.string,
  37. fileList: PropTypes.object,
  38. hasChanges: PropTypes.bool.isRequired,
  39. highlights: PropTypes.arrayOf(PropTypes.object),
  40. logEntries: PropTypes.object,
  41. logEntryAnnotations: PropTypes.object,
  42. pdfDownloadUrl: PropTypes.string,
  43. pdfUrl: PropTypes.string,
  44. pdfViewer: PropTypes.string,
  45. position: PropTypes.object,
  46. rawLog: PropTypes.string,
  47. setAutoCompile: PropTypes.func.isRequired,
  48. setDraft: PropTypes.func.isRequired,
  49. setError: PropTypes.func.isRequired,
  50. setHasLintingError: PropTypes.func.isRequired, // only for storybook
  51. setHighlights: PropTypes.func.isRequired,
  52. setPosition: PropTypes.func.isRequired,
  53. setShowLogs: PropTypes.func.isRequired,
  54. setStopOnValidationError: PropTypes.func.isRequired,
  55. showLogs: PropTypes.bool.isRequired,
  56. stopOnValidationError: PropTypes.bool.isRequired,
  57. uncompiled: PropTypes.bool,
  58. validationIssues: PropTypes.object,
  59. firstRenderDone: PropTypes.func,
  60. cleanupCompileResult: PropTypes.func,
  61. }),
  62. }
  63. export function CompileProvider({ children }) {
  64. const ide = useIdeContext()
  65. const { hasPremiumCompile, isProjectOwner } = useEditorContext()
  66. const project = useProjectContext()
  67. const projectId = project._id
  68. // whether a compile is in progress
  69. const [compiling, setCompiling] = useState(false)
  70. // the log entries parsed from the compile output log
  71. const [logEntries, setLogEntries] = useScopeValueSetterOnly('pdf.logEntries')
  72. // annotations for display in the editor, built from the log entries
  73. const [logEntryAnnotations, setLogEntryAnnotations] = useScopeValue(
  74. 'pdf.logEntryAnnotations'
  75. )
  76. // the PDF viewer
  77. const [pdfViewer] = useScopeValue('settings.pdfViewer')
  78. // the URL for downloading the PDF
  79. const [pdfDownloadUrl, setPdfDownloadUrl] =
  80. useScopeValueSetterOnly('pdf.downloadUrl')
  81. // the URL for loading the PDF in the preview pane
  82. const [pdfUrl, setPdfUrl] = useScopeValueSetterOnly('pdf.url')
  83. // the project is considered to be "uncompiled" if a doc has changed since the last compile started
  84. const [uncompiled, setUncompiled] = useScopeValue('pdf.uncompiled')
  85. // the id of the CLSI server which ran the compile
  86. const [clsiServerId, setClsiServerId] = useState()
  87. // data received in response to a compile request
  88. const [data, setData] = useState()
  89. // callback to be invoked for PdfJsMetrics
  90. const [firstRenderDone, setFirstRenderDone] = useState()
  91. // whether the project has been compiled yet
  92. const [compiledOnce, setCompiledOnce] = useState(false)
  93. // whether the cache is being cleared
  94. const [clearingCache, setClearingCache] = useState(false)
  95. // whether the logs should be visible
  96. const [showLogs, setShowLogs] = useState(false)
  97. // an error that occurred
  98. const [error, setError] = useState()
  99. // the list of files that can be downloaded
  100. const [fileList, setFileList] = useState()
  101. // the raw contents of the log file
  102. const [rawLog, setRawLog] = useState()
  103. // validation issues from CLSI
  104. const [validationIssues, setValidationIssues] = useState()
  105. // areas to highlight on the PDF, from synctex
  106. const [highlights, setHighlights] = useState()
  107. // scroll position of the PDF
  108. const [position, setPosition] = usePersistedState(`pdf.position.${projectId}`)
  109. // whether autocompile is switched on
  110. const [autoCompile, setAutoCompile] = usePersistedState(
  111. `autocompile_enabled:${projectId}`,
  112. false,
  113. true
  114. )
  115. // whether the compile should run in draft mode
  116. const [draft, setDraft] = usePersistedState(`draft:${projectId}`, false, true)
  117. // whether compiling should be prevented if there are linting errors
  118. const [stopOnValidationError, setStopOnValidationError] = usePersistedState(
  119. `stop_on_validation_error:${projectId}`,
  120. true,
  121. true
  122. )
  123. // the Document currently open in the editor
  124. const [currentDoc] = useScopeValue('editor.sharejs_doc')
  125. // whether the editor linter found errors
  126. const [hasLintingError, setHasLintingError] = useScopeValue('hasLintingError')
  127. // whether syntax validation is enabled globally
  128. const [syntaxValidation] = useScopeValue('settings.syntaxValidation')
  129. // the timestamp that a doc was last changed or saved
  130. const [changedAt, setChangedAt] = useState(0)
  131. const { signal } = useAbortController()
  132. const cleanupCompileResult = useCallback(() => {
  133. setPdfUrl(null)
  134. setPdfDownloadUrl(null)
  135. setLogEntries(null)
  136. setLogEntryAnnotations({})
  137. }, [setPdfUrl, setPdfDownloadUrl, setLogEntries, setLogEntryAnnotations])
  138. // the document compiler
  139. const [compiler] = useState(() => {
  140. return new DocumentCompiler({
  141. project,
  142. setChangedAt,
  143. setCompiling,
  144. setData,
  145. setFirstRenderDone,
  146. setError,
  147. cleanupCompileResult,
  148. signal,
  149. })
  150. })
  151. // keep currentDoc in sync with the compiler
  152. useEffect(() => {
  153. compiler.currentDoc = currentDoc
  154. }, [compiler, currentDoc])
  155. // keep draft setting in sync with the compiler
  156. useEffect(() => {
  157. compiler.draft = draft
  158. }, [compiler, draft])
  159. // pass the "uncompiled" value up into the scope for use outside this context provider
  160. useEffect(() => {
  161. if (window.showNewPdfPreview) {
  162. setUncompiled(changedAt > 0)
  163. }
  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. sendMB('paywall-prompt', {
  231. 'paywall-type': 'compile-timeout',
  232. })
  233. }
  234. break
  235. case 'autocompile-backoff':
  236. if (!data.options.isAutoCompileOnLoad) {
  237. setError('autocompile-disabled')
  238. setAutoCompile(false)
  239. }
  240. break
  241. case 'unavailable':
  242. setError('clsi-unavailable')
  243. break
  244. case 'validation-problems':
  245. setError('validation-problems')
  246. setValidationIssues(data.validationProblems)
  247. break
  248. default:
  249. setError('error')
  250. break
  251. }
  252. }
  253. }, [
  254. data,
  255. ide,
  256. hasPremiumCompile,
  257. isProjectOwner,
  258. projectId,
  259. setAutoCompile,
  260. setClsiServerId,
  261. setLogEntries,
  262. setLogEntryAnnotations,
  263. setPdfDownloadUrl,
  264. setPdfUrl,
  265. ])
  266. // switch to logs if there's an error
  267. useEffect(() => {
  268. if (error) {
  269. setShowLogs(true)
  270. }
  271. }, [error])
  272. // whether there has been an autocompile linting error, if syntax validation is switched on
  273. const autoCompileLintingError = Boolean(
  274. autoCompile && syntaxValidation && hasLintingError
  275. )
  276. const codeCheckFailed = stopOnValidationError && autoCompileLintingError
  277. // the project is available for auto-compiling
  278. const canAutoCompile = Boolean(autoCompile && !codeCheckFailed)
  279. // show that the project has pending changes
  280. const hasChanges = Boolean(canAutoCompile && uncompiled && compiledOnce)
  281. // call the debounced autocompile function if the project is available for auto-compiling and it has changed
  282. useEffect(() => {
  283. if (canAutoCompile) {
  284. if (changedAt > 0) {
  285. compiler.debouncedAutoCompile()
  286. }
  287. } else {
  288. compiler.debouncedAutoCompile.cancel()
  289. }
  290. }, [compiler, canAutoCompile, changedAt])
  291. // cancel debounced recompile on unmount
  292. useEffect(() => {
  293. return () => {
  294. compiler.debouncedAutoCompile.cancel()
  295. }
  296. }, [compiler])
  297. // start a compile manually
  298. const startCompile = useCallback(
  299. options => {
  300. compiler.compile(options)
  301. },
  302. [compiler]
  303. )
  304. // stop a compile manually
  305. const stopCompile = useCallback(() => {
  306. compiler.stopCompile()
  307. }, [compiler])
  308. // clear the compile cache
  309. const clearCache = useCallback(() => {
  310. setClearingCache(true)
  311. return compiler
  312. .clearCache()
  313. .then(() => {
  314. setFileList(undefined)
  315. setPdfDownloadUrl(undefined)
  316. setPdfUrl(undefined)
  317. })
  318. .finally(() => {
  319. setClearingCache(false)
  320. })
  321. }, [compiler, setPdfDownloadUrl, setPdfUrl])
  322. // clear the cache then run a compile, triggered by a menu item
  323. const recompileFromScratch = useCallback(() => {
  324. clearCache().then(() => {
  325. compiler.compile()
  326. })
  327. }, [clearCache, compiler])
  328. const value = useMemo(
  329. () => ({
  330. autoCompile,
  331. clearCache,
  332. clearingCache,
  333. clsiServerId,
  334. codeCheckFailed,
  335. compiling,
  336. draft,
  337. error,
  338. fileList,
  339. hasChanges,
  340. highlights,
  341. logEntryAnnotations,
  342. logEntries,
  343. pdfDownloadUrl,
  344. pdfUrl,
  345. pdfViewer,
  346. position,
  347. rawLog,
  348. recompileFromScratch,
  349. setAutoCompile,
  350. setCompiling,
  351. setDraft,
  352. setError,
  353. setHasLintingError, // only for stories
  354. setHighlights,
  355. setPosition,
  356. setShowLogs,
  357. setStopOnValidationError,
  358. showLogs,
  359. startCompile,
  360. stopCompile,
  361. stopOnValidationError,
  362. uncompiled,
  363. validationIssues,
  364. firstRenderDone,
  365. setChangedAt,
  366. cleanupCompileResult,
  367. }),
  368. [
  369. autoCompile,
  370. clearCache,
  371. clearingCache,
  372. clsiServerId,
  373. codeCheckFailed,
  374. compiling,
  375. draft,
  376. error,
  377. fileList,
  378. hasChanges,
  379. highlights,
  380. logEntries,
  381. logEntryAnnotations,
  382. position,
  383. pdfDownloadUrl,
  384. pdfUrl,
  385. pdfViewer,
  386. rawLog,
  387. recompileFromScratch,
  388. setAutoCompile,
  389. setDraft,
  390. setError,
  391. setHasLintingError, // only for stories
  392. setHighlights,
  393. setPosition,
  394. setStopOnValidationError,
  395. showLogs,
  396. startCompile,
  397. stopCompile,
  398. stopOnValidationError,
  399. uncompiled,
  400. validationIssues,
  401. firstRenderDone,
  402. setChangedAt,
  403. cleanupCompileResult,
  404. ]
  405. )
  406. return (
  407. <CompileContext.Provider value={value}>{children}</CompileContext.Provider>
  408. )
  409. }
  410. CompileProvider.propTypes = {
  411. children: PropTypes.any,
  412. }
  413. export function useCompileContext(propTypes) {
  414. const data = useContext(CompileContext)
  415. PropTypes.checkPropTypes(propTypes, data, 'data', 'CompileContext.Provider')
  416. return data
  417. }