Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Redesign the Sign tool around a saved signature (#8208)

Anthony Stirling0b937e0cc1b0
diff --git a/frontend/editor/public/locales/en-GB/translation.toml b/frontend/editor/public/locales/en-GB/translation.toml
index 0f6109de55..6b8c95e473 100644
--- a/frontend/editor/public/locales/en-GB/translation.toml
+++ b/frontend/editor/public/locales/en-GB/translation.toml
@@ -12131,6 +12131,163 @@ saved = "Saved"
text = "Text"
title = "Signature Type"
+[sign.wallet]
+apply_one = "Apply {{count}} signature"
+apply_other = "Apply {{count}} signatures"
+applyEmpty = "Apply signatures"
+count = "{{count}} of {{max}}"
+default = "Default"
+loading = "Loading your signatures..."
+new = "New signature"
+shared = "Shared"
+sharedHint = "Everyone can use these"
+unsaved = "Unsaved"
+yours = "Your signatures"
+
+[sign.wallet.create]
+cancel = "Cancel"
+full = "Your library is full ({{max}} signatures). Delete one to save more."
+makeDefault = "Make default"
+method = "How to create it"
+name = "Name"
+save = "Save to my signatures"
+saveBrowserHint = "Kept in this browser, ready for next time."
+saveHint = "Ready to reuse next time you sign."
+subtitle = "Create it once, reuse it on any document."
+title = "New signature"
+use = "Use signature"
+who = "Who can use it"
+whoEveryone = "Everyone"
+whoMe = "Only me"
+
+[sign.wallet.defaultName]
+draw = "My signature"
+initials = "Initials"
+phone = "Phone signature"
+type = "Typed signature"
+upload = "Uploaded signature"
+
+[sign.wallet.delete]
+body = "\"{{name}}\" is removed from your signatures. Documents you already signed keep it."
+confirm = "Delete"
+title = "Delete this signature?"
+
+[sign.wallet.draw]
+bold = "Bold pen"
+clear = "Clear"
+fine = "Fine pen"
+hint = "Sign above the line"
+medium = "Medium pen"
+pad = "Signature pad"
+pen = "Pen"
+tip = "Use a mouse, trackpad, pen or finger"
+undo = "Undo"
+
+[sign.wallet.ink]
+black = "Black ink"
+blue = "Blue ink"
+label = "Ink"
+navy = "Navy ink"
+
+[sign.wallet.intro]
+body = "Create it once. It is saved here, ready for every document you sign."
+privacy = "Saved signatures are private to you unless you choose to share them."
+privacyBrowser = "Saved signatures stay in this browser."
+title = "Add your signature"
+
+[sign.wallet.menu]
+delete = "Delete"
+discard = "Discard"
+makeDefault = "Make default"
+options = "Options for {{name}}"
+place = "Place on page"
+removeDefault = "Remove as default"
+rename = "Rename"
+save = "Save to my signatures"
+share = "Share with everyone"
+stop = "Stop placing"
+
+[sign.wallet.phone]
+expires = "Expires in {{time}}"
+qr = "QR code to sign on your phone"
+received = "Received from your phone"
+receiveFailed = "Could not read that signature. Scan the new code to try again."
+step1 = "Scan the code with your phone camera"
+step1Hint = "It opens in the phone browser, no app needed."
+step2 = "Draw, type or photograph your signature"
+step2Hint = "A big canvas made for a finger."
+step3 = "It appears here automatically"
+step3Hint = "Keep this window open while you sign."
+waiting = "Waiting for your phone..."
+
+[sign.wallet.placed]
+empty = "Signatures you place on the page are listed here."
+fallbackName = "Signature"
+page = "Page {{page}}"
+remove = "Remove {{name}}"
+show = "Show {{name}} on the page"
+title = "On this document ({{count}})"
+
+[sign.wallet.rename]
+save = "Save"
+title = "Rename signature"
+
+[sign.wallet.status]
+idle = "Pick a signature to place it"
+placing = "Click the page to place {{name}}."
+stop = "Stop"
+
+[sign.wallet.tabs]
+draw = "Draw"
+phone = "Phone"
+type = "Type"
+upload = "Upload"
+
+[sign.wallet.toast]
+applyFailed = "Could not apply signatures"
+applyFailedBody = "Your signatures are still on the document. Try again."
+deleteFailed = "Could not delete the signature"
+draftExists = "Save or discard your unsaved signature first"
+initialsFailed = "Could not save your initials"
+initialsPartial = "Your signature was saved, but your initials were not. Try saving your initials separately."
+renameFailed = "Could not rename the signature"
+saved = "Saved to your signatures"
+saveFailed = "Could not save the signature"
+saveFailedBody = "It is still ready to place on this document."
+shared = "Shared with everyone"
+shareFailed = "Could not share the signature"
+
+[sign.wallet.type]
+initials = "Initials"
+initialsLimit = "Saving initials needs two free signature slots."
+name = "Your name"
+namePlaceholder = "Type your name"
+previewName = "Your name"
+saveInitials = "Also save my initials"
+style = "Style"
+styleOption = "Style {{index}}"
+
+[sign.wallet.upload]
+browse = "or browse files"
+drop = "Drop an image here"
+failed = "Could not read that image."
+hint = "PNG, JPG or WebP up to {{size}} MB. White backgrounds are removed automatically."
+ink = "Ink colour"
+inkBlack = "Black"
+inkBlue = "Blue"
+inkOriginal = "Original"
+preview = "Uploaded signature preview"
+processing = "Cleaning up the image..."
+rejected = "Choose a PNG, JPG or WebP image up to {{size}} MB."
+removeBackground = "Remove background"
+removeBackgroundHint = "White paper becomes transparent"
+replace = "Replace"
+rotate = "Rotate"
+rotateLeft = "Rotate left"
+rotateRight = "Rotate right"
+trim = "Trim to signature"
+trimHint = "Crops the empty space around it"
+
[signatureSettings.tooltip]
header = "Signature Appearance Settings"
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 9a006264d0..030ab2da11 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -12297,6 +12297,163 @@ saved = "Saved"
text = "Text"
title = "Signature Type"
+[sign.wallet]
+apply_one = "Apply {{count}} signature"
+apply_other = "Apply {{count}} signatures"
+applyEmpty = "Apply signatures"
+count = "{{count}} of {{max}}"
+default = "Default"
+loading = "Loading your signatures..."
+new = "New signature"
+shared = "Shared"
+sharedHint = "Everyone can use these"
+unsaved = "Unsaved"
+yours = "Your signatures"
+
+[sign.wallet.create]
+cancel = "Cancel"
+full = "Your library is full ({{max}} signatures). Delete one to save more."
+makeDefault = "Make default"
+method = "How to create it"
+name = "Name"
+save = "Save to my signatures"
+saveBrowserHint = "Kept in this browser, ready for next time."
+saveHint = "Ready to reuse next time you sign."
+subtitle = "Create it once, reuse it on any document."
+title = "New signature"
+use = "Use signature"
+who = "Who can use it"
+whoEveryone = "Everyone"
+whoMe = "Only me"
+
+[sign.wallet.defaultName]
+draw = "My signature"
+initials = "Initials"
+phone = "Phone signature"
+type = "Typed signature"
+upload = "Uploaded signature"
+
+[sign.wallet.delete]
+body = "\"{{name}}\" is removed from your signatures. Documents you already signed keep it."
+confirm = "Delete"
+title = "Delete this signature?"
+
+[sign.wallet.draw]
+bold = "Bold pen"
+clear = "Clear"
+fine = "Fine pen"
+hint = "Sign above the line"
+medium = "Medium pen"
+pad = "Signature pad"
+pen = "Pen"
+tip = "Use a mouse, trackpad, pen or finger"
+undo = "Undo"
+
+[sign.wallet.ink]
+black = "Black ink"
+blue = "Blue ink"
+label = "Ink"
+navy = "Navy ink"
+
+[sign.wallet.intro]
+body = "Create it once. It is saved here, ready for every document you sign."
+privacy = "Saved signatures are private to you unless you choose to share them."
+privacyBrowser = "Saved signatures stay in this browser."
+title = "Add your signature"
+
+[sign.wallet.menu]
+delete = "Delete"
+discard = "Discard"
+makeDefault = "Make default"
+options = "Options for {{name}}"
+place = "Place on page"
+removeDefault = "Remove as default"
+rename = "Rename"
+save = "Save to my signatures"
+share = "Share with everyone"
+stop = "Stop placing"
+
+[sign.wallet.phone]
+expires = "Expires in {{time}}"
+qr = "QR code to sign on your phone"
+received = "Received from your phone"
+receiveFailed = "Could not read that signature. Scan the new code to try again."
+step1 = "Scan the code with your phone camera"
+step1Hint = "It opens in the phone browser, no app needed."
+step2 = "Draw, type or photograph your signature"
+step2Hint = "A big canvas made for a finger."
+step3 = "It appears here automatically"
+step3Hint = "Keep this window open while you sign."
+waiting = "Waiting for your phone..."
+
+[sign.wallet.placed]
+empty = "Signatures you place on the page are listed here."
+fallbackName = "Signature"
+page = "Page {{page}}"
+remove = "Remove {{name}}"
+show = "Show {{name}} on the page"
+title = "On this document ({{count}})"
+
+[sign.wallet.rename]
+save = "Save"
+title = "Rename signature"
+
+[sign.wallet.status]
+idle = "Pick a signature to place it"
+placing = "Click the page to place {{name}}."
+stop = "Stop"
+
+[sign.wallet.tabs]
+draw = "Draw"
+phone = "Phone"
+type = "Type"
+upload = "Upload"
+
+[sign.wallet.toast]
+applyFailed = "Could not apply signatures"
+applyFailedBody = "Your signatures are still on the document. Try again."
+deleteFailed = "Could not delete the signature"
+draftExists = "Save or discard your unsaved signature first"
+initialsFailed = "Could not save your initials"
+initialsPartial = "Your signature was saved, but your initials were not. Try saving your initials separately."
+renameFailed = "Could not rename the signature"
+saved = "Saved to your signatures"
+saveFailed = "Could not save the signature"
+saveFailedBody = "It is still ready to place on this document."
+shared = "Shared with everyone"
+shareFailed = "Could not share the signature"
+
+[sign.wallet.type]
+initials = "Initials"
+initialsLimit = "Saving initials needs two free signature slots."
+name = "Your name"
+namePlaceholder = "Type your name"
+previewName = "Your name"
+saveInitials = "Also save my initials"
+style = "Style"
+styleOption = "Style {{index}}"
+
+[sign.wallet.upload]
+browse = "or browse files"
+drop = "Drop an image here"
+failed = "Could not read that image."
+hint = "PNG, JPG or WebP up to {{size}} MB. White backgrounds are removed automatically."
+ink = "Ink color"
+inkBlack = "Black"
+inkBlue = "Blue"
+inkOriginal = "Original"
+preview = "Uploaded signature preview"
+processing = "Cleaning up the image..."
+rejected = "Choose a PNG, JPG or WebP image up to {{size}} MB."
+removeBackground = "Remove background"
+removeBackgroundHint = "White paper becomes transparent"
+replace = "Replace"
+rotate = "Rotate"
+rotateLeft = "Rotate left"
+rotateRight = "Rotate right"
+trim = "Trim to signature"
+trimHint = "Crops the empty space around it"
+
[signatureSettings.tooltip]
header = "Signature Appearance Settings"
diff --git a/frontend/editor/scripts/generate-licenses.js b/frontend/editor/scripts/generate-licenses.js
index 4c19a39e8d..55a83ed492 100644
--- a/frontend/editor/scripts/generate-licenses.js
+++ b/frontend/editor/scripts/generate-licenses.js
@@ -248,6 +248,7 @@ function getLicenseUrl(licenseType) {
"CC0-1.0": "https://creativecommons.org/publicdomain/zero/1.0/",
Unlicense: "https://unlicense.org/",
"MPL-2.0": "https://www.mozilla.org/en-US/MPL/2.0/",
+ "OFL-1.1": "https://openfontlicense.org/open-font-license-official-text/",
WTFPL: "http://www.wtfpl.net/",
Zlib: "https://opensource.org/licenses/Zlib",
"Artistic-2.0": "https://opensource.org/licenses/Artistic-2.0",
@@ -383,6 +384,7 @@ function checkLicenseCompatibility(licenseSummary, licenseArray) {
"Ruby",
"MPL-2.0",
"CC-BY-4.0",
+ "OFL-1.1",
"SEE LICENSE IN https://raw.githubusercontent.com/Stirling-Tools/Stirling-PDF/refs/heads/main/proprietary/LICENSE",
"SEE LICENSE IN LICENSE https://github.com/PostHog/posthog-js/blob/main/LICENSE",
]);
diff --git a/frontend/editor/src/core/components/annotation/shared/BaseAnnotationTool.tsx b/frontend/editor/src/core/components/annotation/shared/BaseAnnotationTool.tsx
index b720f9fd43..0d69b8dd91 100644
--- a/frontend/editor/src/core/components/annotation/shared/BaseAnnotationTool.tsx
+++ b/frontend/editor/src/core/components/annotation/shared/BaseAnnotationTool.tsx
@@ -1,10 +1,11 @@
-import React, { useEffect, useState } from "react";
+import React, { useState } from "react";
import { Stack, Alert, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { DrawingControls } from "@app/components/annotation/shared/DrawingControls";
import { ColorPicker } from "@app/components/annotation/shared/ColorPicker";
import { usePDFAnnotation } from "@app/components/annotation/providers/PDFAnnotationProvider";
import { useSignature } from "@app/contexts/SignatureContext";
+import { useHistoryAvailability } from "@app/hooks/useHistoryAvailability";
export interface AnnotationToolConfig {
enableDrawing?: boolean;
@@ -42,32 +43,7 @@ export const BaseAnnotationTool: React.FC<BaseAnnotationToolProps> = ({
const [selectedColor, setSelectedColor] = useState("#000000");
const [isColorPickerOpen, setIsColorPickerOpen] = useState(false);
const [signatureData, setSignatureData] = useState<string | null>(null);
- const [historyAvailability, setHistoryAvailability] = useState({
- canUndo: false,
- canRedo: false,
- });
- const historyApiInstance = historyApiRef.current;
-
- useEffect(() => {
- if (!historyApiInstance) {
- setHistoryAvailability({ canUndo: false, canRedo: false });
- return;
- }
-
- const updateAvailability = () => {
- setHistoryAvailability({
- canUndo: historyApiInstance.canUndo?.() ?? false,
- canRedo: historyApiInstance.canRedo?.() ?? false,
- });
- };
-
- const unsubscribe = historyApiInstance.subscribe?.(updateAvailability);
- updateAvailability();
-
- return () => {
- unsubscribe?.();
- };
- }, [historyApiInstance]);
+ const historyAvailability = useHistoryAvailability(historyApiRef);
const handleSignatureDataChange = (data: string | null) => {
setSignatureData(data);
diff --git a/frontend/editor/src/core/components/annotation/shared/DrawingCanvas.tsx b/frontend/editor/src/core/components/annotation/shared/DrawingCanvas.tsx
index c10d9d9023..913a461feb 100644
--- a/frontend/editor/src/core/components/annotation/shared/DrawingCanvas.tsx
+++ b/frontend/editor/src/core/components/annotation/shared/DrawingCanvas.tsx
@@ -6,6 +6,7 @@ import { ColorSwatchButton } from "@app/components/annotation/shared/ColorPicker
import PenSizeSelector from "@app/components/tools/sign/PenSizeSelector";
import SignaturePad from "signature_pad";
import { PrivateContent } from "@app/components/shared/PrivateContent";
+import { trimCanvas } from "@app/utils/canvasImage";
interface DrawingCanvasProps {
selectedColor: string;
@@ -94,56 +95,6 @@ export const DrawingCanvas: React.FC<DrawingCanvasProps> = ({
if (autoOpen) openModal();
}, [autoOpen]);
- const trimCanvas = (canvas: HTMLCanvasElement): string => {
- const ctx = canvas.getContext("2d");
- if (!ctx) return canvas.toDataURL("image/png");
-
- const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const pixels = imageData.data;
-
- let minX = canvas.width,
- minY = canvas.height,
- maxX = 0,
- maxY = 0;
-
- // Find bounds of non-transparent pixels
- for (let y = 0; y < canvas.height; y++) {
- for (let x = 0; x < canvas.width; x++) {
- const alpha = pixels[(y * canvas.width + x) * 4 + 3];
- if (alpha > 0) {
- if (x < minX) minX = x;
- if (x > maxX) maxX = x;
- if (y < minY) minY = y;
- if (y > maxY) maxY = y;
- }
- }
- }
-
- const trimWidth = maxX - minX + 1;
- const trimHeight = maxY - minY + 1;
-
- // Create trimmed canvas
- const trimmedCanvas = document.createElement("canvas");
- trimmedCanvas.width = trimWidth;
- trimmedCanvas.height = trimHeight;
- const trimmedCtx = trimmedCanvas.getContext("2d");
- if (trimmedCtx) {
- trimmedCtx.drawImage(
- canvas,
- minX,
- minY,
- trimWidth,
- trimHeight,
- 0,
- 0,
- trimWidth,
- trimHeight,
- );
- }
-
- return trimmedCanvas.toDataURL("image/png");
- };
-
const renderPreview = (dataUrl: string) => {
const canvas = previewCanvasRef.current;
if (!canvas) return;
@@ -171,7 +122,7 @@ export const DrawingCanvas: React.FC<DrawingCanvasProps> = ({
if (padRef.current && !padRef.current.isEmpty()) {
const canvas = modalCanvasRef.current;
if (canvas) {
- const trimmedPng = trimCanvas(canvas);
+ const trimmedPng = trimCanvas(canvas).toDataURL("image/png");
const untrimmedPng = canvas.toDataURL("image/png");
setSavedSignatureData(untrimmedPng); // Save untrimmed for restoration
onSignatureDataChange(trimmedPng);
diff --git a/frontend/editor/src/core/components/shared/MobileTransferModal.tsx b/frontend/editor/src/core/components/shared/MobileTransferModal.tsx
index bcaba698d2..479889d5ec 100644
--- a/frontend/editor/src/core/components/shared/MobileTransferModal.tsx
+++ b/frontend/editor/src/core/components/shared/MobileTransferModal.tsx
@@ -1,7 +1,6 @@
import { ReactNode } from "react";
import { Modal, Stack, Text, Box, Alert } from "@mantine/core";
import { QRCodeSVG } from "qrcode.react";
-import { useAppConfig } from "@app/contexts/AppConfigContext";
import { Icon } from "@app/ui/Icon";
import { Z_INDEX_OVER_FILE_MANAGER_MODAL } from "@app/styles/zIndex";
import { useMobileTransferSession } from "@app/hooks/useMobileTransferSession";
@@ -54,8 +53,6 @@ export default function MobileTransferModal({
qrTitle = title,
qrSize = 240,
}: MobileTransferModalProps) {
- const { config } = useAppConfig();
-
const { mobileUrl, filesReceived, error, timeRemaining, showExpiryWarning } =
useMobileTransferSession({
active: opened,
@@ -63,13 +60,6 @@ export default function MobileTransferModal({
onFileReceived,
sessionCreateErrorMessage,
pollingErrorMessage,
- // In dev the backend-advertised frontendUrl is the backend origin, which
- // serves no SPA — the phone must open the Vite origin this page runs on,
- // so let the URL builder fall back to it. An explicit server_url still
- // wins, as an escape hatch.
- configuredUrl:
- localStorage.getItem("server_url") ||
- (import.meta.env.DEV ? "" : config?.frontendUrl || ""),
});
return (
diff --git a/frontend/editor/src/core/components/tools/sign/MobileSignatureModal.tsx b/frontend/editor/src/core/components/tools/sign/MobileSignatureModal.tsx
index 82deae8b5f..f91ffaf101 100644
--- a/frontend/editor/src/core/components/tools/sign/MobileSignatureModal.tsx
+++ b/frontend/editor/src/core/components/tools/sign/MobileSignatureModal.tsx
@@ -1,6 +1,7 @@
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import MobileTransferModal from "@app/components/shared/MobileTransferModal";
+import { parseMobileSignatureFile } from "@app/components/tools/sign/parseMobileSignatureFile";
/**
* What the phone sent, routed to the matching signature source: ink and
@@ -11,33 +12,12 @@ export type MobileSignaturePayload =
| { kind: "photo"; dataUrl: string }
| { kind: "text"; text: string; fontFamily: string; color: string };
-/** Fonts the sign tool's text mode offers; anything else falls back. */
-const TEXT_FONTS = new Set([
- "Helvetica",
- "Times-Roman",
- "Courier",
- "Arial",
- "Georgia",
-]);
-const HEX_COLOR = /^#[0-9a-fA-F]{6}$/;
-const MAX_TEXT_LENGTH = 200;
-
interface MobileSignatureModalProps {
opened: boolean;
onClose: () => void;
onSignatureReceived: (payload: MobileSignaturePayload) => void;
}
-/** FileReader-based (rather than File.text/arrayBuffer, absent in jsdom). */
-function readFileAsText(file: File): Promise<string> {
- return new Promise((resolve, reject) => {
- const reader = new FileReader();
- reader.onload = () => resolve(String(reader.result ?? ""));
- reader.onerror = () => reject(reader.error);
- reader.readAsText(file);
- });
-}
-
/**
* QR modal for creating a signature on a phone or tablet. The phone opens the
* public `/mobile-sign` page; the first valid arrival becomes the signature
@@ -50,66 +30,13 @@ export default function MobileSignatureModal({
}: MobileSignatureModalProps) {
const { t } = useTranslation();
- // The session endpoints accept any upload from anyone holding the QR URL,
- // so nothing here is trusted: images pass as pixels, a typed signature is
- // parsed and clamped field by field, everything else is ignored.
const handleFileReceived = useCallback(
async (file: File) => {
- if (
- file.type === "application/json" &&
- file.name.startsWith("signature-text")
- ) {
- try {
- const parsed: unknown = JSON.parse(await readFileAsText(file));
- const record = parsed as Record<string, unknown>;
- const text =
- typeof record?.text === "string"
- ? record.text.trim().slice(0, MAX_TEXT_LENGTH)
- : "";
- if (!text) return;
- onSignatureReceived({
- kind: "text",
- text,
- fontFamily: TEXT_FONTS.has(record.fontFamily as string)
- ? (record.fontFamily as string)
- : "Helvetica",
- color: HEX_COLOR.test(record.color as string)
- ? (record.color as string)
- : "#000000",
- });
- onClose();
- } catch {
- console.warn(
- "[MobileSignatureModal] Ignoring malformed text payload",
- );
- }
- return;
+ const payload = await parseMobileSignatureFile(file);
+ if (payload) {
+ onSignatureReceived(payload);
+ onClose();
}
-
- if (!file.type.startsWith("image/")) {
- console.warn(
- "[MobileSignatureModal] Ignoring non-image upload:",
- file.type,
- );
- return;
- }
-
- await new Promise<void>((resolve) => {
- const reader = new FileReader();
- reader.onload = (event) => {
- const dataUrl = event.target?.result;
- if (typeof dataUrl === "string") {
- onSignatureReceived({
- kind: file.name.startsWith("signature-photo") ? "photo" : "draw",
- dataUrl,
- });
- onClose();
- }
- resolve();
- };
- reader.onerror = () => resolve();
- reader.readAsDataURL(file);
- });
},
[onSignatureReceived, onClose],
);
diff --git a/frontend/editor/src/core/components/tools/sign/SignSettings.tsx b/frontend/editor/src/core/components/tools/sign/SignSettings.tsx
index ee8f901435..1186e9080c 100644
--- a/frontend/editor/src/core/components/tools/sign/SignSettings.tsx
+++ b/frontend/editor/src/core/components/tools/sign/SignSettings.tsx
@@ -13,6 +13,7 @@ import { Button } from "@app/ui/Button";
import { SegmentedControl } from "@app/ui/SegmentedControl";
import { SignParameters } from "@app/hooks/tools/sign/useSignParameters";
import { useSignature } from "@app/contexts/SignatureContext";
+import { useHistoryAvailability } from "@app/hooks/useHistoryAvailability";
import { useViewer } from "@app/contexts/ViewerContext";
import {
PLACEMENT_ACTIVATION_DELAY,
@@ -97,11 +98,7 @@ const SignSettings = ({
const { t } = useTranslation();
const { isPlacementMode, signaturesApplied, historyApiRef } = useSignature();
const { activeFileIndex } = useViewer();
- const [historyAvailability, setHistoryAvailability] = useState({
- canUndo: false,
- canRedo: false,
- });
- const historyApiInstance = historyApiRef.current;
+ const historyAvailability = useHistoryAvailability(historyApiRef);
const translate = useCallback(
(key: string, defaultValue: string, options?: Record<string, unknown>) =>
t(`${translationScope}.${key}`, { defaultValue, ...options }),
@@ -559,27 +556,6 @@ const SignSettings = ({
}
}, [signaturesApplied]);
- useEffect(() => {
- if (!historyApiInstance) {
- setHistoryAvailability({ canUndo: false, canRedo: false });
- return;
- }
-
- const updateAvailability = () => {
- setHistoryAvailability({
- canUndo: historyApiInstance.canUndo?.() ?? false,
- canRedo: historyApiInstance.canRedo?.() ?? false,
- });
- };
-
- const unsubscribe = historyApiInstance.subscribe?.(updateAvailability);
- updateAvailability();
-
- return () => {
- unsubscribe?.();
- };
- }, [historyApiInstance]);
-
// Handle image upload
const handleImageChange = async (file: File | null) => {
if (file && !disabled) {
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/ControlLabel.module.css b/frontend/editor/src/core/components/tools/sign/createSignature/ControlLabel.module.css
new file mode 100644
index 0000000000..a9aaa1dada
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/ControlLabel.module.css
@@ -0,0 +1,7 @@
+.label {
+ font-size: 0.75rem;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--color-section-label);
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/ControlLabel.tsx b/frontend/editor/src/core/components/tools/sign/createSignature/ControlLabel.tsx
new file mode 100644
index 0000000000..435cceda21
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/ControlLabel.tsx
@@ -0,0 +1,15 @@
+import type { ReactNode } from "react";
+import styles from "@app/components/tools/sign/createSignature/ControlLabel.module.css";
+
+interface ControlLabelProps {
+ id?: string;
+ children: ReactNode;
+}
+
+export function ControlLabel({ id, children }: ControlLabelProps) {
+ return (
+ <span id={id} className={styles.label}>
+ {children}
+ </span>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/CreateSignatureModal.module.css b/frontend/editor/src/core/components/tools/sign/createSignature/CreateSignatureModal.module.css
new file mode 100644
index 0000000000..3b7a3687d3
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/CreateSignatureModal.module.css
@@ -0,0 +1,17 @@
+.body {
+ display: flex;
+ flex-direction: column;
+ gap: 1.125rem;
+}
+
+.tabLabel {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.375rem;
+}
+
+.footer {
+ display: flex;
+ justify-content: flex-end;
+ gap: 0.625rem;
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/CreateSignatureModal.stories.tsx b/frontend/editor/src/core/components/tools/sign/createSignature/CreateSignatureModal.stories.tsx
new file mode 100644
index 0000000000..f74975996f
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/CreateSignatureModal.stories.tsx
@@ -0,0 +1,44 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { CreateSignatureModal } from "@app/components/tools/sign/createSignature/CreateSignatureModal";
+
+const limits = {
+ canSave: true,
+ maxLimit: 20,
+ canShare: false,
+ browserStorage: false,
+};
+
+const meta = {
+ title: "Tools/Sign/CreateSignatureModal",
+ component: CreateSignatureModal,
+ parameters: { layout: "fullscreen" },
+ args: {
+ initialTab: "draw",
+ onClose: () => {},
+ onCreate: async () => {},
+ limits,
+ showPhoneTab: false,
+ existingLabels: ["My signature"],
+ },
+} satisfies Meta<typeof CreateSignatureModal>;
+export default meta;
+
+type Story = StoryObj<typeof meta>;
+
+export const Draw: Story = {};
+
+export const Type: Story = {
+ args: { initialTab: "type" },
+};
+
+export const Upload: Story = {
+ args: { initialTab: "upload" },
+};
+
+export const AdminCanShare: Story = {
+ args: { limits: { ...limits, canShare: true } },
+};
+
+export const LibraryFull: Story = {
+ args: { limits: { ...limits, canSave: false } },
+};
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/CreateSignatureModal.tsx b/frontend/editor/src/core/components/tools/sign/createSignature/CreateSignatureModal.tsx
new file mode 100644
index 0000000000..1a9aeede1e
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/CreateSignatureModal.tsx
@@ -0,0 +1,226 @@
+import { useCallback, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Modal } from "@app/ui/Modal";
+import { Button } from "@app/ui/Button";
+import { Icon } from "@app/ui/Icon";
+import { SegmentedControl } from "@app/ui/SegmentedControl";
+import { uniqueName } from "@app/utils/uniqueName";
+import {
+ PHONE_DRAWING_CLEANUP,
+ cleanUpSignatureImage,
+} from "@app/utils/signatureImage";
+import type { MobileSignaturePayload } from "@app/components/tools/sign/MobileSignatureModal";
+import { DrawSignaturePanel } from "@app/components/tools/sign/createSignature/DrawSignaturePanel";
+import { TypeSignaturePanel } from "@app/components/tools/sign/createSignature/TypeSignaturePanel";
+import { UploadSignaturePanel } from "@app/components/tools/sign/createSignature/UploadSignaturePanel";
+import { PhoneSignaturePanel } from "@app/components/tools/sign/createSignature/PhoneSignaturePanel";
+import {
+ SaveSignatureOptions,
+ toSaveChoice,
+ type SaveLibraryLimits,
+ type SaveOptionsState,
+} from "@app/components/tools/sign/createSignature/SaveSignatureOptions";
+import {
+ CREATE_TAB_ICONS,
+ createTabLabel,
+ createTabs,
+ defaultSignatureName,
+} from "@app/components/tools/sign/createSignature/createTabs";
+import type {
+ CreateTab,
+ CreatedSignature,
+ SaveChoice,
+ SignaturePanelHandle,
+ TypePanelHandle,
+ UploadPanelHandle,
+} from "@app/components/tools/sign/createSignature/types";
+import { useTabReadiness } from "@app/components/tools/sign/createSignature/useTabReadiness";
+import styles from "@app/components/tools/sign/createSignature/CreateSignatureModal.module.css";
+
+interface CreateSignatureModalProps {
+ initialTab: CreateTab;
+ onClose: () => void;
+ onCreate: (
+ created: CreatedSignature,
+ save: SaveChoice | null,
+ ) => Promise<void>;
+ limits: SaveLibraryLimits;
+ showPhoneTab: boolean;
+ existingLabels: string[];
+}
+
+export function CreateSignatureModal({
+ initialTab,
+ onClose,
+ onCreate,
+ limits,
+ showPhoneTab,
+ existingLabels,
+}: CreateSignatureModalProps) {
+ const { t } = useTranslation();
+ const tabs = createTabs(showPhoneTab);
+ const [tab, setTab] = useState<CreateTab>(
+ tabs.includes(initialTab) ? initialTab : "draw",
+ );
+ const { ready, handlers } = useTabReadiness();
+ const [phoneResult, setPhoneResult] = useState<string | null>(null);
+ const [saveState, setSaveState] = useState<SaveOptionsState>({
+ enabled: limits.canSave || limits.canShare,
+ label: null,
+ scope: "personal",
+ makeDefault: false,
+ });
+ const [submitting, setSubmitting] = useState(false);
+ const drawRef = useRef<SignaturePanelHandle>(null);
+ const typeRef = useRef<TypePanelHandle>(null);
+ const uploadRef = useRef<UploadPanelHandle>(null);
+
+ const defaultLabel = uniqueName(defaultSignatureName(t, tab), existingLabels);
+
+ const handlePhoneReceived = useCallback(
+ async (payload: MobileSignaturePayload) => {
+ if (payload.kind === "photo") {
+ uploadRef.current?.loadSource(payload.dataUrl, "phone-photo.png");
+ setTab("upload");
+ return;
+ }
+ if (payload.kind === "text") {
+ typeRef.current?.setName(payload.text, {
+ fontFamily: payload.fontFamily,
+ textColor: payload.color,
+ });
+ setTab("type");
+ return;
+ }
+ try {
+ const dataUrl = await cleanUpSignatureImage(
+ payload.dataUrl,
+ PHONE_DRAWING_CLEANUP,
+ );
+ setPhoneResult(dataUrl);
+ handlers.phone(true);
+ } catch (error) {
+ setPhoneResult(null);
+ handlers.phone(false);
+ throw error;
+ }
+ },
+ [handlers],
+ );
+
+ async function currentResult(): Promise<CreatedSignature | null> {
+ if (tab === "phone") {
+ return phoneResult
+ ? { source: "phone", type: "canvas", dataUrl: phoneResult }
+ : null;
+ }
+ const panels = { draw: drawRef, type: typeRef, upload: uploadRef };
+ return (await panels[tab].current?.getResult()) ?? null;
+ }
+
+ async function handleUse() {
+ setSubmitting(true);
+ try {
+ const created = await currentResult();
+ if (created) {
+ await onCreate(created, toSaveChoice(saveState, defaultLabel, limits));
+ }
+ } finally {
+ setSubmitting(false);
+ }
+ }
+
+ const tabOptions = tabs.map((value) => ({
+ value,
+ label: (
+ <span className={styles.tabLabel}>
+ <Icon name={CREATE_TAB_ICONS[value]} size={15} />
+ {createTabLabel(t, value)}
+ </span>
+ ),
+ }));
+
+ const footer = (
+ <div className={styles.footer}>
+ <Button variant="tertiary" onClick={onClose} disabled={submitting}>
+ {t("sign.wallet.create.cancel", "Cancel")}
+ </Button>
+ <Button
+ leftSection={<Icon name="check" size={16} />}
+ onClick={handleUse}
+ disabled={!ready[tab]}
+ loading={submitting}
+ data-testid="use-signature"
+ >
+ {t("sign.wallet.create.use", "Use signature")}
+ </Button>
+ </div>
+ );
+
+ return (
+ <Modal
+ open
+ onClose={() => {
+ if (!submitting) onClose();
+ }}
+ title={t("sign.wallet.create.title", "New signature")}
+ subtitle={t(
+ "sign.wallet.create.subtitle",
+ "Create it once, reuse it on any document.",
+ )}
+ width="lg"
+ footer={footer}
+ disableBackdropClose
+ disableEscapeClose={submitting || Object.values(ready).some(Boolean)}
+ >
+ <div className={styles.body}>
+ <SegmentedControl
+ options={tabOptions}
+ value={tab}
+ onChange={setTab}
+ fullWidth
+ ariaLabel={t("sign.wallet.create.method", "How to create it")}
+ />
+ <div hidden={tab !== "draw"}>
+ <DrawSignaturePanel ref={drawRef} onReadyChange={handlers.draw} />
+ </div>
+ <div hidden={tab !== "type"}>
+ <TypeSignaturePanel
+ ref={typeRef}
+ onReadyChange={handlers.type}
+ saveEnabled={
+ saveState.enabled &&
+ (limits.canSave ||
+ (limits.canShare && saveState.scope === "shared"))
+ }
+ canSaveInitials={
+ saveState.scope === "shared" ||
+ (limits.remainingSlots ?? limits.maxLimit) >= 2
+ }
+ />
+ </div>
+ <div hidden={tab !== "upload"}>
+ <UploadSignaturePanel
+ ref={uploadRef}
+ onReadyChange={handlers.upload}
+ />
+ </div>
+ {showPhoneTab && (
+ <div hidden={tab !== "phone"}>
+ <PhoneSignaturePanel
+ active={tab === "phone"}
+ received={phoneResult}
+ onReceived={handlePhoneReceived}
+ />
+ </div>
+ )}
+ <SaveSignatureOptions
+ value={saveState}
+ onChange={setSaveState}
+ defaultLabel={defaultLabel}
+ limits={limits}
+ />
+ </div>
+ </Modal>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/DrawSignaturePanel.module.css b/frontend/editor/src/core/components/tools/sign/createSignature/DrawSignaturePanel.module.css
new file mode 100644
index 0000000000..a300d82605
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/DrawSignaturePanel.module.css
@@ -0,0 +1,96 @@
+.panel {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+}
+
+.pad {
+ position: relative;
+ height: 15rem;
+ border-radius: 0.75rem;
+ border: 1px solid var(--c-border-subtle);
+ background: white;
+ overflow: hidden;
+}
+
+@media (max-width: 30rem) {
+ .pad {
+ height: 12.5rem;
+ }
+}
+
+.canvas {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ touch-action: none;
+ cursor: crosshair;
+}
+
+.baseline {
+ position: absolute;
+ left: 3.25rem;
+ right: 2.5rem;
+ bottom: 4.25rem;
+ border-top: 1.5px solid var(--c-illustration-line-strong);
+ pointer-events: none;
+}
+
+.cross {
+ position: absolute;
+ left: 1.75rem;
+ bottom: 4.25rem;
+ font-size: 1.25rem;
+ line-height: 1;
+ color: var(--c-illustration-line-strong);
+ pointer-events: none;
+}
+
+.hint {
+ position: absolute;
+ left: 0;
+ right: 0;
+ bottom: 2.75rem;
+ text-align: center;
+ font-size: 0.75rem;
+ color: var(--c-neutral-fill);
+ pointer-events: none;
+}
+
+.padTools {
+ position: absolute;
+ top: 0.625rem;
+ right: 0.625rem;
+ display: flex;
+ gap: 0.375rem;
+}
+
+.controls {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 0.75rem 1.75rem;
+}
+
+.penGroup {
+ display: flex;
+ align-items: center;
+ gap: 0.625rem;
+}
+
+.penDot {
+ display: inline-block;
+ border-radius: 50%;
+ background: currentColor;
+ vertical-align: middle;
+}
+
+.tip {
+ display: flex;
+ align-items: center;
+ gap: 0.375rem;
+ margin-left: auto;
+ font-size: 0.78125rem;
+ color: var(--c-text-subtle);
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/DrawSignaturePanel.tsx b/frontend/editor/src/core/components/tools/sign/createSignature/DrawSignaturePanel.tsx
new file mode 100644
index 0000000000..a0450b1d55
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/DrawSignaturePanel.tsx
@@ -0,0 +1,144 @@
+import {
+ forwardRef,
+ useEffect,
+ useImperativeHandle,
+ useRef,
+ useState,
+} from "react";
+import { useTranslation } from "react-i18next";
+import { VisuallyHidden } from "@mantine/core";
+import { Button } from "@app/ui/Button";
+import { Icon } from "@app/ui/Icon";
+import { SegmentedControl } from "@app/ui/SegmentedControl";
+import { PrivateContent } from "@app/components/shared/PrivateContent";
+import { InkSwatches } from "@app/components/tools/sign/createSignature/InkSwatches";
+import {
+ DEFAULT_INK,
+ type InkColor,
+} from "@app/components/tools/sign/createSignature/signatureStyles";
+import {
+ useSignaturePad,
+ type PenWidth,
+} from "@app/components/tools/sign/createSignature/useSignaturePad";
+import type { SignaturePanelHandle } from "@app/components/tools/sign/createSignature/types";
+import { ControlLabel } from "@app/components/tools/sign/createSignature/ControlLabel";
+import styles from "@app/components/tools/sign/createSignature/DrawSignaturePanel.module.css";
+
+const PEN_DOT_SIZES: Record<PenWidth, number> = {
+ fine: 4,
+ medium: 7,
+ bold: 10,
+};
+
+interface DrawSignaturePanelProps {
+ onReadyChange: (ready: boolean) => void;
+}
+
+export const DrawSignaturePanel = forwardRef<
+ SignaturePanelHandle,
+ DrawSignaturePanelProps
+>(function DrawSignaturePanel({ onReadyChange }, ref) {
+ const { t } = useTranslation();
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const [ink, setInk] = useState<InkColor>(DEFAULT_INK);
+ const [pen, setPen] = useState<PenWidth>("medium");
+ const { strokeCount, undo, clear, toTrimmedDataUrl } = useSignaturePad(
+ canvasRef,
+ ink.value,
+ pen,
+ );
+ const hasDrawing = strokeCount > 0;
+
+ useEffect(() => onReadyChange(hasDrawing), [hasDrawing, onReadyChange]);
+
+ useImperativeHandle(ref, () => ({
+ getResult: async () => {
+ const dataUrl = toTrimmedDataUrl();
+ return dataUrl ? { source: "draw", type: "canvas", dataUrl } : null;
+ },
+ }));
+
+ const penLabels: Record<PenWidth, string> = {
+ fine: t("sign.wallet.draw.fine", "Fine pen"),
+ medium: t("sign.wallet.draw.medium", "Medium pen"),
+ bold: t("sign.wallet.draw.bold", "Bold pen"),
+ };
+ const penOptions = (Object.keys(PEN_DOT_SIZES) as PenWidth[]).map(
+ (width) => ({
+ value: width,
+ label: (
+ <>
+ <span
+ className={styles.penDot}
+ style={{
+ width: PEN_DOT_SIZES[width],
+ height: PEN_DOT_SIZES[width],
+ }}
+ />
+ <VisuallyHidden>{penLabels[width]}</VisuallyHidden>
+ </>
+ ),
+ }),
+ );
+
+ return (
+ <div className={styles.panel}>
+ <div className={styles.pad}>
+ <span className={styles.cross} aria-hidden>
+ ×
+ </span>
+ <span className={styles.baseline} aria-hidden />
+ {!hasDrawing && (
+ <span className={styles.hint} aria-hidden>
+ {t("sign.wallet.draw.hint", "Sign above the line")}
+ </span>
+ )}
+ <PrivateContent>
+ <canvas
+ ref={canvasRef}
+ className={styles.canvas}
+ aria-label={t("sign.wallet.draw.pad", "Signature pad")}
+ data-testid="signature-draw-pad"
+ />
+ </PrivateContent>
+ <div className={styles.padTools}>
+ <Button
+ variant="secondary"
+ size="sm"
+ leftSection={<Icon name="undo-2" size={14} />}
+ onClick={undo}
+ disabled={!hasDrawing}
+ >
+ {t("sign.wallet.draw.undo", "Undo")}
+ </Button>
+ <Button
+ variant="secondary"
+ size="sm"
+ leftSection={<Icon name="eraser" size={14} />}
+ onClick={clear}
+ disabled={!hasDrawing}
+ >
+ {t("sign.wallet.draw.clear", "Clear")}
+ </Button>
+ </div>
+ </div>
+ <div className={styles.controls}>
+ <InkSwatches value={ink} onChange={setInk} />
+ <div className={styles.penGroup}>
+ <ControlLabel>{t("sign.wallet.draw.pen", "Pen")}</ControlLabel>
+ <SegmentedControl
+ options={penOptions}
+ value={pen}
+ onChange={setPen}
+ size="xs"
+ ariaLabel={t("sign.wallet.draw.pen", "Pen")}
+ />
+ </div>
+ <span className={styles.tip}>
+ <Icon name="info" size={14} />
+ {t("sign.wallet.draw.tip", "Use a mouse, trackpad, pen or finger")}
+ </span>
+ </div>
+ </div>
+ );
+});
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/InkSwatches.module.css b/frontend/editor/src/core/components/tools/sign/createSignature/InkSwatches.module.css
new file mode 100644
index 0000000000..e2d510bcfd
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/InkSwatches.module.css
@@ -0,0 +1,25 @@
+.group {
+ display: flex;
+ align-items: center;
+ gap: 0.625rem;
+}
+
+.swatch {
+ width: 1.375rem;
+ height: 1.375rem;
+ padding: 0;
+ border-radius: 50%;
+ border: 1px solid var(--c-border-strong);
+ cursor: pointer;
+}
+
+.swatch[aria-checked="true"] {
+ box-shadow:
+ 0 0 0 2px var(--c-modal-surface),
+ 0 0 0 4px var(--c-primary);
+}
+
+.swatch:focus-visible {
+ outline: 2px solid var(--c-primary);
+ outline-offset: 3px;
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/InkSwatches.tsx b/frontend/editor/src/core/components/tools/sign/createSignature/InkSwatches.tsx
new file mode 100644
index 0000000000..0935ace6a2
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/InkSwatches.tsx
@@ -0,0 +1,45 @@
+import { useId } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ INK_COLORS,
+ type InkColor,
+} from "@app/components/tools/sign/createSignature/signatureStyles";
+import { ControlLabel } from "@app/components/tools/sign/createSignature/ControlLabel";
+import styles from "@app/components/tools/sign/createSignature/InkSwatches.module.css";
+
+interface InkSwatchesProps {
+ value: InkColor;
+ onChange: (ink: InkColor) => void;
+}
+
+export function InkSwatches({ value, onChange }: InkSwatchesProps) {
+ const { t } = useTranslation();
+ const labelId = useId();
+ const names: Record<InkColor["id"], string> = {
+ black: t("sign.wallet.ink.black", "Black ink"),
+ navy: t("sign.wallet.ink.navy", "Navy ink"),
+ blue: t("sign.wallet.ink.blue", "Blue ink"),
+ };
+
+ return (
+ <div className={styles.group}>
+ <ControlLabel id={labelId}>
+ {t("sign.wallet.ink.label", "Ink")}
+ </ControlLabel>
+ <div role="radiogroup" aria-labelledby={labelId} className={styles.group}>
+ {INK_COLORS.map((ink) => (
+ <button
+ key={ink.id}
+ type="button"
+ role="radio"
+ aria-checked={value.value === ink.value}
+ aria-label={names[ink.id]}
+ className={styles.swatch}
+ style={{ background: ink.value }}
+ onClick={() => onChange(ink)}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/PhoneSignaturePanel.module.css b/frontend/editor/src/core/components/tools/sign/createSignature/PhoneSignaturePanel.module.css
new file mode 100644
index 0000000000..f477939962
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/PhoneSignaturePanel.module.css
@@ -0,0 +1,82 @@
+.layout {
+ display: flex;
+ align-items: center;
+ gap: 2rem;
+}
+
+@media (max-width: 36rem) {
+ .layout {
+ flex-direction: column;
+ align-items: stretch;
+ }
+}
+
+.qrCard {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 0.75rem;
+ padding: 1.125rem;
+ border-radius: 0.875rem;
+ border: 1px solid var(--c-border-subtle);
+ background: white;
+}
+
+.expiry {
+ font-size: 0.78125rem;
+ color: var(--c-neutral-fill);
+}
+
+.side {
+ display: flex;
+ flex-direction: column;
+ flex-grow: 1;
+ gap: 1.125rem;
+}
+
+.steps {
+ display: flex;
+ flex-direction: column;
+ gap: 1.125rem;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.step {
+ display: flex;
+ gap: 0.75rem;
+ align-items: flex-start;
+}
+
+.stepNumber {
+ width: 1.625rem;
+ height: 1.625rem;
+ flex-shrink: 0;
+ border-radius: 50%;
+ background: var(--c-surface-sunken);
+ color: var(--c-text);
+ font-size: 0.8125rem;
+ font-weight: 700;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.stepTitle {
+ font-size: 0.875rem;
+ font-weight: 600;
+ color: var(--c-text);
+}
+
+.stepHint {
+ margin-top: 0.125rem;
+ font-size: 0.78125rem;
+ color: var(--c-text-subtle);
+}
+
+.received {
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/PhoneSignaturePanel.tsx b/frontend/editor/src/core/components/tools/sign/createSignature/PhoneSignaturePanel.tsx
new file mode 100644
index 0000000000..e060e0b595
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/PhoneSignaturePanel.tsx
@@ -0,0 +1,162 @@
+import { useCallback, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { QRCodeSVG } from "qrcode.react";
+import { useMobileTransferSession } from "@app/hooks/useMobileTransferSession";
+import { Banner } from "@app/ui/Banner";
+import { Icon } from "@app/ui/Icon";
+import type { MobileSignaturePayload } from "@app/components/tools/sign/MobileSignatureModal";
+import { parseMobileSignatureFile } from "@app/components/tools/sign/parseMobileSignatureFile";
+import { TransparentPreview } from "@app/components/tools/sign/createSignature/TransparentPreview";
+import styles from "@app/components/tools/sign/createSignature/PhoneSignaturePanel.module.css";
+
+interface PhoneSignaturePanelProps {
+ active: boolean;
+ received: string | null;
+ onReceived: (payload: MobileSignaturePayload) => Promise<void>;
+}
+
+function formatRemaining(ms: number): string {
+ const total = Math.max(0, Math.ceil(ms / 1000));
+ return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
+}
+
+export function PhoneSignaturePanel({
+ active,
+ received,
+ onReceived,
+}: PhoneSignaturePanelProps) {
+ const { t } = useTranslation();
+ const [receiveError, setReceiveError] = useState<string | null>(null);
+ const regenerateRef = useRef<() => void>(() => {});
+
+ const handleFile = useCallback(
+ async (file: File) => {
+ const payload = await parseMobileSignatureFile(file);
+ if (!payload) return;
+ try {
+ await onReceived(payload);
+ setReceiveError(null);
+ } catch (err) {
+ console.error("[PhoneSignaturePanel] could not use signature:", err);
+ setReceiveError(
+ t(
+ "sign.wallet.phone.receiveFailed",
+ "Could not read that signature. Scan the new code to try again.",
+ ),
+ );
+ // Fresh session so the phone can send again.
+ regenerateRef.current();
+ }
+ },
+ [onReceived, t],
+ );
+
+ const { mobileUrl, error, timeRemaining, regenerateSession } =
+ useMobileTransferSession({
+ active: active && !received,
+ routePath: "mobile-sign",
+ onFileReceived: handleFile,
+ sessionCreateErrorMessage: t(
+ "sign.mobile.sessionCreateError",
+ "Failed to create session",
+ ),
+ pollingErrorMessage: t(
+ "sign.mobile.pollingError",
+ "Error checking for the signature",
+ ),
+ });
+ regenerateRef.current = regenerateSession;
+
+ const shownError = receiveError ?? error;
+
+ if (received) {
+ return (
+ <div className={styles.received}>
+ <TransparentPreview
+ src={received}
+ label={t("sign.wallet.phone.received", "Received from your phone")}
+ />
+ <Banner
+ tone="success"
+ icon={<Icon name="circle-check" size={16} />}
+ description={t(
+ "sign.wallet.phone.received",
+ "Received from your phone",
+ )}
+ />
+ </div>
+ );
+ }
+
+ const steps = [
+ {
+ title: t(
+ "sign.wallet.phone.step1",
+ "Scan the code with your phone camera",
+ ),
+ hint: t(
+ "sign.wallet.phone.step1Hint",
+ "It opens in the phone browser, no app needed.",
+ ),
+ },
+ {
+ title: t(
+ "sign.wallet.phone.step2",
+ "Draw, type or photograph your signature",
+ ),
+ hint: t("sign.wallet.phone.step2Hint", "A big canvas made for a finger."),
+ },
+ {
+ title: t("sign.wallet.phone.step3", "It appears here automatically"),
+ hint: t(
+ "sign.wallet.phone.step3Hint",
+ "Keep this window open while you sign.",
+ ),
+ },
+ ];
+
+ return (
+ <div className={styles.layout}>
+ <div className={styles.qrCard}>
+ {active && (
+ <QRCodeSVG
+ value={mobileUrl}
+ size={176}
+ level="H"
+ title={t("sign.wallet.phone.qr", "QR code to sign on your phone")}
+ />
+ )}
+ {timeRemaining !== null && (
+ <span className={styles.expiry}>
+ {t("sign.wallet.phone.expires", "Expires in {{time}}", {
+ time: formatRemaining(timeRemaining),
+ })}
+ </span>
+ )}
+ </div>
+ <div className={styles.side}>
+ <ol className={styles.steps}>
+ {steps.map((step, index) => (
+ <li key={step.title} className={styles.step}>
+ <span className={styles.stepNumber}>{index + 1}</span>
+ <div>
+ <div className={styles.stepTitle}>{step.title}</div>
+ <div className={styles.stepHint}>{step.hint}</div>
+ </div>
+ </li>
+ ))}
+ </ol>
+ <Banner
+ tone={shownError ? "danger" : "info"}
+ icon={
+ <Icon name={shownError ? "circle-alert" : "refresh-cw"} size={16} />
+ }
+ description={
+ shownError ??
+ t("sign.wallet.phone.waiting", "Waiting for your phone...")
+ }
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/SaveSignatureOptions.module.css b/frontend/editor/src/core/components/tools/sign/createSignature/SaveSignatureOptions.module.css
new file mode 100644
index 0000000000..b9d89125c9
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/SaveSignatureOptions.module.css
@@ -0,0 +1,27 @@
+.box {
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+ padding: 0.875rem 1rem;
+ border-radius: 0.75rem;
+ background: var(--c-surface);
+ border: 1px solid var(--c-border);
+}
+
+.fields {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: flex-end;
+ gap: 0.75rem;
+ padding-left: 1.75rem;
+}
+
+.name {
+ flex: 1 1 12rem;
+ min-width: 0;
+}
+
+.who {
+ flex: 0 1 12rem;
+ min-width: 9rem;
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/SaveSignatureOptions.tsx b/frontend/editor/src/core/components/tools/sign/createSignature/SaveSignatureOptions.tsx
new file mode 100644
index 0000000000..db02817c27
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/SaveSignatureOptions.tsx
@@ -0,0 +1,143 @@
+import type { TFunction } from "i18next";
+import { useTranslation } from "react-i18next";
+import { Checkbox } from "@app/ui/Checkbox";
+import { FormField } from "@app/ui/FormField";
+import { Input } from "@app/ui/Input";
+import { Select } from "@app/ui/Select";
+import type {
+ SaveChoice,
+ SaveScope,
+} from "@app/components/tools/sign/createSignature/types";
+import styles from "@app/components/tools/sign/createSignature/SaveSignatureOptions.module.css";
+
+export interface SaveOptionsState {
+ enabled: boolean;
+ label: string | null;
+ scope: SaveScope;
+ makeDefault: boolean;
+}
+
+export interface SaveLibraryLimits {
+ canSave: boolean;
+ maxLimit: number;
+ canShare: boolean;
+ browserStorage: boolean;
+ remainingSlots?: number;
+}
+
+export function toSaveChoice(
+ state: SaveOptionsState,
+ defaultLabel: string,
+ limits: SaveLibraryLimits,
+): SaveChoice | null {
+ if (
+ !state.enabled ||
+ (!limits.canSave && !(limits.canShare && state.scope === "shared"))
+ )
+ return null;
+ return {
+ label: state.label?.trim() || defaultLabel,
+ scope: limits.canShare ? state.scope : "personal",
+ makeDefault: state.makeDefault,
+ };
+}
+
+function saveHint(t: TFunction, limits: SaveLibraryLimits): string {
+ if (!limits.canSave) {
+ return t(
+ "sign.wallet.create.full",
+ "Your library is full ({{max}} signatures). Delete one to save more.",
+ { max: limits.maxLimit },
+ );
+ }
+ if (limits.browserStorage) {
+ return t(
+ "sign.wallet.create.saveBrowserHint",
+ "Kept in this browser, ready for next time.",
+ );
+ }
+ return t("sign.wallet.create.saveHint", "Ready to reuse next time you sign.");
+}
+
+interface SaveSignatureOptionsProps {
+ value: SaveOptionsState;
+ onChange: (next: SaveOptionsState) => void;
+ defaultLabel: string;
+ limits: SaveLibraryLimits;
+}
+
+export function SaveSignatureOptions({
+ value,
+ onChange,
+ defaultLabel,
+ limits,
+}: SaveSignatureOptionsProps) {
+ const { t } = useTranslation();
+ const update = (patch: Partial<SaveOptionsState>) =>
+ onChange({ ...value, ...patch });
+ const canSave =
+ limits.canSave || (limits.canShare && value.scope === "shared");
+ const saving = value.enabled && canSave;
+
+ return (
+ <div className={styles.box}>
+ <Checkbox
+ label={t("sign.wallet.create.save", "Save to my signatures")}
+ description={saveHint(t, { ...limits, canSave })}
+ checked={saving}
+ disabled={!canSave}
+ onChange={(event) => update({ enabled: event.currentTarget.checked })}
+ data-testid="save-signature-checkbox"
+ />
+ {(saving || limits.canShare) && (
+ <div className={styles.fields}>
+ <div className={styles.name}>
+ <FormField label={t("sign.wallet.create.name", "Name")}>
+ <Input
+ value={value.label ?? defaultLabel}
+ onChange={(event) =>
+ update({ label: event.currentTarget.value })
+ }
+ maxLength={60}
+ disabled={!saving}
+ data-testid="signature-name-input"
+ />
+ </FormField>
+ </div>
+ {limits.canShare && (
+ <div className={styles.who}>
+ <FormField label={t("sign.wallet.create.who", "Who can use it")}>
+ <Select
+ value={value.scope}
+ onChange={(scope) =>
+ update({
+ scope: scope === "shared" ? "shared" : "personal",
+ })
+ }
+ options={[
+ {
+ value: "personal",
+ label: t("sign.wallet.create.whoMe", "Only me"),
+ },
+ {
+ value: "shared",
+ label: t("sign.wallet.create.whoEveryone", "Everyone"),
+ },
+ ]}
+ />
+ </FormField>
+ </div>
+ )}
+ <Checkbox
+ label={t("sign.wallet.create.makeDefault", "Make default")}
+ checked={value.makeDefault}
+ disabled={!saving}
+ onChange={(event) =>
+ update({ makeDefault: event.currentTarget.checked })
+ }
+ />
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/SignatureStylePicker.module.css b/frontend/editor/src/core/components/tools/sign/createSignature/SignatureStylePicker.module.css
new file mode 100644
index 0000000000..4b0e8834ec
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/SignatureStylePicker.module.css
@@ -0,0 +1,65 @@
+.picker {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+}
+
+.grid {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 0.625rem;
+}
+
+@media (max-width: 36rem) {
+ .grid {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+}
+
+.card {
+ position: relative;
+ height: 5.25rem;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0 0.75rem;
+ overflow: hidden;
+ border-radius: 0.75rem;
+ border: 1px solid var(--c-border-subtle);
+ background: white;
+ cursor: pointer;
+ white-space: nowrap;
+ line-height: 1.1;
+}
+
+.card[aria-checked="true"] {
+ border: 2px solid var(--c-primary);
+ box-shadow: 0 0 0 3px var(--c-primary-subtle);
+}
+
+.card:focus-visible {
+ outline: 2px solid var(--c-primary);
+ outline-offset: 2px;
+}
+
+.preview[data-placeholder] {
+ opacity: 0.35;
+}
+
+.check {
+ position: absolute;
+ top: 0.5rem;
+ right: 0.5rem;
+ width: 1.25rem;
+ height: 1.25rem;
+ border-radius: 50%;
+ background: var(--c-primary);
+ color: var(--c-text-on-primary);
+ display: none;
+ align-items: center;
+ justify-content: center;
+}
+
+.card[aria-checked="true"] .check {
+ display: flex;
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/SignatureStylePicker.tsx b/frontend/editor/src/core/components/tools/sign/createSignature/SignatureStylePicker.tsx
new file mode 100644
index 0000000000..7fe6cc97ae
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/SignatureStylePicker.tsx
@@ -0,0 +1,68 @@
+import { useId } from "react";
+import { useTranslation } from "react-i18next";
+import { Icon } from "@app/ui/Icon";
+import {
+ SIGNATURE_FONTS,
+ type SignatureFont,
+} from "@app/components/tools/sign/createSignature/signatureStyles";
+import { ControlLabel } from "@app/components/tools/sign/createSignature/ControlLabel";
+import styles from "@app/components/tools/sign/createSignature/SignatureStylePicker.module.css";
+
+const PREVIEW_FONT_SIZE = 30;
+
+interface SignatureStylePickerProps {
+ text: string;
+ ink: string;
+ value: SignatureFont;
+ onChange: (font: SignatureFont) => void;
+}
+
+export function SignatureStylePicker({
+ text,
+ ink,
+ value,
+ onChange,
+}: SignatureStylePickerProps) {
+ const { t } = useTranslation();
+ const labelId = useId();
+ const preview = text.trim() || t("sign.wallet.type.previewName", "Your name");
+
+ return (
+ <div className={styles.picker}>
+ <ControlLabel id={labelId}>
+ {t("sign.wallet.type.style", "Style")}
+ </ControlLabel>
+ <div className={styles.grid} role="radiogroup" aria-labelledby={labelId}>
+ {SIGNATURE_FONTS.map((font, index) => (
+ <button
+ key={font.family}
+ type="button"
+ role="radio"
+ aria-checked={font.family === value.family}
+ aria-label={t("sign.wallet.type.styleOption", "Style {{index}}", {
+ index: index + 1,
+ })}
+ className={styles.card}
+ onClick={() => onChange(font)}
+ >
+ <span
+ data-user-content-preview
+ data-placeholder={!text.trim() || undefined}
+ className={styles.preview}
+ style={{
+ fontFamily: `"${font.family}", cursive`,
+ fontSize: PREVIEW_FONT_SIZE * font.previewScale,
+ color: ink,
+ }}
+ >
+ {preview}
+ </span>
+ <span className={styles.check} aria-hidden>
+ <Icon name="check" size={11} strokeWidth={3.2} />
+ </span>
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/TransparentPreview.module.css b/frontend/editor/src/core/components/tools/sign/createSignature/TransparentPreview.module.css
new file mode 100644
index 0000000000..1916e70c92
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/TransparentPreview.module.css
@@ -0,0 +1,36 @@
+.preview {
+ position: relative;
+ height: 14rem;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 1rem;
+ box-sizing: border-box;
+ border-radius: 0.75rem;
+ border: 1px solid var(--c-border-subtle);
+ background-color: white;
+ background-image: repeating-conic-gradient(
+ var(--c-illustration-line) 0% 25%,
+ transparent 0% 50%
+ );
+ background-size: 1.125rem 1.125rem;
+}
+
+.image {
+ max-width: 100%;
+ max-height: 100%;
+ object-fit: contain;
+}
+
+.overlay {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: var(--c-overlay);
+ color: white;
+ font-size: 0.8125rem;
+ font-weight: 600;
+ border-radius: 0.75rem;
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/TransparentPreview.tsx b/frontend/editor/src/core/components/tools/sign/createSignature/TransparentPreview.tsx
new file mode 100644
index 0000000000..a2d943e64c
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/TransparentPreview.tsx
@@ -0,0 +1,26 @@
+import type { ReactNode } from "react";
+import { PrivateContent } from "@app/components/shared/PrivateContent";
+import styles from "@app/components/tools/sign/createSignature/TransparentPreview.module.css";
+
+interface TransparentPreviewProps {
+ src: string | null;
+ label: string;
+ overlay?: ReactNode;
+}
+
+export function TransparentPreview({
+ src,
+ label,
+ overlay,
+}: TransparentPreviewProps) {
+ return (
+ <div className={styles.preview} role="img" aria-label={label}>
+ {src && (
+ <PrivateContent>
+ <img className={styles.image} src={src} alt="" />
+ </PrivateContent>
+ )}
+ {overlay && <span className={styles.overlay}>{overlay}</span>}
+ </div>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/TypeSignaturePanel.module.css b/frontend/editor/src/core/components/tools/sign/createSignature/TypeSignaturePanel.module.css
new file mode 100644
index 0000000000..dfb7eca93a
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/TypeSignaturePanel.module.css
@@ -0,0 +1,19 @@
+.panel {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+}
+
+.nameRow {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 7.5rem;
+ gap: 0.75rem;
+}
+
+.footer {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ gap: 0.75rem;
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/TypeSignaturePanel.test.tsx b/frontend/editor/src/core/components/tools/sign/createSignature/TypeSignaturePanel.test.tsx
new file mode 100644
index 0000000000..a54567080b
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/TypeSignaturePanel.test.tsx
@@ -0,0 +1,63 @@
+import { createRef } from "react";
+import { MantineProvider } from "@mantine/core";
+import { act, render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { TypeSignaturePanel } from "@app/components/tools/sign/createSignature/TypeSignaturePanel";
+import type { TypePanelHandle } from "@app/components/tools/sign/createSignature/types";
+import { renderTypedSignature } from "@app/utils/signatureImage";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, fallback?: unknown) =>
+ typeof fallback === "string" ? fallback : key,
+ }),
+}));
+vi.mock("@app/utils/signatureImage", () => ({
+ deriveInitials: (name: string) =>
+ name
+ .split(" ")
+ .map((part) => part[0])
+ .join(""),
+ renderTypedSignature: vi.fn(async () => "data:image/png;base64,signature"),
+}));
+
+describe("TypeSignaturePanel phone text", () => {
+ it("retains a phone font and custom ink when rendering the received name", async () => {
+ const panel = createRef<TypePanelHandle>();
+ render(
+ <MantineProvider>
+ <TypeSignaturePanel
+ ref={panel}
+ onReadyChange={vi.fn()}
+ saveEnabled={false}
+ canSaveInitials={false}
+ />
+ </MantineProvider>,
+ );
+ act(() =>
+ panel.current?.setName("Alex Doe", {
+ fontFamily: "Georgia",
+ textColor: "#cc3399",
+ }),
+ );
+ expect(screen.getByTestId("signature-type-name")).toHaveValue("Alex Doe");
+ expect(
+ screen
+ .getAllByRole("radio", { name: /ink$/i })
+ .every((radio) => radio.getAttribute("aria-checked") === "false"),
+ ).toBe(true);
+ const result = await panel.current?.getResult();
+ expect(result?.text).toEqual({
+ signerName: "Alex Doe",
+ fontFamily: "Georgia",
+ fontSize: 120,
+ textColor: "#cc3399",
+ });
+ expect(renderTypedSignature).toHaveBeenCalledWith({
+ text: "Alex Doe",
+ fontFamily: "Georgia",
+ fontSize: 120,
+ color: "#cc3399",
+ });
+ });
+});
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/TypeSignaturePanel.tsx b/frontend/editor/src/core/components/tools/sign/createSignature/TypeSignaturePanel.tsx
new file mode 100644
index 0000000000..631510fc42
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/TypeSignaturePanel.tsx
@@ -0,0 +1,162 @@
+import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Checkbox } from "@app/ui/Checkbox";
+import { FormField } from "@app/ui/FormField";
+import { Input } from "@app/ui/Input";
+import {
+ deriveInitials,
+ renderTypedSignature,
+} from "@app/utils/signatureImage";
+import { InkSwatches } from "@app/components/tools/sign/createSignature/InkSwatches";
+import { SignatureStylePicker } from "@app/components/tools/sign/createSignature/SignatureStylePicker";
+import {
+ DEFAULT_INK,
+ INK_COLORS,
+ SIGNATURE_FONTS,
+ type InkColor,
+ type SignatureFont,
+} from "@app/components/tools/sign/createSignature/signatureStyles";
+import type {
+ CreatedSignature,
+ TypePanelHandle,
+ TypedSignatureSource,
+} from "@app/components/tools/sign/createSignature/types";
+import styles from "@app/components/tools/sign/createSignature/TypeSignaturePanel.module.css";
+
+const RENDER_FONT_SIZE = 120;
+
+async function renderSource(
+ source: TypedSignatureSource,
+): Promise<string | null> {
+ return renderTypedSignature({
+ text: source.signerName,
+ fontFamily: source.fontFamily,
+ color: source.textColor,
+ fontSize: source.fontSize,
+ });
+}
+
+interface TypeSignaturePanelProps {
+ onReadyChange: (ready: boolean) => void;
+ saveEnabled: boolean;
+ canSaveInitials: boolean;
+}
+
+export const TypeSignaturePanel = forwardRef<
+ TypePanelHandle,
+ TypeSignaturePanelProps
+>(function TypeSignaturePanel(
+ { onReadyChange, saveEnabled, canSaveInitials },
+ ref,
+) {
+ const { t } = useTranslation();
+ const [name, setName] = useState("");
+ const [initialsOverride, setInitialsOverride] = useState<string | null>(null);
+ const [font, setFont] = useState<SignatureFont>(SIGNATURE_FONTS[0]);
+ const [ink, setInk] = useState<InkColor>(DEFAULT_INK);
+ const [includeInitials, setIncludeInitials] = useState(true);
+
+ const initials = initialsOverride ?? deriveInitials(name);
+ const hasName = name.trim().length > 0;
+ const savesInitials =
+ saveEnabled &&
+ canSaveInitials &&
+ includeInitials &&
+ Boolean(initials.trim());
+
+ useEffect(() => onReadyChange(hasName), [hasName, onReadyChange]);
+
+ async function getResult(): Promise<CreatedSignature | null> {
+ const style = {
+ fontFamily: font.family,
+ fontSize: RENDER_FONT_SIZE,
+ textColor: ink.value,
+ };
+ const text = { signerName: name.trim(), ...style };
+ const dataUrl = await renderSource(text);
+ if (!dataUrl) return null;
+ const initialsSource = { signerName: initials.trim(), ...style };
+ const initialsUrl = savesInitials
+ ? await renderSource(initialsSource)
+ : null;
+ return {
+ source: "type",
+ type: "text",
+ dataUrl,
+ text,
+ initials: initialsUrl
+ ? { ...initialsSource, dataUrl: initialsUrl }
+ : undefined,
+ };
+ }
+
+ useImperativeHandle(ref, () => ({
+ setName: (nextName, style) => {
+ setName(nextName);
+ setInitialsOverride(null);
+ if (!style) return;
+ setFont(
+ SIGNATURE_FONTS.find((entry) => entry.family === style.fontFamily) ?? {
+ family: style.fontFamily,
+ previewScale: 1,
+ },
+ );
+ setInk(
+ INK_COLORS.find((entry) => entry.value === style.textColor) ?? {
+ ...DEFAULT_INK,
+ value: style.textColor,
+ },
+ );
+ },
+ getResult,
+ }));
+
+ return (
+ <div className={styles.panel}>
+ <div className={styles.nameRow}>
+ <FormField label={t("sign.wallet.type.name", "Your name")}>
+ <Input
+ value={name}
+ onChange={(event) => setName(event.currentTarget.value)}
+ placeholder={t(
+ "sign.wallet.type.namePlaceholder",
+ "Type your name",
+ )}
+ maxLength={80}
+ data-testid="signature-type-name"
+ />
+ </FormField>
+ <FormField label={t("sign.wallet.type.initials", "Initials")}>
+ <Input
+ value={initials}
+ onChange={(event) => setInitialsOverride(event.currentTarget.value)}
+ maxLength={6}
+ />
+ </FormField>
+ </div>
+ <SignatureStylePicker
+ text={name}
+ ink={ink.value}
+ value={font}
+ onChange={setFont}
+ />
+ <div className={styles.footer}>
+ <InkSwatches value={ink} onChange={setInk} />
+ <Checkbox
+ label={t("sign.wallet.type.saveInitials", "Also save my initials")}
+ checked={savesInitials}
+ disabled={!saveEnabled || !canSaveInitials || !initials.trim()}
+ description={
+ saveEnabled && !canSaveInitials
+ ? t(
+ "sign.wallet.type.initialsLimit",
+ "Saving initials needs two free signature slots.",
+ )
+ : undefined
+ }
+ onChange={(event) => setIncludeInitials(event.currentTarget.checked)}
+ />
+ </div>
+ </div>
+ );
+});
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/UploadCleanupOptions.tsx b/frontend/editor/src/core/components/tools/sign/createSignature/UploadCleanupOptions.tsx
new file mode 100644
index 0000000000..5f969b13da
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/UploadCleanupOptions.tsx
@@ -0,0 +1,116 @@
+import { useTranslation } from "react-i18next";
+import { ActionIcon } from "@app/ui/ActionIcon";
+import { Icon } from "@app/ui/Icon";
+import { SegmentedControl } from "@app/ui/SegmentedControl";
+import { ToggleSwitch } from "@app/ui/ToggleSwitch";
+import { INK_COLORS } from "@app/components/tools/sign/createSignature/signatureStyles";
+import type { UploadCleanup } from "@app/utils/signatureImage";
+import { ControlLabel } from "@app/components/tools/sign/createSignature/ControlLabel";
+import styles from "@app/components/tools/sign/createSignature/UploadSignaturePanel.module.css";
+
+export type InkChoice = "original" | "black" | "blue";
+
+export interface CleanupSettings {
+ removeBackground: boolean;
+ trim: boolean;
+ ink: InkChoice;
+ quarterTurns: number;
+}
+
+export const DEFAULT_CLEANUP: CleanupSettings = {
+ removeBackground: true,
+ trim: true,
+ ink: "original",
+ quarterTurns: 0,
+};
+
+export function toUploadCleanup(settings: CleanupSettings): UploadCleanup {
+ const ink = INK_COLORS.find((entry) => entry.id === settings.ink);
+ return {
+ removeBackground: settings.removeBackground,
+ trim: settings.trim,
+ inkColor: ink?.value ?? null,
+ quarterTurns: settings.quarterTurns,
+ };
+}
+
+interface UploadCleanupOptionsProps {
+ value: CleanupSettings;
+ onChange: (next: CleanupSettings) => void;
+}
+
+export function UploadCleanupOptions({
+ value,
+ onChange,
+}: UploadCleanupOptionsProps) {
+ const { t } = useTranslation();
+ const update = (patch: Partial<CleanupSettings>) =>
+ onChange({ ...value, ...patch });
+ const inkOptions = [
+ {
+ value: "original" as const,
+ label: t("sign.wallet.upload.inkOriginal", "Original"),
+ },
+ {
+ value: "black" as const,
+ label: t("sign.wallet.upload.inkBlack", "Black"),
+ },
+ { value: "blue" as const, label: t("sign.wallet.upload.inkBlue", "Blue") },
+ ];
+
+ return (
+ <div className={styles.options}>
+ <ToggleSwitch
+ checked={value.removeBackground}
+ onChange={(removeBackground) => update({ removeBackground })}
+ label={t("sign.wallet.upload.removeBackground", "Remove background")}
+ description={t(
+ "sign.wallet.upload.removeBackgroundHint",
+ "White paper becomes transparent",
+ )}
+ />
+ <ToggleSwitch
+ checked={value.trim}
+ onChange={(trim) => update({ trim })}
+ label={t("sign.wallet.upload.trim", "Trim to signature")}
+ description={t(
+ "sign.wallet.upload.trimHint",
+ "Crops the empty space around it",
+ )}
+ />
+ <div className={styles.option}>
+ <ControlLabel>{t("sign.wallet.upload.ink", "Ink color")}</ControlLabel>
+ <SegmentedControl
+ options={inkOptions}
+ value={value.ink}
+ onChange={(ink) => update({ ink })}
+ size="sm"
+ fullWidth
+ disabled={!value.removeBackground}
+ ariaLabel={t("sign.wallet.upload.ink", "Ink color")}
+ />
+ </div>
+ <div className={styles.rotateRow}>
+ <span className={styles.grow}>
+ <ControlLabel>
+ {t("sign.wallet.upload.rotate", "Rotate")}
+ </ControlLabel>
+ </span>
+ <ActionIcon
+ variant="secondary"
+ aria-label={t("sign.wallet.upload.rotateLeft", "Rotate left")}
+ onClick={() => update({ quarterTurns: value.quarterTurns - 1 })}
+ >
+ <Icon name="rotate-ccw" size={16} />
+ </ActionIcon>
+ <ActionIcon
+ variant="secondary"
+ aria-label={t("sign.wallet.upload.rotateRight", "Rotate right")}
+ onClick={() => update({ quarterTurns: value.quarterTurns + 1 })}
+ >
+ <Icon name="rotate-cw" size={16} />
+ </ActionIcon>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/UploadSignaturePanel.module.css b/frontend/editor/src/core/components/tools/sign/createSignature/UploadSignaturePanel.module.css
new file mode 100644
index 0000000000..48fdd2eda1
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/UploadSignaturePanel.module.css
@@ -0,0 +1,133 @@
+.dropArea {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+}
+
+.dropzone {
+ border: 1.5px dashed var(--c-border-strong);
+ border-radius: 0.75rem;
+ background: var(--c-surface);
+ cursor: pointer;
+ transition:
+ border-color 0.15s ease,
+ background 0.15s ease;
+}
+
+.dropzone:hover,
+.dropzone[data-accept] {
+ border-color: var(--c-primary);
+ background: var(--c-primary-tint);
+}
+
+.dropzone[data-reject] {
+ border-color: var(--c-danger);
+}
+
+.dropContent {
+ min-height: 9.5rem;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 0.5rem;
+ text-align: center;
+ pointer-events: none;
+}
+
+.dropIcon {
+ width: 2.5rem;
+ height: 2.5rem;
+ border-radius: 50%;
+ background: var(--c-primary-tint);
+ color: var(--c-accent-text);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.dropTitle {
+ font-size: 0.875rem;
+ font-weight: 700;
+ color: var(--c-text);
+}
+
+.dropBrowse {
+ font-size: 0.8125rem;
+ font-weight: 600;
+ color: var(--c-accent-text);
+}
+
+.dropHint {
+ font-size: 0.75rem;
+ line-height: 1.4;
+ color: var(--c-text-subtle);
+}
+
+.layout {
+ display: grid;
+ grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr);
+ gap: 1.5rem;
+}
+
+@media (max-width: 40rem) {
+ .layout {
+ grid-template-columns: minmax(0, 1fr);
+ }
+}
+
+.previewColumn {
+ display: flex;
+ flex-direction: column;
+ gap: 0.625rem;
+}
+
+.fileRow {
+ display: flex;
+ align-items: center;
+ gap: 0.625rem;
+ min-width: 0;
+ font-size: 0.8125rem;
+ color: var(--c-text);
+}
+
+.fileName {
+ flex-grow: 1;
+ min-width: 0;
+ font-weight: 600;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.fileSize {
+ flex-shrink: 0;
+ color: var(--c-text-subtle);
+}
+
+.error {
+ font-size: 0.8125rem;
+ color: var(--c-danger);
+}
+
+.options {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+}
+
+.option {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+}
+
+.grow {
+ flex-grow: 1;
+}
+
+.rotateRow {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/UploadSignaturePanel.tsx b/frontend/editor/src/core/components/tools/sign/createSignature/UploadSignaturePanel.tsx
new file mode 100644
index 0000000000..582899251d
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/UploadSignaturePanel.tsx
@@ -0,0 +1,190 @@
+import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Dropzone } from "@mantine/dropzone";
+import { FilePicker } from "@app/ui/FilePicker";
+import { Icon } from "@app/ui/Icon";
+import { formatFileSize, readFileAsDataUrl } from "@app/utils/fileUtils";
+import { TransparentPreview } from "@app/components/tools/sign/createSignature/TransparentPreview";
+import {
+ DEFAULT_CLEANUP,
+ UploadCleanupOptions,
+ toUploadCleanup,
+ type CleanupSettings,
+} from "@app/components/tools/sign/createSignature/UploadCleanupOptions";
+import { useCleanedSignatureImage } from "@app/components/tools/sign/createSignature/useCleanedSignatureImage";
+import type { UploadPanelHandle } from "@app/components/tools/sign/createSignature/types";
+import styles from "@app/components/tools/sign/createSignature/UploadSignaturePanel.module.css";
+
+const ACCEPTED_TYPES = ["image/png", "image/jpeg", "image/webp"];
+const MAX_UPLOAD_MB = 10;
+
+type UploadProblem = "unreadable" | "rejected";
+
+interface UploadSource {
+ dataUrl: string;
+ name: string;
+ size?: number;
+}
+
+interface UploadSignaturePanelProps {
+ onReadyChange: (ready: boolean) => void;
+}
+
+export const UploadSignaturePanel = forwardRef<
+ UploadPanelHandle,
+ UploadSignaturePanelProps
+>(function UploadSignaturePanel({ onReadyChange }, ref) {
+ const { t } = useTranslation();
+ const [source, setSource] = useState<UploadSource | null>(null);
+ const [cleanup, setCleanup] = useState<CleanupSettings>(DEFAULT_CLEANUP);
+ const [problem, setProblem] = useState<UploadProblem | null>(null);
+ const cleaned = useCleanedSignatureImage(
+ source?.dataUrl ?? null,
+ toUploadCleanup(cleanup),
+ );
+ const ready = Boolean(cleaned.dataUrl) && !cleaned.processing;
+
+ useEffect(() => onReadyChange(ready), [ready, onReadyChange]);
+
+ function loadSource(next: UploadSource) {
+ setProblem(null);
+ setCleanup((prev) => ({ ...prev, quarterTurns: 0 }));
+ setSource(next);
+ }
+
+ async function acceptFile(file: File | null) {
+ if (!file) return;
+ if (
+ !ACCEPTED_TYPES.includes(file.type) ||
+ file.size > MAX_UPLOAD_MB * 1024 * 1024
+ ) {
+ setProblem("rejected");
+ return;
+ }
+ try {
+ loadSource({
+ dataUrl: await readFileAsDataUrl(file),
+ name: file.name,
+ size: file.size,
+ });
+ } catch {
+ setProblem("unreadable");
+ }
+ }
+
+ useImperativeHandle(ref, () => ({
+ loadSource: (dataUrl: string, name: string) =>
+ loadSource({ dataUrl, name }),
+ getResult: async () =>
+ cleaned.dataUrl && !cleaned.processing
+ ? { source: "upload", type: "image", dataUrl: cleaned.dataUrl }
+ : null,
+ }));
+
+ const problemMessages: Record<UploadProblem, string> = {
+ unreadable: t("sign.wallet.upload.failed", "Could not read that image."),
+ rejected: t(
+ "sign.wallet.upload.rejected",
+ "Choose a PNG, JPG or WebP image up to {{size}} MB.",
+ { size: MAX_UPLOAD_MB },
+ ),
+ };
+ const currentProblem = cleaned.failed ? "unreadable" : problem;
+ const errorMessage = currentProblem ? problemMessages[currentProblem] : null;
+
+ if (!source) {
+ return (
+ <UploadDropzone
+ error={errorMessage}
+ onAccept={(file) => void acceptFile(file)}
+ onReject={() => setProblem("rejected")}
+ />
+ );
+ }
+
+ return (
+ <div className={styles.layout}>
+ <div className={styles.previewColumn}>
+ <TransparentPreview
+ src={cleaned.dataUrl}
+ label={t("sign.wallet.upload.preview", "Uploaded signature preview")}
+ overlay={
+ cleaned.processing &&
+ t("sign.wallet.upload.processing", "Cleaning up the image...")
+ }
+ />
+ <div className={styles.fileRow}>
+ <Icon name="image" size={16} />
+ <span className={styles.fileName}>{source.name}</span>
+ {source.size !== undefined && (
+ <span className={styles.fileSize}>
+ {formatFileSize(source.size)}
+ </span>
+ )}
+ <FilePicker
+ accept={ACCEPTED_TYPES.join(",")}
+ onChange={(file) => void acceptFile(file)}
+ variant="tertiary"
+ size="sm"
+ >
+ {t("sign.wallet.upload.replace", "Replace")}
+ </FilePicker>
+ </div>
+ {errorMessage && (
+ <span className={styles.error} role="alert">
+ {errorMessage}
+ </span>
+ )}
+ </div>
+ <UploadCleanupOptions value={cleanup} onChange={setCleanup} />
+ </div>
+ );
+});
+
+interface UploadDropzoneProps {
+ error: string | null;
+ onAccept: (file: File | null) => void;
+ onReject: () => void;
+}
+
+function UploadDropzone({ error, onAccept, onReject }: UploadDropzoneProps) {
+ const { t } = useTranslation();
+ const label = t("sign.wallet.upload.drop", "Drop an image here");
+
+ return (
+ <div className={styles.dropArea}>
+ <Dropzone
+ onDrop={(files) => onAccept(files[0] ?? null)}
+ onReject={onReject}
+ accept={ACCEPTED_TYPES}
+ maxSize={MAX_UPLOAD_MB * 1024 * 1024}
+ multiple={false}
+ aria-label={label}
+ inputProps={{ "aria-label": label }}
+ className={styles.dropzone}
+ >
+ <div className={styles.dropContent}>
+ <span className={styles.dropIcon}>
+ <Icon name="upload" size={19} />
+ </span>
+ <span className={styles.dropTitle}>{label}</span>
+ <span className={styles.dropBrowse}>
+ {t("sign.wallet.upload.browse", "or browse files")}
+ </span>
+ <span className={styles.dropHint}>
+ {t(
+ "sign.wallet.upload.hint",
+ "PNG, JPG or WebP up to {{size}} MB. White backgrounds are removed automatically.",
+ { size: MAX_UPLOAD_MB },
+ )}
+ </span>
+ </div>
+ </Dropzone>
+ {error && (
+ <span className={styles.error} role="alert">
+ {error}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/createTabs.ts b/frontend/editor/src/core/components/tools/sign/createSignature/createTabs.ts
new file mode 100644
index 0000000000..2be1cfb5c9
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/createTabs.ts
@@ -0,0 +1,36 @@
+import type { TFunction } from "i18next";
+import type { IconName } from "@app/ui/Icon";
+import type { CreateTab } from "@app/components/tools/sign/createSignature/types";
+
+export const CREATE_TAB_ICONS: Record<CreateTab, IconName> = {
+ draw: "signature",
+ type: "type",
+ upload: "upload",
+ phone: "qr-code",
+};
+
+export function createTabs(showPhone: boolean): CreateTab[] {
+ return showPhone
+ ? ["draw", "type", "upload", "phone"]
+ : ["draw", "type", "upload"];
+}
+
+export function createTabLabel(t: TFunction, tab: CreateTab): string {
+ const labels: Record<CreateTab, string> = {
+ draw: t("sign.wallet.tabs.draw", "Draw"),
+ type: t("sign.wallet.tabs.type", "Type"),
+ upload: t("sign.wallet.tabs.upload", "Upload"),
+ phone: t("sign.wallet.tabs.phone", "Phone"),
+ };
+ return labels[tab];
+}
+
+export function defaultSignatureName(t: TFunction, tab: CreateTab): string {
+ const names: Record<CreateTab, string> = {
+ draw: t("sign.wallet.defaultName.draw", "My signature"),
+ type: t("sign.wallet.defaultName.type", "Typed signature"),
+ upload: t("sign.wallet.defaultName.upload", "Uploaded signature"),
+ phone: t("sign.wallet.defaultName.phone", "Phone signature"),
+ };
+ return names[tab];
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/signatureStyles.ts b/frontend/editor/src/core/components/tools/sign/createSignature/signatureStyles.ts
new file mode 100644
index 0000000000..347adbfef9
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/signatureStyles.ts
@@ -0,0 +1,33 @@
+import "@fontsource/mrs-saint-delafield/400.css";
+import "@fontsource/great-vibes/400.css";
+import "@fontsource/dancing-script/500.css";
+import "@fontsource/caveat/500.css";
+import "@fontsource/homemade-apple/400.css";
+import "@fontsource/allura/400.css";
+
+export interface SignatureFont {
+ family: string;
+ previewScale: number;
+}
+
+export const SIGNATURE_FONTS: SignatureFont[] = [
+ { family: "Mrs Saint Delafield", previewScale: 1.3 },
+ { family: "Great Vibes", previewScale: 1 },
+ { family: "Dancing Script", previewScale: 0.85 },
+ { family: "Caveat", previewScale: 0.95 },
+ { family: "Homemade Apple", previewScale: 0.58 },
+ { family: "Allura", previewScale: 1.1 },
+];
+
+export interface InkColor {
+ id: "black" | "navy" | "blue";
+ value: string;
+}
+
+export const INK_COLORS: InkColor[] = [
+ { id: "black", value: "#111111" }, // theme-allow-color signature ink on paper
+ { id: "navy", value: "#16233f" }, // theme-allow-color signature ink on paper
+ { id: "blue", value: "#1d4ed8" }, // theme-allow-color signature ink on paper
+];
+
+export const DEFAULT_INK = INK_COLORS[0];
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/types.ts b/frontend/editor/src/core/components/tools/sign/createSignature/types.ts
new file mode 100644
index 0000000000..6769d9d392
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/types.ts
@@ -0,0 +1,41 @@
+import type { SavedSignatureType, SignatureScope } from "@app/types/signature";
+
+export type CreateTab = "draw" | "type" | "upload" | "phone";
+
+export type SaveScope = Exclude<SignatureScope, "localStorage">;
+
+export interface TypedSignatureSource {
+ signerName: string;
+ fontFamily: string;
+ fontSize: number;
+ textColor: string;
+}
+
+export interface CreatedSignature {
+ source: CreateTab;
+ type: SavedSignatureType;
+ dataUrl: string;
+ text?: TypedSignatureSource;
+ initials?: TypedSignatureSource & { dataUrl: string };
+}
+
+export interface SaveChoice {
+ label: string;
+ scope: SaveScope;
+ makeDefault: boolean;
+}
+
+export interface SignaturePanelHandle {
+ getResult: () => Promise<CreatedSignature | null>;
+}
+
+export interface TypePanelHandle extends SignaturePanelHandle {
+ setName: (
+ name: string,
+ style?: Pick<TypedSignatureSource, "fontFamily" | "textColor">,
+ ) => void;
+}
+
+export interface UploadPanelHandle extends SignaturePanelHandle {
+ loadSource: (dataUrl: string, fileName: string) => void;
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/useCleanedSignatureImage.ts b/frontend/editor/src/core/components/tools/sign/createSignature/useCleanedSignatureImage.ts
new file mode 100644
index 0000000000..379f1340fe
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/useCleanedSignatureImage.ts
@@ -0,0 +1,48 @@
+import { useEffect, useState } from "react";
+import {
+ cleanUpSignatureImage,
+ type UploadCleanup,
+} from "@app/utils/signatureImage";
+
+interface CleanedImage {
+ dataUrl: string | null;
+ processing: boolean;
+ failed: boolean;
+}
+
+const EMPTY: CleanedImage = { dataUrl: null, processing: false, failed: false };
+
+export function useCleanedSignatureImage(
+ source: string | null,
+ cleanup: UploadCleanup,
+): CleanedImage {
+ const [state, setState] = useState<CleanedImage>(EMPTY);
+ const { removeBackground, trim, inkColor, quarterTurns } = cleanup;
+
+ useEffect(() => {
+ if (!source) {
+ setState(EMPTY);
+ return;
+ }
+ let cancelled = false;
+ setState((prev) => ({ ...prev, processing: true }));
+ cleanUpSignatureImage(source, {
+ removeBackground,
+ trim,
+ inkColor,
+ quarterTurns,
+ })
+ .then((dataUrl) => {
+ if (!cancelled) setState({ dataUrl, processing: false, failed: false });
+ })
+ .catch(() => {
+ if (!cancelled)
+ setState({ dataUrl: null, processing: false, failed: true });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [source, removeBackground, trim, inkColor, quarterTurns]);
+
+ return state;
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/useSignaturePad.ts b/frontend/editor/src/core/components/tools/sign/createSignature/useSignaturePad.ts
new file mode 100644
index 0000000000..06bc99b879
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/useSignaturePad.ts
@@ -0,0 +1,131 @@
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type RefObject,
+} from "react";
+import SignaturePad from "signature_pad";
+import { trimCanvas } from "@app/utils/canvasImage";
+import { SIGNATURE_TRIM_PADDING } from "@app/utils/signatureImage";
+
+export type PenWidth = "fine" | "medium" | "bold";
+
+export const PEN_WIDTHS: Record<PenWidth, { min: number; max: number }> = {
+ fine: { min: 0.6, max: 1.8 },
+ medium: { min: 1, max: 3 },
+ bold: { min: 1.8, max: 4.8 },
+};
+
+const MIN_PIXEL_RATIO = 2;
+const padLayouts = new WeakMap<
+ SignaturePad,
+ { width: number; height: number }
+>();
+
+function fitCanvasToLayout(canvas: HTMLCanvasElement, pad: SignaturePad) {
+ // The modal's opening transform changes its visual bounds without changing
+ // layout or notifying ResizeObserver.
+ const layoutWidth = canvas.clientWidth;
+ const layoutHeight = canvas.clientHeight;
+ if (layoutWidth === 0 || layoutHeight === 0) return;
+ const ratio = Math.max(window.devicePixelRatio || 1, MIN_PIXEL_RATIO);
+ const width = Math.round(layoutWidth * ratio);
+ const height = Math.round(layoutHeight * ratio);
+ if (canvas.width === width && canvas.height === height) {
+ padLayouts.set(pad, { width: layoutWidth, height: layoutHeight });
+ return;
+ }
+ const previous = padLayouts.get(pad);
+ const scaleX = previous ? layoutWidth / previous.width : 1;
+ const scaleY = previous ? layoutHeight / previous.height : 1;
+ const strokes = pad.toData().map((group) => ({
+ ...group,
+ points: group.points.map((point) => ({
+ ...point,
+ x: point.x * scaleX,
+ y: point.y * scaleY,
+ })),
+ }));
+ canvas.width = width;
+ canvas.height = height;
+ canvas.getContext("2d")?.scale(ratio, ratio);
+ pad.fromData(strokes);
+ padLayouts.set(pad, { width: layoutWidth, height: layoutHeight });
+}
+
+function restyle(pad: SignaturePad, ink: string, pen: PenWidth) {
+ const { min, max } = PEN_WIDTHS[pen];
+ pad.penColor = ink;
+ pad.minWidth = min;
+ pad.maxWidth = max;
+ pad.fromData(
+ pad.toData().map((group) => ({
+ ...group,
+ penColor: ink,
+ minWidth: min,
+ maxWidth: max,
+ })),
+ );
+}
+
+export function useSignaturePad(
+ canvasRef: RefObject<HTMLCanvasElement | null>,
+ ink: string,
+ pen: PenWidth,
+) {
+ const padRef = useRef<SignaturePad | null>(null);
+ const [strokeCount, setStrokeCount] = useState(0);
+
+ const syncStrokeCount = useCallback(() => {
+ setStrokeCount(padRef.current?.toData().length ?? 0);
+ }, []);
+
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas) return;
+ const pad = new SignaturePad(canvas, {
+ throttle: 8,
+ minDistance: 2,
+ // Signature trimming reads pixels from this context.
+ canvasContextOptions: { willReadFrequently: true },
+ });
+ padRef.current = pad;
+ pad.addEventListener("endStroke", syncStrokeCount);
+ fitCanvasToLayout(canvas, pad);
+ const observer = new ResizeObserver(() => fitCanvasToLayout(canvas, pad));
+ observer.observe(canvas);
+ return () => {
+ observer.disconnect();
+ pad.removeEventListener("endStroke", syncStrokeCount);
+ pad.off();
+ padRef.current = null;
+ };
+ }, [canvasRef, syncStrokeCount]);
+
+ useEffect(() => {
+ if (padRef.current) restyle(padRef.current, ink, pen);
+ }, [ink, pen]);
+
+ const undo = useCallback(() => {
+ const pad = padRef.current;
+ if (!pad) return;
+ pad.fromData(pad.toData().slice(0, -1));
+ syncStrokeCount();
+ }, [syncStrokeCount]);
+
+ const clear = useCallback(() => {
+ padRef.current?.clear();
+ syncStrokeCount();
+ }, [syncStrokeCount]);
+
+ const toTrimmedDataUrl = useCallback(() => {
+ const canvas = canvasRef.current;
+ if (!canvas || !padRef.current || padRef.current.isEmpty()) return null;
+ return trimCanvas(canvas, { padding: SIGNATURE_TRIM_PADDING }).toDataURL(
+ "image/png",
+ );
+ }, [canvasRef]);
+
+ return { strokeCount, undo, clear, toTrimmedDataUrl };
+}
diff --git a/frontend/editor/src/core/components/tools/sign/createSignature/useTabReadiness.ts b/frontend/editor/src/core/components/tools/sign/createSignature/useTabReadiness.ts
new file mode 100644
index 0000000000..0def0b1af9
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/createSignature/useTabReadiness.ts
@@ -0,0 +1,21 @@
+import { useMemo, useState } from "react";
+import type { CreateTab } from "@app/components/tools/sign/createSignature/types";
+
+type TabReadiness = Partial<Record<CreateTab, boolean>>;
+
+export function useTabReadiness() {
+ const [ready, setReady] = useState<TabReadiness>({});
+ const handlers = useMemo(() => {
+ const handlerFor = (tab: CreateTab) => (value: boolean) =>
+ setReady((prev) =>
+ prev[tab] === value ? prev : { ...prev, [tab]: value },
+ );
+ return {
+ draw: handlerFor("draw"),
+ type: handlerFor("type"),
+ upload: handlerFor("upload"),
+ phone: handlerFor("phone"),
+ };
+ }, []);
+ return { ready, handlers };
+}
diff --git a/frontend/editor/src/core/components/tools/sign/parseMobileSignatureFile.ts b/frontend/editor/src/core/components/tools/sign/parseMobileSignatureFile.ts
new file mode 100644
index 0000000000..8c77a6dc6a
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/parseMobileSignatureFile.ts
@@ -0,0 +1,68 @@
+import { readFileAsDataUrl } from "@app/utils/fileUtils";
+import type { MobileSignaturePayload } from "@app/components/tools/sign/MobileSignatureModal";
+
+const TEXT_FONTS = new Set([
+ "Helvetica",
+ "Times-Roman",
+ "Courier",
+ "Arial",
+ "Georgia",
+]);
+const HEX_COLOR = /^#[0-9a-fA-F]{6}$/;
+const MAX_TEXT_LENGTH = 200;
+
+function readFileAsText(file: File): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(String(reader.result ?? ""));
+ reader.onerror = () => reject(reader.error);
+ reader.readAsText(file);
+ });
+}
+
+function stringField(record: Record<string, unknown>, key: string): string {
+ const value = record[key];
+ return typeof value === "string" ? value : "";
+}
+
+function isTextPayload(file: File) {
+ return (
+ file.type === "application/json" && file.name.startsWith("signature-text")
+ );
+}
+
+async function readTextPayload(
+ file: File,
+): Promise<MobileSignaturePayload | null> {
+ try {
+ const record: Record<string, unknown> =
+ JSON.parse(await readFileAsText(file)) ?? {};
+ const text = stringField(record, "text").trim().slice(0, MAX_TEXT_LENGTH);
+ if (!text) return null;
+ const fontFamily = stringField(record, "fontFamily");
+ const color = stringField(record, "color");
+ return {
+ kind: "text",
+ text,
+ fontFamily: TEXT_FONTS.has(fontFamily) ? fontFamily : "Helvetica",
+ color: HEX_COLOR.test(color) ? color : "#000000",
+ };
+ } catch {
+ console.warn("[MobileSignature] Ignoring malformed text payload");
+ return null;
+ }
+}
+
+export async function parseMobileSignatureFile(
+ file: File,
+): Promise<MobileSignaturePayload | null> {
+ if (isTextPayload(file)) return readTextPayload(file);
+ if (!file.type.startsWith("image/")) {
+ console.warn("[MobileSignature] Ignoring non-image upload:", file.type);
+ return null;
+ }
+ const dataUrl = await readFileAsDataUrl(file).catch(() => null);
+ if (!dataUrl) return null;
+ const kind = file.name.startsWith("signature-photo") ? "photo" : "draw";
+ return { kind, dataUrl };
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/ApplySignaturesButton.tsx b/frontend/editor/src/core/components/tools/sign/wallet/ApplySignaturesButton.tsx
new file mode 100644
index 0000000000..c45bd6d4e1
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/ApplySignaturesButton.tsx
@@ -0,0 +1,34 @@
+import { useTranslation } from "react-i18next";
+import { Button } from "@app/ui/Button";
+
+interface ApplySignaturesButtonProps {
+ count: number;
+ disabled: boolean;
+ applying?: boolean;
+ onApply: () => void;
+}
+
+export function ApplySignaturesButton({
+ count,
+ disabled,
+ applying = false,
+ onApply,
+}: ApplySignaturesButtonProps) {
+ const { t } = useTranslation();
+ const label =
+ count === 0
+ ? t("sign.wallet.applyEmpty", "Apply signatures")
+ : t("sign.wallet.apply", "Apply {{count}} signatures", { count });
+
+ return (
+ <Button
+ fullWidth
+ onClick={onApply}
+ disabled={disabled || applying || count === 0}
+ loading={applying}
+ data-testid="apply-signatures"
+ >
+ {label}
+ </Button>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/DeleteSignatureModal.tsx b/frontend/editor/src/core/components/tools/sign/wallet/DeleteSignatureModal.tsx
new file mode 100644
index 0000000000..69bb3e990e
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/DeleteSignatureModal.tsx
@@ -0,0 +1,61 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@app/ui/Button";
+import { Modal } from "@app/ui/Modal";
+import styles from "@app/components/tools/sign/wallet/SignatureWallet.module.css";
+
+interface DeleteSignatureModalProps {
+ name: string;
+ onClose: () => void;
+ onConfirm: () => Promise<boolean>;
+}
+
+export function DeleteSignatureModal({
+ name,
+ onClose,
+ onConfirm,
+}: DeleteSignatureModalProps) {
+ const { t } = useTranslation();
+ const [deleting, setDeleting] = useState(false);
+
+ async function confirm() {
+ if (deleting) return;
+ setDeleting(true);
+ try {
+ if (await onConfirm()) onClose();
+ } finally {
+ setDeleting(false);
+ }
+ }
+
+ const footer = (
+ <div className={styles.dialogFooter}>
+ <Button variant="tertiary" onClick={onClose} disabled={deleting}>
+ {t("sign.wallet.create.cancel", "Cancel")}
+ </Button>
+ <Button accent="danger" onClick={() => void confirm()} loading={deleting}>
+ {t("sign.wallet.delete.confirm", "Delete")}
+ </Button>
+ </div>
+ );
+
+ return (
+ <Modal
+ open
+ onClose={() => {
+ if (!deleting) onClose();
+ }}
+ title={t("sign.wallet.delete.title", "Delete this signature?")}
+ width="sm"
+ footer={footer}
+ >
+ <p className={styles.dialogBody}>
+ {t(
+ "sign.wallet.delete.body",
+ '"{{name}}" is removed from your signatures. Documents you already signed keep it.',
+ { name },
+ )}
+ </p>
+ </Modal>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/PlacedSignaturesList.module.css b/frontend/editor/src/core/components/tools/sign/wallet/PlacedSignaturesList.module.css
new file mode 100644
index 0000000000..da4b1bfb39
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/PlacedSignaturesList.module.css
@@ -0,0 +1,87 @@
+.section {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+}
+
+.header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.5rem;
+}
+
+.title {
+ margin: 0;
+ font-size: 0.8125rem;
+ font-weight: 700;
+ color: var(--c-text);
+}
+
+.empty {
+ margin: 0;
+ font-size: 0.75rem;
+ color: var(--c-text-subtle);
+}
+
+.list {
+ display: flex;
+ flex-direction: column;
+ gap: 0.125rem;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.row {
+ display: flex;
+ align-items: center;
+ gap: 0.625rem;
+ padding: 0.375rem 0.25rem;
+ border-radius: 0.5rem;
+}
+
+.row:hover,
+.row:focus-within {
+ background: var(--c-hover);
+}
+
+.thumb {
+ width: 3.625rem;
+ height: 2rem;
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ overflow: hidden;
+ border-radius: 0.375rem;
+ background: white;
+ border: 1px solid var(--c-border-subtle);
+}
+
+.thumbImage {
+ max-width: 100%;
+ max-height: 100%;
+ object-fit: contain;
+}
+
+.text {
+ display: flex;
+ flex-direction: column;
+ flex-grow: 1;
+ min-width: 0;
+}
+
+.name {
+ font-size: 0.78125rem;
+ font-weight: 600;
+ color: var(--c-text);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.where {
+ font-size: 0.71875rem;
+ color: var(--c-text-subtle);
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/PlacedSignaturesList.tsx b/frontend/editor/src/core/components/tools/sign/wallet/PlacedSignaturesList.tsx
new file mode 100644
index 0000000000..ff8311dfbf
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/PlacedSignaturesList.tsx
@@ -0,0 +1,128 @@
+import { useTranslation } from "react-i18next";
+import { ActionIcon } from "@app/ui/ActionIcon";
+import { Icon } from "@app/ui/Icon";
+import { DrawingControls } from "@app/components/annotation/shared/DrawingControls";
+import type { PlacedSignature } from "@app/contexts/SignatureContext";
+import type { HistoryAvailability } from "@app/hooks/useHistoryAvailability";
+import styles from "@app/components/tools/sign/wallet/PlacedSignaturesList.module.css";
+
+interface PlacedSignaturesListProps {
+ placed: PlacedSignature[];
+ nameFor: (entry: PlacedSignature) => string;
+ history: HistoryAvailability;
+ onUndo?: () => void;
+ onRedo?: () => void;
+ onShow: (entry: PlacedSignature) => void;
+ onRemove: (entry: PlacedSignature) => void;
+ disabled?: boolean;
+}
+
+export function PlacedSignaturesList({
+ placed,
+ nameFor,
+ history,
+ onUndo,
+ onRedo,
+ onShow,
+ onRemove,
+ disabled = false,
+}: PlacedSignaturesListProps) {
+ const { t } = useTranslation();
+
+ return (
+ <section className={styles.section} data-testid="placed-signatures">
+ <div className={styles.header}>
+ <h3 className={styles.title}>
+ {t("sign.wallet.placed.title", "On this document ({{count}})", {
+ count: placed.length,
+ })}
+ </h3>
+ <DrawingControls
+ onUndo={onUndo}
+ onRedo={onRedo}
+ canUndo={!disabled && history.canUndo}
+ canRedo={!disabled && history.canRedo}
+ showPlaceButton={false}
+ />
+ </div>
+ {placed.length === 0 ? (
+ <p className={styles.empty}>
+ {t(
+ "sign.wallet.placed.empty",
+ "Signatures you place on the page are listed here.",
+ )}
+ </p>
+ ) : (
+ <ul className={styles.list}>
+ {placed.map((entry) => (
+ <PlacedSignatureRow
+ key={entry.id}
+ entry={entry}
+ name={nameFor(entry)}
+ onShow={() => onShow(entry)}
+ onRemove={() => onRemove(entry)}
+ disabled={disabled}
+ />
+ ))}
+ </ul>
+ )}
+ </section>
+ );
+}
+
+interface PlacedSignatureRowProps {
+ entry: PlacedSignature;
+ name: string;
+ onShow: () => void;
+ onRemove: () => void;
+ disabled: boolean;
+}
+
+function PlacedSignatureRow({
+ entry,
+ name,
+ onShow,
+ onRemove,
+ disabled,
+}: PlacedSignatureRowProps) {
+ const { t } = useTranslation();
+
+ return (
+ <li className={styles.row}>
+ <span className={styles.thumb} aria-hidden>
+ {entry.imageSrc && (
+ <img className={styles.thumbImage} src={entry.imageSrc} alt="" />
+ )}
+ </span>
+ <span className={styles.text}>
+ <span className={styles.name}>{name}</span>
+ <span className={styles.where}>
+ {t("sign.wallet.placed.page", "Page {{page}}", {
+ page: entry.pageIndex + 1,
+ })}
+ </span>
+ </span>
+ <ActionIcon
+ variant="tertiary"
+ size="sm"
+ aria-label={t("sign.wallet.placed.show", "Show {{name}} on the page", {
+ name,
+ })}
+ onClick={onShow}
+ disabled={disabled}
+ >
+ <Icon name="locate-fixed" size={15} />
+ </ActionIcon>
+ <ActionIcon
+ variant="tertiary"
+ size="sm"
+ accent="danger"
+ aria-label={t("sign.wallet.placed.remove", "Remove {{name}}", { name })}
+ onClick={onRemove}
+ disabled={disabled}
+ >
+ <Icon name="trash" size={15} />
+ </ActionIcon>
+ </li>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/PlacementStatus.tsx b/frontend/editor/src/core/components/tools/sign/wallet/PlacementStatus.tsx
new file mode 100644
index 0000000000..82fb908094
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/PlacementStatus.tsx
@@ -0,0 +1,44 @@
+import { useTranslation } from "react-i18next";
+import { Banner } from "@app/ui/Banner";
+import { Button } from "@app/ui/Button";
+import { Icon } from "@app/ui/Icon";
+
+interface PlacementStatusProps {
+ placing: string | null;
+ onStop: () => void;
+}
+
+export function PlacementStatus({ placing, onStop }: PlacementStatusProps) {
+ const { t } = useTranslation();
+ const icon = <Icon name="locate-fixed" size={16} />;
+
+ return (
+ <div data-testid="placement-status">
+ {placing ? (
+ <Banner
+ tone="info"
+ icon={icon}
+ description={t(
+ "sign.wallet.status.placing",
+ "Click the page to place {{name}}.",
+ { name: placing },
+ )}
+ action={
+ <Button variant="secondary" size="sm" onClick={onStop}>
+ {t("sign.wallet.status.stop", "Stop")}
+ </Button>
+ }
+ />
+ ) : (
+ <Banner
+ tone="neutral"
+ icon={icon}
+ description={t(
+ "sign.wallet.status.idle",
+ "Pick a signature to place it",
+ )}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/RenameSignatureModal.tsx b/frontend/editor/src/core/components/tools/sign/wallet/RenameSignatureModal.tsx
new file mode 100644
index 0000000000..1a5e88eaa1
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/RenameSignatureModal.tsx
@@ -0,0 +1,73 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@app/ui/Button";
+import { FormField } from "@app/ui/FormField";
+import { Input } from "@app/ui/Input";
+import { Modal } from "@app/ui/Modal";
+import styles from "@app/components/tools/sign/wallet/SignatureWallet.module.css";
+
+interface RenameSignatureModalProps {
+ currentName: string;
+ onClose: () => void;
+ onRename: (name: string) => Promise<boolean>;
+}
+
+export function RenameSignatureModal({
+ currentName,
+ onClose,
+ onRename,
+}: RenameSignatureModalProps) {
+ const { t } = useTranslation();
+ const [name, setName] = useState(currentName);
+ const [saving, setSaving] = useState(false);
+ const canSave = name.trim().length > 0;
+
+ async function submit() {
+ if (!canSave || saving) return;
+ setSaving(true);
+ try {
+ if (await onRename(name)) onClose();
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ const footer = (
+ <div className={styles.dialogFooter}>
+ <Button variant="tertiary" onClick={onClose} disabled={saving}>
+ {t("sign.wallet.create.cancel", "Cancel")}
+ </Button>
+ <Button
+ onClick={() => void submit()}
+ disabled={!canSave}
+ loading={saving}
+ >
+ {t("sign.wallet.rename.save", "Save")}
+ </Button>
+ </div>
+ );
+
+ return (
+ <Modal
+ open
+ onClose={() => {
+ if (!saving) onClose();
+ }}
+ title={t("sign.wallet.rename.title", "Rename signature")}
+ width="sm"
+ footer={footer}
+ >
+ <FormField label={t("sign.wallet.create.name", "Name")}>
+ <Input
+ value={name}
+ maxLength={60}
+ disabled={saving}
+ onChange={(event) => setName(event.currentTarget.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") void submit();
+ }}
+ />
+ </FormField>
+ </Modal>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/SignatureLibraryView.tsx b/frontend/editor/src/core/components/tools/sign/wallet/SignatureLibraryView.tsx
new file mode 100644
index 0000000000..ad7efde7b4
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/SignatureLibraryView.tsx
@@ -0,0 +1,121 @@
+import { useTranslation } from "react-i18next";
+import type { SavedSignature } from "@app/types/signature";
+import { SignatureSection } from "@app/components/tools/sign/wallet/SignatureSection";
+import {
+ NewSignatureTile,
+ SignatureTile,
+} from "@app/components/tools/sign/wallet/SignatureTile";
+import {
+ draftSignatureActions,
+ savedSignatureActions,
+} from "@app/components/tools/sign/wallet/signatureTileActions";
+import type { SignatureLibrary } from "@app/components/tools/sign/wallet/useSignatureLibrary";
+import type { SignaturePlacement } from "@app/components/tools/sign/wallet/useSignaturePlacement";
+import {
+ DRAFT_KEY,
+ toWalletEntry,
+} from "@app/components/tools/sign/wallet/walletEntry";
+
+interface SignatureLibraryViewProps {
+ library: SignatureLibrary;
+ placement: SignaturePlacement;
+ disabled: boolean;
+ onNew: () => void;
+ onRename: (signature: SavedSignature) => void;
+ onDelete: (signature: SavedSignature) => void;
+ onShare: (signature: SavedSignature) => void;
+ onSaveDraft: () => void;
+ onDiscardDraft: () => void;
+}
+
+export function SignatureLibraryView({
+ library,
+ placement,
+ disabled,
+ onNew,
+ onRename,
+ onDelete,
+ onShare,
+ onSaveDraft,
+ onDiscardDraft,
+}: SignatureLibraryViewProps) {
+ const { t } = useTranslation();
+ const { draft } = library;
+
+ function savedTile(signature: SavedSignature) {
+ const entry = toWalletEntry(signature);
+ const isDefault = library.defaultId === signature.id;
+ const actions = savedSignatureActions(signature, {
+ t,
+ isPlacing: placement.placingKey === signature.id,
+ isDefault,
+ isAdmin: library.isAdmin,
+ canShare: library.canShare,
+ onPlace: () => placement.arm(entry),
+ onStop: placement.stop,
+ onRename: () => onRename(signature),
+ onToggleDefault: () => library.toggleDefault(signature),
+ onShare: () => onShare(signature),
+ onDelete: () => onDelete(signature),
+ });
+ return (
+ <SignatureTile
+ key={signature.id}
+ label={signature.label}
+ dataUrl={signature.dataUrl}
+ isDefault={isDefault}
+ selected={placement.placingKey === signature.id}
+ disabled={disabled}
+ actions={actions}
+ onClick={() => placement.toggle(entry)}
+ />
+ );
+ }
+
+ return (
+ <>
+ <SignatureSection
+ title={t("sign.wallet.yours", "Your signatures")}
+ meta={t("sign.wallet.count", "{{count}} of {{max}}", {
+ count: library.count,
+ max: library.maxLimit,
+ })}
+ >
+ {draft && (
+ <SignatureTile
+ label={draft.label}
+ dataUrl={draft.dataUrl}
+ badge={t("sign.wallet.unsaved", "Unsaved")}
+ selected={placement.placingKey === DRAFT_KEY}
+ disabled={disabled}
+ actions={draftSignatureActions({
+ t,
+ isPlacing: placement.placingKey === DRAFT_KEY,
+ canSave: !library.isFull,
+ onPlace: () => placement.arm(draft),
+ onStop: placement.stop,
+ onSave: onSaveDraft,
+ onDiscard: onDiscardDraft,
+ })}
+ onClick={() => placement.toggle(draft)}
+ />
+ )}
+ {library.mine.map(savedTile)}
+ <NewSignatureTile
+ label={t("sign.wallet.new", "New signature")}
+ disabled={disabled}
+ onClick={onNew}
+ />
+ </SignatureSection>
+ {library.shared.length > 0 && (
+ <SignatureSection
+ title={t("sign.wallet.shared", "Shared")}
+ meta={t("sign.wallet.sharedHint", "Everyone can use these")}
+ icon="users"
+ >
+ {library.shared.map(savedTile)}
+ </SignatureSection>
+ )}
+ </>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/SignatureSection.tsx b/frontend/editor/src/core/components/tools/sign/wallet/SignatureSection.tsx
new file mode 100644
index 0000000000..d993ff4c09
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/SignatureSection.tsx
@@ -0,0 +1,28 @@
+import type { ReactNode } from "react";
+import { Icon, type IconName } from "@app/ui/Icon";
+import styles from "@app/components/tools/sign/wallet/SignatureWallet.module.css";
+
+interface SignatureSectionProps {
+ title: string;
+ meta?: string;
+ icon?: IconName;
+ children: ReactNode;
+}
+
+export function SignatureSection({
+ title,
+ meta,
+ icon,
+ children,
+}: SignatureSectionProps) {
+ return (
+ <section className={styles.section}>
+ <div className={styles.sectionHeader}>
+ {icon && <Icon name={icon} size={14} className={styles.sectionIcon} />}
+ <h3 className={styles.sectionTitle}>{title}</h3>
+ {meta && <span className={styles.sectionMeta}>{meta}</span>}
+ </div>
+ <div className={styles.grid}>{children}</div>
+ </section>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/SignatureTile.module.css b/frontend/editor/src/core/components/tools/sign/wallet/SignatureTile.module.css
new file mode 100644
index 0000000000..a3c12fb575
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/SignatureTile.module.css
@@ -0,0 +1,168 @@
+.tile {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ gap: 0.375rem;
+ min-width: 0;
+}
+
+.paper {
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 100%;
+ height: 4.25rem;
+ padding: 0.375rem;
+ box-sizing: border-box;
+ background: white;
+ border: 1px solid var(--c-border-subtle);
+ border-radius: 0.625rem;
+ cursor: pointer;
+ transition:
+ border-color 0.15s ease,
+ box-shadow 0.15s ease;
+}
+
+.paper:hover {
+ border-color: var(--c-border-strong);
+}
+
+.paper:focus-visible {
+ outline: 2px solid var(--c-primary);
+ outline-offset: 2px;
+}
+
+.paper:disabled {
+ cursor: default;
+ opacity: 0.6;
+}
+
+.paper[aria-pressed="true"] {
+ border: 2px solid var(--c-primary);
+ box-shadow: 0 0 0 3px var(--c-primary-subtle);
+}
+
+.newPaper {
+ background: var(--c-surface);
+ border: 1.5px dashed var(--c-border-strong);
+ color: var(--c-text-muted);
+}
+
+.newPaper:hover {
+ border-color: var(--c-primary);
+ color: var(--c-accent-text);
+}
+
+.image {
+ max-width: 100%;
+ max-height: 100%;
+ object-fit: contain;
+ pointer-events: none;
+}
+
+.check {
+ position: absolute;
+ top: -0.4375rem;
+ right: -0.4375rem;
+ width: 1.25rem;
+ height: 1.25rem;
+ box-sizing: border-box;
+ border-radius: 50%;
+ background: var(--c-primary);
+ color: var(--c-text-on-primary);
+ border: 2px solid var(--c-bg-raised);
+ display: none;
+ align-items: center;
+ justify-content: center;
+}
+
+.paper[aria-pressed="true"] .check {
+ display: flex;
+}
+
+.badge {
+ position: absolute;
+ left: 0.375rem;
+ top: 0.375rem;
+ height: 1.125rem;
+ padding: 0 0.375rem;
+ border-radius: 999px;
+ background: var(--c-warning-solid);
+ color: white;
+ font-size: 0.65625rem;
+ font-weight: 700;
+ display: flex;
+ align-items: center;
+}
+
+.menu {
+ position: absolute;
+ top: 0.25rem;
+ right: 0.25rem;
+ opacity: 0;
+ transition: opacity 0.12s ease;
+}
+
+.tile:hover .menu,
+.tile:focus-within .menu,
+.menu[data-open] {
+ opacity: 1;
+}
+
+@media (hover: none) {
+ .menu {
+ opacity: 1;
+ }
+}
+
+.menuButton {
+ width: 1.5rem;
+ height: 1.5rem;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0;
+ border-radius: 0.375rem;
+ border: 1px solid var(--c-illustration-line);
+ background: white;
+ color: var(--c-text-on-light);
+ cursor: pointer;
+}
+
+.menuButton:focus-visible {
+ outline: 2px solid var(--c-primary);
+ outline-offset: 1px;
+}
+
+.danger.danger,
+.danger.danger:hover:not(:disabled) {
+ color: var(--c-danger);
+}
+
+.label {
+ display: flex;
+ align-items: center;
+ gap: 0.3125rem;
+ min-width: 0;
+ padding: 0 0.125rem;
+ font-size: 0.78125rem;
+ font-weight: 600;
+ color: var(--c-text);
+}
+
+.tile:has(.paper[aria-pressed="true"]) .label {
+ color: var(--c-accent-text);
+}
+
+.labelText {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.star {
+ display: flex;
+ flex-shrink: 0;
+ color: var(--c-warning);
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/SignatureTile.stories.tsx b/frontend/editor/src/core/components/tools/sign/wallet/SignatureTile.stories.tsx
new file mode 100644
index 0000000000..3054fec7fa
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/SignatureTile.stories.tsx
@@ -0,0 +1,77 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import {
+ NewSignatureTile,
+ SignatureTile,
+} from "@app/components/tools/sign/wallet/SignatureTile";
+
+// icon-lint-allow: storybook-fixture -- Fake signature image for the wallet tile stories.
+const SIGNATURE =
+ "data:image/svg+xml;base64," +
+ btoa(
+ '<svg xmlns="http://www.w3.org/2000/svg" width="240" height="80"><path d="M10 60 C 40 10 60 10 70 50 S 110 70 130 40 S 170 20 190 50 L 230 40" stroke="black" fill="none" stroke-width="3" stroke-linecap="round"/></svg>',
+ );
+
+const actions = [
+ {
+ id: "place",
+ label: "Place on page",
+ icon: "locate-fixed" as const,
+ onSelect: () => {},
+ },
+ {
+ id: "rename",
+ label: "Rename",
+ icon: "pencil" as const,
+ onSelect: () => {},
+ },
+ {
+ id: "default",
+ label: "Make default",
+ icon: "star" as const,
+ onSelect: () => {},
+ },
+ {
+ id: "delete",
+ label: "Delete",
+ icon: "trash" as const,
+ danger: true,
+ onSelect: () => {},
+ },
+];
+
+const meta = {
+ title: "Tools/Sign/SignatureTile",
+ component: SignatureTile,
+ parameters: { layout: "padded" },
+ decorators: [
+ (Story) => (
+ <div style={{ width: 132 }}>
+ <Story />
+ </div>
+ ),
+ ],
+ args: {
+ label: "My signature",
+ dataUrl: SIGNATURE,
+ selected: false,
+ actions,
+ onClick: () => {},
+ },
+} satisfies Meta<typeof SignatureTile>;
+export default meta;
+
+type Story = StoryObj<typeof meta>;
+
+export const Default: Story = {};
+
+export const SelectedDefault: Story = {
+ args: { selected: true, isDefault: true },
+};
+
+export const Unsaved: Story = {
+ args: { label: "Typed signature", badge: "Unsaved" },
+};
+
+export const NewTile: Story = {
+ render: () => <NewSignatureTile label="New signature" onClick={() => {}} />,
+};
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/SignatureTile.tsx b/frontend/editor/src/core/components/tools/sign/wallet/SignatureTile.tsx
new file mode 100644
index 0000000000..abda402fbe
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/SignatureTile.tsx
@@ -0,0 +1,145 @@
+import { Fragment, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Dropdown } from "@app/ui/Dropdown";
+import { Icon, type IconName } from "@app/ui/Icon";
+import styles from "@app/components/tools/sign/wallet/SignatureTile.module.css";
+
+export interface SignatureTileAction {
+ id: string;
+ label: string;
+ icon: IconName;
+ danger?: boolean;
+ onSelect: () => void;
+}
+
+interface SignatureTileProps {
+ label: string;
+ dataUrl: string;
+ selected: boolean;
+ isDefault?: boolean;
+ badge?: string;
+ disabled?: boolean;
+ actions: SignatureTileAction[];
+ onClick: () => void;
+}
+
+export function SignatureTile({
+ label,
+ dataUrl,
+ selected,
+ isDefault = false,
+ badge,
+ disabled = false,
+ actions,
+ onClick,
+}: SignatureTileProps) {
+ const { t } = useTranslation();
+ const defaultLabel = t("sign.wallet.default", "Default");
+
+ return (
+ <div className={styles.tile} data-testid="signature-tile">
+ <button
+ type="button"
+ className={styles.paper}
+ aria-pressed={selected}
+ aria-label={label}
+ disabled={disabled}
+ onClick={onClick}
+ >
+ <img className={styles.image} src={dataUrl} alt="" />
+ {badge && <span className={styles.badge}>{badge}</span>}
+ <span className={styles.check} aria-hidden>
+ <Icon name="check" size={11} strokeWidth={3.2} />
+ </span>
+ </button>
+ <SignatureTileMenu label={label} actions={actions} disabled={disabled} />
+ <span className={styles.label}>
+ <span className={styles.labelText}>{label}</span>
+ {isDefault && (
+ <span className={styles.star} title={defaultLabel}>
+ <Icon name="star" size={12} filled title={defaultLabel} />
+ </span>
+ )}
+ </span>
+ </div>
+ );
+}
+
+interface SignatureTileMenuProps {
+ label: string;
+ actions: SignatureTileAction[];
+ disabled: boolean;
+}
+
+function SignatureTileMenu({
+ label,
+ actions,
+ disabled,
+}: SignatureTileMenuProps) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const firstDanger = actions.findIndex((action) => action.danger);
+
+ return (
+ <div className={styles.menu} data-open={open || undefined}>
+ <Dropdown.Root open={open} onOpenChange={setOpen} align="end">
+ <Dropdown.Trigger>
+ <button
+ type="button"
+ className={styles.menuButton}
+ aria-label={t("sign.wallet.menu.options", "Options for {{name}}", {
+ name: label,
+ })}
+ disabled={disabled}
+ >
+ <Icon name="ellipsis" size={14} />
+ </button>
+ </Dropdown.Trigger>
+ <Dropdown.Menu width={200}>
+ {actions.map((action, index) => (
+ <Fragment key={action.id}>
+ {index === firstDanger && index > 0 && <Dropdown.Divider />}
+ <Dropdown.Item
+ onSelect={action.onSelect}
+ leading={<Icon name={action.icon} size={15} />}
+ className={action.danger ? styles.danger : undefined}
+ >
+ {action.label}
+ </Dropdown.Item>
+ </Fragment>
+ ))}
+ </Dropdown.Menu>
+ </Dropdown.Root>
+ </div>
+ );
+}
+
+interface NewSignatureTileProps {
+ label: string;
+ disabled?: boolean;
+ onClick: () => void;
+}
+
+export function NewSignatureTile({
+ label,
+ disabled = false,
+ onClick,
+}: NewSignatureTileProps) {
+ return (
+ <div className={styles.tile}>
+ <button
+ type="button"
+ className={`${styles.paper} ${styles.newPaper}`}
+ onClick={onClick}
+ disabled={disabled}
+ aria-label={label}
+ data-testid="new-signature-tile"
+ >
+ <Icon name="plus" size={20} />
+ </button>
+ <span className={styles.label}>
+ <span className={styles.labelText}>{label}</span>
+ </span>
+ </div>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/SignatureWallet.module.css b/frontend/editor/src/core/components/tools/sign/wallet/SignatureWallet.module.css
new file mode 100644
index 0000000000..208f7479e3
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/SignatureWallet.module.css
@@ -0,0 +1,61 @@
+.wallet {
+ display: flex;
+ flex-direction: column;
+ gap: 0.875rem;
+}
+
+.loading {
+ margin: 0;
+ font-size: 0.75rem;
+ color: var(--c-text-subtle);
+}
+
+.section {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+}
+
+.sectionHeader {
+ display: flex;
+ align-items: center;
+ gap: 0.375rem;
+ min-height: 1.25rem;
+}
+
+.sectionIcon {
+ color: var(--c-text-subtle);
+}
+
+.sectionTitle {
+ flex-grow: 1;
+ margin: 0;
+ font-size: 0.8125rem;
+ font-weight: 700;
+ color: var(--c-text);
+}
+
+.sectionMeta {
+ font-size: 0.75rem;
+ color: var(--c-text-subtle);
+}
+
+.grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ column-gap: 0.625rem;
+ row-gap: 0.875rem;
+}
+
+.dialogFooter {
+ display: flex;
+ justify-content: flex-end;
+ gap: 0.625rem;
+}
+
+.dialogBody {
+ margin: 0;
+ font-size: 0.8125rem;
+ line-height: 1.5;
+ color: var(--c-text-muted);
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/SignatureWallet.tsx b/frontend/editor/src/core/components/tools/sign/wallet/SignatureWallet.tsx
new file mode 100644
index 0000000000..67f8c65be4
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/SignatureWallet.tsx
@@ -0,0 +1,206 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { useAppConfig } from "@app/contexts/AppConfigContext";
+import { useSignature } from "@app/contexts/SignatureContext";
+import { useIsMobile } from "@app/hooks/useIsMobile";
+import { useHistoryAvailability } from "@app/hooks/useHistoryAvailability";
+import type { SignParameters } from "@app/hooks/tools/sign/useSignParameters";
+import type { SavedSignature } from "@app/types/signature";
+import { CreateSignatureModal } from "@app/components/tools/sign/createSignature/CreateSignatureModal";
+import type { CreateTab } from "@app/components/tools/sign/createSignature/types";
+import { ApplySignaturesButton } from "@app/components/tools/sign/wallet/ApplySignaturesButton";
+import { DeleteSignatureModal } from "@app/components/tools/sign/wallet/DeleteSignatureModal";
+import { PlacedSignaturesList } from "@app/components/tools/sign/wallet/PlacedSignaturesList";
+import { PlacementStatus } from "@app/components/tools/sign/wallet/PlacementStatus";
+import { RenameSignatureModal } from "@app/components/tools/sign/wallet/RenameSignatureModal";
+import { SignatureLibraryView } from "@app/components/tools/sign/wallet/SignatureLibraryView";
+import { SignatureWalletIntro } from "@app/components/tools/sign/wallet/SignatureWalletIntro";
+import { useSignatureLibrary } from "@app/components/tools/sign/wallet/useSignatureLibrary";
+import {
+ useArmDefaultSignature,
+ useSignaturePlacement,
+} from "@app/components/tools/sign/wallet/useSignaturePlacement";
+import { useWalletActions } from "@app/components/tools/sign/wallet/useWalletActions";
+import styles from "@app/components/tools/sign/wallet/SignatureWallet.module.css";
+import { alert } from "@app/components/toast";
+
+type WalletDialog =
+ | { kind: "create"; tab: CreateTab }
+ | { kind: "rename"; signature: SavedSignature }
+ | { kind: "delete"; signature: SavedSignature }
+ | null;
+
+interface SignatureWalletProps {
+ onParameterChange: <K extends keyof SignParameters>(
+ key: K,
+ value: SignParameters[K],
+ ) => void;
+ disabled?: boolean;
+ applying?: boolean;
+ onActivateSignaturePlacement: () => void;
+ onDeactivateSignature: () => void;
+ onUndo?: () => void;
+ onRedo?: () => void;
+ onSave?: () => void;
+}
+
+export function SignatureWallet({
+ onParameterChange,
+ disabled = false,
+ applying = false,
+ onActivateSignaturePlacement,
+ onDeactivateSignature,
+ onUndo,
+ onRedo,
+ onSave,
+}: SignatureWalletProps) {
+ const { t } = useTranslation();
+ const { config } = useAppConfig();
+ const isMobile = useIsMobile();
+ const { placedSignatures, historyApiRef } = useSignature();
+ const history = useHistoryAvailability(historyApiRef);
+ const library = useSignatureLibrary();
+ const [dialog, setDialog] = useState<WalletDialog>(null);
+ const placement = useSignaturePlacement({
+ onParameterChange,
+ onActivate: onActivateSignaturePlacement,
+ onDeactivate: onDeactivateSignature,
+ });
+ const actions = useWalletActions(library, placement);
+ useArmDefaultSignature(
+ !library.isLoading && !disabled,
+ library.defaultEntry,
+ placement.arm,
+ );
+
+ const showPhone = Boolean(config?.enableMobileSignature) && !isMobile;
+ const closeDialog = () => setDialog(null);
+ const openCreate = (tab: CreateTab) => {
+ if (library.draft) {
+ alert({
+ alertType: "warning",
+ title: t(
+ "sign.wallet.toast.draftExists",
+ "Save or discard your unsaved signature first",
+ ),
+ });
+ return;
+ }
+ setDialog({ kind: "create", tab });
+ };
+
+ function renderLibrary() {
+ if (library.isLoading) {
+ return (
+ <p className={styles.loading}>
+ {t("sign.wallet.loading", "Loading your signatures...")}
+ </p>
+ );
+ }
+ if (library.isEmpty) {
+ return (
+ <SignatureWalletIntro
+ showPhone={showPhone}
+ browserStorage={library.browserStorage}
+ disabled={disabled}
+ onCreate={openCreate}
+ />
+ );
+ }
+ return (
+ <>
+ <SignatureLibraryView
+ library={library}
+ placement={placement}
+ disabled={disabled}
+ onNew={() => openCreate("draw")}
+ onRename={(signature) => setDialog({ kind: "rename", signature })}
+ onDelete={(signature) => setDialog({ kind: "delete", signature })}
+ onShare={(signature) => void actions.share(signature)}
+ onSaveDraft={() => void actions.saveDraft()}
+ onDiscardDraft={actions.discardDraft}
+ />
+ <PlacementStatus
+ placing={library.entryFor(placement.placingKey)?.label ?? null}
+ onStop={placement.stop}
+ />
+ <PlacedSignaturesList
+ placed={placedSignatures}
+ nameFor={(entry) =>
+ library.labelForImage(entry.imageSrc) ??
+ t("sign.wallet.placed.fallbackName", "Signature")
+ }
+ history={history}
+ onUndo={onUndo}
+ onRedo={onRedo}
+ onShow={actions.showPlaced}
+ onRemove={actions.removePlaced}
+ disabled={disabled}
+ />
+ </>
+ );
+ }
+
+ return (
+ <div className={styles.wallet} data-testid="signature-wallet">
+ {renderLibrary()}
+ {library.isEmpty &&
+ (placedSignatures.length > 0 || history.canUndo || history.canRedo) && (
+ <PlacedSignaturesList
+ placed={placedSignatures}
+ nameFor={() => t("sign.wallet.placed.fallbackName", "Signature")}
+ history={history}
+ onUndo={onUndo}
+ onRedo={onRedo}
+ onShow={actions.showPlaced}
+ onRemove={actions.removePlaced}
+ disabled={disabled}
+ />
+ )}
+ {onSave && (
+ <ApplySignaturesButton
+ count={placedSignatures.length}
+ disabled={disabled}
+ applying={applying}
+ onApply={() => {
+ placement.stop();
+ onSave();
+ }}
+ />
+ )}
+ {dialog?.kind === "create" && (
+ <CreateSignatureModal
+ initialTab={dialog.tab}
+ onClose={closeDialog}
+ onCreate={async (created, choice) => {
+ await actions.create(created, choice);
+ closeDialog();
+ }}
+ limits={{
+ canSave: !library.isFull,
+ maxLimit: library.maxLimit,
+ canShare: library.canShare,
+ browserStorage: library.browserStorage,
+ remainingSlots: library.maxLimit - library.count,
+ }}
+ showPhoneTab={showPhone}
+ existingLabels={library.labels}
+ />
+ )}
+ {dialog?.kind === "rename" && (
+ <RenameSignatureModal
+ currentName={dialog.signature.label}
+ onClose={closeDialog}
+ onRename={(name) => library.rename(dialog.signature, name)}
+ />
+ )}
+ {dialog?.kind === "delete" && (
+ <DeleteSignatureModal
+ name={dialog.signature.label}
+ onClose={closeDialog}
+ onConfirm={() => actions.remove(dialog.signature)}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/SignatureWalletIntro.module.css b/frontend/editor/src/core/components/tools/sign/wallet/SignatureWalletIntro.module.css
new file mode 100644
index 0000000000..f1a0c7414d
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/SignatureWalletIntro.module.css
@@ -0,0 +1,20 @@
+.intro {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+}
+
+.options {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 0.625rem;
+}
+
+.privacy {
+ display: flex;
+ gap: 0.5rem;
+ margin: 0;
+ font-size: 0.75rem;
+ line-height: 1.45;
+ color: var(--c-text-subtle);
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/SignatureWalletIntro.tsx b/frontend/editor/src/core/components/tools/sign/wallet/SignatureWalletIntro.tsx
new file mode 100644
index 0000000000..b361a54aae
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/SignatureWalletIntro.tsx
@@ -0,0 +1,66 @@
+import { useTranslation } from "react-i18next";
+import { EmptyState } from "@app/ui/EmptyState";
+import { Icon } from "@app/ui/Icon";
+import { OptionCard } from "@app/ui/OptionCard";
+import {
+ CREATE_TAB_ICONS,
+ createTabLabel,
+ createTabs,
+} from "@app/components/tools/sign/createSignature/createTabs";
+import type { CreateTab } from "@app/components/tools/sign/createSignature/types";
+import styles from "@app/components/tools/sign/wallet/SignatureWalletIntro.module.css";
+
+interface SignatureWalletIntroProps {
+ showPhone: boolean;
+ browserStorage: boolean;
+ disabled: boolean;
+ onCreate: (tab: CreateTab) => void;
+}
+
+export function SignatureWalletIntro({
+ showPhone,
+ browserStorage,
+ disabled,
+ onCreate,
+}: SignatureWalletIntroProps) {
+ const { t } = useTranslation();
+ const privacy = browserStorage
+ ? t(
+ "sign.wallet.intro.privacyBrowser",
+ "Saved signatures stay in this browser.",
+ )
+ : t(
+ "sign.wallet.intro.privacy",
+ "Saved signatures are private to you unless you choose to share them.",
+ );
+
+ return (
+ <div className={styles.intro} data-testid="signature-wallet-intro">
+ <EmptyState
+ size="compact"
+ icon={<Icon name="signature" size={22} />}
+ title={t("sign.wallet.intro.title", "Add your signature")}
+ description={t(
+ "sign.wallet.intro.body",
+ "Create it once. It is saved here, ready for every document you sign.",
+ )}
+ />
+ <div className={styles.options}>
+ {createTabs(showPhone).map((tab) => (
+ <OptionCard
+ key={tab}
+ padding="tight"
+ icon={<Icon name={CREATE_TAB_ICONS[tab]} size={17} />}
+ title={createTabLabel(t, tab)}
+ disabled={disabled}
+ onSelect={() => onCreate(tab)}
+ />
+ ))}
+ </div>
+ <p className={styles.privacy}>
+ <Icon name="lock" size={14} />
+ {privacy}
+ </p>
+ </div>
+ );
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/signatureTileActions.test.ts b/frontend/editor/src/core/components/tools/sign/wallet/signatureTileActions.test.ts
new file mode 100644
index 0000000000..08df029ee3
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/signatureTileActions.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it, vi } from "vitest";
+import type { TFunction } from "i18next";
+import type { SavedSignature } from "@app/types/signature";
+import {
+ draftSignatureActions,
+ savedSignatureActions,
+ type SavedActionContext,
+} from "@app/components/tools/sign/wallet/signatureTileActions";
+
+const t = ((_key: string, fallback: string) =>
+ fallback) as unknown as TFunction;
+
+const signature = (scope: SavedSignature["scope"]): SavedSignature => ({
+ id: "sig",
+ type: "canvas",
+ dataUrl: "data:image/png;base64,",
+ label: "Mine",
+ scope,
+ createdAt: 1,
+ updatedAt: 1,
+});
+
+const context = (
+ overrides: Partial<SavedActionContext> = {},
+): SavedActionContext => ({
+ t,
+ isPlacing: false,
+ isDefault: false,
+ isAdmin: false,
+ canShare: false,
+ onPlace: vi.fn(),
+ onStop: vi.fn(),
+ onRename: vi.fn(),
+ onToggleDefault: vi.fn(),
+ onShare: vi.fn(),
+ onDelete: vi.fn(),
+ ...overrides,
+});
+
+const ids = (actions: { id: string }[]) => actions.map((action) => action.id);
+
+describe("savedSignatureActions", () => {
+ it("lets the owner manage a personal signature", () => {
+ expect(
+ ids(savedSignatureActions(signature("personal"), context())),
+ ).toEqual(["place", "rename", "default", "delete"]);
+ });
+
+ it("keeps shared signatures read-only for non-admins", () => {
+ expect(ids(savedSignatureActions(signature("shared"), context()))).toEqual([
+ "place",
+ "default",
+ ]);
+ });
+
+ it("offers sharing only to admins on server storage, for personal signatures", () => {
+ const admin = context({ isAdmin: true, canShare: true });
+ expect(ids(savedSignatureActions(signature("personal"), admin))).toContain(
+ "share",
+ );
+ expect(
+ ids(savedSignatureActions(signature("localStorage"), admin)),
+ ).not.toContain("share");
+ });
+
+ it("swaps place for stop while the signature is being placed", () => {
+ const actions = savedSignatureActions(
+ signature("personal"),
+ context({ isPlacing: true }),
+ );
+ expect(actions[0].id).toBe("stop");
+ });
+
+ it("labels the default toggle by the current state", () => {
+ const actions = savedSignatureActions(
+ signature("personal"),
+ context({ isDefault: true }),
+ );
+ expect(actions.find((action) => action.id === "default")?.label).toBe(
+ "Remove as default",
+ );
+ });
+});
+
+describe("draftSignatureActions", () => {
+ it("hides saving when the library is full", () => {
+ const actions = draftSignatureActions({
+ t,
+ isPlacing: false,
+ canSave: false,
+ onPlace: vi.fn(),
+ onStop: vi.fn(),
+ onSave: vi.fn(),
+ onDiscard: vi.fn(),
+ });
+ expect(ids(actions)).toEqual(["place", "discard"]);
+ });
+});
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/signatureTileActions.ts b/frontend/editor/src/core/components/tools/sign/wallet/signatureTileActions.ts
new file mode 100644
index 0000000000..4d3e197694
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/signatureTileActions.ts
@@ -0,0 +1,115 @@
+import type { TFunction } from "i18next";
+import type { SavedSignature } from "@app/types/signature";
+import type { SignatureTileAction } from "@app/components/tools/sign/wallet/SignatureTile";
+
+interface PlaceActionContext {
+ t: TFunction;
+ isPlacing: boolean;
+ onPlace: () => void;
+ onStop: () => void;
+}
+
+export interface SavedActionContext extends PlaceActionContext {
+ isDefault: boolean;
+ isAdmin: boolean;
+ canShare: boolean;
+ onRename: () => void;
+ onToggleDefault: () => void;
+ onShare: () => void;
+ onDelete: () => void;
+}
+
+export interface DraftActionContext extends PlaceActionContext {
+ canSave: boolean;
+ onSave: () => void;
+ onDiscard: () => void;
+}
+
+const isAction = (
+ action: SignatureTileAction | false,
+): action is SignatureTileAction => action !== false;
+
+function placeAction({
+ t,
+ isPlacing,
+ onPlace,
+ onStop,
+}: PlaceActionContext): SignatureTileAction {
+ if (isPlacing) {
+ return {
+ id: "stop",
+ label: t("sign.wallet.menu.stop", "Stop placing"),
+ icon: "circle-pause",
+ onSelect: onStop,
+ };
+ }
+ return {
+ id: "place",
+ label: t("sign.wallet.menu.place", "Place on page"),
+ icon: "locate-fixed",
+ onSelect: onPlace,
+ };
+}
+
+export function savedSignatureActions(
+ signature: SavedSignature,
+ ctx: SavedActionContext,
+): SignatureTileAction[] {
+ const { t } = ctx;
+ const canEdit = signature.scope !== "shared" || ctx.isAdmin;
+ const canShare = ctx.canShare && signature.scope === "personal";
+ const actions: (SignatureTileAction | false)[] = [
+ placeAction(ctx),
+ canEdit && {
+ id: "rename",
+ label: t("sign.wallet.menu.rename", "Rename"),
+ icon: "pencil",
+ onSelect: ctx.onRename,
+ },
+ {
+ id: "default",
+ label: ctx.isDefault
+ ? t("sign.wallet.menu.removeDefault", "Remove as default")
+ : t("sign.wallet.menu.makeDefault", "Make default"),
+ icon: "star",
+ onSelect: ctx.onToggleDefault,
+ },
+ canShare && {
+ id: "share",
+ label: t("sign.wallet.menu.share", "Share with everyone"),
+ icon: "users",
+ onSelect: ctx.onShare,
+ },
+ canEdit && {
+ id: "delete",
+ label: t("sign.wallet.menu.delete", "Delete"),
+ icon: "trash",
+ danger: true,
+ onSelect: ctx.onDelete,
+ },
+ ];
+ return actions.filter(isAction);
+}
+
+export function draftSignatureActions(
+ ctx: DraftActionContext,
+): SignatureTileAction[] {
+ const { t } = ctx;
+ const actions: (SignatureTileAction | false)[] = [
+ placeAction(ctx),
+ ctx.canSave && {
+ id: "save",
+ label: t("sign.wallet.menu.save", "Save to my signatures"),
+ icon: "save",
+ onSelect: ctx.onSave,
+ },
+ {
+ id: "discard",
+ label: t("sign.wallet.menu.discard", "Discard"),
+ icon: "trash",
+ danger: true,
+ onSelect: ctx.onDiscard,
+ },
+ ];
+ return actions.filter(isAction);
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/useSignatureLibrary.test.ts b/frontend/editor/src/core/components/tools/sign/wallet/useSignatureLibrary.test.ts
new file mode 100644
index 0000000000..003d8631d0
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/useSignatureLibrary.test.ts
@@ -0,0 +1,172 @@
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { useSignatureLibrary } from "@app/components/tools/sign/wallet/useSignatureLibrary";
+import type {
+ CreatedSignature,
+ SaveChoice,
+} from "@app/components/tools/sign/createSignature/types";
+import type { SavedSignature } from "@app/types/signature";
+
+const mocks = vi.hoisted(() => ({
+ addSignature: vi.fn(),
+ removeSignature: vi.fn(),
+ updateSignatureLabel: vi.fn(),
+ setDefaultId: vi.fn(),
+ alert: vi.fn(),
+ ownCount: 0,
+ defaultId: "saved",
+}));
+
+vi.mock("@app/components/toast", () => ({ alert: mocks.alert }));
+vi.mock("@app/hooks/tools/sign/useDefaultSignature", () => ({
+ useDefaultSignature: () => ({
+ defaultId: mocks.defaultId,
+ setDefaultId: mocks.setDefaultId,
+ }),
+}));
+vi.mock("@app/hooks/tools/sign/useSavedSignatures", () => ({
+ useSavedSignatures: () => ({
+ savedSignatures: [],
+ ownCount: mocks.ownCount,
+ maxLimit: 20,
+ isLoading: false,
+ isAtCapacity: mocks.ownCount >= 20,
+ storageType: "backend",
+ isAdmin: true,
+ addSignature: mocks.addSignature,
+ removeSignature: mocks.removeSignature,
+ updateSignatureLabel: mocks.updateSignatureLabel,
+ }),
+}));
+
+const signature: SavedSignature = {
+ id: "saved",
+ type: "text",
+ dataUrl: "data:image/png;base64,name",
+ label: "Name",
+ scope: "personal",
+ signerName: "Alex Brown",
+ fontFamily: "Caveat",
+ fontSize: 120,
+ textColor: "#111111",
+ createdAt: 1,
+ updatedAt: 1,
+};
+const created: CreatedSignature = {
+ source: "type",
+ type: "text",
+ dataUrl: signature.dataUrl,
+ text: {
+ signerName: signature.signerName,
+ fontFamily: signature.fontFamily,
+ fontSize: 120,
+ textColor: "#111111",
+ },
+ initials: {
+ signerName: "AB",
+ fontFamily: "Caveat",
+ fontSize: 120,
+ textColor: "#111111",
+ dataUrl: "data:image/png;base64,initials",
+ },
+};
+const choice: SaveChoice = {
+ label: "Name",
+ scope: "personal",
+ makeDefault: true,
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.ownCount = 0;
+ mocks.defaultId = "saved";
+ mocks.addSignature.mockResolvedValue({ success: true, signature });
+ mocks.removeSignature.mockResolvedValue(true);
+ mocks.updateSignatureLabel.mockResolvedValue(true);
+});
+
+describe("signature library failures", () => {
+ it("does not partially save a requested pair when only one slot remains", async () => {
+ mocks.ownCount = 19;
+ const { result } = renderHook(useSignatureLibrary);
+ expect(await result.current.save(created, choice)).toBeNull();
+ expect(mocks.addSignature).not.toHaveBeenCalled();
+ expect(mocks.alert).toHaveBeenCalledWith(
+ expect.objectContaining({ alertType: "error" }),
+ );
+ });
+
+ it("saves shared signatures and initials without using personal capacity", async () => {
+ mocks.ownCount = 20;
+ const { result } = renderHook(useSignatureLibrary);
+ expect(
+ await result.current.save(created, { ...choice, scope: "shared" }),
+ ).not.toBeNull();
+ expect(mocks.addSignature).toHaveBeenCalledTimes(2);
+ expect(
+ mocks.addSignature.mock.calls.every((call) => call[2] === "shared"),
+ ).toBe(true);
+ });
+
+ it("does not save initials when saving the main signature fails", async () => {
+ mocks.addSignature.mockResolvedValueOnce({
+ success: false,
+ reason: "invalid",
+ });
+ const { result } = renderHook(useSignatureLibrary);
+ expect(await result.current.save(created, choice)).toBeNull();
+ expect(mocks.addSignature).toHaveBeenCalledTimes(1);
+ expect(mocks.setDefaultId).not.toHaveBeenCalled();
+ });
+
+ it("rolls back the main signature when saving initials fails", async () => {
+ mocks.addSignature
+ .mockResolvedValueOnce({ success: true, signature })
+ .mockResolvedValueOnce({ success: false, reason: "invalid" });
+ const { result } = renderHook(useSignatureLibrary);
+ expect(await result.current.save(created, choice)).toBeNull();
+ expect(mocks.removeSignature).toHaveBeenCalledWith("saved");
+ expect(mocks.setDefaultId).not.toHaveBeenCalled();
+ expect(mocks.alert).not.toHaveBeenCalledWith(
+ expect.objectContaining({ alertType: "success" }),
+ );
+ });
+
+ it("keeps an actually saved signature visible when rollback fails", async () => {
+ mocks.addSignature
+ .mockResolvedValueOnce({ success: true, signature })
+ .mockResolvedValueOnce({ success: false, reason: "invalid" });
+ mocks.removeSignature.mockResolvedValue(false);
+ const { result } = renderHook(useSignatureLibrary);
+ expect((await result.current.save(created, choice))?.key).toBe("saved");
+ expect(mocks.alert).toHaveBeenCalledWith(
+ expect.objectContaining({ alertType: "error" }),
+ );
+ });
+
+ it("preserves the default when deletion fails", async () => {
+ mocks.removeSignature.mockResolvedValue(false);
+ const { result } = renderHook(useSignatureLibrary);
+ expect(await result.current.remove(signature)).toBe(false);
+ expect(mocks.setDefaultId).not.toHaveBeenCalled();
+ });
+
+ it("reports a failed rename", async () => {
+ mocks.updateSignatureLabel.mockResolvedValue(false);
+ const { result } = renderHook(useSignatureLibrary);
+ expect(await result.current.rename(signature, "Renamed")).toBe(false);
+ expect(mocks.alert).toHaveBeenCalledWith(
+ expect.objectContaining({ alertType: "error" }),
+ );
+ });
+
+ it("keeps a draft available after a failed save", async () => {
+ mocks.addSignature.mockResolvedValue({ success: false, reason: "invalid" });
+ const { result } = renderHook(useSignatureLibrary);
+ act(() => result.current.keepUnsaved(created, "Draft"));
+ await act(async () => {
+ await result.current.saveDraft();
+ });
+ expect(result.current.draft?.label).toBe("Draft");
+ });
+});
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/useSignatureLibrary.ts b/frontend/editor/src/core/components/tools/sign/wallet/useSignatureLibrary.ts
new file mode 100644
index 0000000000..f2a579fab4
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/useSignatureLibrary.ts
@@ -0,0 +1,270 @@
+import { useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { alert } from "@app/components/toast";
+import { useSavedSignatures } from "@app/hooks/tools/sign/useSavedSignatures";
+import { useDefaultSignature } from "@app/hooks/tools/sign/useDefaultSignature";
+import { uniqueName } from "@app/utils/uniqueName";
+import type { SavedSignature } from "@app/types/signature";
+import type {
+ CreatedSignature,
+ SaveChoice,
+} from "@app/components/tools/sign/createSignature/types";
+import {
+ DRAFT_KEY,
+ createdToPayload,
+ savedToPayload,
+ toWalletEntry,
+ type WalletEntry,
+} from "@app/components/tools/sign/wallet/walletEntry";
+
+function ownFirstDefault(
+ signatures: SavedSignature[],
+ defaultId: string | null,
+) {
+ const own = signatures.filter((sig) => sig.scope !== "shared");
+ return [...own].sort(
+ (a, b) => Number(b.id === defaultId) - Number(a.id === defaultId),
+ );
+}
+
+export function useSignatureLibrary() {
+ const { t } = useTranslation();
+ const {
+ savedSignatures,
+ ownCount,
+ isLoading,
+ isAtCapacity,
+ maxLimit,
+ storageType,
+ isAdmin,
+ addSignature,
+ removeSignature,
+ updateSignatureLabel,
+ } = useSavedSignatures();
+ const { defaultId, setDefaultId } = useDefaultSignature();
+ const [draft, setDraft] = useState<WalletEntry | null>(null);
+
+ const labels = useMemo(
+ () => savedSignatures.map((sig) => sig.label),
+ [savedSignatures],
+ );
+ const mine = useMemo(
+ () => ownFirstDefault(savedSignatures, defaultId),
+ [savedSignatures, defaultId],
+ );
+ const shared = useMemo(
+ () => savedSignatures.filter((sig) => sig.scope === "shared"),
+ [savedSignatures],
+ );
+
+ async function save(
+ created: CreatedSignature,
+ choice: SaveChoice,
+ ): Promise<WalletEntry | null> {
+ const insufficientSpace =
+ created.initials && choice.scope !== "shared" && maxLimit - ownCount < 2;
+ if (insufficientSpace) {
+ alert({
+ alertType: "error",
+ title: t(
+ "sign.wallet.type.initialsLimit",
+ "Saving initials needs two free signature slots.",
+ ),
+ });
+ return null;
+ }
+ const result = await addSignature(
+ createdToPayload(created),
+ choice.label,
+ choice.scope,
+ );
+ if (!result.success) {
+ alert({
+ alertType: "error",
+ title: t(
+ "sign.wallet.toast.saveFailed",
+ "Could not save the signature",
+ ),
+ body: t(
+ "sign.wallet.toast.saveFailedBody",
+ "It is still ready to place on this document.",
+ ),
+ });
+ return null;
+ }
+ if (created.initials) {
+ const initialsResult = await addSignature(
+ { type: "text", ...created.initials },
+ uniqueName(t("sign.wallet.defaultName.initials", "Initials"), [
+ ...labels,
+ choice.label,
+ ]),
+ choice.scope,
+ );
+ if (!initialsResult.success) {
+ const rolledBack = await removeSignature(result.signature.id);
+ alert({
+ alertType: "error",
+ title: t(
+ "sign.wallet.toast.initialsFailed",
+ "Could not save your initials",
+ ),
+ body: rolledBack
+ ? t(
+ "sign.wallet.toast.saveFailedBody",
+ "It is still ready to place on this document.",
+ )
+ : t(
+ "sign.wallet.toast.initialsPartial",
+ "Your signature was saved, but your initials were not. Try saving your initials separately.",
+ ),
+ });
+ return rolledBack ? null : toWalletEntry(result.signature);
+ }
+ }
+ if (choice.makeDefault) setDefaultId(result.signature.id);
+ alert({
+ alertType: "success",
+ title: t("sign.wallet.toast.saved", "Saved to your signatures"),
+ });
+ return toWalletEntry(result.signature);
+ }
+
+ function keepUnsaved(created: CreatedSignature, label: string): WalletEntry {
+ const entry = {
+ key: DRAFT_KEY,
+ label,
+ dataUrl: created.dataUrl,
+ type: created.type,
+ created,
+ };
+ setDraft(entry);
+ return entry;
+ }
+
+ async function saveDraft(): Promise<WalletEntry | null> {
+ if (!draft?.created) return null;
+ const entry = await save(draft.created, {
+ label: uniqueName(draft.label, labels),
+ scope: "personal",
+ makeDefault: false,
+ });
+ if (entry) setDraft(null);
+ return entry;
+ }
+
+ async function shareWithEveryone(
+ signature: SavedSignature,
+ ): Promise<WalletEntry | null> {
+ const result = await addSignature(
+ savedToPayload(signature),
+ signature.label,
+ "shared",
+ );
+ const failShare = () => {
+ alert({
+ alertType: "error",
+ title: t(
+ "sign.wallet.toast.shareFailed",
+ "Could not share the signature",
+ ),
+ });
+ return null;
+ };
+ if (!result.success) return failShare();
+ if (!(await removeSignature(signature.id))) {
+ // Roll back so the user is not left with two copies.
+ await removeSignature(result.signature.id);
+ return failShare();
+ }
+ if (defaultId === signature.id) setDefaultId(result.signature.id);
+ alert({
+ alertType: "success",
+ title: t("sign.wallet.toast.shared", "Shared with everyone"),
+ });
+ return toWalletEntry(result.signature);
+ }
+
+ async function remove(signature: SavedSignature) {
+ const removed = await removeSignature(signature.id);
+ if (removed) {
+ if (defaultId === signature.id) setDefaultId(null);
+ } else {
+ alert({
+ alertType: "error",
+ title: t(
+ "sign.wallet.toast.deleteFailed",
+ "Could not delete the signature",
+ ),
+ });
+ }
+ return removed;
+ }
+
+ async function rename(signature: SavedSignature, label: string) {
+ const next = label.trim();
+ if (next && next !== signature.label) {
+ const renamed = await updateSignatureLabel(signature.id, next);
+ if (!renamed)
+ alert({
+ alertType: "error",
+ title: t(
+ "sign.wallet.toast.renameFailed",
+ "Could not rename the signature",
+ ),
+ });
+ return renamed;
+ }
+ return true;
+ }
+
+ function toggleDefault(signature: SavedSignature) {
+ setDefaultId(defaultId === signature.id ? null : signature.id);
+ }
+
+ function labelForImage(imageSrc: string | undefined): string | null {
+ if (!imageSrc) return null;
+ if (draft?.dataUrl === imageSrc) return draft.label;
+ return (
+ savedSignatures.find((sig) => sig.dataUrl === imageSrc)?.label ?? null
+ );
+ }
+
+ function entryFor(key: string | null): WalletEntry | null {
+ if (!key) return null;
+ if (draft?.key === key) return draft;
+ const signature = savedSignatures.find((sig) => sig.id === key);
+ return signature ? toWalletEntry(signature) : null;
+ }
+
+ const defaultSignature = savedSignatures.find((sig) => sig.id === defaultId);
+
+ return {
+ isLoading,
+ isEmpty: !isLoading && savedSignatures.length === 0 && !draft,
+ mine,
+ shared,
+ draft,
+ defaultId,
+ defaultEntry: defaultSignature ? toWalletEntry(defaultSignature) : null,
+ labels,
+ count: ownCount,
+ maxLimit,
+ isFull: isAtCapacity,
+ isAdmin,
+ canShare: storageType === "backend" && isAdmin,
+ browserStorage: storageType === "localStorage",
+ save,
+ keepUnsaved,
+ saveDraft,
+ discardDraft: () => setDraft(null),
+ shareWithEveryone,
+ remove,
+ rename,
+ toggleDefault,
+ entryFor,
+ labelForImage,
+ };
+}
+
+export type SignatureLibrary = ReturnType<typeof useSignatureLibrary>;
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/useSignaturePlacement.ts b/frontend/editor/src/core/components/tools/sign/wallet/useSignaturePlacement.ts
new file mode 100644
index 0000000000..945033f3b1
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/useSignaturePlacement.ts
@@ -0,0 +1,155 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useSignature } from "@app/contexts/SignatureContext";
+import { useViewer } from "@app/contexts/ViewerContext";
+import type { SignParameters } from "@app/hooks/tools/sign/useSignParameters";
+import {
+ FILE_SWITCH_ACTIVATION_DELAY,
+ PLACEMENT_ACTIVATION_DELAY,
+} from "@app/constants/signConstants";
+import type { WalletEntry } from "@app/components/tools/sign/wallet/walletEntry";
+
+const ARM_RETRY_DELAYS = [PLACEMENT_ACTIVATION_DELAY, 600, 1500];
+
+function useRetriedActivation(
+ onActivate: () => void,
+ isPlacementMode: boolean,
+) {
+ const placementModeRef = useRef(isPlacementMode);
+ const timers = useRef<number[]>([]);
+
+ useEffect(() => {
+ placementModeRef.current = isPlacementMode;
+ }, [isPlacementMode]);
+
+ const cancel = useCallback(() => {
+ timers.current.forEach((timer) => window.clearTimeout(timer));
+ timers.current = [];
+ }, []);
+
+ const activate = useCallback(() => {
+ cancel();
+ timers.current = ARM_RETRY_DELAYS.map((delay, attempt) =>
+ window.setTimeout(() => {
+ if (attempt === 0 || !placementModeRef.current) onActivate();
+ }, delay),
+ );
+ }, [cancel, onActivate]);
+
+ useEffect(() => cancel, [cancel]);
+
+ return useMemo(() => ({ activate, cancel }), [activate, cancel]);
+}
+
+const OVERLAY_SELECTOR = '[role="dialog"], [role="menu"]';
+
+function isOverlayOpen() {
+ return Array.from(document.querySelectorAll(OVERLAY_SELECTOR)).some(
+ (overlay) => overlay.getClientRects().length > 0,
+ );
+}
+
+function useEscapeKey(enabled: boolean, onEscape: () => void) {
+ useEffect(() => {
+ if (!enabled) return;
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== "Escape" || isOverlayOpen()) return;
+ event.preventDefault();
+ onEscape();
+ };
+ window.addEventListener("keydown", handleKeyDown, true);
+ return () => window.removeEventListener("keydown", handleKeyDown, true);
+ }, [enabled, onEscape]);
+}
+
+function useRearmOnFileSwitch(armed: boolean, onActivate: () => void) {
+ const { activeFileIndex } = useViewer();
+ const previous = useRef(activeFileIndex);
+
+ useEffect(() => {
+ if (activeFileIndex === previous.current) return;
+ previous.current = activeFileIndex;
+ if (!armed) return;
+ const timer = window.setTimeout(onActivate, FILE_SWITCH_ACTIVATION_DELAY);
+ return () => window.clearTimeout(timer);
+ }, [activeFileIndex, armed, onActivate]);
+}
+
+// The viewer can mount after a signature is armed (slow loads), so activate once it is ready.
+function useActivateWhenViewerReady(armed: boolean, onActivate: () => void) {
+ const { isSignatureApiReady, isPlacementMode } = useSignature();
+ const pending = useRef(false);
+ pending.current = armed && !isPlacementMode;
+ const activateRef = useRef(onActivate);
+ activateRef.current = onActivate;
+
+ useEffect(() => {
+ if (isSignatureApiReady && pending.current) activateRef.current();
+ }, [isSignatureApiReady]);
+}
+
+interface SignaturePlacementOptions {
+ onParameterChange: <K extends keyof SignParameters>(
+ key: K,
+ value: SignParameters[K],
+ ) => void;
+ onActivate: () => void;
+ onDeactivate: () => void;
+}
+
+export function useSignaturePlacement({
+ onParameterChange,
+ onActivate,
+ onDeactivate,
+}: SignaturePlacementOptions) {
+ const { isPlacementMode } = useSignature();
+ const [armedKey, setArmedKey] = useState<string | null>(null);
+ const activation = useRetriedActivation(onActivate, isPlacementMode);
+
+ const arm = useCallback(
+ (entry: WalletEntry) => {
+ onParameterChange(
+ "signatureType",
+ entry.type === "canvas" ? "canvas" : "image",
+ );
+ onParameterChange("signatureData", entry.dataUrl);
+ setArmedKey(entry.key);
+ activation.activate();
+ },
+ [activation, onParameterChange],
+ );
+
+ const stop = useCallback(() => {
+ activation.cancel();
+ setArmedKey(null);
+ onDeactivate();
+ onParameterChange("signatureData", undefined);
+ }, [activation, onDeactivate, onParameterChange]);
+
+ useEscapeKey(armedKey !== null, stop);
+ useRearmOnFileSwitch(armedKey !== null, onActivate);
+ useActivateWhenViewerReady(armedKey !== null, onActivate);
+
+ const placingKey = isPlacementMode ? armedKey : null;
+
+ const toggle = useCallback(
+ (entry: WalletEntry) => (placingKey === entry.key ? stop() : arm(entry)),
+ [arm, placingKey, stop],
+ );
+
+ return { placingKey, arm, stop, toggle, rekey: setArmedKey };
+}
+
+export type SignaturePlacement = ReturnType<typeof useSignaturePlacement>;
+
+export function useArmDefaultSignature(
+ ready: boolean,
+ defaultEntry: WalletEntry | null,
+ arm: (entry: WalletEntry) => void,
+) {
+ const done = useRef(false);
+ useEffect(() => {
+ if (done.current || !ready) return;
+ done.current = true;
+ if (defaultEntry) arm(defaultEntry);
+ }, [arm, defaultEntry, ready]);
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/useWalletActions.ts b/frontend/editor/src/core/components/tools/sign/wallet/useWalletActions.ts
new file mode 100644
index 0000000000..c99782b158
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/useWalletActions.ts
@@ -0,0 +1,80 @@
+import { useTranslation } from "react-i18next";
+import {
+ useSignature,
+ type PlacedSignature,
+} from "@app/contexts/SignatureContext";
+import { useViewer } from "@app/contexts/ViewerContext";
+import type { SavedSignature } from "@app/types/signature";
+import { PLACEMENT_ACTIVATION_DELAY } from "@app/constants/signConstants";
+import { uniqueName } from "@app/utils/uniqueName";
+import { defaultSignatureName } from "@app/components/tools/sign/createSignature/createTabs";
+import type {
+ CreatedSignature,
+ SaveChoice,
+} from "@app/components/tools/sign/createSignature/types";
+import type { SignatureLibrary } from "@app/components/tools/sign/wallet/useSignatureLibrary";
+import type { SignaturePlacement } from "@app/components/tools/sign/wallet/useSignaturePlacement";
+import { DRAFT_KEY } from "@app/components/tools/sign/wallet/walletEntry";
+
+export function useWalletActions(
+ library: SignatureLibrary,
+ placement: SignaturePlacement,
+) {
+ const { t } = useTranslation();
+ const { signatureApiRef } = useSignature();
+ const { scrollActions } = useViewer();
+
+ async function create(created: CreatedSignature, choice: SaveChoice | null) {
+ const saved = choice ? await library.save(created, choice) : null;
+ const label =
+ choice?.label ??
+ uniqueName(defaultSignatureName(t, created.source), library.labels);
+ placement.arm(saved ?? library.keepUnsaved(created, label));
+ }
+
+ async function saveDraft() {
+ const saved = await library.saveDraft();
+ if (saved && placement.placingKey === DRAFT_KEY) placement.rekey(saved.key);
+ }
+
+ function discardDraft() {
+ if (placement.placingKey === DRAFT_KEY) placement.stop();
+ library.discardDraft();
+ }
+
+ async function share(signature: SavedSignature) {
+ const shared = await library.shareWithEveryone(signature);
+ if (shared && placement.placingKey === signature.id)
+ placement.rekey(shared.key);
+ }
+
+ async function remove(signature: SavedSignature) {
+ const removed = await library.remove(signature);
+ if (removed && placement.placingKey === signature.id) placement.stop();
+ return removed;
+ }
+
+ function showPlaced(entry: PlacedSignature) {
+ placement.stop();
+ scrollActions.scrollToPage(entry.pageIndex + 1);
+ window.setTimeout(
+ () =>
+ signatureApiRef.current?.selectAnnotation(entry.id, entry.pageIndex),
+ PLACEMENT_ACTIVATION_DELAY,
+ );
+ }
+
+ function removePlaced(entry: PlacedSignature) {
+ signatureApiRef.current?.deleteAnnotation(entry.id, entry.pageIndex);
+ }
+
+ return {
+ create,
+ saveDraft,
+ discardDraft,
+ share,
+ remove,
+ showPlaced,
+ removePlaced,
+ };
+}
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/walletEntry.ts b/frontend/editor/src/core/components/tools/sign/wallet/walletEntry.ts
new file mode 100644
index 0000000000..dc40ba0d1d
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/sign/wallet/walletEntry.ts
@@ -0,0 +1,54 @@
+import type {
+ SavedSignature,
+ SavedSignaturePayload,
+ SavedSignatureType,
+} from "@app/types/signature";
+import type { CreatedSignature } from "@app/components/tools/sign/createSignature/types";
+
+export const DRAFT_KEY = "draft";
+
+export interface WalletEntry {
+ key: string;
+ label: string;
+ dataUrl: string;
+ type: SavedSignatureType;
+ created?: CreatedSignature;
+}
+
+export function toWalletEntry(signature: SavedSignature): WalletEntry {
+ return {
+ key: signature.id,
+ label: signature.label,
+ dataUrl: signature.dataUrl,
+ type: signature.type,
+ };
+}
+
+export function createdToPayload(
+ created: CreatedSignature,
+): SavedSignaturePayload {
+ if (created.type === "text" && created.text) {
+ return { type: "text", dataUrl: created.dataUrl, ...created.text };
+ }
+ return {
+ type: created.type === "canvas" ? "canvas" : "image",
+ dataUrl: created.dataUrl,
+ };
+}
+
+export function savedToPayload(
+ signature: SavedSignature,
+): SavedSignaturePayload {
+ if (signature.type !== "text") {
+ return { type: signature.type, dataUrl: signature.dataUrl };
+ }
+ const { signerName, fontFamily, fontSize, textColor } = signature;
+ return {
+ type: "text",
+ dataUrl: signature.dataUrl,
+ signerName,
+ fontFamily,
+ fontSize,
+ textColor,
+ };
+}
diff --git a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
index a5c3131d2e..79bc57b7f7 100644
--- a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
+++ b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
@@ -144,6 +144,7 @@ const EmbedPdfViewerContent = ({
getScrollState,
getSpreadState,
getZoomState,
+ registerImmediateZoomUpdate,
getRotationState,
zoomRestorePendingRef,
notifyZoomRestoreSettled,
@@ -182,6 +183,8 @@ const EmbedPdfViewerContent = ({
historyApiRef,
signatureConfig,
isPlacementMode,
+ isApplyingSignatures,
+ signaturesApplied,
} = useSignature();
// Track whether there are unsaved annotation changes in this viewer session.
@@ -595,6 +598,21 @@ const EmbedPdfViewerContent = ({
isInAnnotationTool && isPlacementMode && signatureConfig,
);
+ const [signatureLineZoom, setSignatureLineZoom] = useState<number | null>(
+ null,
+ );
+ useEffect(() => {
+ if (selectedTool !== "sign") {
+ setSignatureLineZoom(null);
+ return;
+ }
+ setSignatureLineZoom(getZoomState()?.currentZoom ?? 1);
+ const unregister = registerImmediateZoomUpdate((percent) => {
+ setSignatureLineZoom(Math.max(percent / 100, 0.01));
+ });
+ return () => unregister?.();
+ }, [selectedTool, getZoomState, registerImmediateZoomUpdate]);
+
// Determine which file to display — use activeFileId (stable) not activeFileIndex (shifts on removal)
const currentFile = React.useMemo(() => {
if (previewFile) {
@@ -712,6 +730,7 @@ const EmbedPdfViewerContent = ({
// Handle keyboard shortcuts
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
+ if (isApplyingSignatures) return;
const mod = event.ctrlKey || event.metaKey;
// Ctrl+P (print) must be intercepted unconditionally
@@ -860,6 +879,7 @@ const EmbedPdfViewerContent = ({
viewerApplyChanges,
cyclePdfRenderMode,
viewerKeyCommand,
+ isApplyingSignatures,
selectionActions,
getScrollState,
]);
@@ -891,6 +911,17 @@ const EmbedPdfViewerContent = ({
setRedactionsApplied,
]);
+ const previousSignaturesAppliedRef = useRef(signaturesApplied);
+ useEffect(() => {
+ const wasApplied = previousSignaturesAppliedRef.current;
+ previousSignaturesAppliedRef.current = signaturesApplied;
+ if (wasApplied || !signaturesApplied) return;
+ // Signature Apply saves through FileContext rather than the viewer save callback.
+ savedHistoryRevisionRef.current = historyRevisionRef.current;
+ hasAnnotationChangesRef.current = false;
+ setHasUnsavedChanges(false);
+ }, [signaturesApplied, setHasUnsavedChanges]);
+
// Watch the annotation history API to detect when the document becomes "dirty".
// We treat any change that makes the history undoable as unsaved changes until
// the user explicitly applies them via applyChanges.
@@ -1726,6 +1757,7 @@ const EmbedPdfViewerContent = ({
flexDirection: "column",
overflow: "hidden",
contain: "layout style paint",
+ pointerEvents: isApplyingSignatures ? "none" : undefined,
}}
>
{/* Close Button - Only show in preview mode */}
@@ -1851,6 +1883,7 @@ const EmbedPdfViewerContent = ({
containerRef={pdfContainerRef}
isActive={isPlacementOverlayActive}
signatureConfig={signatureConfig}
+ signatureLineZoom={signatureLineZoom}
/>
<RulerOverlay
ref={rulerOverlayRef}
diff --git a/frontend/editor/src/core/components/viewer/SignatureAPIBridge.tsx b/frontend/editor/src/core/components/viewer/SignatureAPIBridge.tsx
index aee7fd8a52..b05031e17f 100644
--- a/frontend/editor/src/core/components/viewer/SignatureAPIBridge.tsx
+++ b/frontend/editor/src/core/components/viewer/SignatureAPIBridge.tsx
@@ -20,6 +20,7 @@ import type {
import type { SignParameters } from "@app/hooks/tools/sign/useSignParameters";
import { useViewer } from "@app/contexts/ViewerContext";
import { useDocumentReady } from "@app/components/viewer/hooks/useDocumentReady";
+import { usePlacedSignatureTracking } from "@app/components/viewer/hooks/usePlacedSignatureTracking";
// The signature tools stash the source image on stamp annotations via custom fields
type StampAnnotation = PdfAnnotationObject & {
@@ -201,6 +202,8 @@ export const SignatureAPIBridge = forwardRef<
isPlacementMode,
placementPreviewSize,
setSignaturesApplied,
+ setSignatureApiReady,
+ isApplyingSignatures,
} = useSignature();
const { getZoomState, registerImmediateZoomUpdate } = useViewer();
const documentReady = useDocumentReady();
@@ -219,6 +222,13 @@ export const SignatureAPIBridge = forwardRef<
};
}, [getZoomState, registerImmediateZoomUpdate]);
+ // Runs after the imperative handle is attached, so callers can use it straight away.
+ const apiReady = Boolean(annotationApi && documentReady);
+ useEffect(() => {
+ setSignatureApiReady(apiReady);
+ return () => setSignatureApiReady(false);
+ }, [apiReady, setSignatureApiReady]);
+
// When entering sign mode, deactivate any active annotation tool immediately.
// Only signature-specific tools (signatureInk, stamp) should be usable.
useEffect(() => {
@@ -323,6 +333,7 @@ export const SignatureAPIBridge = forwardRef<
return;
const handleKeyDown = (event: KeyboardEvent) => {
+ if (isApplyingSignatures) return;
// Skip delete/backspace while a text input/textarea is focused (e.g., editing textbox)
const target = event.target as HTMLElement | null;
const tag = target?.tagName?.toLowerCase();
@@ -382,7 +393,7 @@ export const SignatureAPIBridge = forwardRef<
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
- }, [annotationApi, storeImageData, isPlacementMode]);
+ }, [annotationApi, storeImageData, isPlacementMode, isApplyingSignatures]);
useImperativeHandle(
ref,
@@ -513,6 +524,10 @@ export const SignatureAPIBridge = forwardRef<
annotationApi.deleteAnnotation(pageIndex, annotationId);
},
+ selectAnnotation: (annotationId: string, pageIndex: number) => {
+ annotationApi?.selectAnnotation(pageIndex, annotationId);
+ },
+
deactivateTools: () => {
if (!annotationApi) return;
annotationApi.setActiveTool(null);
@@ -562,7 +577,13 @@ export const SignatureAPIBridge = forwardRef<
rectMove.moveAnnotation?.(pageIndex, annotationId, newRect);
},
}),
- [annotationApi, signatureConfig, placementPreviewSize, applyStampDefaults],
+ [
+ annotationApi,
+ signatureConfig,
+ placementPreviewSize,
+ applyStampDefaults,
+ configureStampDefaults,
+ ],
);
useEffect(() => {
@@ -607,6 +628,8 @@ export const SignatureAPIBridge = forwardRef<
};
}, [annotationApi, storeImageData, setSignaturesApplied, documentReady]);
+ usePlacedSignatureTracking();
+
useEffect(() => {
if (!isPlacementMode || !documentReady) {
return;
diff --git a/frontend/editor/src/core/components/viewer/StampPlacementOverlay.tsx b/frontend/editor/src/core/components/viewer/StampPlacementOverlay.tsx
index e1c85986c3..abaab701e0 100644
--- a/frontend/editor/src/core/components/viewer/StampPlacementOverlay.tsx
+++ b/frontend/editor/src/core/components/viewer/StampPlacementOverlay.tsx
@@ -6,6 +6,7 @@ import {
SignaturePreview,
} from "@app/utils/signaturePreview";
import { useSignature } from "@app/contexts/SignatureContext";
+import { fitPlacedSignatureSize } from "@app/utils/signatureImage";
import {
MAX_PREVIEW_WIDTH_RATIO,
MAX_PREVIEW_HEIGHT_RATIO,
@@ -23,12 +24,14 @@ interface StampPlacementOverlayProps {
containerRef: React.RefObject<HTMLElement | null>;
isActive: boolean;
signatureConfig: SignParameters | null;
+ signatureLineZoom?: number | null;
}
export const StampPlacementOverlay: React.FC<StampPlacementOverlayProps> = ({
containerRef,
isActive,
signatureConfig,
+ signatureLineZoom = null,
}) => {
const [preview, setPreview] = useState<SignaturePreview | null>(null);
const [cursor, setCursor] = useState<{ x: number; y: number } | null>(null);
@@ -89,6 +92,14 @@ export const StampPlacementOverlay: React.FC<StampPlacementOverlayProps> = ({
return null;
}
+ if (signatureLineZoom) {
+ const pdfSize = fitPlacedSignatureSize(preview.width, preview.height);
+ return {
+ width: pdfSize.width * signatureLineZoom,
+ height: pdfSize.height * signatureLineZoom,
+ };
+ }
+
const container = containerRef.current;
const containerWidth = container.clientWidth || 1;
const containerHeight = container.clientHeight || 1;
@@ -118,7 +129,7 @@ export const StampPlacementOverlay: React.FC<StampPlacementOverlayProps> = ({
preview.height * scale,
),
};
- }, [preview, containerRef]);
+ }, [preview, containerRef, signatureLineZoom]);
useEffect(() => {
if (!isActive || !scaledSize) {
diff --git a/frontend/editor/src/core/components/viewer/hooks/usePlacedSignatureTracking.test.ts b/frontend/editor/src/core/components/viewer/hooks/usePlacedSignatureTracking.test.ts
new file mode 100644
index 0000000000..07afea3a4e
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/hooks/usePlacedSignatureTracking.test.ts
@@ -0,0 +1,168 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { act, renderHook } from "@testing-library/react";
+import type { AnnotationEvent } from "@embedpdf/plugin-annotation";
+import {
+ PdfAnnotationSubtype,
+ type PdfAnnotationObject,
+} from "@embedpdf/models";
+import {
+ nextPlacedSignatures,
+ usePlacedSignatureTracking,
+} from "@app/components/viewer/hooks/usePlacedSignatureTracking";
+
+const tracking = vi.hoisted(() => ({
+ api: { forDocument: vi.fn() },
+ documentId: "doc",
+ ready: true,
+ setPlaced: vi.fn(),
+ imageFor: vi.fn((id: string) => `data:image/png;base64,${id}`),
+}));
+vi.mock("@embedpdf/plugin-annotation/react", () => ({
+ useAnnotationCapability: () => ({ provides: tracking.api }),
+}));
+vi.mock("@app/contexts/SignatureContext", () => ({
+ useSignature: () => ({
+ setPlacedSignatures: tracking.setPlaced,
+ getImageData: tracking.imageFor,
+ }),
+}));
+vi.mock("@app/components/viewer/hooks/useDocumentReady", () => ({
+ useDocumentReady: () => tracking.ready,
+}));
+vi.mock("@app/components/viewer/useActiveDocumentId", () => ({
+ useActiveDocumentId: () => tracking.documentId,
+}));
+
+const stamp = (id: string, subject = "Digital Signature - Document signing") =>
+ ({
+ id,
+ type: PdfAnnotationSubtype.STAMP,
+ subject,
+ pageIndex: 0,
+ }) as PdfAnnotationObject;
+
+const event = (
+ type: "create" | "delete",
+ annotation: PdfAnnotationObject,
+ pageIndex = 0,
+): AnnotationEvent => ({
+ type,
+ documentId: "doc",
+ annotation,
+ pageIndex,
+ committed: true,
+});
+
+describe("usePlacedSignatureTracking", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ tracking.documentId = "doc";
+ tracking.ready = true;
+ });
+
+ it("enumerates existing stamps even if loading finished before subscription", () => {
+ let notify: ((event: AnnotationEvent) => void) | undefined;
+ const applied = stamp("applied");
+ applied.flags = ["print", "readOnly", "locked"];
+ const getAnnotations = vi.fn(() => [
+ { commitState: "synced", object: stamp("saved") },
+ { commitState: "synced", object: applied },
+ { commitState: "deleted", object: stamp("deleted") },
+ { commitState: "synced", object: stamp("other", "Approved") },
+ ]);
+ tracking.api.forDocument.mockReturnValue({
+ getAnnotations,
+ onAnnotationEvent: vi.fn((listener: (event: AnnotationEvent) => void) => {
+ notify = listener;
+ return vi.fn();
+ }),
+ });
+ renderHook(() => usePlacedSignatureTracking());
+ expect(tracking.setPlaced).toHaveBeenLastCalledWith([
+ { id: "saved", pageIndex: 0, imageSrc: imageFor("saved") },
+ ]);
+ getAnnotations.mockReturnValue([
+ { commitState: "synced", object: stamp("restored") },
+ ]);
+ act(() => notify?.({ type: "loaded", documentId: "doc", total: 1 }));
+ expect(tracking.setPlaced).toHaveBeenLastCalledWith([
+ { id: "restored", pageIndex: 0, imageSrc: imageFor("restored") },
+ ]);
+ });
+
+ it("clears the old document's list and unsubscribes when it stops being ready", () => {
+ const unsubscribe = vi.fn();
+ tracking.api.forDocument.mockReturnValue({
+ getAnnotations: () => [{ commitState: "synced", object: stamp("saved") }],
+ onAnnotationEvent: () => unsubscribe,
+ });
+ const { rerender } = renderHook(() => usePlacedSignatureTracking());
+ tracking.ready = false;
+ rerender();
+ expect(unsubscribe).toHaveBeenCalledTimes(1);
+ expect(tracking.setPlaced).toHaveBeenLastCalledWith([]);
+ });
+});
+
+const imageFor = (id: string) => `data:image/png;base64,${id}`;
+
+describe("nextPlacedSignatures", () => {
+ it("adds a created signature stamp with its stored image", () => {
+ expect(
+ nextPlacedSignatures([], event("create", stamp("a"), 2), imageFor),
+ ).toEqual([{ id: "a", pageIndex: 2, imageSrc: imageFor("a") }]);
+ });
+
+ it("ignores stamps the sign tool did not make", () => {
+ const placed = nextPlacedSignatures(
+ [],
+ event("create", stamp("a", "Approved")),
+ imageFor,
+ );
+ expect(placed).toEqual([]);
+ });
+
+ it("does not offer applied signatures for placement or removal", () => {
+ const applied = stamp("applied");
+ applied.flags = ["print", "readOnly", "locked"];
+ expect(
+ nextPlacedSignatures([], event("create", applied), imageFor),
+ ).toEqual([]);
+ });
+
+ it("drops a deleted signature, as undo does", () => {
+ const placed = nextPlacedSignatures(
+ [],
+ event("create", stamp("a")),
+ imageFor,
+ );
+ expect(
+ nextPlacedSignatures(placed, event("delete", stamp("a")), imageFor),
+ ).toEqual([]);
+ });
+
+ it("does not list a re-created signature twice", () => {
+ const placed = nextPlacedSignatures(
+ [],
+ event("create", stamp("a")),
+ imageFor,
+ );
+ expect(
+ nextPlacedSignatures(placed, event("create", stamp("a")), imageFor),
+ ).toBe(placed);
+ });
+
+ it("clears the list when another document loads", () => {
+ const placed = nextPlacedSignatures(
+ [],
+ event("create", stamp("a")),
+ imageFor,
+ );
+ const loaded = {
+ type: "loaded",
+ documentId: "doc",
+ total: 0,
+ } as AnnotationEvent;
+ expect(nextPlacedSignatures(placed, loaded, imageFor)).toEqual([]);
+ });
+});
diff --git a/frontend/editor/src/core/components/viewer/hooks/usePlacedSignatureTracking.ts b/frontend/editor/src/core/components/viewer/hooks/usePlacedSignatureTracking.ts
new file mode 100644
index 0000000000..b07a965595
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/hooks/usePlacedSignatureTracking.ts
@@ -0,0 +1,93 @@
+import { useEffect, useRef } from "react";
+import { useAnnotationCapability } from "@embedpdf/plugin-annotation/react";
+import type { AnnotationEvent } from "@embedpdf/plugin-annotation";
+import {
+ PdfAnnotationSubtype,
+ type PdfAnnotationObject,
+} from "@embedpdf/models";
+import {
+ useSignature,
+ type PlacedSignature,
+} from "@app/contexts/SignatureContext";
+import { useDocumentReady } from "@app/components/viewer/hooks/useDocumentReady";
+import { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";
+
+const SIGNATURE_SUBJECT_PREFIXES = ["Digital Signature", "Text Signature"];
+
+function isSignatureStamp(annotation: PdfAnnotationObject): boolean {
+ return (
+ annotation.type === PdfAnnotationSubtype.STAMP &&
+ !annotation.flags?.includes("locked") &&
+ !annotation.flags?.includes("readOnly") &&
+ SIGNATURE_SUBJECT_PREFIXES.some((prefix) =>
+ (annotation.subject ?? "").startsWith(prefix),
+ )
+ );
+}
+
+export function nextPlacedSignatures(
+ placed: PlacedSignature[],
+ event: AnnotationEvent,
+ imageFor: (annotationId: string) => string | undefined,
+): PlacedSignature[] {
+ if (event.type === "loaded") return [];
+ if (event.type === "delete") {
+ return placed.filter((entry) => entry.id !== event.annotation.id);
+ }
+ if (event.type !== "create" || !isSignatureStamp(event.annotation))
+ return placed;
+ const { id } = event.annotation;
+ if (placed.some((entry) => entry.id === id)) return placed;
+ return [
+ ...placed,
+ { id, pageIndex: event.pageIndex, imageSrc: imageFor(id) },
+ ];
+}
+
+export function usePlacedSignatureTracking() {
+ const { provides: annotationApi } = useAnnotationCapability();
+ const { setPlacedSignatures, getImageData } = useSignature();
+ const documentReady = useDocumentReady();
+ const documentId = useActiveDocumentId();
+ const placedRef = useRef<PlacedSignature[]>([]);
+
+ useEffect(() => {
+ placedRef.current = [];
+ setPlacedSignatures([]);
+ if (!annotationApi || !documentReady || !documentId) return;
+ const annotations = annotationApi.forDocument(documentId);
+ const readSignatures = () => {
+ const next = annotations
+ .getAnnotations()
+ .filter(
+ (entry) =>
+ entry.commitState !== "deleted" && isSignatureStamp(entry.object),
+ )
+ .map(({ object }) => ({
+ id: object.id,
+ pageIndex: object.pageIndex,
+ imageSrc: getImageData(object.id),
+ }));
+ placedRef.current = next;
+ setPlacedSignatures(next);
+ };
+ const unsubscribe = annotations.onAnnotationEvent((event) => {
+ if (event.type === "loaded") {
+ readSignatures();
+ return;
+ }
+ const next = nextPlacedSignatures(placedRef.current, event, getImageData);
+ if (next === placedRef.current) return;
+ placedRef.current = next;
+ setPlacedSignatures(next);
+ });
+ readSignatures();
+ return unsubscribe;
+ }, [
+ annotationApi,
+ documentReady,
+ documentId,
+ getImageData,
+ setPlacedSignatures,
+ ]);
+}
diff --git a/frontend/editor/src/core/components/viewer/viewerTypes.ts b/frontend/editor/src/core/components/viewer/viewerTypes.ts
index 75c0c4cb2b..b3c1d09b33 100644
--- a/frontend/editor/src/core/components/viewer/viewerTypes.ts
+++ b/frontend/editor/src/core/components/viewer/viewerTypes.ts
@@ -46,6 +46,7 @@ export interface SignatureAPI {
updateDrawSettings: (color: string, size: number) => void;
deactivateTools: () => void;
getPageAnnotations: (pageIndex: number) => Promise<unknown[]>;
+ selectAnnotation: (annotationId: string, pageIndex: number) => void;
moveAnnotation?: (
pageIndex: number,
annotationId: string,
diff --git a/frontend/editor/src/core/contexts/SignatureContext.tsx b/frontend/editor/src/core/contexts/SignatureContext.tsx
index a53a58ee21..bbe4bbf3e7 100644
--- a/frontend/editor/src/core/contexts/SignatureContext.tsx
+++ b/frontend/editor/src/core/contexts/SignatureContext.tsx
@@ -13,6 +13,12 @@ import type {
AnnotationAPI,
} from "@app/components/viewer/viewerTypes";
+export interface PlacedSignature {
+ id: string;
+ pageIndex: number;
+ imageSrc?: string;
+}
+
// Signature state interface
interface SignatureState {
// Current signature configuration from the tool
@@ -23,6 +29,10 @@ interface SignatureState {
signaturesApplied: boolean;
// Size (in screen units) we want newly placed signatures to use
placementPreviewSize: { width: number; height: number } | null;
+ placedSignatures: PlacedSignature[];
+ // Whether the viewer's signature API is mounted on a loaded document
+ isSignatureApiReady: boolean;
+ isApplyingSignatures: boolean;
}
// Signature actions interface
@@ -42,6 +52,9 @@ interface SignatureActions {
setPlacementPreviewSize: (
size: { width: number; height: number } | null,
) => void;
+ setPlacedSignatures: (placed: PlacedSignature[]) => void;
+ setSignatureApiReady: (ready: boolean) => void;
+ setApplyingSignatures: (applying: boolean) => void;
}
// Combined context interface
@@ -62,6 +75,9 @@ const initialState: SignatureState = {
isPlacementMode: false,
signaturesApplied: true, // Start as true (no signatures placed yet)
placementPreviewSize: null,
+ placedSignatures: [],
+ isSignatureApiReady: false,
+ isApplyingSignatures: false,
};
// Provider component
@@ -174,6 +190,22 @@ export const SignatureProvider: React.FC<{ children: ReactNode }> = ({
[],
);
+ const setPlacedSignatures = useCallback((placed: PlacedSignature[]) => {
+ setState((prev) => ({ ...prev, placedSignatures: placed }));
+ }, []);
+
+ const setSignatureApiReady = useCallback((ready: boolean) => {
+ setState((prev) =>
+ prev.isSignatureApiReady === ready
+ ? prev
+ : { ...prev, isSignatureApiReady: ready },
+ );
+ }, []);
+
+ const setApplyingSignatures = useCallback((applying: boolean) => {
+ setState((prev) => ({ ...prev, isApplyingSignatures: applying }));
+ }, []);
+
// No auto-activation - all modes use manual buttons
const contextValue: SignatureContextValue = {
@@ -194,6 +226,9 @@ export const SignatureProvider: React.FC<{ children: ReactNode }> = ({
getImageData,
setSignaturesApplied,
setPlacementPreviewSize,
+ setPlacedSignatures,
+ setSignatureApiReady,
+ setApplyingSignatures,
};
return (
diff --git a/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx b/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx
index 524eba1f6b..c4a67c2569 100644
--- a/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx
+++ b/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx
@@ -478,7 +478,7 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
navigationState.selectedTool &&
navigationState.selectedTool !== toolId
) {
- actions.requestNavigation(() => handleToolSelect(toolId));
+ actions.requestNavigation(() => handleToolSelectRef.current(toolId));
return;
}
@@ -575,10 +575,12 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
);
const handleBackToTools = useCallback(() => {
- setLeftPanelView("toolPicker");
- setReaderMode(false);
- actions.setSelectedTool(null);
- }, [setLeftPanelView, setReaderMode, actions.setSelectedTool]);
+ actions.requestNavigation(() => {
+ setLeftPanelView("toolPicker");
+ setReaderMode(false);
+ actions.setSelectedTool(null);
+ });
+ }, [setLeftPanelView, setReaderMode, actions]);
const handleReaderToggle = useCallback(() => {
setReaderMode(true);
diff --git a/frontend/editor/src/core/hooks/tools/sign/useDefaultSignature.test.ts b/frontend/editor/src/core/hooks/tools/sign/useDefaultSignature.test.ts
new file mode 100644
index 0000000000..aacfeb05e9
--- /dev/null
+++ b/frontend/editor/src/core/hooks/tools/sign/useDefaultSignature.test.ts
@@ -0,0 +1,38 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { act, renderHook } from "@testing-library/react";
+import { useDefaultSignature } from "@app/hooks/tools/sign/useDefaultSignature";
+
+const KEY = "stirling:sign:default-signature-id";
+
+afterEach(() => {
+ localStorage.clear();
+ vi.restoreAllMocks();
+});
+
+describe("useDefaultSignature", () => {
+ it("reads the stored default on mount", () => {
+ localStorage.setItem(KEY, "sig-1");
+ const { result } = renderHook(() => useDefaultSignature());
+ expect(result.current.defaultId).toBe("sig-1");
+ });
+
+ it("persists a new default and clears it", () => {
+ const { result } = renderHook(() => useDefaultSignature());
+ act(() => result.current.setDefaultId("sig-2"));
+ expect(result.current.defaultId).toBe("sig-2");
+ expect(localStorage.getItem(KEY)).toBe("sig-2");
+
+ act(() => result.current.setDefaultId(null));
+ expect(result.current.defaultId).toBeNull();
+ expect(localStorage.getItem(KEY)).toBeNull();
+ });
+
+ it("keeps the choice for the session when storage is blocked", () => {
+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
+ throw new Error("blocked");
+ });
+ const { result } = renderHook(() => useDefaultSignature());
+ act(() => result.current.setDefaultId("sig-3"));
+ expect(result.current.defaultId).toBe("sig-3");
+ });
+});
diff --git a/frontend/editor/src/core/hooks/tools/sign/useDefaultSignature.ts b/frontend/editor/src/core/hooks/tools/sign/useDefaultSignature.ts
new file mode 100644
index 0000000000..ba4f9f9c8e
--- /dev/null
+++ b/frontend/editor/src/core/hooks/tools/sign/useDefaultSignature.ts
@@ -0,0 +1,35 @@
+import { useCallback, useState } from "react";
+
+const STORAGE_KEY = "stirling:sign:default-signature-id";
+
+function read(): string | null {
+ try {
+ return window.localStorage.getItem(STORAGE_KEY);
+ } catch {
+ return null;
+ }
+}
+
+function write(id: string | null): boolean {
+ try {
+ if (id) {
+ window.localStorage.setItem(STORAGE_KEY, id);
+ } else {
+ window.localStorage.removeItem(STORAGE_KEY);
+ }
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function useDefaultSignature() {
+ const [defaultId, setDefaultIdState] = useState<string | null>(read);
+
+ const setDefaultId = useCallback((id: string | null) => {
+ setDefaultIdState(id);
+ write(id);
+ }, []);
+
+ return { defaultId, setDefaultId };
+}
diff --git a/frontend/editor/src/core/hooks/tools/sign/useSavedSignatures.ts b/frontend/editor/src/core/hooks/tools/sign/useSavedSignatures.ts
index 4359181965..7b38dac8ae 100644
--- a/frontend/editor/src/core/hooks/tools/sign/useSavedSignatures.ts
+++ b/frontend/editor/src/core/hooks/tools/sign/useSavedSignatures.ts
@@ -91,7 +91,10 @@ export const useSavedSignatures = () => {
storageType === "backend"
? MAX_SAVED_SIGNATURES_BACKEND
: MAX_SAVED_SIGNATURES_LOCALSTORAGE;
- const isAtCapacity = savedSignatures.length >= maxLimit;
+ const ownCount = savedSignatures.filter(
+ (entry) => entry.scope !== "shared",
+ ).length;
+ const isAtCapacity = ownCount >= maxLimit;
const addSignature = useCallback(
async (
@@ -107,7 +110,7 @@ export const useSavedSignatures = () => {
return { success: false, reason: "invalid" };
}
- if (isAtCapacity) {
+ if (isAtCapacity && scope !== "shared") {
return { success: false, reason: "limit" };
}
@@ -133,15 +136,17 @@ export const useSavedSignatures = () => {
return { success: false, reason: "invalid" };
}
},
- [savedSignatures.length, storageType],
+ [isAtCapacity, storageType],
);
- const removeSignature = useCallback(async (id: string) => {
+ const removeSignature = useCallback(async (id: string): Promise<boolean> => {
try {
await signatureStorageService.deleteSignature(id);
setSavedSignatures((prev) => prev.filter((entry) => entry.id !== id));
+ return true;
} catch (error) {
console.error("[useSavedSignatures] Failed to delete signature:", error);
+ return false;
}
}, []);
@@ -170,11 +175,13 @@ export const useSavedSignatures = () => {
),
);
}
+ return true;
} catch (error) {
console.error(
"[useSavedSignatures] Failed to update signature label:",
error,
);
+ return false;
}
},
[storageType],
@@ -231,6 +238,7 @@ export const useSavedSignatures = () => {
return {
savedSignatures,
+ ownCount,
isAtCapacity,
maxLimit,
addSignature,
diff --git a/frontend/editor/src/core/hooks/useHistoryAvailability.test.tsx b/frontend/editor/src/core/hooks/useHistoryAvailability.test.tsx
new file mode 100644
index 0000000000..e8067bdae1
--- /dev/null
+++ b/frontend/editor/src/core/hooks/useHistoryAvailability.test.tsx
@@ -0,0 +1,74 @@
+import { useLayoutEffect, type PropsWithChildren, type RefObject } from "react";
+import { act, renderHook } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import type { HistoryAPI } from "@app/components/viewer/viewerTypes";
+import { useHistoryAvailability } from "@app/hooks/useHistoryAvailability";
+
+describe("useHistoryAvailability", () => {
+ it("subscribes to a bridge installed during commit and follows its updates", () => {
+ const historyApiRef: RefObject<HistoryAPI | null> = { current: null };
+ const unsubscribe = vi.fn();
+ let listener = () => {};
+ const api: HistoryAPI = {
+ undo: vi.fn(),
+ redo: vi.fn(),
+ canUndo: vi.fn(() => true),
+ canRedo: vi.fn(() => false),
+ subscribe: vi.fn((next) => {
+ listener = next;
+ return unsubscribe;
+ }),
+ };
+ function Bridge({ children }: PropsWithChildren) {
+ useLayoutEffect(() => {
+ historyApiRef.current = api;
+ }, []);
+ return children;
+ }
+ const { result, rerender, unmount } = renderHook(
+ () => useHistoryAvailability(historyApiRef),
+ { wrapper: Bridge },
+ );
+ expect(result.current).toEqual({ canUndo: true, canRedo: false });
+ rerender();
+ expect(api.subscribe).toHaveBeenCalledTimes(1);
+ vi.mocked(api.canUndo).mockReturnValue(false);
+ vi.mocked(api.canRedo).mockReturnValue(true);
+ act(() => listener());
+ expect(result.current).toEqual({ canUndo: false, canRedo: true });
+ unmount();
+ expect(unsubscribe).toHaveBeenCalledTimes(1);
+ });
+
+ it("replaces a subscription when a later commit replaces the bridge", () => {
+ const unsubscribe = vi.fn();
+ const first: HistoryAPI = {
+ undo: vi.fn(),
+ redo: vi.fn(),
+ canUndo: () => true,
+ canRedo: () => false,
+ subscribe: vi.fn(() => unsubscribe),
+ };
+ const second: HistoryAPI = {
+ undo: vi.fn(),
+ redo: vi.fn(),
+ canUndo: () => false,
+ canRedo: () => true,
+ subscribe: vi.fn(() => vi.fn()),
+ };
+ const historyApiRef: RefObject<HistoryAPI | null> = { current: first };
+ const { result, rerender } = renderHook(
+ ({ api }) => {
+ useLayoutEffect(() => {
+ historyApiRef.current = api;
+ }, [api]);
+ return useHistoryAvailability(historyApiRef);
+ },
+ { initialProps: { api: first } },
+ );
+ rerender({ api: second });
+ expect(unsubscribe).toHaveBeenCalledTimes(1);
+ expect(second.subscribe).toHaveBeenCalledTimes(1);
+ expect(result.current).toEqual({ canUndo: false, canRedo: true });
+ });
+});
diff --git a/frontend/editor/src/core/hooks/useHistoryAvailability.ts b/frontend/editor/src/core/hooks/useHistoryAvailability.ts
new file mode 100644
index 0000000000..fe9a2ff23e
--- /dev/null
+++ b/frontend/editor/src/core/hooks/useHistoryAvailability.ts
@@ -0,0 +1,47 @@
+import { useEffect, useRef, useState, type RefObject } from "react";
+import type { HistoryAPI } from "@app/components/viewer/viewerTypes";
+
+export interface HistoryAvailability {
+ canUndo: boolean;
+ canRedo: boolean;
+}
+
+const NOTHING_TO_STEP: HistoryAvailability = { canUndo: false, canRedo: false };
+
+export function useHistoryAvailability(
+ historyApiRef: RefObject<HistoryAPI | null>,
+): HistoryAvailability {
+ const [availability, setAvailability] = useState(NOTHING_TO_STEP);
+ const subscription = useRef<{
+ api: HistoryAPI | null;
+ unsubscribe?: () => void;
+ }>({ api: null });
+
+ useEffect(() => {
+ const historyApi = historyApiRef.current;
+ if (subscription.current.api === historyApi) return;
+ subscription.current.unsubscribe?.();
+ subscription.current = { api: historyApi };
+ if (!historyApi) {
+ setAvailability(NOTHING_TO_STEP);
+ return;
+ }
+ const update = () =>
+ setAvailability({
+ canUndo: historyApi.canUndo?.() ?? false,
+ canRedo: historyApi.canRedo?.() ?? false,
+ });
+ subscription.current.unsubscribe = historyApi.subscribe?.(update);
+ update();
+ });
+
+ useEffect(
+ () => () => {
+ subscription.current.unsubscribe?.();
+ subscription.current = { api: null };
+ },
+ [],
+ );
+
+ return availability;
+}
diff --git a/frontend/editor/src/core/hooks/useMobileTransferSession.ts b/frontend/editor/src/core/hooks/useMobileTransferSession.ts
index bee78e717b..f9bc6037f5 100644
--- a/frontend/editor/src/core/hooks/useMobileTransferSession.ts
+++ b/frontend/editor/src/core/hooks/useMobileTransferSession.ts
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { BASE_PATH } from "@app/constants/app";
+import { useAppConfig } from "@app/contexts/AppConfigContext";
import { buildMobileRouteUrl } from "@app/utils/mobileScannerUrl";
import apiClient from "@app/services/apiClient";
@@ -66,8 +67,6 @@ interface UseMobileTransferSessionParams {
sessionCreateErrorMessage: string;
/** Message shown when polling for uploads fails. */
pollingErrorMessage: string;
- /** Host the phone should reach, when configured (server_url / frontendUrl). */
- configuredUrl?: string;
}
export function useMobileTransferSession({
@@ -76,8 +75,8 @@ export function useMobileTransferSession({
onFileReceived,
sessionCreateErrorMessage,
pollingErrorMessage,
- configuredUrl,
}: UseMobileTransferSessionParams) {
+ const { config } = useAppConfig();
const [sessionId, setSessionId] = useState(() => generateSessionId());
const [sessionInfo, setSessionInfo] =
useState<MobileTransferSessionInfo | null>(null);
@@ -92,8 +91,11 @@ export function useMobileTransferSession({
// The QR-code URL the phone opens. It must land on the public route under
// the app's base path, otherwise the phone hits the auth-gated catch-all
// route and is bounced to the login page.
+ const configuredUrl =
+ localStorage.getItem("server_url") ||
+ (import.meta.env.DEV ? "" : config?.frontendUrl || "");
const mobileUrl = buildMobileRouteUrl({
- configuredUrl: configuredUrl ?? "",
+ configuredUrl,
sessionId,
origin: window.location.origin,
basePath: BASE_PATH,
diff --git a/frontend/editor/src/core/i18n/translationAudit.ts b/frontend/editor/src/core/i18n/translationAudit.ts
index ba0bff86f8..bf0d0415d9 100644
--- a/frontend/editor/src/core/i18n/translationAudit.ts
+++ b/frontend/editor/src/core/i18n/translationAudit.ts
@@ -31,6 +31,8 @@ export interface TranslationProject {
srcRoot: string;
/** Absolute path to the en-US source locale. */
localeFile: string;
+ /** Other English locales that can receive new source strings. */
+ additionalLocaleFiles?: string[];
/** Static keys flagged as missing that are genuinely fine (false positives). */
ignoredKeys?: Set<string>;
/** Locale keys assembled at runtime; exempt from the unused check. */
@@ -75,6 +77,9 @@ export const I18N_PROJECTS: TranslationProject[] = [
// like any other key.
srcRoot: front("editor/src"),
localeFile: front("editor/public/locales/en-US/translation.toml"),
+ additionalLocaleFiles: [
+ front("editor/public/locales/en-GB/translation.toml"),
+ ],
ignoredKeyPatterns: [
// SignSettings / SavedSignaturesSection resolve every key as
// t(`${scope}.${key}`); scope and leaf only ever exist as separate literals.
@@ -394,6 +399,9 @@ export function findMissingKeys(project: TranslationProject): {
usedCount: number;
} {
const localeKeys = collectLocaleKeys(project.localeFile);
+ for (const localeFile of project.additionalLocaleFiles ?? []) {
+ for (const key of collectLocaleKeys(localeFile)) localeKeys.add(key);
+ }
const ignored = project.ignoredKeys ?? new Set<string>();
// A used key resolves if the locale has it exactly, a plural variant covers
diff --git a/frontend/editor/src/core/icons/icons.ts b/frontend/editor/src/core/icons/icons.ts
index 1c2f354d2f..0ba8c69d89 100644
--- a/frontend/editor/src/core/icons/icons.ts
+++ b/frontend/editor/src/core/icons/icons.ts
@@ -104,6 +104,7 @@ import DraftingCompass from "lucide-static/icons/drafting-compass.svg?react";
import Droplet from "lucide-static/icons/droplet.svg?react";
import Ellipsis from "lucide-static/icons/ellipsis.svg?react";
import EllipsisVertical from "lucide-static/icons/ellipsis-vertical.svg?react";
+import Eraser from "lucide-static/icons/eraser.svg?react";
import ExternalLink from "lucide-static/icons/external-link.svg?react";
import Eye from "lucide-static/icons/eye.svg?react";
import EyeOff from "lucide-static/icons/eye-off.svg?react";
@@ -529,6 +530,7 @@ export const ICONS = {
droplet: { Component: Droplet, kind: "lucide" },
ellipsis: { Component: Ellipsis, kind: "lucide" },
"ellipsis-vertical": { Component: EllipsisVertical, kind: "lucide" },
+ eraser: { Component: Eraser, kind: "lucide" },
"external-link": { Component: ExternalLink, kind: "lucide" },
eye: { Component: Eye, kind: "lucide" },
"eye-off": { Component: EyeOff, kind: "lucide" },
diff --git a/frontend/editor/src/core/tests/missingTranslations.test.ts b/frontend/editor/src/core/tests/missingTranslations.test.ts
index 64b6392dc1..1da7ed685f 100644
--- a/frontend/editor/src/core/tests/missingTranslations.test.ts
+++ b/frontend/editor/src/core/tests/missingTranslations.test.ts
@@ -13,7 +13,7 @@ describe.each(I18N_PROJECTS)(
"Missing translation coverage — $name",
(project) => {
test(
- "fails if any en-US key used in source is missing from the locale",
+ "fails if any key used in source is missing from the English locales",
// Scans/parses the whole source tree: generous headroom for a loaded CPU.
{ timeout: 60_000 },
() => {
@@ -35,7 +35,7 @@ describe.each(I18N_PROJECTS)(
// GitHub Annotations format so misses show up tagged on the code in CI.
for (const { key, fallback, file, line, column } of annotations) {
process.stderr.write(
- `::error file=${file},line=${line},col=${column}::Missing en-US translation for ${key} (${fallback})\n`,
+ `::error file=${file},line=${line},col=${column}::Missing English translation for ${key} (${fallback})\n`,
);
}
diff --git a/frontend/editor/src/core/tests/stubbed/sign-wallet.spec.ts b/frontend/editor/src/core/tests/stubbed/sign-wallet.spec.ts
new file mode 100644
index 0000000000..0740ec6b95
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/sign-wallet.spec.ts
@@ -0,0 +1,543 @@
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+import { uploadFiles } from "@app/tests/helpers/ui-helpers";
+import type { Page, Route } from "@playwright/test";
+import path from "path";
+
+const SAMPLE_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/sample.pdf",
+);
+const STORAGE_KEY = "stirling:saved-signatures:v1";
+const PNG =
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
+
+async function useBrowserStorage(page: Page) {
+ await page.route("**/api/v1/proprietary/signatures**", (route: Route) =>
+ route.fulfill({ status: 404, json: {} }),
+ );
+}
+
+async function seedBrowserSignature(
+ page: Page,
+ label: string,
+ { isDefault = false } = {},
+) {
+ await page.addInitScript(
+ ({ key, png, label, isDefault }) => {
+ const signature = {
+ id: "sig-seeded",
+ type: "image",
+ label,
+ scope: "localStorage",
+ dataUrl: png,
+ createdAt: 1,
+ updatedAt: 1,
+ };
+ localStorage.setItem(key, JSON.stringify([signature]));
+ if (isDefault) {
+ localStorage.setItem(
+ "stirling:sign:default-signature-id",
+ signature.id,
+ );
+ }
+ },
+ { key: STORAGE_KEY, png: PNG, label, isDefault },
+ );
+}
+
+async function openSign(page: Page) {
+ await page.goto("/sign");
+ await uploadFiles(page, SAMPLE_PDF);
+ await page.goto("/sign");
+ await expect(page.getByTestId("signature-wallet")).toBeVisible({
+ timeout: 20_000,
+ });
+}
+
+async function startFromIntro(page: Page, method: "Draw" | "Type") {
+ await page
+ .getByTestId("signature-wallet-intro")
+ .getByRole("button", { name: method })
+ .click();
+}
+
+async function createTypedSignature(page: Page, name: string) {
+ const dialog = page.getByRole("dialog");
+ await expect(dialog).toBeVisible();
+ await dialog.getByText("Type", { exact: true }).click();
+ await page.getByTestId("signature-type-name").fill(name);
+}
+
+test.describe("Sign tool signature wallet", () => {
+ test("first run: type, save, place and apply a signature", async ({
+ page,
+ }) => {
+ await useBrowserStorage(page);
+ await openSign(page);
+
+ await expect(page.getByTestId("signature-wallet-intro")).toBeVisible();
+ await expect(page.getByTestId("apply-signatures")).toBeDisabled();
+
+ await startFromIntro(page, "Type");
+ await createTypedSignature(page, "Jordan Ellis");
+ await page.getByTestId("use-signature").click();
+ await expect(page.getByRole("dialog")).toBeHidden();
+
+ await expect(page.getByTestId("signature-tile")).toHaveCount(2);
+ const stored = await page.evaluate(
+ (key) => JSON.parse(localStorage.getItem(key) ?? "[]"),
+ STORAGE_KEY,
+ );
+ expect(stored.map((sig: { label: string }) => sig.label).sort()).toEqual([
+ "Initials",
+ "Typed signature",
+ ]);
+
+ const status = page.getByTestId("placement-status");
+ await expect(status).toContainText("Click the page");
+ await expect(status).toContainText("Typed signature");
+
+ const pdfPage = page.locator("[data-page-index]").first();
+ await expect(pdfPage).toBeVisible();
+ const box = await pdfPage.boundingBox();
+ if (!box) throw new Error("PDF page has no bounding box");
+ await page.mouse.move(box.x + box.width * 0.4, box.y + box.height * 0.7);
+ await page.mouse.click(box.x + box.width * 0.4, box.y + box.height * 0.75);
+
+ await expect(page.getByTestId("placed-signatures")).toContainText(
+ "On this document (1)",
+ );
+ await expect(page.getByTestId("apply-signatures")).toHaveText(
+ "Apply 1 signature",
+ );
+ await expect(page.getByTestId("apply-signatures")).toBeEnabled();
+
+ await page.getByTestId("apply-signatures").click();
+ await expect(page.getByTestId("apply-signatures")).toBeDisabled();
+ await expect(status).toContainText("Pick a signature");
+ await expect(page.getByTestId("placed-signatures")).toContainText(
+ "On this document (0)",
+ );
+ await page.mouse.click(box.x + box.width * 0.4, box.y + box.height * 0.75);
+ await expect(page.getByTestId("placed-signatures")).toContainText(
+ "On this document (0)",
+ );
+ await page
+ .getByRole("button", { name: "Back to all tools", exact: true })
+ .click();
+ await expect(page.getByTestId("signature-wallet")).not.toBeVisible();
+ await expect(page.getByRole("dialog")).not.toBeVisible();
+ });
+
+ test("finishing a drawing outside the modal keeps the signature", async ({
+ page,
+ }) => {
+ await useBrowserStorage(page);
+ await openSign(page);
+ await startFromIntro(page, "Draw");
+ const pad = page.getByTestId("signature-draw-pad");
+ const box = await pad.boundingBox();
+ if (!box) throw new Error("Signature pad has no bounding box");
+ await page.mouse.move(box.x + 100, box.y + 100);
+ await page.mouse.down();
+ await page.mouse.move(box.x + 200, box.y + 120, { steps: 10 });
+ await page.mouse.move(5, 5, { steps: 10 });
+ await page.mouse.up();
+ await expect(page.getByRole("dialog")).toBeVisible();
+ await expect(page.getByTestId("use-signature")).toBeEnabled();
+ await page.getByTestId("use-signature").click();
+ await expect(page.getByTestId("signature-tile")).toHaveCount(1);
+ });
+
+ test("drawn ink stays under the cursor after the opening animation and resize", async ({
+ page,
+ }) => {
+ await useBrowserStorage(page);
+ await openSign(page);
+ await page.addStyleTag({
+ content: ".sui-modal { animation-play-state: paused !important; }",
+ });
+ await startFromIntro(page, "Draw");
+ const pad = page.getByTestId("signature-draw-pad");
+ await expect(pad).toBeVisible();
+ await expect
+ .poll(() => pad.evaluate((canvas: HTMLCanvasElement) => canvas.width))
+ .toBeGreaterThan(300);
+ await page.getByRole("dialog").evaluate((dialog) => {
+ dialog.getAnimations().forEach((animation) => animation.finish());
+ });
+
+ for (const resize of [false, true]) {
+ if (resize) {
+ await page
+ .getByRole("dialog")
+ .getByRole("button", { name: "Clear", exact: true })
+ .click();
+ await pad.evaluate((canvas) => {
+ canvas.style.width = "65%";
+ });
+ }
+ const box = await pad.boundingBox();
+ if (!box) throw new Error("Signature pad has no bounding box");
+ const point = { x: box.width * 0.75, y: box.height * 0.65 };
+ await pad.click({ position: point });
+ const ink = await pad.evaluate((canvas: HTMLCanvasElement) => {
+ const context = canvas.getContext("2d");
+ if (!context) throw new Error("Signature pad has no drawing context");
+ const pixels = context.getImageData(
+ 0,
+ 0,
+ canvas.width,
+ canvas.height,
+ ).data;
+ let totalAlpha = 0;
+ let weightedX = 0;
+ let weightedY = 0;
+ for (let y = 0; y < canvas.height; y++) {
+ for (let x = 0; x < canvas.width; x++) {
+ const alpha = pixels[(y * canvas.width + x) * 4 + 3];
+ totalAlpha += alpha;
+ weightedX += (x + 0.5) * alpha;
+ weightedY += (y + 0.5) * alpha;
+ }
+ }
+ const rect = canvas.getBoundingClientRect();
+ return {
+ totalAlpha,
+ x: (weightedX / totalAlpha) * (rect.width / canvas.width),
+ y: (weightedY / totalAlpha) * (rect.height / canvas.height),
+ };
+ });
+ expect(ink.totalAlpha).toBeGreaterThan(0);
+ expect(Math.abs(ink.x - point.x)).toBeLessThan(2);
+ expect(Math.abs(ink.y - point.y)).toBeLessThan(2);
+ }
+ });
+
+ test("resizing the drawing modal preserves strokes near its right edge", async ({
+ page,
+ }) => {
+ await useBrowserStorage(page);
+ await openSign(page);
+ await startFromIntro(page, "Draw");
+ const box = await page.getByTestId("signature-draw-pad").boundingBox();
+ if (!box) throw new Error("Signature pad has no bounding box");
+ await page.mouse.move(box.x + box.width * 0.8, box.y + 80);
+ await page.mouse.down();
+ for (let step = 1; step <= 12; step++) {
+ await page.mouse.move(
+ box.x + box.width * (0.8 + (0.15 * step) / 12),
+ box.y + 80 + (50 * step) / 12,
+ );
+ await page.waitForTimeout(20);
+ }
+ await page.mouse.up();
+ await page.getByTestId("signature-draw-pad").evaluate((canvas) => {
+ canvas.style.width = "50%";
+ });
+ await expect
+ .poll(
+ async () =>
+ (await page.getByTestId("signature-draw-pad").boundingBox())?.width,
+ )
+ .toBeLessThan(box.width * 0.6);
+ await page.getByTestId("use-signature").click();
+ await expect(page.getByTestId("signature-tile")).toHaveCount(1);
+ const dimensions = await page.evaluate(async (key) => {
+ const [signature] = JSON.parse(localStorage.getItem(key) ?? "[]");
+ const image = new Image();
+ image.src = signature.dataUrl;
+ await image.decode();
+ return { width: image.naturalWidth, height: image.naturalHeight };
+ }, STORAGE_KEY);
+ expect(dimensions.width).toBeGreaterThan(20);
+ expect(dimensions.width).toBeLessThan(250);
+ expect(dimensions.height).toBeLessThan(200);
+ });
+
+ test("blank paper cannot be saved as an invisible signature", async ({
+ page,
+ }) => {
+ await useBrowserStorage(page);
+ await openSign(page);
+ await startFromIntro(page, "Draw");
+ await page.getByRole("dialog").getByText("Upload", { exact: true }).click();
+ const image = await page.evaluate(() => {
+ const canvas = document.createElement("canvas");
+ canvas.width = 100;
+ canvas.height = 100;
+ const context = canvas.getContext("2d")!;
+ context.fillStyle = "white";
+ context.fillRect(0, 0, 100, 100);
+ return canvas.toDataURL("image/png").split(",")[1];
+ });
+ await page
+ .getByRole("dialog")
+ .locator('input[type="file"]')
+ .first()
+ .setInputFiles({
+ name: "blank.png",
+ mimeType: "image/png",
+ buffer: Buffer.from(image, "base64"),
+ });
+ await expect(page.getByRole("alert")).toContainText(
+ "Could not read that image",
+ );
+ await expect(page.getByTestId("use-signature")).toBeDisabled();
+ });
+
+ test("leaving Sign with unapplied signatures warns and can be cancelled", async ({
+ page,
+ }) => {
+ await useBrowserStorage(page);
+ await seedBrowserSignature(page, "My signature");
+ await openSign(page);
+ await page
+ .getByRole("button", { name: "My signature", exact: true })
+ .click();
+ const pdfPage = page.locator("[data-page-index]").first();
+ const box = await pdfPage.boundingBox();
+ if (!box) throw new Error("PDF page has no bounding box");
+ await page.mouse.click(box.x + box.width * 0.4, box.y + box.height * 0.75);
+ await expect(page.getByTestId("apply-signatures")).toBeEnabled();
+ await page
+ .getByRole("button", { name: "Back to all tools", exact: true })
+ .click();
+ await expect(page.getByTestId("unsaved-discard")).toBeVisible();
+ await page
+ .getByRole("button", { name: "Keep Working", exact: true })
+ .click();
+ await expect(page.getByTestId("signature-wallet")).toBeVisible();
+ await expect(page.getByTestId("apply-signatures")).toBeEnabled();
+ await page
+ .getByRole("button", { name: "Back to all tools", exact: true })
+ .click();
+ await page.getByTestId("unsaved-discard").click();
+ await expect(page.getByTestId("signature-wallet")).toBeHidden();
+ });
+
+ test("deleting the last saved signature preserves document controls", async ({
+ page,
+ }) => {
+ await useBrowserStorage(page);
+ await seedBrowserSignature(page, "My signature");
+ await openSign(page);
+ await page
+ .getByRole("button", { name: "My signature", exact: true })
+ .click();
+ const box = await page.locator("[data-page-index]").first().boundingBox();
+ if (!box) throw new Error("PDF page has no bounding box");
+ await page.mouse.click(box.x + box.width * 0.4, box.y + box.height * 0.75);
+ await expect(page.getByTestId("apply-signatures")).toBeEnabled();
+ await page
+ .getByRole("button", { name: "Options for My signature" })
+ .click();
+ await page.getByRole("menuitem", { name: "Delete", exact: true }).click();
+ await page
+ .getByRole("dialog")
+ .getByRole("button", { name: "Delete", exact: true })
+ .click();
+ await expect(page.getByTestId("signature-wallet-intro")).toBeVisible();
+ await expect(page.getByTestId("placed-signatures")).toContainText(
+ "On this document (1)",
+ );
+ await page
+ .getByRole("button", { name: "Remove Signature", exact: true })
+ .click();
+ await expect(page.getByTestId("apply-signatures")).toBeDisabled();
+ });
+
+ test("saved default signature is ready to place on open", async ({
+ page,
+ }) => {
+ await useBrowserStorage(page);
+ await seedBrowserSignature(page, "Company seal", { isDefault: true });
+ await openSign(page);
+
+ await expect(page.getByTestId("placement-status")).toContainText(
+ "Company seal",
+ );
+ await expect(
+ page.getByRole("button", { name: "Company seal", pressed: true }),
+ ).toBeVisible();
+ });
+
+ test("Escape closes a dialog or menu without stopping placement", async ({
+ page,
+ }) => {
+ await useBrowserStorage(page);
+ await seedBrowserSignature(page, "Company seal");
+ await openSign(page);
+
+ const status = page.getByTestId("placement-status");
+ await page
+ .getByRole("button", { name: "Company seal", exact: true })
+ .click();
+ await expect(status).toContainText("Company seal");
+
+ await page.getByTestId("new-signature-tile").click();
+ await expect(page.getByRole("dialog")).toBeVisible();
+ await page.keyboard.press("Escape");
+ await expect(page.getByRole("dialog")).toBeHidden();
+ await expect(status).toContainText("Company seal");
+
+ await page
+ .getByRole("button", { name: "Options for Company seal" })
+ .click();
+ await expect(page.getByRole("menu")).toBeVisible();
+ await page.keyboard.press("Escape");
+ await expect(page.getByRole("menu")).toBeHidden();
+ await expect(status).toContainText("Company seal");
+
+ await page
+ .getByRole("button", { name: "Company seal", exact: true })
+ .focus();
+ await page.keyboard.press("Escape");
+ await expect(status).toContainText("Pick a signature");
+ });
+
+ test("an unsaved signature does not reuse a saved one's name", async ({
+ page,
+ }) => {
+ await useBrowserStorage(page);
+ await seedBrowserSignature(page, "Typed signature");
+ await openSign(page);
+
+ await page.getByTestId("new-signature-tile").click();
+ await createTypedSignature(page, "Jordan Ellis");
+ await page.getByText("Save to my signatures", { exact: true }).click();
+ await page.getByTestId("use-signature").click();
+
+ await expect(page.getByTestId("placement-status")).toContainText(
+ "place Typed signature 2.",
+ );
+ });
+
+ test("a camera photo is shrunk and trimmed before it is saved", async ({
+ page,
+ }) => {
+ await useBrowserStorage(page);
+ await openSign(page);
+ const photo = await page.evaluate(() => {
+ const canvas = document.createElement("canvas");
+ canvas.width = 4000;
+ canvas.height = 3000;
+ const ctx = canvas.getContext("2d")!;
+ ctx.fillStyle = "#f4f1ea";
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ ctx.strokeStyle = "#1a1a60";
+ ctx.lineWidth = 24;
+ ctx.beginPath();
+ ctx.moveTo(800, 1500);
+ for (let i = 0; i < 50; i++) {
+ ctx.lineTo(800 + i * 48, 1500 + Math.sin(i / 3) * 250);
+ }
+ ctx.stroke();
+ return canvas.toDataURL("image/jpeg", 0.9).split(",")[1];
+ });
+
+ await startFromIntro(page, "Draw");
+ await page.getByRole("dialog").getByText("Upload", { exact: true }).click();
+ await page
+ .getByRole("dialog")
+ .locator('input[type="file"]')
+ .first()
+ .setInputFiles({
+ name: "photo.jpg",
+ mimeType: "image/jpeg",
+ buffer: Buffer.from(photo, "base64"),
+ });
+ await expect(page.getByText("Remove background")).toBeVisible();
+ await page.getByTestId("use-signature").click();
+ await expect(page.getByRole("dialog")).toBeHidden();
+
+ const saved = await page.evaluate(
+ (key) => JSON.parse(localStorage.getItem(key) ?? "[]")[0]?.dataUrl,
+ STORAGE_KEY,
+ );
+ const size = await page.evaluate(async (src: string) => {
+ const img = new Image();
+ img.src = src;
+ await img.decode();
+ return { width: img.naturalWidth, height: img.naturalHeight };
+ }, saved);
+ expect(Math.max(size.width, size.height)).toBeLessThanOrEqual(1200);
+ expect(size.width / size.height).toBeGreaterThan(3);
+ });
+
+ test.describe("server storage", () => {
+ test.use({ stubOptions: { isAdmin: true } });
+
+ test("an admin can share a new signature with everyone", async ({
+ page,
+ }) => {
+ const posted: Array<Record<string, unknown>> = [];
+ await page.route("**/api/v1/proprietary/signatures**", (route: Route) => {
+ const request = route.request();
+ if (request.method() === "POST") {
+ posted.push(request.postDataJSON());
+ return route.fulfill({ json: {} });
+ }
+ return route.fulfill({ json: [] });
+ });
+ await openSign(page);
+
+ await startFromIntro(page, "Type");
+ await createTypedSignature(page, "Finance Team");
+ const dialog = page.getByRole("dialog");
+ await dialog.getByText("Also save my initials").click();
+ await dialog.getByRole("textbox", { name: "Who can use it" }).click();
+ await page.getByRole("option", { name: "Everyone" }).click();
+ await page.getByTestId("use-signature").click();
+ await expect(dialog).toBeHidden();
+
+ expect(posted).toHaveLength(1);
+ expect(posted[0]).toMatchObject({ scope: "shared", type: "text" });
+ await expect(page.getByText("Shared", { exact: true })).toBeVisible();
+ });
+ });
+
+ test.describe("server storage with shared signatures", () => {
+ test("shared signatures do not count toward your own limit", async ({
+ page,
+ }) => {
+ const shared = Array.from({ length: 3 }, (_, i) => ({
+ id: `shared-${i}`,
+ type: "image",
+ label: `Team seal ${i + 1}`,
+ scope: "shared",
+ dataUrl: PNG,
+ createdAt: i,
+ updatedAt: i,
+ }));
+ const mine = {
+ ...shared[0],
+ id: "mine-1",
+ label: "Mine",
+ scope: "personal",
+ };
+ await page.route("**/api/v1/proprietary/signatures**", (route: Route) =>
+ route.fulfill({ json: [mine, ...shared] }),
+ );
+ await openSign(page);
+
+ await expect(page.getByText("1 of 20")).toBeVisible();
+ await expect(page.getByTestId("signature-tile")).toHaveCount(4);
+ });
+ });
+
+ test.describe("server storage without admin rights", () => {
+ test("sharing is not offered", async ({ page }) => {
+ await page.route("**/api/v1/proprietary/signatures**", (route: Route) =>
+ route.fulfill({ json: [] }),
+ );
+ await openSign(page);
+
+ await startFromIntro(page, "Draw");
+ const dialog = page.getByRole("dialog");
+ await expect(dialog).toBeVisible();
+ await expect(dialog.getByText("Save to my signatures")).toBeVisible();
+ await expect(dialog.getByText("Who can use it")).toHaveCount(0);
+ });
+ });
+});
diff --git a/frontend/editor/src/core/tests/stubbed/viewer-annotation-unsaved-changes.spec.ts b/frontend/editor/src/core/tests/stubbed/viewer-annotation-unsaved-changes.spec.ts
index b32825fe64..34dc710d63 100644
--- a/frontend/editor/src/core/tests/stubbed/viewer-annotation-unsaved-changes.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/viewer-annotation-unsaved-changes.spec.ts
@@ -77,28 +77,39 @@ test("undoing the only annotation disarms the unsaved-changes warning", async ({
await expect(page.getByText("Unsaved changes").first()).not.toBeVisible();
});
-test("entering manual redact mode keeps annotation work saveable", async ({
+test("entering manual redact mode preserves annotations through the save guard", async ({
page,
}) => {
test.setTimeout(120_000);
const firstPage = await loadViewer(page);
await highlightSomeText(page, firstPage);
- // Back to the picker first: switching tools while still on Annotate would
- // trip the unsaved-changes guard.
- await page.getByRole("button", { name: "Back to all tools" }).first().click();
- await page.waitForTimeout(700);
- await page.getByRole("link", { name: "Redact" }).first().click();
- await page.waitForTimeout(700);
- await page.getByText("Manual", { exact: true }).first().click();
+ const redact = page
+ .getByRole("button", { name: "Redact", exact: true })
+ .first();
+ await redact.click();
+ const guard = page.getByRole("dialog", {
+ name: "Unsaved Changes",
+ exact: true,
+ });
+ await expect(guard).toBeVisible();
+ await guard
+ .getByRole("button", { name: "Keep Working", exact: true })
+ .click();
+ await expect(
+ page.getByRole("button", { name: "Save Changes", exact: true }).first(),
+ ).toBeEnabled();
+ await redact.click();
+ await guard
+ .getByRole("button", { name: "Save & Leave", exact: true })
+ .click();
+ await expect(guard).toBeHidden();
await expect
.poll(() => viewerCursor(page), { timeout: 15_000 })
.toBe("crosshair");
- // Manual redaction mode used to clear the shared dirty flag, disabling this
- // button while the annotation history was still unsaved.
await expect(
page.getByRole("button", { name: "Save Changes" }).first(),
- ).toBeEnabled({ timeout: 10_000 });
+ ).toBeDisabled({ timeout: 10_000 });
});
diff --git a/frontend/editor/src/core/tools/Sign.tsx b/frontend/editor/src/core/tools/Sign.tsx
index 30ab2bfd5a..230d51d9bb 100644
--- a/frontend/editor/src/core/tools/Sign.tsx
+++ b/frontend/editor/src/core/tools/Sign.tsx
@@ -8,6 +8,7 @@ const Sign = createStampTool({
defaultSignatureType: "canvas",
enableApplyAction: true,
enableSharedSigning: true,
+ settingsPanel: "wallet",
});
export default Sign;
diff --git a/frontend/editor/src/core/tools/stamp/createStampTool.tsx b/frontend/editor/src/core/tools/stamp/createStampTool.tsx
index 1d2bd06d89..dd8fdd2842 100644
--- a/frontend/editor/src/core/tools/stamp/createStampTool.tsx
+++ b/frontend/editor/src/core/tools/stamp/createStampTool.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useCallback, useRef } from "react";
+import { useEffect, useCallback, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { createToolFlow } from "@app/components/tools/shared/createToolFlow";
import SignSettings, {
@@ -18,9 +18,11 @@ import { useSignature } from "@app/contexts/SignatureContext";
import { useFileContext } from "@app/contexts/FileContext";
import { useViewer } from "@app/contexts/ViewerContext";
import { flattenSignatures } from "@app/utils/signatureFlattening";
+import { SignatureWallet } from "@app/components/tools/sign/wallet/SignatureWallet";
import SharedSigningLauncher from "@app/components/shared/signing/SharedSigningLauncher";
import { SuggestedToolsSection } from "@app/components/tools/shared/SuggestedToolsSection";
import { useGroupSigningEnabled } from "@app/hooks/useGroupSigningEnabled";
+import { alert } from "@app/components/toast";
export type StampToolConfig = {
toolId: ToolId;
@@ -30,6 +32,7 @@ export type StampToolConfig = {
defaultSignatureType?: SignParameters["signatureType"];
enableApplyAction?: boolean;
enableSharedSigning?: boolean;
+ settingsPanel?: "stamp" | "wallet";
};
const STAMP_TOOL_DEFAULT_SOURCES: SignatureSource[] = [
@@ -48,6 +51,7 @@ export const createStampTool = (config: StampToolConfig) => {
defaultSignatureType,
enableApplyAction = false,
enableSharedSigning = false,
+ settingsPanel = "stamp",
} = config;
const StampTool = (props: BaseToolProps) => {
@@ -57,11 +61,7 @@ export const createStampTool = (config: StampToolConfig) => {
t(`${translationScope}.${key}`, defaultValue),
[t, translationScope],
);
- const {
- setWorkbench,
- setHasUnsavedChanges,
- unregisterUnsavedChangesChecker,
- } = useNavigation();
+ const { setWorkbench, setHasUnsavedChanges } = useNavigation();
const {
setSignatureConfig,
activateDrawMode,
@@ -73,6 +73,8 @@ export const createStampTool = (config: StampToolConfig) => {
signatureApiRef,
getImageData,
setSignaturesApplied,
+ placedSignatures,
+ setApplyingSignatures,
} = useSignature();
const { consumeFiles, selectors } = useFileContext();
const {
@@ -111,6 +113,10 @@ export const createStampTool = (config: StampToolConfig) => {
]);
const hasOpenedViewer = useRef(false);
+ const [hasApplied, setHasApplied] = useState(false);
+ const [isApplying, setIsApplying] = useState(false);
+ const applyInFlightRef = useRef(false);
+ const showSuggestions = settingsPanel === "stamp" || hasApplied;
const activeModeRef = useRef<"draw" | "placement" | null>(null);
const handleSignaturePlacement = useCallback(() => {
@@ -143,19 +149,24 @@ export const createStampTool = (config: StampToolConfig) => {
setSignatureConfig(base.params.parameters);
}, [base.params.parameters, setSignatureConfig]);
+ useEffect(() => {
+ if (placedSignatures.length > 0) setHasUnsavedChanges(true);
+ }, [placedSignatures, setHasUnsavedChanges]);
+
const handleSaveToSystem = useCallback(async () => {
+ if (applyInFlightRef.current) return;
+ applyInFlightRef.current = true;
+ setIsApplying(true);
+ setApplyingSignatures(true);
+ handleDeactivateSignature();
try {
- unregisterUnsavedChangesChecker();
- setHasUnsavedChanges(false);
-
const allFiles = selectors.getFiles();
const fileIndex =
activeFileIndex < allFiles.length ? activeFileIndex : 0;
const originalFile = allFiles[fileIndex];
if (!originalFile) {
- console.error("No file available to replace");
- return;
+ throw new Error("No file available to replace");
}
const flattenResult = await flattenSignatures({
@@ -177,37 +188,30 @@ export const createStampTool = (config: StampToolConfig) => {
setActiveFileIndex(0);
setSignaturesApplied(true);
+ setHasApplied(true);
handleDeactivateSignature();
-
- const hasSignatureReady = (() => {
- const params = base.params.parameters;
- switch (params.signatureType) {
- case "canvas":
- case "image":
- return Boolean(params.signatureData);
- case "text":
- return Boolean(
- params.signerName && params.signerName.trim() !== "",
- );
- default:
- return false;
- }
- })();
-
- if (hasSignatureReady) {
- if (typeof window !== "undefined") {
- window.setTimeout(() => {
- handleActivateSignaturePlacement();
- }, 150);
- } else {
- handleActivateSignaturePlacement();
- }
- }
+ setHasUnsavedChanges(false);
} else {
- console.error("Signature flattening failed");
+ throw new Error("Signature flattening failed");
}
} catch (error) {
console.error("Error saving signed document:", error);
+ setHasUnsavedChanges(true);
+ alert({
+ alertType: "error",
+ title: t(
+ "sign.wallet.toast.applyFailed",
+ "Could not apply signatures",
+ ),
+ body: t(
+ "sign.wallet.toast.applyFailedBody",
+ "Your signatures are still on the document. Try again.",
+ ),
+ });
+ } finally {
+ applyInFlightRef.current = false;
+ setIsApplying(false);
+ setApplyingSignatures(false);
}
}, [
exportActions,
@@ -222,13 +226,48 @@ export const createStampTool = (config: StampToolConfig) => {
setSignaturesApplied,
getScrollState,
handleDeactivateSignature,
- handleActivateSignaturePlacement,
setHasUnsavedChanges,
- unregisterUnsavedChangesChecker,
+ setApplyingSignatures,
+ t,
activeFileIndex,
setActiveFileIndex,
]);
+ const renderSettings = () => {
+ const onSave = enableApplyAction ? handleSaveToSystem : undefined;
+ if (settingsPanel === "wallet") {
+ return (
+ <SignatureWallet
+ onParameterChange={base.params.updateParameter}
+ disabled={base.endpointLoading || isApplying}
+ applying={isApplying}
+ onActivateSignaturePlacement={handleActivateSignaturePlacement}
+ onDeactivateSignature={handleDeactivateSignature}
+ onUndo={undo}
+ onRedo={redo}
+ onSave={onSave}
+ />
+ );
+ }
+ return (
+ <SignSettings
+ parameters={base.params.parameters}
+ onParameterChange={base.params.updateParameter}
+ disabled={base.endpointLoading}
+ onActivateDrawMode={handleActivateDrawMode}
+ onActivateSignaturePlacement={handleActivateSignaturePlacement}
+ onDeactivateSignature={handleDeactivateSignature}
+ onUpdateDrawSettings={updateDrawSettings}
+ onUndo={undo}
+ onRedo={redo}
+ onSave={onSave}
+ translationScope={translationScope}
+ allowedSignatureSources={allowedSignatureSources}
+ defaultSignatureSource={defaultSignatureSource}
+ />
+ );
+ };
+
const getSteps = () => {
const steps = [];
@@ -237,23 +276,7 @@ export const createStampTool = (config: StampToolConfig) => {
title: translateTool("steps.configure", "Configure Stamp"),
isCollapsed: false,
onCollapsedClick: undefined,
- content: (
- <SignSettings
- parameters={base.params.parameters}
- onParameterChange={base.params.updateParameter}
- disabled={base.endpointLoading}
- onActivateDrawMode={handleActivateDrawMode}
- onActivateSignaturePlacement={handleActivateSignaturePlacement}
- onDeactivateSignature={handleDeactivateSignature}
- onUpdateDrawSettings={updateDrawSettings}
- onUndo={undo}
- onRedo={redo}
- onSave={enableApplyAction ? handleSaveToSystem : undefined}
- translationScope={translationScope}
- allowedSignatureSources={allowedSignatureSources}
- defaultSignatureSource={defaultSignatureSource}
- />
- ),
+ content: renderSettings(),
});
// Optional step: send the document to others to sign instead.
@@ -276,7 +299,7 @@ export const createStampTool = (config: StampToolConfig) => {
isCollapsed: base.operation.files.length > 0,
},
steps: getSteps(),
- preview: <SuggestedToolsSection />,
+ preview: showSuggestions ? <SuggestedToolsSection /> : null,
review: {
isVisible: false,
operation: base.operation,
diff --git a/frontend/editor/src/core/ui/OptionCard.tsx b/frontend/editor/src/core/ui/OptionCard.tsx
index 336489f7d7..59cbd8ecee 100644
--- a/frontend/editor/src/core/ui/OptionCard.tsx
+++ b/frontend/editor/src/core/ui/OptionCard.tsx
@@ -1,5 +1,5 @@
import type { CSSProperties, KeyboardEvent, ReactNode } from "react";
-import { Card } from "@app/ui/Card";
+import { Card, type CardProps } from "@app/ui/Card";
import "@app/ui/OptionCard.css";
export interface OptionCardProps {
@@ -21,6 +21,7 @@ export interface OptionCardProps {
note?: ReactNode;
/** Lines the description clamps to before ellipsis. Default 3. */
descriptionLines?: number;
+ padding?: CardProps["padding"];
/** Fires when a selectable card is clicked or activated by keyboard. Ignored when disabled. */
onSelect?: () => void;
className?: string;
@@ -40,6 +41,7 @@ export function OptionCard({
disabled = false,
note,
descriptionLines = 3,
+ padding,
onSelect,
className,
}: OptionCardProps) {
@@ -54,6 +56,7 @@ export function OptionCard({
return (
<Card
+ padding={padding}
interactive={interactive}
className={[
"sui-option-card",
diff --git a/frontend/editor/src/core/utils/canvasImage.ts b/frontend/editor/src/core/utils/canvasImage.ts
new file mode 100644
index 0000000000..3a0219538f
--- /dev/null
+++ b/frontend/editor/src/core/utils/canvasImage.ts
@@ -0,0 +1,149 @@
+const EMPTY_ALPHA = 8;
+const PAPER_LEVEL = 235;
+
+export function loadImage(src: string): Promise<HTMLImageElement> {
+ return new Promise((resolve, reject) => {
+ const img = new Image();
+ img.onload = () => resolve(img);
+ img.onerror = () => reject(new Error("Failed to load image"));
+ img.src = src;
+ });
+}
+
+export function createCanvas(width: number, height: number): HTMLCanvasElement {
+ const canvas = document.createElement("canvas");
+ canvas.width = Math.max(1, Math.round(width));
+ canvas.height = Math.max(1, Math.round(height));
+ return canvas;
+}
+
+export function imageToCanvas(img: HTMLImageElement): HTMLCanvasElement {
+ const canvas = createCanvas(
+ img.naturalWidth || img.width,
+ img.naturalHeight || img.height,
+ );
+ canvas.getContext("2d")?.drawImage(img, 0, 0);
+ return canvas;
+}
+
+interface InkBounds {
+ left: number;
+ top: number;
+ right: number;
+ bottom: number;
+}
+
+export interface TrimOptions {
+ treatPaperAsEmpty?: boolean;
+ padding?: number;
+ minInkPerLine?: number;
+}
+
+function inkSpan(counts: Uint32Array, min: number): [number, number] | null {
+ let start = -1;
+ let end = -1;
+ counts.forEach((count, index) => {
+ if (count < min) return;
+ if (start < 0) start = index;
+ end = index;
+ });
+ return start < 0 ? null : [start, end];
+}
+
+function findInkBounds(
+ canvas: HTMLCanvasElement,
+ { treatPaperAsEmpty = false, minInkPerLine = 1 }: TrimOptions,
+): InkBounds | null {
+ const ctx = canvas.getContext("2d", { willReadFrequently: true });
+ if (!ctx) return null;
+ const { width, height } = canvas;
+ const pixels = ctx.getImageData(0, 0, width, height).data;
+ const isInk = (i: number) =>
+ pixels[i + 3] > EMPTY_ALPHA &&
+ !(
+ treatPaperAsEmpty &&
+ pixels[i] > PAPER_LEVEL &&
+ pixels[i + 1] > PAPER_LEVEL &&
+ pixels[i + 2] > PAPER_LEVEL
+ );
+ const rows = new Uint32Array(height);
+ const columns = new Uint32Array(width);
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ if (!isInk((y * width + x) * 4)) continue;
+ rows[y]++;
+ columns[x]++;
+ }
+ }
+ const vertical = inkSpan(rows, minInkPerLine);
+ const horizontal = inkSpan(columns, minInkPerLine);
+ if (!vertical || !horizontal) return null;
+ return {
+ top: vertical[0],
+ bottom: vertical[1],
+ left: horizontal[0],
+ right: horizontal[1],
+ };
+}
+
+export function trimCanvas(
+ source: HTMLCanvasElement,
+ options: TrimOptions = {},
+): HTMLCanvasElement {
+ const bounds = findInkBounds(source, options);
+ if (!bounds) return source;
+ const padding = options.padding ?? 0;
+ const left = Math.max(0, bounds.left - padding);
+ const top = Math.max(0, bounds.top - padding);
+ const width = Math.min(source.width, bounds.right + padding + 1) - left;
+ const height = Math.min(source.height, bounds.bottom + padding + 1) - top;
+ const out = createCanvas(width, height);
+ out
+ .getContext("2d")
+ ?.drawImage(source, left, top, width, height, 0, 0, width, height);
+ return out;
+}
+
+/** Reports whether a canvas contains visible foreground pixels. */
+export function hasCanvasInk(canvas: HTMLCanvasElement): boolean {
+ return findInkBounds(canvas, {}) !== null;
+}
+
+export function scaleCanvasToFit(
+ source: HTMLCanvasElement,
+ maxSide: number,
+): HTMLCanvasElement {
+ const scale = maxSide / Math.max(source.width, source.height);
+ if (scale >= 1) return source;
+ const out = createCanvas(source.width * scale, source.height * scale);
+ out.getContext("2d")?.drawImage(source, 0, 0, out.width, out.height);
+ return out;
+}
+
+export function rotateCanvas(
+ source: HTMLCanvasElement,
+ quarterTurns: number,
+): HTMLCanvasElement {
+ const turns = ((quarterTurns % 4) + 4) % 4;
+ if (turns === 0) return source;
+ const sideways = turns % 2 === 1;
+ const out = createCanvas(
+ sideways ? source.height : source.width,
+ sideways ? source.width : source.height,
+ );
+ const ctx = out.getContext("2d");
+ if (!ctx) return source;
+ ctx.translate(out.width / 2, out.height / 2);
+ ctx.rotate((turns * Math.PI) / 2);
+ ctx.drawImage(source, -source.width / 2, -source.height / 2);
+ return out;
+}
+
+export function recolorCanvas(canvas: HTMLCanvasElement, color: string): void {
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return;
+ ctx.globalCompositeOperation = "source-in";
+ ctx.fillStyle = color;
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ ctx.globalCompositeOperation = "source-over";
+}
diff --git a/frontend/editor/src/core/utils/fileUtils.ts b/frontend/editor/src/core/utils/fileUtils.ts
index e71f69e86d..333ccb82d3 100644
--- a/frontend/editor/src/core/utils/fileUtils.ts
+++ b/frontend/editor/src/core/utils/fileUtils.ts
@@ -16,6 +16,18 @@ export function formatFileSize(bytes: number): string {
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
}
+export function readFileAsDataUrl(file: Blob): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => {
+ if (typeof reader.result === "string") resolve(reader.result);
+ else reject(new Error("File could not be read as a data URL"));
+ };
+ reader.onerror = () => reject(reader.error);
+ reader.readAsDataURL(file);
+ });
+}
+
/**
* Get file date as string
*/
diff --git a/frontend/editor/src/core/utils/signatureFlattening.test.ts b/frontend/editor/src/core/utils/signatureFlattening.test.ts
index 59b9e7f381..4f9347327b 100644
--- a/frontend/editor/src/core/utils/signatureFlattening.test.ts
+++ b/frontend/editor/src/core/utils/signatureFlattening.test.ts
@@ -7,10 +7,15 @@ import {
PDFDocument,
PDFName,
PDFNumber,
+ PDFString,
PDFRawStream,
decodePDFRawStream,
} from "@cantoo/pdf-lib";
-import { embedSignatureImages } from "@app/utils/signatureFlattening";
+import {
+ embedSignatureImages,
+ flattenSignatures,
+} from "@app/utils/signatureFlattening";
+import type { SignatureAPI } from "@app/components/viewer/viewerTypes";
const ONE_PIXEL_PNG =
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";
@@ -52,6 +57,40 @@ const readPageContentStreams = (document: PDFDocument): string[] => {
};
describe("signatureFlattening", () => {
+ test("leaves live signatures intact when exporting fails", async () => {
+ const deleteAnnotation = vi.fn();
+ const api: SignatureAPI = {
+ addImageSignature: vi.fn(),
+ activateDrawMode: vi.fn(),
+ activateSignaturePlacementMode: vi.fn(),
+ activateDeleteMode: vi.fn(),
+ deleteAnnotation,
+ updateDrawSettings: vi.fn(),
+ deactivateTools: vi.fn(),
+ selectAnnotation: vi.fn(),
+ getPageAnnotations: async () => [
+ {
+ id: "live",
+ rect: { x: 25, y: 30, width: 120, height: 50 },
+ imageSrc: `data:image/png;base64,${ONE_PIXEL_PNG}`,
+ },
+ ],
+ };
+ const result = await flattenSignatures({
+ signatureApiRef: { current: api },
+ getImageData: () => `data:image/png;base64,${ONE_PIXEL_PNG}`,
+ exportActions: { saveAsCopy: async () => null },
+ selectors: {
+ getAllFileIds: () => [],
+ getStirlingFileStub: () => undefined,
+ getFile: () => undefined,
+ },
+ getScrollState: () => ({ currentPage: 1, totalPages: 1 }),
+ });
+ expect(result).toBeNull();
+ expect(deleteAnnotation).not.toHaveBeenCalled();
+ });
+
test("adds a PDFium stamp without regenerating page content", async () => {
const sourceDocument = await PDFDocument.create();
const sourcePage = sourceDocument.addPage([300, 400]);
@@ -112,4 +151,88 @@ describe("signatureFlattening", () => {
),
).toEqual([25, 320, 145, 370]);
}, 20_000);
+
+ test("locks the exported signature without duplicating it or changing its appearance", async () => {
+ const sourceDocument = await PDFDocument.create();
+ const page = sourceDocument.addPage([300, 400]);
+ const stamp = sourceDocument.context.obj({
+ Type: "Annot",
+ Subtype: "Stamp",
+ NM: PDFString.of("signature-existing"),
+ Rect: [25, 320, 145, 370],
+ F: 4,
+ });
+ const other = sourceDocument.context.obj({
+ Type: "Annot",
+ Subtype: "Text",
+ Rect: [10, 10, 20, 20],
+ F: 4,
+ });
+ page.node.set(
+ PDFName.of("Annots"),
+ sourceDocument.context.obj([
+ sourceDocument.context.register(stamp),
+ sourceDocument.context.register(other),
+ ]),
+ );
+ const bytes = await sourceDocument.save();
+ const decoder = vi.fn();
+ const output = await embedSignatureImages(
+ Uint8Array.from(bytes).buffer,
+ [
+ {
+ pageIndex: 0,
+ annotations: [
+ {
+ id: "signature-existing",
+ rect: { x: 25, y: 30, width: 120, height: 50 },
+ },
+ ],
+ },
+ ],
+ () => undefined,
+ decoder,
+ );
+ const document = await PDFDocument.load(output);
+ const annotations = document.getPage(0).node.Annots();
+ expect(annotations?.size()).toBe(2);
+ expect(
+ annotations
+ ?.lookup(0, PDFDict)
+ .lookup(PDFName.of("F"), PDFNumber)
+ .asNumber(),
+ ).toBe(196);
+ expect(
+ annotations
+ ?.lookup(1, PDFDict)
+ .lookup(PDFName.of("F"), PDFNumber)
+ .asNumber(),
+ ).toBe(4);
+ expect(decoder).not.toHaveBeenCalled();
+ });
+
+ test("rejects failed signature decoding instead of returning a partly signed PDF", async () => {
+ const document = await PDFDocument.create();
+ document.addPage([300, 400]);
+ const bytes = await document.save();
+ await expect(
+ embedSignatureImages(
+ Uint8Array.from(bytes).buffer,
+ [
+ {
+ pageIndex: 0,
+ annotations: [
+ {
+ id: "missing",
+ rect: { x: 25, y: 30, width: 120, height: 50 },
+ imageSrc: `data:image/png;base64,${ONE_PIXEL_PNG}`,
+ },
+ ],
+ },
+ ],
+ () => undefined,
+ async () => null,
+ ),
+ ).rejects.toThrow("Could not decode signature image");
+ });
});
diff --git a/frontend/editor/src/core/utils/signatureFlattening.ts b/frontend/editor/src/core/utils/signatureFlattening.ts
index 6c79fc3461..cf908ee00b 100644
--- a/frontend/editor/src/core/utils/signatureFlattening.ts
+++ b/frontend/editor/src/core/utils/signatureFlattening.ts
@@ -8,6 +8,7 @@ import {
getPdfiumModule,
openRawDocumentSafe,
readEffectivePageBox,
+ readUtf16,
saveRawDocument,
} from "@app/services/pdfiumService";
import { generateThumbnailWithMetadata } from "@app/utils/thumbnailUtils";
@@ -93,7 +94,6 @@ export async function flattenSignatures(
} = options;
try {
- // Step 1: Extract all annotations from EmbedPDF before export
const allAnnotations: Array<{
pageIndex: number;
annotations: SignatureAnnotation[];
@@ -134,26 +134,7 @@ export async function flattenSignatures(
}
}
- // Step 2: Delete ONLY session annotations from EmbedPDF before export
- if (allAnnotations.length > 0 && signatureApiRef?.current) {
- for (const pageData of allAnnotations) {
- for (const annotation of pageData.annotations) {
- try {
- signatureApiRef.current.deleteAnnotation(
- annotation.id,
- pageData.pageIndex,
- );
- } catch (deleteError) {
- console.warn(
- `Failed to delete annotation ${annotation.id}:`,
- deleteError,
- );
- }
- }
- }
- }
-
- // Step 3: Use EmbedPDF's saveAsCopy to get the original PDF
+ // Keep the live annotations intact until FileContext accepts the signed copy.
if (!exportActions) {
console.error("No export actions available");
return null;
@@ -188,24 +169,15 @@ export async function flattenSignatures(
type: "application/pdf",
});
- // Step 4: Add signatures as locked, printable PDFium stamp annotations.
- // FPDFAnnot_AppendObject creates the annotation appearance without asking
- // PDFium to regenerate the page's existing content. GenerateContent would
- // corrupt some Type3/vector content, including the issue #7083 logo.
if (allAnnotations.length > 0) {
- try {
- const resultBytes = await embedSignatureImages(
- await signedFile.arrayBuffer(),
- allAnnotations,
- getImageData,
- );
- signedFile = new File([resultBytes], currentFile.name, {
- type: "application/pdf",
- });
- } catch (renderError) {
- console.error("Failed to embed signature images:", renderError);
- console.warn("Signatures may only remain as annotations");
- }
+ const resultBytes = await embedSignatureImages(
+ await signedFile.arrayBuffer(),
+ allAnnotations,
+ getImageData,
+ );
+ signedFile = new File([resultBytes], currentFile.name, {
+ type: "application/pdf",
+ });
}
const thumbnailResult = await generateThumbnailWithMetadata(signedFile);
@@ -317,31 +289,34 @@ export async function embedSignatureImages(
const pageCount = m.FPDF_GetPageCount(docPtr);
for (const { pageIndex, annotations } of annotationsByPage) {
- if (pageIndex < 0 || pageIndex >= pageCount) continue;
+ if (pageIndex < 0 || pageIndex >= pageCount)
+ throw new Error("Signature page is unavailable");
const pagePtr = m.FPDF_LoadPage(docPtr, pageIndex);
- if (!pagePtr) continue;
+ if (!pagePtr) throw new Error("Could not load signature page");
try {
const pageBox = readEffectivePageBox(m, pagePtr);
const cropHeight = pageBox.top - pageBox.bottom;
for (const annotation of annotations) {
+ if (lockExportedSignature(m, pagePtr, annotation.id)) continue;
const rect =
annotation.rect ??
annotation.bounds ??
annotation.rectangle ??
annotation.position;
- if (!rect) continue;
+ if (!rect) throw new Error("Signature position is unavailable");
const originalX = rect.origin?.x ?? rect.x ?? rect.left ?? 0;
const originalY = rect.origin?.y ?? rect.y ?? rect.top ?? 0;
const width = rect.size?.width ?? rect.width ?? 100;
const height = rect.size?.height ?? rect.height ?? 50;
- if (width <= 0 || height <= 0) continue;
+ if (width <= 0 || height <= 0)
+ throw new Error("Invalid signature size");
let imageDataUrl = getAnnotationImageData(annotation, getImageData);
- if (!imageDataUrl) continue;
+ if (!imageDataUrl) throw new Error("Signature image is unavailable");
if (imageDataUrl.startsWith("data:image/svg+xml")) {
const pngBytes = await rasteriseSvgToPng(
@@ -349,16 +324,17 @@ export async function embedSignatureImages(
width * 2,
height * 2,
);
- if (!pngBytes) continue;
+ if (!pngBytes) throw new Error("Could not render signature image");
imageDataUrl = `data:image/png;base64,${uint8ArrayToBase64(pngBytes)}`;
}
const decodedImage = await imageDecoder(imageDataUrl);
- if (!decodedImage) continue;
+ if (!decodedImage)
+ throw new Error("Could not decode signature image");
const pdfX = pageBox.left + originalX;
const pdfY = pageBox.bottom + cropHeight - originalY - height;
- appendStampAnnotation(
+ const appended = appendStampAnnotation(
m,
docPtr,
pagePtr,
@@ -368,6 +344,7 @@ export async function embedSignatureImages(
width,
height,
);
+ if (!appended) throw new Error("Could not embed signature image");
}
} finally {
m.FPDF_ClosePage(pagePtr);
@@ -385,6 +362,47 @@ const FPDF_ANNOT_FLAG_PRINT = 1 << 2;
const FPDF_ANNOT_FLAG_READONLY = 1 << 6;
const FPDF_ANNOT_FLAG_LOCKED = 1 << 7;
+function lockExportedSignature(
+ m: Awaited<ReturnType<typeof getPdfiumModule>>,
+ pagePtr: number,
+ annotationId: string,
+): boolean {
+ const count = m.FPDFPage_GetAnnotCount(pagePtr);
+ for (let index = 0; index < count; index++) {
+ const annotationPtr = m.FPDFPage_GetAnnot(pagePtr, index);
+ if (!annotationPtr) continue;
+ try {
+ if (m.FPDFAnnot_GetSubtype(annotationPtr) !== FPDF_ANNOT_STAMP) continue;
+ const length = m.FPDFAnnot_GetStringValue(annotationPtr, "NM", 0, 0);
+ if (length <= 2) continue;
+ const buffer = m.pdfium.wasmExports.malloc(length);
+ let name: string;
+ try {
+ m.FPDFAnnot_GetStringValue(annotationPtr, "NM", buffer, length);
+ name = readUtf16(m, buffer, length);
+ } finally {
+ m.pdfium.wasmExports.free(buffer);
+ }
+ if (name !== annotationId) continue;
+ // Lock the exported appearance in place; rebuilding it can lose rotation or duplicate it.
+ if (
+ !m.FPDFAnnot_SetFlags(
+ annotationPtr,
+ FPDF_ANNOT_FLAG_PRINT |
+ FPDF_ANNOT_FLAG_READONLY |
+ FPDF_ANNOT_FLAG_LOCKED,
+ )
+ ) {
+ throw new Error("Could not lock signature annotation");
+ }
+ return true;
+ } finally {
+ m.FPDFPage_CloseAnnot(annotationPtr);
+ }
+ }
+ return false;
+}
+
function appendStampAnnotation(
m: Awaited<ReturnType<typeof getPdfiumModule>>,
docPtr: number,
diff --git a/frontend/editor/src/core/utils/signatureImage.test.ts b/frontend/editor/src/core/utils/signatureImage.test.ts
new file mode 100644
index 0000000000..340f847e0e
--- /dev/null
+++ b/frontend/editor/src/core/utils/signatureImage.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vitest";
+import {
+ deriveInitials,
+ fitPlacedSignatureSize,
+} from "@app/utils/signatureImage";
+
+describe("deriveInitials", () => {
+ it("takes the first letters of the first and last names", () => {
+ expect(deriveInitials("Jordan Ellis")).toBe("JE");
+ expect(deriveInitials(" mary ann lee ")).toBe("ML");
+ });
+
+ it("uses a single letter for a single name and nothing for blanks", () => {
+ expect(deriveInitials("Cher")).toBe("C");
+ expect(deriveInitials(" ")).toBe("");
+ });
+});
+
+describe("fitPlacedSignatureSize", () => {
+ it("fits a wide signature to the line width, keeping its aspect", () => {
+ const size = fitPlacedSignatureSize(1200, 300);
+ expect(size.width).toBeCloseTo(180);
+ expect(size.height).toBeCloseTo(45);
+ });
+
+ it("fits a tall mark (initials, seals) to the line height", () => {
+ const size = fitPlacedSignatureSize(200, 200);
+ expect(size.width).toBeCloseTo(60);
+ expect(size.height).toBeCloseTo(60);
+ });
+
+ it("scales a small image up to the same box", () => {
+ const size = fitPlacedSignatureSize(36, 12);
+ expect(size.width).toBeCloseTo(180);
+ expect(size.height).toBeCloseTo(60);
+ });
+
+ it("survives zero dimensions", () => {
+ const size = fitPlacedSignatureSize(0, 0);
+ expect(Number.isFinite(size.width)).toBe(true);
+ expect(Number.isFinite(size.height)).toBe(true);
+ });
+});
diff --git a/frontend/editor/src/core/utils/signatureImage.ts b/frontend/editor/src/core/utils/signatureImage.ts
new file mode 100644
index 0000000000..86ea8339fa
--- /dev/null
+++ b/frontend/editor/src/core/utils/signatureImage.ts
@@ -0,0 +1,123 @@
+import { removeWhiteBackground } from "@app/utils/imageTransparency";
+import {
+ createCanvas,
+ hasCanvasInk,
+ imageToCanvas,
+ loadImage,
+ recolorCanvas,
+ rotateCanvas,
+ scaleCanvasToFit,
+ trimCanvas,
+} from "@app/utils/canvasImage";
+
+export const SIGNATURE_TRIM_PADDING = 6;
+const MAX_UPLOAD_SIDE = 1200;
+const PHOTO_SPECK_PIXELS = 3;
+const PLACED_MAX_WIDTH = 180;
+const PLACED_MAX_HEIGHT = 60;
+
+export interface TypedSignatureOptions {
+ text: string;
+ fontFamily: string;
+ color: string;
+ fontSize: number;
+}
+
+export async function renderTypedSignature({
+ text,
+ fontFamily,
+ color,
+ fontSize,
+}: TypedSignatureOptions): Promise<string | null> {
+ const value = text.trim();
+ if (!value) return null;
+ const font = `${fontSize}px "${fontFamily}"`;
+ await document.fonts?.load(font, value).catch(() => undefined);
+
+ const ctx = createCanvas(1, 1).getContext("2d");
+ if (!ctx) return null;
+ ctx.font = font;
+ const metrics = ctx.measureText(value);
+ const left = Math.ceil(metrics.actualBoundingBoxLeft || 0);
+ const right = Math.ceil(metrics.actualBoundingBoxRight || metrics.width);
+ const ascent = Math.ceil(metrics.actualBoundingBoxAscent || fontSize);
+ const descent = Math.ceil(metrics.actualBoundingBoxDescent || fontSize * 0.3);
+ const pad = Math.round(fontSize * 0.12);
+
+ const canvas = createCanvas(
+ left + right + pad * 2,
+ ascent + descent + pad * 2,
+ );
+ const out = canvas.getContext("2d");
+ if (!out) return null;
+ out.font = font;
+ out.fillStyle = color;
+ out.fillText(value, pad + left, pad + ascent);
+ return canvas.toDataURL("image/png");
+}
+
+export interface UploadCleanup {
+ removeBackground: boolean;
+ trim: boolean;
+ inkColor: string | null;
+ quarterTurns: number;
+}
+
+async function removePaper(source: string): Promise<HTMLCanvasElement> {
+ const transparent = await removeWhiteBackground(source, {
+ autoDetectCorner: true,
+ tolerance: 15,
+ });
+ return imageToCanvas(await loadImage(transparent));
+}
+
+export const PHONE_DRAWING_CLEANUP: UploadCleanup = {
+ removeBackground: false,
+ trim: true,
+ inkColor: null,
+ quarterTurns: 0,
+};
+
+export async function cleanUpSignatureImage(
+ source: string,
+ { removeBackground, trim, inkColor, quarterTurns }: UploadCleanup,
+): Promise<string> {
+ const photo = scaleCanvasToFit(
+ imageToCanvas(await loadImage(source)),
+ MAX_UPLOAD_SIDE,
+ );
+ const base = removeBackground
+ ? await removePaper(photo.toDataURL("image/png"))
+ : photo;
+ let canvas = rotateCanvas(base, quarterTurns);
+ if (trim) {
+ canvas = trimCanvas(canvas, {
+ treatPaperAsEmpty: !removeBackground,
+ padding: SIGNATURE_TRIM_PADDING,
+ minInkPerLine: PHOTO_SPECK_PIXELS,
+ });
+ }
+ if (removeBackground && inkColor) {
+ recolorCanvas(canvas, inkColor);
+ }
+ if (!hasCanvasInk(canvas))
+ throw new Error("The signature image has no visible ink");
+ return canvas.toDataURL("image/png");
+}
+
+export function deriveInitials(name: string): string {
+ const words = name.trim().split(/\s+/).filter(Boolean);
+ if (words.length === 0) return "";
+ const last = words.length > 1 ? words[words.length - 1].charAt(0) : "";
+ return `${words[0].charAt(0)}${last}`.toUpperCase();
+}
+
+export function fitPlacedSignatureSize(width: number, height: number) {
+ const safeWidth = Math.max(1, width);
+ const safeHeight = Math.max(1, height);
+ const scale = Math.min(
+ PLACED_MAX_WIDTH / safeWidth,
+ PLACED_MAX_HEIGHT / safeHeight,
+ );
+ return { width: safeWidth * scale, height: safeHeight * scale };
+}
diff --git a/frontend/editor/src/core/utils/signaturePreview.ts b/frontend/editor/src/core/utils/signaturePreview.ts
index 84e2d9635c..35242030f8 100644
--- a/frontend/editor/src/core/utils/signaturePreview.ts
+++ b/frontend/editor/src/core/utils/signaturePreview.ts
@@ -3,6 +3,7 @@ import {
HORIZONTAL_PADDING_RATIO,
VERTICAL_PADDING_RATIO,
} from "@app/constants/signConstants";
+import { loadImage } from "@app/utils/canvasImage";
export interface SignaturePreview {
dataUrl: string;
@@ -10,14 +11,6 @@ export interface SignaturePreview {
height: number;
}
-const loadImage = (src: string): Promise<HTMLImageElement> =>
- new Promise((resolve, reject) => {
- const img = new Image();
- img.onload = () => resolve(img);
- img.onerror = reject;
- img.src = src;
- });
-
export const buildSignaturePreview = async (
config: SignParameters | null,
): Promise<SignaturePreview | null> => {
diff --git a/frontend/editor/src/core/utils/uniqueName.test.ts b/frontend/editor/src/core/utils/uniqueName.test.ts
new file mode 100644
index 0000000000..79fce34737
--- /dev/null
+++ b/frontend/editor/src/core/utils/uniqueName.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from "vitest";
+import { uniqueName } from "@app/utils/uniqueName";
+
+describe("uniqueName", () => {
+ it("keeps a free name as it is", () => {
+ expect(uniqueName("Signature", ["Initials"])).toBe("Signature");
+ });
+
+ it("numbers a taken name from 2, ignoring case", () => {
+ expect(uniqueName("Signature", ["signature"])).toBe("Signature 2");
+ expect(uniqueName("Signature", ["Signature", "Signature 2"])).toBe(
+ "Signature 3",
+ );
+ });
+});
diff --git a/frontend/editor/src/core/utils/uniqueName.ts b/frontend/editor/src/core/utils/uniqueName.ts
new file mode 100644
index 0000000000..cfd891b958
--- /dev/null
+++ b/frontend/editor/src/core/utils/uniqueName.ts
@@ -0,0 +1,7 @@
+export function uniqueName(base: string, taken: readonly string[]): string {
+ const used = new Set(taken.map((name) => name.toLowerCase()));
+ if (!used.has(base.toLowerCase())) return base;
+ let index = 2;
+ while (used.has(`${base} ${index}`.toLowerCase())) index++;
+ return `${base} ${index}`;
+}
diff --git a/frontend/editor/src/saas/components/tools/sign/SignSettings.tsx b/frontend/editor/src/saas/components/tools/sign/SignSettings.tsx
index c31678b32c..d7dc5bd788 100644
--- a/frontend/editor/src/saas/components/tools/sign/SignSettings.tsx
+++ b/frontend/editor/src/saas/components/tools/sign/SignSettings.tsx
@@ -13,6 +13,7 @@ import { Button } from "@app/ui/Button";
import { SegmentedControl } from "@app/ui/SegmentedControl";
import { SignParameters } from "@app/hooks/tools/sign/useSignParameters";
import { useSignature } from "@app/contexts/SignatureContext";
+import { useHistoryAvailability } from "@app/hooks/useHistoryAvailability";
import { useViewer } from "@app/contexts/ViewerContext";
import {
PLACEMENT_ACTIVATION_DELAY,
@@ -97,11 +98,7 @@ const SignSettings = ({
const { t } = useTranslation();
const { isPlacementMode, signaturesApplied, historyApiRef } = useSignature();
const { activeFileIndex } = useViewer();
- const [historyAvailability, setHistoryAvailability] = useState({
- canUndo: false,
- canRedo: false,
- });
- const historyApiInstance = historyApiRef.current;
+ const historyAvailability = useHistoryAvailability(historyApiRef);
const translate = useCallback(
(key: string, defaultValue: string, options?: Record<string, unknown>) =>
t(`${translationScope}.${key}`, { defaultValue, ...options }),
@@ -587,27 +584,6 @@ const SignSettings = ({
}
}, [signaturesApplied]);
- useEffect(() => {
- if (!historyApiInstance) {
- setHistoryAvailability({ canUndo: false, canRedo: false });
- return;
- }
-
- const updateAvailability = () => {
- setHistoryAvailability({
- canUndo: historyApiInstance.canUndo?.() ?? false,
- canRedo: historyApiInstance.canRedo?.() ?? false,
- });
- };
-
- const unsubscribe = historyApiInstance.subscribe?.(updateAvailability);
- updateAvailability();
-
- return () => {
- unsubscribe?.();
- };
- }, [historyApiInstance]);
-
// Handle image upload
const handleImageChange = async (file: File | null) => {
if (file && !disabled) {
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 0d62ef68c5..c1e9e9b0d7 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -35,6 +35,12 @@
"@embedpdf/plugin-tiling": "^2.15.1",
"@embedpdf/plugin-viewport": "^2.15.1",
"@embedpdf/plugin-zoom": "^2.15.1",
+ "@fontsource/allura": "^5.3.0",
+ "@fontsource/caveat": "^5.3.0",
+ "@fontsource/dancing-script": "^5.3.0",
+ "@fontsource/great-vibes": "^5.3.0",
+ "@fontsource/homemade-apple": "^5.3.0",
+ "@fontsource/mrs-saint-delafield": "^5.3.0",
"@mantine/core": "^8.3.1",
"@mantine/dates": "^8.3.1",
"@mantine/dropzone": "^8.3.1",
@@ -1823,6 +1829,60 @@
"integrity": "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==",
"license": "MIT"
},
+ "node_modules/@fontsource/allura": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/@fontsource/allura/-/allura-5.3.0.tgz",
+ "integrity": "sha512-UqloNNVxl03+psvtIXCYuo7/v2mD9XmX2HGiczhK6NmDDwbFJJDjrbHZ5tpNuVXKsMEQPc46tZu3hewYN82/YA==",
+ "license": "OFL-1.1",
+ "funding": {
+ "url": "https://github.com/sponsors/ayuhito"
+ }
+ },
+ "node_modules/@fontsource/caveat": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/@fontsource/caveat/-/caveat-5.3.0.tgz",
+ "integrity": "sha512-eHTfzQxFSW9ABERRLNruHoNJmKed2J7pqTUc5lp4a4POMgXGKpxmWj3d9Hz10kmAg6iuTTLe6UagbA4bnsmfQw==",
+ "license": "OFL-1.1",
+ "funding": {
+ "url": "https://github.com/sponsors/ayuhito"
+ }
+ },
+ "node_modules/@fontsource/dancing-script": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/@fontsource/dancing-script/-/dancing-script-5.3.0.tgz",
+ "integrity": "sha512-/FFbz4ZCNN+eG2a6phkZB41iKmyCC6rq2blA/kG9OFeI3/tpzLNazND1bBdEnogLhpfg7o4NfauTbEEYSpSUGg==",
+ "license": "OFL-1.1",
+ "funding": {
+ "url": "https://github.com/sponsors/ayuhito"
+ }
+ },
+ "node_modules/@fontsource/great-vibes": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/@fontsource/great-vibes/-/great-vibes-5.3.0.tgz",
+ "integrity": "sha512-1w60cXzXnC9V4y943po8044O1mqRQBiTTK75h7OpZE+1VQtx+KlAAzoIyEE5KNzu05gUpxaCQg7cbL7ITSwegQ==",
+ "license": "OFL-1.1",
+ "funding": {
+ "url": "https://github.com/sponsors/ayuhito"
+ }
+ },
+ "node_modules/@fontsource/homemade-apple": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/@fontsource/homemade-apple/-/homemade-apple-5.3.0.tgz",
+ "integrity": "sha512-awJSYTbSY3SroC8nirEhDauHvERVvm0LI3FpUHsPZXl9Tht1xrqhiI8ro4yf3ROcvQ7CfFJ/2+DLcOHBOXhJKw==",
+ "license": "Apache-2.0",
+ "funding": {
+ "url": "https://github.com/sponsors/ayuhito"
+ }
+ },
+ "node_modules/@fontsource/mrs-saint-delafield": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/@fontsource/mrs-saint-delafield/-/mrs-saint-delafield-5.3.0.tgz",
+ "integrity": "sha512-OH6pmSgyh8CqpiFmAxthdrlhreJj2jt49kk+NpEZ4UMRrSOcF7qxF1AT0QNxuVVCQWy4h5TOIvep7Hglenrtig==",
+ "license": "OFL-1.1",
+ "funding": {
+ "url": "https://github.com/sponsors/ayuhito"
+ }
+ },
"node_modules/@inquirer/ansi": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.0.5.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index b9f6b0af0c..15ce660c9f 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -32,6 +32,12 @@
"@embedpdf/plugin-tiling": "^2.15.1",
"@embedpdf/plugin-viewport": "^2.15.1",
"@embedpdf/plugin-zoom": "^2.15.1",
+ "@fontsource/allura": "^5.3.0",
+ "@fontsource/caveat": "^5.3.0",
+ "@fontsource/dancing-script": "^5.3.0",
+ "@fontsource/great-vibes": "^5.3.0",
+ "@fontsource/homemade-apple": "^5.3.0",
+ "@fontsource/mrs-saint-delafield": "^5.3.0",
"@mantine/core": "^8.3.1",
"@mantine/dates": "^8.3.1",
"@mantine/dropzone": "^8.3.1",