Skip to content

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

Add ability to add accessibility tags to untagged documents in Text Editor (#8772)

James Brunton8da00dcb9b36
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index 3aa356f010..b44ab16c0a 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -7279,12 +7279,15 @@ widget = "Form field - not page text, so it can't be edited here"
[pdfTextEditor.commands]
edit = "Edit"
+markTagged = "Mark as fully tagged"
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}}"
+tagPageContent = "Auto-tag page"
typeInto = "Type into {{run}}"
ungroupParagraph = "Ungroup paragraph {{run}}"
+unmarkTagged = "Mark as not fully tagged"
wrap = "Wrap {{run}}"
[pdfTextEditor.discard]
@@ -7439,6 +7442,7 @@ addTag = "Add tag"
artifactText = "Decorative"
cannotChange = "This image's accessibility can't be changed."
cannotRetag = "This text's tag can't be changed."
+cannotTagPage = "This page's content can't be tagged."
customTag = "{{role}} (custom tag)"
decorativeInfo = "Screen readers skip decorative images. Use it for borders, backgrounds and other images that carry no information."
decorativeLabel = "Decorative image"
@@ -7448,22 +7452,31 @@ encrypted = "Tags can't be edited in an encrypted file"
heading = "Accessibility"
innerTagLabel = "Tag {{number}}"
innerTags = "Tags in this text"
+markedTagged = "Document is fully tagged"
+markedTaggedHint = "Tells PDF readers to use the accessibility tags. Tick it once everything is tagged."
+markedWithUntagged = "Some content has no tags, so screen readers may skip it."
missingDescriptions = "Missing descriptions"
mixedContent = "Figure includes other content"
+mixedTags = "Mixed"
needsDescriptionBadge = "No description"
nextImage = "Next image"
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"
+tagging = "Tagging pages"
tagLabel = "Tag"
+tagUntagged = "Auto-tag document"
+tagUntaggedHint = "Automatically adds accessibility tags throughout the document. The result is rough: check headings, lists and reading order afterwards."
unknownTag = "Can't be read here"
+unmarkedWithTags = "Some PDF viewers will use the tags anyway and may skip content without them."
unreadable = "This file's tags can't be edited"
untaggableImages = "Can't be tagged here"
untaggedBadge = "Not tagged"
untaggedDocument = "Document has no tags"
untaggedImage = "Can't be tagged here"
untaggedImages = "Untagged images"
+untaggedPages = "Pages to tag"
[pdfTextEditor.inspector.accessibility.outline]
empty = "Heading with no text"
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tagged-structure.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tagged-structure.spec.ts
index 46efd3b509..36a5d62c25 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tagged-structure.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tagged-structure.spec.ts
@@ -224,7 +224,7 @@ test.describe("PDF text editor - tagged documents", () => {
"pdf-editor-image-",
"",
);
- const badge = page.getByTestId(`pdf-editor-image-attention-${imageId}`);
+ const badge = page.getByTestId(`pdf-editor-attention-image-${imageId}`);
const summary = page.getByTestId(
"pdf-editor-document-accessibility-summary",
);
@@ -276,7 +276,7 @@ test.describe("PDF text editor - tagged documents", () => {
.setInputFiles(PNG);
await expect(images).toHaveCount(2);
const untagged = page.locator(
- '[data-testid^="pdf-editor-image-attention-"][data-attention="untagged"]',
+ '[data-testid^="pdf-editor-attention-image-"][data-attention="untagged"]',
);
await expect(untagged).toHaveCount(1);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyStructureEdits.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyStructureEdits.test.ts
index 54a36267eb..5dea717e10 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyStructureEdits.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyStructureEdits.test.ts
@@ -11,6 +11,7 @@ import {
applyStructureEdits,
} from "@editor/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits";
import { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import { readFileStructure } from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";
import {
buildClassicPdf,
buildXrefStreamPdf,
@@ -647,3 +648,128 @@ describe("applyStructureEdits: cutting", () => {
).rejects.toThrow(StructureEditError);
});
});
+
+describe("applyStructureEdits: no structure yet", () => {
+ const paragraph = (pageIndex: number, mcid = 0) => ({
+ pageIndex,
+ mcid,
+ decorative: false,
+ newElement: { type: "P" as const, after: null },
+ });
+ const documentKids = async (bytes: Uint8Array) =>
+ (await elementBody(bytes, 9)).match(/\/K \[([^\]]*)\]/)![1];
+
+ // objects() with page 2 (object 4) dropping its /StructParents and the
+ // ParentTree its entry, its content now marking MCID 0 with no element.
+ function untaggedSecondPage(parentTree = "<< /Nums [0 [10 0 R 11 0 R]] >>") {
+ return objects(parentTree)
+ .filter((obj) => obj.num !== 12)
+ .map((obj) => {
+ if (obj.num === 4) {
+ return { ...obj, body: obj.body.replace(" /StructParents 1", "") };
+ }
+ if (obj.num === 7) {
+ return { ...obj, body: obj.body.replace("/ParentTreeNextKey 2", "") };
+ }
+ if (obj.num === 9) {
+ return {
+ ...obj,
+ body: "<< /Type /StructElem /S /Document /P 7 0 R /K [10 0 R 11 0 R] >>",
+ };
+ }
+ return obj;
+ });
+ }
+
+ test("creates the tree, a Document element and the page's ParentTree array in an untagged file", async () => {
+ const untagged = buildClassicPdf(
+ objects()
+ .filter((obj) => obj.num < 7)
+ .map((obj) => ({
+ ...obj,
+ body:
+ obj.num === 1
+ ? "<< /Type /Catalog /Pages 2 0 R >>"
+ : obj.body.replace(/ \/StructParents \d/, ""),
+ })),
+ 1,
+ );
+ const out = await applyStructureEdits(untagged, [paragraph(1)]);
+
+ const pdf = (await RawPdf.parse(out))!;
+ const catalog = pdf.objectBody(1)!;
+ expect(catalog).not.toContain("/MarkInfo");
+ const root = pdf.objectBody(pdf.dictRef(catalog, "StructTreeRoot")!)!;
+ expect(root).toContain("/ParentTreeNextKey 1");
+ const document = pdf.objectBody(pdf.dictRef(root, "K")!)!;
+ expect(document).toContain("/S /Document");
+ expect(pdf.dictInt(pdf.objectBody(3)!, "StructParents")).toBeNull();
+ expect(pdf.dictInt(pdf.objectBody(4)!, "StructParents")).toBe(0);
+
+ const structure = await readFileStructure(out);
+ expect(structure!.pages.get(1)!.elements.map((el) => el.type)).toEqual([
+ "P",
+ ]);
+ expect(structure!.blocks.map((block) => block.type)).toEqual([
+ "Document",
+ "P",
+ ]);
+ });
+
+ test("gives a page with no /StructParents the next free ParentTree key", async () => {
+ const out = await applyStructureEdits(
+ buildClassicPdf(untaggedSecondPage(), 1),
+ [paragraph(1)],
+ );
+ const pdf = (await RawPdf.parse(out))!;
+ expect(pdf.dictInt(pdf.objectBody(4)!, "StructParents")).toBe(1);
+ const root = pdf.objectBody(7)!;
+ expect(root).toContain("/ParentTreeNextKey 2");
+ expect(root).toMatch(/\/Nums \[0 \[10 0 R 11 0 R\] 1 \d+ 0 R\]/);
+ expect(await documentKids(out)).toMatch(/^10 0 R 11 0 R \d+ 0 R$/);
+ });
+
+ test("adds a leaf for the new page to a ParentTree with kids", async () => {
+ const tree = [
+ ...untaggedSecondPage("20 0 R"),
+ { num: 20, body: "<< /Kids [21 0 R] >>" },
+ { num: 21, body: "<< /Limits [0 0] /Nums [0 [10 0 R 11 0 R]] >>" },
+ ];
+ const out = await applyStructureEdits(buildClassicPdf(tree, 1), [
+ paragraph(1),
+ ]);
+ const pdf = (await RawPdf.parse(out))!;
+ const kids = pdf.objectBody(20)!.match(/\/Kids \[([^\]]*)\]/)![1];
+ const leaf = pdf.objectBody(Number(kids.split(" ")[3]))!;
+ expect(leaf).toMatch(/\/Limits \[1 1\] \/Nums \[1 \d+ 0 R\]/);
+ const structure = await readFileStructure(out);
+ expect(structure!.pages.get(1)!.elements.map((el) => el.type)).toEqual([
+ "P",
+ ]);
+ });
+
+ test("leaves /MarkInfo as the file has it", async () => {
+ const unmarked = untaggedSecondPage().map((obj) =>
+ obj.num === 1
+ ? {
+ ...obj,
+ body: obj.body.replace("/Marked true", "/Marked false"),
+ }
+ : obj,
+ );
+ const out = await applyStructureEdits(buildClassicPdf(unmarked, 1), [
+ paragraph(1),
+ ]);
+ expect(await elementBody(out, 1)).toContain(
+ "/MarkInfo << /Marked false >>",
+ );
+ });
+
+ test("leaves the file's structure alone when every page already has its own", async () => {
+ const bytes = buildClassicPdf(objects(), 1);
+ const out = await applyStructureEdits(bytes, [
+ { pageIndex: 1, mcid: 0, alt: "x", decorative: false },
+ ]);
+ expect(await elementBody(out, 1)).toBe(await elementBody(bytes, 1));
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/innerTags.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/innerTags.test.ts
index d490fbea9e..13641a8c0b 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/innerTags.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/innerTags.test.ts
@@ -11,7 +11,9 @@ import {
test,
vi,
} from "vitest";
+import { MergeRunsCommand } from "@editor/tools/pdfTextEditor/commands/MergeRunsCommand";
import { RetagInnerCommand } from "@editor/tools/pdfTextEditor/commands/RetagInnerCommand";
+import { TagTextCommand } from "@editor/tools/pdfTextEditor/commands/TagTextCommand";
import { TagTextRangeCommand } from "@editor/tools/pdfTextEditor/commands/TagTextRangeCommand";
import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import {
@@ -25,6 +27,7 @@ import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextR
import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
import { innerTags } from "@editor/tools/pdfTextEditor/util/textAccessibility";
+import { singleContentPdf } from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
const SAMPLE = path.join(
import.meta.dirname,
@@ -224,3 +227,47 @@ describe("tags inside a run's text", () => {
expect(doc.structureEdits()).toEqual([]);
});
});
+
+describe("tags inside a run grouped from several paragraphs", () => {
+ const TWO_PARAGRAPHS = singleContentPdf(
+ "BT /F1 12 Tf 72 700 Td (The first paragraph.) Tj ET\n" +
+ "BT /F1 12 Tf 72 640 Td (The second paragraph.) Tj ET\n",
+ );
+
+ async function openFirstPage(bytes: Uint8Array) {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+ }
+
+ function tagEachAsParagraph(doc: EditorDocument, history: HistoryStack) {
+ for (const run of [...doc.page(0).runs]) {
+ history.execute(
+ new TagTextCommand({ pageIndex: 0, runId: run.id, as: "P" }),
+ doc,
+ );
+ }
+ }
+
+ function groupAndListTags(doc: EditorDocument, history: HistoryStack) {
+ const runIds = doc.page(0).runs.map((run) => run.id);
+ expect(runIds).toHaveLength(2);
+ history.execute(new MergeRunsCommand({ pageIndex: 0, runIds }), doc);
+ return innerTags(doc, doc.page(0).runs[0].snapshot());
+ }
+
+ test("lists no tags for paragraphs the session tagged", async () => {
+ const doc = await openFirstPage(TWO_PARAGRAPHS);
+ const history = new HistoryStack();
+ tagEachAsParagraph(doc, history);
+ expect(groupAndListTags(doc, history)).toEqual([]);
+ });
+
+ test("lists no tags for the file's paragraphs", async () => {
+ const tagging = await openFirstPage(TWO_PARAGRAPHS);
+ tagEachAsParagraph(tagging, new HistoryStack());
+ const doc = await openFirstPage((await saved(tagging)).bytes);
+ expect(groupAndListTags(doc, new HistoryStack())).toEqual([]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/markTagged.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/markTagged.test.ts
new file mode 100644
index 0000000000..d4a69df11a
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/markTagged.test.ts
@@ -0,0 +1,70 @@
+// @vitest-environment node
+import { describe, expect, test } from "vitest";
+import { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import {
+ applyMarked,
+ isMarked,
+} from "@editor/tools/pdfTextEditor/pdfdoc/passes/markTagged";
+import { buildClassicPdf } from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+function pdfWithCatalog(
+ catalog: string,
+ extra: { num: number; body: string }[] = [],
+) {
+ return buildClassicPdf(
+ [
+ { num: 1, body: catalog },
+ { 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] >>",
+ },
+ ...extra,
+ ],
+ 1,
+ );
+}
+
+async function marked(bytes: Uint8Array): Promise<boolean> {
+ const pdf = (await RawPdf.parse(bytes))!;
+ return isMarked(pdf, pdf.objectBody(pdf.rootNum)!);
+}
+
+describe("applyMarked", () => {
+ test("adds /MarkInfo to a catalog that has none", async () => {
+ const out = await applyMarked(
+ pdfWithCatalog("<< /Type /Catalog /Pages 2 0 R >>"),
+ true,
+ );
+ expect(await marked(out)).toBe(true);
+ });
+
+ test("clears an inline /Marked", async () => {
+ const out = await applyMarked(
+ pdfWithCatalog(
+ "<< /Type /Catalog /Pages 2 0 R /MarkInfo << /Marked true /Suspects false >> >>",
+ ),
+ false,
+ );
+ expect(await marked(out)).toBe(false);
+ const pdf = (await RawPdf.parse(out))!;
+ expect(pdf.objectBody(1)).toContain("/Suspects false");
+ });
+
+ test("sets /Marked in an indirect /MarkInfo", async () => {
+ const out = await applyMarked(
+ pdfWithCatalog("<< /Type /Catalog /Pages 2 0 R /MarkInfo 4 0 R >>", [
+ { num: 4, body: "<< /Marked false >>" },
+ ]),
+ true,
+ );
+ expect(await marked(out)).toBe(true);
+ const pdf = (await RawPdf.parse(out))!;
+ expect(pdf.objectBody(4)).toContain("/Marked true");
+ });
+
+ test("returns the bytes unchanged when the file already says so", async () => {
+ const bytes = pdfWithCatalog("<< /Type /Catalog /Pages 2 0 R >>");
+ expect(await applyMarked(bytes, false)).toBe(bytes);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/storeApplyRecovery.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/storeApplyRecovery.test.ts
index 83de6344e6..c56379b989 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/storeApplyRecovery.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/storeApplyRecovery.test.ts
@@ -175,3 +175,30 @@ describe("EditorStore recovery from a failed undo/redo", () => {
expect(store.getState().dirty).toBe(true);
});
});
+
+describe("EditorStore recording an applied command", () => {
+ it("records without applying, as one undoable step that dirties the document", async () => {
+ const store = await makeStore();
+ const cmd = makeCmd();
+ store.recordApplied(cmd);
+ expect(cmd.apply).not.toHaveBeenCalled();
+ expect(store.history.peekUndo()).toBe(cmd);
+ expect(store.getState().dirty).toBe(true);
+ store.undo();
+ expect(cmd.revert).toHaveBeenCalledOnce();
+ });
+
+ it("ignores undo and redo while loading", async () => {
+ const store = await makeStore();
+ const cmd = makeCmd();
+ store.dispatch(cmd);
+ store.setLoading(true);
+ store.undo();
+ expect(cmd.revert).not.toHaveBeenCalled();
+ store.setLoading(false);
+ store.undo();
+ store.setLoading(true);
+ store.redo();
+ expect(cmd.apply).toHaveBeenCalledOnce();
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts
index 47cbc3d61d..7d73292f94 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts
@@ -344,12 +344,12 @@ describe("imageAccessibility", () => {
});
});
- test("cannot undo an artifact in an untagged document", async () => {
+ test("can undo an artifact in a document with no structure tree", async () => {
const doc = await open(imagesPdf({ tagged: false }));
const [, rule] = await images(doc);
expect(imageAccessibility(doc, rule)).toEqual({
kind: "decorative",
- canUndecorate: false,
+ canUndecorate: true,
});
});
@@ -363,13 +363,13 @@ describe("imageAccessibility", () => {
});
});
- test("blocks every image in an untagged document", async () => {
+ test("blocks an image marked with an MCID the file has no tree for", async () => {
const doc = await open(imagesPdf({ tagged: false }));
const [image] = await images(doc);
expect(imageAccessibility(doc, image)).toEqual({
kind: "blocked",
blocker: "untagged",
- documentTagged: false,
+ documentTagged: true,
});
});
});
@@ -507,7 +507,7 @@ describe("reviewing images that need attention", () => {
expect(nextImageNeedingAttention(doc, read, null)?.id).toBe(inserted.id);
});
- test("leaves an untagged document's images out of the review", async () => {
+ test("counts an image marked for a missing tree as untaggable", async () => {
const doc = await open(imagesPdf({ tagged: false }));
const page = doc.page(0);
PdfiumTextReader.populate(doc, page);
@@ -517,7 +517,7 @@ describe("reviewing images that need attention", () => {
expect(reviewImages(doc, read)).toEqual({
needsDescription: 0,
untagged: 0,
- untaggable: 0,
+ untaggable: 1,
});
});
});
@@ -1112,15 +1112,17 @@ describe("TagImageCommand", () => {
expect(marks(doc, figure)).toEqual([{ name: "Figure", mcid: 0 }]);
});
- test("refuses an image in an untagged document", async () => {
+ test("tags an image in a document with no structure tree, and saves one for it", async () => {
const doc = await open(imagesPdf({ tagged: false }));
await readPage(doc);
const history = new HistoryStack();
const image = insertImage(doc, history, 60);
- expect(() =>
- history.execute(tagImage(image, "figure", "A logo"), doc),
- ).toThrow(HistoryStepError);
- expect(marks(doc, image)).toEqual([]);
+ history.execute(tagImage(image, "figure", "A logo"), doc);
+
+ const saved = await readFileStructure(await savedBytes(doc));
+ expect(saved!.pages.get(0)!.elements).toMatchObject([
+ { type: "Figure", alt: "A logo" },
+ ]);
});
});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureGrouping.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureGrouping.test.ts
index d66e3c2771..514d1346af 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureGrouping.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureGrouping.test.ts
@@ -204,10 +204,10 @@ describe("textTag", () => {
);
});
- test("reads text in a file without a structure tree as untagged", async () => {
+ test("reads text marked with an MCID the file has no tree for as untagged", async () => {
expect(
await tagOf(paragraphsPdf({ tagged: false }), "Introduction"),
- ).toEqual({ kind: "untagged", documentTagged: false, taggable: false });
+ ).toEqual({ kind: "untagged", documentTagged: true, taggable: false });
});
});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tagPageContent.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tagPageContent.test.ts
new file mode 100644
index 0000000000..5cfec3ada7
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tagPageContent.test.ts
@@ -0,0 +1,382 @@
+// @vitest-environment node
+// jsdom's Blob cannot stream, so a saved object stream would not inflate.
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import {
+ TagPageContentCommand,
+ hasUntaggedContent,
+} from "@editor/tools/pdfTextEditor/commands/TagPageContentCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { tagAllPages } from "@editor/tools/pdfTextEditor/hooks/useBulkTagging";
+import { readAllPagesInBackground } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";
+import { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";
+import { readFileStructure } from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";
+import { readTagMarks } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+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 { textTag } from "@editor/tools/pdfTextEditor/util/textAccessibility";
+import {
+ buildClassicPdf,
+ streamBody,
+ type FixtureObject,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+// Two columns, the right one drawn first, then a rule and an image.
+const COLUMNS =
+ "BT /F1 12 Tf 320 700 Td (Right column opens here.) Tj ET\n" +
+ "BT /F1 12 Tf 320 686 Td (Right column goes on.) Tj ET\n" +
+ "BT /F1 12 Tf 72 700 Td (Left column opens here.) Tj ET\n" +
+ "BT /F1 12 Tf 72 686 Td (Left column goes on.) Tj ET\n" +
+ "72 640 m 540 640 l S\n" +
+ "q 50 0 0 50 72 560 cm /Im1 Do Q\n";
+
+function pagePdf(content: string, catalog = "", page = ""): Uint8Array {
+ const objects: FixtureObject[] = [
+ { num: 1, body: `<< /Type /Catalog /Pages 2 0 R${catalog} >>` },
+ { 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${page} ` +
+ "/Resources << /Font << /F1 5 0 R >> /XObject << /Im1 6 0 R >> >> >>",
+ },
+ { num: 4, body: streamBody("", content) },
+ {
+ num: 5,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ {
+ num: 6,
+ body: streamBody(
+ "/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8",
+ "\x80",
+ ),
+ },
+ ];
+ return buildClassicPdf(objects, 1);
+}
+
+/** A tagged page: an H1 drawn first, then the untagged columns. */
+function partlyTaggedPdf(): Uint8Array {
+ return buildClassicPdf(
+ [
+ {
+ num: 1,
+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 7 0 R /MarkInfo << /Marked true >> >>",
+ },
+ { 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 /StructParents 0 " +
+ "/Resources << /Font << /F1 5 0 R >> /XObject << /Im1 6 0 R >> >> >>",
+ },
+ {
+ num: 4,
+ body: streamBody(
+ "",
+ "/H1 <</MCID 0>> BDC BT /F1 20 Tf 72 740 Td (Report) Tj ET EMC\n" +
+ COLUMNS,
+ ),
+ },
+ {
+ num: 5,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ {
+ num: 6,
+ body: streamBody(
+ "/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8",
+ "\x80",
+ ),
+ },
+ {
+ num: 7,
+ body: "<< /Type /StructTreeRoot /K 8 0 R /ParentTree << /Nums [0 [9 0 R]] >> /ParentTreeNextKey 1 >>",
+ },
+ {
+ num: 8,
+ body: "<< /Type /StructElem /S /Document /P 7 0 R /K [9 0 R] >>",
+ },
+ {
+ num: 9,
+ body: "<< /Type /StructElem /S /H1 /P 8 0 R /Pg 3 0 R /K 0 >>",
+ },
+ ],
+ 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 savedBytes(doc: EditorDocument): Promise<Uint8Array> {
+ const { blob } = await exportToBlob(doc, "page.pdf");
+ return new Uint8Array(await blob.arrayBuffer());
+}
+
+/** The saved file's blocks in reading order, each as its text or its type. */
+async function savedReading(bytes: Uint8Array): Promise<string[]> {
+ const structure = await readFileStructure(bytes);
+ const doc = await open(bytes);
+ const textOf = new Map<number, string>();
+ for (const run of doc.page(0).runs) {
+ const { mcid } = run.snapshot();
+ if (mcid !== undefined) textOf.set(mcid, run.text.replace(/\s+/g, " "));
+ }
+ return structure!.blocks
+ .filter((block) => block.type !== "Document")
+ .map((block) => {
+ const text = block.mcids.map((mcid) => textOf.get(mcid)).join(" ");
+ return `${block.type}: ${text}`.trim();
+ });
+}
+
+/** Every page-level object's marks, by type: 1 text, 2 path, 3 image. */
+function marksByType(doc: EditorDocument): Map<number, string[][]> {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const byType = new Map<number, string[][]>();
+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {
+ const ptr = m.FPDFPage_GetObject(pagePtr, i);
+ const type = m.FPDFPageObj_GetType(ptr);
+ const names = readTagMarks(m, ptr).map((tag) => tag.name);
+ byType.set(type, [...(byType.get(type) ?? []), names]);
+ }
+ return byType;
+}
+
+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("TagPageContentCommand", () => {
+ test("tags text as P and images as Figure in content order, and the rest as artifacts", async () => {
+ const doc = await open(pagePdf(COLUMNS));
+ expect(hasUntaggedContent(doc, 0)).toBe(true);
+ new HistoryStack().execute(
+ new TagPageContentCommand({ pageIndex: 0 }),
+ doc,
+ );
+ expect(hasUntaggedContent(doc, 0)).toBe(false);
+
+ const bytes = await savedBytes(doc);
+ expect(await savedReading(bytes)).toEqual([
+ "P: Right column opens here. Right column goes on.",
+ "P: Left column opens here. Left column goes on.",
+ "Figure:",
+ ]);
+ const reopened = await open(bytes);
+ expect(marksByType(reopened).get(2)).toEqual([["Artifact"]]);
+ for (const run of reopened.page(0).runs) {
+ expect(textTag(reopened, run.snapshot()).kind).toBe("tagged");
+ }
+ });
+
+ test("puts the new elements around the page's tagged content as its content orders them", async () => {
+ const doc = await open(partlyTaggedPdf());
+ new HistoryStack().execute(
+ new TagPageContentCommand({ pageIndex: 0 }),
+ doc,
+ );
+ expect(await savedReading(await savedBytes(doc))).toEqual([
+ "H1: Report",
+ "P: Right column opens here. Right column goes on.",
+ "P: Left column opens here. Left column goes on.",
+ "Figure:",
+ ]);
+ });
+
+ test("retags content marked with MCIDs the file has no tree for", async () => {
+ const stale = COLUMNS.split("\n")
+ .filter(Boolean)
+ .map((line, i) => `/P <</MCID ${i}>> BDC ${line} EMC`)
+ .join("\n");
+ const doc = await open(pagePdf(stale, "", " /StructParents 0"));
+ new HistoryStack().execute(
+ new TagPageContentCommand({ pageIndex: 0 }),
+ doc,
+ );
+
+ const bytes = await savedBytes(doc);
+ expect(await savedReading(bytes)).toEqual([
+ "P: Right column opens here. Right column goes on.",
+ "P: Left column opens here. Left column goes on.",
+ "Figure:",
+ ]);
+ const reopened = await open(bytes);
+ expect(marksByType(reopened).get(2)).toEqual([["Artifact"]]);
+ });
+
+ test("undoes every tag, and redoes them", async () => {
+ const doc = await open(pagePdf(COLUMNS));
+ const history = new HistoryStack();
+ history.execute(new TagPageContentCommand({ pageIndex: 0 }), doc);
+ const tagged = doc.structureEdits();
+
+ history.undo(doc);
+ expect(doc.structureEdits()).toEqual([]);
+ for (const marks of marksByType(doc).values()) {
+ for (const names of marks) expect(names).toEqual([]);
+ }
+ for (const run of doc.page(0).runs) {
+ expect(textTag(doc, run.snapshot()).kind).toBe("untagged");
+ }
+
+ history.redo(doc);
+ expect(doc.structureEdits()).toEqual(tagged);
+ });
+
+ test("refuses a page whose structure the save cannot write", async () => {
+ const doc = await open(
+ pagePdf(COLUMNS, " /StructTreeRoot 7 0 R", " /StructParents 0"),
+ );
+ expect(hasUntaggedContent(doc, 0)).toBe(false);
+ expect(() =>
+ new HistoryStack().execute(
+ new TagPageContentCommand({ pageIndex: 0 }),
+ doc,
+ ),
+ ).toThrow();
+ });
+});
+
+/** A store holding `bytes` as its document, its pages listed but none read. */
+async function storeFor(bytes: Uint8Array): Promise<EditorStore> {
+ const doc = await EditorDocument.open(bytes);
+ const store = new EditorStore();
+ await store.setDocument(doc);
+ store.publishPages(
+ Array.from(
+ { length: doc.pageCount },
+ (_, pageIndex) =>
+ ({
+ pageIndex,
+ revision: -1,
+ runs: [],
+ images: [],
+ shapes: [],
+ annotations: [],
+ rules: [],
+ }) as unknown as PageSnapshot,
+ ),
+ );
+ return store;
+}
+
+describe("tagAllPages", () => {
+ test("reads and tags every page behind the loading overlay, as one undo step", async () => {
+ const store = await storeFor(pagePdf(COLUMNS));
+ const progress = vi.spyOn(store, "setProgress");
+ const tagging = tagAllPages(store);
+ expect(store.getState().loading).toBe(true);
+ await tagging;
+
+ expect(store.getState().loading).toBe(false);
+ expect(progress).toHaveBeenCalledWith(
+ expect.objectContaining({ current: 0, total: 1 }),
+ );
+ const doc = store.document!;
+ expect(hasUntaggedContent(doc, 0)).toBe(false);
+ expect(
+ store.getState().pages[0].runs.every((run) => run.mcid !== undefined),
+ ).toBe(true);
+
+ store.undo();
+ expect(hasUntaggedContent(doc, 0)).toBe(true);
+ expect(store.history.canUndo).toBe(false);
+ store.dispose();
+ });
+
+ test("records nothing when nothing is untagged", async () => {
+ const store = await storeFor(pagePdf(COLUMNS));
+ await tagAllPages(store);
+ const tagged = store.history.peekUndo();
+ await tagAllPages(store);
+ expect(store.history.peekUndo()).toBe(tagged);
+ store.dispose();
+ });
+});
+
+describe("tagAllPages and the tagged flag", () => {
+ test("marks the document fully tagged in the same undo step", async () => {
+ const store = await storeFor(pagePdf(COLUMNS));
+ const doc = store.document!;
+ doc.setMarkedTagged(false);
+ await tagAllPages(store);
+ expect(doc.markedTagged()).toBe(true);
+
+ store.undo();
+ expect(doc.markedTagged()).toBe(false);
+ expect(hasUntaggedContent(doc, 0)).toBe(true);
+ store.dispose();
+ });
+});
+
+describe("readAllPagesInBackground", () => {
+ test("reads unread pages after yielding, then publishes them", async () => {
+ const store = await storeFor(pagePdf(COLUMNS));
+ readAllPagesInBackground(store);
+ expect(store.document!.page(0).loaded).toBe(false);
+
+ await vi.waitFor(() =>
+ expect(store.getState().pages[0].runs.length).toBeGreaterThan(0),
+ );
+ expect(store.document!.page(0).loaded).toBe(true);
+ store.dispose();
+ });
+
+ test("reads nothing once cancelled", async () => {
+ const store = await storeFor(pagePdf(COLUMNS));
+ const publish = vi.spyOn(store, "publishPages");
+ vi.useFakeTimers({ toFake: ["setTimeout"] });
+ try {
+ readAllPagesInBackground(store)();
+ await vi.runAllTimersAsync();
+ } finally {
+ vi.useRealTimers();
+ }
+
+ expect(store.document!.page(0).loaded).toBe(false);
+ expect(publish).not.toHaveBeenCalled();
+ store.dispose();
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textTagging.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textTagging.test.ts
index 884e4e30e4..69f09b59dc 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textTagging.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textTagging.test.ts
@@ -19,16 +19,20 @@ import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureT
import { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";
import { readFileStructure } from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";
import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { SetMarkedTaggedCommand } from "@editor/tools/pdfTextEditor/commands/SetMarkedTaggedCommand";
import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
import {
buildClassicPdf,
+ singleContentPdf,
streamBody,
} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
import {
canTagText,
+ sharedTextTag,
textTag,
} from "@editor/tools/pdfTextEditor/util/textAccessibility";
+import { setTextTagCommand } from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";
const TAGGED_SAMPLE = path.join(
import.meta.dirname,
@@ -309,3 +313,131 @@ describe("tagging untagged text", () => {
}
});
});
+
+describe("tagging text in a file with no structure tree", () => {
+ async function openUntagged(): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(
+ singleContentPdf(
+ "BT /F1 20 Tf 72 700 Td (Summary) Tj ET\n" +
+ "BT /F1 12 Tf 72 670 Td (Sales rose in every region.) Tj ET\n",
+ ),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+ }
+
+ test("offers the untagged text for tagging", async () => {
+ const doc = await openUntagged();
+ const run = doc.page(0).runs.find((r) => r.text.includes("Summary"))!;
+ expect(textTag(doc, run.snapshot())).toEqual({
+ kind: "untagged",
+ documentTagged: true,
+ taggable: true,
+ });
+ });
+
+ test("saves a tree holding the tagged text, in the order it was read", async () => {
+ const doc = await openUntagged();
+ const history = new HistoryStack();
+ tagText(doc, history, "Summary", "H1", 0);
+ tagText(doc, history, "Sales rose", "P", 0);
+ expect(doc.headings()!.map((h) => h.type)).toEqual(["H1"]);
+
+ const bytes = await savedBytes(doc);
+ const saved = await readFileStructure(bytes);
+ expect(saved!.blocks.map((block) => block.type)).toEqual([
+ "Document",
+ "H1",
+ "P",
+ ]);
+ const pdf = (await RawPdf.parse(bytes))!;
+ expect(pdf.objectBody(pdf.rootNum)).not.toContain("/MarkInfo");
+
+ const reopened = await EditorDocument.open(bytes);
+ opened.push(reopened);
+ PdfiumTextReader.populate(reopened, reopened.page(0));
+ expect(
+ reopened.page(0).runs.map((run) => {
+ const tag = textTag(reopened, run.snapshot());
+ return tag.kind === "tagged" ? tag.block.type : tag.kind;
+ }),
+ ).toEqual(["H1", "P"]);
+ });
+
+ test("claims to be tagged only once marked so, and not after an undo", async () => {
+ const doc = await openUntagged();
+ const history = new HistoryStack();
+ tagText(doc, history, "Summary", "H1", 0);
+ expect(doc.markedTagged()).toBe(false);
+ history.execute(new SetMarkedTaggedCommand(true), doc);
+
+ const marked = await savedBytes(doc);
+ const pdf = (await RawPdf.parse(marked))!;
+ expect(pdf.objectBody(pdf.rootNum)).toContain(
+ "/MarkInfo << /Marked true >>",
+ );
+ const reopened = await EditorDocument.open(marked);
+ opened.push(reopened);
+ expect(reopened.markedTagged()).toBe(true);
+
+ history.undo(doc);
+ const unmarked = await savedBytes(doc);
+ const again = (await RawPdf.parse(unmarked))!;
+ expect(again.objectBody(again.rootNum)).not.toContain("/MarkInfo");
+ });
+});
+
+describe("setting one tag on several runs", () => {
+ function targets(doc: EditorDocument, ...fragments: string[]) {
+ return fragments.map((fragment) => {
+ const run = runWith(doc, fragment).snapshot();
+ return { run, tag: textTag(doc, run) };
+ });
+ }
+
+ test("reads runs tagged differently as mixed, and alike as their tag", async () => {
+ const doc = await openSample();
+ const mixed = targets(doc, "Priorities for next quarter", "Confidential");
+ expect(sharedTextTag(mixed.map(({ tag }) => tag))).toEqual({
+ kind: "mixed",
+ settable: true,
+ });
+ const history = new HistoryStack();
+ history.execute(setTextTagCommand(mixed, "H3")!, doc);
+ const alike = targets(doc, "Priorities for next quarter", "Confidential");
+ expect(sharedTextTag(alike.map(({ tag }) => tag))).toMatchObject({
+ kind: "tagged",
+ block: { type: "H3" },
+ cannotRetag: null,
+ });
+ });
+
+ test("retags tagged text and tags untagged text as one undo step", async () => {
+ const doc = await openSample();
+ const history = new HistoryStack();
+ history.execute(
+ setTextTagCommand(
+ targets(doc, "Priorities for next quarter", "Confidential"),
+ "H3",
+ )!,
+ doc,
+ );
+ expect(shownTag(doc, "Priorities for next quarter")).toBe("H3");
+ expect(shownTag(doc, "Confidential")).toBe("H3");
+
+ history.undo(doc);
+ expect(shownTag(doc, "Priorities for next quarter")).not.toBe("H3");
+ expect(shownTag(doc, "Confidential")).toBe("untagged");
+ });
+
+ test("leaves text whose tag cannot be set out, and is not settable with it", async () => {
+ const doc = await openSample();
+ const withArtifact = targets(doc, "Confidential", "Acme Corp");
+ expect(sharedTextTag(withArtifact.map(({ tag }) => tag))).toEqual({
+ kind: "mixed",
+ settable: false,
+ });
+ expect(setTextTagCommand(targets(doc, "Acme Corp"), "P")).toBeNull();
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetMarkedTaggedCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetMarkedTaggedCommand.ts
new file mode 100644
index 0000000000..93cbe53af5
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetMarkedTaggedCommand.ts
@@ -0,0 +1,29 @@
+import i18n from "i18next";
+import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+
+/** Set whether the saved file declares itself tagged (EditorDocument.markedTagged). */
+export class SetMarkedTaggedCommand implements Command {
+ readonly type = "set-marked-tagged";
+ private previous: boolean | null = null;
+
+ constructor(private readonly marked: boolean) {}
+
+ apply(doc: EditorDocument): void {
+ this.previous ??= doc.markedTagged();
+ doc.setMarkedTagged(this.marked);
+ }
+
+ revert(doc: EditorDocument): void {
+ if (this.previous !== null) doc.setMarkedTagged(this.previous);
+ }
+
+ describe(): string {
+ return this.marked
+ ? i18n.t("pdfTextEditor.commands.markTagged", "Mark as fully tagged")
+ : i18n.t(
+ "pdfTextEditor.commands.unmarkTagged",
+ "Mark as not fully tagged",
+ );
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagPageContentCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagPageContentCommand.ts
new file mode 100644
index 0000000000..62c3261a44
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagPageContentCommand.ts
@@ -0,0 +1,342 @@
+import i18n from "i18next";
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import {
+ RolledBackError,
+ type Command,
+} from "@editor/tools/pdfTextEditor/commands/Command";
+import {
+ collectContainersByPtr,
+ collectMemberPtrs,
+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import type { PageStructure } from "@editor/tools/pdfTextEditor/model/PageStructure";
+import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";
+import {
+ ARTIFACT_TAG,
+ addTagMark,
+ highestMcid,
+ innermostMcid,
+ readTagMarks,
+ removeTagMark,
+ type TagMark,
+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+
+const FPDF_PAGEOBJ_PATH = 2;
+const FPDF_PAGEOBJ_SHADING = 4;
+const TEXT_TAG: StructureType = "P";
+const IMAGE_TAG: StructureType = "Figure";
+
+/** An object to retag, and the marks it loses: an MCID no element owns. */
+interface Retag {
+ ptr: number;
+ dropped: TagMark[];
+}
+
+type Step =
+ | {
+ kind: "text";
+ runId: string;
+ mcid: number;
+ objects: Retag[];
+ runMarks: readonly TagMark[];
+ }
+ | { kind: "image"; imageId: string; mcid: number; object: Retag }
+ | { kind: "artifact"; object: Retag };
+
+interface Plan {
+ steps: Step[];
+ /** Each new element's predecessor in content order, by its MCID. */
+ follows: Map<number, number | null>;
+}
+
+/**
+ * Tag the untagged content drawn directly by a page, as a starting point the
+ * user then corrects: each text block a P, each image a Figure, every 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. The page must
+ * already be read.
+ */
+export class TagPageContentCommand implements Command {
+ readonly type = "tag-page-content";
+ readonly pageIndex: number;
+ /** Chosen on first apply, so a redo reuses its MCIDs. */
+ private plan: Plan | null = null;
+
+ constructor(opts: { pageIndex: number }) {
+ this.pageIndex = opts.pageIndex;
+ }
+
+ apply(doc: EditorDocument): void {
+ const page = doc.page(this.pageIndex);
+ const structure = doc.structure(this.pageIndex);
+ if (!page.loaded || structure.cannotAddElement() !== null) {
+ throw new RolledBackError(
+ new Error(
+ i18n.t(
+ "pdfTextEditor.inspector.accessibility.cannotTagPage",
+ "This page's content can't be tagged.",
+ ),
+ ),
+ );
+ }
+ this.plan ??= planTagging(doc, page, structure);
+ const done: Step[] = [];
+ try {
+ for (const step of this.plan.steps) {
+ applyStep(doc, page, structure, step, this.plan.follows);
+ done.push(step);
+ }
+ } catch (err) {
+ for (const step of done.reverse()) revertStep(doc, page, structure, step);
+ throw new RolledBackError(err);
+ }
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ revert(doc: EditorDocument): void {
+ if (!this.plan) return;
+ const page = doc.page(this.pageIndex);
+ const structure = doc.structure(this.pageIndex);
+ for (const step of [...this.plan.steps].reverse()) {
+ revertStep(doc, page, structure, step);
+ }
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ describe(): string {
+ return i18n.t("pdfTextEditor.commands.tagPageContent", "Auto-tag page");
+ }
+}
+
+/** True when TagPageContentCommand would change anything on the page, which must already be read. */
+export function hasUntaggedContent(
+ doc: EditorDocument,
+ pageIndex: number,
+): boolean {
+ const structure = doc.structure(pageIndex);
+ if (structure.cannotAddElement() !== null) return false;
+ return planTagging(doc, doc.page(pageIndex), structure).steps.length > 0;
+}
+
+/** The untagged content as steps, and where each new element reads. */
+function planTagging(
+ doc: EditorDocument,
+ page: Page,
+ structure: PageStructure,
+): Plan {
+ const m = doc.module;
+ const marks = new Map<number, TagMark[]>();
+ const marksOf = (ptr: number): TagMark[] => {
+ if (!marks.has(ptr)) marks.set(ptr, readTagMarks(m, ptr));
+ return marks.get(ptr)!;
+ };
+ /** The marks the object loses when tagged; null when it is not untagged. */
+ const untagged = (ptr: number): TagMark[] | null => {
+ const tags = marksOf(ptr);
+ if (tags.some((tag) => tag.name === ARTIFACT_TAG)) return null;
+ const mcid = innermostMcid(tags);
+ return mcid === null || !structure.element(mcid) ? tags : null;
+ };
+
+ const order = contentOrder(m, page.pagePtr);
+ let nextMcid = structure.freeMcid(highestMcid(m, page.pagePtr));
+ const located: { at: number; step: Step }[] = [];
+
+ for (const run of page.runs) {
+ const containers = collectContainersByPtr(run);
+ const members = collectMemberPtrs(run);
+ if (
+ members.length === 0 ||
+ members.some((ptr) => ptr === 0 || containers.get(ptr))
+ ) {
+ continue;
+ }
+ // A run with a tagged member is part of an element already; an artifact
+ // member beside untagged text, such as a bullet, stays one.
+ if (members.some((ptr) => !untagged(ptr) && !isArtifact(marksOf(ptr)))) {
+ continue;
+ }
+ const objects = members.flatMap((ptr) => {
+ const dropped = untagged(ptr);
+ return dropped ? [{ ptr, dropped }] : [];
+ });
+ if (objects.length === 0) continue;
+ located.push({
+ at: Math.min(...objects.map(({ ptr }) => order.get(ptr) ?? Infinity)),
+ step: {
+ kind: "text",
+ runId: run.id,
+ mcid: nextMcid++,
+ objects,
+ runMarks: run.tagMarks,
+ },
+ });
+ }
+
+ for (const image of page.images) {
+ const dropped =
+ image.containerPtr === 0 ? untagged(image.pdfiumObjPtr) : null;
+ if (!dropped) continue;
+ located.push({
+ at: order.get(image.pdfiumObjPtr) ?? Infinity,
+ step: {
+ kind: "image",
+ imageId: image.id,
+ mcid: nextMcid++,
+ object: { ptr: image.pdfiumObjPtr, dropped },
+ },
+ });
+ }
+
+ for (const [ptr, at] of order) {
+ const type = m.FPDFPageObj_GetType(ptr);
+ if (type !== FPDF_PAGEOBJ_PATH && type !== FPDF_PAGEOBJ_SHADING) continue;
+ const dropped = untagged(ptr);
+ if (dropped) {
+ located.push({
+ at,
+ step: { kind: "artifact", object: { ptr, dropped } },
+ });
+ }
+ }
+
+ located.sort((a, b) => a.at - b.at);
+ return {
+ steps: located.map(({ step }) => step),
+ follows: readingChain(located, order, (ptr) => {
+ const mcid = innermostMcid(marksOf(ptr));
+ return mcid !== null && structure.element(mcid) ? mcid : null;
+ }),
+ };
+}
+
+/**
+ * Each new element's predecessor in content order: the content read last
+ * before it, the file's or another new element's.
+ */
+function readingChain(
+ located: readonly { at: number; step: Step }[],
+ order: ReadonlyMap<number, number>,
+ ownedMcid: (ptr: number) => number | null,
+): Map<number, number | null> {
+ const tagged: { at: number; mcid: number }[] = [];
+ for (const [ptr, at] of order) {
+ const mcid = ownedMcid(ptr);
+ if (mcid !== null) tagged.push({ at, mcid });
+ }
+ for (const { at, step } of located) {
+ if (step.kind !== "artifact") tagged.push({ at, mcid: step.mcid });
+ }
+ tagged.sort((a, b) => a.at - b.at);
+
+ const follows = new Map<number, number | null>();
+ let previous: number | null = null;
+ const added = new Set(
+ located.flatMap(({ step }) =>
+ step.kind === "artifact" ? [] : [step.mcid],
+ ),
+ );
+ for (const { mcid } of tagged) {
+ if (added.has(mcid)) follows.set(mcid, previous);
+ previous = mcid;
+ }
+ return follows;
+}
+
+/** Each page-level object's index in the page's content, by pointer. */
+function contentOrder(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+): Map<number, number> {
+ const order = new Map<number, number>();
+ const count = m.FPDFPage_CountObjects(pagePtr);
+ for (let i = 0; i < count; i++) {
+ const ptr = m.FPDFPage_GetObject(pagePtr, i);
+ if (ptr) order.set(ptr, i);
+ }
+ return order;
+}
+
+function isArtifact(tags: readonly TagMark[]): boolean {
+ return tags.some((tag) => tag.name === ARTIFACT_TAG);
+}
+
+function applyStep(
+ doc: EditorDocument,
+ page: Page,
+ structure: PageStructure,
+ step: Step,
+ follows: ReadonlyMap<number, number | null>,
+): void {
+ switch (step.kind) {
+ case "text": {
+ const run = page.runs.find((r) => r.id === step.runId);
+ if (!run) throw new Error(`no run ${step.runId}`);
+ const tag = { name: TEXT_TAG, mcid: step.mcid };
+ for (const object of step.objects) retag(doc, object, tag);
+ run.tagMarks = [tag];
+ structure.addElement(step.mcid, TEXT_TAG, follows.get(step.mcid));
+ return;
+ }
+ case "image": {
+ const image = page.findImage(step.imageId);
+ if (!image) throw new Error(`no image ${step.imageId}`);
+ retag(doc, step.object, { name: IMAGE_TAG, mcid: step.mcid });
+ image.mcid = step.mcid;
+ structure.addElement(step.mcid, IMAGE_TAG, follows.get(step.mcid));
+ return;
+ }
+ case "artifact":
+ retag(doc, step.object, { name: ARTIFACT_TAG, mcid: null });
+ }
+}
+
+/** Undo applyStep. Best effort: a step half applied is undone as far as it went. */
+function revertStep(
+ doc: EditorDocument,
+ page: Page,
+ structure: PageStructure,
+ step: Step,
+): void {
+ switch (step.kind) {
+ case "text": {
+ for (const object of step.objects) restore(doc, object, TEXT_TAG);
+ const run = page.runs.find((r) => r.id === step.runId);
+ if (run) run.tagMarks = step.runMarks;
+ structure.removeElement(step.mcid);
+ return;
+ }
+ case "image": {
+ restore(doc, step.object, IMAGE_TAG);
+ const image = page.findImage(step.imageId);
+ if (image) image.mcid = innermostMcid(step.object.dropped);
+ structure.removeElement(step.mcid);
+ return;
+ }
+ case "artifact":
+ restore(doc, step.object, ARTIFACT_TAG);
+ }
+}
+
+function retag(doc: EditorDocument, object: Retag, tag: TagMark): void {
+ for (const dropped of [...object.dropped].reverse()) {
+ if (!removeTagMark(doc.module, object.ptr, dropped.name)) {
+ throw new Error("PDFium could not remove a tag");
+ }
+ }
+ if (!addTagMark(doc.module, doc.docPtr, object.ptr, tag)) {
+ throw new Error("PDFium could not tag the content");
+ }
+}
+
+function restore(doc: EditorDocument, object: Retag, name: string): void {
+ removeTagMark(doc.module, object.ptr, name);
+ for (const dropped of object.dropped) {
+ addTagMark(doc.module, doc.docPtr, object.ptr, dropped);
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
index 2aae44e8a9..b76e061e6b 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
@@ -1,7 +1,8 @@
-import { useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import { Box, Center, Group, Stack, Tabs, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Icon } from "@editor/ui/Icon";
+import { useBulkTagging } from "@editor/tools/pdfTextEditor/hooks/useBulkTagging";
import { useHeadingOutline } from "@editor/tools/pdfTextEditor/hooks/useHeadingOutline";
import { useDocumentLanguage } from "@editor/tools/pdfTextEditor/hooks/useDocumentLanguage";
import { useToolbarController } from "@editor/tools/pdfTextEditor/hooks/useToolbarController";
@@ -10,7 +11,8 @@ import { DocumentInspector } from "@editor/tools/pdfTextEditor/components/inspec
import { LanguagesInUse } from "@editor/tools/pdfTextEditor/components/inspector/languagesInUse";
import { SelectionInspector } from "@editor/tools/pdfTextEditor/components/inspector/SelectionInspector";
import { analyzePageFonts } from "@editor/tools/pdfTextEditor/util/pageFonts";
-import { ensureAllPagesRead } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";
+import { readAllPagesInBackground } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";
+import { SetMarkedTaggedCommand } from "@editor/tools/pdfTextEditor/commands/SetMarkedTaggedCommand";
import { ACCESSIBILITY_EDITING } from "@editor/constants/featureFlags";
import {
ScanHint,
@@ -82,7 +84,7 @@ export function EditorSidebar({
const editorDocument = store.document;
const reviewingAccessibility = useMemo(
- () => ACCESSIBILITY_EDITING && !!editorDocument?.isTagged(),
+ () => ACCESSIBILITY_EDITING && !!editorDocument?.treatAsTagged(),
[editorDocument],
);
const imageSelected = controller.imageAccessibility !== null;
@@ -92,15 +94,24 @@ export function EditorSidebar({
if (!reviewingAccessibility || (tab !== "document" && !imageSelected)) {
return;
}
- const id = window.setTimeout(() => ensureAllPagesRead(store), 0);
- return () => window.clearTimeout(id);
+ return readAllPagesInBackground(store);
}, [reviewingAccessibility, tab, imageSelected, store]);
+ const setMarkedTagged = useCallback(
+ (marked: boolean) => store.dispatch(new SetMarkedTaggedCommand(marked)),
+ [store],
+ );
const headings = useHeadingOutline(
store,
state,
reviewingAccessibility && tab === "document",
);
+ const bulkTagging = useBulkTagging(
+ store,
+ state,
+ reviewingAccessibility && tab === "document",
+ );
+
// Following the selection only catches one appearing, so moving from one
// selected image to the next would leave the new one's description hidden.
const selectNextImageToReview = () => {
@@ -183,6 +194,15 @@ export function EditorSidebar({
reviewingAccessibility ? controller.imageReview : null
}
onSelectNextImageToReview={selectNextImageToReview}
+ untaggedPages={bulkTagging.untaggedPages}
+ onTagUntaggedContent={bulkTagging.tagAll}
+ markedTagged={
+ editorDocument?.canSetMarkedTagged()
+ ? editorDocument.markedTagged()
+ : null
+ }
+ onSetMarkedTagged={setMarkedTagged}
+ hasTags={!!editorDocument?.hasStructureTree()}
headingOutline={headings.outline}
onSelectHeading={headings.selectHeading}
documentLanguage={documentLanguage}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.tsx
index 1a8431c314..f24825216c 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.tsx
@@ -14,7 +14,7 @@ import type {
MatchOptions,
TextMatch,
} from "@editor/tools/pdfTextEditor/util/textMatching";
-import { ensureAllPagesRead } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";
+import { readAllPagesInBackground } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";
import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
import type {
PageSnapshot,
@@ -64,11 +64,9 @@ export function FindBar({ store, pages, onClose }: FindBarProps) {
}, []);
// Opening Find is a document-wide request, so pull in every page that lazy
- // loading has not read yet. Yield first: the read is synchronous, and on a
- // long document it would otherwise block before the bar has painted.
+ // loading has not read yet.
useEffect(() => {
- const id = setTimeout(() => ensureAllPagesRead(store), 0);
- return () => clearTimeout(id);
+ return readAllPagesInBackground(store);
}, [store]);
const options: MatchOptions = useMemo(
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx
index b4629521a1..6b92614caa 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx
@@ -192,7 +192,7 @@ export function ImageHandle({
}
>
<span
- data-testid={`pdf-editor-image-attention-${image.id}`}
+ data-testid={`pdf-editor-attention-image-${image.id}`}
data-attention={attention}
style={{
position: "absolute",
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/PageStage.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/PageStage.tsx
index 0c5cb08ec5..410b037a1e 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/PageStage.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/PageStage.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import {
Box,
Center,
@@ -30,7 +30,11 @@ import { InsertTextCommand } from "@editor/tools/pdfTextEditor/commands/InsertTe
import { InsertTableCommand } from "@editor/tools/pdfTextEditor/commands/InsertTableCommand";
import { MoveTextRunCommand } from "@editor/tools/pdfTextEditor/commands/MoveTextRunCommand";
import { SetImageTransformCommand } from "@editor/tools/pdfTextEditor/commands/SetImageTransformCommand";
-import type { SelectionState } from "@editor/tools/pdfTextEditor/types";
+import type {
+ SelectionState,
+ TextRange,
+} from "@editor/tools/pdfTextEditor/types";
+import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
const DEFAULT_SCALE = 1.5;
const DESKTOP_FIT_PAD_PX = 64;
@@ -52,6 +56,8 @@ export function PageStage() {
const stageRootRef = useRef<HTMLDivElement | null>(null);
const isMobile = useIsMobile();
+ const pageHandlers = useMemo(() => pageViewHandlers(store), [store]);
+
useEffect(() => store.selection.subscribe(setSelection), [store]);
useEffect(
() => store.selection.highlight.subscribe(setHighlightedRunId),
@@ -357,101 +363,8 @@ export function PageStage() {
selectedImageIds={selection.imageIds}
selectedShapeIds={selection.shapeIds}
highlightedRunId={highlightedRunId}
- onSelectRun={(runId, shiftKey) => {
- if (shiftKey) store.selection.toggle(runId);
- else store.selection.selectOne(runId);
- }}
- onSelectRunText={(runId, range) =>
- store.selection.setTextRange(runId, range)
- }
selectedTextRange={selection.textRange}
- onSelectImage={(imageId) =>
- store.selection.selectImage(imageId)
- }
- onSelectShape={(shapeId, extend) => {
- if (extend) store.selection.toggleShape(shapeId);
- else store.selection.selectShape(shapeId);
- }}
- onMoveShape={(pageIndex, shapeId, dx, dy) => {
- store.dispatch(
- new MoveShapeCommand({ pageIndex, shapeId, dx, dy }),
- );
- store.selection.selectShape(shapeId);
- }}
- onEditRun={(pageIndex, runId, nextText) => {
- // contentEditable can fire several input events per
- // keystroke burst.
- const current = store.document
- ?.page(pageIndex)
- .findRun(runId);
- if (current && current.text === nextText) return;
- store.dispatch(
- new EditTextCommand({ pageIndex, runId, nextText }),
- );
- }}
- onMoveRun={(pageIndex, runId, dx, dy) => {
- store.dispatch(
- new MoveTextRunCommand({ pageIndex, runId, dx, dy }),
- );
- }}
- onWrapRun={(pageIndex, runId, maxWidthPt) => {
- store.dispatch(
- new ReflowWrapCommand({ pageIndex, runId, maxWidthPt }),
- );
- }}
- onResizeRun={(pageIndex, runId, widthPt) => {
- store.dispatch(
- new ReflowWrapCommand({
- pageIndex,
- runId,
- maxWidthPt: widthPt,
- explicit: true,
- }),
- );
- }}
- onPageClick={(pageIndex, pageX, pageY) => {
- if (state.mode === "addTable") {
- const cmd = new InsertTableCommand({
- pageIndex,
- x: pageX,
- y: pageY,
- width: 360,
- height: 24 * 3,
- rows: 3,
- cols: 3,
- });
- store.dispatch(cmd);
- store.setMode("select");
- return;
- }
- if (state.mode !== "addText") return;
- const cmd = new InsertTextCommand({
- pageIndex,
- x: pageX,
- y: pageY,
- text: "New text",
- });
- store.dispatch(cmd);
- if (cmd.insertedRunId) {
- store.selection.selectOne(cmd.insertedRunId);
- }
- store.setMode("select");
- }}
- onTransformImage={(pageIndex, imageId, nextBounds) => {
- store.dispatch(
- new SetImageTransformCommand({
- pageIndex,
- imageId,
- nextBounds,
- }),
- );
- }}
- onFirstVisible={(pageIndex) =>
- ensurePageRead(store, pageIndex)
- }
- onFirstRendered={(pageIndex) => {
- if (pageIndex === 0) store.markFirstPageRendered();
- }}
+ {...pageHandlers}
/>
) : null,
)}
@@ -480,3 +393,95 @@ export function PageStage() {
</Stack>
);
}
+
+/**
+ * The page views' handlers, made once per store: PageView is memoised, so a
+ * handler made per render would re-render every page on any store change.
+ * They read the store when called, never state captured at render.
+ */
+function pageViewHandlers(store: EditorStore) {
+ return {
+ onSelectRun: (runId: string, shiftKey: boolean) => {
+ if (shiftKey) store.selection.toggle(runId);
+ else store.selection.selectOne(runId);
+ },
+ onSelectRunText: (runId: string, range: TextRange | null) =>
+ store.selection.setTextRange(runId, range),
+ onSelectImage: (imageId: string) => store.selection.selectImage(imageId),
+ onSelectShape: (shapeId: string, extend: boolean) => {
+ if (extend) store.selection.toggleShape(shapeId);
+ else store.selection.selectShape(shapeId);
+ },
+ onMoveShape: (
+ pageIndex: number,
+ shapeId: string,
+ dx: number,
+ dy: number,
+ ) => {
+ store.dispatch(new MoveShapeCommand({ pageIndex, shapeId, dx, dy }));
+ store.selection.selectShape(shapeId);
+ },
+ onEditRun: (pageIndex: number, runId: string, nextText: string) => {
+ // contentEditable can fire several input events per keystroke burst.
+ const current = store.document?.page(pageIndex).findRun(runId);
+ if (current && current.text === nextText) return;
+ store.dispatch(new EditTextCommand({ pageIndex, runId, nextText }));
+ },
+ onMoveRun: (pageIndex: number, runId: string, dx: number, dy: number) => {
+ store.dispatch(new MoveTextRunCommand({ pageIndex, runId, dx, dy }));
+ },
+ onWrapRun: (pageIndex: number, runId: string, maxWidthPt: number) => {
+ store.dispatch(new ReflowWrapCommand({ pageIndex, runId, maxWidthPt }));
+ },
+ onResizeRun: (pageIndex: number, runId: string, widthPt: number) => {
+ store.dispatch(
+ new ReflowWrapCommand({
+ pageIndex,
+ runId,
+ maxWidthPt: widthPt,
+ explicit: true,
+ }),
+ );
+ },
+ onPageClick: (pageIndex: number, pageX: number, pageY: number) => {
+ const { mode } = store.getState();
+ if (mode === "addTable") {
+ const cmd = new InsertTableCommand({
+ pageIndex,
+ x: pageX,
+ y: pageY,
+ width: 360,
+ height: 24 * 3,
+ rows: 3,
+ cols: 3,
+ });
+ store.dispatch(cmd);
+ store.setMode("select");
+ return;
+ }
+ if (mode !== "addText") return;
+ const cmd = new InsertTextCommand({
+ pageIndex,
+ x: pageX,
+ y: pageY,
+ text: "New text",
+ });
+ store.dispatch(cmd);
+ if (cmd.insertedRunId) store.selection.selectOne(cmd.insertedRunId);
+ store.setMode("select");
+ },
+ onTransformImage: (
+ pageIndex: number,
+ imageId: string,
+ nextBounds: { x: number; y: number; width: number; height: number },
+ ) => {
+ store.dispatch(
+ new SetImageTransformCommand({ pageIndex, imageId, nextBounds }),
+ );
+ },
+ onFirstVisible: (pageIndex: number) => ensurePageRead(store, pageIndex),
+ onFirstRendered: (pageIndex: number) => {
+ if (pageIndex === 0) store.markFirstPageRendered();
+ },
+ };
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
index 3a93257fd2..d845bed91b 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useRef, useState } from "react";
+import { memo, useEffect, useMemo, useRef, useState } from "react";
import { Box, Loader } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Button } from "@editor/ui/Button";
@@ -92,9 +92,13 @@ function nearestScrollRoot(el: HTMLElement): HTMLElement | null {
return null;
}
-// One PDF page: a PDFium-rendered bitmap plus an HTML overlay layer with one
-// positioned, editable element per text run.
-export function PageView({
+/**
+ * One PDF page: a PDFium-rendered bitmap plus an overlay with one positioned,
+ * editable element per text run. Memoised: with every page read, re-rendering them
+ * all on each store change takes seconds, so a caller must pass handlers that
+ * keep their identity across renders.
+ */
+export const PageView = memo(function PageView({
document,
store,
page,
@@ -462,4 +466,4 @@ export function PageView({
</Box>
</Box>
);
-}
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsx
index cec981c444..d17ae18492 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsx
@@ -9,6 +9,19 @@ function renderInspector(
imageReview: ImageReview | null,
onNext = vi.fn(),
documentLanguage: DocumentLanguageControl | null = null,
+ {
+ untaggedPages = 0,
+ onTagUntagged = vi.fn(),
+ markedTagged = false,
+ onSetMarkedTagged = vi.fn(),
+ hasTags = false,
+ }: {
+ untaggedPages?: number;
+ onTagUntagged?: () => void;
+ markedTagged?: boolean | null;
+ onSetMarkedTagged?: (marked: boolean) => void;
+ hasTags?: boolean;
+ } = {},
) {
render(
<MantineProvider env="test">
@@ -22,6 +35,11 @@ function renderInspector(
onSetShowRulers={vi.fn()}
imageReview={imageReview}
onSelectNextImageToReview={onNext}
+ untaggedPages={untaggedPages}
+ onTagUntaggedContent={onTagUntagged}
+ markedTagged={markedTagged}
+ onSetMarkedTagged={onSetMarkedTagged}
+ hasTags={hasTags}
headingOutline={null}
onSelectHeading={vi.fn()}
documentLanguage={documentLanguage}
@@ -34,6 +52,10 @@ function renderInspector(
const KEY = "pdfTextEditor.inspector.accessibility";
const SUMMARY = "pdf-editor-document-accessibility-summary";
const NEXT = "pdf-editor-document-accessibility-next";
+const TAG_UNTAGGED = "pdf-editor-document-accessibility-tag-untagged";
+const MARKED = "pdf-editor-document-accessibility-marked";
+const MARKED_WARNING = "pdf-editor-document-accessibility-marked-warning";
+const NOTHING_TO_REVIEW = { needsDescription: 0, untagged: 0, untaggable: 0 };
describe("DocumentInspector accessibility review", () => {
it("counts images missing descriptions and untagged ones, and moves to the next", () => {
@@ -76,6 +98,60 @@ describe("DocumentInspector accessibility review", () => {
screen.queryByTestId("pdf-editor-document-accessibility"),
).not.toBeInTheDocument();
});
+
+ it("counts pages with untagged content and tags them", () => {
+ const onTagUntagged = vi.fn();
+ renderInspector(NOTHING_TO_REVIEW, vi.fn(), null, {
+ untaggedPages: 3,
+ onTagUntagged,
+ });
+ expect(screen.getByTestId(SUMMARY)).toHaveTextContent(
+ `${KEY}.untaggedPages3`,
+ );
+ fireEvent.click(screen.getByTestId(TAG_UNTAGGED));
+ expect(onTagUntagged).toHaveBeenCalledOnce();
+ });
+
+ it("offers no tagging once every page is tagged", () => {
+ renderInspector(NOTHING_TO_REVIEW);
+ expect(screen.queryByTestId(TAG_UNTAGGED)).not.toBeInTheDocument();
+ });
+
+ it("ticks the fully-tagged box to mark the document", () => {
+ const onSetMarkedTagged = vi.fn();
+ renderInspector(NOTHING_TO_REVIEW, vi.fn(), null, { onSetMarkedTagged });
+ const box = screen.getByTestId(MARKED);
+ expect(box).not.toBeChecked();
+ fireEvent.click(box);
+ expect(onSetMarkedTagged).toHaveBeenCalledWith(true);
+ });
+
+ it("leaves the box out when the file's flag can't be changed", () => {
+ renderInspector(NOTHING_TO_REVIEW, vi.fn(), null, { markedTagged: null });
+ expect(screen.queryByTestId(MARKED)).not.toBeInTheDocument();
+ });
+
+ it("warns when marked tagged while content is untagged", () => {
+ renderInspector(NOTHING_TO_REVIEW, vi.fn(), null, {
+ markedTagged: true,
+ untaggedPages: 2,
+ });
+ expect(screen.getByTestId(MARKED_WARNING)).toHaveTextContent(
+ `${KEY}.markedWithUntagged`,
+ );
+ });
+
+ it("warns when tags exist but the document isn't marked tagged", () => {
+ renderInspector(NOTHING_TO_REVIEW, vi.fn(), null, { hasTags: true });
+ expect(screen.getByTestId(MARKED_WARNING)).toHaveTextContent(
+ `${KEY}.unmarkedWithTags`,
+ );
+ });
+
+ it("shows no warning when the flag matches the tags", () => {
+ renderInspector(NOTHING_TO_REVIEW, vi.fn(), null, { markedTagged: true });
+ expect(screen.queryByTestId(MARKED_WARNING)).not.toBeInTheDocument();
+ });
});
describe("DocumentInspector language", () => {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsx
index d11a9f307e..0c6c1a2ac4 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsx
@@ -2,7 +2,9 @@ import { useState } from "react";
import type { TFunction } from "i18next";
import { Badge, Collapse, Group, Stack, Text, Tooltip } from "@mantine/core";
import { useTranslation } from "react-i18next";
+import { Tooltip as InfoTooltip } from "@editor/components/shared/Tooltip";
import { Button } from "@editor/ui/Button";
+import { Checkbox } from "@editor/ui/Checkbox";
import { Icon } from "@editor/ui/Icon";
import {
Field,
@@ -37,6 +39,14 @@ interface Props {
/** Images needing attention; null when there is nothing to review. */
imageReview: ImageReview | null;
onSelectNextImageToReview: () => void;
+ /** Read pages with content left untagged. */
+ untaggedPages: number;
+ onTagUntaggedContent: () => void;
+ /** Whether the file declares itself tagged; null when that can't be changed. */
+ markedTagged: boolean | null;
+ onSetMarkedTagged: (marked: boolean) => void;
+ /** Whether the saved file will hold any tags. */
+ hasTags: boolean;
/** Null when there is nothing to check. */
headingOutline: HeadingOutline | null;
onSelectHeading: (index: number) => void;
@@ -49,6 +59,11 @@ export function DocumentInspector({
pages,
imageReview,
onSelectNextImageToReview,
+ untaggedPages,
+ onTagUntaggedContent,
+ markedTagged,
+ onSetMarkedTagged,
+ hasTags,
headingOutline,
onSelectHeading,
documentLanguage,
@@ -85,6 +100,11 @@ export function DocumentInspector({
<AccessibilitySection
review={imageReview}
onNext={onSelectNextImageToReview}
+ untaggedPages={untaggedPages}
+ onTagUntagged={onTagUntaggedContent}
+ markedTagged={markedTagged}
+ onSetMarkedTagged={onSetMarkedTagged}
+ hasTags={hasTags}
/>
)}
{headingOutline && (
@@ -161,15 +181,25 @@ function documentLanguageHint(
function AccessibilitySection({
review,
onNext,
+ untaggedPages,
+ onTagUntagged,
+ markedTagged,
+ onSetMarkedTagged,
+ hasTags,
}: {
review: ImageReview;
onNext: () => void;
+ untaggedPages: number;
+ onTagUntagged: () => void;
+ markedTagged: boolean | null;
+ onSetMarkedTagged: (marked: boolean) => void;
+ hasTags: boolean;
}) {
const { t } = useTranslation();
const pending = review.needsDescription + review.untagged;
return (
<Section testId="pdf-editor-document-accessibility">
- <SectionLabel>
+ <SectionLabel info={<DocumentAccessibilityInfo />}>
{t("pdfTextEditor.inspector.accessibility.heading", "Accessibility")}
</SectionLabel>
<Stack gap="xs">
@@ -189,7 +219,24 @@ function AccessibilitySection({
value={review.untagged}
/>
<UntaggableRow count={review.untaggable} />
+ <StatRow
+ label={t(
+ "pdfTextEditor.inspector.accessibility.untaggedPages",
+ "Pages to tag",
+ )}
+ value={untaggedPages}
+ />
</Stack>
+ <TagUntaggedButton
+ untaggedPages={untaggedPages}
+ onClick={onTagUntagged}
+ />
+ <MarkedTaggedCheckbox
+ marked={markedTagged}
+ onChange={onSetMarkedTagged}
+ untaggedPages={untaggedPages}
+ hasTags={hasTags}
+ />
{pending > 0 && (
<Button
size="sm"
@@ -209,6 +256,156 @@ function AccessibilitySection({
);
}
+/**
+ * Tags every page's untagged content as a starting point. Absent once there
+ * is none, as Next is once nothing needs attention.
+ */
+function TagUntaggedButton({
+ untaggedPages,
+ onClick,
+}: {
+ untaggedPages: number;
+ onClick: () => void;
+}) {
+ const { t } = useTranslation();
+ if (untaggedPages === 0) return null;
+ return (
+ <Button
+ size="sm"
+ variant="secondary"
+ accent="neutral"
+ fullWidth
+ justify="start"
+ leftSection={<Icon name="tag" size={20} />}
+ onClick={onClick}
+ data-testid="pdf-editor-document-accessibility-tag-untagged"
+ >
+ {t(
+ "pdfTextEditor.inspector.accessibility.tagUntagged",
+ "Auto-tag document",
+ )}
+ </Button>
+ );
+}
+
+/**
+ * The file's claim to be tagged, which readers that honour it read the tags
+ * by. Separate from the tags so a half-tagged file does not make the rest of
+ * its content unreadable. Absent when the file's flag can't be changed.
+ */
+function MarkedTaggedCheckbox({
+ marked,
+ onChange,
+ untaggedPages,
+ hasTags,
+}: {
+ marked: boolean | null;
+ onChange: (marked: boolean) => void;
+ untaggedPages: number;
+ hasTags: boolean;
+}) {
+ const { t } = useTranslation();
+ if (marked === null) return null;
+ return (
+ <Stack gap={4}>
+ <Checkbox
+ checked={marked}
+ onChange={(event) => onChange(event.currentTarget.checked)}
+ label={t(
+ "pdfTextEditor.inspector.accessibility.markedTagged",
+ "Document is fully tagged",
+ )}
+ data-testid="pdf-editor-document-accessibility-marked"
+ />
+ <MarkedTaggedWarning
+ marked={marked}
+ untaggedPages={untaggedPages}
+ hasTags={hasTags}
+ />
+ </Stack>
+ );
+}
+
+/** Why the flag disagrees with the tags; absent when it does not. */
+function MarkedTaggedWarning({
+ marked,
+ untaggedPages,
+ hasTags,
+}: {
+ marked: boolean;
+ untaggedPages: number;
+ hasTags: boolean;
+}) {
+ const { t } = useTranslation();
+ const warning = marked
+ ? untaggedPages > 0 &&
+ t(
+ "pdfTextEditor.inspector.accessibility.markedWithUntagged",
+ "Some content has no tags, so screen readers may skip it.",
+ )
+ : hasTags &&
+ t(
+ "pdfTextEditor.inspector.accessibility.unmarkedWithTags",
+ "Some PDF viewers will use the tags anyway and may skip content without them.",
+ );
+ if (!warning) return null;
+ return (
+ <Text
+ size="xs"
+ style={{ color: "var(--c-danger)" }}
+ data-testid="pdf-editor-document-accessibility-marked-warning"
+ >
+ {warning}
+ </Text>
+ );
+}
+
+/** What the section's controls do, behind the (i) the image section uses too. */
+function DocumentAccessibilityInfo() {
+ const { t } = useTranslation();
+ return (
+ <InfoTooltip
+ sidebarTooltip
+ pinOnClick
+ header={{
+ title: t(
+ "pdfTextEditor.inspector.accessibility.heading",
+ "Accessibility",
+ ),
+ }}
+ tips={[
+ {
+ title: t(
+ "pdfTextEditor.inspector.accessibility.tagUntagged",
+ "Auto-tag document",
+ ),
+ description: t(
+ "pdfTextEditor.inspector.accessibility.tagUntaggedHint",
+ "Automatically adds accessibility tags throughout the document. The result is rough: check headings, lists and reading order afterwards.",
+ ),
+ },
+ {
+ title: t(
+ "pdfTextEditor.inspector.accessibility.markedTagged",
+ "Document is fully tagged",
+ ),
+ description: t(
+ "pdfTextEditor.inspector.accessibility.markedTaggedHint",
+ "Tells PDF readers to use the accessibility tags. Tick it once everything is tagged.",
+ ),
+ },
+ ]}
+ >
+ <span
+ style={{ display: "flex", color: "var(--icon-files-color)" }}
+ data-testid="pdf-editor-document-accessibility-info"
+ >
+ <Icon name="info" size={14} />
+ </span>
+ </InfoTooltip>
+ );
+}
+
/**
* Untagged images nothing here can tag, kept apart so the rows Next works
* through can reach zero. Absent in the usual file, which has none.
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.test.tsx
index 3797146cec..9207278399 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.test.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.test.tsx
@@ -68,6 +68,7 @@ describe("TextAccessibilitySection", () => {
"untaggedDocument",
],
[{ kind: "unknown" } as const, "unknownTag"],
+ [{ kind: "mixed", settable: false } as const, "mixedTags"],
])("explains text with no element (%o)", (tag, message) => {
expect(tagShown(tag)).toHaveTextContent(`${KEY}.${message}`);
});
@@ -91,6 +92,25 @@ describe("TextAccessibilitySection", () => {
expect(onRetag).toHaveBeenCalledWith("Code");
});
+ it("offers a picker for runs tagged differently, set on all of them", () => {
+ const onSetTag = vi.fn();
+ render(
+ <MantineProvider env="test">
+ <TextAccessibilitySection
+ tag={{ kind: "mixed", settable: true }}
+ onSetTag={onSetTag}
+ inner={NO_INNER}
+ language={null}
+ />
+ </MantineProvider>,
+ );
+ const input = screen.getByRole("textbox", { name: `${KEY}.tagLabel` });
+ expect(input).toHaveAttribute("placeholder", `${KEY}.mixedTags`);
+ fireEvent.click(input);
+ fireEvent.click(screen.getByText(`${KEY}.tagName.paragraph`));
+ expect(onSetTag).toHaveBeenCalledWith("P");
+ });
+
it("shows a tag the picker does not offer in its place", () => {
render(
<MantineProvider env="test">
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsx
index 5258caff31..6ac9aa742f 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsx
@@ -15,9 +15,10 @@ import type {
StructureRole,
StructureType,
} from "@editor/tools/pdfTextEditor/model/structureTypes";
-import type {
- InnerTag,
- TextTag,
+import {
+ canSetTextTag,
+ type InnerTag,
+ type TextTag,
} from "@editor/tools/pdfTextEditor/util/textAccessibility";
import type {
InnerTagsControl,
@@ -31,8 +32,8 @@ import { privateContentClassName } from "@editor/components/shared/privateConten
* What the selected text is tagged as and the language it is read in, with
* pickers to change them: retagging its block, or giving untagged text an
* element of its own. Beneath them, the tags marking parts of the text, and
- * pickers for characters selected in it. With several runs selected, only
- * their language: `tag` is null.
+ * pickers for characters selected in it. With several runs selected, the tag
+ * they share and their language.
*/
export function TextAccessibilitySection({
tag,
@@ -75,7 +76,7 @@ function TagField({
}) {
const { t } = useTranslation();
const label = t("pdfTextEditor.inspector.accessibility.tagLabel", "Tag");
- return pickable(tag) ? (
+ return canSetTextTag(tag) ? (
<Field label={label}>
<TagPicker
types={TEXT_BLOCK_TYPES}
@@ -320,11 +321,6 @@ function NewLanguagePicker({ inner }: { inner: InnerTagsControl }) {
);
}
-function pickable(tag: TextTag): boolean {
- if (tag.kind === "tagged") return tag.cannotRetag === null;
- return tag.kind === "untagged" && tag.taggable;
-}
-
function TagPicker({
types,
current,
@@ -400,6 +396,8 @@ function statusText(
"pdfTextEditor.inspector.accessibility.unknownTag",
"Can't be read here",
);
+ case "mixed":
+ return t("pdfTextEditor.inspector.accessibility.mixedTags", "Mixed");
}
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useBulkTagging.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useBulkTagging.ts
new file mode 100644
index 0000000000..a8751911ee
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useBulkTagging.ts
@@ -0,0 +1,117 @@
+import { useCallback, useMemo, useRef } from "react";
+import i18n from "i18next";
+import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
+import { CompositeCommand } from "@editor/tools/pdfTextEditor/commands/CompositeCommand";
+import { SetMarkedTaggedCommand } from "@editor/tools/pdfTextEditor/commands/SetMarkedTaggedCommand";
+import {
+ TagPageContentCommand,
+ hasUntaggedContent,
+} from "@editor/tools/pdfTextEditor/commands/TagPageContentCommand";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { publishAllPages } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import type {
+ EditorStore,
+ EditorViewState,
+} from "@editor/tools/pdfTextEditor/store/EditorStore";
+
+/** Work this long before letting the browser paint the progress. */
+const SLICE_MS = 50;
+
+interface CountCache {
+ doc: EditorDocument | null;
+ /** By page index: whether the page had untagged content at that revision. */
+ pages: Map<number, { revision: number; untagged: boolean }>;
+}
+
+/**
+ * How many read pages have content TagPageContentCommand would tag, and a way
+ * to tag every page's as one undo step. Counted only while `shown`, and only
+ * for pages whose revision changed since the last count.
+ */
+export function useBulkTagging(
+ store: EditorStore,
+ state: EditorViewState,
+ shown: boolean,
+) {
+ const cache = useRef<CountCache>({ doc: null, pages: new Map() });
+
+ const untaggedPages = useMemo(() => {
+ const doc = shown ? store.document : null;
+ if (!doc) return 0;
+ if (cache.current.doc !== doc) cache.current = { doc, pages: new Map() };
+ const counted = cache.current.pages;
+ let count = 0;
+ for (const page of doc.loadedPages()) {
+ if (!page.loaded) continue;
+ let entry = counted.get(page.index);
+ if (entry?.revision !== page.revision) {
+ entry = {
+ revision: page.revision,
+ untagged: hasUntaggedContent(doc, page.index),
+ };
+ counted.set(page.index, entry);
+ }
+ if (entry.untagged) count++;
+ }
+ return count;
+ // state.pages is new whenever a page is read or edited.
+ }, [store, state.pages, shown]);
+
+ const tagAll = useCallback(() => void tagAllPages(store), [store]);
+
+ return { untaggedPages, tagAll };
+}
+
+/**
+ * Read and tag every page behind the loading overlay, a slice at a time so
+ * its progress paints, then mark the document fully tagged and record it all
+ * as one undo step. Every page tagged is untagged again when one fails.
+ */
+export async function tagAllPages(store: EditorStore): Promise<void> {
+ const doc = store.document;
+ if (!doc || store.getState().loading) return;
+ const pageIndices = store.getState().pages.map((p) => p.pageIndex);
+ const stage = i18n.t(
+ "pdfTextEditor.inspector.accessibility.tagging",
+ "Tagging pages",
+ );
+ const applied: TagPageContentCommand[] = [];
+ store.setLoading(true);
+ try {
+ let sliceStart = -Infinity;
+ for (const [done, pageIndex] of pageIndices.entries()) {
+ if (performance.now() - sliceStart > SLICE_MS) {
+ store.setProgress({ stage, current: done, total: pageIndices.length });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ if (store.document !== doc) return;
+ sliceStart = performance.now();
+ }
+ const page = doc.page(pageIndex);
+ if (!page.loaded)
+ PdfiumTextReader.populate(doc, page, store.groupingMode);
+ if (!hasUntaggedContent(doc, pageIndex)) continue;
+ const command = new TagPageContentCommand({ pageIndex });
+ command.apply(doc);
+ applied.push(command);
+ }
+ const steps: Command[] = [...applied];
+ if (doc.canSetMarkedTagged() && !doc.markedTagged()) {
+ const mark = new SetMarkedTaggedCommand(true);
+ mark.apply(doc);
+ steps.push(mark);
+ }
+ publishAllPages(store);
+ if (steps.length > 0) {
+ store.recordApplied(
+ steps.length === 1 ? steps[0] : new CompositeCommand(steps),
+ );
+ }
+ } catch (err) {
+ for (const command of applied.reverse()) command.revert(doc);
+ publishAllPages(store);
+ store.setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ if (store.document === doc) store.setLoading(false);
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
index d4975e8634..6a5aa383f1 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
@@ -15,6 +15,8 @@ import { assertPdfSessionEditable } from "@editor/services/pdfSessionUnlock";
import { readPdfiumAccess } from "@editor/utils/pdfiumAccess";
const EAGER_PAGE_LIMIT = 5;
+/** Work this long before letting the browser paint. */
+const BACKGROUND_SLICE_MS = 50;
/** Yield to the event loop so the React layer can paint progress. */
const yieldToBrowser = () =>
@@ -149,17 +151,66 @@ export function ensureAllPagesRead(store: EditorStore): void {
if (!doc) return;
let any = false;
for (const p of store.getState().pages) {
- const page = doc.page(p.pageIndex);
- if (page.loaded) continue;
- try {
- // Lazy reads must surface failures like the eager path, not throw out of the observer.
- PdfiumTextReader.populate(doc, page, store.groupingMode);
- any = true;
- } catch (err) {
- store.setError(err instanceof Error ? err.message : String(err));
+ any = readPage(store, doc, p.pageIndex) || any;
+ }
+ if (any) publishAllPages(store);
+}
+
+/**
+ * ensureAllPagesRead without blocking: reads a slice at a time, yielding
+ * between slices, and publishes when done or cancelled. The returned function
+ * cancels; it is safe to call after the read has finished.
+ */
+export function readAllPagesInBackground(store: EditorStore): () => void {
+ let cancelled = false;
+ void (async () => {
+ const doc = store.document;
+ if (!doc) return;
+ const pending = store
+ .getState()
+ .pages.map((p) => p.pageIndex)
+ .filter((i) => !doc.page(i).loaded);
+ let any = false;
+ // Yield before the first slice so whatever asked for the read paints first.
+ let sliceStart = -Infinity;
+ for (const pageIndex of pending) {
+ if (performance.now() - sliceStart > BACKGROUND_SLICE_MS) {
+ await yieldToBrowser();
+ sliceStart = performance.now();
+ }
+ // A page read but never published would never get its overlays.
+ if (cancelled || store.document !== doc) break;
+ any = readPage(store, doc, pageIndex) || any;
}
+ if (any && store.document === doc) publishAllPages(store);
+ })();
+ return () => {
+ cancelled = true;
+ };
+}
+
+/** False when the page was already read or failed to read. */
+function readPage(
+ store: EditorStore,
+ doc: EditorDocument,
+ pageIndex: number,
+): boolean {
+ const page = doc.page(pageIndex);
+ if (page.loaded) return false;
+ try {
+ // Lazy reads must surface failures like the eager path, not throw out of the observer.
+ PdfiumTextReader.populate(doc, page, store.groupingMode);
+ return true;
+ } catch (err) {
+ store.setError(err instanceof Error ? err.message : String(err));
+ return false;
}
- if (!any) return;
+}
+
+/** Publish every page's snapshot as the document has it now. */
+export function publishAllPages(store: EditorStore): void {
+ const doc = store.document;
+ if (!doc) return;
const next = store.getState().pages.map((p) => {
const page = doc.page(p.pageIndex);
return {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts
index cf882d95eb..e3b1fea382 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts
@@ -1,5 +1,7 @@
import { useCallback, useMemo } from "react";
import { ACCESSIBILITY_EDITING } from "@editor/constants/featureFlags";
+import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
+import { CompositeCommand } from "@editor/tools/pdfTextEditor/commands/CompositeCommand";
import { RetagInnerCommand } from "@editor/tools/pdfTextEditor/commands/RetagInnerCommand";
import { RetagTextCommand } from "@editor/tools/pdfTextEditor/commands/RetagTextCommand";
import { SetInnerLanguageCommand } from "@editor/tools/pdfTextEditor/commands/SetInnerLanguageCommand";
@@ -26,8 +28,10 @@ import type {
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import {
innerTags,
+ sharedTextTag,
textTag,
type InnerTag,
+ type TextTag,
} from "@editor/tools/pdfTextEditor/util/textAccessibility";
/** The tags marking parts of the selected text, and the selection inside it. */
@@ -55,10 +59,11 @@ export interface TextLanguageControl {
}
/**
- * The tag of the selected text (null unless exactly one run and nothing else
- * is selected), the tags marking parts of it, and ways to change both. A
- * selection inside the text that is exactly one inner tag's text picks that
- * tag; any other is offered as new text to tag.
+ * The tag of the selected text, the one shared by every selected run (null
+ * unless only runs are selected), and a way to set it on all of them. For one
+ * run, also the tags marking parts of it and ways to change them: a selection
+ * inside the text that is exactly one inner tag's text picks that tag; any
+ * other is offered as new text to tag.
*/
export function useTextAccessibility(
store: EditorStore,
@@ -74,29 +79,39 @@ export function useTextAccessibility(
: null,
[store, state, selection],
);
- const { run, tag, inner, newTagTypes } = useMemo(() => {
+ const { run, targets, tag, inner, newTagTypes } = useMemo(() => {
const doc = store.document;
+ const ids = new Set(selection.runIds);
const selected =
ACCESSIBILITY_EDITING &&
- selection.runIds.length === 1 &&
selection.imageIds.length === 0 &&
selection.shapeIds.length === 0
- ? (state.pages
- .flatMap((page) => page.runs)
- .find((r) => r.id === selection.runIds[0]) ?? null)
- : null;
- if (!doc || !selected) {
- return { run: null, tag: null, inner: [], newTagTypes: null };
+ ? state.pages.flatMap((page) => page.runs).filter((r) => ids.has(r.id))
+ : [];
+ if (!doc || selected.length === 0) {
+ return {
+ run: null,
+ targets: [],
+ tag: null,
+ inner: [],
+ newTagTypes: null,
+ };
}
- const tags = innerTags(doc, selected);
+ const targets = selected.map((r) => ({ run: r, tag: textTag(doc, r) }));
+ const shared = sharedTextTag(targets.map((target) => target.tag));
+ const only = selected.length === 1 ? selected[0] : null;
+ if (!only) {
+ return { run: null, targets, tag: shared, inner: [], newTagTypes: null };
+ }
+ const tags = innerTags(doc, only);
const range = selection.textRange;
const picksTag = tags.some((t) => sameRange(t, range));
return {
- run: selected,
- tag: textTag(doc, selected),
+ run: only,
+ targets,
+ tag: shared,
inner: tags,
- newTagTypes:
- range && !picksTag ? tagTypesFor(doc, selected, range) : null,
+ newTagTypes: range && !picksTag ? tagTypesFor(doc, only, range) : null,
};
}, [store, state.pages, selection]);
@@ -105,29 +120,16 @@ export function useTextAccessibility(
[inner, selection.textRange],
);
- /** Retags the text's block, or gives untagged text an element of its own. */
+ /**
+ * Retags each selected run's block, or gives its untagged text an element of
+ * its own, as one undo step.
+ */
const setTag = useCallback(
(type: StructureType) => {
- if (!run || !tag) return;
- if (tag.kind === "tagged" && run.mcid !== undefined) {
- store.dispatch(
- new RetagTextCommand({
- pageIndex: run.pageIndex,
- mcid: run.mcid,
- type,
- }),
- );
- } else if (tag.kind === "untagged" && tag.taggable) {
- store.dispatch(
- new TagTextCommand({
- pageIndex: run.pageIndex,
- runId: run.id,
- as: type,
- }),
- );
- }
+ const command = setTextTagCommand(targets, type);
+ if (command) store.dispatch(command);
},
- [store, run, tag],
+ [store, targets],
);
/** Selects inner tag `index`'s text. */
@@ -290,6 +292,44 @@ function textLanguageTargets(
return targets.length > 0 && targets.length === ids.size ? targets : null;
}
+/**
+ * One undo step setting `type` on every run whose tag can be set; null when
+ * none can.
+ */
+export function setTextTagCommand(
+ targets: readonly { run: TextRunSnapshot; tag: TextTag }[],
+ type: StructureType,
+): Command | null {
+ const commands = targets.flatMap(({ run, tag }) => {
+ const command = runTagCommand(run, tag, type);
+ return command ? [command] : [];
+ });
+ if (commands.length <= 1) return commands[0] ?? null;
+ return new CompositeCommand(commands);
+}
+
+function runTagCommand(
+ run: TextRunSnapshot,
+ tag: TextTag,
+ type: StructureType,
+): Command | null {
+ if (tag.kind === "tagged" && run.mcid !== undefined) {
+ return new RetagTextCommand({
+ pageIndex: run.pageIndex,
+ mcid: run.mcid,
+ type,
+ });
+ }
+ if (tag.kind === "untagged" && tag.taggable) {
+ return new TagTextCommand({
+ pageIndex: run.pageIndex,
+ runId: run.id,
+ as: type,
+ });
+ }
+ return null;
+}
+
function sameRange(a: TextRange, b: TextRange | null): boolean {
return b !== null && a.start === b.start && a.end === b.end;
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts
index dee72a2e99..d67787b90c 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts
@@ -73,6 +73,7 @@ export class EditorDocument {
private documentLangEdit: string | null | undefined;
/** The file's own structure tree; null when only PDFium's view is available. */
private readonly fileStructure: FileStructure | null;
+ private marked: boolean;
private readonly ownedFonts: Map<string, FontRef>;
private _disposed: boolean;
// Form-fill environment. Widgets with no appearance stream are drawn ONLY by
@@ -94,6 +95,7 @@ export class EditorDocument {
this.openedBytes = openedBytes;
this.fileStructure = fileStructure;
this.fileDocumentLang = readCatalogLang(module, docPtr);
+ this.marked = fileStructure?.marked ?? false;
this.pageCache = new Map();
this.ownedFonts = new Map();
this._disposed = false;
@@ -111,9 +113,7 @@ export class EditorDocument {
// footprint; past a point the gradient repair is not worth that.
const keep = prepared.length <= MAX_RETAINED_BYTES ? prepared : EMPTY;
const fileStructure =
- keep.length > 0 && module.FPDFCatalog_IsTagged(docPtr)
- ? await readFileStructure(keep).catch(() => null)
- : null;
+ keep.length > 0 ? await readFileStructure(keep).catch(() => null) : null;
return new EditorDocument(module, docPtr, keep, fileStructure);
}
@@ -213,7 +213,7 @@ export class EditorDocument {
);
}
const page = this.fileStructure.pages.get(pageIndex);
- if (!page) return new PageStructure([]);
+ if (!page) return new PageStructure([], null, 0);
if (page.slotCount === null) return new PageStructure([], "unreadable");
return new PageStructure(page.elements, null, page.slotCount, (key) =>
this.retaggedAs(key),
@@ -433,8 +433,14 @@ export class EditorDocument {
}
}
- /** True when the catalog marks the file as tagged (ISO 32000-1 14.7.1). */
- isTagged(): boolean {
+ /**
+ * True when the catalog marks the file as tagged (ISO 32000-1 14.7.1), or
+ * the save can write tags into it, creating its structure tree if need be.
+ * Not a promise that tags can be edited: an encrypted tagged file is true
+ * here and read-only in its PageStructure, which decides that.
+ */
+ treatAsTagged(): boolean {
+ if (this.fileStructure) return true;
try {
return this.module.FPDFCatalog_IsTagged(this.docPtr);
} catch {
@@ -442,6 +448,41 @@ export class EditorDocument {
}
}
+ /**
+ * Whether the saved file declares itself tagged (/MarkInfo /Marked). Kept
+ * apart from the tags themselves so unfinished tags do not claim the file is
+ * tagged, which readers that honour the flag would then read by.
+ */
+ markedTagged(): boolean {
+ return this.marked;
+ }
+
+ /** False when the file cannot be parsed or is encrypted: the flag is fixed. */
+ canSetMarkedTagged(): boolean {
+ return this.fileStructure !== null;
+ }
+
+ /** Throws when canSetMarkedTagged() is false. */
+ setMarkedTagged(marked: boolean): void {
+ if (!this.canSetMarkedTagged()) {
+ throw new Error("this file's tagged flag can't be changed");
+ }
+ this.marked = marked;
+ }
+
+ /** True when the save must write /MarkInfo /Marked. */
+ markedTaggedChanged(): boolean {
+ return (
+ this.fileStructure !== null && this.marked !== this.fileStructure.marked
+ );
+ }
+
+ /** True when the saved file will have a structure tree, the file's own or one the save creates. */
+ hasStructureTree(): boolean {
+ if (this.fileStructure?.hasTree) return true;
+ return this.structureEdits().some((edit) => edit.newElement);
+ }
+
private encrypted(): boolean {
try {
// -1 when the file has no security handler.
@@ -493,9 +534,9 @@ export class EditorDocument {
}
/**
- * The page's added elements in reading order, so one placed after another
- * finds it already in the tree. An element whose content was deleted is
- * left out: there is nothing left for it to tag.
+ * The page's added elements, each after the added element it reads after,
+ * so it finds that already in the tree. An element whose content was
+ * deleted is left out: there is nothing left for it to tag.
*/
private addedElementEdits(
pageIndex: number,
@@ -506,22 +547,28 @@ export class EditorDocument {
structure.addedElements().map((element) => [element.mcid, element]),
);
if (!page || added.size === 0) return [];
- return taggedContentInReadingOrder(page).flatMap((content) => {
- const element = added.get(content.mcid);
- if (!element) return [];
- added.delete(content.mcid);
- const after = precedingTaggedMcid(page, content);
- return [
- {
- pageIndex,
- mcid: element.mcid,
- alt: element.alt,
- lang: element.lang,
- decorative: false,
- newElement: { type: element.type, after },
- },
- ];
- });
+ const content = taggedContentInReadingOrder(page);
+ const carried = new Set(content.map(({ mcid }) => mcid));
+ const edits = new Map<number, StructureEdit>();
+ for (const item of content) {
+ const element = added.get(item.mcid);
+ if (!element) continue;
+ added.delete(item.mcid);
+ const { follows } = element;
+ const after =
+ follows === null || (follows !== undefined && carried.has(follows))
+ ? follows
+ : precedingTaggedMcid(page, item);
+ edits.set(element.mcid, {
+ pageIndex,
+ mcid: element.mcid,
+ alt: element.alt,
+ lang: element.lang,
+ decorative: false,
+ newElement: { type: element.type, after },
+ });
+ }
+ return anchorsFirst(edits);
}
/**
@@ -713,3 +760,24 @@ function insertionPoint(
);
return next >= 0 ? next : blocks.length;
}
+
+/**
+ * `edits`, keyed by MCID, reordered so each comes after the edit adding the
+ * element it is placed after. A cycle is broken where it closes, that element
+ * placing as though its anchor were not added.
+ */
+function anchorsFirst(edits: Map<number, StructureEdit>): StructureEdit[] {
+ const ordered: StructureEdit[] = [];
+ for (const start of [...edits.keys()]) {
+ const chain: StructureEdit[] = [];
+ let mcid: number | null = start;
+ while (mcid !== null && edits.has(mcid)) {
+ const edit: StructureEdit = edits.get(mcid)!;
+ edits.delete(mcid);
+ chain.push(edit);
+ mcid = edit.newElement!.after;
+ }
+ ordered.push(...chain.reverse());
+ }
+ return ordered;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts
index 91c268151e..86b0b0dc87 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts
@@ -248,6 +248,11 @@ export interface AddedElement {
alt: string | null;
/** The /Lang to save; null for none. */
lang: string | null;
+ /**
+ * The MCID of the content it reads after, null for first, fixed when it was
+ * added. Absent when its place follows from where it sits on the page.
+ */
+ follows?: number | null;
}
/** A change to the /Lang of one of the file's elements marking part of a block's text. */
@@ -268,6 +273,8 @@ export class PageStructure {
private readonly byMcid = new Map<number, StructureElement>();
private readonly edits = new Map<StructureElement, StructureElementEdit>();
private readonly added = new Map<number, AddedStructureElement>();
+ /** AddedElement.follows, by the added element's MCID. */
+ private readonly follows = new Map<number, number | null>();
/** By the new element's MCID, in the order made: a later cut can take text from an earlier one. */
private readonly cuts = new Map<
number,
@@ -458,12 +465,17 @@ export class PageStructure {
return this.added.has(mcid);
}
- /** Give the content `mcid` marks a new element. Throws when an element already owns it. */
- addElement(mcid: number, type: StructureType): void {
+ /**
+ * Give the content `mcid` marks a new element, read after the content
+ * `follows` marks when given (see `AddedElement.follows`). Throws when an
+ * element already owns it.
+ */
+ addElement(mcid: number, type: StructureType, follows?: number | null): void {
if (this.byMcid.has(mcid)) {
throw new Error(`MCID ${mcid} already has an element`);
}
this.putAdded(mcid, type);
+ if (follows !== undefined) this.follows.set(mcid, follows);
}
/**
@@ -518,6 +530,7 @@ export class PageStructure {
const element = this.added.get(mcid);
if (!element && !this.cuts.has(mcid)) return;
this.added.delete(mcid);
+ this.follows.delete(mcid);
this.byMcid.delete(mcid);
this.langs.delete(addedKey(mcid));
if (element) this.edits.delete(element);
@@ -566,6 +579,18 @@ export class PageStructure {
return change === null ? null : { role: change, type: change };
}
+ /**
+ * True when `el` marks part of block `blockKey`'s text: an inline element in
+ * it, or text the session cut from it. The element of a neighbouring block
+ * whose text was grouped in is not.
+ */
+ marksPartOf(el: StructureElement, blockKey: string): boolean {
+ if (el.key === blockKey) return false;
+ const cut = this.cutMcid(el.key);
+ if (cut !== null) return this.cuts.get(cut)!.owner.block.key === blockKey;
+ return this.fileElements.has(el) && el.block.key === blockKey;
+ }
+
/** What element `key` can be changed to. Throws as innerType does. */
innerOptions(key: string): InnerOptions {
if (this.readOnly) return { types: [], removable: false };
@@ -668,12 +693,14 @@ export class PageStructure {
}
private addedElement(mcid: number): AddedElement {
- return {
+ const element: AddedElement = {
mcid,
type: this.added.get(mcid)!.type,
alt: this.alt(mcid),
lang: this.langs.get(addedKey(mcid)) ?? null,
};
+ if (this.follows.has(mcid)) element.follows = this.follows.get(mcid)!;
+ return element;
}
/**
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts
index 771a394c83..67d7376695 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts
@@ -17,6 +17,7 @@ import {
noteId,
} from "@editor/tools/pdfTextEditor/pdfdoc/passes/addElements";
import { cutElements } from "@editor/tools/pdfTextEditor/pdfdoc/passes/cutElements";
+import { ensureStructureTree } from "@editor/tools/pdfTextEditor/pdfdoc/passes/ensureStructureTree";
import { markDecorative } from "@editor/tools/pdfTextEditor/pdfdoc/passes/markDecorative";
import { unwrapElements } from "@editor/tools/pdfTextEditor/pdfdoc/passes/unwrapElements";
import { StructureNodes } from "@editor/tools/pdfTextEditor/pdfdoc/structureNodes";
@@ -78,6 +79,8 @@ export class StructureEditError extends Error {
/**
* Apply `edits` to `bytes`, all or none. Later edits to the same element win.
+ * An element added to a file or page with no structure yet first gets it one
+ * (ensureStructureTree), in a revision of its own.
* Throws StructureEditError when any edit cannot be written, including when
* the file cannot be extended at all.
*/
@@ -89,10 +92,19 @@ export async function applyStructureEdits(
const fail = (reason: string) =>
new StructureEditError(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");
+ if (opened.encrypted) throw fail("the file is encrypted");
+ // Only an added element can be the first on a page or in the file: every
+ // other edit addresses one the file already has.
+ const skeleton = ensureStructureTree(
+ opened,
+ edits.filter((edit) => edit.newElement).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 catalog = pdf.objectBody(pdf.rootNum);
const treeRoot = catalog ? pdf.dictRef(catalog, "StructTreeRoot") : null;
if (treeRoot === null) throw fail("the file has no structure tree");
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/ensureStructureTree.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/ensureStructureTree.ts
new file mode 100644
index 0000000000..425a605efd
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/ensureStructureTree.ts
@@ -0,0 +1,223 @@
+/**
+ * Give a file the structure the other passes write elements into, as an
+ * appended revision: a StructTreeRoot holding a Document element and an empty
+ * ParentTree when the file has none, and a /StructParents key with an empty
+ * ParentTree array on each page that lacks one.
+ */
+import {
+ arrayItems,
+ indirectRef,
+ setDictEntry,
+ type RawPdf,
+} from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import {
+ appendRevision,
+ plainObject,
+ unusedObjectNumber,
+} from "@editor/tools/pdfTextEditor/pdfdoc/revision";
+
+const MAX_TREE_DEPTH = 32;
+
+/**
+ * The file with a structure tree and a ParentTree array for each of
+ * `pageIndices`. Null when nothing needed adding, or when `pageIndices` is
+ * empty; a string saying why when the file cannot be given them.
+ */
+export function ensureStructureTree(
+ pdf: RawPdf,
+ pageIndices: Iterable<number>,
+): Uint8Array | string | null {
+ const catalog = pdf.objectBody(pdf.rootNum);
+ if (!catalog) return "the file's catalog cannot be read";
+ const hasTree = pdf.valueSpan(catalog, "StructTreeRoot") !== null;
+ const pages = pagesToKey(pdf, pageIndices, hasTree);
+ if (typeof pages === "string") return pages;
+ if (pages.length === 0) return null;
+
+ const bodies = new Map<number, string>();
+ const allocate = (body: string): number => {
+ const num = unusedObjectNumber(pdf, bodies);
+ bodies.set(num, body);
+ return num;
+ };
+
+ let treeRoot = pdf.dictRef(catalog, "StructTreeRoot");
+ if (treeRoot === null) {
+ if (pdf.valueSpan(catalog, "StructTreeRoot")) {
+ return "the file's structure tree is not an indirect object";
+ }
+ // Reserved, then written once the Document's number is known.
+ treeRoot = allocate("");
+ const documentNum = allocate(
+ `<< /Type /StructElem /S /Document /P ${treeRoot} 0 R /K [] >>`,
+ );
+ bodies.set(
+ treeRoot,
+ `<< /Type /StructTreeRoot /K ${documentNum} 0 R /ParentTree << /Nums [] >> /ParentTreeNextKey 0 >>`,
+ );
+ }
+ const rootBody = bodies.get(treeRoot) ?? pdf.objectBody(treeRoot);
+ if (!rootBody) return "the file's structure tree cannot be read";
+
+ let nextKey = firstFreeKey(pdf, rootBody);
+ if (nextKey === null) return "the ParentTree cannot be read";
+ const entries: string[] = [];
+ for (const pageNum of pages) {
+ const key = nextKey++;
+ const page = setDictEntry(
+ pdf.objectBody(pageNum)!,
+ "StructParents",
+ String(key),
+ );
+ if (!page) return "a page cannot be given /StructParents";
+ bodies.set(pageNum, page);
+ entries.push(`${key} ${allocate("[]")} 0 R`);
+ }
+
+ const extended = addTreeEntries(pdf, rootBody, entries, bodies, allocate);
+ if (!extended) return "the ParentTree cannot be extended";
+ const root = setDictEntry(extended, "ParentTreeNextKey", String(nextKey));
+ if (!root) return "the file's structure tree cannot be read";
+ bodies.set(treeRoot, root);
+
+ // /MarkInfo is left alone: a file declares itself tagged only when the
+ // user says its tags are finished (markTagged).
+ const named = setDictEntry(
+ catalog,
+ "StructTreeRoot",
+ indirectRef(pdf, treeRoot),
+ );
+ if (!named) return "the file's catalog cannot be read";
+ bodies.set(pdf.rootNum, named);
+
+ const out = appendRevision(
+ pdf,
+ [...bodies].map(([num, body]) => ({ num, body: plainObject(body) })),
+ );
+ return out ?? "the file's cross-reference structure cannot be extended";
+}
+
+/**
+ * The page objects among `pageIndices` that need a ParentTree key, in order:
+ * those with no /StructParents, or every one when the file has no tree for
+ * a key to name.
+ */
+function pagesToKey(
+ pdf: RawPdf,
+ pageIndices: Iterable<number>,
+ hasTree: boolean,
+): number[] | string {
+ const pages: number[] = [];
+ for (const pageIndex of new Set(pageIndices)) {
+ const pageNum = pdf.pageNumberAt(pageIndex);
+ const page = pageNum === null ? null : pdf.objectBody(pageNum);
+ if (pageNum === null || !page) return "no such page";
+ if (!hasTree || !pdf.valueSpan(page, "StructParents")) pages.push(pageNum);
+ }
+ return pages.sort((a, b) => a - b);
+}
+
+/**
+ * A ParentTree key above every one in use: by the tree itself, by a page's
+ * /StructParents or by the root's /ParentTreeNextKey. Null when the tree
+ * cannot be walked.
+ */
+function firstFreeKey(pdf: RawPdf, rootBody: string): number | null {
+ const tree = pdf.resolve(rootBody, "ParentTree");
+ const keys = tree === null ? [] : treeKeys(pdf, tree, new Set(), 0);
+ if (!keys) return null;
+ for (const pageNum of pdf.pageNumbers()) {
+ const page = pdf.objectBody(pageNum);
+ const key = page ? pdf.dictInt(page, "StructParents") : null;
+ if (key !== null) keys.push(key);
+ }
+ return Math.max(
+ pdf.dictInt(rootBody, "ParentTreeNextKey") ?? 0,
+ ...keys.map((key) => key + 1),
+ );
+}
+
+function treeKeys(
+ pdf: RawPdf,
+ node: string,
+ seen: Set<number>,
+ depth: number,
+): number[] | null {
+ if (depth > MAX_TREE_DEPTH) return null;
+ const keys: number[] = [];
+ const nums = pdf.resolve(node, "Nums");
+ const pairs = nums === null ? [] : arrayItems(nums.trim());
+ if (!pairs) return null;
+ for (let i = 0; i < pairs.length; i += 2) {
+ const key = Number(pairs[i].text);
+ if (Number.isInteger(key)) keys.push(key);
+ }
+ const kids = pdf.resolve(node, "Kids");
+ for (const m of kids?.matchAll(/(\d+)\s+\d+\s+R/g) ?? []) {
+ const num = parseInt(m[1], 10);
+ if (seen.has(num)) return null;
+ seen.add(num);
+ const kid = pdf.objectBody(num);
+ const below = kid ? treeKeys(pdf, kid, seen, depth + 1) : null;
+ if (!below) return null;
+ keys.push(...below);
+ }
+ return keys;
+}
+
+/**
+ * The root's body with `entries` (`key value` pairs, keys above every key in
+ * the tree) added to its ParentTree. An indirect tree node is written to
+ * `bodies`. Null when the tree is not one this can extend.
+ */
+function addTreeEntries(
+ pdf: RawPdf,
+ rootBody: string,
+ entries: readonly string[],
+ bodies: Map<number, string>,
+ allocate: (body: string) => number,
+): string | null {
+ const span = pdf.valueSpan(rootBody, "ParentTree");
+ if (!span) {
+ return setDictEntry(
+ rootBody,
+ "ParentTree",
+ `<< /Nums [${entries.join(" ")}] >>`,
+ );
+ }
+ const nodeNum = pdf.dictRef(rootBody, "ParentTree");
+ const node = nodeNum === null ? span.text : pdf.objectBody(nodeNum);
+ const extended = node ? withEntries(pdf, node, entries, allocate) : null;
+ if (!extended) return null;
+ if (nodeNum === null) return setDictEntry(rootBody, "ParentTree", extended);
+ bodies.set(nodeNum, extended);
+ return rootBody;
+}
+
+/**
+ * The tree node with `entries` added: to its /Nums when it holds them, else
+ * as a new leaf at the end of its /Kids, which keeps the keys in order.
+ */
+function withEntries(
+ pdf: RawPdf,
+ node: string,
+ entries: readonly string[],
+ allocate: (body: string) => number,
+): string | null {
+ const kids = pdf.valueSpan(node, "Kids");
+ if (!kids) {
+ const nums = pdf.valueSpan(node, "Nums");
+ const items = nums ? arrayItems(nums.text) : [];
+ if (!items) return null;
+ const all = [...items.map((item) => item.text), ...entries];
+ return setDictEntry(node, "Nums", `[${all.join(" ")}]`);
+ }
+ const items = arrayItems(kids.text);
+ if (!items) return null;
+ const keys = entries.map((entry) => entry.split(" ")[0]);
+ const leaf = allocate(
+ `<< /Limits [${keys[0]} ${keys.at(-1)}] /Nums [${entries.join(" ")}] >>`,
+ );
+ const all = [...items.map((item) => item.text), `${leaf} 0 R`];
+ return setDictEntry(node, "Kids", `[${all.join(" ")}]`);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/markTagged.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/markTagged.ts
new file mode 100644
index 0000000000..f9eb4bb129
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/markTagged.ts
@@ -0,0 +1,76 @@
+/**
+ * Read and write the catalog's /MarkInfo /Marked: whether the file declares
+ * itself a tagged PDF (ISO 32000-1 14.7.1). Kept apart from writing the tree,
+ * because a file can hold tags that are not finished yet.
+ */
+import { RawPdf, setDictEntry } from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import {
+ appendRevision,
+ plainObject,
+} from "@editor/tools/pdfTextEditor/pdfdoc/revision";
+
+/** Thrown when the file's /MarkInfo cannot be written. */
+export class MarkInfoError extends Error {
+ constructor(reason: string) {
+ super(`Could not set /MarkInfo /Marked: ${reason}`);
+ this.name = "MarkInfoError";
+ }
+}
+
+/** The catalog's /MarkInfo /Marked; false when absent or unreadable. */
+export function isMarked(pdf: RawPdf, catalog: string): boolean {
+ const infoNum = pdf.dictRef(catalog, "MarkInfo");
+ const info =
+ infoNum !== null
+ ? pdf.objectBody(infoNum)
+ : (pdf.valueSpan(catalog, "MarkInfo")?.text ?? null);
+ return !!info && pdf.valueSpan(info, "Marked")?.text === "true";
+}
+
+/**
+ * `bytes` with /MarkInfo /Marked set to `marked`, as an appended revision;
+ * `bytes` itself when the file already says so. Throws MarkInfoError when the
+ * catalog cannot be read or changed.
+ */
+export async function applyMarked(
+ bytes: Uint8Array,
+ marked: boolean,
+): Promise<Uint8Array> {
+ const pdf = await RawPdf.parse(bytes);
+ if (!pdf) throw new MarkInfoError("the file could not be read");
+ const catalog = pdf.objectBody(pdf.rootNum);
+ if (!catalog) throw new MarkInfoError("the file's catalog cannot be read");
+ if (isMarked(pdf, catalog) === marked) return bytes;
+
+ const value = marked ? "true" : "false";
+ const objects: { num: number; body: string }[] = [];
+ const infoNum = pdf.dictRef(catalog, "MarkInfo");
+ if (infoNum !== null) {
+ const info = pdf.objectBody(infoNum);
+ const updated = info ? setDictEntry(info, "Marked", value) : null;
+ if (!updated)
+ throw new MarkInfoError("the file's /MarkInfo cannot be read");
+ objects.push({ num: infoNum, body: updated });
+ } else {
+ const info = pdf.valueSpan(catalog, "MarkInfo")?.text;
+ const updatedInfo = info
+ ? setDictEntry(info, "Marked", value)
+ : `<< /Marked ${value} >>`;
+ const updated = updatedInfo
+ ? setDictEntry(catalog, "MarkInfo", updatedInfo)
+ : null;
+ if (!updated)
+ throw new MarkInfoError("the file's catalog cannot be changed");
+ objects.push({ num: pdf.rootNum, body: updated });
+ }
+ const out = appendRevision(
+ pdf,
+ objects.map(({ num, body }) => ({ num, body: plainObject(body) })),
+ );
+ if (!out) {
+ throw new MarkInfoError(
+ "the file's cross-reference structure cannot be extended",
+ );
+ }
+ return out;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
index 14e5e1f05f..76d8266b2f 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
@@ -13,6 +13,7 @@ import {
type ElementNode,
} from "@editor/tools/pdfTextEditor/pdfdoc/structureNodes";
import { decodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString";
+import { isMarked } from "@editor/tools/pdfTextEditor/pdfdoc/passes/markTagged";
type ElementInfo = Omit<StructureElement, "mcids">;
@@ -45,7 +46,8 @@ export interface FileStructure {
/**
* Every page with /StructParents, keyed by page index, its elements each
* listing only the MCIDs the page's ParentTree slots give it: the lookup
- * the save addresses edits by. PDFium lists an element's MCIDs from every
+ * the save addresses edits by. A page without one has no elements yet, and
+ * the save gives it a ParentTree array. PDFium lists an element's MCIDs from every
* page with no page attached, so an element spanning a page break would
* claim another element's MCID there.
*/
@@ -54,11 +56,16 @@ export interface FileStructure {
blocks: FileBlock[];
/** By element key, for every element a page or block names. */
languages: Map<string, ElementLanguage>;
+ /** Whether the file has a /StructTreeRoot at all. */
+ hasTree: boolean;
+ /** Whether the catalog declares the file tagged (/MarkInfo /Marked). */
+ marked: boolean;
}
/**
- * The file's structure tree. Null when the file is untagged, cannot be
- * parsed, or is encrypted, whose strings would read as ciphertext.
+ * The file's structure tree, empty when it has none: the save creates one
+ * for the first element added. Null when the file cannot be parsed, or is
+ * encrypted, whose strings would read as ciphertext.
*/
export async function readFileStructure(
bytes: Uint8Array,
@@ -66,9 +73,21 @@ export async function readFileStructure(
const pdf = await RawPdf.parse(bytes);
if (!pdf || pdf.encrypted) return null;
const catalog = pdf.objectBody(pdf.rootNum);
- const treeRoot = catalog ? pdf.dictRef(catalog, "StructTreeRoot") : null;
- const rootBody = treeRoot === null ? null : pdf.objectBody(treeRoot);
- if (treeRoot === null || !rootBody) return null;
+ if (!catalog) return null;
+ const treeRoot = pdf.dictRef(catalog, "StructTreeRoot");
+ if (treeRoot === null) {
+ return pdf.valueSpan(catalog, "StructTreeRoot")
+ ? null
+ : {
+ pages: new Map(),
+ blocks: [],
+ languages: new Map(),
+ hasTree: false,
+ marked: isMarked(pdf, catalog),
+ };
+ }
+ const rootBody = pdf.objectBody(treeRoot);
+ if (!rootBody) return null;
const nodes = new StructureNodes(pdf, rootBody);
const nodeFor = (num: number) => nodes.node(num);
@@ -84,8 +103,12 @@ export async function readFileStructure(
const byPage = new Map<number, FilePageStructure>();
pdf.pageNumbers().forEach((pageNum, pageIndex) => {
const page = pdf.objectBody(pageNum);
- const key = page ? pdf.dictInt(page, "StructParents") : null;
- if (key === null) return;
+ if (!page || !pdf.valueSpan(page, "StructParents")) return;
+ const key = pdf.dictInt(page, "StructParents");
+ if (key === null) {
+ byPage.set(pageIndex, { elements: [], slotCount: null });
+ return;
+ }
const items = pdf.parentTreeArray(treeRoot, key)?.items;
if (!items) {
byPage.set(pageIndex, { elements: [], slotCount: null });
@@ -114,7 +137,13 @@ export async function readFileStructure(
parent: parent === null ? null : String(parent),
});
}
- return { pages: byPage, blocks, languages };
+ return {
+ pages: byPage,
+ blocks,
+ languages,
+ hasTree: true,
+ marked: isMarked(pdf, catalog),
+ };
}
/** Block elements in the depth-first /K order a reader follows. */
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts b/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts
index 2705561eb4..615e286a5e 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts
@@ -405,6 +405,14 @@ export class EditorStore {
this.resnapshot();
}
+ /** Record a command the caller already applied as one undo step, re-snapshot, and notify. */
+ recordApplied(cmd: Command): void {
+ if (!this.doc) return;
+ this.history.record(cmd);
+ this.resnapshot();
+ this.patch({ dirty: this.isDirty() });
+ }
+
/** Apply a command via the history stack, re-snapshot, and notify. */
dispatch(cmd: Command): void {
if (!this.doc) return;
@@ -499,8 +507,10 @@ export class EditorStore {
});
}
+ // Ignored while loading: a long operation is mid-way through the document,
+ // and an undo would revert under it.
undo(): void {
- if (!this.doc) return;
+ if (!this.doc || this.state.loading) return;
try {
this.history.undo(this.doc);
} catch (err) {
@@ -512,7 +522,7 @@ export class EditorStore {
}
redo(): void {
- if (!this.doc) return;
+ if (!this.doc || this.state.loading) return;
try {
this.history.redo(this.doc);
} catch (err) {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/store/HistoryStack.ts b/frontend/src/editor/core/tools/pdfTextEditor/store/HistoryStack.ts
index bef3cb6166..ffee29fc36 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/store/HistoryStack.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/store/HistoryStack.ts
@@ -101,6 +101,14 @@ export class HistoryStack {
this.redoStack.length = 0;
}
+ /** Push a command the caller already applied, as its own undo step. */
+ record(cmd: Command): void {
+ this.undoStack.push(cmd);
+ if (this.undoStack.length > this.limit) this.undoStack.shift();
+ this.lastCoalesceKey = null;
+ this.redoStack.length = 0;
+ }
+
undo(doc: EditorDocument): Command | null {
const cmd = this.undoStack.pop();
if (!cmd) return null;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts
index da82de76d7..0b8b462d2f 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts
@@ -4,6 +4,10 @@ import {
StructureEditError,
applyStructureEdits,
} from "@editor/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits";
+import {
+ MarkInfoError,
+ applyMarked,
+} from "@editor/tools/pdfTextEditor/pdfdoc/passes/markTagged";
import { repairStructure } from "@editor/tools/pdfTextEditor/pdfdoc/passes/repairStructure";
import { setDocumentLanguage } from "@editor/tools/pdfTextEditor/pdfdoc/passes/setDocumentLanguage";
import { preserveShadings } from "@editor/tools/pdfTextEditor/pdfdoc/passes/preserveShadings";
@@ -32,7 +36,11 @@ export async function exportToBlob(
// starting from what we opened keeps the file byte-identical. Rewriting it
// changed the bytes of 8 of this suite's 10 fixtures and inflated the small
// ones by up to 35% - for no edit at all.
- if (structureEdits.length === 0 && documentLanguage === undefined) {
+ if (
+ structureEdits.length === 0 &&
+ documentLanguage === undefined &&
+ !doc.markedTaggedChanged()
+ ) {
return {
blob: pdfBlob(doc.openedBytes),
filename: exportName(sourceName),
@@ -58,6 +66,14 @@ export async function exportToBlob(
throw accessibilitySaveFailed(err);
}
}
+ if (doc.markedTaggedChanged()) {
+ try {
+ bytes = await applyMarked(bytes, doc.markedTagged());
+ } catch (err) {
+ if (!(err instanceof MarkInfoError)) throw err;
+ throw accessibilitySaveFailed(err);
+ }
+ }
// After the edits: when the content an element described was deleted, the
// repair removes the ParentTree slot an edit to that element is addressed by,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/imageAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/imageAccessibility.ts
index 8278f8bbf9..25821e0400 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/imageAccessibility.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/imageAccessibility.ts
@@ -55,15 +55,15 @@ export type RetaggableTag =
/**
* The image's tag when TagImageCommand can change it: an image the page
- * itself draws in a tagged document, that is untagged, an artifact, or a
- * figure the session added. Null otherwise, for content the file's elements
+ * itself draws, whose save can add an element, that is untagged, an
+ * artifact, or a figure the session added. Null otherwise, for content the file's elements
* own among the rest.
*/
export function retaggableTag(
doc: EditorDocument,
image: ImageObjectSnapshot,
): RetaggableTag | null {
- if (!doc.isTagged() || image.inForm) return null;
+ if (image.inForm) return null;
const structure = doc.structure(image.pageIndex);
if (structure.cannotAddElement()) return null;
if (image.mcid === undefined) {
@@ -81,7 +81,7 @@ function blocked(
doc: EditorDocument,
blocker: DescriptionBlocker,
): ImageAccessibility {
- return { kind: "blocked", blocker, documentTagged: doc.isTagged() };
+ return { kind: "blocked", blocker, documentTagged: doc.treatAsTagged() };
}
/**
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.ts
index 4a6a816a0c..cb47f9a615 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.ts
@@ -22,14 +22,16 @@ export type TextTag =
/** `taggable` when TagTextCommand can give the text an element. */
| { kind: "untagged"; documentTagged: boolean; taggable: boolean }
/** Drawn by a form XObject, whose marks the editor does not read. */
- | { kind: "unknown" };
+ | { kind: "unknown" }
+ /** Several runs' text, not all tagged alike; `settable` when every run's tag can be set. */
+ | { kind: "mixed"; settable: boolean };
export function textTag(doc: EditorDocument, run: TextRunSnapshot): TextTag {
if (run.inForm) return { kind: "unknown" };
if (run.artifact) return { kind: "artifact" };
const untagged = {
kind: "untagged",
- documentTagged: doc.isTagged(),
+ documentTagged: doc.treatAsTagged(),
taggable: canTagText(doc, run),
} as const;
if (run.mcid === undefined) return untagged;
@@ -43,14 +45,60 @@ export function textTag(doc: EditorDocument, run: TextRunSnapshot): TextTag {
};
}
+/** True when the tag picker can set the text's tag: retag it, or tag it. */
+export function canSetTextTag(tag: TextTag): boolean {
+ switch (tag.kind) {
+ case "tagged":
+ return tag.cannotRetag === null;
+ case "untagged":
+ return tag.taggable;
+ case "mixed":
+ return tag.settable;
+ default:
+ return false;
+ }
+}
+
+/**
+ * How several runs' text is tagged together: the tag they share, or mixed.
+ * Shared, it is settable only when every run's is.
+ */
+export function sharedTextTag(tags: readonly TextTag[]): TextTag {
+ const [first, ...rest] = tags;
+ const settable = tags.every(canSetTextTag);
+ if (!rest.every((tag) => sameTagShown(first, tag))) {
+ return { kind: "mixed", settable };
+ }
+ switch (first.kind) {
+ case "tagged":
+ return settable
+ ? { ...first, cannotRetag: null }
+ : (tags.find((tag) => tag.kind === "tagged" && tag.cannotRetag) ??
+ first);
+ case "untagged":
+ return { ...first, taggable: settable };
+ default:
+ return first;
+ }
+}
+
+function sameTagShown(a: TextTag, b: TextTag): boolean {
+ if (a.kind === "tagged" && b.kind === "tagged") {
+ return a.block.role === b.block.role;
+ }
+ if (a.kind === "untagged" && b.kind === "untagged") {
+ return a.documentTagged === b.documentTagged;
+ }
+ return a.kind === b.kind;
+}
+
/**
* True when the run's text can be given an element of its own: it is drawn
- * by the page itself in a tagged document whose save can add one, and has no
- * tag or artifact mark.
+ * by the page itself, whose save can add one, and has no tag or artifact
+ * mark.
*/
export function canTagText(doc: EditorDocument, run: TextRunSnapshot): boolean {
return (
- doc.isTagged() &&
!run.inForm &&
!run.artifact &&
run.mcid === undefined &&
@@ -83,8 +131,8 @@ export function innerTags(
if (!block) return [];
return elementStretches(doc, run.pageIndex, run.id).flatMap(
({ start, end, element }) => {
- const role =
- element.key === block.key ? null : structure.innerType(element.key);
+ if (!structure.marksPartOf(element, block.key)) return [];
+ const role = structure.innerType(element.key);
if (!role) return [];
const options = structure.innerOptions(element.key);
const text = run.text.slice(start, end);