local-compile-context.js 15 KB

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