local-compile-context.tsx 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  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. .then((data: any) => {
  327. // Hand data over to next effect, it will wait for project/doc loading.
  328. setDataFromCache(data)
  329. })
  330. .catch(() => {
  331. // Let the isAutoCompileOnLoad effect take over
  332. setInitialCompileFromCache(false)
  333. setPendingInitialCompileFromCache(false)
  334. })
  335. }
  336. }, [projectId, initialCompileFromCache, pendingInitialCompileFromCache])
  337. // Maybe adopt the compile from cache
  338. useEffect(() => {
  339. if (!dataFromCache) return // no compile from cache available
  340. if (!joinedOnce) return // wait for joinProject, it populates the file-tree.
  341. if (!currentDocument) return // wait for current doc to load, it affects the rootDoc override
  342. if (compiledOnce) return // regular compile triggered
  343. // Gracefully access file-tree and getRootDocOverride
  344. let settingsUpToDate = false
  345. try {
  346. dataFromCache.rootDocId = findEntityByPath(
  347. dataFromCache.options?.rootResourcePath || ''
  348. )?.entity?._id
  349. const rootDocOverride = compiler.getRootDocOverrideId() || rootDocId
  350. settingsUpToDate =
  351. rootDocOverride === dataFromCache.rootDocId &&
  352. dataFromCache.options.imageName === imageName &&
  353. dataFromCache.options.compiler === compilerName &&
  354. dataFromCache.options.draft === draft &&
  355. // Allow stopOnFirstError to be enabled in the compile from cache and disabled locally.
  356. // Compiles that passed with stopOnFirstError=true will also pass with stopOnFirstError=false. The inverse does not hold, and we need to recompile.
  357. !!dataFromCache.options.stopOnFirstError >= stopOnFirstError
  358. } catch (err) {
  359. captureException(
  360. OError.tag(err as unknown as Error, 'validate compile options', {
  361. options: dataFromCache.options,
  362. })
  363. )
  364. }
  365. if (settingsUpToDate) {
  366. sendMB('compile-from-cache', { projectId })
  367. dataFromCache.clsiCachePromptVariant = getSplitTestVariant(
  368. 'clsi-cache-prompt',
  369. 'default'
  370. ) as ClsiCachePromptVariant
  371. if (!dataFromCache.timings) dataFromCache.timings = {}
  372. dataFromCache.timings.compileTimeClientE2E = Math.ceil(
  373. performance.now() - compileFromCacheStartedAt
  374. )
  375. setData(dataFromCache)
  376. setCompiledOnce(true)
  377. }
  378. setDataFromCache(undefined)
  379. setInitialCompileFromCache(false)
  380. setPendingInitialCompileFromCache(false)
  381. }, [
  382. projectId,
  383. compileFromCacheStartedAt,
  384. dataFromCache,
  385. joinedOnce,
  386. currentDocument,
  387. compiledOnce,
  388. rootDocId,
  389. findEntityByPath,
  390. compiler,
  391. compilerName,
  392. imageName,
  393. stopOnFirstError,
  394. draft,
  395. ])
  396. // always compile the PDF once after opening the project, after the doc has loaded
  397. useEffect(() => {
  398. if (
  399. !compiledOnce &&
  400. currentDocument &&
  401. !initialCompileFromCache &&
  402. !pendingInitialCompileFromCache
  403. ) {
  404. setCompiledOnce(true)
  405. compiler.compile({ isAutoCompileOnLoad: true })
  406. }
  407. }, [
  408. compiledOnce,
  409. currentDocument,
  410. initialCompileFromCache,
  411. pendingInitialCompileFromCache,
  412. compiler,
  413. ])
  414. useEffect(() => {
  415. setHasShortCompileTimeout(
  416. features?.compileTimeout !== undefined && features.compileTimeout <= 60
  417. )
  418. }, [features])
  419. useEffect(() => {
  420. if (hasShortCompileTimeout && compiling && isProjectOwner) {
  421. const timeout = window.setTimeout(() => {
  422. setShowCompileTimeWarning(true)
  423. }, 30000)
  424. return () => {
  425. window.clearTimeout(timeout)
  426. }
  427. }
  428. }, [compiling, isProjectOwner, hasShortCompileTimeout])
  429. const hasCompileLogsEvents = useFeatureFlag('compile-log-events')
  430. // compare log entry counts with the previous compile, and record actions between compiles
  431. // these are refs rather than state so they don't trigger the effect to run
  432. const previousRuleCountsRef = useRef<{
  433. ruleCounts: Record<string, number>
  434. rootDocId: string | null | undefined
  435. } | null>(null)
  436. const recordedActionsRef = useRef<Record<string, boolean>>({})
  437. const recordAction = useCallback((action: string) => {
  438. recordedActionsRef.current[action] = true
  439. }, [])
  440. // handle the data returned from a compile request
  441. // note: this should _only_ run when `data` changes,
  442. // the other dependencies must all be static
  443. useEffect(() => {
  444. if (!joinedOnce) return // wait for joinProject, it populates the premium flags.
  445. const abortController = new AbortController()
  446. const recordedActions = recordedActionsRef.current
  447. recordedActionsRef.current = {}
  448. if (data) {
  449. if (data.clsiServerId) {
  450. setClsiServerId(data.clsiServerId) // set in scope, for PdfSynctexController
  451. }
  452. setClsiCachePromptVariant(data.clsiCachePromptVariant ?? 'default')
  453. setClsiCachePromptSegmentation(prev => {
  454. if (
  455. !(
  456. data.status === 'success' &&
  457. (data.fromCache || data.stats?.isInitialCompile === 1)
  458. )
  459. ) {
  460. return { ...prev, compile: null }
  461. }
  462. const pdfSize = (
  463. data.outputFiles.find(f => f.path === 'output.pdf') as PDFFile
  464. )?.size
  465. return {
  466. ...prev,
  467. compile: {
  468. pdfSize,
  469. isCompileFromCache: Boolean(data.fromCache),
  470. isInitialCompile: data.stats?.isInitialCompile === 1,
  471. restoredClsiCache: data.stats?.restoredClsiCache === 1,
  472. compileTimeServerE2E: data.timings?.compileE2E,
  473. compileTimeClientE2E: data.timings?.compileTimeClientE2E,
  474. clsiCacheEnabled: Boolean(data.clsiCacheShard),
  475. },
  476. }
  477. })
  478. if (data.outputFiles) {
  479. const outputFiles = new Map()
  480. for (const outputFile of data.outputFiles) {
  481. // Use a shadow-copy, we will update it in place and append to .url.
  482. outputFiles.set(outputFile.path, { ...outputFile })
  483. }
  484. // set the PDF context
  485. if (data.status === 'success') {
  486. setPdfFile(handleOutputFiles(outputFiles, projectId, data))
  487. }
  488. setFileList(buildFileList(outputFiles, data))
  489. // handle log files
  490. // asynchronous (TODO: cancel on new compile?)
  491. setLogEntryAnnotations(undefined)
  492. setLogEntries(undefined)
  493. setRawLog(undefined)
  494. handleLogFiles(outputFiles, data, abortController.signal).then(
  495. (result: Record<string, any>) => {
  496. setRawLog(result.log)
  497. setLogEntries(result.logEntries)
  498. setLogEntryAnnotations(
  499. buildLogEntryAnnotationsRef.current(result.logEntries.all)
  500. )
  501. // sample compile stats for real users
  502. if (!alphaProgram) {
  503. if (['success', 'stopped-on-first-error'].includes(data.status)) {
  504. sendMBSampled(
  505. 'compile-result',
  506. {
  507. errors: result.logEntries.errors.length,
  508. warnings: result.logEntries.warnings.length,
  509. typesetting: result.logEntries.typesetting.length,
  510. newPdfPreview: true, // TODO: is this useful?
  511. stopOnFirstError: data.options.stopOnFirstError,
  512. },
  513. 0.01
  514. )
  515. }
  516. if (hasCompileLogsEvents) {
  517. const ruleCounts = buildRuleCounts(
  518. result.logEntries.all
  519. ) as Record<string, number>
  520. const rootDocId = data.rootDocId || compiler.projectRootDocId
  521. const previousRuleCounts = previousRuleCountsRef.current
  522. previousRuleCountsRef.current = { ruleCounts, rootDocId }
  523. const ruleDeltas =
  524. previousRuleCounts &&
  525. previousRuleCounts.rootDocId === rootDocId
  526. ? buildRuleDeltas(ruleCounts, previousRuleCounts.ruleCounts)
  527. : {}
  528. sendMB('compile-log-entries', {
  529. status: data.status,
  530. stopOnFirstError: data.options.stopOnFirstError,
  531. isAutoCompileOnLoad: !!data.options.isAutoCompileOnLoad,
  532. isAutoCompileOnChange: !!data.options.isAutoCompileOnChange,
  533. rootDocId,
  534. ...recordedActions,
  535. ...ruleCounts,
  536. ...ruleDeltas,
  537. })
  538. }
  539. }
  540. }
  541. )
  542. }
  543. switch (data.status) {
  544. case 'success':
  545. setError(undefined)
  546. setShowLogs(false)
  547. break
  548. case 'stopped-on-first-error':
  549. setError(undefined)
  550. setShowLogs(true)
  551. break
  552. case 'clsi-maintenance':
  553. case 'compile-in-progress':
  554. case 'exited':
  555. case 'failure':
  556. case 'project-too-large':
  557. case 'rate-limited':
  558. case 'terminated':
  559. case 'too-recently-compiled':
  560. setError(data.status)
  561. break
  562. case 'timedout':
  563. setError('timedout')
  564. if (!hasPremiumCompile && isProjectOwner) {
  565. send(
  566. 'subscription-funnel',
  567. 'editor-click-feature',
  568. 'compile-timeout'
  569. )
  570. }
  571. break
  572. case 'autocompile-backoff':
  573. if (!data.options.isAutoCompileOnLoad) {
  574. setError('autocompile-disabled')
  575. setAutoCompile(false)
  576. }
  577. break
  578. case 'unavailable':
  579. setError('clsi-unavailable')
  580. break
  581. case 'validation-problems':
  582. setError('validation-problems')
  583. setValidationIssues(data.validationProblems)
  584. break
  585. default:
  586. setError('error')
  587. break
  588. }
  589. setStoppedOnFirstError(data.status === 'stopped-on-first-error')
  590. }
  591. return () => {
  592. abortController.abort()
  593. }
  594. }, [
  595. joinedOnce,
  596. data,
  597. alphaProgram,
  598. features,
  599. hasCompileLogsEvents,
  600. hasPremiumCompile,
  601. isProjectOwner,
  602. projectId,
  603. setAutoCompile,
  604. setClsiServerId,
  605. setLogEntries,
  606. setLogEntryAnnotations,
  607. setPdfFile,
  608. compiler,
  609. ])
  610. // switch to logs if there's an error
  611. useEffect(() => {
  612. if (error) {
  613. setShowLogs(true)
  614. }
  615. }, [error])
  616. // whether there has been an autocompile linting error, if syntax validation is switched on
  617. const autoCompileLintingError = Boolean(
  618. autoCompile && syntaxValidation && hasLintingError
  619. )
  620. const codeCheckFailed = stopOnValidationError && autoCompileLintingError
  621. // the project is available for auto-compiling
  622. // (autocompile is enabled, the PDF preview is open, and the code check (if enabled) hasn't failed)
  623. const canAutoCompile = Boolean(
  624. autoCompile && pdfPreviewOpen && !codeCheckFailed
  625. )
  626. // show that the project has pending changes
  627. const hasChanges = Boolean(canAutoCompile && uncompiled && compiledOnce)
  628. // call the debounced autocompile function if the project is available for auto-compiling and it has changed
  629. useEffect(() => {
  630. if (canAutoCompile) {
  631. if (changedAt > 0) {
  632. compiler.debouncedAutoCompile()
  633. }
  634. } else {
  635. compiler.debouncedAutoCompile.cancel()
  636. }
  637. }, [compiler, canAutoCompile, changedAt])
  638. // cancel debounced recompile on unmount
  639. useEffect(() => {
  640. return () => {
  641. compiler.debouncedAutoCompile.cancel()
  642. }
  643. }, [compiler])
  644. // start a compile manually
  645. const startCompile = useCallback(
  646. (options: any) => {
  647. setCompiledOnce(true)
  648. compiler.compile(options)
  649. },
  650. [compiler, setCompiledOnce]
  651. )
  652. // stop a compile manually
  653. const stopCompile = useCallback(() => {
  654. compiler.stopCompile()
  655. }, [compiler])
  656. // clear the compile cache
  657. const clearCache = useCallback(() => {
  658. setClearingCache(true)
  659. return compiler
  660. .clearCache()
  661. .then(() => {
  662. setFileList(undefined)
  663. setPdfFile(undefined)
  664. })
  665. .finally(() => {
  666. setClearingCache(false)
  667. })
  668. }, [compiler])
  669. const syncToEntry = useCallback(
  670. (entry: any, keepCurrentView = false) => {
  671. const result = findEntityByPath(entry.file)
  672. if (result && result.type === 'doc') {
  673. openDocWithId(result.entity._id, {
  674. gotoLine: entry.line ?? undefined,
  675. gotoColumn: entry.column ?? undefined,
  676. keepCurrentView,
  677. })
  678. }
  679. },
  680. [findEntityByPath, openDocWithId]
  681. )
  682. // clear the cache then run a compile, triggered by a menu item
  683. const recompileFromScratch = useCallback(() => {
  684. clearCache().then(() => {
  685. compiler.compile()
  686. })
  687. }, [clearCache, compiler])
  688. // After a compile, the compiler sets `data.options` to the options that were
  689. // used for that compile.
  690. const lastCompileOptions = useMemo(() => data?.options || {}, [data])
  691. const value = useMemo(
  692. () => ({
  693. animateCompileDropdownArrow,
  694. autoCompile,
  695. clearCache,
  696. clearingCache,
  697. clsiServerId,
  698. codeCheckFailed,
  699. compiling,
  700. deliveryLatencies,
  701. draft,
  702. editedSinceCompileStarted,
  703. error,
  704. fileList,
  705. hasChanges,
  706. hasShortCompileTimeout,
  707. highlights,
  708. isProjectOwner,
  709. lastCompileOptions,
  710. logEntryAnnotations,
  711. logEntries,
  712. pdfDownloadUrl: pdfFile?.pdfDownloadUrl,
  713. pdfFile,
  714. pdfUrl: pdfFile?.pdfUrl,
  715. pdfViewer,
  716. position,
  717. rawLog,
  718. recompileFromScratch,
  719. setAnimateCompileDropdownArrow,
  720. setAutoCompile,
  721. setCompiling,
  722. setDraft,
  723. setError,
  724. setHasLintingError, // only for stories
  725. setHighlights,
  726. setPosition,
  727. showCompileTimeWarning,
  728. setShowCompileTimeWarning,
  729. setShowLogs,
  730. toggleLogs,
  731. setStopOnFirstError,
  732. setStopOnValidationError,
  733. showLogs,
  734. clsiCachePromptVariant,
  735. clsiCachePromptSegmentation,
  736. setClsiCachePromptSegmentation,
  737. startCompile,
  738. stopCompile,
  739. stopOnFirstError,
  740. stopOnValidationError,
  741. stoppedOnFirstError,
  742. uncompiled,
  743. validationIssues,
  744. firstRenderDone,
  745. setChangedAt,
  746. cleanupCompileResult,
  747. syncToEntry,
  748. recordAction,
  749. }),
  750. [
  751. animateCompileDropdownArrow,
  752. autoCompile,
  753. clearCache,
  754. clearingCache,
  755. clsiServerId,
  756. codeCheckFailed,
  757. compiling,
  758. deliveryLatencies,
  759. draft,
  760. editedSinceCompileStarted,
  761. error,
  762. fileList,
  763. hasChanges,
  764. hasShortCompileTimeout,
  765. highlights,
  766. isProjectOwner,
  767. lastCompileOptions,
  768. logEntries,
  769. logEntryAnnotations,
  770. position,
  771. pdfFile,
  772. pdfViewer,
  773. rawLog,
  774. recompileFromScratch,
  775. setAnimateCompileDropdownArrow,
  776. setAutoCompile,
  777. setDraft,
  778. setError,
  779. setHasLintingError, // only for stories
  780. setHighlights,
  781. setPosition,
  782. setShowCompileTimeWarning,
  783. setStopOnFirstError,
  784. setStopOnValidationError,
  785. showCompileTimeWarning,
  786. showLogs,
  787. clsiCachePromptVariant,
  788. clsiCachePromptSegmentation,
  789. setClsiCachePromptSegmentation,
  790. startCompile,
  791. stopCompile,
  792. stopOnFirstError,
  793. stopOnValidationError,
  794. stoppedOnFirstError,
  795. uncompiled,
  796. validationIssues,
  797. firstRenderDone,
  798. setChangedAt,
  799. cleanupCompileResult,
  800. setShowLogs,
  801. toggleLogs,
  802. syncToEntry,
  803. recordAction,
  804. ]
  805. )
  806. return (
  807. <LocalCompileContext.Provider value={value}>
  808. {children}
  809. </LocalCompileContext.Provider>
  810. )
  811. }
  812. export function useLocalCompileContext() {
  813. const context = useContext(LocalCompileContext)
  814. if (!context) {
  815. throw new Error(
  816. 'useLocalCompileContext is only available inside LocalCompileProvider'
  817. )
  818. }
  819. return context
  820. }