Skip to content

Build your personal knowledge base with Trilium Notes

fix(pdf): stop the auto-save from dropping the user's annotation selection

Elian Doran0311ad50b9bd
diff --git a/packages/pdfjs-viewer/e2e/annotation-save.spec.ts b/packages/pdfjs-viewer/e2e/annotation-save.spec.ts
index 3b391beea7..62f3cb56c9 100644
--- a/packages/pdfjs-viewer/e2e/annotation-save.spec.ts
+++ b/packages/pdfjs-viewer/e2e/annotation-save.spec.ts
@@ -94,6 +94,27 @@ test("does not ask to confirm leaving after the annotation was saved", async ({
expect(prompted).toBe(false);
});
+test("leaves an annotation the user has selected selected", async ({ page }) => {
+ const viewer = await openHarness(page);
+ await enterHighlightMode(viewer);
+ const box = await pageBox(viewer);
+
+ // Drawing a highlight leaves it selected, which is also the state reached by clicking an
+ // existing one: its floating toolbar — where the colour picker lives — is shown for as
+ // long as it stays selected.
+ await drawStroke(page, box, [[200, 200], [320, 240], [420, 210]]);
+ await viewer.locator(".annotationEditorLayer .highlightEditor").first().waitFor({ state: "visible" });
+ expect(await selectedEditorCount(page)).toBe(1);
+
+ // A save fires a second after the last interaction, which is exactly the gap in which the
+ // user is choosing a colour. Committing pending edits must not take the selection with it
+ // (#11059): a selected annotation is already in annotationStorage, so there is nothing to
+ // commit, and unselecting it tears down the toolbar the user is reaching for.
+ await requestBlob(page, 1);
+ await page.waitForTimeout(300);
+ expect(await selectedEditorCount(page)).toBe(1);
+});
+
test("annotations survive reopening the saved document", async ({ page, context }) => {
const viewer = await openHarness(page);
await enterInkMode(viewer);
@@ -135,6 +156,22 @@ async function enterInkMode(viewer: FrameLocator) {
await viewer.locator(".annotationEditorLayer").first().waitFor({ state: "attached" });
}
+async function enterHighlightMode(viewer: FrameLocator) {
+ await viewer.locator("#editorHighlightButton").click();
+ await viewer.locator(".annotationEditorLayer").first().waitFor({ state: "attached" });
+}
+
+/**
+ * How many editors pdf.js currently shows as selected. `selectedEditor` is the class that
+ * carries the floating toolbar, so it stands in for "the user's selection is still there".
+ */
+function selectedEditorCount(page: Page): Promise<number> {
+ const frame = page.frame({ url: /viewer\.html/ });
+ if (!frame) throw new Error("Viewer frame not found");
+
+ return frame.evaluate(() => document.querySelectorAll(".annotationEditorLayer .selectedEditor").length);
+}
+
async function pageBox(viewer: FrameLocator) {
const box = await viewer.locator(".page").first().boundingBox();
expect(box).not.toBeNull();
diff --git a/packages/pdfjs-viewer/src/bootstrap.spec.ts b/packages/pdfjs-viewer/src/bootstrap.spec.ts
index 64180788ab..c14ed982c8 100644
--- a/packages/pdfjs-viewer/src/bootstrap.spec.ts
+++ b/packages/pdfjs-viewer/src/bootstrap.spec.ts
@@ -30,7 +30,7 @@ afterEach(() => {
/** Marks an annotation-editing tool as active, as pdf.js does while a tool is selected. */
function startEditing(mode = 15) {
- setAnnotationEditorUIManager({ getMode: () => mode, getActive: () => null, unselectAll: vi.fn() });
+ setAnnotationEditorUIManager({ getMode: () => mode, getActive: () => null, hasSelection: false, unselectAll: vi.fn() });
}
/** Adds the `.page` element pdf.js renders each page into, and returns a child of it. */
@@ -251,7 +251,7 @@ describe("producing the saved document", () => {
viewer = await installViewerApp(allFeaturesPdf());
(globalThis as any).pdfjsLib = { getDocument };
const unselectAll = vi.fn();
- setAnnotationEditorUIManager({ getMode: () => 15, getActive: () => null, unselectAll });
+ setAnnotationEditorUIManager({ getMode: () => 15, getActive: () => null, hasSelection: false, unselectAll });
manageSave();
viewer.sendFromParent({ type: "trilium-request-blob" });
diff --git a/packages/pdfjs-viewer/src/editing.spec.ts b/packages/pdfjs-viewer/src/editing.spec.ts
index be097755e2..c41e701857 100644
--- a/packages/pdfjs-viewer/src/editing.spec.ts
+++ b/packages/pdfjs-viewer/src/editing.spec.ts
@@ -15,6 +15,7 @@ function buildManager(overrides: Partial<AnnotationEditorUIManagerLike> = {}): A
return {
getMode: () => INK_MODE,
getActive: () => null,
+ hasSelection: false,
unselectAll: vi.fn(),
...overrides
};
@@ -57,6 +58,17 @@ describe("commitPendingAnnotationEdits", () => {
expect(whileTyping.unselectAll).not.toHaveBeenCalled();
});
+ it("leaves a selected annotation alone", () => {
+ // pdf.js only sets an *active* editor when one enters edit mode, so a selection made by
+ // clicking reaches this with getActive() === null. Committing it would call unselectAll(),
+ // which hides the floating toolbar the colour picker lives in — a second after the user
+ // opened it (#11059). There is nothing to commit either way: a selected annotation is
+ // already in annotationStorage; only an uncommitted drawing session needs the call.
+ const withSelection = buildManager({ hasSelection: true });
+ commitPendingAnnotationEdits(false, withSelection);
+ expect(withSelection.unselectAll).not.toHaveBeenCalled();
+ });
+
it("never lets a commit failure propagate into the save", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const manager = buildManager({
diff --git a/packages/pdfjs-viewer/src/editing.ts b/packages/pdfjs-viewer/src/editing.ts
index 2bb8f638f7..784675cee4 100644
--- a/packages/pdfjs-viewer/src/editing.ts
+++ b/packages/pdfjs-viewer/src/editing.ts
@@ -16,6 +16,9 @@ export const ANNOTATION_EDITOR_MODE_NONE = 0;
export interface AnnotationEditorUIManagerLike {
getMode(): number;
getActive(): { isInEditMode(): boolean } | null;
+ /** Whether any editor is selected. Distinct from {@link getActive}, which pdf.js only sets
+ * once an editor is being *edited* — clicking an annotation selects it without activating it. */
+ readonly hasSelection: boolean;
unselectAll(): void;
}
@@ -51,14 +54,22 @@ export function isAnnotationEditingActive(uiManager: AnnotationEditorUIManagerLi
/**
* Commits pending annotation edits into `annotationStorage` so that a subsequent
* `saveDocument()` includes them — unless the user is literally mid-interaction: committing
- * during an ink stroke would cut the stroke short, and committing a focused free-text editor
- * would steal the caret. Skipped edits are picked up by a later save, re-requested by the
- * interaction-end listeners in `manageSave()`.
+ * during an ink stroke would cut the stroke short, committing a focused free-text editor would
+ * steal the caret, and committing while an annotation is selected would drop the selection.
+ * Skipped edits are picked up by a later save, re-requested by the interaction-end listeners in
+ * `manageSave()`.
*/
export function commitPendingAnnotationEdits(isPointerDown: boolean, uiManager: AnnotationEditorUIManagerLike | null = getAnnotationEditorUIManager()) {
try {
if (!uiManager || uiManager.getMode() === ANNOTATION_EDITOR_MODE_NONE) return;
if (isPointerDown || uiManager.getActive()?.isInEditMode()) return;
+ // A selection is not pending work: whatever is selected is already in annotationStorage,
+ // so unselectAll() has nothing to commit here — it would only deselect, hiding the
+ // floating toolbar the colour picker lives in and closing any open comment popup, a
+ // second after the user opened one (#11059). The call is needed for an uncommitted
+ // drawing session, and that never coexists with a selection: the pen's session leaves
+ // nothing selected, while each free-hand highlight stroke commits as it ends.
+ if (uiManager.hasSelection) return;
// unselectAll() commits the active editor and ends any in-progress drawing session —
// the same code path pdf.js runs when Escape is pressed.
diff --git a/packages/pdfjs-viewer/src/upstream_contract.spec.ts b/packages/pdfjs-viewer/src/upstream_contract.spec.ts
index 295d1f5024..c4bc12c49c 100644
--- a/packages/pdfjs-viewer/src/upstream_contract.spec.ts
+++ b/packages/pdfjs-viewer/src/upstream_contract.spec.ts
@@ -179,6 +179,20 @@ describe("PDFDocumentProxy shape", () => {
expect(order.some((item: any) => Array.isArray(item))).toBe(false);
});
+ it("still lets the editing manager report a selection apart from an active editor", async () => {
+ // commitPendingAnnotationEdits() reads `hasSelection` to know a save has nothing to
+ // commit. Were it renamed, the read would be `undefined` — falsy, so the guard would
+ // quietly stop guarding and every save would again drop the user's selection (#11059).
+ // `getActive()` is not a substitute: pdf.js sets it only once an editor is being edited.
+ const { AnnotationEditorUIManager } = await import("pdfjs-dist/legacy/build/pdf.mjs") as any;
+ expect(AnnotationEditorUIManager).toBeDefined();
+
+ const prototype = AnnotationEditorUIManager.prototype;
+ expect(Object.getOwnPropertyDescriptor(prototype, "hasSelection")?.get).toEqual(expect.any(Function));
+ expect(prototype.getActive).toEqual(expect.any(Function));
+ expect(prototype.unselectAll).toEqual(expect.any(Function));
+ });
+
it("keeps annotationStorage's modification hooks reachable", () => {
// `onSetModified` is a private monkey-patch point (custom.ts, annotations.ts) with no
// public type. We cannot bind its contract, but we can catch it disappearing.