compile-context.js 14 KB

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