compile-context.js 14 KB

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