local-compile-context.tsx 26 KB

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