#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Support accessibility tagging of page furniture (page numbers, watermarks, etc.) in Text Editor (#8857)
James Bruntone5374c2352a3
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.tomlindex 7ef51acb5c..b0b68df3f8 100644--- a/frontend/public/locales/en-US/translation.toml+++ b/frontend/public/locales/en-US/translation.toml@@ -7469,10 +7469,15 @@ y = "Y"[pdfTextEditor.inspector.accessibility]addTag = "Add tag"+applyToOtherPages_one = "Apply to {{count}} other page"+applyToOtherPages_other = "Apply to {{count}} other pages"+artifactGroup = "Skipped by screen readers"artifactText = "Decorative"cannotChange = "This image's accessibility can't be changed."cannotRetag = "This text's tag can't be changed."+cannotSetDecorative = "This can't be marked or unmarked as decorative."cannotTagPage = "This page's content can't be tagged."+contentGroup = "Content"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"@@ -7508,6 +7513,12 @@ untaggedImage = "Can't be tagged here"untaggedImages = "Untagged images"untaggedPages = "Pages to tag"+[pdfTextEditor.inspector.accessibility.furniture]+footer = "Footer"+header = "Header"+pageNumber = "Page number"+watermark = "Watermark"+[pdfTextEditor.inspector.accessibility.outline]empty = "Heading with no text"firstNotH1 = "First heading should be Heading 1"diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/editorDirtyState.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/editorDirtyState.test.tsindex 4d431dd08e..964f2932a7 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/editorDirtyState.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/editorDirtyState.test.ts@@ -22,6 +22,7 @@ function makeDoc(): EditorDocument {loadedPages: () => [],documentLanguage: () => null,languagesInUse: () => [],+ onArtifactKinds: () => () => {},dispose: () => {},} as unknown as EditorDocument;}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fileArtifactKinds.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fileArtifactKinds.test.tsnew file mode 100644index 0000000000..12475272a9--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fileArtifactKinds.test.ts@@ -0,0 +1,99 @@+import { describe, expect, it } from "vitest";+import { pairArtifactKinds } from "@editor/tools/pdfTextEditor/model/fileArtifactKinds";+import { artifactSequences } from "@editor/tools/pdfTextEditor/pdfdoc/artifactSequences";+import { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";+import {+ buildClassicPdf,+ streamBody,+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";++const SHOW = "BT /F1 12 Tf 72 72 Td (x) Tj ET";+const FOOTER = { type: "Pagination", subtype: "Footer" };++/** One page drawing `content`, with property list /P0 naming a layout artifact. */+async function sequencesOf(content: string) {+ const pdf = await RawPdf.parse(+ buildClassicPdf(+ [+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },+ {+ num: 3,+ body:+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R " ++ "/Resources << /Font << /F1 5 0 R >> /Properties << /P0 << /Type /Layout >> >> >> >>",+ },+ { num: 4, body: streamBody("", content) },+ {+ num: 5,+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ },+ ],+ 1,+ ),+ );+ return artifactSequences(pdf!, pdf!.pageNumberAt(0)!);+}++describe("artifactSequences", () => {+ it("reads an inline property list's kind, and its entries", async () => {+ expect(+ await sequencesOf(+ `/Artifact <</Type /Pagination /Subtype /Footer /Attached [/Bottom]>> BDC ${SHOW} EMC`,+ ),+ ).toEqual([{ kind: FOOTER, entries: 3 }]);+ });++ it("reads a named property list", async () => {+ expect(await sequencesOf(`/Artifact /P0 BDC ${SHOW} EMC`)).toEqual([+ { kind: { type: "Layout", subtype: null }, entries: 1 },+ ]);+ });++ it("leaves out artifacts with no named /Type, and those that draw nothing", async () => {+ expect(+ await sequencesOf(+ [+ `/Artifact BMC ${SHOW} EMC`,+ `/Artifact <</Type (Pagination)>> BDC ${SHOW} EMC`,+ "/Artifact <</Type /Pagination>> BDC BT /F1 12 Tf () Tj ET EMC",+ "/Artifact <</Type /Pagination>> BDC 0 0 10 10 re W n EMC",+ ].join("\n"),+ ),+ ).toEqual([]);+ });++ it("counts what a nested sequence draws towards the artifact around it", async () => {+ expect(+ await sequencesOf(+ `/Artifact <</Type /Pagination /Subtype /Footer>> BDC /Span <<>> BDC ${SHOW} EMC EMC`,+ ),+ ).toEqual([{ kind: FOOTER, entries: 2 }]);+ });+});++describe("pairArtifactKinds", () => {+ const sequence = { kind: FOOTER, entries: 2 };++ it("gives each mark the kind of the sequence at its place", () => {+ expect(+ pairArtifactKinds([{ ptr: 7, entries: 2, subtyped: true }], [sequence]),+ ).toEqual(new Map([[7, FOOTER]]));+ });++ it.each([+ ["more marks than sequences", [{ ptr: 7, entries: 2, subtyped: true }], []],+ [+ "entry counts differ",+ [{ ptr: 7, entries: 3, subtyped: true }],+ [sequence],+ ],+ [+ "only one names a /Subtype",+ [{ ptr: 7, entries: 2, subtyped: false }],+ [sequence],+ ],+ ])("pairs nothing when %s", (_, refs, sequences) => {+ expect(pairArtifactKinds(refs, sequences)).toBeNull();+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/nameArtifactKinds.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/nameArtifactKinds.test.tsnew file mode 100644index 0000000000..c19b5fa21f--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/nameArtifactKinds.test.ts@@ -0,0 +1,39 @@+// @vitest-environment node+// jsdom's Blob cannot stream, so a rewritten stream would not inflate.+import { describe, expect, it } from "vitest";+import { toLatin1 } from "@editor/tools/pdfTextEditor/pdfdoc/bytes";+import { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";+import { nameArtifactKinds } from "@editor/tools/pdfTextEditor/pdfdoc/passes/nameArtifactKinds";+import { singleContentPdf } from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";++async function contentOf(bytes: Uint8Array): Promise<string> {+ const pdf = (await RawPdf.parse(bytes))!;+ return toLatin1((await pdf.pageContent(pdf.pageNumberAt(0)!))!);+}++describe("nameArtifactKinds", () => {+ it("writes an artifact's string kind as names", async () => {+ const bytes = singleContentPdf(+ "/Artifact <</Subtype(Footer)/Type(Pagination)>> BDC BT /F1 12 Tf (hi) Tj ET EMC",+ );+ const out = await nameArtifactKinds(bytes, [0]);+ expect(await contentOf(out)).toContain(+ "/Artifact <</Subtype/Footer/Type/Pagination>> BDC",+ );+ });++ it("leaves other marks' strings, and other keys, as they are", async () => {+ const content =+ "/Span <</Type(Pagination)>> BDC EMC " ++ "/Artifact <</Type/Layout/Alt(Rule)>> BDC EMC";+ const bytes = singleContentPdf(content);+ expect(await nameArtifactKinds(bytes, [0])).toBe(bytes);+ });++ it("leaves pages it is not asked about", async () => {+ const bytes = singleContentPdf(+ "/Artifact <</Type(Pagination)>> BDC BT /F1 12 Tf (hi) Tj ET EMC",+ );+ expect(await nameArtifactKinds(bytes, [])).toBe(bytes);+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pageFurniture.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pageFurniture.test.tsnew file mode 100644index 0000000000..e8edf849bd--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pageFurniture.test.ts@@ -0,0 +1,269 @@+import { describe, expect, it } from "vitest";+import type { DisplayTransformData } from "@editor/tools/pdfTextEditor/model/DisplayTransform";+import {+ furnitureText,+ matchingRuns,+ recogniseFurniture,+ type FurniturePage,+} from "@editor/tools/pdfTextEditor/util/pageFurniture";++const LETTER: DisplayTransformData = {+ a: 1,+ b: 0,+ c: 0,+ d: 1,+ e: 0,+ f: 0,+ cropLeft: 0,+ cropBottom: 0,+ cropWidth: 612,+ cropHeight: 792,+ rotate: 0,+ displayWidth: 612,+ displayHeight: 792,+};++/** `n` written in Arabic-Indic digits. */+function arabicIndic(n: number): string {+ return String(n).replace(/\d/g, (digit) =>+ String.fromCodePoint(0x0660 + Number(digit)),+ );+}++/** Turned `angle` degrees about (x, y). */+function turned(angle: number, x: number, y: number) {+ const r = (angle * Math.PI) / 180;+ return {+ a: Math.cos(r),+ b: Math.sin(r),+ c: -Math.sin(r),+ d: Math.cos(r),+ e: x,+ f: y,+ };+}++/**+ * A run of `text` whose box starts `y` points up the page, black and square+ * to it unless `look` says otherwise.+ */+function run(+ id: string,+ text: string,+ y: number,+ x = 72,+ look: { alpha?: number; angle?: number } = {},+) {+ return {+ id,+ text,+ bounds: { x, y, width: 200, height: 10 },+ matrix: turned(look.angle ?? 0, x, y),+ fill: { r: 0, g: 0, b: 0, a: look.alpha ?? 255 },+ };+}++function image(id: string, x: number, y: number) {+ return {+ id,+ bounds: { x, y, width: 30, height: 30 },+ matrix: turned(0, x, y),+ };+}++function page(+ pageIndex: number,+ runs: ReturnType<typeof run>[],+ images: ReturnType<typeof image>[] = [],+): FurniturePage {+ return { pageIndex, display: LETTER, runs, images };+}++/** The kinds found on page `pageIndex`, by id. */+function kindsOn(+ found: ReturnType<typeof recogniseFurniture>,+ pageIndex: number,+) {+ return Object.fromEntries(found.get(pageIndex) ?? []);+}++describe("furnitureText", () => {+ it("reads each run of digits as one, and collapses whitespace", () => {+ expect(furnitureText(" Page 12 of\n30 ")).toBe("Page # of #");+ });++ it("reads digits in any script", () => {+ expect(furnitureText(`Page ${arabicIndic(12)}`)).toBe("Page #");+ });+});++describe("matchingRuns", () => {+ const pages = [+ page(0, [run("a", "Draft 1", 400)]),+ page(1, [run("b", "Draft 2", 402, 300), run("c", "Draft 2", 420)]),+ page(2, [run("d", "Final", 400)]),+ ];++ it("finds the same text, digits aside, at the same height on other pages", () => {+ expect(+ matchingRuns(pages, 0, pages[0].runs[0]).map((m) => m.run.id),+ ).toEqual(["b"]);+ });+});++describe("recogniseFurniture", () => {+ /** Page `i` of a document whose pages each draw `extra` runs too. */+ const furnished = (i: number, extra: ReturnType<typeof run>[] = []) =>+ page(i, [+ run(`h${i}`, "Acme Corp | Q3 report", 760),+ run(`n${i}`, `Page ${i + 1}`, 30),+ run(`f${i}`, "Confidential", 50),+ run(`b${i}`, `Body of page ${i + 1}`, 400),+ ...extra,+ ]);++ it("finds headers, footers and page numbers that most pages repeat", () => {+ const found = recogniseFurniture([furnished(0), furnished(1)], 2);+ expect(found.get(1)).toEqual(+ new Map([+ ["h1", "Header"],+ ["n1", "PageNum"],+ ["f1", "Footer"],+ ]),+ );+ });++ it("leaves text fewer than half the pages repeat", () => {+ const pages = [0, 1, 2, 3, 4].map((i) =>+ i < 2 ? furnished(i, [run(`x${i}`, "Note", 60)]) : furnished(i),+ );+ expect(recogniseFurniture(pages, 5).get(0)?.has("x0")).toBe(false);+ });++ it("leaves text away from the page's edges", () => {+ const found = recogniseFurniture(+ [+ furnished(0, [run("m0", "Draft", 400)]),+ furnished(1, [run("m1", "Draft", 400)]),+ ],+ 2,+ );+ expect(found.get(0)?.has("m0")).toBe(false);+ });++ it("needs two pages, however short the document", () => {+ expect(recogniseFurniture([furnished(0)], 1).size).toBe(0);+ });++ it.each([+ ["alone", (n: number) => `${n}`],+ ["after a word", (n: number) => `Page ${n}`],+ ["before a total", (n: number) => `${n} of 9`],+ ["in German", (n: number) => `Seite ${n} von 9`],+ ["between dashes", (n: number) => `- ${n} -`],+ ["in Arabic-Indic digits", arabicIndic],+ ])(+ "reads a number counting up with the pages %s as a page number",+ (_, text) => {+ // Numbered from 3, as after an unnumbered cover and contents page.+ const pages = [0, 1].map((i) => page(i, [run(`p${i}`, text(i + 3), 30)]));+ expect(recogniseFurniture(pages, 2).get(0)?.get("p0")).toBe("PageNum");+ },+ );++ it.each([+ ["stays the same", () => "Report 2026"],+ ["jumps between chapters", (i: number) => `Chapter ${i < 2 ? 3 : 4}`],+ ])("reads text whose number %s as a footer", (_, text) => {+ const pages = [0, 1, 2].map((i) => page(i, [run(`p${i}`, text(i), 30)]));+ expect(recogniseFurniture(pages, 3).get(0)?.get("p0")).toBe("Footer");+ });+});++describe("recogniseFurniture watermarks", () => {+ /** A see-through "DRAFT" tiled across the page, as the watermark tool draws one. */+ const tiles = (i: number) =>+ [0, 372, 744].flatMap((y) =>+ [0, 200, 400].map((x) =>+ run(`w${i}-${x}-${y}`, "DRAFT", y, x, { alpha: 128 }),+ ),+ );++ it("reads tiled see-through text as a watermark, even at the page's edges", () => {+ const pages = [0, 1].map((i) =>+ page(i, [run(`h${i}`, "Acme Corp", 760), ...tiles(i)]),+ );+ expect(kindsOn(recogniseFurniture(pages, 2), 0)).toEqual({+ h0: "Header",+ ...Object.fromEntries(tiles(0).map((tile) => [tile.id, "Watermark"])),+ });+ });++ it("reads text set at an angle in the same place on most pages as a watermark", () => {+ const pages = [0, 1].map((i) =>+ page(i, [run(`c${i}`, "CONFIDENTIAL", 400, 200, { angle: 45 })]),+ );+ expect(kindsOn(recogniseFurniture(pages, 2), 1)).toEqual({+ c1: "Watermark",+ });+ });++ it("reads a tiled page of a one-page document as watermarked", () => {+ const tiled = [+ run("t1", "COPY", 100, 50),+ run("t2", "COPY", 400, 400),+ run("t3", "COPY", 700, 50),+ ];+ expect(kindsOn(recogniseFurniture([page(0, tiled)], 1), 0)).toEqual({+ t1: "Watermark",+ t2: "Watermark",+ t3: "Watermark",+ });+ });++ it("leaves copies of a label that do not spread across the page", () => {+ const labels = (i: number) =>+ [300, 400, 500].map((y) => run(`n${i}-${y}`, "N/A", y, 300));+ const pages = [0, 1].map((i) => page(i, labels(i)));+ expect(recogniseFurniture(pages, 2).size).toBe(0);+ });++ it("leaves see-through text one page shows once", () => {+ const pages = [+ page(0, [run("s0", "Note", 400, 72, { alpha: 128 })]),+ page(1, []),+ ];+ expect(recogniseFurniture(pages, 2).size).toBe(0);+ });++ it("leaves text that repeats in place but looks like any other", () => {+ const pages = [0, 1].map((i) => page(i, [run(`s${i}`, "Signature:", 400)]));+ expect(recogniseFurniture(pages, 2).size).toBe(0);+ });++ it("reads tiled images as a watermark, and leaves an image each page shows once", () => {+ const spread = [+ [100, 100],+ [450, 400],+ [100, 700],+ ];+ const pages = [0, 1].map((i) =>+ page(+ i,+ [],+ [+ {+ ...image(`logo${i}`, 500, 700),+ bounds: { x: 500, y: 700, width: 60, height: 20 },+ },+ ...spread.map(([x, y]) => image(`i${i}-${y}`, x, y)),+ ],+ ),+ );+ expect(kindsOn(recogniseFurniture(pages, 2), 0)).toEqual({+ "i0-100": "Watermark",+ "i0-400": "Watermark",+ "i0-700": "Watermark",+ });+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/storeApplyRecovery.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/storeApplyRecovery.test.tsindex c56379b989..680cce6496 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/storeApplyRecovery.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/storeApplyRecovery.test.ts@@ -19,6 +19,7 @@ function makeDoc(): EditorDocument {loadedPages: () => [],documentLanguage: () => null,languagesInUse: () => [],+ onArtifactKinds: () => () => {},dispose: () => {},} as unknown as EditorDocument;}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.tsindex 7d73292f94..66d288ecfc 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts@@ -830,11 +830,27 @@ describe("SetDecorativeCommand", () => {]);});- test("refuses a paragraph", async () => {+ test("marks a paragraph decorative", async () => {const doc = await openSample();+ new HistoryStack().execute(+ new SetDecorativeCommand({ pageIndex: 0, mcid: 1, decorative: true }),+ doc,+ );+ expect(doc.structureEdits()).toEqual([+ { pageIndex: 0, mcid: 1, alt: null, decorative: true },+ ]);+ });++ test("refuses text in a list item", async () => {+ const doc = await openSample();+ const body = doc.structure(1).elements.find((el) => el.type === "LBody")!;expect(() =>new HistoryStack().execute(- new SetDecorativeCommand({ pageIndex: 0, mcid: 1, decorative: true }),+ new SetDecorativeCommand({+ pageIndex: 1,+ mcid: body.mcids[0],+ decorative: true,+ }),doc,),).toThrow(HistoryStepError);diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureGrouping.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureGrouping.test.tsindex 514d1346af..1f28a61358 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureGrouping.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureGrouping.test.ts@@ -190,17 +190,24 @@ describe("textTag", () => {}test("gives text the block it belongs to", async () => {- const tagged = (role: string, cannotRetag: string | null) => ({+ const tagged = (+ role: string,+ cannotRetag: string | null,+ canBeArtifact: boolean,+ ) => ({kind: "tagged",block: { role, type: role },cannotRetag,+ canBeArtifact,});expect(await tagOf(paragraphsPdf(), "Introduction")).toEqual(- tagged("H1", null),+ tagged("H1", null, true),+ );+ expect(await tagOf(paragraphsPdf(), "guide")).toEqual(+ tagged("P", null, false),);- expect(await tagOf(paragraphsPdf(), "guide")).toEqual(tagged("P", null));expect(await tagOf(paragraphsPdf(), "Item")).toEqual(- tagged("LI", "not-text"),+ tagged("LI", "not-text", false),);});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableStore.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableStore.test.tsindex 16805f372f..1876375bfb 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableStore.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableStore.test.ts@@ -32,6 +32,7 @@ async function makeStore() {loadedPages: () => [page],documentLanguage: () => null,languagesInUse: () => [],+ onArtifactKinds: () => () => {},module: {},dispose: () => {},} as unknown as EditorDocument;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tagPageContent.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tagPageContent.test.tsindex 5cfec3ada7..c98ba85cbe 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tagPageContent.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tagPageContent.test.ts@@ -20,11 +20,15 @@ import { tagAllPages } from "@editor/tools/pdfTextEditor/hooks/useBulkTagging";import { readAllPagesInBackground } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";import { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";+import { toLatin1 } from "@editor/tools/pdfTextEditor/pdfdoc/bytes";+import { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";import { readFileStructure } from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";import { readTagMarks } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";+import { setTextTagCommand } from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";+import { matchingRuns } from "@editor/tools/pdfTextEditor/util/pageFurniture";import { textTag } from "@editor/tools/pdfTextEditor/util/textAccessibility";import {buildClassicPdf,@@ -312,7 +316,7 @@ describe("tagAllPages", () => {expect(store.getState().loading).toBe(false);expect(progress).toHaveBeenCalledWith(- expect.objectContaining({ current: 0, total: 1 }),+ expect.objectContaining({ current: 0, total: 2 }),);const doc = store.document!;expect(hasUntaggedContent(doc, 0)).toBe(false);@@ -336,6 +340,199 @@ describe("tagAllPages", () => {});});+/**+ * What the watermark tool appends to a page on its default settings: a+ * half-opaque light grey grid of the text, or of the image 30 points high,+ * spaced 50 points apart.+ */+function toolWatermark(kind: "text" | "image"): string {+ const grid =+ kind === "text"+ ? Array.from({ length: 14 * 9 }, (_, n) => {+ const [x, y] = [(n % 9) * 86, Math.floor(n / 9) * 62];+ return `BT /F1 12 Tf 1 0 0 1 ${x} ${y} Tm (DRAFT) Tj 0 -12 Td ET`;+ })+ : Array.from({ length: 10 * 8 }, (_, n) => {+ const [x, y] = [(n % 8) * 80, Math.floor(n / 8) * 80];+ return `q 30 0 0 30 ${x} ${y} cm /Im1 Do Q`;+ });+ return ["/GS0 gs 0.827 0.827 0.827 rg", ...grid].join("\n");+}++/**+ * `count` untagged pages, each with a running header, footer and page number+ * around its own text, and the watermark tool's output over it all when+ * `watermark` says which.+ */+function furnishedPdf(count: number, watermark?: "text" | "image"): Uint8Array {+ const show = (x: number, y: number, text: string) =>+ `BT /F1 10 Tf ${x} ${y} Td (${text}) Tj ET`;+ const pages = Array.from({ length: count }, (_, i) => ({+ page: 10 + 2 * i,+ content: [+ "q",+ show(72, 760, "Acme Corp | Q3 report"),+ show(72, 400, `Results for region ${String.fromCharCode(65 + i)}`),+ show(72, 70, "Confidential"),+ show(300, 30, `Page ${i + 1}`),+ "Q",+ ...(watermark ? [toolWatermark(watermark)] : []),+ ].join("\n"),+ }));+ return buildClassicPdf(+ [+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },+ {+ num: 2,+ body: `<< /Type /Pages /Kids [${pages.map((p) => `${p.page} 0 R`).join(" ")}] /Count ${count} >>`,+ },+ {+ num: 3,+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ },+ {+ num: 4,+ body: streamBody(+ "/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8",+ "\x80",+ ),+ },+ ...pages.flatMap(({ page, content }) => [+ {+ num: page,+ body:+ `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents ${page + 1} 0 R ` ++ "/Resources << /Font << /F1 3 0 R >> /XObject << /Im1 4 0 R >> " ++ "/ExtGState << /GS0 << /ca 0.5 >> >> >> >>",+ },+ { num: page + 1, body: streamBody("", content) },+ ]),+ ],+ 1,+ );+}++/** How each run on the page is tagged, by its text. */+function tagsShown(doc: EditorDocument, pageIndex: number) {+ return new Map(+ doc.page(pageIndex).runs.map((run) => {+ const tag = textTag(doc, run.snapshot());+ const shown =+ tag.kind === "artifact"+ ? (tag.furniture ?? "artifact")+ : tag.kind === "tagged"+ ? tag.block.type+ : tag.kind;+ return [run.text.trim(), shown];+ }),+ );+}++describe("page furniture", () => {+ test("auto-tag makes repeated headers, footers and page numbers artifacts", async () => {+ const store = await storeFor(furnishedPdf(3));+ await tagAllPages(store);+ const doc = store.document!;+ expect(tagsShown(doc, 2)).toEqual(+ new Map([+ ["Acme Corp | Q3 report", "Header"],+ ["Results for region C", "P"],+ ["Confidential", "Footer"],+ ["Page 3", "PageNum"],+ ]),+ );+ const saved = (await RawPdf.parse(await savedBytes(doc)))!;+ const content = toLatin1(+ (await saved.pageContent(saved.pageNumberAt(2)!))!,+ );+ expect(content).toContain(+ "/Artifact <</Subtype/PageNum/Type/Pagination>> BDC",+ );++ store.undo();+ expect(tagsShown(doc, 2).get("Page 3")).toBe("untagged");+ store.dispose();+ });++ test("auto-tag makes the watermark tool's text an artifact, leaving the furniture under it", async () => {+ const store = await storeFor(furnishedPdf(2, "text"));+ await tagAllPages(store);+ const doc = store.document!;+ const drafts = doc+ .page(1)+ .runs.filter((run) => run.text.trim() === "DRAFT")+ .map((run) => textTag(doc, run.snapshot()));+ expect(drafts).toHaveLength(14 * 9);+ expect(+ drafts.every(+ (tag) => tag.kind === "artifact" && tag.furniture === "Watermark",+ ),+ ).toBe(true);+ const others = tagsShown(doc, 1);+ others.delete("DRAFT");+ expect(others).toEqual(+ new Map([+ ["Acme Corp | Q3 report", "Header"],+ ["Results for region B", "P"],+ ["Confidential", "Footer"],+ ["Page 2", "PageNum"],+ ]),+ );+ const saved = (await RawPdf.parse(await savedBytes(doc)))!;+ const content = toLatin1(+ (await saved.pageContent(saved.pageNumberAt(1)!))!,+ );+ expect(content).toContain(+ "/Artifact <</Subtype/Watermark/Type/Pagination>> BDC",+ );+ store.dispose();+ });++ test("auto-tag makes the watermark tool's images artifacts, not figures", async () => {+ const store = await storeFor(furnishedPdf(2, "image"));+ await tagAllPages(store);+ const images = store.document!.page(0).images;+ expect(images).toHaveLength(10 * 8);+ expect(images.every((image) => image.artifact && image.mcid === null)).toBe(+ true,+ );++ store.undo();+ expect(images.every((image) => !image.artifact)).toBe(true);+ store.dispose();+ });++ test("gives matching text on other pages an artifact's kind, as one undo step", async () => {+ const doc = await open(furnishedPdf(3));+ for (const pageIndex of [1, 2]) {+ PdfiumTextReader.populate(doc, doc.page(pageIndex));+ }+ const pages = [0, 1, 2].map((pageIndex) => {+ const { display, runs } = doc.page(pageIndex);+ return { pageIndex, display, runs: runs.map((r) => r.snapshot()) };+ });+ const footer = pages[0].runs.find((r) => r.text.includes("Confidential"))!;+ const targets = [+ footer,+ ...matchingRuns(pages, 0, footer).map(({ run }) => run),+ ].map((run) => ({ run, tag: textTag(doc, run) }));+ expect(targets).toHaveLength(3);+ const history = new HistoryStack();+ history.execute(+ setTextTagCommand(doc, targets, { artifact: "Footer" })!,+ doc,+ );+ expect([0, 1, 2].map((i) => tagsShown(doc, i).get("Confidential"))).toEqual(+ ["Footer", "Footer", "Footer"],+ );++ history.undo(doc);+ expect([0, 1, 2].map((i) => tagsShown(doc, i).get("Confidential"))).toEqual(+ ["untagged", "untagged", "untagged"],+ );+ });+});+describe("tagAllPages and the tagged flag", () => {test("marks the document fully tagged in the same undo step", async () => {const store = await storeFor(pagePdf(COLUMNS));diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textTagging.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textTagging.test.tsindex 69f09b59dc..1a29ca0ac8 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textTagging.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textTagging.test.ts@@ -12,10 +12,12 @@ import {test,vi,} from "vitest";+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";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 { toLatin1 } from "@editor/tools/pdfTextEditor/pdfdoc/bytes";import { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";import { readFileStructure } from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";@@ -28,9 +30,9 @@ import {streamBody,} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";import {- canTagText,sharedTextTag,textTag,+ type TextTagChoice,} from "@editor/tools/pdfTextEditor/util/textAccessibility";import { setTextTagCommand } from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";@@ -186,7 +188,7 @@ function tagText(doc: EditorDocument,history: HistoryStack,fragment: string,- as: StructureType,+ as: TextTagChoice,pageIndex = PAGE,) {const run = doc.page(pageIndex).runs.find((r) => r.text.includes(fragment))!;@@ -287,11 +289,20 @@ describe("tagging untagged text", () => {expect(shownTag(doc, "Confidential")).toBe("P");});- test("refuses text marked as an artifact", async () => {+ test("tags 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();+ const history = new HistoryStack();+ tagText(doc, history, "Acme Corp", "P");+ expect(shownTag(doc, "Acme Corp")).toBe("P");++ const reopened = await EditorDocument.open(await savedBytes(doc));+ opened.push(reopened);+ PdfiumTextReader.populate(reopened, reopened.page(PAGE));+ expect(shownTag(reopened, "Acme Corp")).toBe("P");++ history.undo(doc);+ expect(shownTag(doc, "Acme Corp")).toBe("artifact");+ expect(doc.structureEdits()).toEqual([]);});test("tags every line of a paragraph as one element", async () => {@@ -389,22 +400,16 @@ describe("tagging text in a file with no structure tree", () => {});describe("setting one tag on several runs", () => {- function targets(doc: EditorDocument, ...fragments: string[]) {- return fragments.map((fragment) => {- const run = runWith(doc, fragment).snapshot();- return { run, tag: textTag(doc, run) };- });- }-test("reads runs tagged differently as mixed, and alike as their tag", async () => {const doc = await openSample();const mixed = targets(doc, "Priorities for next quarter", "Confidential");expect(sharedTextTag(mixed.map(({ tag }) => tag))).toEqual({kind: "mixed",settable: true,+ canBeArtifact: true,});const history = new HistoryStack();- history.execute(setTextTagCommand(mixed, "H3")!, doc);+ history.execute(setTextTagCommand(doc, mixed, "H3")!, doc);const alike = targets(doc, "Priorities for next quarter", "Confidential");expect(sharedTextTag(alike.map(({ tag }) => tag))).toMatchObject({kind: "tagged",@@ -418,6 +423,7 @@ describe("setting one tag on several runs", () => {const history = new HistoryStack();history.execute(setTextTagCommand(+ doc,targets(doc, "Priorities for next quarter", "Confidential"),"H3",)!,@@ -433,11 +439,265 @@ describe("setting one tag on several runs", () => {test("leaves text whose tag cannot be set out, and is not settable with it", async () => {const doc = await openSample();- const withArtifact = targets(doc, "Confidential", "Acme Corp");- expect(sharedTextTag(withArtifact.map(({ tag }) => tag))).toEqual({+ const withListItem = targets(doc, "Confidential", "Close the two delayed");+ expect(sharedTextTag(withListItem.map(({ tag }) => tag))).toEqual({kind: "mixed",settable: false,+ canBeArtifact: false,});- expect(setTextTagCommand(targets(doc, "Acme Corp"), "P")).toBeNull();+ expect(+ setTextTagCommand(doc, targets(doc, "Close the two delayed"), "P"),+ ).toBeNull();+ });++ test("makes tagged and untagged text artifacts as one undo step", async () => {+ const doc = await openSample();+ const history = new HistoryStack();+ const both = targets(doc, "All amounts", "Confidential");+ history.execute(setTextTagCommand(doc, both, { artifact: null })!, doc);+ expect(shownTag(doc, "All amounts")).toBe("artifact");+ expect(shownTag(doc, "Confidential")).toBe("artifact");++ history.undo(doc);+ expect(shownTag(doc, "All amounts")).toBe("P");+ expect(shownTag(doc, "Confidential")).toBe("untagged");+ expect(doc.structureEdits()).toEqual([]);});});++describe("reading what the file's artifacts are", () => {+ test("reads the kind the file names for each artifact", async () => {+ const doc = await openSample();+ const heard: number[] = [];+ doc.onArtifactKinds((pageIndex) => heard.push(pageIndex));+ expect(await doc.loadArtifactKinds(PAGE)).toBe(true);+ expect(heard).toEqual([PAGE]);+ expect(furnitureShown(doc, "Acme Corp")).toBe("Header");+ expect(furnitureShown(doc, "Page 2")).toBeNull();+ expect(runWith(doc, "Page 2").tagMarks).toEqual([+ {+ name: "Artifact",+ mcid: null,+ artifact: { type: "Pagination", subtype: null },+ },+ ]);+ });++ test("reads back the kind the session saved", async () => {+ const doc = await openSample();+ const history = new HistoryStack();+ tagAs(doc, history, "Confidential", { artifact: "Footer" });+ const reopened = await EditorDocument.open(await savedBytes(doc));+ opened.push(reopened);+ PdfiumTextReader.populate(reopened, reopened.page(PAGE));+ await reopened.loadArtifactKinds(PAGE);+ expect(furnitureShown(reopened, "Confidential")).toBe("Footer");+ });++ test("gives an artifact back its kind on undo", async () => {+ const doc = await openSample();+ await doc.loadArtifactKinds(PAGE);+ const history = new HistoryStack();+ tagAs(doc, history, "Page 2", { artifact: "PageNum" });+ tagText(doc, history, "Acme Corp", "P");+ history.undo(doc);+ history.undo(doc);+ expect(furnitureShown(doc, "Acme Corp")).toBe("Header");+ expect(await artifactOperators(await savedBytes(doc))).toEqual(+ expect.arrayContaining([+ "/Artifact <</Subtype/Header/Type/Pagination>> BDC",+ "/Artifact <</Type/Pagination>> BDC",+ ]),+ );+ });+});++describe("making text an artifact", () => {+ async function reopen(doc: EditorDocument): Promise<EditorDocument> {+ const reopened = await EditorDocument.open(await savedBytes(doc));+ opened.push(reopened);+ PdfiumTextReader.populate(reopened, reopened.page(PAGE));+ return reopened;+ }++ test("marks untagged text as an artifact, saves it, and undoes", async () => {+ const doc = await openSample();+ const history = new HistoryStack();+ tagAs(doc, history, "Confidential", { artifact: null });+ expect(shownTag(doc, "Confidential")).toBe("artifact");+ expect(shownTag(await reopen(doc), "Confidential")).toBe("artifact");++ history.undo(doc);+ expect(shownTag(doc, "Confidential")).toBe("untagged");+ });++ test("drops an element the session added, and brings it back on undo", async () => {+ const doc = await openSample();+ const history = new HistoryStack();+ const before = doc.headings()!.length;+ tagText(doc, history, "Confidential", "H2");+ tagAs(doc, history, "Confidential", { artifact: null });+ expect(shownTag(doc, "Confidential")).toBe("artifact");+ expect(doc.headings()).toHaveLength(before);+ expect(doc.structureEdits().some((edit) => edit.newElement)).toBe(false);++ history.undo(doc);+ expect(shownTag(doc, "Confidential")).toBe("H2");+ expect(doc.headings()).toHaveLength(before + 1);+ });++ test("turns the file's paragraph into an artifact on save", async () => {+ const doc = await openSample();+ const key = doc+ .structure(PAGE)+ .block(runWith(doc, "All amounts").snapshot().mcid!)!.key;+ tagAs(doc, new HistoryStack(), "All amounts", { artifact: null });+ expect(shownTag(doc, "All amounts")).toBe("artifact");++ const saved = await readFileStructure(await savedBytes(doc));+ expect(saved!.blocks.some((block) => block.key === key)).toBe(false);+ expect(shownTag(await reopen(doc), "All amounts")).toBe("artifact");+ });++ test("leaves a heading marked decorative out of the outline", async () => {+ const doc = await openSample();+ const history = new HistoryStack();+ const before = doc.headings()!.map((h) => h.type);+ tagAs(doc, history, "Outlook", { artifact: null });+ expect(doc.headings()!.map((h) => h.type)).not.toContain("H5");++ history.undo(doc);+ expect(doc.headings()!.map((h) => h.type)).toEqual(before);+ });++ test("gives decorative text a type again, keeping its element", async () => {+ const doc = await openSample();+ const history = new HistoryStack();+ tagAs(doc, history, "Outlook", { artifact: null });+ tagAs(doc, history, "Outlook", "H3");+ expect(shownTag(doc, "Outlook")).toBe("H3");+ expect(doc.structureEdits()).toEqual([+ expect.objectContaining({ type: "H3", decorative: false }),+ ]);+ });++ test("marks untagged text as page furniture, saved as a pagination artifact", async () => {+ const doc = await openSample();+ const history = new HistoryStack();+ tagAs(doc, history, "Confidential", { artifact: "Footer" });+ expect(furnitureShown(doc, "Confidential")).toBe("Footer");+ expect(await artifactOperators(await savedBytes(doc))).toContain(+ "/Artifact <</Subtype/Footer/Type/Pagination>> BDC",+ );++ history.undo(doc);+ expect(shownTag(doc, "Confidential")).toBe("untagged");+ });++ test("keeps page furniture's kind through an edit to its text", async () => {+ const doc = await openSample();+ const history = new HistoryStack();+ tagAs(doc, history, "Confidential", { artifact: "Footer" });+ const run = runWith(doc, "Confidential");+ history.execute(+ new EditTextCommand({+ pageIndex: PAGE,+ runId: run.id,+ nextText: "Confidential - internal use only, do not share",+ }),+ doc,+ );+ expect(furnitureShown(doc, "do not share")).toBe("Footer");+ expect(await artifactOperators(await savedBytes(doc))).toContain(+ "/Artifact <</Subtype/Footer/Type/Pagination>> BDC",+ );+ });++ test("changes what an artifact is, and back on undo", async () => {+ const doc = await openSample();+ const history = new HistoryStack();+ tagAs(doc, history, "Confidential", { artifact: null });+ tagAs(doc, history, "Confidential", { artifact: "Watermark" });+ expect(furnitureShown(doc, "Confidential")).toBe("Watermark");++ history.undo(doc);+ expect(furnitureShown(doc, "Confidential")).toBeNull();+ expect(+ setTextTagCommand(doc, targets(doc, "Confidential"), {+ artifact: null,+ }),+ ).toBeNull();+ });++ test("marks the file's paragraph as page furniture through its element", async () => {+ const doc = await openSample();+ const history = new HistoryStack();+ tagAs(doc, history, "All amounts", { artifact: "Footer" });+ tagAs(doc, history, "All amounts", { artifact: "PageNum" });+ expect(furnitureShown(doc, "All amounts")).toBe("PageNum");+ expect(doc.structureEdits()).toEqual([+ expect.objectContaining({ decorative: true, furniture: "PageNum" }),+ ]);+ expect(await artifactOperators(await savedBytes(doc))).toContain(+ "/Artifact <</Type /Pagination /Subtype /PageNum>> BDC",+ );++ history.undo(doc);+ expect(furnitureShown(doc, "All amounts")).toBe("Footer");+ });++ test("reads artifacts of different kinds as mixed", async () => {+ const doc = await openSample();+ const history = new HistoryStack();+ tagAs(doc, history, "Confidential", { artifact: "Header" });+ const both = targets(doc, "Confidential", "Page 2");+ expect(sharedTextTag(both.map(({ tag }) => tag))).toMatchObject({+ kind: "mixed",+ });+ });++ test("refuses a paragraph holding a link, whose element holds more than text", async () => {+ const doc = await openSample();+ const tag = textTag(doc, runWith(doc, "appendix").snapshot());+ expect(tag).toMatchObject({ kind: "tagged", canBeArtifact: false });+ });++ test("refuses text in a list item", async () => {+ const doc = await openSample();+ const tag = textTag(doc, runWith(doc, "Close the two delayed").snapshot());+ expect(tag).toMatchObject({ kind: "tagged", canBeArtifact: false });+ });+});++function furnitureShown(doc: EditorDocument, fragment: string) {+ const tag = textTag(doc, runWith(doc, fragment).snapshot());+ if (tag.kind !== "artifact") throw new Error(`"${fragment}" is ${tag.kind}`);+ return tag.furniture;+}++function targets(doc: EditorDocument, ...fragments: string[]) {+ return fragments.map((fragment) => {+ const run = runWith(doc, fragment).snapshot();+ return { run, tag: textTag(doc, run) };+ });+}++/** The operators opening artifacts in the saved file's sample page. */+async function artifactOperators(bytes: Uint8Array): Promise<string[]> {+ const pdf = (await RawPdf.parse(bytes))!;+ const content = await pdf.pageContent(pdf.pageNumberAt(PAGE)!);+ return toLatin1(content!).match(/\/Artifact\b[^\n]*?(?:BDC|BMC)/g) ?? [];+}++function tagAs(+ doc: EditorDocument,+ history: HistoryStack,+ fragment: string,+ choice: TextTagChoice,+) {+ const command = setTextTagCommand(doc, targets(doc, fragment), choice);+ if (!command) {+ throw new Error(`"${fragment}" cannot be tagged ${JSON.stringify(choice)}`);+ }+ history.execute(command, doc);+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetDecorativeCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetDecorativeCommand.tsindex 83e0f9415b..97d111a850 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetDecorativeCommand.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetDecorativeCommand.ts@@ -3,6 +3,7 @@ import {RolledBackError,type Command,} from "@editor/tools/pdfTextEditor/commands/Command";+import type { Furniture } from "@editor/tools/pdfTextEditor/model/artifactKind";import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";import type {PageStructure,@@ -10,21 +11,30 @@ import type {} from "@editor/tools/pdfTextEditor/model/PageStructure";/**- * Mark or unmark the structure element owning `mcid` as decorative. Like a- * description, the mark is held on the document's structure index and written- * by the save pass, which turns the element's content into an artifact.+ * Mark or unmark the structure element owning `mcid` as decorative: a figure,+ * or a block of text such as a running header, which `furniture` says it is.+ * Like a description, the mark is held on the document's structure index and+ * written by the save pass, which turns the element's content into an+ * artifact of that kind.*/export class SetDecorativeCommand implements Command {readonly type = "set-decorative";private readonly pageIndex: number;private readonly mcid: number;private readonly decorative: boolean;+ private readonly furniture: Furniture | null;private previous: StructureElementEdit | null | undefined;- constructor(opts: { pageIndex: number; mcid: number; decorative: boolean }) {+ constructor(opts: {+ pageIndex: number;+ mcid: number;+ decorative: boolean;+ furniture?: Furniture | null;+ }) {this.pageIndex = opts.pageIndex;this.mcid = opts.mcid;this.decorative = opts.decorative;+ this.furniture = opts.furniture ?? null;}apply(doc: EditorDocument): void {@@ -35,8 +45,8 @@ export class SetDecorativeCommand implements Command {throw new RolledBackError(new Error(i18n.t(- "pdfTextEditor.inspector.accessibility.cannotChange",- "This image's accessibility can't be changed.",+ "pdfTextEditor.inspector.accessibility.cannotSetDecorative",+ "This can't be marked or unmarked as decorative.",),),);@@ -44,18 +54,15 @@ export class SetDecorativeCommand implements Command {if (this.previous === undefined) {this.previous = structure.editFor(this.mcid);}- structure.setDecorative(this.mcid, this.decorative);+ structure.setDecorative(this.mcid, this.decorative, this.furniture);doc.page(this.pageIndex).bumpRevision();}private refused(structure: PageStructure): boolean {- // An added figure has no element in the file to drop: TagImageCommand- // retags its content instead.+ // An added element has no element in the file to drop: TagImageCommand+ // and TagTextCommand retag its content instead.if (structure.isAdded(this.mcid)) return true;- const blocker = this.decorative- ? structure.cannotMarkDecorative(this.mcid)- : structure.cannotDescribe(this.mcid);- return blocker !== null;+ return structure.cannotMarkDecorative(this.mcid) !== null;}revert(doc: EditorDocument): void {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagPageContentCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagPageContentCommand.tsindex 62c3261a44..a58d95da3f 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagPageContentCommand.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagPageContentCommand.ts@@ -8,41 +8,55 @@ import {collectContainersByPtr,collectMemberPtrs,} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";+import {+ furnitureKind,+ type Furniture,+} from "@editor/tools/pdfTextEditor/model/artifactKind";import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";import type { Page } from "@editor/tools/pdfTextEditor/model/Page";import type { PageStructure } from "@editor/tools/pdfTextEditor/model/PageStructure";import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";import {ARTIFACT_TAG,- addTagMark,highestMcid,innermostMcid,readTagMarks,- removeTagMark,type TagMark,} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";+import {+ restoreObject,+ retagObject,+ type ObjectRetag,+} from "@editor/tools/pdfTextEditor/commands/retagObjects";const FPDF_PAGEOBJ_PATH = 2;const FPDF_PAGEOBJ_SHADING = 4;const TEXT_TAG: StructureType = "P";const IMAGE_TAG: StructureType = "Figure";-/** An object to retag, and the marks it loses: an MCID no element owns. */-interface Retag {- ptr: number;- dropped: TagMark[];-}-type Step =| {kind: "text";runId: string;mcid: number;- objects: Retag[];+ objects: ObjectRetag[];+ runMarks: readonly TagMark[];+ }+ | {+ kind: "furniture";+ runId: string;+ tag: TagMark;+ objects: ObjectRetag[];runMarks: readonly TagMark[];}- | { kind: "image"; imageId: string; mcid: number; object: Retag }- | { kind: "artifact"; object: Retag };+ | { kind: "image"; imageId: string; mcid: number; object: ObjectRetag }+ | {+ kind: "furnitureImage";+ imageId: string;+ tag: TagMark;+ object: ObjectRetag;+ }+ | { kind: "artifact"; object: ObjectRetag };interface Plan {steps: Step[];@@ -52,8 +66,9 @@ interface Plan {/*** Tag the untagged content drawn directly by a page, as a starting point the- * user then corrects: each text block a P, each image a Figure, every other- * object an artifact, the new elements read in content order. Content already+ * user then corrects: each text block a P and each image a Figure, or an+ * artifact of the kind `furniture` names it as (by run or image id), every+ * other object an artifact, the new elements read in content order. Content already* tagged or marked an artifact is left alone. Content marked with an MCID no* element owns counts as untagged, losing that mark. Content in a form* XObject is left alone: the editor cannot tag inside one. The page must@@ -62,11 +77,16 @@ interface Plan {export class TagPageContentCommand implements Command {readonly type = "tag-page-content";readonly pageIndex: number;+ private readonly furniture: ReadonlyMap<string, Furniture>;/** Chosen on first apply, so a redo reuses its MCIDs. */private plan: Plan | null = null;- constructor(opts: { pageIndex: number }) {+ constructor(opts: {+ pageIndex: number;+ furniture?: ReadonlyMap<string, Furniture>;+ }) {this.pageIndex = opts.pageIndex;+ this.furniture = opts.furniture ?? new Map();}apply(doc: EditorDocument): void {@@ -82,7 +102,7 @@ export class TagPageContentCommand implements Command {),);}- this.plan ??= planTagging(doc, page, structure);+ this.plan ??= planTagging(doc, page, structure, this.furniture);const done: Step[] = [];try {for (const step of this.plan.steps) {@@ -120,7 +140,9 @@ export function hasUntaggedContent(): boolean {const structure = doc.structure(pageIndex);if (structure.cannotAddElement() !== null) return false;- return planTagging(doc, doc.page(pageIndex), structure).steps.length > 0;+ return (+ planTagging(doc, doc.page(pageIndex), structure, new Map()).steps.length > 0+ );}/** The untagged content as steps, and where each new element reads. */@@ -128,6 +150,7 @@ function planTagging(doc: EditorDocument,page: Page,structure: PageStructure,+ furniture: ReadonlyMap<string, Furniture>,): Plan {const m = doc.module;const marks = new Map<number, TagMark[]>();@@ -166,15 +189,22 @@ function planTagging(return dropped ? [{ ptr, dropped }] : [];});if (objects.length === 0) continue;+ const at = Math.min(+ ...objects.map(({ ptr }) => order.get(ptr) ?? Infinity),+ );+ const runMarks = run.tagMarks;+ const kind = furniture.get(run.id);located.push({- at: Math.min(...objects.map(({ ptr }) => order.get(ptr) ?? Infinity)),- step: {- kind: "text",- runId: run.id,- mcid: nextMcid++,- objects,- runMarks: run.tagMarks,- },+ at,+ step: kind+ ? {+ kind: "furniture",+ runId: run.id,+ tag: furnitureTag(kind),+ objects,+ runMarks,+ }+ : { kind: "text", runId: run.id, mcid: nextMcid++, objects, runMarks },});}@@ -182,14 +212,18 @@ function planTagging(const dropped =image.containerPtr === 0 ? untagged(image.pdfiumObjPtr) : null;if (!dropped) continue;+ const object = { ptr: image.pdfiumObjPtr, dropped };+ const kind = furniture.get(image.id);located.push({at: order.get(image.pdfiumObjPtr) ?? Infinity,- step: {- kind: "image",- imageId: image.id,- mcid: nextMcid++,- object: { ptr: image.pdfiumObjPtr, dropped },- },+ step: kind+ ? {+ kind: "furnitureImage",+ imageId: image.id,+ tag: furnitureTag(kind),+ object,+ }+ : { kind: "image", imageId: image.id, mcid: nextMcid++, object },});}@@ -230,7 +264,9 @@ function readingChain(if (mcid !== null) tagged.push({ at, mcid });}for (const { at, step } of located) {- if (step.kind !== "artifact") tagged.push({ at, mcid: step.mcid });+ if (step.kind === "text" || step.kind === "image") {+ tagged.push({ at, mcid: step.mcid });+ }}tagged.sort((a, b) => a.at - b.at);@@ -238,7 +274,7 @@ function readingChain(let previous: number | null = null;const added = new Set(located.flatMap(({ step }) =>- step.kind === "artifact" ? [] : [step.mcid],+ step.kind === "text" || step.kind === "image" ? [step.mcid] : [],),);for (const { mcid } of tagged) {@@ -262,6 +298,10 @@ function contentOrder(return order;}+function furnitureTag(kind: Furniture): TagMark {+ return { name: ARTIFACT_TAG, mcid: null, artifact: furnitureKind(kind) };+}+function isArtifact(tags: readonly TagMark[]): boolean {return tags.some((tag) => tag.name === ARTIFACT_TAG);}@@ -278,21 +318,35 @@ function applyStep(const run = page.runs.find((r) => r.id === step.runId);if (!run) throw new Error(`no run ${step.runId}`);const tag = { name: TEXT_TAG, mcid: step.mcid };- for (const object of step.objects) retag(doc, object, tag);+ for (const object of step.objects) retagObject(doc, object, tag);run.tagMarks = [tag];structure.addElement(step.mcid, TEXT_TAG, follows.get(step.mcid));return;}+ case "furniture": {+ const run = page.runs.find((r) => r.id === step.runId);+ if (!run) throw new Error(`no run ${step.runId}`);+ for (const object of step.objects) retagObject(doc, object, step.tag);+ run.tagMarks = [step.tag];+ return;+ }+ case "furnitureImage": {+ const image = page.findImage(step.imageId);+ if (!image) throw new Error(`no image ${step.imageId}`);+ retagObject(doc, step.object, step.tag);+ image.artifact = true;+ return;+ }case "image": {const image = page.findImage(step.imageId);if (!image) throw new Error(`no image ${step.imageId}`);- retag(doc, step.object, { name: IMAGE_TAG, mcid: step.mcid });+ retagObject(doc, step.object, { name: IMAGE_TAG, mcid: step.mcid });image.mcid = step.mcid;structure.addElement(step.mcid, IMAGE_TAG, follows.get(step.mcid));return;}case "artifact":- retag(doc, step.object, { name: ARTIFACT_TAG, mcid: null });+ retagObject(doc, step.object, { name: ARTIFACT_TAG, mcid: null });}}@@ -305,38 +359,34 @@ function revertStep(): void {switch (step.kind) {case "text": {- for (const object of step.objects) restore(doc, object, TEXT_TAG);+ for (const object of step.objects) restoreObject(doc, object, TEXT_TAG);const run = page.runs.find((r) => r.id === step.runId);if (run) run.tagMarks = step.runMarks;structure.removeElement(step.mcid);return;}+ case "furniture": {+ for (const object of step.objects) {+ restoreObject(doc, object, ARTIFACT_TAG);+ }+ const run = page.runs.find((r) => r.id === step.runId);+ if (run) run.tagMarks = step.runMarks;+ return;+ }+ case "furnitureImage": {+ restoreObject(doc, step.object, ARTIFACT_TAG);+ const image = page.findImage(step.imageId);+ if (image) image.artifact = false;+ return;+ }case "image": {- restore(doc, step.object, IMAGE_TAG);+ restoreObject(doc, step.object, IMAGE_TAG);const image = page.findImage(step.imageId);if (image) image.mcid = innermostMcid(step.object.dropped);structure.removeElement(step.mcid);return;}case "artifact":- restore(doc, step.object, ARTIFACT_TAG);- }-}--function retag(doc: EditorDocument, object: Retag, tag: TagMark): void {- for (const dropped of [...object.dropped].reverse()) {- if (!removeTagMark(doc.module, object.ptr, dropped.name)) {- throw new Error("PDFium could not remove a tag");- }- }- if (!addTagMark(doc.module, doc.docPtr, object.ptr, tag)) {- throw new Error("PDFium could not tag the content");- }-}--function restore(doc: EditorDocument, object: Retag, name: string): void {- removeTagMark(doc.module, object.ptr, name);- for (const dropped of object.dropped) {- addTagMark(doc.module, doc.docPtr, object.ptr, dropped);+ restoreObject(doc, step.object, ARTIFACT_TAG);}}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextCommand.tsindex cd7c686ad6..0d0182f400 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextCommand.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextCommand.ts@@ -4,35 +4,57 @@ import {type Command,} from "@editor/tools/pdfTextEditor/commands/Command";import { collectMemberPtrs } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";+import {+ restoreObject,+ retagObject,+ type ObjectRetag,+} from "@editor/tools/pdfTextEditor/commands/retagObjects";+import {+ furnitureKind,+ type Furniture,+} from "@editor/tools/pdfTextEditor/model/artifactKind";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,+ ARTIFACT_TAG,highestMcid,- innermostMcid,readTagMarks,- removeTagMark,type TagMark,} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";-import { canTagText } from "@editor/tools/pdfTextEditor/util/textAccessibility";+import {+ retaggableText,+ type RetaggableText,+ type TextTagChoice,+} from "@editor/tools/pdfTextEditor/util/textAccessibility";++interface Plan {+ from: RetaggableText;+ /** The element the text is given; null when it becomes an artifact. */+ element: { mcid: number; type: StructureType } | null;+ tag: TagMark;+ objects: ObjectRetag[];+ runMarks: readonly TagMark[];+}/**- * 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.+ * Tag text as a new element of `as`, or as an artifact of its kind, where+ * retaggableText allows. Unlike a retag this changes the text's marks, so the+ * save regenerates the page's content; the save pass then gives a new 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.+ * Text in an element the session added can only become an artifact here:+ * RetagTextCommand changes its type.*/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;+ private readonly as: TextTagChoice;+ /** Chosen on first apply, so a redo reuses its MCID. */+ private plan: Plan | null = null;- constructor(opts: { pageIndex: number; runId: string; as: StructureType }) {+ constructor(opts: { pageIndex: number; runId: string; as: TextTagChoice }) {this.pageIndex = opts.pageIndex;this.runId = opts.runId;this.as = opts.as;@@ -41,17 +63,8 @@ export class TagTextCommand implements Command {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- ) {+ this.plan ??= run ? planTagging(doc, run, this.as) : null;+ if (!run || !this.plan) {throw new RolledBackError(new Error(i18n.t(@@ -61,40 +74,90 @@ export class TagTextCommand implements Command {),);}- 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");+ const { from, element, tag, objects } = this.plan;+ const done: ObjectRetag[] = [];+ try {+ for (const object of objects) {+ retagObject(doc, object, tag);+ done.push(object);}- marked.push(ptr);+ } catch (err) {+ for (const object of done.reverse()) restoreObject(doc, object, tag.name);+ throw new RolledBackError(err);}+ const structure = doc.structure(this.pageIndex);+ if (from.kind === "added") structure.removeElement(from.element.mcid);+ if (element) structure.addElement(element.mcid, element.type);run.tagMarks = [tag];- structure.addElement(this.mcid, this.as);page.markDirty();page.markNeedsGenerate();}revert(doc: EditorDocument): void {- if (this.mcid === null) return;+ if (!this.plan) return;const page = doc.page(this.pageIndex);+ const { from, element, tag, objects, runMarks } = this.plan;+ for (const object of [...objects].reverse()) {+ restoreObject(doc, object, tag.name);+ }+ const structure = doc.structure(this.pageIndex);+ if (element) structure.removeElement(element.mcid);+ if (from.kind === "added") structure.restoreElement(from.element);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);+ if (run) run.tagMarks = runMarks;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);- }+/** The run's objects to retag as `as`; null when the text cannot be. */+function planTagging(+ doc: EditorDocument,+ run: TextRun,+ as: TextTagChoice,+): Plan | null {+ const snapshot = run.snapshot();+ const from = retaggableText(doc, snapshot);+ const members = collectMemberPtrs(run);+ if (!from || members.includes(0)) return null;+ // Already so, or a type change RetagTextCommand makes.+ const unchanged =+ typeof as === "string"+ ? from.kind === "added"+ : from.kind === "artifact" &&+ as.artifact === (snapshot.furniture ?? null);+ if (unchanged) return null;+ const objects = members.flatMap((ptr) => {+ const dropped = readTagMarks(doc.module, ptr);+ return movable(from, dropped) ? [{ ptr, dropped }] : [];+ });+ if (objects.length === 0) return null;+ const runMarks = run.tagMarks;+ if (typeof as !== "string") {+ const tag = artifactTag(as.artifact);+ return { from, element: null, tag, objects, runMarks };}- run.tagMarks = [];+ const mcid = doc+ .structure(run.pageIndex)+ .freeMcid(highestMcid(doc.module, doc.page(run.pageIndex).pagePtr));+ const element = { mcid, type: as };+ return { from, element, tag: { name: as, mcid }, objects, runMarks };+}++function artifactTag(furniture: Furniture | null): TagMark {+ const tag = { name: ARTIFACT_TAG, mcid: null };+ return furniture ? { ...tag, artifact: furnitureKind(furniture) } : tag;+}++/**+ * True when an object of text tagged `from`, carrying `marks`, takes the new+ * tag: one with no marks, or only the ones the text is moving from. An+ * artifact beside untagged text, such as a bullet, stays one.+ */+function movable(from: RetaggableText, marks: readonly TagMark[]): boolean {+ return marks.every((mark) =>+ mark.name === ARTIFACT_TAG+ ? from.kind === "artifact"+ : from.kind === "added" && mark.mcid === from.element.mcid,+ );}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/retagObjects.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/retagObjects.tsnew file mode 100644index 0000000000..94cbee2df8--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/retagObjects.ts@@ -0,0 +1,40 @@+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import {+ addTagMark,+ removeTagMark,+ type TagMark,+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";++/** A page object to retag, and the marks it loses. */+export interface ObjectRetag {+ ptr: number;+ dropped: readonly TagMark[];+}++/** Replace the object's dropped marks with `tag`. */+export function retagObject(+ doc: EditorDocument,+ object: ObjectRetag,+ tag: TagMark,+): void {+ for (const dropped of [...object.dropped].reverse()) {+ if (!removeTagMark(doc.module, object.ptr, dropped.name)) {+ throw new Error("PDFium could not remove a tag");+ }+ }+ if (!addTagMark(doc.module, doc.docPtr, object.ptr, tag)) {+ throw new Error("PDFium could not tag the content");+ }+}++/** Undo retagObject, which gave the object a tag named `name`. Best effort. */+export function restoreObject(+ doc: EditorDocument,+ object: ObjectRetag,+ name: string,+): void {+ removeTagMark(doc.module, object.ptr, name);+ for (const dropped of object.dropped) {+ addTagMark(doc.module, doc.docPtr, object.ptr, dropped);+ }+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsxindex b76e061e6b..858ac36518 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx@@ -88,14 +88,15 @@ export function EditorSidebar({[editorDocument],);const imageSelected = controller.imageAccessibility !== null;+ const artifactTextSelected = controller.textTag?.kind === "artifact";// Counts and Next cover only pages already read, which is just the first few- // until the rest scroll into view.+ // until the rest scroll into view; so do an artifact's matches on other pages.useEffect(() => {- if (!reviewingAccessibility || (tab !== "document" && !imageSelected)) {- return;- }+ const reviewing =+ reviewingAccessibility && (tab === "document" || imageSelected);+ if (!reviewing && !(ACCESSIBILITY_EDITING && artifactTextSelected)) return;return readAllPagesInBackground(store);- }, [reviewingAccessibility, tab, imageSelected, store]);+ }, [reviewingAccessibility, tab, imageSelected, artifactTextSelected, store]);const setMarkedTagged = useCallback((marked: boolean) => store.dispatch(new SetMarkedTaggedCommand(marked)),[store],diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsxindex cca9874ee1..f3959809aa 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx@@ -81,6 +81,7 @@ export function SelectionInspector({onSetTag={controller.onSetTextTag}inner={controller.innerTextTags}language={controller.textLanguage}+ otherPages={controller.textOtherPages}/>)}{ACCESSIBILITY_EDITING && controller.imageAccessibility && (diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.test.tsxindex 9207278399..b07cbf44c1 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.test.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.test.tsx@@ -30,6 +30,7 @@ function tagShown(tag: TextTag): HTMLElement {onSetTag={vi.fn()}inner={NO_INNER}language={null}+ otherPages={null}/></MantineProvider>,);@@ -40,6 +41,7 @@ const tagged = (role: string): TextTag => ({kind: "tagged",block: structureRole(role),cannotRetag: "not-text",+ canBeArtifact: false,});describe("TextAccessibilitySection", () => {@@ -58,7 +60,14 @@ describe("TextAccessibilitySection", () => {});it.each([- [{ kind: "artifact" } as const, "artifactText"],+ [+ { kind: "artifact", furniture: null, taggable: false } as const,+ "artifactText",+ ],+ [+ { kind: "artifact", furniture: "PageNum", taggable: false } as const,+ "furniture.pageNumber",+ ],[{ kind: "untagged", documentTagged: true, taggable: false } as const,"untaggedBadge",@@ -68,7 +77,10 @@ describe("TextAccessibilitySection", () => {"untaggedDocument",],[{ kind: "unknown" } as const, "unknownTag"],- [{ kind: "mixed", settable: false } as const, "mixedTags"],+ [+ { kind: "mixed", settable: false, canBeArtifact: false } as const,+ "mixedTags",+ ],])("explains text with no element (%o)", (tag, message) => {expect(tagShown(tag)).toHaveTextContent(`${KEY}.${message}`);});@@ -78,10 +90,16 @@ describe("TextAccessibilitySection", () => {render(<MantineProvider env="test"><TextAccessibilitySection- tag={{ kind: "tagged", block: structureRole("P"), cannotRetag: null }}+ tag={{+ kind: "tagged",+ block: structureRole("P"),+ cannotRetag: null,+ canBeArtifact: true,+ }}onSetTag={onRetag}inner={NO_INNER}language={null}+ otherPages={null}/></MantineProvider>,);@@ -92,15 +110,136 @@ describe("TextAccessibilitySection", () => {expect(onRetag).toHaveBeenCalledWith("Code");});+ it("offers making the text decorative", () => {+ const onSetTag = vi.fn();+ render(+ <MantineProvider env="test">+ <TextAccessibilitySection+ tag={{+ kind: "untagged",+ documentTagged: true,+ taggable: true,+ }}+ onSetTag={onSetTag}+ inner={NO_INNER}+ language={null}+ otherPages={null}+ />+ </MantineProvider>,+ );+ fireEvent.click(screen.getByRole("textbox", { name: `${KEY}.tagLabel` }));+ fireEvent.click(screen.getByText(`${KEY}.artifactText`));+ expect(onSetTag).toHaveBeenCalledWith({ artifact: null });+ });++ it("offers marking the text as page furniture", () => {+ const onSetTag = vi.fn();+ render(+ <MantineProvider env="test">+ <TextAccessibilitySection+ tag={{ kind: "untagged", documentTagged: true, taggable: true }}+ onSetTag={onSetTag}+ inner={NO_INNER}+ language={null}+ otherPages={null}+ />+ </MantineProvider>,+ );+ fireEvent.click(screen.getByRole("textbox", { name: `${KEY}.tagLabel` }));+ fireEvent.click(screen.getByText(`${KEY}.furniture.footer`));+ expect(onSetTag).toHaveBeenCalledWith({ artifact: "Footer" });+ });++ it("shows decorative text as decorative, and offers it a type again", () => {+ const onSetTag = vi.fn();+ render(+ <MantineProvider env="test">+ <TextAccessibilitySection+ tag={{ kind: "artifact", furniture: null, taggable: true }}+ onSetTag={onSetTag}+ inner={NO_INNER}+ language={null}+ otherPages={null}+ />+ </MantineProvider>,+ );+ const input = screen.getByRole("textbox", { name: `${KEY}.tagLabel` });+ expect(input).toHaveValue(`${KEY}.artifactText`);+ fireEvent.click(input);+ fireEvent.click(screen.getByText(`${KEY}.tagName.paragraph`));+ expect(onSetTag).toHaveBeenCalledWith("P");+ });++ it("shows page furniture by its kind, and offers it another", () => {+ const onSetTag = vi.fn();+ render(+ <MantineProvider env="test">+ <TextAccessibilitySection+ tag={{ kind: "artifact", furniture: "Header", taggable: true }}+ onSetTag={onSetTag}+ inner={NO_INNER}+ language={null}+ otherPages={null}+ />+ </MantineProvider>,+ );+ const input = screen.getByRole("textbox", { name: `${KEY}.tagLabel` });+ expect(input).toHaveValue(`${KEY}.furniture.header`);+ fireEvent.click(input);+ fireEvent.click(screen.getByText(`${KEY}.furniture.watermark`));+ expect(onSetTag).toHaveBeenCalledWith({ artifact: "Watermark" });+ });++ it("does not offer decorative where the text cannot become an artifact", () => {+ render(+ <MantineProvider env="test">+ <TextAccessibilitySection+ tag={{+ kind: "tagged",+ block: structureRole("P"),+ cannotRetag: null,+ canBeArtifact: false,+ }}+ onSetTag={vi.fn()}+ inner={NO_INNER}+ language={null}+ otherPages={null}+ />+ </MantineProvider>,+ );+ fireEvent.click(screen.getByRole("textbox", { name: `${KEY}.tagLabel` }));+ expect(+ screen.getByRole("option", { name: `${KEY}.artifactText` }),+ ).toHaveAttribute("data-combobox-disabled", "true");+ });++ it("offers giving matching text on other pages the artifact's kind", () => {+ const onApply = vi.fn();+ render(+ <MantineProvider env="test">+ <TextAccessibilitySection+ tag={{ kind: "artifact", furniture: "Footer", taggable: true }}+ onSetTag={vi.fn()}+ inner={NO_INNER}+ language={null}+ otherPages={{ pages: 3, onApply }}+ />+ </MantineProvider>,+ );+ fireEvent.click(screen.getByTestId("pdf-editor-text-tag-other-pages"));+ expect(onApply).toHaveBeenCalled();+ });+it("offers a picker for runs tagged differently, set on all of them", () => {const onSetTag = vi.fn();render(<MantineProvider env="test"><TextAccessibilitySection- tag={{ kind: "mixed", settable: true }}+ tag={{ kind: "mixed", settable: true, canBeArtifact: true }}onSetTag={onSetTag}inner={NO_INNER}language={null}+ otherPages={null}/></MantineProvider>,);@@ -119,10 +258,12 @@ describe("TextAccessibilitySection", () => {kind: "tagged",block: structureRole("Callout"),cannotRetag: null,+ canBeArtifact: true,}}onSetTag={vi.fn()}inner={NO_INNER}language={null}+ otherPages={null}/></MantineProvider>,);@@ -224,6 +365,7 @@ describe("TextAccessibilitySection", () => {onSetTag={vi.fn()}inner={innerControl()}language={{ language: undefined, onSet: vi.fn() }}+ otherPages={null}/></MantineProvider>,);@@ -316,10 +458,16 @@ function renderSection(render(<MantineProvider env="test"><TextAccessibilitySection- tag={{ kind: "tagged", block: structureRole("P"), cannotRetag: null }}+ tag={{+ kind: "tagged",+ block: structureRole("P"),+ cannotRetag: null,+ canBeArtifact: true,+ }}onSetTag={vi.fn()}inner={inner}language={language}+ otherPages={null}/></MantineProvider>,);diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsxindex 6ac9aa742f..5823a99429 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsx@@ -2,6 +2,7 @@ import type { TFunction } from "i18next";import { useTranslation } from "react-i18next";import { Box, Group, Stack } from "@mantine/core";import { ActionIcon } from "@editor/ui/ActionIcon";+import { Button } from "@editor/ui/Button";import { Icon } from "@editor/ui/Icon";import { Select } from "@editor/ui/Select";import {@@ -10,18 +11,26 @@ import {SectionLabel,StatRow,} from "@editor/tools/pdfTextEditor/components/inspector/InspectorPrimitives";+import {+ FURNITURE,+ type Furniture,+} from "@editor/tools/pdfTextEditor/model/artifactKind";import { TEXT_BLOCK_TYPES } from "@editor/tools/pdfTextEditor/model/PageStructure";import type {StructureRole,StructureType,} from "@editor/tools/pdfTextEditor/model/structureTypes";import {+ canBeArtifact,canSetTextTag,+ canTypeText,type InnerTag,type TextTag,+ type TextTagChoice,} from "@editor/tools/pdfTextEditor/util/textAccessibility";import type {InnerTagsControl,+ OtherPagesControl,TextLanguageControl,} from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";import { LanguagePicker } from "@editor/tools/pdfTextEditor/components/inspector/LanguagePicker";@@ -30,8 +39,8 @@ import { privateContentClassName } from "@editor/components/shared/privateConten/*** What the selected text is tagged as and the language it is read in, with- * pickers to change them: retagging its block, or giving untagged text an- * element of its own. Beneath them, the tags marking parts of the text, and+ * pickers to change them: retagging its block, giving untagged text an+ * element of its own, or making it an artifact. Beneath them, the tags marking parts of the text, and* pickers for characters selected in it. With several runs selected, the tag* they share and their language.*/@@ -40,11 +49,13 @@ export function TextAccessibilitySection({onSetTag,inner,language,+ otherPages,}: {tag: TextTag | null;- onSetTag: (type: StructureType) => void;+ onSetTag: (choice: TextTagChoice) => void;inner: InnerTagsControl;language: TextLanguageControl | null;+ otherPages: OtherPagesControl | null;}) {const { t } = useTranslation();return (@@ -54,6 +65,7 @@ export function TextAccessibilitySection({</SectionLabel><Stack gap="xs">{tag && <TagField tag={tag} onSetTag={onSetTag} />}+ {otherPages && <OtherPagesButton control={otherPages} />}{language && <TextLanguageField control={language} />}{tag && (<>@@ -72,19 +84,17 @@ function TagField({onSetTag,}: {tag: TextTag;- onSetTag: (type: StructureType) => void;+ onSetTag: (choice: TextTagChoice) => void;}) {const { t } = useTranslation();const label = t("pdfTextEditor.inspector.accessibility.tagLabel", "Tag");return canSetTextTag(tag) ? (<Field label={label}>- <TagPicker- types={TEXT_BLOCK_TYPES}- current={tag.kind === "tagged" ? tag.block : null}+ <BlockTagPicker+ tag={tag}placeholder={tagText(t, tag)}onSetTag={onSetTag}label={label}- testId="pdf-editor-text-tag-picker"/></Field>) : (@@ -95,6 +105,101 @@ function TagField({);}+/** Select values for artifact choices: a structure type never starts with a lower-case letter. */+const ARTIFACT_VALUE = "artifact:";++function BlockTagPicker({+ tag,+ placeholder,+ onSetTag,+ label,+}: {+ tag: TextTag;+ placeholder: string;+ onSetTag: (choice: TextTagChoice) => void;+ label: string;+}) {+ const { t } = useTranslation();+ const typed = canTypeText(tag);+ const artifactable = canBeArtifact(tag);+ const artifacts = [null, ...FURNITURE];+ const choices = new Map<string, TextTagChoice>([+ ...TEXT_BLOCK_TYPES.map((type) => [type, type] as const),+ ...artifacts.map(+ (artifact) => [artifactValue(artifact), { artifact }] as const,+ ),+ ]);+ const options = [+ {+ group: t("pdfTextEditor.inspector.accessibility.contentGroup", "Content"),+ options: TEXT_BLOCK_TYPES.map((type) => ({+ value: type,+ label: typeName(t, type),+ disabled: !typed,+ })),+ },+ {+ group: t(+ "pdfTextEditor.inspector.accessibility.artifactGroup",+ "Skipped by screen readers",+ ),+ options: artifacts.map((artifact) => ({+ value: artifactValue(artifact),+ label: artifactName(t, artifact),+ disabled: !artifactable,+ })),+ },+ ];+ const current =+ tag.kind === "artifact"+ ? artifactValue(tag.furniture)+ : (TEXT_BLOCK_TYPES.find(+ (type) => tag.kind === "tagged" && type === tag.block.type,+ ) ?? null);+ return (+ <div data-testid="pdf-editor-text-tag-picker">+ <Select+ inputSize="sm"+ options={options}+ value={current}+ placeholder={placeholder}+ onChange={(value) => {+ const picked = value === null ? undefined : choices.get(value);+ if (picked) onSetTag(picked);+ }}+ aria-label={label}+ />+ </div>+ );+}++function artifactValue(furniture: Furniture | null): string {+ return `${ARTIFACT_VALUE}${furniture ?? ""}`;+}++/** Gives matching text on other pages the selected artifact's kind. */+function OtherPagesButton({ control }: { control: OtherPagesControl }) {+ const { t } = useTranslation();+ return (+ <Button+ size="sm"+ variant="secondary"+ accent="neutral"+ fullWidth+ justify="start"+ leftSection={<Icon name="copy" size={20} />}+ onClick={control.onApply}+ data-testid="pdf-editor-text-tag-other-pages"+ >+ {t(+ "pdfTextEditor.inspector.accessibility.applyToOtherPages",+ "Apply to {{count}} other pages",+ { count: control.pages },+ )}+ </Button>+ );+}+/** The language the selected text's blocks are read in; "Mixed" when they differ. */function TextLanguageField({ control }: { control: TextLanguageControl }) {const { t } = useTranslation();@@ -380,10 +485,7 @@ function statusText(): string {switch (tag.kind) {case "artifact":- return t(- "pdfTextEditor.inspector.accessibility.artifactText",- "Decorative",- );+ return artifactName(t, tag.furniture);case "untagged":return tag.documentTagged? t("pdfTextEditor.inspector.accessibility.untaggedBadge", "Not tagged")@@ -401,6 +503,36 @@ function statusText(}}+function artifactName(t: TFunction, furniture: Furniture | null): string {+ switch (furniture) {+ case null:+ return t(+ "pdfTextEditor.inspector.accessibility.artifactText",+ "Decorative",+ );+ case "Header":+ return t(+ "pdfTextEditor.inspector.accessibility.furniture.header",+ "Header",+ );+ case "Footer":+ return t(+ "pdfTextEditor.inspector.accessibility.furniture.footer",+ "Footer",+ );+ case "PageNum":+ return t(+ "pdfTextEditor.inspector.accessibility.furniture.pageNumber",+ "Page number",+ );+ case "Watermark":+ return t(+ "pdfTextEditor.inspector.accessibility.furniture.watermark",+ "Watermark",+ );+ }+}+/** 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) {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useBulkTagging.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useBulkTagging.tsindex a8751911ee..d80c120451 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useBulkTagging.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useBulkTagging.ts@@ -14,6 +14,7 @@ import type {EditorStore,EditorViewState,} from "@editor/tools/pdfTextEditor/store/EditorStore";+import { recogniseFurniture } from "@editor/tools/pdfTextEditor/util/pageFurniture";/** Work this long before letting the browser paint the progress. */const SLICE_MS = 50;@@ -66,7 +67,9 @@ export function useBulkTagging(/*** Read and tag every page behind the loading overlay, a slice at a time so* its progress paints, then mark the document fully tagged and record it all- * as one undo step. Every page tagged is untagged again when one fails.+ * as one undo step. Every page is read before any is tagged, so text repeated+ * across pages can be recognised as page furniture. Every page tagged is+ * untagged again when one fails.*/export async function tagAllPages(store: EditorStore): Promise<void> {const doc = store.document;@@ -76,22 +79,40 @@ export async function tagAllPages(store: EditorStore): Promise<void> {"pdfTextEditor.inspector.accessibility.tagging","Tagging pages",);+ const total = pageIndices.length * 2;const applied: TagPageContentCommand[] = [];store.setLoading(true);try {- let sliceStart = -Infinity;+ const slices = slicer(() => store.document === doc);for (const [done, pageIndex] of pageIndices.entries()) {- if (performance.now() - sliceStart > SLICE_MS) {- store.setProgress({ stage, current: done, total: pageIndices.length });- await new Promise((resolve) => setTimeout(resolve, 0));- if (store.document !== doc) return;- sliceStart = performance.now();+ if (+ !(await slices(() =>+ store.setProgress({ stage, current: done, total }),+ ))+ ) {+ return;}const page = doc.page(pageIndex);if (!page.loaded)PdfiumTextReader.populate(doc, page, store.groupingMode);+ }+ const furniture = recogniseFurniture(+ pageIndices.map((pageIndex) => {+ const { display, runs, images } = doc.page(pageIndex);+ return { pageIndex, display, runs, images };+ }),+ doc.pageCount,+ );+ for (const [done, pageIndex] of pageIndices.entries()) {+ const current = pageIndices.length + done;+ if (!(await slices(() => store.setProgress({ stage, current, total })))) {+ return;+ }if (!hasUntaggedContent(doc, pageIndex)) continue;- const command = new TagPageContentCommand({ pageIndex });+ const command = new TagPageContentCommand({+ pageIndex,+ furniture: furniture.get(pageIndex),+ });command.apply(doc);applied.push(command);}@@ -115,3 +136,21 @@ export async function tagAllPages(store: EditorStore): Promise<void> {if (store.document === doc) store.setLoading(false);}}++/**+ * A step that yields to the browser once a slice of work has run, after+ * `report`ing progress, so the progress paints. Resolves false when `current`+ * no longer holds, and the work should stop.+ */+function slicer(+ current: () => boolean,+): (report: () => void) => Promise<boolean> {+ let sliceStart = -Infinity;+ return async (report) => {+ if (performance.now() - sliceStart <= SLICE_MS) return true;+ report();+ await new Promise((resolve) => setTimeout(resolve, 0));+ sliceStart = performance.now();+ return current();+ };+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsxindex f2740ba6e4..c278a2b3a4 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsx@@ -57,6 +57,7 @@ function makeDoc(encrypted = false): EditorDocument {loadedPages: () => [],documentLanguage: () => null,languagesInUse: () => [],+ onArtifactKinds: () => () => {},dispose: vi.fn(),} as unknown as EditorDocument;}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.test.tsxnew file mode 100644index 0000000000..5a7a56ccc2--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.test.tsx@@ -0,0 +1,128 @@+import { readFile } from "node:fs/promises";+import { createRequire } from "node:module";+import { act, renderHook } from "@testing-library/react";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import {+ ensureAllPagesRead,+ ensurePageRead,+} from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";+import {+ setTextTagCommand,+ useTextAccessibility,+} from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";+import { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";+import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";+import { textTag } from "@editor/tools/pdfTextEditor/util/textAccessibility";+import {+ buildClassicPdf,+ streamBody,+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";++vi.mock("@editor/constants/featureFlags", () => ({+ ACCESSIBILITY_EDITING: true,+}));++/** Three untagged pages, each with the same footer. */+function footedPdf(): Uint8Array {+ const pages = [10, 12, 14];+ return buildClassicPdf(+ [+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },+ {+ num: 2,+ body: `<< /Type /Pages /Kids [${pages.map((p) => `${p} 0 R`).join(" ")}] /Count 3 >>`,+ },+ {+ num: 3,+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ },+ ...pages.flatMap((page, i) => [+ {+ num: page,+ body:+ `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents ${page + 1} 0 R ` ++ "/Resources << /Font << /F1 3 0 R >> >> >>",+ },+ {+ num: page + 1,+ body: streamBody(+ "",+ `BT /F1 10 Tf 72 400 Td (Body ${i}) Tj ET\n` ++ "BT /F1 10 Tf 72 40 Td (Confidential) Tj ET",+ ),+ },+ ]),+ ],+ 1,+ );+}++beforeAll(async () => {+ const wasmBytes = await readFile(+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),+ );+ vi.stubGlobal(+ "fetch",+ vi.fn(+ async () =>+ new Response(wasmBytes, {+ headers: { "Content-Type": "application/wasm" },+ }),+ ),+ );+});++afterAll(() => {+ vi.unstubAllGlobals();+});++describe("useTextAccessibility other pages", () => {+ it("offers a footer's matches on other pages, and gives them its kind", async () => {+ const store = new EditorStore();+ const doc = await EditorDocument.open(footedPdf());+ await store.setDocument(doc);+ store.publishPages(+ [0, 1, 2].map((pageIndex): PageSnapshot => {+ const page = doc.page(pageIndex);+ return {+ pageIndex,+ width: page.width,+ height: page.height,+ dirty: false,+ revision: 0,+ runs: [],+ images: [],+ shapes: [],+ display: page.display.toData(),+ };+ }),+ );+ ensurePageRead(store, 0);+ const footer = store+ .getState()+ .pages[0].runs.find((r) => r.text.includes("Confidential"))!;+ store.dispatch(+ setTextTagCommand(doc, [{ run: footer, tag: textTag(doc, footer) }], {+ artifact: "Footer",+ })!,+ );+ store.selection.selectOne(footer.id);+ ensureAllPagesRead(store);++ const { result, rerender } = renderHook(() =>+ useTextAccessibility(store, store.getState(), store.selection.value),+ );+ expect(result.current.otherPages?.pages).toBe(2);+ act(() => result.current.otherPages!.onApply());+ rerender();+ expect(result.current.otherPages).toBeNull();+ const kinds = store+ .getState()+ .pages.flatMap((page) => page.runs)+ .filter((r) => r.text.includes("Confidential"))+ .map((r) => r.furniture);+ expect(kinds).toEqual(["Footer", "Footer", "Footer"]);+ store.dispose();+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.tsindex 04cfecc361..569cfc3f02 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts@@ -4,6 +4,7 @@ import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";import { CompositeCommand } from "@editor/tools/pdfTextEditor/commands/CompositeCommand";import { RetagInnerCommand } from "@editor/tools/pdfTextEditor/commands/RetagInnerCommand";import { RetagTextCommand } from "@editor/tools/pdfTextEditor/commands/RetagTextCommand";+import { SetDecorativeCommand } from "@editor/tools/pdfTextEditor/commands/SetDecorativeCommand";import { SetInnerLanguageCommand } from "@editor/tools/pdfTextEditor/commands/SetInnerLanguageCommand";import {SetTextLanguageCommand,@@ -14,6 +15,7 @@ import {rangeTagTypes,TagTextRangeCommand,} from "@editor/tools/pdfTextEditor/commands/TagTextRangeCommand";+import type { Furniture } from "@editor/tools/pdfTextEditor/model/artifactKind";import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";import type { TextLanguage } from "@editor/tools/pdfTextEditor/model/languageTag";import type {@@ -26,12 +28,16 @@ import type {TextRunSnapshot,} from "@editor/tools/pdfTextEditor/types";import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import { ensureAllPagesRead } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";+import { matchingRuns } from "@editor/tools/pdfTextEditor/util/pageFurniture";import {+ canBeArtifact,innerTags,sharedTextTag,textTag,type InnerTag,type TextTag,+ type TextTagChoice,} from "@editor/tools/pdfTextEditor/util/textAccessibility";/** The tags marking parts of the selected text, and the selection inside it. */@@ -51,6 +57,13 @@ export interface InnerTagsControl {onLanguageSelection: ((lang: string) => void) | null;}+/** Matching text on other pages that the selected artifact's kind can be given, and a way to give it. */+export interface OtherPagesControl {+ /** How many other pages show such text. */+ pages: number;+ onApply: () => void;+}+/** The language the selected text's blocks are read in, and a way to change it. */export interface TextLanguageControl {/** The language the blocks share; undefined when they differ. */@@ -106,27 +119,49 @@ export function useTextAccessibility(const tags = innerTags(doc, only);const range = selection.textRange;const picksTag = tags.some((t) => sameRange(t, range));+ const offersNew = range && !picksTag && shared.kind !== "artifact";return {run: only,targets,tag: shared,inner: tags,- newTagTypes: range && !picksTag ? tagTypesFor(doc, only, range) : null,+ newTagTypes: offersNew ? tagTypesFor(doc, only, range) : null,};}, [store, state.pages, selection]);+ const otherPages = useMemo((): OtherPagesControl | null => {+ const doc = store.document;+ if (!doc || !run || tag?.kind !== "artifact") return null;+ const pending = pendingMatches(doc, state.pages, run, tag.furniture);+ if (pending.length === 0) return null;+ return {+ pages: new Set(pending.map((target) => target.run.pageIndex)).size,+ onApply: () => {+ // A page not yet scrolled to would otherwise keep its furniture untagged.+ ensureAllPagesRead(store);+ const command = setTextTagCommand(+ doc,+ pendingMatches(doc, store.getState().pages, run, tag.furniture),+ { artifact: tag.furniture },+ );+ if (command) store.dispatch(command);+ },+ };+ }, [store, state.pages, run, tag]);+const activeInner = useMemo(() => inner.findIndex((t) => sameRange(t, selection.textRange)),[inner, selection.textRange],);/**- * Retags each selected run's block, or gives its untagged text an element of- * its own, as one undo step.+ * Retags each selected run's block, gives its untagged text an element of+ * its own, or makes it an artifact, as one undo step.*/const setTag = useCallback(- (type: StructureType) => {- const command = setTextTagCommand(targets, type);+ (choice: TextTagChoice) => {+ const doc = store.document;+ const command = doc ? setTextTagCommand(doc, targets, choice) : null;if (command) store.dispatch(command);},[store, targets],@@ -261,7 +296,7 @@ export function useTextAccessibility(// state.pages: a language change republishes the pages, not the targets.}, [store, languageTargets, state.pages]);- return { tag, setTag, inner: innerControl, language };+ return { tag, setTag, inner: innerControl, language, otherPages };}/**@@ -285,54 +320,113 @@ function textLanguageTargets(const runs = state.pages.flatMap((page) => page.runs).filter((r) => ids.has(r.id));- const targets = runs.flatMap((r) =>- r.mcid !== undefined &&- !r.inForm &&- doc.structure(r.pageIndex).cannotSetLanguage(r.mcid) === null+ const targets = runs.flatMap((r) => {+ const structure = doc.structure(r.pageIndex);+ return r.mcid !== undefined &&+ !r.inForm &&+ structure.cannotSetLanguage(r.mcid) === null &&+ !structure.decorative(r.mcid)? [{ pageIndex: r.pageIndex, mcid: r.mcid }]- : [],- );+ : [];+ });return targets.length > 0 && targets.length === ids.size ? targets : null;}/**- * One undo step setting `type` on every run whose tag can be set; null when+ * One undo step setting `choice` on every run whose tag can be set; null when* none can.*/export function setTextTagCommand(+ doc: EditorDocument,targets: readonly { run: TextRunSnapshot; tag: TextTag }[],- type: StructureType,+ choice: TextTagChoice,): Command | null {const commands = targets.flatMap(({ run, tag }) => {- const command = runTagCommand(run, tag, type);+ const command =+ typeof choice === "string"+ ? typeCommand(run, tag, choice)+ : artifactCommand(doc, run, tag, choice.artifact);return command ? [command] : [];});if (commands.length <= 1) return commands[0] ?? null;return new CompositeCommand(commands);}-function runTagCommand(+/**+ * Text in the file's own element, or made an artifact through it, becomes an+ * artifact of `furniture` through that element; any other is retagged.+ */+function artifactCommand(+ doc: EditorDocument,+ run: TextRunSnapshot,+ tag: TextTag,+ furniture: Furniture | null,+): Command | null {+ const { pageIndex, mcid } = run;+ if (!canBeArtifact(tag)) return null;+ if (tag.kind === "artifact" && tag.furniture === furniture) return null;+ const retag = new TagTextCommand({+ pageIndex,+ runId: run.id,+ as: { artifact: furniture },+ });+ const throughElement =+ mcid !== undefined &&+ !run.artifact &&+ (tag.kind === "artifact" ||+ (tag.kind === "tagged" && !doc.structure(pageIndex).isAdded(mcid)));+ if (!throughElement) return retag;+ return new SetDecorativeCommand({+ pageIndex,+ mcid,+ decorative: true,+ furniture,+ });+}++function typeCommand(run: TextRunSnapshot,tag: TextTag,type: StructureType,): Command | null {- if (tag.kind === "tagged" && run.mcid !== undefined) {- return new RetagTextCommand({- pageIndex: run.pageIndex,- mcid: run.mcid,- type,- });+ const { pageIndex, mcid } = run;+ if (tag.kind === "tagged") {+ if (tag.cannotRetag !== null || mcid === undefined) return null;+ return new RetagTextCommand({ pageIndex, mcid, type });}- if (tag.kind === "untagged" && tag.taggable) {- return new TagTextCommand({- pageIndex: run.pageIndex,- runId: run.id,- as: type,- });+ if (tag.kind === "untagged" || tag.kind === "artifact") {+ if (!tag.taggable) return null;+ // An artifact by mark has no MCID; one by the session's decorative mark+ // keeps its element, which unmarking returns to the tree.+ if (mcid === undefined) {+ return new TagTextCommand({ pageIndex, runId: run.id, as: type });+ }+ return new CompositeCommand([+ new SetDecorativeCommand({ pageIndex, mcid, decorative: false }),+ new RetagTextCommand({ pageIndex, mcid, type }),+ ]);}return null;}+/**+ * The text on pages other than `run`'s that matches it as page furniture+ * does, and that marking as `furniture` would change.+ */+function pendingMatches(+ doc: EditorDocument,+ pages: EditorViewState["pages"],+ run: TextRunSnapshot,+ furniture: Furniture | null,+): { run: TextRunSnapshot; tag: TextTag }[] {+ return matchingRuns(pages, run.pageIndex, run).flatMap(({ run: match }) => {+ const tag = textTag(doc, match);+ return artifactCommand(doc, match, tag, furniture)+ ? [{ run: match, tag }]+ : [];+ });+}+function sameRange(a: TextRange, b: TextRange | null): boolean {return b !== null && a.start === b.start && a.end === b.end;}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.tsindex 6f77b5fa3d..783e76f455 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts@@ -530,6 +530,7 @@ export function useToolbarController(onSetTextTag: textA11y.setTag,innerTextTags: textA11y.inner,textLanguage: textA11y.language,+ textOtherPages: textA11y.otherPages,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.tsindex d67787b90c..6519c8d5a2 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts@@ -19,7 +19,19 @@ import {readPageStructure,readString,} from "@editor/tools/pdfTextEditor/pdfium/PdfiumStructureReader";-import { carriedMcids } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";+import {+ artifactMarkRefs,+ carriedMcids,+ forgetArtifactKinds,+ forgetArtifactMarks,+ registerArtifactKinds,+ type ArtifactMarkRef,+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";+import {+ readFileArtifactKinds,+ refreshArtifactTags,+} from "@editor/tools/pdfTextEditor/model/fileArtifactKinds";+import { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";import {readFileStructure,type FileStructure,@@ -44,6 +56,8 @@ import { releaseScratch } from "@editor/tools/pdfTextEditor/util/wasmScratch";// full copy of the file alive for the session.const MAX_RETAINED_BYTES = 64 * 1024 * 1024;const EMPTY = new Uint8Array(0);+/** How long the file stays parsed after the last artifact kind read, for the pages read next. */+const RAW_PDF_GRACE_MS = 10_000;export class EditorDocument {readonly module: WrappedPdfiumModule;@@ -83,6 +97,21 @@ export class EditorDocument {private formEnvPtr: number | null = null;private formEnvTried = false;private readonly formLoadedPages = new Set<number>();+ /** By page index, as each page is first read: the artifact marks whose kinds only the file names. */+ private readonly artifactMarks = new Map<number, ArtifactMarkRef[]>();+ private readonly artifactKindReads = new Map<number, Promise<boolean>>();+ private readonly artifactKindListeners = new Set<+ (pageIndex: number) => void+ >();+ /**+ * The opened bytes parsed, shared by the artifact kind reads in flight and+ * dropped soon after the last: it holds a second copy of the file.+ */+ private raw: {+ pdf: Promise<RawPdf | null>;+ reads: number;+ release?: ReturnType<typeof setTimeout>;+ } | null = null;private constructor(module: WrappedPdfiumModule,@@ -192,6 +221,91 @@ export class EditorDocument {return page;}+ /**+ * Note the page's artifact marks whose kinds only the file names, and+ * start reading those kinds. Must run as the page is first read, before+ * any edit and before any of its marks is read: PdfiumTextReader.populate+ * calls it.+ */+ claimArtifactMarks(pageIndex: number): void {+ if (this.artifactMarks.has(pageIndex)) return;+ const refs = artifactMarkRefs(this.module, this.page(pageIndex).pagePtr);+ forgetArtifactMarks(+ this.module,+ refs.map((ref) => ref.ptr),+ );+ this.artifactMarks.set(pageIndex, refs);+ if (refs.length > 0) void this.loadArtifactKinds(pageIndex);+ }++ /**+ * Resolves once the kinds the file names for the page's artifacts are+ * read: true when they were, the page's runs then carrying them and each+ * onArtifactKinds listener told. Never rejects.+ */+ loadArtifactKinds(pageIndex: number): Promise<boolean> {+ this.claimArtifactMarks(pageIndex);+ let read = this.artifactKindReads.get(pageIndex);+ if (!read) {+ read = this.readArtifactKinds(pageIndex).catch(() => false);+ this.artifactKindReads.set(pageIndex, read);+ }+ return read;+ }++ /** Hear of each page whose artifact kinds have been read. Returns the unsubscribe. */+ onArtifactKinds(listener: (pageIndex: number) => void): () => void {+ this.artifactKindListeners.add(listener);+ return () => this.artifactKindListeners.delete(listener);+ }++ private async readArtifactKinds(pageIndex: number): Promise<boolean> {+ const refs = this.artifactMarks.get(pageIndex) ?? [];+ if (refs.length === 0 || this.openedBytes.length === 0) return false;+ const kinds = await this.withRawPdf((pdf) => {+ const pageNum = pdf.encrypted ? null : pdf.pageNumberAt(pageIndex);+ return pageNum === null+ ? Promise.resolve(null)+ : readFileArtifactKinds(pdf, pageNum, refs);+ });+ if (!kinds || this._disposed) return false;+ const page = this.page(pageIndex);+ // Only marks still on the page: one an edit freed meanwhile may be+ // another page's by now.+ const live = new Set(+ artifactMarkRefs(this.module, page.pagePtr).map((ref) => ref.ptr),+ );+ registerArtifactKinds(+ this.module,+ this,+ new Map([...kinds].filter(([ptr]) => live.has(ptr))),+ );+ refreshArtifactTags(this.module, page);+ page.bumpRevision();+ for (const listener of this.artifactKindListeners) listener(pageIndex);+ return true;+ }++ private async withRawPdf<T>(+ read: (pdf: RawPdf) => Promise<T | null>,+ ): Promise<T | null> {+ this.raw ??= { pdf: RawPdf.parse(this.openedBytes), reads: 0 };+ const raw = this.raw;+ clearTimeout(raw.release);+ raw.reads += 1;+ try {+ const pdf = await raw.pdf;+ return pdf ? await read(pdf) : null;+ } finally {+ raw.reads -= 1;+ if (raw.reads === 0 && !this._disposed) {+ raw.release = setTimeout(() => {+ if (this.raw === raw) this.raw = null;+ }, RAW_PDF_GRACE_MS);+ }+ }+ }+/*** The page's structure elements and their unsaved edits.*/@@ -221,20 +335,22 @@ export class EditorDocument {}/**- * 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.+ * The headings in reading order, the session's retags, decorative marks+ * 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 }) => ({+ const blocks: OutlineBlock[] = this.fileStructure.blocks+ .filter(+ ({ pageIndex, mcids }) => !this.markedDecorative(pageIndex, mcids),+ )+ .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!;@@ -258,6 +374,12 @@ export class EditorDocument {);}+ /** True when the session marked the block owning `mcids` decorative. */+ private markedDecorative(pageIndex: number | null, mcids: number[]): boolean {+ if (pageIndex === null || mcids.length === 0) return false;+ return this.structureCache.get(pageIndex)?.decorative(mcids[0]) ?? false;+ }+/** 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;@@ -651,6 +773,10 @@ export class EditorDocument {font.dispose();}this.ownedFonts.clear();+ clearTimeout(this.raw?.release);+ this.raw = null;+ this.artifactKindListeners.clear();+ forgetArtifactKinds(this.module, this);closeDocAndFreeBuffer(this.module, this.docPtr);releaseScratch(this.module);}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.tsindex 86b0b0dc87..56400bc127 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts@@ -1,3 +1,4 @@+import type { Furniture } from "@editor/tools/pdfTextEditor/model/artifactKind";import type {StructureRole,StructureType,@@ -113,6 +114,8 @@ export interface StructureElementEdit {alt: string | null;/** Turn the element's content into an artifact and drop the element. */decorative: boolean;+ /** The page furniture the artifact is, when `decorative`; absent for a plain one. */+ furniture?: Furniture;}/**@@ -130,8 +133,16 @@ export type ReadOnlyReason = "encrypted" | "unreadable";/** Why content cannot take a description. */export type DescriptionBlocker = "untagged" | "not-figure" | ReadOnlyReason;-/** Why content cannot be marked decorative. */-export type DecorativeBlocker = DescriptionBlocker | "mixed-content";+/**+ * Why content cannot be marked decorative. "not-content" is an element that+ * is neither a figure nor a block of text, such as a list item, whose+ * structure would be left broken without it.+ */+export type DecorativeBlocker =+ | "untagged"+ | "not-content"+ | "mixed-content"+ | ReadOnlyReason;/** 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 = [@@ -375,11 +386,33 @@ export class PageStructure {return null;}- /** Why the content `mcid` marks cannot be marked decorative, or null when it can. */+ /**+ * Why the content `mcid` marks cannot be marked decorative, or null when it+ * can: a figure or formula, or one of the file's blocks of text, owning+ * nothing but marked content.+ */cannotMarkDecorative(mcid: number): DecorativeBlocker | null {- const blocker = this.cannotDescribe(mcid);- if (blocker) return blocker;- return this.element(mcid)!.onlyMarkedContent ? null : "mixed-content";+ const el = this.element(mcid);+ if (!el) return "untagged";+ if (this.readOnly) return this.readOnly;+ const describable = el.type !== null && DESCRIBABLE_TYPES.has(el.type);+ if (!describable && !this.isFileTextBlock(el)) return "not-content";+ return el.onlyMarkedContent && !this.hasCutsFrom(el)+ ? null+ : "mixed-content";+ }++ private isFileTextBlock(el: StructureElement): boolean {+ return (+ this.fileElements.has(el) &&+ el.key === el.block.key &&+ this.cannotRetag(el.mcids[0]) === null+ );+ }++ /** True when the session cut text out of `el`, which then still reads as part of it. */+ private hasCutsFrom(el: StructureElement): boolean {+ return [...this.cuts.values()].some(({ owner }) => owner === el);}/** True when the session has marked the element owning `mcid` decorative. */@@ -387,6 +420,12 @@ export class PageStructure {return this.editFor(mcid)?.decorative ?? false;}+ /** The page furniture the session marked the element owning `mcid` as; null when none. */+ furniture(mcid: number): Furniture | null {+ const edit = this.editFor(mcid);+ return (edit?.decorative && edit.furniture) || null;+ }+/** The description as it will be saved: the session's edit, else the file's. */alt(mcid: number): string | null {const el = this.element(mcid);@@ -403,18 +442,40 @@ export class PageStructure {/** Set the description, keeping any decorative mark. Throws as setEdit does. */setAlt(mcid: number, alt: string | null): void {- this.setEdit(mcid, { mcid, alt, decorative: this.decorative(mcid) });+ const edit = this.editFor(mcid);+ this.setEdit(mcid, {+ mcid,+ alt,+ decorative: edit?.decorative ?? false,+ ...(edit?.furniture && { furniture: edit.furniture }),+ });}/**- * Mark or unmark decorative, keeping the description. Throws as setEdit- * does, and for an added element, whose content is retagged instead.+ * Mark or unmark decorative, as `furniture` or a plain artifact, keeping+ * the description. Throws as setEdit does, and for an added element, whose+ * content is retagged instead.*/- setDecorative(mcid: number, decorative: boolean): void {+ setDecorative(+ mcid: number,+ decorative: boolean,+ furniture: Furniture | null = null,+ ): void {if (this.added.has(mcid)) {throw new Error(`MCID ${mcid} is an added element`);}- this.setEdit(mcid, { mcid, alt: this.alt(mcid), decorative });+ const alt = this.alt(mcid);+ if (!decorative) {+ const unchanged = alt === this.element(mcid)?.alt;+ this.setEdit(mcid, unchanged ? null : { mcid, alt, decorative });+ return;+ }+ this.setEdit(mcid, {+ mcid,+ alt,+ decorative,+ ...(furniture && { furniture }),+ });}/** Throws when no element owns `mcid`: a command must not record an edit the save cannot address. */@@ -525,6 +586,28 @@ export class PageStructure {return element;}+ /**+ * The element the session added for untagged content `mcid` marks, where+ * nothing else depends on it: not cut from another element's text, and+ * with no text cut from it. Null otherwise.+ */+ standaloneAdded(mcid: number): AddedElement | null {+ const element = this.added.get(mcid);+ if (!element || this.cuts.has(mcid) || this.hasCutsFrom(element)) {+ return null;+ }+ return this.addedElement(mcid);+ }++ /** Put back an element removeElement dropped, as standaloneAdded read it. */+ restoreElement(element: AddedElement): void {+ this.addElement(element.mcid, element.type, element.follows);+ if (element.lang !== null) {+ this.langs.set(addedKey(element.mcid), element.lang);+ }+ if (element.alt !== null) this.setAlt(element.mcid, element.alt);+ }+/** Drop an added element, its description and language, and the cut it was made by. */removeElement(mcid: number): void {const element = this.added.get(mcid);diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/TextRun.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/TextRun.tsindex 1fc5d9a220..388b34b428 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/model/TextRun.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/TextRun.ts@@ -1,4 +1,5 @@import type { ScanEditState } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";+import { furnitureOf } from "@editor/tools/pdfTextEditor/model/artifactKind";import {ARTIFACT_TAG,innermostMcid,@@ -210,8 +211,9 @@ export class TextRun {locked: this.locked || undefined,wrapWidthPt: this.wrapWidthPt ?? undefined,mcid: innermostMcid(this.tagMarks) ?? undefined,- artifact:- this.tagMarks.some((tag) => tag.name === ARTIFACT_TAG) || undefined,+ artifact: artifactMark(this.tagMarks) !== undefined || undefined,+ furniture:+ furnitureOf(artifactMark(this.tagMarks)?.artifact) ?? undefined,inForm: this.containerPtr !== 0 || undefined,};}@@ -231,3 +233,8 @@ export class TextRun {: undefined;}}++/** The innermost artifact mark: the one that says what the content is. */+function artifactMark(tags: readonly TagMark[]): TagMark | undefined {+ return tags.filter((tag) => tag.name === ARTIFACT_TAG).at(-1);+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/TextTags.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/TextTags.tsindex 96e05ad125..f7e72f50a8 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/model/TextTags.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/TextTags.ts@@ -1,3 +1,4 @@+import { sameArtifactKind } from "@editor/tools/pdfTextEditor/model/artifactKind";import type { TagMark } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";/**@@ -101,6 +102,11 @@ export function sameTags(): boolean {return (a.length === b.length &&- a.every((mark, i) => mark.name === b[i].name && mark.mcid === b[i].mcid)+ a.every(+ (mark, i) =>+ mark.name === b[i].name &&+ mark.mcid === b[i].mcid &&+ sameArtifactKind(mark.artifact, b[i].artifact),+ ));}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/artifactKind.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/artifactKind.tsnew file mode 100644index 0000000000..ccac449559--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/artifactKind.ts@@ -0,0 +1,33 @@+/**+ * What an artifact is (ISO 32000-2 14.8.2.2.2): its /Type and /Subtype, as+ * names without the slash.+ */+export interface ArtifactKind {+ type: string;+ subtype: string | null;+}++/**+ * The page furniture text can be marked as: pagination artifacts, by their+ * /Subtype. PageNum is PDF 2.0's; ISO 32000-2 allows a PDF 1.7 file+ * subtypes beyond its own.+ */+export const FURNITURE = ["Header", "Footer", "PageNum", "Watermark"] as const;+export type Furniture = (typeof FURNITURE)[number];++export function sameArtifactKind(+ a: ArtifactKind | undefined,+ b: ArtifactKind | undefined,+): boolean {+ return a?.type === b?.type && a?.subtype === b?.subtype;+}++export function furnitureKind(furniture: Furniture): ArtifactKind {+ return { type: "Pagination", subtype: furniture };+}++/** The furniture an artifact of `kind` is; null for any other artifact. */+export function furnitureOf(kind: ArtifactKind | undefined): Furniture | null {+ if (kind?.type !== "Pagination") return null;+ return FURNITURE.find((furniture) => furniture === kind.subtype) ?? null;+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/fileArtifactKinds.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/fileArtifactKinds.tsnew file mode 100644index 0000000000..3692cd4455--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/fileArtifactKinds.ts@@ -0,0 +1,85 @@+/**+ * Reading what a file's own artifacts are. PDFium reports that an artifact's+ * /Type is a name but cannot return it, so the page's content is read+ * alongside and its artifact sequences paired, in order, with the marks+ * PDFium made of them. A page whose sequences do not pair one to one is left+ * unread rather than guessed at.+ */+import { collectMemberPtrs } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";+import type { ArtifactKind } from "@editor/tools/pdfTextEditor/model/artifactKind";+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";+import {+ artifactSequences,+ type ArtifactSequence,+} from "@editor/tools/pdfTextEditor/pdfdoc/artifactSequences";+import type { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";+import {+ ARTIFACT_TAG,+ readTagMarks,+ type ArtifactMarkRef,+ type TagMark,+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";++/**+ * The kinds of the marks `refs`, as page `pageNum` of `pdf` names them, by+ * mark pointer. Null when its content cannot be read or does not pair with+ * `refs`.+ */+export async function readFileArtifactKinds(+ pdf: RawPdf,+ pageNum: number,+ refs: readonly ArtifactMarkRef[],+): Promise<Map<number, ArtifactKind> | null> {+ const sequences = await artifactSequences(pdf, pageNum);+ return sequences && pairArtifactKinds(refs, sequences);+}++/**+ * Each mark's kind from the sequence at its place in order; null unless+ * they pair one to one, each pair with as many entries and both naming a+ * /Subtype or neither.+ */+export function pairArtifactKinds(+ refs: readonly ArtifactMarkRef[],+ sequences: readonly ArtifactSequence[],+): Map<number, ArtifactKind> | null {+ if (refs.length !== sequences.length) return null;+ const kinds = new Map<number, ArtifactKind>();+ for (const [i, ref] of refs.entries()) {+ const { kind, entries } = sequences[i];+ if (ref.entries !== entries || ref.subtyped !== (kind.subtype !== null)) {+ return null;+ }+ kinds.set(ref.ptr, kind);+ }+ return kinds;+}++/**+ * Give the page's runs the kinds of their artifact marks, read after the+ * runs were: each takes the tags of a member drawn with the ones it has.+ */+export function refreshArtifactTags(m: WrappedPdfiumModule, page: Page): void {+ for (const run of page.runs) {+ const unread = run.tagMarks.some(+ (tag) => tag.name === ARTIFACT_TAG && !tag.artifact,+ );+ if (!unread || run.containerPtr !== 0) continue;+ for (const ptr of collectMemberPtrs(run)) {+ const tags = readTagMarks(m, ptr);+ if (sameMarks(tags, run.tagMarks)) {+ run.tagMarks = tags;+ break;+ }+ }+ }+}++/** Equal tags, kinds aside. */+function sameMarks(a: readonly TagMark[], b: readonly TagMark[]): boolean {+ return (+ a.length === b.length &&+ a.every((tag, i) => tag.name === b[i].name && tag.mcid === b[i].mcid)+ );+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/artifactSequences.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/artifactSequences.tsnew file mode 100644index 0000000000..907c05965f--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/artifactSequences.ts@@ -0,0 +1,98 @@+import type { ArtifactKind } from "@editor/tools/pdfTextEditor/model/artifactKind";+import { toLatin1 } from "@editor/tools/pdfTextEditor/pdfdoc/bytes";+import {+ PATH_PAINTING,+ TEXT_SHOWING,+ parseOps,+ type ContentOp,+} from "@editor/tools/pdfTextEditor/pdfdoc/contentOps";+import { dictKeys, type RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";++/** An artifact sequence on a page whose property list names its /Type. */+export interface ArtifactSequence {+ kind: ArtifactKind;+ /** How many entries its property list has. */+ entries: number;+}++interface OpenSequence {+ sequence: ArtifactSequence | null;+ draws: boolean;+}++/**+ * The page's artifact sequences whose /Type is a name, in the order they+ * open, leaving out those that draw nothing: one for each artifact mark+ * PDFium gives the page's own objects whose kind it cannot read+ * (PdfiumTagMarks.artifactMarkRefs). Null when the content cannot be read.+ */+export async function artifactSequences(+ pdf: RawPdf,+ pageNum: number,+): Promise<ArtifactSequence[] | null> {+ const page = pdf.objectBody(pageNum);+ if (!page) return null;+ const resources = pdf.pageInherited(pageNum, "Resources");+ const properties = resources ? pdf.resolve(resources, "Properties") : null;+ const propertyList = (op: ContentOp, text: string): string | null => {+ const named = op.operands[1];+ if (!named?.startsWith("/")) return text.slice(op.start, op.end);+ return properties ? pdf.resolve(properties, named.slice(1)) : null;+ };++ const open: OpenSequence[] = [];+ const drawn: OpenSequence[] = [];+ for (const ref of pdf.contentRefs(page)) {+ const data = await pdf.streamData(ref);+ if (!data) return null;+ const text = toLatin1(data);+ for (const op of parseOps(text)) {+ if (op.op === "BMC" || op.op === "BDC") {+ const list =+ op.op === "BDC" && op.operands[0] === "/Artifact"+ ? propertyList(op, text)+ : null;+ const sequence = list ? namedKind(pdf, list) : null;+ const entry = { sequence, draws: false };+ open.push(entry);+ if (sequence) drawn.push(entry);+ } else if (op.op === "EMC") {+ open.pop();+ } else if (draws(op)) {+ for (const entry of open) entry.draws = true;+ }+ }+ }+ return drawn.flatMap(({ sequence, draws }) =>+ sequence && draws ? [sequence] : [],+ );+}++function namedKind(pdf: RawPdf, list: string): ArtifactSequence | null {+ const type = pdf.dictName(list, "Type");+ const entries = dictKeys(list)?.length;+ if (!type || entries === undefined) return null;+ return {+ kind: { type, subtype: pdf.dictName(list, "Subtype") },+ entries,+ };+}++/**+ * True when PDFium makes a page object of the operation: showing text that+ * is not empty, painting a path, or drawing an XObject, inline image or+ * shading.+ */+function draws(op: ContentOp): boolean {+ if (TEXT_SHOWING.has(op.op)) return op.operands.some(nonEmptyString);+ if (PATH_PAINTING.has(op.op)) return op.op !== "n";+ return op.op === "Do" || op.op === "EI" || op.op === "sh";+}++function nonEmptyString(token: string): boolean {+ if (token.startsWith("<<")) return false;+ return (+ (token.startsWith("(") && token !== "()") ||+ (token.startsWith("<") && token !== "<>")+ );+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.tsindex 67d7376695..82fab3f7d8 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts@@ -22,6 +22,11 @@ import { markDecorative } from "@editor/tools/pdfTextEditor/pdfdoc/passes/markDeimport { 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 {+ furnitureKind,+ type ArtifactKind,+ type Furniture,+} from "@editor/tools/pdfTextEditor/model/artifactKind";import type { ContentCut } from "@editor/tools/pdfTextEditor/model/PageStructure";import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";@@ -44,6 +49,8 @@ export interface StructureEdit {blockLang?: string | null;/** Turn the element's content into an artifact and drop the element, its /Alt with it. */decorative: boolean;+ /** The page furniture that artifact is; absent for a plain one. */+ furniture?: Furniture;/*** 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).@@ -198,7 +205,9 @@ export async function applyStructureEdits(}const { streams, failed } = await markDecorative(pdf,- new Set(decorative.keys()),+ new Map(+ [...decorative].map(([num, owned]) => [num, artifactKindOf(owned)]),+ ),bodies,parentTree,);@@ -220,6 +229,12 @@ export async function applyStructureEdits(return out;}+/** The kind of artifact the last of an element's edits makes it; null for a plain one. */+function artifactKindOf(edits: readonly StructureEdit[]): ArtifactKind | null {+ const furniture = edits.at(-1)?.furniture;+ return furniture ? furnitureKind(furniture) : null;+}+/** The element's body with `edit`'s /Alt, /Lang and /S applied; null when it is not a dictionary. */function edited(pdf: RawPdf,diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/markDecorative.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/markDecorative.tsindex c9c0779647..379f1ed0a1 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/markDecorative.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/markDecorative.ts@@ -1,8 +1,9 @@/*** Turn whole structure elements into artifacts (ISO 32000-1 14.8.2.2): each- * marked-content sequence an element owns is retagged `/Artifact BMC` and the- * element leaves the tree. Only the sequences' opening operators change, so- * nothing the page paints does.+ * marked-content sequence an element owns is retagged `/Artifact`, with the+ * kind's /Type and /Subtype when it has one, and the element leaves the tree.+ * Only the sequences' opening operators change, so nothing the page paints+ * does.*/import {ParentTreeWriter,@@ -19,8 +20,7 @@ import {type RawPdf,} from "@editor/tools/pdfTextEditor/pdfdoc/raw";import type { RevisionObject } from "@editor/tools/pdfTextEditor/pdfdoc/revision";--const ARTIFACT = "/Artifact BMC";+import type { ArtifactKind } from "@editor/tools/pdfTextEditor/model/artifactKind";export interface DecorativeWrites {/** Rewritten content streams. */@@ -30,21 +30,22 @@ export interface DecorativeWrites {}/**- * Plan turning `elements` (object numbers) into artifacts. Element and parent- * bodies are read from and written to `bodies`, and ParentTree slots to- * `parentTree`, so the caller can combine them with its other edits. Nothing- * is written for a document with any failure: the caller must discard it all.+ * Plan turning `elements` (object numbers) into artifacts, each of the kind+ * it maps to, or plain for null. Element and parent bodies are read from and+ * written to `bodies`, and ParentTree slots to `parentTree`, so the caller can+ * combine them with its other edits. Nothing is written for a document with+ * any failure: the caller must discard it all.*/export async function markDecorative(pdf: RawPdf,- elements: ReadonlySet<number>,+ elements: ReadonlyMap<number, ArtifactKind | null>,bodies: Map<number, string>,parentTree: ParentTreeWriter,): Promise<DecorativeWrites> {const failed = new Map<number, string>();if (elements.size === 0) return { streams: [], failed };const body = (num: number) => bodies.get(num) ?? pdf.objectBody(num);- for (const num of elements) {+ for (const num of elements.keys()) {const own = body(num);if (!own || !ownsOnlyMarkedContent(pdf, own)) {failed.set(num, "its content is not all marked content on its pages");@@ -75,16 +76,18 @@ export async function markDecorative(// Content an element owned but the page no longer draws needs only its// slot emptied.const retag = read.sites.filter((site) => owners.has(site.mcid));+ const opening = (site: McidSite) =>+ artifactOperator(elements.get(owners.get(site.mcid)!) ?? null);read.texts.forEach((text, stream) => {const here = retag.filter((site) => site.stream === stream);if (here.length > 0) {- streams.push(retaggedStream(read.refs[stream], text, here));+ streams.push(retaggedStream(read.refs[stream], text, here, opening));}});for (const mcid of owners.keys()) slots[mcid] = "null";}- for (const num of elements) {+ for (const num of elements.keys()) {const parentNum = pdf.dictRef(body(num) ?? "", "P");const parent = parentNum === null ? null : body(parentNum);const detached = parent ? withoutKid(pdf, parent, num) : null;@@ -94,11 +97,12 @@ export async function markDecorative(return { streams: await Promise.all(streams), failed };}-/** Stream object `num` holding `text` with each site's opening operator retagged as an artifact. */+/** Stream object `num` holding `text` with each site's opening operator replaced by `opening`'s. */function retaggedStream(num: number,text: string,sites: readonly McidSite[],+ opening: (site: McidSite) => string,): Promise<RevisionObject> {let out = text;for (const site of [...sites].sort(@@ -106,12 +110,19 @@ function retaggedStream()) {out =out.slice(0, site.operator.start) +- ARTIFACT ++ opening(site) +out.slice(site.operator.end);}return contentStreamObject(num, out);}+/** The operator opening an artifact of `kind`. */+function artifactOperator(kind: ArtifactKind | null): string {+ if (!kind) return "/Artifact BMC";+ const subtype = kind.subtype === null ? "" : ` /Subtype /${kind.subtype}`;+ return `/Artifact <</Type /${kind.type}${subtype}>> BDC`;+}+/** The parent's body without `num` among its /K, or null when it is not there. */function withoutKid(pdf: RawPdf, parent: string, num: number): string | null {const span = pdf.valueSpan(parent, "K");diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/nameArtifactKinds.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/nameArtifactKinds.tsnew file mode 100644index 0000000000..2970df367a--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/nameArtifactKinds.ts@@ -0,0 +1,82 @@+import {+ parseOps,+ tokenize,+} from "@editor/tools/pdfTextEditor/pdfdoc/contentOps";+import { toLatin1 } from "@editor/tools/pdfTextEditor/pdfdoc/bytes";+import { contentStreamObject } from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";+import { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";+import {+ appendRevision,+ type RevisionObject,+} from "@editor/tools/pdfTextEditor/pdfdoc/revision";++const KIND_KEYS = new Set(["/Type", "/Subtype"]);+/** A string the editor could have written as a kind, and so can be a name as it is. */+const NAMEABLE = /^\(([A-Za-z0-9]+)\)$/;++/**+ * Write the artifact kinds on `pageIndices` that PDFium wrote as strings as+ * the names ISO 32000-2 14.8.2.2.2 requires, as an appended revision. PDFium+ * can set a mark's parameter only as a string, so a page it regenerates+ * carries `/Artifact <</Type (Pagination)>> BDC`. A stream that cannot be+ * read is left alone: PDFium writes every stream it generates readably. The+ * bytes come back as they are when there is nothing to rewrite, or the file+ * is encrypted, where no edit can give an artifact a kind. Throws when the+ * file cannot be read or extended.+ */+export async function nameArtifactKinds(+ bytes: Uint8Array,+ pageIndices: readonly number[],+): Promise<Uint8Array> {+ if (pageIndices.length === 0) return bytes;+ const pdf = await RawPdf.parse(bytes);+ if (!pdf) throw new Error("The file could not be read");+ if (pdf.encrypted) return bytes;+ const refs = new Set(+ pageIndices.flatMap((pageIndex) => {+ const pageNum = pdf.pageNumberAt(pageIndex);+ const page = pageNum === null ? null : pdf.objectBody(pageNum);+ return page ? pdf.contentRefs(page) : [];+ }),+ );+ const rewritten: Promise<RevisionObject>[] = [];+ for (const ref of refs) {+ const data = await pdf.streamData(ref);+ if (!data) continue;+ const text = toLatin1(data);+ const named = withNamedKinds(text);+ if (named !== text) rewritten.push(contentStreamObject(ref, named));+ }+ if (rewritten.length === 0) return bytes;+ const out = appendRevision(pdf, await Promise.all(rewritten));+ if (!out) throw new Error("The file cannot be extended");+ return out;+}++/** `text` with each artifact property list's string /Type and /Subtype written as names. */+function withNamedKinds(text: string): string {+ if (!text.includes("/Artifact")) return text;+ const names: { start: number; end: number; name: string }[] = [];+ for (const op of parseOps(text)) {+ if (op.op !== "BDC" || op.operands[0] !== "/Artifact") continue;+ const tokens = tokenize(text.slice(op.start, op.end));+ let depth = 0;+ tokens.forEach((token, i) => {+ if (token.text === "<<") depth += 1;+ else if (token.text === ">>") depth -= 1;+ const value = tokens[i + 1];+ const string = value?.text.match(NAMEABLE);+ if (depth !== 1 || !KIND_KEYS.has(token.text) || !string) return;+ names.push({+ start: op.start + value.start,+ end: op.start + value.end,+ name: `/${string[1]}`,+ });+ });+ }+ let out = text;+ for (const { start, end, name } of names.reverse()) {+ out = out.slice(0, start) + name + out.slice(end);+ }+ return out;+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.tsindex f03d292de1..d1f78f15ff 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts@@ -740,8 +740,34 @@ interface Entry {}function findEntry(body: string, key: string): Entry | null {+ let found: Entry | null = null;+ visitEntries(body, (name, entry) => {+ if (name === key) found = entry;+ return found !== null;+ });+ return found;+}++/** The keys of the outermost dictionary in `body`, without their slashes; null when there is none. */+export function dictKeys(body: string): string[] | null {+ const keys: string[] = [];+ const read = visitEntries(body, (name) => {+ keys.push(name);+ return false;+ });+ return read ? keys : null;+}++/**+ * Visit the entries of the outermost dictionary in `body` until `visit`+ * returns true. False when `body` has no dictionary.+ */+function visitEntries(+ body: string,+ visit: (key: string, entry: Entry) => boolean,+): boolean {const open = body.indexOf("<<");- if (open < 0) return null;+ if (open < 0) return false;let i = open + 2;let depth = 1;while (i < body.length) {@@ -762,7 +788,7 @@ function findEntry(body: string, key: string): Entry | null {if (ch === ">" && body[i + 1] === ">") {depth -= 1;i += 2;- if (depth === 0) return null;+ if (depth === 0) return true;continue;}if (ch === "[" || ch === "]") {@@ -773,15 +799,16 @@ function findEntry(body: string, key: string): Entry | null {const nameEnd = scanNameEnd(body, i + 1);const start = skipWhitespace(body, nameEnd);const end = scanValueEnd(body, start);- if (body.slice(i + 1, nameEnd) === key)- return { keyStart: i, start, end };+ if (visit(body.slice(i + 1, nameEnd), { keyStart: i, start, end })) {+ return true;+ }// Past the value too: in `/S /P /P 9 0 R` the value /P is not the key.i = end;continue;}i += 1;}- return null;+ return true;}function skipWhitespace(text: string, at: number): number {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.tsindex 436dad4d9e..b1662089f3 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts@@ -1,13 +1,29 @@import type { WrappedPdfiumModule } from "@embedpdf/pdfium";+import type { ArtifactKind } from "@editor/tools/pdfTextEditor/model/artifactKind";import {SCRATCH,scratchPtr,} from "@editor/tools/pdfTextEditor/util/wasmScratch";const MCID = "MCID";+const TYPE = "Type";+const SUBTYPE = "Subtype";const FPDF_PAGEOBJ_FORM = 5;+const FPDF_OBJECT_STRING = 3;+const FPDF_OBJECT_NAME = 4;export const ARTIFACT_TAG = "Artifact";+/**+ * The kinds a document read from its file for artifact marks whose /Type+ * PDFium holds as a name, which it cannot return: by mark pointer, per+ * module, since every document's marks come from the one heap. Each names+ * the document that read it, which drops its own when disposed.+ */+const fileKinds = new WeakMap<+ WrappedPdfiumModule,+ Map<number, { kind: ArtifactKind; owner: object }>+>();+/*** A marked-content tag that links a page object to the structure tree, or* excludes it from the tree as an artifact (ISO 32000-1 14.7.4, 14.8.2.2).@@ -16,6 +32,12 @@ export interface TagMark {name: string;/** The ID the structure tree refers to the content by; null for an artifact. */mcid: number | null;+ /**+ * What an artifact is: from the strings the editor writes, which the save+ * turns into names (nameArtifactKinds), or from the file's names once its+ * document has read them (registerArtifactKinds). Absent until then.+ */+ artifact?: ArtifactKind;}/**@@ -36,7 +58,12 @@ export function readTagMarks(if (!mark) continue;const name = markName(m, mark);const mcid = markMcid(m, mark);- if (mcid !== null || name === ARTIFACT_TAG) tags.push({ name, mcid });+ if (name === ARTIFACT_TAG) {+ const artifact = artifactKind(m, mark);+ tags.push(artifact ? { name, mcid, artifact } : { name, mcid });+ } else if (mcid !== null) {+ tags.push({ name, mcid });+ }}} catch {return [];@@ -77,9 +104,14 @@ export function addTagMark(): boolean {const mark = m.FPDFPageObj_AddMark(objPtr, tag.name);if (!mark) return false;+ const param = (key: string, value: string | null) =>+ value === null ||+ m.FPDFPageObjMark_SetStringParam(docPtr, objPtr, mark, key, value);return (- tag.mcid === null ||- m.FPDFPageObjMark_SetIntParam(docPtr, objPtr, mark, MCID, tag.mcid)+ (tag.mcid === null ||+ m.FPDFPageObjMark_SetIntParam(docPtr, objPtr, mark, MCID, tag.mcid)) &&+ (!tag.artifact ||+ (param(TYPE, tag.artifact.type) && param(SUBTYPE, tag.artifact.subtype))));}@@ -133,6 +165,114 @@ export function carriedMcids(return carried;}+/**+ * True when an object on the page, form XObject content included, is marked+ * an artifact of a kind PDFium writes as strings, which the save must turn+ * into names (nameArtifactKinds).+ */+export function writesArtifactKinds(+ m: WrappedPdfiumModule,+ pagePtr: number,+): boolean {+ const count = m.FPDFPage_CountObjects(pagePtr);+ const objects = Array.from({ length: count }, (_, i) =>+ m.FPDFPage_GetObject(pagePtr, i),+ );+ while (objects.length > 0) {+ const objPtr = objects.pop()!;+ if (!objPtr) continue;+ for (let i = 0; i < m.FPDFPageObj_CountMarks(objPtr); i++) {+ const mark = m.FPDFPageObj_GetMark(objPtr, i);+ if (mark && artifactType(m, mark) === FPDF_OBJECT_STRING) return true;+ }+ 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 false;+}++/** An artifact mark whose /Type PDFium holds as a name. */+export interface ArtifactMarkRef {+ ptr: number;+ /** Its parameter count, and whether /Subtype is a name among them: to check the file's sequence it pairs with. */+ entries: number;+ subtyped: boolean;+}++/**+ * The artifact marks on the page's own objects whose /Type is a name, each+ * once, in the order the content opens them. Form XObject content is left+ * out. Never throws.+ */+export function artifactMarkRefs(+ m: WrappedPdfiumModule,+ pagePtr: number,+): ArtifactMarkRef[] {+ const refs: ArtifactMarkRef[] = [];+ const seen = new Set<number>();+ try {+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {+ const objPtr = m.FPDFPage_GetObject(pagePtr, i);+ if (!objPtr) continue;+ for (let j = 0; j < m.FPDFPageObj_CountMarks(objPtr); j++) {+ const mark = m.FPDFPageObj_GetMark(objPtr, j);+ if (!mark || seen.has(mark)) continue;+ seen.add(mark);+ if (artifactType(m, mark) !== FPDF_OBJECT_NAME) continue;+ refs.push({+ ptr: mark,+ entries: m.FPDFPageObjMark_CountParams(mark),+ subtyped:+ m.FPDFPageObjMark_GetParamValueType(mark, SUBTYPE) ===+ FPDF_OBJECT_NAME,+ });+ }+ }+ } catch {+ return [];+ }+ return refs;+}++/** Record kinds `owner` read from its file, by mark pointer, for readTagMarks to return. */+export function registerArtifactKinds(+ m: WrappedPdfiumModule,+ owner: object,+ kinds: ReadonlyMap<number, ArtifactKind>,+): void {+ let registered = fileKinds.get(m);+ if (!registered) {+ registered = new Map();+ fileKinds.set(m, registered);+ }+ for (const [ptr, kind] of kinds) registered.set(ptr, { kind, owner });+}++/**+ * Drop the kinds recorded for marks `ptrs`, as a page is first read: a mark+ * an edit freed can come back at the same address when another page is.+ */+export function forgetArtifactMarks(+ m: WrappedPdfiumModule,+ ptrs: Iterable<number>,+): void {+ const registered = fileKinds.get(m);+ for (const ptr of ptrs) registered?.delete(ptr);+}++/** Drop every kind `owner` recorded. */+export function forgetArtifactKinds(+ m: WrappedPdfiumModule,+ owner: object,+): void {+ const registered = fileKinds.get(m);+ for (const [ptr, entry] of registered ?? []) {+ if (entry.owner === owner) registered!.delete(ptr);+ }+}+/** Carry `from`'s tags onto its replacement `to`. */export function copyTagMarks(m: WrappedPdfiumModule,@@ -153,6 +293,46 @@ function markName(m: WrappedPdfiumModule, mark: number): string {return m.pdfium.UTF16ToString(buf);}+/** The artifact mark's kind, from its strings or the kinds read from the file; undefined when neither gives one. */+function artifactKind(+ m: WrappedPdfiumModule,+ mark: number,+): ArtifactKind | undefined {+ const type = stringParam(m, mark, TYPE);+ if (type !== null) return { type, subtype: stringParam(m, mark, SUBTYPE) };+ // Only a mark read from the file has a name: one the editor adds at a+ // freed mark's address must not take that mark's kind.+ if (m.FPDFPageObjMark_GetParamValueType(mark, TYPE) !== FPDF_OBJECT_NAME) {+ return undefined;+ }+ return fileKinds.get(m)?.get(mark)?.kind;+}++/** The object type of an artifact mark's /Type; 0 for any other mark, or one without. */+function artifactType(m: WrappedPdfiumModule, mark: number): number {+ if (markName(m, mark) !== ARTIFACT_TAG) return 0;+ return m.FPDFPageObjMark_GetParamValueType(mark, TYPE);+}++/** The mark's string parameter `key`; null when it has none, or a value of another type. */+function stringParam(+ m: WrappedPdfiumModule,+ mark: number,+ key: string,+): string | null {+ const lenPtr = scratchPtr(m, SCRATCH.tagParamLen, 4);+ if (!m.FPDFPageObjMark_GetParamStringValue(mark, key, 0, 0, lenPtr)) {+ return null;+ }+ const byteLen = m.pdfium.getValue(lenPtr, "i32");+ if (byteLen <= 2) return "";+ const buf = scratchPtr(m, SCRATCH.tagParam, byteLen);+ if (!m.FPDFPageObjMark_GetParamStringValue(mark, key, buf, byteLen, lenPtr)) {+ return null;+ }+ return m.pdfium.UTF16ToString(buf);+}+function markMcid(m: WrappedPdfiumModule, mark: number): number | null {const out = scratchPtr(m, SCRATCH.tagMcid, 4);if (!m.FPDFPageObjMark_GetParamIntValue(mark, MCID, out)) return null;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.tsindex e0f4bd4528..d6ef5ef83a 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts@@ -59,6 +59,7 @@ export class PdfiumTextReader {mode: GroupingMode = "auto",): void {if (page.loaded) return;+ doc.claimArtifactMarks(page.index);const m = doc.module;const pagePtr = page.pagePtr;const count = m.FPDFPage_CountObjects(pagePtr);diff --git a/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts b/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.tsindex 615e286a5e..cc8a72ffba 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts@@ -300,6 +300,9 @@ export class EditorStore {this.disposeDocumentIfAny();resetCharcodeCaches();this.doc = doc;+ doc.onArtifactKinds(() => {+ if (this.doc === doc) this.resnapshot();+ });this.history.clear();this.savedTop = null;this.bakedDirty = false;@@ -617,6 +620,8 @@ export class EditorStore {// once `PdfiumTextReader` finishes for a page.publishPages(pages: PageSnapshot[]): void {this.patch({ pages });+ // A page whose artifact kinds were read after its snapshot was taken.+ this.resnapshot();}/** Document-level dirty bit. */diff --git a/frontend/src/editor/core/tools/pdfTextEditor/types.ts b/frontend/src/editor/core/tools/pdfTextEditor/types.tsindex 319619d3b1..9ff1e96c54 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/types.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/types.ts@@ -2,6 +2,7 @@import type { DisplayTransformData } from "@editor/tools/pdfTextEditor/model/DisplayTransform";import type { AnnotationBox } from "@editor/tools/pdfTextEditor/model/AnnotationBox";+import type { Furniture } from "@editor/tools/pdfTextEditor/model/artifactKind";export interface RGBA {r: number; // 0..255@@ -87,6 +88,8 @@ export interface TextRunSnapshot {mcid?: number;/** Marked as an artifact: content that assistive technology skips. */artifact?: boolean;+ /** The page furniture the artifact is, where its mark says so in a form the editor reads. */+ furniture?: Furniture;/** Drawn by a form XObject, whose marks the editor does not read. */inForm?: boolean;}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.tsindex 0b8b462d2f..75dd30001a 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts@@ -8,10 +8,12 @@ import {MarkInfoError,applyMarked,} from "@editor/tools/pdfTextEditor/pdfdoc/passes/markTagged";+import { nameArtifactKinds } from "@editor/tools/pdfTextEditor/pdfdoc/passes/nameArtifactKinds";import { repairStructure } from "@editor/tools/pdfTextEditor/pdfdoc/passes/repairStructure";import { setDocumentLanguage } from "@editor/tools/pdfTextEditor/pdfdoc/passes/setDocumentLanguage";import { preserveShadings } from "@editor/tools/pdfTextEditor/pdfdoc/passes/preserveShadings";import { PdfiumSave } from "@editor/tools/pdfTextEditor/pdfium/PdfiumSave";+import { writesArtifactKinds } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";import {assertIncrementalAppend,assertSavedPdf,@@ -49,6 +51,11 @@ export async function exportToBlob(bytes = doc.openedBytes;} else {bytes = await serializeEdits(doc, incremental);+ try {+ bytes = await nameArtifactKinds(bytes, pagesWritingArtifactKinds(doc));+ } catch (err) {+ throw accessibilitySaveFailed(err);+ }}// Throws rather than dropping them: a description the user wrote that the@@ -100,6 +107,16 @@ export async function exportToBlob(return { blob: pdfBlob(bytes), filename: exportName(sourceName) };}+function pagesWritingArtifactKinds(doc: EditorDocument): number[] {+ return doc+ .loadedPages()+ .filter(+ (page) =>+ page.regenerated && writesArtifactKinds(doc.module, page.pagePtr),+ )+ .map((page) => page.index);+}+function accessibilitySaveFailed(cause: unknown): Error {// It names pages and MCIDs: for a bug report, not for the user.console.error(cause);diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/pageFurniture.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/pageFurniture.tsnew file mode 100644index 0000000000..7df2bd10cc--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/pageFurniture.ts@@ -0,0 +1,326 @@+/**+ * Recognising page furniture: what a document repeats on its pages, such as+ * running headers, page numbers and watermarks. Text is compared with+ * each run of digits, in any script, read as one, so "Page 3" matches+ * "Page 12", and height as the distance from the page's nearer edge, as+ * displayed, so pages of different sizes still line up.+ */+import type { Furniture } from "@editor/tools/pdfTextEditor/model/artifactKind";+import type { DisplayTransformData } from "@editor/tools/pdfTextEditor/model/DisplayTransform";+import type { Affine, PageRect, RGBA } from "@editor/tools/pdfTextEditor/types";++/** How far apart two runs can sit, in points, and still be at the same height or in the same place. */+const SAME_HEIGHT_PT = 4;+/** How near an edge, as a share of the page's height, auto-tag looks for furniture. */+const EDGE_BAND = 0.12;+/**+ * How many copies of one thing a page draws, spread over at least half its+ * width and half its height, to be tiled with it: a form's repeated labels+ * rarely spread so far, and the watermark tool's grid always covers the page.+ */+const TILED = 3;+/** How far from square to the page, in radians, a run must be turned to read as set at an angle. */+const OFF_AXIS = 0.05;+const DIGITS = /\p{Nd}+/gu;+const DIGIT = /^\p{Nd}$/u;++export interface FurnitureRun {+ id: string;+ text: string;+ bounds: PageRect;+ matrix: Affine;+ fill: RGBA;+}++export interface FurnitureImage {+ id: string;+ bounds: PageRect;+ matrix: Affine;+}++export interface FurniturePage<R extends FurnitureRun = FurnitureRun> {+ pageIndex: number;+ display: DisplayTransformData;+ runs: readonly R[];+ images?: readonly FurnitureImage[];+}++interface Placement {+ edge: "top" | "bottom";+ /** From that edge to the nearer side of the run, in points. */+ distance: number;+ /** As a share of the page's height. */+ share: number;+}++/** The text as furniture compares it: whitespace collapsed, each run of digits one "#". */+export function furnitureText(text: string): string {+ return text.replace(/\s+/g, " ").trim().replace(DIGITS, "#");+}++/**+ * The runs on pages other than `pageIndex` that show `run`'s text, digits+ * aside, at its height, with the page each is on.+ */+export function matchingRuns<R extends FurnitureRun>(+ pages: readonly FurniturePage<R>[],+ pageIndex: number,+ run: FurnitureRun,+): { pageIndex: number; run: R }[] {+ const own = pages.find((page) => page.pageIndex === pageIndex);+ const text = furnitureText(run.text);+ if (!own || !text) return [];+ const at = placement(own.display, run.bounds);+ return pages.flatMap((page) =>+ page.pageIndex === pageIndex+ ? []+ : page.runs+ .filter(+ (other) =>+ furnitureText(other.text) === text &&+ sameHeight(at, placement(page.display, other.bounds)),+ )+ .map((other) => ({ pageIndex: page.pageIndex, run: other })),+ );+}++/**+ * What auto-tag should mark as furniture rather than give an element, by+ * page index and then run or image id. Watermarks come first: text or images+ * drawn in the same place on at least half the document's pages that are+ * tiled across the page, set at an angle, or (text) see-through, and that+ * repeat on two pages or tile one. Then text near the top or bottom of a+ * page that at least half the pages, and at least two, show at the same+ * height: near the top a header, near the bottom a footer, and either a page+ * number when one of its numbers counts up with the pages, whatever words+ * surround it. `pageCount` counts the pages not in `pages` too.+ */+export function recogniseFurniture(+ pages: readonly FurniturePage[],+ pageCount: number,+): Map<number, Map<string, Furniture>> {+ const half = Math.ceil(pageCount / 2);+ const furniture = new Map<number, Map<string, Furniture>>();+ const mark = (pageIndex: number, id: string, kind: Furniture) => {+ const onPage = furniture.get(pageIndex) ?? new Map<string, Furniture>();+ furniture.set(pageIndex, onPage.set(id, kind));+ };+ for (const { pageIndex, id } of watermarks(pages, half)) {+ mark(pageIndex, id, "Watermark");+ }++ const groups = new Map<string, { at: Placement; runs: GroupedRun[] }[]>();+ for (const page of pages) {+ for (const run of page.runs) {+ if (furniture.get(page.pageIndex)?.has(run.id)) continue;+ const at = placement(page.display, run.bounds);+ const text = furnitureText(run.text);+ if (!text || at.share > EDGE_BAND) continue;+ const key = `${at.edge}:${text}`;+ const sameText = groups.get(key) ?? [];+ groups.set(key, sameText);+ const grouped = {+ pageIndex: page.pageIndex,+ id: run.id,+ numbers: numbers(run.text),+ };+ const group = sameText.find((g) => sameHeight(g.at, at));+ if (group) group.runs.push(grouped);+ else sameText.push({ at, runs: [grouped] });+ }+ }++ const needed = Math.max(2, half);+ for (const sameText of groups.values()) {+ for (const { at, runs } of sameText) {+ if (pagesOf(runs) < needed) continue;+ const kind = furnitureKind(runs, at.edge);+ for (const { pageIndex, id } of runs) mark(pageIndex, id, kind);+ }+ }+ return furniture;+}++/** Something a page draws that may be a watermark, keyed by what it shows. */+interface Drawn {+ pageIndex: number;+ id: string;+ key: string;+ centre: { x: number; y: number };+ tiled: boolean;+}++/** The text and images `recogniseFurniture` reads as watermarks. */+function watermarks(+ pages: readonly FurniturePage[],+ half: number,+): { pageIndex: number; id: string }[] {+ const groups = new Map<string, Drawn[][]>();+ for (const drawn of pages.flatMap(watermarkLike)) {+ const sameKey = groups.get(drawn.key) ?? [];+ groups.set(drawn.key, sameKey);+ const group = sameKey.find((g) => samePlace(g[0].centre, drawn.centre));+ if (group) group.push(drawn);+ else sameKey.push([drawn]);+ }+ return [...groups.values()].flat().flatMap((group) => {+ const pages = pagesOf(group);+ const repeats = pages >= 2 || group.some((drawn) => drawn.tiled);+ return pages >= half && repeats ? group : [];+ });+}++/** What the page draws that looks like a watermark: tiled, set at an angle, or see-through. */+function watermarkLike(page: FurniturePage): Drawn[] {+ const items = [+ ...page.runs.map((run) => ({+ id: run.id,+ key: furnitureText(run.text) && `text:${furnitureText(run.text)}`,+ bounds: run.bounds,+ matrix: run.matrix,+ seeThrough: run.fill.a < 255,+ })),+ ...(page.images ?? []).map((image) => ({+ id: image.id,+ key: `image:${Math.round(image.bounds.width)}x${Math.round(image.bounds.height)}`,+ bounds: image.bounds,+ matrix: image.matrix,+ // PDFium reads no fill for an image, so its opacity is unknown.+ seeThrough: false,+ })),+ ].filter((item) => item.key);+ const centres = new Map<string, { x: number; y: number }[]>();+ const placed = items.map((item) => {+ const at = centre(page.display, item.bounds);+ centres.set(item.key, [...(centres.get(item.key) ?? []), at]);+ return { ...item, at };+ });+ return placed.flatMap((item) => {+ const tiled = tiles(centres.get(item.key)!, page.display);+ if (!tiled && !item.seeThrough && !offAxis(item.matrix)) return [];+ return [+ {+ pageIndex: page.pageIndex,+ id: item.id,+ key: item.key,+ centre: item.at,+ tiled,+ },+ ];+ });+}++/** True when copies at `centres` tile the page (see TILED). */+function tiles(+ centres: readonly { x: number; y: number }[],+ { displayWidth, displayHeight }: DisplayTransformData,+): boolean {+ if (centres.length < TILED) return false;+ const span = (values: number[]) => Math.max(...values) - Math.min(...values);+ return (+ span(centres.map((c) => c.x)) >= displayWidth / 2 &&+ span(centres.map((c) => c.y)) >= displayHeight / 2+ );+}++function pagesOf(items: readonly { pageIndex: number }[]): number {+ return new Set(items.map((item) => item.pageIndex)).size;+}++/** True when the matrix turns its content by other than a multiple of a right angle. */+function offAxis({ a, b }: Affine): boolean {+ const turn = Math.abs(Math.atan2(b, a)) % (Math.PI / 2);+ return turn > OFF_AXIS && turn < Math.PI / 2 - OFF_AXIS;+}++function samePlace(+ a: { x: number; y: number },+ b: { x: number; y: number },+): boolean {+ return (+ Math.abs(a.x - b.x) <= SAME_HEIGHT_PT &&+ Math.abs(a.y - b.y) <= SAME_HEIGHT_PT+ );+}++/** The middle of `bounds` on its page as displayed. */+function centre(+ display: DisplayTransformData,+ { x, y, width, height }: PageRect,+): { x: number; y: number } {+ const px = x + width / 2;+ const py = y + height / 2;+ return {+ x: display.a * px + display.c * py + display.e,+ y: display.b * px + display.d * py + display.f,+ };+}++interface GroupedRun {+ pageIndex: number;+ id: string;+ numbers: number[];+}++function furnitureKind(+ runs: readonly GroupedRun[],+ edge: Placement["edge"],+): Furniture {+ if (numbersPages(runs)) return "PageNum";+ return edge === "top" ? "Header" : "Footer";+}++/**+ * True when one of the runs' numbers, at the same place in each, is its+ * page's index plus the same offset on every page: a page number, counting+ * from wherever the document starts. The runs share their text digits+ * aside, so each has as many numbers.+ */+function numbersPages(runs: readonly GroupedRun[]): boolean {+ return runs[0].numbers.some(+ (_, i) =>+ new Set(runs.map((run) => run.numbers[i] - run.pageIndex)).size === 1,+ );+}++/** The text's numbers, written in the digits of any script. */+function numbers(text: string): number[] {+ return [...text.matchAll(DIGITS)].map(([digits]) =>+ [...digits].reduce((value, digit) => value * 10 + digitValue(digit), 0),+ );+}++/**+ * A decimal digit's value. Unicode encodes every script's decimal digits as+ * a contiguous run of ten, zero to nine, so the value is how far into its+ * run the digit sits; runs that abut, such as the mathematical digits, each+ * begin ten after the last.+ */+function digitValue(digit: string): number {+ const code = digit.codePointAt(0)!;+ let below = 0;+ while (DIGIT.test(String.fromCodePoint(code - below - 1))) below++;+ return below % 10;+}++function sameHeight(a: Placement, b: Placement): boolean {+ return (+ a.edge === b.edge && Math.abs(a.distance - b.distance) <= SAME_HEIGHT_PT+ );+}++/** Where the run sits on its page as displayed, by the page's nearer edge. */+function placement(display: DisplayTransformData, bounds: PageRect): Placement {+ const { x, y, width, height } = bounds;+ const ys = [+ [x, y],+ [x + width, y],+ [x, y + height],+ [x + width, y + height],+ ].map(([px, py]) => display.b * px + display.d * py + display.f);+ const fromBottom = Math.min(...ys);+ const fromTop = display.displayHeight - Math.max(...ys);+ const edge = fromTop <= fromBottom ? "top" : "bottom";+ const distance = Math.max(0, Math.min(fromTop, fromBottom));+ return { edge, distance, share: distance / display.displayHeight };+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.tsindex cb47f9a615..ee7253d072 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.ts@@ -1,10 +1,15 @@import { elementStretches } from "@editor/tools/pdfTextEditor/commands/TagTextRangeCommand";+import type { Furniture } from "@editor/tools/pdfTextEditor/model/artifactKind";import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";import type {+ AddedElement,InnerOptions,RetagBlocker,} from "@editor/tools/pdfTextEditor/model/PageStructure";-import type { StructureRole } from "@editor/tools/pdfTextEditor/model/structureTypes";+import type {+ StructureRole,+ StructureType,+} from "@editor/tools/pdfTextEditor/model/structureTypes";import type { TextLanguage } from "@editor/tools/pdfTextEditor/model/languageTag";import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";import { innermostMcid } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";@@ -14,42 +19,76 @@ import type {HeadingText,} from "@editor/tools/pdfTextEditor/util/headingOutline";+/** An artifact, which screen readers skip: page furniture, or plain decoration with null. */+export interface ArtifactChoice {+ artifact: Furniture | null;+}++/** What text can be tagged as: a type, or an artifact. */+export type TextTagChoice = StructureType | ArtifactChoice;+/** 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: "tagged";+ block: StructureRole;+ cannotRetag: RetagBlocker | null;+ canBeArtifact: boolean;+ }+ /**+ * `furniture` null for plain decoration, or an artifact whose kind is not+ * read. `taggable` when the text can be given a type again, or another kind.+ */+ | { kind: "artifact"; furniture: Furniture | null; taggable: boolean }+ /** `taggable` when TagTextCommand can give the text an element, or make it an artifact. */| { kind: "untagged"; documentTagged: boolean; taggable: boolean }/** Drawn by a form XObject, whose marks the editor does not read. */| { kind: "unknown" }- /** Several runs' text, not all tagged alike; `settable` when every run's tag can be set. */- | { kind: "mixed"; settable: boolean };+ /** Several runs' text, not all tagged alike; each flag holds when it does for every run. */+ | { kind: "mixed"; settable: boolean; canBeArtifact: boolean };export function textTag(doc: EditorDocument, run: TextRunSnapshot): TextTag {if (run.inForm) return { kind: "unknown" };- if (run.artifact) return { kind: "artifact" };+ const retaggable = retaggableText(doc, run) !== null;+ if (run.artifact) {+ return {+ kind: "artifact",+ furniture: run.furniture ?? null,+ taggable: retaggable,+ };+ }const untagged = {kind: "untagged",documentTagged: doc.treatAsTagged(),- taggable: canTagText(doc, run),+ taggable: retaggable,} as const;if (run.mcid === undefined) return untagged;const structure = doc.structure(run.pageIndex);const block = structure.block(run.mcid);if (!block) return untagged;+ if (structure.decorative(run.mcid)) {+ return {+ kind: "artifact",+ furniture: structure.furniture(run.mcid),+ taggable: true,+ };+ }return {kind: "tagged",block: { role: block.role, type: block.type },cannotRetag: structure.cannotRetag(run.mcid),+ canBeArtifact:+ retaggable || structure.cannotMarkDecorative(run.mcid) === null,};}-/** True when the tag picker can set the text's tag: retag it, or tag it. */-export function canSetTextTag(tag: TextTag): boolean {+/** True when the tag picker can give the text a type: retag it, or tag it. */+export function canTypeText(tag: TextTag): boolean {switch (tag.kind) {case "tagged":return tag.cannotRetag === null;+ case "artifact":case "untagged":return tag.taggable;case "mixed":@@ -59,22 +98,50 @@ export function canSetTextTag(tag: TextTag): boolean {}}+/** True when the tag picker can make the text an artifact, or another kind of one. */+export function canBeArtifact(tag: TextTag): boolean {+ switch (tag.kind) {+ case "artifact":+ return tag.taggable;+ case "tagged":+ case "mixed":+ return tag.canBeArtifact;+ case "untagged":+ return tag.taggable;+ default:+ return false;+ }+}++/** True when the tag picker can change the text's tag at all. */+export function canSetTextTag(tag: TextTag): boolean {+ return canTypeText(tag) || canBeArtifact(tag);+}+/*** How several runs' text is tagged together: the tag they share, or mixed.- * Shared, it is settable only when every run's is.+ * Shared, it can change only as every run's can.*/export function sharedTextTag(tags: readonly TextTag[]): TextTag {const [first, ...rest] = tags;- const settable = tags.every(canSetTextTag);+ const settable = tags.every(canTypeText);+ const artifactable = tags.every(canBeArtifact);if (!rest.every((tag) => sameTagShown(first, tag))) {- return { kind: "mixed", settable };+ return { kind: "mixed", settable, canBeArtifact: artifactable };}switch (first.kind) {- case "tagged":- return settable- ? { ...first, cannotRetag: null }- : (tags.find((tag) => tag.kind === "tagged" && tag.cannotRetag) ??- first);+ case "tagged": {+ const blocked = tags.find(+ (tag) => tag.kind === "tagged" && tag.cannotRetag !== null,+ );+ return {+ ...first,+ cannotRetag:+ blocked?.kind === "tagged" ? blocked.cannotRetag : first.cannotRetag,+ canBeArtifact: artifactable,+ };+ }+ case "artifact":case "untagged":return { ...first, taggable: settable };default:@@ -89,21 +156,36 @@ function sameTagShown(a: TextTag, b: TextTag): boolean {if (a.kind === "untagged" && b.kind === "untagged") {return a.documentTagged === b.documentTagged;}+ if (a.kind === "artifact" && b.kind === "artifact") {+ return a.furniture === b.furniture;+ }return a.kind === b.kind;}+/** How a run's text is tagged, where TagTextCommand can change it. */+export type RetaggableText =+ | { kind: "untagged" }+ | { kind: "artifact" }+ | { kind: "added"; element: AddedElement };+/**- * True when the run's text can be given an element of its own: it is drawn- * by the page itself, whose save can add one, and has no tag or artifact- * mark.+ * The run's tag when TagTextCommand can change it: text the page itself+ * draws, whose save can add an element, that is untagged, an artifact, or in+ * an element the session added that nothing else depends on. Null+ * otherwise, for text the file's elements own among the rest.*/-export function canTagText(doc: EditorDocument, run: TextRunSnapshot): boolean {- return (- !run.inForm &&- !run.artifact &&- run.mcid === undefined &&- doc.structure(run.pageIndex).cannotAddElement() === null- );+export function retaggableText(+ doc: EditorDocument,+ run: TextRunSnapshot,+): RetaggableText | null {+ if (run.inForm) return null;+ const structure = doc.structure(run.pageIndex);+ if (structure.cannotAddElement() !== null) return null;+ if (run.mcid === undefined) {+ return run.artifact ? { kind: "artifact" } : { kind: "untagged" };+ }+ const element = structure.standaloneAdded(run.mcid);+ return element ? { kind: "added", element } : null;}/** An element marking part of a run's text, rather than the run's own block. */diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.tsindex 9f5214f73d..237ea6e4a3 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.ts@@ -83,6 +83,8 @@ export const SCRATCH = {tagName: key(),tagNameLen: key(),tagMcid: key(),+ tagParam: key(),+ tagParamLen: key(),splitMatrix: key(),splitOriginX: key(),splitOriginY: key(),