Get visible annotations in current page

Q: How can I get the visible annotations on the current page?

A: In order to retrieve the annotations that are currently visible on the page, you need to pass its current visible dimensions and coordinates to instance.transformContentClientToPageSpace() to retrieve the visible page bounding box in page units, which will allow you to compare them to the page annotation’s bounding boxes.

The following snippet shows an example of how to achieve this for the current page (it can be repeated for the previous and next pages if needed):

function getPageVisibleRect(pageIndex) {
  // Page DOM element
  const pageEl = instance.contentDocument.querySelector(
    `.PSPDFKit-Page[data-page-index="${pageIndex}"]`
  );
  const pageBoundingClientRect = pageEl.getBoundingClientRect();
  // Viewport DOM element
  const viewportEl = instance.contentDocument.querySelector(
    ".PSPDFKit-Viewport"
  );
  // Toolbar DOM element, needs offsetting
  const toolbarEl = instance.contentDocument.querySelector(".PSPDFKit-Toolbar");
  // Get visible page area in page units
  return instance.transformContentClientToPageSpace(
    new PSPDFKit.Geometry.Rect({
      left: Math.max(pageBoundingClientRect.left, 0),
      top: Math.max(pageBoundingClientRect.top, toolbarEl.scrollHeight),
      width: Math.min(pageEl.clientWidth, viewportEl.clientWidth),
      height: Math.min(pageEl.clientHeight, viewportEl.clientHeight)
    }),
    pageIndex
  );
}

function detectVisibleAnnotations() {
  const pageIndex = instance.viewState.currentPageIndex;
  const pageRect = getPageVisibleRect(pageIndex);
  // Traverse page annotations and check if their bounding box
  // overlaps the visible area
  instance.getAnnotations(pageIndex).then(annotations => {
    annotations.forEach(annotation => {
      if (annotation.boundingBox.isRectOverlapping(pageRect)) {
        // Visible annotation detected, log it (or keep a reference to it somewhere)
        console.log(annotation.toJS());
      }
    });
  });
}

// Listen to the "viewState.zoom.change" event, triggered on every zoom change
instance.addEventListener("viewState.zoom.change", detectVisibleAnnotations);
// Listen to the "viewState.currentPageIndex.change" event, triggered on every zoom change
instance.addEventListener(
  "viewState.currentPageIndex.change",
  detectVisibleAnnotations
);
// Detect visible annotations again whenever they change
instance.addEventListener("annotations.create", detectVisibleAnnotations);
instance.addEventListener("annotations.update", detectVisibleAnnotations);
instance.addEventListener("annotations.delete", detectVisibleAnnotations);

This has been tested with PSPDFKit for Web 2020.2.4.