Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

fix(part11): prevent side-by-side signature manifestations from overlapping (#220)

Kevin Rose09d5d2e1aeb9
diff --git a/src/lib/services/pdf-finalize.test.ts b/src/lib/services/pdf-finalize.test.ts
index 29601b1..86bf565 100644
--- a/src/lib/services/pdf-finalize.test.ts
+++ b/src/lib/services/pdf-finalize.test.ts
@@ -694,6 +694,7 @@ async function extractTextItems(pdfBytes: Uint8Array) {
const content = await page.getTextContent();
const items = (
content.items as Array<{
+ height?: number;
str?: string;
transform?: number[];
width?: number;
@@ -701,6 +702,7 @@ async function extractTextItems(pdfBytes: Uint8Array) {
)
.filter((item) => item.str && item.transform)
.map((item) => ({
+ height: item.height ?? 0,
left: item.transform![4]!,
right: item.transform![4]! + (item.width ?? 0),
text: item.str!,
@@ -1082,3 +1084,578 @@ test("the new wording leaves the audit fingerprint of a captured email unchanged
"876cbd8661559c69681db5458f3baf2f8e1c8ccc4c43c9352691608e68b61c32",
);
});
+
+type ExtractedTextItem = Awaited<ReturnType<typeof extractTextItems>>[number];
+
+function itemBoxesOverlap2D(
+ left: ExtractedTextItem,
+ right: ExtractedTextItem,
+): boolean {
+ const leftBottom = left.y;
+ const leftTop = left.y + left.height;
+ const rightBottom = right.y;
+ const rightTop = right.y + right.height;
+
+ return (
+ left.left < right.right &&
+ left.right > right.left &&
+ leftBottom < rightTop &&
+ leftTop > rightBottom
+ );
+}
+
+function assertItemInsideLetterPage(item: ExtractedTextItem) {
+ assert.ok(
+ item.left >= 0,
+ `"${item.text}" starts left of page (${item.left})`,
+ );
+ assert.ok(
+ item.right <= LETTER_PAGE.widthPt,
+ `"${item.text}" runs past right edge (${item.right})`,
+ );
+ assert.ok(item.y >= 0, `"${item.text}" sits below bottom edge (${item.y})`);
+ assert.ok(
+ item.y + item.height <= LETTER_PAGE.heightPt,
+ `"${item.text}" runs past top edge (${item.y + item.height})`,
+ );
+}
+
+function assertNoPairwiseOverlap(
+ groups: ReadonlyArray<{ items: readonly ExtractedTextItem[]; label: string }>,
+) {
+ for (let i = 0; i < groups.length; i += 1) {
+ for (let j = i + 1; j < groups.length; j += 1) {
+ for (const left of groups[i]!.items) {
+ for (const right of groups[j]!.items) {
+ assert.equal(
+ itemBoxesOverlap2D(left, right),
+ false,
+ `${groups[i]!.label} ("${left.text}" [${left.left.toFixed(2)}..${left.right.toFixed(2)}, ${left.y.toFixed(2)}..${(left.y + left.height).toFixed(2)}]) overlaps ${groups[j]!.label} ("${right.text}" [${right.left.toFixed(2)}..${right.right.toFixed(2)}, ${right.y.toFixed(2)}..${(right.y + right.height).toFixed(2)}])`,
+ );
+ }
+ }
+ }
+ }
+}
+
+async function renderPart11Scenario(input: {
+ extraFields?: FieldRecord[];
+ signatures: Array<{
+ height?: number;
+ id: string;
+ meaning: "approval" | "authorship" | "responsibility" | "review";
+ name: string;
+ signedAt?: number;
+ width?: number;
+ x: number;
+ y: number;
+ }>;
+}) {
+ const fixture = await makeFixture();
+ const signedAt = Date.UTC(2026, 10, 22, 14, 30, 0) / 1000;
+ const envelope: EnvelopeRecord = {
+ ...fixture.envelope,
+ completedAt: signedAt,
+ part11: true,
+ };
+ const signers: SignerRecord[] = input.signatures.map((entry, index) => ({
+ createdAt: signedAt - 500,
+ email: `signer-${String(index + 1)}@example.com`,
+ id: `part11-signer-${String(index + 1)}`,
+ name: entry.name,
+ signatureMeaning: entry.meaning,
+ signedAt: entry.signedAt ?? signedAt,
+ signOrder: index + 1,
+ status: "signed",
+ updatedAt: entry.signedAt ?? signedAt,
+ }));
+ const signatureFields: FieldRecord[] = input.signatures.map(
+ (entry, index) => ({
+ createdAt: signedAt - 500,
+ envelopeId: envelope.id,
+ height: entry.height ?? 0.07,
+ id: entry.id,
+ inputMethod: "typed",
+ page: 1,
+ required: true,
+ signerId: `part11-signer-${String(index + 1)}`,
+ submittedAt: entry.signedAt ?? signedAt,
+ type: "signature",
+ updatedAt: entry.signedAt ?? signedAt,
+ value: entry.name,
+ width: entry.width ?? 0.24,
+ x: entry.x,
+ y: entry.y,
+ }),
+ );
+ const pdfBytes = await renderFinalizedEnvelopePdf(
+ {
+ auditEvents: fixture.auditEvents,
+ completedAt: signedAt,
+ envelope,
+ fields: [...signatureFields, ...(input.extraFields ?? [])],
+ pages: [LETTER_PAGE],
+ signers,
+ sourcePdfKey: envelope.sourcePdfKey,
+ },
+ { seal: saveUnsealed, storageService: fixture.storageService },
+ );
+
+ return (await extractTextItems(pdfBytes)).filter(
+ (item) => item.text.trim().length > 0,
+ );
+}
+
+test("side-by-side Part 11 signature manifestations do not overlap (issue #220)", async () => {
+ const alice = "Alice Alexander Example-Smythe";
+ const bob = "Bob Bartholomew Example-Jones";
+
+ for (const reverseOrder of [false, true]) {
+ const signatures = [
+ {
+ id: "sig-alice",
+ meaning: "approval" as const,
+ name: alice,
+ width: 0.24,
+ x: 0.1,
+ y: 0.5,
+ },
+ {
+ id: "sig-bob",
+ meaning: "review" as const,
+ name: bob,
+ width: 0.24,
+ x: 0.4,
+ y: 0.5,
+ },
+ ];
+ const items = await renderPart11Scenario({
+ signatures: reverseOrder ? [...signatures].reverse() : signatures,
+ });
+ // Typed signature values sit at ~11-12 pt; manifestations are drawn at <= 6.5 pt.
+ const manifestationItems = items.filter((item) => item.height <= 7);
+ const signatureItems = items.filter((item) => item.height > 7);
+ const aliceManifestation = manifestationItems.filter(
+ (item) => item.left < 0.4 * LETTER_PAGE.widthPt - 1,
+ );
+ const bobManifestation = manifestationItems.filter(
+ (item) => item.left >= 0.4 * LETTER_PAGE.widthPt - 1,
+ );
+
+ assert.ok(aliceManifestation.length >= 2);
+ assert.ok(bobManifestation.length >= 1);
+
+ for (const item of manifestationItems) {
+ assertItemInsideLetterPage(item);
+ assert.ok(
+ item.height >= 5,
+ `"${item.text}" shrunk below readable size (${item.height})`,
+ );
+ }
+
+ assertNoPairwiseOverlap([
+ { items: aliceManifestation, label: "Alice manifestation" },
+ { items: bobManifestation, label: "Bob manifestation" },
+ { items: signatureItems, label: "Signature values" },
+ ]);
+
+ const aliceText = aliceManifestation
+ .map((item) => item.text)
+ .join(" ")
+ .replace(/\s+/g, " ");
+ const bobText = bobManifestation
+ .map((item) => item.text)
+ .join(" ")
+ .replace(/\s+/g, " ");
+
+ assert.ok(aliceText.includes(`Signed by ${alice}`), aliceText);
+ assert.ok(aliceText.includes("2026-11-22 14:30:00 UTC"), aliceText);
+ assert.ok(aliceText.includes("Meaning: Approval"), aliceText);
+
+ assert.ok(bobText.includes(`Signed by ${bob}`), bobText);
+ assert.ok(bobText.includes("2026-11-22 14:30:00 UTC"), bobText);
+ assert.ok(bobText.includes("Meaning: Review"), bobText);
+ }
+});
+
+test("three narrow side-by-side Part 11 signatures wrap cleanly without overlapping (issue #220)", async () => {
+ const columns = [
+ {
+ id: "sig-1",
+ meaning: "authorship" as const,
+ name: "Alice Alexander Example-Smythe",
+ width: 0.18,
+ x: 0.05,
+ y: 0.5,
+ },
+ {
+ id: "sig-2",
+ meaning: "review" as const,
+ name: "Bob Bartholomew Example-Jones",
+ width: 0.18,
+ x: 0.28,
+ y: 0.5,
+ },
+ {
+ id: "sig-3",
+ meaning: "approval" as const,
+ name: "Charlotte Christina Example-Montgomery",
+ width: 0.18,
+ x: 0.51,
+ y: 0.5,
+ },
+ ];
+ const items = await renderPart11Scenario({ signatures: columns });
+ const manifestationItems = items.filter((item) => item.height <= 7);
+ const signatureItems = items.filter((item) => item.height > 7);
+ const col1 = manifestationItems.filter(
+ (item) => item.left < 0.28 * LETTER_PAGE.widthPt - 1,
+ );
+ const col2 = manifestationItems.filter(
+ (item) =>
+ item.left >= 0.28 * LETTER_PAGE.widthPt - 1 &&
+ item.left < 0.51 * LETTER_PAGE.widthPt - 1,
+ );
+ const col3 = manifestationItems.filter(
+ (item) => item.left >= 0.51 * LETTER_PAGE.widthPt - 1,
+ );
+
+ assert.ok(col1.length >= 3);
+ assert.ok(col2.length >= 3);
+ assert.ok(col3.length >= 1);
+
+ for (const item of manifestationItems) {
+ assertItemInsideLetterPage(item);
+ assert.ok(
+ item.height >= 5,
+ `"${item.text}" shrunk below readable size (${item.height})`,
+ );
+ }
+
+ assertNoPairwiseOverlap([
+ { items: col1, label: "Column 1 manifestation" },
+ { items: col2, label: "Column 2 manifestation" },
+ { items: col3, label: "Column 3 manifestation" },
+ { items: signatureItems, label: "Signature values" },
+ ]);
+
+ const joinText = (group: readonly ExtractedTextItem[]) =>
+ group
+ .map((item) => item.text)
+ .join(" ")
+ .replace(/\s+/g, " ");
+
+ assert.ok(
+ joinText(col1).includes("Signed by Alice Alexander Example-Smythe"),
+ );
+ assert.ok(joinText(col1).includes("2026-11-22 14:30:00 UTC"));
+ assert.ok(joinText(col1).includes("Meaning: Authorship"));
+
+ assert.ok(joinText(col2).includes("Signed by Bob Bartholomew Example-Jones"));
+ assert.ok(joinText(col2).includes("2026-11-22 14:30:00 UTC"));
+ assert.ok(joinText(col2).includes("Meaning: Review"));
+
+ assert.ok(
+ joinText(col3).includes("Signed by Charlotte Christina Example-Montgomery"),
+ );
+ assert.ok(joinText(col3).includes("2026-11-22 14:30:00 UTC"));
+ assert.ok(joinText(col3).includes("Meaning: Approval"));
+});
+
+test("a Part 11 signature near the right margin wraps inside the page under its box", async () => {
+ const name = "Alice Alexander Example-Smythe";
+ const items = await renderPart11Scenario({
+ signatures: [
+ {
+ id: "sig-right",
+ meaning: "approval",
+ name,
+ width: 0.24,
+ x: 0.72,
+ y: 0.5,
+ },
+ ],
+ });
+ const manifestationItems = items.filter((item) => item.height <= 7);
+ const fieldLeft = 0.72 * LETTER_PAGE.widthPt;
+
+ assert.ok(manifestationItems.length >= 2);
+
+ for (const item of manifestationItems) {
+ assertItemInsideLetterPage(item);
+ assert.ok(
+ item.left >= fieldLeft - 0.5,
+ `"${item.text}" drifted left of its field (${item.left} < ${fieldLeft})`,
+ );
+ assert.ok(item.height >= 5);
+ }
+
+ const joined = manifestationItems
+ .map((item) => item.text)
+ .join(" ")
+ .replace(/\s+/g, " ");
+
+ assert.ok(joined.includes(`Signed by ${name}`), joined);
+ assert.ok(joined.includes("2026-11-22 14:30:00 UTC"), joined);
+ assert.ok(joined.includes("Meaning: Approval"), joined);
+});
+
+test("Part 11 signatures near the bottom of the page stay inside bounds without overlapping", async () => {
+ const alice = "Alice Alexander Example-Smythe";
+ const bob = "Bob Bartholomew Example-Jones";
+
+ for (const [y, height] of [
+ [0.93, 0.06],
+ [0.9, 0.07],
+ ] as const) {
+ const items = await renderPart11Scenario({
+ signatures: [
+ {
+ height,
+ id: "sig-bottom-1",
+ meaning: "approval",
+ name: alice,
+ width: 0.24,
+ x: 0.1,
+ y,
+ },
+ {
+ height,
+ id: "sig-bottom-2",
+ meaning: "review",
+ name: bob,
+ width: 0.24,
+ x: 0.4,
+ y,
+ },
+ ],
+ });
+ const manifestationItems = items.filter((item) => item.height <= 7);
+ const signatureItems = items.filter((item) => item.height > 7);
+ const aliceManifestation = manifestationItems.filter(
+ (item) => item.left < 0.4 * LETTER_PAGE.widthPt - 1,
+ );
+ const bobManifestation = manifestationItems.filter(
+ (item) => item.left >= 0.4 * LETTER_PAGE.widthPt - 1,
+ );
+
+ assert.ok(aliceManifestation.length >= 2);
+ assert.ok(bobManifestation.length >= 1);
+
+ for (const item of manifestationItems) {
+ assertItemInsideLetterPage(item);
+ assert.ok(item.height >= 5);
+ }
+
+ assertNoPairwiseOverlap([
+ { items: aliceManifestation, label: "Alice bottom manifestation" },
+ { items: bobManifestation, label: "Bob bottom manifestation" },
+ { items: signatureItems, label: "Bottom signature values" },
+ ]);
+
+ const aliceText = aliceManifestation
+ .map((item) => item.text)
+ .join(" ")
+ .replace(/\s+/g, " ");
+ const bobText = bobManifestation
+ .map((item) => item.text)
+ .join(" ")
+ .replace(/\s+/g, " ");
+
+ assert.ok(aliceText.includes(`Signed by ${alice}`), aliceText);
+ assert.ok(aliceText.includes("2026-11-22 14:30:00 UTC"), aliceText);
+ assert.ok(aliceText.includes("Meaning: Approval"), aliceText);
+ assert.ok(bobText.includes(`Signed by ${bob}`), bobText);
+ assert.ok(bobText.includes("2026-11-22 14:30:00 UTC"), bobText);
+ assert.ok(bobText.includes("Meaning: Review"), bobText);
+ }
+});
+
+test("separate-row Part 11 signatures keep clean single-line manifestations", async () => {
+ const alice = "Alice Alexander Example-Smythe";
+ const bob = "Bob Bartholomew Example-Jones";
+ const items = await renderPart11Scenario({
+ signatures: [
+ {
+ id: "sig-row-1",
+ meaning: "approval",
+ name: alice,
+ width: 0.24,
+ x: 0.1,
+ y: 0.5,
+ },
+ {
+ id: "sig-row-2",
+ meaning: "review",
+ name: bob,
+ width: 0.24,
+ x: 0.1,
+ y: 0.7,
+ },
+ ],
+ });
+ const manifestationItems = items.filter((item) => item.height <= 7);
+
+ assert.equal(manifestationItems.length, 2);
+ for (const item of manifestationItems) {
+ assertItemInsideLetterPage(item);
+ assert.equal(item.height, 6.5);
+ }
+
+ assertNoPairwiseOverlap([
+ { items: [manifestationItems[0]!], label: "Row 1 manifestation" },
+ { items: [manifestationItems[1]!], label: "Row 2 manifestation" },
+ ]);
+
+ const texts = manifestationItems.map((item) => item.text);
+
+ assert.ok(
+ texts.includes(
+ `Signed by ${alice} | 2026-11-22 14:30:00 UTC | Meaning: Approval`,
+ ),
+ );
+ assert.ok(
+ texts.includes(
+ `Signed by ${bob} | 2026-11-22 14:30:00 UTC | Meaning: Review`,
+ ),
+ );
+});
+
+test("staggered Part 11 signatures and adjacent date fields do not collide with manifestations", async () => {
+ const signedAt = Date.UTC(2026, 10, 22, 14, 30, 0) / 1000;
+ const items = await renderPart11Scenario({
+ extraFields: [
+ {
+ createdAt: signedAt - 500,
+ envelopeId: "envelope-1",
+ height: 0.05,
+ id: "date-adjacent",
+ page: 1,
+ required: true,
+ signerId: "part11-signer-2",
+ submittedAt: signedAt,
+ type: "date",
+ updatedAt: signedAt,
+ value: "2026-11-22",
+ width: 0.2,
+ x: 0.68,
+ y: 0.54,
+ },
+ ],
+ signatures: [
+ {
+ id: "sig-stagger-1",
+ meaning: "approval",
+ name: "Alice Alexander Example-Smythe",
+ width: 0.24,
+ x: 0.1,
+ y: 0.5,
+ },
+ {
+ id: "sig-stagger-2",
+ meaning: "review",
+ name: "Bob Bartholomew Example-Jones",
+ width: 0.24,
+ x: 0.4,
+ y: 0.515,
+ },
+ ],
+ });
+ const dateItems = items.filter((item) => item.text === "2026-11-22");
+ const manifestationItems = items.filter(
+ (item) => item.height <= 7 && item.text !== "2026-11-22",
+ );
+ const signatureItems = items.filter(
+ (item) => item.height > 7 && item.text !== "2026-11-22",
+ );
+ const aliceManifestation = manifestationItems.filter(
+ (item) => item.left < 0.4 * LETTER_PAGE.widthPt - 1,
+ );
+ const bobManifestation = manifestationItems.filter(
+ (item) => item.left >= 0.4 * LETTER_PAGE.widthPt - 1,
+ );
+
+ assert.equal(dateItems.length, 1);
+ assert.ok(aliceManifestation.length >= 2);
+ assert.ok(bobManifestation.length >= 2);
+
+ for (const item of manifestationItems) {
+ assertItemInsideLetterPage(item);
+ assert.ok(item.height >= 5);
+ }
+
+ assertNoPairwiseOverlap([
+ { items: aliceManifestation, label: "Alice staggered manifestation" },
+ { items: bobManifestation, label: "Bob staggered manifestation" },
+ { items: signatureItems, label: "Staggered signature values" },
+ { items: dateItems, label: "Adjacent date field" },
+ ]);
+});
+
+test("touching side-by-side Part 11 signatures with long unbroken names keep a clean gutter and full text", async () => {
+ const longUnbroken = "Alexandrina-Constantinopoulos-Montgomery-Fitzgerald";
+ const bob = "Bob Bartholomew Example-Jones";
+ // Field 1 ends at x = 0.28 and Field 2 starts immediately at x = 0.28 (0 pt gap).
+ const items = await renderPart11Scenario({
+ signatures: [
+ {
+ id: "sig-touch-1",
+ meaning: "responsibility",
+ name: longUnbroken,
+ width: 0.18,
+ x: 0.1,
+ y: 0.5,
+ },
+ {
+ id: "sig-touch-2",
+ meaning: "approval",
+ name: bob,
+ width: 0.18,
+ x: 0.28,
+ y: 0.5,
+ },
+ ],
+ });
+ const manifestationItems = items.filter((item) => item.height <= 7);
+ const signatureItems = items.filter((item) => item.height > 7);
+ const boundary = 0.28 * LETTER_PAGE.widthPt;
+ const firstManifestation = manifestationItems.filter(
+ (item) => item.left < boundary - 1,
+ );
+ const secondManifestation = manifestationItems.filter(
+ (item) => item.left >= boundary - 1,
+ );
+
+ assert.ok(firstManifestation.length >= 4);
+ assert.ok(secondManifestation.length >= 1);
+
+ for (const item of manifestationItems) {
+ assertItemInsideLetterPage(item);
+ assert.ok(item.height >= 5);
+ }
+
+ // Every line of the left manifestation stops strictly left of the right signature.
+ for (const item of firstManifestation) {
+ assert.ok(
+ item.right < boundary,
+ `"${item.text}" crossed into the adjacent column (${item.right} >= ${boundary})`,
+ );
+ }
+
+ assertNoPairwiseOverlap([
+ { items: firstManifestation, label: "First touching manifestation" },
+ { items: secondManifestation, label: "Second touching manifestation" },
+ { items: signatureItems, label: "Touching signature values" },
+ ]);
+
+ // Every character of the unbroken name, UTC timestamp, and meaning is kept.
+ const firstCompact = firstManifestation.map((item) => item.text).join("");
+ const firstSpaced = firstManifestation
+ .map((item) => item.text)
+ .join(" ")
+ .replace(/\s+/g, " ");
+
+ assert.ok(firstCompact.includes(longUnbroken), firstCompact);
+ assert.ok(firstSpaced.includes("2026-11-22 14:30:00 UTC"), firstSpaced);
+ assert.ok(firstSpaced.includes("Meaning: Responsibility"), firstSpaced);
+});
diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.ts
index d16d880..53cbd10 100644
--- a/src/lib/services/pdf-finalize.ts
+++ b/src/lib/services/pdf-finalize.ts
@@ -887,72 +887,464 @@ async function drawFieldValue(
}
}
+const MANIFESTATION_MARGIN_PT = 2;
+const MANIFESTATION_GUTTER_PT = 8;
+const MANIFESTATION_VERTICAL_CLEARANCE_PT = 2;
+const MANIFESTATION_PREFERRED_SIZE_PT = 6.5;
+const MANIFESTATION_MIN_READABLE_SIZE_PT = 5;
+const MANIFESTATION_LAST_RESORT_SIZE_PT = 0.5;
+const MANIFESTATION_LINE_GAP_PT = 1.5;
+
+type PageBox = {
+ bottom: number;
+ left: number;
+ right: number;
+ top: number;
+};
+
+type ManifestationTextLayout = {
+ fitsHeight: boolean;
+ fitsWidth: boolean;
+ lineHeight: number;
+ lines: string[];
+ maxLineWidth: number;
+ size: number;
+};
+
+type PlacedManifestation = {
+ box: PageBox;
+ collidesWithManifestation: boolean;
+ fitsOnPage: boolean;
+ hasCollision: boolean;
+ lineHeight: number;
+ lines: string[];
+ size: number;
+ topBaseline: number;
+ x: number;
+};
+
+type PageManifestationTarget = {
+ field: FieldRecord;
+ rect: { heightPt: number; widthPt: number; xPt: number; yPt: number };
+ text: string;
+};
+
+function rectToPageBox(rect: {
+ heightPt: number;
+ widthPt: number;
+ xPt: number;
+ yPt: number;
+}): PageBox {
+ return {
+ bottom: rect.yPt,
+ left: rect.xPt,
+ right: rect.xPt + rect.widthPt,
+ top: rect.yPt + rect.heightPt,
+ };
+}
+
+function boxesOverlap(
+ left: PageBox,
+ right: PageBox,
+ padX = 0,
+ padY = 0,
+): boolean {
+ return (
+ left.left < right.right + padX &&
+ left.right + padX > right.left &&
+ left.bottom < right.top + padY &&
+ left.top + padY > right.bottom
+ );
+}
+
+function manifestationLineHeight(size: number): number {
+ return size + Math.min(MANIFESTATION_LINE_GAP_PT, size * 0.3);
+}
+
+function manifestationRequiredHeight(lineCount: number, size: number): number {
+ return lineCount * manifestationLineHeight(size) + size * 0.25;
+}
+
+function measureManifestationLayout(
+ font: TextFace,
+ lines: string[],
+ size: number,
+ maxWidth: number,
+ maxHeight: number,
+): ManifestationTextLayout {
+ const lineHeight = manifestationLineHeight(size);
+ const maxLineWidth = lines.reduce(
+ (widest, line) => Math.max(widest, font.widthOfTextAtSize(line, size)),
+ 0,
+ );
+
+ return {
+ fitsHeight: manifestationRequiredHeight(lines.length, size) <= maxHeight,
+ fitsWidth: maxLineWidth <= maxWidth,
+ lineHeight,
+ lines,
+ maxLineWidth,
+ size,
+ };
+}
+
+function layoutManifestationText(
+ font: TextFace,
+ text: string,
+ maxWidth: number,
+ maxHeight: number,
+ options: { allowVerticalShrink?: boolean } = {},
+): ManifestationTextLayout {
+ const allowVerticalShrink = options.allowVerticalShrink ?? false;
+ const parts = text.split(" | ");
+
+ // One line when it fits at a readable size, preserving the single-line
+ // manifestation whenever there is horizontal room.
+ const oneLineSize = fitTextSize(
+ font,
+ text,
+ maxWidth,
+ 7,
+ MANIFESTATION_PREFERRED_SIZE_PT,
+ );
+
+ if (oneLineSize >= MANIFESTATION_MIN_READABLE_SIZE_PT) {
+ const candidate = measureManifestationLayout(
+ font,
+ [text],
+ oneLineSize,
+ maxWidth,
+ maxHeight,
+ );
+
+ if (candidate.fitsWidth && (!allowVerticalShrink || candidate.fitsHeight)) {
+ return candidate;
+ }
+ }
+
+ // One line per part (name, UTC time, meaning) when every part fits whole
+ // inside maxWidth at a readable size.
+ const partsSize = Math.min(
+ ...parts.map((part) =>
+ fitTextSize(font, part, maxWidth, 7, MANIFESTATION_PREFERRED_SIZE_PT),
+ ),
+ );
+
+ if (partsSize >= MANIFESTATION_MIN_READABLE_SIZE_PT) {
+ const candidate = measureManifestationLayout(
+ font,
+ parts,
+ partsSize,
+ maxWidth,
+ maxHeight,
+ );
+
+ if (candidate.fitsWidth && (!allowVerticalShrink || candidate.fitsHeight)) {
+ return candidate;
+ }
+ }
+
+ // Wrap each part independently inside maxWidth at the largest readable
+ // size that fits, so long names or narrow columns never overflow or lose
+ // text.
+ let firstWidthFit: ManifestationTextLayout | null = null;
+
+ for (
+ let size = MANIFESTATION_PREFERRED_SIZE_PT;
+ size >= MANIFESTATION_MIN_READABLE_SIZE_PT;
+ size -= 0.5
+ ) {
+ const wrapped = parts.flatMap((part) =>
+ wrapFieldText(font, size, maxWidth, part),
+ );
+ const candidate = measureManifestationLayout(
+ font,
+ wrapped,
+ size,
+ maxWidth,
+ maxHeight,
+ );
+
+ if (candidate.fitsWidth) {
+ if (!firstWidthFit) {
+ firstWidthFit = candidate;
+ }
+
+ if (candidate.fitsHeight) {
+ return candidate;
+ }
+ }
+ }
+
+ if (firstWidthFit && !allowVerticalShrink) {
+ return firstWidthFit;
+ }
+
+ // Last resort: shrink below the readable floor only when a single glyph
+ // exceeds maxWidth or neither side of the field can fit the wrapped block
+ // at a readable size, so nothing is ever clipped or truncated.
+ let fallback =
+ firstWidthFit ??
+ measureManifestationLayout(
+ font,
+ parts.flatMap((part) =>
+ wrapFieldText(font, MANIFESTATION_MIN_READABLE_SIZE_PT, maxWidth, part),
+ ),
+ MANIFESTATION_MIN_READABLE_SIZE_PT,
+ maxWidth,
+ maxHeight,
+ );
+
+ for (
+ let size = MANIFESTATION_MIN_READABLE_SIZE_PT - 0.5;
+ size >= 0.01;
+ size = size > MANIFESTATION_LAST_RESORT_SIZE_PT ? size - 0.5 : size / 2
+ ) {
+ const wrapped = parts.flatMap((part) =>
+ wrapFieldText(font, size, maxWidth, part),
+ );
+ const candidate = measureManifestationLayout(
+ font,
+ wrapped,
+ size,
+ maxWidth,
+ maxHeight,
+ );
+
+ fallback = candidate;
+
+ if (candidate.fitsWidth && (!allowVerticalShrink || candidate.fitsHeight)) {
+ return candidate;
+ }
+ }
+
+ return fallback;
+}
+
+/**
+ * Lays out every Part 11 signature manifestation on one page so neighboring
+ * fields and side-by-side manifestations never overlap each other or run past
+ * the page edge (issue #220).
+ */
+function layoutPageManifestations(
+ targets: readonly PageManifestationTarget[],
+ allFieldBoxes: readonly { box: PageBox; field: FieldRecord }[],
+ geometry: DisplayedPageGeometry,
+ font: TextFace,
+): Map<FieldRecord, PlacedManifestation> {
+ const margin = Math.min(
+ MANIFESTATION_MARGIN_PT,
+ geometry.widthPt / 4,
+ geometry.heightPt / 4,
+ );
+ const pageRight = geometry.widthPt - margin;
+ const pageTop = geometry.heightPt - margin;
+
+ // Rightmost signatures go first so every manifestation to the right has its
+ // final bounding box before a signature to its left computes its available
+ // horizontal width. Ties at the same x run bottom-to-top so a signature
+ // forced above at the foot of the page claims its space before one above it.
+ const ordered = [...targets].sort(
+ (left, right) =>
+ right.rect.xPt - left.rect.xPt ||
+ left.rect.yPt - right.rect.yPt ||
+ (left.field.id ?? "").localeCompare(right.field.id ?? ""),
+ );
+ const placed = new Map<FieldRecord, PlacedManifestation>();
+ const placedBoxes: PageBox[] = [];
+
+ for (const target of ordered) {
+ const { field, rect, text } = target;
+ const otherFieldBoxes = allFieldBoxes
+ .filter((entry) => entry.field !== field)
+ .map((entry) => entry.box);
+ const blockers = [...otherFieldBoxes, ...placedBoxes];
+ const x = Math.max(
+ margin,
+ Math.min(rect.xPt, Math.max(margin, pageRight - 4)),
+ );
+ const spaceBelow = Math.max(0, rect.yPt - margin);
+ const spaceAbove = Math.max(0, pageTop - (rect.yPt + rect.heightPt));
+
+ const layoutAtSide = (
+ side: "below" | "above",
+ allowVerticalShrink: boolean,
+ ): PlacedManifestation => {
+ const availableHeight = side === "below" ? spaceBelow : spaceAbove;
+ let rightBound = pageRight;
+ let current!: PlacedManifestation;
+
+ // Each pass that finds a right-side blocker strictly lowers rightBound
+ // against a finite set of blocker left-edges, so this reaches a fixed
+ // point in at most blockers.length + 1 passes.
+ for (let pass = 0; pass <= blockers.length; pass += 1) {
+ const maxWidth = Math.max(0.5, rightBound - x);
+ const layout = layoutManifestationText(
+ font,
+ text,
+ maxWidth,
+ availableHeight,
+ { allowVerticalShrink },
+ );
+ const descender = layout.size * 0.25;
+ const gap = layout.lineHeight - layout.size;
+ let topBaseline: number;
+ let fitsOnPage: boolean;
+
+ if (side === "below") {
+ topBaseline = rect.yPt - layout.lineHeight;
+ const bottomBaseline =
+ topBaseline - (layout.lines.length - 1) * layout.lineHeight;
+
+ fitsOnPage = bottomBaseline - descender >= margin;
+ if (!fitsOnPage && allowVerticalShrink) {
+ const shiftUp = margin - (bottomBaseline - descender);
+
+ topBaseline = Math.min(
+ topBaseline + shiftUp,
+ pageTop - layout.size,
+ );
+ }
+ } else {
+ const bottomBaseline = rect.yPt + rect.heightPt + gap + descender;
+
+ topBaseline =
+ bottomBaseline + (layout.lines.length - 1) * layout.lineHeight;
+ fitsOnPage = topBaseline + layout.size <= pageTop;
+
+ if (!fitsOnPage) {
+ topBaseline = Math.min(topBaseline, pageTop - layout.size);
+ }
+ }
+
+ const finalBottomBaseline =
+ topBaseline - (layout.lines.length - 1) * layout.lineHeight;
+ const box: PageBox = {
+ bottom: finalBottomBaseline - descender,
+ left: x,
+ right: x + layout.maxLineWidth,
+ top: topBaseline + layout.size,
+ };
+
+ let nextRightBound = rightBound;
+
+ for (const blocker of blockers) {
+ const isRightSideBlocker =
+ blocker.left > x &&
+ (blocker.left >= rect.xPt + rect.widthPt - 1 ||
+ blocker.left - x >= 24);
+
+ if (
+ isRightSideBlocker &&
+ boxesOverlap(
+ box,
+ blocker,
+ MANIFESTATION_GUTTER_PT,
+ MANIFESTATION_VERTICAL_CLEARANCE_PT,
+ )
+ ) {
+ const gutter = Math.min(
+ MANIFESTATION_GUTTER_PT,
+ (blocker.left - x) * 0.25,
+ );
+ const candidateBound = blocker.left - gutter;
+
+ if (candidateBound < nextRightBound) {
+ nextRightBound = candidateBound;
+ }
+ }
+ }
+
+ const collidesWithManifestation = placedBoxes.some((blocker) =>
+ boxesOverlap(box, blocker, 0, MANIFESTATION_VERTICAL_CLEARANCE_PT),
+ );
+ const hasCollision =
+ collidesWithManifestation ||
+ otherFieldBoxes.some((blocker) =>
+ boxesOverlap(box, blocker, 0, MANIFESTATION_VERTICAL_CLEARANCE_PT),
+ );
+
+ current = {
+ box,
+ collidesWithManifestation,
+ fitsOnPage,
+ hasCollision,
+ lineHeight: layout.lineHeight,
+ lines: layout.lines,
+ size: layout.size,
+ topBaseline,
+ x,
+ };
+
+ if (nextRightBound >= rightBound - 0.01) {
+ break;
+ }
+
+ rightBound = nextRightBound;
+ }
+
+ return current;
+ };
+
+ const below = layoutAtSide("below", false);
+ let chosen: PlacedManifestation;
+
+ if (below.fitsOnPage && !below.hasCollision) {
+ chosen = below;
+ } else {
+ const above = layoutAtSide("above", false);
+
+ if (above.fitsOnPage && !above.hasCollision) {
+ chosen = above;
+ } else if (below.fitsOnPage && !below.collidesWithManifestation) {
+ chosen = below;
+ } else if (above.fitsOnPage && !above.collidesWithManifestation) {
+ chosen = above;
+ } else if (below.fitsOnPage) {
+ chosen = below;
+ } else if (above.fitsOnPage) {
+ chosen = above;
+ } else {
+ chosen = layoutAtSide(
+ spaceBelow >= spaceAbove ? "below" : "above",
+ true,
+ );
+ }
+ }
+
+ placed.set(field, chosen);
+ placedBoxes.push(chosen.box);
+ }
+
+ return placed;
+}
+
/**
* Prints a Part 11 signature's manifestation just under the signature, or
- * just above it when the field sits at the foot of the page.
+ * just above it when there is no room below.
*/
async function stampSignatureManifestation(
- field: FieldRecord,
page: PDFPage,
+ geometry: DisplayedPageGeometry,
font: TextFace,
- text: string,
+ placement: PlacedManifestation,
): Promise<void> {
- const geometry = getDisplayedPageGeometry(page);
-
await drawOnDisplayedPage(page, geometry, () =>
- drawSignatureManifestation(field, page, geometry, font, text),
+ drawSignatureManifestation(page, font, placement),
);
}
function drawSignatureManifestation(
- field: FieldRecord,
page: PDFPage,
- geometry: DisplayedPageGeometry,
font: TextFace,
- text: string,
+ placement: PlacedManifestation,
): void {
- const pageWidth = geometry.widthPt;
- const rect = normalizedRectToPdfRect(field, geometry);
- const margin = 2;
- const fullWidth = pageWidth - margin * 2;
- const minimumSize = 5;
- // One line when it fits at a readable size, otherwise one line per part
- // (name, time, meaning), so nothing is shrunk away or runs off the page.
- const oneLineSize = fitTextSize(font, text, fullWidth, 7, 6.5);
- const lines =
- font.widthOfTextAtSize(text, oneLineSize) <= fullWidth &&
- oneLineSize >= minimumSize
- ? [text]
- : text.split(" | ");
- const size = Math.max(
- minimumSize,
- Math.min(
- ...lines.map((line) => fitTextSize(font, line, fullWidth, 7, 6.5)),
- ),
- );
- const lineHeight = size + 1.5;
- const blockHeight = lineHeight * lines.length;
- const below = rect.yPt - blockHeight;
- // The top line's baseline. Below the field when there is room, above it
- // at the foot of the page.
- const top =
- below >= margin
- ? rect.yPt - lineHeight
- : Math.min(
- rect.yPt + rect.heightPt + blockHeight - size,
- geometry.heightPt - size - margin,
- );
-
- lines.forEach((line, index) => {
- const width = font.widthOfTextAtSize(line, size);
- // Starts under the field, moved left if it would run off the page.
- const x = Math.max(margin, Math.min(rect.xPt, pageWidth - width - margin));
-
+ placement.lines.forEach((line, index) => {
font.drawText(page, line, {
color: rgb(0.2, 0.2, 0.24),
- size,
- x,
- y: top - index * lineHeight,
+ size: placement.size,
+ x: placement.x,
+ y: placement.topBaseline - index * placement.lineHeight,
});
});
}
@@ -1817,6 +2209,15 @@ export async function renderFinalizedEnvelopePdf(
const storedPages = new Map(
input.pages.map((page) => [page.pageNumber, page]),
);
+ const pageManifestations = new Map<
+ number,
+ {
+ allFieldBoxes: Array<{ box: PageBox; field: FieldRecord }>;
+ geometry: DisplayedPageGeometry;
+ page: PDFPage;
+ targets: PageManifestationTarget[];
+ }
+ >();
for (const placedField of stampedFields) {
const page = pdfDocument.getPage(placedField.page - 1);
@@ -1844,16 +2245,58 @@ export async function renderFinalizedEnvelopePdf(
geometry,
);
- const manifestation =
- field.type === "signature" ? manifestations.get(field.signerId) : null;
+ if (manifestations.size > 0) {
+ let pageContext = pageManifestations.get(placedField.page);
+
+ if (!pageContext) {
+ pageContext = {
+ allFieldBoxes: [],
+ geometry,
+ page,
+ targets: [],
+ };
+ pageManifestations.set(placedField.page, pageContext);
+ }
+
+ const rect = normalizedRectToPdfRect(field, geometry);
- if (manifestation) {
- await stampSignatureManifestation(
+ pageContext.allFieldBoxes.push({
+ box: rectToPageBox(rect),
field,
- page,
- faces.regular,
- manifestation,
- );
+ });
+
+ const manifestation =
+ field.type === "signature" ? manifestations.get(field.signerId) : null;
+
+ if (manifestation) {
+ pageContext.targets.push({ field, rect, text: manifestation });
+ }
+ }
+ }
+
+ for (const pageContext of pageManifestations.values()) {
+ if (pageContext.targets.length === 0) {
+ continue;
+ }
+
+ const placed = layoutPageManifestations(
+ pageContext.targets,
+ pageContext.allFieldBoxes,
+ pageContext.geometry,
+ faces.regular,
+ );
+
+ for (const target of pageContext.targets) {
+ const placement = placed.get(target.field);
+
+ if (placement) {
+ await stampSignatureManifestation(
+ pageContext.page,
+ pageContext.geometry,
+ faces.regular,
+ placement,
+ );
+ }
}
}