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 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. HighlightData,
  49. LogEntry,
  50. PdfFileDataList,
  51. } from '@/features/pdf-preview/util/types'
  52. import { isSplitTestEnabled } from '@/utils/splitTestUtils'
  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. type PdfFile = Record<string, any>
  58. export type CompileContext = {
  59. autoCompile: boolean
  60. clearingCache: boolean
  61. clsiServerId?: string
  62. codeCheckFailed: boolean
  63. compiling: boolean
  64. deliveryLatencies: Record<string, any>
  65. draft: boolean
  66. error?: string
  67. fileList?: PdfFileDataList
  68. hasChanges: boolean
  69. hasShortCompileTimeout: boolean
  70. highlights?: HighlightData[]
  71. isProjectOwner: boolean
  72. logEntries?: {
  73. all: LogEntry[]
  74. errors: LogEntry[]
  75. warnings: LogEntry[]
  76. typesetting: LogEntry[]
  77. }
  78. logEntryAnnotations?: Record<string, Annotation[]>
  79. outputFilesArchive?: string
  80. pdfDownloadUrl?: string
  81. pdfFile?: PdfFile
  82. pdfUrl?: string
  83. pdfViewer?: string
  84. position?: PdfScrollPosition
  85. rawLog?: string
  86. setAutoCompile: (value: boolean) => void
  87. setDraft: (value: any) => void
  88. setError: (value: any) => void
  89. setHasLintingError: (value: boolean) => void // only for storybook
  90. setHighlights: (value: any) => void
  91. setPosition: Dispatch<SetStateAction<PdfScrollPosition>>
  92. setShowCompileTimeWarning: (value: any) => void
  93. setShowLogs: (value: boolean) => void
  94. toggleLogs: () => void
  95. setStopOnFirstError: (value: boolean) => void
  96. setStopOnValidationError: (value: boolean) => void
  97. showCompileTimeWarning: boolean
  98. showLogs: boolean
  99. stopOnFirstError: boolean
  100. stopOnValidationError: boolean
  101. stoppedOnFirstError: boolean
  102. uncompiled: boolean
  103. validationIssues?: Record<string, any>
  104. firstRenderDone: (metrics: {
  105. latencyFetch: number
  106. latencyRender: number | undefined
  107. pdfCachingMetrics: { viewerId: string }
  108. }) => void
  109. cleanupCompileResult?: () => void
  110. animateCompileDropdownArrow: boolean
  111. editedSinceCompileStarted: boolean
  112. lastCompileOptions: any
  113. setAnimateCompileDropdownArrow: (value: boolean) => void
  114. recompileFromScratch: () => void
  115. setCompiling: (value: boolean) => void
  116. startCompile: (options?: any) => void
  117. stopCompile: () => void
  118. setChangedAt: (value: any) => void
  119. clearCache: () => void
  120. syncToEntry: (value: any, keepCurrentView?: boolean) => void
  121. recordAction: (action: string) => void
  122. }
  123. export const LocalCompileContext = createContext<CompileContext | undefined>(
  124. undefined
  125. )
  126. export const LocalCompileProvider: FC<React.PropsWithChildren> = ({
  127. children,
  128. }) => {
  129. const { hasPremiumCompile, isProjectOwner } = useEditorContext()
  130. const { openDocWithId, openDocs } = useEditorManagerContext()
  131. const { currentDocument } = useEditorOpenDocContext()
  132. const { role } = useDetachContext()
  133. const { projectId, joinedOnce, project } = useProjectContext()
  134. const { rootDocId, imageName, compiler: compilerName } = project || {}
  135. const { pdfPreviewOpen } = useLayoutContext()
  136. const { features, alphaProgram, labsProgram } = useUserContext()
  137. const { fileTreeData } = useFileTreeData()
  138. const { findEntityByPath } = useFileTreePathContext()
  139. // whether a compile is in progress
  140. const [compiling, setCompiling] = useState(false)
  141. // whether to show the compile time warning
  142. const [showCompileTimeWarning, setShowCompileTimeWarning] = useState(false)
  143. const [hasShortCompileTimeout, setHasShortCompileTimeout] = useState(false)
  144. // the log entries parsed from the compile output log
  145. const [logEntries, setLogEntries] = useState<CompileContext['logEntries']>()
  146. // annotations for display in the editor, built from the log entries
  147. const [logEntryAnnotations, setLogEntryAnnotations] = useState<
  148. undefined | Record<string, Annotation[]>
  149. >()
  150. // the PDF viewer and whether syntax validation is enabled globally
  151. const { userSettings } = useUserSettingsContext()
  152. const { pdfViewer, syntaxValidation } = userSettings
  153. // low level details for metrics
  154. const [pdfFile, setPdfFile] = useState<PdfFile | undefined>()
  155. // the project is considered to be "uncompiled" if a doc has changed, or finished saving, since the last compile started.
  156. const [uncompiled, setUncompiled] = useState(false)
  157. // whether a doc has been edited since the last compile started
  158. const [editedSinceCompileStarted, setEditedSinceCompileStarted] =
  159. useState(false)
  160. // the id of the CLSI server which ran the compile
  161. const [clsiServerId, setClsiServerId] = useState<string>()
  162. // data received in response to a compile request
  163. const [data, setData] = useState<CompileResponseData>()
  164. // the rootDocId used in the most recent compile request, which may not be the
  165. // same as the project rootDocId. This is used to calculate correct paths when
  166. // parsing the compile logs
  167. const lastCompileRootDocId = data ? (data.rootDocId ?? rootDocId) : null
  168. // callback to be invoked for PdfJsMetrics
  169. const [firstRenderDone, setFirstRenderDone] = useState(() => () => {})
  170. // latencies of compile/pdf download/rendering
  171. const [deliveryLatencies, setDeliveryLatencies] = useState({})
  172. // whether the project has been compiled yet
  173. const [compiledOnce, setCompiledOnce] = useState(false)
  174. // fetch initial compile response from cache
  175. const [initialCompileFromCache, setInitialCompileFromCache] = useState(
  176. getMeta('ol-projectOwnerHasPremiumOnPageLoad') &&
  177. isSplitTestEnabled('populate-clsi-cache') &&
  178. // Avoid fetching the initial compile from cache in PDF detach tab
  179. role !== 'detached'
  180. )
  181. // fetch of initial compile from cache is pending
  182. const [pendingInitialCompileFromCache, setPendingInitialCompileFromCache] =
  183. useState(false)
  184. // Raw data from clsi-cache, will need post-processing and check settings
  185. const [dataFromCache, setDataFromCache] = useState<CompileResponseData>()
  186. // whether the cache is being cleared
  187. const [clearingCache, setClearingCache] = useState(false)
  188. // whether the logs should be visible
  189. const [showLogs, setShowLogs] = useState(false)
  190. // whether the compile dropdown arrow should be animated
  191. const [animateCompileDropdownArrow, setAnimateCompileDropdownArrow] =
  192. useState(false)
  193. const toggleLogs = useCallback(() => {
  194. setShowLogs(prev => {
  195. if (!prev) {
  196. sendMBOnce('ide-open-logs-once')
  197. }
  198. return !prev
  199. })
  200. }, [setShowLogs])
  201. // an error that occurred
  202. const [error, setError] = useState<string>()
  203. // the list of files that can be downloaded
  204. const [fileList, setFileList] = useState<PdfFileDataList>()
  205. // the raw contents of the log file
  206. const [rawLog, setRawLog] = useState<string>()
  207. // validation issues from CLSI
  208. const [validationIssues, setValidationIssues] = useState()
  209. // areas to highlight on the PDF, from synctex
  210. const [highlights, setHighlights] = useState()
  211. const [position, setPosition] = usePdfScrollPosition(lastCompileRootDocId)
  212. // whether autocompile is switched on
  213. const [autoCompile, setAutoCompile] = usePersistedState(
  214. `autocompile_enabled:${projectId}`,
  215. false,
  216. { listen: true }
  217. )
  218. // whether the compile should run in draft mode
  219. const [draft, setDraft] = usePersistedState(`draft:${projectId}`, false, {
  220. listen: true,
  221. })
  222. // whether compiling should stop on first error
  223. const [stopOnFirstError, setStopOnFirstError] = usePersistedState(
  224. `stop_on_first_error:${projectId}`,
  225. false,
  226. { listen: 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. { listen: true }
  235. )
  236. // whether the editor linter found errors
  237. const [hasLintingError, setHasLintingError] = useState(false)
  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. }