compile-context.js 13 KB

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