agentcooper / react-pdf-highlighter

Set of React components for PDF annotation
https://agentcooper.github.io/react-pdf-highlighter
MIT License
973 stars 388 forks source link

Issue with Scrolling to Runtime-Added Highlight #257

Open xyspg opened 7 months ago

xyspg commented 7 months ago

Description

I'm currently using the react-pdf-annotator library in a project and have encountered a bug related to scrolling to a highlighted section added at runtime.

Steps to Reproduce

  1. On initial page load, the PDF highlights defined in test-highlight.ts (a JSON structure) are correctly loaded, and the scroll-to-highlight feature works as expected.
  2. I add a new highlight to the state dynamically using JavaScript. The new highlight appears correctly in the sidebar, holding with a unique position and ID.
  3. However, when I click on the newly added highlight, it fails to trigger a scroll event in the PDF viewer. The URL's search parameter hash changes as expected, but the view does not scroll to the highlighted section.
  4. To test further, I copied the exact JSON object of the dynamically added highlight and added it manually to thetest-highlight.ts file. With this setup, the highlight works correctly, suggesting that the issue arises when highlights are added at runtime.

    Expected Behavior

    When a new highlight is added at runtime and subsequently clicked in the sidebar, the PDF viewer should scroll to the location of that highlight.

Actual Behavior

The PDF viewer does not scroll to the newly added highlight, although the sidebar correctly updates and the URL hash changes.

Possible Issue

It seems that the internal scroll function of the PDFHighlighter component does not recognize or respond to the state change when a new highlight is added dynamically.

Additional Information

CleanShot 2023-11-23 at 21 15 32 CleanShot 2023-11-23 at 21 16 46@2x

DanielArnould commented 7 months ago

I wasn't able to reproduce this using the example app on the repo. It might help to see how you're adding your new highlight and how you're trying to scroll to the new highlight 🤔.

It seems that the internal scroll function of the PDFHighlighter component does not recognize or respond to the state change when a new highlight is added dynamically.

You're right, but this is by design. The scrollTo function provided by and inside the PDFHighlighter is unaware of any other highlights. If you provide a valid highlight to it, it takes the position embedded in that highlight and scrolls to it. Since the scroll works if you add the highlight to test_highlights, I would think that your own scroll function isn't accessing the latest highlights state in your app and is thus passing undefined to the scrollTo function.