compile-context.js 13 KB

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