compile-context.js 13 KB

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