compile-context.js 13 KB

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