Listen to annotation’s hover event

Q: How to listen to text annotations hover event?

A: Annotation’s “hover” events are not emitted. However, achieving something similar to listening to those is not very difficult. For most annotation types, the following snippet would get the job done:

PSPDFKit.load(defaultConfiguration).then(instance => {
  instance.contentDocument.addEventListener("mouseover", ({ target }) => {
    if (target && (target.closest(".PSPDFKit-Annotation") || target.classList.contains("PSPDFKit-Annotation"))) {
      // The annotation ID can be obtained from the `data-annotation-id` attribute of
      // the closest `.PSPDFKit-Annotation` element.
      console.log('Annotation hovered')
    }
  });
});

However, some annotation types (text, markup and links) use custom hit testing logic that prevents us from getting the “hover” event this way. Instead, we can make use of the Custom Renderers API to achieve the same result. Putting both together would result in the following snippet:

PSPDFKit.load({
  ...defaultConfiguration,
  customRenderers: {
    Annotation: ({ annotation }) => {
      if (annotation instanceof PSPDFKit.Annotations.TextAnnotation || annotation instanceof PSPDFKit.Annotations.MarkupAnnotation || annotation instanceof PSPDFKit.Annotations.LinkAnnotation) {
        const node = instance.contentDocument.createElement("div");
        node.style.cssText =
          "position: absolute; width: 100%; height: 100%; pointer-events: all";
        const mouseoverListener = function() {
          console.log(`Hovered text annotation with ID: ${annotation.id}`);
        };
        node.addEventListener("mouseover", mouseoverListener);
        return {
          node,
          append: true
        };
      }
    }
  }
}).then(instance => {
  instance.contentDocument.addEventListener("mouseover", ({ target }) => {
    if (target && (target.closest(".PSPDFKit-Annotation") || target.classList.contains("PSPDFKit-Annotation"))) {
      // The annotation ID can be obtained from the `data-annotation-id` attribute of
      // the closest `.PSPDFKit-Annotation` element.
      console.log('Annotation hovered')
    }
  });
});

This has been tested with PSPDFKit for Web 2019.4.1