use-pdf-scroll-position.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'
  2. import customLocalStorage from '@/infrastructure/local-storage'
  3. import { debugConsole } from '@/utils/debugging'
  4. export type PdfScrollPosition = Record<string, any> | undefined
  5. export const usePdfScrollPosition = (
  6. lastCompileRootDocId: string | null | undefined
  7. ): [PdfScrollPosition, Dispatch<SetStateAction<PdfScrollPosition>>] => {
  8. // scroll position of the PDF
  9. const [position, setPosition] = useState<PdfScrollPosition>()
  10. const lastCompileRootDocIdRef = useRef<string | null | undefined>(
  11. lastCompileRootDocId
  12. )
  13. useEffect(() => {
  14. lastCompileRootDocIdRef.current = lastCompileRootDocId
  15. }, [lastCompileRootDocId])
  16. const initialScrollPositionRef = useRef<PdfScrollPosition | null>(null)
  17. // load the stored PDF scroll position when the compiled root doc changes
  18. useEffect(() => {
  19. if (lastCompileRootDocId) {
  20. const position = customLocalStorage.getItem(
  21. `pdf.position.${lastCompileRootDocId}`
  22. )
  23. if (position) {
  24. debugConsole.log('loaded position for', lastCompileRootDocId, position)
  25. initialScrollPositionRef.current = position
  26. setPosition(position)
  27. }
  28. }
  29. }, [lastCompileRootDocId])
  30. // store the current root doc's PDF scroll position when it changes
  31. useEffect(() => {
  32. if (
  33. lastCompileRootDocIdRef.current &&
  34. position &&
  35. position !== initialScrollPositionRef.current
  36. ) {
  37. debugConsole.log(
  38. 'storing position for',
  39. lastCompileRootDocIdRef.current,
  40. position
  41. )
  42. customLocalStorage.setItem(
  43. `pdf.position.${lastCompileRootDocIdRef.current}`,
  44. position
  45. )
  46. }
  47. }, [position])
  48. return [position, setPosition]
  49. }