local-compile-context.tsx 28 KB

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