Skip to content

Build your personal knowledge base with Trilium Notes

feat(pdf): link to a page or an annotation (closes #8635)

Elian Doran7bf4d0788cac
diff --git a/apps/client/src/components/note_context.ts b/apps/client/src/components/note_context.ts
index eade4b02ef..ba0fdb8575 100644
--- a/apps/client/src/components/note_context.ts
+++ b/apps/client/src/components/note_context.ts
@@ -58,6 +58,8 @@ export interface NoteContextDataMap {
currentPage: number;
scrollToPage(page: number): void;
requestThumbnail(page: number): void;
+ /** Copies a reference that opens the PDF at `page`. */
+ copyReference(page: number): void;
};
pdfAttachments: {
attachments: PdfAttachment[];
@@ -70,6 +72,8 @@ export interface NoteContextDataMap {
pdfAnnotations: {
annotations: PdfAnnotationInfo[];
scrollToAnnotation(annotationId: string, pageNumber: number): void;
+ /** Copies a reference that opens the PDF at the annotation. */
+ copyReference(annotationId: string, pageNumber: number): void;
};
/** Published by a board, so the right pane can list its columns and scroll the board to one. */
boardColumns: {
diff --git a/apps/client/src/services/link.spec.ts b/apps/client/src/services/link.spec.ts
index 26f34e3fa5..d3d5ecc4fe 100644
--- a/apps/client/src/services/link.spec.ts
+++ b/apps/client/src/services/link.spec.ts
@@ -152,6 +152,14 @@ describe("parseNavigationStateFromUrl", () => {
expect((card as any).viewScope).toMatchObject({ card: "card00000001" });
});
+ it("carries a PDF reference through, for the page and for an annotation on it", () => {
+ const page = parseNavigationStateFromUrl("#root/aaaaaaaaaaaa?page=5");
+ expect((page as any).viewScope).toMatchObject({ page: "5" });
+
+ const annotation = parseNavigationStateFromUrl("#root/aaaaaaaaaaaa?page=5&annotation=12R");
+ expect((annotation as any).viewScope).toMatchObject({ page: "5", annotation: "12R" });
+ });
+
it("returns empty object when the note path does not match the id pattern", () => {
// hash present at index 0, but the path is too short to be a valid note id
expect(parseNavigationStateFromUrl("#ab")).toStrictEqual({});
@@ -233,6 +241,17 @@ describe("calculateHash", () => {
.toBe("#root/abc?card=card00000001");
});
+ it("writes a PDF reference back into the hash it was read from", () => {
+ const hash = calculateHash({
+ notePath: "root/abc",
+ viewScope: { page: "5", annotation: "12R" }
+ } as any);
+ expect(hash).toBe("#root/abc?page=5&annotation=12R");
+ const read = `http://localhost:8080/#root/aaaaaaaaaaaa${hash.slice("#root/abc".length)}`;
+ expect(parseNavigationStateFromUrl(read))
+ .toMatchObject({ viewScope: { page: "5", annotation: "12R" } });
+ });
+
it("omits params that are at their defaults", () => {
const hash = calculateHash({
notePath: "root/abc",
@@ -891,6 +910,14 @@ describe("getReferenceLinkTitle / getReferenceLinkTitleSync", () => {
expect(linkService.getReferenceLinkTitleSync(href)).toBe("Board: To Do");
});
+ it("names the PDF a page reference points at, and the page after it", async () => {
+ const pdf = buildNote({ title: "Paper" });
+ const href = `#root/${pdf.noteId}?page=5&annotation=12R`;
+
+ expect(await linkService.getReferenceLinkTitle(href)).toBe("Paper");
+ expect(linkService.getReferenceLinkTitleSync(href)).toBe("Paper - pdf.page_reference");
+ });
+
it("getReferenceLinkTitleSync returns [missing note] when the note is not in cache", () => {
const orig = froca.getNoteFromCache;
froca.getNoteFromCache = vi.fn(() => null) as unknown as typeof froca.getNoteFromCache;
@@ -979,6 +1006,16 @@ describe("loadReferenceLinkTitle", () => {
expect($column.hasClass("color-FF8800")).toBe(true);
});
+ it("appends the page a PDF reference points at", async () => {
+ const pdf = buildNote({ title: "Paper" });
+ const $el = $("<span>");
+
+ await linkService.loadReferenceLinkTitle($el, `#root/${pdf.noteId}?page=5&annotation=12R`);
+
+ expect($el.text()).toBe("Paperpdf.page_reference");
+ expect($el.find("small span").hasClass("bx-file")).toBe(true);
+ });
+
it("falls back to a column glyph for a reference carrying no icon of its own", async () => {
const board = buildNote({ title: "Board" });
const $el = $("<span>");
diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.ts
index a231e218f4..518e2d0897 100644
--- a/apps/client/src/services/link.ts
+++ b/apps/client/src/services/link.ts
@@ -97,6 +97,17 @@ export interface ViewScope {
* is.
*/
card?: string;
+ /**
+ * The PDF page a reference points at, which the PDF viewer turns to once it has opened the
+ * document. Consumed once, as `bookmark` is.
+ */
+ page?: string;
+ /**
+ * The id of the PDF annotation a reference points at, which the viewer scrolls to on
+ * {@link page}. A reference to an annotation always carries its page too, so a deleted
+ * annotation still leaves the reader on the right page.
+ */
+ annotation?: string;
}
/**
@@ -120,7 +131,7 @@ const MAX_SPLIT_PANES_IN_HASH = 8;
/** Hash parameters that belong to a pane's view scope rather than to the window as a whole. */
const VIEW_SCOPE_PARAMS = ["viewMode", "attachmentId", "bookmark", "column", "columnTitle",
- "columnIcon", "columnColor", "card"];
+ "columnIcon", "columnColor", "card", "page", "annotation"];
interface CreateLinkOptions {
title?: string;
@@ -262,6 +273,8 @@ export function calculateHash(
viewScope.columnIcon ? { columnIcon: viewScope.columnIcon } : null,
viewScope.columnColor ? { columnColor: viewScope.columnColor } : null,
viewScope.card ? { card: viewScope.card } : null,
+ viewScope.page ? { page: viewScope.page } : null,
+ viewScope.annotation ? { annotation: viewScope.annotation } : null,
viewScope.searchTerms?.length
? { searchTerms: viewScope.searchTerms.map(encodeURIComponent).join(",") }
: null,
@@ -687,6 +700,13 @@ async function loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string | n
));
}
+ if (viewScope?.page) {
+ $el.append($("<small>").append(
+ $("<span>").addClass("bx bx-file"),
+ document.createTextNode(t("pdf.page_reference", { pageNumber: viewScope.page }))
+ ));
+ }
+
if (viewScope?.columnTitle) {
$el.append($("<small>")
.addClass(cssClassManager.createClassForColor(viewScope.columnColor ?? null))
@@ -756,6 +776,10 @@ function getReferenceLinkTitleSync(href: string) {
return `${note.title} - ${viewScope.bookmark}`;
}
+ if (viewScope?.page) {
+ return `${note.title} - ${t("pdf.page_reference", { pageNumber: viewScope.page })}`;
+ }
+
return note.title;
}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 683a809b30..f27d9e4240 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4014,7 +4014,9 @@
"annotation_drawing": "Drawing on page {{pageNumber}}",
"annotation_highlight": "Highlight on page {{pageNumber}}",
"annotation_note": "Note on page {{pageNumber}}",
- "annotation_text_box": "Text box on page {{pageNumber}}"
+ "annotation_text_box": "Text box on page {{pageNumber}}",
+ "copy_reference": "Copy reference",
+ "page_reference": "Page {{pageNumber}}"
},
"platform_indicator": {
"available_on": "Available on {{platform}}"
diff --git a/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.spec.tsx b/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.spec.tsx
index 11cab555e1..45f153edd2 100644
--- a/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.spec.tsx
+++ b/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.spec.tsx
@@ -2,6 +2,7 @@ import { render } from "preact";
import { afterEach, describe, expect, it, vi } from "vitest";
import FNote from "../../../entities/fnote";
+import contextMenu from "../../../menus/context_menu";
import options from "../../../services/options";
import PdfAnnotations, { isDark } from "./PdfAnnotations";
@@ -9,7 +10,11 @@ import PdfAnnotations, { isDark } from "./PdfAnnotations";
// arrive through hooks that need the whole app context, so they are handed over directly here.
const shown = vi.hoisted(() => ({
note: null as FNote | null,
- annotations: null as { annotations: PdfAnnotationInfo[]; scrollToAnnotation: (id: string, page: number) => void } | null
+ annotations: null as {
+ annotations: PdfAnnotationInfo[];
+ scrollToAnnotation: (id: string, page: number) => void;
+ copyReference: (id: string, page: number) => void;
+ } | null
}));
// i18next is not initialised for client specs, so t() would render every label as an empty
// string. Echoing the key and its interpolations instead keeps the assertions about which
@@ -45,14 +50,18 @@ function annotation(overrides: Partial<PdfAnnotationInfo>): PdfAnnotationInfo {
};
}
-function renderPanel(annotations: PdfAnnotationInfo[], scrollToAnnotation: (id: string, page: number) => void = () => {}) {
+function renderPanel(
+ annotations: PdfAnnotationInfo[],
+ scrollToAnnotation: (id: string, page: number) => void = () => {},
+ copyReference: (id: string, page: number) => void = () => {}
+) {
// The surrounding RightPanelWidget reads which panels the user collapsed from the options.
options.set("rightPaneCollapsedItems", JSON.stringify([]));
const container = document.createElement("div");
document.body.append(container);
shown.note = pdfNote();
- shown.annotations = { annotations, scrollToAnnotation };
+ shown.annotations = { annotations, scrollToAnnotation, copyReference };
render(<PdfAnnotations />, container);
return container;
}
@@ -72,7 +81,7 @@ describe("PdfAnnotations", () => {
options.set("rightPaneCollapsedItems", JSON.stringify([]));
shown.note = { type: "text", mime: "text/html" } as unknown as FNote;
- shown.annotations = { annotations: [ annotation({}) ], scrollToAnnotation: () => {} };
+ shown.annotations = { annotations: [ annotation({}) ], scrollToAnnotation: () => {}, copyReference: () => {} };
const notPdf = document.createElement("div");
document.body.append(notPdf);
render(<PdfAnnotations />, notPdf);
@@ -89,6 +98,21 @@ describe("PdfAnnotations", () => {
expect(scrollTo).toHaveBeenCalledWith("5R", 3);
});
+ it("copies a reference to an annotation from its context menu", () => {
+ const show = vi.spyOn(contextMenu, "show").mockResolvedValue(undefined);
+ const copyReference = vi.fn();
+ const container = renderPanel([ annotation({ id: "5R", pageNumber: 3 }) ], () => {}, copyReference);
+
+ const row = container.querySelector(".pdf-annotation-item") as HTMLElement;
+ row.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
+ expect(show).toHaveBeenCalledOnce();
+ const [ item ] = show.mock.calls[0][0].items as { title: string; handler: () => void }[];
+ expect(item.title).toBe("pdf.copy_reference({})");
+ item.handler();
+ expect(copyReference).toHaveBeenCalledWith("5R", 3);
+ show.mockRestore();
+ });
+
it("falls back to a generic label and icon for a kind it has no specific ones for", () => {
// A sticky note with no text is named a note; a kind the sidebar has no icon for gets the
// generic comment icon rather than none.
diff --git a/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.tsx b/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.tsx
index 5b2315045c..9b6af21b82 100644
--- a/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.tsx
+++ b/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.tsx
@@ -2,6 +2,7 @@ import "./PdfAnnotations.css";
import clsx from "clsx";
+import contextMenu from "../../../menus/context_menu";
import { t } from "../../../services/i18n";
import { useActiveNoteContext, useGetContextData, useNoteProperty } from "../../react/hooks";
import Icon from "../../react/Icon";
@@ -36,6 +37,7 @@ export default function PdfAnnotations() {
key={annotation.id}
annotation={annotation}
onNavigate={annotationsData.scrollToAnnotation}
+ onCopyReference={annotationsData.copyReference}
/>
))}
</div>
@@ -45,10 +47,12 @@ export default function PdfAnnotations() {
function PdfAnnotationItem({
annotation,
- onNavigate
+ onNavigate,
+ onCopyReference
}: {
annotation: PdfAnnotationInfo;
onNavigate: (annotationId: string, pageNumber: number) => void;
+ onCopyReference: (annotationId: string, pageNumber: number) => void;
}) {
// Contents on a highlight or a drawing is a remark somebody attached to it, so the row reads
// as a comment. A free-text box's contents are the box itself, so it keeps its own icon.
@@ -67,6 +71,7 @@ function PdfAnnotationItem({
isDark(annotation.color) && "tinted-dark"
)}
onClick={() => onNavigate(annotation.id, annotation.pageNumber)}
+ onContextMenu={(e) => showCopyReferenceMenu(e, () => onCopyReference(annotation.id, annotation.pageNumber))}
style={annotation.color ? { backgroundColor: annotation.color } : undefined}
>
<Icon icon={icon} />
@@ -102,6 +107,17 @@ export function isDark(color: string | null) {
return (0.299 * r + 0.587 * g + 0.114 * b) < 140;
}
+/** Opens the context menu of a page or an annotation in the PDF sidebar. */
+export function showCopyReferenceMenu(e: MouseEvent, copyReference: () => void) {
+ e.preventDefault();
+ void contextMenu.show({
+ x: e.pageX,
+ y: e.pageY,
+ items: [ { title: t("pdf.copy_reference"), uiIcon: "bx bx-copy", handler: copyReference } ],
+ selectMenuItemHandler: () => {}
+ });
+}
+
/** Names an annotation that carries no text of its own, by kind and page. */
function describeUntitled({ type, pageNumber }: PdfAnnotationInfo) {
switch (type) {
diff --git a/apps/client/src/widgets/sidebar/pdf/PdfPages.spec.tsx b/apps/client/src/widgets/sidebar/pdf/PdfPages.spec.tsx
index 97aa9785e5..3106763edd 100644
--- a/apps/client/src/widgets/sidebar/pdf/PdfPages.spec.tsx
+++ b/apps/client/src/widgets/sidebar/pdf/PdfPages.spec.tsx
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type NoteContext from "../../../components/note_context";
import FNote from "../../../entities/fnote";
+import contextMenu from "../../../menus/context_menu";
import options from "../../../services/options";
import PdfPages from "./PdfPages";
@@ -12,7 +13,13 @@ import PdfPages from "./PdfPages";
const shown = vi.hoisted(() => ({
note: null as FNote | null,
noteContext: null as NoteContext | null,
- pages: null as { totalPages: number; currentPage: number; scrollToPage: (page: number) => void; requestThumbnail: (page: number) => void } | null
+ pages: null as {
+ totalPages: number;
+ currentPage: number;
+ scrollToPage: (page: number) => void;
+ requestThumbnail: (page: number) => void;
+ copyReference: (page: number) => void;
+ } | null
}));
// react-window virtualises rows off the container's laid-out height, which happy-dom does not
// have; and under vitest it resolves a second copy of the hooks and cannot render at all. What the
@@ -49,7 +56,7 @@ beforeEach(() => {
shown.note = { noteId: "note-1", type: "file", mime: "application/pdf" } as unknown as FNote;
shown.noteContext = { ntxId: "ntx-1" } as NoteContext;
- shown.pages = { totalPages: 3, currentPage: 2, scrollToPage: vi.fn(), requestThumbnail: vi.fn() };
+ shown.pages = { totalPages: 3, currentPage: 2, scrollToPage: vi.fn(), requestThumbnail: vi.fn(), copyReference: vi.fn() };
container = document.createElement("div");
document.body.append(container);
@@ -90,6 +97,20 @@ describe("PdfPages", () => {
expect(shown.pages?.scrollToPage).toHaveBeenCalledWith(3);
});
+ it("copies a reference to a page from its context menu", () => {
+ const show = vi.spyOn(contextMenu, "show").mockResolvedValue(undefined);
+ renderPanel();
+
+ const cell = container.querySelectorAll(".pdf-page-item")[2] as HTMLElement;
+ cell.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
+ expect(show).toHaveBeenCalledOnce();
+ const [ item ] = show.mock.calls[0][0].items as { title: string; handler: () => void }[];
+ expect(item.title).toBe("pdf.copy_reference({})");
+ item.handler();
+ expect(shown.pages?.copyReference).toHaveBeenCalledWith(3);
+ show.mockRestore();
+ });
+
it("shows a thumbnail rendered for its own context, and ignores another viewer's", () => {
renderPanel();
@@ -110,14 +131,14 @@ describe("PdfPages", () => {
renderPanel();
expect(container.querySelector(".pdf-pages-list")).toBeNull();
- shown.pages = { totalPages: 3, currentPage: 1, scrollToPage: vi.fn(), requestThumbnail: vi.fn() };
+ shown.pages = { totalPages: 3, currentPage: 1, scrollToPage: vi.fn(), requestThumbnail: vi.fn(), copyReference: vi.fn() };
shown.note = { noteId: "note-2", type: "text", mime: "text/html" } as unknown as FNote;
renderPanel();
expect(container.querySelector(".pdf-pages-list")).toBeNull();
});
it("says so when the document has no pages", () => {
- shown.pages = { totalPages: 0, currentPage: 0, scrollToPage: vi.fn(), requestThumbnail: vi.fn() };
+ shown.pages = { totalPages: 0, currentPage: 0, scrollToPage: vi.fn(), requestThumbnail: vi.fn(), copyReference: vi.fn() };
renderPanel();
expect(container.querySelector(".no-pages")).not.toBeNull();
});
diff --git a/apps/client/src/widgets/sidebar/pdf/PdfPages.tsx b/apps/client/src/widgets/sidebar/pdf/PdfPages.tsx
index 78c4463416..622014dd0b 100644
--- a/apps/client/src/widgets/sidebar/pdf/PdfPages.tsx
+++ b/apps/client/src/widgets/sidebar/pdf/PdfPages.tsx
@@ -9,6 +9,7 @@ import { NoteContextDataMap } from "../../../components/note_context";
import { t } from "../../../services/i18n";
import { useActiveNoteContext, useGetContextData, useNoteProperty } from "../../react/hooks";
import RightPanelWidget from "../RightPanelWidget";
+import { showCopyReferenceMenu } from "./PdfAnnotations";
const ROW_HEIGHT = 180;
const COLUMNS = 2;
@@ -84,7 +85,8 @@ function PdfPagesList({ pagesData, ntxId }: { pagesData: NoteContextDataMap["pdf
thumbnails,
currentPage: pagesData.currentPage,
requestThumbnail,
- scrollToPage: pagesData.scrollToPage
+ scrollToPage: pagesData.scrollToPage,
+ copyReference: pagesData.copyReference
}}
style={{ height: `${containerHeight}px` }}
/>
@@ -99,10 +101,11 @@ interface PdfPageRowData {
currentPage: number;
requestThumbnail: (page: number) => void;
scrollToPage: (page: number) => void;
+ copyReference: (page: number) => void;
}
function PdfPageRow({ index, style, ...data }: RowComponentProps<PdfPageRowData>) {
- const { totalPages, thumbnails, currentPage, requestThumbnail, scrollToPage } = data;
+ const { totalPages, thumbnails, currentPage, requestThumbnail, scrollToPage, copyReference } = data;
const startPage = index * COLUMNS + 1;
const pages = Array.from({ length: COLUMNS }, (_, i) => startPage + i).filter(p => p <= totalPages);
@@ -116,18 +119,20 @@ function PdfPageRow({ index, style, ...data }: RowComponentProps<PdfPageRowData>
thumbnail={thumbnails.get(pageNumber)}
requestThumbnail={requestThumbnail}
scrollToPage={scrollToPage}
+ copyReference={copyReference}
/>
))}
</div>
) as React.ReactElement;
}
-function PdfPageCell({ pageNumber, isActive, thumbnail, requestThumbnail, scrollToPage }: {
+function PdfPageCell({ pageNumber, isActive, thumbnail, requestThumbnail, scrollToPage, copyReference }: {
pageNumber: number;
isActive: boolean;
thumbnail?: string;
requestThumbnail: (page: number) => void;
scrollToPage: (page: number) => void;
+ copyReference: (page: number) => void;
}) {
const hasRequested = useRef(false);
@@ -142,6 +147,7 @@ function PdfPageCell({ pageNumber, isActive, thumbnail, requestThumbnail, scroll
<div
className={`pdf-page-item ${isActive ? 'active' : ''}`}
onClick={() => scrollToPage(pageNumber)}
+ onContextMenu={(e) => showCopyReferenceMenu(e, () => copyReference(pageNumber))}
>
<div className="pdf-page-thumbnail">
{thumbnail ? (
diff --git a/apps/client/src/widgets/type_widgets/file/Pdf.spec.tsx b/apps/client/src/widgets/type_widgets/file/Pdf.spec.tsx
index f8e4222e0f..fee790bd43 100644
--- a/apps/client/src/widgets/type_widgets/file/Pdf.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Pdf.spec.tsx
@@ -47,6 +47,8 @@ const download = vi.hoisted(() => vi.fn());
vi.mock("../../../services/open", () => ({
default: { download, getUrlForDownload: (path: string) => `/${path}` }
}));
+const copyReferenceWithToast = vi.hoisted(() => vi.fn());
+vi.mock("../../../services/clipboard_ext", () => ({ copyReferenceWithToast }));
const { default: PdfPreview } = await import("./Pdf");
@@ -61,6 +63,8 @@ beforeEach(() => {
contextData = {};
noteContext = {
ntxId: "ntx-1",
+ notePath: "root/parent/note-1",
+ viewScope: {},
setContextData: vi.fn((key: string, value: unknown) => { contextData[key] = value; }),
getContextData: vi.fn((key: string) => contextData[key]),
isActive: () => true
@@ -153,6 +157,52 @@ describe("PdfPreview", () => {
expect(posted).toHaveBeenLastCalledWith({ type: "trilium-scroll-to-annotation", annotationId: "5R", pageNumber: 2 }, window.location.origin);
});
+ it("scrolls to the place a link names once the viewer lists its annotations, and only once", () => {
+ const posted = recordPostsToViewer();
+ noteContext.viewScope = { page: "5", annotation: "12R" };
+
+ // A switch that arrives while the viewer is still loading has nothing to talk to yet.
+ eventHandlers.get("noteSwitched")?.({ noteContext: { ntxId: "ntx-1", note: NOTE } });
+ expect(posted).not.toHaveBeenCalled();
+
+ fromThisViewer({ type: "pdfjs-viewer-annotations", annotations: [] });
+ expect(posted).toHaveBeenCalledExactlyOnceWith(
+ { type: "trilium-scroll-to-annotation", annotationId: "12R", pageNumber: 5 }, window.location.origin);
+ expect(noteContext.viewScope).toEqual({ page: undefined, annotation: undefined });
+
+ // The list is sent again on every edit; the link is not followed again.
+ fromThisViewer({ type: "pdfjs-viewer-annotations", annotations: [] });
+ expect(posted).toHaveBeenCalledOnce();
+ });
+
+ it("follows a link to the PDF it already shows, but not one meant for another pane", () => {
+ const posted = recordPostsToViewer();
+ fromThisViewer({ type: "pdfjs-viewer-annotations", annotations: [] });
+
+ noteContext.viewScope = { page: "3" };
+ eventHandlers.get("noteSwitched")?.({ noteContext: { ntxId: "ntx-2", note: NOTE } });
+ expect(posted).not.toHaveBeenCalled();
+
+ eventHandlers.get("noteSwitched")?.({ noteContext: { ntxId: "ntx-1", note: NOTE } });
+ expect(posted).toHaveBeenCalledExactlyOnceWith(
+ { type: "trilium-scroll-to-annotation", annotationId: undefined, pageNumber: 3 }, window.location.origin);
+ });
+
+ it("copies a reference to a page, or to an annotation the document already holds", () => {
+ fromThisViewer({ type: "pdfjs-viewer-page-info", totalPages: 12, currentPage: 1 });
+ (contextData.pdfPages as any).copyReference(7);
+ expect(copyReferenceWithToast).toHaveBeenLastCalledWith("#root/parent/note-1?page=7");
+
+ fromThisViewer({ type: "pdfjs-viewer-annotations", annotations: [] });
+ (contextData.pdfAnnotations as any).copyReference("12R", 5);
+ expect(copyReferenceWithToast).toHaveBeenLastCalledWith("#root/parent/note-1?page=5&annotation=12R");
+
+ // An annotation drawn in this session has only its editor's id, which the next load of
+ // the document does not reuse, so its reference names the page alone.
+ (contextData.pdfAnnotations as any).copyReference("pdfjs_internal_editor_0", 5);
+ expect(copyReferenceWithToast).toHaveBeenLastCalledWith("#root/parent/note-1?page=5");
+ });
+
it("leaves a page-tracking update alone until the page info has arrived", () => {
// A current-page message before page-info has nothing to update, and the active heading
// likewise waits for the table of contents.
diff --git a/apps/client/src/widgets/type_widgets/file/Pdf.tsx b/apps/client/src/widgets/type_widgets/file/Pdf.tsx
index 51958bec09..fc1754dde2 100644
--- a/apps/client/src/widgets/type_widgets/file/Pdf.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Pdf.tsx
@@ -4,6 +4,7 @@ import appContext from "../../../components/app_context";
import type NoteContext from "../../../components/note_context";
import FBlob from "../../../entities/fblob";
import FNote from "../../../entities/fnote";
+import { copyReferenceWithToast } from "../../../services/clipboard_ext";
import open from "../../../services/open";
import options from "../../../services/options";
import { useViewModeConfig } from "../../collections/NoteList";
@@ -16,6 +17,13 @@ import PdfViewer, { getPdfUrl } from "./PdfViewer";
*/
const SAVE_INTERVAL = 5_000;
+/**
+ * The form of the id pdf.js gives an annotation stored in the document: its object reference,
+ * such as `12R`. An annotation drawn in this session has an editor id instead, which the next load
+ * of the document does not reuse.
+ */
+const STORED_ANNOTATION_ID = /^\d+R\d*$/;
+
export default function PdfPreview({ note, blob, componentId, noteContext }: {
note: FNote;
noteContext: NoteContext;
@@ -25,6 +33,30 @@ export default function PdfPreview({ note, blob, componentId, noteContext }: {
const iframeRef = useRef<HTMLIFrameElement>(null);
const isReadOnly = useEffectiveReadOnly(note, noteContext);
const historyConfig = useViewModeConfig<HistoryData>(note, "pdfHistory");
+ /**
+ * The note whose viewer has listed its annotations, which it does once it can scroll to one.
+ * Holds a note id rather than a flag, because the component is reused when the pane switches
+ * to another PDF.
+ */
+ const viewerReadyForRef = useRef<string | null>(null);
+
+ /** Scrolls to the page or annotation a link opened the note at, once the viewer can. */
+ function revealLinkTarget() {
+ const viewScope = noteContext.viewScope;
+ if (viewerReadyForRef.current !== note.noteId || !viewScope?.page) return;
+
+ const pageNumber = Number.parseInt(viewScope.page, 10);
+ const annotationId = viewScope.annotation;
+ viewScope.page = undefined;
+ viewScope.annotation = undefined;
+ if (!(pageNumber >= 1)) return;
+
+ iframeRef.current?.contentWindow?.postMessage({
+ type: "trilium-scroll-to-annotation",
+ annotationId,
+ pageNumber
+ }, window.location.origin);
+ }
const spacedUpdate = useBlobEditorSpacedUpdate({
note,
@@ -57,6 +89,7 @@ export default function PdfPreview({ note, blob, componentId, noteContext }: {
},
onContentChange() {
if (iframeRef.current?.contentWindow) {
+ viewerReadyForRef.current = null;
iframeRef.current.contentWindow.location.reload();
}
},
@@ -136,6 +169,9 @@ export default function PdfPreview({ note, blob, componentId, noteContext }: {
type: "trilium-request-thumbnail",
pageNumber: page
}, window.location.origin);
+ },
+ copyReference: (page: number) => {
+ void copyReferenceWithToast(pdfReference(getNotePath(), page));
}
});
}
@@ -184,8 +220,14 @@ export default function PdfPreview({ note, blob, componentId, noteContext }: {
annotationId,
pageNumber
}, window.location.origin);
+ },
+ copyReference: (annotationId: string, pageNumber: number) => {
+ void copyReferenceWithToast(pdfReference(getNotePath(), pageNumber, annotationId));
}
});
+
+ viewerReadyForRef.current = note.noteId;
+ revealLinkTarget();
}
if (event.data.type === "pdfjs-viewer-layers") {
@@ -202,12 +244,23 @@ export default function PdfPreview({ note, blob, componentId, noteContext }: {
}
}
+ function getNotePath() {
+ return noteContext.notePath ?? note.noteId;
+ }
+
window.addEventListener("message", handleMessage);
return () => {
window.removeEventListener("message", handleMessage);
};
}, [ note, historyConfig, componentId, blob, noteContext, isReadOnly, spacedUpdate ]);
+ // A link to the PDF this pane already shows changes no content, so nothing else re-reads it.
+ useTriliumEvent("noteSwitched", ({ noteContext: switchedContext }) => {
+ if (switchedContext.ntxId !== noteContext.ntxId) return;
+ if (switchedContext.note?.noteId !== note.noteId) return;
+ revealLinkTarget();
+ });
+
useTriliumEvent("customDownload", async ({ ntxId }) => {
if (ntxId !== noteContext.ntxId) return;
@@ -259,6 +312,18 @@ export default function PdfPreview({ note, blob, componentId, noteContext }: {
);
}
+/**
+ * The link that opens a PDF note at `pageNumber`, and at the annotation `annotationId` on it when
+ * the document already stores that annotation.
+ */
+export function pdfReference(notePath: string, pageNumber: number, annotationId?: string) {
+ let reference = `#${notePath}?page=${pageNumber}`;
+ if (annotationId && STORED_ANNOTATION_ID.test(annotationId)) {
+ reference += `&annotation=${encodeURIComponent(annotationId)}`;
+ }
+ return reference;
+}
+
interface PdfHeading {
level: number;
text: string;
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Right Sidebar/Outline tab.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Right Sidebar/Outline tab.html
index 9d2935da6a..a7b76e0e04 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Right Sidebar/Outline tab.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Right Sidebar/Outline tab.html
@@ -114,11 +114,15 @@
<ul>
<li>A preview of all the pages with a small thumbnail.</li>
<li>Clicking on a page will automatically navigate to that page.</li>
+ <li>Right-clicking a page and selecting <em>Copy reference</em> copies a link
+ that opens the PDF at that page.</li>
</ul>
</li>
<li>Annotations
<ul>
<li>Highlight and comment annotations are listed here.</li>
+ <li>Right-clicking an annotation and selecting <em>Copy reference</em> copies
+ a link that opens the PDF at that annotation.</li>
<li>For the old layout, this feature is not directly available, however there
is a listing of comments directly in the PDF toolbar.</li>
</ul>
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/File/PDFs.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/File/PDFs.html
index e354bf2951..b65818129e 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/File/PDFs.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/File/PDFs.html
@@ -91,6 +91,27 @@ class="admonition tip">
<p>The downside is that the entire PDF needs to be sent back to the server,
which can slow down performance for larger documents. If you encounter
any issues from this system, feel free to <a href="#root/_help_wy8So3yZZlH9">report it</a>.</p>
+<h2>Linking to a page or an annotation</h2>
+<p>A link can open a PDF at a given page, or at one of its annotations. To
+ create one:</p>
+<ul>
+ <li>To link to a page, right-click the page in the <em>Pages</em> section of
+ the <a class="reference-link" href="#root/_help_RnaPdbciOfeq">Right Sidebar</a> and
+ select <em>Copy reference</em>.</li>
+ <li>To link to an annotation, right-click it in the <em>Annotations</em> section
+ of the sidebar and select <em>Copy reference</em>.</li>
+</ul>
+<p>Pasted into a text note, the reference becomes one of the&nbsp;<a class="reference-link"
+ href="#root/_help_hrZ1D00cLbal">Internal (reference) links</a>, showing
+ the title of the PDF and the page. Clicking it opens the PDF and scrolls
+ to the page or to the annotation.</p>
+<p>A reference to an annotation also carries its page, so a link to an annotation
+ that was deleted still opens the right page.</p>
+<aside class="admonition note">
+ <p>An annotation drawn since the PDF was opened does not have a permanent
+ identifier until the PDF is opened again, so a reference copied for it
+ points at its page only.</p>
+</aside>
<h2>Filling out forms</h2>
<p>Similar to annotations, forms are also supported by Trilium since v0.102.0.
If the document has fields that can be filled-in, they will be indicated
diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Right Sidebar/Outline tab.md b/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Right Sidebar/Outline tab.md
index f6d9d797a0..d2e8116271 100644
--- a/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Right Sidebar/Outline tab.md
+++ b/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Right Sidebar/Outline tab.md
@@ -72,8 +72,10 @@ When <a class="reference-link" href="../../../Note%20Types/File/PDFs.md">PDFs</
* Pages
* A preview of all the pages with a small thumbnail.
* Clicking on a page will automatically navigate to that page.
+ * Right-clicking a page and selecting _Copy reference_ copies a link that opens the PDF at that page.
* Annotations
* Highlight and comment annotations are listed here.
+ * Right-clicking an annotation and selecting _Copy reference_ copies a link that opens the PDF at that annotation.
* For the old layout, this feature is not directly available, however there is a listing of comments directly in the PDF toolbar.
* Attachments
* If the PDF has its own attachments (not to be confused with Trilium's <a class="reference-link" href="../../Notes/Attachments.md">Attachments</a>), they will be displayed in a list.
diff --git a/docs/User Guide/User Guide/Note Types/File/PDFs.md b/docs/User Guide/User Guide/Note Types/File/PDFs.md
index e2f9b43d01..411ad24e38 100644
--- a/docs/User Guide/User Guide/Note Types/File/PDFs.md
+++ b/docs/User Guide/User Guide/Note Types/File/PDFs.md
@@ -67,6 +67,20 @@ The benefit of “baked-in annotations” is that they are also accessible if do
The downside is that the entire PDF needs to be sent back to the server, which can slow down performance for larger documents. If you encounter any issues from this system, feel free to [report it](../../Troubleshooting/Reporting%20issues.md).
+## Linking to a page or an annotation
+
+A link can open a PDF at a given page, or at one of its annotations. To create one:
+
+* To link to a page, right-click the page in the _Pages_ section of the <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/UI%20Elements/Right%20Sidebar.md">Right Sidebar</a> and select _Copy reference_.
+* To link to an annotation, right-click it in the _Annotations_ section of the sidebar and select _Copy reference_.
+
+Pasted into a text note, the reference becomes one of the <a class="reference-link" href="../Text/Links/Internal%20(reference)%20links.md">Internal (reference) links</a>, showing the title of the PDF and the page. Clicking it opens the PDF and scrolls to the page or to the annotation.
+
+A reference to an annotation also carries its page, so a link to an annotation that was deleted still opens the right page.
+
+> [!NOTE]
+> An annotation drawn since the PDF was opened does not have a permanent identifier until the PDF is opened again, so a reference copied for it points at its page only.
+
## Filling out forms
Similar to annotations, forms are also supported by Trilium since v0.102.0. If the document has fields that can be filled-in, they will be indicated with a colored background.
diff --git a/packages/pdfjs-viewer/src/annotations.spec.ts b/packages/pdfjs-viewer/src/annotations.spec.ts
index e6429fed4f..ef56a9cc65 100644
--- a/packages/pdfjs-viewer/src/annotations.spec.ts
+++ b/packages/pdfjs-viewer/src/annotations.spec.ts
@@ -6,7 +6,8 @@ import {
processAnnotation,
rgbToHex,
setupAnnotationLiveUpdates,
- setupPdfAnnotations
+ setupPdfAnnotations,
+ trackInitialView
} from "./annotations";
import { allFeaturesPdf } from "./test/fixture_pdf";
import { InstalledViewer, installViewerApp, uninstallViewerApp } from "./test/viewer_app";
@@ -419,4 +420,41 @@ describe("scrolling to an annotation", () => {
renderAnnotation("14R");
await vi.waitFor(() => expect(viewer.scrollRequests).toHaveBeenCalled());
});
+
+ it("turns to the page alone when no annotation is named", async () => {
+ viewer = await installViewerApp(allFeaturesPdf());
+ await setupPdfAnnotations();
+
+ viewer.sendFromParent({ type: "trilium-scroll-to-annotation", pageNumber: 2 });
+
+ await vi.waitFor(() => expect(window.PDFViewerApplication?.pdfViewer.currentPageNumber).toBe(2));
+ // A page reference ends at the top of the page. Nothing is looked up by id, not even the
+ // literal "undefined" a missing id turns into.
+ renderAnnotation("undefined");
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(viewer.scrollRequests).not.toHaveBeenCalled();
+ });
+
+ it("waits for pdf.js to apply its initial view, which would undo an earlier scroll", async () => {
+ viewer = await installViewerApp(allFeaturesPdf());
+ const app = window.PDFViewerApplication;
+ if (!app) throw new Error("viewer not installed");
+ let pagesLoaded = () => {};
+ (app.pdfViewer as any).pagesPromise = new Promise<void>((resolve) => { pagesLoaded = resolve; });
+ trackInitialView(app);
+ await setupPdfAnnotations();
+
+ viewer.sendFromParent({ type: "trilium-scroll-to-annotation", annotationId: "14R", pageNumber: 2 });
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(app.pdfViewer.currentPageNumber).toBe(1);
+
+ // pdf.js restores the last-read position at `documentinit`, and again once every page is
+ // sized when the pages differ in size.
+ viewer.eventBus.dispatch("documentinit", { source: null });
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(app.pdfViewer.currentPageNumber).toBe(1);
+
+ pagesLoaded();
+ await vi.waitFor(() => expect(app.pdfViewer.currentPageNumber).toBe(2));
+ });
});
diff --git a/packages/pdfjs-viewer/src/annotations.ts b/packages/pdfjs-viewer/src/annotations.ts
index eeee0fdccd..9b40e76c7b 100644
--- a/packages/pdfjs-viewer/src/annotations.ts
+++ b/packages/pdfjs-viewer/src/annotations.ts
@@ -19,6 +19,13 @@ const COMMENT_TYPES = new Set<number>([
AnnotationType.INK,
]);
+/**
+ * Settles once pdf.js has applied the document's initial view, which restores the last-read
+ * position and would undo a scroll made before it. Already settled unless
+ * {@link trackInitialView} was called.
+ */
+let initialViewApplied: Promise<void> = Promise.resolve();
+
const TYPE_NAMES: Record<number, string> = {
[AnnotationType.TEXT]: "text",
[AnnotationType.FREETEXT]: "freetext",
@@ -67,6 +74,19 @@ function resolveTypeName(ann: Record<string, any>): string {
return TYPE_NAMES[ann.annotationType];
}
+/**
+ * Holds back {@link scrollToAnnotation} until pdf.js has applied the initial view. pdf.js applies
+ * it at `documentinit` and, when the pages differ in size, once more after `pagesPromise`. Must be
+ * called before the document loads.
+ */
+export function trackInitialView(app: NonNullable<Window["PDFViewerApplication"]>) {
+ initialViewApplied = new Promise((resolve) => {
+ app.eventBus.on("documentinit", () => {
+ void app.pdfViewer.pagesPromise.then(() => requestAnimationFrame(() => resolve()));
+ }, { once: true });
+ });
+}
+
export async function setupPdfAnnotations() {
await extractAndSendAnnotations();
@@ -74,7 +94,7 @@ export async function setupPdfAnnotations() {
if (event.origin !== window.location.origin) return;
if (event.data?.type === "trilium-scroll-to-annotation") {
- scrollToAnnotation(event.data.annotationId, event.data.pageNumber);
+ void scrollToAnnotation(event.data.annotationId, event.data.pageNumber);
}
});
}
@@ -221,9 +241,17 @@ function sendAnnotations(annotations: PdfAnnotationInfo[]) {
} satisfies PdfViewerAnnotationsMessage, window.location.origin);
}
-function scrollToAnnotation(annotationId: string, pageNumber: number) {
+/** Scrolls to an annotation, or to the top of `pageNumber` when `annotationId` is not given. */
+async function scrollToAnnotation(annotationId: string | undefined, pageNumber: number) {
+ await initialViewApplied;
const app = window.PDFViewerApplication;
- const container = app.pdfViewer.container as HTMLElement;
+ if (!app) return;
+ const container = app.pdfViewer.container;
+
+ if (!annotationId) {
+ app.pdfViewer.currentPageNumber = pageNumber;
+ return;
+ }
function scrollToEl(el: Element) {
const containerRect = container.getBoundingClientRect();
@@ -237,13 +265,13 @@ function scrollToAnnotation(annotationId: string, pageNumber: number) {
// An annotation the document holds renders with its id in an attribute; one that so far
// exists only in the editor renders as an element carrying the editor id directly.
- function findRendered() {
- return document.querySelector(`[data-annotation-id="${CSS.escape(annotationId)}"]`)
- ?? document.getElementById(annotationId);
+ function findRendered(id: string) {
+ return document.querySelector(`[data-annotation-id="${CSS.escape(id)}"]`)
+ ?? document.getElementById(id);
}
// Try to find the element directly (nearby pages are pre-rendered)
- const el = findRendered();
+ const el = findRendered(annotationId);
if (el) {
scrollToEl(el);
return;
@@ -252,7 +280,7 @@ function scrollToAnnotation(annotationId: string, pageNumber: number) {
// Element not in DOM yet — jump to the page and wait for it to render
app.pdfViewer.currentPageNumber = pageNumber;
const observer = new MutationObserver(() => {
- const el = findRendered();
+ const el = findRendered(annotationId);
if (el) {
observer.disconnect();
scrollToEl(el);
diff --git a/packages/pdfjs-viewer/src/bootstrap.ts b/packages/pdfjs-viewer/src/bootstrap.ts
index 3eaec8b6d6..8054763452 100644
--- a/packages/pdfjs-viewer/src/bootstrap.ts
+++ b/packages/pdfjs-viewer/src/bootstrap.ts
@@ -3,7 +3,7 @@ import { extractAndSendToc, setupScrollToHeading, setupActiveHeadingTracking } f
import { setupPdfPages } from "./pages";
import { setupPdfAttachments } from "./attachments";
import { setupPdfLayers } from "./layers";
-import { setupPdfAnnotations, setupAnnotationLiveUpdates } from "./annotations";
+import { setupPdfAnnotations, setupAnnotationLiveUpdates, trackInitialView } from "./annotations";
import { commitPendingAnnotationEdits, isAnnotationEditingActive, setAnnotationEditorUIManager, suppressViewerUnloadPrompt } from "./editing";
export async function main() {
@@ -45,6 +45,7 @@ export async function main() {
const app = window.PDFViewerApplication;
manageParentCommands();
+ trackInitialView(app);
// Needed to commit in-progress annotation edits before saving; pdf.js recreates the
// manager for each loaded document.
diff --git a/packages/pdfjs-viewer/src/typings.d.ts b/packages/pdfjs-viewer/src/typings.d.ts
index de99088c09..9c40982930 100644
--- a/packages/pdfjs-viewer/src/typings.d.ts
+++ b/packages/pdfjs-viewer/src/typings.d.ts
@@ -25,6 +25,8 @@ declare global {
pdfDocument: PDFDocumentProxy;
pdfViewer: {
currentPageNumber: number;
+ /** Settles once every page has been sized. */
+ pagesPromise: Promise<void>;
/**
* pdf.js' own type, rather than a local restatement of it — the previous
* hand-written shape declared the config object directly and omitted the
@@ -40,7 +42,7 @@ declare global {
goToDestination(dest: PdfJsDestination);
};
eventBus: {
- on(event: string, listener: (...args: any[]) => void): void;
+ on(event: string, listener: (...args: any[]) => void, options?: { once?: boolean }): void;
dispatch(event: string, data?: any): void;
};
findBar?: {