Prevent only editing the content of a text annotation

Q: How can I allow users to move, resize, change properties, etc. of a text annotation but not allow them to change its content?

A: Currently marking an annotation as read-only prevents you to both edit its contents and at the same time drag or resize it around.

However, with some DOM manipulation you can keep the annotation editable as normal, but at any attempt to edit its content, prevent the action from happening.

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
25
26
27
28
29
30
31
32
33
34
35
36
PSPDFKit.load({
 // your configuration
}).then(function (instance) {
  let observer;

  instance.addEventListener("annotations.press", (event) => {
    const isTextSelected =
      event.annotation instanceof PSPDFKit.Annotations.TextAnnotation;

    if (isTextSelected && event.annotation.text) {
      if (!observer) {
        observer = new MutationObserver(() => {
          // Detect when the annotation has started to be edited
          if (
            instance.contentDocument.querySelector("[contenteditable=true]")
          ) {
            instance.setEditingAnnotation(null);
          }
        });
      }

      observer.observe(
        instance.contentDocument.querySelector(".PSPDFKit-Viewport"),
        { childList: true, subtree: true }
      );
    } else if (observer) {
      observer.disconnect();
    }
  });

  instance.addEventListener("annotationSelection.change", (annotation) => {
    if (!annotation && observer) {
      observer.disconnect();
    }
  });
});

This has been tested with PSPDFKit for Web 2020.6.3