pdf-preview-context.js 14 KB

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