agentcooper / react-pdf-highlighter

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

Can't seem to navigate to highlighted portion #277

Open codepeach opened 4 months ago

codepeach commented 4 months ago

I'm trying to use this in Next14, however, when I try to click on the highlights on the sidebar, it doesn't take me to the highlighted portion of the PDF. Anyone know why this might be?

Below is my code

'use client';

import {
  useEffect,
  useState,
  useCallback,
  Dispatch,
  SetStateAction,
} from 'react';
import * as pdfjs from 'pdfjs-dist';
import {
  PdfLoader,
  PdfHighlighter,
  Highlight,
  Popup,
  AreaHighlight,
} from 'react-pdf-highlighter';

import {
  Content,
  IHighlight,
  NewHighlight,
  ScaledPosition,
} from '@/lib/pdf-types';

import book from '/public/100m-offers.pdf';
import { Button } from './ui/button';
import { ChevronLeft, ChevronRight, Menu } from 'lucide-react';
import {
  Sheet,
  SheetClose,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from '@/components/ui/sheet';
import { ScrollArea } from './ui/scroll-area';
import { Separator } from './ui/separator';
import Tip from './Tip';

interface HighlightState {
  url: string;
  highlights: Array<IHighlight>;
}

type Props = {
  isHighlighted: HighlightState;
  setIsHighlighted: Dispatch<SetStateAction<HighlightState>>;
  removeHighlight: any;
};

const updateHash = (highlight: IHighlight) => {
  document.location.hash = `highlight-${highlight.id}`;
};

const getNextId = () => String(Math.random()).slice(2);

const parseIdFromHash = () =>
  document.location.hash.slice('#highlight-'.length);

const resetHash = () => {
  document.location.hash = '';
};

const HighlightPopup = ({
  comment,
}: {
  comment: { text: string; emoji: string; kind: string };
}) =>
  comment.text ? (
    <div className="Highlight__popup">
      {comment.kind}
    </div>
  ) : null;

const PRIMARY_PDF_URL = 'https://arxiv.org/pdf/1708.08021';
const SECONDARY_PDF_URL = 'https://arxiv.org/pdf/1604.02480';

const searchParams = new URLSearchParams(document.location.search);

const initialUrl = searchParams.get('url') || PRIMARY_PDF_URL;

const PDFDisplay = ({
  isHighlighted,
  setIsHighlighted,
  removeHighlight,
}: Props) => {
  const [sheetOpen, setSheetOpen] = useState(false);
  const [isTOC, setIsTOC] = useState<any[]>([]);

  useEffect(() => {
    pdfjs.getDocument(book).promise.then((pdfDocument) => {
      const toc: any[] = [];
      console.log('Saving table of contents');
      return pdfDocument
        .getOutline()
        .then(
          function (outline) {
            let lastPromise = Promise.resolve(); // will be used to chain promises
            if (outline) {
              const getTOCEntry = function (i: any) {
                const dest = outline[i].dest;
                return new Promise((resolve, reject) => {
                  if (typeof dest === 'string') {
                    pdfDocument.getDestination(dest).then((destArray: any) => {
                      resolve(destArray);
                    });
                    return;
                  }
                  resolve(dest);
                }).then((explicitDest: any) => {
                  // Dest array looks like that: <page-ref> </XYZ|/FitXXX> <args..>
                  const destRef = explicitDest[0];
                  if (destRef instanceof Object) {
                    return pdfDocument
                      .getPageIndex(destRef)
                      .then((pageIndex: any) => {
                        toc.push({
                          title: outline[i]['title'],
                          pageNumber: parseInt(pageIndex) + 1,
                        });
                      })
                      .catch(() => {
                        console.error(
                          `${destRef}" not a valid page reference for dest ${dest}`
                        );
                      });
                  }
                });
              };
              for (let i = 0; i < outline.length; i++) {
                lastPromise = lastPromise.then(getTOCEntry.bind(null, i));
              }
            }
            return lastPromise;
          },
          function (err) {
            console.error('Error', err);
          }
        )
        .then(function () {
          setIsTOC(toc);
          console.log(toc);
        });
    });

    return () => {
      // You can do cleanup here if necessary
    };
  }, []);

  useEffect(() => {
    window.addEventListener('hashchange', scrollToHighlightFromHash, false);
  }, []);

  const resetHighlights = () => {
    setIsHighlighted({
      url: '',
      highlights: [],
    });
  };

  const toggleDocument = () => {
    const newUrl =
      isHighlighted.url === PRIMARY_PDF_URL
        ? SECONDARY_PDF_URL
        : PRIMARY_PDF_URL;

    setIsHighlighted({
      url: newUrl,
      highlights: [],
    });
  };

  let scrollViewerTo = (highlight: IHighlight) => {};

  const scrollToHighlightFromHash = () => {
    const highlight = getHighlightById(parseIdFromHash());
    console.log(highlight);

    if (highlight) {
      scrollViewerTo(highlight);
    }
  };

  const getHighlightById = (id: string) => {
    const { highlights } = isHighlighted;

    return highlights.find((highlight) => highlight.id === id);
  };

  const addHighlight = (highlight: NewHighlight) => {
    const { highlights } = isHighlighted;

    console.log('Saving highlight', highlight);

    setIsHighlighted({
      url: isHighlighted.url,
      highlights: [{ ...highlight, id: getNextId() }, ...highlights],
    });
  };

  const updateHighlight = (
    highlightId: string,
    position: Partial<ScaledPosition>,
    content: Partial<Content>
  ) => {
    console.log('Updating highlight', highlightId, position, content);

    setIsHighlighted({
      url: isHighlighted.url,
      highlights: isHighlighted.highlights.map((h) => {
        const {
          id,
          position: originalPosition,
          content: originalContent,
          ...rest
        } = h;
        return id === highlightId
          ? {
              id,
              position: { ...originalPosition, ...position },
              content: { ...originalContent, ...content },
              ...rest,
            }
          : h;
      }),
    });
  };

  return (
    <div className="overflow-auto">
      <Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
        <SheetTrigger
          asChild
          className="absolute left-2 top-2 transform flex items-center z-10"
        >
          <Button variant="outline" size="icon" className="" type="button">
            <Menu />
          </Button>
        </SheetTrigger>
        <SheetContent side="left">
          <SheetHeader>
            <SheetTitle>Contents</SheetTitle>
            <SheetDescription>
              <ScrollArea className="pt-2">
                <ul className="sidebar__highlights">
                  {isHighlighted.highlights.map((highlight, index) => (
                    <li
                      key={index}
                      className="sidebar__highlight"
                      onClick={() => {
                        updateHash(highlight);
                      }}
                    >
                      <div>
                        <strong>{highlight.comment.text}</strong>
                        {highlight.content.text ? (
                          <blockquote style={{ marginTop: '0.5rem' }}>
                            {`${highlight.content.text.slice(0, 90).trim()}…`}
                          </blockquote>
                        ) : null}
                        {highlight.content.image ? (
                          <div
                            className="highlight__image"
                            style={{ marginTop: '0.5rem' }}
                          >
                            <img
                              src={highlight.content.image}
                              alt={'Screenshot'}
                            />
                          </div>
                        ) : null}
                      </div>
                      <div className="highlight__location">
                        Page {highlight.position.pageNumber}
                      </div>
                    </li>
                  ))}
                </ul>
              </ScrollArea>
            </SheetDescription>
          </SheetHeader>
        </SheetContent>
      </Sheet>

      <PdfLoader
        url={book}
        beforeLoad={
          <div role="status">
            <svg
              aria-hidden="true"
              className="w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600"
              viewBox="0 0 100 101"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
                fill="currentColor"
              />
              <path
                d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
                fill="currentFill"
              />
            </svg>
          </div>
        }
      >
        {(pdfDocument) => (
          <PdfHighlighter
            pdfDocument={pdfDocument}
            enableAreaSelection={(event) => event.altKey}
            onScrollChange={resetHash}
            scrollRef={(scrollTo) => {
              // @ts-ignore
              scrollViewerTo(scrollTo);

              scrollToHighlightFromHash();
            }}
            onSelectionFinished={(
              position,
              content,
              hideTipAndSelection,
              transformSelection
            ) => (
              <Tip
                onOpen={transformSelection}
                onConfirm={(comment) => {
                  addHighlight({ content, position, comment });

                  hideTipAndSelection();
                }}
              />
            )}
            highlightTransform={(
              highlight,
              index,
              setTip,
              hideTip,
              viewportToScaled,
              screenshot,
              isScrolledTo
            ) => {
              const isTextHighlight = !highlight.content?.image;

              const component = isTextHighlight ? (
                <Highlight
                  isScrolledTo={isScrolledTo}
                  position={highlight.position}
                  comment={highlight.comment}
                />
              ) : (
                <AreaHighlight
                  isScrolledTo={isScrolledTo}
                  highlight={highlight}
                  onChange={(boundingRect) => {
                    updateHighlight(
                      highlight.id,
                      { boundingRect: viewportToScaled(boundingRect) },
                      { image: screenshot(boundingRect) }
                    );
                  }}
                />
              );

              return (
                <Popup
                  popupContent={<HighlightPopup {...highlight} />}
                  onMouseOver={(popupContent) =>
                    setTip(highlight, (highlight) => popupContent)
                  }
                  onMouseOut={hideTip}
                  key={index}
                >
                  {component}
                </Popup>
              );
            }}
            highlights={isHighlighted.highlights}
          />
        )}
      </PdfLoader>
    </div>
  );
};

export default PDFDisplay;
Gr33nLight commented 4 months ago

Bumb this is happening to me too, after some digging it looks like the event "pagesinit" is not triggered with eventBus.on('pagesinit', this.onDocumentReady); so the scrollRef is not called. Any suggestions?

wyneleaf commented 4 months ago

I had the exact same issue. I think this only occurs in dev-mode cause then NextJS runs react in strict mode and then it will mount the component twice building for production and it worked for me, but obviously not ideal.

The problem as I remembered it is that the react pdf highlighter code in https://github.com/agentcooper/react-pdf-highlighter/blob/14e4e7ccc2a9cd40461f53ce7925482a08a368a4/src/components/PdfHighlighter.tsx#L178C5-L178C16 creates a new eventbus which then is not passed into the "this.view" if it already exists.

Gr33nLight commented 4 months ago

Thanks for the hint! I managed to fix it in my version by turning the eventBus in a class variable, similar to how the viewer is used, and it works in development as well :) Will submit a pull request in a couple of days (i'm unable to do it right now)

codepeach commented 3 months ago

@Gr33nLight Could you show how you were able to achieve it? It still doesn't work for me.

WangTing121314 commented 2 months ago

I had the same issue, please tell me how to work it

WangTing121314 commented 2 months ago

you can try image

codepeach commented 1 month ago

Where do I append this? Do I have to fork the repo into my project just for this fix?

fcFn commented 4 weeks ago

Where do I append this? Do I have to fork the repo into my project just for this fix?

You can use patch-package.