Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(pdf): restore signature drawing and stable dialog placement (#8308)

gbirmana1ba3ac98263
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 58cd3c83b6..ad583d61df 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -130,6 +130,13 @@ the startup bundle, and Lexical nodes.
- `src/features/block-channel`
- `src/features/block-pdf`
+## PDF markup
+
+Keep the signature canvas backing bitmap aligned with its CSS size and device
+pixel ratio; keep dialog centering separate from animated transforms. Verify the
+[signature walkthrough](../../docs/agent-guide/documents.md#pdf-signatures) after
+changing this editor.
+
## Notes
- Don't shy away from pulling good examples into context. In the case of solid-primtiives/kobalte try reading documentation, or just temp clone into /tmp to reference
diff --git a/apps/web/src/features/block-pdf/component/placeables/Signature.test.tsx b/apps/web/src/features/block-pdf/component/placeables/Signature.test.tsx
new file mode 100644
index 0000000000..9647bdbb4c
--- /dev/null
+++ b/apps/web/src/features/block-pdf/component/placeables/Signature.test.tsx
@@ -0,0 +1,210 @@
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { Portal } from 'solid-js/web';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { Signature } from './Signature';
+
+const state = vi.hoisted(() => ({
+ modify: vi.fn(() => true),
+ remove: vi.fn(),
+ clearDraft: vi.fn(),
+ clearActive: vi.fn(),
+}));
+
+vi.mock('@core/component/ScopedPortal', () => ({ ScopedPortal: Portal }));
+vi.mock('../../context/pdf-document-context', () => ({
+ usePdfDocument: () => ({
+ portalScope: () => 'global',
+ markup: {
+ commands: {
+ clearDraftIf: state.clearDraft,
+ clearActiveIf: state.clearActive,
+ },
+ },
+ }),
+}));
+vi.mock('../../context/pdf-viewer-context', () => ({
+ usePdfViewer: () => ({ rootElement: () => undefined }),
+}));
+vi.mock('../../store/placeables', () => ({
+ useModifyPayload: () => state.modify,
+ useDeletePlaceable: () => state.remove,
+}));
+vi.mock('../../../theme/signals/themeSignals', () => ({
+ resolvedThemeColors: () => ({ 'surface-0': { l: 1 } }),
+}));
+
+let canvasWidth = 400;
+let canvasHeight = 100;
+let resize: () => void;
+const context = {
+ scale: vi.fn(),
+ clearRect: vi.fn(),
+ fillRect: vi.fn(),
+ beginPath: vi.fn(),
+ closePath: vi.fn(),
+ moveTo: vi.fn(),
+ arc: vi.fn(),
+ fill: vi.fn(),
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ state.modify.mockReturnValue(true);
+ canvasWidth = 400;
+ canvasHeight = 100;
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(callback: () => void) {
+ resize = callback;
+ }
+ observe() {}
+ disconnect() {}
+ }
+ );
+ vi.stubGlobal('devicePixelRatio', 2);
+ vi.stubGlobal('scrollTo', vi.fn());
+ vi.stubGlobal(
+ 'PointerEvent',
+ class extends MouseEvent {
+ pointerId = 1;
+ pressure = 0.5;
+ }
+ );
+ vi.spyOn(
+ HTMLCanvasElement.prototype,
+ 'offsetWidth',
+ 'get'
+ ).mockImplementation(() => canvasWidth);
+ vi.spyOn(
+ HTMLCanvasElement.prototype,
+ 'offsetHeight',
+ 'get'
+ ).mockImplementation(() => canvasHeight);
+ vi.spyOn(
+ HTMLCanvasElement.prototype,
+ 'getBoundingClientRect'
+ ).mockImplementation(() => new DOMRect(0, 0, canvasWidth, canvasHeight));
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(
+ context as unknown as CanvasRenderingContext2D
+ );
+ vi.spyOn(HTMLCanvasElement.prototype, 'toDataURL').mockReturnValue(
+ 'data:image/png;base64,signature'
+ );
+});
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+function setup() {
+ const [isNew, setIsNew] = createSignal(true);
+ state.clearDraft.mockImplementation(() => setIsNew(false));
+ render(() => (
+ <Signature
+ id="signature-1"
+ base64={null}
+ isActive={true}
+ isNew={isNew()}
+ allowableEdits={{
+ allowResize: true,
+ allowTranslate: true,
+ allowRotate: true,
+ allowDelete: true,
+ lockAspectRatio: true,
+ }}
+ />
+ ));
+ const canvas = screen.getByRole('dialog').querySelector('canvas')!;
+ return { canvas };
+}
+
+function draw(canvas: HTMLCanvasElement) {
+ fireEvent.pointerDown(canvas, {
+ clientX: 300,
+ clientY: 60,
+ buttons: 1,
+ button: 0,
+ });
+ fireEvent.pointerMove(window, { clientX: 350, clientY: 70, buttons: 1 });
+ fireEvent.pointerUp(window, {
+ clientX: 375,
+ clientY: 80,
+ buttons: 0,
+ button: 0,
+ });
+}
+
+describe('PDF signature editor', () => {
+ it('draws using the displayed canvas dimensions and saves before closing', () => {
+ const { canvas } = setup();
+ expect(canvas.width).toBe(800);
+ expect(canvas.height).toBe(200);
+ expect(
+ screen.getByRole<HTMLButtonElement>('button', { name: 'Use signature' })
+ .disabled
+ ).toBe(true);
+ draw(canvas);
+ expect(context.arc).toHaveBeenCalled();
+ expect(context.scale).toHaveBeenCalledWith(2, 2);
+ fireEvent.click(screen.getByRole('button', { name: 'Use signature' }));
+ expect(state.modify).toHaveBeenCalledWith('signature-1', 'signature', {
+ base64: 'data:image/png;base64,signature',
+ });
+ expect(state.modify.mock.invocationCallOrder[0]).toBeLessThan(
+ state.clearDraft.mock.invocationCallOrder[0]
+ );
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(state.remove).not.toHaveBeenCalled();
+ });
+
+ it('retains the drawing when the dialog gets narrower', () => {
+ const { canvas } = setup();
+ draw(canvas);
+ context.arc.mockClear();
+ canvasWidth = 320;
+ canvasHeight = 80;
+ resize();
+ expect(canvas.width).toBe(640);
+ expect(canvas.height).toBe(160);
+ expect(context.arc).toHaveBeenCalledWith(
+ 240,
+ 48,
+ expect.any(Number),
+ 0,
+ 2 * Math.PI,
+ false
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Use signature' }));
+ expect(state.modify).toHaveBeenCalled();
+ });
+
+ it('discards a drawn draft when cancelled and clears its editor state', () => {
+ const { canvas } = setup();
+ draw(canvas);
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel signature' }));
+ expect(state.remove).toHaveBeenCalledExactlyOnceWith('signature-1');
+ expect(state.clearDraft).toHaveBeenCalledWith('signature-1');
+ expect(state.modify).not.toHaveBeenCalled();
+ expect(screen.queryByRole('dialog')).toBeNull();
+ });
+
+ it('discards an empty draft on Escape', () => {
+ setup();
+ fireEvent.keyDown(document, { key: 'Escape' });
+ expect(state.remove).toHaveBeenCalledExactlyOnceWith('signature-1');
+ expect(screen.queryByRole('dialog')).toBeNull();
+ });
+
+ it('keeps the drawing open if the placeable cannot be updated', () => {
+ const { canvas } = setup();
+ draw(canvas);
+ state.modify.mockReturnValue(false);
+ fireEvent.click(screen.getByRole('button', { name: 'Use signature' }));
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ expect(state.clearDraft).not.toHaveBeenCalled();
+ expect(state.remove).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/features/block-pdf/component/placeables/Signature.tsx b/apps/web/src/features/block-pdf/component/placeables/Signature.tsx
index bc37d7eee2..34ea3bab04 100644
--- a/apps/web/src/features/block-pdf/component/placeables/Signature.tsx
+++ b/apps/web/src/features/block-pdf/component/placeables/Signature.tsx
@@ -2,17 +2,9 @@ import { ScopedPortal } from '@core/component/ScopedPortal';
import Dialog from '@corvu/dialog';
import Check from '@phosphor/check.svg';
import Trash from '@phosphor/trash-simple.svg';
-import { createCallback } from '@solid-primitives/rootless';
import { Button, cn } from '@ui';
import SignaturePad from 'signature_pad';
-import {
- createMemo,
- createSignal,
- type JSX,
- onCleanup,
- onMount,
- Show,
-} from 'solid-js';
+import { createSignal, type JSX, onCleanup, onMount, Show } from 'solid-js';
import { resolvedThemeColors } from '../../../theme/signals/themeSignals';
import { usePdfDocument } from '../../context/pdf-document-context';
import { usePdfViewer } from '../../context/pdf-viewer-context';
@@ -36,40 +28,83 @@ function SignatureEditor(props: SignatureEditorProps) {
const rootElement = usePdfViewer().rootElement;
let canvasRef!: HTMLCanvasElement;
let signaturePad: SignaturePad | undefined;
+ let finished = false;
+ const [hasStrokes, setHasStrokes] = createSignal(false);
onMount(() => {
- signaturePad = new SignaturePad(canvasRef);
+ const pad = new SignaturePad(canvasRef);
+ signaturePad = pad;
+ let previousWidth = 0;
+ const resizeCanvas = () => {
+ const width = canvasRef.offsetWidth;
+ const height = canvasRef.offsetHeight;
+ if (!width || !height) return;
+ const ratio = Math.max(window.devicePixelRatio || 1, 1);
+ const data = pad.toData();
+ const scale = previousWidth ? width / previousWidth : 1;
+ // SignaturePad uses CSS coordinates; its backing bitmap must match them.
+ canvasRef.width = Math.round(width * ratio);
+ canvasRef.height = Math.round(height * ratio);
+ canvasRef.getContext('2d')?.scale(ratio, ratio);
+ pad.clear();
+ pad.fromData(
+ data.map((group) => ({
+ ...group,
+ points: group.points.map((point) => ({
+ ...point,
+ x: point.x * scale,
+ y: point.y * scale,
+ })),
+ }))
+ );
+ previousWidth = width;
+ };
+ resizeCanvas();
+ const observer = new ResizeObserver(resizeCanvas);
+ observer.observe(canvasRef);
+ const onEndStroke = () => setHasStrokes(!pad.isEmpty());
+ pad.addEventListener('endStroke', onEndStroke);
+ onCleanup(() => {
+ observer.disconnect();
+ pad.removeEventListener('endStroke', onEndStroke);
+ pad.off();
+ });
});
const modifyPayload = useModifyPayload();
const deletePlaceable = useDeletePlaceable();
- const updatePlaceable = createCallback((e: MouseEvent) => {
+ const cancel = () => {
+ if (finished) return;
+ finished = true;
+ deletePlaceable(props.id);
+ pdf.markup.commands.clearDraftIf(props.id);
+ };
+
+ const updatePlaceable = (e: MouseEvent | KeyboardEvent) => {
e.preventDefault();
e.stopPropagation();
+ if (!signaturePad || signaturePad.isEmpty()) return;
- pdf.markup.commands.clearDraftIf(props.id);
- pdf.markup.commands.clearActive();
-
- if (!signaturePad?.isEmpty()) {
- modifyPayload(props.id, PayloadMode.Signature, {
- base64: signaturePad?.toDataURL(),
- });
+ finished = true;
+ const updated = modifyPayload(props.id, PayloadMode.Signature, {
+ base64: signaturePad.toDataURL(),
+ });
+ if (!updated) {
+ finished = false;
+ return;
}
- });
+ pdf.markup.commands.clearDraftIf(props.id);
+ pdf.markup.commands.clearActiveIf(props.id);
+ };
- // ensure no empty signature boxes after signature modal is closed
- onCleanup(() => {
- if (signaturePad && !signaturePad.isEmpty()) return;
- deletePlaceable(props.id);
- });
+ // Discard unfinished drafts when the editor or its PDF is dismissed.
+ onCleanup(cancel);
// Anchor the editor to the center of the active block rather than the
// viewport, so the signature canvas appears over the PDF block it belongs to
// (which may not be the only thing on screen).
- const [blockRect, setBlockRect] = createSignal<DOMRect | undefined>(
- undefined
- );
+ const [blockRect, setBlockRect] = createSignal<DOMRect>();
onMount(() => {
const el = rootElement();
@@ -86,29 +121,33 @@ function SignatureEditor(props: SignatureEditorProps) {
onCleanup(() => observer.disconnect());
});
- const positionStyle = createMemo<JSX.CSSProperties>(() => {
+ const positionStyle = (): JSX.CSSProperties => {
const rect = blockRect();
if (rect) {
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
return {
- position: 'absolute',
+ position: 'fixed',
top: `${centerY}px`,
left: `${centerX}px`,
- transform: 'translate(-50%, -50%)',
+ translate: '-50% -50%',
+ 'max-width': `min(calc(100vw - 2rem), calc(${rect.width}px - 2rem))`,
};
}
return {
- position: 'absolute',
+ position: 'fixed',
top: '50%',
left: '50%',
- transform: 'translate(-50%, -50%)',
+ translate: '-50% -50%',
};
- });
+ };
return (
<Dialog
open={true}
+ onOpenChange={(open) => {
+ if (!open) cancel();
+ }}
restoreFocus={false}
// prevents the dialog from immediately being dismissed
closeOnOutsidePointerStrategy="pointerdown"
@@ -126,8 +165,7 @@ function SignatureEditor(props: SignatureEditorProps) {
/>
<Dialog.Content
class={cn(
- 'absolute z-modal min-w-[calc(100vw-2rem)]',
- '@sm:min-w-96 p-3',
+ 'fixed z-modal w-[426px] max-w-[calc(100vw-2rem)] p-3',
'bg-surface shadow',
'rounded-lg border border-edge',
'flex-col justify-start inline-flex gap-3',
@@ -135,12 +173,16 @@ function SignatureEditor(props: SignatureEditorProps) {
)}
style={positionStyle()}
>
+ <Dialog.Label class="sr-only">Draw signature</Dialog.Label>
<canvas
+ aria-label="Signature drawing area"
+ class="block w-full aspect-[4/1]"
width={400}
height={100}
ref={canvasRef}
// SCUFFED THEMING TODO: this filter is janky af, checks if it's a "darkish" or "lightish" theme, we should handle this better
style={{
+ height: 'auto',
filter:
resolvedThemeColors()['surface-0'].l < 0.5
? 'invert(1)'
@@ -151,18 +193,17 @@ function SignatureEditor(props: SignatureEditorProps) {
<Button
variant="ghost"
size="icon-md"
- onClick={(e: MouseEvent | KeyboardEvent) =>
- updatePlaceable(e as MouseEvent)
- }
+ label="Use signature"
+ disabled={!hasStrokes()}
+ onClick={updatePlaceable}
>
<Check />
</Button>
<Button
variant="ghost"
size="icon-md"
- onClick={() => {
- deletePlaceable(props.id);
- }}
+ label="Cancel signature"
+ onClick={cancel}
>
<Trash />
</Button>
diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.md
index ab3ddea6f1..58d5b98e69 100644
--- a/docs/agent-guide/documents.md
+++ b/docs/agent-guide/documents.md
@@ -2675,6 +2675,22 @@ highlight; deleting a placeable's discussion removes the placeable. An anchor bo
to a legacy annotation thread that was never imported stays hidden rather than
shown as a bare highlight.
+## PDF signatures
+
+Choose **Signature** in the PDF toolbar, then click the page where it should go.
+The **Draw signature** dialog opens over the active PDF. Drag across the canvas
+with a mouse, pen, or finger; **Use signature** becomes available after drawing.
+Confirm to place the signature, then drag it to adjust its position. **Cancel
+signature**, Escape, or clicking outside discards the unfinished placement.
+Signatures are saved into that PDF through its normal save flow; reusable saved
+signatures are not available yet.
+
+When verifying this flow, draw near the right and bottom edges as well as the
+center. Check at desktop and phone widths and at 2x pixel density; strokes should
+stay under the pointer, survive resizing, and appear on the PDF after confirming.
+Reopen the dialog and verify it stays centered during its opening animation and
+starts with an empty canvas. Cancelling must leave no empty signature box.
+
## Word (DOCX) editor
When `enable-docx-editor` is on, uploaded `.docx` files open at