local-compile-context.tsx 26 KB

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