local-compile-context.js 14 KB

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