local-compile-context.tsx 26 KB

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