compile-context.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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. setUncompiled(changedAt > 0)
  142. }, [setUncompiled, changedAt])
  143. // record changes to the autocompile setting
  144. const setAutoCompile = useCallback(
  145. value => {
  146. _setAutoCompile(value)
  147. sendMB('autocompile-setting-changed', { value })
  148. },
  149. [_setAutoCompile]
  150. )
  151. // always compile the PDF once after opening the project, after the doc has loaded
  152. useEffect(() => {
  153. if (!compiledOnce && currentDoc) {
  154. setCompiledOnce(true)
  155. compiler.compile({ isAutoCompileOnLoad: true })
  156. }
  157. }, [compiledOnce, currentDoc, compiler])
  158. // handle the data returned from a compile request
  159. // note: this should _only_ run when `data` changes,
  160. // the other dependencies must all be static
  161. useEffect(() => {
  162. if (data) {
  163. if (data.clsiServerId) {
  164. setClsiServerId(data.clsiServerId) // set in scope, for PdfSynctexController
  165. compiler.clsiServerId = data.clsiServerId
  166. }
  167. if (data.compileGroup) {
  168. compiler.compileGroup = data.compileGroup
  169. }
  170. if (data.outputFiles) {
  171. handleOutputFiles(projectId, data).then(result => {
  172. setLogEntryAnnotations(
  173. buildLogEntryAnnotations(result.logEntries.all, ide.fileTreeManager)
  174. )
  175. setLogEntries(result.logEntries)
  176. setFileList(result.fileList)
  177. setPdfDownloadUrl(result.pdfDownloadUrl)
  178. setPdfUrl(result.pdfUrl)
  179. setRawLog(result.log)
  180. // sample compile stats for real users
  181. if (!window.user.alphaProgram && data.status === 'success') {
  182. sendMBSampled(
  183. 'compile-result',
  184. {
  185. errors: result.logEntries.errors.length,
  186. warnings: result.logEntries.warnings.length,
  187. typesetting: result.logEntries.typesetting.length,
  188. newPdfPreview: true, // TODO: is this useful?
  189. },
  190. 0.01
  191. )
  192. }
  193. })
  194. }
  195. switch (data.status) {
  196. case 'success':
  197. setError(undefined)
  198. setShowLogs(false)
  199. break
  200. case 'clsi-maintenance':
  201. case 'compile-in-progress':
  202. case 'exited':
  203. case 'failure':
  204. case 'project-too-large':
  205. case 'rate-limited':
  206. case 'terminated':
  207. case 'too-recently-compiled':
  208. setError(data.status)
  209. break
  210. case 'timedout':
  211. setError('timedout')
  212. if (!hasPremiumCompile && isProjectOwner) {
  213. send(
  214. 'subscription-funnel',
  215. 'editor-click-feature',
  216. 'compile-timeout'
  217. )
  218. sendMB('paywall-prompt', {
  219. 'paywall-type': 'compile-timeout',
  220. })
  221. }
  222. break
  223. case 'autocompile-backoff':
  224. if (!data.options.isAutoCompileOnLoad) {
  225. setError('autocompile-disabled')
  226. setAutoCompile(false)
  227. sendMB('autocompile-rate-limited', { hasPremiumCompile })
  228. }
  229. break
  230. case 'unavailable':
  231. setError('clsi-unavailable')
  232. break
  233. case 'validation-problems':
  234. setError('validation-problems')
  235. setValidationIssues(data.validationProblems)
  236. break
  237. default:
  238. setError('error')
  239. break
  240. }
  241. }
  242. }, [
  243. compiler,
  244. data,
  245. ide,
  246. hasPremiumCompile,
  247. isProjectOwner,
  248. projectId,
  249. setAutoCompile,
  250. setClsiServerId,
  251. setLogEntries,
  252. setLogEntryAnnotations,
  253. setPdfDownloadUrl,
  254. setPdfUrl,
  255. ])
  256. // switch to logs if there's an error
  257. useEffect(() => {
  258. if (error) {
  259. setShowLogs(true)
  260. }
  261. }, [error])
  262. // recompile on key press
  263. useEffect(() => {
  264. const listener = event => {
  265. compiler.compile(event.detail)
  266. }
  267. window.addEventListener('pdf:recompile', listener)
  268. return () => {
  269. window.removeEventListener('pdf:recompile', listener)
  270. }
  271. }, [compiler])
  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. // show that the project has pending changes
  278. const hasChanges = Boolean(
  279. autoCompile && uncompiled && compiledOnce && !codeCheckFailed
  280. )
  281. // the project is available for auto-compiling
  282. const canAutoCompile = Boolean(autoCompile && !compiling && !codeCheckFailed)
  283. // call the debounced autocompile function if the project is available for auto-compiling and it has changed
  284. useEffect(() => {
  285. if (canAutoCompile && changedAt > 0) {
  286. compiler.debouncedAutoCompile()
  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. // record doc changes when notified by the editor
  298. useEffect(() => {
  299. const listener = event => {
  300. setChangedAt(Date.now())
  301. }
  302. window.addEventListener('doc:changed', listener)
  303. window.addEventListener('doc:saved', listener)
  304. return () => {
  305. window.removeEventListener('doc:changed', listener)
  306. window.removeEventListener('doc:saved', listener)
  307. }
  308. }, [])
  309. // start a compile manually
  310. const startCompile = useCallback(() => {
  311. compiler.compile()
  312. }, [compiler])
  313. // stop a compile manually
  314. const stopCompile = useCallback(() => {
  315. compiler.stopCompile()
  316. }, [compiler])
  317. // clear the compile cache
  318. const clearCache = useCallback(() => {
  319. setClearingCache(true)
  320. return compiler.clearCache().finally(() => {
  321. setClearingCache(false)
  322. })
  323. }, [compiler, setClearingCache])
  324. // clear the cache then run a compile, triggered by a menu item
  325. const recompileFromScratch = useCallback(() => {
  326. clearCache().then(() => {
  327. compiler.compile()
  328. })
  329. }, [clearCache, compiler])
  330. const value = useMemo(
  331. () => ({
  332. autoCompile,
  333. clearCache,
  334. clearingCache,
  335. clsiServerId,
  336. codeCheckFailed,
  337. compiling,
  338. draft,
  339. error,
  340. fileList,
  341. hasChanges,
  342. hasLintingError,
  343. logEntries,
  344. logEntryAnnotations,
  345. pdfDownloadUrl,
  346. pdfUrl,
  347. rawLog,
  348. recompileFromScratch,
  349. setAutoCompile,
  350. setClearingCache,
  351. setCompiling,
  352. setDraft,
  353. setError,
  354. setHasLintingError, // only for stories
  355. setShowLogs,
  356. setStopOnValidationError,
  357. showLogs,
  358. startCompile,
  359. stopCompile,
  360. stopOnValidationError,
  361. uncompiled,
  362. validationIssues,
  363. firstRenderDone,
  364. }),
  365. [
  366. autoCompile,
  367. clearCache,
  368. clearingCache,
  369. clsiServerId,
  370. codeCheckFailed,
  371. compiling,
  372. draft,
  373. error,
  374. fileList,
  375. hasChanges,
  376. hasLintingError,
  377. logEntries,
  378. logEntryAnnotations,
  379. pdfDownloadUrl,
  380. pdfUrl,
  381. rawLog,
  382. recompileFromScratch,
  383. setAutoCompile,
  384. setDraft,
  385. setError,
  386. setHasLintingError,
  387. setStopOnValidationError,
  388. showLogs,
  389. startCompile,
  390. stopCompile,
  391. stopOnValidationError,
  392. uncompiled,
  393. validationIssues,
  394. firstRenderDone,
  395. ]
  396. )
  397. return (
  398. <CompileContext.Provider value={value}>{children}</CompileContext.Provider>
  399. )
  400. }
  401. CompileProvider.propTypes = {
  402. children: PropTypes.any,
  403. }
  404. export function useCompileContext(propTypes) {
  405. const data = useContext(CompileContext)
  406. PropTypes.checkPropTypes(propTypes, data, 'data', 'CompileContext.Provider')
  407. return data
  408. }