local-compile-context.tsx 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. import {
  2. FC,
  3. createContext,
  4. useCallback,
  5. useContext,
  6. useEffect,
  7. useMemo,
  8. useRef,
  9. useState,
  10. Dispatch,
  11. SetStateAction,
  12. } from 'react'
  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. buildRuleDeltas,
  26. handleLogFiles,
  27. handleOutputFiles,
  28. } from '@/features/pdf-preview/util/output-files'
  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 { useDetachContext } from '@/shared/context/detach-context'
  36. import { useFileTreePathContext } from '@/features/file-tree/contexts/file-tree-path'
  37. import { useUserSettingsContext } from '@/shared/context/user-settings-context'
  38. import { useFeatureFlag } from '@/shared/context/split-test-context'
  39. import { useEditorManagerContext } from '@/features/ide-react/context/editor-manager-context'
  40. import { useEditorOpenDocContext } from '@/features/ide-react/context/editor-open-doc-context'
  41. import { getJSON } from '@/infrastructure/fetch-json'
  42. import { CompileResponseData } from '../../../../types/compile'
  43. import {
  44. PdfScrollPosition,
  45. usePdfScrollPosition,
  46. } from '@/shared/hooks/use-pdf-scroll-position'
  47. import {
  48. DeliveryLatencies,
  49. HighlightData,
  50. LogEntry,
  51. PdfFileDataList,
  52. } from '@/features/pdf-preview/util/types'
  53. import { captureException } from '@/infrastructure/error-reporter'
  54. import OError from '@overleaf/o-error'
  55. import getMeta from '@/utils/meta'
  56. import type { Annotation } from '../../../../types/annotation'
  57. import { useProjectSettingsContext } from '@/features/editor-left-menu/context/project-settings-context'
  58. import {
  59. ActiveOverallTheme,
  60. useActiveOverallTheme,
  61. } from '../hooks/use-active-overall-theme'
  62. type PdfFile = Record<string, any>
  63. export type CompileContext = {
  64. autoCompile: boolean
  65. clearingCache: boolean
  66. clsiServerId?: string
  67. codeCheckFailed: boolean
  68. compiling: boolean
  69. deliveryLatencies: Record<string, any>
  70. draft: boolean
  71. error?: string
  72. fileList?: PdfFileDataList
  73. hasChanges: boolean
  74. hasShortCompileTimeout: boolean
  75. highlights?: HighlightData[]
  76. isProjectOwner: boolean
  77. logEntries?: {
  78. all: LogEntry[]
  79. errors: LogEntry[]
  80. warnings: LogEntry[]
  81. typesetting: LogEntry[]
  82. }
  83. logEntryAnnotations?: Record<string, Annotation[]>
  84. outputFilesArchive?: string
  85. pdfDownloadUrl?: string
  86. pdfFile?: PdfFile | null
  87. pdfUrl?: string
  88. pdfViewer?: string
  89. position?: PdfScrollPosition
  90. rawLog?: string
  91. setAutoCompile: (value: boolean) => void
  92. setDraft: (value: any) => void
  93. setError: (value: any) => void
  94. setHasLintingError: (value: boolean) => void // only for storybook
  95. setHighlights: (value: any) => void
  96. setPosition: Dispatch<SetStateAction<PdfScrollPosition>>
  97. setShowCompileTimeWarning: (value: any) => void
  98. setShowLogs: (value: boolean) => void
  99. toggleLogs: () => void
  100. setStopOnFirstError: (value: boolean) => void
  101. setStopOnValidationError: (value: boolean) => void
  102. showCompileTimeWarning: boolean
  103. showLogs: boolean
  104. stopOnFirstError: boolean
  105. stopOnValidationError: boolean
  106. stoppedOnFirstError: boolean
  107. uncompiled: boolean
  108. validationIssues?: Record<string, any>
  109. firstRenderDone: (metrics: {
  110. latencyFetch: number
  111. latencyRender: number | undefined
  112. pdfCachingMetrics: { viewerId: string }
  113. }) => void
  114. cleanupCompileResult?: () => void
  115. animateCompileDropdownArrow: boolean
  116. editedSinceCompileStarted: boolean
  117. lastCompileOptions: any
  118. setAnimateCompileDropdownArrow: (value: boolean) => void
  119. recompileFromScratch: () => void
  120. setCompiling: (value: boolean) => void
  121. startCompile: (options?: any) => Promise<void>
  122. stopCompile: () => void
  123. setChangedAt: (value: any) => void
  124. clearCache: () => void
  125. syncToEntry: (value: any, keepCurrentView?: boolean) => void
  126. recordAction: (action: string) => void
  127. darkModePdf: boolean | undefined
  128. setDarkModePdf: (value: boolean) => void
  129. activeOverallTheme: ActiveOverallTheme
  130. }
  131. export const LocalCompileContext = createContext<CompileContext | undefined>(
  132. undefined
  133. )
  134. export const LocalCompileProvider: FC<React.PropsWithChildren> = ({
  135. children,
  136. }) => {
  137. const { hasPremiumCompile, isProjectOwner } = useEditorContext()
  138. const { openDocWithId, openDocs } = useEditorManagerContext()
  139. const { currentDocument } = useEditorOpenDocContext()
  140. const { role } = useDetachContext()
  141. const { projectId, joinedOnce, project } = useProjectContext()
  142. const { rootDocId, imageName, compiler: compilerName } = project || {}
  143. const { pdfPreviewOpen } = useLayoutContext()
  144. const { features, alphaProgram } = useUserContext()
  145. const { fileTreeData } = useFileTreeData()
  146. const { findEntityByPath } = useFileTreePathContext()
  147. // whether a compile is in progress
  148. const [compiling, setCompiling] = useState(false)
  149. // whether to show the compile time warning
  150. const [showCompileTimeWarning, setShowCompileTimeWarning] = useState(false)
  151. const [hasShortCompileTimeout, setHasShortCompileTimeout] = useState(false)
  152. // the log entries parsed from the compile output log
  153. const [logEntries, setLogEntries] = useState<CompileContext['logEntries']>()
  154. // annotations for display in the editor, built from the log entries
  155. const [logEntryAnnotations, setLogEntryAnnotations] = useState<
  156. undefined | Record<string, Annotation[]>
  157. >()
  158. // the PDF viewer and whether syntax validation is enabled globally
  159. const { userSettings } = useUserSettingsContext()
  160. const { pdfViewer, syntaxValidation } = userSettings
  161. // The active setting for dark mode PDF
  162. const { darkModePdf, setDarkModePdf } = useProjectSettingsContext()
  163. const activeOverallTheme = useActiveOverallTheme()
  164. // low level details for metrics
  165. const [pdfFile, setPdfFile] = useState<PdfFile | null | undefined>()
  166. // the project is considered to be "uncompiled" if a doc has changed, or finished saving, since the last compile started.
  167. const [uncompiled, setUncompiled] = useState(false)
  168. // whether a doc has been edited since the last compile started
  169. const [editedSinceCompileStarted, setEditedSinceCompileStarted] =
  170. useState(false)
  171. // the id of the CLSI server which ran the compile
  172. const [clsiServerId, setClsiServerId] = useState<string>()
  173. // data received in response to a compile request
  174. const [data, setData] = useState<CompileResponseData>()
  175. // the rootDocId used in the most recent compile request, which may not be the
  176. // same as the project rootDocId. This is used to calculate correct paths when
  177. // parsing the compile logs
  178. const lastCompileRootDocId = data ? (data.rootDocId ?? rootDocId) : null
  179. // callback to be invoked for PdfJsMetrics
  180. const [firstRenderDone, setFirstRenderDone] = useState(() => () => {})
  181. // latencies of compile/pdf download/rendering
  182. const [deliveryLatencies, setDeliveryLatencies] = useState<DeliveryLatencies>(
  183. {}
  184. )
  185. // whether the project has been compiled yet
  186. const [compiledOnce, setCompiledOnce] = useState(false)
  187. // fetch initial compile response from cache
  188. const [initialCompileFromCache, setInitialCompileFromCache] = useState(
  189. getMeta('ol-canUseClsiCache') &&
  190. // Avoid fetching the initial compile from cache in PDF detach tab
  191. role !== 'detached'
  192. )
  193. // fetch of initial compile from cache is pending
  194. const [pendingInitialCompileFromCache, setPendingInitialCompileFromCache] =
  195. useState(false)
  196. // Raw data from clsi-cache, will need post-processing and check settings
  197. const [dataFromCache, setDataFromCache] = useState<CompileResponseData>()
  198. // whether the cache is being cleared
  199. const [clearingCache, setClearingCache] = useState(false)
  200. // whether the logs should be visible
  201. const [showLogs, setShowLogs] = useState(false)
  202. // whether the compile dropdown arrow should be animated
  203. const [animateCompileDropdownArrow, setAnimateCompileDropdownArrow] =
  204. useState(false)
  205. const toggleLogs = useCallback(() => {
  206. setShowLogs(prev => {
  207. if (!prev) {
  208. sendMBOnce('ide-open-logs-once')
  209. }
  210. return !prev
  211. })
  212. }, [setShowLogs])
  213. // an error that occurred
  214. const [error, setError] = useState<string>()
  215. // the list of files that can be downloaded
  216. const [fileList, setFileList] = useState<PdfFileDataList>()
  217. // the raw contents of the log file
  218. const [rawLog, setRawLog] = useState<string>()
  219. // validation issues from CLSI
  220. const [validationIssues, setValidationIssues] = useState()
  221. // areas to highlight on the PDF, from synctex
  222. const [highlights, setHighlights] = useState()
  223. const [position, setPosition] = usePdfScrollPosition(lastCompileRootDocId)
  224. // whether autocompile is switched on
  225. const [autoCompile, setAutoCompile] = usePersistedState(
  226. `autocompile_enabled:${projectId}`,
  227. false,
  228. { listen: true }
  229. )
  230. // whether the compile should run in draft mode
  231. const [draft, setDraft] = usePersistedState(`draft:${projectId}`, false, {
  232. listen: true,
  233. })
  234. // whether compiling should stop on first error
  235. const [stopOnFirstError, setStopOnFirstError] = usePersistedState(
  236. `stop_on_first_error:${projectId}`,
  237. false,
  238. { listen: true }
  239. )
  240. // whether the last compiles stopped on first error
  241. const [stoppedOnFirstError, setStoppedOnFirstError] = useState(false)
  242. // whether compiling should be prevented if there are linting errors
  243. const [stopOnValidationError, setStopOnValidationError] = usePersistedState(
  244. `stop_on_validation_error:${projectId}`,
  245. true,
  246. { listen: true }
  247. )
  248. // whether the editor linter found errors
  249. const [hasLintingError, setHasLintingError] = useState(false)
  250. // the timestamp that a doc was last changed
  251. const [changedAt, setChangedAt] = useState(0)
  252. const { signal } = useAbortController()
  253. const cleanupCompileResult = useCallback(() => {
  254. setPdfFile(undefined)
  255. setLogEntries(undefined)
  256. setLogEntryAnnotations({})
  257. }, [setPdfFile, setLogEntries, setLogEntryAnnotations])
  258. const compilingRef = useRef(false)
  259. useEffect(() => {
  260. compilingRef.current = compiling
  261. }, [compiling])
  262. const _buildLogEntryAnnotations = useCallback(
  263. (entries: LogEntry[]) =>
  264. buildLogEntryAnnotations(entries, fileTreeData, lastCompileRootDocId),
  265. [fileTreeData, lastCompileRootDocId]
  266. )
  267. const buildLogEntryAnnotationsRef = useRef(_buildLogEntryAnnotations)
  268. useEffect(() => {
  269. buildLogEntryAnnotationsRef.current = _buildLogEntryAnnotations
  270. }, [_buildLogEntryAnnotations])
  271. // the document compiler
  272. const [compiler] = useState(() => {
  273. return new DocumentCompiler({
  274. projectId,
  275. setChangedAt,
  276. setCompiling,
  277. setData,
  278. setFirstRenderDone,
  279. setDeliveryLatencies,
  280. setError,
  281. cleanupCompileResult,
  282. compilingRef,
  283. signal,
  284. openDocs,
  285. })
  286. })
  287. // keep currentDoc in sync with the compiler
  288. useEffect(() => {
  289. compiler.currentDoc = currentDocument
  290. }, [compiler, currentDocument])
  291. // keep the project rootDocId in sync with the compiler
  292. useEffect(() => {
  293. compiler.projectRootDocId = rootDocId
  294. }, [compiler, rootDocId])
  295. // keep draft setting in sync with the compiler
  296. useEffect(() => {
  297. compiler.setOption('draft', draft)
  298. }, [compiler, draft])
  299. // keep stop on first error setting in sync with the compiler
  300. useEffect(() => {
  301. compiler.setOption('stopOnFirstError', stopOnFirstError)
  302. }, [compiler, stopOnFirstError])
  303. useEffect(() => {
  304. setUncompiled(changedAt > 0)
  305. }, [setUncompiled, changedAt])
  306. useEffect(() => {
  307. setEditedSinceCompileStarted(changedAt > 0)
  308. }, [setEditedSinceCompileStarted, changedAt])
  309. // try to fetch the last compile result after opening the project, potentially before joining the project.
  310. useEffect(() => {
  311. if (initialCompileFromCache && !pendingInitialCompileFromCache) {
  312. setPendingInitialCompileFromCache(true)
  313. getJSON(`/project/${projectId}/output/cached/output.overleaf.json`, {
  314. signal: AbortSignal.timeout(5_000),
  315. })
  316. .then((data: any) => {
  317. // Hand data over to next effect, it will wait for project/doc loading.
  318. setDataFromCache(data)
  319. })
  320. .catch(() => {
  321. // Let the isAutoCompileOnLoad effect take over
  322. setInitialCompileFromCache(false)
  323. setPendingInitialCompileFromCache(false)
  324. })
  325. }
  326. }, [projectId, initialCompileFromCache, pendingInitialCompileFromCache])
  327. // Maybe adopt the compile from cache
  328. useEffect(() => {
  329. if (!dataFromCache) return // no compile from cache available
  330. if (!joinedOnce) return // wait for joinProject, it populates the file-tree.
  331. if (!currentDocument) return // wait for current doc to load, it affects the rootDoc override
  332. if (compiledOnce) return // regular compile triggered
  333. // Gracefully access file-tree and getRootDocOverride
  334. let settingsUpToDate = false
  335. try {
  336. dataFromCache.rootDocId = findEntityByPath(
  337. dataFromCache.options?.rootResourcePath || ''
  338. )?.entity?._id
  339. const rootDocOverride = compiler.getRootDocOverrideId() || rootDocId
  340. settingsUpToDate =
  341. rootDocOverride === dataFromCache.rootDocId &&
  342. dataFromCache.options.draft === draft &&
  343. // Allow stopOnFirstError to be enabled in the compile from cache and disabled locally.
  344. // Compiles that passed with stopOnFirstError=true will also pass with stopOnFirstError=false. The inverse does not hold, and we need to recompile.
  345. !!dataFromCache.options.stopOnFirstError >= stopOnFirstError
  346. } catch (err) {
  347. captureException(
  348. OError.tag(err as unknown as Error, 'validate compile options', {
  349. options: dataFromCache.options,
  350. })
  351. )
  352. }
  353. if (settingsUpToDate) {
  354. sendMB('compile-from-cache', { projectId })
  355. setData(dataFromCache)
  356. setCompiledOnce(true)
  357. }
  358. setDataFromCache(undefined)
  359. setInitialCompileFromCache(false)
  360. setPendingInitialCompileFromCache(false)
  361. }, [
  362. projectId,
  363. dataFromCache,
  364. joinedOnce,
  365. currentDocument,
  366. compiledOnce,
  367. rootDocId,
  368. findEntityByPath,
  369. compiler,
  370. compilerName,
  371. imageName,
  372. stopOnFirstError,
  373. draft,
  374. ])
  375. // always compile the PDF once after opening the project, after the doc has loaded
  376. useEffect(() => {
  377. if (
  378. !compiledOnce &&
  379. currentDocument &&
  380. !initialCompileFromCache &&
  381. !pendingInitialCompileFromCache
  382. ) {
  383. setCompiledOnce(true)
  384. compiler.compile({ isAutoCompileOnLoad: true })
  385. }
  386. }, [
  387. compiledOnce,
  388. currentDocument,
  389. initialCompileFromCache,
  390. pendingInitialCompileFromCache,
  391. compiler,
  392. ])
  393. useEffect(() => {
  394. setHasShortCompileTimeout(
  395. features?.compileTimeout !== undefined && features.compileTimeout <= 60
  396. )
  397. }, [features])
  398. useEffect(() => {
  399. if (hasShortCompileTimeout && compiling && isProjectOwner) {
  400. const timeout = window.setTimeout(() => {
  401. setShowCompileTimeWarning(true)
  402. }, 30000)
  403. return () => {
  404. window.clearTimeout(timeout)
  405. }
  406. }
  407. }, [compiling, isProjectOwner, hasShortCompileTimeout])
  408. const hasCompileLogsEvents = useFeatureFlag('compile-log-events')
  409. // compare log entry counts with the previous compile, and record actions between compiles
  410. // these are refs rather than state so they don't trigger the effect to run
  411. const previousRuleCountsRef = useRef<{
  412. ruleCounts: Record<string, number>
  413. rootDocId: string | null | undefined
  414. } | null>(null)
  415. const recordedActionsRef = useRef<Record<string, boolean>>({})
  416. const recordAction = useCallback((action: string) => {
  417. recordedActionsRef.current[action] = true
  418. }, [])
  419. // handle the data returned from a compile request
  420. // note: this should _only_ run when `data` changes,
  421. // the other dependencies must all be static
  422. useEffect(() => {
  423. if (!joinedOnce) return // wait for joinProject, it populates the premium flags.
  424. const abortController = new AbortController()
  425. const recordedActions = recordedActionsRef.current
  426. recordedActionsRef.current = {}
  427. if (data) {
  428. if (data.clsiServerId) {
  429. setClsiServerId(data.clsiServerId) // set in scope, for PdfSynctexController
  430. }
  431. if (data.outputFiles) {
  432. const outputFiles = new Map()
  433. for (const outputFile of data.outputFiles) {
  434. // Use a shadow-copy, we will update it in place and append to .url.
  435. outputFiles.set(outputFile.path, { ...outputFile })
  436. }
  437. // set the PDF context
  438. if (data.status === 'success') {
  439. setPdfFile(handleOutputFiles(outputFiles, projectId, data))
  440. }
  441. setFileList(buildFileList(outputFiles, data))
  442. // handle log files
  443. // asynchronous (TODO: cancel on new compile?)
  444. setLogEntryAnnotations(undefined)
  445. setLogEntries(undefined)
  446. setRawLog(undefined)
  447. handleLogFiles(outputFiles, data, abortController.signal).then(
  448. (result: Record<string, any>) => {
  449. setRawLog(result.log)
  450. setLogEntries(result.logEntries)
  451. setLogEntryAnnotations(
  452. buildLogEntryAnnotationsRef.current(result.logEntries.all)
  453. )
  454. // sample compile stats for real users
  455. if (!alphaProgram) {
  456. if (['success', 'stopped-on-first-error'].includes(data.status)) {
  457. sendMBSampled(
  458. 'compile-result',
  459. {
  460. errors: result.logEntries.errors.length,
  461. warnings: result.logEntries.warnings.length,
  462. typesetting: result.logEntries.typesetting.length,
  463. newPdfPreview: true, // TODO: is this useful?
  464. stopOnFirstError: data.options.stopOnFirstError,
  465. },
  466. 0.01
  467. )
  468. }
  469. if (hasCompileLogsEvents) {
  470. const ruleCounts = buildRuleCounts(
  471. result.logEntries.all
  472. ) as Record<string, number>
  473. const rootDocId = data.rootDocId || compiler.projectRootDocId
  474. const previousRuleCounts = previousRuleCountsRef.current
  475. previousRuleCountsRef.current = { ruleCounts, rootDocId }
  476. const ruleDeltas =
  477. previousRuleCounts &&
  478. previousRuleCounts.rootDocId === rootDocId
  479. ? buildRuleDeltas(ruleCounts, previousRuleCounts.ruleCounts)
  480. : {}
  481. sendMB('compile-log-entries', {
  482. status: data.status,
  483. stopOnFirstError: data.options.stopOnFirstError,
  484. isAutoCompileOnLoad: !!data.options.isAutoCompileOnLoad,
  485. isAutoCompileOnChange: !!data.options.isAutoCompileOnChange,
  486. rootDocId,
  487. ...recordedActions,
  488. ...ruleCounts,
  489. ...ruleDeltas,
  490. })
  491. }
  492. }
  493. }
  494. )
  495. }
  496. switch (data.status) {
  497. case 'success':
  498. setError(undefined)
  499. setShowLogs(false)
  500. break
  501. case 'stopped-on-first-error':
  502. setError(undefined)
  503. setShowLogs(true)
  504. break
  505. case 'clsi-maintenance':
  506. case 'compile-in-progress':
  507. case 'exited':
  508. case 'failure':
  509. case 'project-too-large':
  510. case 'rate-limited':
  511. case 'terminated':
  512. case 'too-recently-compiled':
  513. setError(data.status)
  514. break
  515. case 'timedout':
  516. setError('timedout')
  517. if (!hasPremiumCompile && isProjectOwner) {
  518. send(
  519. 'subscription-funnel',
  520. 'editor-click-feature',
  521. 'compile-timeout'
  522. )
  523. }
  524. break
  525. case 'autocompile-backoff':
  526. if (!data.options.isAutoCompileOnLoad) {
  527. setError('autocompile-disabled')
  528. setAutoCompile(false)
  529. }
  530. break
  531. case 'unavailable':
  532. setError('clsi-unavailable')
  533. break
  534. case 'validation-problems':
  535. setError('validation-problems')
  536. setValidationIssues(data.validationProblems)
  537. break
  538. default:
  539. setError('error')
  540. break
  541. }
  542. setStoppedOnFirstError(data.status === 'stopped-on-first-error')
  543. }
  544. return () => {
  545. abortController.abort()
  546. }
  547. }, [
  548. joinedOnce,
  549. data,
  550. alphaProgram,
  551. features,
  552. hasCompileLogsEvents,
  553. hasPremiumCompile,
  554. isProjectOwner,
  555. projectId,
  556. setAutoCompile,
  557. setClsiServerId,
  558. setLogEntries,
  559. setLogEntryAnnotations,
  560. setPdfFile,
  561. compiler,
  562. ])
  563. // switch to logs if there's an error
  564. useEffect(() => {
  565. if (error) {
  566. setShowLogs(true)
  567. }
  568. }, [error])
  569. // whether there has been an autocompile linting error, if syntax validation is switched on
  570. const autoCompileLintingError = Boolean(
  571. autoCompile && syntaxValidation && hasLintingError
  572. )
  573. const codeCheckFailed = stopOnValidationError && autoCompileLintingError
  574. // the project is available for auto-compiling
  575. // (autocompile is enabled, the PDF preview is open, and the code check (if enabled) hasn't failed)
  576. const canAutoCompile = Boolean(
  577. autoCompile && pdfPreviewOpen && !codeCheckFailed
  578. )
  579. // show that the project has pending changes
  580. const hasChanges = Boolean(canAutoCompile && uncompiled && compiledOnce)
  581. // call the debounced autocompile function if the project is available for auto-compiling and it has changed
  582. useEffect(() => {
  583. if (canAutoCompile) {
  584. if (changedAt > 0) {
  585. compiler.debouncedAutoCompile()
  586. }
  587. } else {
  588. compiler.debouncedAutoCompile.cancel()
  589. }
  590. }, [compiler, canAutoCompile, changedAt])
  591. // cancel debounced recompile on unmount
  592. useEffect(() => {
  593. return () => {
  594. compiler.debouncedAutoCompile.cancel()
  595. }
  596. }, [compiler])
  597. // start a compile manually
  598. const startCompile = useCallback(
  599. (options: any) => {
  600. setCompiledOnce(true)
  601. return compiler.compile(options)
  602. },
  603. [compiler, setCompiledOnce]
  604. )
  605. // stop a compile manually
  606. const stopCompile = useCallback(() => {
  607. return compiler.stopCompile()
  608. }, [compiler])
  609. // clear the compile cache
  610. const clearCache = useCallback(() => {
  611. setClearingCache(true)
  612. return compiler
  613. .clearCache()
  614. .then(() => {
  615. setFileList(undefined)
  616. setPdfFile(undefined)
  617. })
  618. .finally(() => {
  619. setClearingCache(false)
  620. })
  621. }, [compiler])
  622. const syncToEntry = useCallback(
  623. (entry: any, keepCurrentView = false) => {
  624. const result = findEntityByPath(entry.file)
  625. if (result && result.type === 'doc') {
  626. openDocWithId(result.entity._id, {
  627. gotoLine: entry.line ?? undefined,
  628. gotoColumn: entry.column ?? undefined,
  629. keepCurrentView,
  630. })
  631. }
  632. },
  633. [findEntityByPath, openDocWithId]
  634. )
  635. // clear the cache then run a compile, triggered by a menu item
  636. const recompileFromScratch = useCallback(() => {
  637. clearCache().then(() => {
  638. compiler.compile()
  639. })
  640. }, [clearCache, compiler])
  641. // After a compile, the compiler sets `data.options` to the options that were
  642. // used for that compile.
  643. const lastCompileOptions = useMemo(() => data?.options || {}, [data])
  644. const value = useMemo(
  645. () => ({
  646. animateCompileDropdownArrow,
  647. autoCompile,
  648. clearCache,
  649. clearingCache,
  650. clsiServerId,
  651. codeCheckFailed,
  652. compiling,
  653. deliveryLatencies,
  654. draft,
  655. editedSinceCompileStarted,
  656. error,
  657. fileList,
  658. hasChanges,
  659. hasShortCompileTimeout,
  660. highlights,
  661. isProjectOwner,
  662. lastCompileOptions,
  663. logEntryAnnotations,
  664. logEntries,
  665. pdfDownloadUrl: pdfFile?.pdfDownloadUrl,
  666. pdfFile,
  667. pdfUrl: pdfFile?.pdfUrl,
  668. pdfViewer,
  669. position,
  670. rawLog,
  671. recompileFromScratch,
  672. setAnimateCompileDropdownArrow,
  673. setAutoCompile,
  674. setCompiling,
  675. setDraft,
  676. setError,
  677. setHasLintingError, // only for stories
  678. setHighlights,
  679. setPosition,
  680. showCompileTimeWarning,
  681. setShowCompileTimeWarning,
  682. setShowLogs,
  683. toggleLogs,
  684. setStopOnFirstError,
  685. setStopOnValidationError,
  686. showLogs,
  687. startCompile,
  688. stopCompile,
  689. stopOnFirstError,
  690. stopOnValidationError,
  691. stoppedOnFirstError,
  692. uncompiled,
  693. validationIssues,
  694. firstRenderDone,
  695. setChangedAt,
  696. cleanupCompileResult,
  697. syncToEntry,
  698. recordAction,
  699. darkModePdf,
  700. setDarkModePdf,
  701. activeOverallTheme,
  702. }),
  703. [
  704. animateCompileDropdownArrow,
  705. autoCompile,
  706. clearCache,
  707. clearingCache,
  708. clsiServerId,
  709. codeCheckFailed,
  710. compiling,
  711. deliveryLatencies,
  712. draft,
  713. editedSinceCompileStarted,
  714. error,
  715. fileList,
  716. hasChanges,
  717. hasShortCompileTimeout,
  718. highlights,
  719. isProjectOwner,
  720. lastCompileOptions,
  721. logEntries,
  722. logEntryAnnotations,
  723. position,
  724. pdfFile,
  725. pdfViewer,
  726. rawLog,
  727. recompileFromScratch,
  728. setAnimateCompileDropdownArrow,
  729. setAutoCompile,
  730. setDraft,
  731. setError,
  732. setHasLintingError, // only for stories
  733. setHighlights,
  734. setPosition,
  735. setShowCompileTimeWarning,
  736. setStopOnFirstError,
  737. setStopOnValidationError,
  738. showCompileTimeWarning,
  739. showLogs,
  740. startCompile,
  741. stopCompile,
  742. stopOnFirstError,
  743. stopOnValidationError,
  744. stoppedOnFirstError,
  745. uncompiled,
  746. validationIssues,
  747. firstRenderDone,
  748. setChangedAt,
  749. cleanupCompileResult,
  750. setShowLogs,
  751. toggleLogs,
  752. syncToEntry,
  753. recordAction,
  754. darkModePdf,
  755. setDarkModePdf,
  756. activeOverallTheme,
  757. ]
  758. )
  759. return (
  760. <LocalCompileContext.Provider value={value}>
  761. {children}
  762. </LocalCompileContext.Provider>
  763. )
  764. }
  765. export function useLocalCompileContext() {
  766. const context = useContext(LocalCompileContext)
  767. if (!context) {
  768. throw new Error(
  769. 'useLocalCompileContext is only available inside LocalCompileProvider'
  770. )
  771. }
  772. return context
  773. }