pdf-preview-context.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. import {
  2. createContext,
  3. useCallback,
  4. useContext,
  5. useEffect,
  6. useMemo,
  7. useState,
  8. } from 'react'
  9. import PropTypes from 'prop-types'
  10. import useScopeValue from '../../../shared/hooks/use-scope-value'
  11. import { useProjectContext } from '../../../shared/context/project-context'
  12. import usePersistedState from '../../../shared/hooks/use-persisted-state'
  13. import {
  14. buildLogEntryAnnotations,
  15. handleOutputFiles,
  16. } from '../util/output-files'
  17. import {
  18. send,
  19. sendMB,
  20. sendMBSampled,
  21. } from '../../../infrastructure/event-tracking'
  22. import { useEditorContext } from '../../../shared/context/editor-context'
  23. import useAbortController from '../../../shared/hooks/use-abort-controller'
  24. import DocumentCompiler from '../util/compiler'
  25. import { useIdeContext } from '../../../shared/context/ide-context'
  26. import { useLayoutContext } from '../../../shared/context/layout-context'
  27. import { useCompileContext } from '../../../shared/context/compile-context'
  28. export const PdfPreviewContext = createContext(undefined)
  29. PdfPreviewProvider.propTypes = {
  30. children: PropTypes.any,
  31. }
  32. export default function PdfPreviewProvider({ children }) {
  33. const ide = useIdeContext()
  34. const { pdfHidden, pdfLayout, setPdfLayout, setView } = useLayoutContext()
  35. const project = useProjectContext()
  36. const projectId = project._id
  37. const { hasPremiumCompile, isProjectOwner } = useEditorContext()
  38. const {
  39. logEntries,
  40. pdfDownloadUrl,
  41. pdfUrl,
  42. setClsiServerId,
  43. setLogEntries,
  44. setLogEntryAnnotations,
  45. setPdfDownloadUrl,
  46. setPdfUrl,
  47. setUncompiled,
  48. uncompiled,
  49. } = useCompileContext()
  50. // whether a compile is in progress
  51. const [compiling, setCompiling] = useState(false)
  52. // data received in response to a compile request
  53. const [data, setData] = useState()
  54. // whether the project has been compiled yet
  55. const [compiledOnce, setCompiledOnce] = useState(false)
  56. // whether the cache is being cleared
  57. const [clearingCache, setClearingCache] = useState(false)
  58. // whether the logs should be visible
  59. const [showLogs, setShowLogs] = useState(false)
  60. // an error that occurred
  61. const [error, setError] = useState()
  62. // the list of files that can be downloaded
  63. const [fileList, setFileList] = useState()
  64. // the raw contents of the log file
  65. const [rawLog, setRawLog] = useState()
  66. // validation issues from CLSI
  67. const [validationIssues, setValidationIssues] = useState()
  68. // whether autocompile is switched on
  69. const [autoCompile, _setAutoCompile] = usePersistedState(
  70. `autocompile_enabled:${projectId}`,
  71. false,
  72. true
  73. )
  74. // whether the compile should run in draft mode
  75. const [draft, setDraft] = usePersistedState(`draft:${projectId}`, false, true)
  76. // whether compiling should be prevented if there are linting errors
  77. const [stopOnValidationError, setStopOnValidationError] = usePersistedState(
  78. `stop_on_validation_error:${projectId}`,
  79. true,
  80. true
  81. )
  82. // the Document currently open in the editor
  83. const [currentDoc] = useScopeValue('editor.sharejs_doc')
  84. // whether the editor linter found errors
  85. const [hasLintingError, setHasLintingError] = useScopeValue('hasLintingError')
  86. // whether syntax validation is enabled globally
  87. const [syntaxValidation] = useScopeValue('settings.syntaxValidation')
  88. // the timestamp that a doc was last changed or saved
  89. const [changedAt, setChangedAt] = useState(0)
  90. const { signal } = useAbortController()
  91. // the document compiler
  92. const [compiler] = useState(() => {
  93. return new DocumentCompiler({
  94. project,
  95. setChangedAt,
  96. setCompiling,
  97. setData,
  98. setError,
  99. signal,
  100. })
  101. })
  102. // clean up the compiler on unmount
  103. useEffect(() => {
  104. return () => {
  105. compiler.destroy()
  106. }
  107. }, [compiler])
  108. // keep currentDoc in sync with the compiler
  109. useEffect(() => {
  110. compiler.currentDoc = currentDoc
  111. }, [compiler, currentDoc])
  112. // keep draft setting in sync with the compiler
  113. useEffect(() => {
  114. compiler.draft = draft
  115. }, [compiler, draft])
  116. // pass the "uncompiled" value up into the scope for use outside this context provider
  117. useEffect(() => {
  118. setUncompiled(changedAt > 0)
  119. }, [setUncompiled, changedAt])
  120. // record changes to the autocompile setting
  121. const setAutoCompile = useCallback(
  122. value => {
  123. _setAutoCompile(value)
  124. sendMB('autocompile-setting-changed', { value })
  125. },
  126. [_setAutoCompile]
  127. )
  128. // always compile the PDF once after opening the project, after the doc has loaded
  129. useEffect(() => {
  130. if (!compiledOnce && currentDoc) {
  131. setCompiledOnce(true)
  132. compiler.compile({ isAutoCompileOnLoad: true })
  133. }
  134. }, [compiledOnce, currentDoc, compiler])
  135. // handle the data returned from a compile request
  136. // note: this should _only_ run when `data` changes,
  137. // the other dependencies must all be static
  138. useEffect(() => {
  139. if (data) {
  140. if (data.clsiServerId) {
  141. setClsiServerId(data.clsiServerId) // set in scope, for PdfSynctexController
  142. compiler.clsiServerId = data.clsiServerId
  143. }
  144. if (data.compileGroup) {
  145. compiler.compileGroup = data.compileGroup
  146. }
  147. if (data.outputFiles) {
  148. handleOutputFiles(projectId, data).then(result => {
  149. setLogEntryAnnotations(
  150. buildLogEntryAnnotations(result.logEntries.all, ide.fileTreeManager)
  151. )
  152. setLogEntries(result.logEntries)
  153. setFileList(result.fileList)
  154. setPdfDownloadUrl(result.pdfDownloadUrl)
  155. setPdfUrl(result.pdfUrl)
  156. setRawLog(result.log)
  157. // sample compile stats for real users
  158. if (!window.user.alphaProgram && data.status === 'success') {
  159. sendMBSampled(
  160. 'compile-result',
  161. {
  162. errors: result.logEntries.errors.length,
  163. warnings: result.logEntries.warnings.length,
  164. typesetting: result.logEntries.typesetting.length,
  165. newPdfPreview: true, // TODO: is this useful?
  166. },
  167. 0.01
  168. )
  169. }
  170. })
  171. }
  172. switch (data.status) {
  173. case 'success':
  174. setError(undefined)
  175. setShowLogs(false)
  176. break
  177. case 'clsi-maintenance':
  178. case 'compile-in-progress':
  179. case 'exited':
  180. case 'failure':
  181. case 'project-too-large':
  182. case 'terminated':
  183. case 'too-recently-compiled':
  184. setError(data.status)
  185. break
  186. case 'timedout':
  187. setError('timedout')
  188. if (!hasPremiumCompile && isProjectOwner) {
  189. send(
  190. 'subscription-funnel',
  191. 'editor-click-feature',
  192. 'compile-timeout'
  193. )
  194. sendMB('paywall-prompt', {
  195. 'paywall-type': 'compile-timeout',
  196. })
  197. }
  198. break
  199. case 'autocompile-backoff':
  200. if (!data.options.isAutoCompileOnLoad) {
  201. setError('autocompile-disabled')
  202. setAutoCompile(false)
  203. sendMB('autocompile-rate-limited', { hasPremiumCompile })
  204. }
  205. break
  206. case 'unavailable':
  207. setError('clsi-unavailable')
  208. break
  209. case 'validation-problems':
  210. setError('validation-problems')
  211. setValidationIssues(data.validationProblems)
  212. break
  213. default:
  214. setError('error')
  215. break
  216. }
  217. }
  218. }, [
  219. compiler,
  220. data,
  221. ide,
  222. hasPremiumCompile,
  223. isProjectOwner,
  224. projectId,
  225. setAutoCompile,
  226. setClsiServerId,
  227. setLogEntries,
  228. setLogEntryAnnotations,
  229. setPdfDownloadUrl,
  230. setPdfUrl,
  231. ])
  232. // switch to logs if there's an error
  233. useEffect(() => {
  234. if (error) {
  235. setShowLogs(true)
  236. }
  237. }, [error])
  238. // recompile on key press
  239. useEffect(() => {
  240. const listener = event => {
  241. compiler.compile(event.detail)
  242. }
  243. window.addEventListener('pdf:recompile', listener)
  244. return () => {
  245. window.removeEventListener('pdf:recompile', listener)
  246. }
  247. }, [compiler])
  248. // whether there has been an autocompile linting error, if syntax validation is switched on
  249. const autoCompileLintingError = Boolean(
  250. autoCompile && syntaxValidation && hasLintingError
  251. )
  252. const codeCheckFailed = stopOnValidationError && autoCompileLintingError
  253. // show that the project has pending changes
  254. const hasChanges = Boolean(
  255. autoCompile && uncompiled && compiledOnce && !codeCheckFailed
  256. )
  257. // the project is available for auto-compiling
  258. const canAutoCompile = Boolean(
  259. autoCompile && !compiling && !pdfHidden && !codeCheckFailed
  260. )
  261. // call the debounced autocompile function if the project is available for auto-compiling and it has changed
  262. useEffect(() => {
  263. if (canAutoCompile && changedAt > 0) {
  264. compiler.debouncedAutoCompile()
  265. } else {
  266. compiler.debouncedAutoCompile.cancel()
  267. }
  268. }, [compiler, canAutoCompile, changedAt])
  269. // cancel debounced recompile on unmount
  270. useEffect(() => {
  271. return () => {
  272. compiler.debouncedAutoCompile.cancel()
  273. }
  274. }, [compiler])
  275. // record doc changes when notified by the editor
  276. useEffect(() => {
  277. const listener = () => {
  278. setChangedAt(Date.now())
  279. }
  280. window.addEventListener('doc:changed', listener)
  281. window.addEventListener('doc:saved', listener)
  282. return () => {
  283. window.removeEventListener('doc:changed', listener)
  284. window.removeEventListener('doc:saved', listener)
  285. }
  286. }, [])
  287. // start a compile manually
  288. const startCompile = useCallback(() => {
  289. compiler.compile()
  290. }, [compiler])
  291. // stop a compile manually
  292. const stopCompile = useCallback(() => {
  293. compiler.stopCompile()
  294. }, [compiler])
  295. // clear the compile cache
  296. const clearCache = useCallback(() => {
  297. setClearingCache(true)
  298. return compiler.clearCache().finally(() => {
  299. setClearingCache(false)
  300. })
  301. }, [compiler])
  302. // clear the cache then run a compile, triggered by a menu item
  303. const recompileFromScratch = useCallback(() => {
  304. clearCache().then(() => {
  305. compiler.compile()
  306. })
  307. }, [clearCache, compiler])
  308. // switch to either side-by-side or flat (full-width) layout
  309. // TODO: move this into LayoutContext?
  310. const switchLayout = useCallback(() => {
  311. setPdfLayout(layout => {
  312. const newLayout = layout === 'sideBySide' ? 'flat' : 'sideBySide'
  313. setView(newLayout === 'sideBySide' ? 'editor' : 'pdf')
  314. setPdfLayout(newLayout)
  315. window.localStorage.setItem('pdf.layout', newLayout)
  316. })
  317. }, [setPdfLayout, setView])
  318. // the context value, memoized to minimize re-rendering
  319. const value = useMemo(() => {
  320. return {
  321. autoCompile,
  322. codeCheckFailed,
  323. clearCache,
  324. clearingCache,
  325. compiling,
  326. draft,
  327. error,
  328. fileList,
  329. hasChanges,
  330. hasLintingError,
  331. logEntries,
  332. pdfDownloadUrl,
  333. pdfLayout,
  334. pdfUrl,
  335. rawLog,
  336. recompileFromScratch,
  337. setAutoCompile,
  338. setDraft,
  339. setHasLintingError, // only for stories
  340. setShowLogs,
  341. setStopOnValidationError,
  342. showLogs,
  343. startCompile,
  344. stopCompile,
  345. stopOnValidationError,
  346. switchLayout,
  347. uncompiled,
  348. validationIssues,
  349. }
  350. }, [
  351. autoCompile,
  352. codeCheckFailed,
  353. clearCache,
  354. clearingCache,
  355. compiling,
  356. draft,
  357. error,
  358. fileList,
  359. hasChanges,
  360. hasLintingError,
  361. logEntries,
  362. pdfDownloadUrl,
  363. pdfLayout,
  364. pdfUrl,
  365. rawLog,
  366. recompileFromScratch,
  367. setAutoCompile,
  368. setDraft,
  369. setHasLintingError, // only for stories
  370. setStopOnValidationError,
  371. showLogs,
  372. startCompile,
  373. stopCompile,
  374. stopOnValidationError,
  375. switchLayout,
  376. uncompiled,
  377. validationIssues,
  378. ])
  379. return (
  380. <PdfPreviewContext.Provider value={value}>
  381. {children}
  382. </PdfPreviewContext.Provider>
  383. )
  384. }
  385. PdfPreviewContext.Provider.propTypes = {
  386. value: PropTypes.shape({
  387. autoCompile: PropTypes.bool.isRequired,
  388. clearCache: PropTypes.func.isRequired,
  389. clearingCache: PropTypes.bool.isRequired,
  390. codeCheckFailed: PropTypes.bool.isRequired,
  391. compiling: PropTypes.bool.isRequired,
  392. draft: PropTypes.bool.isRequired,
  393. error: PropTypes.string,
  394. fileList: PropTypes.object,
  395. hasChanges: PropTypes.bool.isRequired,
  396. hasLintingError: PropTypes.bool,
  397. logEntries: PropTypes.object,
  398. pdfDownloadUrl: PropTypes.string,
  399. pdfLayout: PropTypes.string,
  400. pdfUrl: PropTypes.string,
  401. rawLog: PropTypes.string,
  402. recompileFromScratch: PropTypes.func.isRequired,
  403. setAutoCompile: PropTypes.func.isRequired,
  404. setDraft: PropTypes.func.isRequired,
  405. setHasLintingError: PropTypes.func.isRequired, // only for storybook
  406. setShowLogs: PropTypes.func.isRequired,
  407. setStopOnValidationError: PropTypes.func.isRequired,
  408. showLogs: PropTypes.bool.isRequired,
  409. startCompile: PropTypes.func.isRequired,
  410. stopCompile: PropTypes.func.isRequired,
  411. stopOnValidationError: PropTypes.bool.isRequired,
  412. switchLayout: PropTypes.func.isRequired,
  413. uncompiled: PropTypes.bool,
  414. validationIssues: PropTypes.object,
  415. }),
  416. }
  417. export function usePdfPreviewContext() {
  418. const context = useContext(PdfPreviewContext)
  419. if (!context) {
  420. throw new Error(
  421. 'usePdfPreviewContext is only available inside PdfPreviewProvider'
  422. )
  423. }
  424. return context
  425. }