From a1f2bebe2d6ac28f3d48a4618cb28b6dfe5e5ebb Mon Sep 17 00:00:00 2001 From: mberman84 <748450+mberman84@users.noreply.github.com> Date: Tue, 3 Nov 2026 07:54:39 -0800 Subject: [PATCH 1/8] Remember and choose from multiple handwritten signatures --- README.md | 8 ++-- SECURITY.md | 2 +- scripts/smoke-test.mjs | 92 +++++++++++++++++++++++++++++++---------- src/App.tsx | 11 +++-- src/SettingsDialog.tsx | 20 ++++----- src/SignatureDialog.tsx | 71 +++++++++++++++---------------- src/reading-tools.css | 11 +++++ src/signatures.ts | 47 +++++++++++++++++++-- src/styles.css | 2 +- 9 files changed, 183 insertions(+), 81 deletions(-) diff --git a/README.md b/README.md index 1b0b4df..099a09b 100644 --- a/README.md +++ b/README.md @@ -108,8 +108,8 @@ URL opening, webpage conversion, and Word conversion require the desktop app. Fa - **Explicit approval:** nothing is added until you click **Approve and add signature**. Signatures are visual stamps, not certificate-based digital signatures. Use **Save a copy** to keep a signed PDF; placed signatures are not part of Folio's automatic annotation restoration. -- **Optional reuse:** choose to remember a signature on this computer; remove the saved image in - **Settings → Signature → Forget**. +- **Optional reuse:** select **Remember this signature** and give it a name, such as “Initials”. + Open **Sign** again to choose a saved signature or capture another. Remove individual signatures in **Settings → Signatures**. ### Ask AI about a document @@ -242,8 +242,8 @@ is there when you reopen the document; the **+** button in the panel starts over Stored locally in your user profile (`%APPDATA%\Folio` on Windows, `~/Library/Application Support/Folio` on macOS, `~/.config/Folio` on Linux): recently opened PDFs and their thumbnails (up to 8, removable from the home screen with **Clear all**; password-protected PDFs are never kept), highlights, notes, and -Ask AI conversations for each document (except password-protected ones), reading positions, preferences, and, only if you choose to remember -it, your signature image. Apart from the ChatGPT sign-in, this data isn't encrypted, so anyone with access to your +Ask AI conversations for each document (except password-protected ones), reading positions, preferences, and any +signature images you choose to remember. Apart from the ChatGPT sign-in, this data isn't encrypted, so anyone with access to your user account can read it. ## Building from source diff --git a/SECURITY.md b/SECURITY.md index 2641cff..4773a1a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -64,7 +64,7 @@ Known limitations: (`01AF 1CBF 971E 5482 C064 1A6E EE00 67F5 E3B5 48FC`). These keys are installed by the .deb as `/usr/share/keyrings/folio-archive-keyring.gpg` and used only for Folio's source (`signed-by`). apt rejects any repository metadata not signed with it. -- Local data (recent files, reading positions, an optionally remembered signature) is stored unencrypted in your user +- Local data (recent files, reading positions, and any signatures you choose to remember) is stored unencrypted in your user profile. See [Privacy](README.md#privacy). - Word and LibreOffice convert documents with your own permissions and aren't sandboxed further by Folio. Word is driven through automation, which doesn't use its Protected View. Neither is cut off from the network. diff --git a/scripts/smoke-test.mjs b/scripts/smoke-test.mjs index 5648c05..89d9067 100644 --- a/scripts/smoke-test.mjs +++ b/scripts/smoke-test.mjs @@ -58,9 +58,21 @@ try { assert.match(await page.locator(".textLayer").first().innerText(), /A short tour of Folio/); console.log("ok sample rendered with a text layer"); - // Opening another document (here from the file manager) asks first when there's unsaved work, a placed signature, - // and keeps it if the reader says no. - const photo = await page.evaluate(() => { + const saveCopy = async (name) => { + const file = path.join(env.FOLIO_TEST_USER_DATA, name); + await app.evaluate(({ session }, file) => { + globalThis.folioCopySaved = new Promise((resolve) => session.defaultSession.once("will-download", (_event, item) => { + item.setSavePath(file); + item.once("done", (_done, state) => resolve(state)); + })); + }, file); + await page.keyboard.press("ControlOrMeta+s"); + assert.equal(await app.evaluate(() => globalThis.folioCopySaved), "completed"); + return readFileSync(file, "latin1"); + }; + + // A signature remembered by an earlier Folio can be used alongside a newly captured one. + const photos = await page.evaluate(() => { const canvas = Object.assign(document.createElement("canvas"), { width: 600, height: 200 }); const g = canvas.getContext("2d"); g.fillStyle = "#fff"; @@ -69,17 +81,64 @@ try { g.beginPath(); g.moveTo(40, 150); g.bezierCurveTo(150, 10, 250, 190, 350, 60); + g.stroke(); + const initials = canvas.toDataURL(); + localStorage.setItem("folio:signature", JSON.stringify({ url: initials, width: canvas.width, height: canvas.height })); g.lineTo(560, 120); g.stroke(); - return canvas.toDataURL("image/png").split(",")[1]; + return { initials, fullName: canvas.toDataURL() }; }); - await page.getByTitle("Add a signature").click(); - await page.locator('input[aria-label="Upload signature photo"]').setInputFiles({ name: "signature.png", mimeType: "image/png", buffer: Buffer.from(photo, "base64") }); - await page.getByRole("button", { name: /Use this signature/ }).click(); - await page.locator('select[aria-label="Signature placement"]').selectOption("manual"); - await page.locator('[aria-label^="Place signature on page"]').click(); - await page.getByRole("button", { name: /Approve and add signature/ }).click(); + const sign = page.getByTitle("Add a signature"); + const picker = page.getByRole("combobox", { name: "Saved signature" }); + const uploadPhoto = async (url) => { + await page.getByLabel("Upload signature photo").setInputFiles({ name: "signature.png", mimeType: "image/png", buffer: Buffer.from(url.split(",")[1], "base64") }); + await page.getByRole("button", { name: /Use this signature/ }).click(); + }; + const placeAt = async (x, y) => { + await page.getByRole("combobox", { name: "Signature placement" }).selectOption("manual"); + await page.getByRole("button", { name: "Place signature on page 1" }).click({ position: { x, y } }); + }; + const approve = async () => { + await page.getByRole("button", { name: "Approve and add signature" }).click(); + await page.getByRole("dialog", { name: "Sign page 1" }).waitFor({ state: "hidden" }); + }; + await sign.click(); + assert.equal(await picker.locator("option:checked").textContent(), "Signature 1"); + const originalPage = await page.getByAltText("Page 1 placement preview").getAttribute("src"); + await uploadPhoto(photos.fullName); + const remember = page.getByRole("checkbox", { name: /Remember this signature/ }); + await remember.check(); + await page.getByLabel("Signature name", { exact: true }).fill("Full name"); + const fullName = await page.getByAltText("Your signature preview").getAttribute("src"); + await placeAt(70, 70); + await approve(); + await sign.click(); + assert.ok(await page.getByAltText("Page 1 placement preview").getAttribute("src") !== originalPage, "the preview omitted the first stamp"); + await picker.selectOption({ label: "Full name" }); + assert.ok(await page.getByAltText("Your signature preview").getAttribute("src") === fullName); + await placeAt(145, 180); + const proposedWidth = () => page.getByAltText("Proposed signature location").evaluate(image => image.style.width); + const width = await proposedWidth(); + await picker.selectOption({ label: "Signature 1" }); + assert.ok(await page.getByAltText("Your signature preview").getAttribute("src") !== fullName); + assert.equal(await proposedWidth(), width); + await approve(); + assert.equal((await saveCopy("signed.pdf")).match(/\/Subtype\s*\/Stamp\b/g)?.length, 2); + + await page.keyboard.press("ControlOrMeta+Comma"); + await page.getByRole("button", { name: "Forget Signature 1", exact: true }).click(); + await page.keyboard.press("Escape"); + await sign.click(); + assert.deepEqual(await picker.locator("option").allTextContents(), ["Full name"]); + await uploadPhoto(photos.initials); + await remember.check(); + await placeAt(100, 130); + await approve(); + await sign.click(); + assert.deepEqual(await picker.locator("option:enabled").allTextContents(), ["Full name", "Signature 1"]); + await page.getByRole("button", { name: "Cancel" }).click(); await page.locator(".dirty-dot").waitFor(); + console.log("ok saved signatures can be selected, exported together, and forgotten individually"); // Printing saves nothing, so the signature stays marked as unsaved. The print frame is stubbed for the check, so no // system print dialog opens. @@ -115,7 +174,7 @@ try { await openFromFileManager(); await page.waitForFunction(stub => stub.messages.length === 1, confirmation, { timeout: 15_000 }); assert.equal(await page.title(), "Folio sample.pdf — Folio"); - assert.equal(await page.locator(".stampEditor").count(), 1); + assert.equal(await page.locator(".stampEditor").count(), 3); assert.ok(await page.locator(".dirty-dot").isVisible()); await openFromFileManager(); await page.waitForFunction(() => document.title.startsWith("Another.pdf"), null, { timeout: 15_000 }); @@ -205,16 +264,7 @@ try { await page.getByTitle("Back to library").click(); await page.getByRole("button", { name: /Try a sample/ }).click(); await page.locator(".textLayer span:not(.markedContent)").first().waitFor({ timeout: 30_000 }); - const copy = path.join(env.FOLIO_TEST_USER_DATA, "copy.pdf"); - await app.evaluate(({ session }, file) => { - globalThis.folioCopySaved = new Promise((resolve) => session.defaultSession.once("will-download", (_event, item) => { - item.setSavePath(file); - item.once("done", (_done, state) => resolve(state)); - })); - }, copy); - await page.keyboard.press("ControlOrMeta+s"); - assert.equal(await app.evaluate(() => globalThis.folioCopySaved), "completed"); - assert.equal(readFileSync(copy, "latin1").match(/\/Subtype\s*\/Highlight\b/g)?.length, 2); + assert.equal((await saveCopy("copy.pdf")).match(/\/Subtype\s*\/Highlight\b/g)?.length, 2); console.log("ok saved copy includes marks on pages not drawn yet"); await page.getByRole("button", { name: "More" }).click(); diff --git a/src/App.tsx b/src/App.tsx index bd6ee93..5b2840a 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -32,7 +32,7 @@ import { AboutDialog, InfoDialog, OpenUrlDialog, PasswordDialog, ShortcutsDialog import { SignatureDialog } from "./SignatureDialog"; import { SettingsDialog } from "./SettingsDialog"; import { ChangelogDialog } from "./ChangelogDialog"; -import { detectSignatureTargets, placeSignature, type SignatureTarget } from "./signatures"; +import { detectSignatureTargets, placeSignature, rememberSignature, type SignatureTarget } from "./signatures"; import { keepDrawingPointer } from "./drawing"; import { enableWheelPaging } from "./wheelPaging"; @@ -1350,9 +1350,14 @@ export default function App() { {doc && imageView && setImageView(null)} />} {dialog === "url" && setDialog(null)} onSubmit={(url) => { setDialog(null); openUrl(url); }} />} {doc && signing && setSigning(false)} onApprove={async (signature, rect) => { + onClose={() => setSigning(false)} onApprove={async (signature, rect, rememberAs) => { await placeSignature(viewerRef.current!, doc.pdf, page, signature, rect); - setDirty(true); setSignatureDismissed(true); flash(keys("Signature added. Ctrl+Z to undo; Save copy to export.")); + setDirty(true); setSignatureDismissed(true); + if (rememberAs !== undefined) { + try { rememberSignature(signature, rememberAs); } + catch { flash("Signature added to the page, but couldn't be remembered on this device."); return; } + } + flash(keys("Signature added. Ctrl+Z to undo; Save copy to export.")); }} />} {doc && !signing && signatureTargets.length > 0 && !signatureDismissed &&
{signatureTargets[0].kind === "field" ? "Signature field detected" : "Possible signature area"} on page {page} diff --git a/src/SettingsDialog.tsx b/src/SettingsDialog.tsx index be1368c..0372aad 100644 --- a/src/SettingsDialog.tsx +++ b/src/SettingsDialog.tsx @@ -2,6 +2,7 @@ import { useEffect, useState, type ReactNode } from "react"; import { Modal } from "./Dialogs"; import { CLAUDE_CODE_URL, signInChatGPT, USAGE_URL, type AiProvider } from "./ai"; import { updateSummary } from "./updates"; +import { readSignatures } from "./signatures"; /** One place for every Folio preference. */ interface Props { @@ -93,10 +94,7 @@ export function SettingsDialog({ theme, onTheme, night, onNight, wheelPaging, on const [signingIn, setSigningIn] = useState(false); useEffect(() => { void ai?.status().then(setAiStatus).catch(() => {}); }, [ai]); - // Signature - const [savedSignature, setSavedSignature] = useState(() => { - try { return !!localStorage.getItem("folio:signature"); } catch { return false; } - }); + const [signatures, setSignatures] = useState(readSignatures); return ( @@ -157,15 +155,15 @@ export function SettingsDialog({ theme, onTheme, night, onNight, wheelPaging, on )} -
- - - + )}
{desktop && ( diff --git a/src/SignatureDialog.tsx b/src/SignatureDialog.tsx index 6643217..a32c807 100644 --- a/src/SignatureDialog.tsx +++ b/src/SignatureDialog.tsx @@ -1,18 +1,20 @@ import { useEffect, useRef, useState } from "react"; import type { PDFDocumentProxy } from "./pdf"; -import type { PageViewport } from "pdfjs-dist"; +import { AnnotationMode, type PageViewport } from "pdfjs-dist"; import { Modal } from "./Dialogs"; import { keys } from "./platform"; import { Icon } from "./icons"; -import { cleanSignature, fitSignature, readSignature, type SignatureImage, type SignatureTarget } from "./signatures"; +import { cleanSignature, fitSignature, nextSignatureName, positionSignature, readSignatures, type SignatureImage, type SignatureTarget } from "./signatures"; export function SignatureDialog({ pdf, pageNumber, targets, onApprove, onClose }: { pdf: PDFDocumentProxy; pageNumber: number; targets: SignatureTarget[]; - onApprove: (signature: SignatureImage, rect: number[]) => Promise; onClose: () => void; + onApprove: (signature: SignatureImage, rect: number[], rememberAs?: string) => Promise; onClose: () => void; }) { - const [signature, setSignature] = useState(readSignature); - const [saved, setSaved] = useState(() => !!readSignature()); + const [signatures] = useState(readSignatures); + const [signature, setSignature] = useState(signatures.length === 1 ? signatures[0] : null); + const saved = signatures.find(item => item.url === signature?.url); const [remember, setRemember] = useState(false); + const [name, setName] = useState(""); const [source, setSource] = useState(null); const [crop, setCrop] = useState(null); const [threshold, setThreshold] = useState(180); @@ -22,7 +24,7 @@ export function SignatureDialog({ pdf, pageNumber, targets, onApprove, onClose } const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const [targetId, setTargetId] = useState(targets[0]?.id || "manual"); - const [manualRect, setManualRect] = useState(null); + const [manualCenter, setManualCenter] = useState(null); const [size, setSize] = useState(150); const [preview, setPreview] = useState<{ url: string; width: number; height: number; viewport: PageViewport } | null>(null); const videoRef = useRef(null); @@ -33,8 +35,8 @@ export function SignatureDialog({ pdf, pageNumber, targets, onApprove, onClose } const mounted = useRef(true); const dragStart = useRef(null); const selected = targets.find(target => target.id === targetId); - const bounds = selected?.rect || manualRect; - const rect = signature && bounds ? fitSignature(signature, bounds) : null; + const rect = signature && (selected ? fitSignature(signature, selected.rect) + : manualCenter && preview && positionSignature(signature, size, manualCenter, preview.viewport.viewBox)); useEffect(() => { mounted.current = true; @@ -51,7 +53,7 @@ export function SignatureDialog({ pdf, pageNumber, targets, onApprove, onClose } const canvas = document.createElement("canvas"); canvas.width = Math.ceil(viewport.width); canvas.height = Math.ceil(viewport.height); if (cancelled) return; - const task = page.render({ canvas, viewport }); render = task; + const task = page.render({ canvas, viewport, annotationMode: AnnotationMode.ENABLE_STORAGE }); render = task; await task.promise; if (!cancelled) setPreview({ url: canvas.toDataURL(), width: viewport.width, height: viewport.height, viewport }); })().catch(reason => { if (!cancelled) setError("Couldn't preview this page: " + String(reason)); }); @@ -104,7 +106,7 @@ export function SignatureDialog({ pdf, pageNumber, targets, onApprove, onClose } const factor = Math.min(1, 1600 / Math.max(width, height)); const canvas = document.createElement("canvas"); canvas.width = Math.round(width * factor); canvas.height = Math.round(height * factor); canvas.getContext("2d")!.drawImage(image, 0, 0, canvas.width, canvas.height); - setSource(canvas); setCrop([0, 0, canvas.width, canvas.height]); setRemember(false); setSaved(false); setSignature(null); setError(""); + setSource(canvas); setCrop([0, 0, canvas.width, canvas.height]); setRemember(false); setName(""); setSignature(null); setError(""); }; const capture = () => { const video = videoRef.current; @@ -121,7 +123,7 @@ export function SignatureDialog({ pdf, pageNumber, targets, onApprove, onClose } const bitmap = await createImageBitmap(file); try { if (mounted.current && generation === captureGeneration.current) acceptSource(bitmap, bitmap.width, bitmap.height); } finally { bitmap.close(); } - } catch (reason) { if (mounted.current) setError((reason as Error).message); } + } catch (reason) { if (mounted.current && generation === captureGeneration.current) setError((reason as Error).message); } }; const cropPoint = (event: React.PointerEvent) => { const bounds = event.currentTarget.getBoundingClientRect(); @@ -132,26 +134,13 @@ export function SignatureDialog({ pdf, pageNumber, targets, onApprove, onClose } if (!signature || !rect || !preview || busy || source || camera || cameraStarting) return; setBusy(true); setError(""); try { - await onApprove(signature, rect); - if (remember) { - try { localStorage.setItem("folio:signature", JSON.stringify(signature)); } - catch { setError("Signature added, but couldn't remember it on this device. Close to continue."); setBusy(false); return; } - } + await onApprove(signature, rect, remember && !saved ? name : undefined); onClose(); } catch (reason) { setError((reason as Error).message); setBusy(false); } }; const screenRect = preview && rect ? [...preview.viewport.convertToViewportPoint(rect[0], rect[1]), ...preview.viewport.convertToViewportPoint(rect[2], rect[3])] : null; const ready = !!signature && !source && !camera && !cameraStarting; - const placeAt = (pointX: number, pointY: number, width = size) => { - if (!signature || !preview) return; - const [left, bottom, right, top] = preview.viewport.viewBox; - width = Math.min(width, right - left, (top - bottom) * signature.width / signature.height); - const height = width * signature.height / signature.width; - const positionX = Math.max(left, Math.min(right - width, pointX - width / 2)); - const positionY = Math.max(bottom, Math.min(top - height, pointY - height / 2)); - setManualRect([positionX, positionY, positionX + width, positionY + height]); - }; return { if (!busy) onClose(); }}>
@@ -165,7 +154,17 @@ export function SignatureDialog({ pdf, pageNumber, targets, onApprove, onClose }

Your signature

{saved && ready && Saved on this device}
- {!signature && !source && !camera &&
+ {signatures.length > 0 && !source && !camera && } + {!signatures.length && !signature && !source && !camera &&

Start with pen and paper

Sign white paper with dark ink, then capture or upload a photo.

} @@ -192,7 +191,10 @@ export function SignatureDialog({ pdf, pageNumber, targets, onApprove, onClose }
} {signature && !camera &&
Your signature preview Background removed
} - {ready && } + {ready && !saved && } + {ready && !saved && remember && }
Processed on this device. Never uploaded.
About signatures and saved copies

This adds a visual signature, not a digital certificate. Changes can affect existing digital signatures. Remembered signatures are stored unencrypted on this computer. Use {keys("Ctrl+Z")} to undo; Save copy exports the signed PDF.

@@ -200,11 +202,7 @@ export function SignatureDialog({ pdf, pageNumber, targets, onApprove, onClose }

Page {pageNumber}

{selected ? "Suggested position" : "Page preview"}
{ready &&
- {targetId === "manual" && } + {targetId === "manual" && }
}
{preview ?
{ if (!ready || targetId !== "manual") return; const area = event.currentTarget.getBoundingClientRect(); - const [pointX, pointY] = preview.viewport.convertToPdfPoint((event.clientX - area.left) * preview.width / area.width, (event.clientY - area.top) * preview.height / area.height); - placeAt(pointX, pointY); + setManualCenter(preview.viewport.convertToPdfPoint((event.clientX - area.left) * preview.width / area.width, (event.clientY - area.top) * preview.height / area.height)); }} onKeyDown={event => { if (!ready || targetId !== "manual" || !["Enter", " ", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) return; event.preventDefault(); - const area = manualRect || preview.viewport.viewBox; - placeAt((area[0] + area[2]) / 2 + (event.key === "ArrowLeft" ? -5 : event.key === "ArrowRight" ? 5 : 0), (area[1] + area[3]) / 2 + (event.key === "ArrowDown" ? -5 : event.key === "ArrowUp" ? 5 : 0)); + const area = rect || preview.viewport.viewBox; + setManualCenter([(area[0] + area[2]) / 2 + (event.key === "ArrowLeft" ? -5 : event.key === "ArrowRight" ? 5 : 0), (area[1] + area[3]) / 2 + (event.key === "ArrowDown" ? -5 : event.key === "ArrowUp" ? 5 : 0)]); }}>{"Page {signature && screenRect && Proposed signature location}
:
Loading page preview...
}
-

{!ready ? "Your signature will appear here for review." : selected ? "Signature field or line detected. Check the suggested position." : manualRect ? "Click to reposition, or use the arrow keys to fine-tune." : "Click the page to place your signature, or focus it and press Enter."}

+

{!ready ? "Your signature will appear here for review." : selected ? "Signature field or line detected. Check the suggested position." : manualCenter ? "Click to reposition, or use the arrow keys to fine-tune." : "Click the page to place your signature, or focus it and press Enter."}

{error &&

{error}

} diff --git a/src/reading-tools.css b/src/reading-tools.css index 9b3bacd..0969874 100644 --- a/src/reading-tools.css +++ b/src/reading-tools.css @@ -826,6 +826,17 @@ .settings-label small a { color: var(--text-2); } +.settings-label:has(.settings-signature-preview) { overflow-wrap: anywhere; } +.settings-signature-preview { + display: block; + width: 100px; + max-width: 100%; + height: 36px; + object-fit: contain; + padding: 4px; + border-radius: 4px; + background: white; +} .settings-control { flex: none; } diff --git a/src/signatures.ts b/src/signatures.ts index b5eab3b..41b9c4c 100644 --- a/src/signatures.ts +++ b/src/signatures.ts @@ -3,6 +3,7 @@ import type { PDFDocumentProxy } from "./pdf"; import type { PDFViewer } from "./viewer"; export interface SignatureImage { url: string; width: number; height: number } +export interface SavedSignature extends SignatureImage { key: string; name: string } export interface SignatureTarget { id: string; label: string; rect: number[]; kind: "field" | "label" } const cache = new WeakMap>>(); @@ -52,6 +53,15 @@ export function fitSignature(signature: SignatureImage, bounds: number[]) { return [positionX, positionY, positionX + fittedWidth, positionY + fittedHeight]; } +export function positionSignature(signature: SignatureImage, size: number, center: number[], viewBox: number[]) { + const [left, bottom, right, top] = viewBox; + const width = Math.min(size, right - left, (top - bottom) * signature.width / signature.height); + const height = width * signature.height / signature.width; + const x = Math.max(left, Math.min(right - width, center[0] - width / 2)); + const y = Math.max(bottom, Math.min(top - height, center[1] - height / 2)); + return [x, y, x + width, y + height]; +} + export async function placeSignature(viewer: PDFViewer, pdf: PDFDocumentProxy, pageNumber: number, signature: SignatureImage, rect: number[]) { if (viewer.pdfDocument !== pdf) throw new Error("The document changed. Open Sign again."); viewer.currentPageNumber = pageNumber; @@ -110,11 +120,42 @@ export function cleanSignature(source: HTMLCanvasElement, crop: number[], thresh return { url: trimmed.toDataURL("image/png"), width: trimmed.width, height: trimmed.height }; } -export function readSignature(): SignatureImage | null { +const signatureKey = "folio:signature"; + +function readSavedSignature(key: string): SavedSignature | null { try { - const value = JSON.parse(localStorage.getItem("folio:signature") || "null"); + const value = JSON.parse(localStorage.getItem(key) || "null"); + const name = key === signatureKey ? "Signature 1" : value?.name; return value && typeof value.url === "string" && value.url.startsWith("data:image/png;base64,") && value.url.length < 4000000 && Number.isFinite(value.width) && Number.isFinite(value.height) - && value.width > 0 && value.height > 0 ? value : null; + && value.width > 0 && value.height > 0 && typeof name === "string" && name.trim() + ? { key, name, url: value.url, width: value.width, height: value.height } : null; } catch { return null; } } + +export function readSignatures(): SavedSignature[] { + const signatures: SavedSignature[] = []; + try { + // Keep the original single signature in place. Each new image has its own key so tabs can save independently. + for (const key of Object.keys(localStorage)) { + if (key !== signatureKey && !key.startsWith(signatureKey + ":")) continue; + const signature = readSavedSignature(key); + if (signature) signatures.push(signature); + } + } catch { /* Signing still works when storage is unavailable. */ } + return signatures.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true })); +} + +export function nextSignatureName(signatures: SavedSignature[]) { + let number = 1; + while (signatures.some(signature => signature.name === "Signature " + number)) number++; + return "Signature " + number; +} + +export function rememberSignature(image: SignatureImage, name: string) { + const signatures = readSignatures(); + if (signatures.some(signature => signature.url === image.url)) return; + localStorage.setItem(signatureKey + ":" + crypto.randomUUID(), JSON.stringify({ + ...image, name: name.trim() || nextSignatureName(signatures), + })); +} diff --git a/src/styles.css b/src/styles.css index 01fbf84..cbcf009 100644 --- a/src/styles.css +++ b/src/styles.css @@ -1299,7 +1299,7 @@ kbd { .signature-document { min-width: 0; align-self: start; display: grid; gap: 14px; padding: 16px; background: var(--surface-2); border: 1px solid var(--line); border-radius: 14px; } .signature-placement-controls { display: grid; gap: 12px; } .signature-field { display: grid; gap: 6px; color: var(--text-2); font-size: 11px; } -.signature-field select { min-width: 0; width: 100%; padding: 8px; background: var(--surface); color: var(--text); border: 1px solid var(--line-strong); border-radius: 7px; font: inherit; } +.signature-field select, .signature-field input { min-width: 0; width: 100%; padding: 8px; background: var(--surface); color: var(--text); border: 1px solid var(--line-strong); border-radius: 7px; font: inherit; } .signature-page-stage { display: flex; justify-content: center; min-width: 0; padding: 2px 0; } .signature-page { position: relative; max-width: 100%; background: white; box-shadow: var(--page-shadow); flex-shrink: 1; } .signature-page[data-placeable] { cursor: crosshair; } From fa8518c31a1587c933e49ac458dc1a221626cb0d Mon Sep 17 00:00:00 2001 From: mberman84 <748450+mberman84@users.noreply.github.com> Date: Tue, 3 Nov 2026 09:32:31 -0800 Subject: [PATCH 2/8] Sign detected PDF fields in one click and suggest common signature lines --- README.md | 9 +++---- scripts/smoke-reader-tools.mjs | 49 ++++++++++++++++++++++++++++++++++ scripts/smoke-test.mjs | 5 +++- src/App.tsx | 45 ++++++++++++++++++------------- src/SignatureDialog.tsx | 19 ++++++++++--- src/SignatureSuggestion.tsx | 36 +++++++++++++++++++++++++ src/markup.ts | 7 +++++ src/signatures.ts | 24 ++++++++++++----- src/styles.css | 5 +++- 9 files changed, 164 insertions(+), 35 deletions(-) create mode 100644 src/SignatureSuggestion.tsx diff --git a/README.md b/README.md index 099a09b..b1e39ee 100644 --- a/README.md +++ b/README.md @@ -99,13 +99,12 @@ URL opening, webpage conversion, and Word conversion require the desktop app. Fa ### Add handwritten signatures - **Capture on paper:** sign with dark ink on white paper, then use your camera or upload a PNG, JPEG, or WebP photo. -- **Clean up the image:** crop to the signature and adjust ink sensitivity to remove the paper background. Capture - and image processing stay on your device. -- **Suggested placement:** Folio checks the current page for empty PDF signature fields and likely signature labels, - then offers places to sign. Detection is a suggestion, not a guarantee that every field will be found. +- **Clean up the image:** Folio removes the paper background and trims the image on your device. Use **Adjust crop and ink** if you need to refine it. +- **Sign a detected field:** when the current page has one empty signature field and one saved signature, click **Sign with** followed by its name. With several saved signatures, choose one and click **Sign field**. +- **Suggested placement:** Folio also recognizes printed labels such as **Approved by** and **Initials** in PDFs with embedded text. Click **Review signature** to see the suggested position. - **Preview and position:** review the actual page, pick a suggestion or place the signature manually, and adjust its width before approving. -- **Explicit approval:** nothing is added until you click **Approve and add signature**. Signatures are visual stamps, +- **Explicit approval:** click the sign button on a detected field or **Approve and add signature** in the preview. Signatures are visual stamps, not certificate-based digital signatures. Use **Save a copy** to keep a signed PDF; placed signatures are not part of Folio's automatic annotation restoration. - **Optional reuse:** select **Remember this signature** and give it a name, such as “Initials”. diff --git a/scripts/smoke-reader-tools.mjs b/scripts/smoke-reader-tools.mjs index 5b2bf31..ee40941 100644 --- a/scripts/smoke-reader-tools.mjs +++ b/scripts/smoke-reader-tools.mjs @@ -150,6 +150,54 @@ async function captureDownload(app, file) { }, file); } +async function checkSignatureFields(app, page, folder) { + const labels = "BT /F 12 Tf 30 190 Td (Approved by:) Tj 0 -110 Td (Initials) Tj ET"; + const form = testPdf([ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R] >> >>", + "<< /Type /Pages /Count 2 /Kids [3 0 R 4 0 R] >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Annots [5 0 R] >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Resources << /Font << /F 6 0 R >> >> /Contents 7 0 R >>", + "<< /Type /Annot /Subtype /Widget /FT /Sig /T (Applicant signature) /Rect [30 110 230 155] /P 3 0 R /F 4 >>", + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", + `<< /Length ${labels.length} >>\nstream\n${labels}\nendstream`, + ]); + await app.evaluate(({ BrowserWindow }, data) => BrowserWindow.getAllWindows()[0].webContents.send( + "folio:open-file", { name: "Signature fields.pdf", data: Buffer.from(data) }), form); + const hint = page.getByRole("region", { name: "Signature suggestion" }); + const quick = hint.getByRole("button", { name: "Sign field" }); + await quick.waitFor(); + assert.ok(await quick.isDisabled()); + await hint.getByRole("combobox").selectOption({ label: "Full name" }); + await quick.click(); + await page.locator(".stampEditor canvas").first().waitFor(); + await hint.waitFor({ state: "hidden" }); + await page.keyboard.press("ControlOrMeta+z"); + await quick.waitFor(); + await page.keyboard.press("ControlOrMeta+Comma"); + await page.getByRole("button", { name: "Forget Signature 1", exact: true }).click(); + await page.keyboard.press("Escape"); + await hint.getByRole("button", { name: "Sign with Full name" }).click(); + await hint.waitFor({ state: "hidden" }); + + await page.getByTitle("Next page").click(); + await hint.getByRole("button", { name: "Review signature" }).click(); + const placement = page.getByRole("combobox", { name: "Signature placement" }); + assert.match(await placement.locator("option:checked").innerText(), /Approved by/); + const approve = page.getByRole("button", { name: "Approve and add signature" }); + await approve.click(); + await hint.getByRole("button", { name: "Review signature" }).click(); + assert.match(await placement.locator("option:checked").innerText(), /Initials/); + await approve.click(); + await page.getByRole("dialog", { name: "Sign page 2" }).waitFor({ state: "hidden" }); + await hint.waitFor({ state: "hidden" }); + const file = path.join(folder, "signed-fields.pdf"); + await captureDownload(app, file); + await page.keyboard.press("ControlOrMeta+s"); + assert.equal(await app.evaluate(() => globalThis.folioReordered), "completed"); + assert.equal(readFileSync(file, "latin1").match(/\/Subtype\s*\/Stamp\b/g)?.length, 3); + console.log("ok detected fields accept a saved signature directly and text suggestions advance to the next line"); +} + export async function checkReaderTools(app, page, folder) { const settings = () => page.keyboard.press(process.platform === "darwin" ? "Meta+Comma" : "Control+Comma"); const wheelSwitch = page.getByRole("switch", { name: "Scroll one page at a time" }); @@ -270,5 +318,6 @@ export async function checkReaderTools(app, page, folder) { await page.getByTitle("Next page").click(); assert.equal(await page.locator('.page[data-page-number="2"] .textWidgetAnnotation input').inputValue(), "A filled field"); console.log("ok the normal Save shortcut and Open reordered copy preserve filled form fields"); + await checkSignatureFields(app, page, folder); await checkScanSelection(app, page); } diff --git a/scripts/smoke-test.mjs b/scripts/smoke-test.mjs index 89d9067..dfb4bdc 100644 --- a/scripts/smoke-test.mjs +++ b/scripts/smoke-test.mjs @@ -92,7 +92,7 @@ try { const picker = page.getByRole("combobox", { name: "Saved signature" }); const uploadPhoto = async (url) => { await page.getByLabel("Upload signature photo").setInputFiles({ name: "signature.png", mimeType: "image/png", buffer: Buffer.from(url.split(",")[1], "base64") }); - await page.getByRole("button", { name: /Use this signature/ }).click(); + await page.getByRole("button", { name: "Adjust crop and ink" }).waitFor(); }; const placeAt = async (x, y) => { await page.getByRole("combobox", { name: "Signature placement" }).selectOption("manual"); @@ -131,6 +131,9 @@ try { await sign.click(); assert.deepEqual(await picker.locator("option").allTextContents(), ["Full name"]); await uploadPhoto(photos.initials); + await page.getByRole("button", { name: "Adjust crop and ink" }).click(); + await page.getByLabel("Crop signature photo").waitFor(); + await page.getByRole("button", { name: /Use this signature/ }).click(); await remember.check(); await placeAt(100, 130); await approve(); diff --git a/src/App.tsx b/src/App.tsx index 5b2840a..6817d65 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -30,9 +30,10 @@ import { ZoomMenu } from "./ZoomMenu"; import { SearchBar, type FindResult } from "./SearchBar"; import { AboutDialog, InfoDialog, OpenUrlDialog, PasswordDialog, ShortcutsDialog, parseWebUrl } from "./Dialogs"; import { SignatureDialog } from "./SignatureDialog"; +import { SignatureSuggestion } from "./SignatureSuggestion"; import { SettingsDialog } from "./SettingsDialog"; import { ChangelogDialog } from "./ChangelogDialog"; -import { detectSignatureTargets, placeSignature, rememberSignature, type SignatureTarget } from "./signatures"; +import { detectSignatureTargets, placeSignature, rememberSignature, uncoveredTargets, type SignatureImage, type SignatureTarget } from "./signatures"; import { keepDrawingPointer } from "./drawing"; import { enableWheelPaging } from "./wheelPaging"; @@ -160,8 +161,10 @@ export default function App() { const [error, setError] = useState(null); const [updateVersion, setUpdateVersion] = useState(null); const [signing, setSigning] = useState(false); - const [signatureTargets, setSignatureTargets] = useState([]); - const [signatureDismissed, setSignatureDismissed] = useState(false); + const [detection, setDetection] = useState<{ pdf: PDFDocumentProxy; page: number; targets: SignatureTarget[] } | null>(null); + const signatureTargets = detection?.targets.length && detection.pdf === doc?.pdf && detection.page === page + ? uncoveredTargets(detection.targets, markupRef.current?.stampRects(page - 1) ?? []) : []; + const [dismissedSignaturePages, setDismissedSignaturePages] = useState([]); const [markup, setMarkup] = useState({ marks: [], note: "" }); const [sidebarTab, setSidebarTab] = useState("pages"); const [noteBox, setNoteBox] = useState<{ markId: string; anchor: { x: number; top: number; bottom: number }; quote: string; initial: string } | null>(null); @@ -175,16 +178,17 @@ export default function App() { const [aiContext, setAiContext] = useState(null); useEffect(() => { - setSigning(false); setSignatureTargets([]); setSignatureDismissed(false); + setSigning(false); if (!doc) return; let cancelled = false; const timer = setTimeout(() => { void detectSignatureTargets(doc.pdf, page).then(targets => { - if (!cancelled) setSignatureTargets(targets); + if (!cancelled) setDetection({ pdf: doc.pdf, page, targets }); }).catch(() => {}); }, 350); return () => { cancelled = true; clearTimeout(timer); }; }, [doc, page]); + useEffect(() => { setDismissedSignaturePages([]); setDetection(null); }, [doc]); docRef.current = doc; unsavedRef.current = unsaved; @@ -559,6 +563,19 @@ export default function App() { } }; const startSigning = () => { chooseTool("select"); setSigning(true); }; + const dismissSignatureSuggestion = () => setDismissedSignaturePages(pages => pages.includes(page) ? pages : [...pages, page]); + const addSignature = async (image: SignatureImage, rect: number[], rememberAs?: string) => { + if (!doc || docRef.current !== doc || pageRef.current !== page) throw new Error("The page changed. Open Sign again."); + chooseTool("select"); + await placeSignature(viewerRef.current!, doc.pdf, page, image, rect); + if (docRef.current !== doc) return; + setDirty(true); + if (rememberAs !== undefined) { + try { rememberSignature(image, rememberAs); } + catch { flash("Signature added to the page, but couldn't be remembered on this device."); return; } + } + flash(keys("Signature added. Ctrl+Z to undo; Save copy to export.")); + }; const chooseColor = (hex: string) => { setColors((c) => ({ ...c, [tool]: hex })); @@ -1350,20 +1367,10 @@ export default function App() { {doc && imageView && setImageView(null)} />} {dialog === "url" && setDialog(null)} onSubmit={(url) => { setDialog(null); openUrl(url); }} />} {doc && signing && setSigning(false)} onApprove={async (signature, rect, rememberAs) => { - await placeSignature(viewerRef.current!, doc.pdf, page, signature, rect); - setDirty(true); setSignatureDismissed(true); - if (rememberAs !== undefined) { - try { rememberSignature(signature, rememberAs); } - catch { flash("Signature added to the page, but couldn't be remembered on this device."); return; } - } - flash(keys("Signature added. Ctrl+Z to undo; Save copy to export.")); - }} />} - {doc && !signing && signatureTargets.length > 0 && !signatureDismissed &&
- {signatureTargets[0].kind === "field" ? "Signature field detected" : "Possible signature area"} on page {page} - - -
} + onClose={() => setSigning(false)} onApprove={addSignature} />} + {doc && !signing && !dialog && signatureTargets.length > 0 && !dismissedSignaturePages.includes(page) && + } {updateVersion && (
diff --git a/src/SignatureDialog.tsx b/src/SignatureDialog.tsx index a32c807..2eedc34 100644 --- a/src/SignatureDialog.tsx +++ b/src/SignatureDialog.tsx @@ -16,6 +16,7 @@ export function SignatureDialog({ pdf, pageNumber, targets, onApprove, onClose } const [remember, setRemember] = useState(false); const [name, setName] = useState(""); const [source, setSource] = useState(null); + const originalPhoto = useRef(null); const [crop, setCrop] = useState(null); const [threshold, setThreshold] = useState(180); const [camera, setCamera] = useState(false); @@ -23,7 +24,8 @@ export function SignatureDialog({ pdf, pageNumber, targets, onApprove, onClose } const [cameraStarting, setCameraStarting] = useState(false); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); - const [targetId, setTargetId] = useState(targets[0]?.id || "manual"); + const [chosenTarget, setTargetId] = useState(null); + const targetId = chosenTarget ?? targets[0]?.id ?? "manual"; const [manualCenter, setManualCenter] = useState(null); const [size, setSize] = useState(150); const [preview, setPreview] = useState<{ url: string; width: number; height: number; viewport: PageViewport } | null>(null); @@ -106,7 +108,14 @@ export function SignatureDialog({ pdf, pageNumber, targets, onApprove, onClose } const factor = Math.min(1, 1600 / Math.max(width, height)); const canvas = document.createElement("canvas"); canvas.width = Math.round(width * factor); canvas.height = Math.round(height * factor); canvas.getContext("2d")!.drawImage(image, 0, 0, canvas.width, canvas.height); - setSource(canvas); setCrop([0, 0, canvas.width, canvas.height]); setRemember(false); setName(""); setSignature(null); setError(""); + const bounds = [0, 0, canvas.width, canvas.height]; + originalPhoto.current = canvas; + setCrop(bounds); setThreshold(180); setRemember(false); setName(""); + try { + setSignature(cleanSignature(canvas, bounds, 180)); setSource(null); setError(""); + } catch (reason) { + setSignature(null); setSource(canvas); setError((reason as Error).message); + } }; const capture = () => { const video = videoRef.current; @@ -157,6 +166,7 @@ export function SignatureDialog({ pdf, pageNumber, targets, onApprove, onClose } {signatures.length > 0 && !source && !camera && } {ready && !saved && remember &&