Skip to content

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

Add support for editing image accessibility tags in Text Editor (#8623)

James Bruntoncd48ccb288f6
diff --git a/.github/workflows/PR-Auto-Deploy-V2.yml b/.github/workflows/PR-Auto-Deploy-V2.yml
index fb9b4148ce..ba0cc5f70f 100644
--- a/.github/workflows/PR-Auto-Deploy-V2.yml
+++ b/.github/workflows/PR-Auto-Deploy-V2.yml
@@ -280,6 +280,7 @@ jobs:
VITE_SUPABASE_URL=${{ steps.saas.outputs.supabase_url }}
VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY=${{ secrets.SAAS_SUPABASE_PUBLISHABLE_KEY }}
VITE_SAAS_API_URL=${{ steps.saas.outputs.api_base }}
+ VITE_ACCESSIBILITY_EDITING=true
platforms: linux/amd64
- name: Set up SSH
diff --git a/.github/workflows/Saas-Dev-Deploy.yml b/.github/workflows/Saas-Dev-Deploy.yml
index c59787fd58..519289ac42 100644
--- a/.github/workflows/Saas-Dev-Deploy.yml
+++ b/.github/workflows/Saas-Dev-Deploy.yml
@@ -94,6 +94,7 @@ jobs:
VITE_INCLUDE_PORTAL=true
VITE_SUPABASE_URL=${{ steps.config.outputs.supabase_url }}
VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY=${{ secrets.SAAS_SUPABASE_PUBLISHABLE_KEY }}
+ VITE_ACCESSIBILITY_EDITING=true
platforms: linux/amd64
- name: Build and push AI engine image
diff --git a/.github/workflows/e2e-stubbed.yml b/.github/workflows/e2e-stubbed.yml
index 8b68b4d79a..0a3f88750d 100644
--- a/.github/workflows/e2e-stubbed.yml
+++ b/.github/workflows/e2e-stubbed.yml
@@ -73,6 +73,7 @@ jobs:
env:
VITE_BUILD_FOR_PREVIEW: "1"
VITE_INCLUDE_PORTAL: "true"
+ VITE_ACCESSIBILITY_EDITING: "true"
run: task frontend:build:proprietary
- name: Run stubbed E2E tests (${{ matrix.browser }} ${{ matrix.shard }})
if: matrix.suite != 'desktop'
diff --git a/docker/embedded/Dockerfile b/docker/embedded/Dockerfile
index 83abc570ff..e184a68fb2 100644
--- a/docker/embedded/Dockerfile
+++ b/docker/embedded/Dockerfile
@@ -70,6 +70,7 @@ ARG BUILD_PORTAL=true
ARG VITE_SUPABASE_URL=""
ARG VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY=""
ARG VITE_SAAS_API_URL=""
+ARG VITE_ACCESSIBILITY_EDITING=""
# Bundle only the JPDFium native for this image's target arch.
ARG TARGETARCH
@@ -79,6 +80,7 @@ RUN JPDFIUM_PLATFORM="$([ "$TARGETARCH" = arm64 ] && echo linux-arm64 || echo li
if [ -z "${VITE_SUPABASE_URL}" ]; then unset VITE_SUPABASE_URL; fi; \
if [ -z "${VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY}" ]; then unset VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY; fi; \
if [ -z "${VITE_SAAS_API_URL}" ]; then unset VITE_SAAS_API_URL; fi; \
+ if [ -z "${VITE_ACCESSIBILITY_EDITING}" ]; then unset VITE_ACCESSIBILITY_EDITING; fi; \
STIRLING_FLAVOR=${STIRLING_FLAVOR} \
gradle clean build \
-PbuildWithFrontend=true \
diff --git a/docker/frontend/Dockerfile b/docker/frontend/Dockerfile
index c2f63ade1d..9dcee053a5 100644
--- a/docker/frontend/Dockerfile
+++ b/docker/frontend/Dockerfile
@@ -20,6 +20,7 @@ ARG VITE_INCLUDE_PORTAL=true
ARG VITE_SUPABASE_URL=""
# pragma: allowlist secret
ARG VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY=""
+ARG VITE_ACCESSIBILITY_EDITING=""
# Build vite from editor/, output lands in dist/.
RUN set -eu; \
@@ -27,6 +28,7 @@ RUN set -eu; \
export STIRLING_FLAVOR="${STIRLING_FLAVOR}"; \
if [ -n "${VITE_SUPABASE_URL}" ]; then export VITE_SUPABASE_URL="${VITE_SUPABASE_URL}"; fi; \
if [ -n "${VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY}" ]; then export VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY="${VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY}"; fi; \
+ if [ -n "${VITE_ACCESSIBILITY_EDITING}" ]; then export VITE_ACCESSIBILITY_EDITING="${VITE_ACCESSIBILITY_EDITING}"; fi; \
npx vite build editor --mode "${VITE_BUILD_MODE}"
# Stage 2: nginx
diff --git a/frontend/.env b/frontend/.env
index 0239a6b882..277b034861 100644
--- a/frontend/.env
+++ b/frontend/.env
@@ -11,6 +11,10 @@ VITE_API_BASE_URL=/
# it on; off for plain vite builds, always on in dev.
VITE_INCLUDE_PORTAL=false
+# Image descriptions in the PDF text editor. Off until it ships; the end-to-end
+# tests turn it on.
+VITE_ACCESSIBILITY_EDITING=false
+
# Google Drive integration
VITE_GOOGLE_DRIVE_CLIENT_ID=
VITE_GOOGLE_DRIVE_API_KEY=
diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts
index 8b738d46e6..3bbfdcdcd4 100644
--- a/frontend/playwright.config.ts
+++ b/frontend/playwright.config.ts
@@ -163,6 +163,9 @@ export default defineConfig({
command: process.env.CI
? `npx vite preview --port ${DEV_PORT} --strictPort`
: `npx vite --mode proprietary --port ${DEV_PORT} --strictPort`,
+ env: {
+ VITE_ACCESSIBILITY_EDITING: "true",
+ },
url:
process.env.PLAYWRIGHT_BASE_URL ?? `http://localhost:${DEV_PORT}`,
reuseExistingServer: !process.env.CI,
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index dc98a78f2a..5c682482c5 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -7418,6 +7418,27 @@ widthHint = "Text re-wraps to fit the width."
x = "X"
y = "Y"
+[pdfTextEditor.inspector.accessibility]
+cannotChange = "This image's accessibility can't be changed."
+decorativeInfo = "Screen readers skip decorative images. Use it for borders, backgrounds and other images that carry no information."
+decorativeLabel = "Decorative image"
+description = "Image description"
+descriptionInfo = "Screen readers read this out in place of the image."
+encrypted = "Tags can't be edited in an encrypted file"
+heading = "Accessibility"
+missingDescriptions = "Missing descriptions"
+mixedContent = "Figure includes other content"
+needsDescriptionBadge = "No description"
+nextImage = "Next image"
+notFigure = "Tagged as part of the text"
+saveFailed = "Your accessibility changes couldn't be saved, so the file wasn't saved. Undo them and try again."
+unreadable = "This file's tags can't be edited"
+untaggableImages = "Can't be tagged here"
+untaggedBadge = "Not tagged"
+untaggedDocument = "Document has no tags"
+untaggedImage = "Can't be tagged here"
+untaggedImages = "Untagged images"
+
[pdfTextEditor.mobile]
actions = "Editor actions"
addImage = "Image"
diff --git a/frontend/src/editor/core/constants/featureFlags.ts b/frontend/src/editor/core/constants/featureFlags.ts
index 9c55a4da97..cc407978c8 100644
--- a/frontend/src/editor/core/constants/featureFlags.ts
+++ b/frontend/src/editor/core/constants/featureFlags.ts
@@ -7,4 +7,5 @@
export const WORKBENCH_SESSION_RESTORE: boolean = true;
// Edit image descriptions and decorative markers in the PDF text editor.
-export const ACCESSIBILITY_EDITING: boolean = false;
+export const ACCESSIBILITY_EDITING: boolean =
+ import.meta.env.VITE_ACCESSIBILITY_EDITING === "true";
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tagged-structure.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tagged-structure.spec.ts
index 23af3e2ebe..46efd3b509 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tagged-structure.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tagged-structure.spec.ts
@@ -141,22 +141,30 @@ async function saveAndReopen(page: import("@playwright/test").Page) {
);
}
+async function openFixture(page: import("@playwright/test").Page) {
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
+ timeout: 15_000,
+ });
+ await page
+ .locator('[data-testid="pdf-editor-file-input"]')
+ .setInputFiles(FIXTURE);
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 30_000,
+ });
+ await expect
+ .poll(() => page.evaluate(RUN_ID, "product line"), { timeout: 30_000 })
+ .not.toBeNull();
+}
+
+// `[data-testid^="pdf-editor-image-"]` also matches the hidden file input.
+const IMAGE = '[data-testid^="pdf-editor-image-p"]';
+const PNG = path.join(import.meta.dirname, "../test-fixtures/sample.png");
+
test.describe("PDF text editor - tagged documents", () => {
test("edited text stays in the structure tree", async ({ page }) => {
test.setTimeout(120_000);
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 15_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(FIXTURE);
- await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
- timeout: 30_000,
- });
- await expect
- .poll(() => page.evaluate(RUN_ID, "product line"), { timeout: 30_000 })
- .not.toBeNull();
+ await openFixture(page);
expect(await page.evaluate(AUDIT)).toEqual({
untaggedText: 0,
@@ -186,4 +194,147 @@ test.describe("PDF text editor - tagged documents", () => {
expect(saved.contentMcids).toEqual(saved.treeMcids);
expect(saved.contentMcids).toEqual(expect.arrayContaining([0, 1, 2]));
});
+
+ test("an image's description is edited in the inspector and saved", async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ await openFixture(page);
+
+ await page.locator(IMAGE).first().click();
+ const field = page.getByTestId("pdf-editor-image-description");
+ await expect(field).toHaveValue("Bar chart of revenue by region");
+
+ await field.fill("Revenue by region, third quarter");
+ await saveAndReopen(page);
+
+ await page.locator(IMAGE).first().click();
+ await expect(page.getByTestId("pdf-editor-image-description")).toHaveValue(
+ "Revenue by region, third quarter",
+ );
+ });
+
+ test("an image without a description is flagged and reached from the document summary", async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ await openFixture(page);
+ const image = page.locator(IMAGE).first();
+ const imageId = (await image.getAttribute("data-testid"))!.replace(
+ "pdf-editor-image-",
+ "",
+ );
+ const badge = page.getByTestId(`pdf-editor-image-attention-${imageId}`);
+ const summary = page.getByTestId(
+ "pdf-editor-document-accessibility-summary",
+ );
+ await expect(badge).toBeHidden();
+
+ await image.click();
+ await page.getByTestId("pdf-editor-image-description").fill("");
+ await expect(badge).toBeVisible();
+
+ // Next shows the description of the image it picks, even with one selected.
+ await page.getByTestId("pdf-editor-tab-document").click();
+ await page.getByTestId("pdf-editor-document-accessibility-next").click();
+ await expect(
+ page.getByTestId("pdf-editor-image-description"),
+ ).toBeVisible();
+
+ // Escape from the Document tab clears the selection and leaves the tab open.
+ await page.getByTestId("pdf-editor-tab-document").click();
+ await page.keyboard.press("Escape");
+ await expect(summary).toHaveText(
+ /Missing descriptions\s*1\s*Untagged images\s*0/,
+ );
+
+ await page.getByTestId("pdf-editor-document-accessibility-next").click();
+ const field = page.getByTestId("pdf-editor-image-description");
+ await expect(field).toHaveValue("");
+ await field.fill("Revenue by region");
+ await expect(badge).toBeHidden();
+
+ await page.getByTestId("pdf-editor-tab-document").click();
+ await expect(summary).toHaveText(
+ /Missing descriptions\s*0\s*Untagged images\s*0/,
+ );
+ await expect(
+ page.getByTestId("pdf-editor-document-accessibility-next"),
+ ).toBeHidden();
+ });
+
+ test("an image inserted into a tagged document is flagged, then tagged by describing it", async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ await openFixture(page);
+ const images = page.locator(IMAGE);
+ await expect(images).toHaveCount(1);
+
+ await page
+ .locator('[data-testid="pdf-editor-image-input"]')
+ .setInputFiles(PNG);
+ await expect(images).toHaveCount(2);
+ const untagged = page.locator(
+ '[data-testid^="pdf-editor-image-attention-"][data-attention="untagged"]',
+ );
+ await expect(untagged).toHaveCount(1);
+
+ await page.getByTestId("pdf-editor-tab-document").click();
+ await page.keyboard.press("Escape");
+ const summary = page.getByTestId(
+ "pdf-editor-document-accessibility-summary",
+ );
+ await expect(summary).toHaveText(
+ /Missing descriptions\s*0\s*Untagged images\s*1/,
+ );
+
+ await images.nth(1).click();
+ await page.getByTestId("pdf-editor-image-description").fill("A red square");
+ await expect(untagged).toHaveCount(0);
+ await saveAndReopen(page);
+
+ await page.locator(IMAGE).nth(1).click();
+ await expect(page.getByTestId("pdf-editor-image-description")).toHaveValue(
+ "A red square",
+ );
+ });
+
+ test("an image marked decorative saves as decoration, and can be described again", async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ await openFixture(page);
+
+ await page.locator(IMAGE).first().click();
+ const decorative = page.getByTestId("pdf-editor-image-decorative");
+ await expect(decorative).not.toBeChecked();
+ // The styled box hides its input, so the click goes to the label.
+ await page
+ .getByTestId("pdf-editor-image-accessibility")
+ .getByText("Decorative image", { exact: true })
+ .click();
+ await expect(decorative).toBeChecked();
+ await expect(page.getByTestId("pdf-editor-image-description")).toBeHidden();
+ await saveAndReopen(page);
+
+ await page.locator(IMAGE).first().click();
+ await expect(decorative).toBeChecked();
+ await expect(page.getByTestId("pdf-editor-image-description")).toBeHidden();
+
+ await page
+ .getByTestId("pdf-editor-image-accessibility")
+ .getByText("Decorative image", { exact: true })
+ .click();
+ await expect(decorative).not.toBeChecked();
+ const field = page.getByTestId("pdf-editor-image-description");
+ await expect(field).toHaveValue("");
+ await field.fill("Revenue by region");
+ await saveAndReopen(page);
+
+ await page.locator(IMAGE).first().click();
+ await expect(page.getByTestId("pdf-editor-image-description")).toHaveValue(
+ "Revenue by region",
+ );
+ });
});
diff --git a/frontend/src/editor/core/tests/test-fixtures/generate-tagged-sample.mts b/frontend/src/editor/core/tests/test-fixtures/generate-tagged-sample.mts
index edd7c89ac5..da1928d822 100644
--- a/frontend/src/editor/core/tests/test-fixtures/generate-tagged-sample.mts
+++ b/frontend/src/editor/core/tests/test-fixtures/generate-tagged-sample.mts
@@ -33,6 +33,35 @@ const CONTENT = [
"",
].join("\n");
+const CHART_WIDTH = 120;
+const CHART_HEIGHT = 80;
+/** Revenue for four regions, as bar heights in pixels. */
+const BAR_HEIGHTS = [42, 30, 56, 22];
+
+/**
+ * RGB samples of a bar chart, top row first: four bars on a pair of axes over
+ * light gridlines, so the figure's description describes what it shows.
+ */
+function barChartPixels(): Uint8Array {
+ const pixels = new Uint8Array(CHART_WIDTH * CHART_HEIGHT * 3).fill(255);
+ const paint = (x: number, y: number, rgb: [number, number, number]) => {
+ pixels.set(rgb, (y * CHART_WIDTH + x) * 3);
+ };
+ const baseline = CHART_HEIGHT - 8;
+ for (let y = baseline - 15; y > 6; y -= 15) {
+ for (let x = 9; x < CHART_WIDTH - 6; x++) paint(x, y, [225, 225, 225]);
+ }
+ BAR_HEIGHTS.forEach((height, i) => {
+ const left = 16 + i * 26;
+ for (let y = baseline - height; y < baseline; y++) {
+ for (let x = left; x < left + 18; x++) paint(x, y, [59, 130, 246]);
+ }
+ });
+ for (let x = 8; x < CHART_WIDTH - 6; x++) paint(x, baseline, [90, 90, 90]);
+ for (let y = 6; y <= baseline; y++) paint(8, y, [90, 90, 90]);
+ return pixels;
+}
+
async function main() {
const doc = await PDFDocument.create();
const ctx = doc.context;
@@ -42,23 +71,16 @@ async function main() {
page.node.setFontDictionary(PDFName.of("F1"), regular.ref);
page.node.setFontDictionary(PDFName.of("F2"), bold.ref);
- // 2x2 RGB swatch: the figure only has to exist, not to look like anything.
- const pixels = Uint8Array.from([
- 200, 60, 60, 60, 160, 60, 60, 60, 200, 220, 180, 40,
- ]);
+ // Drawn at one pixel per point, matching the 120x80 box the content places it in.
const image = ctx.register(
- PDFRawStream.of(
- ctx.obj({
- Type: "XObject",
- Subtype: "Image",
- Width: 2,
- Height: 2,
- ColorSpace: "DeviceRGB",
- BitsPerComponent: 8,
- Length: pixels.length,
- }),
- pixels,
- ),
+ ctx.flateStream(barChartPixels(), {
+ Type: "XObject",
+ Subtype: "Image",
+ Width: CHART_WIDTH,
+ Height: CHART_HEIGHT,
+ ColorSpace: "DeviceRGB",
+ BitsPerComponent: 8,
+ }),
);
page.node.setXObject(PDFName.of("Im1"), image);
diff --git a/frontend/src/editor/core/tests/test-fixtures/tagged-sample.pdf b/frontend/src/editor/core/tests/test-fixtures/tagged-sample.pdf
index 251d0a8487..9654c63390 100644
Binary files a/frontend/src/editor/core/tests/test-fixtures/tagged-sample.pdf and b/frontend/src/editor/core/tests/test-fixtures/tagged-sample.pdf differ
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyStructureEdits.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyStructureEdits.test.ts
index 1aa7f1bba3..9786950dbb 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyStructureEdits.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/applyStructureEdits.test.ts
@@ -96,9 +96,9 @@ describe("applyStructureEdits", () => {
test("sets, replaces and removes /Alt on the elements the MCIDs resolve to", async () => {
const bytes = buildClassicPdf(objects(), 1);
const out = await applyStructureEdits(bytes, [
- { pageIndex: 0, mcid: 0, alt: "Intro" },
- { pageIndex: 0, mcid: 1, alt: null },
- { pageIndex: 1, mcid: 0, alt: "Second figure" },
+ { pageIndex: 0, mcid: 0, alt: "Intro", decorative: false },
+ { pageIndex: 0, mcid: 1, alt: null, decorative: false },
+ { pageIndex: 1, mcid: 0, alt: "Second figure", decorative: false },
]);
expect(await elementBody(out, 10)).toContain("/Alt (Intro)");
expect(await elementBody(out, 11)).not.toContain("/Alt");
@@ -108,7 +108,7 @@ describe("applyStructureEdits", () => {
test("appends a revision and leaves the original bytes in place", async () => {
const bytes = buildClassicPdf(objects(), 1);
const out = await applyStructureEdits(bytes, [
- { pageIndex: 1, mcid: 0, alt: "x" },
+ { pageIndex: 1, mcid: 0, alt: "x", decorative: false },
]);
expect(out.subarray(0, bytes.length)).toEqual(bytes);
// Only the one element changed, so only it is appended.
@@ -118,8 +118,8 @@ describe("applyStructureEdits", () => {
test("lets the later of two edits to one element win", async () => {
const out = await applyStructureEdits(buildClassicPdf(objects(), 1), [
- { pageIndex: 0, mcid: 1, alt: "first" },
- { pageIndex: 0, mcid: 1, alt: "second" },
+ { pageIndex: 0, mcid: 1, alt: "first", decorative: false },
+ { pageIndex: 0, mcid: 1, alt: "second", decorative: false },
]);
const body = await elementBody(out, 11);
expect(body).toContain("/Alt (second)");
@@ -134,7 +134,7 @@ describe("applyStructureEdits", () => {
{ num: 22, body: "[10 0 R 11 0 R]" },
];
const out = await applyStructureEdits(buildClassicPdf(tree, 1), [
- { pageIndex: 0, mcid: 1, alt: "Found" },
+ { pageIndex: 0, mcid: 1, alt: "Found", decorative: false },
]);
expect(await elementBody(out, 11)).toContain("/Alt (Found)");
});
@@ -142,7 +142,7 @@ describe("applyStructureEdits", () => {
test("extends a cross-reference-stream file", async () => {
const bytes = buildXrefStreamPdf(objects(), 1);
const out = await applyStructureEdits(bytes, [
- { pageIndex: 0, mcid: 1, alt: "Streamed" },
+ { pageIndex: 0, mcid: 1, alt: "Streamed", decorative: false },
]);
expect(await elementBody(out, 11)).toContain("/Alt (Streamed)");
expect((await RawPdf.parse(out))?.usesXrefStream).toBe(true);
@@ -150,9 +150,9 @@ describe("applyStructureEdits", () => {
test("names every edit it cannot write, and writes none of them", async () => {
const reasons = await failuresOf(buildClassicPdf(objects(), 1), [
- { pageIndex: 0, mcid: 1, alt: "fine on its own" },
- { pageIndex: 5, mcid: 0, alt: "x" },
- { pageIndex: 0, mcid: 7, alt: "x" },
+ { pageIndex: 0, mcid: 1, alt: "fine on its own", decorative: false },
+ { pageIndex: 5, mcid: 0, alt: "x", decorative: false },
+ { pageIndex: 0, mcid: 7, alt: "x", decorative: false },
]);
expect(reasons).toEqual([
"no such page",
@@ -166,7 +166,7 @@ describe("applyStructureEdits", () => {
);
expect(
await failuresOf(buildClassicPdf(untaggedPage, 1), [
- { pageIndex: 1, mcid: 0, alt: "x" },
+ { pageIndex: 1, mcid: 0, alt: "x", decorative: false },
]),
).toEqual(["the page has no /StructParents"]);
});
@@ -177,7 +177,7 @@ describe("applyStructureEdits", () => {
);
expect(
await failuresOf(buildClassicPdf(untagged, 1), [
- { pageIndex: 0, mcid: 0, alt: "x" },
+ { pageIndex: 0, mcid: 0, alt: "x", decorative: false },
]),
).toEqual(["the file has no structure tree"]);
});
@@ -189,7 +189,9 @@ describe("applyStructureEdits", () => {
);
const bytes = Uint8Array.from(encrypted, (c) => c.charCodeAt(0));
expect(
- await failuresOf(bytes, [{ pageIndex: 0, mcid: 0, alt: "x" }]),
+ await failuresOf(bytes, [
+ { pageIndex: 0, mcid: 0, alt: "x", decorative: false },
+ ]),
).toEqual(["the file is encrypted"]);
});
});
@@ -219,7 +221,12 @@ describe("applyStructureEdits on a real producer's output", () => {
test("PDFium reads the new description from the saved file", async () => {
const bytes = new Uint8Array(await readFile(TAGGED_SAMPLE));
const out = await applyStructureEdits(bytes, [
- { pageIndex: 0, mcid: 2, alt: "Revenue by region, \u00e9t\u00e9 2026" },
+ {
+ pageIndex: 0,
+ mcid: 2,
+ alt: "Revenue by region, \u00e9t\u00e9 2026",
+ decorative: false,
+ },
]);
const doc = await EditorDocument.open(out);
@@ -241,3 +248,246 @@ describe("applyStructureEdits on a real producer's output", () => {
}
});
});
+
+async function pageContent(bytes: Uint8Array, pageIndex: number) {
+ const pdf = (await RawPdf.parse(bytes))!;
+ return toLatin1(
+ (await pdf.pageContent(pdf.pageNumberAt(pageIndex)!))!,
+ ).trim();
+}
+
+function parentArray(pdf: RawPdf, key: number): string {
+ const tree = pdf.parentTreeArray(7, key)!;
+ return `[${tree.items!.map((item) => item.text).join(" ")}]`;
+}
+
+/** `objects()` with the bodies in `overrides` swapped in. */
+function withBodies(overrides: Record<number, string>, base = objects()) {
+ return base.map((o) =>
+ o.num in overrides ? { ...o, body: overrides[o.num] } : o,
+ );
+}
+
+const DECORATE_FIGURE = {
+ pageIndex: 0,
+ mcid: 1,
+ alt: null,
+ decorative: true,
+} as const;
+
+describe("applyStructureEdits: marking decorative", () => {
+ test("retags the figure's content as an artifact and drops the figure", async () => {
+ const out = await applyStructureEdits(buildClassicPdf(objects(), 1), [
+ DECORATE_FIGURE,
+ ]);
+ expect(await pageContent(out, 0)).toBe(
+ "/P <</MCID 0>> BDC EMC /Artifact BMC 0 0 10 10 re f EMC",
+ );
+ expect(await pageContent(out, 1)).toBe(
+ "/Figure <</MCID 0>> BDC 0 0 10 10 re f EMC",
+ );
+ const pdf = (await RawPdf.parse(out))!;
+ expect(pdf.valueSpan(pdf.objectBody(9)!, "K")!.text).toBe(
+ "[10 0 R 12 0 R]",
+ );
+ expect(parentArray(pdf, 0)).toBe("[10 0 R null]");
+ });
+
+ test("retags a figure held in a named property list", async () => {
+ const bytes = buildClassicPdf(
+ withBodies({
+ 3: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 5 0 R /StructParents 0 /Resources << /Properties << /MC0 << /MCID 1 >> >> >> >>",
+ 5: streamBody(
+ "",
+ "/P <</MCID 0>> BDC EMC /Figure /MC0 BDC 0 0 10 10 re f EMC",
+ ),
+ }),
+ 1,
+ );
+ const out = await applyStructureEdits(bytes, [DECORATE_FIGURE]);
+ expect(await pageContent(out, 0)).toBe(
+ "/P <</MCID 0>> BDC EMC /Artifact BMC 0 0 10 10 re f EMC",
+ );
+ });
+
+ test("retags every page a figure spans", async () => {
+ const bytes = buildClassicPdf(
+ withBodies(
+ {
+ 11: "<< /Type /StructElem /S /Figure /P 9 0 R /Pg 3 0 R /K [1 << /Type /MCR /Pg 4 0 R /MCID 0 >>] >>",
+ 9: "<< /Type /StructElem /S /Document /P 7 0 R /K [10 0 R 11 0 R] >>",
+ },
+ objects("<< /Nums [0 [10 0 R 11 0 R] 1 [11 0 R]] >>"),
+ ),
+ 1,
+ );
+ const out = await applyStructureEdits(bytes, [DECORATE_FIGURE]);
+ expect(await pageContent(out, 1)).toBe("/Artifact BMC 0 0 10 10 re f EMC");
+ const pdf = (await RawPdf.parse(out))!;
+ expect(parentArray(pdf, 0)).toBe("[10 0 R null]");
+ expect(parentArray(pdf, 1)).toBe("[null]");
+ });
+
+ test("writes a description and a decorative mark in one save", async () => {
+ const out = await applyStructureEdits(buildClassicPdf(objects(), 1), [
+ DECORATE_FIGURE,
+ { pageIndex: 1, mcid: 0, alt: "Second", decorative: false },
+ ]);
+ expect(await elementBody(out, 12)).toContain("/Alt (Second)");
+ const pdf = (await RawPdf.parse(out))!;
+ expect(pdf.valueSpan(pdf.objectBody(9)!, "K")!.text).toBe(
+ "[10 0 R 12 0 R]",
+ );
+ });
+
+ test("refuses a figure whose page draws content another page also draws", async () => {
+ const bytes = buildClassicPdf(
+ withBodies({
+ 4: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 5 0 R /StructParents 1 >>",
+ }),
+ 1,
+ );
+ expect(await failuresOf(bytes, [DECORATE_FIGURE])).toEqual([
+ "its page draws content another page also draws",
+ ]);
+ });
+
+ test("refuses a figure with a child element", async () => {
+ const bytes = buildClassicPdf(
+ [
+ ...withBodies({
+ 11: "<< /Type /StructElem /S /Figure /P 9 0 R /Pg 3 0 R /K [1 13 0 R] >>",
+ }),
+ {
+ num: 13,
+ body: "<< /Type /StructElem /S /Caption /P 11 0 R /Pg 3 0 R >>",
+ },
+ ],
+ 1,
+ );
+ expect(await failuresOf(bytes, [DECORATE_FIGURE])).toEqual([
+ "its content is not all marked content on its pages",
+ ]);
+ });
+
+ test("drops a top-level figure when the ParentTree is held in the StructTreeRoot", async () => {
+ const bytes = buildClassicPdf(
+ withBodies({
+ 7: "<< /Type /StructTreeRoot /K [9 0 R 11 0 R] /ParentTree << /Nums [0 [10 0 R 11 0 R] 1 [12 0 R]] >> /ParentTreeNextKey 2 >>",
+ 9: "<< /Type /StructElem /S /Document /P 7 0 R /K [10 0 R 12 0 R] >>",
+ 11: "<< /Type /StructElem /S /Figure /P 7 0 R /Pg 3 0 R /K 1 >>",
+ }),
+ 1,
+ );
+ const out = await applyStructureEdits(bytes, [DECORATE_FIGURE]);
+ const root = await elementBody(out, 7);
+ expect(root).toContain("/K [9 0 R]");
+ expect(root).toContain("/Nums [0 [10 0 R null] 1 [12 0 R]]");
+ });
+});
+
+describe("applyStructureEdits: adding figures", () => {
+ // Page 1 also draws content marked MCID 2 and 3, which no element owns.
+ function untaggedContent(parentTree?: string): Uint8Array {
+ return buildClassicPdf(
+ objects(parentTree).map((obj) =>
+ obj.num === 5
+ ? {
+ num: 5,
+ body: streamBody(
+ "",
+ "/P <</MCID 0>> BDC EMC /Figure <</MCID 1>> BDC 0 0 10 10 re f EMC " +
+ "/Figure <</MCID 2>> BDC 0 0 5 5 re f EMC /Figure <</MCID 3>> BDC 0 0 2 2 re f EMC",
+ ),
+ }
+ : obj,
+ ),
+ 1,
+ );
+ }
+ const figure = (mcid: number, after: number | null, alt = "Logo") => ({
+ pageIndex: 0,
+ mcid,
+ alt,
+ decorative: false,
+ newFigure: { after },
+ });
+ const documentKids = async (bytes: Uint8Array) =>
+ (await elementBody(bytes, 9)).match(/\/K \[([^\]]*)\]/)![1];
+
+ test("adds a figure after the element owning the content before it", async () => {
+ const out = await applyStructureEdits(untaggedContent(), [figure(2, 0)]);
+ expect(await documentKids(out)).toBe("10 0 R 13 0 R 11 0 R 12 0 R");
+ expect((await elementBody(out, 13)).trim()).toBe(
+ "<< /Type /StructElem /S /Figure /P 9 0 R /Pg 3 0 R /K 2 /Alt (Logo) >>",
+ );
+ expect(await elementBody(out, 7)).toContain(
+ "0 [10 0 R 11 0 R 13 0 R] 1 [12 0 R]",
+ );
+ });
+
+ test("places a figure before the page's first tagged content when nothing precedes it", async () => {
+ const out = await applyStructureEdits(untaggedContent(), [
+ figure(2, null, null as unknown as string),
+ ]);
+ expect(await documentKids(out)).toBe("13 0 R 10 0 R 11 0 R 12 0 R");
+ expect(await elementBody(out, 13)).not.toContain("/Alt");
+ });
+
+ test("places a figure after one added in the same save", async () => {
+ const out = await applyStructureEdits(untaggedContent(), [
+ figure(2, 1),
+ figure(3, 2),
+ ]);
+ expect(await documentKids(out)).toBe("10 0 R 11 0 R 13 0 R 14 0 R 12 0 R");
+ });
+
+ test("files a figure on a page with no tagged content in the document element", async () => {
+ const out = await applyStructureEdits(
+ untaggedContent("<< /Nums [0 [10 0 R 11 0 R] 1 [null]] >>"),
+ [{ ...figure(0, null), pageIndex: 1 }],
+ );
+ expect(await documentKids(out)).toBe("10 0 R 11 0 R 12 0 R 13 0 R");
+ });
+
+ test("files a figure in a StructTreeRoot that also holds the ParentTree", async () => {
+ const out = await applyStructureEdits(
+ buildClassicPdf(
+ [
+ ...withBodies(
+ {
+ 7: "<< /Type /StructTreeRoot /K [9 0 R 8 0 R] /ParentTree << /Nums [0 [10 0 R 11 0 R] 1 [null]] >> /ParentTreeNextKey 2 >>",
+ },
+ objects(),
+ ),
+ { num: 8, body: "<< /Type /StructElem /S /Sect /P 7 0 R >>" },
+ ],
+ 1,
+ ),
+ [{ ...figure(0, null), pageIndex: 1 }],
+ );
+ const root = await elementBody(out, 7);
+ expect(root).toContain("/K [9 0 R 8 0 R 13 0 R]");
+ expect(root).toContain("/Nums [0 [10 0 R 11 0 R] 1 [13 0 R]]");
+ });
+
+ test("adds a figure beside one marked decorative in the same save", async () => {
+ const out = await applyStructureEdits(untaggedContent(), [
+ figure(2, 1),
+ { pageIndex: 0, mcid: 1, alt: null, decorative: true },
+ ]);
+ expect(await documentKids(out)).toBe("10 0 R 13 0 R 12 0 R");
+ expect(await elementBody(out, 7)).toContain(
+ "0 [10 0 R null 13 0 R] 1 [12 0 R]",
+ );
+ });
+
+ test("refuses an MCID the page's content does not carry, or an element owns", async () => {
+ expect(
+ await failuresOf(untaggedContent(), [figure(7, 0), figure(1, 0)]),
+ ).toEqual([
+ "the page's content does not carry its MCID",
+ "another element owns its MCID",
+ ]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rawPdf.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rawPdf.test.ts
index a124a0d30e..f8a9d8c6e1 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rawPdf.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rawPdf.test.ts
@@ -115,6 +115,16 @@ describe("RawPdf.valueSpan", () => {
expect(pdf?.dictName(body, "Type")).toBe("Page");
expect(pdf?.valueSpan(body, "Kids")?.text).toBe("[1 0 R 2 0 R]");
});
+
+ it("does not take a name value for the key it spells", async () => {
+ const pdf = await RawPdf.parse(singleContentPdf());
+ const body = "<< /Type /StructElem /S /P /P 9 0 R >>";
+ expect(pdf?.dictName(body, "S")).toBe("P");
+ expect(pdf?.dictRef(body, "P")).toBe(9);
+ expect(setDictEntry(body, "P", "10 0 R")).toBe(
+ "<< /Type /StructElem /S /P /P 10 0 R >>",
+ );
+ });
});
describe("RawPdf streams and pages", () => {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts
index 58493389fd..11aa95076b 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts
@@ -13,6 +13,12 @@ import {
vi,
} from "vitest";
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 { DeleteImageCommand } from "@editor/tools/pdfTextEditor/commands/DeleteImageCommand";
+import type { ImageObject } from "@editor/tools/pdfTextEditor/model/ImageObject";
+import { readTagMarks } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+import { toLatin1 } from "@editor/tools/pdfTextEditor/pdfdoc/bytes";
import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import { PageStructure } from "@editor/tools/pdfTextEditor/model/PageStructure";
import { StructureEditError } from "@editor/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits";
@@ -26,6 +32,15 @@ import {
HistoryStepError,
} from "@editor/tools/pdfTextEditor/store/HistoryStack";
import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import { expectConsole } from "@editor/tests/failOnConsole";
+import {
+ imageAccessibility,
+ imageAttention,
+ nextImageNeedingAttention,
+ reviewImages,
+} from "@editor/tools/pdfTextEditor/util/imageAccessibility";
+import { InsertImageCommand } from "@editor/tools/pdfTextEditor/commands/InsertImageCommand";
+import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";
import {
buildClassicPdf,
streamBody,
@@ -39,12 +54,19 @@ const FIGURE_MCID = 2;
const FIGURE_ALT = "Bar chart of revenue by region";
// A described figure (MCID 0) and a decorative rule drawn as an artifact image.
-function imagesPdf(): Uint8Array {
+// `ownerType` retypes the element owning MCID 0; `tagged: false` drops the
+// catalog's tree, leaving the content's marks behind.
+function imagesPdf({
+ ownerType = "Figure",
+ tagged = true,
+}: { ownerType?: string; tagged?: boolean } = {}): Uint8Array {
return buildClassicPdf(
[
{
num: 1,
- body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 6 0 R /MarkInfo << /Marked true >> >>",
+ body: tagged
+ ? "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 6 0 R /MarkInfo << /Marked true >> >>"
+ : "<< /Type /Catalog /Pages 2 0 R >>",
},
{ num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
{
@@ -78,7 +100,7 @@ function imagesPdf(): Uint8Array {
},
{
num: 8,
- body: "<< /Type /StructElem /S /Figure /P 7 0 R /Pg 3 0 R /K 0 /Alt (A grey square) >>",
+ body: `<< /Type /StructElem /S /${ownerType} /P 7 0 R /Pg 3 0 R /K 0 /Alt (A grey square) >>`,
},
{ num: 9, body: "<< /Nums [0 [8 0 R]] >>" },
],
@@ -132,11 +154,18 @@ describe("reading the structure tree", () => {
test("lists each element with its type, description and MCIDs", async () => {
const doc = await openSample();
const elements = readPageStructure(doc.module, doc.page(0).pagePtr);
+ const element = (type: string, alt: string | null, mcids: number[]) => ({
+ type,
+ alt,
+ actualText: null,
+ mcids,
+ onlyMarkedContent: false,
+ });
expect(elements).toEqual([
- { type: "Document", alt: null, actualText: null, mcids: [] },
- { type: "H1", alt: null, actualText: null, mcids: [0] },
- { type: "P", alt: null, actualText: null, mcids: [1] },
- { type: "Figure", alt: FIGURE_ALT, actualText: null, mcids: [2] },
+ element("Document", null, []),
+ element("H1", null, [0]),
+ element("P", null, [1]),
+ element("Figure", FIGURE_ALT, [2]),
]);
});
@@ -225,13 +254,21 @@ function spanningPdf(slot0 = "8 0 R"): Uint8Array {
describe("reading tags from the file's ParentTree", () => {
test("gives each page's MCIDs to the element its ParentTree names", async () => {
const structure = (await readFileStructure(spanningPdf()))!;
- expect(structure.get(0)).toEqual([
- { type: "Figure", alt: "Chart", actualText: null, mcids: [0] },
- { type: "P", alt: null, actualText: null, mcids: [5] },
- ]);
- expect(structure.get(1)).toEqual([
- { type: "P", alt: null, actualText: null, mcids: [0] },
- ]);
+ const element = (type: string, alt: string | null, mcids: number[]) => ({
+ type,
+ alt,
+ actualText: null,
+ mcids,
+ onlyMarkedContent: true,
+ });
+ expect(structure.get(0)).toEqual({
+ elements: [element("Figure", "Chart", [0]), element("P", null, [5])],
+ slotCount: 6,
+ });
+ expect(structure.get(1)).toEqual({
+ elements: [element("P", null, [0])],
+ slotCount: 1,
+ });
});
test("describes the figure, not the paragraph that spans the page break", async () => {
@@ -248,7 +285,353 @@ describe("reading tags from the file's ParentTree", () => {
test("refuses an MCID only another page's content carries", async () => {
const doc = await open(spanningPdf("null"));
- expect(doc.structure(0).cannotDescribe(0)).toMatch(/no structure element/);
+ expect(doc.structure(0).cannotDescribe(0)).toBe("untagged");
+ });
+});
+
+describe("imageAccessibility", () => {
+ async function images(doc: EditorDocument) {
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ return page.images.map((img) => img.snapshot());
+ }
+
+ test("offers the figure's description and follows edits to it", async () => {
+ const doc = await open(imagesPdf());
+ const [figure] = await images(doc);
+ expect(imageAccessibility(doc, figure)).toEqual({
+ kind: "describable",
+ description: "A grey square",
+ tagged: true,
+ canBeDecorative: true,
+ });
+ new HistoryStack().execute(
+ new SetAltTextCommand({ pageIndex: 0, mcid: 0, alt: "A dark square" }),
+ doc,
+ );
+ expect(imageAccessibility(doc, figure)).toMatchObject({
+ description: "A dark square",
+ });
+ });
+
+ test("reads an artifact image as decorative, which retagging can undo", async () => {
+ const doc = await open(imagesPdf());
+ const [, rule] = await images(doc);
+ expect(imageAccessibility(doc, rule)).toEqual({
+ kind: "decorative",
+ canUndecorate: true,
+ });
+ });
+
+ test("cannot undo an artifact in an untagged document", async () => {
+ const doc = await open(imagesPdf({ tagged: false }));
+ const [, rule] = await images(doc);
+ expect(imageAccessibility(doc, rule)).toEqual({
+ kind: "decorative",
+ canUndecorate: false,
+ });
+ });
+
+ test("blocks an image tagged as part of a paragraph", async () => {
+ const doc = await open(imagesPdf({ ownerType: "P" }));
+ const [image] = await images(doc);
+ expect(imageAccessibility(doc, image)).toEqual({
+ kind: "blocked",
+ blocker: "not-figure",
+ documentTagged: true,
+ });
+ });
+
+ test("blocks every image in an untagged document", async () => {
+ const doc = await open(imagesPdf({ tagged: false }));
+ const [image] = await images(doc);
+ expect(imageAccessibility(doc, image)).toEqual({
+ kind: "blocked",
+ blocker: "untagged",
+ documentTagged: false,
+ });
+ });
+});
+
+/**
+ * Two pages of figures, every one an image: A (page 0, MCID 0) and C (page 1,
+ * MCID 0) have no description, B (page 0, MCID 1) has one.
+ */
+function figuresPdf(): Uint8Array {
+ const draw = (mcid: number, y: number) =>
+ `/Figure <</MCID ${mcid}>> BDC q 20 0 0 20 10 ${y} cm /Im1 Do Q EMC\n`;
+ const page = (num: number, contents: number, key: number) => ({
+ num,
+ body:
+ `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents ${contents} 0 R ` +
+ `/StructParents ${key} /Resources << /XObject << /Im1 5 0 R >> >> >>`,
+ });
+ const figure = (num: number, pageNum: number, mcid: number, alt = "") => ({
+ num,
+ body: `<< /Type /StructElem /S /Figure /P 7 0 R /Pg ${pageNum} 0 R /K ${mcid}${alt} >>`,
+ });
+ 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 4 0 R] /Count 2 >>" },
+ page(3, 20, 0),
+ page(4, 21, 1),
+ {
+ num: 5,
+ body: streamBody(
+ "/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8",
+ "\x80",
+ ),
+ },
+ {
+ num: 6,
+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 9 0 R /ParentTreeNextKey 2 >>",
+ },
+ {
+ num: 7,
+ body: "<< /Type /StructElem /S /Document /P 6 0 R /K [10 0 R 11 0 R 12 0 R] >>",
+ },
+ { num: 9, body: "<< /Nums [0 [10 0 R 11 0 R] 1 [12 0 R]] >>" },
+ figure(10, 3, 0),
+ figure(11, 3, 1, " /Alt (B)"),
+ figure(12, 4, 0),
+ { num: 20, body: streamBody("", draw(0, 150) + draw(1, 100)) },
+ { num: 21, body: streamBody("", draw(0, 150)) },
+ ],
+ 1,
+ );
+}
+
+describe("reviewing images that need attention", () => {
+ async function pages(doc: EditorDocument): Promise<PageSnapshot[]> {
+ return [0, 1].map((pageIndex) => {
+ const page = doc.page(pageIndex);
+ PdfiumTextReader.populate(doc, page);
+ return {
+ pageIndex,
+ images: page.images.map((img) => img.snapshot()),
+ } as PageSnapshot;
+ });
+ }
+
+ test("counts the undescribed images across pages", async () => {
+ const doc = await open(figuresPdf());
+ expect(reviewImages(doc, await pages(doc))).toEqual({
+ needsDescription: 2,
+ untagged: 0,
+ untaggable: 0,
+ });
+ });
+
+ test("walks to the next one in page order, wrapping round", async () => {
+ const doc = await open(figuresPdf());
+ const read = await pages(doc);
+ const [a, b] = read[0].images;
+ const [c] = read[1].images;
+ const next = (from: string | null) =>
+ nextImageNeedingAttention(doc, read, from)?.id;
+ expect(next(null)).toBe(a.id);
+ expect(next(a.id)).toBe(c.id);
+ expect(next(b.id)).toBe(c.id);
+ expect(next(c.id)).toBe(a.id);
+ });
+
+ test("drops an image once described, but not for a blank description", async () => {
+ const doc = await open(figuresPdf());
+ const read = await pages(doc);
+ const describe = (alt: string) =>
+ new HistoryStack().execute(
+ new SetAltTextCommand({ pageIndex: 0, mcid: 0, alt }),
+ doc,
+ );
+ describe(" ");
+ expect(reviewImages(doc, read).needsDescription).toBe(2);
+ describe("A bar chart");
+ expect(reviewImages(doc, read).needsDescription).toBe(1);
+ const [c] = read[1].images;
+ expect(nextImageNeedingAttention(doc, read, c.id)?.id).toBe(c.id);
+ });
+
+ test("flags an image inserted into a tagged document as untagged", async () => {
+ const doc = await openSample();
+ const history = new HistoryStack();
+ const insert = new InsertImageCommand({
+ pageIndex: 0,
+ rgba: new Uint8ClampedArray([255, 0, 0, 255]),
+ pixelWidth: 1,
+ pixelHeight: 1,
+ x: 300,
+ y: 300,
+ width: 40,
+ height: 40,
+ });
+ history.execute(insert, doc);
+ const page = doc.page(0);
+ const inserted = page.images
+ .find((img) => img.id === insert.insertedImageId)!
+ .snapshot();
+ const read = [
+ { pageIndex: 0, images: page.images.map((img) => img.snapshot()) },
+ ] as PageSnapshot[];
+
+ expect(imageAttention(doc, inserted)).toBe("untagged");
+ expect(reviewImages(doc, read)).toEqual({
+ needsDescription: 0,
+ untagged: 1,
+ untaggable: 0,
+ });
+ expect(nextImageNeedingAttention(doc, read, null)?.id).toBe(inserted.id);
+ });
+
+ test("leaves an untagged document's images out of the review", async () => {
+ const doc = await open(imagesPdf({ tagged: false }));
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ const read = [
+ { pageIndex: 0, images: page.images.map((img) => img.snapshot()) },
+ ] as PageSnapshot[];
+ expect(reviewImages(doc, read)).toEqual({
+ needsDescription: 0,
+ untagged: 0,
+ untaggable: 0,
+ });
+ });
+});
+
+/**
+ * An image drawn by each of three form XObjects: one the page marks as an
+ * artifact, one the page tags as a described Figure (MCID 0), and one whose
+ * form tags its own content, which the page's ParentTree cannot resolve.
+ */
+function formImagesPdf(): Uint8Array {
+ const draw = (y: number) => `q 20 0 0 20 10 ${y} cm /Im1 Do Q\n`;
+ const form = (num: number, content: string, extra = "") => ({
+ num,
+ body: streamBody(
+ `/Type /XObject /Subtype /Form /BBox [0 0 200 200]${extra} ` +
+ "/Resources << /XObject << /Im1 5 0 R >> >>",
+ content,
+ ),
+ });
+ 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 200 200] /Contents 4 0 R /StructParents 0 " +
+ "/Resources << /XObject << /Fm1 10 0 R /Fm2 11 0 R /Fm3 12 0 R >> >> >>",
+ },
+ {
+ num: 4,
+ body: streamBody(
+ "",
+ "/Artifact BMC /Fm1 Do EMC\n/Figure <</MCID 0>> BDC /Fm2 Do EMC\n/Fm3 Do\n",
+ ),
+ },
+ {
+ num: 5,
+ body: streamBody(
+ "/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8",
+ "\x80",
+ ),
+ },
+ {
+ num: 6,
+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 9 0 R /ParentTreeNextKey 2 >>",
+ },
+ {
+ num: 7,
+ body: "<< /Type /StructElem /S /Document /P 6 0 R /K [8 0 R] >>",
+ },
+ {
+ num: 8,
+ body: "<< /Type /StructElem /S /Figure /P 7 0 R /Pg 3 0 R /K 0 /Alt (A framed square) >>",
+ },
+ { num: 9, body: "<< /Nums [0 [8 0 R]] >>" },
+ form(10, draw(150)),
+ form(11, draw(100)),
+ form(12, `/Figure <</MCID 0>> BDC ${draw(50)}EMC\n`, " /StructParents 1"),
+ ],
+ 1,
+ );
+}
+
+describe("images drawn by a form XObject", () => {
+ async function images(doc: EditorDocument) {
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ return page.images.map((img) => img.snapshot());
+ }
+
+ test("is decorative inside a form the page marks as an artifact", async () => {
+ const doc = await open(formImagesPdf());
+ const [artifact] = await images(doc);
+ expect(artifact).toMatchObject({ inForm: true, artifact: true });
+ expect(imageAccessibility(doc, artifact)).toEqual({
+ kind: "decorative",
+ canUndecorate: false,
+ });
+ expect(imageAttention(doc, artifact)).toBeNull();
+ });
+
+ test("takes the tag the page gives its form", async () => {
+ const doc = await open(formImagesPdf());
+ const [, figure] = await images(doc);
+ expect(figure).toMatchObject({ inForm: true, mcid: 0 });
+ expect(imageAccessibility(doc, figure)).toEqual({
+ kind: "describable",
+ description: "A framed square",
+ tagged: true,
+ canBeDecorative: true,
+ });
+ });
+
+ test("is untaggable when its form tags its own content", async () => {
+ const doc = await open(formImagesPdf());
+ const [, , owned] = await images(doc);
+ expect(owned.mcid).toBeUndefined();
+ expect(imageAttention(doc, owned)).toBe("untaggable");
+ });
+
+ 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) },
+ ] as PageSnapshot[];
+ expect(reviewImages(doc, read)).toEqual({
+ needsDescription: 0,
+ untagged: 0,
+ untaggable: 1,
+ });
+ expect(nextImageNeedingAttention(doc, read, null)).toBeNull();
+ });
+
+ test("saves the page's tag on its form as an artifact when marked decorative", async () => {
+ const doc = await open(formImagesPdf());
+ const [, figure] = await images(doc);
+ new HistoryStack().execute(
+ new SetDecorativeCommand({
+ pageIndex: 0,
+ mcid: figure.mcid!,
+ decorative: true,
+ }),
+ doc,
+ );
+
+ const reopened = await open(await savedBytes(doc));
+ const [, saved] = await images(reopened);
+ expect(imageAccessibility(reopened, saved)).toEqual({
+ kind: "decorative",
+ canUndecorate: false,
+ });
});
});
@@ -258,19 +641,22 @@ describe("PageStructure", () => {
alt: "old",
actualText: null,
mcids: [3, 4],
+ onlyMarkedContent: true,
};
test("holds one edit per element, whichever of its MCIDs addressed it", () => {
const s = new PageStructure([figure]);
- s.setEdit(3, { mcid: 3, alt: "new" });
+ s.setEdit(3, { mcid: 3, alt: "new", decorative: false });
expect(s.alt(4)).toBe("new");
- s.setEdit(4, { mcid: 4, alt: "newer" });
- expect(s.pendingEdits()).toEqual([{ mcid: 4, alt: "newer" }]);
+ s.setEdit(4, { mcid: 4, alt: "newer", decorative: false });
+ expect(s.pendingEdits()).toEqual([
+ { mcid: 4, alt: "newer", decorative: false },
+ ]);
});
test("reads back the file's description once an edit is dropped", () => {
const s = new PageStructure([figure]);
- s.setEdit(3, { mcid: 3, alt: null });
+ s.setEdit(3, { mcid: 3, alt: null, decorative: false });
expect(s.alt(3)).toBeNull();
s.setEdit(3, null);
expect(s.alt(3)).toBe("old");
@@ -279,26 +665,52 @@ describe("PageStructure", () => {
test("refuses an edit no element can carry", () => {
expect(() =>
- new PageStructure([figure]).setEdit(9, { mcid: 9, alt: "x" }),
+ new PageStructure([figure]).setEdit(9, {
+ mcid: 9,
+ alt: "x",
+ decorative: false,
+ }),
).toThrow();
});
test("describes figures and formulas but not elements that hold text", () => {
const s = new PageStructure([
figure,
- { type: "Formula", alt: null, actualText: null, mcids: [5] },
- { type: "P", alt: null, actualText: null, mcids: [6] },
+ { ...figure, type: "Formula", alt: null, mcids: [5] },
+ { ...figure, type: "P", alt: null, mcids: [6] },
]);
expect(s.cannotDescribe(3)).toBeNull();
expect(s.cannotDescribe(5)).toBeNull();
- expect(s.cannotDescribe(6)).toMatch(/P element/);
- expect(s.cannotDescribe(9)).toMatch(/no structure element/);
+ expect(s.cannotDescribe(6)).toBe("not-figure");
+ expect(s.cannotDescribe(9)).toBe("untagged");
});
- test("refuses every description when the save cannot write them", () => {
+ 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("refuses decorative for a figure with content besides marked content", () => {
expect(
- new PageStructure([figure], "the file is encrypted").cannotDescribe(3),
- ).toBe("the file is encrypted");
+ new PageStructure([
+ { ...figure, onlyMarkedContent: false },
+ ]).cannotMarkDecorative(3),
+ ).toBe("mixed-content");
+ expect(new PageStructure([figure]).cannotMarkDecorative(3)).toBeNull();
+ });
+
+ test("refuses every description when the save cannot write them", () => {
+ expect(new PageStructure([figure], "encrypted").cannotDescribe(3)).toBe(
+ "encrypted",
+ );
});
});
@@ -316,7 +728,7 @@ describe("SetAltTextCommand", () => {
expect(doc.structureEdits()).toEqual([]);
history.redo(doc);
expect(doc.structureEdits()).toEqual([
- { pageIndex: 0, mcid: FIGURE_MCID, alt: "New" },
+ { pageIndex: 0, mcid: FIGURE_MCID, alt: "New", decorative: false },
]);
});
@@ -371,6 +783,82 @@ describe("SetAltTextCommand", () => {
});
});
+describe("SetDecorativeCommand", () => {
+ test("marks and unmarks a figure, undoably", async () => {
+ const doc = await openSample();
+ const history = new HistoryStack();
+ history.execute(
+ new SetDecorativeCommand({
+ pageIndex: 0,
+ mcid: FIGURE_MCID,
+ decorative: true,
+ }),
+ doc,
+ );
+ expect(doc.structure(0).decorative(FIGURE_MCID)).toBe(true);
+ history.undo(doc);
+ expect(doc.structure(0).decorative(FIGURE_MCID)).toBe(false);
+ expect(doc.structureEdits()).toEqual([]);
+ history.redo(doc);
+ expect(doc.structureEdits()).toEqual([
+ { pageIndex: 0, mcid: FIGURE_MCID, alt: FIGURE_ALT, decorative: true },
+ ]);
+ });
+
+ test("refuses a paragraph", async () => {
+ const doc = await openSample();
+ expect(() =>
+ new HistoryStack().execute(
+ new SetDecorativeCommand({ pageIndex: 0, mcid: 1, decorative: true }),
+ doc,
+ ),
+ ).toThrow(HistoryStepError);
+ expect(doc.structureEdits()).toEqual([]);
+ });
+
+ test("saves the figure as an artifact, touching nothing it paints", async () => {
+ const original = new Uint8Array(await readFile(TAGGED_SAMPLE));
+ const doc = await open(original);
+ new HistoryStack().execute(
+ new SetDecorativeCommand({
+ pageIndex: 0,
+ mcid: FIGURE_MCID,
+ decorative: true,
+ }),
+ doc,
+ );
+ const saved = await savedBytes(doc);
+
+ const content = async (bytes: Uint8Array) => {
+ const pdf = (await RawPdf.parse(bytes))!;
+ return toLatin1((await pdf.pageContent(pdf.pageNumberAt(0)!))!);
+ };
+ expect(await content(saved)).toBe(
+ (await content(original)).replace(
+ `/Figure <</MCID ${FIGURE_MCID}>> BDC`,
+ "/Artifact BMC",
+ ),
+ );
+
+ const reopened = await open(saved);
+ const page = reopened.page(0);
+ PdfiumTextReader.populate(reopened, page);
+ const [image] = page.images.map((img) => img.snapshot());
+ expect(imageAccessibility(reopened, image)).toEqual({
+ kind: "decorative",
+ canUndecorate: true,
+ });
+ expect(reopened.structure(0).elements.map((e) => e.type)).not.toContain(
+ "Figure",
+ );
+ expect(
+ reviewImages(reopened, [
+ { pageIndex: 0, images: [image] },
+ ] as PageSnapshot[]),
+ ).toEqual({ needsDescription: 0, untagged: 0, untaggable: 0 });
+ });
+});
+
describe("saving a description", () => {
test("appends it to the opened file when nothing else changed", async () => {
const doc = await openSample();
@@ -410,10 +898,277 @@ describe("saving a description", () => {
test("fails the save rather than dropping an edit it cannot write", async () => {
const doc = await openSample();
vi.spyOn(doc, "structureEdits").mockReturnValue([
- { pageIndex: 0, mcid: 42, alt: "x" },
+ { pageIndex: 0, mcid: 42, alt: "x", decorative: false },
+ ]);
+ // The detail is logged for a bug report; the user gets a message they can act on.
+ expectConsole.error(/Could not write 1 tag edit/);
+ const error = await exportToBlob(doc, "sample.pdf").catch((e) => e);
+ expect(error.message).toBe(
+ "Your accessibility changes couldn't be saved, so the file wasn't saved. Undo them and try again.",
+ );
+ expect(error.cause).toBeInstanceOf(StructureEditError);
+ });
+});
+
+describe("PageStructure: added figures", () => {
+ const paragraph = {
+ type: "P",
+ alt: null,
+ actualText: null,
+ mcids: [3],
+ onlyMarkedContent: true,
+ };
+
+ test("takes an MCID above every slot, added figure and marked content", () => {
+ const s = new PageStructure([paragraph], null, 5);
+ expect(s.freeMcid(2)).toBe(5);
+ expect(s.freeMcid(7)).toBe(8);
+ s.addFigure(5);
+ expect(s.freeMcid(2)).toBe(6);
+ });
+
+ test("lists added figures apart from edits to the file's elements", () => {
+ const s = new PageStructure([{ ...paragraph, type: "Figure" }], null, 5);
+ s.addFigure(5);
+ s.setAlt(5, "Logo");
+ s.setAlt(3, "Chart");
+ expect(s.pendingEdits()).toEqual([
+ { mcid: 3, alt: "Chart", decorative: false },
+ ]);
+ expect(s.addedFigures()).toEqual([{ mcid: 5, alt: "Logo" }]);
+ expect(() => s.setDecorative(5, true)).toThrow();
+ s.removeFigure(5);
+ expect(s.addedFigures()).toEqual([]);
+ expect(s.element(5)).toBeNull();
+ });
+
+ test("adds none where the page has no ParentTree array or is read-only", () => {
+ expect(
+ new PageStructure([paragraph], null, 5).cannotAddFigure(),
+ ).toBeNull();
+ expect(new PageStructure([]).cannotAddFigure()).toBe("untagged");
+ expect(new PageStructure([], "encrypted", 5).cannotAddFigure()).toBe(
+ "encrypted",
+ );
+ });
+});
+
+async function readPage(doc: EditorDocument) {
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ return page;
+}
+
+/** Insert a 20pt square image at (10, y) on page 0. */
+function insertImage(
+ doc: EditorDocument,
+ history: HistoryStack,
+ y: number,
+): ImageObject {
+ const insert = new InsertImageCommand({
+ pageIndex: 0,
+ rgba: new Uint8ClampedArray([255, 0, 0, 255]),
+ pixelWidth: 1,
+ pixelHeight: 1,
+ x: 10,
+ y,
+ width: 20,
+ height: 20,
+ });
+ history.execute(insert, doc);
+ return doc.page(0).findImage(insert.insertedImageId!)!;
+}
+
+const tagImage = (
+ image: ImageObject,
+ as: "figure" | "artifact",
+ alt?: string,
+) => new TagImageCommand({ pageIndex: 0, imageId: image.id, as, alt });
+
+const describable = (description: string | null) => ({
+ kind: "describable",
+ description,
+ tagged: true,
+ canBeDecorative: true,
+});
+
+describe("TagImageCommand", () => {
+ const marks = (doc: EditorDocument, image: ImageObject) =>
+ readTagMarks(doc.module, image.pdfiumObjPtr);
+
+ test("describes an inserted image as a new figure, undoably", 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);
+ expect(marks(doc, image)).toEqual([{ name: "Figure", mcid: 1 }]);
+ expect(imageAccessibility(doc, image.snapshot())).toEqual(
+ describable("A logo"),
+ );
+
+ history.undo(doc);
+ expect(marks(doc, image)).toEqual([]);
+ expect(imageAttention(doc, image.snapshot())).toBe("untagged");
+ expect(doc.structureEdits()).toEqual([]);
+
+ history.redo(doc);
+ expect(image.mcid).toBe(1);
+ expect(doc.structure(0).alt(1)).toBe("A logo");
+ });
+
+ test("undoes the typing that follows in the same step", 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"), doc);
+ history.execute(
+ new SetAltTextCommand({ pageIndex: 0, mcid: 1, alt: "A logo" }),
+ doc,
+ );
+ history.undo(doc);
+ expect(image.mcid).toBeNull();
+ expect(doc.structure(0).addedFigures()).toEqual([]);
+ });
+
+ test("un-decorates an artifact, restoring the mark on undo", async () => {
+ const doc = await open(imagesPdf());
+ const [, rule] = (await readPage(doc)).images;
+ const history = new HistoryStack();
+ history.execute(tagImage(rule, "figure"), doc);
+ expect(marks(doc, rule)).toEqual([{ name: "Figure", mcid: 1 }]);
+ expect(imageAccessibility(doc, rule.snapshot())).toEqual(describable(null));
+
+ history.undo(doc);
+ expect(marks(doc, rule)).toEqual([{ name: "Artifact", mcid: null }]);
+ expect(imageAccessibility(doc, rule.snapshot())).toEqual({
+ kind: "decorative",
+ canUndecorate: true,
+ });
+ });
+
+ test("marks an added figure decorative, dropping it and its description", 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(tagImage(image, "artifact"), doc);
+ expect(marks(doc, image)).toEqual([{ name: "Artifact", mcid: null }]);
+ expect(doc.structure(0).addedFigures()).toEqual([]);
+
+ history.undo(doc);
+ expect(doc.structure(0).addedFigures()).toEqual([
+ { mcid: 1, alt: "A logo" },
]);
- await expect(exportToBlob(doc, "sample.pdf")).rejects.toBeInstanceOf(
- StructureEditError,
+ });
+
+ test("refuses content the file's elements own", async () => {
+ const doc = await open(imagesPdf());
+ const [figure] = (await readPage(doc)).images;
+ expect(() =>
+ new HistoryStack().execute(tagImage(figure, "artifact"), doc),
+ ).toThrow(HistoryStepError);
+ expect(marks(doc, figure)).toEqual([{ name: "Figure", mcid: 0 }]);
+ });
+
+ test("refuses an image in an untagged document", async () => {
+ const doc = await open(imagesPdf({ tagged: false }));
+ await readPage(doc);
+ const history = new HistoryStack();
+ const image = insertImage(doc, history, 60);
+ expect(() =>
+ history.execute(tagImage(image, "figure", "A logo"), doc),
+ ).toThrow(HistoryStepError);
+ expect(marks(doc, image)).toEqual([]);
+ });
+});
+
+describe("saving an added figure", () => {
+ async function reopen(bytes: Uint8Array) {
+ const doc = await open(bytes);
+ const page = await readPage(doc);
+ return { doc, images: page.images.map((img) => img.snapshot()) };
+ }
+
+ /** The page's elements in tree order, each as its description or else its type. */
+ const tree = (doc: EditorDocument) =>
+ readPageStructure(doc.module, doc.page(0).pagePtr).map(
+ (el) => el.alt ?? el.type,
+ );
+
+ test("puts an inserted image's figure after the content above it, every save", 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);
+
+ await savedBytes(doc);
+ const { doc: reopened, images } = await reopen(await savedBytes(doc));
+ const added = images.find((img) => img.mcid === 1)!;
+ expect(imageAccessibility(reopened, added)).toEqual(describable("A logo"));
+ expect(tree(reopened)).toEqual(["Document", "A grey square", "A logo"]);
+ });
+
+ test("puts a figure above all the page's tagged content first", async () => {
+ const doc = await open(imagesPdf());
+ await readPage(doc);
+ const history = new HistoryStack();
+ const image = insertImage(doc, history, 170);
+ 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"]);
+ });
+
+ test("saves an un-decorated artifact as a described figure", async () => {
+ const doc = await open(imagesPdf());
+ const [, rule] = (await readPage(doc)).images;
+ const history = new HistoryStack();
+ history.execute(tagImage(rule, "figure"), doc);
+ history.execute(
+ new SetAltTextCommand({ pageIndex: 0, mcid: 1, alt: "A divider" }),
+ doc,
);
+
+ const { doc: reopened, images } = await reopen(await savedBytes(doc));
+ expect(images.map((img) => imageAccessibility(reopened, img))).toEqual([
+ describable("A grey square"),
+ describable("A divider"),
+ ]);
+ expect(tree(reopened)).toEqual(["Document", "A grey square", "A divider"]);
+ });
+
+ test("saves an untagged image marked decorative as an artifact", async () => {
+ const doc = await open(imagesPdf());
+ await readPage(doc);
+ const history = new HistoryStack();
+ const image = insertImage(doc, history, 60);
+ history.execute(tagImage(image, "artifact"), doc);
+
+ 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[]),
+ ).toEqual({ needsDescription: 0, untagged: 0, untaggable: 0 });
+ expect(tree(reopened)).toEqual(["Document", "A grey square"]);
+ });
+
+ test("leaves out the figure of an image deleted after it was described", 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 DeleteImageCommand({ pageIndex: 0, imageId: image.id }),
+ doc,
+ );
+ expect(doc.structureEdits()).toEqual([]);
+
+ const { doc: reopened } = await reopen(await savedBytes(doc));
+ expect(tree(reopened)).toEqual(["Document", "A grey square"]);
});
});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetAltTextCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetAltTextCommand.ts
index dc16f83c9d..0696594669 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetAltTextCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetAltTextCommand.ts
@@ -1,3 +1,4 @@
+import i18n from "i18next";
import {
RolledBackError,
type Command,
@@ -30,13 +31,18 @@ export class SetAltTextCommand implements Command {
const refusal = structure.cannotDescribe(this.mcid);
if (refusal) {
throw new RolledBackError(
- new Error(`MCID ${this.mcid} cannot take a description: ${refusal}`),
+ new Error(
+ i18n.t(
+ "pdfTextEditor.inspector.accessibility.cannotChange",
+ "This image's accessibility can't be changed.",
+ ),
+ ),
);
}
if (this.previous === undefined) {
this.previous = structure.editFor(this.mcid);
}
- structure.setEdit(this.mcid, { mcid: this.mcid, alt: this.alt });
+ structure.setAlt(this.mcid, this.alt);
doc.page(this.pageIndex).bumpRevision();
}
@@ -46,8 +52,12 @@ export class SetAltTextCommand implements Command {
doc.page(this.pageIndex).bumpRevision();
}
- /** Keystrokes in one description field collapse into one undo step. */
coalesceKey(): string {
- return `${this.type}:${this.pageIndex}:${this.mcid}`;
+ return descriptionCoalesceKey(this.pageIndex, this.mcid);
}
}
+
+/** Keystrokes in one description field collapse into one undo step. */
+export function descriptionCoalesceKey(pageIndex: number, mcid: number) {
+ return `set-alt-text:${pageIndex}:${mcid}`;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetDecorativeCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetDecorativeCommand.ts
new file mode 100644
index 0000000000..83e0f9415b
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetDecorativeCommand.ts
@@ -0,0 +1,66 @@
+import i18n from "i18next";
+import {
+ RolledBackError,
+ type Command,
+} from "@editor/tools/pdfTextEditor/commands/Command";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type {
+ PageStructure,
+ StructureElementEdit,
+} from "@editor/tools/pdfTextEditor/model/PageStructure";
+
+/**
+ * Mark or unmark the structure element owning `mcid` as decorative. Like a
+ * description, the mark is held on the document's structure index and written
+ * by the save pass, which turns the element's content into an artifact.
+ */
+export class SetDecorativeCommand implements Command {
+ readonly type = "set-decorative";
+ private readonly pageIndex: number;
+ private readonly mcid: number;
+ private readonly decorative: boolean;
+ private previous: StructureElementEdit | null | undefined;
+
+ constructor(opts: { pageIndex: number; mcid: number; decorative: boolean }) {
+ this.pageIndex = opts.pageIndex;
+ this.mcid = opts.mcid;
+ this.decorative = opts.decorative;
+ }
+
+ apply(doc: EditorDocument): void {
+ const structure = doc.structure(this.pageIndex);
+ // Refused here, not at save: a mark the save cannot write would fail every
+ // later save, the user's other edits included.
+ if (this.refused(structure)) {
+ throw new RolledBackError(
+ new Error(
+ i18n.t(
+ "pdfTextEditor.inspector.accessibility.cannotChange",
+ "This image's accessibility can't be changed.",
+ ),
+ ),
+ );
+ }
+ if (this.previous === undefined) {
+ this.previous = structure.editFor(this.mcid);
+ }
+ structure.setDecorative(this.mcid, this.decorative);
+ doc.page(this.pageIndex).bumpRevision();
+ }
+
+ private refused(structure: PageStructure): boolean {
+ // An added figure has no element in the file to drop: TagImageCommand
+ // retags its content instead.
+ if (structure.isAdded(this.mcid)) return true;
+ const blocker = this.decorative
+ ? structure.cannotMarkDecorative(this.mcid)
+ : structure.cannotDescribe(this.mcid);
+ return blocker !== null;
+ }
+
+ revert(doc: EditorDocument): void {
+ if (this.previous === undefined) return;
+ doc.structure(this.pageIndex).setEdit(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.ts
new file mode 100644
index 0000000000..8b0f99812d
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagImageCommand.ts
@@ -0,0 +1,135 @@
+import i18n from "i18next";
+import {
+ RolledBackError,
+ type Command,
+} from "@editor/tools/pdfTextEditor/commands/Command";
+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 {
+ ARTIFACT_TAG,
+ addTagMark,
+ highestMcid,
+ removeTagMark,
+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+import {
+ retaggableTag,
+ type RetaggableTag,
+} from "@editor/tools/pdfTextEditor/util/imageAccessibility";
+
+const FIGURE_TAG = "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.
+ */
+export class TagImageCommand implements Command {
+ readonly type = "tag-image";
+ private readonly pageIndex: number;
+ private readonly imageId: string;
+ private readonly as: "figure" | "artifact";
+ private readonly alt: string | null;
+ /** Chosen on first apply, so a redo reuses it. */
+ private mcid: number | null = null;
+ private previous: RetaggableTag | undefined;
+
+ constructor(opts: {
+ pageIndex: number;
+ imageId: string;
+ as: "figure" | "artifact";
+ /** The new figure's description. */
+ alt?: string | null;
+ }) {
+ this.pageIndex = opts.pageIndex;
+ this.imageId = opts.imageId;
+ this.as = opts.as;
+ this.alt = opts.alt ?? null;
+ }
+
+ apply(doc: EditorDocument): void {
+ const page = doc.page(this.pageIndex);
+ const image = page.findImage(this.imageId);
+ const current = image ? retaggableTag(doc, image.snapshot()) : null;
+ if (!image || !current) {
+ throw new RolledBackError(
+ new Error(
+ i18n.t(
+ "pdfTextEditor.inspector.accessibility.cannotChange",
+ "This image's accessibility can't be changed.",
+ ),
+ ),
+ );
+ }
+ this.previous ??= current;
+ if (this.as === "figure") {
+ this.mcid ??= doc
+ .structure(this.pageIndex)
+ .freeMcid(highestMcid(doc.module, page.pagePtr));
+ }
+ retag(doc, image, current, this.target());
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ revert(doc: EditorDocument): void {
+ if (this.previous === undefined) return;
+ const page = doc.page(this.pageIndex);
+ const image = page.findImage(this.imageId);
+ const current = image ? retaggableTag(doc, image.snapshot()) : null;
+ if (!image || !current) return;
+ retag(doc, image, current, this.previous);
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ /** Describing an untagged image and typing on in its field is one undo step. */
+ coalesceKey(): string | null {
+ if (this.mcid === null || this.alt === null) return null;
+ return descriptionCoalesceKey(this.pageIndex, this.mcid);
+ }
+
+ private target(): RetaggableTag {
+ if (this.as === "artifact") return { kind: "artifact" };
+ return { kind: "figure", mcid: this.mcid!, alt: this.alt };
+ }
+}
+
+function retag(
+ doc: EditorDocument,
+ image: ImageObject,
+ from: RetaggableTag,
+ to: RetaggableTag,
+): void {
+ const m = doc.module;
+ const structure = doc.structure(image.pageIndex);
+ const objPtr = image.pdfiumObjPtr;
+ if (from.kind === "artifact") {
+ marked(removeTagMark(m, objPtr, ARTIFACT_TAG));
+ }
+ if (from.kind === "figure") {
+ marked(removeTagMark(m, objPtr, FIGURE_TAG));
+ structure.removeFigure(from.mcid);
+ }
+ image.mcid = null;
+ image.artifact = false;
+ if (to.kind === "artifact") {
+ marked(
+ addTagMark(m, doc.docPtr, objPtr, { name: ARTIFACT_TAG, mcid: null }),
+ );
+ image.artifact = true;
+ }
+ if (to.kind === "figure") {
+ marked(
+ addTagMark(m, doc.docPtr, objPtr, { name: FIGURE_TAG, mcid: to.mcid }),
+ );
+ structure.addFigure(to.mcid);
+ if (to.alt !== null) structure.setAlt(to.mcid, to.alt);
+ image.mcid = to.mcid;
+ }
+}
+
+function marked(ok: boolean): void {
+ if (!ok) throw new Error("PDFium could not change the image's tags");
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
index cfa9bca14c..529b3202c1 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
@@ -7,6 +7,8 @@ import { useSelectionGeometry } from "@editor/tools/pdfTextEditor/hooks/useSelec
import { DocumentInspector } from "@editor/tools/pdfTextEditor/components/inspector/DocumentInspector";
import { SelectionInspector } from "@editor/tools/pdfTextEditor/components/inspector/SelectionInspector";
import { analyzePageFonts } from "@editor/tools/pdfTextEditor/util/pageFonts";
+import { ensureAllPagesRead } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";
+import { ACCESSIBILITY_EDITING } from "@editor/constants/featureFlags";
import {
ScanHint,
type ScanHintProps,
@@ -74,6 +76,26 @@ export function EditorSidebar({
const fontNote = useSelectedFontNote(state, selection);
+ const editorDocument = store.document;
+ const reviewingImages = useMemo(
+ () => ACCESSIBILITY_EDITING && !!editorDocument?.isTagged(),
+ [editorDocument],
+ );
+ const imageSelected = controller.imageAccessibility !== null;
+ // Counts and Next cover only pages already read, which is just the first few
+ // until the rest scroll into view.
+ useEffect(() => {
+ if (!reviewingImages || (tab !== "document" && !imageSelected)) return;
+ const id = window.setTimeout(() => ensureAllPagesRead(store), 0);
+ return () => window.clearTimeout(id);
+ }, [reviewingImages, tab, imageSelected, 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");
+ };
+
if (!state.hasDocument) {
return (
<Box p="md" style={{ flex: 1, overflow: "auto" }}>
@@ -145,6 +167,8 @@ export function EditorSidebar({
onSetGroupingMode={onSetGroupingMode}
onSetWidthMode={onSetWidthMode}
onSetShowRulers={onSetShowRulers}
+ imageReview={reviewingImages ? controller.imageReview : null}
+ onSelectNextImageToReview={selectNextImageToReview}
/>
</Tabs.Panel>
</Box>
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx
index a83e2189fd..b4629521a1 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx
@@ -1,6 +1,10 @@
import { useState } from "react";
import React from "react";
import { Rnd } from "react-rnd";
+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";
import type {
ImageObjectSnapshot,
PageRect,
@@ -16,6 +20,8 @@ interface ImageHandleProps {
selected: boolean;
onSelect: () => void;
onTransformCommit: (next: PageRect) => void;
+ /** Why the image needs the user's attention, if it does. */
+ attention?: ImageAttention | null;
}
/** Draggable + resizable affordance for an image object. */
@@ -27,7 +33,9 @@ export function ImageHandle({
selected,
onSelect,
onTransformCommit,
+ attention = null,
}: 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
@@ -168,6 +176,40 @@ export function ImageHandle({
onMouseLeave={() => setHovered(false)}
data-testid={`pdf-editor-image-${image.id}`}
data-locked={locked ? "true" : undefined}
- />
+ >
+ {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-image-attention-${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>
+ )}
+ </Rnd>
);
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
index 3aad732ed1..7c0b969a9e 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { Box, Loader } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Button } from "@editor/ui/Button";
@@ -7,6 +7,11 @@ import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDoc
import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";
import { TextRunOverlay } from "@editor/tools/pdfTextEditor/components/TextRunOverlay";
import { TableOverlay } from "@editor/tools/pdfTextEditor/components/TableOverlay";
+import { ACCESSIBILITY_EDITING } from "@editor/constants/featureFlags";
+import {
+ imageAttention,
+ type ImageAttention,
+} from "@editor/tools/pdfTextEditor/util/imageAccessibility";
import { ImageHandle } from "@editor/tools/pdfTextEditor/components/ImageHandle";
import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
import { ShapeHandle } from "@editor/tools/pdfTextEditor/components/ShapeHandle";
@@ -106,6 +111,15 @@ export function PageView({
onFirstRendered,
}: 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 canvasRef = useRef<HTMLCanvasElement | null>(null);
const containerRef = useRef<HTMLDivElement | null>(null);
// `raster` is the CSS layout size; the bitmap itself renders at deviceScale
@@ -379,6 +393,7 @@ export function PageView({
onTransformCommit={(next) =>
onTransformImage?.(page.pageIndex, image.id, next)
}
+ attention={imageAttentions.get(image.id) ?? null}
/>
))}
{/* Grid + empty-cell editors sit below the run overlays so filled
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsx
new file mode 100644
index 0000000000..46a25b1f84
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsx
@@ -0,0 +1,71 @@
+import { MantineProvider } from "@mantine/core";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { DocumentInspector } from "@editor/tools/pdfTextEditor/components/inspector/DocumentInspector";
+import type { ImageReview } from "@editor/tools/pdfTextEditor/util/imageAccessibility";
+
+function renderInspector(imageReview: ImageReview | null, onNext = vi.fn()) {
+ render(
+ <MantineProvider env="test">
+ <DocumentInspector
+ pages={[]}
+ groupingMode="auto"
+ widthMode="grow"
+ showRulers={false}
+ onSetGroupingMode={vi.fn()}
+ onSetWidthMode={vi.fn()}
+ onSetShowRulers={vi.fn()}
+ imageReview={imageReview}
+ onSelectNextImageToReview={onNext}
+ />
+ </MantineProvider>,
+ );
+ return onNext;
+}
+
+const KEY = "pdfTextEditor.inspector.accessibility";
+const SUMMARY = "pdf-editor-document-accessibility-summary";
+const NEXT = "pdf-editor-document-accessibility-next";
+
+describe("DocumentInspector accessibility review", () => {
+ it("counts images missing descriptions and untagged ones, and moves to the next", () => {
+ const onNext = renderInspector({
+ needsDescription: 2,
+ untagged: 1,
+ untaggable: 0,
+ });
+ expect(screen.getByTestId(SUMMARY)).toHaveTextContent(
+ `${KEY}.missingDescriptions2${KEY}.untaggedImages1`,
+ );
+ fireEvent.click(screen.getByTestId(NEXT));
+ expect(onNext).toHaveBeenCalledOnce();
+ });
+
+ it("offers the next image while any is untagged", () => {
+ renderInspector({ needsDescription: 0, untagged: 1, untaggable: 0 });
+ expect(screen.getByTestId(NEXT)).toBeVisible();
+ });
+
+ it("counts images that can't be tagged apart, without offering them", () => {
+ renderInspector({ needsDescription: 0, untagged: 0, untaggable: 2 });
+ expect(screen.getByTestId(SUMMARY)).toHaveTextContent(
+ `${KEY}.missingDescriptions0${KEY}.untaggedImages0${KEY}.untaggableImages2`,
+ );
+ expect(screen.queryByTestId(NEXT)).not.toBeInTheDocument();
+ });
+
+ it("offers no next image once every image is dealt with", () => {
+ renderInspector({ needsDescription: 0, untagged: 0, untaggable: 0 });
+ expect(screen.getByTestId(SUMMARY)).toHaveTextContent(
+ `${KEY}.missingDescriptions0${KEY}.untaggedImages0`,
+ );
+ expect(screen.queryByTestId(NEXT)).not.toBeInTheDocument();
+ });
+
+ it("leaves the review out when there is nothing to review", () => {
+ renderInspector(null);
+ expect(
+ screen.queryByTestId("pdf-editor-document-accessibility"),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsx
index c0c4ed23a2..514c23744a 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsx
@@ -18,6 +18,7 @@ import type {
PageSnapshot,
WidthMode,
} from "@editor/tools/pdfTextEditor/types";
+import type { ImageReview } from "@editor/tools/pdfTextEditor/util/imageAccessibility";
interface Props {
pages: PageSnapshot[];
@@ -27,10 +28,18 @@ 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;
}
/** Facts about the open document. Nothing here acts on a selection. */
-export function DocumentInspector({ pages, ...settings }: Props) {
+export function DocumentInspector({
+ pages,
+ imageReview,
+ onSelectNextImageToReview,
+ ...settings
+}: Props) {
const { t } = useTranslation();
const runs = pages.reduce((n, p) => n + p.runs.length, 0);
const images = pages.reduce((n, p) => n + p.images.length, 0);
@@ -55,12 +64,87 @@ export function DocumentInspector({ pages, ...settings }: Props) {
/>
</Stack>
</Section>
+ {imageReview && (
+ <AccessibilitySection
+ review={imageReview}
+ onNext={onSelectNextImageToReview}
+ />
+ )}
<FontsSection pages={pages} />
<DocumentSettings {...settings} />
</Stack>
);
}
+function AccessibilitySection({
+ review,
+ onNext,
+}: {
+ review: ImageReview;
+ onNext: () => void;
+}) {
+ const { t } = useTranslation();
+ const pending = review.needsDescription + review.untagged;
+ return (
+ <Section testId="pdf-editor-document-accessibility">
+ <SectionLabel>
+ {t("pdfTextEditor.inspector.accessibility.heading", "Accessibility")}
+ </SectionLabel>
+ <Stack gap="xs">
+ <Stack gap={4} data-testid="pdf-editor-document-accessibility-summary">
+ <StatRow
+ label={t(
+ "pdfTextEditor.inspector.accessibility.missingDescriptions",
+ "Missing descriptions",
+ )}
+ value={review.needsDescription}
+ />
+ <StatRow
+ label={t(
+ "pdfTextEditor.inspector.accessibility.untaggedImages",
+ "Untagged images",
+ )}
+ value={review.untagged}
+ />
+ <UntaggableRow count={review.untaggable} />
+ </Stack>
+ {pending > 0 && (
+ <Button
+ size="sm"
+ variant="secondary"
+ accent="neutral"
+ fullWidth
+ justify="start"
+ leftSection={<Icon name="arrow-right" size={20} />}
+ onClick={onNext}
+ data-testid="pdf-editor-document-accessibility-next"
+ >
+ {t("pdfTextEditor.inspector.accessibility.nextImage", "Next image")}
+ </Button>
+ )}
+ </Stack>
+ </Section>
+ );
+}
+
+/**
+ * Untagged images nothing here can tag, kept apart so the rows Next works
+ * through can reach zero. Absent in the usual file, which has none.
+ */
+function UntaggableRow({ count }: { count: number }) {
+ const { t } = useTranslation();
+ if (count === 0) return null;
+ return (
+ <StatRow
+ label={t(
+ "pdfTextEditor.inspector.accessibility.untaggableImages",
+ "Can't be tagged here",
+ )}
+ value={count}
+ />
+ );
+}
+
const FONT_STATUS_COLOR = {
standard: "green",
embedded: "blue",
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.tsx
new file mode 100644
index 0000000000..77003665ab
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ImageAccessibilitySection.test.tsx
@@ -0,0 +1,206 @@
+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";
+
+function renderSection(
+ accessibility: ImageAccessibility,
+ {
+ review = { needsDescription: 0, untagged: 0, untaggable: 0 },
+ onSetDescription = vi.fn(),
+ onSetDecorative = vi.fn(),
+ onNext = vi.fn(),
+ } = {},
+) {
+ render(
+ <MantineProvider env="test">
+ <ImageAccessibilitySection
+ accessibility={accessibility}
+ onSetDescription={onSetDescription}
+ onSetDecorative={onSetDecorative}
+ review={review}
+ onNext={onNext}
+ />
+ </MantineProvider>,
+ );
+ return { onSetDescription, onSetDecorative, onNext };
+}
+
+const KEY = "pdfTextEditor.inspector.accessibility";
+const FIELD = "pdf-editor-image-description";
+const DECORATIVE = "pdf-editor-image-decorative";
+const NEXT = "pdf-editor-image-description-next";
+
+const describable = (
+ description: string | null,
+ canBeDecorative = true,
+): ImageAccessibility => ({
+ kind: "describable",
+ description,
+ tagged: true,
+ canBeDecorative,
+});
+const taggable: ImageAccessibility = {
+ kind: "describable",
+ description: null,
+ tagged: false,
+ canBeDecorative: true,
+};
+const untagged: ImageAccessibility = {
+ kind: "blocked",
+ blocker: "untagged",
+ documentTagged: true,
+};
+
+describe("ImageAccessibilitySection", () => {
+ it("edits the description", () => {
+ const { onSetDescription } = renderSection(describable("Bar chart"));
+ const field = screen.getByTestId(FIELD);
+ expect(field).toHaveValue("Bar chart");
+ fireEvent.change(field, { target: { value: "Bar chart of revenue" } });
+ expect(onSetDescription).toHaveBeenCalledWith("Bar chart of revenue");
+ });
+
+ it("offers to describe an untagged image or mark it decorative", () => {
+ const { onSetDescription } = renderSection(taggable);
+ fireEvent.change(screen.getByTestId(FIELD), {
+ target: { value: "A logo" },
+ });
+ expect(onSetDescription).toHaveBeenCalledWith("A logo");
+ expect(screen.getByTestId(DECORATIVE)).toBeEnabled();
+ });
+
+ it.each<[ImageAccessibility, string]>([
+ [
+ { kind: "blocked", blocker: "untagged", documentTagged: false },
+ "untaggedDocument",
+ ],
+ [untagged, "untaggedImage"],
+ [
+ { kind: "blocked", blocker: "not-figure", documentTagged: true },
+ "notFigure",
+ ],
+ [
+ { kind: "blocked", blocker: "encrypted", documentTagged: true },
+ "encrypted",
+ ],
+ [
+ { kind: "blocked", blocker: "unreadable", documentTagged: true },
+ "unreadable",
+ ],
+ ])("says why an image cannot be described: %o", (accessibility, message) => {
+ renderSection(accessibility);
+ expect(screen.queryByTestId(FIELD)).not.toBeInTheDocument();
+ expect(
+ screen.getByTestId("pdf-editor-image-accessibility-status"),
+ ).toHaveTextContent(`${KEY}.${message}`);
+ });
+
+ describe("decorative", () => {
+ it("marks a describable image decorative", () => {
+ const { onSetDecorative } = renderSection(describable("Bar chart"));
+ const box = screen.getByTestId(DECORATIVE);
+ expect(box).not.toBeChecked();
+ fireEvent.click(box);
+ expect(onSetDecorative).toHaveBeenCalledWith(true);
+ });
+
+ it("unmarks a decorative image", () => {
+ const { onSetDecorative } = renderSection({
+ kind: "decorative",
+ canUndecorate: true,
+ });
+ const box = screen.getByTestId(DECORATIVE);
+ expect(box).toBeChecked();
+ fireEvent.click(box);
+ expect(onSetDecorative).toHaveBeenCalledWith(false);
+ });
+
+ it("cannot unmark a decorative image it cannot retag", () => {
+ renderSection({ kind: "decorative", canUndecorate: false });
+ expect(screen.getByTestId(DECORATIVE)).toBeChecked();
+ expect(screen.getByTestId(DECORATIVE)).toBeDisabled();
+ expect(screen.queryByTestId(FIELD)).not.toBeInTheDocument();
+ });
+
+ it("cannot mark a figure with other content, and says why", () => {
+ renderSection(describable("Bar chart", false));
+ expect(screen.getByTestId(DECORATIVE)).toBeDisabled();
+ expect(screen.getByText(`${KEY}.mixedContent`)).toBeVisible();
+ });
+
+ it("is not offered for an image that cannot be described", () => {
+ renderSection(untagged);
+ expect(screen.queryByTestId(DECORATIVE)).not.toBeInTheDocument();
+ });
+ });
+
+ it("moves on to the next image needing attention", () => {
+ const { onNext } = renderSection(describable("Done"), {
+ review: { needsDescription: 1, untagged: 1, untaggable: 0 },
+ });
+ fireEvent.click(screen.getByTestId(NEXT));
+ expect(onNext).toHaveBeenCalledOnce();
+ });
+
+ it.each<[string, ImageAccessibility, ImageReview, boolean]>([
+ [
+ "only this one needs a description",
+ describable(null),
+ { needsDescription: 1, untagged: 0, untaggable: 0 },
+ false,
+ ],
+ [
+ "another needs a description",
+ describable(null),
+ { needsDescription: 2, untagged: 0, untaggable: 0 },
+ true,
+ ],
+ [
+ "this one can't be tagged, nor can another",
+ untagged,
+ { needsDescription: 0, untagged: 0, untaggable: 2 },
+ false,
+ ],
+ [
+ "this one can't be tagged, and another is untagged",
+ untagged,
+ { needsDescription: 0, untagged: 1, untaggable: 1 },
+ true,
+ ],
+ [
+ "only this one is untagged, and can be tagged",
+ taggable,
+ { needsDescription: 0, untagged: 1, untaggable: 0 },
+ false,
+ ],
+ [
+ "another is untagged",
+ describable("Done"),
+ { needsDescription: 0, untagged: 1, untaggable: 0 },
+ true,
+ ],
+ [
+ "a decorative image, one elsewhere",
+ { kind: "decorative", canUndecorate: false },
+ { needsDescription: 1, untagged: 0, untaggable: 0 },
+ true,
+ ],
+ [
+ "nothing left",
+ describable("Done"),
+ { needsDescription: 0, untagged: 0, untaggable: 0 },
+ false,
+ ],
+ ])(
+ "offers Next only when another image needs attention: %s",
+ (_, accessibility, review, offered) => {
+ renderSection(accessibility, { review });
+ expect(screen.queryByTestId(NEXT) !== null).toBe(offered);
+ },
+ );
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ImageAccessibilitySection.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ImageAccessibilitySection.tsx
new file mode 100644
index 0000000000..6c2cf502a5
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ImageAccessibilitySection.tsx
@@ -0,0 +1,194 @@
+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 {
+ Section,
+ SectionLabel,
+} from "@editor/tools/pdfTextEditor/components/inspector/InspectorPrimitives";
+import {
+ attentionFor,
+ isActionable,
+ type ImageAccessibility,
+ type ImageReview,
+} from "@editor/tools/pdfTextEditor/util/imageAccessibility";
+
+/**
+ * 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.
+ */
+export function ImageAccessibilitySection({
+ accessibility,
+ onSetDescription,
+ onSetDecorative,
+ review,
+ onNext,
+}: {
+ accessibility: ImageAccessibility;
+ onSetDescription: (text: string) => void;
+ onSetDecorative: (decorative: boolean) => void;
+ review: ImageReview;
+ onNext: () => void;
+}) {
+ const { t } = useTranslation();
+ const othersPending =
+ review.needsDescription +
+ review.untagged -
+ (isActionable(attentionFor(accessibility)) ? 1 : 0);
+ return (
+ <Section testId="pdf-editor-image-accessibility">
+ <SectionLabel info={<AccessibilityInfo />}>
+ {t("pdfTextEditor.inspector.accessibility.heading", "Accessibility")}
+ </SectionLabel>
+ <Stack gap="xs">
+ {accessibility.kind === "blocked" ? (
+ <Text
+ size="xs"
+ c="dimmed"
+ data-testid="pdf-editor-image-accessibility-status"
+ >
+ {blockedMessage(t, accessibility)}
+ </Text>
+ ) : (
+ <>
+ <Checkbox
+ label={t(
+ "pdfTextEditor.inspector.accessibility.decorativeLabel",
+ "Decorative image",
+ )}
+ description={
+ accessibility.kind === "describable" &&
+ !accessibility.canBeDecorative
+ ? t(
+ "pdfTextEditor.inspector.accessibility.mixedContent",
+ "Figure includes other content",
+ )
+ : undefined
+ }
+ checked={accessibility.kind === "decorative"}
+ disabled={
+ accessibility.kind === "decorative"
+ ? !accessibility.canUndecorate
+ : !accessibility.canBeDecorative
+ }
+ onChange={(e) => onSetDecorative(e.currentTarget.checked)}
+ data-testid="pdf-editor-image-decorative"
+ />
+ {accessibility.kind === "describable" && (
+ <Textarea
+ label={t(
+ "pdfTextEditor.inspector.accessibility.description",
+ "Image description",
+ )}
+ value={accessibility.description ?? ""}
+ onChange={(e) => onSetDescription(e.currentTarget.value)}
+ autosize
+ minRows={2}
+ maxRows={6}
+ size="xs"
+ data-testid="pdf-editor-image-description"
+ />
+ )}
+ </>
+ )}
+ {othersPending > 0 && (
+ <Button
+ size="sm"
+ variant="secondary"
+ accent="neutral"
+ fullWidth
+ justify="start"
+ leftSection={<Icon name="arrow-right" size={20} />}
+ onClick={onNext}
+ data-testid="pdf-editor-image-description-next"
+ >
+ {t("pdfTextEditor.inspector.accessibility.nextImage", "Next image")}
+ </Button>
+ )}
+ </Stack>
+ </Section>
+ );
+}
+
+function blockedMessage(
+ t: TFunction,
+ accessibility: Extract<ImageAccessibility, { kind: "blocked" }>,
+): string {
+ switch (accessibility.blocker) {
+ case "untagged":
+ return accessibility.documentTagged
+ ? t(
+ "pdfTextEditor.inspector.accessibility.untaggedImage",
+ "Can't be tagged here",
+ )
+ : t(
+ "pdfTextEditor.inspector.accessibility.untaggedDocument",
+ "Document has no tags",
+ );
+ case "not-figure":
+ return t(
+ "pdfTextEditor.inspector.accessibility.notFigure",
+ "Tagged as part of the text",
+ );
+ case "encrypted":
+ return t(
+ "pdfTextEditor.inspector.accessibility.encrypted",
+ "Tags can't be edited in an encrypted file",
+ );
+ case "unreadable":
+ return t(
+ "pdfTextEditor.inspector.accessibility.unreadable",
+ "This file's tags can't be edited",
+ );
+ }
+}
+
+/** What the section's controls are for, behind the (i) tool steps use. */
+function AccessibilityInfo() {
+ const { t } = useTranslation();
+ return (
+ <Tooltip
+ sidebarTooltip
+ pinOnClick
+ header={{
+ title: t(
+ "pdfTextEditor.inspector.accessibility.heading",
+ "Accessibility",
+ ),
+ }}
+ tips={[
+ {
+ title: t(
+ "pdfTextEditor.inspector.accessibility.decorativeLabel",
+ "Decorative image",
+ ),
+ description: t(
+ "pdfTextEditor.inspector.accessibility.decorativeInfo",
+ "Screen readers skip decorative images. Use it for borders, backgrounds and other images that carry no information.",
+ ),
+ },
+ {
+ title: t(
+ "pdfTextEditor.inspector.accessibility.description",
+ "Image description",
+ ),
+ description: t(
+ "pdfTextEditor.inspector.accessibility.descriptionInfo",
+ "Screen readers read this out in place of the image.",
+ ),
+ },
+ ]}
+ >
+ <span
+ style={{ display: "flex", color: "var(--icon-files-color)" }}
+ data-testid="pdf-editor-image-accessibility-info"
+ >
+ <Icon name="info" size={14} />
+ </span>
+ </Tooltip>
+ );
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/InspectorPrimitives.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/InspectorPrimitives.tsx
index 029a307d7a..7ee905e2c0 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/InspectorPrimitives.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/InspectorPrimitives.tsx
@@ -3,25 +3,30 @@ import { Box, Group, NumberInput, Stack, Text, Tooltip } from "@mantine/core";
import { Icon } from "@editor/ui/Icon";
/** Shared layout atoms for the editor's properties inspector. */
-/** Uppercase section heading, optionally with a trailing control. */
+/** Uppercase section heading, optionally with an info affordance beside it and a trailing control. */
export function SectionLabel({
children,
+ info,
right,
}: {
children: ReactNode;
+ info?: ReactNode;
right?: ReactNode;
}) {
return (
<Group justify="space-between" wrap="nowrap" gap={4} mb={8}>
- <Text
- size="xs"
- fw={600}
- c="dimmed"
- tt="uppercase"
- style={{ letterSpacing: "0.5px" }}
- >
- {children}
- </Text>
+ <Group gap={6} wrap="nowrap">
+ <Text
+ size="xs"
+ fw={600}
+ c="dimmed"
+ tt="uppercase"
+ style={{ letterSpacing: "0.5px" }}
+ >
+ {children}
+ </Text>
+ {info}
+ </Group>
{right}
</Group>
);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx
index 1343837f7a..46233afa5a 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx
@@ -13,6 +13,8 @@ import type { SelectionGeometry } from "@editor/tools/pdfTextEditor/hooks/useSel
import type { useToolbarController } from "@editor/tools/pdfTextEditor/hooks/useToolbarController";
import type { SelectionState } from "@editor/tools/pdfTextEditor/types";
import { modShortcut } from "@editor/utils/hotkeys";
+import { ACCESSIBILITY_EDITING } from "@editor/constants/featureFlags";
+import { ImageAccessibilitySection } from "@editor/tools/pdfTextEditor/components/inspector/ImageAccessibilitySection";
export type InspectorController = ReturnType<typeof useToolbarController>;
@@ -71,6 +73,15 @@ export function SelectionInspector({
/>
)}
{hasImageSelection && <ImageSection controller={controller} />}
+ {ACCESSIBILITY_EDITING && controller.imageAccessibility && (
+ <ImageAccessibilitySection
+ accessibility={controller.imageAccessibility}
+ onSetDescription={controller.onSetImageDescription}
+ onSetDecorative={controller.onSetImageDecorative}
+ review={controller.imageReview}
+ onNext={controller.onSelectNextImageToReview}
+ />
+ )}
</Stack>
);
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useImageAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useImageAccessibility.ts
new file mode 100644
index 0000000000..77e658e9a3
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useImageAccessibility.ts
@@ -0,0 +1,156 @@
+import { useCallback, useMemo } from "react";
+import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
+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 {
+ EditorStore,
+ EditorViewState,
+} from "@editor/tools/pdfTextEditor/store/EditorStore";
+import type {
+ ImageObjectSnapshot,
+ SelectionState,
+} from "@editor/tools/pdfTextEditor/types";
+import {
+ imageAccessibility,
+ nextImageNeedingAttention,
+ retaggableTag,
+ reviewImages,
+ type ImageAccessibility,
+ type ImageReview,
+} from "@editor/tools/pdfTextEditor/util/imageAccessibility";
+
+/**
+ * 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.
+ */
+export function useImageAccessibility(
+ store: EditorStore,
+ state: EditorViewState,
+ selection: SelectionState,
+) {
+ const image = useMemo((): ImageObjectSnapshot | null => {
+ if (
+ selection.imageIds.length !== 1 ||
+ selection.runIds.length > 0 ||
+ selection.shapeIds.length > 0
+ )
+ return null;
+ return (
+ state.pages
+ .flatMap((page) => page.images)
+ .find((img) => img.id === selection.imageIds[0]) ?? null
+ );
+ }, [state.pages, selection]);
+
+ const accessibility = useMemo((): ImageAccessibility | null => {
+ const doc = store.document;
+ return doc && image ? imageAccessibility(doc, image) : null;
+ }, [store, image]);
+
+ const setDescription = useCallback(
+ (text: string) => {
+ if (!image || accessibility?.kind !== "describable") return;
+ // An emptied field removes the description rather than saving an empty one.
+ const command = describeCommand(image, text === "" ? null : text);
+ if (command) store.dispatch(command);
+ },
+ [store, image, accessibility],
+ );
+
+ const setDecorative = useCallback(
+ (decorative: boolean) => {
+ const doc = store.document;
+ if (!doc || !image) return;
+ const command = decorativeCommand(doc, image, decorative);
+ if (command) store.dispatch(command);
+ },
+ [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(() =>
+ document
+ .querySelector(`[data-testid="pdf-editor-image-${next.id}"]`)
+ ?.scrollIntoView({ block: "center", behavior: "smooth" }),
+ );
+ return true;
+ }, [store]);
+
+ return {
+ accessibility,
+ setDescription,
+ setDecorative,
+ review,
+ selectNextImage,
+ };
+}
+
+function describeCommand(
+ image: ImageObjectSnapshot,
+ alt: string | null,
+): Command | null {
+ if (image.mcid !== undefined) {
+ return new SetAltTextCommand({
+ pageIndex: image.pageIndex,
+ mcid: image.mcid,
+ alt,
+ });
+ }
+ // Clearing the field of an image no element owns leaves it untagged.
+ if (alt === null) return null;
+ return new TagImageCommand({
+ pageIndex: image.pageIndex,
+ imageId: image.id,
+ as: "figure",
+ alt,
+ });
+}
+
+/**
+ * Content the file's elements own changes through its element; anything
+ * else is retagged.
+ */
+function decorativeCommand(
+ doc: EditorDocument,
+ image: ImageObjectSnapshot,
+ decorative: boolean,
+): Command | null {
+ if (retaggableTag(doc, image)) {
+ return new TagImageCommand({
+ pageIndex: image.pageIndex,
+ imageId: image.id,
+ as: decorative ? "artifact" : "figure",
+ });
+ }
+ if (image.mcid === undefined) return null;
+ return new SetDecorativeCommand({
+ pageIndex: image.pageIndex,
+ mcid: image.mcid,
+ decorative,
+ });
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts
index 1fd0cd0d44..1fbd75f6f9 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 { useImageAccessibility } from "@editor/tools/pdfTextEditor/hooks/useImageAccessibility";
import { deriveToolbarState } from "@editor/tools/pdfTextEditor/util/toolbarState";
import { warmDocumentDeviceFonts } from "@editor/tools/pdfTextEditor/util/fontCapability";
import {
@@ -51,6 +52,7 @@ export function useToolbarController(
selection: SelectionState,
) {
const sel = useSelectionActions(store);
+ const imageA11y = useImageAccessibility(store, state, selection);
const onToggleLock = useCallback(() => {
const doc = store.document;
@@ -517,6 +519,11 @@ export function useToolbarController(
onReplaceImage,
onEditImageExternally,
externalEditSupported: isExternalImageEditSupported(),
+ imageAccessibility: imageA11y.accessibility,
+ onSetImageDescription: imageA11y.setDescription,
+ onSetImageDecorative: imageA11y.setDecorative,
+ imageReview: imageA11y.review,
+ onSelectNextImageToReview: imageA11y.selectNextImage,
selectionAllLocked,
hasRunSelection: selection.runIds.length > 0,
hasImageSelection: selection.imageIds.length > 0,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts
index e7c8b15742..4e17cfadcb 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts
@@ -5,13 +5,17 @@ import {
openRawDocument,
} from "@editor/services/pdfiumService";
import { Page } from "@editor/tools/pdfTextEditor/model/Page";
-import {
- PageStructure,
- type StructureElement,
-} from "@editor/tools/pdfTextEditor/model/PageStructure";
+import { PageStructure } from "@editor/tools/pdfTextEditor/model/PageStructure";
import type { StructureEdit } from "@editor/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits";
import { readPageStructure } from "@editor/tools/pdfTextEditor/pdfium/PdfiumStructureReader";
-import { readFileStructure } from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";
+import {
+ readFileStructure,
+ type FilePageStructure,
+} from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";
+import {
+ imagesInReadingOrder,
+ precedingTaggedMcid,
+} from "@editor/tools/pdfTextEditor/util/figurePlacement";
import { DisplayTransform } from "@editor/tools/pdfTextEditor/model/DisplayTransform";
import { FontRef } from "@editor/tools/pdfTextEditor/model/FontRef";
import { prepareForEditing } from "@editor/tools/pdfTextEditor/pdfdoc/prepareForEditing";
@@ -33,7 +37,7 @@ export class EditorDocument {
private readonly pageCache: Map<number, Page>;
private readonly structureCache = new Map<number, PageStructure>();
/** Each page's elements from the file's own ParentTree; null when only PDFium's view is available. */
- private readonly fileStructure: Map<number, StructureElement[]> | null;
+ private readonly fileStructure: Map<number, FilePageStructure> | null;
private readonly ownedFonts: Map<string, FontRef>;
private _disposed: boolean;
// Form-fill environment. Widgets with no appearance stream are drawn ONLY by
@@ -48,7 +52,7 @@ export class EditorDocument {
module: WrappedPdfiumModule,
docPtr: number,
openedBytes: Uint8Array,
- fileStructure: Map<number, StructureElement[]> | null,
+ fileStructure: Map<number, FilePageStructure> | null,
) {
this.module = module;
this.docPtr = docPtr;
@@ -158,20 +162,35 @@ export class EditorDocument {
structure(pageIndex: number): PageStructure {
const cached = this.structureCache.get(pageIndex);
if (cached) return cached;
- // PDFium's tree is the fallback, read-only: its MCIDs carry no page, so
- // an edit made through it could land on the wrong element.
- const structure = this.fileStructure
- ? new PageStructure(this.fileStructure.get(pageIndex) ?? [])
- : new PageStructure(
- readPageStructure(this.module, this.page(pageIndex).pagePtr),
- this.encrypted()
- ? "the file is encrypted"
- : "the file's tags could not be read for editing",
- );
+ const structure = this.readStructure(pageIndex);
this.structureCache.set(pageIndex, structure);
return structure;
}
+ private readStructure(pageIndex: number): PageStructure {
+ // PDFium's tree is the fallback, read-only: its MCIDs carry no page, so
+ // an edit made through it could land on the wrong element.
+ if (!this.fileStructure) {
+ return new PageStructure(
+ readPageStructure(this.module, this.page(pageIndex).pagePtr),
+ this.encrypted() ? "encrypted" : "unreadable",
+ );
+ }
+ const page = this.fileStructure.get(pageIndex);
+ if (!page) return new PageStructure([]);
+ if (page.slotCount === null) return new PageStructure([], "unreadable");
+ return new PageStructure(page.elements, null, page.slotCount);
+ }
+
+ /** True when the catalog marks the file as tagged (ISO 32000-1 14.7.1). */
+ isTagged(): boolean {
+ try {
+ return this.module.FPDFCatalog_IsTagged(this.docPtr);
+ } catch {
+ return false;
+ }
+ }
+
private encrypted(): boolean {
try {
// -1 when the file has no security handler.
@@ -183,9 +202,36 @@ export class EditorDocument {
/** Every unsaved structure edit, in the form the save pass takes. */
structureEdits(): StructureEdit[] {
- return [...this.structureCache].flatMap(([pageIndex, structure]) =>
- structure.pendingEdits().map((edit) => ({ pageIndex, ...edit })),
- );
+ return [...this.structureCache].flatMap(([pageIndex, structure]) => [
+ ...structure.pendingEdits().map((edit) => ({ pageIndex, ...edit })),
+ ...this.addedFigureEdits(pageIndex, structure),
+ ]);
+ }
+
+ /**
+ * The page's added figures in reading order, so one placed after another
+ * finds it already in the tree. A figure whose image was deleted is left
+ * out: there is nothing left for it to describe.
+ */
+ private addedFigureEdits(
+ pageIndex: number,
+ structure: PageStructure,
+ ): StructureEdit[] {
+ const page = this.pageCache.get(pageIndex);
+ if (!page) return [];
+ const figures = structure.addedFigures();
+ return imagesInReadingOrder(page).flatMap((image) => {
+ const figure = figures.find((f) => f.mcid === image.mcid);
+ if (!figure) return [];
+ return [
+ {
+ pageIndex,
+ ...figure,
+ decorative: false,
+ newFigure: { after: precedingTaggedMcid(page, image) },
+ },
+ ];
+ });
}
registerOwnedFont(font: FontRef): void {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/ImageObject.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/ImageObject.ts
index fe0c01232a..71b2ce0689 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/ImageObject.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/ImageObject.ts
@@ -15,8 +15,13 @@ export class ImageObject {
dirty: boolean;
/** Session-only lock; see TextRun.locked. */
locked: boolean;
- readonly mcid: number | null;
- readonly artifact: boolean;
+ /**
+ * The page's MCID for the image: its own, or the form's for an image drawn
+ * by a form XObject. Changed by TagImageCommand, along with the object's
+ * marks.
+ */
+ mcid: number | null;
+ artifact: boolean;
constructor(
init: ImageObjectSnapshot & {
@@ -45,6 +50,7 @@ export class ImageObject {
locked: this.locked || undefined,
mcid: this.mcid ?? undefined,
artifact: this.artifact || undefined,
+ inForm: this.containerPtr !== 0 || undefined,
};
}
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts
index f3b7037fc3..f8769c1a3b 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts
@@ -9,13 +9,20 @@ export interface StructureElement {
* pages apart, so there it can also list other pages' MCIDs.
*/
mcids: number[];
+ /**
+ * True when the element's content is all marked content on its pages: no
+ * child elements, annotations or form XObject content.
+ */
+ onlyMarkedContent: boolean;
}
/** An unsaved change to an element, and the MCID the save addresses it by. */
export interface StructureElementEdit {
mcid: number;
- /** The new /Alt; null removes it. */
+ /** The /Alt to save; null removes it. */
alt: string | null;
+ /** Turn the element's content into an artifact and drop the element. */
+ decorative: boolean;
}
/**
@@ -24,25 +31,50 @@ export interface StructureElementEdit {
*/
const DESCRIBABLE_TYPES = new Set(["Figure", "Formula"]);
+/** Why the save cannot write descriptions for a page. */
+export type ReadOnlyReason = "encrypted" | "unreadable";
+
+/** Why content cannot take a description. */
+export type DescriptionBlocker = "untagged" | "not-figure" | ReadOnlyReason;
+
+/** Why content cannot be marked decorative. */
+export type DecorativeBlocker = DescriptionBlocker | "mixed-content";
+
+/** A Figure the session adds for content the file leaves untagged. */
+export interface AddedFigure {
+ mcid: number;
+ /** The /Alt to save; null for none. */
+ alt: string | null;
+}
+
/**
* The structure elements of one page plus the session's unsaved edits to
- * them. Edits are keyed by element rather than MCID, so an element that owns
- * several MCIDs has one description however it was addressed.
+ * them, and the figures it adds. Edits are keyed by element rather than MCID,
+ * so an element that owns several MCIDs has one description however it was
+ * addressed.
*/
export class PageStructure {
readonly elements: readonly StructureElement[];
private readonly byMcid = new Map<number, StructureElement>();
private readonly edits = new Map<StructureElement, StructureElementEdit>();
+ private readonly added = new Map<number, StructureElement>();
/** Why the save cannot write descriptions for this page, or null when it can. */
- readonly readOnly: string | null;
+ readonly readOnly: ReadOnlyReason | null;
+ /**
+ * The length of the page's ParentTree array, so the first MCID it has no
+ * slot for; null when the page has no array to add a figure to.
+ */
+ private readonly slotCount: number | null;
constructor(
elements: readonly StructureElement[],
- readOnly: string | null = null,
+ readOnly: ReadOnlyReason | null = null,
+ slotCount: number | null = null,
) {
this.elements = elements;
this.readOnly = readOnly;
+ this.slotCount = slotCount;
for (const el of elements) {
for (const mcid of el.mcids) this.byMcid.set(mcid, el);
}
@@ -57,16 +89,26 @@ export class PageStructure {
}
/** Why the content `mcid` marks cannot take a description, or null when it can. */
- cannotDescribe(mcid: number): string | null {
+ cannotDescribe(mcid: number): DescriptionBlocker | null {
const el = this.element(mcid);
- if (!el) return "no structure element owns it";
+ if (!el) return "untagged";
if (this.readOnly) return this.readOnly;
- if (!DESCRIBABLE_TYPES.has(el.type)) {
- return `it belongs to a ${el.type || "untyped"} element, whose description would replace its text`;
- }
+ if (!DESCRIBABLE_TYPES.has(el.type)) return "not-figure";
return null;
}
+ /** Why the content `mcid` marks cannot be marked decorative, or null when it can. */
+ cannotMarkDecorative(mcid: number): DecorativeBlocker | null {
+ const blocker = this.cannotDescribe(mcid);
+ if (blocker) return blocker;
+ return this.element(mcid)!.onlyMarkedContent ? null : "mixed-content";
+ }
+
+ /** True when the session has marked the element owning `mcid` decorative. */
+ decorative(mcid: number): boolean {
+ return this.editFor(mcid)?.decorative ?? false;
+ }
+
/** The description as it will be saved: the session's edit, else the file's. */
alt(mcid: number): string | null {
const el = this.element(mcid);
@@ -81,6 +123,22 @@ export class PageStructure {
return el ? (this.edits.get(el) ?? null) : null;
}
+ /** Set the description, keeping any decorative mark. Throws as setEdit does. */
+ setAlt(mcid: number, alt: string | null): void {
+ this.setEdit(mcid, { mcid, alt, decorative: this.decorative(mcid) });
+ }
+
+ /**
+ * Mark or unmark decorative, keeping the description. Throws as setEdit
+ * does, and for an added figure, whose content is retagged instead.
+ */
+ setDecorative(mcid: number, decorative: boolean): void {
+ if (this.added.has(mcid)) {
+ throw new Error(`MCID ${mcid} is an added figure`);
+ }
+ this.setEdit(mcid, { mcid, alt: this.alt(mcid), decorative });
+ }
+
/** Throws when no element owns `mcid`: a command must not record an edit the save cannot address. */
setEdit(mcid: number, edit: StructureElementEdit | null): void {
const el = this.element(mcid);
@@ -89,7 +147,65 @@ export class PageStructure {
else this.edits.delete(el);
}
+ /** Edits to the file's elements; added figures are listed by addedFigures. */
pendingEdits(): StructureElementEdit[] {
- return [...this.edits.values()];
+ const added = new Set(this.added.values());
+ return [...this.edits]
+ .filter(([el]) => !added.has(el))
+ .map(([, edit]) => edit);
+ }
+
+ /** Why untagged content on this page cannot be given a figure, or null when it can. */
+ cannotAddFigure(): DescriptionBlocker | null {
+ if (this.readOnly) return this.readOnly;
+ return this.slotCount === null ? "untagged" : null;
+ }
+
+ /**
+ * An MCID no slot or added figure on the page uses, above `contentMax`: the
+ * highest MCID the page's content carries, -1 for none.
+ */
+ freeMcid(contentMax: number): number {
+ return Math.max(
+ this.slotCount ?? 0,
+ contentMax + 1,
+ ...[...this.added.keys()].map((mcid) => mcid + 1),
+ );
+ }
+
+ isAdded(mcid: number): boolean {
+ return this.added.has(mcid);
+ }
+
+ /** Give the content `mcid` marks a new Figure. Throws when an element already owns it. */
+ addFigure(mcid: number): void {
+ if (this.byMcid.has(mcid)) {
+ throw new Error(`MCID ${mcid} already has an element`);
+ }
+ const figure: StructureElement = {
+ type: "Figure",
+ alt: null,
+ actualText: null,
+ mcids: [mcid],
+ onlyMarkedContent: true,
+ };
+ this.added.set(mcid, figure);
+ this.byMcid.set(mcid, figure);
+ }
+
+ /** Drop an added figure and its description. */
+ removeFigure(mcid: number): void {
+ const figure = this.added.get(mcid);
+ if (!figure) return;
+ this.added.delete(mcid);
+ this.byMcid.delete(mcid);
+ this.edits.delete(figure);
+ }
+
+ addedFigures(): AddedFigure[] {
+ return [...this.added.keys()].map((mcid) => ({
+ mcid,
+ alt: this.alt(mcid),
+ }));
}
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/markedContent.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/markedContent.ts
new file mode 100644
index 0000000000..f9239127ec
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/markedContent.ts
@@ -0,0 +1,275 @@
+/**
+ * Reading and rewriting a page's marked content and its ParentTree entry, for
+ * the passes that keep the structure tree and the content in step.
+ */
+import {
+ deflate,
+ fromLatin1,
+ toLatin1,
+} from "@editor/tools/pdfTextEditor/pdfdoc/bytes";
+import {
+ parseOps,
+ tokenize,
+} from "@editor/tools/pdfTextEditor/pdfdoc/contentOps";
+import {
+ arrayItems,
+ referencedObject,
+ setDictEntry,
+ spliceValue,
+ type NumberTreeEntry,
+ type RawPdf,
+ type ValueSpan,
+} from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import {
+ plainObject,
+ streamObject,
+ type RevisionObject,
+} from "@editor/tools/pdfTextEditor/pdfdoc/revision";
+
+interface Span {
+ start: number;
+ end: number;
+}
+
+/** One `BDC` that carries an MCID. Spans index the text of stream `stream`. */
+export interface McidSite {
+ stream: number;
+ mcid: number;
+ /** The whole operator, operands included. */
+ operator: Span;
+ /** The MCID's number; null when a named property list holds it. */
+ number: Span | null;
+}
+
+export interface PageSites {
+ /** The page's content stream objects, in /Contents order. */
+ refs: number[];
+ /** Each stream's decoded text, parallel to `refs`. */
+ texts: string[];
+ sites: McidSite[];
+}
+
+/** The page's content streams and every MCID they carry, or null when a stream cannot be read. */
+export async function pageSites(
+ pdf: RawPdf,
+ pageNum: number,
+): Promise<PageSites | null> {
+ const page = pdf.objectBody(pageNum);
+ const refs = page ? pdf.contentRefs(page) : [];
+ if (refs.length === 0) return null;
+ const texts: string[] = [];
+ for (const ref of refs) {
+ const data = await pdf.streamData(ref);
+ if (!data) return null;
+ texts.push(toLatin1(data));
+ }
+ const resources = pdf.pageInherited(pageNum, "Resources");
+ const properties = resources ? pdf.resolve(resources, "Properties") : null;
+ const namedMcid = (name: string): number | null => {
+ const list = properties ? pdf.resolve(properties, name) : null;
+ return list ? pdf.dictInt(list, "MCID") : null;
+ };
+ return {
+ refs,
+ texts,
+ sites: texts.flatMap((text, stream) => mcidSites(text, stream, namedMcid)),
+ };
+}
+
+/**
+ * Every `BDC` carrying an MCID, in content order: inline (`/P <</MCID 0>> BDC`)
+ * or through a named property list (`/P /MC0 BDC`), which PDFium keeps in that
+ * form when it regenerates a page.
+ */
+function mcidSites(
+ text: string,
+ stream: number,
+ namedMcid: (name: string) => number | null,
+): McidSite[] {
+ const sites: McidSite[] = [];
+ for (const op of parseOps(text)) {
+ if (op.op !== "BDC") continue;
+ const operator = { start: op.start, end: op.end };
+ const properties = op.operands[1];
+ if (properties?.startsWith("/")) {
+ const mcid = namedMcid(properties.slice(1));
+ if (mcid !== null) sites.push({ stream, mcid, operator, number: null });
+ continue;
+ }
+ const tokens = tokenize(text.slice(op.start, op.end));
+ let depth = 0;
+ for (let i = 0; i < tokens.length; i++) {
+ const t = tokens[i].text;
+ if (t === "<<") depth += 1;
+ else if (t === ">>") depth -= 1;
+ else if (
+ depth === 1 &&
+ t === "/MCID" &&
+ /^\d+$/.test(tokens[i + 1]?.text ?? "")
+ ) {
+ const number = tokens[i + 1];
+ sites.push({
+ stream,
+ mcid: parseInt(number.text, 10),
+ operator,
+ number: {
+ start: op.start + number.start,
+ end: op.start + number.end,
+ },
+ });
+ break;
+ }
+ }
+ }
+ return sites;
+}
+
+/** The value texts of an element's /K: none when it has no /K, null when /K cannot be read. */
+export function elementKids(pdf: RawPdf, body: string): string[] | null {
+ const span = pdf.valueSpan(body, "K");
+ if (!span) return [];
+ if (!span.text.startsWith("[")) return [span.text];
+ return arrayItems(span.text)?.map((kid) => kid.text) ?? null;
+}
+
+/** True when every kid in the element's /K is an MCID or an MCR on a page, rather than a child element, an annotation or form XObject content. */
+export function ownsOnlyMarkedContent(pdf: RawPdf, body: string): boolean {
+ const kids = elementKids(pdf, body);
+ if (!kids || kids.length === 0) return false;
+ return kids.every((kid) => {
+ if (/^\d+$/.test(kid)) return true;
+ const ref = referencedObject(kid);
+ const dict = ref === null ? kid : pdf.objectBody(ref);
+ if (!dict?.trimStart().startsWith("<<")) return false;
+ return pdf.dictName(dict, "Type") === "MCR" && !pdf.valueSpan(dict, "Stm");
+ });
+}
+
+/** Content streams more than one page draws; rewriting one would change every page that draws it. */
+export function streamsUsedByMoreThanOnePage(pdf: RawPdf): Set<number> {
+ const seen = new Set<number>();
+ const shared = new Set<number>();
+ for (const pageNum of pdf.pageNumbers()) {
+ const body = pdf.objectBody(pageNum);
+ for (const ref of body ? new Set(pdf.contentRefs(body)) : []) {
+ if (seen.has(ref)) shared.add(ref);
+ seen.add(ref);
+ }
+ }
+ return shared;
+}
+
+/** Content stream object `num` holding `text`, compressed when the platform can. */
+export async function contentStreamObject(
+ num: number,
+ text: string,
+): Promise<RevisionObject> {
+ const raw = fromLatin1(text);
+ const packed = await deflate(raw);
+ return {
+ num,
+ body: packed
+ ? streamObject("<< /Filter /FlateDecode >>", packed)
+ : streamObject("<< >>", raw),
+ };
+}
+
+interface PageSlots {
+ entry: NumberTreeEntry;
+ /** The slots as read, joined, to tell whether the edits changed them. */
+ read: string;
+ slots: string[];
+}
+
+/**
+ * The pages' ParentTree arrays as a save's edits leave them, shared by the
+ * passes that change them so no pass writes over another's slots. An array
+ * written directly in its number-tree node is spliced into that node, back to
+ * front, so pages whose arrays share one node each keep their own span.
+ */
+export class ParentTreeWriter {
+ private readonly pages = new Map<number, PageSlots | null>();
+
+ constructor(
+ private readonly pdf: RawPdf,
+ private readonly treeRoot: number,
+ ) {}
+
+ /**
+ * The page's slots as the edits so far leave them, for the caller to change
+ * in place; null when the page has no ParentTree array.
+ */
+ slots(pageNum: number): string[] | null {
+ if (!this.pages.has(pageNum))
+ this.pages.set(pageNum, this.readPage(pageNum));
+ return this.pages.get(pageNum)?.slots ?? null;
+ }
+
+ /**
+ * The changed arrays, or the nodes that hold them directly. A node another
+ * pass already rewrote in `bodies` is merged there instead, so the revision
+ * does not carry the object twice. Null when such a node cannot be merged.
+ */
+ objects(bodies: Map<number, string>): RevisionObject[] | null {
+ const arrays = new Map<number, string>();
+ const splices = new Map<number, { span: ValueSpan; text: string }[]>();
+ for (const page of this.pages.values()) {
+ if (!page) continue;
+ const array = `[${page.slots.join(" ")}]`;
+ if (array === page.read) continue;
+ const arrayNum = referencedObject(page.entry.span.text);
+ if (arrayNum !== null) {
+ arrays.set(arrayNum, array);
+ continue;
+ }
+ const node = splices.get(page.entry.objNum) ?? [];
+ node.push({ span: page.entry.span, text: array });
+ splices.set(page.entry.objNum, node);
+ }
+ const out: RevisionObject[] = [];
+ for (const [num, array] of arrays) {
+ out.push({ num, body: plainObject(array) });
+ }
+ for (const [num, node] of splices) {
+ let body = this.pdf.objectBody(num)!;
+ for (const s of node.sort((a, b) => b.span.start - a.span.start)) {
+ body = spliceValue(body, s.span, s.text);
+ }
+ const edited = bodies.get(num);
+ if (edited === undefined) {
+ out.push({ num, body: plainObject(body) });
+ continue;
+ }
+ const merged = this.mergeInlineTree(num, body, edited);
+ if (!merged) return null;
+ bodies.set(num, merged);
+ }
+ return out;
+ }
+
+ /**
+ * `edited` with the /ParentTree of `spliced`. Spans index the original body,
+ * so they are applied there and the whole tree carried across. Only the
+ * StructTreeRoot can be both an element's parent and an inline tree's node:
+ * an indirect node is never an element.
+ */
+ private mergeInlineTree(
+ num: number,
+ spliced: string,
+ edited: string,
+ ): string | null {
+ if (num !== this.treeRoot) return null;
+ const tree = this.pdf.valueSpan(spliced, "ParentTree");
+ return tree ? setDictEntry(edited, "ParentTree", tree.text) : null;
+ }
+
+ private readPage(pageNum: number): PageSlots | null {
+ const page = this.pdf.objectBody(pageNum);
+ const key = page ? this.pdf.dictInt(page, "StructParents") : null;
+ const tree =
+ key === null ? null : this.pdf.parentTreeArray(this.treeRoot, key);
+ if (!tree?.items) return null;
+ const slots = tree.items.map((item) => item.text);
+ return { entry: tree.entry, read: `[${slots.join(" ")}]`, slots };
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addFigures.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addFigures.ts
new file mode 100644
index 0000000000..917c19ff92
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addFigures.ts
@@ -0,0 +1,144 @@
+/**
+ * Give content the file leaves untagged a Figure element of its own. The
+ * editor marked the content with its MCID before PDFium regenerated the page,
+ * so only the tree changes here.
+ */
+import {
+ elementKids,
+ pageSites,
+ type ParentTreeWriter,
+ type PageSites,
+} from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";
+import {
+ referencedObject,
+ setDictEntry,
+ type RawPdf,
+} from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import { encodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString";
+
+export interface NewFigure {
+ pageIndex: number;
+ mcid: number;
+ alt: string | null;
+ /**
+ * The MCID of the content the figure reads after: it goes after the element
+ * owning that, or before the element owning the page's first tagged content
+ * when null or unowned.
+ */
+ after: number | null;
+}
+
+interface Placement {
+ parent: number;
+ sibling: number | null;
+ before: boolean;
+}
+
+/**
+ * Plan a Figure for each of `figures`, in order, so one placed after an
+ * earlier one finds it. New element bodies, and the parents they join, are
+ * written to `bodies`, and ParentTree slots to `parentTree`. Returns why a
+ * figure could not be added, by index; nothing is written for a document
+ * with any failure, so the caller must discard it all.
+ */
+export async function addFigures(
+ pdf: RawPdf,
+ treeRoot: number,
+ figures: readonly NewFigure[],
+ bodies: Map<number, string>,
+ parentTree: ParentTreeWriter,
+): Promise<Map<number, string>> {
+ const failed = new Map<number, string>();
+ const body = (num: number) => bodies.get(num) ?? pdf.objectBody(num);
+ const sites = new Map<number, Promise<PageSites | null>>();
+ let nextNum = pdf.highestObjectNumber + 1;
+
+ for (const [index, figure] of figures.entries()) {
+ const pageNum = pdf.pageNumberAt(figure.pageIndex);
+ const slots = pageNum === null ? null : parentTree.slots(pageNum);
+ if (pageNum === null || !slots) {
+ failed.set(index, "its page has no ParentTree array");
+ continue;
+ }
+ if (referencedObject(slots[figure.mcid] ?? "") !== null) {
+ failed.set(index, "another element owns its MCID");
+ continue;
+ }
+ if (!sites.has(pageNum)) sites.set(pageNum, pageSites(pdf, pageNum));
+ const read = await sites.get(pageNum)!;
+ if (!read?.sites.some((site) => site.mcid === figure.mcid)) {
+ failed.set(index, "the page's content does not carry its MCID");
+ continue;
+ }
+
+ const place = placement(pdf, body, treeRoot, slots, figure.after);
+ const parent = body(place.parent);
+ const joined = parent ? withKid(pdf, parent, place, nextNum) : null;
+ if (!joined) {
+ failed.set(index, "its parent element cannot be read");
+ continue;
+ }
+ const num = nextNum++;
+ bodies.set(place.parent, joined);
+ const alt =
+ figure.alt === null ? "" : ` /Alt ${encodeTextString(figure.alt)}`;
+ bodies.set(
+ num,
+ `<< /Type /StructElem /S /Figure /P ${ref(pdf, place.parent)} ` +
+ `/Pg ${ref(pdf, pageNum)} /K ${figure.mcid}${alt} >>`,
+ );
+ while (slots.length < figure.mcid) slots.push("null");
+ slots[figure.mcid] = `${num} 0 R`;
+ }
+ return failed;
+}
+
+/**
+ * Beside the element owning MCID `after`; else before the element owning the
+ * page's first tagged content; else last in the document's top element, for a
+ * page with no tagged content.
+ */
+function placement(
+ pdf: RawPdf,
+ body: (num: number) => string | null,
+ treeRoot: number,
+ slots: readonly string[],
+ after: number | null,
+): Placement {
+ const beside = (owner: number | null, before: boolean): Placement | null => {
+ const parent = owner === null ? null : pdf.dictRef(body(owner) ?? "", "P");
+ return parent === null ? null : { parent, sibling: owner, before };
+ };
+ const anchor = after === null ? null : referencedObject(slots[after] ?? "");
+ const first = slots
+ .map((slot) => referencedObject(slot))
+ .find((num) => num !== null);
+ const found = beside(anchor, false) ?? beside(first ?? null, true);
+ if (found) return found;
+ const top = elementKids(pdf, body(treeRoot) ?? "");
+ const only = top?.length === 1 ? referencedObject(top[0]) : null;
+ return { parent: only ?? treeRoot, sibling: null, before: false };
+}
+
+/** The parent's body with `num` among its /K as `place` puts it; at the end when the sibling is not there. */
+function withKid(
+ pdf: RawPdf,
+ parent: string,
+ place: Placement,
+ num: number,
+): string | null {
+ const kids = elementKids(pdf, parent);
+ if (!kids) return null;
+ const at = kids.findIndex((kid) => referencedObject(kid) === place.sibling);
+ kids.splice(insertionIndex(kids.length, at, place.before), 0, `${num} 0 R`);
+ return setDictEntry(parent, "K", `[${kids.join(" ")}]`);
+}
+
+function insertionIndex(count: number, at: number, before: boolean): number {
+ if (at < 0) return count;
+ return before ? at : at + 1;
+}
+
+function ref(pdf: RawPdf, num: number): string {
+ return `${num} ${pdf.generationOf(num)} R`;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts
index 4d70dd6736..c0439c37bb 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts
@@ -11,6 +11,9 @@ import {
appendRevision,
plainObject,
} from "@editor/tools/pdfTextEditor/pdfdoc/revision";
+import { ParentTreeWriter } from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";
+import { addFigures } from "@editor/tools/pdfTextEditor/pdfdoc/passes/addFigures";
+import { markDecorative } from "@editor/tools/pdfTextEditor/pdfdoc/passes/markDecorative";
import { encodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString";
/** A change to the structure element that owns marked content `mcid` on a page. */
@@ -19,6 +22,13 @@ export interface StructureEdit {
mcid: number;
/** The new /Alt; null removes it. */
alt: string | null;
+ /** Turn the element's content into an artifact and drop the element, its /Alt with it. */
+ decorative: boolean;
+ /**
+ * Set when no element owns the content yet: add a Figure for it, after the
+ * element owning MCID `after` on the page (see NewFigure).
+ */
+ newFigure?: { after: number | null };
}
export interface StructureEditFailure {
@@ -65,12 +75,19 @@ export async function applyStructureEdits(
const bodies = new Map<number, string>();
const failures: StructureEditFailure[] = [];
+ const decorative = new Map<number, StructureEdit[]>();
+ const figures = edits.filter((edit) => edit.newFigure);
for (const edit of edits) {
+ if (edit.newFigure) continue;
const owner = elementFor(pdf, treeRoot, edit);
if (typeof owner === "string") {
failures.push({ edit, reason: owner });
continue;
}
+ if (edit.decorative) {
+ decorative.set(owner, [...(decorative.get(owner) ?? []), edit]);
+ continue;
+ }
const body = bodies.get(owner) ?? pdf.objectBody(owner)!;
const updated =
edit.alt === null
@@ -85,12 +102,39 @@ export async function applyStructureEdits(
}
bodies.set(owner, updated);
}
- if (failures.length > 0) throw new StructureEditError(failures);
- const out = appendRevision(
+ const parentTree = new ParentTreeWriter(pdf, treeRoot);
+ // Before the decorative marks, so a figure placed beside an element they
+ // drop keeps its place among the kids that remain.
+ const unplaced = await addFigures(
pdf,
- [...bodies].map(([num, body]) => ({ num, body: plainObject(body) })),
+ treeRoot,
+ figures.map((edit) => ({ ...edit, after: edit.newFigure!.after })),
+ bodies,
+ parentTree,
);
+ for (const [index, reason] of unplaced) {
+ failures.push({ edit: figures[index], reason });
+ }
+ const { streams, failed } = await markDecorative(
+ pdf,
+ new Set(decorative.keys()),
+ bodies,
+ parentTree,
+ );
+ for (const [num, reason] of failed) {
+ for (const edit of decorative.get(num)!) failures.push({ edit, reason });
+ }
+ if (failures.length > 0) throw new StructureEditError(failures);
+
+ // Before `bodies` is read: it may merge an inline tree into one of them.
+ const parentTreeObjects = parentTree.objects(bodies);
+ if (!parentTreeObjects) throw fail("the ParentTree cannot be rewritten");
+ const out = appendRevision(pdf, [
+ ...[...bodies].map(([num, body]) => ({ num, body: plainObject(body) })),
+ ...streams,
+ ...parentTreeObjects,
+ ]);
if (!out)
throw fail("the file's cross-reference structure cannot be extended");
return out;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/markDecorative.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/markDecorative.ts
new file mode 100644
index 0000000000..c9c0779647
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/markDecorative.ts
@@ -0,0 +1,128 @@
+/**
+ * Turn whole structure elements into artifacts (ISO 32000-1 14.8.2.2): each
+ * marked-content sequence an element owns is retagged `/Artifact BMC` and the
+ * element leaves the tree. Only the sequences' opening operators change, so
+ * nothing the page paints does.
+ */
+import {
+ ParentTreeWriter,
+ contentStreamObject,
+ ownsOnlyMarkedContent,
+ pageSites,
+ streamsUsedByMoreThanOnePage,
+ type McidSite,
+} from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";
+import {
+ arrayItems,
+ referencedObject,
+ setDictEntry,
+ type RawPdf,
+} from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import type { RevisionObject } from "@editor/tools/pdfTextEditor/pdfdoc/revision";
+
+const ARTIFACT = "/Artifact BMC";
+
+export interface DecorativeWrites {
+ /** Rewritten content streams. */
+ streams: RevisionObject[];
+ /** Why an element could not be turned into an artifact, by object number. */
+ failed: Map<number, string>;
+}
+
+/**
+ * Plan turning `elements` (object numbers) into artifacts. Element and parent
+ * bodies are read from and written to `bodies`, and ParentTree slots to
+ * `parentTree`, so the caller can combine them with its other edits. Nothing
+ * is written for a document with any failure: the caller must discard it all.
+ */
+export async function markDecorative(
+ pdf: RawPdf,
+ elements: ReadonlySet<number>,
+ bodies: Map<number, string>,
+ parentTree: ParentTreeWriter,
+): Promise<DecorativeWrites> {
+ const failed = new Map<number, string>();
+ if (elements.size === 0) return { streams: [], failed };
+ const body = (num: number) => bodies.get(num) ?? pdf.objectBody(num);
+ for (const num of elements) {
+ const own = body(num);
+ if (!own || !ownsOnlyMarkedContent(pdf, own)) {
+ failed.set(num, "its content is not all marked content on its pages");
+ }
+ }
+
+ const shared = streamsUsedByMoreThanOnePage(pdf);
+ const streams: Promise<RevisionObject>[] = [];
+ for (const pageNum of pdf.pageNumbers()) {
+ const slots = parentTree.slots(pageNum);
+ if (!slots) continue;
+ const owners = new Map<number, number>();
+ slots.forEach((slot, mcid) => {
+ const num = referencedObject(slot);
+ if (num !== null && elements.has(num)) owners.set(mcid, num);
+ });
+ if (owners.size === 0) continue;
+
+ const read = await pageSites(pdf, pageNum);
+ if (!read || read.refs.some((ref) => shared.has(ref))) {
+ const reason = read
+ ? "its page draws content another page also draws"
+ : "its page's content cannot be read";
+ for (const num of owners.values()) failed.set(num, reason);
+ continue;
+ }
+
+ // Content an element owned but the page no longer draws needs only its
+ // slot emptied.
+ const retag = read.sites.filter((site) => owners.has(site.mcid));
+ read.texts.forEach((text, stream) => {
+ const here = retag.filter((site) => site.stream === stream);
+ if (here.length > 0) {
+ streams.push(retaggedStream(read.refs[stream], text, here));
+ }
+ });
+ for (const mcid of owners.keys()) slots[mcid] = "null";
+ }
+
+ for (const num of elements) {
+ const parentNum = pdf.dictRef(body(num) ?? "", "P");
+ const parent = parentNum === null ? null : body(parentNum);
+ const detached = parent ? withoutKid(pdf, parent, num) : null;
+ if (parentNum !== null && detached) bodies.set(parentNum, detached);
+ }
+
+ return { streams: await Promise.all(streams), failed };
+}
+
+/** Stream object `num` holding `text` with each site's opening operator retagged as an artifact. */
+function retaggedStream(
+ num: number,
+ text: string,
+ sites: readonly McidSite[],
+): Promise<RevisionObject> {
+ let out = text;
+ for (const site of [...sites].sort(
+ (a, b) => b.operator.start - a.operator.start,
+ )) {
+ out =
+ out.slice(0, site.operator.start) +
+ ARTIFACT +
+ out.slice(site.operator.end);
+ }
+ return contentStreamObject(num, out);
+}
+
+/** The parent's body without `num` among its /K, or null when it is not there. */
+function withoutKid(pdf: RawPdf, parent: string, num: number): string | null {
+ const span = pdf.valueSpan(parent, "K");
+ if (!span) return null;
+ if (!span.text.startsWith("[")) {
+ return referencedObject(span.text) === num
+ ? setDictEntry(parent, "K", "[]")
+ : null;
+ }
+ const kids = arrayItems(span.text);
+ if (!kids?.some((kid) => referencedObject(kid.text) === num)) return null;
+ const kept = kids.filter((kid) => referencedObject(kid.text) !== num);
+ return setDictEntry(parent, "K", `[${kept.map((k) => k.text).join(" ")}]`);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/repairStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/repairStructure.ts
index b039592343..a0928e5bb4 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/repairStructure.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/repairStructure.ts
@@ -2,45 +2,26 @@
* Repair the structure tree after PDFium regenerates a tagged page.
*/
import {
- deflate,
- fromLatin1,
- toLatin1,
-} from "@editor/tools/pdfTextEditor/pdfdoc/bytes";
-import {
- parseOps,
- tokenize,
-} from "@editor/tools/pdfTextEditor/pdfdoc/contentOps";
+ ParentTreeWriter,
+ contentStreamObject,
+ elementKids,
+ pageSites,
+ streamsUsedByMoreThanOnePage,
+ type McidSite,
+} from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";
import {
RawPdf,
- arrayItems,
referencedObject,
setDictEntry,
- spliceValue,
- type NumberTreeEntry,
- type ValueSpan,
} from "@editor/tools/pdfTextEditor/pdfdoc/raw";
import {
appendRevision,
plainObject,
- streamObject,
type RevisionObject,
} from "@editor/tools/pdfTextEditor/pdfdoc/revision";
const REF = /^(\d+)\s+\d+\s+R$/;
-interface McidSite {
- stream: number;
- mcid: number;
- /** Where the MCID's number is in the stream's text; null when a named property list holds it. */
- number: { start: number; end: number } | null;
-}
-
-interface PageSites {
- refs: number[];
- texts: string[];
- sites: McidSite[];
-}
-
/** Changes to one element's /K for one page. */
interface KidChanges {
pageNum: number;
@@ -51,9 +32,6 @@ interface KidChanges {
interface PageRepair {
streams: Map<number, string>;
- /** Where the page's ParentTree array lives, and its replacement. */
- parentEntry: NumberTreeEntry;
- parentArray: string;
elements: Map<number, KidChanges>;
}
@@ -76,7 +54,7 @@ export async function repairStructure(
const sharedStreams = streamsUsedByMoreThanOnePage(pdf);
const objects: RevisionObject[] = [];
const elementBodies = new Map<number, string>();
- const nodeSplices = new Map<number, { span: ValueSpan; text: string }[]>();
+ const parentTree = new ParentTreeWriter(pdf, treeRoot);
for (const pageIndex of new Set(opts.pages)) {
const pageNum = pdf.pageNumberAt(pageIndex);
@@ -86,7 +64,7 @@ export async function repairStructure(
before && beforeNum !== null ? await pageSites(before, beforeNum) : null;
const repair = await planPage(
pdf,
- treeRoot,
+ parentTree,
pageNum,
sharedStreams,
new Set(beforeSites?.sites.map((s) => s.mcid)),
@@ -94,27 +72,7 @@ export async function repairStructure(
if (!repair) continue;
for (const [num, text] of repair.streams) {
- const raw = fromLatin1(text);
- const packed = await deflate(raw);
- objects.push({
- num,
- body: packed
- ? streamObject("<< /Filter /FlateDecode >>", packed)
- : streamObject("<< >>", raw),
- });
- }
-
- const entry = repair.parentEntry;
- const arrayRef = entry.span.text.match(REF);
- if (arrayRef) {
- objects.push({
- num: parseInt(arrayRef[1], 10),
- body: plainObject(repair.parentArray),
- });
- } else {
- const splices = nodeSplices.get(entry.objNum) ?? [];
- splices.push({ span: entry.span, text: repair.parentArray });
- nodeSplices.set(entry.objNum, splices);
+ objects.push(await contentStreamObject(num, text));
}
for (const [num, changes] of repair.elements) {
@@ -124,14 +82,9 @@ export async function repairStructure(
}
}
- for (const [num, splices] of nodeSplices) {
- // Spans index the original body, so splice back to front.
- let body = pdf.objectBody(num)!;
- for (const s of splices.sort((a, b) => b.span.start - a.span.start)) {
- body = spliceValue(body, s.span, s.text);
- }
- objects.push({ num, body: plainObject(body) });
- }
+ const parentTreeObjects = parentTree.objects(elementBodies);
+ if (!parentTreeObjects) return null;
+ objects.push(...parentTreeObjects);
for (const [num, body] of elementBodies) {
objects.push({ num, body: plainObject(body) });
}
@@ -140,25 +93,21 @@ export async function repairStructure(
return appendRevision(pdf, objects);
}
+/** Plan the page's repair, writing its ParentTree slots to `parentTree`. */
async function planPage(
pdf: RawPdf,
- treeRoot: number,
+ parentTree: ParentTreeWriter,
pageNum: number,
sharedStreams: Set<number>,
mcidsBefore: ReadonlySet<number>,
): Promise<PageRepair | null> {
- const page = pdf.objectBody(pageNum);
- const key = page ? pdf.dictInt(page, "StructParents") : null;
- if (!page || key === null) return null;
+ const slots = parentTree.slots(pageNum);
+ if (!slots) return null;
const read = await pageSites(pdf, pageNum);
// Renumbering a stream another page also draws would corrupt that page.
if (!read || read.refs.some((r) => sharedStreams.has(r))) return null;
const { refs, texts, sites } = read;
- const tree = pdf.parentTreeArray(treeRoot, key);
- if (!tree?.items) return null;
- const entry = tree.entry;
- const slots = tree.items.map((item) => item.text);
const owner = (mcid: number): number | null =>
referencedObject(slots[mcid] ?? "");
@@ -219,85 +168,7 @@ async function planPage(
streams.set(refs[stream], out);
});
- return {
- streams,
- parentEntry: entry,
- parentArray: `[${slots.join(" ")}]`,
- elements,
- };
-}
-
-/** The page's content streams and every MCID they carry, or null when a stream cannot be read. */
-async function pageSites(
- pdf: RawPdf,
- pageNum: number,
-): Promise<PageSites | null> {
- const page = pdf.objectBody(pageNum);
- const refs = page ? pdf.contentRefs(page) : [];
- if (refs.length === 0) return null;
- const texts: string[] = [];
- for (const ref of refs) {
- const data = await pdf.streamData(ref);
- if (!data) return null;
- texts.push(toLatin1(data));
- }
- const resources = pdf.pageInherited(pageNum, "Resources");
- const properties = resources ? pdf.resolve(resources, "Properties") : null;
- const namedMcid = (name: string): number | null => {
- const list = properties ? pdf.resolve(properties, name) : null;
- return list ? pdf.dictInt(list, "MCID") : null;
- };
- return {
- refs,
- texts,
- sites: texts.flatMap((text, stream) => mcidSites(text, stream, namedMcid)),
- };
-}
-
-/**
- * Every `BDC` carrying an MCID, in content order: inline (`/P <</MCID 0>> BDC`)
- * or through a named property list (`/P /MC0 BDC`), which PDFium keeps in that
- * form when it regenerates a page.
- */
-function mcidSites(
- text: string,
- stream: number,
- namedMcid: (name: string) => number | null,
-): McidSite[] {
- const sites: McidSite[] = [];
- for (const op of parseOps(text)) {
- if (op.op !== "BDC") continue;
- const properties = op.operands[1];
- if (properties?.startsWith("/")) {
- const mcid = namedMcid(properties.slice(1));
- if (mcid !== null) sites.push({ stream, mcid, number: null });
- continue;
- }
- const tokens = tokenize(text.slice(op.start, op.end));
- let depth = 0;
- for (let i = 0; i < tokens.length; i++) {
- const t = tokens[i].text;
- if (t === "<<") depth += 1;
- else if (t === ">>") depth -= 1;
- else if (
- depth === 1 &&
- t === "/MCID" &&
- /^\d+$/.test(tokens[i + 1]?.text ?? "")
- ) {
- const number = tokens[i + 1];
- sites.push({
- stream,
- mcid: parseInt(number.text, 10),
- number: {
- start: op.start + number.start,
- end: op.start + number.end,
- },
- });
- break;
- }
- }
- }
- return sites;
+ return { streams, elements };
}
/**
@@ -309,12 +180,7 @@ function rewriteKids(
body: string,
changes: KidChanges,
): string | null {
- const span = pdf.valueSpan(body, "K");
- const kids = !span
- ? []
- : span.text.startsWith("[")
- ? (arrayItems(span.text)?.map((k) => k.text) ?? null)
- : [span.text];
+ const kids = elementKids(pdf, body);
if (!kids) return null;
const elementPage = pdf.dictRef(body, "Pg");
@@ -353,16 +219,3 @@ function rewriteKids(
}
return setDictEntry(body, "K", `[${out.join(" ")}]`);
}
-
-function streamsUsedByMoreThanOnePage(pdf: RawPdf): Set<number> {
- const seen = new Set<number>();
- const shared = new Set<number>();
- for (const pageNum of pdf.pageNumbers()) {
- const body = pdf.objectBody(pageNum);
- for (const ref of body ? new Set(pdf.contentRefs(body)) : []) {
- if (seen.has(ref)) shared.add(ref);
- seen.add(ref);
- }
- }
- return shared;
-}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts
index 8e6e155d5b..4f5c6ea8f5 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/raw.ts
@@ -766,11 +766,12 @@ function findEntry(body: string, key: string): Entry | null {
}
if (ch === "/" && depth === 1) {
const nameEnd = scanNameEnd(body, i + 1);
- if (body.slice(i + 1, nameEnd) === key) {
- const start = skipWhitespace(body, nameEnd);
- return { keyStart: i, start, end: scanValueEnd(body, start) };
- }
- i = nameEnd;
+ const start = skipWhitespace(body, nameEnd);
+ const end = scanValueEnd(body, start);
+ if (body.slice(i + 1, nameEnd) === key)
+ return { keyStart: i, start, end };
+ // Past the value too: in `/S /P /P 9 0 R` the value /P is not the key.
+ i = end;
continue;
}
i += 1;
@@ -812,6 +813,9 @@ function skipLiteralString(text: string, at: number): number {
return i;
}
+/** Sticky, so a value is matched where it starts without copying the rest of the body. */
+const REF_AT = /\d+\s+\d+\s+R\b/y;
+
/** End index of one complete object starting at `at`. */
function scanValueEnd(text: string, at: number): number {
let i = at;
@@ -860,7 +864,8 @@ function scanValueEnd(text: string, at: number): number {
}
// Bare token(s). An indirect reference is three tokens, so consume them
// together or `/Length 12 0 R` reads back as the integer 12.
- const refMatch = /^\d+\s+\d+\s+R\b/.exec(text.slice(i));
+ REF_AT.lastIndex = i;
+ const refMatch = REF_AT.exec(text);
if (refMatch) return i + refMatch[0].length;
if (text[i] === "/") return scanNameEnd(text, i + 1);
while (
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
index 67a33f1206..e62b9d70c0 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
@@ -1,4 +1,5 @@
import type { StructureElement } from "@editor/tools/pdfTextEditor/model/PageStructure";
+import { ownsOnlyMarkedContent } from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";
import {
RawPdf,
referencedObject,
@@ -7,17 +8,24 @@ import { decodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString"
type ElementInfo = Omit<StructureElement, "mcids">;
+/** One page's elements as its ParentTree array gives them. */
+export interface FilePageStructure {
+ elements: StructureElement[];
+ /** The array's length; null when the page names an entry that cannot be read. */
+ slotCount: number | null;
+}
+
/**
- * Every page's structure elements, keyed by page index, each listing only the
- * MCIDs the page's ParentTree slots give it: the lookup the save addresses
- * edits by. PDFium lists an element's MCIDs from every page with no page
- * attached, so an element spanning a page break would claim another element's
- * MCID there. Null when the file is untagged, cannot be parsed, or is
- * encrypted, whose strings would read as ciphertext.
+ * Every page with /StructParents, keyed by page index, its elements each
+ * listing only the MCIDs the page's ParentTree slots give it: the lookup the
+ * save addresses edits by. PDFium lists an element's MCIDs from every page
+ * with no page attached, so an element spanning a page break would claim
+ * another element's MCID there. Null when the file is untagged, cannot be
+ * parsed, or is encrypted, whose strings would read as ciphertext.
*/
export async function readFileStructure(
bytes: Uint8Array,
-): Promise<Map<number, StructureElement[]> | null> {
+): Promise<Map<number, FilePageStructure> | null> {
const pdf = await RawPdf.parse(bytes);
if (!pdf || pdf.encrypted) return null;
const catalog = pdf.objectBody(pdf.rootNum);
@@ -32,13 +40,16 @@ export async function readFileStructure(
return infos.get(num)!;
};
- const byPage = new Map<number, StructureElement[]>();
+ const byPage = new Map<number, FilePageStructure>();
pdf.pageNumbers().forEach((pageNum, pageIndex) => {
const page = pdf.objectBody(pageNum);
const key = page ? pdf.dictInt(page, "StructParents") : null;
- const items =
- key === null ? null : pdf.parentTreeArray(treeRoot, key)?.items;
- if (!items) return;
+ if (key === null) return;
+ const items = pdf.parentTreeArray(treeRoot, key)?.items;
+ if (!items) {
+ byPage.set(pageIndex, { elements: [], slotCount: null });
+ return;
+ }
const owned = new Map<number, StructureElement>();
items.forEach((item, mcid) => {
const num = referencedObject(item.text);
@@ -48,7 +59,10 @@ export async function readFileStructure(
element.mcids.push(mcid);
owned.set(num, element);
});
- byPage.set(pageIndex, [...owned.values()]);
+ byPage.set(pageIndex, {
+ elements: [...owned.values()],
+ slotCount: items.length,
+ });
});
return byPage;
}
@@ -69,6 +83,7 @@ function readElement(
type: applyRoleMap(pdf, roleMap, type),
alt: text("Alt"),
actualText: text("ActualText"),
+ onlyMarkedContent: ownsOnlyMarkedContent(pdf, body),
};
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/textString.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/textString.ts
index 8285e0e8ca..d3ee228546 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/textString.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/textString.ts
@@ -23,11 +23,7 @@ export function encodeTextString(text: string): string {
* PDFDocEncoding. Null when the token is not a string.
*/
export function decodeTextString(token: string): string | null {
- const bytes = token.startsWith("(")
- ? literalBytes(token)
- : token.startsWith("<") && !token.startsWith("<<")
- ? hexBytes(token)
- : null;
+ const bytes = stringBytes(token);
if (!bytes) return null;
if (bytes[0] === 0xfe && bytes[1] === 0xff) {
let text = "";
@@ -42,6 +38,12 @@ export function decodeTextString(token: string): string | null {
return String.fromCharCode(...bytes.map(fromPdfDocEncoding));
}
+function stringBytes(token: string): number[] | null {
+ if (token.startsWith("(")) return literalBytes(token);
+ if (token.startsWith("<") && !token.startsWith("<<")) return hexBytes(token);
+ return null;
+}
+
const LITERAL_ESCAPES: Record<string, number> = {
n: 0x0a,
r: 0x0d,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumStructureReader.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumStructureReader.ts
index d0cb93d330..e0949d66cc 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumStructureReader.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumStructureReader.ts
@@ -34,6 +34,8 @@ export function readPageStructure(
alt: readString(m, el, m.FPDF_StructElement_GetAltText),
actualText: readString(m, el, m.FPDF_StructElement_GetActualText),
mcids,
+ // PDFium does not expose the kids' kinds; the fallback is read-only anyway.
+ onlyMarkedContent: false,
});
const kids = m.FPDF_StructElement_CountChildren(el);
for (let i = 0; i < kids; i++) {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts
index 6399187d55..49887cdcc8 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts
@@ -5,6 +5,7 @@ import {
} from "@editor/tools/pdfTextEditor/util/wasmScratch";
const MCID = "MCID";
+const FPDF_PAGEOBJ_FORM = 5;
export const ARTIFACT_TAG = "Artifact";
/**
@@ -43,6 +44,11 @@ export function readTagMarks(
return tags;
}
+/** The MCID of the innermost tag that has one: the content's own. */
+export function innermostMcid(tags: readonly TagMark[]): number | null {
+ return [...tags].reverse().find((t) => t.mcid !== null)?.mcid ?? null;
+}
+
/**
* Give newly created objects the tags of the content they replace. Objects
* that already carry a mark are left alone: PDFium appends a mark on every
@@ -58,13 +64,62 @@ export function applyTagMarks(
if (tags.length === 0) return;
for (const ptr of ptrs) {
if (!ptr || m.FPDFPageObj_CountMarks(ptr) > 0) continue;
- for (const tag of tags) {
- const mark = m.FPDFPageObj_AddMark(ptr, tag.name);
- if (mark && tag.mcid !== null) {
- m.FPDFPageObjMark_SetIntParam(docPtr, ptr, mark, MCID, tag.mcid);
- }
+ for (const tag of tags) addTagMark(m, docPtr, ptr, tag);
+ }
+}
+
+/** Add `tag` to the object, innermost. False when PDFium refuses it. */
+export function addTagMark(
+ m: WrappedPdfiumModule,
+ docPtr: number,
+ objPtr: number,
+ tag: TagMark,
+): boolean {
+ const mark = m.FPDFPageObj_AddMark(objPtr, tag.name);
+ if (!mark) return false;
+ return (
+ tag.mcid === null ||
+ m.FPDFPageObjMark_SetIntParam(docPtr, objPtr, mark, MCID, tag.mcid)
+ );
+}
+
+/** Remove the object's innermost tag named `name`. False when it has none. */
+export function removeTagMark(
+ m: WrappedPdfiumModule,
+ objPtr: number,
+ name: string,
+): boolean {
+ for (let i = m.FPDFPageObj_CountMarks(objPtr) - 1; i >= 0; i--) {
+ const mark = m.FPDFPageObj_GetMark(objPtr, i);
+ if (mark && markName(m, mark) === name) {
+ return m.FPDFPageObj_RemoveMark(objPtr, mark);
+ }
+ }
+ return false;
+}
+
+/**
+ * The highest MCID any object on the page is marked with, form XObject
+ * content included; -1 when none is.
+ */
+export function highestMcid(m: WrappedPdfiumModule, pagePtr: number): number {
+ const count = m.FPDFPage_CountObjects(pagePtr);
+ const objects = Array.from({ length: count }, (_, i) =>
+ m.FPDFPage_GetObject(pagePtr, i),
+ );
+ let highest = -1;
+ while (objects.length > 0) {
+ const objPtr = objects.pop()!;
+ if (!objPtr) continue;
+ for (const tag of readTagMarks(m, objPtr)) {
+ highest = Math.max(highest, tag.mcid ?? -1);
+ }
+ if (m.FPDFPageObj_GetType(objPtr) !== FPDF_PAGEOBJ_FORM) continue;
+ for (let i = 0; i < m.FPDFFormObj_CountObjects(objPtr); i++) {
+ objects.push(m.FPDFFormObj_GetObject(objPtr, i));
}
}
+ return highest;
}
/** Carry `from`'s tags onto its replacement `to`. */
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
index 94d91b3021..ce521cf9a2 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
@@ -23,6 +23,7 @@ import {
} from "@editor/tools/pdfTextEditor/util/wasmScratch";
import {
ARTIFACT_TAG,
+ innermostMcid,
readTagMarks,
} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
@@ -443,7 +444,15 @@ function walkObjects(
}
} else if (type === FPDF_PAGEOBJ_IMAGE) {
const indexId = [...path, i].join("-");
- const img = readImage(m, page, objPtr, indexId, transform, containerPtr);
+ const img = readImage(
+ m,
+ page,
+ objPtr,
+ indexId,
+ transform,
+ containerPtr,
+ path,
+ );
if (img) images.push(img);
} else if (type === FPDF_PAGEOBJ_FORM && depth < MAX_DEPTH) {
let formCount: number;
@@ -535,12 +544,26 @@ function getFormContainer(
pagePtr: number,
path: number[],
): number {
+ return formChain(m, pagePtr, path).at(-1)!;
+}
+
+/** The form objects the index path passes through, outermost first. */
+function formChain(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ path: number[],
+): number[] {
const formModule = m as PdfiumWithForms;
- let current = m.FPDFPage_GetObject(pagePtr, path[0]);
- for (let i = 1; i < path.length; i++) {
- current = formModule.FPDFFormObj_GetObject(current, path[i]);
+ const chain: number[] = [];
+ for (const index of path) {
+ const parent = chain.at(-1);
+ chain.push(
+ parent === undefined
+ ? m.FPDFPage_GetObject(pagePtr, index)
+ : formModule.FPDFFormObj_GetObject(parent, index),
+ );
}
- return current;
+ return chain;
}
// The ruling lines a path object draws.
@@ -1059,13 +1082,13 @@ function readImage(
index: number | string,
transform: Affine,
containerPtr: number,
+ formPath: number[],
): ImageObject | null {
const localBounds = readBounds(m, objPtr);
if (!localBounds) return null;
const localMatrix = readMatrix(m, objPtr);
const ident = isIdentity(transform);
- // A form XObject's MCIDs are not the page's, so only page-level images are tagged.
- const tags = containerPtr === 0 ? readTagMarks(m, objPtr) : [];
+ const tags = imageTags(m, page.pagePtr, formPath, objPtr);
return new ImageObject({
id: `p${page.index}-i${index}`,
pageIndex: page.index,
@@ -1073,7 +1096,30 @@ function readImage(
bounds: ident ? localBounds : transformRect(transform, localBounds),
matrix: ident ? localMatrix : composeAffine(transform, localMatrix),
containerPtr,
- mcid: [...tags].reverse().find((t) => t.mcid !== null)?.mcid ?? undefined,
- artifact: tags.some((t) => t.name === ARTIFACT_TAG) || undefined,
+ mcid: tags.mcid ?? undefined,
+ artifact: tags.artifact || undefined,
});
}
+
+/**
+ * An image's tags as the page's structure tree sees them. PDFium gives an
+ * object in a form XObject only the marks in the form's content, whose MCIDs
+ * resolve against the form's own /StructParents, so the page's MCID is the
+ * one on the outermost form. An /Artifact at any level still makes the image
+ * one (ISO 32000-1 14.8.2.2).
+ */
+function imageTags(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ formPath: number[],
+ objPtr: number,
+): { mcid: number | null; artifact: boolean } {
+ const [onPage, ...inForms] = [...formChain(m, pagePtr, formPath), objPtr].map(
+ (ptr) => readTagMarks(m, ptr),
+ );
+ const formOwnsContent = inForms.flat().some((t) => t.mcid !== null);
+ return {
+ mcid: formOwnsContent ? null : innermostMcid(onPage),
+ artifact: [onPage, ...inForms].flat().some((t) => t.name === ARTIFACT_TAG),
+ };
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/types.ts b/frontend/src/editor/core/tools/pdfTextEditor/types.ts
index 5e17940565..36161febc7 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/types.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/types.ts
@@ -92,10 +92,15 @@ export interface ImageObjectSnapshot {
matrix: Affine;
/** Editor-only: see TextRunSnapshot.locked. */
locked?: boolean;
- /** The marked-content ID that ties the image into the structure tree. */
+ /**
+ * The page's marked-content ID that ties the image into the structure tree:
+ * for an image in a form XObject, the form's.
+ */
mcid?: number;
/** Marked as an artifact: decoration that assistive technology skips. */
artifact?: boolean;
+ /** Drawn by a form XObject, whose marks are not the page's to change. */
+ inForm?: boolean;
}
// One ruling line the page draws, with the ink needed to reproduce it: a table
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts
index 84992fb508..82eb2e825c 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts
@@ -1,5 +1,9 @@
+import i18n from "i18next";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
-import { applyStructureEdits } from "@editor/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits";
+import {
+ StructureEditError,
+ applyStructureEdits,
+} from "@editor/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits";
import { repairStructure } from "@editor/tools/pdfTextEditor/pdfdoc/passes/repairStructure";
import { preserveShadings } from "@editor/tools/pdfTextEditor/pdfdoc/passes/preserveShadings";
import { PdfiumSave } from "@editor/tools/pdfTextEditor/pdfium/PdfiumSave";
@@ -39,7 +43,20 @@ export async function exportToBlob(
// Throws rather than dropping them: a description the user wrote that the
// saved file silently lacks is worse than a save that reports it failed.
- bytes = await applyStructureEdits(bytes, structureEdits);
+ try {
+ bytes = await applyStructureEdits(bytes, structureEdits);
+ } catch (err) {
+ if (!(err instanceof StructureEditError)) throw err;
+ // Its failures name pages and MCIDs: for a bug report, not for the user.
+ console.error(err);
+ throw new Error(
+ i18n.t(
+ "pdfTextEditor.inspector.accessibility.saveFailed",
+ "Your accessibility changes couldn't be saved, so the file wasn't saved. Undo them and try again.",
+ ),
+ { cause: err },
+ );
+ }
// After the edits: when the content an element described was deleted, the
// repair removes the ParentTree slot an edit to that element is addressed by,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/figurePlacement.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/figurePlacement.test.ts
new file mode 100644
index 0000000000..73b9408676
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/figurePlacement.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from "vitest";
+import type { ImageObject } from "@editor/tools/pdfTextEditor/model/ImageObject";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import type { PageRect } from "@editor/tools/pdfTextEditor/types";
+import {
+ imagesInReadingOrder,
+ precedingTaggedMcid,
+} from "@editor/tools/pdfTextEditor/util/figurePlacement";
+
+const UPRIGHT = { apply: (x: number, y: number) => ({ x, y }) };
+
+const box = (x: number, y: number, width = 80, height = 10): PageRect => ({
+ x,
+ y,
+ width,
+ height,
+});
+const run = (mcid: number | null, bounds: PageRect) => ({
+ bounds,
+ tagMarks: mcid === null ? [] : [{ name: "P", mcid }],
+});
+const image = (mcid: number | null, bounds: PageRect) =>
+ ({ bounds, mcid, containerPtr: 0 }) as ImageObject;
+const page = (
+ runs: ReturnType<typeof run>[],
+ images: ImageObject[],
+ display = UPRIGHT,
+) => ({ runs, images, display }) as unknown as Page;
+
+describe("precedingTaggedMcid", () => {
+ it("follows the tagged content closest above the image", () => {
+ const target = image(null, box(10, 60, 20, 20));
+ const p = page([run(0, box(10, 180)), run(1, box(10, 120))], [target]);
+ expect(precedingTaggedMcid(p, target)).toBe(1);
+ });
+
+ it("prefers content in the image's column to closer content beside it", () => {
+ const target = image(null, box(110, 80, 80, 20));
+ const p = page(
+ [run(0, box(0, 100, 90)), run(1, box(110, 150, 90))],
+ [target],
+ );
+ expect(precedingTaggedMcid(p, target)).toBe(1);
+ });
+
+ it("reads content level with the image and to its left first", () => {
+ const target = image(null, box(100, 90, 20, 20));
+ const p = page([run(0, box(0, 100, 50))], [target]);
+ expect(precedingTaggedMcid(p, target)).toBe(0);
+ });
+
+ it("skips untagged content and the image itself", () => {
+ const target = image(4, box(10, 60, 20, 20));
+ const p = page([run(null, box(10, 120))], [target]);
+ expect(precedingTaggedMcid(p, target)).toBeNull();
+ });
+
+ it("reads a page as it is displayed", () => {
+ const target = image(null, box(10, 60, 20, 20));
+ const upsideDown = { apply: (x: number, y: number) => ({ x, y: -y }) };
+ const p = page([run(1, box(10, 120))], [target], upsideDown);
+ expect(precedingTaggedMcid(p, target)).toBeNull();
+ });
+});
+
+describe("imagesInReadingOrder", () => {
+ it("orders the page's images top to bottom, then left to right", () => {
+ const low = image(null, box(10, 20));
+ const right = image(null, box(100, 120));
+ const left = image(null, box(10, 120));
+ expect(imagesInReadingOrder(page([], [low, right, left]))).toEqual([
+ left,
+ right,
+ low,
+ ]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/figurePlacement.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/figurePlacement.ts
new file mode 100644
index 0000000000..81ec8352d8
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/figurePlacement.ts
@@ -0,0 +1,99 @@
+/**
+ * Where a figure added for an untagged image goes in the reading order: after
+ * the tagged content closest before the image as the page displays it, read
+ * top to bottom and then left to right. The content order cannot say this: an
+ * inserted image is drawn last whatever its position on the page.
+ */
+import type { ImageObject } from "@editor/tools/pdfTextEditor/model/ImageObject";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import { innermostMcid } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+import type { PageRect } from "@editor/tools/pdfTextEditor/types";
+
+/** Tops this close (points) read as one line. */
+const SAME_LINE = 2;
+
+interface Box {
+ left: number;
+ right: number;
+ top: number;
+}
+
+interface TaggedContent {
+ mcid: number;
+ box: Box;
+}
+
+/**
+ * The MCID of the tagged content read last before `image`, or null when none
+ * precedes it. Content in the image's column wins over content beside it, so
+ * a figure under a paragraph follows that paragraph and not the one across
+ * the gutter.
+ */
+export function precedingTaggedMcid(
+ page: Page,
+ image: ImageObject,
+): number | null {
+ const target = displayBox(page, image.bounds);
+ const before = taggedContent(page, image).filter((c) =>
+ readsBefore(c.box, target),
+ );
+ const inColumn = before.filter(
+ (c) => c.box.left < target.right && c.box.right > target.left,
+ );
+ const pool = inColumn.length > 0 ? inColumn : before;
+ let last: TaggedContent | null = null;
+ for (const content of pool) {
+ if (!last || readsBefore(last.box, content.box)) last = content;
+ }
+ return last?.mcid ?? null;
+}
+
+export function imagesInReadingOrder(page: Page): ImageObject[] {
+ return page.images
+ .map((image) => ({ image, box: displayBox(page, image.bounds) }))
+ .sort((a, b) => readingOrder(a.box, b.box))
+ .map(({ image }) => image);
+}
+
+function taggedContent(page: Page, except: ImageObject): TaggedContent[] {
+ const content: TaggedContent[] = [];
+ for (const run of page.runs) {
+ const mcid = innermostMcid(run.tagMarks);
+ if (mcid !== null)
+ content.push({ mcid, box: displayBox(page, run.bounds) });
+ }
+ for (const image of page.images) {
+ if (image === except || image.mcid === null || image.containerPtr !== 0) {
+ continue;
+ }
+ content.push({ mcid: image.mcid, box: displayBox(page, image.bounds) });
+ }
+ return content;
+}
+
+function readsBefore(a: Box, b: Box): boolean {
+ if (Math.abs(a.top - b.top) > SAME_LINE) return a.top > b.top;
+ return a.left < b.left;
+}
+
+function readingOrder(a: Box, b: Box): number {
+ if (readsBefore(a, b)) return -1;
+ if (readsBefore(b, a)) return 1;
+ return 0;
+}
+
+/** The rect's bounds as displayed, y-up, so a /Rotate page reads as it is shown. */
+function displayBox(page: Page, rect: PageRect): Box {
+ const corners = [
+ page.display.apply(rect.x, rect.y),
+ page.display.apply(rect.x + rect.width, rect.y),
+ page.display.apply(rect.x, rect.y + rect.height),
+ page.display.apply(rect.x + rect.width, rect.y + rect.height),
+ ];
+ const xs = corners.map((c) => c.x);
+ return {
+ left: Math.min(...xs),
+ right: Math.max(...xs),
+ top: Math.max(...corners.map((c) => c.y)),
+ };
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/imageAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/imageAccessibility.ts
new file mode 100644
index 0000000000..c6994bdd7c
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/imageAccessibility.ts
@@ -0,0 +1,166 @@
+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";
+
+/** What can be said and done about one image's accessibility. */
+export type ImageAccessibility =
+ | { kind: "decorative"; canUndecorate: boolean }
+ | { kind: "blocked"; blocker: DescriptionBlocker; documentTagged: boolean }
+ | {
+ kind: "describable";
+ description: string | null;
+ /** False for an image no element owns yet: describing it adds one. */
+ tagged: boolean;
+ canBeDecorative: boolean;
+ };
+
+export function imageAccessibility(
+ doc: EditorDocument,
+ image: ImageObjectSnapshot,
+): ImageAccessibility {
+ const retaggable = retaggableTag(doc, image) !== null;
+ if (image.artifact) return { kind: "decorative", canUndecorate: retaggable };
+ if (image.mcid === undefined) {
+ if (!retaggable) return blocked(doc, "untagged");
+ return {
+ kind: "describable",
+ description: null,
+ tagged: false,
+ canBeDecorative: true,
+ };
+ }
+ const structure = doc.structure(image.pageIndex);
+ const blocker = structure.cannotDescribe(image.mcid);
+ if (blocker) return blocked(doc, blocker);
+ if (structure.decorative(image.mcid)) {
+ return { kind: "decorative", canUndecorate: true };
+ }
+ return {
+ kind: "describable",
+ description: structure.alt(image.mcid),
+ tagged: true,
+ canBeDecorative:
+ retaggable || structure.cannotMarkDecorative(image.mcid) === null,
+ };
+}
+
+/** How an image is tagged, where TagImageCommand can change it. */
+export type RetaggableTag =
+ | { kind: "untagged" }
+ | { kind: "artifact" }
+ | { kind: "figure"; mcid: number; alt: string | null };
+
+/**
+ * The image's tag when TagImageCommand can change it: an image the page
+ * itself draws in a tagged document, that is untagged, an artifact, or a
+ * figure the session added. Null otherwise, for content the file's elements
+ * own among the rest.
+ */
+export function retaggableTag(
+ doc: EditorDocument,
+ image: ImageObjectSnapshot,
+): RetaggableTag | null {
+ if (!doc.isTagged() || image.inForm) return null;
+ const structure = doc.structure(image.pageIndex);
+ if (structure.cannotAddFigure()) return null;
+ if (image.mcid === undefined) {
+ return image.artifact ? { kind: "artifact" } : { kind: "untagged" };
+ }
+ if (!structure.isAdded(image.mcid)) return null;
+ return {
+ kind: "figure",
+ mcid: image.mcid,
+ alt: structure.alt(image.mcid),
+ };
+}
+
+function blocked(
+ doc: EditorDocument,
+ blocker: DescriptionBlocker,
+): ImageAccessibility {
+ return { kind: "blocked", blocker, documentTagged: doc.isTagged() };
+}
+
+/**
+ * Why an image needs the user's attention: it can take a description and has
+ * none, or it sits untagged in a tagged document, unreachable by a screen
+ * reader. An untagged image is "untaggable" when nothing here can tag it.
+ */
+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";
+ return accessibility.description?.trim() ? null : "needs-description";
+ }
+ if (
+ accessibility.kind === "blocked" &&
+ accessibility.blocker === "untagged" &&
+ accessibility.documentTagged
+ ) {
+ return "untaggable";
+ }
+ return null;
+}
+
+/** Attention the user can resolve here, which Next walks through. */
+export function isActionable(attention: ImageAttention | null): boolean {
+ return attention === "needs-description" || attention === "untagged";
+}
+
+export function imageAttention(
+ doc: EditorDocument,
+ image: ImageObjectSnapshot,
+): 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;
+}
diff --git a/frontend/vite-env.d.ts b/frontend/vite-env.d.ts
index a410ba3bc7..ca71e946df 100644
--- a/frontend/vite-env.d.ts
+++ b/frontend/vite-env.d.ts
@@ -5,6 +5,8 @@ interface ImportMetaEnv {
readonly VITE_API_BASE_URL: string;
/** "true" includes the admin portal's lazy route/chunk in the editor build. */
readonly VITE_INCLUDE_PORTAL: string;
+ /** "true" shows the PDF text editor's accessibility editing. */
+ readonly VITE_ACCESSIBILITY_EDITING: string;
readonly VITE_GOOGLE_DRIVE_CLIENT_ID: string;
readonly VITE_GOOGLE_DRIVE_API_KEY: string;
readonly VITE_GOOGLE_DRIVE_APP_ID: string;