compile-context.js 14 KB

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