Skip to content

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

Add support for accessibility tagging of links in Text Editor (#8868)

James Brunton01da4d96a0a2
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index 8c019fb56d..5529268bf8 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -7314,6 +7314,7 @@ mergeRuns_one = "Merge {{count}} run into a paragraph"
mergeRuns_other = "Merge {{count}} runs into a paragraph"
setColour = "Set colour on {{run}}"
setOutline = "Set outline on {{run}}"
+tagLink = "Tag link"
tagPageContent = "Auto-tag page"
typeInto = "Type into {{run}}"
ungroupParagraph = "Ungroup paragraph {{run}}"
@@ -7474,8 +7475,10 @@ applyToOtherPages_other = "Apply to {{count}} other pages"
artifactGroup = "Skipped by screen readers"
artifactText = "Decorative"
cannotChange = "This image's accessibility can't be changed."
+cannotDescribeLink = "This link's description can't be changed."
cannotRetag = "This text's tag can't be changed."
cannotSetDecorative = "This can't be marked or unmarked as decorative."
+cannotTagLink = "This link can't be tagged."
cannotTagPage = "This page's content can't be tagged."
contentGroup = "Content"
customTag = "{{role}} (custom tag)"
@@ -7487,6 +7490,7 @@ encrypted = "Tags can't be edited in an encrypted file"
heading = "Accessibility"
innerTagLabel = "Tag {{number}}"
innerTags = "Tags in this text"
+linkDescription = "Link description"
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."
@@ -7501,6 +7505,8 @@ saveFailed = "Your accessibility changes couldn't be saved, so the file wasn't s
selectedText = "Selected text"
tagging = "Tagging pages"
tagLabel = "Tag"
+tagLinks_one = "Tag link"
+tagLinks_other = "Tag {{count}} links"
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"
diff --git a/frontend/src/editor/core/tests/test-fixtures/generate-tagged-sample.mts b/frontend/src/editor/core/tests/test-fixtures/generate-tagged-sample.mts
index cea6b0ac41..cd5b878253 100644
--- a/frontend/src/editor/core/tests/test-fixtures/generate-tagged-sample.mts
+++ b/frontend/src/editor/core/tests/test-fixtures/generate-tagged-sample.mts
@@ -9,13 +9,17 @@ import process from "node:process";
// Page 2 has text in each tag the text editor shows: H2, H3 and a deliberately
// skipped H5, paragraphs holding an inline Link, Quote and Span, a list with
// Lbl and LBody, a Code block, a Note, a custom role the RoleMap leaves
-// unmapped, a header artifact, and one line of untagged text.
+// unmapped, a header artifact, and one line of untagged text. Its two link
+// annotations are one the Link holds through an OBJR, with /Contents, and one
+// over "Atlas" that no element holds and that has no /Contents.
//
// Run with: npx tsx generate-tagged-sample.mts
import { writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import {
+ PDFArray,
+ PDFDict,
PDFDocument,
PDFName,
PDFNumber,
@@ -71,8 +75,11 @@ function show(font: Font, size: number, x: number, y: number, text: string) {
return `BT /${font.name} ${size} Tf ${x.toFixed(2)} ${y} Td ${encoded} Tj ET`;
}
-/** One kid of a structure element: an MCID on its page, or a child element. */
-type Kid = number | PDFRef;
+/**
+ * One kid of a structure element: an MCID on its page, a child element, or an
+ * OBJR naming an annotation.
+ */
+type Kid = number | PDFRef | PDFDict;
interface PendingElement {
ref: PDFRef;
@@ -94,6 +101,8 @@ class StructureBuilder {
private readonly byRef = new Map<PDFRef, PendingElement>();
/** Per page, in StructParents order: the element owning each MCID. */
private readonly owners: PDFRef[][] = [];
+ /** Annotations elements hold, keyed in the ParentTree after every page. */
+ private readonly held: { annotation: PDFRef; owner: PDFRef }[] = [];
constructor(private readonly ctx: PDFContext) {
this.rootRef = ctx.nextRef();
@@ -149,6 +158,14 @@ class StructureBuilder {
});
}
+ /** Make `owner` hold `annotation`, which `page` lists in its /Annots. */
+ holdAnnotation(owner: PDFRef, page: PDFPage, annotation: PDFRef): void {
+ const el = this.byRef.get(owner)!;
+ this.attach(el);
+ el.kids.push(this.ctx.obj({ Type: "OBJR", Obj: annotation, Pg: page.ref }));
+ this.held.push({ annotation, owner });
+ }
+
finish(topLevel: PDFRef): void {
const ctx = this.ctx;
for (const el of this.elements) {
@@ -168,13 +185,20 @@ class StructureBuilder {
this.owners.forEach((owners, key) => {
nums.push(PDFNumber.of(key), ctx.obj(owners));
});
+ this.held.forEach(({ annotation, owner }, i) => {
+ const key = this.owners.length + i;
+ ctx
+ .lookup(annotation, PDFDict)
+ .set(PDFName.of("StructParent"), PDFNumber.of(key));
+ nums.push(PDFNumber.of(key), owner);
+ });
ctx.assign(
this.rootRef,
ctx.obj({
Type: "StructTreeRoot",
K: topLevel,
ParentTree: ctx.register(ctx.obj({ Nums: nums })),
- ParentTreeNextKey: this.owners.length,
+ ParentTreeNextKey: this.owners.length + this.held.length,
}),
);
}
@@ -199,21 +223,24 @@ class TaggedContent {
/**
* One line of pieces set side by side from `x`, each its own sequence: how
- * an inline element sits inside its paragraph's line.
+ * an inline element sits inside its paragraph's line. Returns where each
+ * piece starts and ends.
*/
line(
x: number,
y: number,
size: number,
pieces: { tag: string; owner: PDFRef; font: Font; text: string }[],
- ): void {
+ ): { left: number; right: number }[] {
let at = x;
- for (const piece of pieces) {
+ return pieces.map((piece) => {
this.mark(piece.tag, piece.owner, [
show(piece.font, size, at, y, piece.text),
]);
+ const left = at;
at += piece.font.pdf.widthOfTextAtSize(piece.text, size);
- }
+ return { left, right: at };
+ });
}
artifact(properties: string, ops: string[]): void {
@@ -233,6 +260,46 @@ class TaggedContent {
}
}
+/**
+ * A link annotation over `left`..`right` of the line set at baseline `y` in
+ * `size` pt, added to the page's /Annots.
+ */
+function addLink(
+ ctx: PDFContext,
+ page: PDFPage,
+ span: { left: number; right: number; y: number; size: number },
+ extra: Record<string, PDFObject>,
+): PDFRef {
+ const { left, right, y, size } = span;
+ const annotation = ctx.register(
+ ctx.obj({
+ Type: "Annot",
+ Subtype: "Link",
+ Rect: [left, y - 3, right, y + size - 2],
+ Border: [0, 0, 0],
+ P: page.ref,
+ ...extra,
+ }),
+ );
+ const annots = page.node.lookupMaybe(PDFName.of("Annots"), PDFArray);
+ if (annots) annots.push(annotation);
+ else page.node.set(PDFName.of("Annots"), ctx.obj([annotation]));
+ return annotation;
+}
+
+/** Where `word` sits in `text` set at `x` in `font` at `size` pt. */
+function wordSpan(
+ font: Font,
+ size: number,
+ x: number,
+ text: string,
+ word: string,
+): { left: number; right: number } {
+ const left =
+ x + font.pdf.widthOfTextAtSize(text.slice(0, text.indexOf(word)), size);
+ return { left, right: left + font.pdf.widthOfTextAtSize(word, size) };
+}
+
async function main() {
const doc = await PDFDocument.create();
const ctx = doc.context;
@@ -321,7 +388,7 @@ async function main() {
),
]);
const appendixLink = tree.element("Link", intro, second);
- two.line(72, 656, 12, [
+ const [, appendix] = two.line(72, 656, 12, [
{ tag: "P", owner: intro, font: regular, text: "are in the " },
{ tag: "Link", owner: appendixLink, font: regular, text: "appendix" },
{
@@ -333,6 +400,7 @@ async function main() {
]);
block("H3", bold, 16, 620, "North America");
+ const atlasLine = "and the launch of the Atlas product line in Canada.";
two.mark("P", el("P"), [
show(
regular,
@@ -341,13 +409,7 @@ async function main() {
598,
"Revenue rose 18% to $4.2 million, driven by enterprise renewals",
),
- show(
- regular,
- 12,
- 72,
- 582,
- "and the launch of the Atlas product line in Canada.",
- ),
+ show(regular, 12, 72, 582, atlasLine),
]);
block("H3", bold, 16, 548, "Europe");
@@ -463,6 +525,31 @@ async function main() {
two.artifact("/Type /Pagination", [show(regular, 10, 300, 40, "Page 2")]);
two.writeTo(ctx, second);
+ // Made after the page's content and elements, so their object numbers do
+ // not move.
+ tree.holdAnnotation(
+ appendixLink,
+ second,
+ addLink(
+ ctx,
+ second,
+ { ...appendix, y: 656, size: 12 },
+ {
+ Contents: PDFString.of("Appendix: method"),
+ Dest: ctx.obj([second.ref, "XYZ", 72, 330, 0]),
+ },
+ ),
+ );
+ addLink(
+ ctx,
+ second,
+ { ...wordSpan(regular, 12, 72, atlasLine, "Atlas"), y: 582, size: 12 },
+ {
+ A: ctx.obj({ S: "URI", URI: PDFString.of("https://example.com/atlas") }),
+ },
+ );
+ second.node.set(PDFName.of("Tabs"), PDFName.of("S"));
+
tree.finish(document);
doc.catalog.set(PDFName.of("StructTreeRoot"), tree.rootRef);
diff --git a/frontend/src/editor/core/tests/test-fixtures/tagged-sample.pdf b/frontend/src/editor/core/tests/test-fixtures/tagged-sample.pdf
index c50eeefab8..37693fb659 100644
Binary files a/frontend/src/editor/core/tests/test-fixtures/tagged-sample.pdf and b/frontend/src/editor/core/tests/test-fixtures/tagged-sample.pdf differ
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyAnnotationEdits.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyAnnotationEdits.test.ts
new file mode 100644
index 0000000000..ee03ded83b
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyAnnotationEdits.test.ts
@@ -0,0 +1,251 @@
+// @vitest-environment node
+import { describe, expect, test } from "vitest";
+import {
+ AnnotationEditError,
+ applyAnnotationEdits,
+ type AnnotationEdit,
+} from "@editor/tools/pdfTextEditor/pdfdoc/passes/applyAnnotationEdits";
+import { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import { readFileStructure } from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";
+import { decodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString";
+import {
+ buildClassicPdf,
+ streamBody,
+ type FixtureObject,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+// One page: a paragraph (10) holding MCID 0 and a Link (11) holding MCID 1,
+// over two link annotations (20, 21). Object 22 is a dictionary the page does
+// not list as an annotation.
+function objects(
+ overrides: Record<number, string> = {},
+ extra: FixtureObject[] = [],
+): FixtureObject[] {
+ const base: FixtureObject[] = [
+ {
+ num: 1,
+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 7 0 R >>",
+ },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 5 0 R /StructParents 0 /Annots [20 0 R 21 0 R] >>",
+ },
+ {
+ num: 5,
+ body: streamBody(
+ "",
+ "/P <</MCID 0>> BDC 0 0 10 10 re f EMC /Link <</MCID 1>> BDC 20 0 10 10 re f EMC",
+ ),
+ },
+ {
+ num: 7,
+ body: "<< /Type /StructTreeRoot /K 9 0 R /ParentTree << /Nums [0 [10 0 R 11 0 R]] >> /ParentTreeNextKey 1 >>",
+ },
+ {
+ num: 9,
+ body: "<< /Type /StructElem /S /Document /P 7 0 R /K [10 0 R] >>",
+ },
+ {
+ num: 10,
+ body: "<< /Type /StructElem /S /P /P 9 0 R /Pg 3 0 R /K [0 11 0 R] >>",
+ },
+ {
+ num: 11,
+ body: "<< /Type /StructElem /S /Link /P 10 0 R /Pg 3 0 R /K 1 >>",
+ },
+ {
+ num: 20,
+ body: "<< /Type /Annot /Subtype /Link /Rect [20 0 30 10] /A << /S /URI /URI (https://example.com) >> >>",
+ },
+ {
+ num: 21,
+ body: "<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /A << /S /URI /URI (https://example.org) >> >>",
+ },
+ { num: 22, body: "<< /Subtype /Link >>" },
+ ];
+ return [
+ ...base.map((o) =>
+ o.num in overrides ? { ...o, body: overrides[o.num] } : o,
+ ),
+ ...extra,
+ ];
+}
+
+const LINK_TO_ELEMENT: AnnotationEdit = {
+ pageIndex: 0,
+ annotation: 20,
+ mcid: 1,
+};
+
+// Annotation 20 already held by the Link through ParentTree key 1.
+const HELD = {
+ 7: "<< /Type /StructTreeRoot /K 9 0 R /ParentTree << /Nums [0 [10 0 R 11 0 R] 1 11 0 R] >> /ParentTreeNextKey 2 >>",
+ 11: "<< /Type /StructElem /S /Link /P 10 0 R /Pg 3 0 R /K [1 << /Type /OBJR /Obj 20 0 R >>] >>",
+ 20: "<< /Type /Annot /Subtype /Link /Rect [20 0 30 10] /StructParent 1 >>",
+};
+
+async function apply(
+ edits: AnnotationEdit[],
+ fixture = objects(),
+): Promise<RawPdf> {
+ return (await RawPdf.parse(
+ await applyAnnotationEdits(buildClassicPdf(fixture, 1), edits),
+ ))!;
+}
+
+async function failure(
+ edits: AnnotationEdit[],
+ fixture = objects(),
+): Promise<string[]> {
+ const err = await applyAnnotationEdits(
+ buildClassicPdf(fixture, 1),
+ edits,
+ ).catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(AnnotationEditError);
+ return (err as AnnotationEditError).failures.map((f) => f.reason);
+}
+
+function entry(pdf: RawPdf, key: number): string | undefined {
+ return pdf.numberTreeEntry(7, "ParentTree", key)?.span.text;
+}
+
+describe("applyAnnotationEdits", () => {
+ test("hands back the bytes untouched when there is nothing to write", async () => {
+ const bytes = buildClassicPdf(objects(), 1);
+ expect(await applyAnnotationEdits(bytes, [])).toBe(bytes);
+ });
+
+ test("gives the element an OBJR and the annotation a ParentTree key naming the element", async () => {
+ const pdf = await apply([LINK_TO_ELEMENT]);
+
+ expect(pdf.valueSpan(pdf.objectBody(11)!, "K")!.text).toBe(
+ "[1 << /Type /OBJR /Obj 20 0 R /Pg 3 0 R >>]",
+ );
+ expect(pdf.dictInt(pdf.objectBody(20)!, "StructParent")).toBe(1);
+ expect(entry(pdf, 1)).toBe("11 0 R");
+ expect(entry(pdf, 0)).toBe("[10 0 R 11 0 R]");
+ expect(pdf.dictInt(pdf.objectBody(7)!, "ParentTreeNextKey")).toBe(2);
+ expect(pdf.dictName(pdf.objectBody(3)!, "Tabs")).toBe("S");
+ });
+
+ test("gives each annotation an element holds a key of its own", async () => {
+ const pdf = await apply([
+ LINK_TO_ELEMENT,
+ { pageIndex: 0, annotation: 21, mcid: 0 },
+ ]);
+ expect(pdf.dictInt(pdf.objectBody(21)!, "StructParent")).toBe(2);
+ expect(entry(pdf, 2)).toBe("10 0 R");
+ expect(pdf.dictInt(pdf.objectBody(7)!, "ParentTreeNextKey")).toBe(3);
+ });
+
+ test("keeps the element readable, its marked content with it", async () => {
+ const bytes = await applyAnnotationEdits(buildClassicPdf(objects(), 1), [
+ LINK_TO_ELEMENT,
+ ]);
+ const structure = await readFileStructure(bytes);
+ expect(
+ structure!.pages.get(0)!.elements.map(({ mcids, type }) => [mcids, type]),
+ ).toEqual([
+ [[0], "P"],
+ [[1], "Link"],
+ ]);
+ });
+
+ test("sets, replaces and removes /Contents", async () => {
+ const contents = (pdf: RawPdf) => {
+ const span = pdf.valueSpan(pdf.objectBody(20)!, "Contents");
+ return span && decodeTextString(span.text);
+ };
+ const set = await apply([
+ { pageIndex: 0, annotation: 20, contents: "Old" },
+ { pageIndex: 0, annotation: 20, contents: "Café menu" },
+ ]);
+ expect(contents(set)).toBe("Café menu");
+ expect(set.dictInt(set.objectBody(20)!, "StructParent")).toBeNull();
+
+ const removed = await apply(
+ [{ pageIndex: 0, annotation: 20, contents: null }],
+ objects({ 20: "<< /Type /Annot /Subtype /Link /Contents (Old) >>" }),
+ );
+ expect(contents(removed)).toBeNull();
+ });
+
+ test("changes nothing for an annotation its element already holds", async () => {
+ const pdf = await apply(
+ [{ ...LINK_TO_ELEMENT, contents: "Example" }],
+ objects(HELD),
+ );
+ expect(pdf.valueSpan(pdf.objectBody(11)!, "K")!.text).toBe(
+ "[1 << /Type /OBJR /Obj 20 0 R >>]",
+ );
+ expect(pdf.dictInt(pdf.objectBody(20)!, "StructParent")).toBe(1);
+ expect(pdf.dictInt(pdf.objectBody(7)!, "ParentTreeNextKey")).toBe(2);
+ });
+
+ test("adds a leaf to a ParentTree with kids", async () => {
+ const pdf = await apply(
+ [LINK_TO_ELEMENT],
+ objects(
+ {
+ 7: "<< /Type /StructTreeRoot /K 9 0 R /ParentTree 30 0 R /ParentTreeNextKey 1 >>",
+ },
+ [
+ { num: 30, body: "<< /Kids [31 0 R] >>" },
+ { num: 31, body: "<< /Limits [0 0] /Nums [0 [10 0 R 11 0 R]] >>" },
+ ],
+ ),
+ );
+ expect(entry(pdf, 1)).toBe("11 0 R");
+ expect(pdf.objectBody(30)).toMatch(/\/Kids \[31 0 R \d+ 0 R\]/);
+ });
+
+ test("reads /Annots held by reference", async () => {
+ const pdf = await apply(
+ [LINK_TO_ELEMENT],
+ objects(
+ {
+ 3: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 5 0 R /StructParents 0 /Annots 23 0 R >>",
+ },
+ [{ num: 23, body: "[20 0 R 21 0 R]" }],
+ ),
+ );
+ expect(entry(pdf, 1)).toBe("11 0 R");
+ });
+
+ test("names every edit it cannot write, and writes none of them", async () => {
+ expect(
+ await failure([
+ LINK_TO_ELEMENT,
+ { pageIndex: 0, annotation: 22, contents: "x" },
+ { pageIndex: 0, annotation: 21, mcid: 5 },
+ { pageIndex: 3, annotation: 21, contents: "x" },
+ ]),
+ ).toEqual([
+ "the page's /Annots does not reference it",
+ "no structure element owns this MCID",
+ "no such page",
+ ]);
+ });
+
+ test("refuses an annotation another element holds", async () => {
+ expect(
+ await failure([{ pageIndex: 0, annotation: 20, mcid: 0 }], objects(HELD)),
+ ).toEqual(["another element holds it"]);
+ expect(
+ await failure([
+ LINK_TO_ELEMENT,
+ { pageIndex: 0, annotation: 20, mcid: 0 },
+ ]),
+ ).toEqual(["another element holds it"]);
+ });
+
+ test("refuses to give an annotation to an element in a file with no structure tree", async () => {
+ expect(
+ await failure(
+ [LINK_TO_ELEMENT],
+ objects({ 1: "<< /Type /Catalog /Pages 2 0 R >>" }),
+ ),
+ ).toEqual(["the file has no structure tree"]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/linkTagging.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/linkTagging.test.ts
new file mode 100644
index 0000000000..dff2337618
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/linkTagging.test.ts
@@ -0,0 +1,526 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { DeleteObjectCommand } from "@editor/tools/pdfTextEditor/commands/DeleteObjectCommand";
+import { linkTexts } from "@editor/tools/pdfTextEditor/commands/linkText";
+import { SetLinkContentsCommand } from "@editor/tools/pdfTextEditor/commands/SetLinkContentsCommand";
+import {
+ TagLinkCommand,
+ taggableLinks,
+} from "@editor/tools/pdfTextEditor/commands/TagLinkCommand";
+import {
+ TagPageContentCommand,
+ hasUntaggedContent,
+} from "@editor/tools/pdfTextEditor/commands/TagPageContentCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { elementKids } from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";
+import {
+ RawPdf,
+ referencedObject,
+} from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import { readFileStructure } from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";
+import { decodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import { innerTags } from "@editor/tools/pdfTextEditor/util/textAccessibility";
+import {
+ buildClassicPdf,
+ streamBody,
+ type FixtureObject,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+const LINE = "Visit stirlingpdf.com today.";
+// In 12 pt Helvetica from x 72, "Visit " is 26.0 pt wide and the address
+// 77.4 pt, so this covers the address and neither space beside it.
+const ADDRESS_RECT = "[97 696 176 710]";
+const LINK = 20;
+
+function linkAnnotation(extra = ""): FixtureObject {
+ return {
+ num: LINK,
+ body: `<< /Type /Annot /Subtype /Link /Rect ${ADDRESS_RECT} /Border [0 0 0] /A << /S /URI /URI (https://stirlingpdf.com) >>${extra} >>`,
+ };
+}
+
+function page(content: string, extra = ""): FixtureObject[] {
+ return [
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body:
+ `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Annots [${LINK} 0 R]${extra} ` +
+ "/Resources << /Font << /F1 5 0 R >> >> >>",
+ },
+ { num: 4, body: streamBody("", content) },
+ { num: 5, body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>" },
+ ];
+}
+
+/** No structure tree; `LINE` drawn with the link over its address. */
+function untaggedPdf(link = linkAnnotation()): Uint8Array {
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ ...page(`BT /F1 12 Tf 72 700 Td (${LINE}) Tj ET\n`),
+ link,
+ ],
+ 1,
+ );
+}
+
+/**
+ * `LINE` tagged as paragraph 9 (MCID 0) in Document 8, or with
+ * `linkElement` its address a Link 10 (MCID 1) in it, its text after MCID 2.
+ */
+function taggedPdf({
+ linkElement = false,
+ link = linkAnnotation(),
+ parentTree = "",
+} = {}): Uint8Array {
+ const content = linkElement
+ ? "/P <</MCID 0>> BDC BT /F1 12 Tf 72 700 Td (Visit ) Tj ET EMC\n" +
+ "/Link <</MCID 1>> BDC BT /F1 12 Tf 98.004 700 Td (stirlingpdf.com) Tj ET EMC\n" +
+ "/P <</MCID 2>> BDC BT /F1 12 Tf 175.356 700 Td ( today.) Tj ET EMC\n"
+ : `/P <</MCID 0>> BDC BT /F1 12 Tf 72 700 Td (${LINE}) Tj ET EMC\n`;
+ const slots = linkElement ? "[9 0 R 10 0 R 9 0 R]" : "[9 0 R]";
+ return buildClassicPdf(
+ [
+ {
+ num: 1,
+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 7 0 R >>",
+ },
+ ...page(content, " /StructParents 0"),
+ {
+ num: 7,
+ body: `<< /Type /StructTreeRoot /K 8 0 R /ParentTree << /Nums [0 ${slots}${parentTree}] >> /ParentTreeNextKey 2 >>`,
+ },
+ {
+ num: 8,
+ body: "<< /Type /StructElem /S /Document /P 7 0 R /K [9 0 R] >>",
+ },
+ {
+ num: 9,
+ body: `<< /Type /StructElem /S /P /P 8 0 R /Pg 3 0 R /K ${linkElement ? "[0 10 0 R 2]" : "0"} >>`,
+ },
+ ...(linkElement
+ ? [
+ {
+ num: 10,
+ body: "<< /Type /StructElem /S /Link /P 9 0 R /Pg 3 0 R /K 1 >>",
+ },
+ ]
+ : []),
+ link,
+ ],
+ 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, "links.pdf");
+ return new Uint8Array(await blob.arrayBuffer());
+}
+
+async function saved(doc: EditorDocument): Promise<RawPdf> {
+ return (await RawPdf.parse(await savedBytes(doc)))!;
+}
+
+function documentElement(pdf: RawPdf): number {
+ const catalog = pdf.objectBody(pdf.rootNum)!;
+ const root = pdf.objectBody(pdf.dictRef(catalog, "StructTreeRoot")!)!;
+ return pdf.dictRef(root, "K")!;
+}
+
+/** An element's kids: an MCID as its number, an element as its /S, an OBJR as `OBJR n` for the object it names. */
+function kidsOf(pdf: RawPdf, num: number): string[] {
+ return elementKids(pdf, pdf.objectBody(num)!)!.map((kid) => {
+ const ref = referencedObject(kid);
+ if (ref !== null) return `/${pdf.dictName(pdf.objectBody(ref)!, "S")}`;
+ if (!kid.startsWith("<<")) return kid;
+ return `${pdf.dictName(kid, "Type")} ${pdf.dictRef(kid, "Obj")}`;
+ });
+}
+
+function kidNamed(pdf: RawPdf, num: number, type: string): number {
+ const kid = elementKids(pdf, pdf.objectBody(num)!)!
+ .map(referencedObject)
+ .find(
+ (ref) => ref !== null && pdf.dictName(pdf.objectBody(ref)!, "S") === type,
+ );
+ if (kid == null) throw new Error(`no /${type} under ${num}`);
+ return kid;
+}
+
+/** The element the link's /StructParent entry names; null when it has none. */
+function holder(pdf: RawPdf): number | null {
+ const catalog = pdf.objectBody(pdf.rootNum)!;
+ const key = pdf.dictInt(pdf.objectBody(LINK)!, "StructParent");
+ if (key === null) return null;
+ const entry = pdf.numberTreeEntry(
+ pdf.dictRef(catalog, "StructTreeRoot")!,
+ "ParentTree",
+ key,
+ );
+ return entry ? referencedObject(entry.span.text) : null;
+}
+
+function contents(pdf: RawPdf): string | null {
+ const span = pdf.valueSpan(pdf.objectBody(LINK)!, "Contents");
+ return span && decodeTextString(span.text);
+}
+
+beforeAll(async () => {
+ const wasmPath = createRequire(import.meta.url).resolve(
+ "@embedpdf/pdfium/pdfium.wasm",
+ );
+ const wasmBytes = await readFile(wasmPath);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Promise.resolve(
+ new Response(wasmBytes, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ ),
+ );
+});
+
+afterEach(() => {
+ while (opened.length) opened.pop()!.dispose();
+});
+
+afterAll(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("reading link annotations", () => {
+ test("reads each link the page references, with what it covers and who holds it", async () => {
+ const structure = await readFileStructure(
+ taggedPdf({
+ link: linkAnnotation(
+ " /StructParent 1 /Contents (Our site) /QuadPoints [97 710 176 710 97 696 176 696]",
+ ),
+ parentTree: " 1 9 0 R",
+ }),
+ );
+ expect(structure!.links.get(0)).toEqual([
+ {
+ annotation: LINK,
+ areas: [{ left: 97, bottom: 696, right: 176, top: 710 }],
+ contents: "Our site",
+ holder: "9",
+ },
+ ]);
+ });
+
+ test("reads links in a file with no structure tree", async () => {
+ const structure = await readFileStructure(untaggedPdf());
+ expect(structure!.links.get(0)).toEqual([
+ {
+ annotation: LINK,
+ areas: [{ left: 97, bottom: 696, right: 176, top: 710 }],
+ contents: null,
+ holder: null,
+ },
+ ]);
+ });
+
+ test("finds the run text a link covers", async () => {
+ const doc = await open(untaggedPdf());
+ const [link] = doc.structure(0).links();
+ const text = linkTexts(doc, 0, [link]).get(LINK)!;
+ const run = doc.page(0).findRun(text.runId)!;
+ expect(run.text.slice(text.start, text.end)).toBe("stirlingpdf.com");
+ });
+});
+
+describe("tagging links", () => {
+ test("tags a page's link as a Link in its paragraph, holding the annotation", async () => {
+ const doc = await open(untaggedPdf());
+ new HistoryStack().execute(
+ new TagPageContentCommand({ pageIndex: 0 }),
+ doc,
+ );
+
+ const bytes = await savedBytes(doc);
+ const pdf = (await RawPdf.parse(bytes))!;
+ const paragraph = kidNamed(pdf, documentElement(pdf), "P");
+ expect(kidsOf(pdf, paragraph)).toEqual([
+ expect.any(String),
+ "/Link",
+ expect.any(String),
+ ]);
+ const link = kidNamed(pdf, paragraph, "Link");
+ expect(kidsOf(pdf, link)).toEqual([expect.any(String), `OBJR ${LINK}`]);
+ expect(holder(pdf)).toBe(link);
+ expect(contents(pdf)).toBe("stirlingpdf.com");
+ expect(pdf.dictName(pdf.objectBody(3)!, "Tabs")).toBe("S");
+
+ const reopened = await open(bytes);
+ expect(reopened.structure(0).linkHeld(LINK)).toBe(true);
+ expect(reopened.structure(0).linkContents(LINK)).toBe("stirlingpdf.com");
+ });
+
+ test("keeps the description a link already has", async () => {
+ const doc = await open(
+ untaggedPdf(linkAnnotation(" /Contents (Stirling PDF home)")),
+ );
+ new HistoryStack().execute(
+ new TagPageContentCommand({ pageIndex: 0 }),
+ doc,
+ );
+ const pdf = await saved(doc);
+ expect(contents(pdf)).toBe("Stirling PDF home");
+ expect(holder(pdf)).not.toBeNull();
+ });
+
+ test("undoing the page's tags leaves the link as it was", async () => {
+ const doc = await open(untaggedPdf());
+ const history = new HistoryStack();
+ history.execute(new TagPageContentCommand({ pageIndex: 0 }), doc);
+ history.undo(doc);
+ expect(doc.annotationEdits()).toEqual([]);
+ history.redo(doc);
+ expect(doc.annotationEdits()).toEqual([
+ expect.objectContaining({
+ annotation: LINK,
+ contents: "stirlingpdf.com",
+ }),
+ ]);
+ expect(holder(await saved(doc))).not.toBeNull();
+ });
+
+ test("tags the untagged link on a page whose text is tagged", async () => {
+ const doc = await open(taggedPdf());
+ expect(hasUntaggedContent(doc, 0)).toBe(true);
+ new HistoryStack().execute(
+ new TagPageContentCommand({ pageIndex: 0 }),
+ doc,
+ );
+ expect(hasUntaggedContent(doc, 0)).toBe(false);
+
+ const pdf = await saved(doc);
+ expect(kidsOf(pdf, 9)).toEqual([
+ expect.any(String),
+ "/Link",
+ expect.any(String),
+ ]);
+ expect(holder(pdf)).toBe(kidNamed(pdf, 9, "Link"));
+ });
+
+ test("gives the link to the Link its text already is", async () => {
+ const doc = await open(taggedPdf({ linkElement: true }));
+ new HistoryStack().execute(
+ new TagLinkCommand({ pageIndex: 0, annotation: LINK }),
+ doc,
+ );
+ const pdf = await saved(doc);
+ expect(kidsOf(pdf, 9)).toEqual(["0", "/Link", "2"]);
+ expect(kidsOf(pdf, 10)).toEqual(["1", `OBJR ${LINK}`]);
+ expect(holder(pdf)).toBe(10);
+ });
+
+ test("leaves a tagged link unheld once its text is deleted, keeping its description", async () => {
+ const doc = await open(taggedPdf());
+ const history = new HistoryStack();
+ history.execute(
+ new TagLinkCommand({ pageIndex: 0, annotation: LINK }),
+ doc,
+ );
+ const run = doc.page(0).runs.find((r) => r.text.includes("stirlingpdf"))!;
+ history.execute(
+ new DeleteObjectCommand({ pageIndex: 0, runId: run.id }),
+ doc,
+ );
+
+ const pdf = await saved(doc);
+ expect(holder(pdf)).toBeNull();
+ expect(contents(pdf)).toBe("stirlingpdf.com");
+ });
+
+ test("leaves a link the file already gives an element alone", async () => {
+ const doc = await open(
+ taggedPdf({
+ linkElement: true,
+ link: linkAnnotation(" /StructParent 1"),
+ parentTree: " 1 10 0 R",
+ }),
+ );
+ expect(hasUntaggedContent(doc, 0)).toBe(false);
+ expect(() =>
+ new HistoryStack().execute(
+ new TagLinkCommand({ pageIndex: 0, annotation: LINK }),
+ doc,
+ ),
+ ).toThrow();
+ });
+});
+
+describe("describing links", () => {
+ function linkTag(doc: EditorDocument) {
+ const run = doc.page(0).runs.find((r) => r.text.includes("stirlingpdf"))!;
+ return innerTags(doc, run.snapshot()).find(
+ (tag) => tag.role.type === "Link",
+ );
+ }
+
+ test("shows the link a tagged Link holds, and its description", async () => {
+ const doc = await open(taggedPdf());
+ new HistoryStack().execute(
+ new TagLinkCommand({ pageIndex: 0, annotation: LINK }),
+ doc,
+ );
+ expect(linkTag(doc)?.link).toEqual({
+ annotations: [LINK],
+ description: "stirlingpdf.com",
+ editable: true,
+ });
+ });
+
+ test("saves an edited description, and undoing it restores the one before", async () => {
+ const doc = await open(taggedPdf());
+ const history = new HistoryStack();
+ history.execute(
+ new TagLinkCommand({ pageIndex: 0, annotation: LINK }),
+ doc,
+ );
+ history.execute(
+ new SetLinkContentsCommand({
+ pageIndex: 0,
+ annotations: [LINK],
+ contents: "Stirling PDF home page",
+ }),
+ doc,
+ );
+ expect(contents(await saved(doc))).toBe("Stirling PDF home page");
+ history.undo(doc);
+ expect(linkTag(doc)?.link?.description).toBe("stirlingpdf.com");
+ });
+
+ test("describes a link the file already gives an element without moving it", async () => {
+ const doc = await open(
+ taggedPdf({
+ linkElement: true,
+ link: linkAnnotation(" /StructParent 1 /Contents (Old)"),
+ parentTree: " 1 10 0 R",
+ }),
+ );
+ expect(linkTag(doc)?.link?.description).toBe("Old");
+ new HistoryStack().execute(
+ new SetLinkContentsCommand({
+ pageIndex: 0,
+ annotations: [LINK],
+ contents: "New",
+ }),
+ doc,
+ );
+ expect(doc.annotationEdits()).toEqual([
+ { pageIndex: 0, annotation: LINK, contents: "New" },
+ ]);
+ const pdf = await saved(doc);
+ expect(contents(pdf)).toBe("New");
+ expect(holder(pdf)).toBe(10);
+ });
+
+ test("lists a run's untagged links, and no other run's", async () => {
+ const doc = await open(taggedPdf());
+ const run = doc.page(0).runs.find((r) => r.text.includes("stirlingpdf"))!;
+ expect(taggableLinks(doc, 0, run.id).map((l) => l.annotation)).toEqual([
+ LINK,
+ ]);
+ expect(taggableLinks(doc, 0, "another run")).toEqual([]);
+ });
+});
+
+describe("links in a word processor's tagged export", () => {
+ const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/tagged-sample.pdf",
+ );
+ const PAGE = 1;
+
+ async function sampleStructure() {
+ return (await readFileStructure(new Uint8Array(await readFile(SAMPLE))))!;
+ }
+
+ async function openSample(): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(
+ new Uint8Array(await readFile(SAMPLE)),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(PAGE));
+ return doc;
+ }
+
+ test("reads the link its Link holds, and the one nothing holds", async () => {
+ const structure = await sampleStructure();
+ const link = structure.pages
+ .get(PAGE)!
+ .elements.find((el) => el.type === "Link")!;
+ expect(
+ structure.links
+ .get(PAGE)!
+ .map(({ contents, holder }) => ({ contents, holder })),
+ ).toEqual([
+ { contents: "Appendix: method", holder: link.key },
+ { contents: null, holder: null },
+ ]);
+ });
+
+ test("shows the description of the link the file's Link holds", async () => {
+ const doc = await openSample();
+ const run = doc.page(PAGE).runs.find((r) => r.text.includes("appendix"))!;
+ const tag = innerTags(doc, run.snapshot()).find(
+ (inner) => inner.role.type === "Link",
+ );
+ expect(tag?.link).toMatchObject({
+ description: "Appendix: method",
+ editable: true,
+ });
+ });
+
+ test("tags the link nothing holds as a Link of the word it covers", async () => {
+ const appendixHolder = (await sampleStructure()).links.get(PAGE)![0].holder;
+ const doc = await openSample();
+ const [atlas] = taggableLinks(doc, PAGE);
+ const run = doc.page(PAGE).findRun(atlas.text.runId)!;
+ expect(run.text.slice(atlas.text.start, atlas.text.end)).toBe("Atlas");
+ new HistoryStack().execute(
+ new TagLinkCommand({ pageIndex: PAGE, annotation: atlas.annotation }),
+ doc,
+ );
+
+ const structure = (await readFileStructure(await savedBytes(doc)))!;
+ const [appendix, tagged] = structure.links.get(PAGE)!;
+ expect(appendix).toMatchObject({
+ contents: "Appendix: method",
+ holder: appendixHolder,
+ });
+ expect(tagged.contents).toBe("Atlas");
+ expect(
+ structure.pages.get(PAGE)!.elements.find((el) => el.key === tagged.holder)
+ ?.type,
+ ).toBe("Link");
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textRangeTagging.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textRangeTagging.test.ts
index 6f271f43b0..d1b4707f61 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textRangeTagging.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textRangeTagging.test.ts
@@ -16,6 +16,7 @@ import {
TagTextRangeCommand,
} from "@editor/tools/pdfTextEditor/commands/TagTextRangeCommand";
import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { TagPageContentCommand } from "@editor/tools/pdfTextEditor/commands/TagPageContentCommand";
import { RetagInnerCommand } from "@editor/tools/pdfTextEditor/commands/RetagInnerCommand";
import { readObjTexts } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
import {
@@ -116,6 +117,31 @@ function cutPdf(): Uint8Array {
);
}
+/** A page with no structure tree, drawing each of `lines` a line apart. */
+function untaggedPdf(...lines: string[]): Uint8Array {
+ const content = lines
+ .map((line, i) => `BT /F1 12 Tf 72 ${700 - i * 30} Td (${line}) Tj ET\n`)
+ .join("");
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { 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 " +
+ "/Resources << /Font << /F1 5 0 R >> >> >>",
+ },
+ { num: 4, body: streamBody("", content) },
+ {
+ num: 5,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ ],
+ 1,
+ );
+}
+
/** A page whose one paragraph (MCID 0) draws `line`, a text-showing operation with its spacing set before it. */
function linePdf(line: string): Uint8Array {
return paragraphPdf(`BT /F1 12 Tf 72 700 Td ${line} ET`);
@@ -326,6 +352,13 @@ function kidsOf(pdf: RawPdf, num: number): string[] {
});
}
+/** The object number of the saved file's top structure element. */
+function documentElement(pdf: RawPdf): number {
+ const catalog = pdf.objectBody(pdf.rootNum)!;
+ const root = pdf.objectBody(pdf.dictRef(catalog, "StructTreeRoot")!)!;
+ return pdf.dictRef(root, "K")!;
+}
+
/** The child element of `num` with /S `type`. */
function kidNamed(pdf: RawPdf, num: number, type: string): number {
const kid = elementKids(pdf, pdf.objectBody(num)!)!
@@ -712,6 +745,79 @@ describe("a block cut from part of a run", () => {
});
});
+describe("tagging part of the text of an element the session added", () => {
+ async function taggedPage(...lines: string[]) {
+ const doc = await open(untaggedPdf(...lines));
+ const history = new HistoryStack();
+ history.execute(new TagPageContentCommand({ pageIndex: 0 }), doc);
+ return { doc, history };
+ }
+
+ test("saves a Span among the added paragraph's kids", async () => {
+ const { doc, history } = await taggedPage("Read the guide for more.");
+ tagRange(doc, history, "guide", "Span");
+
+ const pdf = (await RawPdf.parse(await savedBytes(doc)))!;
+ const [paragraph] = kidsOf(pdf, documentElement(pdf));
+ expect(paragraph).toBe("/P");
+ const p = kidNamed(pdf, documentElement(pdf), "P");
+ expect(kidsOf(pdf, p)).toEqual([
+ expect.any(String),
+ "/Span",
+ expect.any(String),
+ ]);
+ expect(kidsOf(pdf, kidNamed(pdf, p, "Span"))).toHaveLength(1);
+ });
+
+ test("keeps an added paragraph whose text was all cut out, in its place", async () => {
+ const { doc, history } = await taggedPage(
+ "Opening line.",
+ "stirlingpdf.com",
+ "Closing line.",
+ );
+ tagRange(doc, history, "stirlingpdf.com", "Span");
+
+ const bytes = await savedBytes(doc);
+ const pdf = (await RawPdf.parse(bytes))!;
+ const top = documentElement(pdf);
+ expect(kidsOf(pdf, top)).toEqual(["/P", "/P", "/P"]);
+ const [first, middle, last] = elementKids(pdf, pdf.objectBody(top)!)!.map(
+ (kid) => referencedObject(kid)!,
+ );
+ expect(kidsOf(pdf, middle)).toEqual(["/Span"]);
+ const texts = textByMcid(await open(bytes));
+ const textOf = (num: number) =>
+ texts.get(Number(kidsOf(pdf, num)[0]))?.trim();
+ expect(textOf(first)).toBe("Opening line.");
+ expect(textOf(kidNamed(pdf, middle, "Span"))).toBe("stirlingpdf.com");
+ expect(textOf(last)).toBe("Closing line.");
+ });
+
+ test("splits a heading out of an added paragraph", async () => {
+ const { doc, history } = await taggedPage("Outlook Growth will slow.");
+ tagRange(doc, history, "Outlook", "H2");
+
+ expect(await savedHeadings(doc)).toEqual(["H2"]);
+ const pdf = (await RawPdf.parse(await savedBytes(doc)))!;
+ expect(kidsOf(pdf, documentElement(pdf))).toEqual(["/H2", "/P"]);
+ });
+
+ test("saves a cut from the text an earlier cut left before it", async () => {
+ const { doc, history } = await taggedPage("Read the guide for more.");
+ tagRange(doc, history, "guide", "Span");
+ tagRange(doc, history, "Read", "Span");
+
+ const pdf = (await RawPdf.parse(await savedBytes(doc)))!;
+ const p = kidNamed(pdf, documentElement(pdf), "P");
+ expect(kidsOf(pdf, p)).toEqual([
+ "/Span",
+ expect.any(String),
+ "/Span",
+ expect.any(String),
+ ]);
+ });
+});
+
describe("which tags part of a run's text can take", () => {
const typesFor = (
doc: EditorDocument,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetLinkContentsCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetLinkContentsCommand.ts
new file mode 100644
index 0000000000..72f861c84d
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetLinkContentsCommand.ts
@@ -0,0 +1,66 @@
+import i18n from "i18next";
+import {
+ RolledBackError,
+ type Command,
+} from "@editor/tools/pdfTextEditor/commands/Command";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+
+/**
+ * Set or, with null, remove the /Contents of link annotations on a page: the
+ * description a screen reader gives the link. Touches no page content; the
+ * save pass writes it.
+ */
+export class SetLinkContentsCommand implements Command {
+ readonly type = "set-link-contents";
+ private readonly pageIndex: number;
+ private readonly annotations: readonly number[];
+ private readonly contents: string | null;
+ /** Each annotation's /Contents before the first apply. */
+ private previous: Map<number, string | null> | null = null;
+
+ constructor(opts: {
+ pageIndex: number;
+ annotations: readonly number[];
+ contents: string | null;
+ }) {
+ this.pageIndex = opts.pageIndex;
+ this.annotations = opts.annotations;
+ this.contents = opts.contents;
+ }
+
+ apply(doc: EditorDocument): void {
+ const structure = doc.structure(this.pageIndex);
+ const links = new Set(structure.links().map((link) => link.annotation));
+ if (structure.readOnly || !this.annotations.every((a) => links.has(a))) {
+ throw new RolledBackError(
+ new Error(
+ i18n.t(
+ "pdfTextEditor.inspector.accessibility.cannotDescribeLink",
+ "This link's description can't be changed.",
+ ),
+ ),
+ );
+ }
+ this.previous ??= new Map(
+ this.annotations.map((a) => [a, structure.linkContents(a)]),
+ );
+ for (const annotation of this.annotations) {
+ structure.setLinkContents(annotation, this.contents);
+ }
+ doc.page(this.pageIndex).bumpRevision();
+ }
+
+ revert(doc: EditorDocument): void {
+ if (!this.previous) return;
+ const structure = doc.structure(this.pageIndex);
+ for (const [annotation, contents] of this.previous) {
+ structure.setLinkContents(annotation, contents);
+ }
+ doc.page(this.pageIndex).bumpRevision();
+ }
+
+ /** Keystrokes in one link's description field collapse into one undo step. */
+ coalesceKey(): string {
+ return `set-link-contents:${this.pageIndex}:${this.annotations.join(",")}`;
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagLinkCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagLinkCommand.ts
new file mode 100644
index 0000000000..8e9f7e2857
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagLinkCommand.ts
@@ -0,0 +1,183 @@
+import i18n from "i18next";
+import {
+ RolledBackError,
+ type Command,
+} from "@editor/tools/pdfTextEditor/commands/Command";
+import {
+ linkTexts,
+ type LinkText,
+} from "@editor/tools/pdfTextEditor/commands/linkText";
+import {
+ elementStretches,
+ rangeTagTypes,
+ TagTextRangeCommand,
+} from "@editor/tools/pdfTextEditor/commands/TagTextRangeCommand";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { isInlineType } from "@editor/tools/pdfTextEditor/model/PageStructure";
+
+/**
+ * How a link can be tagged: by cutting the text it covers out into a Link,
+ * or by giving it to the Link that text already is. `contents` is that text,
+ * for a link with no /Contents.
+ */
+type LinkTagPlan = { text: LinkText; contents: string } & (
+ | { kind: "cut" }
+ | { kind: "existing"; mcid: number }
+);
+
+/** A link TagLinkCommand can tag, and the text it covers. */
+export interface TaggableLink {
+ annotation: number;
+ text: LinkText;
+}
+
+interface AppliedPlan {
+ cut: TagTextRangeCommand | null;
+ /** The MCID of the existing Link, when there is no cut. */
+ holder: number | null;
+ contents: string;
+}
+
+/**
+ * Give link annotation `annotation` an element: the text it covers, cut out
+ * of the element whose text it is as a Link (TagTextRangeCommand), or the Link
+ * that text already is. A link with no /Contents gets that text as one. The
+ * page must already be read.
+ */
+export class TagLinkCommand implements Command {
+ readonly type = "tag-link";
+ private readonly pageIndex: number;
+ private readonly annotation: number;
+ /** Chosen on first apply, so a redo cuts the same text with the same MCIDs. */
+ private plan: AppliedPlan | null = null;
+ private setContents = false;
+
+ constructor(opts: { pageIndex: number; annotation: number }) {
+ this.pageIndex = opts.pageIndex;
+ this.annotation = opts.annotation;
+ }
+
+ apply(doc: EditorDocument): void {
+ const plan = (this.plan ??= this.choosePlan(doc));
+ const structure = doc.structure(this.pageIndex);
+ plan.cut?.apply(doc);
+ try {
+ structure.holdLink(this.annotation, plan.cut?.cutMcid ?? plan.holder);
+ } catch (err) {
+ plan.cut?.revert(doc);
+ throw new RolledBackError(err);
+ }
+ this.setContents = structure.linkContents(this.annotation) === null;
+ if (this.setContents) {
+ structure.setLinkContents(this.annotation, plan.contents);
+ }
+ }
+
+ revert(doc: EditorDocument): void {
+ if (!this.plan) return;
+ const structure = doc.structure(this.pageIndex);
+ if (this.setContents) structure.setLinkContents(this.annotation, null);
+ structure.holdLink(this.annotation, null);
+ this.plan.cut?.revert(doc);
+ }
+
+ describe(): string {
+ return i18n.t("pdfTextEditor.commands.tagLink", "Tag link");
+ }
+
+ private choosePlan(doc: EditorDocument): AppliedPlan {
+ const plan = planLinkTags(doc, this.pageIndex, [this.annotation]).get(
+ this.annotation,
+ );
+ if (!plan) {
+ throw new RolledBackError(
+ new Error(
+ i18n.t(
+ "pdfTextEditor.inspector.accessibility.cannotTagLink",
+ "This link can't be tagged.",
+ ),
+ ),
+ );
+ }
+ if (plan.kind === "existing") {
+ return { cut: null, holder: plan.mcid, contents: plan.contents };
+ }
+ const { runId, start, end } = plan.text;
+ return {
+ cut: new TagTextRangeCommand({
+ pageIndex: this.pageIndex,
+ runId,
+ start,
+ end,
+ as: "Link",
+ }),
+ holder: null,
+ contents: plan.contents,
+ };
+ }
+}
+
+/**
+ * The links TagLinkCommand can tag on a page, which must already be read;
+ * with `runId`, only those over that run's text.
+ */
+export function taggableLinks(
+ doc: EditorDocument,
+ pageIndex: number,
+ runId?: string,
+): TaggableLink[] {
+ const structure = doc.structure(pageIndex);
+ const untagged = structure
+ .links()
+ .flatMap(({ annotation }) =>
+ structure.linkHeld(annotation) ? [] : [annotation],
+ );
+ return [...planLinkTags(doc, pageIndex, untagged, runId)].map(
+ ([annotation, { text }]) => ({ annotation, text }),
+ );
+}
+
+/**
+ * How each of `annotations` can be tagged, by annotation. Left out when it
+ * cannot: an element already holds it, it covers no text of one run, or that
+ * text cannot be cut out (rangeTagTypes).
+ */
+function planLinkTags(
+ doc: EditorDocument,
+ pageIndex: number,
+ annotations: readonly number[],
+ runId?: string,
+): Map<number, LinkTagPlan> {
+ const structure = doc.structure(pageIndex);
+ const out = new Map<number, LinkTagPlan>();
+ if (structure.cannotAddElement()) return out;
+ const wanted = new Set(annotations);
+ const links = structure
+ .links()
+ .filter(
+ ({ annotation }) =>
+ wanted.has(annotation) && !structure.linkHeld(annotation),
+ );
+ const page = doc.page(pageIndex);
+ for (const [annotation, text] of linkTexts(doc, pageIndex, links)) {
+ const run = page.findRun(text.runId);
+ if (!run || (runId !== undefined && run.id !== runId)) continue;
+ const contents = run.text
+ .slice(text.start, text.end)
+ .replace(/\s+/g, " ")
+ .trim();
+ const owner = elementStretches(doc, pageIndex, text.runId).find(
+ (stretch) => stretch.start <= text.start && stretch.end >= text.end,
+ )?.element;
+ if (owner?.type === "Link") {
+ const mcid = owner.mcids[0];
+ out.set(annotation, { kind: "existing", mcid, text, contents });
+ continue;
+ }
+ const { start, end } = text;
+ if (rangeTagTypes(doc, pageIndex, run.id, start, end).some(isInlineType)) {
+ out.set(annotation, { kind: "cut", text, contents });
+ }
+ }
+ return out;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagPageContentCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagPageContentCommand.ts
index a58d95da3f..3407482ed1 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagPageContentCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagPageContentCommand.ts
@@ -12,6 +12,10 @@ import {
furnitureKind,
type Furniture,
} from "@editor/tools/pdfTextEditor/model/artifactKind";
+import {
+ TagLinkCommand,
+ taggableLinks,
+} from "@editor/tools/pdfTextEditor/commands/TagLinkCommand";
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";
@@ -71,8 +75,9 @@ interface Plan {
* other object an artifact, the new elements read in content order. Content already
* tagged or marked an artifact is left alone. Content marked with an MCID no
* element owns counts as untagged, losing that mark. Content in a form
- * XObject is left alone: the editor cannot tag inside one. The page must
- * already be read.
+ * XObject is left alone: the editor cannot tag inside one. Each link
+ * annotation no element holds is then tagged (TagLinkCommand), where it can
+ * be. The page must already be read.
*/
export class TagPageContentCommand implements Command {
readonly type = "tag-page-content";
@@ -80,6 +85,8 @@ export class TagPageContentCommand implements Command {
private readonly furniture: ReadonlyMap<string, Furniture>;
/** Chosen on first apply, so a redo reuses its MCIDs. */
private plan: Plan | null = null;
+ /** The links the first apply tagged, which a redo tags again. */
+ private links: TagLinkCommand[] | null = null;
constructor(opts: {
pageIndex: number;
@@ -109,6 +116,7 @@ export class TagPageContentCommand implements Command {
applyStep(doc, page, structure, step, this.plan.follows);
done.push(step);
}
+ this.tagLinks(doc);
} catch (err) {
for (const step of done.reverse()) revertStep(doc, page, structure, step);
throw new RolledBackError(err);
@@ -121,6 +129,7 @@ export class TagPageContentCommand implements Command {
if (!this.plan) return;
const page = doc.page(this.pageIndex);
const structure = doc.structure(this.pageIndex);
+ for (const link of [...(this.links ?? [])].reverse()) link.revert(doc);
for (const step of [...this.plan.steps].reverse()) {
revertStep(doc, page, structure, step);
}
@@ -131,6 +140,40 @@ export class TagPageContentCommand implements Command {
describe(): string {
return i18n.t("pdfTextEditor.commands.tagPageContent", "Auto-tag page");
}
+
+ /**
+ * Tag the links once their text is: on the first apply each one that can
+ * be, and on a redo the same ones. Throws, with none tagged, when a redo
+ * cannot.
+ */
+ private tagLinks(doc: EditorDocument): void {
+ if (this.links === null) {
+ this.links = [];
+ for (const { annotation } of taggableLinks(doc, this.pageIndex)) {
+ const link = new TagLinkCommand({
+ pageIndex: this.pageIndex,
+ annotation,
+ });
+ try {
+ link.apply(doc);
+ this.links.push(link);
+ } catch {
+ /* left untagged rather than failing the page */
+ }
+ }
+ return;
+ }
+ const done: TagLinkCommand[] = [];
+ try {
+ for (const link of this.links) {
+ link.apply(doc);
+ done.push(link);
+ }
+ } catch (err) {
+ for (const link of done.reverse()) link.revert(doc);
+ throw err;
+ }
+ }
}
/** True when TagPageContentCommand would change anything on the page, which must already be read. */
@@ -140,9 +183,8 @@ export function hasUntaggedContent(
): boolean {
const structure = doc.structure(pageIndex);
if (structure.cannotAddElement() !== null) return false;
- return (
- planTagging(doc, doc.page(pageIndex), structure, new Map()).steps.length > 0
- );
+ const { steps } = planTagging(doc, doc.page(pageIndex), structure, new Map());
+ return steps.length > 0 || taggableLinks(doc, pageIndex).length > 0;
}
/** The untagged content as steps, and where each new element reads. */
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts
index c203bc8095..0b03943d20 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts
@@ -102,6 +102,11 @@ export class TagTextRangeCommand implements Command {
return this.movedTo;
}
+ /** The MCID the cut text carries, chosen on first apply; null before then. */
+ get cutMcid(): number | null {
+ return this.mcids?.cut ?? null;
+ }
+
apply(doc: EditorDocument): void {
const page = doc.page(this.pageIndex);
const undo: Array<() => void> = [];
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/linkText.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/linkText.ts
new file mode 100644
index 0000000000..bf548ee6c1
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/linkText.ts
@@ -0,0 +1,128 @@
+import {
+ leaves,
+ type Leaf,
+} from "@editor/tools/pdfTextEditor/commands/runLeaves";
+import { nextMatch } from "@editor/tools/pdfTextEditor/commands/textPieces";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import {
+ areaContains,
+ type LinkAnnotation,
+} from "@editor/tools/pdfTextEditor/model/LinkAnnotation";
+import {
+ SCRATCH,
+ scratchPtr,
+} from "@editor/tools/pdfTextEditor/util/wasmScratch";
+
+/** The stretch of a run's text, in code units, that a link covers. */
+export interface LinkText {
+ runId: string;
+ start: number;
+ end: number;
+}
+
+interface Covered {
+ ptr: number;
+ annotation: number;
+ runId: string;
+ start: number;
+ end: number;
+}
+
+/**
+ * The run text each of `links` covers, by annotation: from the first to the
+ * last character whose box's centre is in one of its areas. A link over no
+ * text, or over text of more than one run, is left out. The page must
+ * already be read.
+ */
+export function linkTexts(
+ doc: EditorDocument,
+ pageIndex: number,
+ links: readonly LinkAnnotation[],
+): Map<number, LinkText> {
+ if (links.length === 0) return new Map();
+ const byAnnotation = new Map<number, Covered[]>();
+ for (const char of coveredCharacters(doc, pageIndex, links)) {
+ const chars = byAnnotation.get(char.annotation) ?? [];
+ chars.push(char);
+ byAnnotation.set(char.annotation, chars);
+ }
+ const out = new Map<number, LinkText>();
+ for (const [annotation, chars] of byAnnotation) {
+ const runs = new Set(chars.map((char) => char.runId));
+ if (runs.size !== 1) continue;
+ out.set(annotation, {
+ runId: chars[0].runId,
+ start: Math.min(...chars.map((char) => char.start)),
+ end: Math.max(...chars.map((char) => char.end)),
+ });
+ }
+ return out;
+}
+
+/**
+ * Each inked character a run lists that falls in a link's areas. The text
+ * page's characters for an object are matched to its text in order, as
+ * charOrigins does; an object whose characters do not spell its text is left
+ * out, since none of its places can be trusted.
+ */
+function coveredCharacters(
+ doc: EditorDocument,
+ pageIndex: number,
+ links: readonly LinkAnnotation[],
+): Covered[] {
+ const m = doc.module;
+ const page = doc.page(pageIndex);
+ const leafOf = new Map<number, Leaf>();
+ for (const run of page.runs) {
+ for (const leaf of leaves(run) ?? []) leafOf.set(leaf.ptr, leaf);
+ }
+ const covered: Covered[] = [];
+ const read = new Map<number, number>();
+ const untrusted = new Set<number>();
+ const textPage = m.FPDFText_LoadPage(page.pagePtr);
+ if (!textPage) return [];
+ try {
+ const box = scratchPtr(m, SCRATCH.linkCharBox, 32);
+ const count = m.FPDFText_CountChars(textPage);
+ for (let i = 0; i < count; i++) {
+ const ptr = m.FPDFText_GetTextObject(textPage, i);
+ const leaf = leafOf.get(ptr);
+ if (!leaf || untrusted.has(ptr)) continue;
+ if (m.FPDFText_IsGenerated(textPage, i) === 1) continue;
+ const char = String.fromCodePoint(m.FPDFText_GetUnicode(textPage, i));
+ const at = nextMatch(leaf.text, read.get(ptr) ?? 0, char);
+ if (at === null) {
+ untrusted.add(ptr);
+ continue;
+ }
+ read.set(ptr, at + char.length);
+ if (!/\S/.test(char)) continue;
+ if (
+ !m.FPDFText_GetCharBox(textPage, i, box, box + 8, box + 16, box + 24)
+ ) {
+ continue;
+ }
+ const [left, right, bottom, top] = [0, 8, 16, 24].map((offset) =>
+ m.pdfium.getValue(box + offset, "double"),
+ );
+ const centre = { x: (left + right) / 2, y: (bottom + top) / 2 };
+ for (const { annotation, areas } of links) {
+ if (!areas.some((area) => areaContains(area, centre))) continue;
+ const start = leaf.start + at;
+ covered.push({
+ ptr,
+ annotation,
+ runId: leaf.run.id,
+ start,
+ end: start + char.length,
+ });
+ }
+ }
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ }
+ for (const [ptr, leaf] of leafOf) {
+ if (/\S/.test(leaf.text.slice(read.get(ptr) ?? 0))) untrusted.add(ptr);
+ }
+ return covered.filter((char) => !untrusted.has(char.ptr));
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/textPieces.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/textPieces.ts
index 81b4d5f1d5..4d88790eef 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/textPieces.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/textPieces.ts
@@ -124,7 +124,11 @@ export function charOrigins(
}
/** Where `char` comes next in `text` from code unit `at`, past spaces; null when it does not. */
-function nextMatch(text: string, at: number, char: string): number | null {
+export function nextMatch(
+ text: string,
+ at: number,
+ char: string,
+): number | null {
let unit = at;
while (!text.startsWith(char, unit) && /\s/.test(text[unit] ?? "")) unit++;
return text.startsWith(char, unit) ? unit : null;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx
index f3959809aa..030c5692c9 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx
@@ -82,6 +82,7 @@ export function SelectionInspector({
inner={controller.innerTextTags}
language={controller.textLanguage}
otherPages={controller.textOtherPages}
+ untaggedLinks={controller.textUntaggedLinks}
/>
)}
{ACCESSIBILITY_EDITING && controller.imageAccessibility && (
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 b07cbf44c1..65a87b839d 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
@@ -6,6 +6,7 @@ import { structureRole } from "@editor/tools/pdfTextEditor/model/structureTypes"
import type {
InnerTagsControl,
TextLanguageControl,
+ UntaggedLinksControl,
} from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";
import type { TextTag } from "@editor/tools/pdfTextEditor/util/textAccessibility";
@@ -20,6 +21,7 @@ const NO_INNER: InnerTagsControl = {
onTagSelection: () => {},
onSetLanguage: () => {},
onLanguageSelection: null,
+ onSetLinkDescription: () => {},
};
function tagShown(tag: TextTag): HTMLElement {
@@ -31,6 +33,7 @@ function tagShown(tag: TextTag): HTMLElement {
inner={NO_INNER}
language={null}
otherPages={null}
+ untaggedLinks={null}
/>
</MantineProvider>,
);
@@ -100,6 +103,7 @@ describe("TextAccessibilitySection", () => {
inner={NO_INNER}
language={null}
otherPages={null}
+ untaggedLinks={null}
/>
</MantineProvider>,
);
@@ -124,6 +128,7 @@ describe("TextAccessibilitySection", () => {
inner={NO_INNER}
language={null}
otherPages={null}
+ untaggedLinks={null}
/>
</MantineProvider>,
);
@@ -142,6 +147,7 @@ describe("TextAccessibilitySection", () => {
inner={NO_INNER}
language={null}
otherPages={null}
+ untaggedLinks={null}
/>
</MantineProvider>,
);
@@ -160,6 +166,7 @@ describe("TextAccessibilitySection", () => {
inner={NO_INNER}
language={null}
otherPages={null}
+ untaggedLinks={null}
/>
</MantineProvider>,
);
@@ -180,6 +187,7 @@ describe("TextAccessibilitySection", () => {
inner={NO_INNER}
language={null}
otherPages={null}
+ untaggedLinks={null}
/>
</MantineProvider>,
);
@@ -204,6 +212,7 @@ describe("TextAccessibilitySection", () => {
inner={NO_INNER}
language={null}
otherPages={null}
+ untaggedLinks={null}
/>
</MantineProvider>,
);
@@ -223,6 +232,7 @@ describe("TextAccessibilitySection", () => {
inner={NO_INNER}
language={null}
otherPages={{ pages: 3, onApply }}
+ untaggedLinks={null}
/>
</MantineProvider>,
);
@@ -240,6 +250,7 @@ describe("TextAccessibilitySection", () => {
inner={NO_INNER}
language={null}
otherPages={null}
+ untaggedLinks={null}
/>
</MantineProvider>,
);
@@ -264,6 +275,7 @@ describe("TextAccessibilitySection", () => {
inner={NO_INNER}
language={null}
otherPages={null}
+ untaggedLinks={null}
/>
</MantineProvider>,
);
@@ -366,6 +378,7 @@ describe("TextAccessibilitySection", () => {
inner={innerControl()}
language={{ language: undefined, onSet: vi.fn() }}
otherPages={null}
+ untaggedLinks={null}
/>
</MantineProvider>,
);
@@ -405,6 +418,31 @@ describe("TextAccessibilitySection", () => {
});
});
+describe("TextAccessibilitySection links", () => {
+ it("edits the description of the link a tag holds", () => {
+ const inner = innerControl({ active: 1 });
+ renderSection(inner);
+ const field = screen.getByTestId("pdf-editor-inner-tag-link-description");
+ expect(field).toHaveValue("The appendix");
+ fireEvent.change(field, { target: { value: "Appendix B" } });
+ expect(inner.onSetLinkDescription).toHaveBeenCalledWith(1, "Appendix B");
+ });
+
+ it("shows no link description for a tag holding no link", () => {
+ renderSection(innerControl({ active: 0 }));
+ expect(
+ screen.queryByTestId("pdf-editor-inner-tag-link-description"),
+ ).toBeNull();
+ });
+
+ it("offers tagging the links over the text", () => {
+ const onTag = vi.fn();
+ renderSection(innerControl(), null, { count: 2, onTag });
+ fireEvent.click(screen.getByTestId("pdf-editor-tag-links"));
+ expect(onTag).toHaveBeenCalled();
+ });
+});
+
function languageControl(
inherited: string | null,
own: string | null,
@@ -427,6 +465,7 @@ function innerControl(
removable: true,
language: { own: "de", inherited: "en" },
languageEditable: true,
+ link: null,
},
{
key: "2",
@@ -438,6 +477,11 @@ function innerControl(
removable: false,
language: { own: null, inherited: "en" },
languageEditable: true,
+ link: {
+ annotations: [20],
+ description: "The appendix",
+ editable: true,
+ },
},
],
active: null,
@@ -447,6 +491,7 @@ function innerControl(
onTagSelection: vi.fn(),
onSetLanguage: vi.fn(),
onLanguageSelection: null,
+ onSetLinkDescription: vi.fn(),
...overrides,
};
}
@@ -454,6 +499,7 @@ function innerControl(
function renderSection(
inner: InnerTagsControl,
language: TextLanguageControl | null = null,
+ untaggedLinks: UntaggedLinksControl | null = null,
) {
render(
<MantineProvider env="test">
@@ -468,6 +514,7 @@ function renderSection(
inner={inner}
language={language}
otherPages={null}
+ untaggedLinks={untaggedLinks}
/>
</MantineProvider>,
);
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 5823a99429..0d6aab529b 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsx
@@ -1,6 +1,6 @@
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
-import { Box, Group, Stack } from "@mantine/core";
+import { Box, Group, Stack, Textarea } from "@mantine/core";
import { ActionIcon } from "@editor/ui/ActionIcon";
import { Button } from "@editor/ui/Button";
import { Icon } from "@editor/ui/Icon";
@@ -32,6 +32,7 @@ import type {
InnerTagsControl,
OtherPagesControl,
TextLanguageControl,
+ UntaggedLinksControl,
} from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";
import { LanguagePicker } from "@editor/tools/pdfTextEditor/components/inspector/LanguagePicker";
import "@editor/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.css";
@@ -40,9 +41,9 @@ 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, giving untagged text an
- * element of its own, or making it an artifact. Beneath them, the tags marking parts of the text, and
- * pickers for characters selected in it. With several runs selected, the tag
- * they share and their language.
+ * element of its own, or making it an artifact. Beneath them, the tags marking parts of the text, a
+ * way to tag the links over it, and pickers for characters selected in it.
+ * With several runs selected, the tag they share and their language.
*/
export function TextAccessibilitySection({
tag,
@@ -50,12 +51,14 @@ export function TextAccessibilitySection({
inner,
language,
otherPages,
+ untaggedLinks,
}: {
tag: TextTag | null;
onSetTag: (choice: TextTagChoice) => void;
inner: InnerTagsControl;
language: TextLanguageControl | null;
otherPages: OtherPagesControl | null;
+ untaggedLinks: UntaggedLinksControl | null;
}) {
const { t } = useTranslation();
return (
@@ -70,6 +73,7 @@ export function TextAccessibilitySection({
{tag && (
<>
<InnerTagList inner={inner} />
+ {untaggedLinks && <TagLinksButton control={untaggedLinks} />}
<NewTagPicker inner={inner} />
<NewLanguagePicker inner={inner} />
</>
@@ -200,6 +204,26 @@ function OtherPagesButton({ control }: { control: OtherPagesControl }) {
);
}
+function TagLinksButton({ control }: { control: UntaggedLinksControl }) {
+ const { t } = useTranslation();
+ return (
+ <Button
+ size="sm"
+ variant="secondary"
+ accent="neutral"
+ fullWidth
+ justify="start"
+ leftSection={<Icon name="link" size={20} />}
+ onClick={control.onTag}
+ data-testid="pdf-editor-tag-links"
+ >
+ {t("pdfTextEditor.inspector.accessibility.tagLinks", "Tag link", {
+ count: control.count,
+ })}
+ </Button>
+ );
+}
+
/** The language the selected text's blocks are read in; "Mixed" when they differ. */
function TextLanguageField({ control }: { control: TextLanguageControl }) {
const { t } = useTranslation();
@@ -253,6 +277,9 @@ function InnerTagList({ inner }: { inner: InnerTagsControl }) {
onSelect={() => inner.onSelect(index)}
onSet={(type) => inner.onSet(index, type)}
onSetLanguage={(lang) => inner.onSetLanguage(index, lang)}
+ onSetLinkDescription={(description) =>
+ inner.onSetLinkDescription(index, description)
+ }
/>
))}
</Stack>
@@ -267,6 +294,7 @@ function InnerTagRow({
onSelect,
onSet,
onSetLanguage,
+ onSetLinkDescription,
}: {
number: number;
innerTag: InnerTag;
@@ -274,6 +302,7 @@ function InnerTagRow({
onSelect: () => void;
onSet: (type: StructureType | null) => void;
onSetLanguage: (lang: string | null) => void;
+ onSetLinkDescription: (description: string) => void;
}) {
const text = innerTag.text.replace(/\s+/g, " ").trim();
return (
@@ -298,6 +327,7 @@ function InnerTagRow({
innerTag={innerTag}
onSet={onSet}
onSetLanguage={onSetLanguage}
+ onSetLinkDescription={onSetLinkDescription}
/>
)}
</div>
@@ -309,11 +339,13 @@ function InnerTagControls({
innerTag,
onSet,
onSetLanguage,
+ onSetLinkDescription,
}: {
number: number;
innerTag: InnerTag;
onSet: (type: StructureType | null) => void;
onSetLanguage: (lang: string | null) => void;
+ onSetLinkDescription: (description: string) => void;
}) {
const { t } = useTranslation();
const removeLabel = t(
@@ -366,6 +398,23 @@ function InnerTagControls({
testId="pdf-editor-inner-tag-language-picker"
disabled={!innerTag.languageEditable}
/>
+ {innerTag.link && (
+ <Textarea
+ label={t(
+ "pdfTextEditor.inspector.accessibility.linkDescription",
+ "Link description",
+ )}
+ value={innerTag.link.description ?? ""}
+ className={privateContentClassName}
+ onChange={(e) => onSetLinkDescription(e.currentTarget.value)}
+ disabled={!innerTag.link.editable}
+ autosize
+ minRows={1}
+ maxRows={4}
+ size="xs"
+ data-testid="pdf-editor-inner-tag-link-description"
+ />
+ )}
</Stack>
);
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts
index 569cfc3f02..4a4da50a20 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts
@@ -6,10 +6,15 @@ import { RetagInnerCommand } from "@editor/tools/pdfTextEditor/commands/RetagInn
import { RetagTextCommand } from "@editor/tools/pdfTextEditor/commands/RetagTextCommand";
import { SetDecorativeCommand } from "@editor/tools/pdfTextEditor/commands/SetDecorativeCommand";
import { SetInnerLanguageCommand } from "@editor/tools/pdfTextEditor/commands/SetInnerLanguageCommand";
+import { SetLinkContentsCommand } from "@editor/tools/pdfTextEditor/commands/SetLinkContentsCommand";
import {
SetTextLanguageCommand,
type LanguageTarget,
} from "@editor/tools/pdfTextEditor/commands/SetTextLanguageCommand";
+import {
+ TagLinkCommand,
+ taggableLinks,
+} from "@editor/tools/pdfTextEditor/commands/TagLinkCommand";
import { TagTextCommand } from "@editor/tools/pdfTextEditor/commands/TagTextCommand";
import {
rangeTagTypes,
@@ -55,6 +60,14 @@ export interface InnerTagsControl {
onSetLanguage: (index: number, lang: string | null) => void;
/** Tags the characters selected inside the run as a Span in `lang`; null when they cannot take one. */
onLanguageSelection: ((lang: string) => void) | null;
+ /** Sets the description of the links tag `index` holds; empty removes it. */
+ onSetLinkDescription: (index: number, description: string) => void;
+}
+
+/** The selected run's links no element holds that can be tagged, and a way to tag them. */
+export interface UntaggedLinksControl {
+ count: number;
+ onTag: () => void;
}
/** Matching text on other pages that the selected artifact's kind can be given, and a way to give it. */
@@ -149,6 +162,30 @@ export function useTextAccessibility(
};
}, [store, state.pages, run, tag]);
+ const untaggedLinks = useMemo((): UntaggedLinksControl | null => {
+ const doc = store.document;
+ const links = doc && run ? taggableLinks(doc, run.pageIndex, run.id) : [];
+ if (!doc || !run || links.length === 0) return null;
+ return {
+ count: links.length,
+ onTag: () => {
+ const commands = links.map(
+ ({ annotation }) =>
+ new TagLinkCommand({ pageIndex: run.pageIndex, annotation }),
+ );
+ store.dispatch(
+ commands.length === 1 ? commands[0] : new CompositeCommand(commands),
+ );
+ // Selecting the one link's text opens its description.
+ if (links.length === 1) {
+ const { start, end } = links[0].text;
+ store.selection.setTextRange(run.id, { start, end });
+ }
+ },
+ };
+ // state.pages: tagging republishes the pages, not the run.
+ }, [store, run, state.pages]);
+
const activeInner = useMemo(
() => inner.findIndex((t) => sameRange(t, selection.textRange)),
[inner, selection.textRange],
@@ -234,6 +271,21 @@ export function useTextAccessibility(
[store, run, inner],
);
+ const setLinkDescription = useCallback(
+ (index: number, description: string) => {
+ const link = inner[index]?.link;
+ if (!run || !link) return;
+ store.dispatch(
+ new SetLinkContentsCommand({
+ pageIndex: run.pageIndex,
+ annotations: link.annotations,
+ contents: description === "" ? null : description,
+ }),
+ );
+ },
+ [store, run, inner],
+ );
+
const spansSelection = newTagTypes?.includes("Span") ?? false;
const setSelectionLanguage = useCallback(
(lang: string) => {
@@ -263,6 +315,7 @@ export function useTextAccessibility(
onTagSelection: tagSelectedText,
onSetLanguage: setInnerLanguage,
onLanguageSelection: spansSelection ? setSelectionLanguage : null,
+ onSetLinkDescription: setLinkDescription,
}),
[
inner,
@@ -274,6 +327,7 @@ export function useTextAccessibility(
setInnerLanguage,
spansSelection,
setSelectionLanguage,
+ setLinkDescription,
],
);
@@ -296,7 +350,14 @@ export function useTextAccessibility(
// state.pages: a language change republishes the pages, not the targets.
}, [store, languageTargets, state.pages]);
- return { tag, setTag, inner: innerControl, language, otherPages };
+ return {
+ tag,
+ setTag,
+ inner: innerControl,
+ language,
+ otherPages,
+ untaggedLinks,
+ };
}
/**
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts
index 783e76f455..b9c97f24bd 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts
@@ -531,6 +531,7 @@ export function useToolbarController(
innerTextTags: textA11y.inner,
textLanguage: textA11y.language,
textOtherPages: textA11y.otherPages,
+ textUntaggedLinks: textA11y.untaggedLinks,
selectionAllLocked,
hasRunSelection: selection.runIds.length > 0,
hasImageSelection: selection.imageIds.length > 0,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts
index 6519c8d5a2..37d7fb0bb5 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts
@@ -7,13 +7,17 @@ import {
import { Page } from "@editor/tools/pdfTextEditor/model/Page";
import {
PageStructure,
+ givenMcids,
isInlineType,
+ type AddedElement,
+ type CutElement,
type ReadOnlyReason,
} from "@editor/tools/pdfTextEditor/model/PageStructure";
import {
effectiveLanguage,
type TextLanguage,
} from "@editor/tools/pdfTextEditor/model/languageTag";
+import type { AnnotationEdit } from "@editor/tools/pdfTextEditor/pdfdoc/passes/applyAnnotationEdits";
import type { StructureEdit } from "@editor/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits";
import {
readPageStructure,
@@ -327,10 +331,16 @@ export class EditorDocument {
);
}
const page = this.fileStructure.pages.get(pageIndex);
- if (!page) return new PageStructure([], null, 0);
+ const links = this.fileStructure.links.get(pageIndex) ?? [];
+ const retaggedAs = (key: string) => this.retaggedAs(key);
+ if (!page) return new PageStructure([], null, 0, retaggedAs, links);
if (page.slotCount === null) return new PageStructure([], "unreadable");
- return new PageStructure(page.elements, null, page.slotCount, (key) =>
- this.retaggedAs(key),
+ return new PageStructure(
+ page.elements,
+ null,
+ page.slotCount,
+ retaggedAs,
+ links,
);
}
@@ -655,10 +665,29 @@ export class EditorDocument {
];
}
+ /**
+ * Every unsaved change to a link annotation, in the form the save pass
+ * takes. A link whose holder's text is no longer on the page is left
+ * unheld, as the save drops a session element with no text (cutEdits,
+ * addedElementEdits).
+ */
+ annotationEdits(): AnnotationEdit[] {
+ return [...this.structureCache].flatMap(([pageIndex, structure]) => {
+ const page = this.pageCache.get(pageIndex);
+ const carried = page && carriedMcids(this.module, page.pagePtr);
+ return structure.linkEdits().flatMap(({ mcid, ...edit }) => {
+ const held = mcid !== undefined && (!carried || carried.has(mcid));
+ if (!held && edit.contents === undefined) return [];
+ return [{ pageIndex, ...edit, ...(held && { mcid }) }];
+ });
+ });
+ }
+
/**
* 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.
+ * so it finds that already in the tree. Text cut from an element stands
+ * for it, which keeps one whose text was all cut out. An element whose
+ * content was deleted is left out: there is nothing left for it to tag.
*/
private addedElementEdits(
pageIndex: number,
@@ -670,17 +699,25 @@ export class EditorDocument {
);
if (!page || added.size === 0) return [];
const content = taggedContentInReadingOrder(page);
- const carried = new Set(content.map(({ mcid }) => mcid));
+ // The save writes a cut from an added element after every added element,
+ // so content is placed beside the element its text was cut from.
+ const owners = addedOwners(added, structure.cutElements());
+ const ownerOf = (mcid: number) => owners.get(mcid) ?? mcid;
+ const present = new Set(content.map(({ mcid }) => ownerOf(mcid)));
const edits = new Map<number, StructureEdit>();
for (const item of content) {
- const element = added.get(item.mcid);
+ const element = added.get(ownerOf(item.mcid));
if (!element) continue;
- added.delete(item.mcid);
+ added.delete(element.mcid);
const { follows } = element;
+ const preceding = () => {
+ const mcid = precedingTaggedMcid(page, item);
+ return mcid === null ? null : ownerOf(mcid);
+ };
const after =
- follows === null || (follows !== undefined && carried.has(follows))
+ follows === null || (follows !== undefined && present.has(follows))
? follows
- : precedingTaggedMcid(page, item);
+ : preceding();
edits.set(element.mcid, {
pageIndex,
mcid: element.mcid,
@@ -887,6 +924,25 @@ function insertionPoint(
return next >= 0 ? next : blocks.length;
}
+/**
+ * The added element each cut's text was taken from, through cuts from cuts,
+ * by the cut's MCID and those it gave the text it was cut from. Cuts from
+ * the file's elements are left out.
+ */
+function addedOwners(
+ added: ReadonlyMap<number, AddedElement>,
+ cuts: readonly CutElement[],
+): Map<number, number> {
+ const owners = new Map<number, number>();
+ for (const { mcid, cut } of cuts) {
+ const from = cut.from[0];
+ const owner = added.has(from) ? from : owners.get(from);
+ if (owner === undefined) continue;
+ for (const part of [mcid, ...givenMcids(cut)]) owners.set(part, owner);
+ }
+ return owners;
+}
+
/**
* `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
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/LinkAnnotation.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/LinkAnnotation.ts
new file mode 100644
index 0000000000..4ba00b7eba
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/LinkAnnotation.ts
@@ -0,0 +1,34 @@
+/** An area of the page, in page space (y-up). */
+export interface PageArea {
+ left: number;
+ bottom: number;
+ right: number;
+ top: number;
+}
+
+/** A link annotation the file has, as the save addresses it. */
+export interface LinkAnnotation {
+ /** Its object number, which the save gives it to an element by. */
+ annotation: number;
+ /**
+ * What it covers: the box around each of its /QuadPoints quadrilaterals,
+ * or its /Rect when it has none.
+ */
+ areas: PageArea[];
+ /** Its /Contents as the file has it; null when it has none. */
+ contents: string | null;
+ /** The key of the element the file gives it to; null when none. */
+ holder: string | null;
+}
+
+export function areaContains(
+ area: PageArea,
+ point: { x: number; y: number },
+): boolean {
+ return (
+ point.x >= area.left &&
+ point.x <= area.right &&
+ point.y >= area.bottom &&
+ point.y <= area.top
+ );
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts
index 56400bc127..43f39b4d95 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts
@@ -1,4 +1,5 @@
import type { Furniture } from "@editor/tools/pdfTextEditor/model/artifactKind";
+import type { LinkAnnotation } from "@editor/tools/pdfTextEditor/model/LinkAnnotation";
import type {
StructureRole,
StructureType,
@@ -220,7 +221,7 @@ export interface ContentCut {
}
/** The MCIDs a cut gave to the content it was cut from. */
-function givenMcids(cut: ContentCut): number[] {
+export function givenMcids(cut: ContentCut): number[] {
return [cut.before, cut.after].filter(
(mcid): mcid is number => mcid !== null && !cut.from.includes(mcid),
);
@@ -273,6 +274,15 @@ export interface ElementLanguageEdit {
lang: string | null;
}
+/** A change to one of the page's link annotations, for the save (see AnnotationEdit). */
+export interface LinkEdit {
+ annotation: number;
+ /** The MCID of the Link element to give it to; absent leaves it as the file has it. */
+ mcid?: number;
+ /** The /Contents to save, null for none; absent leaves the file's. */
+ contents?: string | null;
+}
+
/**
* The structure elements of one page plus the session's unsaved edits to
* them, and the elements it adds. Edits are keyed by element rather than MCID,
@@ -308,6 +318,11 @@ export class PageStructure {
* block can span pages.
*/
private readonly langs = new Map<string, string | null>();
+ private readonly linkAnnotations: ReadonlyMap<number, LinkAnnotation>;
+ /** The MCID of the element the session gives each link annotation to, by annotation. */
+ private readonly linkHolders = new Map<number, number>();
+ /** The session's /Contents for link annotations, by annotation. */
+ private readonly linkContentsEdits = new Map<number, string | null>();
/** Why the save cannot write descriptions for this page, or null when it can. */
readonly readOnly: ReadOnlyReason | null;
@@ -323,11 +338,15 @@ export class PageStructure {
readOnly: ReadOnlyReason | null = null,
slotCount: number | null = null,
retaggedAs: RetagLookup = () => null,
+ links: readonly LinkAnnotation[] = [],
) {
this.elements = elements;
this.readOnly = readOnly;
this.slotCount = slotCount;
this.retaggedAs = retaggedAs;
+ this.linkAnnotations = new Map(
+ links.map((link) => [link.annotation, link]),
+ );
this.fileElements = new Set(elements);
for (const el of elements) {
for (const mcid of el.mcids) this.byMcid.set(mcid, el);
@@ -856,6 +875,99 @@ export class PageStructure {
private isStandIn(el: StructureElement): boolean {
return this.standIns.get(el.key) === el;
}
+
+ /** The page's link annotations the save can give an element. */
+ links(): LinkAnnotation[] {
+ return [...this.linkAnnotations.values()];
+ }
+
+ /**
+ * True when an element holds link `annotation`: the file's, or a Link the
+ * session gave it to. One that has stopped being a Link no longer holds it.
+ */
+ linkHeld(annotation: number): boolean {
+ const link = this.linkAnnotations.get(annotation);
+ return link?.holder != null || this.sessionLinkHolder(annotation) !== null;
+ }
+
+ /**
+ * Give link `annotation` to the Link element owning `mcid`, or take it back
+ * with null. Throws for a page whose save cannot write it, an annotation
+ * the page does not have or the file already gives an element, and an
+ * MCID no Link owns.
+ */
+ holdLink(annotation: number, mcid: number | null): void {
+ const link = this.editableLink(annotation);
+ if (link.holder !== null) {
+ throw new Error(`Link ${annotation} already has an element`);
+ }
+ if (mcid === null) {
+ this.linkHolders.delete(annotation);
+ return;
+ }
+ if (this.element(mcid)?.type !== "Link") {
+ throw new Error(`No Link owns MCID ${mcid}`);
+ }
+ this.linkHolders.set(annotation, mcid);
+ }
+
+ /** The link annotations element `key` holds, as the session has it. */
+ linksHeldBy(key: string): number[] {
+ return this.links().flatMap(({ annotation, holder }) => {
+ const held = holder ?? this.sessionLinkHolder(annotation)?.key;
+ return held === key ? [annotation] : [];
+ });
+ }
+
+ /** The link's /Contents as it will be saved: the session's, else the file's. Throws as holdLink does for an unknown annotation. */
+ linkContents(annotation: number): string | null {
+ if (this.linkContentsEdits.has(annotation)) {
+ return this.linkContentsEdits.get(annotation)!;
+ }
+ return this.knownLink(annotation).contents;
+ }
+
+ /** Set or, with null, remove the link's /Contents. Throws for a page whose save cannot write it, or an unknown annotation. */
+ setLinkContents(annotation: number, contents: string | null): void {
+ const link = this.editableLink(annotation);
+ if (contents === link.contents) this.linkContentsEdits.delete(annotation);
+ else this.linkContentsEdits.set(annotation, contents);
+ }
+
+ /** Changes to the page's link annotations, for the save. */
+ linkEdits(): LinkEdit[] {
+ return this.links().flatMap(({ annotation }) => {
+ const held = this.sessionLinkHolder(annotation) !== null;
+ const described = this.linkContentsEdits.has(annotation);
+ if (!held && !described) return [];
+ return [
+ {
+ annotation,
+ ...(held && { mcid: this.linkHolders.get(annotation)! }),
+ ...(described && {
+ contents: this.linkContentsEdits.get(annotation)!,
+ }),
+ },
+ ];
+ });
+ }
+
+ private sessionLinkHolder(annotation: number): StructureElement | null {
+ const mcid = this.linkHolders.get(annotation);
+ const el = mcid === undefined ? null : this.element(mcid);
+ return el?.type === "Link" ? el : null;
+ }
+
+ private editableLink(annotation: number): LinkAnnotation {
+ if (this.readOnly) throw new Error(`The page is ${this.readOnly}`);
+ return this.knownLink(annotation);
+ }
+
+ private knownLink(annotation: number): LinkAnnotation {
+ const link = this.linkAnnotations.get(annotation);
+ if (!link) throw new Error(`No link annotation ${annotation} on the page`);
+ return link;
+ }
}
function addedKey(mcid: number): string {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/parentTreeEntries.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/parentTreeEntries.ts
new file mode 100644
index 0000000000..ed20862511
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/parentTreeEntries.ts
@@ -0,0 +1,116 @@
+/**
+ * Adding entries to a structure tree's ParentTree (ISO 32000-1 14.7.4.4), for
+ * the passes that give a page or an annotation a key of its own.
+ */
+import {
+ arrayItems,
+ setDictEntry,
+ type RawPdf,
+} from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+
+const MAX_TREE_DEPTH = 32;
+
+/**
+ * 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.
+ */
+export 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.
+ */
+export 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/addElements.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addElements.ts
index 83b5d7a345..dddd5c0e37 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addElements.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addElements.ts
@@ -33,6 +33,12 @@ export interface NewElement {
* content when null or unowned (see StructureNodes.placementSibling).
*/
after: number | null;
+ /**
+ * True when text was cut out of it, which cutElements writes once it is in
+ * the tree. The cut may have taken all of it, so its MCID need not be on
+ * the page.
+ */
+ cutFrom?: boolean;
}
interface Placement {
@@ -73,7 +79,8 @@ export async function addElements(
}
if (!sites.has(pageNum)) sites.set(pageNum, pageSites(pdf, pageNum));
const read = await sites.get(pageNum)!;
- if (!read?.sites.some((site) => site.mcid === element.mcid)) {
+ const carried = read?.sites.some((site) => site.mcid === element.mcid);
+ if (!carried && !element.cutFrom) {
failed.set(index, "the page's content does not carry its MCID");
continue;
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyAnnotationEdits.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyAnnotationEdits.ts
new file mode 100644
index 0000000000..c8e6f95ee8
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyAnnotationEdits.ts
@@ -0,0 +1,271 @@
+/**
+ * Give annotations their place in the structure tree and their /Contents, as
+ * an appended revision. An element holds an annotation through an OBJR kid,
+ * and the annotation names it back through /StructParent and that key's
+ * ParentTree entry (ISO 32000-1 14.7.4.4). PDF/UA-1 7.18 also wants the
+ * annotation's /Contents, and /Tabs /S on its page.
+ */
+import { elementKids } from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";
+import {
+ addTreeEntries,
+ firstFreeKey,
+} from "@editor/tools/pdfTextEditor/pdfdoc/parentTreeEntries";
+import {
+ elementOwning,
+ withTextEntry,
+} from "@editor/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits";
+import {
+ RawPdf,
+ arrayItems,
+ indirectRef,
+ referencedObject,
+ setDictEntry,
+} from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import {
+ appendRevision,
+ plainObject,
+ unusedObjectNumber,
+} from "@editor/tools/pdfTextEditor/pdfdoc/revision";
+
+/** A change to one annotation on a page. */
+export interface AnnotationEdit {
+ pageIndex: number;
+ /** The annotation's object number; the page's /Annots must reference it. */
+ annotation: number;
+ /**
+ * Give it to the element owning this MCID on the page, as the structure
+ * edits leave the tree; absent leaves it where it is.
+ */
+ mcid?: number;
+ /** The new /Contents; null removes it, absent leaves it. */
+ contents?: string | null;
+}
+
+export interface AnnotationEditFailure {
+ edit: AnnotationEdit;
+ reason: string;
+}
+
+/** Thrown with every edit that could not be written; none of them were. */
+export class AnnotationEditError extends Error {
+ constructor(readonly failures: AnnotationEditFailure[]) {
+ super(
+ `Could not write ${failures.length} annotation edit(s): ` +
+ failures
+ .map(
+ (f) =>
+ `page ${f.edit.pageIndex + 1} annotation ${f.edit.annotation}: ${f.reason}`,
+ )
+ .join("; "),
+ );
+ this.name = "AnnotationEditError";
+ }
+}
+
+/**
+ * Apply `edits` to `bytes`, all or none; later edits to the same annotation
+ * win. Runs after applyStructureEdits, whose elements an edit's MCID may
+ * name. Giving an annotation to the element that already holds it changes
+ * nothing. Throws AnnotationEditError when any edit cannot be written.
+ */
+export async function applyAnnotationEdits(
+ bytes: Uint8Array,
+ edits: readonly AnnotationEdit[],
+): Promise<Uint8Array> {
+ if (edits.length === 0) return bytes;
+ const fail = (reason: string) =>
+ new AnnotationEditError(edits.map((edit) => ({ edit, reason })));
+
+ const pdf = await RawPdf.parse(bytes);
+ if (!pdf) throw fail("the file could not be read");
+ // Strings in an encrypted file must be encrypted too, which this cannot do.
+ if (pdf.encrypted) throw fail("the file is encrypted");
+ const keys = edits.some((edit) => edit.mcid !== undefined)
+ ? ParentKeys.open(pdf)
+ : null;
+ if (typeof keys === "string") throw fail(keys);
+
+ const bodies = new Map<number, string>();
+ const body = (num: number) => bodies.get(num) ?? pdf.objectBody(num);
+ const holders = new Map<number, number>();
+ const failures: AnnotationEditFailure[] = [];
+ for (const edit of edits) {
+ const pageNum = pdf.pageNumberAt(edit.pageIndex);
+ const page = pageNum === null ? null : body(pageNum);
+ if (pageNum === null || !page) {
+ failures.push({ edit, reason: "no such page" });
+ continue;
+ }
+ if (!pageAnnotations(pdf, page).includes(edit.annotation)) {
+ failures.push({
+ edit,
+ reason: "the page's /Annots does not reference it",
+ });
+ continue;
+ }
+ let annotation = body(edit.annotation);
+ if (!annotation || pdf.dictName(annotation, "Subtype") === null) {
+ failures.push({ edit, reason: "it is not an annotation" });
+ continue;
+ }
+ if (edit.contents !== undefined) {
+ annotation = withTextEntry(annotation, "Contents", edit.contents);
+ }
+ if (annotation !== null && keys && edit.mcid !== undefined) {
+ const element = elementOwning(pdf, keys.treeRoot, {
+ pageIndex: edit.pageIndex,
+ mcid: edit.mcid,
+ });
+ if (typeof element === "string") {
+ failures.push({ edit, reason: element });
+ continue;
+ }
+ const holder =
+ holders.get(edit.annotation) ??
+ holderOf(pdf, keys.treeRoot, annotation);
+ if (holder !== null && holder !== element) {
+ failures.push({ edit, reason: "another element holds it" });
+ continue;
+ }
+ if (holder === null) {
+ const held = withAnnotationKid(
+ pdf,
+ body(element) ?? "",
+ edit.annotation,
+ pageNum,
+ );
+ if (!held) {
+ failures.push({ edit, reason: "its element's kids cannot be read" });
+ continue;
+ }
+ bodies.set(element, held);
+ holders.set(edit.annotation, element);
+ const key = keys.add(element);
+ annotation = setDictEntry(annotation, "StructParent", String(key));
+ if (pdf.dictName(page, "Tabs") !== "S") {
+ bodies.set(pageNum, setDictEntry(page, "Tabs", "/S") ?? page);
+ }
+ }
+ }
+ if (annotation === null) {
+ failures.push({ edit, reason: "it is not a dictionary" });
+ continue;
+ }
+ bodies.set(edit.annotation, annotation);
+ }
+ if (failures.length > 0) throw new AnnotationEditError(failures);
+ if (keys && !keys.write(bodies)) {
+ throw fail("the ParentTree cannot be extended");
+ }
+
+ const out = appendRevision(
+ pdf,
+ [...bodies].map(([num, written]) => ({ num, body: plainObject(written) })),
+ );
+ if (!out)
+ throw fail("the file's cross-reference structure cannot be extended");
+ return out;
+}
+
+/** The object numbers of the annotations the page's /Annots references. */
+function pageAnnotations(pdf: RawPdf, page: string): number[] {
+ const annots = pdf.resolve(page, "Annots")?.trim();
+ const items = annots ? arrayItems(annots) : null;
+ return (items ?? [])
+ .map((item) => referencedObject(item.text))
+ .filter((num) => num !== null);
+}
+
+/** The element the annotation's /StructParent entry names; null when it has none. */
+function holderOf(
+ pdf: RawPdf,
+ treeRoot: number,
+ annotation: string,
+): number | null {
+ const key = pdf.dictInt(annotation, "StructParent");
+ const entry =
+ key === null ? null : pdf.numberTreeEntry(treeRoot, "ParentTree", key);
+ return entry ? referencedObject(entry.span.text) : null;
+}
+
+/**
+ * The element's body with an OBJR for the annotation last among its /K, or
+ * as it is when one is already there. Null when its /K cannot be read.
+ */
+function withAnnotationKid(
+ pdf: RawPdf,
+ element: string,
+ annotation: number,
+ pageNum: number,
+): string | null {
+ const kids = elementKids(pdf, element);
+ if (!kids) return null;
+ if (kids.some((kid) => objrTarget(pdf, kid) === annotation)) return element;
+ kids.push(
+ `<< /Type /OBJR /Obj ${indirectRef(pdf, annotation)} /Pg ${indirectRef(pdf, pageNum)} >>`,
+ );
+ return setDictEntry(element, "K", `[${kids.join(" ")}]`);
+}
+
+/** The object an OBJR kid references; null for any other kid. */
+function objrTarget(pdf: RawPdf, kid: string): number | null {
+ const ref = referencedObject(kid);
+ const dict = ref === null ? kid : pdf.objectBody(ref);
+ if (!dict?.trimStart().startsWith("<<")) return null;
+ return pdf.dictName(dict, "Type") === "OBJR"
+ ? pdf.dictRef(dict, "Obj")
+ : null;
+}
+
+/** The ParentTree keys a save gives annotations, from the first one free. */
+class ParentKeys {
+ private readonly entries: string[] = [];
+
+ private constructor(
+ private readonly pdf: RawPdf,
+ readonly treeRoot: number,
+ private readonly rootBody: string,
+ private next: number,
+ ) {}
+
+ /** The keys from the file's first free one, or why there are none. */
+ static open(pdf: RawPdf): ParentKeys | string {
+ 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 "the file has no structure tree";
+ const next = firstFreeKey(pdf, rootBody);
+ if (next === null) return "the ParentTree cannot be read";
+ return new ParentKeys(pdf, treeRoot, rootBody, next);
+ }
+
+ /** A new key, whose ParentTree entry names `element`. */
+ add(element: number): number {
+ const key = this.next++;
+ this.entries.push(`${key} ${indirectRef(this.pdf, element)}`);
+ return key;
+ }
+
+ /** Write the new entries to `bodies`; false when the tree cannot take them. */
+ write(bodies: Map<number, string>): boolean {
+ if (this.entries.length === 0) return true;
+ const allocate = (written: string): number => {
+ const num = unusedObjectNumber(this.pdf, bodies);
+ bodies.set(num, written);
+ return num;
+ };
+ const extended = addTreeEntries(
+ this.pdf,
+ this.rootBody,
+ this.entries,
+ bodies,
+ allocate,
+ );
+ const root = extended
+ ? setDictEntry(extended, "ParentTreeNextKey", String(this.next))
+ : null;
+ if (!root) return false;
+ bodies.set(this.treeRoot, root);
+ return true;
+ }
+}
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 82fab3f7d8..8c845d5a7c 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts
@@ -27,7 +27,10 @@ import {
type ArtifactKind,
type Furniture,
} from "@editor/tools/pdfTextEditor/model/artifactKind";
-import type { ContentCut } from "@editor/tools/pdfTextEditor/model/PageStructure";
+import {
+ givenMcids,
+ type ContentCut,
+} from "@editor/tools/pdfTextEditor/model/PageStructure";
import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";
/** A change to the structure element that owns marked content `mcid` on a page. */
@@ -127,9 +130,10 @@ export async function applyStructureEdits(
const unwraps: { edit: StructureEdit; owner: number }[] = [];
const added = edits.filter((edit) => edit.newElement);
const cuts = edits.filter((edit) => edit.cut);
+ const cutsFromAdded = cutsFromAddedElements(added, cuts);
for (const edit of edits) {
if (edit.newElement || edit.cut) continue;
- const owner = elementFor(pdf, treeRoot, edit);
+ const owner = elementOwning(pdf, treeRoot, edit);
if (typeof owner === "string") {
failures.push({ edit, reason: owner });
continue;
@@ -168,23 +172,27 @@ export async function applyStructureEdits(
for (const [index, reason] of kept) {
failures.push({ edit: unwraps[index].edit, reason });
}
- // After the retags, which address elements by the MCIDs a cut can take
- // from them, and before the added elements, which may be placed beside a cut.
- const uncut = await cutElements(
- pdf,
- cuts.map((edit) => ({
- ...edit,
- type: edit.cut!.type,
- alt: edit.alt ?? null,
- lang: edit.lang ?? null,
- cut: edit.cut!,
- })),
- bodies,
- parentTree,
- );
- for (const [index, reason] of uncut) {
- failures.push({ edit: cuts[index], reason });
- }
+ const writeCuts = async (written: readonly StructureEdit[]) => {
+ const uncut = await cutElements(
+ pdf,
+ written.map((edit) => ({
+ ...edit,
+ type: edit.cut!.type,
+ alt: edit.alt ?? null,
+ lang: edit.lang ?? null,
+ cut: edit.cut!,
+ })),
+ bodies,
+ parentTree,
+ );
+ for (const [index, reason] of uncut) {
+ failures.push({ edit: written[index], reason });
+ }
+ };
+ // Cuts from the file's elements: after the retags, which address elements
+ // by the MCIDs a cut can take from them, and before the added elements,
+ // which may be placed beside a cut.
+ await writeCuts(cuts.filter((edit) => !cutsFromAdded.has(edit)));
// Before the decorative marks, so an element placed beside one they drop
// keeps its place among the kids that remain.
const unplaced = await addElements(
@@ -196,6 +204,10 @@ export async function applyStructureEdits(
...edit.newElement!,
alt: edit.alt ?? null,
lang: edit.lang ?? null,
+ cutFrom: [...cutsFromAdded].some(
+ (cut) =>
+ cut.pageIndex === edit.pageIndex && cut.cut!.from[0] === edit.mcid,
+ ),
})),
bodies,
parentTree,
@@ -203,6 +215,7 @@ export async function applyStructureEdits(
for (const [index, reason] of unplaced) {
failures.push({ edit: added[index], reason });
}
+ await writeCuts([...cutsFromAdded]);
const { streams, failed } = await markDecorative(
pdf,
new Map(
@@ -229,6 +242,28 @@ export async function applyStructureEdits(
return out;
}
+/**
+ * The cuts taking text from an element the save adds, directly or through
+ * the element or the parts an earlier such cut made, in the order made: none
+ * can be written until that element is in the tree.
+ */
+function cutsFromAddedElements(
+ added: readonly StructureEdit[],
+ cuts: readonly StructureEdit[],
+): Set<StructureEdit> {
+ const key = (pageIndex: number, mcid: number) => `${pageIndex}:${mcid}`;
+ const owners = new Set(added.map((edit) => key(edit.pageIndex, edit.mcid)));
+ const late = new Set<StructureEdit>();
+ for (const edit of cuts) {
+ if (!owners.has(key(edit.pageIndex, edit.cut!.from[0]))) continue;
+ late.add(edit);
+ for (const mcid of [edit.mcid, ...givenMcids(edit.cut!)]) {
+ owners.add(key(edit.pageIndex, mcid));
+ }
+ }
+ return late;
+}
+
/** The kind of artifact the last of an element's edits makes it; null for a plain one. */
function artifactKindOf(edits: readonly StructureEdit[]): ArtifactKind | null {
const furniture = edits.at(-1)?.furniture;
@@ -261,7 +296,7 @@ function edited(
}
/** The body with text-string entry `key` set to `value`, or removed for null. */
-function withTextEntry(
+export function withTextEntry(
body: string,
key: string,
value: string | null,
@@ -271,13 +306,13 @@ function withTextEntry(
: setDictEntry(body, key, encodeTextString(value));
}
-/** The structure element's object number, or why it cannot be found. */
-function elementFor(
+/** The object number of the element owning MCID `mcid` on the page, or why it cannot be found. */
+export function elementOwning(
pdf: RawPdf,
treeRoot: number,
- edit: StructureEdit,
+ { pageIndex, mcid }: { pageIndex: number; mcid: number },
): number | string {
- const pageNum = pdf.pageNumberAt(edit.pageIndex);
+ const pageNum = pdf.pageNumberAt(pageIndex);
const page = pageNum === null ? null : pdf.objectBody(pageNum);
if (!page) return "no such page";
const key = pdf.dictInt(page, "StructParents");
@@ -287,7 +322,7 @@ function elementFor(
if (!tree) return "the ParentTree has no entry for the page";
if (!tree.items) return "the page's ParentTree entry is not an array";
- const num = referencedObject(tree.items[edit.mcid]?.text ?? "");
+ const num = referencedObject(tree.items[mcid]?.text ?? "");
if (num === null) return "no structure element owns this MCID";
const body = pdf.objectBody(num);
if (!body || pdf.dictName(body, "S") === null) {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/ensureStructureTree.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/ensureStructureTree.ts
index 425a605efd..f052d1011e 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/ensureStructureTree.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/ensureStructureTree.ts
@@ -5,7 +5,10 @@
* ParentTree array on each page that lacks one.
*/
import {
- arrayItems,
+ addTreeEntries,
+ firstFreeKey,
+} from "@editor/tools/pdfTextEditor/pdfdoc/parentTreeEntries";
+import {
indirectRef,
setDictEntry,
type RawPdf,
@@ -16,8 +19,6 @@ import {
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
@@ -116,108 +117,3 @@ function pagesToKey(
}
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/readFileStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
index 76d8266b2f..ce3ebff631 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
@@ -1,3 +1,4 @@
+import type { LinkAnnotation } from "@editor/tools/pdfTextEditor/model/LinkAnnotation";
import type { StructureElement } from "@editor/tools/pdfTextEditor/model/PageStructure";
import type { StructureRole } from "@editor/tools/pdfTextEditor/model/structureTypes";
import {
@@ -12,6 +13,7 @@ import {
StructureNodes,
type ElementNode,
} from "@editor/tools/pdfTextEditor/pdfdoc/structureNodes";
+import { readLinks } from "@editor/tools/pdfTextEditor/pdfdoc/readLinks";
import { decodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString";
import { isMarked } from "@editor/tools/pdfTextEditor/pdfdoc/passes/markTagged";
@@ -56,6 +58,8 @@ export interface FileStructure {
blocks: FileBlock[];
/** By element key, for every element a page or block names. */
languages: Map<string, ElementLanguage>;
+ /** The link annotations the save can give an element, by page index (see readLinks). */
+ links: Map<number, LinkAnnotation[]>;
/** Whether the file has a /StructTreeRoot at all. */
hasTree: boolean;
/** Whether the catalog declares the file tagged (/MarkInfo /Marked). */
@@ -82,6 +86,7 @@ export async function readFileStructure(
pages: new Map(),
blocks: [],
languages: new Map(),
+ links: readLinks(pdf, null),
hasTree: false,
marked: isMarked(pdf, catalog),
};
@@ -141,6 +146,7 @@ export async function readFileStructure(
pages: byPage,
blocks,
languages,
+ links: readLinks(pdf, treeRoot),
hasTree: true,
marked: isMarked(pdf, catalog),
};
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readLinks.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readLinks.ts
new file mode 100644
index 0000000000..9537bb5bf1
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readLinks.ts
@@ -0,0 +1,105 @@
+import type {
+ LinkAnnotation,
+ PageArea,
+} from "@editor/tools/pdfTextEditor/model/LinkAnnotation";
+import {
+ arrayItems,
+ referencedObject,
+ type RawPdf,
+} from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import { decodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString";
+
+/** Bounds a pathological page; PdfiumAnnotationReader stops at the same count. */
+const MAX_ANNOTS = 2000;
+
+/**
+ * The link annotations of each page, by page index, that the save can give an
+ * element: those the page's /Annots references, as an OBJR's /Obj must
+ * (ISO 32000-1 14.7.4.3). `treeRoot` resolves the element each is given to;
+ * null for a file with no structure tree. Pages with none are left out.
+ */
+export function readLinks(
+ pdf: RawPdf,
+ treeRoot: number | null,
+): Map<number, LinkAnnotation[]> {
+ const out = new Map<number, LinkAnnotation[]>();
+ pdf.pageNumbers().forEach((pageNum, pageIndex) => {
+ const page = pdf.objectBody(pageNum);
+ const annots = page ? pdf.resolve(page, "Annots")?.trim() : null;
+ const refs = (annots ? arrayItems(annots) : null) ?? [];
+ const links = refs.slice(0, MAX_ANNOTS).flatMap((ref) => {
+ const num = referencedObject(ref.text);
+ const link = num === null ? null : readLink(pdf, num, treeRoot);
+ return link ? [link] : [];
+ });
+ if (links.length > 0) out.set(pageIndex, links);
+ });
+ return out;
+}
+
+function readLink(
+ pdf: RawPdf,
+ num: number,
+ treeRoot: number | null,
+): LinkAnnotation | null {
+ const body = pdf.objectBody(num);
+ if (!body || pdf.dictName(body, "Subtype") !== "Link") return null;
+ const quads = numbers(pdf.resolve(body, "QuadPoints"));
+ const rect = numbers(pdf.resolve(body, "Rect"));
+ const fromQuads = quadAreas(quads ?? []);
+ const areas = fromQuads.length > 0 ? fromQuads : quadAreas(rectQuad(rect));
+ if (areas.length === 0) return null;
+ const contents = pdf.resolve(body, "Contents");
+ return {
+ annotation: num,
+ areas,
+ contents: contents === null ? null : decodeTextString(contents.trim()),
+ holder: holderKey(pdf, body, treeRoot),
+ };
+}
+
+/** A /Rect as the one quadrilateral /QuadPoints would give it. */
+function rectQuad(rect: number[] | null): number[] {
+ if (rect?.length !== 4) return [];
+ const [x1, y1, x2, y2] = rect;
+ return [x1, y1, x2, y1, x1, y2, x2, y2];
+}
+
+/**
+ * The box around each quadrilateral: its points' order varies between
+ * producers, and a box is enough to find the text under it.
+ */
+function quadAreas(values: readonly number[]): PageArea[] {
+ const areas: PageArea[] = [];
+ for (let i = 0; i + 8 <= values.length; i += 8) {
+ const xs = [values[i], values[i + 2], values[i + 4], values[i + 6]];
+ const ys = [values[i + 1], values[i + 3], values[i + 5], values[i + 7]];
+ const area = {
+ left: Math.min(...xs),
+ bottom: Math.min(...ys),
+ right: Math.max(...xs),
+ top: Math.max(...ys),
+ };
+ if (area.right > area.left && area.top > area.bottom) areas.push(area);
+ }
+ return areas;
+}
+
+/** An array of numbers; null when the value is not one. */
+function numbers(value: string | null): number[] | null {
+ const items = value ? arrayItems(value.trim()) : null;
+ const read = items?.map((item) => Number(item.text));
+ return read?.every(Number.isFinite) ? read : null;
+}
+
+function holderKey(
+ pdf: RawPdf,
+ body: string,
+ treeRoot: number | null,
+): string | null {
+ const key = pdf.dictInt(body, "StructParent");
+ if (treeRoot === null || key === null) return null;
+ const entry = pdf.numberTreeEntry(treeRoot, "ParentTree", key);
+ const holder = entry ? referencedObject(entry.span.text) : null;
+ return holder === null ? null : String(holder);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts
index 75dd30001a..feb70264c4 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts
@@ -1,5 +1,9 @@
import i18n from "i18next";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import {
+ AnnotationEditError,
+ applyAnnotationEdits,
+} from "@editor/tools/pdfTextEditor/pdfdoc/passes/applyAnnotationEdits";
import {
StructureEditError,
applyStructureEdits,
@@ -28,6 +32,7 @@ export async function exportToBlob(
filename: string;
}> {
const structureEdits = doc.structureEdits();
+ const annotationEdits = doc.annotationEdits();
const documentLanguage = doc.documentLanguageEdit();
// A signed document is appended to rather than rewritten, so the bytes the
// signature covers are still there and still verify for their revision.
@@ -40,6 +45,7 @@ export async function exportToBlob(
// ones by up to 35% - for no edit at all.
if (
structureEdits.length === 0 &&
+ annotationEdits.length === 0 &&
documentLanguage === undefined &&
!doc.markedTaggedChanged()
) {
@@ -66,6 +72,13 @@ export async function exportToBlob(
if (!(err instanceof StructureEditError)) throw err;
throw accessibilitySaveFailed(err);
}
+ // After the structure edits, which add the elements links are given to.
+ try {
+ bytes = await applyAnnotationEdits(bytes, annotationEdits);
+ } catch (err) {
+ if (!(err instanceof AnnotationEditError)) throw err;
+ throw accessibilitySaveFailed(err);
+ }
if (documentLanguage !== undefined) {
try {
bytes = await setDocumentLanguage(bytes, documentLanguage);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.ts
index ee7253d072..46e82a2ad7 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.ts
@@ -200,6 +200,16 @@ export interface InnerTag extends InnerOptions {
language: TextLanguage;
/** False when the save cannot write the page's tags. */
languageEditable: boolean;
+ /** The link annotations it holds, and their description; null when it holds none. */
+ link: InnerTagLink | null;
+}
+
+export interface InnerTagLink {
+ annotations: number[];
+ /** The first annotation's /Contents, as the session has it. */
+ description: string | null;
+ /** False when the save cannot write the page's tags. */
+ editable: boolean;
}
/** The run's inner tags in reading order, as the session has them. */
@@ -219,7 +229,16 @@ export function innerTags(
const options = structure.innerOptions(element.key);
const text = run.text.slice(start, end);
const language = doc.innerLanguage(run.pageIndex, run.mcid!, element.key);
- const languageEditable = structure.readOnly === null;
+ const editable = structure.readOnly === null;
+ const annotations = structure.linksHeldBy(element.key);
+ const link =
+ annotations.length > 0
+ ? {
+ annotations,
+ description: structure.linkContents(annotations[0]),
+ editable,
+ }
+ : null;
return [
{
key: element.key,
@@ -228,7 +247,8 @@ export function innerTags(
end,
role,
language,
- languageEditable,
+ languageEditable: editable,
+ link,
...options,
},
];
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.ts
index 237ea6e4a3..b83299c83c 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.ts
@@ -90,6 +90,7 @@ export const SCRATCH = {
splitOriginY: key(),
splitFontSize: key(),
splitStrokeWidth: key(),
+ linkCharBox: key(),
} as const;
/** Structural minimum: any wrapper that exposes PDFium's wasm allocator. */