local-compile-context.tsx 26 KB

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