local-compile-context.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. import {
  2. FC,
  3. createContext,
  4. useCallback,
  5. useContext,
  6. useEffect,
  7. useMemo,
  8. useRef,
  9. useState,
  10. } from 'react'
  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. sendMB,
  19. sendMBOnce,
  20. sendMBSampled,
  21. } from '../../infrastructure/event-tracking'
  22. import {
  23. buildLogEntryAnnotations,
  24. buildRuleCounts,
  25. handleLogFiles,
  26. handleOutputFiles,
  27. } from '../../features/pdf-preview/util/output-files'
  28. import { useIdeContext } from './ide-context'
  29. import { useProjectContext } from './project-context'
  30. import { useEditorContext } from './editor-context'
  31. import { buildFileList } from '../../features/pdf-preview/util/file-list'
  32. import { useLayoutContext } from './layout-context'
  33. import { useUserContext } from './user-context'
  34. import { useFileTreeData } from '@/shared/context/file-tree-data-context'
  35. import { useFileTreePathContext } from '@/features/file-tree/contexts/file-tree-path'
  36. import { useUserSettingsContext } from '@/shared/context/user-settings-context'
  37. import { useFeatureFlag } from '@/shared/context/split-test-context'
  38. type PdfFile = Record<string, any>
  39. export type CompileContext = {
  40. autoCompile: boolean
  41. clearingCache: boolean
  42. clsiServerId?: string
  43. codeCheckFailed: boolean
  44. compiling: boolean
  45. deliveryLatencies: Record<string, any>
  46. draft: boolean
  47. error?: string
  48. fileList?: Record<string, any>
  49. hasChanges: boolean
  50. hasShortCompileTimeout: boolean
  51. highlights?: Record<string, any>[]
  52. isProjectOwner: boolean
  53. logEntries?: Record<string, any>
  54. logEntryAnnotations?: Record<string, any>
  55. pdfDownloadUrl?: string
  56. pdfFile?: PdfFile
  57. pdfUrl?: string
  58. pdfViewer?: string
  59. position?: Record<string, any>
  60. rawLog?: string
  61. setAutoCompile: (value: boolean) => void
  62. setDraft: (value: any) => void
  63. setError: (value: any) => void
  64. setHasLintingError: (value: any) => void // only for storybook
  65. setHighlights: (value: any) => void
  66. setPosition: (value: any) => void
  67. setShowCompileTimeWarning: (value: any) => void
  68. setShowLogs: (value: boolean) => void
  69. toggleLogs: () => void
  70. setStopOnFirstError: (value: boolean) => void
  71. setStopOnValidationError: (value: boolean) => void
  72. showCompileTimeWarning: boolean
  73. showLogs: boolean
  74. stopOnFirstError: boolean
  75. stopOnValidationError: boolean
  76. stoppedOnFirstError: boolean
  77. uncompiled?: boolean
  78. validationIssues?: Record<string, any>
  79. firstRenderDone: () => void
  80. cleanupCompileResult?: () => void
  81. animateCompileDropdownArrow: boolean
  82. editedSinceCompileStarted: boolean
  83. lastCompileOptions: any
  84. setAnimateCompileDropdownArrow: (value: boolean) => void
  85. recompileFromScratch: () => void
  86. setCompiling: (value: boolean) => void
  87. startCompile: (options?: any) => void
  88. stopCompile: () => void
  89. setChangedAt: (value: any) => void
  90. clearCache: () => void
  91. syncToEntry: (value: any) => void
  92. }
  93. export const LocalCompileContext = createContext<CompileContext | undefined>(
  94. undefined
  95. )
  96. export const LocalCompileProvider: FC = ({ children }) => {
  97. const ide = useIdeContext()
  98. const { hasPremiumCompile, isProjectOwner } = useEditorContext()
  99. const { _id: projectId, rootDocId } = useProjectContext()
  100. const { pdfPreviewOpen } = useLayoutContext()
  101. const { features } = useUserContext()
  102. const { fileTreeData } = useFileTreeData()
  103. const { findEntityByPath } = useFileTreePathContext()
  104. // whether a compile is in progress
  105. const [compiling, setCompiling] = useState(false)
  106. // whether to show the compile time warning
  107. const [showCompileTimeWarning, setShowCompileTimeWarning] = useState(false)
  108. const [hasShortCompileTimeout, setHasShortCompileTimeout] = useState(false)
  109. // the log entries parsed from the compile output log
  110. const [logEntries, setLogEntries] = useScopeValueSetterOnly('pdf.logEntries')
  111. // annotations for display in the editor, built from the log entries
  112. const [logEntryAnnotations, setLogEntryAnnotations] = useScopeValue(
  113. 'pdf.logEntryAnnotations'
  114. )
  115. // the PDF viewer and whether syntax validation is enabled globally
  116. const { userSettings } = useUserSettingsContext()
  117. const { pdfViewer, syntaxValidation } = userSettings
  118. // the URL for downloading the PDF
  119. const [, setPdfDownloadUrl] =
  120. useScopeValueSetterOnly<string>('pdf.downloadUrl')
  121. // the URL for loading the PDF in the preview pane
  122. const [, setPdfUrl] = useScopeValueSetterOnly<string>('pdf.url')
  123. // low level details for metrics
  124. const [pdfFile, setPdfFile] = useState<PdfFile | undefined>()
  125. useEffect(() => {
  126. setPdfDownloadUrl(pdfFile?.pdfDownloadUrl)
  127. setPdfUrl(pdfFile?.pdfUrl)
  128. }, [pdfFile, setPdfDownloadUrl, setPdfUrl])
  129. // the project is considered to be "uncompiled" if a doc has changed, or finished saving, since the last compile started.
  130. const [uncompiled, setUncompiled] = useScopeValue('pdf.uncompiled')
  131. // whether a doc has been edited since the last compile started
  132. const [editedSinceCompileStarted, setEditedSinceCompileStarted] =
  133. useState(false)
  134. // the id of the CLSI server which ran the compile
  135. const [clsiServerId, setClsiServerId] = useState()
  136. // data received in response to a compile request
  137. const [data, setData] = useState<Record<string, any>>()
  138. // the rootDocId used in the most recent compile request, which may not be the
  139. // same as the project rootDocId. This is used to calculate correct paths when
  140. // parsing the compile logs
  141. const lastCompileRootDocId = data?.rootDocId
  142. // callback to be invoked for PdfJsMetrics
  143. const [firstRenderDone, setFirstRenderDone] = useState(() => () => {})
  144. // latencies of compile/pdf download/rendering
  145. const [deliveryLatencies, setDeliveryLatencies] = useState({})
  146. // whether the project has been compiled yet
  147. const [compiledOnce, setCompiledOnce] = useState(false)
  148. // whether the cache is being cleared
  149. const [clearingCache, setClearingCache] = useState(false)
  150. // whether the logs should be visible
  151. const [showLogs, setShowLogs] = useState(false)
  152. // whether the compile dropdown arrow should be animated
  153. const [animateCompileDropdownArrow, setAnimateCompileDropdownArrow] =
  154. useState(false)
  155. const toggleLogs = useCallback(() => {
  156. setShowLogs(prev => {
  157. if (!prev) {
  158. sendMBOnce('ide-open-logs-once')
  159. }
  160. return !prev
  161. })
  162. }, [setShowLogs])
  163. // an error that occurred
  164. const [error, setError] = useState<string>()
  165. // the list of files that can be downloaded
  166. const [fileList, setFileList] = useState<Record<string, any[]>>()
  167. // the raw contents of the log file
  168. const [rawLog, setRawLog] = useState<string>()
  169. // validation issues from CLSI
  170. const [validationIssues, setValidationIssues] = useState()
  171. // areas to highlight on the PDF, from synctex
  172. const [highlights, setHighlights] = useState()
  173. // scroll position of the PDF
  174. const [position, setPosition] = usePersistedState(`pdf.position.${projectId}`)
  175. // whether autocompile is switched on
  176. const [autoCompile, setAutoCompile] = usePersistedState(
  177. `autocompile_enabled:${projectId}`,
  178. false,
  179. true
  180. )
  181. // whether the compile should run in draft mode
  182. const [draft, setDraft] = usePersistedState(`draft:${projectId}`, false, true)
  183. // whether compiling should stop on first error
  184. const [stopOnFirstError, setStopOnFirstError] = usePersistedState(
  185. `stop_on_first_error:${projectId}`,
  186. false,
  187. true
  188. )
  189. // whether the last compiles stopped on first error
  190. const [stoppedOnFirstError, setStoppedOnFirstError] = useState(false)
  191. // whether compiling should be prevented if there are linting errors
  192. const [stopOnValidationError, setStopOnValidationError] = usePersistedState(
  193. `stop_on_validation_error:${projectId}`,
  194. true,
  195. true
  196. )
  197. // the Document currently open in the editor
  198. const [currentDoc] = useScopeValue('editor.sharejs_doc')
  199. // whether the editor linter found errors
  200. const [hasLintingError, setHasLintingError] = useScopeValue('hasLintingError')
  201. // the timestamp that a doc was last changed
  202. const [changedAt, setChangedAt] = useState(0)
  203. const { signal } = useAbortController()
  204. const cleanupCompileResult = useCallback(() => {
  205. setPdfFile(undefined)
  206. setLogEntries(null)
  207. setLogEntryAnnotations({})
  208. }, [setPdfFile, setLogEntries, setLogEntryAnnotations])
  209. const compilingRef = useRef(false)
  210. useEffect(() => {
  211. compilingRef.current = compiling
  212. }, [compiling])
  213. const _buildLogEntryAnnotations = useCallback(
  214. entries =>
  215. buildLogEntryAnnotations(entries, fileTreeData, lastCompileRootDocId),
  216. [fileTreeData, lastCompileRootDocId]
  217. )
  218. const buildLogEntryAnnotationsRef = useRef(_buildLogEntryAnnotations)
  219. useEffect(() => {
  220. buildLogEntryAnnotationsRef.current = _buildLogEntryAnnotations
  221. }, [_buildLogEntryAnnotations])
  222. // the document compiler
  223. const [compiler] = useState(() => {
  224. return new DocumentCompiler({
  225. projectId,
  226. setChangedAt,
  227. setCompiling,
  228. setData,
  229. setFirstRenderDone,
  230. setDeliveryLatencies,
  231. setError,
  232. cleanupCompileResult,
  233. compilingRef,
  234. signal,
  235. })
  236. })
  237. // keep currentDoc in sync with the compiler
  238. useEffect(() => {
  239. compiler.currentDoc = currentDoc
  240. }, [compiler, currentDoc])
  241. // keep the project rootDocId in sync with the compiler
  242. useEffect(() => {
  243. compiler.projectRootDocId = rootDocId
  244. }, [compiler, rootDocId])
  245. // keep draft setting in sync with the compiler
  246. useEffect(() => {
  247. compiler.setOption('draft', draft)
  248. }, [compiler, draft])
  249. // keep stop on first error setting in sync with the compiler
  250. useEffect(() => {
  251. compiler.setOption('stopOnFirstError', stopOnFirstError)
  252. }, [compiler, stopOnFirstError])
  253. useEffect(() => {
  254. setUncompiled(changedAt > 0)
  255. }, [setUncompiled, changedAt])
  256. useEffect(() => {
  257. setEditedSinceCompileStarted(changedAt > 0)
  258. }, [setEditedSinceCompileStarted, changedAt])
  259. // always compile the PDF once after opening the project, after the doc has loaded
  260. useEffect(() => {
  261. if (!compiledOnce && currentDoc) {
  262. setCompiledOnce(true)
  263. compiler.compile({ isAutoCompileOnLoad: true })
  264. }
  265. }, [compiledOnce, currentDoc, compiler])
  266. useEffect(() => {
  267. setHasShortCompileTimeout(
  268. features?.compileTimeout !== undefined && features.compileTimeout <= 60
  269. )
  270. }, [features])
  271. useEffect(() => {
  272. if (hasShortCompileTimeout && compiling && isProjectOwner) {
  273. const timeout = window.setTimeout(() => {
  274. setShowCompileTimeWarning(true)
  275. }, 30000)
  276. return () => {
  277. window.clearTimeout(timeout)
  278. }
  279. }
  280. }, [compiling, isProjectOwner, hasShortCompileTimeout])
  281. const hasCompileLogsEvents = useFeatureFlag('compile-log-events')
  282. // handle the data returned from a compile request
  283. // note: this should _only_ run when `data` changes,
  284. // the other dependencies must all be static
  285. useEffect(() => {
  286. const abortController = new AbortController()
  287. if (data) {
  288. if (data.clsiServerId) {
  289. setClsiServerId(data.clsiServerId) // set in scope, for PdfSynctexController
  290. }
  291. if (data.outputFiles) {
  292. const outputFiles = new Map()
  293. for (const outputFile of data.outputFiles) {
  294. outputFiles.set(outputFile.path, outputFile)
  295. }
  296. // set the PDF context
  297. if (data.status === 'success') {
  298. setPdfFile(handleOutputFiles(outputFiles, projectId, data))
  299. }
  300. setFileList(
  301. buildFileList(outputFiles, data.clsiServerId, data.compileGroup)
  302. )
  303. // handle log files
  304. // asynchronous (TODO: cancel on new compile?)
  305. setLogEntryAnnotations(null)
  306. setLogEntries(null)
  307. setRawLog(undefined)
  308. handleLogFiles(outputFiles, data, abortController.signal).then(
  309. (result: Record<string, any>) => {
  310. setRawLog(result.log)
  311. setLogEntries(result.logEntries)
  312. setLogEntryAnnotations(
  313. buildLogEntryAnnotationsRef.current(result.logEntries.all)
  314. )
  315. // sample compile stats for real users
  316. if (!window.user.alphaProgram) {
  317. if (['success', 'stopped-on-first-error'].includes(data.status)) {
  318. sendMBSampled(
  319. 'compile-result',
  320. {
  321. errors: result.logEntries.errors.length,
  322. warnings: result.logEntries.warnings.length,
  323. typesetting: result.logEntries.typesetting.length,
  324. newPdfPreview: true, // TODO: is this useful?
  325. stopOnFirstError: data.options.stopOnFirstError,
  326. },
  327. 0.01
  328. )
  329. }
  330. if (hasCompileLogsEvents) {
  331. sendMB('compile-log-entries', {
  332. status: data.status,
  333. stopOnFirstError: data.options.stopOnFirstError,
  334. isAutoCompileOnLoad: !!data.options.isAutoCompileOnLoad,
  335. isAutoCompileOnChange: !!data.options.isAutoCompileOnChange,
  336. ...buildRuleCounts(result.logEntries.all),
  337. })
  338. }
  339. }
  340. }
  341. )
  342. }
  343. switch (data.status) {
  344. case 'success':
  345. setError(undefined)
  346. setShowLogs(false)
  347. break
  348. case 'stopped-on-first-error':
  349. setError(undefined)
  350. setShowLogs(true)
  351. break
  352. case 'clsi-maintenance':
  353. case 'compile-in-progress':
  354. case 'exited':
  355. case 'failure':
  356. case 'project-too-large':
  357. case 'rate-limited':
  358. case 'terminated':
  359. case 'too-recently-compiled':
  360. setError(data.status)
  361. break
  362. case 'timedout':
  363. setError('timedout')
  364. if (!hasPremiumCompile && isProjectOwner) {
  365. send(
  366. 'subscription-funnel',
  367. 'editor-click-feature',
  368. 'compile-timeout'
  369. )
  370. }
  371. break
  372. case 'autocompile-backoff':
  373. if (!data.options.isAutoCompileOnLoad) {
  374. setError('autocompile-disabled')
  375. setAutoCompile(false)
  376. }
  377. break
  378. case 'unavailable':
  379. setError('clsi-unavailable')
  380. break
  381. case 'validation-problems':
  382. setError('validation-problems')
  383. setValidationIssues(data.validationProblems)
  384. break
  385. default:
  386. setError('error')
  387. break
  388. }
  389. setStoppedOnFirstError(data.status === 'stopped-on-first-error')
  390. }
  391. return () => {
  392. abortController.abort()
  393. }
  394. }, [
  395. data,
  396. ide,
  397. hasCompileLogsEvents,
  398. hasPremiumCompile,
  399. isProjectOwner,
  400. projectId,
  401. setAutoCompile,
  402. setClsiServerId,
  403. setLogEntries,
  404. setLogEntryAnnotations,
  405. setPdfFile,
  406. ])
  407. // switch to logs if there's an error
  408. useEffect(() => {
  409. if (error) {
  410. setShowLogs(true)
  411. }
  412. }, [error])
  413. // whether there has been an autocompile linting error, if syntax validation is switched on
  414. const autoCompileLintingError = Boolean(
  415. autoCompile && syntaxValidation && hasLintingError
  416. )
  417. const codeCheckFailed = stopOnValidationError && autoCompileLintingError
  418. // the project is available for auto-compiling
  419. // (autocompile is enabled, the PDF preview is open, and the code check (if enabled) hasn't failed)
  420. const canAutoCompile = Boolean(
  421. autoCompile && pdfPreviewOpen && !codeCheckFailed
  422. )
  423. // show that the project has pending changes
  424. const hasChanges = Boolean(canAutoCompile && uncompiled && compiledOnce)
  425. // call the debounced autocompile function if the project is available for auto-compiling and it has changed
  426. useEffect(() => {
  427. if (canAutoCompile) {
  428. if (changedAt > 0) {
  429. compiler.debouncedAutoCompile()
  430. }
  431. } else {
  432. compiler.debouncedAutoCompile.cancel()
  433. }
  434. }, [compiler, canAutoCompile, changedAt])
  435. // cancel debounced recompile on unmount
  436. useEffect(() => {
  437. return () => {
  438. compiler.debouncedAutoCompile.cancel()
  439. }
  440. }, [compiler])
  441. // start a compile manually
  442. const startCompile = useCallback(
  443. options => {
  444. compiler.compile(options)
  445. },
  446. [compiler]
  447. )
  448. // stop a compile manually
  449. const stopCompile = useCallback(() => {
  450. compiler.stopCompile()
  451. }, [compiler])
  452. // clear the compile cache
  453. const clearCache = useCallback(() => {
  454. setClearingCache(true)
  455. return compiler
  456. .clearCache()
  457. .then(() => {
  458. setFileList(undefined)
  459. setPdfFile(undefined)
  460. })
  461. .finally(() => {
  462. setClearingCache(false)
  463. })
  464. }, [compiler])
  465. const syncToEntry = useCallback(
  466. entry => {
  467. const result = findEntityByPath(entry.file)
  468. if (result && result.type === 'doc') {
  469. ide.editorManager.openDocId(result.entity._id, {
  470. gotoLine: entry.line ?? undefined,
  471. gotoColumn: entry.column ?? undefined,
  472. })
  473. }
  474. },
  475. [findEntityByPath, ide.editorManager]
  476. )
  477. // clear the cache then run a compile, triggered by a menu item
  478. const recompileFromScratch = useCallback(() => {
  479. clearCache().then(() => {
  480. compiler.compile()
  481. })
  482. }, [clearCache, compiler])
  483. // After a compile, the compiler sets `data.options` to the options that were
  484. // used for that compile.
  485. const lastCompileOptions = useMemo(() => data?.options || {}, [data])
  486. const value = useMemo(
  487. () => ({
  488. animateCompileDropdownArrow,
  489. autoCompile,
  490. clearCache,
  491. clearingCache,
  492. clsiServerId,
  493. codeCheckFailed,
  494. compiling,
  495. deliveryLatencies,
  496. draft,
  497. editedSinceCompileStarted,
  498. error,
  499. fileList,
  500. hasChanges,
  501. hasShortCompileTimeout,
  502. highlights,
  503. isProjectOwner,
  504. lastCompileOptions,
  505. logEntryAnnotations,
  506. logEntries,
  507. pdfDownloadUrl: pdfFile?.pdfDownloadUrl,
  508. pdfFile,
  509. pdfUrl: pdfFile?.pdfUrl,
  510. pdfViewer,
  511. position,
  512. rawLog,
  513. recompileFromScratch,
  514. setAnimateCompileDropdownArrow,
  515. setAutoCompile,
  516. setCompiling,
  517. setDraft,
  518. setError,
  519. setHasLintingError, // only for stories
  520. setHighlights,
  521. setPosition,
  522. showCompileTimeWarning,
  523. setShowCompileTimeWarning,
  524. setShowLogs,
  525. toggleLogs,
  526. setStopOnFirstError,
  527. setStopOnValidationError,
  528. showLogs,
  529. startCompile,
  530. stopCompile,
  531. stopOnFirstError,
  532. stopOnValidationError,
  533. stoppedOnFirstError,
  534. uncompiled,
  535. validationIssues,
  536. firstRenderDone,
  537. setChangedAt,
  538. cleanupCompileResult,
  539. syncToEntry,
  540. }),
  541. [
  542. animateCompileDropdownArrow,
  543. autoCompile,
  544. clearCache,
  545. clearingCache,
  546. clsiServerId,
  547. codeCheckFailed,
  548. compiling,
  549. deliveryLatencies,
  550. draft,
  551. editedSinceCompileStarted,
  552. error,
  553. fileList,
  554. hasChanges,
  555. hasShortCompileTimeout,
  556. highlights,
  557. isProjectOwner,
  558. lastCompileOptions,
  559. logEntries,
  560. logEntryAnnotations,
  561. position,
  562. pdfFile,
  563. pdfViewer,
  564. rawLog,
  565. recompileFromScratch,
  566. setAnimateCompileDropdownArrow,
  567. setAutoCompile,
  568. setDraft,
  569. setError,
  570. setHasLintingError, // only for stories
  571. setHighlights,
  572. setPosition,
  573. setShowCompileTimeWarning,
  574. setStopOnFirstError,
  575. setStopOnValidationError,
  576. showCompileTimeWarning,
  577. showLogs,
  578. startCompile,
  579. stopCompile,
  580. stopOnFirstError,
  581. stopOnValidationError,
  582. stoppedOnFirstError,
  583. uncompiled,
  584. validationIssues,
  585. firstRenderDone,
  586. setChangedAt,
  587. cleanupCompileResult,
  588. setShowLogs,
  589. toggleLogs,
  590. syncToEntry,
  591. ]
  592. )
  593. return (
  594. <LocalCompileContext.Provider value={value}>
  595. {children}
  596. </LocalCompileContext.Provider>
  597. )
  598. }
  599. export function useLocalCompileContext() {
  600. const context = useContext(LocalCompileContext)
  601. if (!context) {
  602. throw new Error(
  603. 'useLocalCompileContext is only available inside LocalCompileProvider'
  604. )
  605. }
  606. return context
  607. }