Skip to content

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

Add support for editing text accessibility tags in Text Editor (#8670)

James Bruntonf80c69287847
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index bf04ce3b8e..49b0a8ecf6 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -7419,19 +7419,29 @@ x = "X"
y = "Y"
[pdfTextEditor.inspector.accessibility]
+addTag = "Add tag"
+artifactText = "Decorative"
cannotChange = "This image's accessibility can't be changed."
+cannotRetag = "This text's tag can't be changed."
+customTag = "{{role}} (custom tag)"
decorativeInfo = "Screen readers skip decorative images. Use it for borders, backgrounds and other images that carry no information."
decorativeLabel = "Decorative image"
description = "Image description"
descriptionInfo = "Screen readers read this out in place of the image."
encrypted = "Tags can't be edited in an encrypted file"
heading = "Accessibility"
+innerTagLabel = "Tag {{number}}"
+innerTags = "Tags in this text"
missingDescriptions = "Missing descriptions"
mixedContent = "Figure includes other content"
needsDescriptionBadge = "No description"
nextImage = "Next image"
notFigure = "Tagged as part of the text"
+removeTag = "Remove tag"
saveFailed = "Your accessibility changes couldn't be saved, so the file wasn't saved. Undo them and try again."
+selectedText = "Selected text"
+tagLabel = "Tag"
+unknownTag = "Can't be read here"
unreadable = "This file's tags can't be edited"
untaggableImages = "Can't be tagged here"
untaggedBadge = "Not tagged"
@@ -7439,6 +7449,64 @@ untaggedDocument = "Document has no tags"
untaggedImage = "Can't be tagged here"
untaggedImages = "Untagged images"
+[pdfTextEditor.inspector.accessibility.outline]
+empty = "Heading with no text"
+firstNotH1 = "First heading should be Heading 1"
+heading = "Headings"
+mixedNumbering = "Mixes numbered and unnumbered headings"
+none = "No headings"
+onPage = "Heading on page {{page}}"
+problems = "Heading problems"
+skippedLevel = "Skips a level after Heading {{previous}}"
+
+[pdfTextEditor.inspector.accessibility.tagName]
+annotation = "Annotation"
+article = "Article"
+artifact = "Artifact"
+aside = "Aside"
+bibliographyEntry = "Bibliography entry"
+blockQuote = "Block quote"
+caption = "Caption"
+code = "Code"
+contents = "Table of contents"
+contentsEntry = "Contents entry"
+division = "Division"
+document = "Document"
+documentFragment = "Document fragment"
+emphasis = "Emphasis"
+figure = "Figure"
+footnote = "Footnote"
+form = "Form field"
+formula = "Formula"
+heading = "Heading"
+headingLevel = "Heading {{level}}"
+index = "Index"
+label = "Label"
+link = "Link"
+list = "List"
+listItem = "List item"
+listItemBody = "List item body"
+note = "Note"
+paragraph = "Paragraph"
+part = "Part"
+quote = "Quote"
+reference = "Reference"
+ruby = "Ruby"
+rubyBase = "Ruby base"
+rubyPunctuation = "Ruby punctuation"
+rubyText = "Ruby text"
+section = "Section"
+span = "Span"
+strong = "Strong emphasis"
+table = "Table"
+tableBody = "Table body"
+tableCell = "Table cell"
+tableFoot = "Table foot"
+tableHead = "Table head"
+tableHeader = "Table header"
+tableRow = "Table row"
+title = "Title"
+
[pdfTextEditor.mobile]
actions = "Editor actions"
addImage = "Image"
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 da1928d822..cea6b0ac41 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
@@ -1,9 +1,15 @@
import process from "node:process";
-// One-off script: generate `tagged-sample.pdf`, a tagged page whose text, image
-// and page number are each tied into the structure tree the way a word
-// processor's accessible export ties them: a heading (MCID 0), a two-line
-// paragraph in ONE marked-content sequence (MCID 1), a described figure
-// (MCID 2), and a page number marked as a pagination artifact.
+// One-off script: generate `tagged-sample.pdf`, a two-page quarterly report
+// tagged the way a word processor's accessible export tags one.
+//
+// Page 1 is what the structure-editing tests assert on, so keep it as is: a
+// heading (MCID 0), a two-line paragraph in ONE marked-content sequence
+// (MCID 1), a described figure (MCID 2), and a page number artifact.
+//
+// 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.
//
// Run with: npx tsx generate-tagged-sample.mts
import { writeFileSync } from "node:fs";
@@ -13,26 +19,18 @@ import {
PDFDocument,
PDFName,
PDFNumber,
+ type PDFFont,
type PDFObject,
+ type PDFPage,
PDFRawStream,
type PDFRef,
PDFString,
StandardFonts,
+ type PDFContext,
} from "@cantoo/pdf-lib";
const __dirname = dirname(fileURLToPath(import.meta.url));
-const CONTENT = [
- "/H1 <</MCID 0>> BDC BT /F2 28 Tf 72 700 Td (Quarterly report) Tj ET EMC",
- "/P <</MCID 1>> BDC",
- "BT /F1 14 Tf 72 660 Td (Revenue grew in every region this quarter,) Tj ET",
- "BT /F1 14 Tf 72 642 Td (led by demand for the new product line.) Tj ET",
- "EMC",
- "/Figure <</MCID 2>> BDC q 120 0 0 80 72 520 cm /Im1 Do Q EMC",
- "/Artifact <</Type /Pagination>> BDC BT /F1 10 Tf 300 40 Td (Page 1) Tj ET EMC",
- "",
-].join("\n");
-
const CHART_WIDTH = 120;
const CHART_HEIGHT = 80;
/** Revenue for four regions, as bar heights in pixels. */
@@ -62,15 +60,205 @@ function barChartPixels(): Uint8Array {
return pixels;
}
+interface Font {
+ /** The page's resource name for it. */
+ name: string;
+ pdf: PDFFont;
+}
+
+function show(font: Font, size: number, x: number, y: number, text: string) {
+ const encoded = font.pdf.encodeText(text).toString();
+ 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;
+
+interface PendingElement {
+ ref: PDFRef;
+ type: string;
+ parent: PDFRef;
+ page: PDFRef | null;
+ kids: Kid[];
+ extra: Record<string, PDFObject>;
+ attached: boolean;
+}
+
+/**
+ * Builds the structure tree alongside each page's content, so an element's
+ * /K, the content's MCIDs and the ParentTree cannot disagree.
+ */
+class StructureBuilder {
+ readonly rootRef: PDFRef;
+ private readonly elements: PendingElement[] = [];
+ private readonly byRef = new Map<PDFRef, PendingElement>();
+ /** Per page, in StructParents order: the element owning each MCID. */
+ private readonly owners: PDFRef[][] = [];
+
+ constructor(private readonly ctx: PDFContext) {
+ this.rootRef = ctx.nextRef();
+ }
+
+ element(
+ type: string,
+ parent: PDFRef,
+ page: PDFPage | null,
+ extra: Record<string, PDFObject> = {},
+ ): PDFRef {
+ const ref = this.ctx.nextRef();
+ const pending = {
+ ref,
+ type,
+ parent,
+ page: page?.ref ?? null,
+ kids: [],
+ extra,
+ attached: false,
+ };
+ this.elements.push(pending);
+ this.byRef.set(ref, pending);
+ return ref;
+ }
+
+ /**
+ * Joins the element to its parent's /K when its first content is drawn, not
+ * when it is created, so a Link made before its paragraph's first words
+ * still reads after them.
+ */
+ private attach(el: PendingElement): void {
+ if (el.attached) return;
+ el.attached = true;
+ const parent = this.byRef.get(el.parent);
+ if (!parent) return;
+ this.attach(parent);
+ parent.kids.push(el.ref);
+ }
+
+ /** Start a page's content; its StructParents key is its index here. */
+ page(page: PDFPage): TaggedContent {
+ const owners: PDFRef[] = [];
+ page.node.set(
+ PDFName.of("StructParents"),
+ PDFNumber.of(this.owners.length),
+ );
+ this.owners.push(owners);
+ return new TaggedContent(owners, (owner, mcid) => {
+ const el = this.byRef.get(owner)!;
+ this.attach(el);
+ el.kids.push(mcid);
+ });
+ }
+
+ finish(topLevel: PDFRef): void {
+ const ctx = this.ctx;
+ for (const el of this.elements) {
+ ctx.assign(
+ el.ref,
+ ctx.obj({
+ Type: "StructElem",
+ S: el.type,
+ P: el.parent,
+ ...(el.page ? { Pg: el.page } : {}),
+ K: el.kids.length === 1 ? el.kids[0] : el.kids,
+ ...el.extra,
+ }),
+ );
+ }
+ const nums: PDFObject[] = [];
+ this.owners.forEach((owners, key) => {
+ nums.push(PDFNumber.of(key), ctx.obj(owners));
+ });
+ ctx.assign(
+ this.rootRef,
+ ctx.obj({
+ Type: "StructTreeRoot",
+ K: topLevel,
+ ParentTree: ctx.register(ctx.obj({ Nums: nums })),
+ ParentTreeNextKey: this.owners.length,
+ }),
+ );
+ }
+}
+
+/** One page's content stream, marking each tagged piece with the next MCID. */
+class TaggedContent {
+ private readonly ops: string[] = [];
+
+ constructor(
+ private readonly owners: PDFRef[],
+ private readonly own: (owner: PDFRef, mcid: number) => void,
+ ) {}
+
+ /** `ops` as one marked-content sequence of `owner`, tagged `tag`. */
+ mark(tag: string, owner: PDFRef, ops: string[]): void {
+ const mcid = this.owners.length;
+ this.owners.push(owner);
+ this.own(owner, mcid);
+ this.ops.push(`/${tag} <</MCID ${mcid}>> BDC`, ...ops, "EMC");
+ }
+
+ /**
+ * One line of pieces set side by side from `x`, each its own sequence: how
+ * an inline element sits inside its paragraph's line.
+ */
+ line(
+ x: number,
+ y: number,
+ size: number,
+ pieces: { tag: string; owner: PDFRef; font: Font; text: string }[],
+ ): void {
+ let at = x;
+ for (const piece of pieces) {
+ this.mark(piece.tag, piece.owner, [
+ show(piece.font, size, at, y, piece.text),
+ ]);
+ at += piece.font.pdf.widthOfTextAtSize(piece.text, size);
+ }
+ }
+
+ artifact(properties: string, ops: string[]): void {
+ this.ops.push(`/Artifact <<${properties}>> BDC`, ...ops, "EMC");
+ }
+
+ untagged(ops: string[]): void {
+ this.ops.push(...ops);
+ }
+
+ writeTo(ctx: PDFContext, page: PDFPage): void {
+ const bytes = new TextEncoder().encode([...this.ops, ""].join("\n"));
+ page.node.set(
+ PDFName.of("Contents"),
+ ctx.register(PDFRawStream.of(ctx.obj({ Length: bytes.length }), bytes)),
+ );
+ }
+}
+
async function main() {
const doc = await PDFDocument.create();
const ctx = doc.context;
- const regular = await doc.embedFont(StandardFonts.Helvetica);
- const bold = await doc.embedFont(StandardFonts.HelveticaBold);
- const page = doc.addPage([612, 792]);
- page.node.setFontDictionary(PDFName.of("F1"), regular.ref);
- page.node.setFontDictionary(PDFName.of("F2"), bold.ref);
+ const regular: Font = {
+ name: "F1",
+ pdf: await doc.embedFont(StandardFonts.Helvetica),
+ };
+ const bold: Font = {
+ name: "F2",
+ pdf: await doc.embedFont(StandardFonts.HelveticaBold),
+ };
+ const mono: Font = {
+ name: "F3",
+ pdf: await doc.embedFont(StandardFonts.Courier),
+ };
+ const italic: Font = {
+ name: "F4",
+ pdf: await doc.embedFont(StandardFonts.HelveticaOblique),
+ };
+ const tree = new StructureBuilder(ctx);
+ const document = tree.element("Document", tree.rootRef, null);
+
+ const first = doc.addPage([612, 792]);
+ first.node.setFontDictionary(PDFName.of("F1"), regular.pdf.ref);
+ first.node.setFontDictionary(PDFName.of("F2"), bold.pdf.ref);
// Drawn at one pixel per point, matching the 120x80 box the content places it in.
const image = ctx.register(
ctx.flateStream(barChartPixels(), {
@@ -82,60 +270,202 @@ async function main() {
BitsPerComponent: 8,
}),
);
- page.node.setXObject(PDFName.of("Im1"), image);
+ first.node.setXObject(PDFName.of("Im1"), image);
- const content = new TextEncoder().encode(CONTENT);
- page.node.set(
- PDFName.of("Contents"),
- ctx.register(PDFRawStream.of(ctx.obj({ Length: content.length }), content)),
+ const one = tree.page(first);
+ one.mark("H1", tree.element("H1", document, first), [
+ "BT /F2 28 Tf 72 700 Td (Quarterly report) Tj ET",
+ ]);
+ one.mark("P", tree.element("P", document, first), [
+ "BT /F1 14 Tf 72 660 Td (Revenue grew in every region this quarter,) Tj ET",
+ "BT /F1 14 Tf 72 642 Td (led by demand for the new product line.) Tj ET",
+ ]);
+ one.mark(
+ "Figure",
+ tree.element("Figure", document, first, {
+ Alt: PDFString.of("Bar chart of revenue by region"),
+ }),
+ ["q 120 0 0 80 72 520 cm /Im1 Do Q"],
);
- page.node.set(PDFName.of("StructParents"), PDFNumber.of(0));
+ one.artifact("/Type /Pagination", ["BT /F1 10 Tf 300 40 Td (Page 1) Tj ET"]);
+ one.writeTo(ctx, first);
- const rootRef = ctx.nextRef();
- const documentRef = ctx.nextRef();
- const element = (
- type: string,
- mcid: number,
- extra: Record<string, PDFObject> = {},
- ): PDFRef =>
- ctx.register(
- ctx.obj({
- Type: "StructElem",
- S: type,
- P: documentRef,
- Pg: page.ref,
- K: mcid,
- ...extra,
- }),
- );
- const heading = element("H1", 0);
- const paragraph = element("P", 1);
- const figure = element("Figure", 2, {
- Alt: PDFString.of("Bar chart of revenue by region"),
+ const second = doc.addPage([612, 792]);
+ for (const font of [regular, bold, mono, italic]) {
+ second.node.setFontDictionary(PDFName.of(font.name), font.pdf.ref);
+ }
+ const two = tree.page(second);
+ const el = (type: string, extra?: Record<string, PDFObject>) =>
+ tree.element(type, document, second, extra);
+ const block = (
+ tag: string,
+ font: Font,
+ size: number,
+ y: number,
+ text: string,
+ ) => two.mark(tag, el(tag), [show(font, size, 72, y, text)]);
+
+ two.artifact("/Type /Pagination /Subtype /Header", [
+ show(regular, 9, 72, 750, "Acme Corp | Q3 2026 quarterly report"),
+ ]);
+
+ block("H2", bold, 20, 700, "Regional performance");
+ const intro = el("P");
+ two.mark("P", intro, [
+ show(
+ regular,
+ 12,
+ 72,
+ 672,
+ "All three regions beat their revenue targets. The detailed figures",
+ ),
+ ]);
+ const appendixLink = tree.element("Link", intro, second);
+ two.line(72, 656, 12, [
+ { tag: "P", owner: intro, font: regular, text: "are in the " },
+ { tag: "Link", owner: appendixLink, font: regular, text: "appendix" },
+ {
+ tag: "P",
+ owner: intro,
+ font: regular,
+ text: " at the end of this report.",
+ },
+ ]);
+
+ block("H3", bold, 16, 620, "North America");
+ two.mark("P", el("P"), [
+ show(
+ regular,
+ 12,
+ 72,
+ 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.",
+ ),
+ ]);
+
+ block("H3", bold, 16, 548, "Europe");
+ const europe = el("P");
+ two.mark("P", europe, [
+ show(
+ regular,
+ 12,
+ 72,
+ 526,
+ "Growth slowed to 6% as two large contracts moved into the fourth",
+ ),
+ ]);
+ const quote = tree.element("Quote", europe, second);
+ two.line(72, 510, 12, [
+ {
+ tag: "P",
+ owner: europe,
+ font: regular,
+ text: "quarter. Our regional director called it ",
+ },
+ {
+ tag: "Quote",
+ owner: quote,
+ font: italic,
+ text: "“a timing issue, not a demand issue.”",
+ },
+ ]);
+ const local = el("P");
+ const term = tree.element("Span", local, second, {
+ Lang: PDFString.of("de-DE"),
});
- ctx.assign(
- documentRef,
- ctx.obj({
- Type: "StructElem",
- S: "Document",
- P: rootRef,
- K: [heading, paragraph, figure],
- }),
+ two.line(72, 488, 12, [
+ {
+ tag: "P",
+ owner: local,
+ font: regular,
+ text: "German subsidiaries report this line as ",
+ },
+ { tag: "Span", owner: term, font: italic, text: "Umsatzerlöse" },
+ { tag: "P", owner: local, font: regular, text: "." },
+ ]);
+
+ // H3 to H5: the skipped level a checker flags.
+ block("H5", bold, 13, 456, "Outlook");
+ // The RoleMap names no Callout: a custom role a checker reports as unmapped.
+ block(
+ "Callout",
+ bold,
+ 14,
+ 434,
+ "Pipeline for Q4 is up 25% on the same point last year.",
);
- const parentTree = ctx.register(
- ctx.obj({ Nums: [0, [heading, paragraph, figure]] }),
+ block("P", regular, 12, 408, "Priorities for next quarter:");
+ const list = el("L", { A: ctx.obj({ O: "List", ListNumbering: "Decimal" }) });
+ const priorities = [
+ "Close the two delayed European contracts.",
+ "Expand the Atlas pilot to three more enterprise customers.",
+ "Hire a second account manager for the Canadian market.",
+ ];
+ priorities.forEach((text, i) => {
+ const item = tree.element("LI", list, second);
+ const y = 388 - i * 18;
+ two.line(84, y, 12, [
+ {
+ tag: "Lbl",
+ owner: tree.element("Lbl", item, second),
+ font: regular,
+ text: `${i + 1}. `,
+ },
+ {
+ tag: "LBody",
+ owner: tree.element("LBody", item, second),
+ font: regular,
+ text,
+ },
+ ]);
+ });
+
+ block("H2", bold, 20, 306, "Appendix: method");
+ block(
+ "P",
+ regular,
+ 12,
+ 282,
+ "Figures come from the finance warehouse, using this query:",
);
- ctx.assign(
- rootRef,
- ctx.obj({
- Type: "StructTreeRoot",
- K: documentRef,
- ParentTree: parentTree,
- ParentTreeNextKey: 1,
- }),
+ two.mark("Code", el("Code"), [
+ show(mono, 10, 84, 260, "SELECT region, SUM(amount) AS revenue"),
+ show(mono, 10, 84, 246, "FROM invoices"),
+ show(mono, 10, 84, 232, "WHERE quarter = '2026-Q3'"),
+ show(mono, 10, 84, 218, "GROUP BY region;"),
+ ]);
+ block(
+ "P",
+ regular,
+ 12,
+ 192,
+ "All amounts are in US dollars and exclude sales tax.",
);
- doc.catalog.set(PDFName.of("StructTreeRoot"), rootRef);
+ // PDF/UA-1 (7.9) requires a Note to carry an ID.
+ two.mark("Note", el("Note", { ID: PDFString.of("note-unaudited") }), [
+ show(
+ regular,
+ 9,
+ 72,
+ 96,
+ "Note: these figures are unaudited and may change before the annual report.",
+ ),
+ ]);
+ two.untagged([show(regular, 8, 72, 72, "Confidential - internal use only")]);
+ two.artifact("/Type /Pagination", [show(regular, 10, 300, 40, "Page 2")]);
+ two.writeTo(ctx, second);
+
+ tree.finish(document);
+
+ doc.catalog.set(PDFName.of("StructTreeRoot"), tree.rootRef);
doc.catalog.set(PDFName.of("MarkInfo"), ctx.obj({ Marked: true }));
doc.catalog.set(PDFName.of("Lang"), PDFString.of("en-US"));
doc.setTitle("Quarterly report");
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 9654c63390..c50eeefab8 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__/applyStructureEdits.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyStructureEdits.test.ts
index 9786950dbb..54a36267eb 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyStructureEdits.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyStructureEdits.test.ts
@@ -410,7 +410,7 @@ describe("applyStructureEdits: adding figures", () => {
mcid,
alt,
decorative: false,
- newFigure: { after },
+ newElement: { type: "Figure" as const, after },
});
const documentKids = async (bytes: Uint8Array) =>
(await elementBody(bytes, 9)).match(/\/K \[([^\]]*)\]/)![1];
@@ -491,3 +491,159 @@ describe("applyStructureEdits: adding figures", () => {
]);
});
});
+
+describe("applyStructureEdits: blocks", () => {
+ // Document 9 holds a P (10) whose text is all in a Span (13), then a list
+ // (14) of one item (15). The page also draws MCID 2, which no element owns.
+ function blocksPdf(): Uint8Array {
+ return buildClassicPdf(
+ objects("<< /Nums [0 [13 0 R 15 0 R]] >>")
+ .map((obj) => {
+ switch (obj.num) {
+ case 5:
+ return {
+ num: 5,
+ body: streamBody(
+ "",
+ "/Span <</MCID 0>> BDC 0 0 10 10 re f EMC /LI <</MCID 1>> BDC 0 0 5 5 re f EMC " +
+ "/P <</MCID 2>> BDC 0 0 2 2 re f EMC",
+ ),
+ };
+ case 9:
+ return {
+ num: 9,
+ body: "<< /Type /StructElem /S /Document /P 7 0 R /K [10 0 R 14 0 R] >>",
+ };
+ case 10:
+ return {
+ num: 10,
+ body: "<< /Type /StructElem /S /P /P 9 0 R /K 13 0 R >>",
+ };
+ default:
+ return obj;
+ }
+ })
+ .concat([
+ {
+ num: 13,
+ body: "<< /Type /StructElem /S /Span /P 10 0 R /Pg 3 0 R /K 0 >>",
+ },
+ {
+ num: 14,
+ body: "<< /Type /StructElem /S /L /P 9 0 R /K 15 0 R >>",
+ },
+ {
+ num: 15,
+ body: "<< /Type /StructElem /S /LI /P 14 0 R /Pg 3 0 R /K 1 >>",
+ },
+ ]),
+ 1,
+ );
+ }
+ const added = (after: number) => ({
+ pageIndex: 0,
+ mcid: 2,
+ decorative: false,
+ newElement: { type: "P" as const, after },
+ });
+ const documentKids = async (bytes: Uint8Array) =>
+ (await elementBody(bytes, 9)).match(/\/K \[([^\]]*)\]/)![1];
+
+ test("retags the paragraph a Span's text sits in", async () => {
+ const out = await applyStructureEdits(blocksPdf(), [
+ { pageIndex: 0, mcid: 0, type: "H2", decorative: false },
+ ]);
+ expect(await elementBody(out, 10)).toContain("/S /H2");
+ expect(await elementBody(out, 13)).toContain("/S /Span");
+ });
+
+ test("places an element after the paragraph, not inside it beside the Span", async () => {
+ const out = await applyStructureEdits(blocksPdf(), [added(0)]);
+ expect(await documentKids(out)).toBe("10 0 R 16 0 R 14 0 R");
+ });
+
+ test("places an element after a list, not among its items", async () => {
+ const out = await applyStructureEdits(blocksPdf(), [added(1)]);
+ expect(await documentKids(out)).toBe("10 0 R 14 0 R 16 0 R");
+ });
+});
+
+describe("applyStructureEdits: cutting", () => {
+ // Document 9 holds P 10, whose kids are MCID 0, Link 13 (MCID 2) and MCID
+ // 1. The page also carries MCIDs 3 and 4, which the editor gave the text
+ // it cut out of MCID 0 and the text after that cut.
+ function cutPdf(): Uint8Array {
+ return buildClassicPdf(
+ objects("<< /Nums [0 [10 0 R 10 0 R 13 0 R]] >>")
+ .map((obj) => {
+ switch (obj.num) {
+ case 5:
+ return {
+ num: 5,
+ body: streamBody(
+ "",
+ "/P <</MCID 0>> BDC 0 0 1 1 re f EMC /H2 <</MCID 3>> BDC 0 0 2 2 re f EMC " +
+ "/P <</MCID 4>> BDC 0 0 3 3 re f EMC /Link <</MCID 2>> BDC 0 0 4 4 re f EMC " +
+ "/P <</MCID 1>> BDC 0 0 5 5 re f EMC",
+ ),
+ };
+ case 9:
+ return {
+ num: 9,
+ body: "<< /Type /StructElem /S /Document /P 7 0 R /K [10 0 R] >>",
+ };
+ case 10:
+ return {
+ num: 10,
+ body: "<< /Type /StructElem /S /P /P 9 0 R /Pg 3 0 R /K [0 13 0 R 1] >>",
+ };
+ default:
+ return obj;
+ }
+ })
+ .concat([
+ {
+ num: 13,
+ body: "<< /Type /StructElem /S /Link /P 10 0 R /Pg 3 0 R /K 2 >>",
+ },
+ ]),
+ 1,
+ );
+ }
+ const cut = (type: "H2" | "Span") => ({
+ pageIndex: 0,
+ mcid: 3,
+ alt: null,
+ decorative: false,
+ cut: { type, from: [0], before: 0, after: 4 },
+ });
+ const kids = async (bytes: Uint8Array, num: number) =>
+ (await elementBody(bytes, num)).match(/\/K \[([^\]]*)\]/)![1];
+
+ test("puts an inline element among the kids, between the parts it was cut from", async () => {
+ const out = await applyStructureEdits(cutPdf(), [cut("Span")]);
+ expect(await kids(out, 10)).toBe("0 14 0 R 4 13 0 R 1");
+ expect(await elementBody(out, 14)).toContain("/S /Span /P 10 0 R");
+ });
+
+ test("splits the element around a block, moving the kids after it to a new one", async () => {
+ const out = await applyStructureEdits(cutPdf(), [cut("H2")]);
+ expect(await kids(out, 9)).toBe("10 0 R 14 0 R 15 0 R");
+ expect(await kids(out, 10)).toBe("0");
+ expect(await elementBody(out, 14)).toContain("/S /H2 /P 9 0 R");
+ expect(await kids(out, 15)).toBe("4 13 0 R 1");
+ expect(await elementBody(out, 13)).toContain("/P 15 0 R");
+
+ const pdf = (await RawPdf.parse(out))!;
+ const slots = pdf.parentTreeArray(7, 0)!.items!.map((item) => item.text);
+ expect(slots).toEqual(["10 0 R", "15 0 R", "13 0 R", "14 0 R", "15 0 R"]);
+ });
+
+ test("refuses a cut from MCIDs that are not consecutive kids", async () => {
+ await expect(
+ applyStructureEdits(cutPdf(), [
+ { ...cut("Span"), cut: { ...cut("Span").cut, from: [0, 1] } },
+ ]),
+ ).rejects.toThrow(StructureEditError);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/headingOutline.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/headingOutline.test.ts
new file mode 100644
index 0000000000..982e943062
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/headingOutline.test.ts
@@ -0,0 +1,110 @@
+// @vitest-environment node
+// jsdom's Blob cannot stream, so the fixture's object stream would not inflate.
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { describe, expect, test } from "vitest";
+import type { HeadingType } from "@editor/tools/pdfTextEditor/model/structureTypes";
+import { readFileStructure } from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";
+import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";
+import {
+ headingOutline,
+ issueCount,
+ type DocumentHeading,
+} from "@editor/tools/pdfTextEditor/util/headingOutline";
+
+const TAGGED_SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/tagged-sample.pdf",
+);
+
+const heading = (type: HeadingType, mcid = 0): DocumentHeading => ({
+ type,
+ pageIndex: 0,
+ mcids: [mcid],
+});
+
+function issues(...types: HeadingType[]) {
+ return headingOutline(
+ types.map((type) => heading(type)),
+ [],
+ ).entries.map((entry) => entry.issue);
+}
+
+describe("headingOutline", () => {
+ test("accepts levels that step down one at a time and jump back up", () => {
+ expect(issues("H1", "H2", "H3", "H1", "H2")).toEqual([
+ null,
+ null,
+ null,
+ null,
+ null,
+ ]);
+ });
+
+ test("reports a first heading other than H1", () => {
+ expect(issues("H2", "H3")).toEqual([{ kind: "first-not-h1" }, null]);
+ });
+
+ test("reports a level skipped on the way down", () => {
+ expect(issues("H1", "H3", "H4", "H2", "H5")).toEqual([
+ null,
+ { kind: "skipped-level", previous: 1 },
+ null,
+ null,
+ { kind: "skipped-level", previous: 2 },
+ ]);
+ });
+
+ test("reports H used alongside numbered headings, once", () => {
+ const outline = headingOutline(
+ [heading("H1"), heading("H"), heading("H2")],
+ [],
+ );
+ expect(outline.mixesNumbering).toBe(true);
+ expect(outline.entries.map((entry) => entry.issue)).toEqual([
+ null,
+ null,
+ null,
+ ]);
+ expect(issueCount(outline)).toBe(1);
+ expect(
+ headingOutline([heading("H"), heading("H")], []).mixesNumbering,
+ ).toBe(false);
+ });
+
+ test("finds the run showing each heading on its page", () => {
+ const page = {
+ pageIndex: 0,
+ runs: [
+ { id: "body", text: "Body", mcid: 1 },
+ { id: "title", text: "Title", mcid: 0 },
+ ],
+ } as unknown as PageSnapshot;
+ const [found, missing] = headingOutline(
+ [heading("H1", 0), heading("H2", 5)],
+ [page],
+ ).entries;
+ expect(found.run?.id).toBe("title");
+ expect(missing.run).toBeNull();
+ });
+});
+
+describe("reading blocks from the file", () => {
+ test("lists blocks in reading order with the pages they are drawn on", async () => {
+ const structure = await readFileStructure(
+ new Uint8Array(await readFile(TAGGED_SAMPLE)),
+ );
+ expect(
+ structure!.blocks
+ .filter(({ type }) => type?.startsWith("H"))
+ .map(({ type, pageIndex }) => [type, pageIndex]),
+ ).toEqual([
+ ["H1", 0],
+ ["H2", 1],
+ ["H3", 1],
+ ["H3", 1],
+ ["H5", 1],
+ ["H2", 1],
+ ]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/innerTags.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/innerTags.test.ts
new file mode 100644
index 0000000000..d490fbea9e
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/innerTags.test.ts
@@ -0,0 +1,226 @@
+// @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 { RetagInnerCommand } from "@editor/tools/pdfTextEditor/commands/RetagInnerCommand";
+import { TagTextRangeCommand } from "@editor/tools/pdfTextEditor/commands/TagTextRangeCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import {
+ isInlineType,
+ TEXT_RANGE_TYPES,
+ type StructureElement,
+} from "@editor/tools/pdfTextEditor/model/PageStructure";
+import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";
+import { readFileStructure } from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";
+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";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/tagged-sample.pdf",
+);
+const PAGE = 1;
+const INLINE_RANGE_TYPES = TEXT_RANGE_TYPES.filter(isInlineType);
+
+const opened: EditorDocument[] = [];
+
+async function open(bytes?: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(
+ bytes ?? new Uint8Array(await readFile(SAMPLE)),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(PAGE));
+ return doc;
+}
+
+function runWith(doc: EditorDocument, fragment: string) {
+ const run = doc.page(PAGE).runs.find((r) => r.text.includes(fragment));
+ if (!run) throw new Error(`no run contains "${fragment}"`);
+ return run;
+}
+
+function tagsIn(doc: EditorDocument, fragment: string) {
+ return innerTags(doc, runWith(doc, fragment).snapshot());
+}
+
+function retag(
+ doc: EditorDocument,
+ history: HistoryStack,
+ key: string,
+ type: StructureType | null,
+) {
+ history.execute(new RetagInnerCommand({ pageIndex: PAGE, key, type }), doc);
+}
+
+async function saved(doc: EditorDocument) {
+ const { blob } = await exportToBlob(doc, "tags.pdf");
+ const bytes = new Uint8Array(await blob.arrayBuffer());
+ return { bytes, structure: (await readFileStructure(bytes))! };
+}
+
+/** The page's elements of `type` whose text is in block `block`. */
+function elementsIn(
+ elements: readonly StructureElement[],
+ block: string,
+ type: StructureType,
+) {
+ return elements.filter((el) => el.type === type && el.block.key === block);
+}
+
+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("tags inside a run's text", () => {
+ test("lists a file's inline elements with the text they mark", async () => {
+ const doc = await open();
+ expect(tagsIn(doc, "German subsidiaries")).toMatchObject([
+ {
+ text: "Umsatzerlöse",
+ role: { type: "Span" },
+ types: INLINE_RANGE_TYPES,
+ removable: true,
+ },
+ ]);
+ });
+
+ test("offers no change to a list item's parts", async () => {
+ const doc = await open();
+ expect(tagsIn(doc, "Close the two delayed")).toMatchObject([
+ { text: "1. ", role: { type: "Lbl" }, types: [], removable: false },
+ { role: { type: "LBody" }, types: [], removable: false },
+ ]);
+ });
+
+ test("lists none for text with no element inside its block", async () => {
+ const doc = await open();
+ expect(tagsIn(doc, "these figures are unaudited")).toEqual([]);
+ });
+
+ test("saves a retagged inline element under its new type", async () => {
+ const doc = await open();
+ const [span] = tagsIn(doc, "German subsidiaries");
+ retag(doc, new HistoryStack(), span.key, "Code");
+ expect(tagsIn(doc, "German subsidiaries")).toMatchObject([
+ { text: "Umsatzerlöse", role: { type: "Code" } },
+ ]);
+
+ const block = doc
+ .structure(PAGE)
+ .element(
+ doc.structure(PAGE).elements.find((el) => el.key === span.key)!
+ .mcids[0],
+ )!.block.key;
+ const { structure } = await saved(doc);
+ const elements = structure.pages.get(PAGE)!.elements;
+ expect(elementsIn(elements, block, "Span")).toHaveLength(0);
+ expect(elementsIn(elements, block, "Code")).toHaveLength(1);
+ });
+
+ test("saves a removed inline element's text as its paragraph's", async () => {
+ const doc = await open();
+ const [span] = tagsIn(doc, "German subsidiaries");
+ const removed = doc
+ .structure(PAGE)
+ .elements.find((el) => el.key === span.key)!;
+ retag(doc, new HistoryStack(), span.key, null);
+ expect(tagsIn(doc, "German subsidiaries")).toEqual([]);
+
+ const { structure } = await saved(doc);
+ const elements = structure.pages.get(PAGE)!.elements;
+ expect(elementsIn(elements, removed.block.key, "Span")).toHaveLength(0);
+ const paragraph = elements.find((el) => el.key === removed.block.key)!;
+ expect(paragraph.type).toBe("P");
+ expect(paragraph.mcids).toEqual(expect.arrayContaining(removed.mcids));
+ });
+
+ test("lists text the session tagged, and can change or remove it", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const run = runWith(doc, "Growth slowed");
+ const start = run.text.indexOf("two large contracts");
+ history.execute(
+ new TagTextRangeCommand({
+ pageIndex: PAGE,
+ runId: run.id,
+ start,
+ end: start + "two large contracts".length,
+ as: "Span",
+ }),
+ doc,
+ );
+ const sessionTags = () =>
+ tagsIn(doc, "Growth slowed").filter((tag) => tag.key.startsWith("added"));
+ const [cut] = sessionTags();
+ expect(cut).toMatchObject({
+ text: "two large contracts",
+ role: { type: "Span" },
+ types: TEXT_RANGE_TYPES,
+ removable: true,
+ });
+
+ retag(doc, history, cut.key, "Code");
+ expect(sessionTags()).toMatchObject([{ role: { type: "Code" } }]);
+ retag(doc, history, cut.key, null);
+ expect(sessionTags()).toEqual([]);
+ expect(doc.structureEdits()).toMatchObject([{ cut: { type: null } }]);
+
+ const paragraph = doc.structure(PAGE).block(run.snapshot().mcid!)!.key;
+ const { structure } = await saved(doc);
+ const elements = structure.pages.get(PAGE)!.elements;
+ expect(elementsIn(elements, paragraph, "Span")).toHaveLength(0);
+ expect(elementsIn(elements, paragraph, "Code")).toHaveLength(0);
+ });
+
+ test("puts a removed element back on undo", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const [span] = tagsIn(doc, "German subsidiaries");
+ retag(doc, history, span.key, null);
+
+ history.undo(doc);
+ expect(tagsIn(doc, "German subsidiaries")).toMatchObject([
+ { text: "Umsatzerlöse", role: { type: "Span" } },
+ ]);
+ expect(doc.structureEdits()).toEqual([]);
+ });
+
+ test("refuses a change it does not offer", async () => {
+ const doc = await open();
+ const [label] = tagsIn(doc, "Close the two delayed");
+ expect(() => retag(doc, new HistoryStack(), label.key, null)).toThrow();
+ expect(doc.structureEdits()).toEqual([]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/overlayPainter.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/overlayPainter.test.ts
index 864de84e88..624d662e74 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/overlayPainter.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/overlayPainter.test.ts
@@ -5,6 +5,8 @@ import {
paintLines,
paintPlainText,
plainCaretOffset,
+ plainDomRange,
+ plainSelectionRange,
readOverlayText,
refitEditedTokens,
restoreCaretOffset,
@@ -378,3 +380,40 @@ describe("refitEditedTokens", () => {
);
});
});
+
+describe("selection ranges", () => {
+ function select(from: [Node, number], to: [Node, number]): void {
+ const selection = window.getSelection()!;
+ selection.removeAllRanges();
+ selection.setBaseAndExtent(from[0], from[1], to[0], to[1]);
+ }
+
+ it("counts the selected characters as the model text does, either way round", () => {
+ const el = host();
+ paintLines(el, [line("Hello world"), line("second line")], OPTS);
+ const first = el.children[0].firstChild!.firstChild!;
+ const second = el.children[1].firstChild!.firstChild!;
+ select([first, 2], [second, 3]);
+ expect(plainSelectionRange(el)).toEqual({ start: 2, end: 15 });
+ select([second, 3], [first, 2]);
+ expect(plainSelectionRange(el)).toEqual({ start: 2, end: 15 });
+ });
+
+ it("reads a caret as no range", () => {
+ const el = host();
+ paintLines(el, [line("Hello")], OPTS);
+ const text = el.children[0].firstChild!.firstChild!;
+ select([text, 2], [text, 2]);
+ expect(plainSelectionRange(el)).toBeNull();
+ });
+
+ it("maps a range back onto the painted text it was read from", () => {
+ const el = host();
+ paintLines(el, [line("Hello world"), line("second line")], OPTS);
+ const range = plainDomRange(el, { start: 6, end: 18 })!;
+ const selection = window.getSelection()!;
+ selection.removeAllRanges();
+ selection.addRange(range);
+ expect(plainSelectionRange(el)).toEqual({ start: 6, end: 18 });
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/selectionTextRange.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/selectionTextRange.test.ts
new file mode 100644
index 0000000000..f5fb9c2488
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/selectionTextRange.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from "vitest";
+import { Selection } from "@editor/tools/pdfTextEditor/store/Selection";
+
+describe("Selection text ranges", () => {
+ it("records a range only for the run that is the whole selection", () => {
+ const selection = new Selection();
+ selection.selectOne("a");
+ selection.setTextRange("b", { start: 0, end: 2 });
+ expect(selection.value.textRange).toBeNull();
+ selection.setTextRange("a", { start: 1, end: 3 });
+ expect(selection.value.textRange).toEqual({ start: 1, end: 3 });
+ selection.toggle("b");
+ expect(selection.value.textRange).toBeNull();
+ });
+
+ it("drops the range when the selection changes", () => {
+ const selection = new Selection();
+ selection.selectOne("a");
+ selection.setTextRange("a", { start: 1, end: 3 });
+ selection.selectOne("a");
+ expect(selection.value.textRange).toBeNull();
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts
index 11aa95076b..f7c6287ec9 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts
@@ -154,18 +154,26 @@ describe("reading the structure tree", () => {
test("lists each element with its type, description and MCIDs", async () => {
const doc = await openSample();
const elements = readPageStructure(doc.module, doc.page(0).pagePtr);
- const element = (type: string, alt: string | null, mcids: number[]) => ({
+ const element = (
+ type: string,
+ alt: string | null,
+ mcids: number[],
+ key: string,
+ ) => ({
+ role: type,
type,
alt,
actualText: null,
mcids,
onlyMarkedContent: false,
+ key,
+ block: { key, role: type, type },
});
expect(elements).toEqual([
- element("Document", null, []),
- element("H1", null, [0]),
- element("P", null, [1]),
- element("Figure", FIGURE_ALT, [2]),
+ element("Document", null, [], "0"),
+ element("H1", null, [0], "1"),
+ element("P", null, [1], "2"),
+ element("Figure", FIGURE_ALT, [2], "3"),
]);
});
@@ -253,20 +261,31 @@ function spanningPdf(slot0 = "8 0 R"): Uint8Array {
describe("reading tags from the file's ParentTree", () => {
test("gives each page's MCIDs to the element its ParentTree names", async () => {
- const structure = (await readFileStructure(spanningPdf()))!;
- const element = (type: string, alt: string | null, mcids: number[]) => ({
+ const structure = (await readFileStructure(spanningPdf()))!.pages;
+ const element = (
+ type: string,
+ alt: string | null,
+ mcids: number[],
+ num: number,
+ ) => ({
+ role: type,
type,
alt,
actualText: null,
mcids,
onlyMarkedContent: true,
+ key: String(num),
+ block: { key: String(num), role: type, type },
});
expect(structure.get(0)).toEqual({
- elements: [element("Figure", "Chart", [0]), element("P", null, [5])],
+ elements: [
+ element("Figure", "Chart", [0], 8),
+ element("P", null, [5], 9),
+ ],
slotCount: 6,
});
expect(structure.get(1)).toEqual({
- elements: [element("P", null, [0])],
+ elements: [element("P", null, [0], 9)],
slotCount: 1,
});
});
@@ -637,11 +656,14 @@ describe("images drawn by a form XObject", () => {
describe("PageStructure", () => {
const figure = {
- type: "Figure",
+ role: "Figure",
+ type: "Figure" as const,
alt: "old",
actualText: null,
mcids: [3, 4],
onlyMarkedContent: true,
+ key: "figure",
+ block: { key: "figure", role: "Figure", type: "Figure" as const },
};
test("holds one edit per element, whichever of its MCIDs addressed it", () => {
@@ -912,42 +934,51 @@ describe("saving a description", () => {
describe("PageStructure: added figures", () => {
const paragraph = {
- type: "P",
+ role: "P",
+ type: "P" as const,
alt: null,
actualText: null,
mcids: [3],
onlyMarkedContent: true,
+ key: "paragraph",
+ block: { key: "paragraph", role: "P", type: "P" as const },
};
- test("takes an MCID above every slot, added figure and marked content", () => {
+ test("takes an MCID above every slot, added element and marked content", () => {
const s = new PageStructure([paragraph], null, 5);
expect(s.freeMcid(2)).toBe(5);
expect(s.freeMcid(7)).toBe(8);
- s.addFigure(5);
+ s.addElement(5, "Figure");
expect(s.freeMcid(2)).toBe(6);
});
- test("lists added figures apart from edits to the file's elements", () => {
- const s = new PageStructure([{ ...paragraph, type: "Figure" }], null, 5);
- s.addFigure(5);
+ test("lists added elements apart from edits to the file's elements", () => {
+ const s = new PageStructure(
+ [{ ...paragraph, role: "Figure", type: "Figure" }],
+ null,
+ 5,
+ );
+ s.addElement(5, "Figure");
s.setAlt(5, "Logo");
s.setAlt(3, "Chart");
expect(s.pendingEdits()).toEqual([
{ mcid: 3, alt: "Chart", decorative: false },
]);
- expect(s.addedFigures()).toEqual([{ mcid: 5, alt: "Logo" }]);
+ expect(s.addedElements()).toEqual([
+ { mcid: 5, type: "Figure", alt: "Logo" },
+ ]);
expect(() => s.setDecorative(5, true)).toThrow();
- s.removeFigure(5);
- expect(s.addedFigures()).toEqual([]);
+ s.removeElement(5);
+ expect(s.addedElements()).toEqual([]);
expect(s.element(5)).toBeNull();
});
test("adds none where the page has no ParentTree array or is read-only", () => {
expect(
- new PageStructure([paragraph], null, 5).cannotAddFigure(),
+ new PageStructure([paragraph], null, 5).cannotAddElement(),
).toBeNull();
- expect(new PageStructure([]).cannotAddFigure()).toBe("untagged");
- expect(new PageStructure([], "encrypted", 5).cannotAddFigure()).toBe(
+ expect(new PageStructure([]).cannotAddElement()).toBe("untagged");
+ expect(new PageStructure([], "encrypted", 5).cannotAddElement()).toBe(
"encrypted",
);
});
@@ -1029,7 +1060,7 @@ describe("TagImageCommand", () => {
);
history.undo(doc);
expect(image.mcid).toBeNull();
- expect(doc.structure(0).addedFigures()).toEqual([]);
+ expect(doc.structure(0).addedElements()).toEqual([]);
});
test("un-decorates an artifact, restoring the mark on undo", async () => {
@@ -1056,11 +1087,11 @@ describe("TagImageCommand", () => {
history.execute(tagImage(image, "figure", "A logo"), doc);
history.execute(tagImage(image, "artifact"), doc);
expect(marks(doc, image)).toEqual([{ name: "Artifact", mcid: null }]);
- expect(doc.structure(0).addedFigures()).toEqual([]);
+ expect(doc.structure(0).addedElements()).toEqual([]);
history.undo(doc);
- expect(doc.structure(0).addedFigures()).toEqual([
- { mcid: 1, alt: "A logo" },
+ expect(doc.structure(0).addedElements()).toEqual([
+ { mcid: 1, type: "Figure", alt: "A logo" },
]);
});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureGrouping.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureGrouping.test.ts
new file mode 100644
index 0000000000..d66e3c2771
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureGrouping.test.ts
@@ -0,0 +1,440 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import {
+ containingBlock,
+ type StructureBlock,
+} from "@editor/tools/pdfTextEditor/model/PageStructure";
+import { structureRole } from "@editor/tools/pdfTextEditor/model/structureTypes";
+import { readFileStructure } from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { textTag } from "@editor/tools/pdfTextEditor/util/textAccessibility";
+import { RetagTextCommand } from "@editor/tools/pdfTextEditor/commands/RetagTextCommand";
+import { TagTextCommand } from "@editor/tools/pdfTextEditor/commands/TagTextCommand";
+import { collectMemberPtrs } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import { readTagMarks } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+// One font, size and left edge throughout, at body line spacing, so geometry
+// alone would group all but the list into one paragraph.
+const CONTENT =
+ "/H1 <</MCID 0>> BDC BT /F1 12 Tf 72 700 Td (Introduction) Tj ET EMC\n" +
+ "/P <</MCID 1>> BDC BT /F1 12 Tf 72 686 Td (Read the ) Tj ET EMC\n" +
+ "/Link <</MCID 2>> BDC BT /F1 12 Tf 126 686 Td (guide ) Tj ET EMC\n" +
+ "/P <</MCID 3>> BDC BT /F1 12 Tf 160 686 Td (for details.) Tj ET EMC\n" +
+ "/P <</MCID 4>> BDC BT /F1 12 Tf 72 672 Td (More text.) Tj ET EMC\n" +
+ "/P <</MCID 5>> BDC BT /F1 12 Tf 72 658 Td (Second paragraph.) Tj ET EMC\n" +
+ "/Lbl <</MCID 6>> BDC BT /F1 12 Tf 72 630 Td (1.) Tj ET EMC\n" +
+ "/LBody <</MCID 7>> BDC BT /F1 12 Tf 84 630 Td (Item) Tj ET EMC\n";
+
+/** H1, then a P holding a Link, a second P, and a one-item list. */
+function paragraphsPdf({ tagged = true } = {}): Uint8Array {
+ return buildClassicPdf(
+ [
+ {
+ num: 1,
+ body: tagged
+ ? "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 6 0 R /MarkInfo << /Marked true >> >>"
+ : "<< /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 /StructParents 0 " +
+ "/Resources << /Font << /F1 5 0 R >> >> >>",
+ },
+ { num: 4, body: streamBody("", CONTENT) },
+ {
+ num: 5,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ {
+ num: 6,
+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 20 0 R /ParentTreeNextKey 1 >>",
+ },
+ {
+ num: 7,
+ body: "<< /Type /StructElem /S /Document /P 6 0 R /K [8 0 R 9 0 R 11 0 R 12 0 R] >>",
+ },
+ {
+ num: 8,
+ body: "<< /Type /StructElem /S /H1 /P 7 0 R /Pg 3 0 R /K 0 >>",
+ },
+ {
+ num: 9,
+ body: "<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K [1 10 0 R 3 4] >>",
+ },
+ {
+ num: 10,
+ body: "<< /Type /StructElem /S /Link /P 9 0 R /Pg 3 0 R /K 2 >>",
+ },
+ {
+ num: 11,
+ body: "<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K 5 >>",
+ },
+ {
+ num: 12,
+ body: "<< /Type /StructElem /S /L /P 7 0 R /K 13 0 R >>",
+ },
+ {
+ num: 13,
+ body: "<< /Type /StructElem /S /LI /P 12 0 R /K [14 0 R 15 0 R] >>",
+ },
+ {
+ num: 14,
+ body: "<< /Type /StructElem /S /Lbl /P 13 0 R /Pg 3 0 R /K 6 >>",
+ },
+ {
+ num: 15,
+ body: "<< /Type /StructElem /S /LBody /P 13 0 R /Pg 3 0 R /K 7 >>",
+ },
+ {
+ num: 20,
+ body: "<< /Nums [0 [8 0 R 9 0 R 10 0 R 9 0 R 9 0 R 11 0 R 14 0 R 15 0 R]] >>",
+ },
+ ],
+ 1,
+ );
+}
+
+const opened: EditorDocument[] = [];
+
+async function runTexts(bytes: Uint8Array): Promise<string[]> {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ return page.runs.map((run) => run.text);
+}
+
+function runWith(texts: string[], fragment: string): string {
+ const found = texts.find((text) => text.includes(fragment));
+ if (found === undefined) throw new Error(`no run contains "${fragment}"`);
+ return found;
+}
+
+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("grouping text by structure block", () => {
+ test("keeps each block's text in a run of its own", async () => {
+ const texts = await runTexts(paragraphsPdf());
+ expect(runWith(texts, "Introduction")).not.toContain("Read");
+ expect(runWith(texts, "Second paragraph")).not.toContain("More text");
+ });
+
+ test("keeps inline elements in their block's run", async () => {
+ const texts = await runTexts(paragraphsPdf());
+ const paragraph = runWith(texts, "Read the");
+ expect(paragraph).toContain("guide");
+ expect(paragraph).toContain("for details.");
+ expect(paragraph).toContain("More text.");
+ expect(runWith(texts, "Item")).toContain("1.");
+ });
+
+ test("groups by geometry alone when the file has no structure tree", async () => {
+ const texts = await runTexts(paragraphsPdf({ tagged: false }));
+ const merged = runWith(texts, "Introduction");
+ expect(merged).toContain("More text.");
+ expect(merged).toContain("Second paragraph.");
+ });
+});
+
+describe("textTag", () => {
+ async function tagOf(bytes: Uint8Array, fragment: string) {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ const run = page.runs.find((r) => r.text.includes(fragment))!;
+ return textTag(doc, run.snapshot());
+ }
+
+ test("gives text the block it belongs to", async () => {
+ const tagged = (role: string, cannotRetag: string | null) => ({
+ kind: "tagged",
+ block: { role, type: role },
+ cannotRetag,
+ });
+ expect(await tagOf(paragraphsPdf(), "Introduction")).toEqual(
+ tagged("H1", null),
+ );
+ expect(await tagOf(paragraphsPdf(), "guide")).toEqual(tagged("P", null));
+ expect(await tagOf(paragraphsPdf(), "Item")).toEqual(
+ tagged("LI", "not-text"),
+ );
+ });
+
+ test("reads text in a file without a structure tree as untagged", async () => {
+ expect(
+ await tagOf(paragraphsPdf({ tagged: false }), "Introduction"),
+ ).toEqual({ kind: "untagged", documentTagged: false, taggable: false });
+ });
+});
+
+describe("containingBlock", () => {
+ const block = (key: string, role: string): StructureBlock => ({
+ key,
+ ...structureRole(role),
+ });
+ const within = (parent: StructureBlock) => ({
+ type: parent.type,
+ block: parent,
+ });
+ const p = block("p", "P");
+ const sect = block("sect", "Sect");
+
+ test("puts an inline element in its parent's block", () => {
+ expect(containingBlock(block("link", "Link"), within(p))).toBe(p);
+ });
+
+ test("makes an inline element placed directly in a grouping element its own block", () => {
+ const code = block("code", "Code");
+ expect(containingBlock(code, within(sect))).toBe(code);
+ });
+
+ test("keeps a block element its own block", () => {
+ const h2 = block("h2", "H2");
+ expect(containingBlock(h2, within(sect))).toBe(h2);
+ });
+
+ test("treats a custom role as a block that holds text", () => {
+ const custom = block("custom", "Callout");
+ expect(containingBlock(custom, within(p))).toBe(custom);
+ expect(containingBlock(block("span", "Span"), within(custom))).toBe(custom);
+ });
+});
+
+describe("structureRole", () => {
+ test("gives a standard type its type, and a custom role none", () => {
+ expect(structureRole("H3")).toEqual({ role: "H3", type: "H3" });
+ expect(structureRole("Callout")).toEqual({ role: "Callout", type: null });
+ });
+});
+
+describe("reading blocks from the file", () => {
+ test("resolves nested inline elements to their block", async () => {
+ const structure = (await readFileStructure(paragraphsPdf()))!.pages;
+ const blocks = structure
+ .get(0)!
+ .elements.map((el) => [el.type, el.block.type, el.block.key]);
+ expect(blocks).toEqual([
+ ["H1", "H1", "8"],
+ ["P", "P", "9"],
+ ["Link", "P", "9"],
+ ["P", "P", "11"],
+ ["Lbl", "LI", "13"],
+ ["LBody", "LI", "13"],
+ ]);
+ });
+
+ test("reads a role the RoleMap leaves unmapped as custom", async () => {
+ const bytes = buildClassicPdf(
+ [
+ {
+ num: 1,
+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 6 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 10 10] /StructParents 0 >>",
+ },
+ {
+ num: 6,
+ body: "<< /Type /StructTreeRoot /K [7 0 R 8 0 R] /ParentTree 9 0 R /RoleMap << /Heading1 /H1 >> >>",
+ },
+ { num: 7, body: "<< /Type /StructElem /S /Heading1 /P 6 0 R /K 0 >>" },
+ { num: 8, body: "<< /Type /StructElem /S /Callout /P 6 0 R /K 1 >>" },
+ { num: 9, body: "<< /Nums [0 [7 0 R 8 0 R]] >>" },
+ ],
+ 1,
+ );
+ const structure = (await readFileStructure(bytes))!.pages;
+ expect(
+ structure.get(0)!.elements.map(({ role, type }) => ({ role, type })),
+ ).toEqual([
+ { role: "H1", type: "H1" },
+ { role: "Callout", type: null },
+ ]);
+ });
+
+ test("ends a /P cycle at the top of the tree", async () => {
+ const bytes = buildClassicPdf(
+ [
+ {
+ num: 1,
+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 6 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 10 10] /StructParents 0 >>",
+ },
+ {
+ num: 6,
+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 9 0 R >>",
+ },
+ { num: 7, body: "<< /Type /StructElem /S /Span /P 8 0 R /K 0 >>" },
+ { num: 8, body: "<< /Type /StructElem /S /Span /P 7 0 R /K 7 0 R >>" },
+ { num: 9, body: "<< /Nums [0 [7 0 R]] >>" },
+ ],
+ 1,
+ );
+ const structure = (await readFileStructure(bytes))!.pages;
+ expect(structure.get(0)!.elements[0].block.type).toBe("Span");
+ });
+});
+
+// As Chrome tags: each element's text inside a NonStruct, list bullets drawn
+// outside any element or as artifacts, and one loose line with no tag at all.
+const CHROME_CONTENT =
+ "/NonStruct <</MCID 0>> BDC BT /F1 20 Tf 72 700 Td (Introduction) Tj ET EMC\n" +
+ "/NonStruct <</MCID 1>> BDC BT /F1 12 Tf 72 670 Td (Body text.) Tj ET EMC\n" +
+ "BT /F1 12 Tf 72 640 Td (\\267) Tj ET\n" +
+ "/NonStruct <</MCID 2>> BDC BT /F1 12 Tf 84 640 Td (First item) Tj ET EMC\n" +
+ "/Artifact BMC BT /F1 12 Tf 72 620 Td (\\267) Tj ET EMC\n" +
+ "/NonStruct <</MCID 3>> BDC BT /F1 12 Tf 84 620 Td (Second item) Tj ET EMC\n" +
+ "/Artifact BMC BT /F1 12 Tf 72 560 Td (\\267) Tj ET EMC\n" +
+ "BT /F1 12 Tf 84 560 Td (Loose item) Tj ET\n";
+
+function chromePdf(): Uint8Array {
+ const element = (num: number, s: string, parent: number, k: string) => ({
+ num,
+ body: `<< /Type /StructElem /S /${s} /P ${parent} 0 R /Pg 3 0 R /K ${k} >>`,
+ });
+ return buildClassicPdf(
+ [
+ {
+ num: 1,
+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 6 0 R /MarkInfo << /Marked true >> >>",
+ },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body:
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /StructParents 0 " +
+ "/Resources << /Font << /F1 5 0 R >> >> >>",
+ },
+ { num: 4, body: streamBody("", CHROME_CONTENT) },
+ {
+ num: 5,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ {
+ num: 6,
+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 20 0 R /ParentTreeNextKey 1 >>",
+ },
+ element(7, "Document", 6, "[8 0 R 10 0 R 12 0 R]"),
+ element(8, "H1", 7, "9 0 R"),
+ element(9, "NonStruct", 8, "0"),
+ element(10, "P", 7, "11 0 R"),
+ element(11, "NonStruct", 10, "1"),
+ element(12, "L", 7, "[13 0 R 15 0 R]"),
+ element(13, "LI", 12, "14 0 R"),
+ element(14, "NonStruct", 13, "2"),
+ element(15, "LI", 12, "16 0 R"),
+ element(16, "NonStruct", 15, "3"),
+ { num: 20, body: "<< /Nums [0 [9 0 R 11 0 R 14 0 R 16 0 R]] >>" },
+ ],
+ 1,
+ );
+}
+
+describe("Chrome-style tagging", () => {
+ async function openChrome() {
+ const doc = await EditorDocument.open(chromePdf());
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ const run = (fragment: string) =>
+ doc.page(0).runs.find((r) => r.text.includes(fragment))!;
+ const tagOf = (fragment: string) => {
+ const tag = textTag(doc, run(fragment).snapshot());
+ return tag.kind === "tagged" ? tag.block.type : tag.kind;
+ };
+ return { doc, run, tagOf };
+ }
+
+ test("reads text inside a NonStruct as its parent's", async () => {
+ const { doc, tagOf } = await openChrome();
+ expect(tagOf("Introduction")).toBe("H1");
+ expect(tagOf("Body text.")).toBe("P");
+ expect(doc.headings()).toEqual([{ type: "H1", pageIndex: 0, mcids: [0] }]);
+ });
+
+ test("keeps a list bullet with its item, however the bullet is tagged", async () => {
+ const { run, tagOf } = await openChrome();
+ expect(run("First item").text).toContain("\u2022");
+ expect(run("Second item").text).toContain("\u2022");
+ expect(tagOf("First item")).toBe("LI");
+ expect(tagOf("Second item")).toBe("LI");
+ });
+
+ test("retags the heading through the NonStruct holding its text", async () => {
+ const { doc, run } = await openChrome();
+ new HistoryStack().execute(
+ new RetagTextCommand({
+ pageIndex: 0,
+ mcid: run("Introduction").snapshot().mcid!,
+ type: "H2",
+ }),
+ doc,
+ );
+ const { blob } = await exportToBlob(doc, "chrome.pdf");
+ const pdf = (await RawPdf.parse(new Uint8Array(await blob.arrayBuffer())))!;
+ expect(pdf.dictName(pdf.objectBody(8)!, "S")).toBe("H2");
+ expect(pdf.dictName(pdf.objectBody(9)!, "S")).toBe("NonStruct");
+ });
+
+ test("tags untagged text without tagging the artifact bullet beside it", async () => {
+ const { doc, run } = await openChrome();
+ const loose = run("Loose item");
+ new HistoryStack().execute(
+ new TagTextCommand({ pageIndex: 0, runId: loose.id, as: "P" }),
+ doc,
+ );
+ const marks = collectMemberPtrs(loose).map((ptr) =>
+ readTagMarks(doc.module, ptr).map((tag) => tag.name),
+ );
+ expect(marks).toEqual([["Artifact"], ["P"]]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textRangeTagging.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textRangeTagging.test.ts
new file mode 100644
index 0000000000..9b9c16b108
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textRangeTagging.test.ts
@@ -0,0 +1,432 @@
+// @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 {
+ rangeTagTypes,
+ TagTextRangeCommand,
+} from "@editor/tools/pdfTextEditor/commands/TagTextRangeCommand";
+import { readObjTexts } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import {
+ charOrigins,
+ readMatrix,
+} from "@editor/tools/pdfTextEditor/commands/textPieces";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import {
+ isInlineType,
+ TEXT_RANGE_TYPES,
+ type StructureElement,
+} from "@editor/tools/pdfTextEditor/model/PageStructure";
+import {
+ isHeadingType,
+ type StructureType,
+} from "@editor/tools/pdfTextEditor/model/structureTypes";
+import { elementKids } from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";
+import {
+ RawPdf,
+ referencedObject,
+} from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import {
+ innermostMcid,
+ readTagMarks,
+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+import { readFileStructure } from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import { headingOutline } from "@editor/tools/pdfTextEditor/util/headingOutline";
+import { locateHeading } from "@editor/tools/pdfTextEditor/util/textAccessibility";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+// An H1 (MCID 0); a one-line P (MCID 1); a P whose first line is a heading
+// merged into it (MCID 2); and a P with a heading merged into its middle
+// (MCID 3). Text the file leaves untagged closes the page.
+const CONTENT =
+ "/H1 <</MCID 0>> BDC BT /F1 20 Tf 72 700 Td (Summary) Tj ET EMC\n" +
+ "/P <</MCID 1>> BDC BT /F1 12 Tf 72 670 Td (Sales rose in every region.) Tj ET EMC\n" +
+ "/P <</MCID 2>> BDC BT /F1 16 Tf 72 630 Td (Outlook) Tj ET " +
+ "BT /F1 12 Tf 72 612 Td (Growth will slow next year.) Tj ET EMC\n" +
+ "/P <</MCID 3>> BDC BT /F1 12 Tf 72 560 Td (That ends the outlook.) Tj ET " +
+ "BT /F1 16 Tf 72 530 Td (Methods) Tj ET " +
+ "BT /F1 12 Tf 72 512 Td (We sampled every store.) Tj ET EMC\n" +
+ "BT /F1 12 Tf 72 400 Td (Printed in house) Tj ET\n";
+
+/** Document 7 holds H1 8 and paragraphs 9, 10 and 11, in that order. */
+function cutPdf(): Uint8Array {
+ return buildClassicPdf(
+ [
+ {
+ num: 1,
+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 6 0 R /MarkInfo << /Marked true >> >>",
+ },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body:
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /StructParents 0 " +
+ "/Resources << /Font << /F1 5 0 R >> >> >>",
+ },
+ { num: 4, body: streamBody("", CONTENT) },
+ {
+ num: 5,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ {
+ num: 6,
+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 12 0 R /ParentTreeNextKey 1 >>",
+ },
+ {
+ num: 7,
+ body: "<< /Type /StructElem /S /Document /P 6 0 R /K [8 0 R 9 0 R 10 0 R 11 0 R] >>",
+ },
+ {
+ num: 8,
+ body: "<< /Type /StructElem /S /H1 /P 7 0 R /Pg 3 0 R /K 0 >>",
+ },
+ { num: 9, body: "<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K 1 >>" },
+ {
+ num: 10,
+ body: "<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K 2 >>",
+ },
+ {
+ num: 11,
+ body: "<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K 3 >>",
+ },
+ { num: 12, body: "<< /Nums [0 [8 0 R 9 0 R 10 0 R 11 0 R]] >>" },
+ ],
+ 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;
+}
+
+function runWith(doc: EditorDocument, fragment: string) {
+ const run = doc.page(0).runs.find((r) => r.text.includes(fragment));
+ if (!run) throw new Error(`no run contains "${fragment}"`);
+ return run;
+}
+
+function tagRange(
+ doc: EditorDocument,
+ history: HistoryStack,
+ fragment: string,
+ as: StructureType,
+) {
+ const run = runWith(doc, fragment);
+ const start = run.text.indexOf(fragment);
+ history.execute(
+ new TagTextRangeCommand({
+ pageIndex: 0,
+ runId: run.id,
+ start,
+ end: start + fragment.length,
+ as,
+ }),
+ doc,
+ );
+}
+
+async function savedBytes(doc: EditorDocument): Promise<Uint8Array> {
+ const { blob } = await exportToBlob(doc, "cut.pdf");
+ return new Uint8Array(await blob.arrayBuffer());
+}
+
+async function savedHeadings(doc: EditorDocument): Promise<string[]> {
+ const structure = await readFileStructure(await savedBytes(doc));
+ return structure!.blocks.flatMap(({ type }) =>
+ type && isHeadingType(type) ? [type] : [],
+ );
+}
+
+/** Each MCID's text on page 0, its objects read in page order. */
+function textByMcid(doc: EditorDocument): Map<number, string> {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const ptrs = Array.from(
+ { length: m.FPDFPage_CountObjects(pagePtr) },
+ (_, i) => m.FPDFPage_GetObject(pagePtr, i),
+ );
+ const texts = readObjTexts(m, pagePtr, ptrs);
+ const out = new Map<number, string>();
+ ptrs.forEach((ptr, i) => {
+ const mcid = innermostMcid(readTagMarks(m, ptr));
+ if (mcid !== null) out.set(mcid, (out.get(mcid) ?? "") + (texts[i] ?? ""));
+ });
+ return out;
+}
+
+/** An element's kids: an MCID as its number, a child element as its /S. */
+function kidsOf(pdf: RawPdf, num: number): string[] {
+ return elementKids(pdf, pdf.objectBody(num)!)!.map((kid) => {
+ const ref = referencedObject(kid);
+ return ref === null ? kid : `/${pdf.dictName(pdf.objectBody(ref)!, "S")}`;
+ });
+}
+
+/** The child element of `num` with /S `type`. */
+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;
+}
+
+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("tagging part of an element's text", () => {
+ test("saves a Span among its paragraph's kids, where its text is read", async () => {
+ const doc = await open(cutPdf());
+ tagRange(doc, new HistoryStack(), "every", "Span");
+
+ const bytes = await savedBytes(doc);
+ const pdf = (await RawPdf.parse(bytes))!;
+ expect(kidsOf(pdf, 9)).toEqual(["1", "/Span", "5"]);
+ expect(kidsOf(pdf, kidNamed(pdf, 9, "Span"))).toEqual(["4"]);
+
+ // The part after is the shorter, so it is the one redrawn with an MCID of its own.
+ const texts = textByMcid(await open(bytes));
+ expect(texts.get(1)?.trim()).toBe("Sales rose in");
+ expect(texts.get(4)?.trim()).toBe("every");
+ expect(texts.get(5)?.trim()).toBe("region.");
+ });
+
+ test("draws the cut text where it was drawn", async () => {
+ const doc = await open(cutPdf());
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const line = runWith(doc, "every").mergedFromPtrs[0];
+ const origin = charOrigins(
+ m,
+ pagePtr,
+ new Map([[line, new Set([14])]]),
+ new Map([[line, 27]]),
+ )
+ .get(line)!
+ .get(14)!;
+ tagRange(doc, new HistoryStack(), "every", "Span");
+
+ const run = runWith(doc, "every");
+ const cut = run.mergedFromPtrs[run.mergedFromTexts.indexOf("every")];
+ const matrix = readMatrix(m, cut)!;
+ expect(matrix[4]).toBeCloseTo(origin.x, 3);
+ expect(matrix[5]).toBeCloseTo(origin.y, 3);
+ });
+
+ test("splits a heading out of the start of its paragraph", async () => {
+ const doc = await open(cutPdf());
+ tagRange(doc, new HistoryStack(), "Outlook", "H2");
+ expect(doc.headings()!.map((h) => h.type)).toEqual(["H1", "H2"]);
+
+ const pdf = (await RawPdf.parse(await savedBytes(doc)))!;
+ expect(kidsOf(pdf, 7)).toEqual(["/H1", "/P", "/H2", "/P", "/P"]);
+ expect(kidsOf(pdf, 10)).toEqual(["2"]);
+ expect(kidsOf(pdf, kidNamed(pdf, 7, "H2"))).toEqual(["4"]);
+ });
+
+ test("outlines two headings cut from one paragraph as the save orders them", async () => {
+ const doc = await open(cutPdf());
+ const history = new HistoryStack();
+ tagRange(doc, history, "Methods", "H2");
+ tagRange(doc, history, "sampled", "H3");
+ expect(doc.headings()!.map((h) => h.type)).toEqual(["H1", "H2", "H3"]);
+ expect(await savedHeadings(doc)).toEqual(["H1", "H2", "H3"]);
+ });
+
+ test("outlines the part of a split heading read after the cut", async () => {
+ const doc = await open(cutPdf());
+ doc.setRetag(0, 1, "H2");
+ tagRange(doc, new HistoryStack(), "every", "P");
+ expect(doc.headings()!.map((h) => h.type)).toEqual(["H1", "H2", "H2"]);
+ expect(await savedHeadings(doc)).toEqual(["H1", "H2", "H2"]);
+ });
+
+ test("finds the text of a heading cut from a run", async () => {
+ const doc = await open(cutPdf());
+ tagRange(doc, new HistoryStack(), "Methods", "H2");
+ const { entries } = headingOutline(
+ doc.headings()!,
+ [
+ {
+ pageIndex: 0,
+ runs: doc.page(0).runs.map((r) => r.snapshot()),
+ } as PageSnapshot,
+ ],
+ (heading) => locateHeading(doc, heading),
+ );
+ const { run, range } = entries[1];
+ expect(run!.text.slice(range!.start, range!.end)).toBe("Methods");
+ });
+
+ test("splits a paragraph in two around a heading in its middle", async () => {
+ const doc = await open(cutPdf());
+ tagRange(doc, new HistoryStack(), "Methods", "H2");
+
+ const bytes = await savedBytes(doc);
+ const pdf = (await RawPdf.parse(bytes))!;
+ expect(kidsOf(pdf, 7)).toEqual(["/H1", "/P", "/P", "/P", "/H2", "/P"]);
+ // The part before is the shorter, so it is redrawn with an MCID of its own.
+ expect(kidsOf(pdf, 11)).toEqual(["5"]);
+ const rest = referencedObject(
+ elementKids(pdf, pdf.objectBody(7)!)!.at(-1)!,
+ )!;
+ expect(kidsOf(pdf, rest)).toEqual(["3"]);
+
+ const texts = textByMcid(await open(bytes));
+ expect(texts.get(5)?.trim()).toBe("That ends the outlook.");
+ expect(texts.get(4)?.trim()).toBe("Methods");
+ expect(texts.get(3)?.trim()).toBe("We sampled every store.");
+ });
+
+ test("puts the text back as it was on undo, and cuts it again on redo", async () => {
+ const doc = await open(cutPdf());
+ const before = textByMcid(doc);
+ const history = new HistoryStack();
+ tagRange(doc, history, "every", "Span");
+
+ history.undo(doc);
+ expect(textByMcid(doc)).toEqual(before);
+ expect(doc.structureEdits()).toEqual([]);
+
+ history.redo(doc);
+ expect(doc.structureEdits()).toMatchObject([
+ { mcid: 4, cut: { type: "Span", from: [1], before: 1, after: 5 } },
+ ]);
+ });
+
+ test("tags a word of a real file's paragraph as a Span inside it", async () => {
+ const sample = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/tagged-sample.pdf",
+ );
+ const doc = await EditorDocument.open(
+ new Uint8Array(await readFile(sample)),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(1));
+ const run = doc.page(1).runs.find((r) => r.text.includes("All amounts"))!;
+ const paragraph = doc.structure(1).block(run.snapshot().mcid!)!.key;
+ const spansIn = (elements: readonly StructureElement[]) =>
+ elements.filter((el) => el.type === "Span" && el.block.key === paragraph)
+ .length;
+ expect(spansIn(doc.structure(1).elements)).toBe(0);
+ const start = run.text.indexOf("amounts");
+ new HistoryStack().execute(
+ new TagTextRangeCommand({
+ pageIndex: 1,
+ runId: run.id,
+ start,
+ end: start + "amounts".length,
+ as: "Span",
+ }),
+ doc,
+ );
+
+ const saved = await readFileStructure(await savedBytes(doc));
+ expect(spansIn(saved!.pages.get(1)!.elements)).toBe(1);
+ });
+
+ test("refuses untagged text, and changes nothing", async () => {
+ const doc = await open(cutPdf());
+ const before = textByMcid(doc);
+ expect(() =>
+ tagRange(doc, new HistoryStack(), "Printed", "Span"),
+ ).toThrow();
+ expect(textByMcid(doc)).toEqual(before);
+ expect(doc.structureEdits()).toEqual([]);
+ });
+});
+
+describe("which tags part of a run's text can take", () => {
+ const typesFor = (
+ doc: EditorDocument,
+ pageIndex: number,
+ fragment: string,
+ within = fragment,
+ ) => {
+ const run = doc.page(pageIndex).runs.find((r) => r.text.includes(within))!;
+ const start = run.text.indexOf(fragment);
+ return rangeTagTypes(
+ doc,
+ pageIndex,
+ run.id,
+ start,
+ start + fragment.length,
+ );
+ };
+
+ test("offers every type for text inside a block it can split", async () => {
+ const doc = await open(cutPdf());
+ expect(typesFor(doc, 0, "rose in every")).toEqual([...TEXT_RANGE_TYPES]);
+ });
+
+ test("offers only inline types for text in an inline element", async () => {
+ const doc = await EditorDocument.open(
+ new Uint8Array(
+ await readFile(
+ path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/tagged-sample.pdf",
+ ),
+ ),
+ ),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(1));
+ expect(typesFor(doc, 1, "appendix")).toEqual(
+ TEXT_RANGE_TYPES.filter(isInlineType),
+ );
+ expect(typesFor(doc, 1, "in the appendix")).toEqual([]);
+ });
+
+ test("offers none for untagged text or only spaces", async () => {
+ const doc = await open(cutPdf());
+ expect(typesFor(doc, 0, "Printed")).toEqual([]);
+ expect(typesFor(doc, 0, " ", "Sales rose")).toEqual([]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textTagging.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textTagging.test.ts
new file mode 100644
index 0000000000..884e4e30e4
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textTagging.test.ts
@@ -0,0 +1,311 @@
+// @vitest-environment node
+// jsdom's Blob cannot stream, so the fixture's object stream would not inflate.
+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 { RetagTextCommand } from "@editor/tools/pdfTextEditor/commands/RetagTextCommand";
+import { TagTextCommand } from "@editor/tools/pdfTextEditor/commands/TagTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";
+import { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import { readFileStructure } from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+import {
+ canTagText,
+ textTag,
+} from "@editor/tools/pdfTextEditor/util/textAccessibility";
+
+const TAGGED_SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/tagged-sample.pdf",
+);
+/** The sample's second page: the one with text in every tag. */
+const PAGE = 1;
+
+const opened: EditorDocument[] = [];
+
+async function openSample(): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(
+ new Uint8Array(await readFile(TAGGED_SAMPLE)),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(PAGE));
+ return doc;
+}
+
+function runWith(doc: EditorDocument, fragment: string) {
+ const run = doc.page(PAGE).runs.find((r) => r.text.includes(fragment));
+ if (!run) throw new Error(`no run contains "${fragment}"`);
+ return run;
+}
+
+function retag(
+ doc: EditorDocument,
+ history: HistoryStack,
+ fragment: string,
+ type: StructureType | null,
+) {
+ const run = runWith(doc, fragment);
+ const mcid = run.snapshot().mcid!;
+ history.execute(new RetagTextCommand({ pageIndex: PAGE, mcid, type }), doc);
+ return { run, key: doc.structure(PAGE).block(mcid)!.key };
+}
+
+function shownTag(doc: EditorDocument, fragment: string) {
+ const tag = textTag(doc, runWith(doc, fragment).snapshot());
+ return tag.kind === "tagged" ? tag.block.type : tag.kind;
+}
+
+async function savedBytes(doc: EditorDocument): Promise<Uint8Array> {
+ const { blob } = await exportToBlob(doc, "sample.pdf");
+ return new Uint8Array(await blob.arrayBuffer());
+}
+
+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("retagging text", () => {
+ test("shows the new tag, adds it to the headings, and undoes", async () => {
+ const doc = await openSample();
+ const history = new HistoryStack();
+ retag(doc, history, "Priorities for next quarter", "H3");
+
+ expect(shownTag(doc, "Priorities for next quarter")).toBe("H3");
+ expect(doc.headings()!.map((h) => h.type)).toEqual([
+ "H1",
+ "H2",
+ "H3",
+ "H3",
+ "H5",
+ "H3",
+ "H2",
+ ]);
+
+ history.undo(doc);
+ expect(shownTag(doc, "Priorities for next quarter")).toBe("P");
+ expect(doc.structureEdits()).toEqual([]);
+ });
+
+ test("saves the new tag as the element's /S", async () => {
+ const doc = await openSample();
+ const { key } = retag(doc, new HistoryStack(), "Outlook", "H3");
+
+ const saved = await readFileStructure(await savedBytes(doc));
+ const block = saved!.blocks.find((b) => b.key === key);
+ expect(block).toMatchObject({ role: "H3", type: "H3" });
+ });
+
+ test("gives text retagged as a Note the ID PDF/UA requires", async () => {
+ const doc = await openSample();
+ const { key } = retag(doc, new HistoryStack(), "All amounts", "Note");
+
+ const pdf = await RawPdf.parse(await savedBytes(doc));
+ const body = pdf!.objectBody(Number(key))!;
+ expect(pdf!.dictName(body, "S")).toBe("Note");
+ expect(pdf!.valueSpan(body, "ID")?.text).toBe(`(note-${key})`);
+ });
+
+ test("drops the retag when the text is set back to its own tag", async () => {
+ const doc = await openSample();
+ const history = new HistoryStack();
+ retag(doc, history, "Priorities for next quarter", "H2");
+ retag(doc, history, "Priorities for next quarter", "P");
+ expect(doc.structureEdits()).toEqual([]);
+ });
+
+ test("retags a paragraph through the text of a link inside it", async () => {
+ const doc = await openSample();
+ const structure = doc.structure(PAGE);
+ const link = structure.elements.find((el) => el.type === "Link")!;
+ expect(structure.cannotRetag(link.mcids[0])).toBeNull();
+ expect(structure.block(link.mcids[0])?.type).toBe("P");
+ });
+
+ test("retags a custom role, giving it a standard meaning", async () => {
+ const doc = await openSample();
+ retag(doc, new HistoryStack(), "Pipeline for Q4", "P");
+ expect(shownTag(doc, "Pipeline for Q4")).toBe("P");
+ });
+
+ test("refuses text in a list item, whose element holds more than text", async () => {
+ const doc = await openSample();
+ const mcid = runWith(doc, "Close the two delayed").snapshot().mcid!;
+ expect(doc.structure(PAGE).cannotRetag(mcid)).toBe("not-text");
+ expect(() =>
+ new HistoryStack().execute(
+ new RetagTextCommand({ pageIndex: PAGE, mcid, type: "H2" }),
+ doc,
+ ),
+ ).toThrow();
+ expect(doc.structureEdits()).toEqual([]);
+ });
+});
+
+function tagText(
+ doc: EditorDocument,
+ history: HistoryStack,
+ fragment: string,
+ as: StructureType,
+ pageIndex = PAGE,
+) {
+ const run = doc.page(pageIndex).runs.find((r) => r.text.includes(fragment))!;
+ history.execute(new TagTextCommand({ pageIndex, runId: run.id, as }), doc);
+ return run;
+}
+
+/** A tagged page: an H1, then a two-line paragraph its content leaves untagged. */
+function untaggedParagraphPdf(): Uint8Array {
+ return buildClassicPdf(
+ [
+ {
+ num: 1,
+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 6 0 R /MarkInfo << /Marked true >> >>",
+ },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body:
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /StructParents 0 " +
+ "/Resources << /Font << /F1 5 0 R >> >> >>",
+ },
+ {
+ num: 4,
+ body: streamBody(
+ "",
+ "/H1 <</MCID 0>> BDC BT /F1 20 Tf 72 700 Td (Summary) Tj ET EMC\n" +
+ "BT /F1 12 Tf 72 670 Td (Sales rose in every region,) Tj ET\n" +
+ "BT /F1 12 Tf 72 656 Td (led by the new product line.) Tj ET\n",
+ ),
+ },
+ {
+ num: 5,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ {
+ num: 6,
+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 9 0 R /ParentTreeNextKey 1 >>",
+ },
+ {
+ num: 7,
+ body: "<< /Type /StructElem /S /Document /P 6 0 R /K [8 0 R] >>",
+ },
+ {
+ num: 8,
+ body: "<< /Type /StructElem /S /H1 /P 7 0 R /Pg 3 0 R /K 0 >>",
+ },
+ { num: 9, body: "<< /Nums [0 [8 0 R]] >>" },
+ ],
+ 1,
+ );
+}
+
+describe("tagging untagged text", () => {
+ test("tags the text, shows it, and saves it as a new element", async () => {
+ const doc = await openSample();
+ tagText(doc, new HistoryStack(), "Confidential", "P");
+ expect(shownTag(doc, "Confidential")).toBe("P");
+
+ const reopened = await EditorDocument.open(await savedBytes(doc));
+ opened.push(reopened);
+ PdfiumTextReader.populate(reopened, reopened.page(PAGE));
+ expect(shownTag(reopened, "Confidential")).toBe("P");
+ });
+
+ test("puts a new heading in the outline where the save puts it", async () => {
+ const doc = await openSample();
+ tagText(doc, new HistoryStack(), "Confidential", "H2");
+ const inSession = doc.headings()!.map((h) => h.type);
+ expect(inSession.at(-1)).toBe("H2");
+
+ const saved = await readFileStructure(await savedBytes(doc));
+ expect(
+ saved!.blocks.flatMap(({ type }) =>
+ type?.startsWith("H") ? [type] : [],
+ ),
+ ).toEqual(inSession);
+ });
+
+ test("removes the tag on undo", async () => {
+ const doc = await openSample();
+ const history = new HistoryStack();
+ const run = tagText(doc, history, "Confidential", "P");
+ history.undo(doc);
+ expect(run.snapshot().mcid).toBeUndefined();
+ expect(shownTag(doc, "Confidential")).toBe("untagged");
+ expect(doc.structureEdits()).toEqual([]);
+ });
+
+ test("retags text it tagged before the save", async () => {
+ const doc = await openSample();
+ const history = new HistoryStack();
+ tagText(doc, history, "Confidential", "P");
+ retag(doc, history, "Confidential", "Note");
+ expect(shownTag(doc, "Confidential")).toBe("Note");
+
+ history.undo(doc);
+ expect(shownTag(doc, "Confidential")).toBe("P");
+ });
+
+ test("refuses text marked as an artifact", async () => {
+ const doc = await openSample();
+ const header = runWith(doc, "Acme Corp");
+ expect(canTagText(doc, header.snapshot())).toBe(false);
+ expect(() => tagText(doc, new HistoryStack(), "Acme Corp", "P")).toThrow();
+ });
+
+ test("tags every line of a paragraph as one element", async () => {
+ const doc = await EditorDocument.open(untaggedParagraphPdf());
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ tagText(doc, new HistoryStack(), "Sales rose", "P", 0);
+
+ const saved = await readFileStructure(await savedBytes(doc));
+ const elements = saved!.pages.get(0)!.elements;
+ expect(elements.map((el) => el.type)).toEqual(["H1", "P"]);
+ expect(elements[1].mcids.length).toBeGreaterThanOrEqual(1);
+
+ const reopened = await EditorDocument.open(await savedBytes(doc));
+ opened.push(reopened);
+ PdfiumTextReader.populate(reopened, reopened.page(0));
+ for (const run of reopened.page(0).runs) {
+ expect(textTag(reopened, run.snapshot()).kind).toBe("tagged");
+ }
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/RetagInnerCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/RetagInnerCommand.ts
new file mode 100644
index 0000000000..285bf42993
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/RetagInnerCommand.ts
@@ -0,0 +1,62 @@
+import i18n from "i18next";
+import {
+ RolledBackError,
+ type Command,
+} from "@editor/tools/pdfTextEditor/commands/Command";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type {
+ StructureRole,
+ StructureType,
+} from "@editor/tools/pdfTextEditor/model/structureTypes";
+
+/**
+ * Retag element `key`, one marking part of a block's text, or remove it with
+ * null, its text read as its block's again. Held on the page's structure and
+ * written by the save; the page content keeps its marks.
+ */
+export class RetagInnerCommand implements Command {
+ readonly type = "retag-inner";
+ private readonly pageIndex: number;
+ private readonly key: string;
+ private readonly to: StructureType | null;
+ private previous: StructureRole | null | undefined;
+
+ constructor(opts: {
+ pageIndex: number;
+ key: string;
+ type: StructureType | null;
+ }) {
+ this.pageIndex = opts.pageIndex;
+ this.key = opts.key;
+ this.to = opts.type;
+ }
+
+ apply(doc: EditorDocument): void {
+ const structure = doc.structure(this.pageIndex);
+ try {
+ const previous = structure.innerType(this.key);
+ structure.setInnerType(this.key, this.to);
+ if (this.previous === undefined) this.previous = previous;
+ } catch (err) {
+ throw new RolledBackError(
+ new Error(
+ i18n.t(
+ "pdfTextEditor.inspector.accessibility.cannotRetag",
+ "This text's tag can't be changed.",
+ ),
+ { cause: err },
+ ),
+ );
+ }
+ doc.page(this.pageIndex).bumpRevision();
+ }
+
+ revert(doc: EditorDocument): void {
+ if (this.previous === undefined) return;
+ // Only an element of a standard type can be changed or removed.
+ doc
+ .structure(this.pageIndex)
+ .setInnerType(this.key, this.previous?.type ?? null);
+ doc.page(this.pageIndex).bumpRevision();
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/RetagTextCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/RetagTextCommand.ts
new file mode 100644
index 0000000000..e3d418555c
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/RetagTextCommand.ts
@@ -0,0 +1,55 @@
+import i18n from "i18next";
+import {
+ RolledBackError,
+ type Command,
+} from "@editor/tools/pdfTextEditor/commands/Command";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";
+
+/**
+ * Retag the whole block the text `mcid` marks belongs to as `type`, or drop
+ * the session's retag with null. Held on the document and written by the save pass as the
+ * element's /S; the page content keeps its marks, so it is never regenerated.
+ */
+export class RetagTextCommand implements Command {
+ readonly type = "retag-text";
+ private readonly pageIndex: number;
+ private readonly mcid: number;
+ private readonly to: StructureType | null;
+ private previous: StructureType | null | undefined;
+
+ constructor(opts: {
+ pageIndex: number;
+ mcid: number;
+ type: StructureType | null;
+ }) {
+ this.pageIndex = opts.pageIndex;
+ this.mcid = opts.mcid;
+ this.to = opts.type;
+ }
+
+ apply(doc: EditorDocument): void {
+ const structure = doc.structure(this.pageIndex);
+ if (structure.cannotRetag(this.mcid)) {
+ throw new RolledBackError(
+ new Error(
+ i18n.t(
+ "pdfTextEditor.inspector.accessibility.cannotRetag",
+ "This text's tag can't be changed.",
+ ),
+ ),
+ );
+ }
+ if (this.previous === undefined) {
+ this.previous = structure.block(this.mcid)!.type;
+ }
+ doc.setRetag(this.pageIndex, this.mcid, this.to);
+ doc.page(this.pageIndex).bumpRevision();
+ }
+
+ revert(doc: EditorDocument): void {
+ if (this.previous === undefined) return;
+ doc.setRetag(this.pageIndex, this.mcid, this.previous);
+ doc.page(this.pageIndex).bumpRevision();
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetColourCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetColourCommand.ts
index 2ac25f776c..3477333865 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetColourCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetColourCommand.ts
@@ -4,10 +4,7 @@ import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDoc
import type { RGBA } from "@editor/tools/pdfTextEditor/types";
import { PdfiumTextWriter } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextWriter";
import { collectMemberPtrs } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
-import {
- SCRATCH,
- scratchPtr,
-} from "@editor/tools/pdfTextEditor/util/wasmScratch";
+import { readObjFill } from "@editor/tools/pdfTextEditor/pdfium/PdfiumObjectColour";
import {
setScanOverride,
type ScanOverride,
@@ -113,25 +110,3 @@ export class SetColourCommand implements Command {
});
}
}
-
-/** Read an object's current fill colour (0-255 RGBA), or null on failure. */
-export function readObjFill(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
- objPtr: number,
-): RGBA | null {
- const r = scratchPtr(m, SCRATCH.colourR, 4);
- const g = scratchPtr(m, SCRATCH.colourG, 4);
- const b = scratchPtr(m, SCRATCH.colourB, 4);
- const a = scratchPtr(m, SCRATCH.colourA, 4);
- try {
- if (!m.FPDFPageObj_GetFillColor(objPtr, r, g, b, a)) return null;
- return {
- r: m.pdfium.getValue(r, "i32"),
- g: m.pdfium.getValue(g, "i32"),
- b: m.pdfium.getValue(b, "i32"),
- a: m.pdfium.getValue(a, "i32"),
- };
- } catch {
- return null;
- }
-}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetTextOutlineCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetTextOutlineCommand.ts
index cc1d173883..95d8628220 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetTextOutlineCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetTextOutlineCommand.ts
@@ -6,6 +6,7 @@ import {
applyInkState,
collectMemberPtrs,
} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { readObjStroke } from "@editor/tools/pdfTextEditor/pdfium/PdfiumObjectColour";
import {
SCRATCH,
scratchPtr,
@@ -151,13 +152,6 @@ export class SetTextOutlineCommand implements Command {
}
interface OutlineModule {
- FPDFPageObj_GetStrokeColor?: (
- obj: number,
- r: number,
- g: number,
- b: number,
- a: number,
- ) => boolean;
FPDFPageObj_GetStrokeWidth?: (obj: number, out: number) => boolean;
FPDFPageObj_SetStrokeColor?: (
obj: number,
@@ -184,21 +178,9 @@ function readMemberInk(
} catch {
/* keep the run-level value */
}
- const r = scratchPtr(m, SCRATCH.outlineR, 4);
- const g = scratchPtr(m, SCRATCH.outlineG, 4);
- const b = scratchPtr(m, SCRATCH.outlineB, 4);
- const a = scratchPtr(m, SCRATCH.outlineA, 4);
const w = scratchPtr(m, SCRATCH.outlineW, 4);
try {
- let stroke: RGBA | null = null;
- if (mod.FPDFPageObj_GetStrokeColor?.(ptr, r, g, b, a)) {
- stroke = {
- r: m.pdfium.getValue(r, "i32") & 0xff,
- g: m.pdfium.getValue(g, "i32") & 0xff,
- b: m.pdfium.getValue(b, "i32") & 0xff,
- a: m.pdfium.getValue(a, "i32") & 0xff,
- };
- }
+ const stroke = readObjStroke(m, ptr);
let strokeWidth = 0;
if (mod.FPDFPageObj_GetStrokeWidth?.(ptr, w)) {
const raw = m.pdfium.getValue(w, "float");
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagImageCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagImageCommand.ts
index 8b0f99812d..9f1c9c5c66 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagImageCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagImageCommand.ts
@@ -6,6 +6,7 @@ import {
import { descriptionCoalesceKey } from "@editor/tools/pdfTextEditor/commands/SetAltTextCommand";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import type { ImageObject } from "@editor/tools/pdfTextEditor/model/ImageObject";
+import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";
import {
ARTIFACT_TAG,
addTagMark,
@@ -17,7 +18,8 @@ import {
type RetaggableTag,
} from "@editor/tools/pdfTextEditor/util/imageAccessibility";
-const FIGURE_TAG = "Figure";
+// Marked-content tags conventionally name the structure type they mark.
+const FIGURE_TAG: StructureType = "Figure";
/**
* Tag an image as a new Figure, or as an artifact, where retaggableTag allows.
@@ -110,7 +112,7 @@ function retag(
}
if (from.kind === "figure") {
marked(removeTagMark(m, objPtr, FIGURE_TAG));
- structure.removeFigure(from.mcid);
+ structure.removeElement(from.mcid);
}
image.mcid = null;
image.artifact = false;
@@ -124,7 +126,7 @@ function retag(
marked(
addTagMark(m, doc.docPtr, objPtr, { name: FIGURE_TAG, mcid: to.mcid }),
);
- structure.addFigure(to.mcid);
+ structure.addElement(to.mcid, FIGURE_TAG);
if (to.alt !== null) structure.setAlt(to.mcid, to.alt);
image.mcid = to.mcid;
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextCommand.ts
new file mode 100644
index 0000000000..cd7c686ad6
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextCommand.ts
@@ -0,0 +1,100 @@
+import i18n from "i18next";
+import {
+ RolledBackError,
+ type Command,
+} from "@editor/tools/pdfTextEditor/commands/Command";
+import { collectMemberPtrs } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import {
+ addTagMark,
+ highestMcid,
+ innermostMcid,
+ readTagMarks,
+ removeTagMark,
+ type TagMark,
+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+import { canTagText } from "@editor/tools/pdfTextEditor/util/textAccessibility";
+
+/**
+ * Tag untagged text as a new element of `as`. Like tagging an image this
+ * changes the text's marks, so the save regenerates the page's content; the
+ * save pass then gives the element its place in the tree. Every object
+ * backing the run carries the one MCID, and the save's repair gives each
+ * sequence PDFium writes for them its own.
+ */
+export class TagTextCommand implements Command {
+ readonly type = "tag-text";
+ private readonly pageIndex: number;
+ private readonly runId: string;
+ private readonly as: StructureType;
+ /** Chosen on first apply, so a redo reuses it. */
+ private mcid: number | null = null;
+
+ constructor(opts: { pageIndex: number; runId: string; as: StructureType }) {
+ this.pageIndex = opts.pageIndex;
+ this.runId = opts.runId;
+ this.as = opts.as;
+ }
+
+ apply(doc: EditorDocument): void {
+ const page = doc.page(this.pageIndex);
+ const run = page.runs.find((r) => r.id === this.runId);
+ const members = run ? collectMemberPtrs(run) : [];
+ // Only the untagged objects: an artifact bullet beside the text stays one.
+ const ptrs = members.filter(
+ (ptr) => readTagMarks(doc.module, ptr).length === 0,
+ );
+ if (
+ !run ||
+ !canTagText(doc, run.snapshot()) ||
+ members.includes(0) ||
+ ptrs.length === 0
+ ) {
+ throw new RolledBackError(
+ new Error(
+ i18n.t(
+ "pdfTextEditor.inspector.accessibility.cannotRetag",
+ "This text's tag can't be changed.",
+ ),
+ ),
+ );
+ }
+ const structure = doc.structure(this.pageIndex);
+ this.mcid ??= structure.freeMcid(highestMcid(doc.module, page.pagePtr));
+ const tag = { name: this.as, mcid: this.mcid };
+ const marked: number[] = [];
+ for (const ptr of ptrs) {
+ if (!addTagMark(doc.module, doc.docPtr, ptr, tag)) {
+ for (const done of marked) removeTagMark(doc.module, done, this.as);
+ throw new Error("PDFium could not tag the text");
+ }
+ marked.push(ptr);
+ }
+ run.tagMarks = [tag];
+ structure.addElement(this.mcid, this.as);
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ revert(doc: EditorDocument): void {
+ if (this.mcid === null) return;
+ const page = doc.page(this.pageIndex);
+ const run = page.runs.find((r) => r.id === this.runId);
+ if (!run) return;
+ untag(doc, run, { name: this.as, mcid: this.mcid });
+ doc.structure(this.pageIndex).removeElement(this.mcid);
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+}
+
+function untag(doc: EditorDocument, run: TextRun, tag: TagMark): void {
+ for (const ptr of collectMemberPtrs(run)) {
+ if (innermostMcid(readTagMarks(doc.module, ptr)) === tag.mcid) {
+ removeTagMark(doc.module, ptr, tag.name);
+ }
+ }
+ run.tagMarks = [];
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts
new file mode 100644
index 0000000000..edd37962ae
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts
@@ -0,0 +1,676 @@
+import i18n from "i18next";
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import {
+ RolledBackError,
+ type Command,
+} from "@editor/tools/pdfTextEditor/commands/Command";
+import {
+ collectMemberPtrs,
+ measureObjBoxPt,
+ readObjTexts,
+ removeAndDestroyObject,
+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import {
+ addTextPiece,
+ charOrigins,
+ readMatrix,
+ readTextSource,
+ restoreText,
+ setPieceText,
+ type Point,
+ type TextSource,
+} from "@editor/tools/pdfTextEditor/commands/textPieces";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import {
+ isInlineType,
+ TEXT_RANGE_TYPES,
+ type StructureElement,
+} from "@editor/tools/pdfTextEditor/model/PageStructure";
+import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";
+import {
+ cloneParagraphLineSlot,
+ type TextRun,
+} from "@editor/tools/pdfTextEditor/model/TextRun";
+import {
+ ARTIFACT_TAG,
+ highestMcid,
+ innermostMcid,
+ readTagMarks,
+ type TagMark,
+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+
+/**
+ * Tag part of a run's tagged text, code units `start` to `end`, as its own
+ * element of `as`. The save pass gives the element its place: inside the
+ * element the text was cut from for an inline type, else splitting that
+ * element around it.
+ */
+export class TagTextRangeCommand implements Command {
+ readonly type = "tag-text-range";
+ private readonly pageIndex: number;
+ private readonly runId: string;
+ private readonly start: number;
+ private readonly end: number;
+ private readonly as: StructureType;
+ /** Chosen on first apply, so a redo reuses them. */
+ private mcids: { cut: number; part: number } | null = null;
+ private undo: Array<() => void> = [];
+
+ constructor(opts: {
+ pageIndex: number;
+ runId: string;
+ start: number;
+ end: number;
+ as: StructureType;
+ }) {
+ this.pageIndex = opts.pageIndex;
+ this.runId = opts.runId;
+ this.start = opts.start;
+ this.end = opts.end;
+ this.as = opts.as;
+ }
+
+ apply(doc: EditorDocument): void {
+ const page = doc.page(this.pageIndex);
+ const undo: Array<() => void> = [];
+ try {
+ this.cut(doc, page, undo);
+ } catch (err) {
+ rollBack(undo);
+ throw new RolledBackError(
+ new Error(
+ i18n.t(
+ "pdfTextEditor.inspector.accessibility.cannotRetag",
+ "This text's tag can't be changed.",
+ ),
+ { cause: err },
+ ),
+ );
+ }
+ this.undo = undo;
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ revert(doc: EditorDocument): void {
+ rollBack(this.undo);
+ this.undo = [];
+ const page = doc.page(this.pageIndex);
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ private cut(doc: EditorDocument, page: Page, undo: Array<() => void>): void {
+ const run = page.findRun(this.runId);
+ if (!run) throw new Error(`No run ${this.runId}`);
+ const structure = doc.structure(this.pageIndex);
+ const blocker = structure.cannotAddElement();
+ if (blocker) throw new Error(`The page cannot take an element: ${blocker}`);
+ if (!/\S/.test(run.text.slice(this.start, this.end))) {
+ throw new Error("The range holds no text");
+ }
+ const owner = rangeOwner(doc, run, this.start, this.end);
+ if (!isInlineType(this.as) && !structure.canSplit(owner)) {
+ throw new Error("Only a block of text can be split into blocks");
+ }
+
+ const plan = planCut(doc, page, run, this.start, this.end);
+ if (!this.mcids) {
+ const cut = structure.freeMcid(highestMcid(doc.module, page.pagePtr));
+ this.mcids = { cut, part: cut + 1 };
+ }
+ const { cut, part } = this.mcids;
+ const tagFor = (piece: Piece): TagMark =>
+ piece.group === "cut"
+ ? { name: this.as, mcid: cut }
+ : { name: piece.tag.name, mcid: part };
+ const drawn = redraw(doc, page, plan, tagFor, undo);
+ for (const affected of new Set(plan.objects.map((o) => o.leaf.run))) {
+ undo.push(snapshotRun(affected));
+ relist(doc, affected, plan, drawn);
+ keepRunTag(doc, affected);
+ }
+
+ const partMcid = (group: Group, own: number): number | null => {
+ if (!plan.pieces.some((piece) => piece.group === group)) return null;
+ return plan.redrawn.has(group) ? part : own;
+ };
+ structure.addCut(cut, this.as, {
+ from: plan.from,
+ before: partMcid("before", plan.from[0]),
+ after: partMcid("after", plan.from.at(-1)!),
+ });
+ undo.push(() => structure.removeElement(cut));
+ }
+}
+
+function rollBack(undo: Array<() => void>): void {
+ while (undo.length > 0) undo.pop()!();
+}
+
+type Group = "before" | "cut" | "after";
+
+/** Part of one object's text, code units `from` to `to`, and where it falls against the cut. */
+interface Piece {
+ ptr: number;
+ from: number;
+ to: number;
+ group: Group;
+ /** The object's own MCID tag. */
+ tag: TagMark;
+}
+
+/** An object the cut redraws some or all of, as its run lists it. */
+interface CutObject {
+ leaf: Leaf;
+ source: TextSource;
+ pieces: Piece[];
+}
+
+interface CutPlan {
+ /** The MCIDs cut from, in reading order. */
+ from: number[];
+ /** Every piece of their content, in reading order. */
+ pieces: Piece[];
+ /** The groups drawn by new objects: always the cut, and maybe one part. */
+ redrawn: ReadonlySet<Group>;
+ objects: CutObject[];
+ origins: Map<number, Map<number, Point>>;
+}
+
+/**
+ * Lay the content of every MCID the range draws out in the order the file
+ * holds it, the range's ends cutting objects into pieces. The range must be
+ * one stretch of that content, with only the first MCID keeping a part
+ * before it and only the last a part after.
+ */
+function planCut(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ start: number,
+ end: number,
+): CutPlan {
+ const m = doc.module;
+ const leafOf = pageLeaves(page);
+ const inRange = leaves(run)!.filter(
+ (leaf) => leaf.start < end && leaf.start + leaf.text.length > start,
+ );
+ const from = [
+ ...new Set(inRange.map((leaf) => ownMark(doc, leaf.ptr)!.mcid!)),
+ ];
+ const objects = pageObjects(m, page);
+ const ranged = new Map(inRange.map((leaf) => [leaf.ptr, leaf]));
+
+ const pieces: Piece[] = [];
+ for (const [n, mcid] of from.entries()) {
+ const own = objects.flatMap((ptr) => {
+ const tag = ownMark(doc, ptr);
+ if (tag?.mcid !== mcid) return [];
+ const leaf = ranged.get(ptr);
+ if (!leaf) {
+ const to = leafOf.get(ptr)?.text.length ?? 0;
+ return [{ ptr, tag, from: 0, to, cut: false }];
+ }
+ return cutLeaf(leaf, start, end).map((part) => ({ ptr, tag, ...part }));
+ });
+ const cut = own.map((part) => part.cut);
+ const first = cut.indexOf(true);
+ const last = cut.lastIndexOf(true);
+ const stretch = first >= 0 && cut.slice(first, last + 1).every(Boolean);
+ const before = first > 0 && n > 0;
+ const after = last < own.length - 1 && n < from.length - 1;
+ if (!stretch || before || after) {
+ throw new Error("The range is not one stretch of its element's text");
+ }
+ own.forEach(({ ptr, tag, from: at, to }, i) => {
+ pieces.push({ ptr, tag, from: at, to, group: groupAt(i, first, last) });
+ });
+ }
+
+ const redrawn = new Set<Group>(["cut"]);
+ const length = (group: Group) =>
+ pieces
+ .filter((piece) => piece.group === group)
+ .reduce((sum, piece) => sum + piece.to - piece.from, 0);
+ if (from.length === 1 && length("before") > 0 && length("after") > 0) {
+ redrawn.add(length("before") <= length("after") ? "before" : "after");
+ }
+
+ const cutObjects: CutObject[] = [];
+ for (const ptr of new Set(pieces.map((piece) => piece.ptr))) {
+ const own = pieces.filter((piece) => piece.ptr === ptr);
+ if (!own.some((piece) => redrawn.has(piece.group))) continue;
+ const leaf = leafOf.get(ptr);
+ const source = readTextSource(m, ptr);
+ if (!leaf || !source) {
+ throw new Error("Only text the editor reads can be redrawn");
+ }
+ cutObjects.push({ leaf, source, pieces: own });
+ }
+ verifyTexts(m, page, cutObjects);
+ return {
+ from,
+ pieces,
+ redrawn,
+ objects: cutObjects,
+ origins: originsFor(m, page, cutObjects),
+ };
+}
+
+function groupAt(i: number, first: number, last: number): Group {
+ if (i < first) return "before";
+ return i > last ? "after" : "cut";
+}
+
+/** A leaf's parts outside and inside the range, by its text's code units. */
+function cutLeaf(
+ leaf: Leaf,
+ start: number,
+ end: number,
+): Array<{ from: number; to: number; cut: boolean }> {
+ const length = leaf.text.length;
+ const cutFrom = Math.max(0, start - leaf.start);
+ const cutTo = Math.min(length, end - leaf.start);
+ return [
+ { from: 0, to: cutFrom, cut: false },
+ { from: cutFrom, to: cutTo, cut: true },
+ { from: cutTo, to: length, cut: false },
+ ].filter((part) => part.to > part.from);
+}
+
+function verifyTexts(
+ m: WrappedPdfiumModule,
+ page: Page,
+ objects: readonly CutObject[],
+): void {
+ const held = readObjTexts(
+ m,
+ page.pagePtr,
+ objects.map((o) => o.leaf.ptr),
+ );
+ if (held.some((text, i) => text !== objects[i].leaf.text)) {
+ throw new Error("The text the editor shows is not the text drawn");
+ }
+}
+
+/** Where each piece starts, for every piece that does not start its object. */
+function originsFor(
+ m: WrappedPdfiumModule,
+ page: Page,
+ objects: readonly CutObject[],
+): Map<number, Map<number, Point>> {
+ const wanted = new Map<number, Set<number>>();
+ const lengths = new Map<number, number>();
+ for (const { leaf, pieces } of objects) {
+ const offsets = pieces.map((piece) => piece.from).filter((at) => at > 0);
+ if (offsets.length === 0) continue;
+ wanted.set(leaf.ptr, new Set(offsets));
+ lengths.set(leaf.ptr, leaf.text.length);
+ }
+ const origins = charOrigins(m, page.pagePtr, wanted, lengths);
+ for (const [ptr, offsets] of wanted) {
+ if ([...offsets].some((at) => !origins.get(ptr)?.has(at))) {
+ throw new Error("PDFium cannot place a piece of the text");
+ }
+ }
+ return origins;
+}
+
+/** The objects drawing each cut object's pieces, in reading order, by the object it was. */
+type Drawn = Map<number, Array<{ ptr: number; piece: Piece }>>;
+
+/**
+ * Redraw the pieces in the redrawn groups as new objects, in reading order so
+ * PDFium writes each MCID's content in that order. An object keeping a piece
+ * is cut down to it; one keeping none is taken off the page.
+ */
+function redraw(
+ doc: EditorDocument,
+ page: Page,
+ plan: CutPlan,
+ tagFor: (piece: Piece) => TagMark,
+ undo: Array<() => void>,
+): Drawn {
+ const m = doc.module;
+ const drawn: Drawn = new Map();
+ const expected = new Map<number, string>();
+ const objectFor = new Map(plan.objects.map((o) => [o.leaf.ptr, o]));
+ for (const piece of plan.pieces) {
+ const object = objectFor.get(piece.ptr);
+ if (!object || !plan.redrawn.has(piece.group)) continue;
+ const text = object.leaf.text.slice(piece.from, piece.to);
+ const origin = startOf(object, piece, plan.origins);
+ const ptr = addTextPiece(m, doc.docPtr, page, object.source, text, origin, [
+ tagFor(piece),
+ ]);
+ if (!ptr) throw new Error("PDFium could not draw the text");
+ undo.push(() => removeAndDestroyObject(m, page.pagePtr, ptr));
+ expected.set(ptr, text);
+ drawn.set(piece.ptr, [...(drawn.get(piece.ptr) ?? []), { ptr, piece }]);
+ }
+
+ for (const object of plan.objects) {
+ const { ptr, text } = object.leaf;
+ const kept = object.pieces.find((piece) => !plan.redrawn.has(piece.group));
+ if (!kept) {
+ const index = pageObjects(m, page).indexOf(ptr);
+ m.FPDFPage_RemoveObject(page.pagePtr, ptr);
+ undo.push(() => m.FPDFPage_InsertObjectAtIndex(page.pagePtr, ptr, index));
+ continue;
+ }
+ const matrix = readMatrix(m, ptr);
+ const keptText = text.slice(kept.from, kept.to);
+ const origin = kept.from > 0 ? startOf(object, kept, plan.origins) : null;
+ if (!matrix || !setPieceText(m, ptr, keptText, origin)) {
+ throw new Error("PDFium could not redraw the text");
+ }
+ undo.push(() => restoreText(m, ptr, text, matrix));
+ expected.set(ptr, keptText);
+ const pieces = [...(drawn.get(ptr) ?? []), { ptr, piece: kept }];
+ drawn.set(
+ ptr,
+ pieces.sort((a, b) => a.piece.from - b.piece.from),
+ );
+ }
+
+ // The text page ends an object's text with a space it infers from the gap
+ // to the next, which is no glyph of the object's.
+ const read = readObjTexts(m, page.pagePtr, [...expected.keys()]);
+ if (
+ [...expected.values()].some(
+ (text, i) => read[i]?.trimEnd() !== text.trimEnd(),
+ )
+ ) {
+ throw new Error("PDFium redrew the text differently");
+ }
+ return drawn;
+}
+
+function startOf(
+ object: CutObject,
+ piece: Piece,
+ origins: ReadonlyMap<number, ReadonlyMap<number, Point>>,
+): Point {
+ if (piece.from > 0) return origins.get(object.leaf.ptr)!.get(piece.from)!;
+ return { x: object.source.matrix[4], y: object.source.matrix[5] };
+}
+
+/** List the objects now drawing a run's text in place of the ones they replace. */
+function relist(
+ doc: EditorDocument,
+ run: TextRun,
+ plan: CutPlan,
+ drawn: Drawn,
+): void {
+ const m = doc.module;
+ const replaced = plan.objects
+ .map((o) => o.leaf)
+ .filter((leaf) => leaf.run === run)
+ .sort((a, b) => b.index - a.index);
+ for (const leaf of replaced) {
+ const now = drawn.get(leaf.ptr)!;
+ const box = (ptr: number) => {
+ const measured = measureObjBoxPt(m, ptr);
+ if (!measured) return leaf.list.bounds[leaf.index];
+ return { x: measured.x, right: measured.x + measured.width };
+ };
+ const entries = {
+ ptrs: now.map((d) => d.ptr),
+ texts: now.map((d) => leaf.text.slice(d.piece.from, d.piece.to)),
+ bounds: now.map((d) => box(d.ptr)),
+ starts: now.map((d) => d.piece.from),
+ };
+ replaceEntries(leaf.list, leaf.index, entries);
+ // A paragraph keeps its first line's arrays on the run as well.
+ const first = run.mergedFromPtrs.indexOf(leaf.ptr);
+ if (run.mergedFromPtrs !== leaf.list.ptrs && first >= 0) {
+ replaceEntries(lineList(run), first, entries);
+ }
+ const j = run.paragraphLeafPtrs.indexOf(leaf.ptr);
+ if (j >= 0) {
+ run.paragraphLeafPtrs.splice(j, 1, ...entries.ptrs);
+ run.paragraphLeafContainers.splice(j, 1, ...entries.ptrs.map(() => 0));
+ }
+ run.paragraphMemberPtrs = run.paragraphMemberPtrs.map((ptr) =>
+ ptr === leaf.ptr ? entries.ptrs[0] : ptr,
+ );
+ if (run.pdfiumObjPtr === leaf.ptr) run.pdfiumObjPtr = entries.ptrs[0];
+ }
+}
+
+function replaceEntries(
+ list: LeafList,
+ index: number,
+ entries: {
+ ptrs: number[];
+ texts: string[];
+ bounds: Array<{ x: number; right: number }>;
+ starts: number[];
+ },
+): void {
+ const start = list.charStarts[index];
+ list.ptrs.splice(index, 1, ...entries.ptrs);
+ list.texts.splice(index, 1, ...entries.texts);
+ list.bounds.splice(index, 1, ...entries.bounds);
+ list.charStarts.splice(index, 1, ...entries.starts.map((at) => start + at));
+}
+
+/** One object's text in a run, where it starts in the run's text, and the arrays listing it. */
+interface Leaf {
+ run: TextRun;
+ ptr: number;
+ text: string;
+ start: number;
+ list: LeafList;
+ index: number;
+}
+
+/** A run's parallel arrays for one line's objects. */
+interface LeafList {
+ ptrs: number[];
+ texts: string[];
+ bounds: Array<{ x: number; right: number }>;
+ charStarts: number[];
+ /** Where the line starts in the run's text. */
+ base: number;
+}
+
+function lineList(run: TextRun): LeafList {
+ return {
+ ptrs: run.mergedFromPtrs,
+ texts: run.mergedFromTexts,
+ bounds: run.mergedFromBounds,
+ charStarts: run.mergedFromCharStarts,
+ base: 0,
+ };
+}
+
+/** The run's objects in reading order; null when their texts do not tile the run's. */
+function leaves(run: TextRun): Leaf[] | null {
+ const lists: LeafList[] =
+ run.paragraphLineSlots.length > 0
+ ? run.paragraphLineSlots.map((slot) => ({
+ ptrs: slot.mergedFromPtrs,
+ texts: slot.mergedFromTexts,
+ bounds: slot.mergedFromBounds,
+ charStarts: slot.mergedFromCharStarts,
+ base: slot.startChar,
+ }))
+ : [lineList(run)];
+ const out = lists.flatMap((list) =>
+ list.ptrs.map((ptr, index) => ({
+ run,
+ ptr,
+ text: list.texts[index] ?? "",
+ start: list.base + (list.charStarts[index] ?? Number.NaN),
+ list,
+ index,
+ })),
+ );
+ const tiles = out.every(
+ (leaf, i) =>
+ leaf.ptr !== 0 &&
+ run.text.slice(leaf.start, leaf.start + leaf.text.length) === leaf.text &&
+ (i === 0 || leaf.start >= out[i - 1].start + out[i - 1].text.length),
+ );
+ return out.length > 0 && tiles ? out : null;
+}
+
+/** Every page-level object a run lists, and where. */
+function pageLeaves(page: Page): Map<number, Leaf> {
+ const out = new Map<number, Leaf>();
+ for (const run of page.runs) {
+ for (const leaf of leaves(run) ?? []) out.set(leaf.ptr, leaf);
+ }
+ return out;
+}
+
+/** The page's top-level objects, in the order PDFium writes them. */
+function pageObjects(m: WrappedPdfiumModule, page: Page): number[] {
+ return Array.from({ length: m.FPDFPage_CountObjects(page.pagePtr) }, (_, i) =>
+ m.FPDFPage_GetObject(page.pagePtr, i),
+ );
+}
+
+/**
+ * The element owning every object the range draws. Throws when the run's
+ * objects cannot be mapped to its text, or the range holds untagged or
+ * artifact text, or text of more than one element.
+ */
+function rangeOwner(
+ doc: EditorDocument,
+ run: TextRun,
+ start: number,
+ end: number,
+): StructureElement {
+ const all = leaves(run);
+ if (!all) throw new Error("The run's objects do not match its text");
+ const inRange = all.filter(
+ (leaf) => leaf.start < end && leaf.start + leaf.text.length > start,
+ );
+ const structure = doc.structure(run.pageIndex);
+ const owners = new Set(
+ inRange.map((leaf) => {
+ const mcid = ownMark(doc, leaf.ptr)?.mcid ?? null;
+ return mcid === null ? null : structure.element(mcid);
+ }),
+ );
+ const [owner] = owners;
+ if (owners.size !== 1 || !owner) {
+ throw new Error("The range must be text of one element");
+ }
+ return owner;
+}
+
+/**
+ * The types code units `start` to `end` of run `runId` can be tagged as:
+ * every TEXT_RANGE_TYPES entry, only the inline ones when the text's element
+ * is not a block it can split, or none. Checks what apply refuses, without
+ * changing anything.
+ */
+export function rangeTagTypes(
+ doc: EditorDocument,
+ pageIndex: number,
+ runId: string,
+ start: number,
+ end: number,
+): StructureType[] {
+ const run = doc.page(pageIndex).findRun(runId);
+ const structure = doc.structure(pageIndex);
+ if (!run || structure.cannotAddElement()) return [];
+ if (!/\S/.test(run.text.slice(start, end))) return [];
+ let owner: StructureElement;
+ try {
+ owner = rangeOwner(doc, run, start, end);
+ } catch {
+ return [];
+ }
+ const splits = structure.canSplit(owner);
+ return TEXT_RANGE_TYPES.filter((type) => splits || isInlineType(type));
+}
+
+/** A stretch of a run's text, code units `start` to `end`, that one element marks. */
+export interface ElementStretch {
+ start: number;
+ end: number;
+ element: StructureElement;
+}
+
+/**
+ * The stretches of run `runId`'s text each element marks, in reading order:
+ * one for each series of the run's objects one element marks. Untagged and
+ * artifact text is left out, and every stretch when the run's objects cannot
+ * be mapped to its text.
+ */
+export function elementStretches(
+ doc: EditorDocument,
+ pageIndex: number,
+ runId: string,
+): ElementStretch[] {
+ const run = doc.page(pageIndex).findRun(runId);
+ const all = run ? leaves(run) : null;
+ if (!all) return [];
+ const structure = doc.structure(pageIndex);
+ const out: ElementStretch[] = [];
+ let previous: StructureElement | null = null;
+ for (const leaf of all) {
+ const mcid = ownMark(doc, leaf.ptr)?.mcid ?? null;
+ const element = mcid === null ? null : structure.element(mcid);
+ const end = leaf.start + leaf.text.length;
+ if (element && element === previous) out.at(-1)!.end = end;
+ else if (element) out.push({ start: leaf.start, end, element });
+ previous = element;
+ }
+ return out;
+}
+
+/** The object's innermost tag with an MCID; null for an artifact or untagged object. */
+function ownMark(doc: EditorDocument, ptr: number): TagMark | null {
+ const marks = readTagMarks(doc.module, ptr);
+ if (marks.some((mark) => mark.name === ARTIFACT_TAG)) return null;
+ const mcid = innermostMcid(marks);
+ return [...marks].reverse().find((mark) => mark.mcid === mcid) ?? null;
+}
+
+/**
+ * Keep the run's tag one its objects still carry, since text typed into the
+ * run is given it: the first tagged object's when the cut took the last of
+ * its own.
+ */
+function keepRunTag(doc: EditorDocument, run: TextRun): void {
+ const marks = collectMemberPtrs(run).map((ptr) =>
+ readTagMarks(doc.module, ptr),
+ );
+ const own = innermostMcid(run.tagMarks);
+ if (marks.some((tags) => innermostMcid(tags) === own)) return;
+ run.tagMarks = marks.find((tags) => innermostMcid(tags) !== null) ?? [];
+}
+
+/** Restores what `relist` and `keepRunTag` change on a run. */
+function snapshotRun(run: TextRun): () => void {
+ const line = {
+ ptrs: [...run.mergedFromPtrs],
+ texts: [...run.mergedFromTexts],
+ bounds: run.mergedFromBounds.map((b) => ({ ...b })),
+ charStarts: [...run.mergedFromCharStarts],
+ };
+ const slots = run.paragraphLineSlots.map(cloneParagraphLineSlot);
+ const leafPtrs = [...run.paragraphLeafPtrs];
+ const leafContainers = [...run.paragraphLeafContainers];
+ const memberPtrs = [...run.paragraphMemberPtrs];
+ const { pdfiumObjPtr, tagMarks } = run;
+ return () => {
+ run.mergedFromPtrs = line.ptrs;
+ run.mergedFromTexts = line.texts;
+ run.mergedFromBounds = line.bounds;
+ run.mergedFromCharStarts = line.charStarts;
+ run.paragraphLineSlots = slots;
+ run.paragraphLeafPtrs = leafPtrs;
+ run.paragraphLeafContainers = leafContainers;
+ run.paragraphMemberPtrs = memberPtrs;
+ run.pdfiumObjPtr = pdfiumObjPtr;
+ run.tagMarks = tagMarks;
+ };
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/textPieces.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/textPieces.ts
new file mode 100644
index 0000000000..ef8524c4f4
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/textPieces.ts
@@ -0,0 +1,213 @@
+/**
+ * Redrawing part of a text object's text as an object of its own, for giving
+ * that part a tag of its own. PDFium shares one set of marks between every
+ * object a marked-content sequence draws, so changing one object's marks
+ * changes them all; a fresh object has marks of its own.
+ */
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import { writeUtf16 } from "@editor/services/pdfiumService";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import type { RGBA } from "@editor/tools/pdfTextEditor/types";
+import {
+ readObjFill,
+ readObjStroke,
+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumObjectColour";
+import {
+ addTagMark,
+ type TagMark,
+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+import {
+ SCRATCH,
+ scratchPtr,
+} from "@editor/tools/pdfTextEditor/util/wasmScratch";
+
+const FPDF_PAGEOBJ_TEXT = 1;
+
+/** How a text object draws its text, read before it is changed. */
+export interface TextSource {
+ font: number;
+ size: number;
+ matrix: Float32Array;
+ fill: RGBA | null;
+ stroke: RGBA | null;
+ strokeWidth: number | null;
+ renderMode: number;
+}
+
+export interface Point {
+ x: number;
+ y: number;
+}
+
+/** Null for an object that is not text, or whose font or matrix cannot be read. */
+export function readTextSource(
+ m: WrappedPdfiumModule,
+ objPtr: number,
+): TextSource | null {
+ if (m.FPDFPageObj_GetType(objPtr) !== FPDF_PAGEOBJ_TEXT) return null;
+ const font = m.FPDFTextObj_GetFont(objPtr);
+ const sizePtr = scratchPtr(m, SCRATCH.splitFontSize, 4);
+ const matrix = readMatrix(m, objPtr);
+ if (!font || !matrix || !m.FPDFTextObj_GetFontSize(objPtr, sizePtr)) {
+ return null;
+ }
+ const width = scratchPtr(m, SCRATCH.splitStrokeWidth, 4);
+ return {
+ font,
+ size: m.pdfium.getValue(sizePtr, "float"),
+ matrix,
+ fill: readObjFill(m, objPtr),
+ stroke: readObjStroke(m, objPtr),
+ strokeWidth: m.FPDFPageObj_GetStrokeWidth(objPtr, width)
+ ? m.pdfium.getValue(width, "float")
+ : null,
+ renderMode: m.FPDFTextObj_GetTextRenderMode(objPtr),
+ };
+}
+
+/**
+ * Where each character starting at the wanted code units of each object's
+ * text is drawn, in page space. An object is left out when the text page's
+ * characters for it do not tile `lengths` code units, so none of its
+ * positions can be trusted.
+ */
+export function charOrigins(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ wanted: ReadonlyMap<number, ReadonlySet<number>>,
+ lengths: ReadonlyMap<number, number>,
+): Map<number, Map<number, Point>> {
+ const found = new Map<number, Map<number, Point>>();
+ const units = new Map<number, number>();
+ const textPage = m.FPDFText_LoadPage(pagePtr);
+ if (!textPage) return found;
+ try {
+ const xPtr = scratchPtr(m, SCRATCH.splitOriginX, 8);
+ const yPtr = scratchPtr(m, SCRATCH.splitOriginY, 8);
+ const count = m.FPDFText_CountChars(textPage);
+ for (let i = 0; i < count; i++) {
+ const objPtr = m.FPDFText_GetTextObject(textPage, i);
+ const offsets = wanted.get(objPtr);
+ if (!offsets || m.FPDFText_IsGenerated(textPage, i) === 1) continue;
+ const at = units.get(objPtr) ?? 0;
+ if (
+ offsets.has(at) &&
+ m.FPDFText_GetCharOrigin(textPage, i, xPtr, yPtr)
+ ) {
+ const origins = found.get(objPtr) ?? new Map<number, Point>();
+ origins.set(at, {
+ x: m.pdfium.getValue(xPtr, "double"),
+ y: m.pdfium.getValue(yPtr, "double"),
+ });
+ found.set(objPtr, origins);
+ }
+ units.set(
+ objPtr,
+ at + (m.FPDFText_GetUnicode(textPage, i) > 0xffff ? 2 : 1),
+ );
+ }
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ }
+ for (const objPtr of [...found.keys()]) {
+ if (units.get(objPtr) !== lengths.get(objPtr)) found.delete(objPtr);
+ }
+ return found;
+}
+
+/**
+ * Draw `text` as `source` draws its own, starting at `origin`, as a new
+ * object last on the page carrying `tags`. Re-encoded through the font, so
+ * any kerning or character spacing the source applied is lost. Returns 0
+ * when PDFium cannot create it.
+ */
+export function addTextPiece(
+ m: WrappedPdfiumModule,
+ docPtr: number,
+ page: Page,
+ source: TextSource,
+ text: string,
+ origin: Point,
+ tags: readonly TagMark[],
+): number {
+ const ptr = m.FPDFPageObj_CreateTextObj(docPtr, source.font, source.size);
+ if (!ptr) return 0;
+ if (!setText(m, ptr, text)) {
+ m.FPDFPageObj_Destroy(ptr);
+ return 0;
+ }
+ const matrix = Float32Array.from(source.matrix);
+ matrix[4] = origin.x;
+ matrix[5] = origin.y;
+ writeMatrix(m, ptr, matrix);
+ const { fill, stroke } = source;
+ if (fill) m.FPDFPageObj_SetFillColor(ptr, fill.r, fill.g, fill.b, fill.a);
+ if (stroke) {
+ m.FPDFPageObj_SetStrokeColor(ptr, stroke.r, stroke.g, stroke.b, stroke.a);
+ }
+ if (source.strokeWidth !== null) {
+ m.FPDFPageObj_SetStrokeWidth(ptr, source.strokeWidth);
+ }
+ m.FPDFTextObj_SetTextRenderMode(ptr, source.renderMode);
+ for (const tag of tags) addTagMark(m, docPtr, ptr, tag);
+ m.FPDFPage_InsertObject(page.pagePtr, ptr);
+ return ptr;
+}
+
+/** Give an existing object `text`, starting at `origin`: its own when null. */
+export function setPieceText(
+ m: WrappedPdfiumModule,
+ objPtr: number,
+ text: string,
+ origin: Point | null,
+): boolean {
+ const matrix = readMatrix(m, objPtr);
+ if (!matrix || !setText(m, objPtr, text)) return false;
+ if (origin) {
+ matrix[4] = origin.x;
+ matrix[5] = origin.y;
+ }
+ writeMatrix(m, objPtr, matrix);
+ return true;
+}
+
+/** Restore an object `setPieceText` changed. */
+export function restoreText(
+ m: WrappedPdfiumModule,
+ objPtr: number,
+ text: string,
+ matrix: Float32Array,
+): void {
+ setText(m, objPtr, text);
+ writeMatrix(m, objPtr, matrix);
+}
+
+export function readMatrix(
+ m: WrappedPdfiumModule,
+ objPtr: number,
+): Float32Array | null {
+ const buf = scratchPtr(m, SCRATCH.splitMatrix, 6 * 4);
+ if (!m.FPDFPageObj_GetMatrix(objPtr, buf)) return null;
+ return Float32Array.from({ length: 6 }, (_, i) =>
+ m.pdfium.getValue(buf + i * 4, "float"),
+ );
+}
+
+function writeMatrix(
+ m: WrappedPdfiumModule,
+ objPtr: number,
+ matrix: Float32Array,
+): void {
+ const buf = scratchPtr(m, SCRATCH.splitMatrix, 6 * 4);
+ matrix.forEach((value, i) => m.pdfium.setValue(buf + i * 4, value, "float"));
+ m.FPDFPageObj_SetMatrix(objPtr, buf);
+}
+
+function setText(m: WrappedPdfiumModule, objPtr: number, text: string) {
+ const buf = writeUtf16(m, text);
+ try {
+ return m.FPDFText_SetText(objPtr, buf);
+ } finally {
+ m.pdfium.wasmExports.free(buf);
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
index 529b3202c1..5b1d526e1a 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useState } from "react";
import { Box, Center, Group, Stack, Tabs, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Icon } from "@editor/ui/Icon";
+import { useHeadingOutline } from "@editor/tools/pdfTextEditor/hooks/useHeadingOutline";
import { useToolbarController } from "@editor/tools/pdfTextEditor/hooks/useToolbarController";
import { useSelectionGeometry } from "@editor/tools/pdfTextEditor/hooks/useSelectionGeometry";
import { DocumentInspector } from "@editor/tools/pdfTextEditor/components/inspector/DocumentInspector";
@@ -77,7 +78,7 @@ export function EditorSidebar({
const fontNote = useSelectedFontNote(state, selection);
const editorDocument = store.document;
- const reviewingImages = useMemo(
+ const reviewingAccessibility = useMemo(
() => ACCESSIBILITY_EDITING && !!editorDocument?.isTagged(),
[editorDocument],
);
@@ -85,10 +86,17 @@ export function EditorSidebar({
// Counts and Next cover only pages already read, which is just the first few
// until the rest scroll into view.
useEffect(() => {
- if (!reviewingImages || (tab !== "document" && !imageSelected)) return;
+ if (!reviewingAccessibility || (tab !== "document" && !imageSelected)) {
+ return;
+ }
const id = window.setTimeout(() => ensureAllPagesRead(store), 0);
return () => window.clearTimeout(id);
- }, [reviewingImages, tab, imageSelected, store]);
+ }, [reviewingAccessibility, tab, imageSelected, store]);
+ const headings = useHeadingOutline(
+ store,
+ state,
+ reviewingAccessibility && tab === "document",
+ );
// Following the selection only catches one appearing, so moving from one
// selected image to the next would leave the new one's description hidden.
@@ -167,8 +175,10 @@ export function EditorSidebar({
onSetGroupingMode={onSetGroupingMode}
onSetWidthMode={onSetWidthMode}
onSetShowRulers={onSetShowRulers}
- imageReview={reviewingImages ? controller.imageReview : null}
+ imageReview={reviewingAccessibility ? controller.imageReview : null}
onSelectNextImageToReview={selectNextImageToReview}
+ headingOutline={headings.outline}
+ onSelectHeading={headings.selectHeading}
/>
</Tabs.Panel>
</Box>
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/PageStage.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/PageStage.tsx
index 416f5c7996..0c5cb08ec5 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/PageStage.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/PageStage.tsx
@@ -361,6 +361,10 @@ export function PageStage() {
if (shiftKey) store.selection.toggle(runId);
else store.selection.selectOne(runId);
}}
+ onSelectRunText={(runId, range) =>
+ store.selection.setTextRange(runId, range)
+ }
+ selectedTextRange={selection.textRange}
onSelectImage={(imageId) =>
store.selection.selectImage(imageId)
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
index 7c0b969a9e..dc6aabd552 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
@@ -4,7 +4,10 @@ import { useTranslation } from "react-i18next";
import { Button } from "@editor/ui/Button";
import { PdfiumPageRenderer } from "@editor/tools/pdfTextEditor/pdfium/PdfiumPageRenderer";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
-import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";
+import type {
+ PageSnapshot,
+ TextRange,
+} from "@editor/tools/pdfTextEditor/types";
import { TextRunOverlay } from "@editor/tools/pdfTextEditor/components/TextRunOverlay";
import { TableOverlay } from "@editor/tools/pdfTextEditor/components/TableOverlay";
import { ACCESSIBILITY_EDITING } from "@editor/constants/featureFlags";
@@ -49,6 +52,10 @@ interface PageViewProps {
dy: number,
) => void;
onEditRun: (pageIndex: number, runId: string, nextText: string) => void;
+ /** The characters selected inside a run's box, while it has focus. */
+ onSelectRunText?: (runId: string, range: TextRange | null) => void;
+ /** The characters selected inside the one selected run. */
+ selectedTextRange?: TextRange | null;
/** Ctrl+drag committed; dx/dy in PDF points. */
onMoveRun?: (
pageIndex: number,
@@ -102,6 +109,8 @@ export function PageView({
onSelectShape,
onMoveShape,
onEditRun,
+ onSelectRunText,
+ selectedTextRange,
onMoveRun,
onWrapRun,
onResizeRun,
@@ -418,6 +427,16 @@ export function PageView({
highlighted={highlightedRunId === run.id}
onSelect={(shiftKey) => onSelectRun(run.id, shiftKey)}
onEdit={(nextText) => onEditRun(page.pageIndex, run.id, nextText)}
+ onTextRangeChange={
+ ACCESSIBILITY_EDITING
+ ? (range) => onSelectRunText?.(run.id, range)
+ : undefined
+ }
+ textRange={
+ selectedRunIds.length === 1 && selectedRunIds[0] === run.id
+ ? selectedTextRange
+ : null
+ }
onMove={(dx, dy) => onMoveRun?.(page.pageIndex, run.id, dx, dy)}
onWrap={(maxWidthPt) =>
onWrapRun?.(page.pageIndex, run.id, maxWidthPt)
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.css b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.css
index 8bccca1bc2..d385a8d9b7 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.css
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.css
@@ -22,3 +22,8 @@
color: transparent;
-webkit-text-fill-color: transparent;
}
+
+/* Must stay in sync with TEXT_RANGE_HIGHLIGHT in overlayPainter.ts. */
+::highlight(pdf-editor-text-range) {
+ background-color: color-mix(in srgb, var(--c-primary) 28%, transparent);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx
index 4d8f55f697..0ca35a8900 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx
@@ -1,6 +1,7 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import type {
+ TextRange,
TextRunSnapshot,
WidthMode,
} from "@editor/tools/pdfTextEditor/types";
@@ -30,8 +31,11 @@ import {
normalizeContainerCaret,
type PaintLine,
paintLines,
+ highlightTextRange,
paintPlainText,
plainCaretOffset,
+ plainDomRange,
+ plainSelectionRange,
readOverlayText,
refitEditedTokens,
refitTokens,
@@ -317,6 +321,10 @@ interface TextRunOverlayProps {
onWrap?: (maxWidthPt: number) => void;
/** Fires when the user drags the right edge to a new width, in PDF points. */
onResize?: (widthPt: number) => void;
+ /** Fires while the box has focus, as the characters selected inside it change. */
+ onTextRangeChange?: (range: TextRange | null) => void;
+ /** The characters selected inside the box, highlighted while it has no focus. */
+ textRange?: TextRange | null;
}
/**
@@ -368,6 +376,8 @@ export function TextRunOverlay({
onMove,
onWrap,
onResize,
+ onTextRangeChange,
+ textRange,
}: TextRunOverlayProps) {
const { t } = useTranslation();
// Subscribed, so toggling the preference re-renders every overlay.
@@ -375,6 +385,21 @@ export function TextRunOverlay({
const ref = useRef<HTMLDivElement | null>(null);
const [hovered, setHovered] = useState(false);
const [focused, setFocused] = useState(false);
+ // Only while focused: blurring clears the browser's selection, and the
+ // range must outlive that for the inspector to act on it.
+ useEffect(() => {
+ if (!focused || !onTextRangeChange) return;
+ const report = () => {
+ const el = ref.current;
+ const selection = window.getSelection();
+ if (!el || !selection?.focusNode || !el.contains(selection.focusNode)) {
+ return;
+ }
+ onTextRangeChange(plainSelectionRange(el));
+ };
+ document.addEventListener("selectionchange", report);
+ return () => document.removeEventListener("selectionchange", report);
+ }, [focused, onTextRangeChange]);
// Masking a run the user has only clicked into swaps real PDF ink for a
// CSS approximation, so hold the pristine bitmap until an actual edit.
const [touched, setTouchedState] = useState(false);
@@ -640,6 +665,16 @@ export function TextRunOverlay({
if (caret !== null && ownsFocus) restoreCaretOffset(el, caret);
}, [run.text, freshExact, font, fontSizePx, touched, faceEpoch]);
+ // After the paint above, which replaces the nodes a range would hold. The
+ // browser's own selection goes with the focus, as when the inspector is
+ // used, so the stored range is painted in its place.
+ useEffect(() => {
+ const el = ref.current;
+ if (focused || !textRange || !el) return;
+ const range = plainDomRange(el, textRange);
+ return range ? highlightTextRange(range) : undefined;
+ }, [focused, textRange, run.text, freshExact, font, fontSizePx, faceEpoch]);
+
const anchor = transform.apply(run.matrix.e, run.matrix.f);
const flowLeft = anchor.x * scale;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsx
index 46a25b1f84..d67d009af8 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsx
@@ -17,6 +17,8 @@ function renderInspector(imageReview: ImageReview | null, onNext = vi.fn()) {
onSetShowRulers={vi.fn()}
imageReview={imageReview}
onSelectNextImageToReview={onNext}
+ headingOutline={null}
+ onSelectHeading={vi.fn()}
/>
</MantineProvider>,
);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsx
index 514c23744a..043eaf87f3 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsx
@@ -19,6 +19,8 @@ import type {
WidthMode,
} from "@editor/tools/pdfTextEditor/types";
import type { ImageReview } from "@editor/tools/pdfTextEditor/util/imageAccessibility";
+import type { HeadingOutline } from "@editor/tools/pdfTextEditor/util/headingOutline";
+import { HeadingOutlineSection } from "@editor/tools/pdfTextEditor/components/inspector/HeadingOutlineSection";
interface Props {
pages: PageSnapshot[];
@@ -31,6 +33,9 @@ interface Props {
/** Images needing attention; null when there is nothing to review. */
imageReview: ImageReview | null;
onSelectNextImageToReview: () => void;
+ /** Null when there is nothing to check. */
+ headingOutline: HeadingOutline | null;
+ onSelectHeading: (index: number) => void;
}
/** Facts about the open document. Nothing here acts on a selection. */
@@ -38,6 +43,8 @@ export function DocumentInspector({
pages,
imageReview,
onSelectNextImageToReview,
+ headingOutline,
+ onSelectHeading,
...settings
}: Props) {
const { t } = useTranslation();
@@ -70,6 +77,12 @@ export function DocumentInspector({
onNext={onSelectNextImageToReview}
/>
)}
+ {headingOutline && (
+ <HeadingOutlineSection
+ outline={headingOutline}
+ onSelect={onSelectHeading}
+ />
+ )}
<FontsSection pages={pages} />
<DocumentSettings {...settings} />
</Stack>
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/HeadingOutlineSection.css b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/HeadingOutlineSection.css
new file mode 100644
index 0000000000..e1d1723172
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/HeadingOutlineSection.css
@@ -0,0 +1,29 @@
+/* One line of xs text, so rows keep the stat rows' rhythm. The negative
+ margin lets the hover background extend past the text without indenting it. */
+.pdf-editor-heading-outline__entry {
+ display: block;
+ width: calc(100% + 0.5rem);
+ margin: 0 -0.25rem;
+ padding: 0 0.25rem;
+ border: 0;
+ border-radius: 0.25rem;
+ background: transparent;
+ color: var(--c-text);
+ font: inherit;
+ font-size: var(--mantine-font-size-xs);
+ line-height: var(--mantine-line-height-xs);
+ text-align: left;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ cursor: pointer;
+}
+
+.pdf-editor-heading-outline__entry:hover:not(:disabled) {
+ background: var(--c-hover);
+}
+
+.pdf-editor-heading-outline__entry:disabled {
+ color: var(--c-text-muted);
+ cursor: default;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/HeadingOutlineSection.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/HeadingOutlineSection.test.tsx
new file mode 100644
index 0000000000..cc9a7ef916
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/HeadingOutlineSection.test.tsx
@@ -0,0 +1,78 @@
+import { MantineProvider } from "@mantine/core";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { HeadingOutlineSection } from "@editor/tools/pdfTextEditor/components/inspector/HeadingOutlineSection";
+import type { TextRunSnapshot } from "@editor/tools/pdfTextEditor/types";
+import type {
+ HeadingOutline,
+ OutlineEntry,
+} from "@editor/tools/pdfTextEditor/util/headingOutline";
+
+const KEY = "pdfTextEditor.inspector.accessibility.outline";
+
+function renderOutline(outline: HeadingOutline, onSelect = vi.fn()) {
+ render(
+ <MantineProvider env="test">
+ <HeadingOutlineSection outline={outline} onSelect={onSelect} />
+ </MantineProvider>,
+ );
+ return onSelect;
+}
+
+const entry = (
+ level: number,
+ text: string | null,
+ issue: OutlineEntry["issue"] = null,
+): OutlineEntry => ({
+ type: `H${level}` as OutlineEntry["type"],
+ level,
+ pageIndex: 1,
+ run: text === null ? null : ({ id: text, text } as TextRunSnapshot),
+ range: null,
+ issue,
+});
+
+describe("HeadingOutlineSection", () => {
+ it("lists headings indented by level and selects the one clicked", () => {
+ const onSelect = renderOutline({
+ entries: [
+ entry(1, "Quarterly report"),
+ entry(2, "Regional\nperformance"),
+ ],
+ mixesNumbering: false,
+ });
+ const rows = screen.getAllByTestId("pdf-editor-heading-entry");
+ expect(rows.map((row) => row.dataset.level)).toEqual(["1", "2"]);
+ fireEvent.click(screen.getByText("Regional performance"));
+ expect(onSelect).toHaveBeenCalledWith(1);
+ });
+
+ it("shows each issue under its heading and counts them", () => {
+ renderOutline({
+ entries: [
+ entry(1, "Quarterly report"),
+ entry(3, "Outlook", { kind: "skipped-level", previous: 1 }),
+ ],
+ mixesNumbering: true,
+ });
+ expect(screen.getByTestId("pdf-editor-heading-issue")).toHaveTextContent(
+ `${KEY}.skippedLevel`,
+ );
+ expect(screen.getByTestId("pdf-editor-heading-mixed")).toBeVisible();
+ expect(screen.getByTestId("pdf-editor-heading-problems")).toHaveTextContent(
+ "2",
+ );
+ });
+
+ it("names a heading by its page until that page is read", () => {
+ renderOutline({ entries: [entry(1, null)], mixesNumbering: false });
+ expect(screen.getByTestId("pdf-editor-heading-entry")).toHaveTextContent(
+ `${KEY}.onPage`,
+ );
+ });
+
+ it("says when there are no headings", () => {
+ renderOutline({ entries: [], mixesNumbering: false });
+ expect(screen.getByTestId("pdf-editor-heading-none")).toBeVisible();
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/HeadingOutlineSection.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/HeadingOutlineSection.tsx
new file mode 100644
index 0000000000..cf65467939
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/HeadingOutlineSection.tsx
@@ -0,0 +1,153 @@
+import { Box, Divider, Group, Stack, Text } from "@mantine/core";
+import type { TFunction } from "i18next";
+import { useTranslation } from "react-i18next";
+import { Icon } from "@editor/ui/Icon";
+import {
+ Section,
+ SectionLabel,
+ StatRow,
+} from "@editor/tools/pdfTextEditor/components/inspector/InspectorPrimitives";
+import {
+ issueCount,
+ type HeadingIssue,
+ type HeadingOutline,
+ type OutlineEntry,
+} from "@editor/tools/pdfTextEditor/util/headingOutline";
+import "@editor/tools/pdfTextEditor/components/inspector/HeadingOutlineSection.css";
+
+const INDENT_PX = 12;
+
+/** The document's headings in reading order, each issue under the heading it belongs to. */
+export function HeadingOutlineSection({
+ outline,
+ onSelect,
+}: {
+ outline: HeadingOutline;
+ onSelect: (index: number) => void;
+}) {
+ const { t } = useTranslation();
+ return (
+ <Section testId="pdf-editor-heading-outline">
+ <SectionLabel>
+ {t("pdfTextEditor.inspector.accessibility.outline.heading", "Headings")}
+ </SectionLabel>
+ <Stack gap={4}>
+ <StatRow
+ label={t(
+ "pdfTextEditor.inspector.accessibility.outline.problems",
+ "Heading problems",
+ )}
+ value={
+ <span data-testid="pdf-editor-heading-problems">
+ {issueCount(outline)}
+ </span>
+ }
+ />
+ {outline.mixesNumbering && (
+ <IssueText
+ text={t(
+ "pdfTextEditor.inspector.accessibility.outline.mixedNumbering",
+ "Mixes numbered and unnumbered headings",
+ )}
+ testId="pdf-editor-heading-mixed"
+ />
+ )}
+ <Divider my={4} />
+ {outline.entries.length === 0 ? (
+ <Text size="xs" c="dimmed" data-testid="pdf-editor-heading-none">
+ {t(
+ "pdfTextEditor.inspector.accessibility.outline.none",
+ "No headings",
+ )}
+ </Text>
+ ) : (
+ outline.entries.map((entry, index) => (
+ <OutlineRow
+ // Headings carry no identity of their own; their order is fixed for the read.
+ key={index}
+ entry={entry}
+ onSelect={() => onSelect(index)}
+ />
+ ))
+ )}
+ </Stack>
+ </Section>
+ );
+}
+
+function headingText({ run, range }: OutlineEntry): string {
+ if (!run) return "";
+ return range ? run.text.slice(range.start, range.end) : run.text;
+}
+
+function OutlineRow({
+ entry,
+ onSelect,
+}: {
+ entry: OutlineEntry;
+ onSelect: () => void;
+}) {
+ const { t } = useTranslation();
+ const label =
+ headingText(entry).replace(/\s+/g, " ").trim() ||
+ (entry.pageIndex === null
+ ? t(
+ "pdfTextEditor.inspector.accessibility.outline.empty",
+ "Heading with no text",
+ )
+ : t(
+ "pdfTextEditor.inspector.accessibility.outline.onPage",
+ "Heading on page {{page}}",
+ { page: entry.pageIndex + 1 },
+ ));
+ return (
+ <Box
+ pl={((entry.level ?? 1) - 1) * INDENT_PX}
+ data-testid="pdf-editor-heading-entry"
+ data-level={entry.level ?? undefined}
+ >
+ <button
+ type="button"
+ className="pdf-editor-heading-outline__entry"
+ title={label}
+ disabled={entry.pageIndex === null}
+ onClick={onSelect}
+ >
+ {label}
+ </button>
+ {entry.issue && (
+ <IssueText
+ text={issueText(t, entry.issue)}
+ testId="pdf-editor-heading-issue"
+ />
+ )}
+ </Box>
+ );
+}
+
+function IssueText({ text, testId }: { text: string; testId: string }) {
+ return (
+ <Group gap={4} wrap="nowrap" c="var(--c-warning)" data-testid={testId}>
+ <Icon name="triangle-alert" size={14} style={{ flexShrink: 0 }} />
+ <Text size="xs" c="var(--c-warning)">
+ {text}
+ </Text>
+ </Group>
+ );
+}
+
+function issueText(t: TFunction, issue: HeadingIssue): string {
+ switch (issue.kind) {
+ case "first-not-h1":
+ return t(
+ "pdfTextEditor.inspector.accessibility.outline.firstNotH1",
+ "First heading should be Heading 1",
+ );
+ case "skipped-level":
+ return t(
+ "pdfTextEditor.inspector.accessibility.outline.skippedLevel",
+ "Skips a level after Heading {{previous}}",
+ { previous: issue.previous },
+ );
+ }
+}
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 46233afa5a..51a2863a96 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx
@@ -15,6 +15,7 @@ import type { SelectionState } from "@editor/tools/pdfTextEditor/types";
import { modShortcut } from "@editor/utils/hotkeys";
import { ACCESSIBILITY_EDITING } from "@editor/constants/featureFlags";
import { ImageAccessibilitySection } from "@editor/tools/pdfTextEditor/components/inspector/ImageAccessibilitySection";
+import { TextAccessibilitySection } from "@editor/tools/pdfTextEditor/components/inspector/TextAccessibilitySection";
export type InspectorController = ReturnType<typeof useToolbarController>;
@@ -73,6 +74,13 @@ export function SelectionInspector({
/>
)}
{hasImageSelection && <ImageSection controller={controller} />}
+ {ACCESSIBILITY_EDITING && controller.textTag && (
+ <TextAccessibilitySection
+ tag={controller.textTag}
+ onSetTag={controller.onSetTextTag}
+ inner={controller.innerTextTags}
+ />
+ )}
{ACCESSIBILITY_EDITING && controller.imageAccessibility && (
<ImageAccessibilitySection
accessibility={controller.imageAccessibility}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.css b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.css
new file mode 100644
index 0000000000..f10923df5f
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.css
@@ -0,0 +1,40 @@
+/* One line of xs text, matching the heading outline's rows. The negative
+ margin lets the hover background extend past the text without indenting it. */
+.pdf-editor-inner-tag__entry {
+ display: flex;
+ gap: 0.5rem;
+ width: calc(100% + 0.5rem);
+ margin: 0 -0.25rem;
+ padding: 0 0.25rem;
+ border: 0;
+ border-radius: 0.25rem;
+ background: transparent;
+ color: var(--c-text);
+ font: inherit;
+ font-size: var(--mantine-font-size-xs);
+ line-height: var(--mantine-line-height-xs);
+ text-align: left;
+ cursor: pointer;
+}
+
+.pdf-editor-inner-tag__entry:hover {
+ background: var(--c-hover);
+}
+
+.pdf-editor-inner-tag__entry[aria-pressed="true"] {
+ background: var(--c-active);
+}
+
+.pdf-editor-inner-tag__number {
+ flex-shrink: 0;
+ min-width: 1ch;
+ color: var(--c-text-muted);
+ font-variant-numeric: tabular-nums;
+}
+
+.pdf-editor-inner-tag__text {
+ min-width: 0;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
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
new file mode 100644
index 0000000000..a8db7459b9
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.test.tsx
@@ -0,0 +1,201 @@
+import { MantineProvider } from "@mantine/core";
+import { fireEvent, render, screen, within } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { TextAccessibilitySection } from "@editor/tools/pdfTextEditor/components/inspector/TextAccessibilitySection";
+import { structureRole } from "@editor/tools/pdfTextEditor/model/structureTypes";
+import type { InnerTagsControl } from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";
+import type { TextTag } from "@editor/tools/pdfTextEditor/util/textAccessibility";
+
+const KEY = "pdfTextEditor.inspector.accessibility";
+const NO_INNER: InnerTagsControl = {
+ tags: [],
+ active: null,
+ onSelect: () => {},
+ onSet: () => {},
+ newTagTypes: null,
+ onTagSelection: () => {},
+};
+
+function tagShown(tag: TextTag): HTMLElement {
+ render(
+ <MantineProvider env="test">
+ <TextAccessibilitySection tag={tag} onSetTag={vi.fn()} inner={NO_INNER} />
+ </MantineProvider>,
+ );
+ return screen.getByTestId("pdf-editor-text-tag");
+}
+
+const tagged = (role: string): TextTag => ({
+ kind: "tagged",
+ block: structureRole(role),
+ cannotRetag: "not-text",
+});
+
+describe("TextAccessibilitySection", () => {
+ it("names a type by its name alone", () => {
+ expect(tagShown(tagged("H2"))).toHaveTextContent(
+ new RegExp(`^${KEY}.tagName.headingLevel$`),
+ );
+ });
+
+ it("shows a type with no plain-language name as the type", () => {
+ expect(tagShown(tagged("Warichu"))).toHaveTextContent(/^Warichu$/);
+ });
+
+ it("marks a custom role as custom", () => {
+ expect(tagShown(tagged("Callout"))).toHaveTextContent(`${KEY}.customTag`);
+ });
+
+ it.each([
+ [{ kind: "artifact" } as const, "artifactText"],
+ [
+ { kind: "untagged", documentTagged: true, taggable: false } as const,
+ "untaggedBadge",
+ ],
+ [
+ { kind: "untagged", documentTagged: false, taggable: false } as const,
+ "untaggedDocument",
+ ],
+ [{ kind: "unknown" } as const, "unknownTag"],
+ ])("explains text with no element (%o)", (tag, message) => {
+ expect(tagShown(tag)).toHaveTextContent(`${KEY}.${message}`);
+ });
+
+ it("offers a picker where the text's block can be retagged", () => {
+ const onRetag = vi.fn();
+ render(
+ <MantineProvider env="test">
+ <TextAccessibilitySection
+ tag={{ kind: "tagged", block: structureRole("P"), cannotRetag: null }}
+ onSetTag={onRetag}
+ inner={NO_INNER}
+ />
+ </MantineProvider>,
+ );
+ const input = screen.getByRole("textbox", { name: `${KEY}.tagLabel` });
+ expect(input).toHaveValue(`${KEY}.tagName.paragraph`);
+ fireEvent.click(input);
+ fireEvent.click(screen.getByText(`${KEY}.tagName.code`));
+ expect(onRetag).toHaveBeenCalledWith("Code");
+ });
+
+ it("shows a tag the picker does not offer in its place", () => {
+ render(
+ <MantineProvider env="test">
+ <TextAccessibilitySection
+ tag={{
+ kind: "tagged",
+ block: structureRole("Callout"),
+ cannotRetag: null,
+ }}
+ onSetTag={vi.fn()}
+ inner={NO_INNER}
+ />
+ </MantineProvider>,
+ );
+ expect(
+ screen.getByRole("textbox", { name: `${KEY}.tagLabel` }),
+ ).toHaveAttribute("placeholder", `${KEY}.customTag`);
+ });
+
+ it("numbers the tags inside the text and selects one when clicked", () => {
+ const inner = innerControl();
+ renderSection(inner);
+ const rows = screen.getAllByTestId("pdf-editor-inner-tag");
+ expect(rows.map((row) => row.textContent)).toEqual([
+ "1Umsatzerlöse",
+ "2the appendix",
+ ]);
+ fireEvent.click(within(rows[1]).getByRole("button"));
+ expect(inner.onSelect).toHaveBeenCalledWith(1);
+ expect(screen.queryByTestId("pdf-editor-inner-tag-picker")).toBeNull();
+ });
+
+ it("changes or removes the selected tag", () => {
+ const inner = innerControl({ active: 0 });
+ renderSection(inner);
+ const input = screen.getByRole("textbox", {
+ name: `${KEY}.innerTagLabel`,
+ });
+ expect(input).toHaveValue(`${KEY}.tagName.span`);
+ fireEvent.click(input);
+ fireEvent.click(within(listboxOf(input)).getByText(`${KEY}.tagName.code`));
+ expect(inner.onSet).toHaveBeenCalledWith(0, "Code");
+ fireEvent.click(screen.getByTestId("pdf-editor-inner-tag-remove"));
+ expect(inner.onSet).toHaveBeenCalledWith(0, null);
+ });
+
+ it("offers no change to a tag that cannot take one", () => {
+ renderSection(innerControl({ active: 1 }));
+ expect(
+ screen.getByRole("textbox", { name: `${KEY}.innerTagLabel` }),
+ ).toBeDisabled();
+ expect(screen.queryByTestId("pdf-editor-inner-tag-remove")).toBeNull();
+ });
+
+ it("tags characters selected inside the text", () => {
+ const inner = innerControl({ newTagTypes: ["Span", "Code"] });
+ renderSection(inner);
+ const input = screen.getByRole("textbox", { name: `${KEY}.selectedText` });
+ fireEvent.click(input);
+ fireEvent.click(within(listboxOf(input)).getByText(`${KEY}.tagName.code`));
+ expect(inner.onTagSelection).toHaveBeenCalledWith("Code");
+ });
+
+ it("disables adding a tag the selected characters cannot take", () => {
+ renderSection(innerControl({ newTagTypes: [] }));
+ expect(
+ screen.getByRole("textbox", { name: `${KEY}.selectedText` }),
+ ).toBeDisabled();
+ });
+});
+
+function innerControl(
+ overrides: Partial<InnerTagsControl> = {},
+): InnerTagsControl {
+ return {
+ tags: [
+ {
+ key: "1",
+ text: "Umsatzerlöse",
+ start: 4,
+ end: 9,
+ role: structureRole("Span"),
+ types: ["Span", "Code"],
+ removable: true,
+ },
+ {
+ key: "2",
+ text: " the\nappendix ",
+ start: 12,
+ end: 20,
+ role: structureRole("Link"),
+ types: [],
+ removable: false,
+ },
+ ],
+ active: null,
+ onSelect: vi.fn(),
+ onSet: vi.fn(),
+ newTagTypes: null,
+ onTagSelection: vi.fn(),
+ ...overrides,
+ };
+}
+
+function renderSection(inner: InnerTagsControl) {
+ render(
+ <MantineProvider env="test">
+ <TextAccessibilitySection
+ tag={{ kind: "tagged", block: structureRole("P"), cannotRetag: null }}
+ onSetTag={vi.fn()}
+ inner={inner}
+ />
+ </MantineProvider>,
+ );
+}
+
+/** The options of a picker: every picker's are in the document at once. */
+function listboxOf(input: HTMLElement): HTMLElement {
+ return document.getElementById(input.getAttribute("aria-controls")!)!;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsx
new file mode 100644
index 0000000000..61c314ed37
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsx
@@ -0,0 +1,496 @@
+import type { TFunction } from "i18next";
+import { useTranslation } from "react-i18next";
+import { Box, Group, Stack } from "@mantine/core";
+import { ActionIcon } from "@editor/ui/ActionIcon";
+import { Icon } from "@editor/ui/Icon";
+import { Select } from "@editor/ui/Select";
+import {
+ Field,
+ Section,
+ SectionLabel,
+ StatRow,
+} from "@editor/tools/pdfTextEditor/components/inspector/InspectorPrimitives";
+import { TEXT_BLOCK_TYPES } from "@editor/tools/pdfTextEditor/model/PageStructure";
+import type {
+ StructureRole,
+ StructureType,
+} from "@editor/tools/pdfTextEditor/model/structureTypes";
+import type {
+ InnerTag,
+ TextTag,
+} from "@editor/tools/pdfTextEditor/util/textAccessibility";
+import type { InnerTagsControl } from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";
+import "@editor/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.css";
+
+/**
+ * What the selected text is tagged as, and a picker to change it: retagging
+ * its block, or giving untagged text an element of its own. Beneath it, the
+ * tags marking parts of the text, and a picker for characters selected in it.
+ */
+export function TextAccessibilitySection({
+ tag,
+ onSetTag,
+ inner,
+}: {
+ tag: TextTag;
+ onSetTag: (type: StructureType) => void;
+ inner: InnerTagsControl;
+}) {
+ const { t } = useTranslation();
+ const label = t("pdfTextEditor.inspector.accessibility.tagLabel", "Tag");
+ return (
+ <Section testId="pdf-editor-text-accessibility">
+ <SectionLabel>
+ {t("pdfTextEditor.inspector.accessibility.heading", "Accessibility")}
+ </SectionLabel>
+ <Stack gap="xs">
+ {pickable(tag) ? (
+ <Field label={label}>
+ <TagPicker
+ types={TEXT_BLOCK_TYPES}
+ current={tag.kind === "tagged" ? tag.block : null}
+ placeholder={tagText(t, tag)}
+ onSetTag={onSetTag}
+ label={label}
+ testId="pdf-editor-text-tag-picker"
+ />
+ </Field>
+ ) : (
+ <StatRow
+ label={label}
+ value={
+ <span data-testid="pdf-editor-text-tag">{tagText(t, tag)}</span>
+ }
+ />
+ )}
+ <InnerTagList inner={inner} />
+ <NewTagPicker inner={inner} />
+ </Stack>
+ </Section>
+ );
+}
+
+/** The tags marking parts of the text, numbered in reading order; the one picked opens its controls. */
+function InnerTagList({ inner }: { inner: InnerTagsControl }) {
+ const { t } = useTranslation();
+ if (inner.tags.length === 0) return null;
+ return (
+ <Field
+ label={t(
+ "pdfTextEditor.inspector.accessibility.innerTags",
+ "Tags in this text",
+ )}
+ >
+ <Stack gap={2} data-testid="pdf-editor-inner-tags">
+ {inner.tags.map((innerTag, index) => (
+ <InnerTagRow
+ key={innerTag.key}
+ number={index + 1}
+ innerTag={innerTag}
+ active={inner.active === index}
+ onSelect={() => inner.onSelect(index)}
+ onSet={(type) => inner.onSet(index, type)}
+ />
+ ))}
+ </Stack>
+ </Field>
+ );
+}
+
+function InnerTagRow({
+ number,
+ innerTag,
+ active,
+ onSelect,
+ onSet,
+}: {
+ number: number;
+ innerTag: InnerTag;
+ active: boolean;
+ onSelect: () => void;
+ onSet: (type: StructureType | null) => void;
+}) {
+ const text = innerTag.text.replace(/\s+/g, " ").trim();
+ return (
+ <div data-testid="pdf-editor-inner-tag">
+ <button
+ type="button"
+ className="pdf-editor-inner-tag__entry"
+ aria-pressed={active}
+ onClick={onSelect}
+ >
+ <span className="pdf-editor-inner-tag__number">{number}</span>
+ <span className="pdf-editor-inner-tag__text" title={text}>
+ {text}
+ </span>
+ </button>
+ {active && (
+ <InnerTagControls number={number} innerTag={innerTag} onSet={onSet} />
+ )}
+ </div>
+ );
+}
+
+function InnerTagControls({
+ number,
+ innerTag,
+ onSet,
+}: {
+ number: number;
+ innerTag: InnerTag;
+ onSet: (type: StructureType | null) => void;
+}) {
+ const { t } = useTranslation();
+ const removeLabel = t(
+ "pdfTextEditor.inspector.accessibility.removeTag",
+ "Remove tag",
+ );
+ return (
+ <Group gap={4} wrap="nowrap" mt={4}>
+ <Box style={{ flex: 1, minWidth: 0 }}>
+ <TagPicker
+ types={innerTag.types}
+ current={innerTag.role}
+ placeholder={blockName(t, innerTag.role)}
+ onSetTag={onSet}
+ label={t(
+ "pdfTextEditor.inspector.accessibility.innerTagLabel",
+ "Tag {{number}}",
+ { number },
+ )}
+ testId="pdf-editor-inner-tag-picker"
+ />
+ </Box>
+ {innerTag.removable && (
+ <ActionIcon
+ variant="tertiary"
+ size="sm"
+ aria-label={removeLabel}
+ title={removeLabel}
+ onClick={() => onSet(null)}
+ data-testid="pdf-editor-inner-tag-remove"
+ >
+ <Icon name="trash" size={14} />
+ </ActionIcon>
+ )}
+ </Group>
+ );
+}
+
+/** A picker tagging the characters selected in the text, shown while some are. */
+function NewTagPicker({ inner }: { inner: InnerTagsControl }) {
+ const { t } = useTranslation();
+ if (!inner.newTagTypes) return null;
+ const label = t(
+ "pdfTextEditor.inspector.accessibility.selectedText",
+ "Selected text",
+ );
+ return (
+ <Field label={label}>
+ <TagPicker
+ types={inner.newTagTypes}
+ current={null}
+ placeholder={t(
+ "pdfTextEditor.inspector.accessibility.addTag",
+ "Add tag",
+ )}
+ onSetTag={inner.onTagSelection}
+ label={label}
+ testId="pdf-editor-new-tag-picker"
+ />
+ </Field>
+ );
+}
+
+function pickable(tag: TextTag): boolean {
+ if (tag.kind === "tagged") return tag.cannotRetag === null;
+ return tag.kind === "untagged" && tag.taggable;
+}
+
+function TagPicker({
+ types,
+ current,
+ placeholder,
+ onSetTag,
+ label,
+ testId,
+}: {
+ types: readonly StructureType[];
+ /** Null for untagged text. */
+ current: StructureRole | null;
+ /** Shown when the current tag is not one the picker offers, such as a custom role. */
+ placeholder: string;
+ onSetTag: (type: StructureType) => void;
+ label: string;
+ testId: string;
+}) {
+ const { t } = useTranslation();
+ const offered = types.find((type) => type === current?.type) ?? null;
+ return (
+ <div data-testid={testId}>
+ <Select
+ disabled={types.length === 0}
+ inputSize="sm"
+ options={types.map((type) => ({
+ value: type,
+ label: typeName(t, type),
+ }))}
+ value={offered}
+ placeholder={placeholder}
+ onChange={(value) => {
+ const picked = types.find((type) => type === value);
+ if (picked) onSetTag(picked);
+ }}
+ aria-label={label}
+ />
+ </div>
+ );
+}
+
+function tagText(t: TFunction, tag: TextTag): string {
+ return tag.kind === "tagged" ? blockName(t, tag.block) : statusText(t, tag);
+}
+
+function blockName(t: TFunction, { role, type }: StructureRole): string {
+ if (type !== null) return typeName(t, type);
+ return t(
+ "pdfTextEditor.inspector.accessibility.customTag",
+ "{{role}} (custom tag)",
+ { role },
+ );
+}
+
+function statusText(
+ t: TFunction,
+ tag: Exclude<TextTag, { kind: "tagged" }>,
+): string {
+ switch (tag.kind) {
+ case "artifact":
+ return t(
+ "pdfTextEditor.inspector.accessibility.artifactText",
+ "Decorative",
+ );
+ case "untagged":
+ return tag.documentTagged
+ ? t("pdfTextEditor.inspector.accessibility.untaggedBadge", "Not tagged")
+ : t(
+ "pdfTextEditor.inspector.accessibility.untaggedDocument",
+ "Document has no tags",
+ );
+ case "unknown":
+ return t(
+ "pdfTextEditor.inspector.accessibility.unknownTag",
+ "Can't be read here",
+ );
+ }
+}
+
+/** The type's name for a reader; the type itself where it has no plain-language name. */
+function typeName(t: TFunction, type: StructureType): string {
+ switch (type) {
+ case "Document":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.document",
+ "Document",
+ );
+ case "DocumentFragment":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.documentFragment",
+ "Document fragment",
+ );
+ case "Part":
+ return t("pdfTextEditor.inspector.accessibility.tagName.part", "Part");
+ case "Art":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.article",
+ "Article",
+ );
+ case "Sect":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.section",
+ "Section",
+ );
+ case "Div":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.division",
+ "Division",
+ );
+ case "Aside":
+ return t("pdfTextEditor.inspector.accessibility.tagName.aside", "Aside");
+ case "BlockQuote":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.blockQuote",
+ "Block quote",
+ );
+ case "Caption":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.caption",
+ "Caption",
+ );
+ case "TOC":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.contents",
+ "Table of contents",
+ );
+ case "TOCI":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.contentsEntry",
+ "Contents entry",
+ );
+ case "Index":
+ return t("pdfTextEditor.inspector.accessibility.tagName.index", "Index");
+ case "Title":
+ return t("pdfTextEditor.inspector.accessibility.tagName.title", "Title");
+ case "FENote":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.footnote",
+ "Footnote",
+ );
+ case "P":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.paragraph",
+ "Paragraph",
+ );
+ case "H":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.heading",
+ "Heading",
+ );
+ case "L":
+ return t("pdfTextEditor.inspector.accessibility.tagName.list", "List");
+ case "LI":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.listItem",
+ "List item",
+ );
+ case "Lbl":
+ return t("pdfTextEditor.inspector.accessibility.tagName.label", "Label");
+ case "LBody":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.listItemBody",
+ "List item body",
+ );
+ case "Table":
+ return t("pdfTextEditor.inspector.accessibility.tagName.table", "Table");
+ case "TR":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.tableRow",
+ "Table row",
+ );
+ case "TH":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.tableHeader",
+ "Table header",
+ );
+ case "TD":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.tableCell",
+ "Table cell",
+ );
+ case "THead":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.tableHead",
+ "Table head",
+ );
+ case "TBody":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.tableBody",
+ "Table body",
+ );
+ case "TFoot":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.tableFoot",
+ "Table foot",
+ );
+ case "Span":
+ return t("pdfTextEditor.inspector.accessibility.tagName.span", "Span");
+ case "Quote":
+ return t("pdfTextEditor.inspector.accessibility.tagName.quote", "Quote");
+ case "Note":
+ return t("pdfTextEditor.inspector.accessibility.tagName.note", "Note");
+ case "Reference":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.reference",
+ "Reference",
+ );
+ case "BibEntry":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.bibliographyEntry",
+ "Bibliography entry",
+ );
+ case "Code":
+ return t("pdfTextEditor.inspector.accessibility.tagName.code", "Code");
+ case "Link":
+ return t("pdfTextEditor.inspector.accessibility.tagName.link", "Link");
+ case "Annot":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.annotation",
+ "Annotation",
+ );
+ case "Ruby":
+ return t("pdfTextEditor.inspector.accessibility.tagName.ruby", "Ruby");
+ case "RB":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.rubyBase",
+ "Ruby base",
+ );
+ case "RT":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.rubyText",
+ "Ruby text",
+ );
+ case "RP":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.rubyPunctuation",
+ "Ruby punctuation",
+ );
+ case "Em":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.emphasis",
+ "Emphasis",
+ );
+ case "Strong":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.strong",
+ "Strong emphasis",
+ );
+ case "Figure":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.figure",
+ "Figure",
+ );
+ case "Formula":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.formula",
+ "Formula",
+ );
+ case "Form":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.form",
+ "Form field",
+ );
+ case "Artifact":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.artifact",
+ "Artifact",
+ );
+ case "H1":
+ case "H2":
+ case "H3":
+ case "H4":
+ case "H5":
+ case "H6":
+ return t(
+ "pdfTextEditor.inspector.accessibility.tagName.headingLevel",
+ "Heading {{level}}",
+ { level: type.slice(1) },
+ );
+ case "NonStruct":
+ case "Private":
+ case "Sub":
+ case "Warichu":
+ case "WT":
+ case "WP":
+ return type;
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useHeadingOutline.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useHeadingOutline.ts
new file mode 100644
index 0000000000..cd83d98b11
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useHeadingOutline.ts
@@ -0,0 +1,58 @@
+import { useCallback, useMemo } from "react";
+import { ensurePageRead } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";
+import type {
+ EditorStore,
+ EditorViewState,
+} from "@editor/tools/pdfTextEditor/store/EditorStore";
+import {
+ headingOutline,
+ type HeadingOutline,
+} from "@editor/tools/pdfTextEditor/util/headingOutline";
+import { locateHeading } from "@editor/tools/pdfTextEditor/util/textAccessibility";
+
+/**
+ * The document's heading outline, null when its structure tree could not be
+ * read or `shown` is false, and a way to select a heading on the page. The
+ * outline is rebuilt on every page change, so it is left unbuilt while hidden.
+ */
+export function useHeadingOutline(
+ store: EditorStore,
+ state: EditorViewState,
+ shown: boolean,
+) {
+ const outline = useMemo((): HeadingOutline | null => {
+ const doc = shown ? store.document : null;
+ const headings = doc?.headings();
+ return doc && headings
+ ? headingOutline(headings, state.pages, (h) => locateHeading(doc, h))
+ : null;
+ }, [store, state.pages, shown]);
+
+ /** Selects the run showing heading `index`, reading its page first. */
+ const selectHeading = useCallback(
+ (index: number) => {
+ const doc = store.document;
+ const headings = doc?.headings();
+ const pageIndex = headings?.[index]?.pageIndex;
+ if (!doc || !headings || pageIndex == null) return;
+ ensurePageRead(store, pageIndex);
+ const { run, range } = headingOutline(
+ headings,
+ store.getState().pages,
+ (h) => locateHeading(doc, h),
+ ).entries[index];
+ if (!run) return;
+ store.selection.selectOne(run.id);
+ if (range) store.selection.setTextRange(run.id, range);
+ // A page read just now has no overlay until React commits it.
+ window.requestAnimationFrame(() =>
+ document
+ .querySelector(`[data-testid="pdf-editor-run-${run.id}"]`)
+ ?.scrollIntoView({ block: "center", behavior: "smooth" }),
+ );
+ },
+ [store],
+ );
+
+ return { outline, selectHeading };
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts
new file mode 100644
index 0000000000..4a4eeb5ead
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts
@@ -0,0 +1,196 @@
+import { useCallback, useMemo } from "react";
+import { ACCESSIBILITY_EDITING } from "@editor/constants/featureFlags";
+import { RetagInnerCommand } from "@editor/tools/pdfTextEditor/commands/RetagInnerCommand";
+import { RetagTextCommand } from "@editor/tools/pdfTextEditor/commands/RetagTextCommand";
+import { TagTextCommand } from "@editor/tools/pdfTextEditor/commands/TagTextCommand";
+import {
+ rangeTagTypes,
+ TagTextRangeCommand,
+} from "@editor/tools/pdfTextEditor/commands/TagTextRangeCommand";
+import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";
+import type {
+ EditorStore,
+ EditorViewState,
+} from "@editor/tools/pdfTextEditor/store/EditorStore";
+import type {
+ SelectionState,
+ TextRange,
+ TextRunSnapshot,
+} from "@editor/tools/pdfTextEditor/types";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import {
+ innerTags,
+ textTag,
+ type InnerTag,
+} from "@editor/tools/pdfTextEditor/util/textAccessibility";
+
+/** The tags marking parts of the selected text, and the selection inside it. */
+export interface InnerTagsControl {
+ tags: readonly InnerTag[];
+ /** The tag whose text is exactly what is selected inside the run. */
+ active: number | null;
+ onSelect: (index: number) => void;
+ /** Retags tag `index`, or removes it with null. */
+ onSet: (index: number, type: StructureType | null) => void;
+ /** What the characters selected inside the run can be tagged as; null when nothing new is selected. */
+ newTagTypes: readonly StructureType[] | null;
+ onTagSelection: (type: StructureType) => void;
+}
+
+/**
+ * The tag of the selected text (null unless exactly one run and nothing else
+ * is selected), the tags marking parts of it, and ways to change both. A
+ * selection inside the text that is exactly one inner tag's text picks that
+ * tag; any other is offered as new text to tag.
+ */
+export function useTextAccessibility(
+ store: EditorStore,
+ state: EditorViewState,
+ selection: SelectionState,
+) {
+ // One memo over the pages: a retag changes no snapshot of the run, only
+ // republishes them.
+ const { run, tag, inner, newTagTypes } = useMemo(() => {
+ const doc = store.document;
+ const selected =
+ ACCESSIBILITY_EDITING &&
+ selection.runIds.length === 1 &&
+ selection.imageIds.length === 0 &&
+ selection.shapeIds.length === 0
+ ? (state.pages
+ .flatMap((page) => page.runs)
+ .find((r) => r.id === selection.runIds[0]) ?? null)
+ : null;
+ if (!doc || !selected) {
+ return { run: null, tag: null, inner: [], newTagTypes: null };
+ }
+ const tags = innerTags(doc, selected);
+ const range = selection.textRange;
+ const picksTag = tags.some((t) => sameRange(t, range));
+ return {
+ run: selected,
+ tag: textTag(doc, selected),
+ inner: tags,
+ newTagTypes:
+ range && !picksTag ? tagTypesFor(doc, selected, range) : null,
+ };
+ }, [store, state.pages, selection]);
+
+ const activeInner = useMemo(
+ () => inner.findIndex((t) => sameRange(t, selection.textRange)),
+ [inner, selection.textRange],
+ );
+
+ /** Retags the text's block, or gives untagged text an element of its own. */
+ const setTag = useCallback(
+ (type: StructureType) => {
+ if (!run || !tag) return;
+ if (tag.kind === "tagged" && run.mcid !== undefined) {
+ store.dispatch(
+ new RetagTextCommand({
+ pageIndex: run.pageIndex,
+ mcid: run.mcid,
+ type,
+ }),
+ );
+ } else if (tag.kind === "untagged" && tag.taggable) {
+ store.dispatch(
+ new TagTextCommand({
+ pageIndex: run.pageIndex,
+ runId: run.id,
+ as: type,
+ }),
+ );
+ }
+ },
+ [store, run, tag],
+ );
+
+ /** Selects inner tag `index`'s text. */
+ const selectInner = useCallback(
+ (index: number) => {
+ const picked = inner[index];
+ if (!run || !picked) return;
+ store.selection.setTextRange(run.id, {
+ start: picked.start,
+ end: picked.end,
+ });
+ },
+ [store, run, inner],
+ );
+
+ /** Retags inner tag `index`, or removes it with null. */
+ const setInnerTag = useCallback(
+ (index: number, type: StructureType | null) => {
+ const picked = inner[index];
+ if (!run || !picked) return;
+ store.dispatch(
+ new RetagInnerCommand({
+ pageIndex: run.pageIndex,
+ key: picked.key,
+ type,
+ }),
+ );
+ if (type === null) store.selection.setTextRange(run.id, null);
+ },
+ [store, run, inner],
+ );
+
+ /** Tags the characters selected inside the run as an element of their own. */
+ const tagSelectedText = useCallback(
+ (type: StructureType) => {
+ const range = selection.textRange;
+ if (!run || !range) return;
+ store.dispatch(
+ new TagTextRangeCommand({
+ pageIndex: run.pageIndex,
+ runId: run.id,
+ ...range,
+ as: type,
+ }),
+ );
+ // The cut redraws the text, so the range no longer names what it did.
+ store.selection.setTextRange(run.id, null);
+ },
+ [store, run, selection.textRange],
+ );
+
+ const innerControl = useMemo(
+ (): InnerTagsControl => ({
+ tags: inner,
+ active: activeInner < 0 ? null : activeInner,
+ onSelect: selectInner,
+ onSet: setInnerTag,
+ newTagTypes,
+ onTagSelection: tagSelectedText,
+ }),
+ [
+ inner,
+ activeInner,
+ selectInner,
+ setInnerTag,
+ newTagTypes,
+ tagSelectedText,
+ ],
+ );
+
+ return { tag, setTag, inner: innerControl };
+}
+
+function sameRange(a: TextRange, b: TextRange | null): boolean {
+ return b !== null && a.start === b.start && a.end === b.end;
+}
+
+/**
+ * The tags the selected characters can take; null when they are all of the
+ * run's text, which the run's own tag already offers.
+ */
+function tagTypesFor(
+ doc: EditorDocument,
+ run: TextRunSnapshot,
+ { start, end }: TextRange,
+): StructureType[] | null {
+ if (end > run.text.length) return null;
+ if (run.text.slice(start, end).trim() === run.text.trim()) return null;
+ return rangeTagTypes(doc, run.pageIndex, run.id, start, end);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts
index 1fbd75f6f9..5ff808eaf8 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts
@@ -7,6 +7,7 @@ import {
} from "react";
import { useSelectionActions } from "@editor/tools/pdfTextEditor/hooks/useSelectionActions";
import { useImageAccessibility } from "@editor/tools/pdfTextEditor/hooks/useImageAccessibility";
+import { useTextAccessibility } from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";
import { deriveToolbarState } from "@editor/tools/pdfTextEditor/util/toolbarState";
import { warmDocumentDeviceFonts } from "@editor/tools/pdfTextEditor/util/fontCapability";
import {
@@ -53,6 +54,7 @@ export function useToolbarController(
) {
const sel = useSelectionActions(store);
const imageA11y = useImageAccessibility(store, state, selection);
+ const textA11y = useTextAccessibility(store, state, selection);
const onToggleLock = useCallback(() => {
const doc = store.document;
@@ -524,6 +526,9 @@ export function useToolbarController(
onSetImageDecorative: imageA11y.setDecorative,
imageReview: imageA11y.review,
onSelectNextImageToReview: imageA11y.selectNextImage,
+ textTag: textA11y.tag,
+ onSetTextTag: textA11y.setTag,
+ innerTextTags: textA11y.inner,
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 4e17cfadcb..6a91c3e4d5 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts
@@ -5,17 +5,26 @@ import {
openRawDocument,
} from "@editor/services/pdfiumService";
import { Page } from "@editor/tools/pdfTextEditor/model/Page";
-import { PageStructure } from "@editor/tools/pdfTextEditor/model/PageStructure";
+import {
+ PageStructure,
+ isInlineType,
+} from "@editor/tools/pdfTextEditor/model/PageStructure";
import type { StructureEdit } from "@editor/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits";
import { readPageStructure } from "@editor/tools/pdfTextEditor/pdfium/PdfiumStructureReader";
+import { carriedMcids } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
import {
readFileStructure,
- type FilePageStructure,
+ type FileStructure,
} from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";
import {
- imagesInReadingOrder,
+ isHeadingType,
+ type StructureType,
+} from "@editor/tools/pdfTextEditor/model/structureTypes";
+import type { DocumentHeading } from "@editor/tools/pdfTextEditor/util/headingOutline";
+import {
precedingTaggedMcid,
-} from "@editor/tools/pdfTextEditor/util/figurePlacement";
+ taggedContentInReadingOrder,
+} from "@editor/tools/pdfTextEditor/util/elementPlacement";
import { DisplayTransform } from "@editor/tools/pdfTextEditor/model/DisplayTransform";
import { FontRef } from "@editor/tools/pdfTextEditor/model/FontRef";
import { prepareForEditing } from "@editor/tools/pdfTextEditor/pdfdoc/prepareForEditing";
@@ -36,8 +45,17 @@ export class EditorDocument {
readonly openedBytes: Uint8Array;
private readonly pageCache: Map<number, Page>;
private readonly structureCache = new Map<number, PageStructure>();
- /** Each page's elements from the file's own ParentTree; null when only PDFium's view is available. */
- private readonly fileStructure: Map<number, FilePageStructure> | null;
+ /**
+ * Unsaved retags by block key, each with the content the save addresses it
+ * by. Held here rather than per page: an element spanning a page break is
+ * one element.
+ */
+ private readonly retags = new Map<
+ string,
+ { pageIndex: number; mcid: number; type: StructureType }
+ >();
+ /** The file's own structure tree; null when only PDFium's view is available. */
+ private readonly fileStructure: FileStructure | null;
private readonly ownedFonts: Map<string, FontRef>;
private _disposed: boolean;
// Form-fill environment. Widgets with no appearance stream are drawn ONLY by
@@ -52,7 +70,7 @@ export class EditorDocument {
module: WrappedPdfiumModule,
docPtr: number,
openedBytes: Uint8Array,
- fileStructure: Map<number, FilePageStructure> | null,
+ fileStructure: FileStructure | null,
) {
this.module = module;
this.docPtr = docPtr;
@@ -176,10 +194,80 @@ export class EditorDocument {
this.encrypted() ? "encrypted" : "unreadable",
);
}
- const page = this.fileStructure.get(pageIndex);
+ const page = this.fileStructure.pages.get(pageIndex);
if (!page) return new PageStructure([]);
if (page.slotCount === null) return new PageStructure([], "unreadable");
- return new PageStructure(page.elements, null, page.slotCount);
+ return new PageStructure(page.elements, null, page.slotCount, (key) =>
+ this.retaggedAs(key),
+ );
+ }
+
+ /**
+ * The headings in reading order, the session's retags and added elements
+ * applied. Null when the file's structure tree could not be read, which
+ * leaves nothing to check them against.
+ */
+ headings(): DocumentHeading[] | null {
+ if (!this.fileStructure) return null;
+ const blocks: OutlineBlock[] = this.fileStructure.blocks.map(
+ ({ key, type, pageIndex, mcids }) => ({
+ key,
+ type: this.retaggedAs(key) ?? type,
+ pageIndex,
+ mcids,
+ }),
+ );
+ for (const [pageIndex, structure] of this.structureCache) {
+ for (const edit of this.addedElementEdits(pageIndex, structure)) {
+ const { type, after } = edit.newElement!;
+ const anchor = after === null ? null : structure.block(after)?.key;
+ blocks.splice(insertionPoint(blocks, pageIndex, anchor ?? null), 0, {
+ key: structure.block(edit.mcid)!.key,
+ type,
+ pageIndex,
+ mcids: [edit.mcid],
+ });
+ }
+ for (const edit of this.cutEdits(pageIndex, structure)) {
+ const owner = structure.element(edit.cut!.from[0])!.block.key;
+ applyCut(blocks, pageIndex, edit, owner, structure);
+ }
+ }
+ return blocks.flatMap(({ type, pageIndex, mcids, partOf }) =>
+ isHeadingType(type)
+ ? [{ type, pageIndex, mcids, ...(partOf && { partOf }) }]
+ : [],
+ );
+ }
+
+ /** The type the session has retagged block `key` as; null when it has not. */
+ retaggedAs(key: string): StructureType | null {
+ return this.retags.get(key)?.type ?? null;
+ }
+
+ /**
+ * Retag the block the text `mcid` marks belongs to as `type`. Null, or the
+ * type it has in the file, drops the change. Throws when cannotRetag
+ * refuses it: a retag the save cannot write would fail every later save.
+ */
+ setRetag(pageIndex: number, mcid: number, type: StructureType | null): void {
+ const structure = this.structure(pageIndex);
+ const blocker = structure.cannotRetag(mcid);
+ if (blocker) throw new Error(`MCID ${mcid} cannot be retagged: ${blocker}`);
+ const block = structure.element(mcid)!.block;
+ // An added element is not in the file yet: its type is just changed.
+ const added = structure.addedBlockMcid(block.key);
+ if (added !== null) {
+ if (type !== null) structure.setAddedType(added, type);
+ return;
+ }
+ if (type === null || type === block.type) {
+ this.retags.delete(block.key);
+ } else {
+ // The save climbs from the element owning this to the same block.
+ const address = structure.fileMcid(mcid)!;
+ this.retags.set(block.key, { pageIndex, mcid: address, type });
+ }
}
/** True when the catalog marks the file as tagged (ISO 32000-1 14.7.1). */
@@ -202,33 +290,86 @@ export class EditorDocument {
/** Every unsaved structure edit, in the form the save pass takes. */
structureEdits(): StructureEdit[] {
- return [...this.structureCache].flatMap(([pageIndex, structure]) => [
- ...structure.pendingEdits().map((edit) => ({ pageIndex, ...edit })),
- ...this.addedFigureEdits(pageIndex, structure),
- ]);
+ const retags = [...this.retags.values()].map(
+ ({ pageIndex, mcid, type }) => ({
+ pageIndex,
+ mcid,
+ type,
+ decorative: false,
+ }),
+ );
+ return [
+ ...[...this.structureCache].flatMap(([pageIndex, structure]) => [
+ ...structure.pendingEdits().map((edit) => ({ pageIndex, ...edit })),
+ ...structure.innerEdits().map(({ mcid, type }) => ({
+ pageIndex,
+ mcid,
+ ownType: type,
+ decorative: false,
+ })),
+ ...this.addedElementEdits(pageIndex, structure),
+ ...this.cutEdits(pageIndex, structure),
+ ]),
+ ...retags,
+ ];
}
/**
- * The page's added figures in reading order, so one placed after another
- * finds it already in the tree. A figure whose image was deleted is left
- * out: there is nothing left for it to describe.
+ * The page's added elements in reading order, so one placed after another
+ * finds it already in the tree. An element whose content was deleted is
+ * left out: there is nothing left for it to tag.
*/
- private addedFigureEdits(
+ private addedElementEdits(
pageIndex: number,
structure: PageStructure,
): StructureEdit[] {
const page = this.pageCache.get(pageIndex);
- if (!page) return [];
- const figures = structure.addedFigures();
- return imagesInReadingOrder(page).flatMap((image) => {
- const figure = figures.find((f) => f.mcid === image.mcid);
- if (!figure) return [];
+ const added = new Map(
+ structure.addedElements().map((element) => [element.mcid, element]),
+ );
+ if (!page || added.size === 0) return [];
+ return taggedContentInReadingOrder(page).flatMap((content) => {
+ const element = added.get(content.mcid);
+ if (!element) return [];
+ added.delete(content.mcid);
+ const after = precedingTaggedMcid(page, content);
+ return [
+ {
+ pageIndex,
+ mcid: element.mcid,
+ alt: element.alt,
+ decorative: false,
+ newElement: { type: element.type, after },
+ },
+ ];
+ });
+ }
+
+ /**
+ * The page's cuts, in the order made. One whose text was since deleted is
+ * left out, and a part before or after it that was deleted is not kept.
+ */
+ private cutEdits(
+ pageIndex: number,
+ structure: PageStructure,
+ ): StructureEdit[] {
+ const page = this.pageCache.get(pageIndex);
+ const cuts = structure.cutElements();
+ if (!page || cuts.length === 0) return [];
+ const carried = carriedMcids(this.module, page.pagePtr);
+ return cuts.flatMap(({ mcid, type, alt, cut }) => {
+ if (!carried.has(mcid)) return [];
+ const kept = (part: number | null) =>
+ part !== null && carried.has(part) ? part : null;
+ const before = kept(cut.before);
+ const after = kept(cut.after);
return [
{
pageIndex,
- ...figure,
+ mcid,
+ alt,
decorative: false,
- newFigure: { after: precedingTaggedMcid(page, image) },
+ cut: { type, from: cut.from, before, after },
},
];
});
@@ -287,3 +428,96 @@ export class EditorDocument {
releaseScratch(this.module);
}
}
+
+interface OutlineBlock {
+ key: string;
+ /** Null for an untyped block. */
+ type: StructureType | null;
+ pageIndex: number | null;
+ /** In reading order. */
+ mcids: number[];
+ partOf?: number[];
+}
+
+/**
+ * Change `blocks` as cutElements changes the tree for `edit`: an inline or
+ * removed cut stays in its owner; any other splits the owner around it, the
+ * owner keeping what is read before, a block of the owner's type taking what
+ * is read after. Must stay in step with cutElements.
+ */
+function applyCut(
+ blocks: OutlineBlock[],
+ pageIndex: number,
+ edit: StructureEdit,
+ ownerKey: string,
+ structure: PageStructure,
+): void {
+ const { type, from, before, after } = edit.cut!;
+ // By MCID before key: a split owner's key stays on only one of its parts.
+ let at = blocks.findIndex(
+ (block) => block.pageIndex === pageIndex && block.mcids.includes(from[0]),
+ );
+ if (at < 0) at = blocks.findIndex((block) => block.key === ownerKey);
+ const owner = blocks.at(at);
+ const first = owner?.mcids.indexOf(from[0]) ?? -1;
+ const last = owner?.mcids.indexOf(from.at(-1)!) ?? -1;
+ const read = owner
+ ? [...owner.mcids.slice(0, first), ...(before === null ? [] : [before])]
+ : [];
+ const later = owner
+ ? [...(after === null ? [] : [after]), ...owner.mcids.slice(last + 1)]
+ : [];
+
+ if (type === null || isInlineType(type)) {
+ if (owner && first >= 0) owner.mcids = [...read, edit.mcid, ...later];
+ return;
+ }
+ const cut: OutlineBlock = {
+ key: structure.block(edit.mcid)!.key,
+ type,
+ pageIndex,
+ mcids: [edit.mcid],
+ };
+ if (!owner || first < 0 || last < 0) {
+ blocks.splice(at < 0 ? blocks.length : at + 1, 0, cut);
+ return;
+ }
+ cut.partOf = [...owner.mcids, ...read, ...later];
+ if (read.length === 0 && later.length === 0) {
+ blocks[at] = { ...cut, key: owner.key };
+ } else if (read.length === 0) {
+ owner.mcids = later;
+ blocks.splice(at, 0, cut);
+ } else if (later.length === 0) {
+ owner.mcids = read;
+ blocks.splice(at + 1, 0, cut);
+ } else {
+ owner.mcids = read;
+ const rest = { ...owner, key: `${owner.key}:rest`, mcids: later };
+ blocks.splice(at + 1, 0, cut, rest);
+ }
+}
+
+/**
+ * Where an added element goes among `blocks`, as the save places it: after
+ * the block `anchor` names on its page, else before the page's first block,
+ * else before the next page's.
+ */
+function insertionPoint(
+ blocks: readonly { key: string; pageIndex: number | null }[],
+ pageIndex: number,
+ anchor: string | null,
+): number {
+ // Added keys repeat across pages; a file block spanning pages is listed
+ // under its first.
+ const onPage = blocks.findIndex(
+ (block) => block.key === anchor && block.pageIndex === pageIndex,
+ );
+ const at =
+ onPage >= 0 ? onPage : blocks.findIndex((block) => block.key === anchor);
+ if (at >= 0) return at + 1;
+ const next = blocks.findIndex(
+ (block) => block.pageIndex !== null && block.pageIndex >= pageIndex,
+ );
+ return next >= 0 ? next : blocks.length;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts
index f8769c1a3b..566d0d4b00 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts
@@ -1,7 +1,12 @@
+import type {
+ StructureRole,
+ StructureType,
+} from "@editor/tools/pdfTextEditor/model/structureTypes";
+
/** One structure element as the page sees it, read once when the page is first asked about. */
-export interface StructureElement {
- /** The element's /S after the /RoleMap: "Figure", "P", or an unmapped custom role. */
- type: string;
+export interface StructureElement extends StructureRole {
+ /** The element's StructureBlock key: equal to `block.key` when it is a block itself. */
+ key: string;
alt: string | null;
actualText: string | null;
/**
@@ -14,6 +19,89 @@ export interface StructureElement {
* child elements, annotations or form XObject content.
*/
onlyMarkedContent: boolean;
+ block: StructureBlock;
+}
+
+/**
+ * The block-level element content belongs to: the element itself, or for an
+ * inline one (a Link in a P, an Lbl in an LI) its nearest block ancestor.
+ * Text is grouped by block, so a link does not split its paragraph.
+ */
+export interface StructureBlock extends StructureRole {
+ /** Distinguishes blocks within one read of the tree; not stable across reads. */
+ key: string;
+}
+
+/**
+ * Elements that sit inside a block rather than being one: the inline-level
+ * types (ISO 32000-1 14.8.4.4, plus PDF 2.0's Em, Strong and Sub), the two
+ * halves of a list item, and NonStruct, whose content is processed as if it
+ * were its parent's (14.8.4.2).
+ */
+const INLINE_TYPES: ReadonlySet<StructureType> = new Set<StructureType>([
+ "Span",
+ "Quote",
+ "Note",
+ "Reference",
+ "BibEntry",
+ "Code",
+ "Link",
+ "Annot",
+ "Ruby",
+ "RB",
+ "RT",
+ "RP",
+ "Warichu",
+ "WT",
+ "WP",
+ "Em",
+ "Strong",
+ "Sub",
+ "Lbl",
+ "LBody",
+ "NonStruct",
+]);
+
+/**
+ * Elements that hold blocks rather than text. An inline type placed directly
+ * in one is used as a block (a Code listing in a Sect), so it is its own.
+ */
+const GROUPING_TYPES: ReadonlySet<StructureType> = new Set<StructureType>([
+ "Document",
+ "DocumentFragment",
+ "Part",
+ "Art",
+ "Sect",
+ "Div",
+ "BlockQuote",
+ "Aside",
+ "Private",
+ "TOC",
+ "Index",
+ "L",
+ "Table",
+ "THead",
+ "TBody",
+ "TFoot",
+ "TR",
+]);
+
+/**
+ * The block an element belongs to, given itself as a block and its parent,
+ * null at the top of the tree. A custom role is neither inline nor grouping:
+ * nothing says what it holds.
+ */
+export function containingBlock(
+ own: StructureBlock,
+ parent: { type: StructureType | null; block: StructureBlock } | null,
+): StructureBlock {
+ const inline = own.type !== null && isInlineType(own.type);
+ const grouping = parent?.type != null && GROUPING_TYPES.has(parent.type);
+ return parent !== null && inline && !grouping ? parent.block : own;
+}
+
+export function isInlineType(type: StructureType): boolean {
+ return INLINE_TYPES.has(type);
}
/** An unsaved change to an element, and the MCID the save addresses it by. */
@@ -29,7 +117,10 @@ export interface StructureElementEdit {
* Types whose /Alt stands in for the content. On any other element it would
* replace text a reader speaks, so a description there is refused.
*/
-const DESCRIBABLE_TYPES = new Set(["Figure", "Formula"]);
+const DESCRIBABLE_TYPES: ReadonlySet<StructureType> = new Set<StructureType>([
+ "Figure",
+ "Formula",
+]);
/** Why the save cannot write descriptions for a page. */
export type ReadOnlyReason = "encrypted" | "unreadable";
@@ -40,16 +131,122 @@ export type DescriptionBlocker = "untagged" | "not-figure" | ReadOnlyReason;
/** Why content cannot be marked decorative. */
export type DecorativeBlocker = DescriptionBlocker | "mixed-content";
-/** A Figure the session adds for content the file leaves untagged. */
-export interface AddedFigure {
+/** What a whole element's text can be retagged as. Lbl and Span only tag part of one (TEXT_RANGE_TYPES). */
+export const TEXT_BLOCK_TYPES = [
+ "P",
+ "H1",
+ "H2",
+ "H3",
+ "H4",
+ "H5",
+ "H6",
+ "Quote",
+ "Note",
+ "Code",
+] as const satisfies readonly StructureType[];
+
+/**
+ * What part of an element's text can be tagged as: an inline type joins the
+ * element, and any other splits the element around it.
+ */
+export const TEXT_RANGE_TYPES = [
+ "P",
+ "H1",
+ "H2",
+ "H3",
+ "H4",
+ "H5",
+ "H6",
+ "Lbl",
+ "Span",
+ "Quote",
+ "Note",
+ "Code",
+] as const satisfies readonly StructureType[];
+
+/** What an inline element of the file's own can be retagged as: changing it to a block would split its block. */
+const INLINE_RANGE_TYPES: readonly StructureType[] =
+ TEXT_RANGE_TYPES.filter(isInlineType);
+
+const RETAGGABLE_TYPES: ReadonlySet<StructureType> = new Set<StructureType>([
+ ...TEXT_BLOCK_TYPES,
+ "H",
+]);
+
+/**
+ * Why text cannot be retagged. "not-text" is a block holding more than text,
+ * such as a list item or table cell, whose retagging would break the
+ * structure around it.
+ */
+export type RetagBlocker = "untagged" | "not-text" | ReadOnlyReason;
+
+/** The type the session has retagged a block as, by block key; null when it has not. */
+export type RetagLookup = (key: string) => StructureType | null;
+
+type AddedStructureElement = StructureElement & { type: StructureType };
+
+/**
+ * Text the session cut out of an element into a new one. An inline type
+ * joins the element it was cut from; any other splits it, the cut becoming
+ * a sibling.
+ */
+export interface ContentCut {
+ /**
+ * The MCIDs the text was cut from, in reading order: consecutive kids of
+ * one element. All of their content is in the cut but for the parts
+ * `before` and `after` mark.
+ */
+ from: readonly number[];
+ /**
+ * The MCID of the content cut from that is read before the cut: the first
+ * of `from`, or one the cut gave it. Null when there is none.
+ */
+ before: number | null;
+ /** As `before`, for the content read after the cut, and the last of `from`. */
+ after: number | null;
+}
+
+/** The MCIDs a cut gave to the content it was cut from. */
+function givenMcids(cut: ContentCut): number[] {
+ return [cut.before, cut.after].filter(
+ (mcid): mcid is number => mcid !== null && !cut.from.includes(mcid),
+ );
+}
+
+/** An element the session cut out of another's text. */
+export interface CutElement {
+ mcid: number;
+ /** Null once removed: the save gives the text back to the element it was cut from. */
+ type: StructureType | null;
+ alt: string | null;
+ cut: ContentCut;
+}
+
+/** What an element marking part of a block's text can be changed to. */
+export interface InnerOptions {
+ /** Empty when its type cannot be changed. */
+ types: readonly StructureType[];
+ removable: boolean;
+}
+
+/** A change to one of the file's elements marking part of a block's text. */
+export interface InnerElementEdit {
mcid: number;
+ /** Null removes the element, its content joining its parent. */
+ type: StructureType | null;
+}
+
+/** An element the session adds for content the file leaves untagged. */
+export interface AddedElement {
+ mcid: number;
+ type: StructureType;
/** The /Alt to save; null for none. */
alt: string | null;
}
/**
* The structure elements of one page plus the session's unsaved edits to
- * them, and the figures it adds. Edits are keyed by element rather than MCID,
+ * them, and the elements it adds. Edits are keyed by element rather than MCID,
* so an element that owns several MCIDs has one description however it was
* addressed.
*/
@@ -57,24 +254,44 @@ export class PageStructure {
readonly elements: readonly StructureElement[];
private readonly byMcid = new Map<number, StructureElement>();
private readonly edits = new Map<StructureElement, StructureElementEdit>();
- private readonly added = new Map<number, StructureElement>();
+ private readonly added = new Map<number, AddedStructureElement>();
+ /** By the new element's MCID, in the order made: a later cut can take text from an earlier one. */
+ private readonly cuts = new Map<
+ number,
+ { cut: ContentCut; owner: StructureElement }
+ >();
+ private readonly fileElements: ReadonlySet<StructureElement>;
+ /** Changes to the file's inner elements: null for one the session removed. */
+ private readonly innerChanges = new Map<
+ StructureElement,
+ StructureType | null
+ >();
+ /**
+ * What a removed inner element's text belongs to, by block key, where the
+ * block owns no content of its own on the page to stand for it.
+ */
+ private readonly standIns = new Map<string, StructureElement>();
/** Why the save cannot write descriptions for this page, or null when it can. */
readonly readOnly: ReadOnlyReason | null;
/**
* The length of the page's ParentTree array, so the first MCID it has no
- * slot for; null when the page has no array to add a figure to.
+ * slot for; null when the page has no array to add an element to.
*/
private readonly slotCount: number | null;
+ private readonly retaggedAs: RetagLookup;
constructor(
elements: readonly StructureElement[],
readOnly: ReadOnlyReason | null = null,
slotCount: number | null = null,
+ retaggedAs: RetagLookup = () => null,
) {
this.elements = elements;
this.readOnly = readOnly;
this.slotCount = slotCount;
+ this.retaggedAs = retaggedAs;
+ this.fileElements = new Set(elements);
for (const el of elements) {
for (const mcid of el.mcids) this.byMcid.set(mcid, el);
}
@@ -88,12 +305,37 @@ export class PageStructure {
return this.byMcid.get(mcid) ?? null;
}
+ /**
+ * The block the content `mcid` marks belongs to, as the session has
+ * retagged it; null when no element owns it.
+ */
+ block(mcid: number): StructureBlock | null {
+ const block = this.element(mcid)?.block;
+ if (!block) return null;
+ const type = this.retaggedAs(block.key);
+ return type ? { key: block.key, role: type, type } : block;
+ }
+
+ /** Why the block the text `mcid` marks belongs to cannot be retagged, or null when it can. */
+ cannotRetag(mcid: number): RetagBlocker | null {
+ const el = this.element(mcid);
+ if (!el) return "untagged";
+ if (this.readOnly) return this.readOnly;
+ // A custom role's meaning is unknown, and giving it a standard one is the fix.
+ if (el.block.type !== null && !RETAGGABLE_TYPES.has(el.block.type)) {
+ return "not-text";
+ }
+ return null;
+ }
+
/** Why the content `mcid` marks cannot take a description, or null when it can. */
cannotDescribe(mcid: number): DescriptionBlocker | null {
const el = this.element(mcid);
if (!el) return "untagged";
if (this.readOnly) return this.readOnly;
- if (!DESCRIBABLE_TYPES.has(el.type)) return "not-figure";
+ if (el.type === null || !DESCRIBABLE_TYPES.has(el.type)) {
+ return "not-figure";
+ }
return null;
}
@@ -130,11 +372,11 @@ export class PageStructure {
/**
* Mark or unmark decorative, keeping the description. Throws as setEdit
- * does, and for an added figure, whose content is retagged instead.
+ * does, and for an added element, whose content is retagged instead.
*/
setDecorative(mcid: number, decorative: boolean): void {
if (this.added.has(mcid)) {
- throw new Error(`MCID ${mcid} is an added figure`);
+ throw new Error(`MCID ${mcid} is an added element`);
}
this.setEdit(mcid, { mcid, alt: this.alt(mcid), decorative });
}
@@ -147,65 +389,283 @@ export class PageStructure {
else this.edits.delete(el);
}
- /** Edits to the file's elements; added figures are listed by addedFigures. */
+ /** Edits to the file's elements; added elements are listed by addedElements. */
pendingEdits(): StructureElementEdit[] {
- const added = new Set(this.added.values());
+ const added = new Set<StructureElement>(this.added.values());
return [...this.edits]
.filter(([el]) => !added.has(el))
.map(([, edit]) => edit);
}
- /** Why untagged content on this page cannot be given a figure, or null when it can. */
- cannotAddFigure(): DescriptionBlocker | null {
+ /** Why untagged content on this page cannot be given an element, or null when it can. */
+ cannotAddElement(): DescriptionBlocker | null {
if (this.readOnly) return this.readOnly;
return this.slotCount === null ? "untagged" : null;
}
/**
- * An MCID no slot or added figure on the page uses, above `contentMax`: the
+ * An MCID no slot or added element on the page uses, above `contentMax`: the
* highest MCID the page's content carries, -1 for none.
*/
freeMcid(contentMax: number): number {
+ const used = [
+ ...this.added.keys(),
+ ...this.cuts.keys(),
+ ...this.cutGivenMcids(),
+ ];
return Math.max(
this.slotCount ?? 0,
contentMax + 1,
- ...[...this.added.keys()].map((mcid) => mcid + 1),
+ ...used.map((mcid) => mcid + 1),
);
}
+ /** The MCIDs cuts gave to content read before or after them. */
+ private cutGivenMcids(): number[] {
+ return [...this.cuts.values()].flatMap(({ cut }) => givenMcids(cut));
+ }
+
isAdded(mcid: number): boolean {
return this.added.has(mcid);
}
- /** Give the content `mcid` marks a new Figure. Throws when an element already owns it. */
- addFigure(mcid: number): void {
+ /** Give the content `mcid` marks a new element. Throws when an element already owns it. */
+ addElement(mcid: number, type: StructureType): void {
if (this.byMcid.has(mcid)) {
throw new Error(`MCID ${mcid} already has an element`);
}
- const figure: StructureElement = {
- type: "Figure",
+ this.putAdded(mcid, type);
+ }
+
+ /**
+ * Give the text `cut` takes from an element its own element of `type`,
+ * the content it took now marked `mcid`. Throws when `mcid` already has an
+ * element or no element owns the content it was cut from.
+ */
+ addCut(mcid: number, type: StructureType, cut: ContentCut): void {
+ const owner = this.element(cut.from[0]);
+ if (!owner)
+ throw new Error(`No structure element owns MCID ${cut.from[0]}`);
+ if (this.byMcid.has(mcid)) {
+ throw new Error(`MCID ${mcid} already has an element`);
+ }
+ this.cuts.set(mcid, { cut, owner });
+ this.putAdded(mcid, type);
+ for (const given of givenMcids(cut)) this.byMcid.set(given, owner);
+ }
+
+ /** Change the type of the element added for `mcid`. Throws when none was added. */
+ setAddedType(mcid: number, type: StructureType): void {
+ const previous = this.added.get(mcid);
+ if (!previous) throw new Error(`MCID ${mcid} was not added`);
+ const edit = this.edits.get(previous);
+ this.edits.delete(previous);
+ const element = this.putAdded(mcid, type);
+ if (edit) this.edits.set(element, edit);
+ }
+
+ private putAdded(mcid: number, type: StructureType): AddedStructureElement {
+ const key = addedKey(mcid);
+ const owner = this.cuts.get(mcid)?.owner;
+ const own = { key, role: type, type };
+ const element: AddedStructureElement = {
+ role: type,
+ type,
alt: null,
actualText: null,
mcids: [mcid],
onlyMarkedContent: true,
+ key,
+ block: owner ? containingBlock(own, owner) : own,
};
- this.added.set(mcid, figure);
- this.byMcid.set(mcid, figure);
+ this.added.set(mcid, element);
+ this.byMcid.set(mcid, element);
+ return element;
}
- /** Drop an added figure and its description. */
- removeFigure(mcid: number): void {
- const figure = this.added.get(mcid);
- if (!figure) return;
+ /** Drop an added element, its description, and the cut it was made by. */
+ removeElement(mcid: number): void {
+ const element = this.added.get(mcid);
+ if (!element && !this.cuts.has(mcid)) return;
this.added.delete(mcid);
this.byMcid.delete(mcid);
- this.edits.delete(figure);
+ if (element) this.edits.delete(element);
+ const cut = this.cuts.get(mcid)?.cut;
+ this.cuts.delete(mcid);
+ for (const given of cut ? givenMcids(cut) : []) this.byMcid.delete(given);
+ }
+
+ /** Elements added for untagged content; cutElements lists the rest. */
+ addedElements(): AddedElement[] {
+ return [...this.added.keys()]
+ .filter((mcid) => !this.cuts.has(mcid))
+ .map((mcid) => this.addedElement(mcid));
}
- addedFigures(): AddedFigure[] {
- return [...this.added.keys()].map((mcid) => ({
+ /** Elements cut from others' text, in the order they were cut. */
+ cutElements(): CutElement[] {
+ return [...this.cuts].map(([mcid, { cut }]) => ({
mcid,
+ type: this.added.get(mcid)?.type ?? null,
alt: this.alt(mcid),
+ cut,
+ }));
+ }
+
+ /** True when the element is a block of text, which a block cut out of it can split. */
+ canSplit(el: StructureElement): boolean {
+ return el.block.key === el.key && this.cannotRetag(el.mcids[0]) === null;
+ }
+
+ /**
+ * The role element `key` has as the session has it, one marking part of a
+ * block's text; null once the session removed it. Throws when the page has
+ * no such element.
+ */
+ innerType(key: string): StructureRole | null {
+ const cut = this.cutMcid(key);
+ if (cut !== null) {
+ const type = this.added.get(cut)?.type;
+ return type ? { role: type, type } : null;
+ }
+ const el = this.fileElement(key);
+ const change = this.innerChanges.get(el);
+ if (change === undefined) return el;
+ return change === null ? null : { role: change, type: change };
+ }
+
+ /** What element `key` can be changed to. Throws as innerType does. */
+ innerOptions(key: string): InnerOptions {
+ if (this.readOnly) return { types: [], removable: false };
+ const cut = this.cutMcid(key);
+ if (cut !== null) {
+ const { owner } = this.cuts.get(cut)!;
+ const types = this.canSplit(owner)
+ ? TEXT_RANGE_TYPES
+ : INLINE_RANGE_TYPES;
+ return { types, removable: true };
+ }
+ const el = this.fileElement(key);
+ // In a list item or table cell the element is part of that structure:
+ // an LI's Lbl must stay one.
+ if (el.key === el.block.key || this.cannotRetag(el.mcids[0]) !== null) {
+ return { types: [], removable: false };
+ }
+ const inline = el.type !== null && INLINE_RANGE_TYPES.includes(el.type);
+ return {
+ types: inline ? INLINE_RANGE_TYPES : [],
+ // Only marked content can join the parent without re-parenting
+ // annotations or child elements.
+ removable: el.type !== null && el.onlyMarkedContent,
+ };
+ }
+
+ /**
+ * Retag element `key`, or remove it with null, its text read as its
+ * block's again. Throws as innerType does, and for a change innerOptions
+ * does not offer, but for going back to the file's type: one the save
+ * cannot write would fail every later save.
+ */
+ setInnerType(key: string, type: StructureType | null): void {
+ const cut = this.cutMcid(key);
+ const el = cut === null ? this.fileElement(key) : null;
+ const options = this.innerOptions(key);
+ const allowed =
+ type === null
+ ? options.removable
+ : type === el?.type || options.types.includes(type);
+ if (!allowed) throw new Error(`Element ${key} cannot become ${type}`);
+ if (!el) {
+ this.setCutType(cut!, type);
+ return;
+ }
+ const holder = type === null ? this.standIn(el) : el;
+ for (const mcid of el.mcids) this.byMcid.set(mcid, holder);
+ if (type === el.type) this.innerChanges.delete(el);
+ else this.innerChanges.set(el, type);
+ }
+
+ /** Changes to the file's inner elements, for the save. */
+ innerEdits(): InnerElementEdit[] {
+ return [...this.innerChanges].map(([el, type]) => ({
+ mcid: el.mcids[0],
+ type,
}));
}
+
+ private setCutType(mcid: number, type: StructureType | null): void {
+ if (type !== null) {
+ if (this.added.has(mcid)) this.setAddedType(mcid, type);
+ else this.putAdded(mcid, type);
+ return;
+ }
+ const element = this.added.get(mcid);
+ if (element) this.edits.delete(element);
+ this.added.delete(mcid);
+ this.byMcid.set(mcid, this.cuts.get(mcid)!.owner);
+ }
+
+ private cutMcid(key: string): number | null {
+ for (const mcid of this.cuts.keys()) {
+ if (addedKey(mcid) === key) return mcid;
+ }
+ return null;
+ }
+
+ private fileElement(key: string): StructureElement {
+ const el = this.elements.find((candidate) => candidate.key === key);
+ if (!el) throw new Error(`No element ${key} on the page`);
+ return el;
+ }
+
+ /** The element a removed inner element's text belongs to: its block. */
+ private standIn(el: StructureElement): StructureElement {
+ const block = this.elements.find((other) => other.key === el.block.key);
+ if (block) return block;
+ const made = this.standIns.get(el.block.key) ?? {
+ ...el.block,
+ alt: null,
+ actualText: null,
+ mcids: el.mcids,
+ onlyMarkedContent: true,
+ block: el.block,
+ };
+ this.standIns.set(el.block.key, made);
+ return made;
+ }
+
+ private addedElement(mcid: number): AddedElement {
+ return { mcid, type: this.added.get(mcid)!.type, alt: this.alt(mcid) };
+ }
+
+ /** The MCID of the element the session added that is block `key`; null for a block the file has. */
+ addedBlockMcid(key: string): number | null {
+ for (const [mcid, element] of this.added) {
+ if (element.key === key && element.block.key === key) return mcid;
+ }
+ return null;
+ }
+
+ /**
+ * An MCID the file's own tree resolves to the element holding `mcid`'s
+ * content, or for text cut into an inline element, to the element it was
+ * cut from. Null for text in an element the session added.
+ */
+ fileMcid(mcid: number): number | null {
+ const cut = this.cuts.get(mcid);
+ const el = cut ? cut.owner : this.element(mcid);
+ if (!el) return null;
+ // A stand-in's MCIDs still name the removed element in the file, whose
+ // block the save climbs to.
+ if (this.fileElements.has(el) || this.isStandIn(el)) return el.mcids[0];
+ return cut ? this.fileMcid(el.mcids[0]) : null;
+ }
+
+ private isStandIn(el: StructureElement): boolean {
+ return this.standIns.get(el.key) === el;
+ }
+}
+
+function addedKey(mcid: number): string {
+ return `added:${mcid}`;
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/TextRun.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/TextRun.ts
index a9e1d37ac1..1fc5d9a220 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/TextRun.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/TextRun.ts
@@ -1,5 +1,9 @@
import type { ScanEditState } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
-import type { TagMark } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+import {
+ ARTIFACT_TAG,
+ innermostMcid,
+ type TagMark,
+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
import type {
Affine,
PageRect,
@@ -205,6 +209,10 @@ export class TextRun {
paragraphLineLefts: this.lineLefts(),
locked: this.locked || undefined,
wrapWidthPt: this.wrapWidthPt ?? undefined,
+ mcid: innermostMcid(this.tagMarks) ?? undefined,
+ artifact:
+ this.tagMarks.some((tag) => tag.name === ARTIFACT_TAG) || undefined,
+ inForm: this.containerPtr !== 0 || undefined,
};
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/structureTypes.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/structureTypes.ts
new file mode 100644
index 0000000000..d24d32783c
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/structureTypes.ts
@@ -0,0 +1,105 @@
+/**
+ * The standard structure types: ISO 32000-1 14.8.4, plus the types ISO
+ * 32000-2 adds. A file may name others, which are only meaningful through a
+ * /RoleMap entry mapping them to one of these.
+ */
+export const STANDARD_STRUCTURE_TYPES = [
+ "Document",
+ "DocumentFragment",
+ "Part",
+ "Art",
+ "Sect",
+ "Div",
+ "Aside",
+ "BlockQuote",
+ "Caption",
+ "TOC",
+ "TOCI",
+ "Index",
+ "NonStruct",
+ "Private",
+ "Title",
+ "FENote",
+ "P",
+ "H",
+ "H1",
+ "H2",
+ "H3",
+ "H4",
+ "H5",
+ "H6",
+ "L",
+ "LI",
+ "Lbl",
+ "LBody",
+ "Table",
+ "TR",
+ "TH",
+ "TD",
+ "THead",
+ "TBody",
+ "TFoot",
+ "Span",
+ "Quote",
+ "Note",
+ "Reference",
+ "BibEntry",
+ "Code",
+ "Link",
+ "Annot",
+ "Ruby",
+ "RB",
+ "RT",
+ "RP",
+ "Warichu",
+ "WT",
+ "WP",
+ "Em",
+ "Strong",
+ "Sub",
+ "Figure",
+ "Formula",
+ "Form",
+ "Artifact",
+] as const;
+
+export type StructureType = (typeof STANDARD_STRUCTURE_TYPES)[number];
+
+const STANDARD = new Set<string>(STANDARD_STRUCTURE_TYPES);
+
+export function isStandardStructureType(name: string): name is StructureType {
+ return STANDARD.has(name);
+}
+
+/** What an element is tagged as. */
+export interface StructureRole {
+ /** The name /S resolves to through the /RoleMap: a standard type, or a custom role left unmapped. */
+ role: string;
+ /** `role` as a standard type; null for a custom role, whose meaning is unknown. */
+ type: StructureType | null;
+}
+
+export function structureRole(role: string): StructureRole {
+ return { role, type: isStandardStructureType(role) ? role : null };
+}
+
+export type HeadingType = "H" | "H1" | "H2" | "H3" | "H4" | "H5" | "H6";
+
+const HEADING_LEVELS: Record<HeadingType, number | null> = {
+ H: null,
+ H1: 1,
+ H2: 2,
+ H3: 3,
+ H4: 4,
+ H5: 5,
+ H6: 6,
+};
+
+export function isHeadingType(type: StructureType | null): type is HeadingType {
+ return type !== null && Object.hasOwn(HEADING_LEVELS, type);
+}
+
+/** A numbered heading's level; null for H, whose level is its nesting. */
+export function headingLevel(type: HeadingType): number | null {
+ return HEADING_LEVELS[type];
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/markedContent.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/markedContent.ts
index f9239127ec..72e1f6e1a5 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/markedContent.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/markedContent.ts
@@ -13,6 +13,7 @@ import {
} from "@editor/tools/pdfTextEditor/pdfdoc/contentOps";
import {
arrayItems,
+ indirectRef,
referencedObject,
setDictEntry,
spliceValue,
@@ -132,6 +133,42 @@ export function elementKids(pdf: RawPdf, body: string): string[] | null {
return arrayItems(span.text)?.map((kid) => kid.text) ?? null;
}
+/**
+ * The MCID a /K entry marks on page `pageNum`, in an element whose /Pg is
+ * `elementPage`: an integer names an MCID on that page. Null for any other
+ * kid: a child element, an annotation, form XObject content, or content on
+ * another page.
+ */
+export function kidMcid(
+ pdf: RawPdf,
+ kid: string,
+ elementPage: number | null,
+ pageNum: number,
+): number | null {
+ if (/^\d+$/.test(kid)) {
+ return elementPage === pageNum ? parseInt(kid, 10) : null;
+ }
+ const ref = referencedObject(kid);
+ const dict = ref === null ? kid : pdf.objectBody(ref);
+ if (!dict?.trimStart().startsWith("<<")) return null;
+ if (pdf.dictName(dict, "Type") !== "MCR" || pdf.valueSpan(dict, "Stm")) {
+ return null;
+ }
+ const page = pdf.dictRef(dict, "Pg") ?? elementPage;
+ return page === pageNum ? pdf.dictInt(dict, "MCID") : null;
+}
+
+/** The /K entry for MCID `mcid` on page `pageNum`, in an element whose /Pg is `elementPage`. */
+export function mcidKid(
+ pdf: RawPdf,
+ mcid: number,
+ elementPage: number | null,
+ pageNum: number,
+): string {
+ if (elementPage === pageNum) return String(mcid);
+ return `<< /Type /MCR /Pg ${indirectRef(pdf, pageNum)} /MCID ${mcid} >>`;
+}
+
/** True when every kid in the element's /K is an MCID or an MCR on a page, rather than a child element, an annotation or form XObject content. */
export function ownsOnlyMarkedContent(pdf: RawPdf, body: string): boolean {
const kids = elementKids(pdf, body);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addFigures.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addElements.ts
similarity index 58%
rename from frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addFigures.ts
rename to frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addElements.ts
index 917c19ff92..cab8468be5 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addFigures.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addElements.ts
@@ -1,7 +1,7 @@
/**
- * Give content the file leaves untagged a Figure element of its own. The
- * editor marked the content with its MCID before PDFium regenerated the page,
- * so only the tree changes here.
+ * Give content the file leaves untagged an element of its own. The editor
+ * marked the content with its MCID before PDFium regenerated the page, so
+ * only the tree changes here.
*/
import {
elementKids,
@@ -10,20 +10,25 @@ import {
type PageSites,
} from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";
import {
+ indirectRef,
referencedObject,
setDictEntry,
type RawPdf,
} from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import type { StructureNodes } from "@editor/tools/pdfTextEditor/pdfdoc/structureNodes";
+import { unusedObjectNumber } from "@editor/tools/pdfTextEditor/pdfdoc/revision";
import { encodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString";
+import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";
-export interface NewFigure {
+export interface NewElement {
pageIndex: number;
mcid: number;
+ type: StructureType;
alt: string | null;
/**
- * The MCID of the content the figure reads after: it goes after the element
- * owning that, or before the element owning the page's first tagged content
- * when null or unowned.
+ * The MCID of the content the element reads after: it goes after the
+ * block holding that, or before the block holding the page's first tagged
+ * content when null or unowned (see StructureNodes.placementSibling).
*/
after: number | null;
}
@@ -35,66 +40,67 @@ interface Placement {
}
/**
- * Plan a Figure for each of `figures`, in order, so one placed after an
+ * Plan an element for each of `elements`, in order, so one placed after an
* earlier one finds it. New element bodies, and the parents they join, are
* written to `bodies`, and ParentTree slots to `parentTree`. Returns why a
* figure could not be added, by index; nothing is written for a document
* with any failure, so the caller must discard it all.
*/
-export async function addFigures(
+export async function addElements(
pdf: RawPdf,
treeRoot: number,
- figures: readonly NewFigure[],
+ nodes: StructureNodes,
+ elements: readonly NewElement[],
bodies: Map<number, string>,
parentTree: ParentTreeWriter,
): Promise<Map<number, string>> {
const failed = new Map<number, string>();
const body = (num: number) => bodies.get(num) ?? pdf.objectBody(num);
const sites = new Map<number, Promise<PageSites | null>>();
- let nextNum = pdf.highestObjectNumber + 1;
- for (const [index, figure] of figures.entries()) {
- const pageNum = pdf.pageNumberAt(figure.pageIndex);
+ for (const [index, element] of elements.entries()) {
+ const pageNum = pdf.pageNumberAt(element.pageIndex);
const slots = pageNum === null ? null : parentTree.slots(pageNum);
if (pageNum === null || !slots) {
failed.set(index, "its page has no ParentTree array");
continue;
}
- if (referencedObject(slots[figure.mcid] ?? "") !== null) {
+ if (referencedObject(slots[element.mcid] ?? "") !== null) {
failed.set(index, "another element owns its MCID");
continue;
}
if (!sites.has(pageNum)) sites.set(pageNum, pageSites(pdf, pageNum));
const read = await sites.get(pageNum)!;
- if (!read?.sites.some((site) => site.mcid === figure.mcid)) {
+ if (!read?.sites.some((site) => site.mcid === element.mcid)) {
failed.set(index, "the page's content does not carry its MCID");
continue;
}
- const place = placement(pdf, body, treeRoot, slots, figure.after);
+ const place = placement(pdf, body, treeRoot, nodes, slots, element.after);
const parent = body(place.parent);
- const joined = parent ? withKid(pdf, parent, place, nextNum) : null;
+ const num = unusedObjectNumber(pdf, bodies);
+ const joined = parent ? withKid(pdf, parent, place, num) : null;
if (!joined) {
failed.set(index, "its parent element cannot be read");
continue;
}
- const num = nextNum++;
bodies.set(place.parent, joined);
const alt =
- figure.alt === null ? "" : ` /Alt ${encodeTextString(figure.alt)}`;
+ element.alt === null ? "" : ` /Alt ${encodeTextString(element.alt)}`;
+ const id = element.type === "Note" ? ` /ID ${noteId(num)}` : "";
bodies.set(
num,
- `<< /Type /StructElem /S /Figure /P ${ref(pdf, place.parent)} ` +
- `/Pg ${ref(pdf, pageNum)} /K ${figure.mcid}${alt} >>`,
+ `<< /Type /StructElem /S /${element.type} /P ${indirectRef(pdf, place.parent)} ` +
+ `/Pg ${indirectRef(pdf, pageNum)} /K ${element.mcid}${alt}${id} >>`,
);
- while (slots.length < figure.mcid) slots.push("null");
- slots[figure.mcid] = `${num} 0 R`;
+ while (slots.length < element.mcid) slots.push("null");
+ slots[element.mcid] = `${num} 0 R`;
}
return failed;
}
/**
- * Beside the element owning MCID `after`; else before the element owning the
+ * After the block holding MCID `after`; else before the block holding the
* page's first tagged content; else last in the document's top element, for a
* page with no tagged content.
*/
@@ -102,12 +108,17 @@ function placement(
pdf: RawPdf,
body: (num: number) => string | null,
treeRoot: number,
+ nodes: StructureNodes,
slots: readonly string[],
after: number | null,
): Placement {
+ // Text read after a paragraph that ends in a link is not part of the link,
+ // nor of the paragraph.
const beside = (owner: number | null, before: boolean): Placement | null => {
- const parent = owner === null ? null : pdf.dictRef(body(owner) ?? "", "P");
- return parent === null ? null : { parent, sibling: owner, before };
+ const sibling = owner === null ? null : nodes.placementSibling(owner);
+ const parent =
+ sibling === null ? null : pdf.dictRef(body(sibling) ?? "", "P");
+ return parent === null ? null : { parent, sibling, before };
};
const anchor = after === null ? null : referencedObject(slots[after] ?? "");
const first = slots
@@ -139,6 +150,10 @@ function insertionIndex(count: number, at: number, before: boolean): number {
return before ? at : at + 1;
}
-function ref(pdf: RawPdf, num: number): string {
- return `${num} ${pdf.generationOf(num)} R`;
+/**
+ * The /ID PDF/UA-1 7.9 requires on a Note, unique in the file as the
+ * object number is.
+ */
+export function noteId(num: number): string {
+ return `(note-${num})`;
}
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 c0439c37bb..f85d8a168f 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts
@@ -12,23 +12,43 @@ import {
plainObject,
} from "@editor/tools/pdfTextEditor/pdfdoc/revision";
import { ParentTreeWriter } from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";
-import { addFigures } from "@editor/tools/pdfTextEditor/pdfdoc/passes/addFigures";
+import {
+ addElements,
+ noteId,
+} from "@editor/tools/pdfTextEditor/pdfdoc/passes/addElements";
+import { cutElements } from "@editor/tools/pdfTextEditor/pdfdoc/passes/cutElements";
import { markDecorative } from "@editor/tools/pdfTextEditor/pdfdoc/passes/markDecorative";
+import { unwrapElements } from "@editor/tools/pdfTextEditor/pdfdoc/passes/unwrapElements";
+import { StructureNodes } from "@editor/tools/pdfTextEditor/pdfdoc/structureNodes";
import { encodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString";
+import 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. */
export interface StructureEdit {
pageIndex: number;
mcid: number;
- /** The new /Alt; null removes it. */
- alt: string | null;
+ /** The new /Alt; null removes it, absent leaves it. */
+ alt?: string | null;
+ /**
+ * The new /S of the block the element belongs to: the element itself when
+ * it is one, else the block an inline element such as a Span sits in.
+ */
+ type?: StructureType;
+ /** The new /S of the element itself; null removes it, its content joining its parent. */
+ ownType?: StructureType | null;
/** Turn the element's content into an artifact and drop the element, its /Alt with it. */
decorative: boolean;
/**
- * Set when no element owns the content yet: add a Figure for it, after the
- * element owning MCID `after` on the page (see NewFigure).
+ * Set when no element owns the content yet: add one of `type` for it, after
+ * the element owning MCID `after` on the page (see NewElement).
+ */
+ newElement?: { type: StructureType; after: number | null };
+ /**
+ * Set when the content was cut out of an element's: give it one of `type`,
+ * or give it back to that element with null (see cutElements).
*/
- newFigure?: { after: number | null };
+ cut?: ContentCut & { type: StructureType | null };
}
export interface StructureEditFailure {
@@ -74,11 +94,18 @@ export async function applyStructureEdits(
if (treeRoot === null) throw fail("the file has no structure tree");
const bodies = new Map<number, string>();
+ const nodes = new StructureNodes(
+ pdf,
+ pdf.objectBody(treeRoot) ?? "",
+ (num) => bodies.get(num) ?? pdf.objectBody(num),
+ );
const failures: StructureEditFailure[] = [];
const decorative = new Map<number, StructureEdit[]>();
- const figures = edits.filter((edit) => edit.newFigure);
+ const unwraps: { edit: StructureEdit; owner: number }[] = [];
+ const added = edits.filter((edit) => edit.newElement);
+ const cuts = edits.filter((edit) => edit.cut);
for (const edit of edits) {
- if (edit.newFigure) continue;
+ if (edit.newElement || edit.cut) continue;
const owner = elementFor(pdf, treeRoot, edit);
if (typeof owner === "string") {
failures.push({ edit, reason: owner });
@@ -88,11 +115,13 @@ export async function applyStructureEdits(
decorative.set(owner, [...(decorative.get(owner) ?? []), edit]);
continue;
}
- const body = bodies.get(owner) ?? pdf.objectBody(owner)!;
- const updated =
- edit.alt === null
- ? removeDictEntry(body, "Alt")
- : setDictEntry(body, "Alt", encodeTextString(edit.alt));
+ if (edit.ownType === null) {
+ unwraps.push({ edit, owner });
+ continue;
+ }
+ const target = edit.type ? nodes.blockOf(owner) : owner;
+ const body = bodies.get(target) ?? pdf.objectBody(target);
+ const updated = body === null ? null : edited(pdf, body, edit, target);
if (updated === null) {
failures.push({
edit,
@@ -100,21 +129,53 @@ export async function applyStructureEdits(
});
continue;
}
- bodies.set(owner, updated);
+ bodies.set(target, updated);
}
const parentTree = new ParentTreeWriter(pdf, treeRoot);
- // Before the decorative marks, so a figure placed beside an element they
- // drop keeps its place among the kids that remain.
- const unplaced = await addFigures(
+ // After the retags, which address elements through the ParentTree as the
+ // file has it, and before the cuts, which may take text an element held.
+ const kept = unwrapElements(
+ pdf,
+ unwraps.map(({ owner }) => owner),
+ bodies,
+ parentTree,
+ );
+ 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,
+ cut: edit.cut!,
+ })),
+ bodies,
+ parentTree,
+ );
+ for (const [index, reason] of uncut) {
+ failures.push({ edit: cuts[index], reason });
+ }
+ // Before the decorative marks, so an element placed beside one they drop
+ // keeps its place among the kids that remain.
+ const unplaced = await addElements(
pdf,
treeRoot,
- figures.map((edit) => ({ ...edit, after: edit.newFigure!.after })),
+ nodes,
+ added.map((edit) => ({
+ ...edit,
+ ...edit.newElement!,
+ alt: edit.alt ?? null,
+ })),
bodies,
parentTree,
);
for (const [index, reason] of unplaced) {
- failures.push({ edit: figures[index], reason });
+ failures.push({ edit: added[index], reason });
}
const { streams, failed } = await markDecorative(
pdf,
@@ -140,6 +201,30 @@ export async function applyStructureEdits(
return out;
}
+/** The element's body with `edit`'s /Alt and /S applied; null when it is not a dictionary. */
+function edited(
+ pdf: RawPdf,
+ body: string,
+ edit: StructureEdit,
+ num: number,
+): string | null {
+ let out: string | null = body;
+ const type = edit.type ?? edit.ownType;
+ if (edit.alt !== undefined) {
+ out =
+ edit.alt === null
+ ? removeDictEntry(out, "Alt")
+ : setDictEntry(out, "Alt", encodeTextString(edit.alt));
+ }
+ if (out !== null && type) {
+ out = setDictEntry(out, "S", `/${type}`);
+ if (out !== null && type === "Note" && !pdf.valueSpan(out, "ID")) {
+ out = setDictEntry(out, "ID", noteId(num));
+ }
+ }
+ return out;
+}
+
/** The structure element's object number, or why it cannot be found. */
function elementFor(
pdf: RawPdf,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/cutElements.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/cutElements.ts
new file mode 100644
index 0000000000..25d3373805
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/cutElements.ts
@@ -0,0 +1,337 @@
+/**
+ * Give text cut out of an element its own element. The editor marked the cut
+ * text with a new MCID before PDFium regenerated the page, so only the tree
+ * changes here: an inline element joins the element the text was cut from,
+ * among its kids where the text was read, and any other splits that element
+ * in two around it.
+ */
+import {
+ elementKids,
+ kidMcid,
+ mcidKid,
+ pageSites,
+ type ParentTreeWriter,
+ type PageSites,
+} from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";
+import { noteId } from "@editor/tools/pdfTextEditor/pdfdoc/passes/addElements";
+import {
+ indirectRef,
+ referencedObject,
+ setDictEntry,
+ type RawPdf,
+} from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import { unusedObjectNumber } from "@editor/tools/pdfTextEditor/pdfdoc/revision";
+import { encodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString";
+import {
+ isInlineType,
+ type ContentCut,
+} from "@editor/tools/pdfTextEditor/model/PageStructure";
+import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";
+
+export interface NewCut {
+ pageIndex: number;
+ /** The MCID the cut text carries. */
+ mcid: number;
+ /** Null for a cut the session removed. */
+ type: StructureType | null;
+ alt: string | null;
+ cut: ContentCut;
+}
+
+type TypedCut = NewCut & { type: StructureType };
+
+/** What one cut changes, worked out before anything is written. */
+interface CutPlan {
+ pageNum: number;
+ slots: string[];
+ owner: number;
+ ownerBody: string;
+ ownerPage: number | null;
+ /** The owner's kids read before the cut, and after it. */
+ before: string[];
+ after: string[];
+}
+
+/**
+ * Write an element for each of `cuts`, in order, so a cut from an earlier
+ * one's text finds it. Bodies are written to `bodies` and ParentTree slots to
+ * `parentTree`. Returns why a cut could not be written, by index; the caller
+ * must then discard everything.
+ */
+export async function cutElements(
+ pdf: RawPdf,
+ cuts: readonly NewCut[],
+ bodies: Map<number, string>,
+ parentTree: ParentTreeWriter,
+): Promise<Map<number, string>> {
+ const failed = new Map<number, string>();
+ const sites = new Map<number, Promise<PageSites | null>>();
+ const read = (pageNum: number) => {
+ if (!sites.has(pageNum)) sites.set(pageNum, pageSites(pdf, pageNum));
+ return sites.get(pageNum)!;
+ };
+ for (const [index, cut] of cuts.entries()) {
+ const plan = await planCut(pdf, cut, bodies, parentTree, read);
+ if (typeof plan === "string") {
+ failed.set(index, plan);
+ continue;
+ }
+ const reason =
+ cut.type === null || isInlineType(cut.type)
+ ? joinOwner(pdf, cut, plan, bodies)
+ : splitOwner(pdf, { ...cut, type: cut.type }, plan, bodies, parentTree);
+ if (reason) failed.set(index, reason);
+ }
+ return failed;
+}
+
+async function planCut(
+ pdf: RawPdf,
+ { pageIndex, mcid, cut }: NewCut,
+ bodies: Map<number, string>,
+ parentTree: ParentTreeWriter,
+ read: (pageNum: number) => Promise<PageSites | null>,
+): Promise<CutPlan | string> {
+ const pageNum = pdf.pageNumberAt(pageIndex);
+ const slots = pageNum === null ? null : parentTree.slots(pageNum);
+ if (pageNum === null || !slots) return "its page has no ParentTree array";
+ if (referencedObject(slots[mcid] ?? "") !== null) {
+ return "another element owns its MCID";
+ }
+ const carried = new Set((await read(pageNum))?.sites.map((s) => s.mcid));
+ const parts = [cut.before, cut.after].filter((part) => part !== null);
+ if (![mcid, ...parts].every((part) => carried.has(part))) {
+ return "the page's content does not carry its MCIDs";
+ }
+
+ const owner = referencedObject(slots[cut.from[0]] ?? "");
+ if (
+ owner === null ||
+ cut.from.some((from) => referencedObject(slots[from] ?? "") !== owner)
+ ) {
+ return "the text it was cut from is not one element's";
+ }
+ const ownerBody = bodies.get(owner) ?? pdf.objectBody(owner);
+ const kids = ownerBody ? elementKids(pdf, ownerBody) : null;
+ if (!ownerBody || !kids) return "the element it was cut from cannot be read";
+ const ownerPage = pdf.dictRef(ownerBody, "Pg");
+ const at = cut.from.map((from) =>
+ kids.findIndex((kid) => kidMcid(pdf, kid, ownerPage, pageNum) === from),
+ );
+ if (at[0] < 0 || at.some((i, n) => i !== at[0] + n)) {
+ return "the text it was cut from is not consecutive in its element";
+ }
+
+ const first = at[0];
+ const last = at.at(-1)!;
+ // A part the cut left an MCID it was cut from keeps that MCID's kid.
+ const partKid = (part: number | null, kid: number): string[] => {
+ if (part === null) return [];
+ if (part === cut.from[kid - first]) return [kids[kid]];
+ return [mcidKid(pdf, part, ownerPage, pageNum)];
+ };
+ for (const from of cut.from) {
+ if (from !== cut.before && from !== cut.after) slots[from] = "null";
+ }
+ return {
+ pageNum,
+ slots,
+ owner,
+ ownerBody,
+ ownerPage,
+ before: [...kids.slice(0, first), ...partKid(cut.before, first)],
+ after: [...partKid(cut.after, last), ...kids.slice(last + 1)],
+ };
+}
+
+/**
+ * Put the cut among the owner's kids, between the parts read before and
+ * after it: as an element of its own, or as the owner's own content when the
+ * session removed it.
+ */
+function joinOwner(
+ pdf: RawPdf,
+ cut: NewCut,
+ plan: CutPlan,
+ bodies: Map<number, string>,
+): string | null {
+ const num = cut.type === null ? null : unusedObjectNumber(pdf, bodies);
+ const kid =
+ num === null
+ ? mcidKid(pdf, cut.mcid, plan.ownerPage, plan.pageNum)
+ : indirectRef(pdf, num);
+ const kids = [...plan.before, kid, ...plan.after];
+ const owner = setDictEntry(plan.ownerBody, "K", `[${kids.join(" ")}]`);
+ if (!owner) return "the element it was cut from cannot be written";
+ bodies.set(plan.owner, owner);
+ if (num !== null && cut.type !== null) {
+ const element = newElement(
+ pdf,
+ { ...cut, type: cut.type },
+ num,
+ plan.owner,
+ plan.pageNum,
+ );
+ bodies.set(num, element);
+ }
+ setSlot(plan.slots, cut.mcid, num ?? plan.owner);
+ keepParts(plan, [cut.cut.before, cut.cut.after]);
+ return null;
+}
+
+/** Give the parts read before or after the cut to the owner. */
+function keepParts(plan: CutPlan, parts: readonly (number | null)[]): void {
+ for (const part of parts) {
+ if (part !== null) setSlot(plan.slots, part, plan.owner);
+ }
+}
+
+/**
+ * Make the cut a sibling of the owner. The owner keeps what is read before
+ * it, and what is read after moves to a new element of the owner's type; one
+ * with nothing read before or after is retagged instead.
+ */
+function splitOwner(
+ pdf: RawPdf,
+ cut: TypedCut,
+ plan: CutPlan,
+ bodies: Map<number, string>,
+ parentTree: ParentTreeWriter,
+): string | null {
+ const { before, after, owner, ownerBody, slots } = plan;
+ if (before.length === 0 && after.length === 0) {
+ return retagOwner(pdf, cut, plan, bodies);
+ }
+ const parent = pdf.dictRef(ownerBody, "P");
+ const parentBody =
+ parent === null ? null : (bodies.get(parent) ?? pdf.objectBody(parent));
+ const siblings = parentBody ? elementKids(pdf, parentBody) : null;
+ const at = siblings?.findIndex((kid) => referencedObject(kid) === owner);
+ if (
+ parent === null ||
+ !parentBody ||
+ !siblings ||
+ at === undefined ||
+ at < 0
+ ) {
+ return "the element it was cut from has no parent to split it in";
+ }
+
+ const num = unusedObjectNumber(pdf, bodies);
+ bodies.set(num, newElement(pdf, cut, num, parent, plan.pageNum));
+ setSlot(slots, cut.mcid, num);
+ const added = [indirectRef(pdf, num)];
+ let kept = after;
+ if (before.length > 0 && after.length > 0) {
+ const rest = unusedObjectNumber(pdf, bodies);
+ const reason = moveKids(pdf, after, rest, plan, bodies, parentTree);
+ if (reason) return reason;
+ const page =
+ plan.ownerPage === null ? "" : ` /Pg ${indirectRef(pdf, plan.ownerPage)}`;
+ bodies.set(
+ rest,
+ `<< /Type /StructElem /S /${pdf.dictName(ownerBody, "S")} ` +
+ `/P ${indirectRef(pdf, parent)}${page} /K [${after.join(" ")}] >>`,
+ );
+ added.push(indirectRef(pdf, rest));
+ kept = before;
+ } else {
+ if (before.length > 0) kept = before;
+ keepParts(plan, [cut.cut.after]);
+ }
+ keepParts(plan, [cut.cut.before]);
+
+ const ownerOut = setDictEntry(ownerBody, "K", `[${kept.join(" ")}]`);
+ const parentKids = [...siblings];
+ parentKids.splice(before.length > 0 ? at + 1 : at, 0, ...added);
+ const parentOut = setDictEntry(parentBody, "K", `[${parentKids.join(" ")}]`);
+ if (!ownerOut || !parentOut) return "its elements cannot be written";
+ bodies.set(owner, ownerOut);
+ bodies.set(parent, parentOut);
+ return null;
+}
+
+/** The cut is all of the owner's content: the owner becomes the cut's type, keeping only the cut. */
+function retagOwner(
+ pdf: RawPdf,
+ cut: TypedCut,
+ plan: CutPlan,
+ bodies: Map<number, string>,
+): string | null {
+ const kid = mcidKid(pdf, cut.mcid, plan.ownerPage, plan.pageNum);
+ let body = setDictEntry(plan.ownerBody, "S", `/${cut.type}`);
+ body = body && setDictEntry(body, "K", `[${kid}]`);
+ if (body && cut.type === "Note" && !pdf.valueSpan(body, "ID")) {
+ body = setDictEntry(body, "ID", noteId(plan.owner));
+ }
+ if (!body) return "the element it was cut from cannot be written";
+ bodies.set(plan.owner, body);
+ setSlot(plan.slots, cut.mcid, plan.owner);
+ return null;
+}
+
+/**
+ * Re-parent `kids` from the owner to element `to`: the ParentTree slots of
+ * marked content, the /P of child elements. Fails for any other kid, such as
+ * an annotation, whose parent is kept elsewhere.
+ */
+function moveKids(
+ pdf: RawPdf,
+ kids: readonly string[],
+ to: number,
+ plan: CutPlan,
+ bodies: Map<number, string>,
+ parentTree: ParentTreeWriter,
+): string | null {
+ const ref = indirectRef(pdf, to);
+ for (const kid of kids) {
+ const num = referencedObject(kid);
+ const body = num === null ? kid : (bodies.get(num) ?? pdf.objectBody(num));
+ if (num !== null && body && pdf.dictName(body, "S") !== null) {
+ const moved = setDictEntry(body, "P", ref);
+ if (!moved) return "a child element cannot be moved";
+ bodies.set(num, moved);
+ continue;
+ }
+ const page = kidPage(pdf, kid, body, plan.ownerPage);
+ const mcid = page === null ? null : kidMcid(pdf, kid, plan.ownerPage, page);
+ const slots = page === null ? null : parentTree.slots(page);
+ if (mcid === null || !slots) {
+ return "the element holds content that cannot be moved";
+ }
+ setSlot(slots, mcid, to);
+ }
+ return null;
+}
+
+/** The page a marked-content kid's content is on; null for any other kid. */
+function kidPage(
+ pdf: RawPdf,
+ kid: string,
+ body: string | null,
+ ownerPage: number | null,
+): number | null {
+ if (/^\d+$/.test(kid)) return ownerPage;
+ if (!body || pdf.dictName(body, "Type") !== "MCR") return null;
+ return pdf.dictRef(body, "Pg") ?? ownerPage;
+}
+
+function newElement(
+ pdf: RawPdf,
+ { type, mcid, alt }: TypedCut,
+ num: number,
+ parent: number,
+ pageNum: number,
+): string {
+ const altEntry = alt === null ? "" : ` /Alt ${encodeTextString(alt)}`;
+ const id = type === "Note" ? ` /ID ${noteId(num)}` : "";
+ return (
+ `<< /Type /StructElem /S /${type} /P ${indirectRef(pdf, parent)} ` +
+ `/Pg ${indirectRef(pdf, pageNum)} /K ${mcid}${altEntry}${id} >>`
+ );
+}
+
+function setSlot(slots: string[], mcid: number, num: number): void {
+ while (slots.length < mcid) slots.push("null");
+ slots[mcid] = `${num} 0 R`;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/repairStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/repairStructure.ts
index a0928e5bb4..b8c03cb817 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/repairStructure.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/repairStructure.ts
@@ -5,6 +5,8 @@ import {
ParentTreeWriter,
contentStreamObject,
elementKids,
+ kidMcid,
+ mcidKid,
pageSites,
streamsUsedByMoreThanOnePage,
type McidSite,
@@ -20,8 +22,6 @@ import {
type RevisionObject,
} from "@editor/tools/pdfTextEditor/pdfdoc/revision";
-const REF = /^(\d+)\s+\d+\s+R$/;
-
/** Changes to one element's /K for one page. */
interface KidChanges {
pageNum: number;
@@ -183,24 +183,10 @@ function rewriteKids(
const kids = elementKids(pdf, body);
if (!kids) return null;
const elementPage = pdf.dictRef(body, "Pg");
-
- const mcidOnPage = (kid: string): number | null => {
- if (/^\d+$/.test(kid)) {
- return elementPage === changes.pageNum ? parseInt(kid, 10) : null;
- }
- const ref = kid.match(REF);
- const dict = ref ? pdf.objectBody(parseInt(ref[1], 10)) : kid;
- if (!dict?.trimStart().startsWith("<<")) return null;
- if (pdf.dictName(dict, "Type") !== "MCR" || pdf.valueSpan(dict, "Stm")) {
- return null;
- }
- const page = pdf.dictRef(dict, "Pg") ?? elementPage;
- return page === changes.pageNum ? pdf.dictInt(dict, "MCID") : null;
- };
- const newKid = (mcid: number): string =>
- elementPage === changes.pageNum
- ? String(mcid)
- : `<< /Type /MCR /Pg ${changes.pageNum} 0 R /MCID ${mcid} >>`;
+ const mcidOnPage = (kid: string) =>
+ kidMcid(pdf, kid, elementPage, changes.pageNum);
+ const newKid = (mcid: number) =>
+ mcidKid(pdf, mcid, elementPage, changes.pageNum);
const out: string[] = [];
const placed = new Set<number>();
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/unwrapElements.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/unwrapElements.ts
new file mode 100644
index 0000000000..22fc81239b
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/unwrapElements.ts
@@ -0,0 +1,88 @@
+/**
+ * Remove elements that mark part of another element's text. Only the tree
+ * changes: the content keeps its MCIDs, which join the parent where the
+ * element stood, their ParentTree slots moving with them.
+ */
+import {
+ elementKids,
+ kidMcid,
+ mcidKid,
+ type ParentTreeWriter,
+} from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";
+import {
+ indirectRef,
+ referencedObject,
+ setDictEntry,
+ type RawPdf,
+} from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+
+/**
+ * Remove each of `elements`, by object number. Bodies are written to
+ * `bodies` and ParentTree slots to `parentTree`. Returns why an element could
+ * not be removed, by index; the caller must then discard everything.
+ */
+export function unwrapElements(
+ pdf: RawPdf,
+ elements: readonly number[],
+ bodies: Map<number, string>,
+ parentTree: ParentTreeWriter,
+): Map<number, string> {
+ const failed = new Map<number, string>();
+ elements.forEach((num, index) => {
+ const reason = unwrap(pdf, num, bodies, parentTree);
+ if (reason) failed.set(index, reason);
+ });
+ return failed;
+}
+
+function unwrap(
+ pdf: RawPdf,
+ num: number,
+ bodies: Map<number, string>,
+ parentTree: ParentTreeWriter,
+): string | null {
+ const read = (n: number) => bodies.get(n) ?? pdf.objectBody(n);
+ const body = read(num);
+ const parent = body === null ? null : pdf.dictRef(body, "P");
+ const parentBody = parent === null ? null : read(parent);
+ const siblings = parentBody ? elementKids(pdf, parentBody) : null;
+ const at = siblings?.findIndex((kid) => referencedObject(kid) === num) ?? -1;
+ const kids = body ? elementKids(pdf, body) : null;
+ if (!body || parent === null || !parentBody || !siblings || at < 0 || !kids) {
+ return "the element has no parent to give its content to";
+ }
+
+ const elementPage = pdf.dictRef(body, "Pg");
+ const parentPage = pdf.dictRef(parentBody, "Pg");
+ const moved: string[] = [];
+ for (const kid of kids) {
+ const site = markedSite(pdf, kid, elementPage);
+ const slots = site && parentTree.slots(site.pageNum);
+ if (!site || !slots) return "the element holds more than marked content";
+ slots[site.mcid] = indirectRef(pdf, parent);
+ moved.push(mcidKid(pdf, site.mcid, parentPage, site.pageNum));
+ }
+ siblings.splice(at, 1, ...moved);
+ const out = setDictEntry(parentBody, "K", `[${siblings.join(" ")}]`);
+ if (!out) return "the element's parent cannot be written";
+ bodies.set(parent, out);
+ return null;
+}
+
+/** The page and MCID a /K entry marks; null for any kid but marked content on a page. */
+function markedSite(
+ pdf: RawPdf,
+ kid: string,
+ elementPage: number | null,
+): { pageNum: number; mcid: number } | null {
+ if (/^\d+$/.test(kid)) {
+ if (elementPage === null) return null;
+ return { pageNum: elementPage, mcid: parseInt(kid, 10) };
+ }
+ const ref = referencedObject(kid);
+ const dict = ref === null ? kid : pdf.objectBody(ref);
+ const pageNum = (dict ? pdf.dictRef(dict, "Pg") : null) ?? elementPage;
+ if (pageNum === null) return null;
+ const mcid = kidMcid(pdf, kid, elementPage, pageNum);
+ return mcid === null ? null : { pageNum, mcid };
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts
index 4f5c6ea8f5..f03d292de1 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts
@@ -708,6 +708,11 @@ export function referencedObject(text: string): number | null {
return m ? parseInt(m[1], 10) : null;
}
+/** A reference to object `num`, at the generation the file has it. */
+export function indirectRef(pdf: RawPdf, num: number): string {
+ return `${num} ${pdf.generationOf(num)} R`;
+}
+
export function arrayItems(text: string): ValueSpan[] | null {
if (text[0] !== "[") return null;
const items: ValueSpan[] = [];
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
index e62b9d70c0..c778f420c2 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
@@ -1,9 +1,17 @@
import type { StructureElement } from "@editor/tools/pdfTextEditor/model/PageStructure";
-import { ownsOnlyMarkedContent } from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";
+import type { StructureRole } from "@editor/tools/pdfTextEditor/model/structureTypes";
+import {
+ elementKids,
+ ownsOnlyMarkedContent,
+} from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";
import {
RawPdf,
referencedObject,
} from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import {
+ StructureNodes,
+ type ElementNode,
+} from "@editor/tools/pdfTextEditor/pdfdoc/structureNodes";
import { decodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString";
type ElementInfo = Omit<StructureElement, "mcids">;
@@ -15,28 +23,51 @@ export interface FilePageStructure {
slotCount: number | null;
}
+/** A block element, and where its text is drawn. */
+export interface FileBlock extends StructureRole {
+ /** Its StructureBlock key. */
+ key: string;
+ /** The first page drawing its text; null when it draws none. */
+ pageIndex: number | null;
+ /** Its MCIDs on that page, its inline elements' included. */
+ mcids: number[];
+}
+
+export interface FileStructure {
+ /**
+ * Every page with /StructParents, keyed by page index, its elements each
+ * listing only the MCIDs the page's ParentTree slots give it: the lookup
+ * the save addresses edits by. PDFium lists an element's MCIDs from every
+ * page with no page attached, so an element spanning a page break would
+ * claim another element's MCID there.
+ */
+ pages: Map<number, FilePageStructure>;
+ /** Every block element, in the tree's reading order. */
+ blocks: FileBlock[];
+}
+
/**
- * Every page with /StructParents, keyed by page index, its elements each
- * listing only the MCIDs the page's ParentTree slots give it: the lookup the
- * save addresses edits by. PDFium lists an element's MCIDs from every page
- * with no page attached, so an element spanning a page break would claim
- * another element's MCID there. Null when the file is untagged, cannot be
+ * The file's structure tree. Null when the file is untagged, cannot be
* parsed, or is encrypted, whose strings would read as ciphertext.
*/
export async function readFileStructure(
bytes: Uint8Array,
-): Promise<Map<number, FilePageStructure> | null> {
+): Promise<FileStructure | null> {
const pdf = await RawPdf.parse(bytes);
if (!pdf || pdf.encrypted) return null;
const catalog = pdf.objectBody(pdf.rootNum);
const treeRoot = catalog ? pdf.dictRef(catalog, "StructTreeRoot") : null;
const rootBody = treeRoot === null ? null : pdf.objectBody(treeRoot);
if (treeRoot === null || !rootBody) return null;
- const roleMap = pdf.resolve(rootBody, "RoleMap");
+ const nodes = new StructureNodes(pdf, rootBody);
+ const nodeFor = (num: number) => nodes.node(num);
const infos = new Map<number, ElementInfo | null>();
const infoFor = (num: number): ElementInfo | null => {
- if (!infos.has(num)) infos.set(num, readElement(pdf, num, roleMap));
+ if (!infos.has(num)) {
+ const node = nodeFor(num);
+ infos.set(num, node && readElement(pdf, num, node));
+ }
return infos.get(num)!;
};
@@ -64,42 +95,74 @@ export async function readFileStructure(
slotCount: items.length,
});
});
- return byPage;
+ return {
+ pages: byPage,
+ blocks: readBlocks(pdf, rootBody, nodeFor, byPage),
+ };
+}
+
+/** Block elements in the depth-first /K order a reader follows. */
+function readBlocks(
+ pdf: RawPdf,
+ rootBody: string,
+ nodeFor: (num: number) => ElementNode | null,
+ pages: Map<number, FilePageStructure>,
+): FileBlock[] {
+ const drawn = new Map<string, { pageIndex: number; mcids: number[] }>();
+ for (const [pageIndex, page] of pages) {
+ for (const el of page.elements) {
+ const at = drawn.get(el.block.key) ?? { pageIndex, mcids: [] };
+ if (at.pageIndex === pageIndex) at.mcids.push(...el.mcids);
+ drawn.set(el.block.key, at);
+ }
+ }
+
+ const blocks: FileBlock[] = [];
+ const seen = new Set<number>();
+ const visit = (body: string): void => {
+ for (const kid of elementKids(pdf, body) ?? []) {
+ const num = referencedObject(kid);
+ if (num === null || seen.has(num)) continue;
+ seen.add(num);
+ const node = nodeFor(num);
+ const kidBody = pdf.objectBody(num);
+ if (!node || !kidBody) continue;
+ const key = String(num);
+ if (node.block.key === key) {
+ const at = drawn.get(key);
+ blocks.push({
+ key,
+ role: node.role,
+ type: node.type,
+ pageIndex: at?.pageIndex ?? null,
+ mcids: at ? [...at.mcids].sort((a, b) => a - b) : [],
+ });
+ }
+ visit(kidBody);
+ }
+ };
+ visit(rootBody);
+ return blocks;
}
function readElement(
pdf: RawPdf,
num: number,
- roleMap: string | null,
+ node: ElementNode,
): ElementInfo | null {
const body = pdf.objectBody(num);
- const type = body ? pdf.dictName(body, "S") : null;
- if (!body || type === null) return null;
+ if (!body) return null;
const text = (key: string): string | null => {
const value = pdf.resolve(body, key);
return value === null ? null : decodeTextString(value.trim());
};
return {
- type: applyRoleMap(pdf, roleMap, type),
+ role: node.role,
+ type: node.type,
+ block: node.block,
+ key: String(num),
alt: text("Alt"),
actualText: text("ActualText"),
onlyMarkedContent: ownsOnlyMarkedContent(pdf, body),
};
}
-
-/** Follow /RoleMap (ISO 32000-1 14.8.4) until a type it does not remap. */
-function applyRoleMap(
- pdf: RawPdf,
- roleMap: string | null,
- type: string,
-): string {
- let current = type;
- const seen = new Set<string>();
- while (roleMap && !seen.has(current)) {
- seen.add(current);
- const mapped = pdf.dictName(roleMap, current);
- if (mapped === null) break;
- current = mapped;
- }
- return current;
-}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/revision.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/revision.ts
index c43ff44e6f..53fb8b18e4 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/revision.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/revision.ts
@@ -35,6 +35,19 @@ export function plainObject(body: string): Uint8Array {
return fromLatin1(body);
}
+/**
+ * A number for a new object: above every object the file has and every one
+ * in `bodies`, so passes adding objects to one revision never collide.
+ */
+export function unusedObjectNumber(
+ pdf: RawPdf,
+ bodies: ReadonlyMap<number, string>,
+): number {
+ let highest = pdf.highestObjectNumber;
+ for (const num of bodies.keys()) highest = Math.max(highest, num);
+ return highest + 1;
+}
+
/**
* Serialise `objects` as a new revision appended to `pdf`.
*
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/structureNodes.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/structureNodes.ts
new file mode 100644
index 0000000000..d3a00343b6
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/structureNodes.ts
@@ -0,0 +1,108 @@
+import {
+ containingBlock,
+ type StructureBlock,
+} from "@editor/tools/pdfTextEditor/model/PageStructure";
+import {
+ structureRole,
+ type StructureRole,
+ type StructureType,
+} from "@editor/tools/pdfTextEditor/model/structureTypes";
+import type { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+
+export interface ElementNode extends StructureRole {
+ block: StructureBlock;
+ /** The parent element's object number; null at the top of the tree. */
+ parent: number | null;
+}
+
+/**
+ * Elements that hold only their own parts, so nothing else may be placed
+ * among their kids: a list holds items, a table its rows.
+ */
+const PARTS_ONLY: ReadonlySet<StructureType> = new Set<StructureType>([
+ "L",
+ "Table",
+ "THead",
+ "TBody",
+ "TFoot",
+ "TR",
+ "TOC",
+]);
+
+/**
+ * The role and block of each element in a file's structure tree, read from
+ * the raw objects as asked for. The editor reads blocks through this and the
+ * save resolves them through it, so both mean the same element by a block.
+ */
+export class StructureNodes {
+ private readonly nodes = new Map<number, ElementNode | null>();
+ private readonly roleMap: string | null;
+
+ /**
+ * `body` reads an object as the caller has it, so a pass that adds elements
+ * can resolve them; by default, as the file has it. An element is read
+ * once, when first asked about.
+ */
+ constructor(
+ private readonly pdf: RawPdf,
+ treeRootBody: string,
+ private readonly body: (num: number) => string | null = (num) =>
+ pdf.objectBody(num),
+ ) {
+ this.roleMap = pdf.resolve(treeRootBody, "RoleMap");
+ }
+
+ /** Null for an object that is not a structure element. */
+ node(num: number): ElementNode | null {
+ if (this.nodes.has(num)) return this.nodes.get(num)!;
+ // Set before recursing so a /P cycle ends as the top of the tree.
+ this.nodes.set(num, null);
+ const body = this.body(num);
+ const s = body ? this.pdf.dictName(body, "S") : null;
+ if (!body || s === null) return null;
+ const role = structureRole(this.applyRoleMap(s));
+ const parentNum = this.pdf.dictRef(body, "P");
+ const parent = parentNum === null ? null : this.node(parentNum);
+ const node = {
+ ...role,
+ block: containingBlock({ key: String(num), ...role }, parent),
+ parent: parent ? parentNum : null,
+ };
+ this.nodes.set(num, node);
+ return node;
+ }
+
+ /** The object number of the block element `num` belongs to: `num` itself for a block. */
+ blockOf(num: number): number {
+ const node = this.node(num);
+ return node ? Number(node.block.key) : num;
+ }
+
+ /**
+ * The element new content read after (or before) element `num`'s content
+ * is placed beside: its block, or the list or table holding that block,
+ * since those take no other kids.
+ */
+ placementSibling(num: number): number {
+ let sibling = this.blockOf(num);
+ for (;;) {
+ const parent = this.node(sibling)?.parent ?? null;
+ const type = parent === null ? null : this.node(parent)?.type;
+ if (parent === null || !type || !PARTS_ONLY.has(type)) return sibling;
+ sibling = parent;
+ }
+ }
+
+ /** Follow /RoleMap (ISO 32000-1 14.8.4) until a type it does not remap. */
+ private applyRoleMap(type: string): string {
+ let current = type;
+ const seen = new Set<string>();
+ while (this.roleMap && !seen.has(current)) {
+ seen.add(current);
+ const mapped = this.pdf.dictName(this.roleMap, current);
+ if (mapped === null) break;
+ current = mapped;
+ }
+ return current;
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/LineGrouper.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/LineGrouper.ts
index 9e96606484..4ea1d415be 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/LineGrouper.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/LineGrouper.ts
@@ -1,5 +1,6 @@
import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import { innermostMcid } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
/** Cluster adjacent text runs on a page into "line groups". */
export interface LineGroupInfo {
@@ -9,6 +10,14 @@ export interface LineGroupInfo {
members: TextRun[];
}
+/**
+ * The structure block a run's text belongs to. Runs with different keys are
+ * never grouped: a heading merged into its paragraph could not be tagged apart.
+ */
+export type BlockKey = (run: TextRun) => string;
+
+export const SAME_BLOCK: BlockKey = () => "";
+
const BASELINE_TOLERANCE = 0.4;
// Two runs on the same baseline join the same line only when the horizontal gap
// between them is below this absolute cap.
@@ -67,9 +76,23 @@ function isBulletLead(run: TextRun): boolean {
return BULLET_GLYPHS.test(run.text) && run.bounds.width <= run.fontSize;
}
+/**
+ * The block a line's text belongs to, or null while it holds only bullets. A
+ * bullet decides nothing: producers commonly leave it untagged, or mark it an
+ * artifact, beside an item they tag.
+ */
+function lineBlock(members: TextRun[], blockKey: BlockKey): string | null {
+ const text = members.find((member) => !isBulletLead(member));
+ return text ? blockKey(text) : null;
+}
+
// Sort one container's runs top-to-bottom / left-to-right and merge
// same-baseline, close-together runs into line groups.
-function groupPartitionIntoLines(runs: TextRun[], out: LineGroupInfo[]): void {
+function groupPartitionIntoLines(
+ runs: TextRun[],
+ blockKey: BlockKey,
+ out: LineGroupInfo[],
+): void {
const sorted = [...runs].sort((a, b) => {
const yDiff = b.matrix.f - a.matrix.f;
// Same-line band scaled to font size so a list bullet sitting a couple of
@@ -105,7 +128,11 @@ function groupPartitionIntoLines(runs: TextRun[], out: LineGroupInfo[]): void {
const minNegGap = 0.25 * Math.max(ref.fontSize, 4);
const close = gap <= effMaxGap && gap >= -minNegGap;
- if (sameLine && close) {
+ const block = lineBlock(current.members, blockKey);
+ const sameBlock =
+ isBulletLead(run) || block === null || blockKey(run) === block;
+
+ if (sameLine && close && sameBlock) {
current.members.push(run);
} else {
current = { representative: run, members: [run] };
@@ -116,7 +143,7 @@ function groupPartitionIntoLines(runs: TextRun[], out: LineGroupInfo[]): void {
export class LineGrouper {
/** Group a page's runs and store the result back onto the page. */
- static apply(page: Page): LineGroupInfo[] {
+ static apply(page: Page, blockKey: BlockKey = SAME_BLOCK): LineGroupInfo[] {
// Partition by form-xobject container BEFORE grouping.
const partitions = new Map<number, TextRun[]>();
for (const run of page.runs) {
@@ -128,7 +155,7 @@ export class LineGrouper {
const groups: LineGroupInfo[] = [];
for (const partition of partitions.values()) {
- groupPartitionIntoLines(partition, groups);
+ groupPartitionIntoLines(partition, blockKey, groups);
}
// Refine: a "line" whose glyphs heavily OVERLAP in x is not real running
@@ -163,6 +190,12 @@ export class LineGrouper {
group.representative.mergedFromCharStarts = [0];
continue;
}
+ // A bullet with no tag of its own would otherwise make a tagged item
+ // read as untagged, and its text lose its tag when re-emitted.
+ const text = group.members.find((member) => !isBulletLead(member));
+ if (text && innermostMcid(group.representative.tagMarks) === null) {
+ group.representative.tagMarks = text.tagMarks;
+ }
// Snapshot per-member texts and bounds BEFORE we mutate the
// representative.
const memberTexts = group.members.map((m) => m.text);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/ParagraphGrouper.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/ParagraphGrouper.ts
index 57292d794b..ac24bccdaf 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/ParagraphGrouper.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/ParagraphGrouper.ts
@@ -1,4 +1,8 @@
import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import {
+ SAME_BLOCK,
+ type BlockKey,
+} from "@editor/tools/pdfTextEditor/pdfium/LineGrouper";
import type {
ParagraphLineSlot,
TextRun,
@@ -23,7 +27,8 @@ export interface ParagraphInfo {
}
export class ParagraphGrouper {
- static apply(page: Page): ParagraphInfo[] {
+ /** `blockKey` must be the one LineGrouper grouped the page's lines by. */
+ static apply(page: Page, blockKey: BlockKey = SAME_BLOCK): ParagraphInfo[] {
const allLines = [...page.runs];
const paragraphs: ParagraphInfo[] = [];
@@ -35,7 +40,7 @@ export class ParagraphGrouper {
if (Math.abs(yDiff) > 0.5) return yDiff;
return a.bounds.x - b.bounds.x;
});
- groupColumnLines(sorted, paragraphs);
+ groupColumnLines(sorted, blockKey, paragraphs);
}
// Fold member bounds + text into the representative and drop the member
@@ -245,7 +250,11 @@ function segmentColumns(lines: TextRun[]): TextRun[][] {
// Sequentially group one column's already-sorted (top-to-bottom) lines into
// paragraphs, appending each paragraph to `out`.
-function groupColumnLines(sorted: TextRun[], out: ParagraphInfo[]): void {
+function groupColumnLines(
+ sorted: TextRun[],
+ blockKey: BlockKey,
+ out: ParagraphInfo[],
+): void {
let current: ParagraphInfo | null = null;
let currentDeltas: number[] = [];
let currentLeftEdge = 0;
@@ -282,7 +291,9 @@ function groupColumnLines(sorted: TextRun[], out: ParagraphInfo[]): void {
deltaFromLeft >= -MARGIN_OUTDENT_LEFT &&
deltaFromLeft <= MARGIN_INDENT_RIGHT;
- if (sameFont && sameColor && lineHeightOk && leftOk) {
+ const sameBlock = blockKey(prev) === blockKey(line);
+
+ if (sameFont && sameColor && lineHeightOk && leftOk && sameBlock) {
current.members.push(line);
currentDeltas.push(baselineDelta);
if (line.bounds.x < currentLeftEdge) currentLeftEdge = line.bounds.x;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumObjectColour.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumObjectColour.ts
new file mode 100644
index 0000000000..f70cbf631f
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumObjectColour.ts
@@ -0,0 +1,52 @@
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import type { RGBA } from "@editor/tools/pdfTextEditor/types";
+import {
+ SCRATCH,
+ scratchPtr,
+} from "@editor/tools/pdfTextEditor/util/wasmScratch";
+
+type ColourReader = (
+ obj: number,
+ r: number,
+ g: number,
+ b: number,
+ a: number,
+) => boolean;
+
+/** A page object's fill colour, 0-255 per channel. Null when unreadable; never throws. */
+export function readObjFill(
+ m: WrappedPdfiumModule,
+ objPtr: number,
+): RGBA | null {
+ return readObjColour(m, objPtr, m.FPDFPageObj_GetFillColor);
+}
+
+/** A page object's stroke colour, 0-255 per channel. Null when unreadable; never throws. */
+export function readObjStroke(
+ m: WrappedPdfiumModule,
+ objPtr: number,
+): RGBA | null {
+ return readObjColour(m, objPtr, m.FPDFPageObj_GetStrokeColor);
+}
+
+function readObjColour(
+ m: WrappedPdfiumModule,
+ objPtr: number,
+ read: ColourReader,
+): RGBA | null {
+ const r = scratchPtr(m, SCRATCH.colourR, 4);
+ const g = scratchPtr(m, SCRATCH.colourG, 4);
+ const b = scratchPtr(m, SCRATCH.colourB, 4);
+ const a = scratchPtr(m, SCRATCH.colourA, 4);
+ try {
+ if (!read(objPtr, r, g, b, a)) return null;
+ return {
+ r: m.pdfium.getValue(r, "i32"),
+ g: m.pdfium.getValue(g, "i32"),
+ b: m.pdfium.getValue(b, "i32"),
+ a: m.pdfium.getValue(a, "i32"),
+ };
+ } catch {
+ return null;
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumStructureReader.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumStructureReader.ts
index e0949d66cc..d07d8218c2 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumStructureReader.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumStructureReader.ts
@@ -1,6 +1,10 @@
import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
import { readUtf16 } from "@editor/services/pdfiumService";
-import type { StructureElement } from "@editor/tools/pdfTextEditor/model/PageStructure";
+import {
+ containingBlock,
+ type StructureElement,
+} from "@editor/tools/pdfTextEditor/model/PageStructure";
+import { structureRole } from "@editor/tools/pdfTextEditor/model/structureTypes";
type StringGetter = (el: number, buf: number, len: number) => number;
@@ -21,7 +25,11 @@ export function readPageStructure(
try {
tree = m.FPDF_StructTree_GetForPage(pagePtr);
if (!tree) return out;
- const visit = (el: number, depth: number): void => {
+ const visit = (
+ el: number,
+ depth: number,
+ parent: StructureElement | null,
+ ): void => {
if (!el || depth > MAX_DEPTH) return;
const mcids: number[] = [];
const count = m.FPDF_StructElement_GetMarkedContentIdCount(el);
@@ -29,22 +37,28 @@ export function readPageStructure(
const id = m.FPDF_StructElement_GetMarkedContentIdAtIndex(el, i);
if (id >= 0) mcids.push(id);
}
- out.push({
- type: readString(m, el, m.FPDF_StructElement_GetType) ?? "",
+ const role = structureRole(
+ readString(m, el, m.FPDF_StructElement_GetType) ?? "",
+ );
+ const element: StructureElement = {
+ ...role,
alt: readString(m, el, m.FPDF_StructElement_GetAltText),
actualText: readString(m, el, m.FPDF_StructElement_GetActualText),
mcids,
// PDFium does not expose the kids' kinds; the fallback is read-only anyway.
onlyMarkedContent: false,
- });
+ key: String(out.length),
+ block: containingBlock({ key: String(out.length), ...role }, parent),
+ };
+ out.push(element);
const kids = m.FPDF_StructElement_CountChildren(el);
for (let i = 0; i < kids; i++) {
- visit(m.FPDF_StructElement_GetChildAtIndex(el, i), depth + 1);
+ visit(m.FPDF_StructElement_GetChildAtIndex(el, i), depth + 1, element);
}
};
const roots = m.FPDF_StructTree_CountChildren(tree);
for (let i = 0; i < roots; i++) {
- visit(m.FPDF_StructTree_GetChildAtIndex(tree, i), 0);
+ visit(m.FPDF_StructTree_GetChildAtIndex(tree, i), 0, null);
}
} catch {
return [];
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts
index 49887cdcc8..436dad4d9e 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts
@@ -103,23 +103,34 @@ export function removeTagMark(
* content included; -1 when none is.
*/
export function highestMcid(m: WrappedPdfiumModule, pagePtr: number): number {
+ let highest = -1;
+ for (const mcid of carriedMcids(m, pagePtr))
+ highest = Math.max(highest, mcid);
+ return highest;
+}
+
+/** Every MCID any object on the page is marked with, form XObject content included. */
+export function carriedMcids(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+): Set<number> {
const count = m.FPDFPage_CountObjects(pagePtr);
const objects = Array.from({ length: count }, (_, i) =>
m.FPDFPage_GetObject(pagePtr, i),
);
- let highest = -1;
+ const carried = new Set<number>();
while (objects.length > 0) {
const objPtr = objects.pop()!;
if (!objPtr) continue;
for (const tag of readTagMarks(m, objPtr)) {
- highest = Math.max(highest, tag.mcid ?? -1);
+ if (tag.mcid !== null) carried.add(tag.mcid);
}
if (m.FPDFPageObj_GetType(objPtr) !== FPDF_PAGEOBJ_FORM) continue;
for (let i = 0; i < m.FPDFFormObj_CountObjects(objPtr); i++) {
objects.push(m.FPDFFormObj_GetObject(objPtr, i));
}
}
- return highest;
+ return carried;
}
/** Carry `from`'s tags onto its replacement `to`. */
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
index ce521cf9a2..372d16061b 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
@@ -4,7 +4,11 @@ import { ImageObject } from "@editor/tools/pdfTextEditor/model/ImageObject";
import { ShapeObject } from "@editor/tools/pdfTextEditor/model/ShapeObject";
import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
-import { LineGrouper } from "@editor/tools/pdfTextEditor/pdfium/LineGrouper";
+import type { PageStructure } from "@editor/tools/pdfTextEditor/model/PageStructure";
+import {
+ LineGrouper,
+ type BlockKey,
+} from "@editor/tools/pdfTextEditor/pdfium/LineGrouper";
import { ParagraphGrouper } from "@editor/tools/pdfTextEditor/pdfium/ParagraphGrouper";
import { PdfiumAnnotationReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumAnnotationReader";
import { primeFontGlyphMap } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";
@@ -21,6 +25,10 @@ import {
SCRATCH,
scratchPtr,
} from "@editor/tools/pdfTextEditor/util/wasmScratch";
+import {
+ readObjFill,
+ readObjStroke,
+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumObjectColour";
import {
ARTIFACT_TAG,
innermostMcid,
@@ -33,6 +41,8 @@ const FPDF_PAGEOBJ_PATH = 2;
const FPDF_PAGEOBJ_IMAGE = 3;
const FPDF_PAGEOBJ_FORM = 5;
+const OPAQUE_BLACK: RGBA = { r: 0, g: 0, b: 0, a: 255 };
+
// A ruling line is hairline-thin on one axis and long on the other. Anything
// squarer is a box, a shading or a glyph-like drawing.
const RULE_MAX_THICKNESS_PT = 3;
@@ -92,8 +102,9 @@ export class PdfiumTextReader {
PdfiumAnnotationReader.populate(m, page);
// LineGrouper always runs (merges per-glyph/per-word source objects into
// one line).
- LineGrouper.apply(page);
- if (mode === "auto") ParagraphGrouper.apply(page);
+ const blockKey = structureBlockKey(doc, page.index);
+ LineGrouper.apply(page, blockKey);
+ if (mode === "auto") ParagraphGrouper.apply(page, blockKey);
// Grouping is done.
// One walk feeds both: each was reading the same characters with its
// own WASM round-trips, doubling the cost of every page read.
@@ -486,6 +497,25 @@ function walkObjects(
}
}
+/**
+ * Keys a run by the structure block of its own MCID, keeping artifacts and
+ * untagged text apart from tagged text and from each other. The structure is
+ * read only once a run carries an MCID, so an untagged file pays nothing.
+ */
+function structureBlockKey(doc: EditorDocument, pageIndex: number): BlockKey {
+ let structure: PageStructure | null = null;
+ return (run) => {
+ const mcid = innermostMcid(run.tagMarks);
+ if (mcid !== null) {
+ structure ??= doc.structure(pageIndex);
+ const block = structure.block(mcid);
+ if (block) return `block:${block.key}`;
+ }
+ const artifact = run.tagMarks.some((tag) => tag.name === ARTIFACT_TAG);
+ return artifact ? "artifact" : "untagged";
+ };
+}
+
/** Identity affine - the page-level transform. */
const IDENTITY: Affine = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
@@ -644,61 +674,20 @@ function readPaint(m: WrappedPdfiumModule, objPtr: number): RulePaint | null {
m.pdfium.wasmExports.free(strokePtr);
}
if (fillMode === 0 && !stroked) return null;
- const mod = m as unknown as RulePaintModule;
- const read = stroked
- ? mod.FPDFPageObj_GetStrokeColor
- : mod.FPDFPageObj_GetFillColor;
- const color = read ? readRGBA(m, objPtr, read) : null;
+ const color = stroked ? readObjStroke(m, objPtr) : readObjFill(m, objPtr);
return {
stroked,
thickness: stroked ? readStrokeWidth(m, objPtr) : 0,
- color: color ?? { r: 0, g: 0, b: 0, a: 255 },
+ color: color ?? { ...OPAQUE_BLACK },
};
}
-interface RulePaintModule {
- FPDFPageObj_GetStrokeColor?: ColorReader;
- FPDFPageObj_GetFillColor?: ColorReader;
+interface StrokeWidthModule {
FPDFPageObj_GetStrokeWidth?: (obj: number, w: number) => boolean | number;
}
-type ColorReader = (
- obj: number,
- r: number,
- g: number,
- b: number,
- a: number,
-) => boolean | number;
-
-function readRGBA(
- m: WrappedPdfiumModule,
- objPtr: number,
- read: ColorReader,
-): RGBA | null {
- const r = m.pdfium.wasmExports.malloc(4);
- const g = m.pdfium.wasmExports.malloc(4);
- const b = m.pdfium.wasmExports.malloc(4);
- const a = m.pdfium.wasmExports.malloc(4);
- try {
- if (!read(objPtr, r, g, b, a)) return null;
- return {
- r: m.pdfium.getValue(r, "i32") & 0xff,
- g: m.pdfium.getValue(g, "i32") & 0xff,
- b: m.pdfium.getValue(b, "i32") & 0xff,
- a: m.pdfium.getValue(a, "i32") & 0xff,
- };
- } catch {
- return null;
- } finally {
- m.pdfium.wasmExports.free(r);
- m.pdfium.wasmExports.free(g);
- m.pdfium.wasmExports.free(b);
- m.pdfium.wasmExports.free(a);
- }
-}
-
function readStrokeWidth(m: WrappedPdfiumModule, objPtr: number): number {
- const get = (m as unknown as RulePaintModule).FPDFPageObj_GetStrokeWidth;
+ const get = (m as unknown as StrokeWidthModule).FPDFPageObj_GetStrokeWidth;
if (!get) return 0;
const w = m.pdfium.wasmExports.malloc(4);
try {
@@ -816,35 +805,6 @@ function readMatrix(m: WrappedPdfiumModule, objPtr: number): Affine {
};
}
-function readFill(m: WrappedPdfiumModule, objPtr: number): RGBA {
- const buf = scratchPtr(m, SCRATCH.readerFill, 16);
- const ok = m.FPDFPageObj_GetFillColor(
- objPtr,
- buf,
- buf + 4,
- buf + 8,
- buf + 12,
- );
- if (!ok) return { r: 0, g: 0, b: 0, a: 255 };
- return {
- r: m.pdfium.getValue(buf, "i32") & 0xff,
- g: m.pdfium.getValue(buf + 4, "i32") & 0xff,
- b: m.pdfium.getValue(buf + 8, "i32") & 0xff,
- a: m.pdfium.getValue(buf + 12, "i32") & 0xff,
- };
-}
-
-interface StrokeReaderModule {
- FPDFPageObj_GetStrokeColor?: (
- obj: number,
- r: number,
- g: number,
- b: number,
- a: number,
- ) => boolean;
- FPDFPageObj_GetStrokeWidth?: (obj: number, out: number) => boolean;
-}
-
/** Render modes that actually put stroke ink on the page. */
const STROKING_MODES = new Set([1, 2, 5, 6]);
@@ -856,34 +816,9 @@ function readStroke(
renderMode: number,
): { stroke: RGBA | null; strokeWidth: number } {
if (!STROKING_MODES.has(renderMode)) return { stroke: null, strokeWidth: 0 };
- const mod = m as unknown as StrokeReaderModule;
- const getColor = mod.FPDFPageObj_GetStrokeColor;
- const getWidth = mod.FPDFPageObj_GetStrokeWidth;
- if (!getColor) return { stroke: null, strokeWidth: 0 };
- try {
- const buf = scratchPtr(m, SCRATCH.readerStroke, 20);
- if (!getColor(objPtr, buf, buf + 4, buf + 8, buf + 12)) {
- return { stroke: null, strokeWidth: 0 };
- }
- const alpha = m.pdfium.getValue(buf + 12, "i32") & 0xff;
- let strokeWidth = 0;
- if (getWidth && getWidth(objPtr, buf + 16)) {
- const raw = m.pdfium.getValue(buf + 16, "float");
- if (Number.isFinite(raw) && raw > 0) strokeWidth = raw;
- }
- return {
- stroke: {
- r: m.pdfium.getValue(buf, "i32") & 0xff,
- g: m.pdfium.getValue(buf + 4, "i32") & 0xff,
- b: m.pdfium.getValue(buf + 8, "i32") & 0xff,
- a: alpha,
- },
- strokeWidth,
- };
- } catch {
- // A throwing stroke accessor must not abort the rest of the page.
- return { stroke: null, strokeWidth: 0 };
- }
+ const stroke = readObjStroke(m, objPtr);
+ if (!stroke) return { stroke: null, strokeWidth: 0 };
+ return { stroke, strokeWidth: readStrokeWidth(m, objPtr) };
}
function readTextObjString(
@@ -955,7 +890,7 @@ function readTextRun(
const localBounds = readBounds(m, objPtr);
if (!localBounds) return null;
const localMatrix = readMatrix(m, objPtr);
- const fill = readFill(m, objPtr);
+ const fill = readObjFill(m, objPtr) ?? { ...OPAQUE_BLACK };
// Lift form-local coordinates into page space. For page-level text
// `transform` is identity and these are no-ops.
@@ -1062,19 +997,11 @@ function isPainted(m: WrappedPdfiumModule, objPtr: number): boolean {
const fills = m.pdfium.getValue(buf, "i32") !== 0;
const strokes = m.pdfium.getValue(buf + 4, "i32") !== 0;
return (
- (fills && readFill(m, objPtr).a > 0) ||
- (strokes && readStrokeAlpha(m, objPtr) > 0)
+ (fills && (readObjFill(m, objPtr) ?? OPAQUE_BLACK).a > 0) ||
+ (strokes && (readObjStroke(m, objPtr)?.a ?? 0) > 0)
);
}
-function readStrokeAlpha(m: WrappedPdfiumModule, objPtr: number): number {
- const buf = scratchPtr(m, SCRATCH.shapeStrokeAlpha, 16);
- if (!m.FPDFPageObj_GetStrokeColor(objPtr, buf, buf + 4, buf + 8, buf + 12)) {
- return 0;
- }
- return m.pdfium.getValue(buf + 12, "i32") & 0xff;
-}
-
function readImage(
m: WrappedPdfiumModule,
page: Page,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/store/Selection.ts b/frontend/src/editor/core/tools/pdfTextEditor/store/Selection.ts
index df6e58c212..4dbc5185ed 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/store/Selection.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/store/Selection.ts
@@ -1,4 +1,7 @@
-import type { SelectionState } from "@editor/tools/pdfTextEditor/types";
+import type {
+ SelectionState,
+ TextRange,
+} from "@editor/tools/pdfTextEditor/types";
// Singleton "find highlight" state, kept off the SelectionState (which is used
// for edit commands) so search highlights survive normal selection changes.
@@ -35,7 +38,13 @@ export class Selection {
readonly highlight: FindHighlight;
constructor() {
- this.state = { runIds: [], imageIds: [], shapeIds: [], caret: null };
+ this.state = {
+ runIds: [],
+ imageIds: [],
+ shapeIds: [],
+ caret: null,
+ textRange: null,
+ };
this.listeners = new Set();
this.highlight = new FindHighlight();
}
@@ -50,11 +59,23 @@ export class Selection {
}
clear(): void {
- this.set({ runIds: [], imageIds: [], shapeIds: [], caret: null });
+ this.set({
+ runIds: [],
+ imageIds: [],
+ shapeIds: [],
+ caret: null,
+ textRange: null,
+ });
}
selectOne(runId: string, caret: number | null = null): void {
- this.set({ runIds: [runId], imageIds: [], shapeIds: [], caret });
+ this.set({
+ runIds: [runId],
+ imageIds: [],
+ shapeIds: [],
+ caret,
+ textRange: null,
+ });
}
toggle(runId: string): void {
@@ -63,29 +84,43 @@ export class Selection {
...this.state,
runIds: this.state.runIds.filter((id) => id !== runId),
caret: null,
+ textRange: null,
});
} else {
this.set({
...this.state,
runIds: [...this.state.runIds, runId],
caret: null,
+ textRange: null,
});
}
}
selectImage(imageId: string): void {
- this.set({ runIds: [], imageIds: [imageId], shapeIds: [], caret: null });
+ this.set({
+ runIds: [],
+ imageIds: [imageId],
+ shapeIds: [],
+ caret: null,
+ textRange: null,
+ });
}
selectShape(shapeId: string): void {
- this.set({ runIds: [], imageIds: [], shapeIds: [shapeId], caret: null });
+ this.set({
+ runIds: [],
+ imageIds: [],
+ shapeIds: [shapeId],
+ caret: null,
+ textRange: null,
+ });
}
toggleShape(shapeId: string): void {
const shapeIds = this.state.shapeIds.includes(shapeId)
? this.state.shapeIds.filter((id) => id !== shapeId)
: [...this.state.shapeIds, shapeId];
- this.set({ ...this.state, shapeIds, caret: null });
+ this.set({ ...this.state, shapeIds, caret: null, textRange: null });
}
/**
@@ -105,6 +140,7 @@ export class Selection {
imageIds: [...imageIds],
shapeIds: [...shapeIds],
caret: null,
+ textRange: null,
});
return;
}
@@ -113,9 +149,25 @@ export class Selection {
imageIds: unionInOrder(this.state.imageIds, imageIds),
shapeIds: unionInOrder(this.state.shapeIds, shapeIds),
caret: null,
+ textRange: null,
});
}
+ /**
+ * Record the characters selected inside run `runId`. Ignored unless that
+ * run is the whole selection: a box keeps reporting while another
+ * selection is made.
+ */
+ setTextRange(runId: string, range: TextRange | null): void {
+ const { runIds, imageIds, shapeIds, textRange } = this.state;
+ if (runIds.length !== 1 || runIds[0] !== runId) return;
+ if (imageIds.length > 0 || shapeIds.length > 0) return;
+ if (textRange?.start === range?.start && textRange?.end === range?.end) {
+ return;
+ }
+ this.set({ ...this.state, textRange: range });
+ }
+
subscribe(listener: (s: SelectionState) => void): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/types.ts b/frontend/src/editor/core/tools/pdfTextEditor/types.ts
index 36161febc7..319619d3b1 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/types.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/types.ts
@@ -83,6 +83,12 @@ export interface TextRunSnapshot {
locked?: boolean;
/** Box width the user set by resize, in PDF points; absent = follow the ink. */
wrapWidthPt?: number;
+ /** The marked-content ID that ties the run's text into the structure tree. */
+ mcid?: number;
+ /** Marked as an artifact: content that assistive technology skips. */
+ artifact?: boolean;
+ /** Drawn by a form XObject, whose marks the editor does not read. */
+ inForm?: boolean;
}
export interface ImageObjectSnapshot {
@@ -217,6 +223,18 @@ export interface SelectionState {
shapeIds: string[];
/** Caret position when exactly one run is selected and the user is typing */
caret: number | null;
+ /**
+ * The characters selected inside the one selected run, as code units of
+ * its text; null when nothing within it is selected. Kept after the run's
+ * box loses focus, so a control outside it can act on the selection.
+ */
+ textRange: TextRange | null;
+}
+
+/** Code units `start` (inclusive) to `end` (exclusive) of a run's text; never empty. */
+export interface TextRange {
+ start: number;
+ end: number;
}
export interface ToolbarState {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/figurePlacement.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/elementPlacement.test.ts
similarity index 60%
rename from frontend/src/editor/core/tools/pdfTextEditor/util/figurePlacement.test.ts
rename to frontend/src/editor/core/tools/pdfTextEditor/util/elementPlacement.test.ts
index 73b9408676..a15430a40d 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/figurePlacement.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/elementPlacement.test.ts
@@ -3,9 +3,9 @@ import type { ImageObject } from "@editor/tools/pdfTextEditor/model/ImageObject"
import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import type { PageRect } from "@editor/tools/pdfTextEditor/types";
import {
- imagesInReadingOrder,
precedingTaggedMcid,
-} from "@editor/tools/pdfTextEditor/util/figurePlacement";
+ taggedContentInReadingOrder,
+} from "@editor/tools/pdfTextEditor/util/elementPlacement";
const UPRIGHT = { apply: (x: number, y: number) => ({ x, y }) };
@@ -21,6 +21,8 @@ const run = (mcid: number | null, bounds: PageRect) => ({
});
const image = (mcid: number | null, bounds: PageRect) =>
({ bounds, mcid, containerPtr: 0 }) as ImageObject;
+/** An image as the content it draws, the way an added element's content is placed. */
+const placed = (img: ImageObject) => ({ mcid: img.mcid!, bounds: img.bounds });
const page = (
runs: ReturnType<typeof run>[],
images: ImageObject[],
@@ -29,49 +31,50 @@ const page = (
describe("precedingTaggedMcid", () => {
it("follows the tagged content closest above the image", () => {
- const target = image(null, box(10, 60, 20, 20));
+ const target = image(9, box(10, 60, 20, 20));
const p = page([run(0, box(10, 180)), run(1, box(10, 120))], [target]);
- expect(precedingTaggedMcid(p, target)).toBe(1);
+ expect(precedingTaggedMcid(p, placed(target))).toBe(1);
});
it("prefers content in the image's column to closer content beside it", () => {
- const target = image(null, box(110, 80, 80, 20));
+ const target = image(9, box(110, 80, 80, 20));
const p = page(
[run(0, box(0, 100, 90)), run(1, box(110, 150, 90))],
[target],
);
- expect(precedingTaggedMcid(p, target)).toBe(1);
+ expect(precedingTaggedMcid(p, placed(target))).toBe(1);
});
it("reads content level with the image and to its left first", () => {
- const target = image(null, box(100, 90, 20, 20));
+ const target = image(9, box(100, 90, 20, 20));
const p = page([run(0, box(0, 100, 50))], [target]);
- expect(precedingTaggedMcid(p, target)).toBe(0);
+ expect(precedingTaggedMcid(p, placed(target))).toBe(0);
});
it("skips untagged content and the image itself", () => {
const target = image(4, box(10, 60, 20, 20));
const p = page([run(null, box(10, 120))], [target]);
- expect(precedingTaggedMcid(p, target)).toBeNull();
+ expect(precedingTaggedMcid(p, placed(target))).toBeNull();
});
it("reads a page as it is displayed", () => {
- const target = image(null, box(10, 60, 20, 20));
+ const target = image(9, box(10, 60, 20, 20));
const upsideDown = { apply: (x: number, y: number) => ({ x, y: -y }) };
const p = page([run(1, box(10, 120))], [target], upsideDown);
- expect(precedingTaggedMcid(p, target)).toBeNull();
+ expect(precedingTaggedMcid(p, placed(target))).toBeNull();
});
});
-describe("imagesInReadingOrder", () => {
- it("orders the page's images top to bottom, then left to right", () => {
- const low = image(null, box(10, 20));
- const right = image(null, box(100, 120));
- const left = image(null, box(10, 120));
- expect(imagesInReadingOrder(page([], [low, right, left]))).toEqual([
- left,
- right,
- low,
+describe("taggedContentInReadingOrder", () => {
+ it("orders tagged text and images top to bottom, then left to right", () => {
+ const low = image(2, box(10, 20));
+ const right = image(1, box(100, 120));
+ const p = page(
+ [run(0, box(10, 120)), run(null, box(10, 160))],
+ [low, right],
+ );
+ expect(taggedContentInReadingOrder(p).map((c) => c.mcid)).toEqual([
+ 0, 1, 2,
]);
});
});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/figurePlacement.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/elementPlacement.ts
similarity index 57%
rename from frontend/src/editor/core/tools/pdfTextEditor/util/figurePlacement.ts
rename to frontend/src/editor/core/tools/pdfTextEditor/util/elementPlacement.ts
index 81ec8352d8..3b1f64b109 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/figurePlacement.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/elementPlacement.ts
@@ -1,10 +1,9 @@
/**
- * Where a figure added for an untagged image goes in the reading order: after
- * the tagged content closest before the image as the page displays it, read
+ * Where an element added for untagged content goes in the reading order:
+ * after the tagged content closest before it as the page displays it, read
* top to bottom and then left to right. The content order cannot say this: an
* inserted image is drawn last whatever its position on the page.
*/
-import type { ImageObject } from "@editor/tools/pdfTextEditor/model/ImageObject";
import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import { innermostMcid } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
import type { PageRect } from "@editor/tools/pdfTextEditor/types";
@@ -18,55 +17,55 @@ interface Box {
top: number;
}
-interface TaggedContent {
+/** Page-level content with an MCID, and where it is drawn. */
+export interface TaggedContent {
mcid: number;
- box: Box;
+ bounds: PageRect;
}
/**
- * The MCID of the tagged content read last before `image`, or null when none
- * precedes it. Content in the image's column wins over content beside it, so
- * a figure under a paragraph follows that paragraph and not the one across
+ * The MCID of the tagged content read last before `target`, or null when none
+ * precedes it. Content in the target's column wins over content beside it, so
+ * an element under a paragraph follows that paragraph and not the one across
* the gutter.
*/
export function precedingTaggedMcid(
page: Page,
- image: ImageObject,
+ target: TaggedContent,
): number | null {
- const target = displayBox(page, image.bounds);
- const before = taggedContent(page, image).filter((c) =>
- readsBefore(c.box, target),
- );
+ const box = displayBox(page, target.bounds);
+ const before = taggedContent(page)
+ .filter((c) => c.mcid !== target.mcid)
+ .map((c) => ({ mcid: c.mcid, box: displayBox(page, c.bounds) }))
+ .filter((c) => readsBefore(c.box, box));
const inColumn = before.filter(
- (c) => c.box.left < target.right && c.box.right > target.left,
+ (c) => c.box.left < box.right && c.box.right > box.left,
);
const pool = inColumn.length > 0 ? inColumn : before;
- let last: TaggedContent | null = null;
+ let last: (typeof pool)[number] | null = null;
for (const content of pool) {
if (!last || readsBefore(last.box, content.box)) last = content;
}
return last?.mcid ?? null;
}
-export function imagesInReadingOrder(page: Page): ImageObject[] {
- return page.images
- .map((image) => ({ image, box: displayBox(page, image.bounds) }))
+/** The page's tagged content, text and images alike, top to bottom then left to right. */
+export function taggedContentInReadingOrder(page: Page): TaggedContent[] {
+ return taggedContent(page)
+ .map((content) => ({ content, box: displayBox(page, content.bounds) }))
.sort((a, b) => readingOrder(a.box, b.box))
- .map(({ image }) => image);
+ .map(({ content }) => content);
}
-function taggedContent(page: Page, except: ImageObject): TaggedContent[] {
+function taggedContent(page: Page): TaggedContent[] {
const content: TaggedContent[] = [];
for (const run of page.runs) {
const mcid = innermostMcid(run.tagMarks);
- if (mcid !== null)
- content.push({ mcid, box: displayBox(page, run.bounds) });
+ if (mcid !== null) content.push({ mcid, bounds: run.bounds });
}
for (const image of page.images) {
- if (image === except || image.mcid === null || image.containerPtr !== 0) {
- continue;
- }
- content.push({ mcid: image.mcid, box: displayBox(page, image.bounds) });
+ if (image.mcid === null || image.containerPtr !== 0) continue;
+ content.push({ mcid: image.mcid, bounds: image.bounds });
}
return content;
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/headingOutline.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/headingOutline.ts
new file mode 100644
index 0000000000..a0302841ba
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/headingOutline.ts
@@ -0,0 +1,115 @@
+import {
+ headingLevel,
+ type HeadingType,
+} from "@editor/tools/pdfTextEditor/model/structureTypes";
+import type {
+ PageSnapshot,
+ TextRange,
+ TextRunSnapshot,
+} from "@editor/tools/pdfTextEditor/types";
+
+/** A heading as the document has it now: the file's, the session's retags applied. */
+export interface DocumentHeading {
+ type: HeadingType;
+ /** The first page drawing its text; null when it draws none. */
+ pageIndex: number | null;
+ /** Its MCIDs on that page. */
+ mcids: number[];
+ /** Set when its text was cut from a run's: MCIDs that run likely carries. */
+ partOf?: number[];
+}
+
+/** Where a heading whose text is part of a run's is shown. */
+export interface HeadingText {
+ runId: string;
+ range: TextRange;
+}
+
+/**
+ * What a checker reports against one heading (ISO 14289-1 7.4.2, Matterhorn
+ * checkpoints 14-002 and 14-003). Moving back up any number of levels is
+ * allowed; only going deeper may not skip one.
+ */
+export type HeadingIssue =
+ | { kind: "first-not-h1" }
+ | { kind: "skipped-level"; previous: number };
+
+export interface OutlineEntry {
+ type: HeadingType;
+ /** Null for H, which has no number. */
+ level: number | null;
+ pageIndex: number | null;
+ /** The run showing the heading; null until its page has been read, or when it draws no text. */
+ run: TextRunSnapshot | null;
+ /** The part of the run's text that is the heading's; null for all of it. */
+ range: TextRange | null;
+ issue: HeadingIssue | null;
+}
+
+export interface HeadingOutline {
+ entries: OutlineEntry[];
+ /** H alongside H1-H6, which ISO 14289-1 7.4.4 forbids (Matterhorn 14-007). */
+ mixesNumbering: boolean;
+}
+
+/**
+ * The headings in reading order, each with the run showing it and the issue
+ * a checker would report. `pages` supplies the runs, and `locate` finds a
+ * heading set `partOf` within them.
+ */
+export function headingOutline(
+ headings: readonly DocumentHeading[],
+ pages: readonly PageSnapshot[],
+ locate: (heading: DocumentHeading) => HeadingText | null = () => null,
+): HeadingOutline {
+ let previous: number | null = null;
+ const entries = headings.map((heading): OutlineEntry => {
+ const level = headingLevel(heading.type);
+ const entry = {
+ type: heading.type,
+ level,
+ pageIndex: heading.pageIndex,
+ ...runShowing(heading, pages, locate),
+ issue: null,
+ };
+ if (level === null) return entry;
+ const issue = issueAt(level, previous);
+ previous = level;
+ return { ...entry, issue };
+ });
+ const unnumbered = entries.some((entry) => entry.level === null);
+ const numbered = entries.some((entry) => entry.level !== null);
+ return { entries, mixesNumbering: unnumbered && numbered };
+}
+
+function issueAt(level: number, previous: number | null): HeadingIssue | null {
+ if (previous === null) return level === 1 ? null : { kind: "first-not-h1" };
+ return level > previous + 1 ? { kind: "skipped-level", previous } : null;
+}
+
+function runShowing(
+ heading: DocumentHeading,
+ pages: readonly PageSnapshot[],
+ locate: (heading: DocumentHeading) => HeadingText | null,
+): { run: TextRunSnapshot | null; range: TextRange | null } {
+ const runs =
+ heading.pageIndex === null
+ ? undefined
+ : pages.find((p) => p.pageIndex === heading.pageIndex)?.runs;
+ if (!runs) return { run: null, range: null };
+ const text = heading.partOf ? locate(heading) : null;
+ if (text) {
+ const run = runs.find((r) => r.id === text.runId) ?? null;
+ return { run, range: run && text.range };
+ }
+ const run = runs.find(
+ (r) => r.mcid !== undefined && heading.mcids.includes(r.mcid),
+ );
+ return { run: run ?? null, range: null };
+}
+
+/** Headings carrying an issue, the document-wide mixed numbering counted once. */
+export function issueCount(outline: HeadingOutline): number {
+ const perHeading = outline.entries.filter((entry) => entry.issue).length;
+ return perHeading + (outline.mixesNumbering ? 1 : 0);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/imageAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/imageAccessibility.ts
index c6994bdd7c..8278f8bbf9 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/imageAccessibility.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/imageAccessibility.ts
@@ -65,7 +65,7 @@ export function retaggableTag(
): RetaggableTag | null {
if (!doc.isTagged() || image.inForm) return null;
const structure = doc.structure(image.pageIndex);
- if (structure.cannotAddFigure()) return null;
+ if (structure.cannotAddElement()) return null;
if (image.mcid === undefined) {
return image.artifact ? { kind: "artifact" } : { kind: "untagged" };
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/overlayPainter.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/overlayPainter.ts
index b039cdf78a..a29363b440 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/overlayPainter.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/overlayPainter.ts
@@ -3,6 +3,7 @@ import {
type TokenFit,
} from "@editor/tools/pdfTextEditor/util/lineLayout";
import { measureAdvancePx } from "@editor/tools/pdfTextEditor/util/textMetrics";
+import type { TextRange } from "@editor/tools/pdfTextEditor/types";
export interface PaintToken {
text: string;
@@ -264,11 +265,36 @@ export function plainCaretOffset(el: HTMLElement): number | null {
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) return null;
const { focusNode, focusOffset } = selection;
- if (!focusNode || !el.contains(focusNode)) return null;
+ return focusNode ? plainOffset(el, focusNode, focusOffset) : null;
+}
+
+/**
+ * The characters of the run's model text the selection covers, counted as
+ * plainCaretOffset counts; null for a caret or a selection that leaves `el`.
+ */
+export function plainSelectionRange(el: HTMLElement): TextRange | null {
+ const selection = window.getSelection();
+ if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
+ return null;
+ }
+ const { anchorNode, anchorOffset, focusNode, focusOffset } = selection;
+ if (!anchorNode || !focusNode) return null;
+ const anchor = plainOffset(el, anchorNode, anchorOffset);
+ const focus = plainOffset(el, focusNode, focusOffset);
+ if (anchor === null || focus === null || anchor === focus) return null;
+ return { start: Math.min(anchor, focus), end: Math.max(anchor, focus) };
+}
+
+function plainOffset(
+ el: HTMLElement,
+ node: Node,
+ offset: number,
+): number | null {
+ if (!el.contains(node)) return null;
const range = document.createRange();
try {
range.setStart(el, 0);
- range.setEnd(focusNode, focusOffset);
+ range.setEnd(node, offset);
} catch {
return null;
}
@@ -278,8 +304,8 @@ export function plainCaretOffset(el: HTMLElement): number | null {
// A caret parked on the container BETWEEN two line children sits at the
// start of the next line - one past the end of the truncated text. Past the
// last line child it belongs at that line's end, not on a fresh one.
- if (focusNode === el) {
- const idx = Math.min(focusOffset, el.childNodes.length);
+ if (node === el) {
+ const idx = Math.min(offset, el.childNodes.length);
const children = Array.from(el.childNodes);
const isLineChild = (n: Node) =>
n instanceof HTMLElement && n.tagName !== "BR";
@@ -342,6 +368,50 @@ export function normalizeContainerCaret(
export function restoreCaretOffset(el: HTMLElement, offset: number): void {
const selection = window.getSelection();
if (!selection) return;
+ const at = domPosition(el, offset);
+ setCollapsed(selection, at.node, at.offset);
+}
+
+const TEXT_RANGE_HIGHLIGHT = "pdf-editor-text-range";
+
+/**
+ * Paint `range` as selected text, through the CSS Custom Highlight API, until
+ * the returned cleanup runs. One range at a time: a later call replaces it.
+ * Does nothing where the browser lacks the API.
+ */
+export function highlightTextRange(range: Range): () => void {
+ if (typeof CSS === "undefined" || !("highlights" in CSS)) return () => {};
+ const highlight = new Highlight(range);
+ CSS.highlights.set(TEXT_RANGE_HIGHLIGHT, highlight);
+ return () => {
+ if (CSS.highlights.get(TEXT_RANGE_HIGHLIGHT) === highlight) {
+ CSS.highlights.delete(TEXT_RANGE_HIGHLIGHT);
+ }
+ };
+}
+
+/**
+ * A DOM range over the characters of the run's model text `range` covers,
+ * counted as plainSelectionRange counts; null when the DOM cannot hold it.
+ */
+export function plainDomRange(el: HTMLElement, range: TextRange): Range | null {
+ const from = domPosition(el, range.start);
+ const to = domPosition(el, range.end);
+ const out = document.createRange();
+ try {
+ out.setStart(from.node, from.offset);
+ out.setEnd(to.node, to.offset);
+ } catch {
+ return null;
+ }
+ return out;
+}
+
+/** Where character `offset` of the run's model text falls in the overlay's DOM. */
+function domPosition(
+ el: HTMLElement,
+ offset: number,
+): { node: Node; offset: number } {
const target = Math.max(0, offset);
const blocks = lineBlocks(el);
@@ -368,13 +438,12 @@ export function restoreCaretOffset(el: HTMLElement, offset: number): void {
while (node) {
const length = (node.nodeValue ?? "").length;
if (seen + length >= remaining) {
- setCollapsed(selection, node, remaining - seen);
- return;
+ return { node, offset: remaining - seen };
}
seen += length;
node = walker.nextNode();
}
- setCollapsed(selection, scope, 0);
+ return { node: scope, offset: 0 };
}
function setCollapsed(selection: Selection, node: Node, offset: number): void {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.ts
new file mode 100644
index 0000000000..4b3b1e36e1
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.ts
@@ -0,0 +1,121 @@
+import { elementStretches } from "@editor/tools/pdfTextEditor/commands/TagTextRangeCommand";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type {
+ InnerOptions,
+ RetagBlocker,
+} from "@editor/tools/pdfTextEditor/model/PageStructure";
+import type { StructureRole } from "@editor/tools/pdfTextEditor/model/structureTypes";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import { innermostMcid } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+import type { TextRunSnapshot } from "@editor/tools/pdfTextEditor/types";
+import type {
+ DocumentHeading,
+ HeadingText,
+} from "@editor/tools/pdfTextEditor/util/headingOutline";
+
+/** How a run's text is tagged. */
+export type TextTag =
+ /** The block the text belongs to, so a Link in a P reads as the P. */
+ | { kind: "tagged"; block: StructureRole; cannotRetag: RetagBlocker | null }
+ | { kind: "artifact" }
+ /** `taggable` when TagTextCommand can give the text an element. */
+ | { kind: "untagged"; documentTagged: boolean; taggable: boolean }
+ /** Drawn by a form XObject, whose marks the editor does not read. */
+ | { kind: "unknown" };
+
+export function textTag(doc: EditorDocument, run: TextRunSnapshot): TextTag {
+ if (run.inForm) return { kind: "unknown" };
+ if (run.artifact) return { kind: "artifact" };
+ const untagged = {
+ kind: "untagged",
+ documentTagged: doc.isTagged(),
+ taggable: canTagText(doc, run),
+ } as const;
+ if (run.mcid === undefined) return untagged;
+ const structure = doc.structure(run.pageIndex);
+ const block = structure.block(run.mcid);
+ if (!block) return untagged;
+ return {
+ kind: "tagged",
+ block: { role: block.role, type: block.type },
+ cannotRetag: structure.cannotRetag(run.mcid),
+ };
+}
+
+/**
+ * True when the run's text can be given an element of its own: it is drawn
+ * by the page itself in a tagged document whose save can add one, and has no
+ * tag or artifact mark.
+ */
+export function canTagText(doc: EditorDocument, run: TextRunSnapshot): boolean {
+ return (
+ doc.isTagged() &&
+ !run.inForm &&
+ !run.artifact &&
+ run.mcid === undefined &&
+ doc.structure(run.pageIndex).cannotAddElement() === null
+ );
+}
+
+/** An element marking part of a run's text, rather than the run's own block. */
+export interface InnerTag extends InnerOptions {
+ /** As PageStructure.innerType takes it. */
+ key: string;
+ /** The text it marks, and where in the run's text, in code units. */
+ text: string;
+ start: number;
+ end: number;
+ role: StructureRole;
+}
+
+/** The run's inner tags in reading order, as the session has them. */
+export function innerTags(
+ doc: EditorDocument,
+ run: TextRunSnapshot,
+): InnerTag[] {
+ if (run.inForm || run.mcid === undefined) return [];
+ const structure = doc.structure(run.pageIndex);
+ const block = structure.block(run.mcid);
+ if (!block) return [];
+ return elementStretches(doc, run.pageIndex, run.id).flatMap(
+ ({ start, end, element }) => {
+ const role =
+ element.key === block.key ? null : structure.innerType(element.key);
+ if (!role) return [];
+ const options = structure.innerOptions(element.key);
+ const text = run.text.slice(start, end);
+ return [{ key: element.key, text, start, end, role, ...options }];
+ },
+ );
+}
+
+/**
+ * The run and range showing a heading cut from a run's text. Runs carrying
+ * `partOf` are tried first, since reading a run's marks walks its objects.
+ */
+export function locateHeading(
+ doc: EditorDocument,
+ heading: DocumentHeading,
+): HeadingText | null {
+ if (heading.pageIndex === null) return null;
+ const pageIndex = heading.pageIndex;
+ const runs = doc.page(pageIndex).runs;
+ const likely = (run: TextRun) =>
+ heading.partOf?.includes(innermostMcid(run.tagMarks) ?? -1) ?? false;
+ const ordered = [
+ ...runs.filter(likely),
+ ...runs.filter((run) => !likely(run)),
+ ];
+ for (const run of ordered) {
+ const stretch = elementStretches(doc, pageIndex, run.id).find((s) =>
+ s.element.mcids.includes(heading.mcids[0]),
+ );
+ if (stretch) {
+ return {
+ runId: run.id,
+ range: { start: stretch.start, end: stretch.end },
+ };
+ }
+ }
+ return null;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.test.ts
index 95262746dd..fb5f542e4b 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.test.ts
@@ -50,7 +50,7 @@ describe("scratchPtr", () => {
it("never allocates less than four bytes", () => {
const { m, malloc } = fakeModule();
- scratchPtr(m, SCRATCH.readerFill, 1);
+ scratchPtr(m, SCRATCH.colourR, 1);
expect(malloc).toHaveBeenCalledWith(4);
});
@@ -75,10 +75,10 @@ describe("scratchPtr", () => {
it("releases every slot and re-allocates on next use", () => {
const { m, malloc, free } = fakeModule();
const rect = scratchPtr(m, SCRATCH.readerCharRect, 16);
- const fill = scratchPtr(m, SCRATCH.readerFill, 16);
+ const colour = scratchPtr(m, SCRATCH.colourR, 16);
releaseScratch(m);
expect(free).toHaveBeenCalledWith(rect);
- expect(free).toHaveBeenCalledWith(fill);
+ expect(free).toHaveBeenCalledWith(colour);
expect(free).toHaveBeenCalledTimes(2);
scratchPtr(m, SCRATCH.readerCharRect, 16);
expect(malloc).toHaveBeenCalledTimes(3);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.ts
index 0008ef984c..9f5214f73d 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.ts
@@ -40,9 +40,7 @@ export const SCRATCH = {
readerCharX: key(),
readerCharY: key(),
readerBounds: key(),
- readerFill: key(),
readerMatrix: key(),
- readerStroke: key(),
writerBbox: key(),
editBbox: key(),
reflowBbox: key(),
@@ -51,15 +49,10 @@ export const SCRATCH = {
imageMatrix: key(),
annotRect: key(),
shapeDrawMode: key(),
- shapeStrokeAlpha: key(),
colourR: key(),
colourG: key(),
colourB: key(),
colourA: key(),
- outlineR: key(),
- outlineG: key(),
- outlineB: key(),
- outlineA: key(),
outlineW: key(),
faceL: key(),
faceB: key(),
@@ -90,6 +83,11 @@ export const SCRATCH = {
tagName: key(),
tagNameLen: key(),
tagMcid: key(),
+ splitMatrix: key(),
+ splitOriginX: key(),
+ splitOriginY: key(),
+ splitFontSize: key(),
+ splitStrokeWidth: key(),
} as const;
/** Structural minimum: any wrapper that exposes PDFium's wasm allocator. */