pdf-synctex-controls.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import classNames from 'classnames'
  2. import { memo, useCallback, useEffect, useState } from 'react'
  3. import PropTypes from 'prop-types'
  4. import { useIdeContext } from '../../../shared/context/ide-context'
  5. import { useProjectContext } from '../../../shared/context/project-context'
  6. import { getJSON } from '../../../infrastructure/fetch-json'
  7. import { useCompileContext } from '../../../shared/context/compile-context'
  8. import { useLayoutContext } from '../../../shared/context/layout-context'
  9. import useScopeValue from '../../../shared/hooks/use-scope-value'
  10. import { Button, OverlayTrigger, Tooltip } from 'react-bootstrap'
  11. import Icon from '../../../shared/components/icon'
  12. import { useTranslation } from 'react-i18next'
  13. import useIsMounted from '../../../shared/hooks/use-is-mounted'
  14. import useAbortController from '../../../shared/hooks/use-abort-controller'
  15. import useDetachState from '../../../shared/hooks/use-detach-state'
  16. import useDetachAction from '../../../shared/hooks/use-detach-action'
  17. import localStorage from '../../../infrastructure/local-storage'
  18. function GoToCodeButton({
  19. position,
  20. syncToCode,
  21. syncToCodeInFlight,
  22. isDetachLayout,
  23. }) {
  24. const { t } = useTranslation()
  25. const tooltipPlacement = isDetachLayout ? 'bottom' : 'right'
  26. const buttonClasses = classNames('synctex-control', {
  27. 'detach-synctex-control': !!isDetachLayout,
  28. })
  29. let buttonIcon = null
  30. if (syncToCodeInFlight) {
  31. buttonIcon = <Icon type="refresh" spin className="synctex-spin-icon" />
  32. } else if (!isDetachLayout) {
  33. buttonIcon = <Icon type="arrow-left" className="synctex-control-icon" />
  34. }
  35. return (
  36. <OverlayTrigger
  37. placement={tooltipPlacement}
  38. overlay={
  39. <Tooltip id="sync-to-code-tooltip">
  40. {t('go_to_pdf_location_in_code')}
  41. </Tooltip>
  42. }
  43. >
  44. <Button
  45. bsStyle="default"
  46. bsSize="xs"
  47. onClick={() => syncToCode(position, 72)}
  48. disabled={syncToCodeInFlight}
  49. className={buttonClasses}
  50. aria-label={t('go_to_pdf_location_in_code')}
  51. >
  52. {buttonIcon}
  53. {isDetachLayout ? <span>&nbsp;{t('show_in_code')}</span> : ''}
  54. </Button>
  55. </OverlayTrigger>
  56. )
  57. }
  58. function GoToPdfButton({
  59. cursorPosition,
  60. syncToPdf,
  61. syncToPdfInFlight,
  62. isDetachLayout,
  63. }) {
  64. const { t } = useTranslation()
  65. const tooltipPlacement = isDetachLayout ? 'bottom' : 'right'
  66. const buttonClasses = classNames('synctex-control', {
  67. 'detach-synctex-control': !!isDetachLayout,
  68. })
  69. let buttonIcon = null
  70. if (syncToPdfInFlight) {
  71. buttonIcon = <Icon type="refresh" spin className="synctex-spin-icon" />
  72. } else if (!isDetachLayout) {
  73. buttonIcon = <Icon type="arrow-right" className="synctex-control-icon" />
  74. }
  75. return (
  76. <OverlayTrigger
  77. placement={tooltipPlacement}
  78. overlay={
  79. <Tooltip id="sync-to-pdf-tooltip">
  80. {t('go_to_code_location_in_pdf')}
  81. </Tooltip>
  82. }
  83. >
  84. <Button
  85. bsStyle="default"
  86. bsSize="xs"
  87. onClick={() => syncToPdf(cursorPosition)}
  88. disabled={syncToPdfInFlight || !cursorPosition}
  89. className={buttonClasses}
  90. aria-label={t('go_to_code_location_in_pdf')}
  91. >
  92. {buttonIcon}
  93. {isDetachLayout ? <span>&nbsp;{t('show_in_pdf')}</span> : ''}
  94. </Button>
  95. </OverlayTrigger>
  96. )
  97. }
  98. function PdfSynctexControls() {
  99. const ide = useIdeContext()
  100. const { _id: projectId } = useProjectContext()
  101. const { detachRole } = useLayoutContext()
  102. const {
  103. clsiServerId,
  104. pdfUrl,
  105. pdfViewer,
  106. position,
  107. setShowLogs,
  108. setHighlights,
  109. } = useCompileContext()
  110. const [cursorPosition, setCursorPosition] = useState(() => {
  111. const position = localStorage.getItem(
  112. `doc.position.${ide.editorManager.getCurrentDocId()}`
  113. )
  114. return position ? position.cursorPosition : null
  115. })
  116. const isMounted = useIsMounted()
  117. const { signal } = useAbortController()
  118. // for detacher editor tab, which cannot access pdfUrl in a scope value in
  119. // detached state
  120. const [pdfExists, setPdfExists] = useDetachState(
  121. 'pdf-exists',
  122. !!pdfUrl,
  123. 'detached',
  124. 'detacher'
  125. )
  126. useEffect(() => {
  127. setPdfExists(!!pdfUrl)
  128. }, [pdfUrl, setPdfExists])
  129. useEffect(() => {
  130. const listener = event => setCursorPosition(event.detail)
  131. window.addEventListener('cursor:editor:update', listener)
  132. return () => window.removeEventListener('cursor:editor:update', listener)
  133. }, [ide])
  134. const [syncToPdfInFlight, setSyncToPdfInFlight] = useDetachState(
  135. 'sync-to-pdf-inflight',
  136. false,
  137. 'detached',
  138. 'detacher'
  139. )
  140. const [syncToCodeInFlight, setSyncToCodeInFlight] = useState(false)
  141. const [, setSynctexError] = useScopeValue('sync_tex_error')
  142. const getCurrentFilePath = useCallback(() => {
  143. const docId = ide.editorManager.getCurrentDocId()
  144. const doc = ide.fileTreeManager.findEntityById(docId)
  145. let path = ide.fileTreeManager.getEntityPath(doc)
  146. // If the root file is folder/main.tex, then synctex sees the path as folder/./main.tex
  147. const rootDocDirname = ide.fileTreeManager.getRootDocDirname()
  148. if (rootDocDirname) {
  149. path = path.replace(RegExp(`^${rootDocDirname}`), `${rootDocDirname}/.`)
  150. }
  151. return path
  152. }, [ide])
  153. const _goToCodeLine = useCallback(
  154. (file, line) => {
  155. if (file) {
  156. const doc = ide.fileTreeManager.findEntityByPath(file)
  157. ide.editorManager.openDoc(doc, {
  158. gotoLine: line,
  159. })
  160. } else {
  161. setSynctexError(true)
  162. window.setTimeout(() => {
  163. if (isMounted.current) {
  164. setSynctexError(false)
  165. }
  166. }, 4000)
  167. }
  168. },
  169. [ide, isMounted, setSynctexError]
  170. )
  171. const goToCodeLine = useDetachAction(
  172. 'go-to-code-line',
  173. _goToCodeLine,
  174. 'detached',
  175. 'detacher'
  176. )
  177. const _goToPdfLocation = useCallback(
  178. params => {
  179. setSyncToPdfInFlight(true)
  180. if (clsiServerId) {
  181. params += `&clsiserverid=${clsiServerId}`
  182. }
  183. getJSON(`/project/${projectId}/sync/code?${params}`, { signal })
  184. .then(data => {
  185. setShowLogs(false)
  186. setHighlights(data.pdf)
  187. })
  188. .catch(error => {
  189. console.error(error)
  190. })
  191. .finally(() => {
  192. if (isMounted.current) {
  193. setSyncToPdfInFlight(false)
  194. }
  195. })
  196. },
  197. [
  198. clsiServerId,
  199. isMounted,
  200. projectId,
  201. setShowLogs,
  202. setHighlights,
  203. setSyncToPdfInFlight,
  204. signal,
  205. ]
  206. )
  207. const goToPdfLocation = useDetachAction(
  208. 'go-to-pdf-location',
  209. _goToPdfLocation,
  210. 'detacher',
  211. 'detached'
  212. )
  213. const syncToPdf = useCallback(
  214. cursorPosition => {
  215. const params = new URLSearchParams({
  216. file: getCurrentFilePath(),
  217. line: cursorPosition.row + 1,
  218. column: cursorPosition.column,
  219. }).toString()
  220. goToPdfLocation(params)
  221. },
  222. [getCurrentFilePath, goToPdfLocation]
  223. )
  224. const syncToCode = useCallback(
  225. (position, visualOffset = 0) => {
  226. setSyncToCodeInFlight(true)
  227. // FIXME: this actually works better if it's halfway across the
  228. // page (or the visible part of the page). Synctex doesn't
  229. // always find the right place in the file when the point is at
  230. // the edge of the page, it sometimes returns the start of the
  231. // next paragraph instead.
  232. const h = position.offset.left
  233. // Compute the vertical position to pass to synctex, which
  234. // works with coordinates increasing from the top of the page
  235. // down. This matches the browser's DOM coordinate of the
  236. // click point, but the pdf position is measured from the
  237. // bottom of the page so we need to invert it.
  238. let v = 0
  239. if (position.pageSize?.height) {
  240. v += position.pageSize.height - position.offset.top // measure from pdf point (inverted)
  241. } else {
  242. v += position.offset.top // measure from html click position
  243. }
  244. v += visualOffset
  245. const params = new URLSearchParams({
  246. page: position.page + 1,
  247. h: h.toFixed(2),
  248. v: v.toFixed(2),
  249. })
  250. if (clsiServerId) {
  251. params.set('clsiserverid', clsiServerId)
  252. }
  253. getJSON(`/project/${projectId}/sync/pdf?${params}`, { signal })
  254. .then(data => {
  255. const [{ file, line }] = data.code
  256. goToCodeLine(file, line)
  257. })
  258. .catch(error => {
  259. console.error(error)
  260. })
  261. .finally(() => {
  262. if (isMounted.current) {
  263. setSyncToCodeInFlight(false)
  264. }
  265. })
  266. },
  267. [
  268. clsiServerId,
  269. projectId,
  270. signal,
  271. isMounted,
  272. setSyncToCodeInFlight,
  273. goToCodeLine,
  274. ]
  275. )
  276. useEffect(() => {
  277. const listener = event => syncToCode(event.detail)
  278. window.addEventListener('synctex:sync-to-position', listener)
  279. return () => {
  280. window.removeEventListener('synctex:sync-to-position', listener)
  281. }
  282. }, [syncToCode])
  283. if (!position) {
  284. return null
  285. }
  286. if (!pdfExists || pdfViewer === 'native') {
  287. return null
  288. }
  289. if (detachRole === 'detacher') {
  290. return (
  291. <>
  292. <GoToPdfButton
  293. cursorPosition={cursorPosition}
  294. syncToPdf={syncToPdf}
  295. syncToPdfInFlight={syncToPdfInFlight}
  296. isDetachLayout
  297. />
  298. </>
  299. )
  300. } else if (detachRole === 'detached') {
  301. return (
  302. <>
  303. <GoToCodeButton
  304. position={position}
  305. syncToCode={syncToCode}
  306. syncToCodeInFlight={syncToCodeInFlight}
  307. isDetachLayout
  308. />
  309. </>
  310. )
  311. } else {
  312. return (
  313. <>
  314. <GoToPdfButton
  315. cursorPosition={cursorPosition}
  316. syncToPdf={syncToPdf}
  317. syncToPdfInFlight={syncToPdfInFlight}
  318. />
  319. <GoToCodeButton
  320. position={position}
  321. syncToCode={syncToCode}
  322. syncToCodeInFlight={syncToCodeInFlight}
  323. />
  324. </>
  325. )
  326. }
  327. }
  328. export default memo(PdfSynctexControls)
  329. GoToCodeButton.propTypes = {
  330. isDetachLayout: PropTypes.bool,
  331. position: PropTypes.object.isRequired,
  332. syncToCode: PropTypes.func.isRequired,
  333. syncToCodeInFlight: PropTypes.bool.isRequired,
  334. }
  335. GoToPdfButton.propTypes = {
  336. cursorPosition: PropTypes.object,
  337. isDetachLayout: PropTypes.bool,
  338. syncToPdf: PropTypes.func.isRequired,
  339. syncToPdfInFlight: PropTypes.bool.isRequired,
  340. }