#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 formulas in Text Editor (#8945)
EthanHealy01cd84607d45a5
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.tomlindex 5319ad64e2..6804d42eca 100644--- a/frontend/public/locales/en-US/translation.toml+++ b/frontend/public/locales/en-US/translation.toml@@ -7832,7 +7832,11 @@ decorativeLabel = "Decorative image"description = "Image description"descriptionInfo = "Screen readers read this out in place of the image."encrypted = "Tags can't be edited in an encrypted file"+figureDescription = "Figure description"+figureDescriptionInfo = "Screen readers read this out in place of the figure."formFieldDescription = "Field description"+formulaDescription = "Formula description"+formulaDescriptionInfo = "Screen readers read this out in place of the formula. Say it as you would aloud, such as \"x squared plus one\"."heading = "Accessibility"innerTagLabel = "Tag {{number}}"innerTags = "Tags in this text"@@ -7844,7 +7848,7 @@ missingDescriptions = "Missing descriptions"mixedContent = "Figure includes other content"mixedTags = "Mixed"needsDescriptionBadge = "No description"-nextImage = "Next image"+nextToReview = "Next to review"notFigure = "Tagged as part of the text"removeTag = "Remove tag"saveFailed = "Your accessibility changes couldn't be saved, so the file wasn't saved. Undo them and try again."diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-formula-review.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-formula-review.spec.tsnew file mode 100644index 0000000000..db1cc8b232--- /dev/null+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-formula-review.spec.ts@@ -0,0 +1,47 @@+import { test, expect } from "@editor/tests/helpers/stub-test-base";+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";+import { formulasPdf } from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";++// A formula drawn as text needs a description as much as one drawn as an+// image: without one a PDF/UA checker fails it, so the review must find it.++test("an undescribed text formula is flagged, reached by Next, and cleared by describing it", async ({+ page,+}) => {+ test.setTimeout(120_000);+ await openInTextEditor(page, {+ name: "formulas.pdf",+ mimeType: "application/pdf",+ buffer: Buffer.from(formulasPdf()),+ });+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({+ timeout: 30_000,+ });++ const badges = page.locator('[data-testid^="pdf-editor-attention-run-"]');+ await expect(badges).toHaveCount(1);+ await badges.first().hover();+ await expect(+ page.getByRole("tooltip", { name: "No description" }),+ ).toBeVisible();++ await page.getByTestId("pdf-editor-tab-document").click();+ const summary = page.getByTestId("pdf-editor-document-accessibility-summary");+ await expect(summary).toHaveText(/Missing descriptions\s*1/);++ await page.getByTestId("pdf-editor-document-accessibility-next").click();+ const field = page.getByTestId("pdf-editor-text-description");+ await expect(field).toHaveValue("");+ // The only one: nothing else to move on to.+ await expect(+ page.getByTestId("pdf-editor-text-description-next"),+ ).toBeHidden();++ await field.fill("a equals b, c equals d");+ await expect(badges).toHaveCount(0);+ await page.getByTestId("pdf-editor-tab-document").click();+ await expect(summary).toHaveText(/Missing descriptions\s*0/);+ await expect(+ page.getByTestId("pdf-editor-document-accessibility-next"),+ ).toBeHidden();+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pdfFixtures.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pdfFixtures.tsindex 991c0d1878..312f9b065e 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pdfFixtures.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pdfFixtures.ts@@ -138,3 +138,128 @@ export function splitContentPdf(parts: string[], tight = false): Uint8Array {);return buildClassicPdf(objects, 1);}++/**+ * One page, top to bottom: a formula drawn as two lines with no description+ * (MCIDs 0 and 1, one element), a described formula (MCID 2), and a+ * paragraph (MCID 3).+ */+export function formulasPdf(): Uint8Array {+ return buildClassicPdf(+ [+ {+ num: 1,+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 6 0 R /MarkInfo << /Marked true >> >>",+ },+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },+ {+ num: 3,+ body:+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /StructParents 0 " ++ "/Resources << /Font << /F1 5 0 R >> >> >>",+ },+ {+ num: 4,+ body: streamBody(+ "",+ "/Formula <</MCID 0>> BDC BT /F1 12 Tf 72 700 Td (a = b) Tj ET EMC\n" ++ "/Formula <</MCID 1>> BDC BT /F1 12 Tf 72 600 Td (c = d) Tj ET EMC\n" ++ "/Formula <</MCID 2>> BDC BT /F1 12 Tf 72 500 Td (e = f) Tj ET EMC\n" ++ "/P <</MCID 3>> BDC BT /F1 12 Tf 72 400 Td (Where a is) Tj ET EMC\n",+ ),+ },+ {+ num: 5,+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ },+ {+ num: 6,+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 11 0 R /ParentTreeNextKey 1 >>",+ },+ {+ num: 7,+ body: "<< /Type /StructElem /S /Document /P 6 0 R /K [8 0 R 9 0 R 10 0 R] >>",+ },+ {+ num: 8,+ body: "<< /Type /StructElem /S /Formula /P 7 0 R /Pg 3 0 R /K [0 1] >>",+ },+ {+ num: 9,+ body: "<< /Type /StructElem /S /Formula /P 7 0 R /Pg 3 0 R /K 2 /Alt (e equals f) >>",+ },+ {+ num: 10,+ body: "<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K 3 >>",+ },+ { num: 11, body: "<< /Nums [0 [8 0 R 8 0 R 9 0 R 10 0 R]] >>" },+ ],+ 1,+ );+}++/**+ * Formulas whose text their own element does not mark, over two pages. Page+ * 0, top to bottom: a paragraph whose text is in a NonStruct (MCID 0), the+ * way Chrome tags it; a formula described "x squared equals y" whose text is+ * in a Span (MCID 1); and the start of a formula (MCID 2) that ends on page 1+ * (MCID 0).+ */+export function blockFormulasPdf(): Uint8Array {+ const page = (num: number, contents: number, structParents: number) => ({+ num,+ body:+ `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents ${contents} 0 R ` ++ `/StructParents ${structParents} /Resources << /Font << /F1 5 0 R >> >> >>`,+ });+ const element = (num: number, s: string, parent: number, rest: string) => ({+ num,+ body: `<< /Type /StructElem /S /${s} /P ${parent} 0 R /Pg 3 0 R ${rest} >>`,+ });+ return buildClassicPdf(+ [+ {+ num: 1,+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 6 0 R /MarkInfo << /Marked true >> >>",+ },+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R 15 0 R] /Count 2 >>" },+ page(3, 4, 0),+ {+ num: 4,+ body: streamBody(+ "",+ "/NonStruct <</MCID 0>> BDC BT /F1 12 Tf 72 700 Td (Where x is) Tj ET EMC\n" ++ "/Span <</MCID 1>> BDC BT /F1 12 Tf 72 600 Td (x2 = y) Tj ET EMC\n" ++ "/Formula <</MCID 2>> BDC BT /F1 12 Tf 72 500 Td (a + b) Tj ET EMC\n",+ ),+ },+ {+ num: 5,+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ },+ {+ num: 6,+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 20 0 R /ParentTreeNextKey 2 >>",+ },+ element(7, "Document", 6, "/K [10 0 R 12 0 R 14 0 R]"),+ element(10, "P", 7, "/K 11 0 R"),+ element(11, "NonStruct", 10, "/K 0"),+ element(12, "Formula", 7, "/K 13 0 R /Alt (x squared equals y)"),+ element(13, "Span", 12, "/K 1"),+ element(14, "Formula", 7, "/K [2 << /Type /MCR /Pg 15 0 R /MCID 0 >>]"),+ page(15, 16, 1),+ {+ num: 16,+ body: streamBody(+ "",+ "/Formula <</MCID 0>> BDC BT /F1 12 Tf 72 700 Td (= c) Tj ET EMC\n",+ ),+ },+ {+ num: 20,+ body: "<< /Nums [0 [11 0 R 13 0 R 14 0 R] 1 [14 0 R]] >>",+ },+ ],+ 1,+ );+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.tsindex 2a9b20f04b..524a7a4060 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts@@ -12,6 +12,7 @@ import {test,vi,} from "vitest";+import { RetagBlockCommand } from "@editor/tools/pdfTextEditor/commands/RetagBlockCommand";import { SetAltTextCommand } from "@editor/tools/pdfTextEditor/commands/SetAltTextCommand";import { SetDecorativeCommand } from "@editor/tools/pdfTextEditor/commands/SetDecorativeCommand";import { TagImageCommand } from "@editor/tools/pdfTextEditor/commands/TagImageCommand";@@ -36,11 +37,16 @@ import { expectConsole } from "@editor/tests/failOnConsole";import {imageAccessibility,imageAttention,- nextImageNeedingAttention,- reviewImages,} from "@editor/tools/pdfTextEditor/util/imageAccessibility";+import {+ nextNeedingAttention,+ reviewAccessibility,+} from "@editor/tools/pdfTextEditor/util/accessibilityReview";import { InsertImageCommand } from "@editor/tools/pdfTextEditor/commands/InsertImageCommand";-import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";+import type {+ PageSnapshot,+ TextRunSnapshot,+} from "@editor/tools/pdfTextEditor/types";import {buildClassicPdf,streamBody,@@ -323,7 +329,7 @@ describe("imageAccessibility", () => {expect(imageAccessibility(doc, figure)).toEqual({kind: "describable",description: "A grey square",- tagged: true,+ type: "Figure",canBeDecorative: true,});new HistoryStack().execute(@@ -434,13 +440,15 @@ describe("reviewing images that need attention", () => {return {pageIndex,images: page.images.map((img) => img.snapshot()),+ runs: [] as TextRunSnapshot[],+ display: page.display.toData(),} as PageSnapshot;});}test("counts the undescribed images across pages", async () => {const doc = await open(figuresPdf());- expect(reviewImages(doc, await pages(doc))).toEqual({+ expect(reviewAccessibility(doc, await pages(doc))).toEqual({needsDescription: 2,untagged: 0,untaggable: 0,@@ -453,7 +461,7 @@ describe("reviewing images that need attention", () => {const [a, b] = read[0].images;const [c] = read[1].images;const next = (from: string | null) =>- nextImageNeedingAttention(doc, read, from)?.id;+ nextNeedingAttention(doc, read, from)?.id;expect(next(null)).toBe(a.id);expect(next(a.id)).toBe(c.id);expect(next(b.id)).toBe(c.id);@@ -469,11 +477,11 @@ describe("reviewing images that need attention", () => {doc,);describe(" ");- expect(reviewImages(doc, read).needsDescription).toBe(2);+ expect(reviewAccessibility(doc, read).needsDescription).toBe(2);describe("A bar chart");- expect(reviewImages(doc, read).needsDescription).toBe(1);+ expect(reviewAccessibility(doc, read).needsDescription).toBe(1);const [c] = read[1].images;- expect(nextImageNeedingAttention(doc, read, c.id)?.id).toBe(c.id);+ expect(nextNeedingAttention(doc, read, c.id)?.id).toBe(c.id);});test("flags an image inserted into a tagged document as untagged", async () => {@@ -495,16 +503,21 @@ describe("reviewing images that need attention", () => {.find((img) => img.id === insert.insertedImageId)!.snapshot();const read = [- { pageIndex: 0, images: page.images.map((img) => img.snapshot()) },+ {+ pageIndex: 0,+ images: page.images.map((img) => img.snapshot()),+ runs: [] as TextRunSnapshot[],+ display: page.display.toData(),+ },] as PageSnapshot[];expect(imageAttention(doc, inserted)).toBe("untagged");- expect(reviewImages(doc, read)).toEqual({+ expect(reviewAccessibility(doc, read)).toEqual({needsDescription: 0,untagged: 1,untaggable: 0,});- expect(nextImageNeedingAttention(doc, read, null)?.id).toBe(inserted.id);+ expect(nextNeedingAttention(doc, read, null)?.id).toBe(inserted.id);});test("counts an image marked for a missing tree as untaggable", async () => {@@ -512,9 +525,14 @@ describe("reviewing images that need attention", () => {const page = doc.page(0);PdfiumTextReader.populate(doc, page);const read = [- { pageIndex: 0, images: page.images.map((img) => img.snapshot()) },+ {+ pageIndex: 0,+ images: page.images.map((img) => img.snapshot()),+ runs: [] as TextRunSnapshot[],+ display: page.display.toData(),+ },] as PageSnapshot[];- expect(reviewImages(doc, read)).toEqual({+ expect(reviewAccessibility(doc, read)).toEqual({needsDescription: 0,untagged: 0,untaggable: 1,@@ -610,7 +628,7 @@ describe("images drawn by a form XObject", () => {expect(imageAccessibility(doc, figure)).toEqual({kind: "describable",description: "A framed square",- tagged: true,+ type: "Figure",canBeDecorative: true,});});@@ -625,14 +643,19 @@ describe("images drawn by a form XObject", () => {test("counts an untaggable image apart, and Next passes it by", async () => {const doc = await open(formImagesPdf());const read = [- { pageIndex: 0, images: await images(doc) },+ {+ pageIndex: 0,+ images: await images(doc),+ runs: [] as TextRunSnapshot[],+ display: doc.page(0).display.toData(),+ },] as PageSnapshot[];- expect(reviewImages(doc, read)).toEqual({+ expect(reviewAccessibility(doc, read)).toEqual({needsDescription: 0,untagged: 0,untaggable: 1,});- expect(nextImageNeedingAttention(doc, read, null)).toBeNull();+ expect(nextNeedingAttention(doc, read, null)).toBeNull();});test("saves the page's tag on its form as an artifact when marked decorative", async () => {@@ -699,10 +722,18 @@ describe("PageStructure", () => {});test("describes figures and formulas but not elements that hold text", () => {+ const own = (key: string, type: "Formula" | "P", mcid: number) => ({+ ...figure,+ type,+ alt: null,+ mcids: [mcid],+ key,+ block: { key, role: type, type },+ });const s = new PageStructure([figure,- { ...figure, type: "Formula", alt: null, mcids: [5] },- { ...figure, type: "P", alt: null, mcids: [6] },+ own("formula", "Formula", 5),+ own("paragraph", "P", 6),]);expect(s.cannotDescribe(3)).toBeNull();expect(s.cannotDescribe(5)).toBeNull();@@ -710,17 +741,27 @@ describe("PageStructure", () => {expect(s.cannotDescribe(9)).toBe("untagged");});- test("keeps the description when marked decorative, and the mark when described", () => {- const s = new PageStructure([figure]);- s.setAlt(3, "new");- s.setDecorative(4, true);- expect(s.pendingEdits()).toEqual([- { mcid: 4, alt: "new", decorative: true },- ]);- s.setAlt(3, "newer");- expect(s.decorative(3)).toBe(true);- s.setDecorative(3, false);- expect(s.alt(3)).toBe("newer");+ test("describes the block an inline element's content belongs to", () => {+ const span = {+ ...figure,+ role: "Span",+ type: "Span" as const,+ alt: null,+ mcids: [7],+ key: "span",+ };+ const s = new PageStructure(+ [span],+ null,+ null,+ () => null,+ { links: [], widgets: [] },+ undefined,+ (key) => (key === "figure" ? "old" : undefined),+ );+ expect(s.cannotDescribe(7)).toBeNull();+ expect(s.describableType(7)).toBe("Figure");+ expect(s.alt(7)).toBe("old");});test("refuses decorative for a figure with content besides marked content", () => {@@ -753,7 +794,36 @@ describe("SetAltTextCommand", () => {expect(doc.structureEdits()).toEqual([]);history.redo(doc);expect(doc.structureEdits()).toEqual([- { pageIndex: 0, mcid: FIGURE_MCID, alt: "New", decorative: false },+ { pageIndex: 0, mcid: FIGURE_MCID, blockAlt: "New", decorative: false },+ ]);+ });++ test("keeps the description when marked decorative, and the mark when described", async () => {+ const doc = await openSample();+ const history = new HistoryStack();+ const decorative = (on: boolean) =>+ history.execute(+ new SetDecorativeCommand({+ pageIndex: 0,+ mcid: FIGURE_MCID,+ decorative: on,+ }),+ doc,+ );+ history.execute(+ new SetAltTextCommand({ pageIndex: 0, mcid: FIGURE_MCID, alt: "New" }),+ doc,+ );+ decorative(true);+ history.execute(+ new SetAltTextCommand({ pageIndex: 0, mcid: FIGURE_MCID, alt: "Newer" }),+ doc,+ );+ expect(doc.structure(0).decorative(FIGURE_MCID)).toBe(true);+ decorative(false);+ expect(doc.structure(0).alt(FIGURE_MCID)).toBe("Newer");+ expect(doc.structureEdits()).toEqual([+ { pageIndex: 0, mcid: FIGURE_MCID, blockAlt: "Newer", decorative: false },]);});@@ -893,8 +963,8 @@ describe("SetDecorativeCommand", () => {"Figure",);expect(- reviewImages(reopened, [- { pageIndex: 0, images: [image] },+ reviewAccessibility(reopened, [+ { pageIndex: 0, images: [image], runs: [] as TextRunSnapshot[] },] as PageSnapshot[]),).toEqual({needsDescription: 0,@@ -984,9 +1054,10 @@ describe("PageStructure: added figures", () => {);s.addElement(5, "Figure");s.setAlt(5, "Logo");- s.setAlt(3, "Chart");+ expect(() => s.setAlt(3, "Chart")).toThrow();+ s.setDecorative(3, true);expect(s.pendingEdits()).toEqual([- { mcid: 3, alt: "Chart", decorative: false },+ { mcid: 3, alt: null, decorative: true },]);expect(s.addedElements()).toEqual([{ mcid: 5, type: "Figure", alt: "Logo", lang: null },@@ -1036,14 +1107,14 @@ function insertImage(const tagImage = (image: ImageObject,- as: "figure" | "artifact",+ as: "Figure" | "Formula" | "artifact",alt?: string,) => new TagImageCommand({ pageIndex: 0, imageId: image.id, as, alt });const describable = (description: string | null) => ({kind: "describable",description,- tagged: true,+ type: "Figure",canBeDecorative: true,});@@ -1056,7 +1127,7 @@ describe("TagImageCommand", () => {await readPage(doc);const history = new HistoryStack();const image = insertImage(doc, history, 60);- history.execute(tagImage(image, "figure", "A logo"), doc);+ history.execute(tagImage(image, "Figure", "A logo"), doc);expect(marks(doc, image)).toEqual([{ name: "Figure", mcid: 1 }]);expect(imageAccessibility(doc, image.snapshot())).toEqual(describable("A logo"),@@ -1077,7 +1148,7 @@ describe("TagImageCommand", () => {await readPage(doc);const history = new HistoryStack();const image = insertImage(doc, history, 60);- history.execute(tagImage(image, "figure", "A"), doc);+ history.execute(tagImage(image, "Figure", "A"), doc);history.execute(new SetAltTextCommand({ pageIndex: 0, mcid: 1, alt: "A logo" }),doc,@@ -1091,7 +1162,7 @@ describe("TagImageCommand", () => {const doc = await open(imagesPdf());const [, rule] = (await readPage(doc)).images;const history = new HistoryStack();- history.execute(tagImage(rule, "figure"), doc);+ history.execute(tagImage(rule, "Figure"), doc);expect(marks(doc, rule)).toEqual([{ name: "Figure", mcid: 1 }]);expect(imageAccessibility(doc, rule.snapshot())).toEqual(describable(null));@@ -1108,7 +1179,7 @@ describe("TagImageCommand", () => {await readPage(doc);const history = new HistoryStack();const image = insertImage(doc, history, 60);- history.execute(tagImage(image, "figure", "A logo"), doc);+ history.execute(tagImage(image, "Figure", "A logo"), doc);history.execute(tagImage(image, "artifact"), doc);expect(marks(doc, image)).toEqual([{ name: "Artifact", mcid: null }]);expect(doc.structure(0).addedElements()).toEqual([]);@@ -1128,12 +1199,75 @@ describe("TagImageCommand", () => {expect(marks(doc, figure)).toEqual([{ name: "Figure", mcid: 0 }]);});+ test("tags an untagged image as a described formula, and saves it", async () => {+ const doc = await open(imagesPdf());+ await readPage(doc);+ const history = new HistoryStack();+ const image = insertImage(doc, history, 60);+ history.execute(tagImage(image, "Formula", "x squared"), doc);+ expect(marks(doc, image)).toEqual([{ name: "Formula", mcid: 1 }]);+ expect(imageAccessibility(doc, image.snapshot())).toEqual({+ ...describable("x squared"),+ type: "Formula",+ });++ const saved = await readFileStructure(await savedBytes(doc));+ expect(saved!.pages.get(0)!.elements).toMatchObject([+ { type: "Figure", alt: "A grey square" },+ { type: "Formula", alt: "x squared" },+ ]);+ });++ test("retags the file's figure as a formula, keeping its description", async () => {+ const doc = await open(imagesPdf());+ const [figure] = (await readPage(doc)).images;+ const history = new HistoryStack();+ history.execute(+ new RetagBlockCommand({ pageIndex: 0, mcid: 0, type: "Formula" }),+ doc,+ );+ expect(imageAccessibility(doc, figure.snapshot())).toEqual({+ ...describable("A grey square"),+ type: "Formula",+ });++ const saved = await readFileStructure(await savedBytes(doc));+ expect(saved!.pages.get(0)!.elements).toMatchObject([+ { type: "Formula", alt: "A grey square" },+ ]);++ history.undo(doc);+ expect(imageAccessibility(doc, figure.snapshot())).toEqual(+ describable("A grey square"),+ );+ expect(doc.structureEdits()).toEqual([]);+ });++ test("removes the mark of an added figure retagged as a formula", async () => {+ const doc = await open(imagesPdf());+ await readPage(doc);+ const history = new HistoryStack();+ const image = insertImage(doc, history, 60);+ history.execute(tagImage(image, "Figure", "A logo"), doc);+ history.execute(+ new RetagBlockCommand({ pageIndex: 0, mcid: 1, type: "Formula" }),+ doc,+ );+ expect(imageAccessibility(doc, image.snapshot())).toMatchObject({+ type: "Formula",+ description: "A logo",+ });+ history.execute(tagImage(image, "artifact"), doc);+ expect(marks(doc, image)).toEqual([{ name: "Artifact", mcid: null }]);+ expect(doc.structure(0).addedElements()).toEqual([]);+ });+test("tags an image in a document with no structure tree, and saves one for it", async () => {const doc = await open(imagesPdf({ tagged: false }));await readPage(doc);const history = new HistoryStack();const image = insertImage(doc, history, 60);- history.execute(tagImage(image, "figure", "A logo"), doc);+ history.execute(tagImage(image, "Figure", "A logo"), doc);const saved = await readFileStructure(await savedBytes(doc));expect(saved!.pages.get(0)!.elements).toMatchObject([@@ -1160,7 +1294,7 @@ describe("saving an added figure", () => {await readPage(doc);const history = new HistoryStack();const image = insertImage(doc, history, 60);- history.execute(tagImage(image, "figure", "A logo"), doc);+ history.execute(tagImage(image, "Figure", "A logo"), doc);await savedBytes(doc);const { doc: reopened, images } = await reopen(await savedBytes(doc));@@ -1174,7 +1308,7 @@ describe("saving an added figure", () => {await readPage(doc);const history = new HistoryStack();const image = insertImage(doc, history, 170);- history.execute(tagImage(image, "figure", "A logo"), doc);+ history.execute(tagImage(image, "Figure", "A logo"), doc);const { doc: reopened } = await reopen(await savedBytes(doc));expect(tree(reopened)).toEqual(["Document", "A logo", "A grey square"]);@@ -1184,7 +1318,7 @@ describe("saving an added figure", () => {const doc = await open(imagesPdf());const [, rule] = (await readPage(doc)).images;const history = new HistoryStack();- history.execute(tagImage(rule, "figure"), doc);+ history.execute(tagImage(rule, "Figure"), doc);history.execute(new SetAltTextCommand({ pageIndex: 0, mcid: 1, alt: "A divider" }),doc,@@ -1208,7 +1342,9 @@ describe("saving an added figure", () => {const { doc: reopened, images } = await reopen(await savedBytes(doc));expect(images.filter((img) => img.artifact)).toHaveLength(2);expect(- reviewImages(reopened, [{ pageIndex: 0, images }] as PageSnapshot[]),+ reviewAccessibility(reopened, [+ { pageIndex: 0, images, runs: [] as TextRunSnapshot[] },+ ] as PageSnapshot[]),).toEqual({needsDescription: 0,untagged: 0,@@ -1222,7 +1358,7 @@ describe("saving an added figure", () => {await readPage(doc);const history = new HistoryStack();const image = insertImage(doc, history, 60);- history.execute(tagImage(image, "figure", "A logo"), doc);+ history.execute(tagImage(image, "Figure", "A logo"), doc);history.execute(new DeleteImageCommand({ pageIndex: 0, imageId: image.id }),doc,diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureGrouping.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureGrouping.test.tsindex 8775f02feb..f306ae7a18 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureGrouping.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureGrouping.test.ts@@ -19,7 +19,7 @@ import { structureRole } from "@editor/tools/pdfTextEditor/model/structureTypes"import { readFileStructure } from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";import { textTag } from "@editor/tools/pdfTextEditor/util/textAccessibility";-import { RetagTextCommand } from "@editor/tools/pdfTextEditor/commands/RetagTextCommand";+import { RetagBlockCommand } from "@editor/tools/pdfTextEditor/commands/RetagBlockCommand";import { TagTextCommand } from "@editor/tools/pdfTextEditor/commands/TagTextCommand";import { collectMemberPtrs } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";import { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";@@ -419,7 +419,7 @@ describe("Chrome-style tagging", () => {test("retags the heading through the NonStruct holding its text", async () => {const { doc, run } = await openChrome();new HistoryStack().execute(- new RetagTextCommand({+ new RetagBlockCommand({pageIndex: 0,mcid: run("Introduction").snapshot().mcid!,type: "H2",diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textTagging.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textTagging.test.tsindex 37720e7b6f..43be1f3f6c 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textTagging.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textTagging.test.ts@@ -13,7 +13,8 @@ import {vi,} from "vitest";import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";-import { RetagTextCommand } from "@editor/tools/pdfTextEditor/commands/RetagTextCommand";+import { RetagBlockCommand } from "@editor/tools/pdfTextEditor/commands/RetagBlockCommand";+import { SetAltTextCommand } from "@editor/tools/pdfTextEditor/commands/SetAltTextCommand";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";@@ -25,10 +26,12 @@ import { SetMarkedTaggedCommand } from "@editor/tools/pdfTextEditor/commands/Setimport { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";import {+ blockFormulasPdf,buildClassicPdf,singleContentPdf,streamBody,} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";+import { describableTextBlock } from "@editor/tools/pdfTextEditor/util/accessibilityReview";import {sharedTextTag,textTag,@@ -68,7 +71,7 @@ function retag() {const run = runWith(doc, fragment);const mcid = run.snapshot().mcid!;- history.execute(new RetagTextCommand({ pageIndex: PAGE, mcid, type }), doc);+ history.execute(new RetagBlockCommand({ pageIndex: PAGE, mcid, type }), doc);return { run, key: doc.structure(PAGE).block(mcid)!.key };}@@ -176,7 +179,7 @@ describe("retagging text", () => {expect(doc.structure(PAGE).cannotRetag(mcid)).toBe("not-text");expect(() =>new HistoryStack().execute(- new RetagTextCommand({ pageIndex: PAGE, mcid, type: "H2" }),+ new RetagBlockCommand({ pageIndex: PAGE, mcid, type: "H2" }),doc,),).toThrow();@@ -669,6 +672,89 @@ describe("making text an artifact", () => {});});+describe("describing a formula whose text a child element marks", () => {+ async function openFormulas() {+ const doc = await EditorDocument.open(blockFormulasPdf());+ opened.push(doc);+ PdfiumTextReader.populate(doc, doc.page(0));+ PdfiumTextReader.populate(doc, doc.page(1));+ const history = new HistoryStack();+ const mcidOf = (pageIndex: number, fragment: string) =>+ doc+ .page(pageIndex)+ .runs.find((r) => r.text.includes(fragment))!+ .snapshot().mcid!;+ const retagAt = (+ pageIndex: number,+ fragment: string,+ type: StructureType,+ ) =>+ history.execute(+ new RetagBlockCommand({+ pageIndex,+ mcid: mcidOf(pageIndex, fragment),+ type,+ }),+ doc,+ );+ const savedBlock = async (key: string) => {+ const saved = await readFileStructure(await savedBytes(doc));+ return saved!.blocks.find((block) => block.key === key);+ };+ return { doc, history, mcidOf, retagAt, savedBlock };+ }++ test("describes a NonStruct paragraph retagged as a formula, and saves it on the formula", async () => {+ const { doc, history, mcidOf, retagAt, savedBlock } = await openFormulas();+ retagAt(0, "Where x is", "Formula");+ const mcid = mcidOf(0, "Where x is");+ const run = doc+ .page(0)+ .runs.find((r) => r.text.includes("Where x is"))!+ .snapshot();+ expect(doc.structure(0).describableType(mcid)).toBe("Formula");+ expect(describableTextBlock(doc, run)).toEqual({+ key: "10",+ type: "Formula",+ });++ history.execute(+ new SetAltTextCommand({ pageIndex: 0, mcid, alt: "x is a number" }),+ doc,+ );+ expect(await savedBlock("10")).toMatchObject({+ type: "Formula",+ alt: "x is a number",+ });+ });++ test("drops the description of a formula whose text is in a Span when retagged as text", async () => {+ const { doc, history, mcidOf, retagAt, savedBlock } = await openFormulas();+ const mcid = mcidOf(0, "x2 = y");+ expect(doc.structure(0).alt(mcid)).toBe("x squared equals y");+ retagAt(0, "x2 = y", "P");+ expect(doc.structure(0).alt(mcid)).toBeNull();+ expect(await savedBlock("12")).toMatchObject({ type: "P", alt: null });++ history.undo(doc);+ expect(doc.structure(0).alt(mcid)).toBe("x squared equals y");+ expect(doc.structureEdits()).toEqual([]);+ });++ test("drops a description given on one page when the formula is retagged from another", async () => {+ const { doc, history, mcidOf, retagAt, savedBlock } = await openFormulas();+ const second = mcidOf(1, "= c");+ history.execute(+ new SetAltTextCommand({ pageIndex: 1, mcid: second, alt: "a plus b" }),+ doc,+ );+ expect(doc.structure(0).alt(mcidOf(0, "a + b"))).toBe("a plus b");+ retagAt(0, "a + b", "P");+ expect(doc.structure(1).alt(second)).toBeNull();+ expect(await savedBlock("14")).toMatchObject({ type: "P", alt: null });+ });+});+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}`);@@ -701,3 +787,65 @@ function tagAs(}history.execute(command, doc);}++describe("tagging text as a formula", () => {+ function describe_(+ doc: EditorDocument,+ history: HistoryStack,+ fragment: string,+ alt: string | null,+ ) {+ const mcid = runWith(doc, fragment).snapshot().mcid!;+ history.execute(new SetAltTextCommand({ pageIndex: PAGE, mcid, alt }), doc);+ return mcid;+ }++ test("refuses a description on text that is not a formula", async () => {+ const doc = await openSample();+ const mcid = runWith(doc, "All amounts").snapshot().mcid!;+ expect(doc.structure(PAGE).cannotDescribe(mcid)).toBe("not-figure");+ });++ test("describes a paragraph retagged as a formula, and saves both", async () => {+ const doc = await openSample();+ const history = new HistoryStack();+ const { key } = retag(doc, history, "All amounts", "Formula");+ const mcid = describe_(doc, history, "All amounts", "x squared");+ expect(doc.structure(PAGE).describableType(mcid)).toBe("Formula");+ expect(doc.structure(PAGE).alt(mcid)).toBe("x squared");++ const saved = await readFileStructure(await savedBytes(doc));+ const element = saved!.pages+ .get(PAGE)!+ .elements.find((el) => el.key === key);+ expect(element).toMatchObject({ type: "Formula", alt: "x squared" });+ });++ test("drops the description when a formula is retagged as text, and restores it on undo", async () => {+ const doc = await openSample();+ const history = new HistoryStack();+ retag(doc, history, "All amounts", "Formula");+ const mcid = describe_(doc, history, "All amounts", "x squared");+ retag(doc, history, "All amounts", "P");+ expect(doc.structure(PAGE).alt(mcid)).toBeNull();+ expect(doc.structureEdits()).toEqual([]);++ history.undo(doc);+ expect(shownTag(doc, "All amounts")).toBe("Formula");+ expect(doc.structure(PAGE).alt(mcid)).toBe("x squared");+ });++ test("tags untagged text as a described formula", async () => {+ const doc = await openSample();+ const history = new HistoryStack();+ tagText(doc, history, "Confidential", "Formula");+ describe_(doc, history, "Confidential", "E equals m c squared");++ const reopened = await EditorDocument.open(await savedBytes(doc));+ opened.push(reopened);+ PdfiumTextReader.populate(reopened, reopened.page(PAGE));+ const mcid = runWith(reopened, "Confidential").snapshot().mcid!;+ expect(shownTag(reopened, "Confidential")).toBe("Formula");+ expect(reopened.structure(PAGE).alt(mcid)).toBe("E equals m c squared");+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/RetagTextCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/RetagBlockCommand.tssimilarity index 55%rename from frontend/src/editor/core/tools/pdfTextEditor/commands/RetagTextCommand.tsrename to frontend/src/editor/core/tools/pdfTextEditor/commands/RetagBlockCommand.tsindex e3d418555c..85b307da59 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/RetagTextCommand.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/RetagBlockCommand.ts@@ -7,16 +7,20 @@ import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocimport type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";/**- * Retag the whole block the text `mcid` marks belongs to as `type`, or drop- * the session's retag with null. Held on the document and written by the save pass as the- * element's /S; the page content keeps its marks, so it is never regenerated.+ * Retag the whole block the content `mcid` marks belongs to as `type`, or+ * drop the session's retag with null. Held on the document and written by the+ * save pass as the element's /S; the page content keeps its marks, so it is+ * never regenerated. A figure or formula retagged as anything else loses its+ * description, which would otherwise replace the text a reader speaks.*/-export class RetagTextCommand implements Command {- readonly type = "retag-text";+export class RetagBlockCommand implements Command {+ readonly type = "retag-block";private readonly pageIndex: number;private readonly mcid: number;private readonly to: StructureType | null;private previous: StructureType | null | undefined;+ /** The block's description before it was dropped; undefined when it was not. */+ private described: string | undefined;constructor(opts: {pageIndex: number;@@ -30,7 +34,7 @@ export class RetagTextCommand implements Command {apply(doc: EditorDocument): void {const structure = doc.structure(this.pageIndex);- if (structure.cannotRetag(this.mcid)) {+ if (doc.cannotRetagAs(this.pageIndex, this.mcid, this.to)) {throw new RolledBackError(new Error(i18n.t(@@ -43,13 +47,25 @@ export class RetagTextCommand implements Command {if (this.previous === undefined) {this.previous = structure.block(this.mcid)!.type;}+ const description =+ structure.cannotDescribe(this.mcid) === null+ ? structure.alt(this.mcid)+ : null;doc.setRetag(this.pageIndex, this.mcid, this.to);+ if (description !== null && structure.cannotDescribe(this.mcid) !== null) {+ this.described = description;+ doc.setDescription(this.pageIndex, this.mcid, null);+ }doc.page(this.pageIndex).bumpRevision();}revert(doc: EditorDocument): void {if (this.previous === undefined) return;doc.setRetag(this.pageIndex, this.mcid, this.previous);+ if (this.described !== undefined) {+ doc.setDescription(this.pageIndex, this.mcid, this.described);+ this.described = undefined;+ }doc.page(this.pageIndex).bumpRevision();}}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetAltTextCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetAltTextCommand.tsindex 0696594669..3b4762d9c1 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetAltTextCommand.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetAltTextCommand.ts@@ -4,10 +4,10 @@ import {type Command,} from "@editor/tools/pdfTextEditor/commands/Command";import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";-import type { StructureElementEdit } from "@editor/tools/pdfTextEditor/model/PageStructure";/**- * Set or remove the description of the structure element owning `mcid`.+ * Set or remove the description of the block the content `mcid` marks+ * belongs to.* Touches no page content: the edit is held on the document's structure index* and written by the save pass, so the page is never regenerated for it.*/@@ -16,7 +16,7 @@ export class SetAltTextCommand implements Command {private readonly pageIndex: number;private readonly mcid: number;private readonly alt: string | null;- private previous: StructureElementEdit | null | undefined;+ private previous: string | null | undefined;constructor(opts: { pageIndex: number; mcid: number; alt: string | null }) {this.pageIndex = opts.pageIndex;@@ -40,15 +40,15 @@ export class SetAltTextCommand implements Command {);}if (this.previous === undefined) {- this.previous = structure.editFor(this.mcid);+ this.previous = structure.alt(this.mcid);}- structure.setAlt(this.mcid, this.alt);+ doc.setDescription(this.pageIndex, this.mcid, this.alt);doc.page(this.pageIndex).bumpRevision();}revert(doc: EditorDocument): void {if (this.previous === undefined) return;- doc.structure(this.pageIndex).setEdit(this.mcid, this.previous);+ doc.setDescription(this.pageIndex, this.mcid, this.previous);doc.page(this.pageIndex).bumpRevision();}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagImageCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagImageCommand.tsindex 9f1c9c5c66..f8769d2bc4 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagImageCommand.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagImageCommand.ts@@ -6,11 +6,12 @@ import {import { descriptionCoalesceKey } from "@editor/tools/pdfTextEditor/commands/SetAltTextCommand";import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";import type { ImageObject } from "@editor/tools/pdfTextEditor/model/ImageObject";-import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";+import type { DescribableType } from "@editor/tools/pdfTextEditor/model/PageStructure";import {ARTIFACT_TAG,addTagMark,highestMcid,+ readTagMarks,removeTagMark,} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";import {@@ -18,20 +19,18 @@ import {type RetaggableTag,} from "@editor/tools/pdfTextEditor/util/imageAccessibility";-// Marked-content tags conventionally name the structure type they mark.-const FIGURE_TAG: StructureType = "Figure";-/**- * Tag an image as a new Figure, or as an artifact, where retaggableTag allows.- * Unlike a description this changes the image's marks, so the save- * regenerates the content stream that draws it, and the save pass then gives- * a new figure its element.+ * Tag an image as a new Figure or Formula, or as an artifact, where+ * retaggableTag allows. Unlike a description this changes the image's marks,+ * so the save regenerates the content stream that draws it, and the save pass+ * then gives a new element its place in the tree. The mark is named after the+ * element's type, as marked-content tags conventionally are.*/export class TagImageCommand implements Command {readonly type = "tag-image";private readonly pageIndex: number;private readonly imageId: string;- private readonly as: "figure" | "artifact";+ private readonly as: DescribableType | "artifact";private readonly alt: string | null;/** Chosen on first apply, so a redo reuses it. */private mcid: number | null = null;@@ -40,8 +39,8 @@ export class TagImageCommand implements Command {constructor(opts: {pageIndex: number;imageId: string;- as: "figure" | "artifact";- /** The new figure's description. */+ as: DescribableType | "artifact";+ /** The new element's description. */alt?: string | null;}) {this.pageIndex = opts.pageIndex;@@ -65,7 +64,7 @@ export class TagImageCommand implements Command {);}this.previous ??= current;- if (this.as === "figure") {+ if (this.as !== "artifact") {this.mcid ??= doc.structure(this.pageIndex).freeMcid(highestMcid(doc.module, page.pagePtr));@@ -94,7 +93,7 @@ export class TagImageCommand implements Command {private target(): RetaggableTag {if (this.as === "artifact") return { kind: "artifact" };- return { kind: "figure", mcid: this.mcid!, alt: this.alt };+ return { kind: "element", type: this.as, mcid: this.mcid!, alt: this.alt };}}@@ -110,8 +109,10 @@ function retag(if (from.kind === "artifact") {marked(removeTagMark(m, objPtr, ARTIFACT_TAG));}- if (from.kind === "figure") {- marked(removeTagMark(m, objPtr, FIGURE_TAG));+ if (from.kind === "element") {+ // A retag since it was added changed the element's type but not its mark.+ const mark = readTagMarks(m, objPtr).find(({ mcid }) => mcid === from.mcid);+ if (mark) marked(removeTagMark(m, objPtr, mark.name));structure.removeElement(from.mcid);}image.mcid = null;@@ -122,11 +123,9 @@ function retag();image.artifact = true;}- if (to.kind === "figure") {- marked(- addTagMark(m, doc.docPtr, objPtr, { name: FIGURE_TAG, mcid: to.mcid }),- );- structure.addElement(to.mcid, FIGURE_TAG);+ if (to.kind === "element") {+ marked(addTagMark(m, doc.docPtr, objPtr, { name: to.type, mcid: to.mcid }));+ structure.addElement(to.mcid, to.type);if (to.alt !== null) structure.setAlt(to.mcid, to.alt);image.mcid = to.mcid;}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextCommand.tsindex 0d0182f400..a3588c39e7 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextCommand.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextCommand.ts@@ -44,7 +44,7 @@ interface Plan {* 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.+ * RetagBlockCommand changes its type.*/export class TagTextCommand implements Command {readonly type = "tag-text";@@ -120,7 +120,7 @@ function planTagging(const from = retaggableText(doc, snapshot);const members = collectMemberPtrs(run);if (!from || members.includes(0)) return null;- // Already so, or a type change RetagTextCommand makes.+ // Already so, or a type change RetagBlockCommand makes.const unchanged =typeof as === "string"? from.kind === "added"diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/AttentionBadge.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/AttentionBadge.tsxnew file mode 100644index 0000000000..d46c4f1502--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/AttentionBadge.tsx@@ -0,0 +1,55 @@+import type { CSSProperties } from "react";+import { Tooltip } from "@mantine/core";+import { useTranslation } from "react-i18next";+import { Icon } from "@editor/ui/Icon";+import type { ImageAttention } from "@editor/tools/pdfTextEditor/util/imageAccessibility";++/**+ * The warning mark on content the accessibility review flags. `style` places+ * it; the caller's box must be positioned.+ */+export function AttentionBadge({+ attention,+ testId,+ style,+}: {+ attention: ImageAttention;+ testId: string;+ style: CSSProperties;+}) {+ const { t } = useTranslation();+ return (+ <Tooltip+ label={+ attention === "needs-description"+ ? t(+ "pdfTextEditor.inspector.accessibility.needsDescriptionBadge",+ "No description",+ )+ : t(+ "pdfTextEditor.inspector.accessibility.untaggedBadge",+ "Not tagged",+ )+ }+ >+ <span+ data-testid={testId}+ data-attention={attention}+ style={{+ position: "absolute",+ display: "flex",+ padding: 2,+ borderRadius: "50%",+ background: "var(--c-surface)",+ color: "var(--c-warning)",+ boxShadow: "0 0 0 1px var(--c-border)",+ // The text overlay passes pointer events through; the tooltip needs hover.+ pointerEvents: "auto",+ ...style,+ }}+ >+ <Icon name="circle-alert" size={14} />+ </span>+ </Tooltip>+ );+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsxindex df244d6432..7824d343c8 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx@@ -29,7 +29,7 @@ import {scanTypingDropped,} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";import { ScanFontMatchModal } from "@editor/tools/pdfTextEditor/components/inspector/ScanFontMatchModal";-import type { ImageReview } from "@editor/tools/pdfTextEditor/util/imageAccessibility";+import type { AccessibilityReview } from "@editor/tools/pdfTextEditor/util/accessibilityReview";import type {EditorViewState,LoadProgress,@@ -115,8 +115,8 @@ export const EditorSidebar = memo(function EditorSidebar({}, [reviewingAccessibility, tab, imageSelected, artifactTextSelected, store]);// Following the selection only catches one appearing, so moving from one// selected image to the next would leave the new one's description hidden.- const selectNextImageToReview = () => {- if (controller.onSelectNextImageToReview()) setTab("selected");+ const selectNextToReview = () => {+ if (controller.onSelectNextToReview()) setTab("selected");};if (!state.hasDocument) {@@ -189,10 +189,10 @@ export const EditorSidebar = memo(function EditorSidebar({store={store}state={state}reviewingAccessibility={reviewingAccessibility}- imageReview={- reviewingAccessibility ? controller.imageReview : null+ accessibilityReview={+ reviewingAccessibility ? controller.accessibilityReview : null}- onSelectNextImageToReview={selectNextImageToReview}+ onSelectNextToReview={selectNextToReview}onSetGroupingMode={onSetGroupingMode}onSetWidthMode={onSetWidthMode}onSetShowRulers={onSetShowRulers}@@ -210,8 +210,8 @@ function DocumentTab({store,state,reviewingAccessibility,- imageReview,- onSelectNextImageToReview,+ accessibilityReview,+ onSelectNextToReview,onSetGroupingMode,onSetWidthMode,onSetShowRulers,@@ -220,8 +220,8 @@ function DocumentTab({"store" | "state" | "onSetGroupingMode" | "onSetWidthMode" | "onSetShowRulers"> & {reviewingAccessibility: boolean;- imageReview: ImageReview | null;- onSelectNextImageToReview: () => void;+ accessibilityReview: AccessibilityReview | null;+ onSelectNextToReview: () => void;}) {const documentLanguage = useDocumentLanguage(store, state);const headings = useHeadingOutline(store, state, reviewingAccessibility);@@ -240,8 +240,8 @@ function DocumentTab({onSetGroupingMode={onSetGroupingMode}onSetWidthMode={onSetWidthMode}onSetShowRulers={onSetShowRulers}- imageReview={imageReview}- onSelectNextImageToReview={onSelectNextImageToReview}+ accessibilityReview={accessibilityReview}+ onSelectNextToReview={onSelectNextToReview}untaggedPages={bulkTagging.untaggedPages}onTagUntaggedContent={bulkTagging.tagAll}markedTagged={diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsxindex 5725c1da0d..6e9373aa6e 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx@@ -1,9 +1,7 @@import { useEffect, useRef, useState } from "react";import React from "react";import { Rnd, type RndDragEvent } from "react-rnd";-import { Tooltip } from "@mantine/core";-import { useTranslation } from "react-i18next";-import { Icon } from "@editor/ui/Icon";+import { AttentionBadge } from "@editor/tools/pdfTextEditor/components/AttentionBadge";import type { ImageAttention } from "@editor/tools/pdfTextEditor/util/imageAccessibility";import type {ImageObjectSnapshot,@@ -125,7 +123,6 @@ export function ImageHandle({onSettle,pageRevision = -1,}: ImageHandleProps) {- const { t } = useTranslation();const [dragging, setDragging] = useState(false);const [hovered, setHovered] = useState(false);// Shift during a corner drag keeps the proportions, as in Acrobat. Read@@ -410,37 +407,11 @@ export function ImageHandle({</div>)}{attention && (- <Tooltip- label={- attention === "needs-description"- ? t(- "pdfTextEditor.inspector.accessibility.needsDescriptionBadge",- "No description",- )- : t(- "pdfTextEditor.inspector.accessibility.untaggedBadge",- "Not tagged",- )- }- >- <span- data-testid={`pdf-editor-attention-image-${image.id}`}- data-attention={attention}- style={{- position: "absolute",- top: 4,- right: 4,- display: "flex",- padding: 2,- borderRadius: "50%",- background: "var(--c-surface)",- color: "var(--c-warning)",- boxShadow: "0 0 0 1px var(--c-border)",- }}- >- <Icon name="circle-alert" size={14} />- </span>- </Tooltip>+ <AttentionBadge+ attention={attention}+ testId={`pdf-editor-attention-image-${image.id}`}+ style={{ top: 4, right: 4 }}+ />)}</Rnd>);diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsxindex 6b3fe76205..2111b37bbd 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx@@ -1,4 +1,11 @@-import { memo, useEffect, useMemo, useRef, useState } from "react";+import {+ memo,+ useEffect,+ useMemo,+ useRef,+ useState,+ type CSSProperties,+} from "react";import type { FindMatch } from "@editor/tools/pdfTextEditor/store/Selection";import { Box } from "@mantine/core";import { useTranslation } from "react-i18next";@@ -21,9 +28,10 @@ import {import { TableOverlay } from "@editor/tools/pdfTextEditor/components/TableOverlay";import { ACCESSIBILITY_EDITING } from "@editor/constants/featureFlags";import {- imageAttention,- type ImageAttention,-} from "@editor/tools/pdfTextEditor/util/imageAccessibility";+ pageAttention,+ type PageAttention,+} from "@editor/tools/pdfTextEditor/util/accessibilityReview";+import { AttentionBadge } from "@editor/tools/pdfTextEditor/components/AttentionBadge";import { ImageHandle } from "@editor/tools/pdfTextEditor/components/ImageHandle";import { readShownImagePixels } from "@editor/tools/pdfTextEditor/util/imagePixels";import { visibleImageBounds } from "@editor/tools/pdfTextEditor/util/imageClip";@@ -157,15 +165,13 @@ export const PageView = memo(function PageView({onFirstPainted,}: PageViewProps) {const { t } = useTranslation();- const imageAttentions = useMemo(() => {- const out = new Map<string, ImageAttention>();- if (!ACCESSIBILITY_EDITING) return out;- for (const image of page.images) {- const attention = imageAttention(document, image);- if (attention) out.set(image.id, attention);- }- return out;- }, [document, page]);+ const attention = useMemo(+ (): PageAttention =>+ ACCESSIBILITY_EDITING+ ? pageAttention(document, page)+ : { images: new Map(), runs: new Map() },+ [document, page],+ );const runGrowEdges = useMemo(() =>widthMode === "grow" ? growEdges(page.runs) : new Map<string, GrowEdge>(),@@ -520,7 +526,7 @@ export const PageView = memo(function PageView({onTransformCommit={(next) =>onTransformImage?.(page.pageIndex, image.id, next)}- attention={imageAttentions.get(image.id) ?? null}+ attention={attention.images.get(image.id) ?? null}readPixels={() =>readShownImagePixels(store, page.pageIndex, image.id)}@@ -579,6 +585,16 @@ export const PageView = memo(function PageView({}/>))}+ {page.runs+ .filter((run) => attention.runs.has(run.id))+ .map((run) => (+ <AttentionBadge+ key={run.id}+ attention="needs-description"+ testId={`pdf-editor-attention-run-${run.id}`}+ style={besideRun(run, transform, page.height, cssScale)}+ />+ ))}{showRulers && (<PageGuidespageIndex={page.pageIndex}@@ -593,6 +609,23 @@ export const PageView = memo(function PageView({);});+/** Just past the top-right corner of a run's box, in page pixels. */+function besideRun(+ run: TextRunSnapshot,+ transform: DisplayTransform,+ pageHeight: number,+ scale: number,+): CSSProperties {+ const { x, y, width, height } = run.bounds;+ const corners = [+ transform.apply(x, y),+ transform.apply(x + width, y + height),+ ];+ const right = Math.max(...corners.map((c) => c.x));+ const top = Math.max(...corners.map((c) => c.y));+ return { left: right * scale + 4, top: (pageHeight - top) * scale };+}+// Long enough a typing pause to draw the page whole, repairing anything a partial redraw missed.const FULL_REDRAW_AFTER_TYPING_MS = 400;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsxindex d17ae18492..f85d6e3c1a 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsx@@ -3,10 +3,10 @@ import { fireEvent, render, screen, within } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";import { DocumentInspector } from "@editor/tools/pdfTextEditor/components/inspector/DocumentInspector";import type { DocumentLanguageControl } from "@editor/tools/pdfTextEditor/hooks/useDocumentLanguage";-import type { ImageReview } from "@editor/tools/pdfTextEditor/util/imageAccessibility";+import type { AccessibilityReview } from "@editor/tools/pdfTextEditor/util/accessibilityReview";function renderInspector(- imageReview: ImageReview | null,+ accessibilityReview: AccessibilityReview | null,onNext = vi.fn(),documentLanguage: DocumentLanguageControl | null = null,{@@ -33,8 +33,8 @@ function renderInspector(onSetGroupingMode={vi.fn()}onSetWidthMode={vi.fn()}onSetShowRulers={vi.fn()}- imageReview={imageReview}- onSelectNextImageToReview={onNext}+ accessibilityReview={accessibilityReview}+ onSelectNextToReview={onNext}untaggedPages={untaggedPages}onTagUntaggedContent={onTagUntagged}markedTagged={markedTagged}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsxindex 0c6c1a2ac4..0c037bb1d1 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsx@@ -24,7 +24,8 @@ import type {PageSnapshot,WidthMode,} from "@editor/tools/pdfTextEditor/types";-import type { ImageReview } from "@editor/tools/pdfTextEditor/util/imageAccessibility";+import type { AccessibilityReview } from "@editor/tools/pdfTextEditor/util/accessibilityReview";+import { NextToReviewButton } from "@editor/tools/pdfTextEditor/components/inspector/NextToReviewButton";import type { HeadingOutline } from "@editor/tools/pdfTextEditor/util/headingOutline";import { HeadingOutlineSection } from "@editor/tools/pdfTextEditor/components/inspector/HeadingOutlineSection";@@ -36,9 +37,9 @@ interface Props {onSetGroupingMode: (mode: GroupingMode) => void;onSetWidthMode: (mode: WidthMode) => void;onSetShowRulers: (show: boolean) => void;- /** Images needing attention; null when there is nothing to review. */- imageReview: ImageReview | null;- onSelectNextImageToReview: () => void;+ /** Images and text needing attention; null when there is nothing to review. */+ accessibilityReview: AccessibilityReview | null;+ onSelectNextToReview: () => void;/** Read pages with content left untagged. */untaggedPages: number;onTagUntaggedContent: () => void;@@ -57,8 +58,8 @@ interface Props {/** Facts about the open document. Nothing here acts on a selection. */export function DocumentInspector({pages,- imageReview,- onSelectNextImageToReview,+ accessibilityReview,+ onSelectNextToReview,untaggedPages,onTagUntaggedContent,markedTagged,@@ -96,10 +97,10 @@ export function DocumentInspector({<DocumentLanguageField control={documentLanguage} />)}</Section>- {imageReview && (+ {accessibilityReview && (<AccessibilitySection- review={imageReview}- onNext={onSelectNextImageToReview}+ review={accessibilityReview}+ onNext={onSelectNextToReview}untaggedPages={untaggedPages}onTagUntagged={onTagUntaggedContent}markedTagged={markedTagged}@@ -187,7 +188,7 @@ function AccessibilitySection({onSetMarkedTagged,hasTags,}: {- review: ImageReview;+ review: AccessibilityReview;onNext: () => void;untaggedPages: number;onTagUntagged: () => void;@@ -238,18 +239,10 @@ function AccessibilitySection({hasTags={hasTags}/>{pending > 0 && (- <Button- size="sm"- variant="secondary"- accent="neutral"- fullWidth- justify="start"- leftSection={<Icon name="arrow-right" size={20} />}+ <NextToReviewButtononClick={onNext}- data-testid="pdf-editor-document-accessibility-next"- >- {t("pdfTextEditor.inspector.accessibility.nextImage", "Next image")}- </Button>+ testId="pdf-editor-document-accessibility-next"+ />)}</Stack></Section>diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ImageAccessibilitySection.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ImageAccessibilitySection.test.tsxindex 77003665ab..c153650199 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ImageAccessibilitySection.test.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ImageAccessibilitySection.test.tsx@@ -2,16 +2,15 @@ import { MantineProvider } from "@mantine/core";import { fireEvent, render, screen } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";import { ImageAccessibilitySection } from "@editor/tools/pdfTextEditor/components/inspector/ImageAccessibilitySection";-import type {- ImageAccessibility,- ImageReview,-} from "@editor/tools/pdfTextEditor/util/imageAccessibility";+import type { ImageAccessibility } from "@editor/tools/pdfTextEditor/util/imageAccessibility";+import type { AccessibilityReview } from "@editor/tools/pdfTextEditor/util/accessibilityReview";function renderSection(accessibility: ImageAccessibility,{review = { needsDescription: 0, untagged: 0, untaggable: 0 },onSetDescription = vi.fn(),+ onSetType = vi.fn(),onSetDecorative = vi.fn(),onNext = vi.fn(),} = {},@@ -21,13 +20,14 @@ function renderSection(<ImageAccessibilitySectionaccessibility={accessibility}onSetDescription={onSetDescription}+ onSetType={onSetType}onSetDecorative={onSetDecorative}review={review}onNext={onNext}/></MantineProvider>,);- return { onSetDescription, onSetDecorative, onNext };+ return { onSetDescription, onSetType, onSetDecorative, onNext };}const KEY = "pdfTextEditor.inspector.accessibility";@@ -41,13 +41,13 @@ const describable = (): ImageAccessibility => ({kind: "describable",description,- tagged: true,+ type: "Figure",canBeDecorative,});const taggable: ImageAccessibility = {kind: "describable",description: null,- tagged: false,+ type: null,canBeDecorative: true,};const untagged: ImageAccessibility = {@@ -147,7 +147,7 @@ describe("ImageAccessibilitySection", () => {expect(onNext).toHaveBeenCalledOnce();});- it.each<[string, ImageAccessibility, ImageReview, boolean]>([+ it.each<[string, ImageAccessibility, AccessibilityReview, boolean]>([["only this one needs a description",describable(null),@@ -203,4 +203,29 @@ describe("ImageAccessibilitySection", () => {expect(screen.queryByTestId(NEXT) !== null).toBe(offered);},);+ it("tags an image as a formula and names its description so", () => {+ const { onSetType } = renderSection({+ kind: "describable",+ description: "x squared",+ type: "Formula",+ canBeDecorative: true,+ });+ expect(screen.getByLabelText(`${KEY}.formulaDescription`)).toHaveValue(+ "x squared",+ );+ const picker = screen.getByRole("textbox", { name: `${KEY}.tagLabel` });+ expect(picker).toHaveValue(`${KEY}.tagName.formula`);+ fireEvent.click(picker);+ fireEvent.click(screen.getByText(`${KEY}.tagName.figure`));+ expect(onSetType).toHaveBeenCalledWith("Figure");+ });++ it("offers an untagged image both types", () => {+ const { onSetType } = renderSection(taggable);+ const picker = screen.getByRole("textbox", { name: `${KEY}.tagLabel` });+ expect(picker).toHaveValue("");+ fireEvent.click(picker);+ fireEvent.click(screen.getByText(`${KEY}.tagName.formula`));+ expect(onSetType).toHaveBeenCalledWith("Formula");+ });});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ImageAccessibilitySection.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ImageAccessibilitySection.tsxindex 1675fbf087..f92f54f8a7 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ImageAccessibilitySection.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ImageAccessibilitySection.tsx@@ -2,37 +2,45 @@ import { Stack, Text, Textarea } from "@mantine/core";import type { TFunction } from "i18next";import { useTranslation } from "react-i18next";import { Tooltip } from "@editor/components/shared/Tooltip";-import { Button } from "@editor/ui/Button";import { Checkbox } from "@editor/ui/Checkbox";import { Icon } from "@editor/ui/Icon";+import { Select } from "@editor/ui/Select";import {+ Field,Section,SectionLabel,} from "@editor/tools/pdfTextEditor/components/inspector/InspectorPrimitives";+import {+ DESCRIBABLE_TYPES,+ type DescribableType,+} from "@editor/tools/pdfTextEditor/model/PageStructure";import {attentionFor,isActionable,type ImageAccessibility,- type ImageReview,} from "@editor/tools/pdfTextEditor/util/imageAccessibility";+import type { AccessibilityReview } from "@editor/tools/pdfTextEditor/util/accessibilityReview";+import { NextToReviewButton } from "@editor/tools/pdfTextEditor/components/inspector/NextToReviewButton";import { privateContentClassName } from "@editor/components/shared/privateContentClassName";/**- * The selected image's description or decorative mark, or why it cannot have- * either, and a way on to the next image needing attention. `review` counts- * this image too.+ * The selected image's tag as a figure or formula and its description, or+ * its decorative mark, or why it cannot have any, and a way on to the next+ * image or text needing attention. `review` counts this image too.*/export function ImageAccessibilitySection({accessibility,onSetDescription,+ onSetType,onSetDecorative,review,onNext,}: {accessibility: ImageAccessibility;onSetDescription: (text: string) => void;+ onSetType: (type: DescribableType) => void;onSetDecorative: (decorative: boolean) => void;- review: ImageReview;+ review: AccessibilityReview;onNext: () => void;}) {const { t } = useTranslation();@@ -56,6 +64,9 @@ export function ImageAccessibilitySection({</Text>) : (<>+ {accessibility.kind === "describable" && (+ <TypePicker type={accessibility.type} onSetType={onSetType} />+ )}<Checkboxlabel={t("pdfTextEditor.inspector.accessibility.decorativeLabel",@@ -81,10 +92,17 @@ export function ImageAccessibilitySection({/>{accessibility.kind === "describable" && (<Textarea- label={t(- "pdfTextEditor.inspector.accessibility.description",- "Image description",- )}+ label={+ accessibility.type === "Formula"+ ? t(+ "pdfTextEditor.inspector.accessibility.formulaDescription",+ "Formula description",+ )+ : t(+ "pdfTextEditor.inspector.accessibility.description",+ "Image description",+ )+ }value={accessibility.description ?? ""}className={privateContentClassName}onChange={(e) => onSetDescription(e.currentTarget.value)}@@ -98,24 +116,60 @@ export function ImageAccessibilitySection({</>)}{othersPending > 0 && (- <Button- size="sm"- variant="secondary"- accent="neutral"- fullWidth- justify="start"- leftSection={<Icon name="arrow-right" size={20} />}+ <NextToReviewButtononClick={onNext}- data-testid="pdf-editor-image-description-next"- >- {t("pdfTextEditor.inspector.accessibility.nextImage", "Next image")}- </Button>+ testId="pdf-editor-image-description-next"+ />)}</Stack></Section>);}+/**+ * Whether the image is a figure or a formula; an untagged one is given an+ * element of the type picked.+ */+function TypePicker({+ type,+ onSetType,+}: {+ type: DescribableType | null;+ onSetType: (type: DescribableType) => void;+}) {+ const { t } = useTranslation();+ const label = t("pdfTextEditor.inspector.accessibility.tagLabel", "Tag");+ return (+ <Field label={label}>+ <div data-testid="pdf-editor-image-tag-picker">+ <Select+ inputSize="sm"+ options={DESCRIBABLE_TYPES.map((option) => ({+ value: option,+ label: typeName(t, option),+ }))}+ value={type}+ placeholder={t(+ "pdfTextEditor.inspector.accessibility.untaggedBadge",+ "Not tagged",+ )}+ onChange={(value) => {+ const picked = DESCRIBABLE_TYPES.find((option) => option === value);+ if (picked) onSetType(picked);+ }}+ aria-label={label}+ />+ </div>+ </Field>+ );+}++function typeName(t: TFunction, type: DescribableType): string {+ return type === "Formula"+ ? t("pdfTextEditor.inspector.accessibility.tagName.formula", "Formula")+ : t("pdfTextEditor.inspector.accessibility.tagName.figure", "Figure");+}+function blockedMessage(t: TFunction,accessibility: Extract<ImageAccessibility, { kind: "blocked" }>,diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/NextToReviewButton.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/NextToReviewButton.tsxnew file mode 100644index 0000000000..089b6f5ee1--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/NextToReviewButton.tsx@@ -0,0 +1,31 @@+import { useTranslation } from "react-i18next";+import { Button } from "@editor/ui/Button";+import { Icon } from "@editor/ui/Icon";++/** Selects the next image or text the accessibility review flags. */+export function NextToReviewButton({+ onClick,+ testId,+}: {+ onClick: () => void;+ testId: string;+}) {+ const { t } = useTranslation();+ return (+ <Button+ size="sm"+ variant="secondary"+ accent="neutral"+ fullWidth+ justify="start"+ leftSection={<Icon name="arrow-right" size={20} />}+ onClick={onClick}+ data-testid={testId}+ >+ {t(+ "pdfTextEditor.inspector.accessibility.nextToReview",+ "Next to review",+ )}+ </Button>+ );+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsxindex 54bb78aa8f..e290fd6837 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx@@ -89,16 +89,20 @@ export function SelectionInspector({inner={controller.innerTextTags}language={controller.textLanguage}otherPages={controller.textOtherPages}+ description={controller.textDescription}untaggedLinks={controller.textUntaggedLinks}+ review={controller.accessibilityReview}+ onNext={controller.onSelectNextToReview}/>)}{ACCESSIBILITY_EDITING && controller.imageAccessibility && (<ImageAccessibilitySectionaccessibility={controller.imageAccessibility}onSetDescription={controller.onSetImageDescription}+ onSetType={controller.onSetImageType}onSetDecorative={controller.onSetImageDecorative}- review={controller.imageReview}- onNext={controller.onSelectNextImageToReview}+ review={controller.accessibilityReview}+ onNext={controller.onSelectNextToReview}/>)}{ACCESSIBILITY_EDITING && controller.formFieldAccessibility && (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 65a87b839d..07edb4eadb 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@@ -9,9 +9,15 @@ import type {UntaggedLinksControl,} from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";import type { TextTag } from "@editor/tools/pdfTextEditor/util/textAccessibility";+import type { AccessibilityReview } from "@editor/tools/pdfTextEditor/util/accessibilityReview";const KEY = "pdfTextEditor.inspector.accessibility";const LANGUAGE_KEY = "pdfTextEditor.inspector.language";+const NO_REVIEW: AccessibilityReview = {+ needsDescription: 0,+ untagged: 0,+ untaggable: 0,+};const NO_INNER: InnerTagsControl = {tags: [],active: null,@@ -33,7 +39,10 @@ function tagShown(tag: TextTag): HTMLElement {inner={NO_INNER}language={null}otherPages={null}+ description={null}untaggedLinks={null}+ review={NO_REVIEW}+ onNext={vi.fn()}/></MantineProvider>,);@@ -103,7 +112,10 @@ describe("TextAccessibilitySection", () => {inner={NO_INNER}language={null}otherPages={null}+ description={null}untaggedLinks={null}+ review={NO_REVIEW}+ onNext={vi.fn()}/></MantineProvider>,);@@ -114,6 +126,98 @@ describe("TextAccessibilitySection", () => {expect(onRetag).toHaveBeenCalledWith("Code");});+ it("edits the description of text tagged as a formula", () => {+ const onSet = vi.fn();+ render(+ <MantineProvider env="test">+ <TextAccessibilitySection+ tag={{+ kind: "tagged",+ block: structureRole("Formula"),+ cannotRetag: null,+ canBeArtifact: true,+ }}+ onSetTag={vi.fn()}+ inner={NO_INNER}+ language={null}+ otherPages={null}+ description={{ type: "Formula", description: "x squared", onSet }}+ untaggedLinks={null}+ review={NO_REVIEW}+ onNext={vi.fn()}+ />+ </MantineProvider>,+ );+ const field = screen.getByRole("textbox", {+ name: `${KEY}.formulaDescription`,+ });+ expect(field).toHaveValue("x squared");+ fireEvent.change(field, { target: { value: "x squared plus one" } });+ expect(onSet).toHaveBeenCalledWith("x squared plus one");+ });++ it.each([+ ["only this formula needs a description", null, 1, false],+ ["another needs one too", null, 2, true],+ ["this one is described and another is not", "x squared", 1, true],+ ])("offers Next when %s", (_, description, pending, shown) => {+ const onNext = vi.fn();+ render(+ <MantineProvider env="test">+ <TextAccessibilitySection+ tag={{+ kind: "tagged",+ block: structureRole("Formula"),+ cannotRetag: null,+ canBeArtifact: true,+ }}+ onSetTag={vi.fn()}+ inner={NO_INNER}+ language={null}+ otherPages={null}+ description={{ type: "Formula", description, onSet: vi.fn() }}+ untaggedLinks={null}+ review={{ ...NO_REVIEW, needsDescription: pending }}+ onNext={onNext}+ />+ </MantineProvider>,+ );+ const next = screen.queryByTestId("pdf-editor-text-description-next");+ expect(next !== null).toBe(shown);+ if (next) {+ fireEvent.click(next);+ expect(onNext).toHaveBeenCalled();+ }+ });++ it("offers formula among the types text can be tagged as", () => {+ const onSetTag = vi.fn();+ render(+ <MantineProvider env="test">+ <TextAccessibilitySection+ tag={{+ kind: "tagged",+ block: structureRole("P"),+ cannotRetag: null,+ canBeArtifact: true,+ }}+ onSetTag={onSetTag}+ inner={NO_INNER}+ language={null}+ otherPages={null}+ description={null}+ untaggedLinks={null}+ review={NO_REVIEW}+ onNext={vi.fn()}+ />+ </MantineProvider>,+ );+ expect(screen.queryByTestId("pdf-editor-text-description")).toBeNull();+ fireEvent.click(screen.getByRole("textbox", { name: `${KEY}.tagLabel` }));+ fireEvent.click(screen.getByText(`${KEY}.tagName.formula`));+ expect(onSetTag).toHaveBeenCalledWith("Formula");+ });+it("offers making the text decorative", () => {const onSetTag = vi.fn();render(@@ -128,7 +232,10 @@ describe("TextAccessibilitySection", () => {inner={NO_INNER}language={null}otherPages={null}+ description={null}untaggedLinks={null}+ review={NO_REVIEW}+ onNext={vi.fn()}/></MantineProvider>,);@@ -147,7 +254,10 @@ describe("TextAccessibilitySection", () => {inner={NO_INNER}language={null}otherPages={null}+ description={null}untaggedLinks={null}+ review={NO_REVIEW}+ onNext={vi.fn()}/></MantineProvider>,);@@ -166,7 +276,10 @@ describe("TextAccessibilitySection", () => {inner={NO_INNER}language={null}otherPages={null}+ description={null}untaggedLinks={null}+ review={NO_REVIEW}+ onNext={vi.fn()}/></MantineProvider>,);@@ -187,7 +300,10 @@ describe("TextAccessibilitySection", () => {inner={NO_INNER}language={null}otherPages={null}+ description={null}untaggedLinks={null}+ review={NO_REVIEW}+ onNext={vi.fn()}/></MantineProvider>,);@@ -212,7 +328,10 @@ describe("TextAccessibilitySection", () => {inner={NO_INNER}language={null}otherPages={null}+ description={null}untaggedLinks={null}+ review={NO_REVIEW}+ onNext={vi.fn()}/></MantineProvider>,);@@ -232,7 +351,10 @@ describe("TextAccessibilitySection", () => {inner={NO_INNER}language={null}otherPages={{ pages: 3, onApply }}+ description={null}untaggedLinks={null}+ review={NO_REVIEW}+ onNext={vi.fn()}/></MantineProvider>,);@@ -250,7 +372,10 @@ describe("TextAccessibilitySection", () => {inner={NO_INNER}language={null}otherPages={null}+ description={null}untaggedLinks={null}+ review={NO_REVIEW}+ onNext={vi.fn()}/></MantineProvider>,);@@ -275,7 +400,10 @@ describe("TextAccessibilitySection", () => {inner={NO_INNER}language={null}otherPages={null}+ description={null}untaggedLinks={null}+ review={NO_REVIEW}+ onNext={vi.fn()}/></MantineProvider>,);@@ -378,7 +506,10 @@ describe("TextAccessibilitySection", () => {inner={innerControl()}language={{ language: undefined, onSet: vi.fn() }}otherPages={null}+ description={null}untaggedLinks={null}+ review={NO_REVIEW}+ onNext={vi.fn()}/></MantineProvider>,);@@ -514,7 +645,10 @@ function renderSection(inner={inner}language={language}otherPages={null}+ description={null}untaggedLinks={untaggedLinks}+ review={NO_REVIEW}+ onNext={vi.fn()}/></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 0d6aab529b..b0046e057c 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsx@@ -15,7 +15,10 @@ import {FURNITURE,type Furniture,} from "@editor/tools/pdfTextEditor/model/artifactKind";-import { TEXT_BLOCK_TYPES } from "@editor/tools/pdfTextEditor/model/PageStructure";+import {+ TEXT_BLOCK_TYPES,+ type DescribableType,+} from "@editor/tools/pdfTextEditor/model/PageStructure";import type {StructureRole,StructureType,@@ -31,17 +34,22 @@ import {import type {InnerTagsControl,OtherPagesControl,+ TextDescriptionControl,TextLanguageControl,UntaggedLinksControl,} from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";import { LanguagePicker } from "@editor/tools/pdfTextEditor/components/inspector/LanguagePicker";import "@editor/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.css";import { privateContentClassName } from "@editor/components/shared/privateContentClassName";+import { NextToReviewButton } from "@editor/tools/pdfTextEditor/components/inspector/NextToReviewButton";+import type { AccessibilityReview } from "@editor/tools/pdfTextEditor/util/accessibilityReview";/*** What the selected text is tagged as and the language it is read in, with* pickers to change them: retagging its block, giving untagged text an- * element of its own, or making it an artifact. Beneath them, the tags marking parts of the text, a+ * element of its own, or making it an artifact. A formula or figure also+ * takes a description, with a way on to the next image or text needing+ * attention; `review` counts this text too. Beneath them, the tags marking parts of the text, a* way to tag the links over it, and pickers for characters selected in it.* With several runs selected, the tag they share and their language.*/@@ -51,14 +59,20 @@ export function TextAccessibilitySection({inner,language,otherPages,+ description,untaggedLinks,+ review,+ onNext,}: {tag: TextTag | null;onSetTag: (choice: TextTagChoice) => void;inner: InnerTagsControl;language: TextLanguageControl | null;otherPages: OtherPagesControl | null;+ description: TextDescriptionControl | null;untaggedLinks: UntaggedLinksControl | null;+ review: AccessibilityReview;+ onNext: () => void;}) {const { t } = useTranslation();return (@@ -68,6 +82,13 @@ export function TextAccessibilitySection({</SectionLabel><Stack gap="xs">{tag && <TagField tag={tag} onSetTag={onSetTag} />}+ {description && (+ <DescriptionField+ control={description}+ review={review}+ onNext={onNext}+ />+ )}{otherPages && <OtherPagesButton control={otherPages} />}{language && <TextLanguageField control={language} />}{tag && (@@ -181,6 +202,71 @@ function artifactValue(furniture: Furniture | null): string {return `${ARTIFACT_VALUE}${furniture ?? ""}`;}+/** What screen readers read out in place of the formula or figure the text makes up. */+function DescriptionField({+ control,+ review,+ onNext,+}: {+ control: TextDescriptionControl;+ review: AccessibilityReview;+ onNext: () => void;+}) {+ const { t } = useTranslation();+ const label = descriptionLabel(t, control.type);+ const othersPending =+ review.needsDescription ++ review.untagged -+ (control.description?.trim() ? 0 : 1);+ return (+ <>+ <Field label={label} hint={descriptionHint(t, control.type)}>+ <Textarea+ aria-label={label}+ value={control.description ?? ""}+ className={privateContentClassName}+ onChange={(e) => control.onSet(e.currentTarget.value)}+ autosize+ minRows={2}+ maxRows={6}+ size="xs"+ data-testid="pdf-editor-text-description"+ />+ </Field>+ {othersPending > 0 && (+ <NextToReviewButton+ onClick={onNext}+ testId="pdf-editor-text-description-next"+ />+ )}+ </>+ );+}++function descriptionLabel(t: TFunction, type: DescribableType): string {+ return type === "Formula"+ ? t(+ "pdfTextEditor.inspector.accessibility.formulaDescription",+ "Formula description",+ )+ : t(+ "pdfTextEditor.inspector.accessibility.figureDescription",+ "Figure description",+ );+}++function descriptionHint(t: TFunction, type: DescribableType): string {+ return type === "Formula"+ ? t(+ "pdfTextEditor.inspector.accessibility.formulaDescriptionInfo",+ 'Screen readers read this out in place of the formula. Say it as you would aloud, such as "x squared plus one".',+ )+ : t(+ "pdfTextEditor.inspector.accessibility.figureDescriptionInfo",+ "Screen readers read this out in place of the figure.",+ );+}+/** Gives matching text on other pages the selected artifact's kind. */function OtherPagesButton({ control }: { control: OtherPagesControl }) {const { t } = useTranslation();diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useAccessibilityReview.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useAccessibilityReview.tsnew file mode 100644index 0000000000..5541affdcd--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useAccessibilityReview.ts@@ -0,0 +1,60 @@+import { useCallback, useMemo } from "react";+import { ensureAllPagesRead } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";+import type {+ EditorStore,+ EditorViewState,+} from "@editor/tools/pdfTextEditor/store/EditorStore";+import {+ nextNeedingAttention,+ reviewAccessibility,+ type AccessibilityReview,+} from "@editor/tools/pdfTextEditor/util/accessibilityReview";+import { revealOnPage } from "@editor/tools/pdfTextEditor/util/dom";++/**+ * The images and text needing attention, and a way to select the next one.+ * `review` covers only pages read so far.+ */+export function useAccessibilityReview(+ store: EditorStore,+ state: EditorViewState,+) {+ const review = useMemo(+ (): AccessibilityReview =>+ store.document+ ? reviewAccessibility(store.document, state.pages)+ : { needsDescription: 0, untagged: 0, untaggable: 0 },+ [store, state.pages],+ );++ /** False when nothing needs attention, leaving the selection alone. */+ const selectNext = useCallback((): boolean => {+ // Content on a page not yet scrolled to would otherwise be skipped.+ ensureAllPagesRead(store);+ const doc = store.document;+ if (!doc) return false;+ const { imageIds, runIds } = store.selection.value;+ const next = nextNeedingAttention(+ doc,+ store.getState().pages,+ imageIds[0] ?? runIds[0] ?? null,+ );+ if (!next) return false;+ if (next.kind === "image") store.selection.selectImage(next.id);+ else store.selection.selectOne(next.id);+ const testId =+ next.kind === "image"+ ? `pdf-editor-image-${next.id}`+ : `pdf-editor-run-${next.id}`;+ // A page read just now has no overlay until React commits it.+ window.requestAnimationFrame(() =>+ revealOnPage(+ document.querySelector(`[data-testid="${testId}"]`),+ next.pageIndex,+ ),+ );+ return true;+ }, [store]);++ return { review, selectNext };+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useImageAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useImageAccessibility.tsindex 02bcd7d616..060301b09e 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useImageAccessibility.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useImageAccessibility.ts@@ -1,10 +1,11 @@import { useCallback, useMemo } from "react";import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";+import { RetagBlockCommand } from "@editor/tools/pdfTextEditor/commands/RetagBlockCommand";import { SetAltTextCommand } from "@editor/tools/pdfTextEditor/commands/SetAltTextCommand";import { SetDecorativeCommand } from "@editor/tools/pdfTextEditor/commands/SetDecorativeCommand";import { TagImageCommand } from "@editor/tools/pdfTextEditor/commands/TagImageCommand";-import { ensureAllPagesRead } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import type { DescribableType } from "@editor/tools/pdfTextEditor/model/PageStructure";import type {EditorStore,EditorViewState,@@ -15,18 +16,13 @@ import type {} from "@editor/tools/pdfTextEditor/types";import {imageAccessibility,- nextImageNeedingAttention,retaggableTag,- reviewImages,type ImageAccessibility,- type ImageReview,} from "@editor/tools/pdfTextEditor/util/imageAccessibility";-import { revealOnPage } from "@editor/tools/pdfTextEditor/util/dom";/**- * The accessibility of the selected image (null unless exactly one image and- * nothing else is selected), and the review of images needing attention.- * `review` covers only pages read so far.+ * The accessibility of the selected image: null unless exactly one image and+ * nothing else is selected.*/export function useImageAccessibility(store: EditorStore,@@ -62,6 +58,15 @@ export function useImageAccessibility([store, image, accessibility],);+ const setType = useCallback(+ (type: DescribableType) => {+ if (!image || accessibility?.kind !== "describable") return;+ if (type === accessibility.type) return;+ store.dispatch(typeCommand(image, type));+ },+ [store, image, accessibility],+ );+const setDecorative = useCallback((decorative: boolean) => {const doc = store.document;@@ -72,43 +77,11 @@ export function useImageAccessibility([store, image],);- const review = useMemo(- (): ImageReview =>- store.document- ? reviewImages(store.document, state.pages)- : { needsDescription: 0, untagged: 0, untaggable: 0 },- [store, state.pages],- );-- /** False when no image needs attention, leaving the selection alone. */- const selectNextImage = useCallback((): boolean => {- // An image on a page not yet scrolled to would otherwise be skipped.- ensureAllPagesRead(store);- const doc = store.document;- if (!doc) return false;- const next = nextImageNeedingAttention(- doc,- store.getState().pages,- store.selection.value.imageIds[0] ?? null,- );- if (!next) return false;- store.selection.selectImage(next.id);- // A page read just now has no overlay until React commits it.- window.requestAnimationFrame(() =>- revealOnPage(- document.querySelector(`[data-testid="pdf-editor-image-${next.id}"]`),- next.pageIndex,- ),- );- return true;- }, [store]);-return {accessibility,setDescription,+ setType,setDecorative,- review,- selectNextImage,};}@@ -128,11 +101,22 @@ function describeCommand(return new TagImageCommand({pageIndex: image.pageIndex,imageId: image.id,- as: "figure",+ as: "Figure",alt,});}+/** An untagged image is given an element of `type`; a tagged one is retagged. */+function typeCommand(+ image: ImageObjectSnapshot,+ type: DescribableType,+): Command {+ const { pageIndex, mcid } = image;+ if (mcid !== undefined)+ return new RetagBlockCommand({ pageIndex, mcid, type });+ return new TagImageCommand({ pageIndex, imageId: image.id, as: type });+}+/*** Content the file's elements own changes through its element; anything* else is retagged.@@ -146,7 +130,7 @@ function decorativeCommand(return new TagImageCommand({pageIndex: image.pageIndex,imageId: image.id,- as: decorative ? "artifact" : "figure",+ as: decorative ? "artifact" : "Figure",});}if (image.mcid === undefined) return null;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.test.tsxindex 5a7a56ccc2..445520138c 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.test.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.test.tsx@@ -126,3 +126,99 @@ describe("useTextAccessibility other pages", () => {store.dispose();});});++/** A formula drawn as two lines of text, one element over both, then a paragraph. */+function formulaPdf(): Uint8Array {+ return buildClassicPdf(+ [+ {+ num: 1,+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 6 0 R /MarkInfo << /Marked true >> >>",+ },+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },+ {+ num: 3,+ body:+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /StructParents 0 " ++ "/Resources << /Font << /F1 5 0 R >> >> >>",+ },+ {+ num: 4,+ body: streamBody(+ "",+ "/Formula <</MCID 0>> BDC BT /F1 12 Tf 72 700 Td (a = b) Tj ET EMC\n" ++ "/Formula <</MCID 1>> BDC BT /F1 12 Tf 72 600 Td (c = d) Tj ET EMC\n" ++ "/P <</MCID 2>> BDC BT /F1 12 Tf 72 500 Td (Where a is) Tj ET EMC\n",+ ),+ },+ {+ num: 5,+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ },+ {+ num: 6,+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 10 0 R /ParentTreeNextKey 1 >>",+ },+ {+ num: 7,+ body: "<< /Type /StructElem /S /Document /P 6 0 R /K [8 0 R 9 0 R] >>",+ },+ {+ num: 8,+ body: "<< /Type /StructElem /S /Formula /P 7 0 R /Pg 3 0 R /K [0 1] >>",+ },+ {+ num: 9,+ body: "<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K 2 >>",+ },+ { num: 10, body: "<< /Nums [0 [8 0 R 8 0 R 9 0 R]] >>" },+ ],+ 1,+ );+}++describe("useTextAccessibility description", () => {+ it("describes a formula selected across its runs, and nothing mixed with other text", async () => {+ const store = new EditorStore();+ const doc = await EditorDocument.open(formulaPdf());+ await store.setDocument(doc);+ const page = doc.page(0);+ store.publishPages([+ {+ pageIndex: 0,+ width: page.width,+ height: page.height,+ dirty: false,+ revision: 0,+ runs: [],+ images: [],+ shapes: [],+ display: page.display.toData(),+ },+ ]);+ ensurePageRead(store, 0);+ const runs = store.getState().pages[0].runs;+ const idOf = (text: string) => runs.find((r) => r.text.includes(text))!.id;+ const render = () =>+ renderHook(() =>+ useTextAccessibility(store, store.getState(), store.selection.value),+ );++ store.selection.selectOne(idOf("a = b"));+ store.selection.toggle(idOf("c = d"));+ const { result, rerender } = render();+ expect(result.current.description).toMatchObject({+ type: "Formula",+ description: null,+ });+ act(() => result.current.description!.onSet("a equals b, c equals d"));+ rerender();+ expect(result.current.description?.description).toBe(+ "a equals b, c equals d",+ );++ store.selection.toggle(idOf("Where a is"));+ expect(render().result.current.description).toBeNull();+ store.dispose();+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.tsindex 4a4da50a20..88ab6b633c 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts@@ -3,7 +3,8 @@ import { ACCESSIBILITY_EDITING } from "@editor/constants/featureFlags";import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";import { CompositeCommand } from "@editor/tools/pdfTextEditor/commands/CompositeCommand";import { RetagInnerCommand } from "@editor/tools/pdfTextEditor/commands/RetagInnerCommand";-import { RetagTextCommand } from "@editor/tools/pdfTextEditor/commands/RetagTextCommand";+import { RetagBlockCommand } from "@editor/tools/pdfTextEditor/commands/RetagBlockCommand";+import { SetAltTextCommand } from "@editor/tools/pdfTextEditor/commands/SetAltTextCommand";import { SetDecorativeCommand } from "@editor/tools/pdfTextEditor/commands/SetDecorativeCommand";import { SetInnerLanguageCommand } from "@editor/tools/pdfTextEditor/commands/SetInnerLanguageCommand";import { SetLinkContentsCommand } from "@editor/tools/pdfTextEditor/commands/SetLinkContentsCommand";@@ -21,7 +22,12 @@ import {TagTextRangeCommand,} from "@editor/tools/pdfTextEditor/commands/TagTextRangeCommand";import type { Furniture } from "@editor/tools/pdfTextEditor/model/artifactKind";+import type { DescribableType } from "@editor/tools/pdfTextEditor/model/PageStructure";import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";+import {+ describableTextBlock,+ documentBlockId,+} from "@editor/tools/pdfTextEditor/util/accessibilityReview";import type { TextLanguage } from "@editor/tools/pdfTextEditor/model/languageTag";import type {EditorStore,@@ -84,6 +90,14 @@ export interface TextLanguageControl {onSet: (lang: string | null) => void;}+/** The description of the formula or figure the selected text makes up, and a way to change it. */+export interface TextDescriptionControl {+ type: DescribableType;+ description: string | null;+ /** An empty string removes the description. */+ onSet: (text: string) => void;+}+/*** The tag of the selected text, the one shared by every selected run (null* unless only runs are selected), and a way to set it on all of them. For one@@ -162,6 +176,27 @@ export function useTextAccessibility(};}, [store, state.pages, run, tag]);+ const description = useMemo((): TextDescriptionControl | null => {+ const doc = store.document;+ const element = doc ? describedElement(doc, targets) : null;+ if (!doc || !element) return null;+ const { pageIndex, mcid } = element;+ const structure = doc.structure(pageIndex);+ return {+ type: element.type,+ description: structure.alt(mcid),+ onSet: (text) =>+ store.dispatch(+ new SetAltTextCommand({+ pageIndex,+ mcid,+ alt: text === "" ? null : text,+ }),+ ),+ };+ // state.pages: a description change republishes the pages, not the targets.+ }, [store, targets, state.pages]);+const untaggedLinks = useMemo((): UntaggedLinksControl | null => {const doc = store.document;const links = doc && run ? taggableLinks(doc, run.pageIndex, run.id) : [];@@ -356,10 +391,35 @@ export function useTextAccessibility(inner: innerControl,language,otherPages,+ description,untaggedLinks,};}+/**+ * The figure or formula every selected run's text belongs to, addressed by+ * one of its MCIDs; null when the runs do not all make up one that can take+ * a description.+ */+function describedElement(+ doc: EditorDocument,+ targets: readonly { run: TextRunSnapshot; tag: TextTag }[],+): { pageIndex: number; mcid: number; type: DescribableType } | null {+ const [first, ...rest] = targets.map(({ run }) => run);+ const described = first ? describableTextBlock(doc, first) : null;+ if (!first || !described) return null;+ // A file block may continue on the next page; one description covers it.+ const block = documentBlockId(doc, first.pageIndex, described.key);+ const sameBlock = rest.every((run) => {+ if (run.mcid === undefined || run.inForm) return false;+ const key = doc.structure(run.pageIndex).block(run.mcid)?.key;+ return !!key && documentBlockId(doc, run.pageIndex, key) === block;+ });+ return sameBlock+ ? { pageIndex: first.pageIndex, mcid: first.mcid!, type: described.type }+ : null;+}+/*** The text the selection's runs are tagged as, for setting their blocks'* language; null unless only runs are selected and every one can take one.@@ -453,7 +513,7 @@ function typeCommand(const { pageIndex, mcid } = run;if (tag.kind === "tagged") {if (tag.cannotRetag !== null || mcid === undefined) return null;- return new RetagTextCommand({ pageIndex, mcid, type });+ return new RetagBlockCommand({ pageIndex, mcid, type });}if (tag.kind === "untagged" || tag.kind === "artifact") {if (!tag.taggable) return null;@@ -464,7 +524,7 @@ function typeCommand(}return new CompositeCommand([new SetDecorativeCommand({ pageIndex, mcid, decorative: false }),- new RetagTextCommand({ pageIndex, mcid, type }),+ new RetagBlockCommand({ pageIndex, mcid, type }),]);}return null;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.tsindex 43eddcecb0..58a3510199 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts@@ -6,6 +6,7 @@ import {useSyncExternalStore,} from "react";import { useSelectionActions } from "@editor/tools/pdfTextEditor/hooks/useSelectionActions";+import { useAccessibilityReview } from "@editor/tools/pdfTextEditor/hooks/useAccessibilityReview";import { useFormFieldAccessibility } from "@editor/tools/pdfTextEditor/hooks/useFormFieldAccessibility";import { useImageAccessibility } from "@editor/tools/pdfTextEditor/hooks/useImageAccessibility";import { useTextAccessibility } from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";@@ -95,6 +96,7 @@ export function useToolbarController(const sel = useSelectionActions(store);const history = useHistoryFlags(store);const imageA11y = useImageAccessibility(store, state, selection);+ const a11yReview = useAccessibilityReview(store, state);const textA11y = useTextAccessibility(store, state, selection);const formFieldA11y = useFormFieldAccessibility(store, state, selection);@@ -605,14 +607,16 @@ export function useToolbarController(externalEditSupported: isExternalImageEditSupported(),imageAccessibility: imageA11y.accessibility,onSetImageDescription: imageA11y.setDescription,+ onSetImageType: imageA11y.setType,onSetImageDecorative: imageA11y.setDecorative,- imageReview: imageA11y.review,- onSelectNextImageToReview: imageA11y.selectNextImage,+ accessibilityReview: a11yReview.review,+ onSelectNextToReview: a11yReview.selectNext,textTag: textA11y.tag,onSetTextTag: textA11y.setTag,innerTextTags: textA11y.inner,textLanguage: textA11y.language,textOtherPages: textA11y.otherPages,+ textDescription: textA11y.description,textUntaggedLinks: textA11y.untaggedLinks,formFieldAccessibility: formFieldA11y.accessibility,onTagFormField: formFieldA11y.tag,diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.tsindex 365ce485ed..5411a30032 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts@@ -9,10 +9,13 @@ import { documentClosed } from "@editor/tools/pdfTextEditor/pdfium/pointerCachesimport {PageStructure,givenMcids,+ isDescribableType,isInlineType,type AddedElement,type CutElement,+ type DescriptionBlocker,type ReadOnlyReason,+ type RetagBlocker,} from "@editor/tools/pdfTextEditor/model/PageStructure";import {effectiveLanguage,@@ -94,6 +97,13 @@ export class EditorDocument {string,{ pageIndex: number; mcid: number; lang: string | null }>();+ /** Unsaved /Alt changes to the file's blocks, by block key, held here as retags are. */+ private readonly blockAlts = new Map<+ string,+ { pageIndex: number; mcid: number; alt: string | null }+ >();+ /** The file's blocks' /Alt, by block key. */+ private readonly fileBlockAlts: ReadonlyMap<string, string | null>;/** The catalog /Lang as the file has it; null when it has none. */private readonly fileDocumentLang: string | null;/** The session's catalog /Lang; undefined when unchanged. */@@ -142,6 +152,9 @@ export class EditorDocument {this.docPtr = docPtr;this.openedBytes = openedBytes;this.fileStructure = fileStructure;+ this.fileBlockAlts = new Map(+ fileStructure?.blocks.map(({ key, alt }) => [key, alt]),+ );this.fileDocumentLang = readCatalogLang(module, docPtr);this.marked = fileStructure?.marked ?? false;this.pageCache = new Map();@@ -365,6 +378,7 @@ export class EditorDocument {widgets: this.fileStructure.widgets.get(pageIndex) ?? [],};const retaggedAs = (key: string) => this.retaggedAs(key);+ const describedAs = (key: string) => this.blockDescription(key);if (!page) {return new PageStructure([],@@ -373,6 +387,7 @@ export class EditorDocument {retaggedAs,annotations,this.fieldTooltips,+ describedAs,);}if (page.slotCount === null) return new PageStructure([], "unreadable");@@ -383,6 +398,7 @@ export class EditorDocument {retaggedAs,annotations,this.fieldTooltips,+ describedAs,);}@@ -438,13 +454,30 @@ export class EditorDocument {}/**- * Retag the block the text `mcid` marks belongs to as `type`. Null, or the- * type it has in the file, drops the change. Throws when cannotRetag+ * Why the block `mcid` marks cannot be retagged as `type`, or null when it+ * can: a block of text as any type, and a figure or formula as either,+ * since only its /S changes and it may hold content other than text.+ */+ cannotRetagAs(+ pageIndex: number,+ mcid: number,+ type: StructureType | null,+ ): RetagBlocker | DescriptionBlocker | null {+ const structure = this.structure(pageIndex);+ if (isDescribableType(type) && structure.cannotDescribe(mcid) === null) {+ return null;+ }+ return structure.cannotRetag(mcid);+ }++ /**+ * Retag the block the content `mcid` marks belongs to as `type`. Null, or+ * the type it has in the file, drops the change. Throws when cannotRetagAs* refuses it: a retag the save cannot write would fail every later save.*/setRetag(pageIndex: number, mcid: number, type: StructureType | null): void {const structure = this.structure(pageIndex);- const blocker = structure.cannotRetag(mcid);+ const blocker = this.cannotRetagAs(pageIndex, mcid, type);if (blocker) throw new Error(`MCID ${mcid} cannot be retagged: ${blocker}`);const block = structure.element(mcid)!.block;// An added element is not in the file yet: its type is just changed.@@ -462,6 +495,49 @@ export class EditorDocument {}}+ private blockDescription(key: string): string | null | undefined {+ const edit = this.blockAlts.get(key);+ return edit ? edit.alt : this.fileBlockAlts.get(key);+ }++ /**+ * Set or, with null, remove the description of the block the content+ * `mcid` marks belongs to, on every page it spans. Throws when no element+ * owns `mcid`. Whether the block can take one is the caller's to check+ * (cannotDescribe): a retag clears the description of a block it has just+ * made a paragraph.+ */+ setDescription(pageIndex: number, mcid: number, alt: string | null): void {+ const structure = this.structure(pageIndex);+ const block = structure.block(mcid);+ if (!block) throw new Error(`No structure element owns MCID ${mcid}`);+ const added = structure.addedBlockMcid(block.key);+ if (added !== null) {+ structure.setAlt(added, alt);+ return;+ }+ if (alt === (this.fileBlockAlts.get(block.key) ?? null)) {+ this.blockAlts.delete(block.key);+ } else {+ // The save climbs from the element owning this to the same block.+ const address = structure.fileMcid(mcid)!;+ this.blockAlts.set(block.key, { pageIndex, mcid: address, alt });+ }+ this.republishPagesHolding(block.key, pageIndex);+ }++ /**+ * Bumps every other read page showing block `key`, so its snapshot, and the+ * badges drawn from it, follow a change made through `pageIndex`.+ */+ private republishPagesHolding(key: string, pageIndex: number): void {+ for (const [index, structure] of this.structureCache) {+ if (index !== pageIndex && structure.holdsBlock(key)) {+ this.pageCache.get(index)?.bumpRevision();+ }+ }+ }+/** The language the document is read in, as the session has it; null when unknown. */documentLanguage(): string | null {return this.documentLangEdit === undefined@@ -684,6 +760,14 @@ export class EditorDocument {decorative: false,}),);+ const blockAlts = [...this.blockAlts.values()].map(+ ({ pageIndex, mcid, alt }) => ({+ pageIndex,+ mcid,+ blockAlt: alt,+ decorative: false,+ }),+ );return [...[...this.structureCache].flatMap(([pageIndex, structure]) => [...structure.pendingEdits().map((edit) => ({ pageIndex, ...edit })),@@ -704,6 +788,7 @@ export class EditorDocument {]),...retags,...blockLangs,+ ...blockAlts,];}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.tsindex 85e8c96f2c..c2e3365f47 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts@@ -128,10 +128,18 @@ export interface StructureElementEdit {* Types whose /Alt stands in for the content. On any other element it would* replace text a reader speaks, so a description there is refused.*/-const DESCRIBABLE_TYPES: ReadonlySet<StructureType> = new Set<StructureType>([+export const DESCRIBABLE_TYPES = ["Figure","Formula",-]);+] as const satisfies readonly StructureType[];++export type DescribableType = (typeof DESCRIBABLE_TYPES)[number];++export function isDescribableType(+ type: StructureType | null,+): type is DescribableType {+ return DESCRIBABLE_TYPES.some((describable) => describable === type);+}/** Why the save cannot write descriptions for a page. */export type ReadOnlyReason = "encrypted" | "unreadable";@@ -162,6 +170,7 @@ export const TEXT_BLOCK_TYPES = ["Quote","Note","Code",+ "Formula",] as const satisfies readonly StructureType[];/**@@ -202,6 +211,12 @@ export type RetagBlocker = "untagged" | "not-text" | ReadOnlyReason;/** The type the session has retagged a block as, by block key; null when it has not. */export type RetagLookup = (key: string) => StructureType | null;+/**+ * The description of one of the file's blocks as the session has it, by+ * block key; undefined when the document knows no such block.+ */+export type DescriptionLookup = (key: string) => string | null | undefined;+type AddedStructureElement = StructureElement & { type: StructureType };/**@@ -299,8 +314,11 @@ export interface LinkEdit {/*** The structure elements of one page plus the session's unsaved edits to* them, and the elements it adds. Edits are keyed by element rather than MCID,- * so an element that owns several MCIDs has one description however it was- * addressed.+ * so an element that owns several MCIDs has one edit however it was+ * addressed. A description belongs to the block, not to the element owning+ * the content: the document holds the file's blocks' (DescriptionLookup), as+ * a block can span pages and own no content itself; the page holds those of+ * the blocks it adds.*/export class PageStructure {readonly elements: readonly StructureElement[];@@ -346,6 +364,7 @@ export class PageStructure {*/private readonly slotCount: number | null;private readonly retaggedAs: RetagLookup;+ private readonly describedAs: DescriptionLookup;constructor(elements: readonly StructureElement[],@@ -354,11 +373,13 @@ export class PageStructure {retaggedAs: RetagLookup = () => null,annotations: PageAnnotations = NO_ANNOTATIONS,fieldTooltips?: FieldTooltips,+ describedAs: DescriptionLookup = () => undefined,) {this.elements = elements;this.readOnly = readOnly;this.slotCount = slotCount;this.retaggedAs = retaggedAs;+ this.describedAs = describedAs;this.linkAnnotations = new Map(annotations.links.map((link) => [link.annotation, link]),);@@ -414,15 +435,24 @@ export class PageStructure {return this.readOnly;}- /** Why the content `mcid` marks cannot take a description, or null when it can. */+ /**+ * Why the block the content `mcid` marks belongs to cannot take a+ * description, or null when it can.+ */cannotDescribe(mcid: number): DescriptionBlocker | null {- const el = this.element(mcid);- if (!el) return "untagged";+ const block = this.block(mcid);+ if (!block) return "untagged";if (this.readOnly) return this.readOnly;- if (el.type === null || !DESCRIBABLE_TYPES.has(el.type)) {- return "not-figure";- }- return null;+ return isDescribableType(block.type) ? null : "not-figure";+ }++ /**+ * The figure or formula type of the block the content `mcid` marks belongs+ * to, as the session has it; null when it is neither.+ */+ describableType(mcid: number): DescribableType | null {+ const type = this.block(mcid)?.type ?? null;+ return isDescribableType(type) ? type : null;}/**@@ -434,8 +464,9 @@ export class PageStructure {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";+ if (!isDescribableType(el.type) && !this.isFileTextBlock(el)) {+ return "not-content";+ }return el.onlyMarkedContent && !this.hasCutsFrom(el)? null: "mixed-content";@@ -465,10 +496,22 @@ export class PageStructure {return (edit?.decorative && edit.furniture) || null;}- /** The description as it will be saved: the session's edit, else the file's. */+ /**+ * The description of the block the content `mcid` marks belongs to, as it+ * will be saved: the session's edit, else the file's.+ */alt(mcid: number): string | null {- const el = this.element(mcid);- if (!el) return null;+ const key = this.element(mcid)?.block.key;+ if (key === undefined) return null;+ const added = this.addedBlockMcid(key);+ if (added !== null) return this.ownAlt(this.added.get(added)!);+ const described = this.describedAs(key);+ if (described !== undefined) return described;+ const own = this.elements.find((el) => el.key === key);+ return own ? this.ownAlt(own) : null;+ }++ private ownAlt(el: StructureElement): string | null {const edit = this.edits.get(el);return edit ? edit.alt : el.alt;}@@ -479,8 +522,12 @@ export class PageStructure {return el ? (this.edits.get(el) ?? null) : null;}- /** Set the description, keeping any decorative mark. Throws as setEdit does. */+ /**+ * Set the description of the element added for `mcid`. Throws when none+ * was added: the document holds the file's blocks' descriptions.+ */setAlt(mcid: number, alt: string | null): void {+ if (!this.added.has(mcid)) throw new Error(`MCID ${mcid} was not added`);const edit = this.editFor(mcid);this.setEdit(mcid, {mcid,@@ -503,15 +550,14 @@ export class PageStructure {if (this.added.has(mcid)) {throw new Error(`MCID ${mcid} is an added element`);}- const alt = this.alt(mcid);+ // Unmarking leaves no edit: the description is the document's, not the mark's.if (!decorative) {- const unchanged = alt === this.element(mcid)?.alt;- this.setEdit(mcid, unchanged ? null : { mcid, alt, decorative });+ this.setEdit(mcid, null);return;}this.setEdit(mcid, {mcid,- alt,+ alt: this.alt(mcid),decorative,...(furniture && { furniture }),});@@ -670,13 +716,16 @@ export class PageStructure {/** Elements cut from others' text, in the order they were cut. */cutElements(): CutElement[] {- return [...this.cuts].map(([mcid, { cut }]) => ({- mcid,- type: this.added.get(mcid)?.type ?? null,- alt: this.alt(mcid),- lang: this.langs.get(addedKey(mcid)) ?? null,- cut,- }));+ return [...this.cuts].map(([mcid, { cut }]) => {+ const element = this.added.get(mcid);+ return {+ mcid,+ type: element?.type ?? null,+ alt: element ? this.ownAlt(element) : null,+ lang: this.langs.get(addedKey(mcid)) ?? null,+ cut,+ };+ });}/** True when the element is a block of text, which a block cut out of it can split. */@@ -818,7 +867,7 @@ export class PageStructure {const element: AddedElement = {mcid,type: this.added.get(mcid)!.type,- alt: this.alt(mcid),+ alt: this.ownAlt(this.added.get(mcid)!),lang: this.langs.get(addedKey(mcid)) ?? null,};if (this.follows.has(mcid)) element.follows = this.follows.get(mcid)!;@@ -869,6 +918,11 @@ export class PageStructure {return null;}+ /** Whether any of this page's content belongs to block `key`. */+ holdsBlock(key: string): boolean {+ return this.elements.some((el) => el.block.key === key);+ }+/** The MCID of the element the session added that is block `key`; null for a block the file has. */addedBlockMcid(key: string): number | null {for (const [mcid, element] of this.added) {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.tsindex 8c845d5a7c..48861e142b 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts@@ -50,6 +50,8 @@ export interface StructureEdit {lang?: string | null;/** As `lang`, for the block the element belongs to, as `type` is. */blockLang?: string | null;+ /** As `alt`, for the block the element belongs to, as `type` is. */+ blockAlt?: 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. */@@ -146,7 +148,10 @@ export async function applyStructureEdits(unwraps.push({ edit, owner });continue;}- const ofBlock = edit.type !== undefined || edit.blockLang !== undefined;+ const ofBlock =+ edit.type !== undefined ||+ edit.blockLang !== undefined ||+ edit.blockAlt !== undefined;const target = ofBlock ? nodes.blockOf(owner) : owner;const body = bodies.get(target) ?? pdf.objectBody(target);const updated = body === null ? null : edited(pdf, body, edit, target);@@ -279,8 +284,9 @@ function edited(): string | null {let out: string | null = body;const type = edit.type ?? edit.ownType;- if (edit.alt !== undefined) {- out = withTextEntry(out, "Alt", edit.alt);+ const alt = edit.blockAlt !== undefined ? edit.blockAlt : edit.alt;+ if (alt !== undefined) {+ out = withTextEntry(out, "Alt", alt);}const lang = edit.blockLang !== undefined ? edit.blockLang : edit.lang;if (out !== null && lang !== undefined) {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.tsindex 59bd685804..7192a1956e 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts@@ -36,6 +36,7 @@ export interface FileBlock extends StructureRole {pageIndex: number | null;/** Its MCIDs on that page, its inline elements' included. */mcids: number[];+ alt: string | null;}/** An element's /Lang, and its nearest ancestor's. */@@ -198,6 +199,7 @@ function readBlocks(type: node.type,pageIndex: at?.pageIndex ?? null,mcids: at ? [...at.mcids].sort((a, b) => a - b) : [],+ alt: textEntry(pdf, kidBody, "Alt"),});}visit(kidBody);@@ -214,10 +216,7 @@ function readElement(): ElementInfo | null {const body = pdf.objectBody(num);if (!body) return null;- const text = (key: string): string | null => {- const value = pdf.resolve(body, key);- return value === null ? null : decodeTextString(value.trim());- };+ const text = (key: string) => textEntry(pdf, body, key);return {role: node.role,type: node.type,@@ -229,3 +228,8 @@ function readElement(onlyMarkedContent: ownsOnlyMarkedContent(pdf, body),};}++function textEntry(pdf: RawPdf, body: string, key: string): string | null {+ const value = pdf.resolve(body, key);+ return value === null ? null : decodeTextString(value.trim());+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/accessibilityReview.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/accessibilityReview.test.tsnew file mode 100644index 0000000000..12a3387dc6--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/accessibilityReview.test.ts@@ -0,0 +1,165 @@+import { readFile } from "node:fs/promises";+import { createRequire } from "node:module";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { SetAltTextCommand } from "@editor/tools/pdfTextEditor/commands/SetAltTextCommand";+import { RetagBlockCommand } from "@editor/tools/pdfTextEditor/commands/RetagBlockCommand";+import { ensurePageRead } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";+import {+ nextNeedingAttention,+ pageAttention,+ reviewAccessibility,+} from "@editor/tools/pdfTextEditor/util/accessibilityReview";+import {+ blockFormulasPdf,+ formulasPdf,+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";++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();+});++async function openFormulas() {+ const store = new EditorStore();+ const doc = await EditorDocument.open(formulasPdf());+ await store.setDocument(doc);+ const page = doc.page(0);+ store.publishPages([+ {+ pageIndex: 0,+ width: page.width,+ height: page.height,+ dirty: false,+ revision: 0,+ runs: [],+ images: [],+ shapes: [],+ display: page.display.toData(),+ },+ ]);+ ensurePageRead(store, 0);+ const pages = () => store.getState().pages;+ const idOf = (text: string) =>+ pages()[0].runs.find((r) => r.text.includes(text))!.id;+ return { store, doc, pages, idOf };+}++describe("reviewing text that makes up a formula", () => {+ it("flags an undescribed formula once, on its first run", async () => {+ const { store, doc, pages, idOf } = await openFormulas();+ expect([...pageAttention(doc, pages()[0]).runs.keys()]).toEqual([+ idOf("a = b"),+ ]);+ expect(reviewAccessibility(doc, pages()).needsDescription).toBe(1);+ store.dispose();+ });++ it("walks Next to the formula from anywhere, and stops once it is described", async () => {+ const { store, doc, pages, idOf } = await openFormulas();+ const target = { kind: "text", id: idOf("a = b"), pageIndex: 0 };+ expect(nextNeedingAttention(doc, pages(), null)).toEqual(target);+ expect(nextNeedingAttention(doc, pages(), idOf("Where a is"))).toEqual(+ target,+ );+ expect(nextNeedingAttention(doc, pages(), idOf("a = b"))).toEqual(target);++ store.dispatch(+ new SetAltTextCommand({ pageIndex: 0, mcid: 0, alt: "a equals b" }),+ );+ expect(reviewAccessibility(doc, pages()).needsDescription).toBe(0);+ expect(nextNeedingAttention(doc, pages(), null)).toBeNull();+ store.dispose();+ });++ it("flags a paragraph once retagged as a formula, and drops it retagged back", async () => {+ const { store, doc, pages, idOf } = await openFormulas();+ store.dispatch(+ new RetagBlockCommand({ pageIndex: 0, mcid: 3, type: "Formula" }),+ );+ expect(pageAttention(doc, pages()[0]).runs.has(idOf("Where a is"))).toBe(+ true,+ );+ expect(reviewAccessibility(doc, pages()).needsDescription).toBe(2);++ store.dispatch(new RetagBlockCommand({ pageIndex: 0, mcid: 3, type: "P" }));+ expect(reviewAccessibility(doc, pages()).needsDescription).toBe(1);+ store.dispose();+ });+});++describe("reviewing a formula that continues on the next page", () => {+ async function openSpanning() {+ const store = new EditorStore();+ const doc = await EditorDocument.open(blockFormulasPdf());+ await store.setDocument(doc);+ store.publishPages(+ [0, 1].map((pageIndex) => {+ 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);+ ensurePageRead(store, 1);+ const pages = () => store.getState().pages;+ const idOf = (pageIndex: number, text: string) =>+ pages()[pageIndex].runs.find((r) => r.text.includes(text))!.id;+ return { store, doc, pages, idOf };+ }++ it("flags both halves but counts and visits the formula once", async () => {+ const { store, doc, pages, idOf } = await openSpanning();+ expect(pageAttention(doc, pages()[0]).runs.has(idOf(0, "a + b"))).toBe(+ true,+ );+ expect(pageAttention(doc, pages()[1]).runs.has(idOf(1, "= c"))).toBe(true);+ expect(reviewAccessibility(doc, pages()).needsDescription).toBe(1);++ const first = { kind: "text", id: idOf(0, "a + b"), pageIndex: 0 };+ expect(nextNeedingAttention(doc, pages(), null)).toEqual(first);+ expect(nextNeedingAttention(doc, pages(), idOf(1, "= c"))).toEqual(first);+ store.dispose();+ });++ it("clears the other page's flag when the formula is described from one", async () => {+ const { store, doc, pages } = await openSpanning();+ const before = pages()[0].revision;+ store.dispatch(+ new SetAltTextCommand({ pageIndex: 1, mcid: 0, alt: "a plus b" }),+ );+ expect(pages()[0].revision).not.toBe(before);+ expect(pageAttention(doc, pages()[0]).runs.size).toBe(0);+ expect(reviewAccessibility(doc, pages()).needsDescription).toBe(0);++ const described = pages()[0].revision;+ store.undo();+ expect(pages()[0].revision).not.toBe(described);+ expect(pageAttention(doc, pages()[0]).runs.size).toBe(1);+ store.dispose();+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/accessibilityReview.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/accessibilityReview.tsnew file mode 100644index 0000000000..c32386efe8--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/accessibilityReview.ts@@ -0,0 +1,216 @@+import { DisplayTransform } from "@editor/tools/pdfTextEditor/model/DisplayTransform";+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import type { DescribableType } from "@editor/tools/pdfTextEditor/model/PageStructure";+import type {+ PageRect,+ PageSnapshot,+ TextRunSnapshot,+} from "@editor/tools/pdfTextEditor/types";+import {+ imageAttention,+ isActionable,+ type ImageAttention,+} from "@editor/tools/pdfTextEditor/util/imageAccessibility";++/**+ * One identity for block `key` on page `pageIndex` across the document. A+ * file block's key is already unique to the file; a block the session added+ * is keyed by its MCID, which other pages reuse, so it is scoped to its page.+ */+export function documentBlockId(+ doc: EditorDocument,+ pageIndex: number,+ key: string,+): string {+ return doc.structure(pageIndex).addedBlockMcid(key) === null+ ? key+ : `${pageIndex}/${key}`;+}++/**+ * The figure or formula block a run's text belongs to, by block key, when it+ * can take a description here; null for any other text.+ */+export function describableTextBlock(+ doc: EditorDocument,+ run: TextRunSnapshot,+): { key: string; type: DescribableType } | null {+ if (run.mcid === undefined || run.inForm) return null;+ const structure = doc.structure(run.pageIndex);+ const type = structure.describableType(run.mcid);+ const block = structure.block(run.mcid);+ if (+ !type ||+ !block ||+ structure.cannotDescribe(run.mcid) !== null ||+ structure.decorative(run.mcid)+ ) {+ return null;+ }+ return { key: block.key, type };+}++/**+ * Why each image and run on a page needs the user's attention. Text is+ * flagged on the first run of a figure or formula with no description, so an+ * element drawn as several runs counts once, and not at all when one of its+ * images already carries the flag.+ */+export interface PageAttention {+ images: Map<string, ImageAttention>;+ runs: Map<string, "needs-description">;+}++export function pageAttention(+ doc: EditorDocument,+ page: PageSnapshot,+): PageAttention {+ const images = new Map<string, ImageAttention>();+ const seen = new Set<string>();+ // Read only for content that may need it: a page with none never opens it.+ const structure = () => doc.structure(page.pageIndex);+ for (const image of page.images) {+ const attention = imageAttention(doc, image);+ if (!attention) continue;+ images.set(image.id, attention);+ const block =+ image.mcid === undefined ? null : structure().block(image.mcid);+ if (block) seen.add(block.key);+ }+ const runs = new Map<string, "needs-description">();+ for (const run of page.runs) {+ const describable = describableTextBlock(doc, run);+ if (!describable || seen.has(describable.key)) continue;+ seen.add(describable.key);+ if (!structure().alt(run.mcid!)?.trim()) {+ runs.set(run.id, "needs-description");+ }+ }+ return { images, runs };+}++/** Images and text needing attention, by reason. */+export interface AccessibilityReview {+ needsDescription: number;+ untagged: number;+ untaggable: number;+}++/** Covers only the pages in `pages` that have been read. */+export function reviewAccessibility(+ doc: EditorDocument,+ pages: readonly PageSnapshot[],+): AccessibilityReview {+ const review: AccessibilityReview = {+ needsDescription: 0,+ untagged: 0,+ untaggable: 0,+ };+ // A block spanning pages is flagged on each, but one description clears it.+ const counted = new Set<string>();+ for (const page of pages) {+ for (const item of pageItems(doc, page)) {+ if (!item.attention) continue;+ if (item.block !== null && item.attention === "needs-description") {+ if (counted.has(item.block)) continue;+ counted.add(item.block);+ }+ if (item.attention === "needs-description") review.needsDescription++;+ if (item.attention === "untagged") review.untagged++;+ if (item.attention === "untaggable") review.untaggable++;+ }+ }+ return review;+}++/** An image or run the user can resolve, which Next selects. */+export interface ReviewTarget {+ kind: "image" | "text";+ id: string;+ pageIndex: number;+}++/**+ * The first target after `currentId`, in page order and then top to bottom,+ * wrapping round to the start. `currentId` may name any image or run; one not+ * on the read pages (or null) starts from the first. A block is visited once,+ * at its first flag, and the block `currentId` belongs to is passed over+ * unless nothing else is left.+ */+export function nextNeedingAttention(+ doc: EditorDocument,+ pages: readonly PageSnapshot[],+ currentId: string | null,+): ReviewTarget | null {+ const items = pages.flatMap((page) =>+ inDisplayOrder(page, pageItems(doc, page)),+ );+ const visited = new Set<string>();+ const stops: number[] = [];+ items.forEach((item, index) => {+ if (!isActionable(item.attention)) return;+ if (item.block !== null) {+ if (visited.has(item.block)) return;+ visited.add(item.block);+ }+ stops.push(index);+ });+ const current = items.findIndex((item) => item.target.id === currentId);+ const currentBlock = current < 0 ? null : items[current].block;+ const ordered = [+ ...stops.filter((index) => index > current),+ ...stops.filter((index) => index <= current),+ ].map((index) => items[index]);+ const next =+ ordered.find(+ (item) => currentBlock === null || item.block !== currentBlock,+ ) ?? ordered[0];+ return next?.target ?? null;+}++interface ReviewItem {+ target: ReviewTarget;+ attention: ImageAttention | null;+ /** The figure or formula the item belongs to (documentBlockId); null for none. */+ block: string | null;+ bounds: PageRect;+}++/** Every image and run on the page, images first, with what it needs. */+function pageItems(doc: EditorDocument, page: PageSnapshot): ReviewItem[] {+ const { images, runs } = pageAttention(doc, page);+ const blockOf = (key: string | null | undefined) =>+ key ? documentBlockId(doc, page.pageIndex, key) : null;+ const items: ReviewItem[] = [+ ...page.images.map((image) => ({+ target: {+ kind: "image" as const,+ id: image.id,+ pageIndex: page.pageIndex,+ },+ attention: images.get(image.id) ?? null,+ block:+ image.mcid === undefined+ ? null+ : blockOf(doc.structure(page.pageIndex).block(image.mcid)?.key),+ bounds: image.bounds,+ })),+ ...page.runs.map((run) => ({+ target: { kind: "text" as const, id: run.id, pageIndex: page.pageIndex },+ attention: runs.get(run.id) ?? null,+ block: blockOf(describableTextBlock(doc, run)?.key),+ bounds: run.bounds,+ })),+ ];+ return items;+}++/** Top to bottom as the page shows them, so a turned page reads in its turned order. */+function inDisplayOrder(page: PageSnapshot, items: ReviewItem[]): ReviewItem[] {+ const transform = DisplayTransform.fromData(page.display);+ const displayedTop = ({ x, y, width, height }: PageRect) =>+ Math.max(transform.apply(x, y).y, transform.apply(x + width, y + height).y);+ const tops = new Map(items.map((item) => [item, displayedTop(item.bounds)]));+ // Stable, so items at one height keep images-then-text draw order.+ return [...items].sort((a, b) => tops.get(b)! - tops.get(a)!);+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/imageAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/imageAccessibility.tsindex 25821e0400..02d748531d 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/imageAccessibility.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/imageAccessibility.ts@@ -1,9 +1,9 @@import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";-import type { DescriptionBlocker } from "@editor/tools/pdfTextEditor/model/PageStructure";import type {- ImageObjectSnapshot,- PageSnapshot,-} from "@editor/tools/pdfTextEditor/types";+ DescribableType,+ DescriptionBlocker,+} from "@editor/tools/pdfTextEditor/model/PageStructure";+import type { ImageObjectSnapshot } from "@editor/tools/pdfTextEditor/types";/** What can be said and done about one image's accessibility. */export type ImageAccessibility =@@ -12,8 +12,8 @@ export type ImageAccessibility =| {kind: "describable";description: string | null;- /** False for an image no element owns yet: describing it adds one. */- tagged: boolean;+ /** Null for an image no element owns yet: describing it adds a Figure. */+ type: DescribableType | null;canBeDecorative: boolean;};@@ -28,7 +28,7 @@ export function imageAccessibility(return {kind: "describable",description: null,- tagged: false,+ type: null,canBeDecorative: true,};}@@ -41,7 +41,7 @@ export function imageAccessibility(return {kind: "describable",description: structure.alt(image.mcid),- tagged: true,+ type: structure.describableType(image.mcid),canBeDecorative:retaggable || structure.cannotMarkDecorative(image.mcid) === null,};@@ -51,13 +51,18 @@ export function imageAccessibility(export type RetaggableTag =| { kind: "untagged" }| { kind: "artifact" }- | { kind: "figure"; mcid: number; alt: string | null };+ | {+ kind: "element";+ type: DescribableType;+ mcid: number;+ alt: string | null;+ };/*** The image's tag when TagImageCommand can change it: an image the page* itself draws, whose save can add an element, that is untagged, an- * artifact, or a figure the session added. Null otherwise, for content the file's elements- * own among the rest.+ * artifact, or a figure or formula the session added. Null otherwise, for+ * content the file's elements own among the rest.*/export function retaggableTag(doc: EditorDocument,@@ -69,9 +74,11 @@ export function retaggableTag(if (image.mcid === undefined) {return image.artifact ? { kind: "artifact" } : { kind: "untagged" };}- if (!structure.isAdded(image.mcid)) return null;+ const type = structure.describableType(image.mcid);+ if (!structure.isAdded(image.mcid) || !type) return null;return {- kind: "figure",+ kind: "element",+ type,mcid: image.mcid,alt: structure.alt(image.mcid),};@@ -91,18 +98,11 @@ function blocked(*/export type ImageAttention = "needs-description" | "untagged" | "untaggable";-/** Images needing attention, by reason. */-export interface ImageReview {- needsDescription: number;- untagged: number;- untaggable: number;-}-export function attentionFor(accessibility: ImageAccessibility,): ImageAttention | null {if (accessibility.kind === "describable") {- if (!accessibility.tagged) return "untagged";+ if (accessibility.type === null) return "untagged";return accessibility.description?.trim() ? null : "needs-description";}if (@@ -126,41 +126,3 @@ export function imageAttention(): ImageAttention | null {return attentionFor(imageAccessibility(doc, image));}--export function reviewImages(- doc: EditorDocument,- pages: readonly PageSnapshot[],-): ImageReview {- const review: ImageReview = {- needsDescription: 0,- untagged: 0,- untaggable: 0,- };- for (const image of pages.flatMap((page) => page.images)) {- const attention = imageAttention(doc, image);- if (attention === "needs-description") review.needsDescription++;- if (attention === "untagged") review.untagged++;- if (attention === "untaggable") review.untaggable++;- }- return review;-}--/**- * The first image with actionable attention after `currentId`, in page order- * and then the order each page draws its images, wrapping round to the start.- * Covers only the pages in `pages` that have been read.- */-export function nextImageNeedingAttention(- doc: EditorDocument,- pages: readonly PageSnapshot[],- currentId: string | null,-): ImageObjectSnapshot | null {- const images = pages.flatMap((page) => page.images);- // An id not in the list (or none) yields 0: start from the first image.- const start = images.findIndex((img) => img.id === currentId) + 1;- for (let i = 0; i < images.length; i++) {- const image = images[(start + i) % images.length];- if (isActionable(imageAttention(doc, image))) return image;- }- return null;-}