compile-context.js 14 KB

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