pdf-synctex-controls.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. import classNames from 'classnames'
  2. import { memo, useCallback, useEffect, useState, useRef } from 'react'
  3. import { useProjectContext } from '../../../shared/context/project-context'
  4. import { getJSON } from '../../../infrastructure/fetch-json'
  5. import { useDetachCompileContext as useCompileContext } from '../../../shared/context/detach-compile-context'
  6. import { useLayoutContext } from '../../../shared/context/layout-context'
  7. import useScopeValue from '../../../shared/hooks/use-scope-value'
  8. import { useTranslation } from 'react-i18next'
  9. import useIsMounted from '../../../shared/hooks/use-is-mounted'
  10. import useAbortController from '../../../shared/hooks/use-abort-controller'
  11. import useDetachState from '../../../shared/hooks/use-detach-state'
  12. import useDetachAction from '../../../shared/hooks/use-detach-action'
  13. import localStorage from '../../../infrastructure/local-storage'
  14. import { useFileTreeData } from '../../../shared/context/file-tree-data-context'
  15. import useScopeEventListener from '../../../shared/hooks/use-scope-event-listener'
  16. import * as eventTracking from '../../../infrastructure/event-tracking'
  17. import { debugConsole } from '@/utils/debugging'
  18. import { useFileTreePathContext } from '@/features/file-tree/contexts/file-tree-path'
  19. import OLTooltip from '@/features/ui/components/ol/ol-tooltip'
  20. import OLButton from '@/features/ui/components/ol/ol-button'
  21. import MaterialIcon from '@/shared/components/material-icon'
  22. import { Spinner } from 'react-bootstrap-5'
  23. import { useEditorManagerContext } from '@/features/ide-react/context/editor-manager-context'
  24. import useEventListener from '@/shared/hooks/use-event-listener'
  25. import { PdfScrollPosition } from '@/shared/hooks/use-pdf-scroll-position'
  26. import { CursorPosition } from '@/features/ide-react/types/cursor-position'
  27. import { isValidTeXFile } from '@/main/is-valid-tex-file'
  28. function GoToCodeButton({
  29. position,
  30. syncToCode,
  31. syncToCodeInFlight,
  32. isDetachLayout,
  33. }: {
  34. position: PdfScrollPosition
  35. syncToCode: (position: PdfScrollPosition, visualOffset?: number) => void
  36. syncToCodeInFlight: boolean
  37. isDetachLayout?: boolean
  38. }) {
  39. const { t } = useTranslation()
  40. const tooltipPlacement = isDetachLayout ? 'bottom' : 'right'
  41. const buttonClasses = classNames('synctex-control', {
  42. 'detach-synctex-control': !!isDetachLayout,
  43. })
  44. let buttonIcon = null
  45. if (syncToCodeInFlight) {
  46. buttonIcon = (
  47. <Spinner animation="border" aria-hidden="true" size="sm" role="status" />
  48. )
  49. } else if (!isDetachLayout) {
  50. buttonIcon = (
  51. <MaterialIcon type="arrow_left_alt" className="synctex-control-icon" />
  52. )
  53. }
  54. const syncToCodeWithButton = () => {
  55. eventTracking.sendMB('jump-to-location', {
  56. direction: 'pdf-location-in-code',
  57. method: 'arrow',
  58. })
  59. syncToCode(position, 72)
  60. }
  61. return (
  62. <OLTooltip
  63. id="sync-to-code"
  64. description={t('go_to_pdf_location_in_code')}
  65. overlayProps={{ placement: tooltipPlacement }}
  66. >
  67. <OLButton
  68. variant="secondary"
  69. size="sm"
  70. onClick={syncToCodeWithButton}
  71. disabled={syncToCodeInFlight}
  72. className={buttonClasses}
  73. aria-label={t('go_to_pdf_location_in_code')}
  74. >
  75. {buttonIcon}
  76. {isDetachLayout ? <span>&nbsp;{t('show_in_code')}</span> : ''}
  77. </OLButton>
  78. </OLTooltip>
  79. )
  80. }
  81. function GoToPdfButton({
  82. cursorPosition,
  83. syncToPdf,
  84. syncToPdfInFlight,
  85. isDetachLayout,
  86. canSyncToPdf,
  87. }: {
  88. cursorPosition: CursorPosition | null
  89. syncToPdf: (cursorPosition: CursorPosition | null) => void
  90. syncToPdfInFlight: boolean
  91. canSyncToPdf: boolean
  92. isDetachLayout?: boolean
  93. }) {
  94. const { t } = useTranslation()
  95. const tooltipPlacement = isDetachLayout ? 'bottom' : 'right'
  96. const buttonClasses = classNames('synctex-control', {
  97. 'detach-synctex-control': !!isDetachLayout,
  98. })
  99. let buttonIcon = null
  100. if (syncToPdfInFlight) {
  101. buttonIcon = (
  102. <Spinner animation="border" aria-hidden="true" size="sm" role="status" />
  103. )
  104. } else if (!isDetachLayout) {
  105. buttonIcon = (
  106. <MaterialIcon type="arrow_right_alt" className="synctex-control-icon" />
  107. )
  108. }
  109. return (
  110. <OLTooltip
  111. id="sync-to-pdf"
  112. description={t('go_to_code_location_in_pdf')}
  113. overlayProps={{ placement: tooltipPlacement }}
  114. >
  115. <OLButton
  116. variant="secondary"
  117. size="sm"
  118. onClick={() => syncToPdf(cursorPosition)}
  119. disabled={syncToPdfInFlight || !canSyncToPdf}
  120. className={buttonClasses}
  121. aria-label={t('go_to_code_location_in_pdf')}
  122. >
  123. {buttonIcon}
  124. {isDetachLayout ? <span>&nbsp;{t('show_in_pdf')}</span> : ''}
  125. </OLButton>
  126. </OLTooltip>
  127. )
  128. }
  129. function PdfSynctexControls() {
  130. const { _id: projectId, rootDocId } = useProjectContext()
  131. const { detachRole } = useLayoutContext()
  132. const {
  133. clsiServerId,
  134. pdfUrl,
  135. pdfViewer,
  136. position,
  137. setShowLogs,
  138. setHighlights,
  139. } = useCompileContext()
  140. const { selectedEntities } = useFileTreeData()
  141. const { findEntityByPath, dirname, pathInFolder } = useFileTreePathContext()
  142. const { getCurrentDocumentId, openDocWithId, openDocName } =
  143. useEditorManagerContext()
  144. const [cursorPosition, setCursorPosition] = useState<CursorPosition | null>(
  145. () => {
  146. const position = localStorage.getItem(
  147. `doc.position.${getCurrentDocumentId()}`
  148. )
  149. return position ? position.cursorPosition : null
  150. }
  151. )
  152. const isMounted = useIsMounted()
  153. const { signal } = useAbortController()
  154. const editorUpdateListener = useCallback(
  155. event => setCursorPosition(event.detail),
  156. []
  157. )
  158. useEventListener('cursor:editor:update', editorUpdateListener)
  159. const [syncToPdfInFlight, setSyncToPdfInFlight] = useState(false)
  160. const [syncToCodeInFlight, setSyncToCodeInFlight] = useDetachState(
  161. 'sync-to-code-inflight',
  162. false,
  163. 'detacher',
  164. 'detached'
  165. )
  166. const [, setSynctexError] = useScopeValue('sync_tex_error')
  167. const getCurrentFilePath = useCallback(() => {
  168. const docId = getCurrentDocumentId()
  169. if (!docId || !rootDocId) {
  170. return null
  171. }
  172. let path = pathInFolder(docId)
  173. if (!path) {
  174. return null
  175. }
  176. // If the root file is folder/main.tex, then synctex sees the path as folder/./main.tex
  177. const rootDocDirname = dirname(rootDocId)
  178. if (rootDocDirname) {
  179. path = path.replace(RegExp(`^${rootDocDirname}`), `${rootDocDirname}/.`)
  180. }
  181. return path
  182. }, [dirname, getCurrentDocumentId, pathInFolder, rootDocId])
  183. const goToCodeLine = useCallback(
  184. (file, line) => {
  185. if (file) {
  186. const doc = findEntityByPath(file)?.entity
  187. if (!doc) {
  188. debugConsole.warn(`Document with path ${file} not found`)
  189. return
  190. }
  191. openDocWithId(doc._id, {
  192. gotoLine: line,
  193. })
  194. } else {
  195. setSynctexError(true)
  196. window.setTimeout(() => {
  197. if (isMounted.current) {
  198. setSynctexError(false)
  199. }
  200. }, 4000)
  201. }
  202. },
  203. [findEntityByPath, openDocWithId, isMounted, setSynctexError]
  204. )
  205. const goToPdfLocation = useCallback(
  206. params => {
  207. setSyncToPdfInFlight(true)
  208. if (clsiServerId) {
  209. params += `&clsiserverid=${clsiServerId}`
  210. }
  211. getJSON(`/project/${projectId}/sync/code?${params}`, { signal })
  212. .then(data => {
  213. setShowLogs(false)
  214. setHighlights(data.pdf)
  215. })
  216. .catch(debugConsole.error)
  217. .finally(() => {
  218. if (isMounted.current) {
  219. setSyncToPdfInFlight(false)
  220. }
  221. })
  222. },
  223. [
  224. clsiServerId,
  225. isMounted,
  226. projectId,
  227. setShowLogs,
  228. setHighlights,
  229. setSyncToPdfInFlight,
  230. signal,
  231. ]
  232. )
  233. const syncToPdf = useCallback(
  234. cursorPosition => {
  235. const file = getCurrentFilePath()
  236. const params = new URLSearchParams({
  237. file: file ?? '',
  238. line: cursorPosition.row + 1,
  239. column: cursorPosition.column,
  240. }).toString()
  241. eventTracking.sendMB('jump-to-location', {
  242. direction: 'code-location-in-pdf',
  243. method: 'arrow',
  244. })
  245. goToPdfLocation(params)
  246. },
  247. [getCurrentFilePath, goToPdfLocation]
  248. )
  249. const cursorPositionRef = useRef(cursorPosition)
  250. useEffect(() => {
  251. cursorPositionRef.current = cursorPosition
  252. }, [cursorPosition])
  253. useScopeEventListener(
  254. 'cursor:editor:syncToPdf',
  255. useCallback(() => {
  256. syncToPdf(cursorPositionRef.current)
  257. }, [syncToPdf])
  258. )
  259. const _syncToCode = useCallback(
  260. (position, visualOffset = 0) => {
  261. setSyncToCodeInFlight(true)
  262. // FIXME: this actually works better if it's halfway across the
  263. // page (or the visible part of the page). Synctex doesn't
  264. // always find the right place in the file when the point is at
  265. // the edge of the page, it sometimes returns the start of the
  266. // next paragraph instead.
  267. const h = position.offset.left
  268. // Compute the vertical position to pass to synctex, which
  269. // works with coordinates increasing from the top of the page
  270. // down. This matches the browser's DOM coordinate of the
  271. // click point, but the pdf position is measured from the
  272. // bottom of the page so we need to invert it.
  273. let v = 0
  274. if (position.pageSize?.height) {
  275. v += position.pageSize.height - position.offset.top // measure from pdf point (inverted)
  276. } else {
  277. v += position.offset.top // measure from html click position
  278. }
  279. v += visualOffset
  280. const params = new URLSearchParams({
  281. page: position.page + 1,
  282. h: h.toFixed(2),
  283. v: v.toFixed(2),
  284. })
  285. if (clsiServerId) {
  286. params.set('clsiserverid', clsiServerId)
  287. }
  288. getJSON(`/project/${projectId}/sync/pdf?${params}`, { signal })
  289. .then(data => {
  290. const [{ file, line }] = data.code
  291. goToCodeLine(file, line)
  292. })
  293. .catch(debugConsole.error)
  294. .finally(() => {
  295. if (isMounted.current) {
  296. setSyncToCodeInFlight(false)
  297. }
  298. })
  299. },
  300. [
  301. clsiServerId,
  302. projectId,
  303. signal,
  304. isMounted,
  305. setSyncToCodeInFlight,
  306. goToCodeLine,
  307. ]
  308. )
  309. const syncToCode = useDetachAction(
  310. 'sync-to-code',
  311. _syncToCode,
  312. 'detached',
  313. 'detacher'
  314. )
  315. const syncToPositionListener = useCallback(
  316. event => syncToCode(event.detail),
  317. [syncToCode]
  318. )
  319. useEventListener('synctex:sync-to-position', syncToPositionListener)
  320. const [hasSingleSelectedDoc, setHasSingleSelectedDoc] = useDetachState(
  321. 'has-single-selected-doc',
  322. false,
  323. 'detacher',
  324. 'detached'
  325. )
  326. useEffect(() => {
  327. if (selectedEntities.length !== 1) {
  328. setHasSingleSelectedDoc(false)
  329. return
  330. }
  331. if (selectedEntities[0].type !== 'doc') {
  332. setHasSingleSelectedDoc(false)
  333. return
  334. }
  335. setHasSingleSelectedDoc(true)
  336. }, [selectedEntities, setHasSingleSelectedDoc])
  337. if (!position) {
  338. return null
  339. }
  340. if (!pdfUrl || pdfViewer === 'native') {
  341. return null
  342. }
  343. const canSyncToPdf: boolean =
  344. hasSingleSelectedDoc &&
  345. cursorPosition &&
  346. openDocName &&
  347. isValidTeXFile(openDocName)
  348. if (detachRole === 'detacher') {
  349. return (
  350. <>
  351. <GoToPdfButton
  352. cursorPosition={cursorPosition}
  353. syncToPdf={syncToPdf}
  354. syncToPdfInFlight={syncToPdfInFlight}
  355. isDetachLayout
  356. canSyncToPdf={canSyncToPdf}
  357. />
  358. </>
  359. )
  360. } else if (detachRole === 'detached') {
  361. return (
  362. <>
  363. <GoToCodeButton
  364. position={position}
  365. syncToCode={syncToCode}
  366. syncToCodeInFlight={syncToCodeInFlight}
  367. isDetachLayout
  368. />
  369. </>
  370. )
  371. } else {
  372. return (
  373. <>
  374. <GoToPdfButton
  375. cursorPosition={cursorPosition}
  376. syncToPdf={syncToPdf}
  377. syncToPdfInFlight={syncToPdfInFlight}
  378. canSyncToPdf={canSyncToPdf}
  379. />
  380. <GoToCodeButton
  381. position={position}
  382. syncToCode={syncToCode}
  383. syncToCodeInFlight={syncToCodeInFlight}
  384. />
  385. </>
  386. )
  387. }
  388. }
  389. export default memo(PdfSynctexControls)