Skip to content

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

Add accessibility tagging support to Text Editor for forms (#8884)

James Brunton49631cd5db8a
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index 90f44f2fe4..6c5dce0b65 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -7616,6 +7616,7 @@ mergeRuns_one = "Merge {{count}} run into a paragraph"
mergeRuns_other = "Merge {{count}} runs into a paragraph"
setColour = "Set colour on {{run}}"
setOutline = "Set outline on {{run}}"
+tagFormField = "Tag form field"
tagLink = "Tag link"
tagPageContent = "Auto-tag page"
typeInto = "Type into {{run}}"
@@ -7744,6 +7745,7 @@ fontCompletedOriginal = "Embedded font · characters it lacks are drawn in {{nam
fontEmbedded = "Embedded font · a character it lacks falls back to Helvetica."
fontGap = "{{name}} · missing {{glyphs}} - typing those falls back to {{fallback}}."
fontUnknownCoverage = "{{name}} · a character it lacks falls back to {{fallback}}."
+formField = "Form field"
geometry = "Position & size"
height = "Height"
heightHint = "A text box's height follows its type size and line count."
@@ -7788,9 +7790,11 @@ applyToOtherPages_other = "Apply to {{count}} other pages"
artifactGroup = "Skipped by screen readers"
artifactText = "Decorative"
cannotChange = "This image's accessibility can't be changed."
+cannotDescribeFormField = "This form field's description can't be changed."
cannotDescribeLink = "This link's description can't be changed."
cannotRetag = "This text's tag can't be changed."
cannotSetDecorative = "This can't be marked or unmarked as decorative."
+cannotTagFormField = "This form field can't be tagged."
cannotTagLink = "This link can't be tagged."
cannotTagPage = "This page's content can't be tagged."
contentGroup = "Content"
@@ -7800,6 +7804,7 @@ decorativeLabel = "Decorative image"
description = "Image description"
descriptionInfo = "Screen readers read this out in place of the image."
encrypted = "Tags can't be edited in an encrypted file"
+formFieldDescription = "Field description"
heading = "Accessibility"
innerTagLabel = "Tag {{number}}"
innerTags = "Tags in this text"
@@ -7816,6 +7821,7 @@ notFigure = "Tagged as part of the text"
removeTag = "Remove tag"
saveFailed = "Your accessibility changes couldn't be saved, so the file wasn't saved. Undo them and try again."
selectedText = "Selected text"
+tagFormField = "Tag form field"
tagging = "Tagging pages"
tagLabel = "Tag"
tagLinks_one = "Tag link"
diff --git a/frontend/src/editor/core/tests/test-fixtures/generate-tagged-sample.mts b/frontend/src/editor/core/tests/test-fixtures/generate-tagged-sample.mts
index cd5b878253..ed73700923 100644
--- a/frontend/src/editor/core/tests/test-fixtures/generate-tagged-sample.mts
+++ b/frontend/src/editor/core/tests/test-fixtures/generate-tagged-sample.mts
@@ -13,6 +13,12 @@ import process from "node:process";
// annotations are one the Link holds through an OBJR, with /Contents, and one
// over "Atlas" that no element holds and that has no /Contents.
//
+// Page 3 is a sign-off form with no heading, so the document's outline stays
+// as pages 1 and 2 give it. "Reviewed by:" has a field a Form holds through an
+// OBJR, with a /TU; "Department:" has a field no element holds and with no /TU,
+// labelled on its left; "Approved for release" has a checkbox likewise
+// untagged and unnamed, labelled on its right.
+//
// Run with: npx tsx generate-tagged-sample.mts
import { writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
@@ -300,6 +306,64 @@ function wordSpan(
return { left, right: left + font.pdf.widthOfTextAtSize(word, size) };
}
+/** The widget `page` lists last in its /Annots. */
+function lastAnnotation(page: PDFPage): PDFRef {
+ const annots = page.node.lookup(PDFName.of("Annots"), PDFArray);
+ return annots.get(annots.size() - 1) as PDFRef;
+}
+
+/**
+ * Page 3: labelled form fields, made after pages 1 and 2 are done so their
+ * object numbers do not move.
+ */
+function addSignOffPage(
+ doc: PDFDocument,
+ tree: StructureBuilder,
+ document: PDFRef,
+ regular: Font,
+): void {
+ const ctx = doc.context;
+ const form = doc.getForm();
+ const third = doc.addPage([612, 792]);
+ third.node.setFontDictionary(PDFName.of(regular.name), regular.pdf.ref);
+ const content = tree.page(third);
+ const paragraph = (x: number, y: number, text: string) =>
+ content.mark("P", tree.element("P", document, third), [
+ show(regular, 12, x, y, text),
+ ]);
+ const fieldX = 160;
+ const textField = { width: 240, height: 20, font: regular.pdf };
+
+ paragraph(72, 712, "Please complete this section before filing the report.");
+
+ paragraph(72, 660, "Reviewed by:");
+ const reviewer = form.createTextField("reviewer");
+ reviewer.acroField.dict.set(PDFName.of("TU"), PDFString.of("Reviewer name"));
+ reviewer.addToPage(third, { x: fieldX, y: 654, ...textField });
+ tree.holdAnnotation(
+ tree.element("Form", document, third),
+ third,
+ lastAnnotation(third),
+ );
+
+ paragraph(72, 624, "Department:");
+ form
+ .createTextField("department")
+ .addToPage(third, { x: fieldX, y: 618, ...textField });
+
+ form.createCheckBox("approved").addToPage(third, {
+ x: 72,
+ y: 570,
+ width: 14,
+ height: 14,
+ });
+ paragraph(94, 573, "Approved for release");
+
+ content.artifact("/Type /Pagination", [show(regular, 10, 300, 40, "Page 3")]);
+ content.writeTo(ctx, third);
+ third.node.set(PDFName.of("Tabs"), PDFName.of("S"));
+}
+
async function main() {
const doc = await PDFDocument.create();
const ctx = doc.context;
@@ -550,6 +614,8 @@ async function main() {
);
second.node.set(PDFName.of("Tabs"), PDFName.of("S"));
+ addSignOffPage(doc, tree, document, regular);
+
tree.finish(document);
doc.catalog.set(PDFName.of("StructTreeRoot"), tree.rootRef);
@@ -557,7 +623,9 @@ async function main() {
doc.catalog.set(PDFName.of("Lang"), PDFString.of("en-US"));
doc.setTitle("Quarterly report");
- const bytes = await doc.save();
+ // addToPage drew each field's appearance in the page's own font; refreshing
+ // them here would embed a second Helvetica for nothing.
+ const bytes = await doc.save({ updateFieldAppearances: false });
const out = join(__dirname, "tagged-sample.pdf");
writeFileSync(out, bytes);
console.log(`wrote ${out} (${bytes.length} bytes)`);
diff --git a/frontend/src/editor/core/tests/test-fixtures/tagged-sample.pdf b/frontend/src/editor/core/tests/test-fixtures/tagged-sample.pdf
index 37693fb659..c29f1dbe91 100644
Binary files a/frontend/src/editor/core/tests/test-fixtures/tagged-sample.pdf and b/frontend/src/editor/core/tests/test-fixtures/tagged-sample.pdf differ
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyAnnotationEdits.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyAnnotationEdits.test.ts
index ee03ded83b..dc228fddaf 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyAnnotationEdits.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyAnnotationEdits.test.ts
@@ -240,6 +240,172 @@ describe("applyAnnotationEdits", () => {
).toEqual(["another element holds it"]);
});
+ describe("widgets", () => {
+ // Widget 24 is its own field; widget 25 is a kid of field 27.
+ const WIDGETS: Record<number, string> = {
+ 3: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 5 0 R /StructParents 0 /Annots [20 0 R 24 0 R 25 0 R] >>",
+ };
+ const widgetObjects = (
+ overrides: Record<number, string> = {},
+ extra: FixtureObject[] = [],
+ ) =>
+ objects({ ...WIDGETS, ...overrides }, [
+ ...extra,
+ {
+ num: 24,
+ body: "<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /Rect [0 50 50 60] >>",
+ },
+ {
+ num: 25,
+ body: "<< /Type /Annot /Subtype /Widget /Parent 27 0 R /Rect [0 70 50 80] >>",
+ },
+ { num: 27, body: "<< /FT /Btn /T (choice) /Kids [25 0 R] >>" },
+ ]);
+ const kids = (pdf: RawPdf, num: number) =>
+ pdf.valueSpan(pdf.objectBody(num)!, "K")!.text;
+ const refs = (array: string) =>
+ [...array.matchAll(/(\d+) 0 R/g)].map((m) => Number(m[1]));
+ const tooltip = (pdf: RawPdf, num: number) => {
+ const span = pdf.valueSpan(pdf.objectBody(num)!, "TU");
+ return span && decodeTextString(span.text);
+ };
+
+ test("gives a widget a new Form holding only it, after the block its content is in", async () => {
+ const pdf = await apply(
+ [{ pageIndex: 0, annotation: 24, newForm: { after: 1 } }],
+ widgetObjects(),
+ );
+
+ const [paragraph, form] = refs(kids(pdf, 9));
+ expect(paragraph).toBe(10);
+ const body = pdf.objectBody(form)!;
+ expect(pdf.dictName(body, "S")).toBe("Form");
+ expect(pdf.dictRef(body, "P")).toBe(9);
+ expect(pdf.dictRef(body, "Pg")).toBe(3);
+ expect(kids(pdf, form)).toBe("[<< /Type /OBJR /Obj 24 0 R /Pg 3 0 R >>]");
+ expect(pdf.dictInt(pdf.objectBody(24)!, "StructParent")).toBe(1);
+ expect(entry(pdf, 1)).toBe(`${form} 0 R`);
+ expect(pdf.dictName(pdf.objectBody(3)!, "Tabs")).toBe("S");
+ });
+
+ test("reads Forms placed after the same content in the order of their edits", async () => {
+ const pdf = await apply(
+ [
+ { pageIndex: 0, annotation: 24, newForm: { after: 0 } },
+ { pageIndex: 0, annotation: 25, newForm: { after: 0 } },
+ ],
+ widgetObjects(),
+ );
+ const [, first, second] = refs(kids(pdf, 9));
+ expect(kids(pdf, first)).toContain("/Obj 24 0 R");
+ expect(kids(pdf, second)).toContain("/Obj 25 0 R");
+ });
+
+ test("reads a Form placed after no content before the page's first", async () => {
+ const pdf = await apply(
+ [{ pageIndex: 0, annotation: 24, newForm: { after: null } }],
+ widgetObjects(),
+ );
+ const [form, paragraph] = refs(kids(pdf, 9));
+ expect(paragraph).toBe(10);
+ expect(kids(pdf, form)).toContain("/Obj 24 0 R");
+ });
+
+ test("adds a Form to a structure root with several kids, keeping it in the ParentTree too", async () => {
+ const pdf = await apply(
+ [{ pageIndex: 0, annotation: 24, newForm: { after: null } }],
+ widgetObjects(
+ {
+ 3: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 5 0 R /Annots [24 0 R] >>",
+ 7: "<< /Type /StructTreeRoot /K [9 0 R 12 0 R] /ParentTree << /Nums [0 [10 0 R 11 0 R]] >> /ParentTreeNextKey 1 >>",
+ },
+ [
+ {
+ num: 12,
+ body: "<< /Type /StructElem /S /Sect /P 7 0 R /K [] >>",
+ },
+ ],
+ ),
+ );
+ const [, , form] = refs(kids(pdf, 7));
+ expect(kids(pdf, form)).toContain("/Obj 24 0 R");
+ expect(pdf.dictRef(pdf.objectBody(form)!, "P")).toBe(7);
+ const key = pdf.dictInt(pdf.objectBody(24)!, "StructParent")!;
+ expect(entry(pdf, key)).toBe(`${form} 0 R`);
+ });
+
+ test("gives a file with no structure tree one to hold the Form", async () => {
+ const pdf = await apply(
+ [{ pageIndex: 0, annotation: 24, newForm: { after: null } }],
+ widgetObjects({
+ 1: "<< /Type /Catalog /Pages 2 0 R >>",
+ 3: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 5 0 R /Annots [24 0 R] >>",
+ }),
+ );
+ const treeRoot = pdf.dictRef(pdf.objectBody(1)!, "StructTreeRoot")!;
+ const [top] = refs(kids(pdf, treeRoot));
+ const [form] = refs(kids(pdf, top));
+ expect(pdf.dictName(pdf.objectBody(form)!, "S")).toBe("Form");
+ const key = pdf.dictInt(pdf.objectBody(24)!, "StructParent")!;
+ expect(pdf.numberTreeEntry(treeRoot, "ParentTree", key)?.span.text).toBe(
+ `${form} 0 R`,
+ );
+ });
+
+ test("sets /TU on a widget that is its own field", async () => {
+ const pdf = await apply(
+ [{ pageIndex: 0, annotation: 24, tooltip: "Full name" }],
+ widgetObjects(),
+ );
+ expect(tooltip(pdf, 24)).toBe("Full name");
+ });
+
+ test("sets and removes /TU on the field a widget belongs to", async () => {
+ const set = await apply(
+ [{ pageIndex: 0, annotation: 25, tooltip: "Delivery option" }],
+ widgetObjects(),
+ );
+ expect(tooltip(set, 27)).toBe("Delivery option");
+ expect(tooltip(set, 25)).toBeNull();
+
+ const removed = await apply(
+ [{ pageIndex: 0, annotation: 25, tooltip: null }],
+ widgetObjects({
+ 27: "<< /FT /Btn /T (choice) /TU (Old) /Kids [25 0 R] >>",
+ }),
+ );
+ expect(tooltip(removed, 27)).toBeNull();
+ });
+
+ test("refuses a Form or /TU for an annotation that is not a widget", async () => {
+ expect(
+ await failure(
+ [
+ { pageIndex: 0, annotation: 20, newForm: { after: null } },
+ { pageIndex: 0, annotation: 20, tooltip: "x" },
+ ],
+ widgetObjects(),
+ ),
+ ).toEqual(["it is not a widget", "it is not a widget"]);
+ });
+
+ test("refuses a widget a second element", async () => {
+ expect(
+ await failure(
+ [
+ { pageIndex: 0, annotation: 24, newForm: { after: null } },
+ { pageIndex: 0, annotation: 24, newForm: { after: 0 } },
+ { pageIndex: 0, annotation: 25, mcid: 0, newForm: { after: 0 } },
+ ],
+ widgetObjects(),
+ ),
+ ).toEqual([
+ "an element already holds it",
+ "it cannot be given two elements",
+ ]);
+ });
+ });
+
test("refuses to give an annotation to an element in a file with no structure tree", async () => {
expect(
await failure(
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/formFieldTagging.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/formFieldTagging.test.ts
new file mode 100644
index 0000000000..ee113b9047
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/formFieldTagging.test.ts
@@ -0,0 +1,619 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { SetFormFieldTooltipCommand } from "@editor/tools/pdfTextEditor/commands/SetFormFieldTooltipCommand";
+import {
+ TagFormFieldCommand,
+ taggableFormFields,
+} from "@editor/tools/pdfTextEditor/commands/TagFormFieldCommand";
+import {
+ TagPageContentCommand,
+ hasUntaggedContent,
+} from "@editor/tools/pdfTextEditor/commands/TagPageContentCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { elementKids } from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";
+import {
+ RawPdf,
+ referencedObject,
+} from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import { readFileStructure } from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";
+import { decodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import { formFieldAccessibility } from "@editor/tools/pdfTextEditor/util/formFieldAccessibility";
+import { fieldLabel } from "@editor/tools/pdfTextEditor/util/formLabel";
+import {
+ buildClassicPdf,
+ streamBody,
+ type FixtureObject,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+// "Name:" in 12 pt Helvetica from x 72 ends near x 104, left of NAME_FIELD;
+// "Email:" sits the same way 60 pt lower, left of EMAIL_FIELD.
+const NAME_LINE = "BT /F1 12 Tf 72 700 Td (Name: ) Tj ET\n";
+const EMAIL_LINE = "BT /F1 12 Tf 72 640 Td (Email:) Tj ET\n";
+const NAME_FIELD = 20;
+const EMAIL_FIELD = 21;
+const EMAIL_PARENT = 22;
+
+function nameField(extra = ""): FixtureObject {
+ return {
+ num: NAME_FIELD,
+ body: `<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /Rect [110 694 300 714]${extra} >>`,
+ };
+}
+
+/** A widget kid of field EMAIL_PARENT, which says its type. */
+function emailField(fieldExtra = ""): FixtureObject[] {
+ return [
+ {
+ num: EMAIL_FIELD,
+ body: `<< /Type /Annot /Subtype /Widget /Parent ${EMAIL_PARENT} 0 R /Rect [110 634 300 654] >>`,
+ },
+ {
+ num: EMAIL_PARENT,
+ body: `<< /FT /Tx /T (email) /Kids [${EMAIL_FIELD} 0 R]${fieldExtra} >>`,
+ },
+ ];
+}
+
+function page(
+ content: string,
+ annots: readonly number[],
+ extra = "",
+): FixtureObject[] {
+ return [
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body:
+ `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R ` +
+ `/Annots [${annots.map((a) => `${a} 0 R`).join(" ")}]${extra} ` +
+ "/Resources << /Font << /F1 5 0 R >> >> >>",
+ },
+ { num: 4, body: streamBody("", content) },
+ { num: 5, body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>" },
+ ];
+}
+
+/** No structure tree: `content` and the `widgets` the page lists. */
+function untaggedPdf(
+ content: string,
+ widgets: FixtureObject[],
+ annots = widgets
+ .filter((w) => w.body.includes("/Subtype /Widget"))
+ .map((w) => w.num),
+): Uint8Array {
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ ...page(content, annots),
+ ...widgets,
+ ],
+ 1,
+ );
+}
+
+/**
+ * "Name:" tagged as paragraph 9 (MCID 0) in Document 8, with NAME_FIELD, or
+ * with `held` a Form 10 already holding it.
+ */
+function taggedPdf({ held = false } = {}): Uint8Array {
+ const parentTree = held ? " 1 10 0 R" : "";
+ return buildClassicPdf(
+ [
+ {
+ num: 1,
+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 7 0 R >>",
+ },
+ ...page(
+ `/P <</MCID 0>> BDC ${NAME_LINE}EMC\n`,
+ [NAME_FIELD],
+ " /StructParents 0",
+ ),
+ {
+ num: 7,
+ body: `<< /Type /StructTreeRoot /K 8 0 R /ParentTree << /Nums [0 [9 0 R]${parentTree}] >> /ParentTreeNextKey 2 >>`,
+ },
+ {
+ num: 8,
+ body: `<< /Type /StructElem /S /Document /P 7 0 R /K [9 0 R${held ? " 10 0 R" : ""}] >>`,
+ },
+ {
+ num: 9,
+ body: "<< /Type /StructElem /S /P /P 8 0 R /Pg 3 0 R /K 0 >>",
+ },
+ ...(held
+ ? [
+ {
+ num: 10,
+ body: `<< /Type /StructElem /S /Form /P 8 0 R /Pg 3 0 R /K << /Type /OBJR /Obj ${NAME_FIELD} 0 R >> >>`,
+ },
+ ]
+ : []),
+ nameField(held ? " /StructParent 1" : ""),
+ ],
+ 1,
+ );
+}
+
+const opened: EditorDocument[] = [];
+
+async function open(bytes: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+async function saved(doc: EditorDocument): Promise<RawPdf> {
+ const blob = await exportToBlob(doc);
+ return (await RawPdf.parse(new Uint8Array(await blob.arrayBuffer())))!;
+}
+
+function autoTag(doc: EditorDocument, history = new HistoryStack()): void {
+ history.execute(new TagPageContentCommand({ pageIndex: 0 }), doc);
+}
+
+function treeRoot(pdf: RawPdf): number {
+ return pdf.dictRef(pdf.objectBody(pdf.rootNum)!, "StructTreeRoot")!;
+}
+
+/** An element's kids: an element as its /S, an OBJR as `OBJR n` for the object it names, an MCID as its number. */
+function kidsOf(pdf: RawPdf, num: number): string[] {
+ return elementKids(pdf, pdf.objectBody(num)!)!.map((kid) => {
+ const ref = referencedObject(kid);
+ if (ref !== null) return `/${pdf.dictName(pdf.objectBody(ref)!, "S")}`;
+ if (!kid.startsWith("<<")) return kid;
+ return `${pdf.dictName(kid, "Type")} ${pdf.dictRef(kid, "Obj")}`;
+ });
+}
+
+function documentElement(pdf: RawPdf): number {
+ return pdf.dictRef(pdf.objectBody(treeRoot(pdf))!, "K")!;
+}
+
+/** The element the widget's /StructParent entry names; null when it has none. */
+function holder(pdf: RawPdf, widget: number): number | null {
+ const key = pdf.dictInt(pdf.objectBody(widget)!, "StructParent");
+ if (key === null) return null;
+ const entry = pdf.numberTreeEntry(treeRoot(pdf), "ParentTree", key);
+ return entry ? referencedObject(entry.span.text) : null;
+}
+
+function tooltip(pdf: RawPdf, field: number): string | null {
+ const span = pdf.valueSpan(pdf.objectBody(field)!, "TU");
+ return span && decodeTextString(span.text);
+}
+
+beforeAll(async () => {
+ const wasmPath = createRequire(import.meta.url).resolve(
+ "@embedpdf/pdfium/pdfium.wasm",
+ );
+ const wasmBytes = await readFile(wasmPath);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Promise.resolve(
+ new Response(wasmBytes, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ ),
+ );
+});
+
+afterEach(() => {
+ while (opened.length) opened.pop()!.dispose();
+});
+
+afterAll(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("reading form fields", () => {
+ test("reads each shown widget the page references, with its field's type and name", async () => {
+ const structure = await readFileStructure(
+ untaggedPdf(
+ NAME_LINE,
+ [
+ nameField(),
+ ...emailField(" /TU (Email address)"),
+ {
+ num: 23,
+ body: "<< /Type /Annot /Subtype /Widget /FT /Tx /F 2 /Rect [0 0 10 10] >>",
+ },
+ ],
+ [NAME_FIELD, EMAIL_FIELD, 23],
+ ),
+ );
+ expect(structure!.widgets.get(0)).toEqual([
+ {
+ annotation: NAME_FIELD,
+ position: 0,
+ field: NAME_FIELD,
+ fieldShared: false,
+ rect: { x: 110, y: 694, width: 190, height: 20 },
+ fieldType: "Tx",
+ tooltip: null,
+ holder: null,
+ },
+ expect.objectContaining({
+ annotation: EMAIL_FIELD,
+ position: 1,
+ field: EMAIL_PARENT,
+ fieldType: "Tx",
+ tooltip: "Email address",
+ }),
+ ]);
+ });
+
+ test("reads the Form the file gives a widget", async () => {
+ const structure = await readFileStructure(taggedPdf({ held: true }));
+ expect(structure!.widgets.get(0)![0].holder).toBe("10");
+ });
+});
+
+describe("tagging form fields", () => {
+ test("tags a field as a Form after its label, named by the label", async () => {
+ const doc = await open(untaggedPdf(NAME_LINE, [nameField()]));
+ autoTag(doc);
+
+ const pdf = await saved(doc);
+ const document = documentElement(pdf);
+ expect(kidsOf(pdf, document)).toEqual(["/P", "/Form"]);
+ const form = holder(pdf, NAME_FIELD)!;
+ expect(kidsOf(pdf, form)).toEqual([`OBJR ${NAME_FIELD}`]);
+ expect(pdf.dictRef(pdf.objectBody(form)!, "P")).toBe(document);
+ expect(tooltip(pdf, NAME_FIELD)).toBe("Name");
+ });
+
+ test("reads each field after its own label, and names a kid's field", async () => {
+ const doc = await open(
+ untaggedPdf(NAME_LINE + EMAIL_LINE, [nameField(), ...emailField()]),
+ );
+ autoTag(doc);
+
+ const pdf = await saved(doc);
+ const document = documentElement(pdf);
+ expect(kidsOf(pdf, document)).toEqual(["/P", "/Form", "/P", "/Form"]);
+ const forms = elementKids(pdf, pdf.objectBody(document)!)!
+ .map(referencedObject)
+ .filter((_, index) => index % 2 === 1);
+ expect(forms).toEqual([holder(pdf, NAME_FIELD), holder(pdf, EMAIL_FIELD)]);
+ expect(tooltip(pdf, EMAIL_PARENT)).toBe("Email");
+ expect(tooltip(pdf, EMAIL_FIELD)).toBeNull();
+ });
+
+ test("names a check box by the text right of it", async () => {
+ const doc = await open(
+ untaggedPdf("BT /F1 12 Tf 90 600 Td (I agree) Tj ET\n", [
+ {
+ num: NAME_FIELD,
+ body: "<< /Type /Annot /Subtype /Widget /FT /Btn /T (agree) /Rect [72 598 84 610] >>",
+ },
+ ]),
+ );
+ autoTag(doc);
+ expect(tooltip(await saved(doc), NAME_FIELD)).toBe("I agree");
+ });
+
+ test("leaves a field with no label nearby unnamed", async () => {
+ const doc = await open(
+ untaggedPdf("BT /F1 12 Tf 72 300 Td (Far away) Tj ET\n", [nameField()]),
+ );
+ autoTag(doc);
+ const pdf = await saved(doc);
+ expect(holder(pdf, NAME_FIELD)).not.toBeNull();
+ expect(tooltip(pdf, NAME_FIELD)).toBeNull();
+ });
+
+ test("keeps the name a field already has", async () => {
+ const doc = await open(
+ untaggedPdf(NAME_LINE + EMAIL_LINE, [
+ nameField(" /TU (Full name)"),
+ ...emailField(" /TU (Email address)"),
+ ]),
+ );
+ autoTag(doc);
+ const pdf = await saved(doc);
+ expect(tooltip(pdf, NAME_FIELD)).toBe("Full name");
+ expect(tooltip(pdf, EMAIL_PARENT)).toBe("Email address");
+ });
+
+ test("undoing the page's tags leaves the field as it was", async () => {
+ const doc = await open(untaggedPdf(NAME_LINE, [nameField()]));
+ const history = new HistoryStack();
+ autoTag(doc, history);
+ history.undo(doc);
+ expect(doc.annotationEdits()).toEqual([]);
+ history.redo(doc);
+ expect(doc.annotationEdits()).toEqual([
+ expect.objectContaining({
+ annotation: NAME_FIELD,
+ newForm: { after: expect.any(Number) },
+ tooltip: "Name",
+ }),
+ ]);
+ });
+
+ test("tags the untagged field on a page whose text is tagged", async () => {
+ const doc = await open(taggedPdf());
+ expect(hasUntaggedContent(doc, 0)).toBe(true);
+ new HistoryStack().execute(
+ new TagFormFieldCommand({ pageIndex: 0, annotation: NAME_FIELD }),
+ doc,
+ );
+ const pdf = await saved(doc);
+ expect(kidsOf(pdf, 8)).toEqual(["/P", "/Form"]);
+ expect(tooltip(pdf, NAME_FIELD)).toBe("Name");
+ });
+
+ test("leaves a field the file already gives an element alone", async () => {
+ const doc = await open(taggedPdf({ held: true }));
+ expect(taggableFormFields(doc, 0)).toEqual([]);
+ expect(hasUntaggedContent(doc, 0)).toBe(false);
+ });
+});
+
+describe("describing form fields", () => {
+ test("finds a widget by its place in the page's /Annots", async () => {
+ const doc = await open(taggedPdf());
+ expect(formFieldAccessibility(doc, 0, 0)).toEqual({
+ kind: "editable",
+ widget: expect.objectContaining({ annotation: NAME_FIELD }),
+ tagged: false,
+ description: null,
+ });
+ expect(formFieldAccessibility(doc, 0, 1)).toEqual({
+ kind: "blocked",
+ blocker: "unknown",
+ });
+ });
+
+ test("shows a field as tagged once tagged, named by its label", async () => {
+ const doc = await open(taggedPdf());
+ new HistoryStack().execute(
+ new TagFormFieldCommand({ pageIndex: 0, annotation: NAME_FIELD }),
+ doc,
+ );
+ expect(formFieldAccessibility(doc, 0, 0)).toMatchObject({
+ tagged: true,
+ description: "Name",
+ });
+ });
+
+ test("shows a field the file gives an element as tagged", async () => {
+ const doc = await open(taggedPdf({ held: true }));
+ expect(formFieldAccessibility(doc, 0, 0)).toMatchObject({ tagged: true });
+ });
+
+ test("saves an edited description on the field, and undoing it restores the file's", async () => {
+ const doc = await open(
+ untaggedPdf(EMAIL_LINE, emailField(" /TU (Email address)")),
+ );
+ const history = new HistoryStack();
+ history.execute(
+ new SetFormFieldTooltipCommand({
+ pageIndex: 0,
+ annotation: EMAIL_FIELD,
+ tooltip: "Work email",
+ }),
+ doc,
+ );
+ expect(tooltip(await saved(doc), EMAIL_PARENT)).toBe("Work email");
+ history.undo(doc);
+ expect(doc.annotationEdits()).toEqual([]);
+ });
+
+ test("removes a description with null", async () => {
+ const doc = await open(
+ untaggedPdf(NAME_LINE, [nameField(" /TU (Full name)")]),
+ );
+ new HistoryStack().execute(
+ new SetFormFieldTooltipCommand({
+ pageIndex: 0,
+ annotation: NAME_FIELD,
+ tooltip: null,
+ }),
+ doc,
+ );
+ expect(tooltip(await saved(doc), NAME_FIELD)).toBeNull();
+ });
+
+ test("refuses a widget the page does not have", async () => {
+ const doc = await open(taggedPdf());
+ expect(() =>
+ new HistoryStack().execute(
+ new SetFormFieldTooltipCommand({
+ pageIndex: 0,
+ annotation: EMAIL_FIELD,
+ tooltip: "Email",
+ }),
+ doc,
+ ),
+ ).toThrow();
+ });
+});
+
+describe("form fields in a word processor's tagged export", () => {
+ const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/tagged-sample.pdf",
+ );
+ const PAGE = 2;
+
+ async function sampleBytes(): Promise<Uint8Array> {
+ return new Uint8Array(await readFile(SAMPLE));
+ }
+
+ async function openSample(): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(await sampleBytes());
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(PAGE));
+ return doc;
+ }
+
+ /** The field each of the page's widgets belongs to, in /Annots order. */
+ function fields(pdf: RawPdf, widgets: readonly number[]): number[] {
+ return widgets.map(
+ (widget) => pdf.dictRef(pdf.objectBody(widget)!, "Parent") ?? widget,
+ );
+ }
+
+ test("reads the field its Form holds, and the two nothing holds", async () => {
+ const bytes = await sampleBytes();
+ const widgets = (await readFileStructure(bytes))!.widgets.get(PAGE)!;
+ expect(
+ widgets.map(({ fieldType, tooltip, holder }) => ({
+ fieldType,
+ tooltip,
+ held: holder !== null,
+ })),
+ ).toEqual([
+ { fieldType: "Tx", tooltip: "Reviewer name", held: true },
+ { fieldType: "Tx", tooltip: null, held: false },
+ { fieldType: "Btn", tooltip: null, held: false },
+ ]);
+ const pdf = (await RawPdf.parse(bytes))!;
+ const form = pdf.objectBody(Number(widgets[0].holder))!;
+ expect(pdf.dictName(form, "S")).toBe("Form");
+ });
+
+ test("finds each outline PDFium draws as the widget at its place in /Annots", async () => {
+ const doc = await openSample();
+ const boxes = doc.page(PAGE).annotations;
+ expect(boxes.map((box) => box.kind)).toEqual([
+ "widget",
+ "widget",
+ "widget",
+ ]);
+ for (const box of boxes) {
+ const field = formFieldAccessibility(doc, PAGE, box.index);
+ if (field.kind !== "editable") throw new Error(`no widget ${box.index}`);
+ expect(field.widget.rect).toEqual(box.rect);
+ }
+ expect(formFieldAccessibility(doc, PAGE, 0)).toMatchObject({
+ tagged: true,
+ description: "Reviewer name",
+ });
+ });
+
+ test("tags each untagged field after its label, named by it, and leaves the Form the file has", async () => {
+ const doc = await openSample();
+ expect(hasUntaggedContent(doc, PAGE)).toBe(true);
+ const widgets = doc
+ .structure(PAGE)
+ .formFields.all()
+ .map((w) => w.annotation);
+ new HistoryStack().execute(
+ new TagPageContentCommand({ pageIndex: PAGE }),
+ doc,
+ );
+ expect(hasUntaggedContent(doc, PAGE)).toBe(false);
+
+ const pdf = await saved(doc);
+ expect(kidsOf(pdf, documentElement(pdf)).slice(-7)).toEqual([
+ "/P",
+ "/P",
+ "/Form",
+ "/P",
+ "/Form",
+ "/P",
+ "/Form",
+ ]);
+ expect(fields(pdf, widgets).map((field) => tooltip(pdf, field))).toEqual([
+ "Reviewer name",
+ "Department",
+ "Approved for release",
+ ]);
+ const structure = (await readFileStructure(await sampleBytes()))!;
+ expect(holder(pdf, widgets[0])).toBe(
+ Number(structure.widgets.get(PAGE)![0].holder),
+ );
+ });
+});
+
+describe("fields with several widgets", () => {
+ const GROUP = 30;
+ const YES = 31;
+ const NO = 32;
+ // "Yes" and "No" each sit right of their radio button, far enough apart
+ // that each would name its button were it the field's only widget.
+ const RADIO_LINES =
+ "BT /F1 12 Tf 90 602 Td (Yes) Tj ET\nBT /F1 12 Tf 90 540 Td (No) Tj ET\n";
+
+ function radioGroup(): FixtureObject[] {
+ return [
+ {
+ num: GROUP,
+ body: `<< /FT /Btn /Ff 49152 /T (agree) /Kids [${YES} 0 R ${NO} 0 R] >>`,
+ },
+ {
+ num: YES,
+ body: `<< /Type /Annot /Subtype /Widget /Parent ${GROUP} 0 R /Rect [72 600 84 612] >>`,
+ },
+ {
+ num: NO,
+ body: `<< /Type /Annot /Subtype /Widget /Parent ${GROUP} 0 R /Rect [72 538 84 550] >>`,
+ },
+ ];
+ }
+
+ test("tags each widget but names the field from neither's label", async () => {
+ const doc = await open(untaggedPdf(RADIO_LINES, radioGroup()));
+ const labels = doc
+ .structure(0)
+ .formFields.all()
+ .map((widget) => fieldLabel(doc.page(0), widget)?.text);
+ expect(labels).toEqual(["Yes", "No"]);
+ autoTag(doc);
+ expect(doc.annotationEdits()).toEqual([
+ expect.not.objectContaining({ tooltip: expect.anything() }),
+ expect.not.objectContaining({ tooltip: expect.anything() }),
+ ]);
+ const pdf = await saved(doc);
+ expect(holder(pdf, YES)).not.toBeNull();
+ expect(holder(pdf, NO)).not.toBeNull();
+ expect(tooltip(pdf, GROUP)).toBeNull();
+ });
+
+ test("shows and saves one description for the field, whichever widget it is edited through", async () => {
+ const doc = await open(untaggedPdf(RADIO_LINES, radioGroup()));
+ const history = new HistoryStack();
+ const describe = (annotation: number, text: string) =>
+ history.execute(
+ new SetFormFieldTooltipCommand({
+ pageIndex: 0,
+ annotation,
+ tooltip: text,
+ }),
+ doc,
+ );
+ describe(YES, "Agree to the terms");
+ describe(NO, "Consent");
+ expect(formFieldAccessibility(doc, 0, 0)).toMatchObject({
+ description: "Consent",
+ });
+ expect(doc.annotationEdits()).toEqual([
+ { pageIndex: 0, annotation: YES, tooltip: "Consent" },
+ ]);
+ expect(tooltip(await saved(doc), GROUP)).toBe("Consent");
+
+ history.undo(doc);
+ expect(formFieldAccessibility(doc, 0, 1)).toMatchObject({
+ description: "Agree to the terms",
+ });
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rawPdf.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rawPdf.test.ts
index f8a9d8c6e1..1c4c692c86 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rawPdf.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rawPdf.test.ts
@@ -384,6 +384,18 @@ describe("setDictEntry", () => {
expect(out).toContain("/Alt (outer) >>");
});
+ it("adds after a hex string that closes the dictionary", () => {
+ expect(setDictEntry("<</T<FEFF0041>>>", "TU", "(x)")).toBe(
+ "<</T<FEFF0041> /TU (x) >>",
+ );
+ });
+
+ it("replaces a nested dictionary that ends in a hex string whole", () => {
+ expect(setDictEntry("<< /A <</B<41>>> /S /P >>", "A", "1")).toBe(
+ "<< /A 1 /S /P >>",
+ );
+ });
+
it("keeps the result lexable when the value abuts its key", () => {
expect(setDictEntry("<< /K[1 2] >>", "K", "3")).toBe("<< /K 3 >>");
});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFormFieldTooltipCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFormFieldTooltipCommand.ts
new file mode 100644
index 0000000000..798c25e576
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFormFieldTooltipCommand.ts
@@ -0,0 +1,64 @@
+import i18n from "i18next";
+import {
+ RolledBackError,
+ type Command,
+} from "@editor/tools/pdfTextEditor/commands/Command";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+
+/**
+ * Set or, with null, remove the /TU of the field form field widget
+ * `annotation` belongs to: the name a screen reader gives the field. Touches
+ * no page content; the save pass writes it.
+ */
+export class SetFormFieldTooltipCommand implements Command {
+ readonly type = "set-form-field-tooltip";
+ private readonly pageIndex: number;
+ private readonly annotation: number;
+ private readonly tooltip: string | null;
+ /** The /TU before the first apply. */
+ private previous: string | null | undefined;
+
+ constructor(opts: {
+ pageIndex: number;
+ annotation: number;
+ tooltip: string | null;
+ }) {
+ this.pageIndex = opts.pageIndex;
+ this.annotation = opts.annotation;
+ this.tooltip = opts.tooltip;
+ }
+
+ apply(doc: EditorDocument): void {
+ const structure = doc.structure(this.pageIndex);
+ const fields = structure.formFields;
+ const known = fields.all().some((w) => w.annotation === this.annotation);
+ if (structure.readOnly || !known) {
+ throw new RolledBackError(
+ new Error(
+ i18n.t(
+ "pdfTextEditor.inspector.accessibility.cannotDescribeFormField",
+ "This form field's description can't be changed.",
+ ),
+ ),
+ );
+ }
+ if (this.previous === undefined) {
+ this.previous = fields.tooltip(this.annotation);
+ }
+ fields.setTooltip(this.annotation, this.tooltip);
+ doc.page(this.pageIndex).bumpRevision();
+ }
+
+ revert(doc: EditorDocument): void {
+ if (this.previous === undefined) return;
+ doc
+ .structure(this.pageIndex)
+ .formFields.setTooltip(this.annotation, this.previous);
+ doc.page(this.pageIndex).bumpRevision();
+ }
+
+ /** Keystrokes in one field's description collapse into one undo step. */
+ coalesceKey(): string {
+ return `set-form-field-tooltip:${this.pageIndex}:${this.annotation}`;
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagFormFieldCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagFormFieldCommand.ts
new file mode 100644
index 0000000000..c4b470c37e
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagFormFieldCommand.ts
@@ -0,0 +1,77 @@
+import i18n from "i18next";
+import {
+ RolledBackError,
+ type Command,
+} from "@editor/tools/pdfTextEditor/commands/Command";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { WidgetAnnotation } from "@editor/tools/pdfTextEditor/model/WidgetAnnotation";
+import { fieldLabel } from "@editor/tools/pdfTextEditor/util/formLabel";
+
+/**
+ * Give form field widget `annotation` a Form element of its own. A field with
+ * no /TU is named by the widget's label (fieldLabel), where it has one and the
+ * field has no other widget: one radio button's label does not name its
+ * group. The page must already be read.
+ */
+export class TagFormFieldCommand implements Command {
+ readonly type = "tag-form-field";
+ private readonly pageIndex: number;
+ private readonly annotation: number;
+ /** Found on first apply, so a redo names the field the same. */
+ private label: string | null | undefined;
+ private named = false;
+
+ constructor(opts: { pageIndex: number; annotation: number }) {
+ this.pageIndex = opts.pageIndex;
+ this.annotation = opts.annotation;
+ }
+
+ apply(doc: EditorDocument): void {
+ const fields = doc.structure(this.pageIndex).formFields;
+ const widget = taggableFormFields(doc, this.pageIndex).find(
+ (w) => w.annotation === this.annotation,
+ );
+ if (!widget) {
+ throw new RolledBackError(
+ new Error(
+ i18n.t(
+ "pdfTextEditor.inspector.accessibility.cannotTagFormField",
+ "This form field can't be tagged.",
+ ),
+ ),
+ );
+ }
+ if (this.label === undefined) {
+ this.label = widget.fieldShared
+ ? null
+ : (fieldLabel(doc.page(this.pageIndex), widget)?.text ?? null);
+ }
+ fields.setTagged(this.annotation, true);
+ this.named =
+ this.label !== null && fields.tooltip(this.annotation) === null;
+ if (this.named) fields.setTooltip(this.annotation, this.label);
+ doc.page(this.pageIndex).bumpRevision();
+ }
+
+ revert(doc: EditorDocument): void {
+ const fields = doc.structure(this.pageIndex).formFields;
+ if (this.named) fields.setTooltip(this.annotation, null);
+ fields.setTagged(this.annotation, false);
+ doc.page(this.pageIndex).bumpRevision();
+ }
+
+ describe(): string {
+ return i18n.t("pdfTextEditor.commands.tagFormField", "Tag form field");
+ }
+}
+
+/** The page's form fields TagFormFieldCommand can tag: those no element holds, on a page whose save can write them. */
+export function taggableFormFields(
+ doc: EditorDocument,
+ pageIndex: number,
+): WidgetAnnotation[] {
+ const structure = doc.structure(pageIndex);
+ if (structure.readOnly) return [];
+ const fields = structure.formFields;
+ return fields.all().filter((w) => !fields.held(w.annotation));
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagPageContentCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagPageContentCommand.ts
index 3407482ed1..1fcb20db7d 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagPageContentCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagPageContentCommand.ts
@@ -12,6 +12,10 @@ import {
furnitureKind,
type Furniture,
} from "@editor/tools/pdfTextEditor/model/artifactKind";
+import {
+ TagFormFieldCommand,
+ taggableFormFields,
+} from "@editor/tools/pdfTextEditor/commands/TagFormFieldCommand";
import {
TagLinkCommand,
taggableLinks,
@@ -75,9 +79,9 @@ interface Plan {
* other object an artifact, the new elements read in content order. Content already
* tagged or marked an artifact is left alone. Content marked with an MCID no
* element owns counts as untagged, losing that mark. Content in a form
- * XObject is left alone: the editor cannot tag inside one. Each link
- * annotation no element holds is then tagged (TagLinkCommand), where it can
- * be. The page must already be read.
+ * XObject is left alone: the editor cannot tag inside one. Each link and
+ * form field no element holds is then tagged (TagLinkCommand,
+ * TagFormFieldCommand), where it can be. The page must already be read.
*/
export class TagPageContentCommand implements Command {
readonly type = "tag-page-content";
@@ -85,8 +89,8 @@ export class TagPageContentCommand implements Command {
private readonly furniture: ReadonlyMap<string, Furniture>;
/** Chosen on first apply, so a redo reuses its MCIDs. */
private plan: Plan | null = null;
- /** The links the first apply tagged, which a redo tags again. */
- private links: TagLinkCommand[] | null = null;
+ /** The annotations the first apply tagged, which a redo tags again. */
+ private annotations: Command[] | null = null;
constructor(opts: {
pageIndex: number;
@@ -116,7 +120,7 @@ export class TagPageContentCommand implements Command {
applyStep(doc, page, structure, step, this.plan.follows);
done.push(step);
}
- this.tagLinks(doc);
+ this.tagAnnotations(doc);
} catch (err) {
for (const step of done.reverse()) revertStep(doc, page, structure, step);
throw new RolledBackError(err);
@@ -129,7 +133,9 @@ export class TagPageContentCommand implements Command {
if (!this.plan) return;
const page = doc.page(this.pageIndex);
const structure = doc.structure(this.pageIndex);
- for (const link of [...(this.links ?? [])].reverse()) link.revert(doc);
+ for (const tag of [...(this.annotations ?? [])].reverse()) {
+ tag.revert(doc);
+ }
for (const step of [...this.plan.steps].reverse()) {
revertStep(doc, page, structure, step);
}
@@ -142,38 +148,46 @@ export class TagPageContentCommand implements Command {
}
/**
- * Tag the links once their text is: on the first apply each one that can
- * be, and on a redo the same ones. Throws, with none tagged, when a redo
- * cannot.
+ * Tag the links and form fields once the text is, which links cut from and
+ * fields are named by: on the first apply each one that can be, and on a
+ * redo the same ones. Throws, with none tagged, when a redo cannot.
*/
- private tagLinks(doc: EditorDocument): void {
- if (this.links === null) {
- this.links = [];
- for (const { annotation } of taggableLinks(doc, this.pageIndex)) {
- const link = new TagLinkCommand({
- pageIndex: this.pageIndex,
- annotation,
- });
+ private tagAnnotations(doc: EditorDocument): void {
+ if (this.annotations === null) {
+ this.annotations = [];
+ for (const tag of this.annotationTags(doc)) {
try {
- link.apply(doc);
- this.links.push(link);
+ tag.apply(doc);
+ this.annotations.push(tag);
} catch {
/* left untagged rather than failing the page */
}
}
return;
}
- const done: TagLinkCommand[] = [];
+ const done: Command[] = [];
try {
- for (const link of this.links) {
- link.apply(doc);
- done.push(link);
+ for (const tag of this.annotations) {
+ tag.apply(doc);
+ done.push(tag);
}
} catch (err) {
- for (const link of done.reverse()) link.revert(doc);
+ for (const tag of done.reverse()) tag.revert(doc);
throw err;
}
}
+
+ private annotationTags(doc: EditorDocument): Command[] {
+ const pageIndex = this.pageIndex;
+ return [
+ ...taggableLinks(doc, pageIndex).map(
+ ({ annotation }) => new TagLinkCommand({ pageIndex, annotation }),
+ ),
+ ...taggableFormFields(doc, pageIndex).map(
+ ({ annotation }) => new TagFormFieldCommand({ pageIndex, annotation }),
+ ),
+ ];
+ }
}
/** True when TagPageContentCommand would change anything on the page, which must already be read. */
@@ -184,7 +198,11 @@ export function hasUntaggedContent(
const structure = doc.structure(pageIndex);
if (structure.cannotAddElement() !== null) return false;
const { steps } = planTagging(doc, doc.page(pageIndex), structure, new Map());
- return steps.length > 0 || taggableLinks(doc, pageIndex).length > 0;
+ return (
+ steps.length > 0 ||
+ taggableLinks(doc, pageIndex).length > 0 ||
+ taggableFormFields(doc, pageIndex).length > 0
+ );
}
/** The untagged content as steps, and where each new element reads. */
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/AnnotationOutline.css b/frontend/src/editor/core/tools/pdfTextEditor/components/AnnotationOutline.css
index 6cb74be1d9..33b15fce3b 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/AnnotationOutline.css
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/AnnotationOutline.css
@@ -9,11 +9,20 @@
background-color 120ms ease;
}
+.pdf-editor-annotation-outline--selectable {
+ cursor: pointer;
+}
+
+.pdf-editor-annotation-outline--selected,
.pdf-editor-annotation-outline:hover {
border-color: color-mix(in srgb, var(--c-primary) 90%, transparent);
background: color-mix(in srgb, var(--c-primary) 8%, transparent);
}
+.pdf-editor-annotation-outline--selected {
+ border-style: solid;
+}
+
@media (prefers-reduced-motion: reduce) {
.pdf-editor-annotation-outline {
transition: none;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/AnnotationOutline.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/AnnotationOutline.tsx
index 71474a08ce..78fb847c88 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/AnnotationOutline.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/AnnotationOutline.tsx
@@ -8,6 +8,9 @@ interface AnnotationOutlineProps {
pageHeight: number;
transform: DisplayTransform;
scale: number;
+ selected?: boolean;
+ /** Makes the outline selectable by click. */
+ onSelect?: () => void;
}
// FreeText/widget/stamp text is painted by FPDF_ANNOT but lives outside the
@@ -19,6 +22,8 @@ export function AnnotationOutline({
pageHeight,
transform,
scale,
+ selected = false,
+ onSelect,
}: AnnotationOutlineProps) {
const { t } = useTranslation();
const { rect, kind } = annotation;
@@ -59,9 +64,16 @@ export function AnnotationOutline({
return (
<div
- className="pdf-editor-annotation-outline"
+ className={[
+ "pdf-editor-annotation-outline",
+ onSelect && "pdf-editor-annotation-outline--selectable",
+ selected && "pdf-editor-annotation-outline--selected",
+ ]
+ .filter(Boolean)
+ .join(" ")}
data-testid={`pdf-editor-annot-${annotation.id}`}
data-annot-kind={kind}
+ data-selected={selected ? "true" : undefined}
title={label}
aria-label={label}
style={{
@@ -75,6 +87,18 @@ export function AnnotationOutline({
// click and stays editable.
pointerEvents: "auto",
}}
+ onPointerDown={
+ onSelect &&
+ ((e) => {
+ // Ctrl/Cmd+Shift+drag is the marquee gesture - let it reach the stage.
+ if ((e.ctrlKey || e.metaKey) && e.shiftKey) return;
+ // Otherwise the stage's "press on empty space clears" handler would
+ // drop the selection this press makes.
+ e.stopPropagation();
+ onSelect();
+ })
+ }
+ onClick={onSelect && ((e) => e.stopPropagation())}
/>
);
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
index 9323fdd444..8738766c5a 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
@@ -80,7 +80,8 @@ export function EditorSidebar({
const hasSelection =
selection.runIds.length > 0 ||
selection.imageIds.length > 0 ||
- selection.shapeIds.length > 0;
+ selection.shapeIds.length > 0 ||
+ selection.formFieldId !== null;
const [tab, setTab] = useState<SidebarTab>(initialTab);
// Picking something on the page is a request to see its properties, so the
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/MobileEditorSheets.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/MobileEditorSheets.tsx
index 9d4f476409..8aa3749194 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/MobileEditorSheets.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/MobileEditorSheets.tsx
@@ -27,7 +27,8 @@ export function MobileEditorSheets(props: Omit<SidebarProps, "initialTab">) {
const hasSelection =
selection.runIds.length > 0 ||
selection.imageIds.length > 0 ||
- selection.shapeIds.length > 0;
+ selection.shapeIds.length > 0 ||
+ selection.formFieldId !== null;
useEffect(() => {
if (sheet === "style" && !controller.hasRunSelection) {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
index 7e4b1ad880..f4b7432f4b 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
@@ -43,11 +43,15 @@ interface PageViewProps {
selectedRunIds: string[];
selectedImageIds: string[];
selectedShapeIds: string[];
+ /** The AnnotationBox id of the selected form field widget. */
+ selectedFormFieldId?: string | null;
/** Run id currently highlighted by the find-bar (yellow). */
highlightedRunId?: string | null;
onSelectRun: (runId: string, shiftKey: boolean) => void;
onSelectImage: (imageId: string) => void;
onSelectShape: (shapeId: string, extend: boolean) => void;
+ /** Selects a form field widget by its AnnotationBox id. */
+ onSelectFormField?: (annotationId: string) => void;
/** Fires when a shape drag completes; dx/dy in raw PDF points. */
onMoveShape?: (
pageIndex: number,
@@ -111,10 +115,12 @@ export const PageView = memo(function PageView({
selectedRunIds,
selectedImageIds,
selectedShapeIds,
+ selectedFormFieldId = null,
highlightedRunId,
onSelectRun,
onSelectImage,
onSelectShape,
+ onSelectFormField,
onMoveShape,
onEditRun,
onSelectRunText,
@@ -358,6 +364,14 @@ export const PageView = memo(function PageView({
pageHeight={page.height}
transform={transform}
scale={cssScale}
+ selected={annotation.id === selectedFormFieldId}
+ onSelect={
+ ACCESSIBILITY_EDITING &&
+ annotation.kind === "widget" &&
+ onSelectFormField
+ ? () => onSelectFormField(annotation.id)
+ : undefined
+ }
/>
))}
{/* Before images and runs: anything drawn over a shape wins its clicks. */}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditLayer.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditLayer.tsx
index e662467fce..94c791b428 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditLayer.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditLayer.tsx
@@ -113,6 +113,9 @@ function EditablePage({
const imageIds = useOwnIds(selection.imageIds, page.images);
const shapeIds = useOwnIds(selection.shapeIds, page.shapes);
const ownsHighlight = page.runs.some((r) => r.id === highlightedRunId);
+ const ownsFormField = (page.annotations ?? []).some(
+ (a) => a.id === selection.formFieldId,
+ );
const handlers = pageViewHandlers(store);
return (
@@ -126,6 +129,7 @@ function EditablePage({
selectedRunIds={runIds}
selectedImageIds={imageIds}
selectedShapeIds={shapeIds}
+ selectedFormFieldId={ownsFormField ? selection.formFieldId : null}
highlightedRunId={ownsHighlight ? highlightedRunId : null}
selectedTextRange={
runIds.length === 1 && selection.runIds.length === 1
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/FormFieldAccessibilitySection.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/FormFieldAccessibilitySection.test.tsx
new file mode 100644
index 0000000000..4ab62763cc
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/FormFieldAccessibilitySection.test.tsx
@@ -0,0 +1,77 @@
+import { MantineProvider } from "@mantine/core";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { FormFieldAccessibilitySection } from "@editor/tools/pdfTextEditor/components/inspector/FormFieldAccessibilitySection";
+import type { FormFieldAccessibility } from "@editor/tools/pdfTextEditor/util/formFieldAccessibility";
+
+const KEY = "pdfTextEditor.inspector.accessibility";
+const WIDGET = {
+ annotation: 20,
+ position: 0,
+ field: 20,
+ fieldShared: false,
+ rect: { x: 110, y: 694, width: 190, height: 20 },
+ fieldType: "Tx",
+ tooltip: null,
+ holder: null,
+};
+
+function editable(
+ tagged: boolean,
+ description: string | null = null,
+): FormFieldAccessibility {
+ return { kind: "editable", widget: WIDGET, tagged, description };
+}
+
+function renderSection(accessibility: FormFieldAccessibility) {
+ const onTag = vi.fn();
+ const onSetDescription = vi.fn();
+ render(
+ <MantineProvider env="test">
+ <FormFieldAccessibilitySection
+ accessibility={accessibility}
+ onTag={onTag}
+ onSetDescription={onSetDescription}
+ />
+ </MantineProvider>,
+ );
+ return { onTag, onSetDescription };
+}
+
+describe("FormFieldAccessibilitySection", () => {
+ it("offers tagging an untagged field", () => {
+ const { onTag } = renderSection(editable(false));
+ expect(screen.getByTestId("pdf-editor-form-field-tag")).toHaveTextContent(
+ `${KEY}.untaggedBadge`,
+ );
+ fireEvent.click(screen.getByTestId("pdf-editor-tag-form-field"));
+ expect(onTag).toHaveBeenCalled();
+ });
+
+ it("offers no tagging for a tagged field", () => {
+ renderSection(editable(true));
+ expect(screen.getByTestId("pdf-editor-form-field-tag")).toHaveTextContent(
+ `${KEY}.tagName.form`,
+ );
+ expect(screen.queryByTestId("pdf-editor-tag-form-field")).toBeNull();
+ });
+
+ it("edits the field's description", () => {
+ const { onSetDescription } = renderSection(editable(true, "Name"));
+ const field = screen.getByTestId("pdf-editor-form-field-description");
+ expect(field).toHaveValue("Name");
+ fireEvent.change(field, { target: { value: "Full name" } });
+ expect(onSetDescription).toHaveBeenCalledWith("Full name");
+ });
+
+ it("says why a field can't be changed, and offers nothing", () => {
+ renderSection({ kind: "blocked", blocker: "unknown" });
+ expect(
+ screen.getByTestId("pdf-editor-form-field-accessibility-status"),
+ ).toHaveTextContent(`${KEY}.cannotTagFormField`);
+ expect(screen.queryByTestId("pdf-editor-tag-form-field")).toBeNull();
+ expect(
+ screen.queryByTestId("pdf-editor-form-field-description"),
+ ).toBeNull();
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/FormFieldAccessibilitySection.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/FormFieldAccessibilitySection.tsx
new file mode 100644
index 0000000000..416a9b9ec0
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/FormFieldAccessibilitySection.tsx
@@ -0,0 +1,117 @@
+import { Stack, Text, Textarea } from "@mantine/core";
+import type { TFunction } from "i18next";
+import { useTranslation } from "react-i18next";
+import { Button } from "@editor/ui/Button";
+import { Icon } from "@editor/ui/Icon";
+import {
+ Section,
+ SectionLabel,
+ StatRow,
+} from "@editor/tools/pdfTextEditor/components/inspector/InspectorPrimitives";
+import type {
+ FormFieldAccessibility,
+ FormFieldBlocker,
+} from "@editor/tools/pdfTextEditor/util/formFieldAccessibility";
+import { privateContentClassName } from "@editor/components/shared/privateContentClassName";
+
+/**
+ * Whether the selected form field is tagged, with a way to tag it, and the
+ * description its field is read by; or why neither can change.
+ */
+export function FormFieldAccessibilitySection({
+ accessibility,
+ onTag,
+ onSetDescription,
+}: {
+ accessibility: FormFieldAccessibility;
+ onTag: () => void;
+ onSetDescription: (text: string) => void;
+}) {
+ const { t } = useTranslation();
+ return (
+ <Section testId="pdf-editor-form-field-accessibility">
+ <SectionLabel>
+ {t("pdfTextEditor.inspector.accessibility.heading", "Accessibility")}
+ </SectionLabel>
+ {accessibility.kind === "blocked" ? (
+ <Text
+ size="xs"
+ c="dimmed"
+ data-testid="pdf-editor-form-field-accessibility-status"
+ >
+ {blockedMessage(t, accessibility.blocker)}
+ </Text>
+ ) : (
+ <Stack gap="xs">
+ <StatRow
+ label={t("pdfTextEditor.inspector.accessibility.tagLabel", "Tag")}
+ value={
+ <span data-testid="pdf-editor-form-field-tag">
+ {accessibility.tagged
+ ? t(
+ "pdfTextEditor.inspector.accessibility.tagName.form",
+ "Form field",
+ )
+ : t(
+ "pdfTextEditor.inspector.accessibility.untaggedBadge",
+ "Not tagged",
+ )}
+ </span>
+ }
+ />
+ {!accessibility.tagged && (
+ <Button
+ size="sm"
+ variant="secondary"
+ accent="neutral"
+ fullWidth
+ justify="start"
+ leftSection={<Icon name="form-input" size={20} />}
+ onClick={onTag}
+ data-testid="pdf-editor-tag-form-field"
+ >
+ {t(
+ "pdfTextEditor.inspector.accessibility.tagFormField",
+ "Tag form field",
+ )}
+ </Button>
+ )}
+ <Textarea
+ label={t(
+ "pdfTextEditor.inspector.accessibility.formFieldDescription",
+ "Field description",
+ )}
+ value={accessibility.description ?? ""}
+ className={privateContentClassName}
+ onChange={(e) => onSetDescription(e.currentTarget.value)}
+ autosize
+ minRows={1}
+ maxRows={4}
+ size="xs"
+ data-testid="pdf-editor-form-field-description"
+ />
+ </Stack>
+ )}
+ </Section>
+ );
+}
+
+function blockedMessage(t: TFunction, blocker: FormFieldBlocker): string {
+ switch (blocker) {
+ case "encrypted":
+ return t(
+ "pdfTextEditor.inspector.accessibility.encrypted",
+ "Tags can't be edited in an encrypted file",
+ );
+ case "unreadable":
+ return t(
+ "pdfTextEditor.inspector.accessibility.unreadable",
+ "This file's tags can't be edited",
+ );
+ case "unknown":
+ return t(
+ "pdfTextEditor.inspector.accessibility.cannotTagFormField",
+ "This form field can't be tagged.",
+ );
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx
index 9fbf2a288d..54bb78aa8f 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx
@@ -14,6 +14,7 @@ import type { useToolbarController } from "@editor/tools/pdfTextEditor/hooks/use
import type { SelectionState } from "@editor/tools/pdfTextEditor/types";
import { modShortcut } from "@editor/utils/hotkeys";
import { ACCESSIBILITY_EDITING } from "@editor/constants/featureFlags";
+import { FormFieldAccessibilitySection } from "@editor/tools/pdfTextEditor/components/inspector/FormFieldAccessibilitySection";
import { ImageAccessibilitySection } from "@editor/tools/pdfTextEditor/components/inspector/ImageAccessibilitySection";
import { TextAccessibilitySection } from "@editor/tools/pdfTextEditor/components/inspector/TextAccessibilitySection";
import { ScanFontMatchRow } from "@editor/tools/pdfTextEditor/components/inspector/ScanFontMatchModal";
@@ -64,6 +65,7 @@ export function SelectionInspector({
runCount={runCount}
imageCount={imageCount}
shapeCount={shapeCount}
+ formField={selection.formFieldId !== null}
fontNote={hasRunSelection ? fontNote : null}
/>
{scanFontMatch?.canShow && <ScanFontMatchRow match={scanFontMatch} />}
@@ -99,6 +101,13 @@ export function SelectionInspector({
onNext={controller.onSelectNextImageToReview}
/>
)}
+ {ACCESSIBILITY_EDITING && controller.formFieldAccessibility && (
+ <FormFieldAccessibilitySection
+ accessibility={controller.formFieldAccessibility}
+ onTag={controller.onTagFormField}
+ onSetDescription={controller.onSetFormFieldDescription}
+ />
+ )}
</Stack>
);
}
@@ -108,17 +117,22 @@ function SelectionHeader({
runCount,
imageCount,
shapeCount,
+ formField,
fontNote,
}: {
runCount: number;
imageCount: number;
shapeCount: number;
+ /** A form field is only ever selected alone. */
+ formField: boolean;
fontNote: string | null;
}) {
const { t } = useTranslation();
const kinds = [runCount, imageCount, shapeCount].filter((n) => n > 0).length;
let title: string;
- if (kinds > 1) {
+ if (formField) {
+ title = t("pdfTextEditor.inspector.formField", "Form field");
+ } else if (kinds > 1) {
title = t("pdfTextEditor.inspector.mixed", "{{count}} objects", {
count: runCount + imageCount + shapeCount,
});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useFormFieldAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useFormFieldAccessibility.ts
new file mode 100644
index 0000000000..d413615c5a
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useFormFieldAccessibility.ts
@@ -0,0 +1,77 @@
+import { useCallback, useMemo } from "react";
+import { SetFormFieldTooltipCommand } from "@editor/tools/pdfTextEditor/commands/SetFormFieldTooltipCommand";
+import { TagFormFieldCommand } from "@editor/tools/pdfTextEditor/commands/TagFormFieldCommand";
+import type {
+ EditorStore,
+ EditorViewState,
+} from "@editor/tools/pdfTextEditor/store/EditorStore";
+import type { SelectionState } from "@editor/tools/pdfTextEditor/types";
+import {
+ formFieldAccessibility,
+ type FormFieldAccessibility,
+} from "@editor/tools/pdfTextEditor/util/formFieldAccessibility";
+
+interface SelectedFormField {
+ pageIndex: number;
+ accessibility: FormFieldAccessibility;
+}
+
+/** The accessibility of the selected form field, null when none is selected. */
+export function useFormFieldAccessibility(
+ store: EditorStore,
+ state: EditorViewState,
+ selection: SelectionState,
+) {
+ const { formFieldId } = selection;
+ const selected = useMemo((): SelectedFormField | null => {
+ const doc = store.document;
+ if (!doc || formFieldId === null) return null;
+ for (const page of state.pages) {
+ const box = page.annotations?.find((a) => a.id === formFieldId);
+ if (box) {
+ const { pageIndex } = page;
+ const accessibility = formFieldAccessibility(doc, pageIndex, box.index);
+ return { pageIndex, accessibility };
+ }
+ }
+ return null;
+ }, [store, state.pages, formFieldId]);
+
+ const tag = useCallback(() => {
+ const field = editableField(selected);
+ if (!field || field.tagged) return;
+ store.dispatch(
+ new TagFormFieldCommand({
+ pageIndex: field.pageIndex,
+ annotation: field.widget.annotation,
+ }),
+ );
+ }, [store, selected]);
+
+ const setDescription = useCallback(
+ (text: string) => {
+ const field = editableField(selected);
+ if (!field) return;
+ // An emptied field removes the description rather than saving an empty one.
+ store.dispatch(
+ new SetFormFieldTooltipCommand({
+ pageIndex: field.pageIndex,
+ annotation: field.widget.annotation,
+ tooltip: text === "" ? null : text,
+ }),
+ );
+ },
+ [store, selected],
+ );
+
+ return {
+ accessibility: selected?.accessibility ?? null,
+ tag,
+ setDescription,
+ };
+}
+
+function editableField(selected: SelectedFormField | null) {
+ if (selected?.accessibility.kind !== "editable") return null;
+ return { pageIndex: selected.pageIndex, ...selected.accessibility };
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useOpenAtViewerText.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useOpenAtViewerText.ts
index 635f6bab5f..5576e9b514 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useOpenAtViewerText.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useOpenAtViewerText.ts
@@ -56,6 +56,7 @@ export function useOpenAtViewerText(
runIds: [found.runId],
imageIds: [],
shapeIds: [],
+ formFieldId: null,
caret: null,
textRange: found.range,
});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts
index 609780f3e3..3d433ccdc1 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts
@@ -6,6 +6,7 @@ import {
useSyncExternalStore,
} from "react";
import { useSelectionActions } from "@editor/tools/pdfTextEditor/hooks/useSelectionActions";
+import { useFormFieldAccessibility } from "@editor/tools/pdfTextEditor/hooks/useFormFieldAccessibility";
import { useImageAccessibility } from "@editor/tools/pdfTextEditor/hooks/useImageAccessibility";
import { useTextAccessibility } from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";
import {
@@ -65,6 +66,7 @@ export function useToolbarController(
const sel = useSelectionActions(store);
const imageA11y = useImageAccessibility(store, state, selection);
const textA11y = useTextAccessibility(store, state, selection);
+ const formFieldA11y = useFormFieldAccessibility(store, state, selection);
const onToggleLock = useCallback(() => {
const doc = store.document;
@@ -557,6 +559,9 @@ export function useToolbarController(
textLanguage: textA11y.language,
textOtherPages: textA11y.otherPages,
textUntaggedLinks: textA11y.untaggedLinks,
+ formFieldAccessibility: formFieldA11y.accessibility,
+ onTagFormField: formFieldA11y.tag,
+ onSetFormFieldDescription: formFieldA11y.setDescription,
selectionAllLocked,
hasRunSelection: selection.runIds.length > 0,
hasImageSelection: selection.imageIds.length > 0,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/AnnotationBox.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/AnnotationBox.ts
index 6c164854b8..a0734c7350 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/AnnotationBox.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/AnnotationBox.ts
@@ -10,6 +10,8 @@ export type AnnotationKind = "freetext" | "widget" | "stamp";
export interface AnnotationBox {
id: string;
kind: AnnotationKind;
+ /** Its index in the page's /Annots, which is how PDFium numbers annotations. */
+ index: number;
/** Raw PDF page-space rect (y-up), pre-DisplayTransform. */
rect: { x: number; y: number; width: number; height: number };
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts
index c12390a77e..741df9f52c 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts
@@ -49,6 +49,8 @@ import {
precedingTaggedMcid,
taggedContentInReadingOrder,
} from "@editor/tools/pdfTextEditor/util/elementPlacement";
+import { fieldAnchor } from "@editor/tools/pdfTextEditor/util/formLabel";
+import type { FieldTooltips } from "@editor/tools/pdfTextEditor/model/PageFormFields";
import { DisplayTransform } from "@editor/tools/pdfTextEditor/model/DisplayTransform";
import { FontRef } from "@editor/tools/pdfTextEditor/model/FontRef";
import { prepareForEditing } from "@editor/tools/pdfTextEditor/pdfdoc/prepareForEditing";
@@ -71,6 +73,8 @@ export class EditorDocument {
readonly openedBytes: Uint8Array;
private readonly pageCache: Map<number, Page>;
private readonly structureCache = new Map<number, PageStructure>();
+ /** Held here rather than per page: a field's widgets can sit on several pages. */
+ private readonly fieldTooltips: FieldTooltips = new Map();
/**
* Unsaved retags by block key, each with the content the save addresses it
* by. Held here rather than per page: an element spanning a page break is
@@ -333,16 +337,29 @@ export class EditorDocument {
);
}
const page = this.fileStructure.pages.get(pageIndex);
- const links = this.fileStructure.links.get(pageIndex) ?? [];
+ const annotations = {
+ links: this.fileStructure.links.get(pageIndex) ?? [],
+ widgets: this.fileStructure.widgets.get(pageIndex) ?? [],
+ };
const retaggedAs = (key: string) => this.retaggedAs(key);
- if (!page) return new PageStructure([], null, 0, retaggedAs, links);
+ if (!page) {
+ return new PageStructure(
+ [],
+ null,
+ 0,
+ retaggedAs,
+ annotations,
+ this.fieldTooltips,
+ );
+ }
if (page.slotCount === null) return new PageStructure([], "unreadable");
return new PageStructure(
page.elements,
null,
page.slotCount,
retaggedAs,
- links,
+ annotations,
+ this.fieldTooltips,
);
}
@@ -667,24 +684,63 @@ export class EditorDocument {
];
}
+ /** Every unsaved change to a link or form field annotation, in the form the save pass takes. */
+ annotationEdits(): AnnotationEdit[] {
+ const namedFields = new Set<number>();
+ return [...this.structureCache].flatMap(([pageIndex, structure]) => [
+ ...this.linkEdits(pageIndex, structure),
+ ...this.formFieldEdits(pageIndex, structure, namedFields),
+ ]);
+ }
+
/**
- * Every unsaved change to a link annotation, in the form the save pass
- * takes. A link whose holder's text is no longer on the page is left
- * unheld, as the save drops a session element with no text (cutEdits,
+ * A link whose holder's text is no longer on the page is left unheld, as
+ * the save drops a session element with no text (cutEdits,
* addedElementEdits).
*/
- annotationEdits(): AnnotationEdit[] {
- return [...this.structureCache].flatMap(([pageIndex, structure]) => {
- const page = this.pageCache.get(pageIndex);
- const carried = page && carriedMcids(this.module, page.pagePtr);
- return structure.linkEdits().flatMap(({ mcid, ...edit }) => {
- const held = mcid !== undefined && (!carried || carried.has(mcid));
- if (!held && edit.contents === undefined) return [];
- return [{ pageIndex, ...edit, ...(held && { mcid }) }];
- });
+ private linkEdits(
+ pageIndex: number,
+ structure: PageStructure,
+ ): AnnotationEdit[] {
+ const page = this.pageCache.get(pageIndex);
+ const carried = page && carriedMcids(this.module, page.pagePtr);
+ return structure.linkEdits().flatMap(({ mcid, ...edit }) => {
+ const held = mcid !== undefined && (!carried || carried.has(mcid));
+ if (!held && edit.contents === undefined) return [];
+ return [{ pageIndex, ...edit, ...(held && { mcid }) }];
});
}
+ /**
+ * A new Form reads where fieldAnchor places it on the page as the save
+ * finds it. A field's /TU goes through the first of its widgets only;
+ * `namedFields` collects the fields named so far.
+ */
+ private formFieldEdits(
+ pageIndex: number,
+ structure: PageStructure,
+ namedFields: Set<number>,
+ ): AnnotationEdit[] {
+ const page = this.pageCache.get(pageIndex);
+ return structure.formFields
+ .edits()
+ .flatMap(({ widget, newForm, tooltip }) => {
+ const names = tooltip !== undefined && !namedFields.has(widget.field);
+ if (names) namedFields.add(widget.field);
+ if (!newForm && !names) return [];
+ return [
+ {
+ pageIndex,
+ annotation: widget.annotation,
+ ...(names && { tooltip }),
+ ...(newForm && {
+ newForm: { after: page ? fieldAnchor(page, widget) : null },
+ }),
+ },
+ ];
+ });
+ }
+
/**
* The page's added elements, each after the added element it reads after,
* so it finds that already in the tree. Text cut from an element stands
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/PageFormFields.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/PageFormFields.ts
new file mode 100644
index 0000000000..a9fd636577
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/PageFormFields.ts
@@ -0,0 +1,99 @@
+import type { ReadOnlyReason } from "@editor/tools/pdfTextEditor/model/PageStructure";
+import type { WidgetAnnotation } from "@editor/tools/pdfTextEditor/model/WidgetAnnotation";
+
+/** A change to one of the page's widgets, for the save (see AnnotationEdit). */
+export interface FormFieldEdit {
+ widget: WidgetAnnotation;
+ /** True when the save gives it a Form element of its own. */
+ newForm: boolean;
+ /** The /TU to save on its field, null for none; absent leaves the file's. */
+ tooltip?: string | null;
+}
+
+/**
+ * The session's /TU edits, by field object number. One per document, shared
+ * by every page's PageFormFields, so all the widgets of a field show and save
+ * one name.
+ */
+export type FieldTooltips = Map<number, string | null>;
+
+/**
+ * The page's form field widgets and the session's unsaved changes to them:
+ * which the session gives a Form element, and the name each field is read by.
+ */
+export class PageFormFields {
+ private readonly widgets: ReadonlyMap<number, WidgetAnnotation>;
+ private readonly tagged = new Set<number>();
+
+ constructor(
+ widgets: readonly WidgetAnnotation[],
+ private readonly readOnly: ReadOnlyReason | null,
+ private readonly tooltips: FieldTooltips = new Map(),
+ ) {
+ this.widgets = new Map(widgets.map((w) => [w.annotation, w]));
+ }
+
+ all(): WidgetAnnotation[] {
+ return [...this.widgets.values()];
+ }
+
+ /** True when an element holds the widget: the file's, or a Form the session gives it. */
+ held(annotation: number): boolean {
+ return (
+ this.known(annotation).holder !== null || this.tagged.has(annotation)
+ );
+ }
+
+ /**
+ * Give the widget a Form element of its own, or take it back with false.
+ * Throws for a page whose save cannot write it, a widget the page does not
+ * have, and one the file already gives an element.
+ */
+ setTagged(annotation: number, tagged: boolean): void {
+ if (this.editable(annotation).holder !== null) {
+ throw new Error(`Widget ${annotation} already has an element`);
+ }
+ if (tagged) this.tagged.add(annotation);
+ else this.tagged.delete(annotation);
+ }
+
+ /** The /TU of the widget's field as it will be saved: the session's, else the file's. Throws for an unknown widget. */
+ tooltip(annotation: number): string | null {
+ const { field, tooltip } = this.known(annotation);
+ return this.tooltips.has(field) ? this.tooltips.get(field)! : tooltip;
+ }
+
+ /** Set or, with null, remove the /TU of the widget's field. Throws as setTagged does, bar the holder. */
+ setTooltip(annotation: number, tooltip: string | null): void {
+ const widget = this.editable(annotation);
+ if (tooltip === widget.tooltip) this.tooltips.delete(widget.field);
+ else this.tooltips.set(widget.field, tooltip);
+ }
+
+ /** Each widget of a renamed field carries the name: the caller saves it once per field. */
+ edits(): FormFieldEdit[] {
+ return this.all().flatMap((widget) => {
+ const newForm = this.tagged.has(widget.annotation);
+ const named = this.tooltips.has(widget.field);
+ if (!newForm && !named) return [];
+ return [
+ {
+ widget,
+ newForm,
+ ...(named && { tooltip: this.tooltips.get(widget.field)! }),
+ },
+ ];
+ });
+ }
+
+ private editable(annotation: number): WidgetAnnotation {
+ if (this.readOnly) throw new Error(`The page is ${this.readOnly}`);
+ return this.known(annotation);
+ }
+
+ private known(annotation: number): WidgetAnnotation {
+ const widget = this.widgets.get(annotation);
+ if (!widget) throw new Error(`No widget ${annotation} on the page`);
+ return widget;
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts
index 43f39b4d95..85e8c96f2c 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts
@@ -1,5 +1,10 @@
import type { Furniture } from "@editor/tools/pdfTextEditor/model/artifactKind";
import type { LinkAnnotation } from "@editor/tools/pdfTextEditor/model/LinkAnnotation";
+import {
+ PageFormFields,
+ type FieldTooltips,
+} from "@editor/tools/pdfTextEditor/model/PageFormFields";
+import type { WidgetAnnotation } from "@editor/tools/pdfTextEditor/model/WidgetAnnotation";
import type {
StructureRole,
StructureType,
@@ -274,6 +279,14 @@ export interface ElementLanguageEdit {
lang: string | null;
}
+/** The page's annotations the save can give an element. */
+export interface PageAnnotations {
+ links: readonly LinkAnnotation[];
+ widgets: readonly WidgetAnnotation[];
+}
+
+const NO_ANNOTATIONS: PageAnnotations = { links: [], widgets: [] };
+
/** A change to one of the page's link annotations, for the save (see AnnotationEdit). */
export interface LinkEdit {
annotation: number;
@@ -326,6 +339,7 @@ export class PageStructure {
/** Why the save cannot write descriptions for this page, or null when it can. */
readonly readOnly: ReadOnlyReason | null;
+ readonly formFields: PageFormFields;
/**
* The length of the page's ParentTree array, so the first MCID it has no
* slot for; null when the page has no array to add an element to.
@@ -338,14 +352,20 @@ export class PageStructure {
readOnly: ReadOnlyReason | null = null,
slotCount: number | null = null,
retaggedAs: RetagLookup = () => null,
- links: readonly LinkAnnotation[] = [],
+ annotations: PageAnnotations = NO_ANNOTATIONS,
+ fieldTooltips?: FieldTooltips,
) {
this.elements = elements;
this.readOnly = readOnly;
this.slotCount = slotCount;
this.retaggedAs = retaggedAs;
this.linkAnnotations = new Map(
- links.map((link) => [link.annotation, link]),
+ annotations.links.map((link) => [link.annotation, link]),
+ );
+ this.formFields = new PageFormFields(
+ annotations.widgets,
+ readOnly,
+ fieldTooltips,
);
this.fileElements = new Set(elements);
for (const el of elements) {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/WidgetAnnotation.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/WidgetAnnotation.ts
new file mode 100644
index 0000000000..a85da01f33
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/WidgetAnnotation.ts
@@ -0,0 +1,21 @@
+import type { PageRect } from "@editor/tools/pdfTextEditor/types";
+
+/** A form field's widget annotation, as the save addresses it. */
+export interface WidgetAnnotation {
+ /** Its object number, which the save gives it a Form element by. */
+ annotation: number;
+ /** Its index in the page's /Annots: the AnnotationBox.index PDFium reads it at. */
+ position: number;
+ /** The object number of the field whose /TU names it: its /Parent when it is a kid, else itself. */
+ field: number;
+ /** True when another widget a page shows belongs to its field too, as a radio group's do. */
+ fieldShared: boolean;
+ /** Its /Rect, in page space (y-up). */
+ rect: PageRect;
+ /** Its field's /FT, inherited through /Parent; null when none says. */
+ fieldType: string | null;
+ /** Its field's /TU as the file has it; null when it has none. */
+ tooltip: string | null;
+ /** The key of the element the file gives it to; null when none. */
+ holder: string | null;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addElements.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addElements.ts
index dddd5c0e37..edaee50410 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addElements.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addElements.ts
@@ -41,7 +41,8 @@ export interface NewElement {
cutFrom?: boolean;
}
-interface Placement {
+/** Where a new element joins `parent`'s kids: beside `sibling`, or last when that is null or not among them. */
+export interface Placement {
parent: number;
sibling: number | null;
before: boolean;
@@ -117,7 +118,7 @@ export function textEntry(key: string, value: string | null): string {
* page's first tagged content; else last in the document's top element, for a
* page with no tagged content.
*/
-function placement(
+export function placement(
pdf: RawPdf,
body: (num: number) => string | null,
treeRoot: number,
@@ -145,7 +146,7 @@ function placement(
}
/** The parent's body with `num` among its /K as `place` puts it; at the end when the sibling is not there. */
-function withKid(
+export function withKid(
pdf: RawPdf,
parent: string,
place: Placement,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyAnnotationEdits.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyAnnotationEdits.ts
index c8e6f95ee8..2efe9e7535 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyAnnotationEdits.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyAnnotationEdits.ts
@@ -1,19 +1,25 @@
/**
- * Give annotations their place in the structure tree and their /Contents, as
- * an appended revision. An element holds an annotation through an OBJR kid,
- * and the annotation names it back through /StructParent and that key's
- * ParentTree entry (ISO 32000-1 14.7.4.4). PDF/UA-1 7.18 also wants the
- * annotation's /Contents, and /Tabs /S on its page.
+ * Give annotations their place in the structure tree, their /Contents and a
+ * widget's field its /TU, as an appended revision. An element holds an
+ * annotation through an OBJR kid, and the annotation names it back through
+ * /StructParent and that key's ParentTree entry (ISO 32000-1 14.7.4.4).
+ * PDF/UA-1 7.18 also wants the annotation's /Contents, a widget in a Form
+ * element with its field's /TU, and /Tabs /S on its page.
*/
import { elementKids } from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";
import {
addTreeEntries,
firstFreeKey,
} from "@editor/tools/pdfTextEditor/pdfdoc/parentTreeEntries";
+import {
+ placement,
+ withKid,
+} from "@editor/tools/pdfTextEditor/pdfdoc/passes/addElements";
import {
elementOwning,
withTextEntry,
} from "@editor/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits";
+import { ensureStructureTree } from "@editor/tools/pdfTextEditor/pdfdoc/passes/ensureStructureTree";
import {
RawPdf,
arrayItems,
@@ -26,6 +32,8 @@ import {
plainObject,
unusedObjectNumber,
} from "@editor/tools/pdfTextEditor/pdfdoc/revision";
+import { separateField } from "@editor/tools/pdfTextEditor/pdfdoc/readWidgets";
+import { StructureNodes } from "@editor/tools/pdfTextEditor/pdfdoc/structureNodes";
/** A change to one annotation on a page. */
export interface AnnotationEdit {
@@ -37,8 +45,19 @@ export interface AnnotationEdit {
* edits leave the tree; absent leaves it where it is.
*/
mcid?: number;
+ /**
+ * Give a widget a new Form element holding only it, read after the content
+ * with MCID `after` (see NewElement.after); absent leaves it where it is.
+ * Forms read after the same content keep the order of their edits.
+ */
+ newForm?: { after: number | null };
/** The new /Contents; null removes it, absent leaves it. */
contents?: string | null;
+ /**
+ * The new /TU of a widget's field, the name a screen reader gives the
+ * field; null removes it, absent leaves it.
+ */
+ tooltip?: string | null;
}
export interface AnnotationEditFailure {
@@ -64,9 +83,10 @@ export class AnnotationEditError extends Error {
/**
* Apply `edits` to `bytes`, all or none; later edits to the same annotation
- * win. Runs after applyStructureEdits, whose elements an edit's MCID may
- * name. Giving an annotation to the element that already holds it changes
- * nothing. Throws AnnotationEditError when any edit cannot be written.
+ * or field win. Runs after applyStructureEdits, whose elements an edit's MCID
+ * may name. Giving an annotation to the element that already holds it
+ * changes nothing. Throws AnnotationEditError when any edit cannot be
+ * written.
*/
export async function applyAnnotationEdits(
bytes: Uint8Array,
@@ -76,95 +96,234 @@ export async function applyAnnotationEdits(
const fail = (reason: string) =>
new AnnotationEditError(edits.map((edit) => ({ edit, reason })));
- const pdf = await RawPdf.parse(bytes);
- if (!pdf) throw fail("the file could not be read");
+ const opened = await RawPdf.parse(bytes);
+ if (!opened) throw fail("the file could not be read");
// Strings in an encrypted file must be encrypted too, which this cannot do.
- if (pdf.encrypted) throw fail("the file is encrypted");
- const keys = edits.some((edit) => edit.mcid !== undefined)
+ if (opened.encrypted) throw fail("the file is encrypted");
+ // A Form can be the first element in the file or on its page.
+ const skeleton = ensureStructureTree(
+ opened,
+ edits.filter((edit) => edit.newForm).map((edit) => edit.pageIndex),
+ );
+ if (typeof skeleton === "string") throw fail(skeleton);
+ const pdf = skeleton ? await RawPdf.parse(skeleton) : opened;
+ if (!pdf) throw fail("the file could not be read");
+ const keys = edits.some((edit) => edit.mcid !== undefined || edit.newForm)
? ParentKeys.open(pdf)
: null;
if (typeof keys === "string") throw fail(keys);
- const bodies = new Map<number, string>();
- const body = (num: number) => bodies.get(num) ?? pdf.objectBody(num);
- const holders = new Map<number, number>();
- const failures: AnnotationEditFailure[] = [];
- for (const edit of edits) {
- const pageNum = pdf.pageNumberAt(edit.pageIndex);
- const page = pageNum === null ? null : body(pageNum);
- if (pageNum === null || !page) {
- failures.push({ edit, reason: "no such page" });
- continue;
+ const revision = new AnnotationRevision(pdf, keys);
+ const failures = edits.flatMap((edit) => {
+ const reason = revision.write(edit);
+ return reason === null ? [] : [{ edit, reason }];
+ });
+ if (failures.length > 0) throw new AnnotationEditError(failures);
+ if (keys && !keys.write(revision.bodies)) {
+ throw fail("the ParentTree cannot be extended");
+ }
+
+ const out = appendRevision(
+ pdf,
+ [...revision.bodies].map(([num, written]) => ({
+ num,
+ body: plainObject(written),
+ })),
+ );
+ if (!out)
+ throw fail("the file's cross-reference structure cannot be extended");
+ return out;
+}
+
+/** Why an edit cannot be written. */
+class Refused extends Error {}
+
+/** The objects a save rewrites, as its edits leave them. */
+class AnnotationRevision {
+ readonly bodies = new Map<number, string>();
+ /** The element this save gives each annotation to, by annotation. */
+ private readonly holders = new Map<number, number>();
+ /** The Form last placed after each kid, by `parent:kid`. */
+ private readonly lastPlaced = new Map<string, number>();
+ private nodes: StructureNodes | null = null;
+
+ constructor(
+ private readonly pdf: RawPdf,
+ private readonly keys: ParentKeys | null,
+ ) {}
+
+ /** Write `edit` to the bodies; why it cannot be written, or null. */
+ write(edit: AnnotationEdit): string | null {
+ try {
+ this.writeEdit(edit);
+ return null;
+ } catch (err) {
+ if (err instanceof Refused) return err.message;
+ throw err;
}
- if (!pageAnnotations(pdf, page).includes(edit.annotation)) {
- failures.push({
- edit,
- reason: "the page's /Annots does not reference it",
- });
- continue;
+ }
+
+ private body(num: number): string | null {
+ return this.bodies.get(num) ?? this.pdf.objectBody(num);
+ }
+
+ private writeEdit(edit: AnnotationEdit): void {
+ const pageNum = this.pdf.pageNumberAt(edit.pageIndex);
+ const page = pageNum === null ? null : this.body(pageNum);
+ if (pageNum === null || !page) throw new Refused("no such page");
+ if (!pageAnnotations(this.pdf, page).includes(edit.annotation)) {
+ throw new Refused("the page's /Annots does not reference it");
+ }
+ let annotation = this.body(edit.annotation);
+ const subtype = annotation
+ ? this.pdf.dictName(annotation, "Subtype")
+ : null;
+ if (!annotation || subtype === null) {
+ throw new Refused("it is not an annotation");
}
- let annotation = body(edit.annotation);
- if (!annotation || pdf.dictName(annotation, "Subtype") === null) {
- failures.push({ edit, reason: "it is not an annotation" });
- continue;
+ const widgetOnly = edit.newForm || edit.tooltip !== undefined;
+ if (widgetOnly && subtype !== "Widget") {
+ throw new Refused("it is not a widget");
+ }
+ if (edit.newForm && edit.mcid !== undefined) {
+ throw new Refused("it cannot be given two elements");
}
if (edit.contents !== undefined) {
- annotation = withTextEntry(annotation, "Contents", edit.contents);
+ annotation = dictionary(
+ withTextEntry(annotation, "Contents", edit.contents),
+ );
}
- if (annotation !== null && keys && edit.mcid !== undefined) {
- const element = elementOwning(pdf, keys.treeRoot, {
- pageIndex: edit.pageIndex,
- mcid: edit.mcid,
- });
- if (typeof element === "string") {
- failures.push({ edit, reason: element });
- continue;
- }
- const holder =
- holders.get(edit.annotation) ??
- holderOf(pdf, keys.treeRoot, annotation);
- if (holder !== null && holder !== element) {
- failures.push({ edit, reason: "another element holds it" });
- continue;
- }
- if (holder === null) {
- const held = withAnnotationKid(
- pdf,
- body(element) ?? "",
- edit.annotation,
- pageNum,
- );
- if (!held) {
- failures.push({ edit, reason: "its element's kids cannot be read" });
- continue;
- }
- bodies.set(element, held);
- holders.set(edit.annotation, element);
- const key = keys.add(element);
- annotation = setDictEntry(annotation, "StructParent", String(key));
- if (pdf.dictName(page, "Tabs") !== "S") {
- bodies.set(pageNum, setDictEntry(page, "Tabs", "/S") ?? page);
- }
+ if (edit.tooltip !== undefined) {
+ annotation = this.withTooltip(annotation, edit.tooltip);
+ }
+ const element = this.newHolder(edit, pageNum, annotation);
+ if (element !== null) {
+ this.holders.set(edit.annotation, element);
+ const key = this.parentKeys().add(element);
+ annotation = dictionary(
+ setDictEntry(annotation, "StructParent", String(key)),
+ );
+ if (this.pdf.dictName(page, "Tabs") !== "S") {
+ this.bodies.set(pageNum, setDictEntry(page, "Tabs", "/S") ?? page);
}
}
- if (annotation === null) {
- failures.push({ edit, reason: "it is not a dictionary" });
- continue;
+ this.bodies.set(edit.annotation, annotation);
+ }
+
+ private parentKeys(): ParentKeys {
+ if (!this.keys) throw new Refused("the file has no structure tree");
+ return this.keys;
+ }
+
+ /**
+ * The element the edit gives the annotation to, once it holds it; null when
+ * the edit gives it none or the element already holds it.
+ */
+ private newHolder(
+ edit: AnnotationEdit,
+ pageNum: number,
+ annotation: string,
+ ): number | null {
+ if (edit.newForm) {
+ if (this.currentHolder(edit.annotation, annotation) !== null) {
+ throw new Refused("an element already holds it");
+ }
+ return this.addForm(pageNum, edit.annotation, edit.newForm.after);
}
- bodies.set(edit.annotation, annotation);
+ if (edit.mcid === undefined) return null;
+ const element = elementOwning(this.pdf, this.parentKeys().treeRoot, {
+ pageIndex: edit.pageIndex,
+ mcid: edit.mcid,
+ });
+ if (typeof element === "string") throw new Refused(element);
+ const current = this.currentHolder(edit.annotation, annotation);
+ if (current === element) return null;
+ if (current !== null) throw new Refused("another element holds it");
+ const held = withAnnotationKid(
+ this.pdf,
+ this.body(element) ?? "",
+ edit.annotation,
+ pageNum,
+ );
+ if (!held) throw new Refused("its element's kids cannot be read");
+ this.bodies.set(element, held);
+ return element;
}
- if (failures.length > 0) throw new AnnotationEditError(failures);
- if (keys && !keys.write(bodies)) {
- throw fail("the ParentTree cannot be extended");
+
+ /** The element holding the annotation, as the edits so far leave it; null for none. */
+ private currentHolder(num: number, annotation: string): number | null {
+ return (
+ this.holders.get(num) ??
+ holderOf(this.pdf, this.parentKeys().treeRoot, annotation)
+ );
}
- const out = appendRevision(
- pdf,
- [...bodies].map(([num, written]) => ({ num, body: plainObject(written) })),
- );
- if (!out)
- throw fail("the file's cross-reference structure cannot be extended");
- return out;
+ /** A new Form element holding only the annotation, read after MCID `after` on the page. */
+ private addForm(
+ pageNum: number,
+ annotation: number,
+ after: number | null,
+ ): number {
+ const { treeRoot } = this.parentKeys();
+ const body = (num: number) => this.body(num);
+ this.nodes ??= new StructureNodes(
+ this.pdf,
+ this.pdf.objectBody(treeRoot) ?? "",
+ body,
+ );
+ const anchored = placement(
+ this.pdf,
+ body,
+ treeRoot,
+ this.nodes,
+ this.pageSlots(treeRoot, pageNum),
+ after,
+ );
+ // Each Form placed after a kid goes after the last one placed there, so
+ // they read in the order of their edits.
+ const anchor = `${anchored.parent}:${anchored.sibling}`;
+ const previous = anchored.before ? undefined : this.lastPlaced.get(anchor);
+ const place =
+ previous === undefined ? anchored : { ...anchored, sibling: previous };
+ const num = unusedObjectNumber(this.pdf, this.bodies);
+ const parent = this.body(place.parent);
+ const joined = parent ? withKid(this.pdf, parent, place, num) : null;
+ if (!joined) throw new Refused("its parent element cannot be read");
+ this.bodies.set(place.parent, joined);
+ this.bodies.set(
+ num,
+ `<< /Type /StructElem /S /Form /P ${indirectRef(this.pdf, place.parent)} ` +
+ `/Pg ${indirectRef(this.pdf, pageNum)} /K [${objr(this.pdf, annotation, pageNum)}] >>`,
+ );
+ if (!anchored.before) this.lastPlaced.set(anchor, num);
+ return num;
+ }
+
+ /** The page's ParentTree array as the file has it; empty when it has none. */
+ private pageSlots(treeRoot: number, pageNum: number): string[] {
+ const page = this.pdf.objectBody(pageNum);
+ const key = page ? this.pdf.dictInt(page, "StructParents") : null;
+ const array = key === null ? null : this.pdf.parentTreeArray(treeRoot, key);
+ return array?.items?.map((item) => item.text) ?? [];
+ }
+
+ /** The widget's body with its field's /TU set (see separateField). */
+ private withTooltip(widget: string, tooltip: string | null): string {
+ const parent = separateField(this.pdf, widget);
+ if (parent === null) {
+ return dictionary(withTextEntry(widget, "TU", tooltip));
+ }
+ const field = this.body(parent);
+ const written = field ? withTextEntry(field, "TU", tooltip) : null;
+ if (!written) throw new Refused("its field cannot be read");
+ this.bodies.set(parent, written);
+ return widget;
+ }
+}
+
+function dictionary(body: string | null): string {
+ if (body === null) throw new Refused("it is not a dictionary");
+ return body;
}
/** The object numbers of the annotations the page's /Annots references. */
@@ -188,6 +347,10 @@ function holderOf(
return entry ? referencedObject(entry.span.text) : null;
}
+function objr(pdf: RawPdf, annotation: number, pageNum: number): string {
+ return `<< /Type /OBJR /Obj ${indirectRef(pdf, annotation)} /Pg ${indirectRef(pdf, pageNum)} >>`;
+}
+
/**
* The element's body with an OBJR for the annotation last among its /K, or
* as it is when one is already there. Null when its /K cannot be read.
@@ -201,9 +364,7 @@ function withAnnotationKid(
const kids = elementKids(pdf, element);
if (!kids) return null;
if (kids.some((kid) => objrTarget(pdf, kid) === annotation)) return element;
- kids.push(
- `<< /Type /OBJR /Obj ${indirectRef(pdf, annotation)} /Pg ${indirectRef(pdf, pageNum)} >>`,
- );
+ kids.push(objr(pdf, annotation, pageNum));
return setDictEntry(element, "K", `[${kids.join(" ")}]`);
}
@@ -254,9 +415,10 @@ class ParentKeys {
bodies.set(num, written);
return num;
};
+ // A Form placed under the root has already changed its /K.
const extended = addTreeEntries(
this.pdf,
- this.rootBody,
+ bodies.get(this.treeRoot) ?? this.rootBody,
this.entries,
bodies,
allocate,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts
index 2b08840706..ca6f42ba54 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts
@@ -819,6 +819,10 @@ function visitEntries(
i += 2;
continue;
}
+ if (ch === "<") {
+ i = skipHexString(body, i);
+ continue;
+ }
if (ch === ">" && body[i + 1] === ">") {
depth -= 1;
i += 2;
@@ -863,6 +867,12 @@ function scanNameEnd(text: string, at: number): number {
return i;
}
+/** Past the `>` closing the hex string at `at`, which would otherwise read as half of a dictionary's `>>`. */
+function skipHexString(text: string, at: number): number {
+ const close = text.indexOf(">", at);
+ return close < 0 ? text.length : close + 1;
+}
+
function skipLiteralString(text: string, at: number): number {
let i = at + 1;
let depth = 1;
@@ -898,6 +908,10 @@ function scanValueEnd(text: string, at: number): number {
i += 2;
continue;
}
+ if (text[i] === "<") {
+ i = skipHexString(text, i);
+ continue;
+ }
if (text[i] === ">" && text[i + 1] === ">") {
depth -= 1;
i += 2;
@@ -908,10 +922,7 @@ function scanValueEnd(text: string, at: number): number {
}
return i;
}
- if (text[i] === "<") {
- const close = text.indexOf(">", i);
- return close < 0 ? text.length : close + 1;
- }
+ if (text[i] === "<") return skipHexString(text, i);
if (text[i] === "[") {
let depth = 0;
while (i < text.length) {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
index ce3ebff631..93fb9ef6d6 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
@@ -1,4 +1,5 @@
import type { LinkAnnotation } from "@editor/tools/pdfTextEditor/model/LinkAnnotation";
+import type { WidgetAnnotation } from "@editor/tools/pdfTextEditor/model/WidgetAnnotation";
import type { StructureElement } from "@editor/tools/pdfTextEditor/model/PageStructure";
import type { StructureRole } from "@editor/tools/pdfTextEditor/model/structureTypes";
import {
@@ -14,6 +15,7 @@ import {
type ElementNode,
} from "@editor/tools/pdfTextEditor/pdfdoc/structureNodes";
import { readLinks } from "@editor/tools/pdfTextEditor/pdfdoc/readLinks";
+import { readWidgets } from "@editor/tools/pdfTextEditor/pdfdoc/readWidgets";
import { decodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString";
import { isMarked } from "@editor/tools/pdfTextEditor/pdfdoc/passes/markTagged";
@@ -60,6 +62,8 @@ export interface FileStructure {
languages: Map<string, ElementLanguage>;
/** The link annotations the save can give an element, by page index (see readLinks). */
links: Map<number, LinkAnnotation[]>;
+ /** The widget annotations the save can give a Form element, by page index (see readWidgets). */
+ widgets: Map<number, WidgetAnnotation[]>;
/** Whether the file has a /StructTreeRoot at all. */
hasTree: boolean;
/** Whether the catalog declares the file tagged (/MarkInfo /Marked). */
@@ -87,6 +91,7 @@ export async function readFileStructure(
blocks: [],
languages: new Map(),
links: readLinks(pdf, null),
+ widgets: readWidgets(pdf, null),
hasTree: false,
marked: isMarked(pdf, catalog),
};
@@ -147,6 +152,7 @@ export async function readFileStructure(
blocks,
languages,
links: readLinks(pdf, treeRoot),
+ widgets: readWidgets(pdf, treeRoot),
hasTree: true,
marked: isMarked(pdf, catalog),
};
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readLinks.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readLinks.ts
index 9537bb5bf1..3dd775f32b 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readLinks.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readLinks.ts
@@ -22,17 +22,29 @@ export function readLinks(
pdf: RawPdf,
treeRoot: number | null,
): Map<number, LinkAnnotation[]> {
- const out = new Map<number, LinkAnnotation[]>();
+ return annotationsByPage(pdf, (num) => readLink(pdf, num, treeRoot));
+}
+
+/**
+ * What `read` makes of each annotation a page's /Annots references, given its
+ * object number and its index in /Annots, by page index; null leaves one out.
+ * Pages with none are left out.
+ */
+export function annotationsByPage<T>(
+ pdf: RawPdf,
+ read: (num: number, position: number) => T | null,
+): Map<number, T[]> {
+ const out = new Map<number, T[]>();
pdf.pageNumbers().forEach((pageNum, pageIndex) => {
const page = pdf.objectBody(pageNum);
const annots = page ? pdf.resolve(page, "Annots")?.trim() : null;
const refs = (annots ? arrayItems(annots) : null) ?? [];
- const links = refs.slice(0, MAX_ANNOTS).flatMap((ref) => {
+ const found = refs.slice(0, MAX_ANNOTS).flatMap((ref, position) => {
const num = referencedObject(ref.text);
- const link = num === null ? null : readLink(pdf, num, treeRoot);
- return link ? [link] : [];
+ const annotation = num === null ? null : read(num, position);
+ return annotation ? [annotation] : [];
});
- if (links.length > 0) out.set(pageIndex, links);
+ if (found.length > 0) out.set(pageIndex, found);
});
return out;
}
@@ -86,13 +98,14 @@ function quadAreas(values: readonly number[]): PageArea[] {
}
/** An array of numbers; null when the value is not one. */
-function numbers(value: string | null): number[] | null {
+export function numbers(value: string | null): number[] | null {
const items = value ? arrayItems(value.trim()) : null;
const read = items?.map((item) => Number(item.text));
return read?.every(Number.isFinite) ? read : null;
}
-function holderKey(
+/** The key of the element the annotation's /StructParent names; null when none. */
+export function holderKey(
pdf: RawPdf,
body: string,
treeRoot: number | null,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readWidgets.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readWidgets.ts
new file mode 100644
index 0000000000..089675de25
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readWidgets.ts
@@ -0,0 +1,99 @@
+import type { WidgetAnnotation } from "@editor/tools/pdfTextEditor/model/WidgetAnnotation";
+import {
+ annotationsByPage,
+ holderKey,
+ numbers,
+} from "@editor/tools/pdfTextEditor/pdfdoc/readLinks";
+import type { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import { decodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString";
+
+/** /F bits for an annotation no reader shows (ISO 32000-1 12.5.3): Hidden, NoView. */
+const UNSHOWN = 2 | 32;
+const MAX_FIELD_DEPTH = 32;
+
+/**
+ * The widget annotations of each page, by page index, that PDF/UA-1 7.18.4
+ * wants in a Form element: those the page's /Annots references and a reader
+ * shows. `treeRoot` resolves the element each is given to; null for a file
+ * with no structure tree. Pages with none are left out.
+ */
+export function readWidgets(
+ pdf: RawPdf,
+ treeRoot: number | null,
+): Map<number, WidgetAnnotation[]> {
+ const byPage = annotationsByPage(pdf, (num, position) =>
+ readWidget(pdf, num, position, treeRoot),
+ );
+ const widgetCounts = new Map<number, number>();
+ for (const widgets of byPage.values()) {
+ for (const { field } of widgets) {
+ widgetCounts.set(field, (widgetCounts.get(field) ?? 0) + 1);
+ }
+ }
+ return new Map(
+ [...byPage].map(([pageIndex, widgets]) => [
+ pageIndex,
+ widgets.map((widget) => ({
+ ...widget,
+ fieldShared: (widgetCounts.get(widget.field) ?? 0) > 1,
+ })),
+ ]),
+ );
+}
+
+/**
+ * The object number of the field a widget is a kid of; null when the widget
+ * is its own field. One with no /T but a /Parent is a kid, as PDFBox reads it.
+ */
+export function separateField(pdf: RawPdf, widget: string): number | null {
+ if (pdf.valueSpan(widget, "T") !== null) return null;
+ return pdf.dictRef(widget, "Parent");
+}
+
+function readWidget(
+ pdf: RawPdf,
+ num: number,
+ position: number,
+ treeRoot: number | null,
+): Omit<WidgetAnnotation, "fieldShared"> | null {
+ const body = pdf.objectBody(num);
+ if (!body || pdf.dictName(body, "Subtype") !== "Widget") return null;
+ if (((pdf.dictInt(body, "F") ?? 0) & UNSHOWN) !== 0) return null;
+ const rect = numbers(pdf.resolve(body, "Rect"));
+ if (rect?.length !== 4) return null;
+ const [x1, y1, x2, y2] = rect;
+ const area = {
+ x: Math.min(x1, x2),
+ y: Math.min(y1, y2),
+ width: Math.abs(x2 - x1),
+ height: Math.abs(y2 - y1),
+ };
+ if (area.width <= 0 || area.height <= 0) return null;
+ const field = separateField(pdf, body) ?? num;
+ const fieldBody = field === num ? body : pdf.objectBody(field);
+ const tooltip = fieldBody ? pdf.resolve(fieldBody, "TU") : null;
+ return {
+ annotation: num,
+ position,
+ field,
+ rect: area,
+ fieldType: fieldType(pdf, body),
+ tooltip: tooltip === null ? null : decodeTextString(tooltip.trim()),
+ holder: holderKey(pdf, body, treeRoot),
+ };
+}
+
+/** /FT, which a field inherits from its ancestors (ISO 32000-1 12.7.3.1). */
+function fieldType(pdf: RawPdf, widget: string): string | null {
+ let body: string | null = widget;
+ const seen = new Set<number>();
+ for (let depth = 0; body && depth < MAX_FIELD_DEPTH; depth++) {
+ const type = pdf.dictName(body, "FT");
+ if (type !== null) return type;
+ const parent = pdf.dictRef(body, "Parent");
+ if (parent === null || seen.has(parent)) return null;
+ seen.add(parent);
+ body = pdf.objectBody(parent);
+ }
+ return null;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumAnnotationReader.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumAnnotationReader.ts
index bbc4347d19..cf1d1095a5 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumAnnotationReader.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumAnnotationReader.ts
@@ -81,6 +81,7 @@ export class PdfiumAnnotationReader {
out.push({
id: `p${page.index}-annot-${i}`,
kind,
+ index: i,
rect: { x, y, width, height },
});
} finally {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/store/Selection.ts b/frontend/src/editor/core/tools/pdfTextEditor/store/Selection.ts
index 4dbc5185ed..cdb71ad621 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/store/Selection.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/store/Selection.ts
@@ -42,6 +42,7 @@ export class Selection {
runIds: [],
imageIds: [],
shapeIds: [],
+ formFieldId: null,
caret: null,
textRange: null,
};
@@ -63,6 +64,7 @@ export class Selection {
runIds: [],
imageIds: [],
shapeIds: [],
+ formFieldId: null,
caret: null,
textRange: null,
});
@@ -73,6 +75,7 @@ export class Selection {
runIds: [runId],
imageIds: [],
shapeIds: [],
+ formFieldId: null,
caret,
textRange: null,
});
@@ -83,6 +86,7 @@ export class Selection {
this.set({
...this.state,
runIds: this.state.runIds.filter((id) => id !== runId),
+ formFieldId: null,
caret: null,
textRange: null,
});
@@ -90,6 +94,7 @@ export class Selection {
this.set({
...this.state,
runIds: [...this.state.runIds, runId],
+ formFieldId: null,
caret: null,
textRange: null,
});
@@ -101,6 +106,7 @@ export class Selection {
runIds: [],
imageIds: [imageId],
shapeIds: [],
+ formFieldId: null,
caret: null,
textRange: null,
});
@@ -111,6 +117,7 @@ export class Selection {
runIds: [],
imageIds: [],
shapeIds: [shapeId],
+ formFieldId: null,
caret: null,
textRange: null,
});
@@ -120,7 +127,25 @@ export class Selection {
const shapeIds = this.state.shapeIds.includes(shapeId)
? this.state.shapeIds.filter((id) => id !== shapeId)
: [...this.state.shapeIds, shapeId];
- this.set({ ...this.state, shapeIds, caret: null, textRange: null });
+ this.set({
+ ...this.state,
+ shapeIds,
+ formFieldId: null,
+ caret: null,
+ textRange: null,
+ });
+ }
+
+ /** Select form field widget `annotationId` (an AnnotationBox id) alone. */
+ selectFormField(annotationId: string): void {
+ this.set({
+ runIds: [],
+ imageIds: [],
+ shapeIds: [],
+ formFieldId: annotationId,
+ caret: null,
+ textRange: null,
+ });
}
/**
@@ -139,6 +164,7 @@ export class Selection {
runIds: [...runIds],
imageIds: [...imageIds],
shapeIds: [...shapeIds],
+ formFieldId: null,
caret: null,
textRange: null,
});
@@ -148,6 +174,7 @@ export class Selection {
runIds: unionInOrder(this.state.runIds, runIds),
imageIds: unionInOrder(this.state.imageIds, imageIds),
shapeIds: unionInOrder(this.state.shapeIds, shapeIds),
+ formFieldId: null,
caret: null,
textRange: null,
});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/types.ts b/frontend/src/editor/core/tools/pdfTextEditor/types.ts
index 2ff71fe262..d978676dbe 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/types.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/types.ts
@@ -228,6 +228,8 @@ export interface SelectionState {
imageIds: string[];
/** Selected vector shape ids. */
shapeIds: string[];
+ /** The AnnotationBox id of the selected form field widget; only ever selected alone. */
+ formFieldId: string | null;
/** Caret position when exactly one run is selected and the user is typing */
caret: number | null;
/**
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/elementPlacement.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/elementPlacement.ts
index 3b1f64b109..fa417ad87a 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/elementPlacement.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/elementPlacement.ts
@@ -11,10 +11,12 @@ import type { PageRect } from "@editor/tools/pdfTextEditor/types";
/** Tops this close (points) read as one line. */
const SAME_LINE = 2;
-interface Box {
+/** A rect as the page displays it, y-up. */
+export interface DisplayBox {
left: number;
right: number;
top: number;
+ bottom: number;
}
/** Page-level content with an MCID, and where it is drawn. */
@@ -33,9 +35,29 @@ export function precedingTaggedMcid(
page: Page,
target: TaggedContent,
): number | null {
- const box = displayBox(page, target.bounds);
+ return lastTaggedBefore(page, displayBox(page, target.bounds), target.mcid);
+}
+
+/**
+ * The MCID of the tagged content read last before a form field drawn in
+ * `rect`, as precedingTaggedMcid reads it. The field's line is its middle,
+ * since its box is taller than the text beside it.
+ */
+export function taggedMcidBeforeField(
+ page: Page,
+ rect: PageRect,
+): number | null {
+ const box = displayBox(page, rect);
+ return lastTaggedBefore(page, { ...box, top: (box.top + box.bottom) / 2 });
+}
+
+function lastTaggedBefore(
+ page: Page,
+ box: DisplayBox,
+ except?: number,
+): number | null {
const before = taggedContent(page)
- .filter((c) => c.mcid !== target.mcid)
+ .filter((c) => c.mcid !== except)
.map((c) => ({ mcid: c.mcid, box: displayBox(page, c.bounds) }))
.filter((c) => readsBefore(c.box, box));
const inColumn = before.filter(
@@ -70,19 +92,19 @@ function taggedContent(page: Page): TaggedContent[] {
return content;
}
-function readsBefore(a: Box, b: Box): boolean {
+function readsBefore(a: DisplayBox, b: DisplayBox): boolean {
if (Math.abs(a.top - b.top) > SAME_LINE) return a.top > b.top;
return a.left < b.left;
}
-function readingOrder(a: Box, b: Box): number {
+function readingOrder(a: DisplayBox, b: DisplayBox): number {
if (readsBefore(a, b)) return -1;
if (readsBefore(b, a)) return 1;
return 0;
}
/** The rect's bounds as displayed, y-up, so a /Rotate page reads as it is shown. */
-function displayBox(page: Page, rect: PageRect): Box {
+export function displayBox(page: Page, rect: PageRect): DisplayBox {
const corners = [
page.display.apply(rect.x, rect.y),
page.display.apply(rect.x + rect.width, rect.y),
@@ -90,9 +112,11 @@ function displayBox(page: Page, rect: PageRect): Box {
page.display.apply(rect.x + rect.width, rect.y + rect.height),
];
const xs = corners.map((c) => c.x);
+ const ys = corners.map((c) => c.y);
return {
left: Math.min(...xs),
right: Math.max(...xs),
- top: Math.max(...corners.map((c) => c.y)),
+ top: Math.max(...ys),
+ bottom: Math.min(...ys),
};
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/formFieldAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/formFieldAccessibility.ts
new file mode 100644
index 0000000000..8c18f1a37b
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/formFieldAccessibility.ts
@@ -0,0 +1,39 @@
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { ReadOnlyReason } from "@editor/tools/pdfTextEditor/model/PageStructure";
+import type { WidgetAnnotation } from "@editor/tools/pdfTextEditor/model/WidgetAnnotation";
+
+/** Why a form field's accessibility can't be changed; "unknown" for a widget the save can't address. */
+export type FormFieldBlocker = ReadOnlyReason | "unknown";
+
+/** What can be said and done about one form field widget's accessibility. */
+export type FormFieldAccessibility =
+ | { kind: "blocked"; blocker: FormFieldBlocker }
+ | {
+ kind: "editable";
+ widget: WidgetAnnotation;
+ /** True when an element holds it: the file's, or a Form the session gives it. */
+ tagged: boolean;
+ /** Its field's /TU as it will be saved. */
+ description: string | null;
+ };
+
+/** The accessibility of the widget at index `position` of page `pageIndex`'s /Annots. */
+export function formFieldAccessibility(
+ doc: EditorDocument,
+ pageIndex: number,
+ position: number,
+): FormFieldAccessibility {
+ const structure = doc.structure(pageIndex);
+ if (structure.readOnly) {
+ return { kind: "blocked", blocker: structure.readOnly };
+ }
+ const fields = structure.formFields;
+ const widget = fields.all().find((w) => w.position === position);
+ if (!widget) return { kind: "blocked", blocker: "unknown" };
+ return {
+ kind: "editable",
+ widget,
+ tagged: fields.held(widget.annotation),
+ description: fields.tooltip(widget.annotation),
+ };
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/formLabel.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/formLabel.ts
new file mode 100644
index 0000000000..00369ea225
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/formLabel.ts
@@ -0,0 +1,114 @@
+/**
+ * The text a form field is labelled by, found by where the page displays it:
+ * the nearest one-line text beside the field on its line or just above it.
+ * A guess for the user to check, as the auto-tagger's tags are.
+ */
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import type { WidgetAnnotation } from "@editor/tools/pdfTextEditor/model/WidgetAnnotation";
+import {
+ ARTIFACT_TAG,
+ innermostMcid,
+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+import {
+ displayBox,
+ taggedMcidBeforeField,
+ type DisplayBox,
+} from "@editor/tools/pdfTextEditor/util/elementPlacement";
+
+/** Points a label may sit from the field beside it, on its line. */
+const MAX_BESIDE_GAP = 144;
+/** Points a label may sit above the field. */
+const MAX_ABOVE_GAP = 24;
+/** Points of overlap still read as beside or above rather than over. */
+const TOLERANCE = 2;
+
+export interface FieldLabel {
+ /** The label's text, without the blanks and colon that lead into the field. */
+ text: string;
+ /** The MCID of the run the label is; null when it has none. */
+ mcid: number | null;
+}
+
+/**
+ * The run nearest the field that ends left of it on its line, or sits above
+ * it overlapping it; for a check box or radio button, also one that starts
+ * right of it. Null when none is close enough. Text in a paragraph of several
+ * lines, artifacts, and text drawn over the field are never labels.
+ */
+export function fieldLabel(
+ page: Page,
+ widget: WidgetAnnotation,
+): FieldLabel | null {
+ const field = displayBox(page, widget.rect);
+ const toRight = widget.fieldType === "Btn";
+ let best: { run: TextRun; text: string; gap: number } | null = null;
+ for (const run of page.runs) {
+ const text = labelText(run.text);
+ if (!text || !mayLabel(run)) continue;
+ const gap = labelGap(displayBox(page, run.bounds), field, toRight);
+ if (gap !== null && (!best || gap < best.gap)) best = { run, text, gap };
+ }
+ return best && { text: best.text, mcid: innermostMcid(best.run.tagMarks) };
+}
+
+/**
+ * The MCID of the content a new Form for the field reads after: its label's,
+ * else the tagged content before it (taggedMcidBeforeField). Null when none.
+ */
+export function fieldAnchor(
+ page: Page,
+ widget: WidgetAnnotation,
+): number | null {
+ return (
+ fieldLabel(page, widget)?.mcid ?? taggedMcidBeforeField(page, widget.rect)
+ );
+}
+
+function mayLabel(run: TextRun): boolean {
+ if (run.paragraphMemberPtrs.length > 1) return false;
+ return !run.tagMarks.some((mark) => mark.name === ARTIFACT_TAG);
+}
+
+/** How far the run is from the field, if it is placed to label it; null when not. */
+function labelGap(
+ run: DisplayBox,
+ field: DisplayBox,
+ toRight: boolean,
+): number | null {
+ const onLine =
+ within(middle(run.bottom, run.top), field.bottom, field.top) ||
+ within(middle(field.bottom, field.top), run.bottom, run.top);
+ const overColumn = run.left < field.right && run.right > field.left;
+ if (onLine && run.right <= field.left + TOLERANCE) {
+ return capped(field.left - run.right, MAX_BESIDE_GAP);
+ }
+ if (onLine && toRight && run.left >= field.right - TOLERANCE) {
+ return capped(run.left - field.right, MAX_BESIDE_GAP);
+ }
+ if (!onLine && overColumn && run.bottom >= field.top - TOLERANCE) {
+ return capped(run.bottom - field.top, MAX_ABOVE_GAP);
+ }
+ return null;
+}
+
+/** The run's text as a field's name: one line, without trailing blanks, dot leaders or colon. */
+function labelText(text: string): string {
+ return text
+ .replace(/\s+/g, " ")
+ .replace(/^[\s_]+/, "")
+ .replace(/(?:[\s_:]|\.{2,})+$/, "");
+}
+
+function middle(low: number, high: number): number {
+ return (low + high) / 2;
+}
+
+function within(value: number, low: number, high: number): boolean {
+ return value >= low && value <= high;
+}
+
+function capped(gap: number, max: number): number | null {
+ const distance = Math.max(gap, 0);
+ return distance <= max ? distance : null;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/pageViewHandlers.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/pageViewHandlers.ts
index 855cc29a8e..359df27d8d 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/pageViewHandlers.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/pageViewHandlers.ts
@@ -42,6 +42,8 @@ function createHandlers(store: EditorStore) {
onSelectRunText: (runId: string, range: TextRange | null) =>
store.selection.setTextRange(runId, range),
onSelectImage: (imageId: string) => store.selection.selectImage(imageId),
+ onSelectFormField: (annotationId: string) =>
+ store.selection.selectFormField(annotationId),
onSelectShape: (shapeId: string, extend: boolean) => {
if (extend) store.selection.toggleShape(shapeId);
else store.selection.selectShape(shapeId);