diff --git a/README.md b/README.md index a899282..efab990 100644 --- a/README.md +++ b/README.md @@ -141,17 +141,17 @@ The editor works with unsigned, unencrypted PDFs. Choose **Sign** in the toolbar to add a signature. - **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:** click an empty PDF signature field, then choose your saved signature or initials from the picker beside it. The chosen image fits the field. If you have no saved signatures yet, clicking the field opens capture with that field selected. A page with a single field also offers a signing shortcut at the bottom. +- **Suggested placement:** On PDFs with selectable text, click a printed line labeled **Signature** or **Initials** to pick a saved mark beside it. Folio recognizes drawn rules and underscores. When it finds only a possible signing area, **Review signature** lets you check the placement. - **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:** choose to remember a signature on this computer; remove the saved image in - **Settings → Storage → 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 → Storage → Signatures**. ### Ask AI about a document @@ -319,8 +319,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 provider credentials, 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 provider credentials, 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 5653871..ce80863 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -67,7 +67,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-reader-tools.mjs b/scripts/smoke-reader-tools.mjs index 652267f..f473f93 100644 --- a/scripts/smoke-reader-tools.mjs +++ b/scripts/smoke-reader-tools.mjs @@ -268,6 +268,189 @@ 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 lines = [ + "q 1 0 0 1 30 225 cm 0 0 m 200 0 l S Q BT /F 12 Tf 30 208 Td (Signature) Tj ET", + "BT /F 12 Tf 30 140 Td (Initials: ____________) Tj ET", + "30 65 m 170 65 l S BT /F 12 Tf 30 50 Td (Witness signature) Tj ET", + "BT /F 10 Tf 30 20 Td (Your signature confirms approval.) Tj ET", + ].join("\n"); + // Page 4 has no PDF signature field: a sentence that mentions signing, then a captioned rule. + const prose = [ + "BT /F 10 Tf 30 250 Td (This agreement may be amended only by a) Tj 0 -14 Td (writing signed by both parties.) Tj ET", + "30 65 m 170 65 l S BT /F 12 Tf 30 50 Td (Witness signature) Tj ET", + ].join("\n"); + const form = testPdf([ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 8 0 R 11 0 R] >> >>", + "<< /Type /Pages /Count 4 /Kids [3 0 R 4 0 R 9 0 R 12 0 R] >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [20 30 320 330] /Rotate 90 /Annots [5 0 R 8 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`, + "<< /Type /Annot /Subtype /Widget /FT /Sig /T (Approval initials) /Rect [45 60 107 92] /P 3 0 R /F 4 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Annots [11 0 R] /Resources << /Font << /F 6 0 R >> >> /Contents 10 0 R >>", + `<< /Length ${lines.length} >>\nstream\n${lines}\nendstream`, + "<< /Type /Annot /Subtype /Widget /FT /Sig /T (Witness signature) /Rect [30 65 170 105] /P 9 0 R /F 4 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Resources << /Font << /F 6 0 R >> >> /Contents 13 0 R >>", + `<< /Length ${prose.length} >>\nstream\n${prose}\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 field = page.getByRole("button", { name: "Sign Applicant signature", exact: true }); + const initials = page.getByRole("button", { name: "Sign Approval initials", exact: true }); + const fieldPicker = page.getByRole("dialog", { name: "Sign Applicant signature", exact: true }); + async function clickAtPageFraction(button, x, y) { + await button.scrollIntoViewIfNeeded(); + const position = await button.evaluate((el, point) => { + const paper = el.closest(".page").querySelector(".canvasWrapper").getBoundingClientRect(); + const bounds = el.getBoundingClientRect(); + return { x: paper.x + point.x * paper.width - bounds.x - el.clientLeft, + y: paper.y + point.y * paper.height - bounds.y - el.clientTop }; + }, { x, y }); + await button.click({ position }); + } + await field.waitFor(); + await page.getByRole("button", { name: "Edit mode", exact: true }).click(); + await field.waitFor({ state: "hidden" }); + await page.getByRole("button", { name: "Sign", exact: true }).click(); + await page.getByRole("dialog", { name: "Sign page 1", exact: true }).getByRole("button", { name: "Cancel" }).click(); + await field.waitFor(); + const saved = await page.evaluate(() => { + const entries = Object.entries(localStorage).filter(([key]) => key === "folio:signature" || key.startsWith("folio:signature:")); + for (const [key] of entries) localStorage.removeItem(key); + return entries; + }); + await initials.click(); + const capture = page.getByRole("dialog", { name: "Sign page 1", exact: true }); + const image = JSON.parse(saved[0][1]).url.split(",")[1]; + await capture.getByLabel("Upload signature photo").setInputFiles({ name: "first.png", mimeType: "image/png", buffer: Buffer.from(image, "base64") }); + assert.equal(await capture.getByRole("combobox", { name: "Signature placement" }).locator("option:checked").innerText(), "Approval initials"); + await capture.getByRole("button", { name: "Cancel" }).click(); + await page.evaluate(entries => { for (const [key, value] of entries) localStorage.setItem(key, value); }, saved); + await page.getByTitle(/^Zoom in/).click(); + // Hit the PDF field's real center after zooming a rotated page with an offset crop box. + await clickAtPageFraction(field, (132.5 - 30) / 300, (130 - 20) / 300); + await fieldPicker.getByRole("button", { name: "Full name", exact: true }).waitFor(); + await page.keyboard.press("Escape"); + await fieldPicker.waitFor({ state: "hidden" }); + assert.equal(await page.locator(".stampEditor").count(), 0); + await field.press("Enter"); + await fieldPicker.getByRole("button", { name: "Full name", exact: true }).waitFor(); + await page.keyboard.press("ControlOrMeta+="); + await fieldPicker.getByRole("button", { name: "Full name", exact: true }).click(); + await field.waitFor({ state: "hidden" }); + await initials.click(); + await page.getByRole("dialog", { name: "Sign Approval initials" }).getByRole("button", { name: "Signature 1", exact: true }).click(); + await initials.waitFor({ state: "hidden" }); + assert.equal(await page.getByRole("dialog", { name: "Sign page 1" }).count(), 0); + // Two saved marks can share a name, so the shortcut shows each mark's image. + const other = saved.map(([key, value]) => ({ key, ...JSON.parse(value) })) + .find(mark => mark.key === "folio:signature" || mark.name !== "Full name"); + await page.evaluate(mark => localStorage.setItem("folio:signature:same-name-check", JSON.stringify(mark)), + { url: other.url, width: other.width, height: other.height, name: "Full name" }); + await page.keyboard.press("ControlOrMeta+z"); + await initials.waitFor(); + const sameName = hint.getByRole("button", { name: "Sign with Full name", exact: true }); + await sameName.first().waitFor(); + const shown = await sameName.locator("img").evaluateAll(images => images.map(image => image.src)); + assert.equal(shown.length, 2); + assert.notEqual(shown[0], shown[1], "marks that share a name show different images"); + assert.ok(shown.includes(other.url)); + await hint.getByRole("button", { name: "Sign with Signature 1", exact: true }).waitFor(); + await sameName.nth(shown.indexOf(other.url)).click(); + await initials.waitFor({ state: "hidden" }); + await hint.waitFor({ state: "hidden" }); + await page.evaluate(() => localStorage.removeItem("folio:signature:same-name-check")); + await page.keyboard.press("ControlOrMeta+z"); + await initials.waitFor(); + await hint.getByRole("button", { name: "Sign with Signature 1", exact: true }).waitFor(); + await page.keyboard.press("ControlOrMeta+Comma"); + await page.getByRole("dialog", { name: "Settings" }).getByRole("button", { name: "Storage", exact: true }).click(); + await page.getByRole("button", { name: "Forget Full name", exact: true }).click(); + await page.keyboard.press("Escape"); + await hint.getByRole("button", { name: "Sign with Signature 1" }).click(); + await hint.waitFor({ state: "hidden" }); + console.log("ok native signature fields support capture, keyboard selection, zoom and undo"); + + 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 page.getByRole("dialog", { name: "Sign page 2" }).waitFor({ state: "hidden" }); + const inferred = page.locator('.page[data-page-number="2"]').getByRole("button", { name: "Sign Initials", exact: true }); + await inferred.click(); + await page.getByRole("dialog", { name: "Sign Initials", exact: true }).getByRole("button", { name: "Signature 1", exact: true }).click(); + await inferred.waitFor({ state: "hidden" }); + await hint.waitFor({ state: "hidden" }); + await page.evaluate(entries => { for (const [key, value] of entries) localStorage.setItem(key, value); }, saved); + await page.getByTitle("Next page").click(); + const thirdPage = page.locator('.page[data-page-number="3"]'); + const printed = thirdPage.getByRole("button", { name: "Sign Signature", exact: true }); + const printedInitials = thirdPage.getByRole("button", { name: "Sign Initials", exact: true }); + await printed.waitFor(); + assert.equal(await thirdPage.locator(".signature-hit").count(), 3, "two printed lines and one native field"); + // Click the ink itself, first on the drawn rule, then on underscores beside the initials label. + await clickAtPageFraction(printed, 130 / 300, 1 - 225 / 300); + await page.getByRole("dialog", { name: "Sign Signature", exact: true }).getByRole("button", { name: "Full name", exact: true }).click(); + await printed.waitFor({ state: "hidden" }); + await clickAtPageFraction(printedInitials, 105 / 300, 1 - 139 / 300); + await page.getByRole("dialog", { name: "Sign Initials", exact: true }).getByRole("button", { name: "Signature 1", exact: true }).click(); + await printedInitials.waitFor({ state: "hidden" }); + await thirdPage.locator(".stampEditor canvas").nth(1).waitFor(); + assert.equal(await page.getByRole("dialog", { name: "Sign page 3", exact: true }).count(), 0); + await page.keyboard.press("ControlOrMeta+z"); + await printedInitials.waitFor(); + await page.keyboard.press("ControlOrMeta+Shift+z"); + await thirdPage.locator(".stampEditor canvas").nth(1).waitFor(); + await printedInitials.waitFor({ state: "hidden" }); + // A sentence that mentions signing is not a place to sign; the captioned rule on the same page is. + await page.getByTitle("Next page").click(); + const fourthPage = page.locator('.page[data-page-number="4"]'); + await fourthPage.getByRole("button", { name: "Sign Witness signature", exact: true }).waitFor(); + assert.equal(await fourthPage.locator(".signature-hit").count(), 1); + await page.getByRole("button", { name: "Sign", exact: true }).click(); + const fourthDialog = page.getByRole("dialog", { name: "Sign page 4", exact: true }); + // With two saved marks nothing is preselected, and the placement list appears once a mark is chosen. + await fourthDialog.getByRole("combobox", { name: "Saved signature" }).selectOption({ label: "Signature 1" }); + // The page's places to sign reach the dialog shortly after the page turn. + const placements = fourthDialog.getByRole("combobox", { name: "Signature placement" }).locator("option"); + await placements.filter({ hasText: "Witness signature" }).waitFor({ state: "attached" }); + assert.deepEqual(await placements.allTextContents(), ["Witness signature", "Choose a position on this page"]); + await fourthDialog.getByRole("button", { name: "Cancel" }).click(); + await fourthDialog.waitFor({ state: "hidden" }); + assert.equal(await hint.count(), 0, "contract prose is not suggested as a signing area"); + 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, 6); + const stampCenters = await page.evaluate(async bytes => { + const task = pdfjsLib.getDocument({ data: Uint8Array.from(bytes) }); + try { + const pdf = await task.promise; + return await Promise.all([1, 3].map(async number => { + const annotations = await (await pdf.getPage(number)).getAnnotations(); + return annotations.filter(a => a.subtype === "Stamp").map(({ rect: [x1, y1, x2, y2] }) => + [Math.round((x1 + x2) / 2), Math.round((y1 + y2) / 2)]); + })); + } finally { await task.destroy(); } + }, Array.from(readFileSync(file))); + const [nativeCenters, printedCenters] = stampCenters; + assert.equal(nativeCenters.length, 2); + for (const [x, y] of [[130, 132.5], [76, 76]]) { + assert.ok(nativeCenters.some(([cx, cy]) => Math.abs(cx - x) < 2 && Math.abs(cy - y) < 2), JSON.stringify(nativeCenters)); + } + assert.equal(printedCenters.length, 2); + assert.ok(printedCenters.some(([x, y]) => Math.abs(x - 130) < 2 && Math.abs(y - 245) < 2), JSON.stringify(printedCenters)); + assert.ok(printedCenters.some(([x, y]) => x > 98 && x < 113 && Math.abs(y - 154) < 2), JSON.stringify(printedCenters)); + console.log("ok on-page signing finds native fields, printed rules, underscores and standalone captions, ignores sentences that mention signing, and exports marks at the chosen positions"); +} + async function checkPenDrawing(app, page, folder, shots) { const blank = testPdf(["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Count 1 /Kids [3 0 R] >>", "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 480 320] /Resources << >> >>"]); @@ -1179,6 +1362,7 @@ export async function checkReaderTools(app, page, folder, shots) { 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 organized copy preserve filled form fields"); + await checkSignatureFields(app, page, folder); await checkScanSelection(app, page); await checkContentEditing(app, page, folder, shots); await checkImageInsertion(app, page, folder, shots); diff --git a/scripts/smoke-signature-targets.mjs b/scripts/smoke-signature-targets.mjs index c32b5f2..68288a7 100644 --- a/scripts/smoke-signature-targets.mjs +++ b/scripts/smoke-signature-targets.mjs @@ -18,13 +18,13 @@ export async function checkSignatureTargets(app, page, photo, shots) { await page.locator(".textLayer span:not(.markedContent)").first().waitFor(); await page.getByTitle("Add a signature").click(); await page.getByLabel("Upload signature photo").setInputFiles({ name: "mark.png", mimeType: "image/png", buffer: Buffer.from(photo, "base64") }); - await page.getByRole("button", { name: /Use this signature/ }).click(); + await page.getByRole("button", { name: "Adjust crop and ink" }).waitFor(); const placement = page.getByLabel("Signature placement", { exact: true }); await placement.locator("option").filter({ hasText: "Witness signature" }).waitFor({ state: "attached" }); await placement.selectOption({ index: 0 }); const options = await placement.locator("option").allTextContents(); await page.screenshot({ path: path.join(shots, "signature-targets.png") }); - assert.deepEqual(options, ["Witness signature: __________ (suggested)", "Choose a position on this page"], + assert.deepEqual(options, ["Witness signature", "Choose a position on this page"], "only a standalone signing caption is suggested, never signature-related prose"); await page.getByRole("button", { name: "Cancel", exact: true }).click(); console.log("ok signature detection rejects contract prose and keeps standalone captions"); diff --git a/scripts/smoke-test.mjs b/scripts/smoke-test.mjs index 167d49b..a7fbb3d 100644 --- a/scripts/smoke-test.mjs +++ b/scripts/smoke-test.mjs @@ -194,8 +194,21 @@ try { console.log("ok a sidebar bookmark persists on its own and toggling it leaves the current page in place"); console.log("ok Bookmarked filters the sidebar, jumps to the original page, and updates as bookmarks are removed"); - // A signature is an unsaved edit that must survive a tab switch. - 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"; @@ -204,17 +217,68 @@ 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") }); + 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: "Adjust crop and ink" }).waitFor(); + }; + 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.getByRole("img", { name: "Page 1 placement preview", exact: true }).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.getByRole("img", { name: "Your signature preview", exact: true }).getAttribute("src"); + await placeAt(70, 70); + await approve(); + await sign.click(); + assert.ok(await page.getByRole("img", { name: "Page 1 placement preview", exact: true }).getAttribute("src") !== originalPage, "the preview omitted the first stamp"); + await picker.selectOption({ label: "Full name" }); + assert.ok(await page.getByRole("img", { name: "Your signature preview", exact: true }).getAttribute("src") === fullName); + await placeAt(145, 180); + const proposedWidth = () => page.getByRole("img", { name: "Proposed signature location", exact: true }).evaluate(image => image.style.width); + const width = await proposedWidth(); + await picker.selectOption({ label: "Signature 1" }); + assert.ok(await page.getByRole("img", { name: "Your signature preview", exact: true }).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("dialog", { name: "Settings" }).getByRole("button", { name: "Storage", exact: true }).click(); + 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 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 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(); + 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"); // Stub the PDF viewer handoff in this renderer so printing cannot open a system dialog. await page.evaluate(interceptPdfPrint); @@ -253,7 +317,8 @@ try { await select("Folio sample.pdf"); assert.equal(await page.getByLabel("Page number", { exact: true }).inputValue(), "2"); await page.getByTitle("Previous page").click(); - await page.locator(".stampEditor").waitFor(); + await page.locator(".stampEditor").first().waitFor(); + assert.equal(await page.locator(".stampEditor").count(), 3); assert.deepEqual(await page.window.evaluate(() => window.tabPrompts), []); await select("Another.pdf"); const closeSigned = docs.getByRole("button", { name: "Close Folio sample.pdf, unsaved changes" }); @@ -467,6 +532,9 @@ try { await page.evaluate(() => { Worker.prototype.postMessage = window.folioPostMessage; }); await page.evaluate(() => document.querySelector('.page[data-page-number="1"]').scrollIntoView()); await page.waitForTimeout(800); + const firstPageMarks = '.page[data-page-number="1"] .annotationEditorLayer [id^="pdfjs_internal_editor_"]'; + const marksBefore = await page.locator(firstPageMarks).count(); + assert.equal(marksBefore, 6); await page.keyboard.press("ControlOrMeta+w"); await page.getByRole("button", { name: /Try a sample/ }).waitFor(); // A slow notes read can finish after the reopened PDF is already usable. Hold the result until Save is pressed. @@ -1128,10 +1196,17 @@ try { // Asked again at the end: the windows that convert a webpage or a Word document didn't bring it forward either. await checkStaysHidden(); - await checkSignatureTargets(app, page, photo, shots); + await checkSignatureTargets(app, page, photos.fullName.split(",")[1], shots); assert.deepEqual(failures, []); console.log(`PASS (${process.platform})`); } finally { + // A failed interaction can leave a dirty tab. Closing the disposable profile must not wait on a native prompt. + await app.evaluate(({ BrowserWindow }) => { + for (const win of BrowserWindow.getAllWindows()) { + win.webContents.removeAllListeners("will-prevent-unload"); + win.webContents.on("will-prevent-unload", event => event.preventDefault()); + } + }).catch(() => {}); await app.close(); } diff --git a/src/App.tsx b/src/App.tsx index 4a3a2ff..c2c839b 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -38,6 +38,8 @@ import { ZoomMenu } from "./ZoomMenu"; import { SearchBar, type FindResult } from "./SearchBar"; import { AboutDialog, InfoDialog, OpenUrlDialog, PasswordDialog, ShortcutsDialog, parseWebUrl } from "./Dialogs"; import { SignatureDialog } from "./SignatureDialog"; +import { SignatureFields } from "./SignatureFields"; +import { SignatureSuggestion } from "./SignatureSuggestion"; import { newImageDraft, type ImageDraft } from "./ImagePlacement"; import { ContentEditor, type ContentEditorHandle, type NextSelection } from "./ContentEditor"; import { VersionHistoryPanel } from "./VersionHistoryPanel"; @@ -46,7 +48,7 @@ import { SettingsDialog } from "./SettingsDialog"; import { ChangelogDialog } from "./ChangelogDialog"; import { PrintDialog } from "./PrintDialog"; import type { Release } from "./releaseNotes"; -import { detectSignatureTargets, placeSignature, type SignatureTarget } from "./signatures"; +import { detectSignatureTargets, placeSignature, rememberSignature, uncoveredTargets, type SignatureImage, type SignatureTarget } from "./signatures"; import { keepDrawingPointer } from "./drawing"; import { useOcrSearchRefresh } from "./hooks/ocr"; import { OcrSession, copyWithText, savedMessage } from "./lib/ocr"; @@ -253,9 +255,16 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs const [toast, setToast] = useState(null); 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 [signing, setSigning] = useState<{ page: number; field?: SignatureTarget } | null>(null); + const placingSignature = useRef(false); + const [pendingStamp, setPendingStamp] = useState<{ pdf: PDFDocumentProxy; index: number; previous: number[][] } | null>(null); + // PDF.js exposes the editor before its image is ready for undo. Keep the field in place until insertion completes. + const stampRects = (index: number) => pendingStamp && pendingStamp.pdf === doc?.pdf && pendingStamp.index === index + ? pendingStamp.previous : markupRef.current?.stampRects(index) ?? []; + 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, stampRects(page - 1)) : []; + const [dismissedSignaturePages, setDismissedSignaturePages] = useState([]); const [markup, setMarkup] = useState({ marks: [], note: "", bookmarkedPages: null }); const [sidebarTab, setSidebarTab] = useState("pages"); const [noteBox, setNoteBox] = useState<{ markId: string; anchor: { x: number; top: number; bottom: number }; quote: string; initial: string } | null>(null); @@ -278,17 +287,28 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs } }, [active, doc, focus, dialog, signing, pending, imageView]); + useEffect(() => { setSigning(current => current?.field ? current : null); }, [page]); useEffect(() => { - setSigning(false); setSignatureTargets([]); setSignatureDismissed(false); if (!doc || contentEditing) return; let cancelled = false; - const timer = setTimeout(() => { + const bus = busRef.current; + const refresh = () => { 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); }; + }; + // Undo and redo change stamp coverage without changing the PDF page or the saved notes. + const timer = setTimeout(refresh, 350); + bus?.on("editingaction", refresh); + bus?.on("editingstateschanged", refresh); + return () => { + cancelled = true; + clearTimeout(timer); + bus?.off("editingaction", refresh); + bus?.off("editingstateschanged", refresh); + }; }, [doc, page, contentEditing]); + useEffect(() => { setSigning(null); setDismissedSignaturePages([]); setDetection(null); }, [doc]); docRef.current = doc; preferencesRef.current = { sidebar, spread }; @@ -727,6 +747,28 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs } catch { flash("Annotations aren’t supported for this document"); return false; } }; const leaveEditMode = () => chooseTool("select"); + const startSigning = async () => { if (await chooseTool("select")) setSigning({ page }); }; + const dismissSignatureSuggestion = () => setDismissedSignaturePages(pages => pages.includes(page) ? pages : [...pages, page]); + const addSignature = async (pageNumber: number, image: SignatureImage, rect: number[], rememberAs?: string) => { + if (!doc || docRef.current !== doc || !active) throw new Error("The document changed. Open Sign again."); + if (placingSignature.current) throw new Error("Another signature is being placed."); + placingSignature.current = true; + setPendingStamp({ pdf: doc.pdf, index: pageNumber - 1, previous: stampRects(pageNumber - 1) }); + try { + if (!(await chooseTool("select")) || docRef.current !== doc) throw new Error("The document changed. Open Sign again."); + await placeSignature(viewerRef.current!, doc.pdf, pageNumber, image, rect, !!signing); + } finally { + placingSignature.current = false; + setPendingStamp(null); + } + if (docRef.current !== doc) return; + markDirty(); + 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 insertImage = useCallback(async (file: File) => { const editor = contentRef.current, owner = docRef.current, viewer = viewerRef.current; if (!editor || !owner || !viewer) return; @@ -755,7 +797,6 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs if (request === imageLoad.current && docRef.current === owner) flash(err instanceof Error ? err.message : "Couldn't insert this image."); } }, [flash]); - const startSigning = async () => { if (await chooseTool("select")) setSigning(true); }; useEffect(() => { if (!doc || tool !== "ink" || drawTool === "Pen") return; @@ -1762,16 +1803,17 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs {dialog === "upgrade" && setDialog(null)} />} {doc && imageView && setImageView(null)} />} {dialog === "url" && setDialog(null)} onSubmit={(url) => { setDialog(null); tabs.open([{ kind: "url", name: new URL(url).hostname, url }]); }} />} - {doc && signing && setSigning(false)} onApprove={async (signature, rect) => { - await placeSignature(viewerRef.current!, doc.pdf, page, signature, rect); - markDirty(); setSignatureDismissed(true); flash(keys("Signature added. Ctrl+Z to undo; Save copy to export.")); - }} />} - {doc && !contentEditing && !signing && signatureTargets.length > 0 && !signatureDismissed &&
- {signatureTargets[0].kind === "field" ? "Signature field detected" : "Possible signature area"} on page {page} - - -
} + {active && doc && !contentEditing && tool === "select" && !dialog && !signing && !imageView && !pending && viewerRef.current && busRef.current && + setSigning({ page: pageNumber, field })} />} + {doc && signing && setSigning(null)} + onApprove={(image, rect, name) => addSignature(signing.page, image, rect, name)} />} + {active && doc && !contentEditing && tool === "select" && !signing && !dialog && signatureTargets.length > 0 && !dismissedSignaturePages.includes(page) && + ((signatureTargets.length === 1 && signatureTargets[0].kind === "field") || signatureTargets.some(target => target.kind === "label")) && + addSignature(page, image, rect)} + onReview={startSigning} onDismiss={dismissSignatureSuggestion} />} {updateVersion && (
diff --git a/src/SettingsDialog.tsx b/src/SettingsDialog.tsx index d2a65b8..8295cee 100644 --- a/src/SettingsDialog.tsx +++ b/src/SettingsDialog.tsx @@ -5,6 +5,7 @@ import { CLAUDE_CODE_URL, PROVIDERS, savedProvider, saveAiPreference, signInChat import { OpenRouterSettings } from "./OpenRouterSettings"; import { CustomEndpointSettings } from "./CustomEndpointSettings"; import { updateSummary } from "./updates"; +import { readSignatures } from "./signatures"; import { ScanLanguagePicker } from "./ScanLanguagePicker"; import type { ScanLanguage } from "./scanLanguage"; import { Icon } from "./icons"; @@ -186,10 +187,7 @@ export function SettingsDialog({ initialSection = "General", theme, onTheme, nig return () => { current = false; }; }, [ai, section]); - // Signature - const [savedSignature, setSavedSignature] = useState(() => { - try { return !!localStorage.getItem("folio:signature"); } catch { return false; } - }); + const [signatures, setSignatures] = useState(readSignatures); return ( @@ -273,15 +271,15 @@ export function SettingsDialog({ initialSection = "General", theme, onTheme, nig -
- - - + )}
} {desktop && section === "General" && ( diff --git a/src/SignatureDialog.tsx b/src/SignatureDialog.tsx index 9a30d3a..6767c39 100644 --- a/src/SignatureDialog.tsx +++ b/src/SignatureDialog.tsx @@ -1,19 +1,22 @@ 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 originalPhoto = useRef(null); const [crop, setCrop] = useState(null); const [threshold, setThreshold] = useState(180); const [camera, setCamera] = useState(false); @@ -21,8 +24,9 @@ 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 [manualRect, setManualRect] = useState(null); + 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); const videoRef = useRef(null); @@ -33,8 +37,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 +55,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)); }); @@ -111,7 +115,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); setSaved(false); 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; @@ -128,7 +139,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(); @@ -139,26 +150,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(); }}>
@@ -172,7 +170,18 @@ 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.

} @@ -196,10 +205,14 @@ export function SignatureDialog({ pdf, pageNumber, targets, onApprove, onClose } try { setSignature(cleanSignature(source, crop!, threshold)); setSource(null); setError(""); } catch (reason) { setError((reason as Error).message); } }}>Use this signature - +
} {signature && !camera &&
Your signature preview Background removed
} - {ready && } + {ready && originalPhoto.current && } + {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.

@@ -207,30 +220,27 @@ 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; + setTargetId("manual"); 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 (event.altKey || !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)); + setTargetId("manual"); + 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/SignatureFields.tsx b/src/SignatureFields.tsx new file mode 100644 index 0000000..81f5770 --- /dev/null +++ b/src/SignatureFields.tsx @@ -0,0 +1,154 @@ +import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; +import { createPortal } from "react-dom"; +import type { PageViewport } from "pdfjs-dist"; +import type { PDFDocumentProxy } from "./pdf"; +import type { EventBus, PDFViewer } from "./viewer"; +import { Icon } from "./icons"; +import { detectSignatureTargets, fitSignature, readSignatures, uncoveredTargets, type SavedSignature, type SignatureImage, type SignatureTarget } from "./signatures"; + +interface FieldActions { + placing: boolean; + stampRects: (pageIndex: number) => number[][]; + onSign: (page: number, image: SignatureImage, rect: number[]) => Promise; + onCapture: (page: number, target: SignatureTarget) => void; +} +interface PageView { id: number; div: HTMLDivElement; viewport: PageViewport } +interface Pick { field: SignatureTarget; button: HTMLButtonElement; saved: SavedSignature[] } + +function FieldPicker({ pick, close, onSign, container }: { + pick: Pick; close: () => void; container: HTMLDivElement; onSign: (image: SavedSignature) => Promise; +}) { + const card = useRef(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + useLayoutEffect(() => { + const menu = card.current!; + const anchor = pick.button; + let dismissTimer: number | undefined; + const outsideView = (a: DOMRect, stage: DOMRect) => + a.bottom <= stage.top || a.top >= stage.bottom || a.right <= stage.left || a.left >= stage.right; + const position = () => { + // The page renderer can briefly detach the field during a zoom redraw. + if (!anchor.isConnected || !anchor.offsetWidth || !anchor.offsetHeight) return; + const a = anchor.getBoundingClientRect(), stage = container.getBoundingClientRect(); + if (outsideView(a, stage)) { + menu.style.visibility = "hidden"; + if (dismissTimer === undefined) dismissTimer = window.setTimeout(() => { + dismissTimer = undefined; + if (anchor.isConnected && anchor.offsetWidth && outsideView(anchor.getBoundingClientRect(), container.getBoundingClientRect())) close(); + else position(); + }, 350); + return; + } + window.clearTimeout(dismissTimer); + dismissTimer = undefined; + menu.style.visibility = ""; + const left = Math.max(8, Math.min(a.left, window.innerWidth - menu.offsetWidth - 8)); + const top = a.bottom + menu.offsetHeight + 6 <= window.innerHeight - 8 ? a.bottom + 6 : a.top - menu.offsetHeight - 6; + menu.style.left = left + "px"; + menu.style.top = Math.max(8, Math.min(top, window.innerHeight - menu.offsetHeight - 8)) + "px"; + }; + position(); + menu.querySelector("button")?.focus({ preventScroll: true }); + const outside = (event: Event) => { + if (event.target instanceof Node && !menu.contains(event.target) && !anchor.contains(event.target)) close(); + }; + const onKey = (event: KeyboardEvent) => { + if (event.key === "Escape") { + event.stopPropagation(); event.preventDefault(); close(); anchor.focus({ preventScroll: true }); + } else if (event.key === "Tab" && document.activeElement === menu.querySelector(event.shiftKey ? "button:first-of-type" : "button:last-of-type")) { + close(); anchor.focus({ preventScroll: true }); + } + }; + const size = new ResizeObserver(position); + size.observe(menu); size.observe(container); size.observe(anchor); + container.addEventListener("scroll", position, { passive: true }); + window.addEventListener("resize", position); + document.addEventListener("pointerdown", outside, true); + document.addEventListener("keydown", onKey, true); + return () => { + window.clearTimeout(dismissTimer); + size.disconnect(); + container.removeEventListener("scroll", position); + window.removeEventListener("resize", position); + document.removeEventListener("pointerdown", outside, true); + document.removeEventListener("keydown", onKey, true); + }; + }, [pick, close, container]); + async function choose(image: SavedSignature) { + if (busy) return; + setBusy(true); setError(""); + try { await onSign(image); close(); } + catch (reason) { setError((reason as Error).message); setBusy(false); } + } + return createPortal(
+ {pick.field.label} + {pick.saved.map(image => )} + {error &&

{error}

} +
, document.body); +} + +function PageFields({ pdf, view, container, stampRects, placing, onSign, onCapture }: FieldActions & { + pdf: PDFDocumentProxy; view: PageView; container: HTMLDivElement; +}) { + const [host] = useState(() => Object.assign(document.createElement("div"), { className: "signature-field-layer" })); + const [fields, setFields] = useState([]); + const [pick, setPick] = useState(null); + const close = useCallback(() => setPick(null), []); + useEffect(() => { + let current = true; + void detectSignatureTargets(pdf, view.id).then(targets => { + if (current) setFields(targets.filter(target => target.kind !== "label")); + }).catch(() => {}); + return () => { current = false; }; + }, [pdf, view.id]); + const open = fields.length ? uncoveredTargets(fields, stampRects(view.id - 1)) : []; + const hasFields = open.length > 0; + useLayoutEffect(() => { + if (!hasFields) return; + // PDF.js owns the page's children and can remove this layer before its next pagerendered event. + const attach = () => { + if (host.parentElement !== view.div && view.div.querySelector(".canvasWrapper")) view.div.append(host); + }; + attach(); + const observer = new MutationObserver(attach); + observer.observe(view.div, { childList: true }); + return () => { observer.disconnect(); host.remove(); }; + }, [host, view, hasFields]); + useLayoutEffect(() => { if (pick && !open.includes(pick.field)) close(); }, [pick, open, close]); + if (!hasFields) return null; + const vp = view.viewport; + return <>{createPortal(open.map(field => { + const [left, bottom, right, top] = field.rect; + const [x1, y1] = vp.convertToViewportPoint(left, bottom), [x2, y2] = vp.convertToViewportPoint(right, top); + return ; + }), host)} + {pick && open.includes(pick.field) && onSign(view.id, image, fitSignature(image, pick.field.rect))} />} + ; +} + +export function SignatureFields({ pdf, viewer, bus, ...actions }: FieldActions & { + pdf: PDFDocumentProxy; viewer: PDFViewer; bus: EventBus; +}) { + const [views, setViews] = useState([]); + useLayoutEffect(() => { + const refresh = () => setViews(viewer.pdfDocument === pdf + ? Array.from(viewer.getCachedPageViews()).filter(v => v.div.isConnected && v.pdfPage) : []); + refresh(); + bus.on("pagerendered", refresh); + return () => bus.off("pagerendered", refresh); + }, [pdf, viewer, bus]); + return <>{views.map(view => )}; +} diff --git a/src/SignatureSuggestion.tsx b/src/SignatureSuggestion.tsx new file mode 100644 index 0000000..2a8442a --- /dev/null +++ b/src/SignatureSuggestion.tsx @@ -0,0 +1,30 @@ +import { useState } from "react"; +import { Icon } from "./icons"; +import { fitSignature, readSignatures, type SavedSignature, type SignatureImage, type SignatureTarget } from "./signatures"; + +export function SignatureSuggestion({ targets, page, placing, onSign, onReview, onDismiss }: { + targets: SignatureTarget[]; page: number; placing: boolean; + onSign: (image: SignatureImage, rect: number[]) => Promise; + onReview: () => void; onDismiss: () => void; +}) { + const field = targets.length === 1 && targets[0].kind === "field" ? targets[0] : null; + const [saved] = useState(() => field ? readSignatures() : []); + const [error, setError] = useState(""); + const sign = async (mark: SavedSignature) => { + if (!field || placing) return; + setError(""); + try { await onSign(mark, fitSignature(mark, field.rect)); } + catch (reason) { setError((reason as Error).message); } + }; + return
+ {field?.label || "Possible signature area"} on page {page} + {/* Names can repeat, so each saved mark shows its image and signs in one click. */} + {saved.map(mark => )} + + + {error &&

{error}

} +
; +} diff --git a/src/markup.ts b/src/markup.ts index cb8528d..65e5496 100644 --- a/src/markup.ts +++ b/src/markup.ts @@ -124,6 +124,13 @@ export class MarkupController { return { marks: this.#sorted(), note: this.#note, bookmarkedPages: this.#bookmarkedPages }; } + stampRects(pageIndex: number): number[][] { + if (!this.#ui) return []; + return Array.from(this.#ui.getEditors(pageIndex)) + .filter(editor => editor.constructor._type === "stamp" && !editor.deleted && !editor.isEmpty()) + .map(editor => editor.getPDFRect()); + } + clearEditorSelection() { this.#ui?.unselectAll(); } diff --git a/src/printedSignatureLines.ts b/src/printedSignatureLines.ts new file mode 100644 index 0000000..3ac1599 --- /dev/null +++ b/src/printedSignatureLines.ts @@ -0,0 +1,117 @@ +import { AnnotationMode, OPS, Util, type PDFPageProxy } from "pdfjs-dist"; +import type { TextItem } from "pdfjs-dist/types/src/display/api"; +import type { SignatureTarget } from "./signatures"; + +interface Rule { left: number; right: number; y: number } +const caption = /^(?:(?:your|applicant(?:['’]s)?|signer(?:['’]s)?|approver(?:['’]s)?|approval|authorized|witness(?:['’]s)?)\s+)?(signature|initials)$/i; +// Without a matching rule, only a text run that is nothing but a signing caption is offered. +// A sentence that mentions signing ("a writing signed by both parties") is not a place to sign. +const standalone = /^(?:(?:(?:your|applicant(?:['’]s)?|signer(?:['’]s)?|approver(?:['’]s)?|approval|authorized|witness(?:['’]s)?|client(?:['’]s)?|customer(?:['’]s)?)\s+)?signature|sign here|signed by|approved by)$/i; +const painted = new Set([OPS.stroke, OPS.closeStroke, OPS.fill, OPS.eoFill, OPS.fillStroke, OPS.eoFillStroke, OPS.closeFillStroke, OPS.closeEOFillStroke]); + +async function drawnRules(page: PDFPageProxy): Promise { + const { fnArray, argsArray } = await page.getOperatorList({ annotationMode: AnnotationMode.DISABLE }); + const rules: Rule[] = [], stack: number[][] = []; + let matrix = [1, 0, 0, 1, 0, 0]; + for (let i = 0; i < fnArray.length; i++) { + const op = fnArray[i], args = argsArray[i]; + if (op === OPS.save || op === OPS.paintFormXObjectBegin) { + stack.push(matrix); + if (op === OPS.paintFormXObjectBegin && args[0]) matrix = Util.transform(matrix, args[0]); + } else if (op === OPS.restore || op === OPS.paintFormXObjectEnd) { + matrix = stack.pop() ?? matrix; + } else if (op === OPS.transform) { + matrix = Util.transform(matrix, args); + } else if (op === OPS.constructPath && args[2] && painted.has(args[0])) { + // Exporters use both stroked paths and thin filled rectangles for printed rules. + const bounds = [Infinity, Infinity, -Infinity, -Infinity]; + Util.axialAlignedBoundingBox(args[2], matrix, bounds); + if (bounds[2] - bounds[0] >= 16 && bounds[3] - bounds[1] <= 2) { + rules.push({ left: bounds[0], right: bounds[2], y: (bounds[1] + bounds[3]) / 2 }); + } + } + } + return rules; +} + +function nearbyRule(item: TextItem, rules: Rule[]) { + const [, , , , x, y] = item.transform; + let best: Rule | undefined, distance = Infinity; + for (const rule of rules) { + const gap = rule.left - (x + item.width), dy = rule.y - y; + const beside = gap >= -2 && gap <= 3 * item.height && Math.abs(dy) <= item.height * 0.6; + const aligned = Math.abs(rule.left - x) <= item.height * 1.5; + const above = dy >= item.height * 0.6 && dy <= item.height + 18; + const below = dy <= -12 && dy >= -48; + if (!beside && !(aligned && (above || below))) continue; + const score = beside ? Math.abs(gap) + Math.abs(dy) : Math.abs(rule.left - x) + Math.abs(dy); + if (score < distance) { best = rule; distance = score; } + } + return best; +} + +export async function printedSignatureTargets(page: PDFPageProxy): Promise { + const { items, styles } = await page.getTextContent(); + const text = items.filter((item): item is TextItem => "str" in item); + const labels = text.flatMap((item, index) => { + const label = item.str.replace(/^[_\s]+|[:_\s]+$/g, "").trim(); + const exact = caption.exec(label); + if (!exact && !standalone.test(label)) return []; + if (/digital|electronic|verified|invalid/i.test(label)) return []; + return [{ item, index, label, exact }]; + }); + if (!labels.length) return []; + const rules: Rule[] = []; + if (labels.some(({ exact }) => exact)) { + for (const item of text) { + if (/^_{3,}$/.test(item.str.trim())) rules.push({ left: item.transform[4], right: item.transform[4] + item.width, y: item.transform[5] - item.height * 0.12 }); + } + for (const rule of await drawnRules(page).catch(() => [])) rules.push(rule); + } + const [left, bottom, right, top] = page.view; + const targets: SignatureTarget[] = []; + const used = new Set(); + let suggestions = 0; + const measure = document.createElement("canvas").getContext("2d"); + for (const { item, index, label, exact } of labels) { + const [, , , , x, y] = item.transform; + const initials = exact?.[1].toLowerCase() === "initials"; + const id = "label-" + index; + const horizontalCaption = exact && item.transform[0] > 0 && Math.abs(item.transform[1]) < 0.01; + if (horizontalCaption) { + let rule = nearbyRule(item, rules); + const underline = /_{3,}/.exec(item.str); + if (underline && measure) { + // PDF.js can combine the caption and underline. Scale font metrics to the actual PDF text run. + measure.font = "100px " + (styles[item.fontName]?.fontFamily || "sans-serif"); + const scale = item.width / measure.measureText(item.str).width; + const start = x + measure.measureText(item.str.slice(0, underline.index)).width * scale; + rule = { left: start, right: start + measure.measureText(underline[0]).width * scale, y: y - item.height * 0.12 }; + } + if (rule) { + if (used.has(rule)) continue; + used.add(rule); + const height = Math.min(initials ? 32 : 42, rule.y <= y - 12 ? y - rule.y - 3 : Infinity); + const rect = [Math.max(left, rule.left), Math.max(bottom, rule.y - 2), Math.min(right, rule.right), Math.min(top, rule.y + height)]; + if (rect[2] - rect[0] > 4 && rect[3] - rect[1] > 4) targets.push({ id, label, rect, kind: "line" }); + continue; + } + } + const width = initials ? 64 : 180; + const beside = exact && item.str.trimEnd().endsWith(":") && x + item.width + 8 + width <= right; + const px = Math.max(left, Math.min(beside ? x + item.width + 8 : x, right - width)); + const py = Math.max(bottom, Math.min(beside ? y - 2 : y + Math.max(item.height, 10) + 3, top - 42)); + const rect = [px, py, Math.min(right, px + width), Math.min(top, py + 42)]; + // A rule can be baked into the page image while its caption is selectable. Offer the usual signing + // space only when the caption stands alone and the hit area would leave other text accessible. + const blank = horizontalCaption && !text.some(other => + other.str.trim() && other.transform[4] < rect[2] && other.transform[4] + other.width > rect[0] && + other.transform[5] < rect[3] && other.transform[5] + other.height > rect[1]); + if (blank) targets.push({ id, label, rect, kind: "line" }); + else if (suggestions < 12) { + targets.push({ id, label: label.slice(0, 80) + " (suggested)", rect, kind: "label" }); + suggestions++; + } + } + return targets; +} diff --git a/src/reading-tools.css b/src/reading-tools.css index d098435..bf278fc 100644 --- a/src/reading-tools.css +++ b/src/reading-tools.css @@ -847,6 +847,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 ac40970..9c6f723 100644 --- a/src/signatures.ts +++ b/src/signatures.ts @@ -1,21 +1,30 @@ import { AnnotationEditorType } from "pdfjs-dist"; import type { PDFDocumentProxy } from "./pdf"; import type { PDFViewer } from "./viewer"; +import { printedSignatureTargets } from "./printedSignatureLines"; export interface SignatureImage { url: string; width: number; height: number } -export interface SignatureTarget { id: string; label: string; rect: number[]; kind: "field" | "label" } +export interface SavedSignature extends SignatureImage { key: string; name: string } +export interface SignatureTarget { id: string; label: string; rect: number[]; kind: "field" | "line" | "label" } const cache = new WeakMap>>(); -export function detectSignatureTargets(pdf: PDFDocumentProxy, pageNumber: number) { +export function uncoveredTargets(targets: SignatureTarget[], stamps: number[][]) { + return targets.filter(({ rect }) => !stamps.some(stamp => + stamp[0] < rect[2] && stamp[2] > rect[0] && stamp[1] < rect[3] && stamp[3] > rect[1])); +} + +export async function detectSignatureTargets(pdf: PDFDocumentProxy, pageNumber: number) { let pages = cache.get(pdf); if (!pages) cache.set(pdf, pages = new Map()); let result = pages.get(pageNumber); if (!result) { - result = (async () => { + result = (async (): Promise => { const page = await pdf.getPage(pageNumber); const annotations = await page.getAnnotations(); const signedFields = await pdf.getSignatures(); if (signedFields?.length) return []; + const stamps = annotations.filter(annotation => annotation.subtype === "Stamp" && annotation.rect?.length === 4) + .map(annotation => annotation.rect); const fields: SignatureTarget[] = annotations.filter(annotation => annotation.subtype === "Widget" && annotation.fieldType === "Sig" && !annotation.fieldValue && !(annotation.fieldFlags & 1) && !(annotation.annotationFlags & 35) && annotation.rect.length === 4 && annotation.rect.every(Number.isFinite)) @@ -23,18 +32,11 @@ export function detectSignatureTargets(pdf: PDFDocumentProxy, pageNumber: number rect: [Math.max(page.view[0], annotation.rect[0]), Math.max(page.view[1], annotation.rect[1]), Math.min(page.view[2], annotation.rect[2]), Math.min(page.view[3], annotation.rect[3])], kind: "field" })) .filter(target => target.rect[2] - target.rect[0] > 4 && target.rect[3] - target.rect[1] > 4); - if (fields.length) return fields; - const text = await page.getTextContent(); - return text.items.flatMap((item, index): SignatureTarget[] => { - // A word in a paragraph is not a signing caption. Keep this fallback conservative; - // native PDF signature fields above are the authoritative targets. - if (!("str" in item) || !/^(?:(?:your|applicant(?:['’]s)?|signer(?:['’]s)?|authorized|witness(?:['’]s)?|client|customer)\s+)?(?:signature|sign here|signed by)\s*[:_\s]*$/i.test(item.str.trim())) return []; - const [left, bottom, right, top] = page.view; - const positionX = Math.max(left, Math.min(item.transform[4], right - Math.min(180, right - left))); - const positionY = Math.max(bottom, Math.min(item.transform[5] + Math.max(item.height, 10) + 3, top - 42)); - return [{ id: "label-" + index, label: item.str.trim().slice(0, 80) + " (suggested)", - rect: [positionX, positionY, Math.min(right, positionX + 180), Math.min(top, positionY + 42)], kind: "label" }]; - }).slice(0, 12); + // A printed caption for a native control must never create a second hit area, including over a locked field. + const widgets = annotations.filter(annotation => annotation.subtype === "Widget" && annotation.rect?.length === 4); + const printed = await printedSignatureTargets(page).catch(() => []); + const clear = uncoveredTargets(printed, [...stamps, ...widgets.map(widget => widget.rect)]); + return [...uncoveredTargets(fields, stamps), ...clear.filter(target => !fields.length || target.kind === "line")]; })(); pages.set(pageNumber, result); result.catch(() => pages!.delete(pageNumber)); @@ -53,9 +55,18 @@ export function fitSignature(signature: SignatureImage, bounds: number[]) { return [positionX, positionY, positionX + fittedWidth, positionY + fittedHeight]; } -export async function placeSignature(viewer: PDFViewer, pdf: PDFDocumentProxy, pageNumber: number, signature: SignatureImage, rect: number[]) { +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[], navigate = true) { if (viewer.pdfDocument !== pdf) throw new Error("The document changed. Open Sign again."); - viewer.currentPageNumber = pageNumber; + if (navigate) viewer.currentPageNumber = pageNumber; viewer.annotationEditorMode = { mode: AnnotationEditorType.STAMP }; try { let layer; @@ -111,11 +122,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 e6cdd4b..d9975bd 100644 --- a/src/styles.css +++ b/src/styles.css @@ -1437,7 +1437,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; } @@ -1457,7 +1457,22 @@ kbd { .signature-empty { padding-top: 12px; } } .signature-suggestion { position: fixed; bottom: 60px; left: 50%; transform: translateX(-50%); z-index: 20; display: flex; align-items: center; gap: 12px; background: var(--bg); color: var(--text); border: 1px solid var(--line-strong); padding: 12px 16px; border-radius: 12px; box-shadow: var(--shadow-lg); max-width: calc(100vw - 24px); font-size: 13px; } -.signature-suggestion > span { min-width: 100px; } +.signature-suggestion { width: max-content; flex-wrap: wrap; justify-content: center; } +.signature-suggestion > span, .signature-suggestion .btn { max-width: 100%; overflow-wrap: anywhere; } +.signature-suggestion-mark { display: flex; align-items: center; gap: 8px; max-width: 100%; padding: 4px 10px 4px 4px; color: var(--text); background: var(--surface); border: 1px solid var(--line-strong); border-radius: 8px; text-align: left; overflow-wrap: anywhere; } +.signature-suggestion-mark:hover:not(:disabled), .signature-suggestion-mark:focus-visible { background: var(--hover); } +.signature-suggestion-mark:disabled { opacity: 0.6; } +.signature-suggestion-mark img { flex: none; width: 76px; height: 32px; padding: 3px 5px; object-fit: contain; background: white; border: 1px solid var(--line); border-radius: 4px; } +.signature-suggestion .form-error { margin: 0; width: 100%; } +.signature-field-layer { position: absolute; inset: 0; z-index: 4; pointer-events: none; } +.signature-hit { position: absolute; pointer-events: auto; display: flex; align-items: center; justify-content: center; gap: 5px; overflow: hidden; padding: 0; border: 1px dashed #c34b37; border-radius: 4px; background: #fff1eae6; color: #8d3020; font: 600 12px var(--font); } +.signature-hit:hover, .signature-hit[aria-expanded="true"] { border-style: solid; background: #ffe2d6; } +.signature-field-picker { position: fixed; z-index: 100; display: grid; gap: 4px; width: min(238px, calc(100vw - 16px)); max-height: min(300px, calc(100dvh - 16px)); overflow: auto; padding: 8px; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--surface); color: var(--text); box-shadow: var(--shadow-lg); } +.signature-field-picker > strong { padding: 4px 6px; overflow-wrap: anywhere; color: var(--text-2); font-size: 12px; } +.signature-field-picker > button { display: flex; align-items: center; gap: 10px; padding: 6px; border-radius: 6px; text-align: left; overflow-wrap: anywhere; } +.signature-field-picker > button:hover, .signature-field-picker > button:focus-visible { background: var(--hover); } +.signature-field-picker img { flex: none; width: 76px; height: 32px; padding: 3px 5px; object-fit: contain; background: white; border: 1px solid var(--line); border-radius: 4px; } +body:has(.signature-field-picker) .signature-suggestion { display: none; } @keyframes modal-in { from { opacity: 0;