Keep current annotation tool enabled

Q: I want to implement a persistent annotation button that remains on so users can quickly add multiple annotations.

A: After a new annotation is created, the PSPDFKit.ViewState#interactionMode goes back to the default value of null, meaning that no interaction mode is enabled.

You can override this behavior by preserving the previous interaction mode after an annotation has been created by adding a handler of viewState.change events to programmatically change the interaction mode back to the desired one if needed.

The following code snippet shows how to keep the text annotation tool selected after a text annotation has been created. You can adapt it for other types of annotations if you wish so:

Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
let interactionMode = instance.viewState.interactionMode;
let textAnnotationCreation = false;

instance.addEventListener("viewState.change", viewState => {
  const newInteractionMode = viewState.interactionMode;
  if (
    newInteractionMode === null &&
    interactionMode === PSPDFKit.InteractionMode.TEXT &&
    textAnnotationCreation
  ) {
    instance.setViewState(state =>
      state.set("interactionMode", PSPDFKit.InteractionMode.TEXT)
    );
    textAnnotationCreation = false;
  }
  interactionMode = newInteractionMode;
});

instance.addEventListener("annotations.create", annotations => {
  textAnnotationCreation =
    annotations.size === 1 &&
    annotations.get(0) instanceof PSPDFKit.Annotations.TextAnnotation &&
    interactionMode === PSPDFKit.InteractionMode.TEXT;
});

This has been tested with PSPDFKit for Web 2019.5.3.