local-compile-context.js 15 KB

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