compile-context.js 13 KB

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