Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions scripts/smoke-test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,63 @@ try {
await page.locator(".dirty-dot").waitFor();
console.log("ok saved signatures can be selected, exported together, and forgotten individually");

// Select a placed signature in Select mode: drag to move, resize, undo, delete by key and trash button, and click away to read.
const stamps = page.locator(".annotationEditorLayer .stampEditor");
const initialStamps = await stamps.count();
assert.ok(initialStamps >= 1, "expected placed signatures on page 1");
const firstStamp = stamps.first();
const beforeMove = await firstStamp.boundingBox();
await page.mouse.click(beforeMove.x + beforeMove.width / 2, beforeMove.y + beforeMove.height / 2);
await page.locator(".stampEditor.selectedEditor").waitFor();
assert.equal(await page.getByRole("button", { name: "Select", exact: true }).getAttribute("aria-pressed"), "true");
const removeSignature = page.getByRole("button", { name: "Remove signature", exact: true });
await removeSignature.waitFor();
assert.equal(await page.locator(".stampEditor.selectedEditor .editToolbar .altText").isVisible(), false);

await page.mouse.move(beforeMove.x + beforeMove.width / 2, beforeMove.y + beforeMove.height / 2);
await page.mouse.down();
await page.mouse.move(beforeMove.x + beforeMove.width / 2 + 36, beforeMove.y + beforeMove.height / 2 + 24, { steps: 5 });
await page.mouse.up();
const afterMove = await firstStamp.boundingBox();
assert.ok(afterMove.x > beforeMove.x + 15 && afterMove.y > beforeMove.y + 10, "signature did not move when dragged");

const handle = await firstStamp.locator(".resizer.bottomRight").boundingBox();
await page.mouse.move(handle.x + handle.width / 2, handle.y + handle.height / 2);
await page.mouse.down();
await page.mouse.move(handle.x + handle.width / 2 + 28, handle.y + handle.height / 2 + 16, { steps: 5 });
await page.mouse.up();
const afterResize = await firstStamp.boundingBox();
assert.ok(afterResize.width > afterMove.width + 10, "signature did not resize from handle");

await page.keyboard.press("ControlOrMeta+z");
await page.waitForTimeout(150);
const afterUndoResize = await firstStamp.boundingBox();
assert.ok(Math.abs(afterUndoResize.width - afterMove.width) < 6, "undo did not revert signature resize");

await page.keyboard.press("Delete");
await page.waitForFunction((n) => document.querySelectorAll(".annotationEditorLayer .stampEditor").length === n, initialStamps - 1);
assert.equal(await page.locator(".stampEditor.selectedEditor").count(), 0);
await page.keyboard.press("ControlOrMeta+z");
await page.waitForFunction((n) => document.querySelectorAll(".annotationEditorLayer .stampEditor canvas").length === n, initialStamps);
assert.equal(await page.locator(".stampEditor.selectedEditor").count(), 0);

const restoredBox = await stamps.first().boundingBox();
await page.mouse.click(restoredBox.x + restoredBox.width / 2, restoredBox.y + restoredBox.height / 2);
await page.locator(".stampEditor.selectedEditor").waitFor();
await removeSignature.waitFor();
await removeSignature.click();
await page.waitForFunction((n) => document.querySelectorAll(".annotationEditorLayer .stampEditor").length === n, initialStamps - 1);
await page.keyboard.press("ControlOrMeta+z");
await page.waitForFunction((n) => document.querySelectorAll(".annotationEditorLayer .stampEditor canvas").length === n, initialStamps);
assert.equal(await page.locator(".stampEditor.selectedEditor").count(), 0);

const boxForEscape = await stamps.first().boundingBox();
await page.mouse.click(boxForEscape.x + boxForEscape.width / 2, boxForEscape.y + boxForEscape.height / 2);
await page.locator(".stampEditor.selectedEditor").waitFor();
await page.keyboard.press("Escape");
assert.equal(await page.locator(".stampEditor.selectedEditor").count(), 0);
console.log("ok placed signatures can be selected, moved, resized, undone, and removed from Select mode");

// Stub the PDF viewer handoff in this renderer so printing cannot open a system dialog.
await page.evaluate(interceptPdfPrint);
await page.keyboard.press("ControlOrMeta+p");
Expand Down
19 changes: 15 additions & 4 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ import { SettingsDialog } from "./SettingsDialog";
import { ChangelogDialog } from "./ChangelogDialog";
import { PrintDialog } from "./PrintDialog";
import type { Release } from "./releaseNotes";
import { detectSignatureTargets, placeSignature, rememberSignature, uncoveredTargets, type SignatureImage, type SignatureTarget } from "./signatures";
import { detectSignatureTargets, enableSignatureEditing, placeSignature, rememberSignature, uncoveredTargets, type SignatureImage, type SignatureTarget } from "./signatures";
import { keepDrawingPointer } from "./drawing";
import { useOcrSearchRefresh } from "./hooks/ocr";
import { OcrSession, copyWithText, savedMessage } from "./lib/ocr";
Expand Down Expand Up @@ -233,6 +233,8 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs
const editRevision = useRef(0);
const markDirty = useCallback(() => { editRevision.current++; setDirty(true); }, []);
const [contentEditing, setContentEditing] = useState(false);
const contentEditingRef = useRef(false);
contentEditingRef.current = contentEditing;
const contentRef = useRef<ContentEditorHandle>(null);
const imageFile = useRef<HTMLInputElement>(null);
const imageLoad = useRef(0);
Expand Down Expand Up @@ -370,6 +372,12 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs
trackPageImages(eventBus);
const stopDrawingPointer = keepDrawingPointer(container);
const stopTextClickAway = finishTextOnClickAway(container, viewer, eventBus);
const stopSignatureEditing = enableSignatureEditing(container, viewer, eventBus, {
isBusy: () => placingSignature.current,
isContentEditing: () => contentEditingRef.current,
onSelectStart: () => { setHighlightMenu(null); setImageMenu(null); setPinned(null); },
onStampChanged: markDirty,
});
linkService.setViewer(viewer);
const history = new LinkHistory(viewer, (state, followed) => {
setNavigation(state);
Expand Down Expand Up @@ -443,7 +451,7 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs
});
};
container.addEventListener("wheel", onWheel, { passive: false });
return () => { stopTextClickAway(); stopDrawingPointer(); container.removeEventListener("wheel", onWheel); };
return () => { stopSignatureEditing(); stopTextClickAway(); stopDrawingPointer(); container.removeEventListener("wheel", onWheel); };
}, [tabs, tabKey]);

useEffect(() => {
Expand Down Expand Up @@ -879,7 +887,7 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs
if (toolRef.current !== "select" || e.button !== 0) return;
const current = document.getSelection();
if (current && !current.isCollapsed) return;
if ((e.target as HTMLElement).closest("a, .annotationCommentButton, .folio-content-layer")) return;
if ((e.target as HTMLElement).closest("a, .annotationCommentButton, .folio-content-layer, .stampEditor")) return;
const hit = markupRef.current?.markAt(e.clientX, e.clientY);
if (!hit) return setHighlightMenu(null);
const stage = container.parentElement!.getBoundingClientRect();
Expand All @@ -903,7 +911,7 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs
if (!container) return;
const onClick = (e: MouseEvent) => {
setImageMenu(null);
if ((e.target as Element).closest(".folio-content-layer")) return;
if ((e.target as Element).closest(".folio-content-layer, .stampEditor")) return;
if (toolRef.current !== "select" || e.button !== 0) return;
const current = document.getSelection();
if (current && !current.isCollapsed) return;
Expand Down Expand Up @@ -1353,6 +1361,9 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs
else if (noteBox) setNoteBox(null);
else if (searchOpen) setSearchOpen(false);
else if (contentRef.current?.deselect()) return;
else if (Number(viewerRef.current?.annotationEditorMode) === AnnotationEditorType.STAMP) {
viewerRef.current!.annotationEditorMode = { mode: AnnotationEditorType.NONE };
}
else if (contentEditing || tool !== "select") void leaveEditMode();
else if (focus) toggleFocus();
} else if (e.key === "f" || e.key === "F") {
Expand Down
133 changes: 132 additions & 1 deletion src/signatures.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { AnnotationEditorType } from "pdfjs-dist";
import type { PDFDocumentProxy } from "./pdf";
import type { PDFViewer } from "./viewer";
import type { EventBus, PDFViewer } from "./viewer";
import { printedSignatureTargets } from "./printedSignatureLines";

export interface SignatureImage { url: string; width: number; height: number }
Expand Down Expand Up @@ -95,6 +95,137 @@ export async function placeSignature(viewer: PDFViewer, pdf: PDFDocumentProxy, p
}
}

/**
* Lets readers click a placed signature in Select mode to move, resize, or remove it,
* and returns to normal reading/text selection when they click away, delete it, or press Escape.
*/
export function enableSignatureEditing(
container: HTMLElement,
viewer: PDFViewer,
eventBus: EventBus,
options: {
isBusy: () => boolean;
isContentEditing: () => boolean;
onSelectStart: () => void;
onStampChanged: () => void;
},
) {
let tracked = false;
let hasSelected = false;
let snapshot = "";

const stampSnapshot = () =>
Array.from(container.querySelectorAll<HTMLElement>(".annotationEditorLayer .stampEditor"),
el => `${el.id}:${el.style.left}:${el.style.top}:${el.style.width}:${el.style.height}`).join("|");

const checkChanged = () => {
const next = stampSnapshot();
if (next !== snapshot) {
snapshot = next;
options.onStampChanged();
}
};

const labelDeleteButtons = () => {
for (const button of container.querySelectorAll<HTMLButtonElement>(".stampEditor .editToolbar .deleteButton")) {
if (!button.getAttribute("aria-label")) button.setAttribute("aria-label", "Remove signature");
if (!button.title) button.title = "Remove signature";
}
};
const toolbarObserver = new MutationObserver(labelDeleteButtons);

const finish = () => {
if (!tracked) return;
tracked = false;
hasSelected = false;
toolbarObserver.disconnect();
checkChanged();
if (Number(viewer.annotationEditorMode) === AnnotationEditorType.STAMP && !options.isBusy()) {
viewer.annotationEditorMode = { mode: AnnotationEditorType.NONE };
}
};

const onPointerDown = (event: PointerEvent) => {
if (!event.isPrimary || event.button !== 0 || event.ctrlKey || options.isBusy()) return;
const target = event.target;
if (!(target instanceof Element)) return;
const mode = Number(viewer.annotationEditorMode);

if (mode === AnnotationEditorType.NONE) {
if (options.isContentEditing() || !container.contains(target) || target.closest(".editToolbar")) return;
const stamp = target.closest<HTMLElement>(".stampEditor");
if (!stamp?.id) return;
event.stopPropagation();
event.preventDefault();
options.onSelectStart();
tracked = true;
hasSelected = false;
snapshot = stampSnapshot();
toolbarObserver.observe(container, { childList: true, subtree: true });
(viewer as unknown as { annotationEditorMode: { mode: number; editId?: string } }).annotationEditorMode = {
mode: AnnotationEditorType.STAMP,
editId: stamp.id,
};
return;
}

if (mode === AnnotationEditorType.STAMP && tracked && !target.closest(".stampEditor")) {
finish();
}
};

const onEditingStatesChanged = ({ details }: { details?: { hasSelectedEditor?: boolean } }) => {
if (!tracked || options.isBusy() || Number(viewer.annotationEditorMode) !== AnnotationEditorType.STAMP) return;
checkChanged();
if (details?.hasSelectedEditor) {
hasSelected = true;
labelDeleteButtons();
} else if (hasSelected && details?.hasSelectedEditor === false) {
finish();
}
};

const onEditingAction = () => {
if (!tracked || options.isBusy()) return;
requestAnimationFrame(checkChanged);
};

const onModeChanged = ({ mode }: { mode: number }) => {
if (mode !== AnnotationEditorType.STAMP && tracked) {
tracked = false;
hasSelected = false;
toolbarObserver.disconnect();
checkChanged();
}
};

// After undoing a deleted stamp in Select mode, pdf.js finishes decoding the bitmap and calls
// div.focus(), which would otherwise leave a stamp selected with live resizers while mode is NONE.
const onFocusIn = (event: FocusEvent) => {
if (options.isBusy() || Number(viewer.annotationEditorMode) !== AnnotationEditorType.NONE) return;
const target = event.target;
if (!(target instanceof HTMLElement) || !container.contains(target)) return;
if (target.closest(".stampEditor")) {
event.stopPropagation();
target.blur();
}
};

container.addEventListener("focusin", onFocusIn, true);
document.addEventListener("pointerdown", onPointerDown, true);
eventBus.on("editingstateschanged", onEditingStatesChanged);
eventBus.on("editingaction", onEditingAction);
eventBus.on("annotationeditormodechanged", onModeChanged);
return () => {
toolbarObserver.disconnect();
container.removeEventListener("focusin", onFocusIn, true);
document.removeEventListener("pointerdown", onPointerDown, true);
eventBus.off("editingstateschanged", onEditingStatesChanged);
eventBus.off("editingaction", onEditingAction);
eventBus.off("annotationeditormodechanged", onModeChanged);
};
}

export function cleanSignature(source: HTMLCanvasElement, crop: number[], threshold: number): SignatureImage {
const canvas = document.createElement("canvas");
const factor = Math.min(1, 1200 / crop[2], 600 / crop[3]);
Expand Down
25 changes: 25 additions & 0 deletions src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,7 @@ kbd {

.viewer-container {
position: absolute;
isolation: isolate;
inset: 0;
overflow: auto;
outline: none;
Expand Down Expand Up @@ -1422,6 +1423,30 @@ kbd {
.signature-photo { overflow: hidden; border: 1px solid var(--line-strong); border-radius: 10px; background: white; }
.signature-crop canvas { display: block; max-width: 100%; max-height: 240px; margin: auto; touch-action: none; cursor: crosshair; }
.annotationEditorLayer.inkEditing { touch-action: none; }
/* Placed signatures stay clickable in Select mode (outside Edit mode) so readers can move, resize, or remove them. */
.app:not([data-content-edit]) .annotationEditorLayer.disabled.nonEditing .stampEditor {
pointer-events: auto;
cursor: grab;
}
/* Reset the 100px layer font-size inherited by button { font: inherit } so toolbar icons stay centered inside their buttons. */
.annotationEditorLayer .editToolbar {
font-size: 13px;
line-height: 1;
--editor-toolbar-bg-color: var(--surface);
--editor-toolbar-fg-color: var(--text);
--editor-toolbar-border-color: var(--line-strong);
--editor-toolbar-hover-bg-color: var(--hover);
--editor-toolbar-hover-fg-color: var(--text);
}
.annotationEditorLayer .editToolbar .buttons button {
display: inline-flex;
align-items: center;
justify-content: center;
}
/* Folio doesn't use pdf.js's alt-text dialog, so keep only the working Delete button on the stamp toolbar. */
.annotationEditorLayer .stampEditor .editToolbar :is(.altText, .altText + .divider) {
display: none;
}
.signature-range { display: flex; align-items: center; justify-content: space-between; gap: 12px; color: var(--text-2); font-size: 11px; }
.signature-range input { min-width: 0; width: 52%; accent-color: var(--accent); }
.signature-use { width: 100%; }
Expand Down
Loading