Skip to content

Build your personal knowledge base with Trilium Notes

feat(pdf): sync the pdf.js signature library via a synced option

Elian Dorana35001b2afb6
diff --git a/apps/client/src/types-pdfjs.d.ts b/apps/client/src/types-pdfjs.d.ts
index 3202dafb63..a2cf64144e 100644
--- a/apps/client/src/types-pdfjs.d.ts
+++ b/apps/client/src/types-pdfjs.d.ts
@@ -10,6 +10,18 @@ type HistoryData = {
}[];
};
+/**
+ * A single reusable signature as stored by pdf.js' `SignatureStorage` (`web/signature_storage.js`):
+ * a human-readable description plus the compressed outline data produced by `SignatureExtractor`.
+ */
+type PdfSignatureEntry = {
+ description: string;
+ signatureData: unknown;
+};
+
+/** The pdf.js reusable signature library, keyed by signature UUID. Mirrors `localStorage["pdfjs.signature"]`. */
+type PdfSignatureStore = Record<string, PdfSignatureEntry>;
+
interface Window {
/**
* By default, pdf.js will try to store information about the opened PDFs such as zoom and scroll position in local storage.
@@ -19,6 +31,15 @@ interface Window {
*/
TRILIUM_VIEW_HISTORY_STORE?: HistoryData;
+ /**
+ * The reusable signature library used by the pdf.js signature tool. pdf.js keeps this in
+ * per-browser `localStorage`; Trilium instead injects it here (from a synced option) so signatures
+ * follow the user across devices. Reads/writes of `localStorage["pdfjs.signature"]` are intercepted
+ * in the viewer and routed through this global + a `pdfjs-viewer-save-signatures` message.
+ * Must be set early at startup, before pdf.js fully initializes.
+ */
+ TRILIUM_SIGNATURES?: PdfSignatureStore;
+
/**
* If set to true, hides the pdf.js viewer default sidebar containing the outline, page navigation, etc.
* This needs to be set early in the main method.
@@ -57,6 +78,12 @@ interface PdfSaveViewHistoryMessage extends WithContext {
data: string;
}
+interface PdfSaveSignaturesMessage extends WithContext {
+ type: "pdfjs-viewer-save-signatures";
+ /** JSON string of the full signature library, as written by pdf.js to `localStorage["pdfjs.signature"]`. */
+ data: string;
+}
+
interface PdfViewerTocMessage {
type: "pdfjs-viewer-toc";
data: PdfOutlineItem[];
@@ -127,6 +154,7 @@ interface PdfViewerAnnotationsMessage {
type PdfMessageEvent = MessageEvent<
PdfDocumentModifiedMessage
| PdfSaveViewHistoryMessage
+ | PdfSaveSignaturesMessage
| PdfViewerTocMessage
| PdfViewerActiveHeadingMessage
| PdfViewerPageInfoMessage
diff --git a/apps/client/src/widgets/type_widgets/file/Pdf.tsx b/apps/client/src/widgets/type_widgets/file/Pdf.tsx
index e6d98ad084..4630c060a4 100644
--- a/apps/client/src/widgets/type_widgets/file/Pdf.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Pdf.tsx
@@ -5,6 +5,7 @@ import type NoteContext from "../../../components/note_context";
import FBlob from "../../../entities/fblob";
import FNote from "../../../entities/fnote";
import open from "../../../services/open";
+import options from "../../../services/options";
import { useViewModeConfig } from "../../collections/NoteList";
import { useBlobEditorSpacedUpdate, useEffectiveReadOnly, useTriliumEvent } from "../../react/hooks";
import PdfViewer from "./PdfViewer";
@@ -70,6 +71,14 @@ export default function PdfPreview({ note, blob, componentId, noteContext }: {
}
}
+ if (event.data.type === "pdfjs-viewer-save-signatures" && event.data?.data) {
+ // The signature library is global (not per-note), but scope the write to this
+ // viewer instance so multiple open PDFs don't each re-save the same payload.
+ if (event.data.noteId === note.noteId && event.data.ntxId === noteContext.ntxId) {
+ options.save("pdfSignatures", event.data.data);
+ }
+ }
+
if (event.data.type === "pdfjs-viewer-toc") {
if (event.data.data) {
// Convert PDF outline to HeadingContext format
@@ -223,6 +232,7 @@ export default function PdfPreview({ note, blob, componentId, noteContext }: {
const win = iframeRef.current?.contentWindow;
if (win) {
win.TRILIUM_VIEW_HISTORY_STORE = historyConfig.config;
+ win.TRILIUM_SIGNATURES = options.getJson("pdfSignatures") ?? {};
win.TRILIUM_NOTE_ID = note.noteId;
win.TRILIUM_NTX_ID = noteContext.ntxId;
}
diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.ts
index acf5677d91..a77893b40c 100644
--- a/packages/commons/src/lib/options_interface.ts
+++ b/packages/commons/src/lib/options_interface.ts
@@ -194,6 +194,14 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActi
backgroundEffects: boolean;
newLayout: boolean;
+ // PDF settings
+ /**
+ * The pdf.js reusable signature library, stored as a JSON string keyed by signature UUID
+ * (`{ [uuid]: { description, signatureData } }`). Persisted here — instead of pdf.js' default
+ * per-browser `localStorage` — so saved signatures sync across devices.
+ */
+ pdfSignatures: string;
+
// Search settings
/** Whether fuzzy matching is enabled in search (matches similar words when exact matches are insufficient). */
searchEnableFuzzyMatching: boolean;
diff --git a/packages/pdfjs-viewer/src/persistence.ts b/packages/pdfjs-viewer/src/persistence.ts
index 977db124f2..ee44c36606 100644
--- a/packages/pdfjs-viewer/src/persistence.ts
+++ b/packages/pdfjs-viewer/src/persistence.ts
@@ -1,3 +1,6 @@
+/** pdf.js' localStorage key for the reusable signature library (`web/signature_storage.js`). */
+const SIGNATURE_STORAGE_KEY = "pdfjs.signature";
+
export default function interceptViewHistory(customOptions?: object) {
// We need to monkey-patch the localStorage used by PDF.js to store view history.
// Other attempts to intercept the history saving/loading (like overriding methods on PDFViewerApplication) have failed.
@@ -8,6 +11,11 @@ export default function interceptViewHistory(customOptions?: object) {
return;
}
+ if (key === SIGNATURE_STORAGE_KEY) {
+ saveSignatures(value);
+ return;
+ }
+
return originalSetItem.call(this, key, value);
}
@@ -21,6 +29,10 @@ export default function interceptViewHistory(customOptions?: object) {
return JSON.stringify(window.TRILIUM_VIEW_HISTORY_STORE || {});
}
+ if (key === SIGNATURE_STORAGE_KEY) {
+ return JSON.stringify(window.TRILIUM_SIGNATURES || {});
+ }
+
return originalGetItem.call(this, key);
}
}
@@ -48,3 +60,24 @@ function saveHistory(value: string) {
saveTimeout = null;
}, 2_000);
}
+
+/**
+ * Persists the reusable signature library. pdf.js writes the full library to `localStorage` on every
+ * add/remove; we mirror it into the injected `TRILIUM_SIGNATURES` global (so in-session reads stay
+ * consistent) and forward it to the parent, which stores it in the synced `pdfSignatures` option.
+ * These are discrete user actions, so — unlike view history — no debounce is needed.
+ */
+function saveSignatures(value: string) {
+ try {
+ window.TRILIUM_SIGNATURES = JSON.parse(value);
+ } catch {
+ // Malformed payload should never reach here; keep the previous in-memory copy if it does.
+ }
+
+ window.parent.postMessage({
+ type: "pdfjs-viewer-save-signatures",
+ data: value,
+ ntxId: window.TRILIUM_NTX_ID,
+ noteId: window.TRILIUM_NOTE_ID
+ } satisfies PdfSaveSignaturesMessage, window.location.origin);
+}
diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.ts
index 0948274c71..c2f505cdea 100644
--- a/packages/trilium-core/src/routes/api/options.ts
+++ b/packages/trilium-core/src/routes/api/options.ts
@@ -43,6 +43,7 @@ const ALLOWED_OPTIONS = new Set<OptionNames>([
"codeNoteThemeDark",
"codeNoteTabWidth",
"codeNoteIndentWithTabs",
+ "pdfSignatures",
"syncServerHost",
"syncServerTimeout",
"syncServerTimeoutTimeScale",
diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.ts
index cb78a96af7..402fdf7689 100644
--- a/packages/trilium-core/src/services/options_init.ts
+++ b/packages/trilium-core/src/services/options_init.ts
@@ -216,6 +216,9 @@ const defaultOptions: DefaultOption[] = [
{ name: "smoothScrollEnabled", value: "true", isSynced: false },
{ name: "newLayout", value: "true", isSynced: true },
+ // PDF
+ { name: "pdfSignatures", value: "{}", isSynced: true },
+
// Internationalization
{ name: "locale", value: "en", isSynced: true },
{ name: "formattingLocale", value: "", isSynced: true }, // no value means auto-detect