#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Mark the language of a document and of passages in the Text Editor (#8723)
EthanHealy013b4c202890f7
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.tomlindex f1f418f552..3480a7bde5 100644--- a/frontend/public/locales/en-US/translation.toml+++ b/frontend/public/locales/en-US/translation.toml@@ -7507,6 +7507,23 @@ tableHeader = "Table header"tableRow = "Table row"title = "Title"+[pdfTextEditor.inspector.language]+allLanguages = "All languages"+cannotSetDocument = "This document's language can't be changed."+cannotSetText = "This text's language can't be changed."+documentHint = "The language screen readers use unless a part of the text sets its own."+documentLabel = "Language"+documentLocked = "An encrypted document's language can't be changed here."+inDocument = "In this document"+innerLabel = "Tag {{number}} language"+label = "Language"+missing = "No language set. Screen readers will guess, and may read the whole document in the wrong voice."+mixed = "Mixed"+noMatch = "No matching language. Type its code instead, such as mt or en-IE."+placeholder = "Select language"+selectedText = "Selected text language"+textHint = "Screen readers switch voice and pronunciation to this language."+[pdfTextEditor.mobile]actions = "Editor actions"addImage = "Image"diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-language.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-language.spec.tsnew file mode 100644index 0000000000..b8452dd6e2--- /dev/null+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-language.spec.ts@@ -0,0 +1,127 @@+import { test, expect } from "@editor/tests/helpers/stub-test-base";+import type { Page } from "@playwright/test";+import path from "path";++// A screen reader picks its voice by /Lang: the catalog's for the document,+// an element's own for a passage in another language (ISO 32000-1 14.9.2).+// Both are set in the inspector and must survive a save.++const FIXTURE = path.join(+ import.meta.dirname,+ "../test-fixtures/tagged-sample.pdf",+);++interface EditorWindow {+ __editor_store: {+ document: {+ documentLanguage: () => string | null;+ textLanguage: (+ pageIndex: number,+ mcid: number,+ ) => { own: string | null; inherited: string | null } | null;+ };+ state: {+ pages: { runs: { id: string; text: string; mcid?: number }[] }[];+ };+ };+ __prev_document?: unknown;+}++const RUN = (needle: string) =>+ (window as unknown as EditorWindow).__editor_store.state.pages[0].runs.find(+ (r) => r.text.includes(needle),+ ) ?? null;++async function openFixture(page: 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, "product line"), { timeout: 30_000 })+ .not.toBeNull();+}++async function saveAndReopen(page: Page) {+ const downloaded = page.waitForEvent("download", { timeout: 30_000 });+ await page.getByTestId("pdf-editor-download").click();+ const confirm = page.getByTestId("pdf-editor-save-risk-confirm");+ if (await confirm.isVisible().catch(() => false)) await confirm.click();+ const saved = test.info().outputPath("language.pdf");+ await (await downloaded).saveAs(saved);+ await page.evaluate(() => {+ const w = window as unknown as EditorWindow;+ w.__prev_document = w.__editor_store.document;+ });+ await page+ .locator('[data-testid="pdf-editor-file-input"]')+ .setInputFiles(saved);+ await page.waitForFunction(+ () => {+ const w = window as unknown as EditorWindow;+ const s = w.__editor_store;+ if (!s?.document || s.document === w.__prev_document) return false;+ return (s.state.pages[0]?.runs.length ?? 0) > 0;+ },+ undefined,+ { timeout: 30_000 },+ );+}++async function pickLanguage(page: Page, testId: string, tag: string) {+ const input = page.getByTestId(testId).getByRole("textbox");+ await input.click();+ await input.fill(tag);+ await page.getByRole("option", { name: new RegExp(`\\(${tag}\\)$`) }).click();+}++test.describe("PDF text editor - languages", () => {+ test("the document's and a paragraph's language are set and saved", async ({+ page,+ }) => {+ test.setTimeout(120_000);+ await openFixture(page);++ await page.getByTestId("pdf-editor-tab-document").click();+ const documentPicker = page+ .getByTestId("pdf-editor-document-language-picker")+ .getByRole("textbox");+ await expect(documentPicker).toHaveValue(/\(en-US\)$/);+ await pickLanguage(page, "pdf-editor-document-language-picker", "en-IE");+ await expect(documentPicker).toHaveValue(/\(en-IE\)$/);+ await page.screenshot({+ path: test.info().outputPath("document-language.png"),+ });++ const paragraph = (await page.evaluate(RUN, "product line"))!;+ await page.getByTestId(`pdf-editor-run-${paragraph.id}`).click();+ const textPicker = page+ .getByTestId("pdf-editor-text-language-picker")+ .getByRole("textbox");+ await expect(textPicker).toHaveValue(/English \(Ireland\)/);+ await pickLanguage(page, "pdf-editor-text-language-picker", "fr");+ await expect(textPicker).toHaveValue(/\(fr\)$/);+ await page.screenshot({+ path: test.info().outputPath("text-language.png"),+ });++ await saveAndReopen(page);+ const reopened = await page.evaluate((mcid) => {+ const doc = (window as unknown as EditorWindow).__editor_store.document;+ return {+ document: doc.documentLanguage(),+ paragraph: doc.textLanguage(0, mcid),+ };+ }, paragraph.mcid!);+ expect(reopened).toEqual({+ document: "en-IE",+ paragraph: { own: "fr", inherited: "en-IE" },+ });+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/editorDirtyState.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/editorDirtyState.test.tsindex 6f1d9abce4..4d431dd08e 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/editorDirtyState.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/editorDirtyState.test.ts@@ -20,6 +20,8 @@ function makeDoc(): EditorDocument {return {pageCount: 0,loadedPages: () => [],+ documentLanguage: () => null,+ languagesInUse: () => [],dispose: () => {},} as unknown as EditorDocument;}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/languageTagging.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/languageTagging.test.tsnew file mode 100644index 0000000000..4136fb9db8--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/languageTagging.test.ts@@ -0,0 +1,503 @@+// @vitest-environment node+// jsdom's Blob cannot stream, so the fixture's object stream would not inflate.+import { readFile } from "node:fs/promises";+import { createRequire } from "node:module";+import path from "node:path";+import {+ afterAll,+ afterEach,+ beforeAll,+ describe,+ expect,+ test,+ vi,+} from "vitest";+import { SetDocumentLanguageCommand } from "@editor/tools/pdfTextEditor/commands/SetDocumentLanguageCommand";+import { SetInnerLanguageCommand } from "@editor/tools/pdfTextEditor/commands/SetInnerLanguageCommand";+import { SetTextLanguageCommand } from "@editor/tools/pdfTextEditor/commands/SetTextLanguageCommand";+import { TagTextRangeCommand } from "@editor/tools/pdfTextEditor/commands/TagTextRangeCommand";+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import { canonicalLanguageTag } from "@editor/tools/pdfTextEditor/model/languageTag";+import { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";+import { readFileStructure } from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";+import { decodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString";+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";+import { innerTags } from "@editor/tools/pdfTextEditor/util/textAccessibility";+import {+ buildClassicPdf,+ streamBody,+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";++const TAGGED_SAMPLE = path.join(+ import.meta.dirname,+ "../../../tests/test-fixtures/tagged-sample.pdf",+);+/** The sample's second page: paragraphs, and a German Span inside one. */+const PAGE = 1;++// A French test set in English: the question (MCID 0) and the letter it asks+// about, two paragraphs (MCIDs 1 and 2), the second already marked French.+const CONTENT =+ "/P <</MCID 0>> BDC BT /F1 12 Tf 72 700 Td (Describe the letter below.) Tj ET EMC\n" ++ "/P <</MCID 1>> BDC BT /F1 12 Tf 72 670 Td (Chere Marie, merci pour ta lettre.) Tj ET EMC\n" ++ "/P <</MCID 2>> BDC BT /F1 16 Tf 72 630 Td (Mes vacances) Tj ET " ++ "BT /F1 12 Tf 72 612 Td (Nous sommes alles a la plage.) Tj ET EMC\n";++/** Document 7 holds paragraphs 8, 9 and 10; the catalog sets `catalogLang`. */+function letterPdf(catalogLang = ""): Uint8Array {+ return buildClassicPdf(+ [+ {+ num: 1,+ body: `<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 6 0 R /MarkInfo << /Marked true >>${catalogLang} >>`,+ },+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },+ {+ num: 3,+ body:+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /StructParents 0 " ++ "/Resources << /Font << /F1 5 0 R >> >> >>",+ },+ { num: 4, body: streamBody("", CONTENT) },+ {+ num: 5,+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ },+ {+ num: 6,+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 11 0 R /ParentTreeNextKey 1 >>",+ },+ {+ num: 7,+ body: "<< /Type /StructElem /S /Document /P 6 0 R /K [8 0 R 9 0 R 10 0 R] >>",+ },+ { num: 8, body: "<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K 0 >>" },+ { num: 9, body: "<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K 1 >>" },+ {+ num: 10,+ body: "<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K 2 /Lang (fr) >>",+ },+ { num: 11, body: "<< /Nums [0 [8 0 R 9 0 R 10 0 R]] >>" },+ ],+ 1,+ );+}++function untaggedPdf(): Uint8Array {+ return buildClassicPdf(+ [+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },+ {+ num: 3,+ body:+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R " ++ "/Resources << /Font << /F1 5 0 R >> >> >>",+ },+ {+ num: 4,+ body: streamBody("", "BT /F1 12 Tf 72 700 Td (Untagged) Tj ET"),+ },+ {+ num: 5,+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ },+ ],+ 1,+ );+}++function nestedLanguagePdf(): Uint8Array {+ return buildClassicPdf(+ [+ {+ num: 1,+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 6 0 R /MarkInfo << /Marked true >> /Lang (en) >>",+ },+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },+ {+ num: 3,+ body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /StructParents 0 /Resources << /Font << /F1 5 0 R >> >> >>",+ },+ {+ num: 4,+ body: streamBody(+ "",+ "/Span <</MCID 0>> BDC BT /F1 12 Tf 72 700 Td (Inner text) Tj ET EMC\n/Span <</MCID 1>> BDC BT /F1 12 Tf 72 680 Td (Parent text) Tj ET EMC\n/P <</MCID 2>> BDC BT /F1 12 Tf 72 660 Td (Block text) Tj ET EMC",+ ),+ },+ {+ num: 5,+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ },+ {+ num: 6,+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 11 0 R /ParentTreeNextKey 1 >>",+ },+ {+ num: 7,+ body: "<< /Type /StructElem /S /Document /P 6 0 R /K 8 0 R >>",+ },+ {+ num: 8,+ body: "<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K [2 9 0 R] >>",+ },+ {+ num: 9,+ body: "<< /Type /StructElem /S /Span /P 8 0 R /Pg 3 0 R /K [1 10 0 R] /Lang (fr) >>",+ },+ {+ num: 10,+ body: "<< /Type /StructElem /S /Span /P 9 0 R /Pg 3 0 R /K 0 /Lang (de) >>",+ },+ { num: 11, body: "<< /Nums [0 [10 0 R 9 0 R 8 0 R]] >>" },+ ],+ 1,+ );+}++const opened: EditorDocument[] = [];++async function open(bytes: Uint8Array, page = 0): Promise<EditorDocument> {+ const doc = await EditorDocument.open(bytes);+ opened.push(doc);+ PdfiumTextReader.populate(doc, doc.page(page));+ return doc;+}++async function openSample(): Promise<EditorDocument> {+ return open(new Uint8Array(await readFile(TAGGED_SAMPLE)), PAGE);+}++function runWith(doc: EditorDocument, page: number, fragment: string) {+ const run = doc.page(page).runs.find((r) => r.text.includes(fragment));+ if (!run) throw new Error(`no run contains "${fragment}"`);+ return run;+}++function mcidOf(doc: EditorDocument, page: number, fragment: string): number {+ return runWith(doc, page, fragment).snapshot().mcid!;+}++async function savedBytes(doc: EditorDocument): Promise<Uint8Array> {+ const { blob } = await exportToBlob(doc, "letter.pdf");+ return new Uint8Array(await blob.arrayBuffer());+}++async function catalogLang(bytes: Uint8Array): Promise<string | null> {+ const pdf = (await RawPdf.parse(bytes))!;+ const value = pdf.resolve(pdf.objectBody(pdf.rootNum)!, "Lang");+ return value === null ? null : decodeTextString(value.trim());+}++async function savedLangs(doc: EditorDocument) {+ return (await readFileStructure(await savedBytes(doc)))!.languages;+}++beforeAll(async () => {+ const wasmPath = createRequire(import.meta.url).resolve(+ "@embedpdf/pdfium/pdfium.wasm",+ );+ const wasmBytes = await readFile(wasmPath);+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ Promise.resolve(+ new Response(wasmBytes, {+ headers: { "Content-Type": "application/wasm" },+ }),+ ),+ ),+ );+});++afterEach(() => {+ while (opened.length) opened.pop()!.dispose();+});++afterAll(() => {+ vi.unstubAllGlobals();+});++describe("language tags", () => {+ test.each([+ ["en-ie", "en-IE"],+ ["FR", "fr"],+ [" ga ", "ga"],+ ["zh-hant", "zh-Hant"],+ ])("canonicalises %j as %j", (tag, canonical) => {+ expect(canonicalLanguageTag(tag)).toBe(canonical);+ });++ test.each(["", "en_IE", "english please", "-fr", "toolongtag"])(+ "refuses %j",+ (tag) => {+ expect(canonicalLanguageTag(tag)).toBeNull();+ },+ );+});++describe("document language", () => {+ test("reads the catalog's /Lang", async () => {+ const doc = await openSample();+ expect(doc.documentLanguage()).toBe("en-US");+ });++ test("saves a new language as the catalog's /Lang, and undoes", async () => {+ const doc = await open(letterPdf());+ expect(doc.documentLanguage()).toBeNull();+ const history = new HistoryStack();+ history.execute(new SetDocumentLanguageCommand({ lang: "en-IE" }), doc);++ expect(doc.documentLanguage()).toBe("en-IE");+ expect(await catalogLang(await savedBytes(doc))).toBe("en-IE");++ history.undo(doc);+ expect(doc.documentLanguageEdit()).toBeUndefined();+ });++ test("removes the catalog's /Lang", async () => {+ const doc = await open(letterPdf(" /Lang (en)"));+ new HistoryStack().execute(+ new SetDocumentLanguageCommand({ lang: null }),+ doc,+ );+ expect(await catalogLang(await savedBytes(doc))).toBeNull();+ });++ test("sets an untagged document's language", async () => {+ const doc = await open(untaggedPdf());+ const mcid = runWith(doc, 0, "Untagged").snapshot().mcid;+ expect(mcid).toBeUndefined();+ new HistoryStack().execute(+ new SetDocumentLanguageCommand({ lang: "ga" }),+ doc,+ );+ expect(await catalogLang(await savedBytes(doc))).toBe("ga");+ });+});++describe("text language", () => {+ test("reads a block's own language, and one it inherits", async () => {+ const doc = await open(letterPdf(" /Lang (en-IE)"));+ expect(doc.textLanguage(0, mcidOf(doc, 0, "Describe the letter"))).toEqual({+ own: null,+ inherited: "en-IE",+ });+ expect(doc.textLanguage(0, mcidOf(doc, 0, "Mes vacances"))).toEqual({+ own: "fr",+ inherited: "en-IE",+ });+ });++ test("saves several blocks' language in one step, and undoes it", async () => {+ const doc = await open(letterPdf(" /Lang (en-IE)"));+ const targets = ["Chere Marie", "Mes vacances"].map((fragment) => ({+ pageIndex: 0,+ mcid: mcidOf(doc, 0, fragment),+ }));+ const history = new HistoryStack();+ history.execute(+ new SetTextLanguageCommand({ targets, lang: "fr-FR" }),+ doc,+ );++ const langs = await savedLangs(doc);+ expect(langs.get("9")?.lang).toBe("fr-FR");+ expect(langs.get("10")?.lang).toBe("fr-FR");+ expect(langs.get("8")?.lang).toBeNull();++ history.undo(doc);+ expect(doc.textLanguage(0, targets[1].mcid)!.own).toBe("fr");+ expect(doc.structureEdits()).toEqual([]);+ });++ test("clears a block's language, leaving it to inherit", async () => {+ const doc = await open(letterPdf(" /Lang (en-IE)"));+ const mcid = mcidOf(doc, 0, "Mes vacances");+ new HistoryStack().execute(+ new SetTextLanguageCommand({+ targets: [{ pageIndex: 0, mcid }],+ lang: null,+ }),+ doc,+ );+ expect(doc.textLanguage(0, mcid)).toEqual({+ own: null,+ inherited: "en-IE",+ });+ expect((await savedLangs(doc)).get("10")?.lang).toBeNull();+ });++ test("lists the languages in use, as the session has them", async () => {+ const doc = await open(letterPdf(" /Lang (en-IE)"));+ expect(doc.languagesInUse()).toEqual(["en-IE", "fr"]);++ const target = { pageIndex: 0, mcid: mcidOf(doc, 0, "Mes vacances") };+ new HistoryStack().execute(+ new SetTextLanguageCommand({ targets: [target], lang: "de" }),+ doc,+ );+ expect(doc.languagesInUse()).toEqual(["en-IE", "de"]);+ });++ test("refuses text with no element", async () => {+ const doc = await open(untaggedPdf());+ expect(doc.structure(0).cannotSetLanguage(0)).toBe("untagged");+ });+});++describe("part of a block's text", () => {+ test("a nested Span inherits its nearest ancestor, including edits, save and undo", async () => {+ const doc = await open(nestedLanguagePdf());+ const history = new HistoryStack();+ expect(doc.innerLanguage(0, 0, "10")).toEqual({+ own: "de",+ inherited: "fr",+ });++ history.execute(+ new SetInnerLanguageCommand({ pageIndex: 0, key: "10", lang: null }),+ doc,+ );+ expect(doc.innerLanguage(0, 0, "10")).toEqual({+ own: null,+ inherited: "fr",+ });+ expect((await savedLangs(doc)).get("10")).toMatchObject({+ lang: null,+ inheritedLang: "fr",+ });+ const reopened = await open(await savedBytes(doc));+ expect(reopened.innerLanguage(0, 0, "10")).toEqual({+ own: null,+ inherited: "fr",+ });+ history.undo(doc);+ expect(doc.innerLanguage(0, 0, "10")).toEqual({+ own: "de",+ inherited: "fr",+ });++ history.execute(+ new SetInnerLanguageCommand({ pageIndex: 0, key: "9", lang: "es" }),+ doc,+ );+ expect(doc.innerLanguage(0, 0, "10")).toEqual({+ own: "de",+ inherited: "es",+ });+ history.undo(doc);+ expect(doc.innerLanguage(0, 0, "10")).toEqual({+ own: "de",+ inherited: "fr",+ });++ history.execute(+ new SetInnerLanguageCommand({ pageIndex: 0, key: "9", lang: null }),+ doc,+ );+ expect(doc.innerLanguage(0, 0, "10")).toEqual({+ own: "de",+ inherited: "en",+ });+ history.execute(+ new SetTextLanguageCommand({+ targets: [{ pageIndex: 0, mcid: 2 }],+ lang: "it",+ }),+ doc,+ );+ expect(doc.innerLanguage(0, 0, "10")).toEqual({+ own: "de",+ inherited: "it",+ });+ });++ test("an explicit catalog-language override still differs from its inline parent's language", async () => {+ const doc = await open(nestedLanguagePdf());+ new HistoryStack().execute(+ new SetInnerLanguageCommand({ pageIndex: 0, key: "10", lang: "en" }),+ doc,+ );+ expect(doc.innerLanguage(0, 0, "10")).toEqual({+ own: "en",+ inherited: "fr",+ });+ });++ test("reads the language a Span inside a paragraph has", async () => {+ const doc = await openSample();+ const run = runWith(doc, PAGE, "Umsatzerlöse").snapshot();+ const tag = innerTags(doc, run).find((t) => t.text === "Umsatzerlöse")!;+ expect(tag.language).toEqual({ own: "de-DE", inherited: "en-US" });+ });++ test("saves a new language for a Span inside a paragraph", async () => {+ const doc = await openSample();+ const run = runWith(doc, PAGE, "Umsatzerlöse").snapshot();+ const { key } = innerTags(doc, run).find((t) => t.text === "Umsatzerlöse")!;+ new HistoryStack().execute(+ new SetInnerLanguageCommand({ pageIndex: PAGE, key, lang: "de-AT" }),+ doc,+ );+ expect((await savedLangs(doc)).get(key)?.lang).toBe("de-AT");+ });++ test("marks selected words as a Span in another language", async () => {+ const doc = await open(letterPdf(" /Lang (en-IE)"));+ const run = runWith(doc, 0, "Describe the letter");+ const start = run.text.indexOf("letter");+ new HistoryStack().execute(+ new TagTextRangeCommand({+ pageIndex: 0,+ runId: run.id,+ start,+ end: start + "letter".length,+ as: "Span",+ lang: "fr",+ }),+ doc,+ );++ const saved = (await readFileStructure(await savedBytes(doc)))!;+ const span = saved.pages.get(0)!.elements.find((el) => el.type === "Span")!;+ expect(span.lang).toBe("fr");+ expect(span.block.key).toBe("8");+ expect(saved.languages.get("8")?.lang).toBeNull();+ });++ test("keeps a French paragraph's language on both halves of a heading cut from it", async () => {+ const doc = await open(letterPdf(" /Lang (en-IE)"));+ const run = runWith(doc, 0, "Chere Marie");+ const start = run.text.indexOf("merci");+ new HistoryStack().execute(+ new SetTextLanguageCommand({+ targets: [{ pageIndex: 0, mcid: run.snapshot().mcid! }],+ lang: "fr",+ }),+ doc,+ );+ new HistoryStack().execute(+ new TagTextRangeCommand({+ pageIndex: 0,+ runId: run.id,+ start,+ end: start + "merci".length,+ as: "H2",+ }),+ doc,+ );++ const saved = (await readFileStructure(await savedBytes(doc)))!;+ const paragraphs = saved.blocks.filter((b) => ["P", "H2"].includes(b.role));+ const french = paragraphs+ .filter((b) => saved.languages.get(b.key)?.lang === "fr")+ .map((b) => b.role);+ // The paragraph, the heading cut from it, the rest of it, and the+ // paragraph the file already marked French.+ expect(french).toEqual(["P", "H2", "P", "P"]);+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/storeApplyRecovery.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/storeApplyRecovery.test.tsindex ce62751a35..83de6344e6 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/storeApplyRecovery.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/storeApplyRecovery.test.ts@@ -17,6 +17,8 @@ function makeDoc(): EditorDocument {return {pageCount: 0,loadedPages: () => [],+ documentLanguage: () => null,+ languagesInUse: () => [],dispose: () => {},} as unknown as EditorDocument;}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.tsindex f7c6287ec9..47cbc3d61d 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/structureEditing.test.ts@@ -164,6 +164,7 @@ describe("reading the structure tree", () => {type,alt,actualText: null,+ lang: null,mcids,onlyMarkedContent: false,key,@@ -272,6 +273,7 @@ describe("reading tags from the file's ParentTree", () => {type,alt,actualText: null,+ lang: null,mcids,onlyMarkedContent: true,key: String(num),@@ -660,6 +662,7 @@ describe("PageStructure", () => {type: "Figure" as const,alt: "old",actualText: null,+ lang: null,mcids: [3, 4],onlyMarkedContent: true,key: "figure",@@ -877,7 +880,11 @@ describe("SetDecorativeCommand", () => {reviewImages(reopened, [{ pageIndex: 0, images: [image] },] as PageSnapshot[]),- ).toEqual({ needsDescription: 0, untagged: 0, untaggable: 0 });+ ).toEqual({+ needsDescription: 0,+ untagged: 0,+ untaggable: 0,+ });});});@@ -938,6 +945,7 @@ describe("PageStructure: added figures", () => {type: "P" as const,alt: null,actualText: null,+ lang: null,mcids: [3],onlyMarkedContent: true,key: "paragraph",@@ -965,7 +973,7 @@ describe("PageStructure: added figures", () => {{ mcid: 3, alt: "Chart", decorative: false },]);expect(s.addedElements()).toEqual([- { mcid: 5, type: "Figure", alt: "Logo" },+ { mcid: 5, type: "Figure", alt: "Logo", lang: null },]);expect(() => s.setDecorative(5, true)).toThrow();s.removeElement(5);@@ -1091,7 +1099,7 @@ describe("TagImageCommand", () => {history.undo(doc);expect(doc.structure(0).addedElements()).toEqual([- { mcid: 1, type: "Figure", alt: "A logo" },+ { mcid: 1, type: "Figure", alt: "A logo", lang: null },]);});@@ -1183,7 +1191,11 @@ describe("saving an added figure", () => {expect(images.filter((img) => img.artifact)).toHaveLength(2);expect(reviewImages(reopened, [{ pageIndex: 0, images }] as PageSnapshot[]),- ).toEqual({ needsDescription: 0, untagged: 0, untaggable: 0 });+ ).toEqual({+ needsDescription: 0,+ untagged: 0,+ untaggable: 0,+ });expect(tree(reopened)).toEqual(["Document", "A grey square"]);});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableStore.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableStore.test.tsindex dbbb55ab67..16805f372f 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableStore.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableStore.test.ts@@ -30,6 +30,8 @@ async function makeStore() {pageCount: 1,page: () => page,loadedPages: () => [page],+ documentLanguage: () => null,+ languagesInUse: () => [],module: {},dispose: () => {},} as unknown as EditorDocument;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetDocumentLanguageCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetDocumentLanguageCommand.tsnew file mode 100644index 0000000000..ee0f96d270--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetDocumentLanguageCommand.ts@@ -0,0 +1,41 @@+import i18n from "i18next";+import {+ RolledBackError,+ type Command,+} from "@editor/tools/pdfTextEditor/commands/Command";+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";++/**+ * Set or, with null, remove the document's language: the catalog /Lang every+ * text is read in unless its element says otherwise. Held on the document and+ * written by the save, so no page is regenerated for it.+ */+export class SetDocumentLanguageCommand implements Command {+ readonly type = "set-document-language";+ private readonly lang: string | null;+ private previous: string | null | undefined;++ constructor(opts: { lang: string | null }) {+ this.lang = opts.lang;+ }++ apply(doc: EditorDocument): void {+ if (doc.cannotSetDocumentLanguage()) {+ throw new RolledBackError(+ new Error(+ i18n.t(+ "pdfTextEditor.inspector.language.cannotSetDocument",+ "This document's language can't be changed.",+ ),+ ),+ );+ }+ if (this.previous === undefined) this.previous = doc.documentLanguage();+ doc.setDocumentLanguage(this.lang);+ }++ revert(doc: EditorDocument): void {+ if (this.previous === undefined) return;+ doc.setDocumentLanguage(this.previous);+ }+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetInnerLanguageCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetInnerLanguageCommand.tsnew file mode 100644index 0000000000..dd8f999e0f--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetInnerLanguageCommand.ts@@ -0,0 +1,53 @@+import i18n from "i18next";+import {+ RolledBackError,+ type Command,+} from "@editor/tools/pdfTextEditor/commands/Command";+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";++/**+ * Set or, with null, remove the language of element `key`, one marking part+ * of a block's text, such as a French phrase in an English question. Held on+ * the page's structure and written by the save as the element's /Lang.+ */+export class SetInnerLanguageCommand implements Command {+ readonly type = "set-inner-language";+ private readonly pageIndex: number;+ private readonly key: string;+ private readonly lang: string | null;+ private previous: string | null | undefined;++ constructor(opts: { pageIndex: number; key: string; lang: string | null }) {+ this.pageIndex = opts.pageIndex;+ this.key = opts.key;+ this.lang = opts.lang;+ }++ apply(doc: EditorDocument): void {+ const structure = doc.structure(this.pageIndex);+ try {+ const previous = structure.ownLang(this.key);+ structure.setOwnLang(this.key, this.lang);+ if (this.previous === undefined) this.previous = previous;+ } catch (err) {+ throw new RolledBackError(+ new Error(+ i18n.t(+ "pdfTextEditor.inspector.language.cannotSetText",+ "This text's language can't be changed.",+ ),+ {+ cause: err,+ },+ ),+ );+ }+ doc.page(this.pageIndex).bumpRevision();+ }++ revert(doc: EditorDocument): void {+ if (this.previous === undefined) return;+ doc.structure(this.pageIndex).setOwnLang(this.key, this.previous);+ doc.page(this.pageIndex).bumpRevision();+ }+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetTextLanguageCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetTextLanguageCommand.tsnew file mode 100644index 0000000000..9627f53935--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetTextLanguageCommand.ts@@ -0,0 +1,67 @@+import i18n from "i18next";+import {+ RolledBackError,+ type Command,+} from "@editor/tools/pdfTextEditor/commands/Command";+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";++/** Text a language is set for: the block the content `mcid` marks belongs to. */+export interface LanguageTarget {+ pageIndex: number;+ mcid: number;+}++/**+ * Set or, with null, remove the language of each target's block, as one+ * step: a letter set in French is often several paragraphs. Held on the+ * document and written by the save as each block's /Lang; the page content+ * keeps its marks, so it is never regenerated.+ */+export class SetTextLanguageCommand implements Command {+ readonly type = "set-text-language";+ private readonly targets: readonly LanguageTarget[];+ private readonly lang: string | null;+ private previous: (string | null)[] | null = null;++ constructor(opts: {+ targets: readonly LanguageTarget[];+ lang: string | null;+ }) {+ this.targets = opts.targets;+ this.lang = opts.lang;+ }++ apply(doc: EditorDocument): void {+ const refused = this.targets.some(+ ({ pageIndex, mcid }) =>+ doc.structure(pageIndex).cannotSetLanguage(mcid) !== null,+ );+ if (refused) {+ throw new RolledBackError(+ new Error(+ i18n.t(+ "pdfTextEditor.inspector.language.cannotSetText",+ "This text's language can't be changed.",+ ),+ ),+ );+ }+ // Read before any is set: two targets in one block share its language.+ this.previous ??= this.targets.map(+ ({ pageIndex, mcid }) => doc.textLanguage(pageIndex, mcid)!.own,+ );+ for (const { pageIndex, mcid } of this.targets) {+ doc.setTextLanguage(pageIndex, mcid, this.lang);+ doc.page(pageIndex).bumpRevision();+ }+ }++ revert(doc: EditorDocument): void {+ if (!this.previous) return;+ for (let i = this.targets.length - 1; i >= 0; i--) {+ const { pageIndex, mcid } = this.targets[i];+ doc.setTextLanguage(pageIndex, mcid, this.previous[i]);+ doc.page(pageIndex).bumpRevision();+ }+ }+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.tsindex edd37962ae..a1c5607cf7 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts@@ -42,9 +42,9 @@ import {/*** Tag part of a run's tagged text, code units `start` to `end`, as its own- * element of `as`. The save pass gives the element its place: inside the- * element the text was cut from for an inline type, else splitting that- * element around it.+ * element of `as`, read in language `lang` when given. The save pass gives+ * the element its place: inside the element the text was cut from for an+ * inline type, else splitting that element around it.*/export class TagTextRangeCommand implements Command {readonly type = "tag-text-range";@@ -53,6 +53,7 @@ export class TagTextRangeCommand implements Command {private readonly start: number;private readonly end: number;private readonly as: StructureType;+ private readonly lang: string | null;/** Chosen on first apply, so a redo reuses them. */private mcids: { cut: number; part: number } | null = null;private undo: Array<() => void> = [];@@ -63,12 +64,14 @@ export class TagTextRangeCommand implements Command {start: number;end: number;as: StructureType;+ lang?: string | null;}) {this.pageIndex = opts.pageIndex;this.runId = opts.runId;this.start = opts.start;this.end = opts.end;this.as = opts.as;+ this.lang = opts.lang ?? null;}apply(doc: EditorDocument): void {@@ -84,7 +87,9 @@ export class TagTextRangeCommand implements Command {"pdfTextEditor.inspector.accessibility.cannotRetag","This text's tag can't be changed.",),- { cause: err },+ {+ cause: err,+ },),);}@@ -142,6 +147,9 @@ export class TagTextRangeCommand implements Command {after: partMcid("after", plan.from.at(-1)!),});undo.push(() => structure.removeElement(cut));+ if (this.lang !== null) {+ structure.setOwnLang(structure.element(cut)!.key, this.lang);+ }}}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsxindex 5b1d526e1a..2aae44e8a9 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx@@ -3,9 +3,11 @@ import { Box, Center, Group, Stack, Tabs, Text } from "@mantine/core";import { useTranslation } from "react-i18next";import { Icon } from "@editor/ui/Icon";import { useHeadingOutline } from "@editor/tools/pdfTextEditor/hooks/useHeadingOutline";+import { useDocumentLanguage } from "@editor/tools/pdfTextEditor/hooks/useDocumentLanguage";import { useToolbarController } from "@editor/tools/pdfTextEditor/hooks/useToolbarController";import { useSelectionGeometry } from "@editor/tools/pdfTextEditor/hooks/useSelectionGeometry";import { DocumentInspector } from "@editor/tools/pdfTextEditor/components/inspector/DocumentInspector";+import { LanguagesInUse } from "@editor/tools/pdfTextEditor/components/inspector/languagesInUse";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";@@ -62,6 +64,7 @@ export function EditorSidebar({const { t } = useTranslation();const controller = useToolbarController(store, state, selection);const geometry = useSelectionGeometry(store, state, selection);+ const documentLanguage = useDocumentLanguage(store, state);const hasSelection =selection.runIds.length > 0 ||selection.imageIds.length > 0 ||@@ -142,46 +145,51 @@ export function EditorSidebar({</Tabs.List></Group>- <Box>- <Tabs.Panel value="selected">- {hasSelection ? (- <SelectionInspector- controller={controller}- selection={selection}- geometry={geometry}- fontNote={fontNote}- canGroup={canGroup}- canUngroup={canUngroup}- onGroup={onGroup}- onUngroup={onUngroup}- />- ) : (- <NothingSelected+ <LanguagesInUse.Provider value={state.languagesInUse}>+ <Box>+ <Tabs.Panel value="selected">+ {hasSelection ? (+ <SelectionInspector+ controller={controller}+ selection={selection}+ geometry={geometry}+ fontNote={fontNote}+ canGroup={canGroup}+ canUngroup={canUngroup}+ onGroup={onGroup}+ onUngroup={onUngroup}+ />+ ) : (+ <NothingSelected+ pages={state.pages}+ onRunOcr={onRunOcr}+ ocrRunning={ocrRunning}+ ocrAvailable={ocrAvailable}+ ocrBlockedReason={ocrBlockedReason}+ onRemovePassword={onRemovePassword}+ />+ )}+ </Tabs.Panel>+ <Tabs.Panel value="document">+ <DocumentInspectorpages={state.pages}- onRunOcr={onRunOcr}- ocrRunning={ocrRunning}- ocrAvailable={ocrAvailable}- ocrBlockedReason={ocrBlockedReason}- onRemovePassword={onRemovePassword}+ groupingMode={state.groupingMode}+ widthMode={state.widthMode}+ showRulers={state.showRulers}+ onSetGroupingMode={onSetGroupingMode}+ onSetWidthMode={onSetWidthMode}+ onSetShowRulers={onSetShowRulers}+ imageReview={+ reviewingAccessibility ? controller.imageReview : null+ }+ onSelectNextImageToReview={selectNextImageToReview}+ headingOutline={headings.outline}+ onSelectHeading={headings.selectHeading}+ documentLanguage={documentLanguage}/>- )}- </Tabs.Panel>- <Tabs.Panel value="document">- <DocumentInspector- pages={state.pages}- groupingMode={state.groupingMode}- widthMode={state.widthMode}- showRulers={state.showRulers}- onSetGroupingMode={onSetGroupingMode}- onSetWidthMode={onSetWidthMode}- onSetShowRulers={onSetShowRulers}- imageReview={reviewingAccessibility ? controller.imageReview : null}- onSelectNextImageToReview={selectNextImageToReview}- headingOutline={headings.outline}- onSelectHeading={headings.selectHeading}- />- </Tabs.Panel>- </Box>+ </Tabs.Panel>+ </Box>+ </LanguagesInUse.Provider></Tabs>);}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsxindex d67d009af8..cec981c444 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.test.tsx@@ -1,10 +1,15 @@import { MantineProvider } from "@mantine/core";-import { fireEvent, render, screen } from "@testing-library/react";+import { fireEvent, render, screen, within } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";import { DocumentInspector } from "@editor/tools/pdfTextEditor/components/inspector/DocumentInspector";+import type { DocumentLanguageControl } from "@editor/tools/pdfTextEditor/hooks/useDocumentLanguage";import type { ImageReview } from "@editor/tools/pdfTextEditor/util/imageAccessibility";-function renderInspector(imageReview: ImageReview | null, onNext = vi.fn()) {+function renderInspector(+ imageReview: ImageReview | null,+ onNext = vi.fn(),+ documentLanguage: DocumentLanguageControl | null = null,+) {render(<MantineProvider env="test"><DocumentInspector@@ -19,6 +24,7 @@ function renderInspector(imageReview: ImageReview | null, onNext = vi.fn()) {onSelectNextImageToReview={onNext}headingOutline={null}onSelectHeading={vi.fn()}+ documentLanguage={documentLanguage}/></MantineProvider>,);@@ -71,3 +77,59 @@ describe("DocumentInspector accessibility review", () => {).not.toBeInTheDocument();});});++describe("DocumentInspector language", () => {+ const LANGUAGE_KEY = "pdfTextEditor.inspector.language";+ const MISSING = "pdf-editor-document-language-missing";+ const language = (+ lang: string | null,+ editable = true,+ ): DocumentLanguageControl => ({+ language: lang,+ editable,+ onSet: vi.fn(),+ });++ function picker(): HTMLInputElement {+ return screen.getByRole("textbox", {+ name: `${LANGUAGE_KEY}.documentLabel`,+ });+ }++ it("flags a document with no language and sets one", () => {+ const control = language(null);+ renderInspector(null, vi.fn(), control);+ expect(screen.getByTestId(MISSING)).toBeVisible();+ expect(picker()).toHaveValue("");+ expect(picker()).toHaveAttribute(+ "placeholder",+ `${LANGUAGE_KEY}.placeholder`,+ );+ fireEvent.click(picker());+ const options = document.getElementById(+ picker().getAttribute("aria-controls")!,+ )!;+ fireEvent.click(+ within(options).getByRole("option", { name: /(^|\()en-IE\)?$/ }),+ );+ expect(control.onSet).toHaveBeenCalledWith("en-IE");+ });++ it("shows the document's language without flagging it", () => {+ renderInspector(null, vi.fn(), language("fr"));+ expect(picker().value).toMatch(/(^|\()fr\)?$/);+ expect(screen.queryByTestId(MISSING)).not.toBeInTheDocument();+ });++ it("disables the picker where the language can't be saved", () => {+ renderInspector(null, vi.fn(), language("fr", false));+ expect(picker()).toBeDisabled();+ });++ it("leaves the language out when it can't be edited here", () => {+ renderInspector(null);+ expect(+ screen.queryByTestId("pdf-editor-document-language-picker"),+ ).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.tsxindex 043eaf87f3..d11a9f307e 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/DocumentInspector.tsx@@ -1,13 +1,17 @@import { useState } from "react";+import type { TFunction } from "i18next";import { Badge, Collapse, Group, Stack, Text, Tooltip } from "@mantine/core";import { useTranslation } from "react-i18next";import { Button } from "@editor/ui/Button";import { Icon } from "@editor/ui/Icon";import {+ Field,Section,SectionLabel,StatRow,} from "@editor/tools/pdfTextEditor/components/inspector/InspectorPrimitives";+import { LanguagePicker } from "@editor/tools/pdfTextEditor/components/inspector/LanguagePicker";+import type { DocumentLanguageControl } from "@editor/tools/pdfTextEditor/hooks/useDocumentLanguage";import {analyzePageFonts,type PageFont,@@ -36,6 +40,8 @@ interface Props {/** Null when there is nothing to check. */headingOutline: HeadingOutline | null;onSelectHeading: (index: number) => void;+ /** Null when the language cannot be edited here. */+ documentLanguage: DocumentLanguageControl | null;}/** Facts about the open document. Nothing here acts on a selection. */@@ -45,6 +51,7 @@ export function DocumentInspector({onSelectNextImageToReview,headingOutline,onSelectHeading,+ documentLanguage,...settings}: Props) {const { t } = useTranslation();@@ -70,6 +77,9 @@ export function DocumentInspector({value={images}/></Stack>+ {documentLanguage && (+ <DocumentLanguageField control={documentLanguage} />+ )}</Section>{imageReview && (<AccessibilitySection@@ -89,6 +99,65 @@ export function DocumentInspector({);}+/**+ * The language every text is read in unless its own element says otherwise.+ * Flagged while unset: PDF/UA and WCAG 3.1.1 require it, and a screen reader+ * left to guess reads the whole document in the wrong voice.+ */+function DocumentLanguageField({+ control,+}: {+ control: DocumentLanguageControl;+}) {+ const { t } = useTranslation();+ const label = t("pdfTextEditor.inspector.language.documentLabel", "Language");+ return (+ <Stack gap={4} mt="sm">+ <Field label={label} hint={documentLanguageHint(t, control)}>+ <LanguagePicker+ own={control.language}+ inherited={null}+ placeholder={t(+ "pdfTextEditor.inspector.language.placeholder",+ "Select language",+ )}+ onChange={control.onSet}+ label={label}+ testId="pdf-editor-document-language-picker"+ disabled={!control.editable}+ />+ </Field>+ {control.language === null && (+ <Text+ size="xs"+ c="yellow.8"+ data-testid="pdf-editor-document-language-missing"+ >+ {t(+ "pdfTextEditor.inspector.language.missing",+ "No language set. Screen readers will guess, and may read the whole document in the wrong voice.",+ )}+ </Text>+ )}+ </Stack>+ );+}++function documentLanguageHint(+ t: TFunction,+ control: DocumentLanguageControl,+): string {+ return control.editable+ ? t(+ "pdfTextEditor.inspector.language.documentHint",+ "The language screen readers use unless a part of the text sets its own.",+ )+ : t(+ "pdfTextEditor.inspector.language.documentLocked",+ "An encrypted document's language can't be changed here.",+ );+}+function AccessibilitySection({review,onNext,diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/InspectorPrimitives.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/InspectorPrimitives.test.tsxnew file mode 100644index 0000000000..07e62e13ce--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/InspectorPrimitives.test.tsx@@ -0,0 +1,31 @@+import { MantineProvider } from "@mantine/core";+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import { Field } from "@editor/tools/pdfTextEditor/components/inspector/InspectorPrimitives";++const HINT = "Screen readers switch voice to this language.";++function renderField() {+ render(+ <MantineProvider env="test">+ <Field label="Language" hint={HINT}>+ <input />+ </Field>+ </MantineProvider>,+ );+ return screen.getByRole("img", { name: HINT });+}++describe("Field hint", () => {+ it("shows the hint when the pointer rests on its icon", async () => {+ fireEvent.mouseEnter(renderField());+ expect(await screen.findByRole("tooltip")).toHaveTextContent(HINT);+ });++ it("shows the hint when its icon takes keyboard focus", async () => {+ const icon = renderField();+ expect(icon).toHaveAttribute("tabindex", "0");+ fireEvent.focus(icon);+ expect(await screen.findByRole("tooltip")).toHaveTextContent(HINT);+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/InspectorPrimitives.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/InspectorPrimitives.tsxindex 7ee905e2c0..c24996452b 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/InspectorPrimitives.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/InspectorPrimitives.tsx@@ -85,19 +85,34 @@ export function Field({);}-/** The `?` that replaced the panel's permanent explanatory paragraphs. */+/**+ * The `?` that replaced the panel's permanent explanatory paragraphs, its+ * hint shown on hover or keyboard focus and read out as its name.+ */export function HintIcon({ label }: { label: string }) {return (- <Tooltip label={label} multiline w={220} withArrow position="left">- <Icon- name="circle-question-mark"- size="1em"+ <Tooltip+ label={label}+ multiline+ w={220}+ withArrow+ position="left"+ events={{ hover: true, focus: true, touch: true }}+ >+ {/* Tooltip anchors to its child's ref and handlers, which Icon drops. */}+ <span+ role="img"+ aria-label={label}+ tabIndex={0}style={{+ display: "inline-flex",cursor: "help",color: "var(--mantine-color-dimmed)",flexShrink: 0,}}- />+ >+ <Icon name="circle-question-mark" size="1em" />+ </span></Tooltip>);}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/LanguagePicker.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/LanguagePicker.test.tsxnew file mode 100644index 0000000000..60ad69e49f--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/LanguagePicker.test.tsx@@ -0,0 +1,199 @@+import { MantineProvider } from "@mantine/core";+import { act, fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import { LanguagePicker } from "@editor/tools/pdfTextEditor/components/inspector/LanguagePicker";+import { LanguagesInUse } from "@editor/tools/pdfTextEditor/components/inspector/languagesInUse";+import {+ OFFERED_LANGUAGE_TAGS,+ filterLanguages,+ languageOptions,+} from "@editor/tools/pdfTextEditor/util/languageOptions";++const tagsOf = (options: { tag: string }[]) => options.map((o) => o.tag);++describe("languageOptions", () => {+ it("offers every OCR language and the regional variants", () => {+ expect(OFFERED_LANGUAGE_TAGS.length).toBeGreaterThanOrEqual(100);+ expect(OFFERED_LANGUAGE_TAGS).toEqual(+ expect.arrayContaining([+ "ga",+ "mt",+ "fil",+ "mi",+ "la",+ "en-IE",+ "zh-Hant",+ ]),+ );+ expect(new Set(OFFERED_LANGUAGE_TAGS).size).toBe(+ OFFERED_LANGUAGE_TAGS.length,+ );+ });++ it("offers a typed tag the list lacks, in canonical form", () => {+ expect(tagsOf(languageOptions(null, "en", "HAW").others)).toContain("haw");+ });++ it("offers the code edited inside a shown label", () => {+ expect(+ tagsOf(languageOptions(null, "en", "Spanish (es-AR)").others),+ ).toContain("es-AR");+ expect(+ tagsOf(languageOptions(null, "en", "Spanish (es)-CL").others),+ ).toContain("es-CL");+ });++ it("offers the code edited inside a label naming a region", () => {+ expect(+ tagsOf(languageOptions(null, "en", "English (Ireland) (en-MT)").others),+ ).toContain("en-MT");+ });++ it("offers one option for two spellings of a tag", () => {+ const { inUse, others } = languageOptions("EN-ie", "en", "", ["EN-ie"]);+ expect(tagsOf(inUse)).toEqual(["en-IE"]);+ expect(tagsOf(others)).not.toContain("EN-ie");+ expect(tagsOf(others)).not.toContain("en-IE");+ });++ it("offers nothing extra for a language's name typed in place of its code", () => {+ for (const typed of ["French", "Fren", "x-klingon"]) {+ expect(languageOptions(null, "en", typed).others).toHaveLength(+ OFFERED_LANGUAGE_TAGS.length,+ );+ }+ });++ it("offers nothing extra for text that is not a tag", () => {+ const { inUse, others } = languageOptions(null, "en", "not a language");+ expect(inUse).toEqual([]);+ expect(others).toHaveLength(OFFERED_LANGUAGE_TAGS.length);+ });++ it("keeps the file's own tag when the list lacks it", () => {+ expect(tagsOf(languageOptions("x-klingon", "en").others)).toContain(+ "x-klingon",+ );+ });++ it("lists the document's languages apart from the rest", () => {+ const { inUse, others } = languageOptions(null, "en", "", [+ "fr",+ "x-klingon",+ ]);+ expect(new Set(tagsOf(inUse))).toEqual(new Set(["fr", "x-klingon"]));+ expect(tagsOf(others)).not.toContain("fr");+ expect(others).toHaveLength(OFFERED_LANGUAGE_TAGS.length - 1);+ });+});++describe("filterLanguages", () => {+ const options = [+ {+ group: "In this document",+ items: [{ value: "fr", label: "French (fr)" }],+ },+ {+ group: "All languages",+ items: [+ { value: "es", label: "Spanish (es)" },+ { value: "es-MX", label: "Spanish (Mexico) (es-MX)" },+ ],+ },+ ];+ const valuesFor = (search: string) =>+ filterLanguages({ options, search, limit: Infinity }).flatMap((item) =>+ "items" in item ? item.items.map((i) => i.value) : [item.value],+ );++ it("matches a language by its name", () => {+ expect(valuesFor("fren")).toEqual(["fr"]);+ });++ it("matches the code edited inside a shown label", () => {+ expect(valuesFor("Spanish (es-MX)")).toEqual(["es-MX"]);+ expect(valuesFor("Spanish (es)-M")).toEqual(["es-MX"]);+ expect(valuesFor("Spanish (Mexico) (es-MX)")).toEqual(["es-MX"]);+ expect(valuesFor("Spanish (Mexico) (es)")).toEqual(["es", "es-MX"]);+ });++ it("matches a deprecated code by the tag it stands for", () => {+ const withHebrew = [{ value: "he", label: "Hebrew (he)" }];+ expect(+ filterLanguages({ options: withHebrew, search: "iw", limit: Infinity }),+ ).toEqual(withHebrew);+ });++ it("drops a group left with nothing", () => {+ expect(+ filterLanguages({ options, search: "fren", limit: Infinity }),+ ).toHaveLength(1);+ });+});++function renderPicker(+ props: Partial<Parameters<typeof LanguagePicker>[0]> = {},+ inUse: string[] = [],+) {+ const onChange = vi.fn();+ render(+ <MantineProvider env="test">+ <LanguagesInUse.Provider value={inUse}>+ <LanguagePicker+ own={null}+ inherited={null}+ placeholder="Select language"+ onChange={onChange}+ label="Language"+ testId="picker"+ {...props}+ />+ </LanguagesInUse.Provider>+ </MantineProvider>,+ );+ return {+ onChange,+ input: screen.getByRole("textbox", {+ name: "Language",+ }) as HTMLInputElement,+ };+}++describe("LanguagePicker", () => {+ it("picks a language typed by its code", () => {+ const { onChange, input } = renderPicker();+ fireEvent.click(input);+ fireEvent.change(input, { target: { value: "haw" } });+ fireEvent.click(screen.getByRole("option", { name: /haw/ }));+ expect(onChange).toHaveBeenCalledWith("haw");+ });++ it("lists the document's languages first", () => {+ const { input } = renderPicker({}, ["ga"]);+ fireEvent.click(input);+ expect(screen.getAllByRole("option")[0]).toHaveAccessibleName(+ /(^|\()ga\)?$/,+ );+ });++ it("selects its text on focus, so typing replaces it", () => {+ const { input } = renderPicker({ own: "fr" });+ act(() => input.focus());+ expect(input.selectionStart).toBe(0);+ expect(input.selectionEnd).toBe(input.value.length);+ expect(input.value).not.toBe("");+ });++ it("mutes its own tag spelled differently from the inherited one", () => {+ const { input } = renderPicker({ own: "EN-ie", inherited: "en-IE" });+ expect(input.style.color).toBe("var(--c-text-muted)");+ expect(input.value).toMatch(/(^|\()en-IE\)?$/);+ });++ it("leaves the language as it is when the inherited one is picked again", () => {+ const { onChange, input } = renderPicker({ inherited: "ga" });+ fireEvent.click(input);+ fireEvent.click(screen.getByRole("option", { name: /(^|\()ga\)?$/ }));+ expect(onChange).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/LanguagePicker.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/LanguagePicker.tsxnew file mode 100644index 0000000000..37005b1923--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/LanguagePicker.tsx@@ -0,0 +1,117 @@+import { useContext, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Select } from "@editor/ui/Select";+import { LanguagesInUse } from "@editor/tools/pdfTextEditor/components/inspector/languagesInUse";+import { comparableLanguageTag } from "@editor/tools/pdfTextEditor/model/languageTag";+import {+ filterLanguages,+ languageOptions,+ type LanguageOption,+} from "@editor/tools/pdfTextEditor/util/languageOptions";++/**+ * A searchable language list for text read in `own`, else in `inherited`.+ * The language shown is muted while it is only the inherited one, or the+ * same as it; with neither, `placeholder` shows. A language set apart from+ * the inherited one can be cleared, calling onChange with null.+ *+ * Languages the document uses are listed first. A tag the list lacks, as a+ * file may have or a user may type, becomes an option of its own.+ */+export function LanguagePicker({+ own: ownAsGiven,+ inherited: inheritedAsGiven,+ placeholder,+ onChange,+ label,+ testId,+ disabled,+}: {+ own: string | null;+ inherited: string | null;+ placeholder: string;+ onChange: (lang: string | null) => void;+ label: string;+ testId: string;+ disabled?: boolean;+}) {+ const { t, i18n } = useTranslation();+ const inUse = useContext(LanguagesInUse);+ const [typed, setTyped] = useState("");+ // The click that focuses the field selects its text, so typing replaces+ // the language; a later click places the caret to edit its code.+ const selectOnMouseUp = useRef(false);+ const own = ownAsGiven === null ? null : comparableLanguageTag(ownAsGiven);+ const inherited =+ inheritedAsGiven === null ? null : comparableLanguageTag(inheritedAsGiven);+ const shown = own ?? inherited;+ const options = useMemo(() => {+ const groups = languageOptions(shown, i18n.language, typed, inUse);+ const toOption = ({ tag, label }: LanguageOption) => ({+ value: tag,+ label,+ });+ if (groups.inUse.length === 0) return groups.others.map(toOption);+ return [+ {+ group: t(+ "pdfTextEditor.inspector.language.inDocument",+ "In this document",+ ),+ options: groups.inUse.map(toOption),+ },+ {+ group: t(+ "pdfTextEditor.inspector.language.allLanguages",+ "All languages",+ ),+ options: groups.others.map(toOption),+ },+ ];+ }, [shown, i18n.language, typed, inUse, t]);+ return (+ <div+ data-testid={testId}+ onFocus={(e) => {+ if (e.target instanceof HTMLInputElement) e.target.select();+ }}+ onMouseDown={(e) => {+ selectOnMouseUp.current = e.target !== document.activeElement;+ }}+ onMouseUp={(e) => {+ if (!selectOnMouseUp.current) return;+ selectOnMouseUp.current = false;+ if (e.target instanceof HTMLInputElement) {+ e.preventDefault();+ e.target.select();+ }+ }}+ >+ <Select+ searchable+ onSearchChange={setTyped}+ filter={filterLanguages}+ allowDeselect={false}+ clearable={own !== null && own !== inherited}+ muted={own === null || own === inherited}+ disabled={disabled}+ inputSize="sm"+ options={options}+ value={shown}+ placeholder={placeholder}+ nothingFoundMessage={t(+ "pdfTextEditor.inspector.language.noMatch",+ "No matching language. Type its code instead, such as mt or en-IE.",+ )}+ onChange={(picked) => {+ if (picked === null) {+ if (own !== null) onChange(null);+ } else if (picked !== shown) {+ onChange(picked);+ }+ }}+ aria-label={label}+ />+ </div>+ );+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsxindex 51a2863a96..cca9874ee1 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx@@ -74,13 +74,15 @@ export function SelectionInspector({/>)}{hasImageSelection && <ImageSection controller={controller} />}- {ACCESSIBILITY_EDITING && controller.textTag && (- <TextAccessibilitySection- tag={controller.textTag}- onSetTag={controller.onSetTextTag}- inner={controller.innerTextTags}- />- )}+ {ACCESSIBILITY_EDITING &&+ (controller.textTag || controller.textLanguage) && (+ <TextAccessibilitySection+ tag={controller.textTag}+ onSetTag={controller.onSetTextTag}+ inner={controller.innerTextTags}+ language={controller.textLanguage}+ />+ )}{ACCESSIBILITY_EDITING && controller.imageAccessibility && (<ImageAccessibilitySectionaccessibility={controller.imageAccessibility}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.test.tsxindex a8db7459b9..3797146cec 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.test.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.test.tsx@@ -3,10 +3,14 @@ import { fireEvent, render, screen, within } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";import { TextAccessibilitySection } from "@editor/tools/pdfTextEditor/components/inspector/TextAccessibilitySection";import { structureRole } from "@editor/tools/pdfTextEditor/model/structureTypes";-import type { InnerTagsControl } from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";+import type {+ InnerTagsControl,+ TextLanguageControl,+} from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";import type { TextTag } from "@editor/tools/pdfTextEditor/util/textAccessibility";const KEY = "pdfTextEditor.inspector.accessibility";+const LANGUAGE_KEY = "pdfTextEditor.inspector.language";const NO_INNER: InnerTagsControl = {tags: [],active: null,@@ -14,12 +18,19 @@ const NO_INNER: InnerTagsControl = {onSet: () => {},newTagTypes: null,onTagSelection: () => {},+ onSetLanguage: () => {},+ onLanguageSelection: null,};function tagShown(tag: TextTag): HTMLElement {render(<MantineProvider env="test">- <TextAccessibilitySection tag={tag} onSetTag={vi.fn()} inner={NO_INNER} />+ <TextAccessibilitySection+ tag={tag}+ onSetTag={vi.fn()}+ inner={NO_INNER}+ language={null}+ /></MantineProvider>,);return screen.getByTestId("pdf-editor-text-tag");@@ -69,6 +80,7 @@ describe("TextAccessibilitySection", () => {tag={{ kind: "tagged", block: structureRole("P"), cannotRetag: null }}onSetTag={onRetag}inner={NO_INNER}+ language={null}/></MantineProvider>,);@@ -90,6 +102,7 @@ describe("TextAccessibilitySection", () => {}}onSetTag={vi.fn()}inner={NO_INNER}+ language={null}/></MantineProvider>,);@@ -148,8 +161,95 @@ describe("TextAccessibilitySection", () => {screen.getByRole("textbox", { name: `${KEY}.selectedText` }),).toBeDisabled();});++ it("shows the language the text inherits, muted, and sets one of its own", () => {+ const language = languageControl("en-IE", null);+ renderSection(innerControl(), language);+ const input = screen.getByRole("textbox", {+ name: `${LANGUAGE_KEY}.label`,+ });+ expect((input as HTMLInputElement).value).toMatch(/(^|\()en-IE\)?$/);+ expect(isMuted(input)).toBe(true);+ fireEvent.click(input);+ fireEvent.click(optionFor(input, "fr"));+ expect(language.onSet).toHaveBeenCalledWith("fr");+ });++ it("mutes a language set the same as the one inherited", () => {+ renderSection(innerControl(), languageControl("en-IE", "en-IE"));+ const input = screen.getByRole("textbox", {+ name: `${LANGUAGE_KEY}.label`,+ });+ expect(isMuted(input)).toBe(true);+ expect(clearButtonOf(input)).toBeNull();+ });++ it("clears the text's own language", () => {+ const language = languageControl("en", "fr");+ renderSection(innerControl(), language);+ const input = screen.getByRole("textbox", {+ name: `${LANGUAGE_KEY}.label`,+ });+ expect((input as HTMLInputElement).value).toMatch(/(^|\()fr\)?$/);+ expect(isMuted(input)).toBe(false);+ fireEvent.click(clearButtonOf(input)!);+ expect(language.onSet).toHaveBeenCalledWith(null);+ });++ it("shows only the language for several selected runs", () => {+ render(+ <MantineProvider env="test">+ <TextAccessibilitySection+ tag={null}+ onSetTag={vi.fn()}+ inner={innerControl()}+ language={{ language: undefined, onSet: vi.fn() }}+ />+ </MantineProvider>,+ );+ expect(screen.queryByTestId("pdf-editor-text-tag")).toBeNull();+ expect(screen.queryByTestId("pdf-editor-inner-tags")).toBeNull();+ const input = screen.getByRole("textbox", {+ name: `${LANGUAGE_KEY}.label`,+ });+ expect(input).toHaveValue("");+ expect(input).toHaveAttribute("placeholder", `${LANGUAGE_KEY}.mixed`);+ });++ it("sets the language of the selected tag", () => {+ const inner = innerControl({ active: 0 });+ renderSection(inner);+ const input = screen.getByRole("textbox", {+ name: `${LANGUAGE_KEY}.innerLabel`,+ });+ expect((input as HTMLInputElement).value).toMatch(/(^|\()de\)?$/);+ fireEvent.click(input);+ fireEvent.click(optionFor(input, "ga"));+ expect(inner.onSetLanguage).toHaveBeenCalledWith(0, "ga");+ });++ it("marks characters selected inside the text as another language", () => {+ const inner = innerControl({+ newTagTypes: ["Span"],+ onLanguageSelection: vi.fn(),+ });+ renderSection(inner);+ const input = screen.getByRole("textbox", {+ name: `${LANGUAGE_KEY}.selectedText`,+ });+ fireEvent.click(input);+ fireEvent.click(optionFor(input, "fr"));+ expect(inner.onLanguageSelection).toHaveBeenCalledWith("fr");+ });});+function languageControl(+ inherited: string | null,+ own: string | null,+): TextLanguageControl & { onSet: ReturnType<typeof vi.fn> } {+ return { language: { own, inherited }, onSet: vi.fn() };+}+function innerControl(overrides: Partial<InnerTagsControl> = {},): InnerTagsControl {@@ -163,6 +263,8 @@ function innerControl(role: structureRole("Span"),types: ["Span", "Code"],removable: true,+ language: { own: "de", inherited: "en" },+ languageEditable: true,},{key: "2",@@ -172,6 +274,8 @@ function innerControl(role: structureRole("Link"),types: [],removable: false,+ language: { own: null, inherited: "en" },+ languageEditable: true,},],active: null,@@ -179,22 +283,43 @@ function innerControl(onSet: vi.fn(),newTagTypes: null,onTagSelection: vi.fn(),+ onSetLanguage: vi.fn(),+ onLanguageSelection: null,...overrides,};}-function renderSection(inner: InnerTagsControl) {+function renderSection(+ inner: InnerTagsControl,+ language: TextLanguageControl | null = null,+) {render(<MantineProvider env="test"><TextAccessibilitySectiontag={{ kind: "tagged", block: structureRole("P"), cannotRetag: null }}onSetTag={vi.fn()}inner={inner}+ language={language}/></MantineProvider>,);}+function isMuted(input: HTMLElement): boolean {+ return input.closest('[style*="--c-text-muted"]') !== null;+}++function clearButtonOf(input: HTMLElement): HTMLElement | null {+ return input.closest(".mantine-Input-wrapper")!.querySelector("button");+}++/** A language picker's option for `tag`: "Name (tag)", or the tag alone where the locale has no name. */+function optionFor(input: HTMLElement, tag: string): HTMLElement {+ return within(listboxOf(input)).getByRole("option", {+ name: new RegExp(`(^|\\()${tag}\\)?$`),+ });+}+/** The options of a picker: every picker's are in the document at once. */function listboxOf(input: HTMLElement): HTMLElement {return document.getElementById(input.getAttribute("aria-controls")!)!;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsxindex 7b0c9aaa85..5258caff31 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.tsx@@ -19,58 +19,113 @@ import type {InnerTag,TextTag,} from "@editor/tools/pdfTextEditor/util/textAccessibility";-import type { InnerTagsControl } from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";+import type {+ InnerTagsControl,+ TextLanguageControl,+} from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";+import { LanguagePicker } from "@editor/tools/pdfTextEditor/components/inspector/LanguagePicker";import "@editor/tools/pdfTextEditor/components/inspector/TextAccessibilitySection.css";import { privateContentClassName } from "@editor/components/shared/privateContentClassName";/**- * What the selected text is tagged as, and a picker to change it: retagging- * its block, or giving untagged text an element of its own. Beneath it, the- * tags marking parts of the text, and a picker for characters selected in it.+ * What the selected text is tagged as and the language it is read in, with+ * pickers to change them: retagging its block, or giving untagged text an+ * element of its own. Beneath them, the tags marking parts of the text, and+ * pickers for characters selected in it. With several runs selected, only+ * their language: `tag` is null.*/export function TextAccessibilitySection({tag,onSetTag,inner,+ language,}: {- tag: TextTag;+ tag: TextTag | null;onSetTag: (type: StructureType) => void;inner: InnerTagsControl;+ language: TextLanguageControl | null;}) {const { t } = useTranslation();- const label = t("pdfTextEditor.inspector.accessibility.tagLabel", "Tag");return (<Section testId="pdf-editor-text-accessibility"><SectionLabel>{t("pdfTextEditor.inspector.accessibility.heading", "Accessibility")}</SectionLabel><Stack gap="xs">- {pickable(tag) ? (- <Field label={label}>- <TagPicker- types={TEXT_BLOCK_TYPES}- current={tag.kind === "tagged" ? tag.block : null}- placeholder={tagText(t, tag)}- onSetTag={onSetTag}- label={label}- testId="pdf-editor-text-tag-picker"- />- </Field>- ) : (- <StatRow- label={label}- value={- <span data-testid="pdf-editor-text-tag">{tagText(t, tag)}</span>- }- />+ {tag && <TagField tag={tag} onSetTag={onSetTag} />}+ {language && <TextLanguageField control={language} />}+ {tag && (+ <>+ <InnerTagList inner={inner} />+ <NewTagPicker inner={inner} />+ <NewLanguagePicker inner={inner} />+ </>)}- <InnerTagList inner={inner} />- <NewTagPicker inner={inner} /></Stack></Section>);}+function TagField({+ tag,+ onSetTag,+}: {+ tag: TextTag;+ onSetTag: (type: StructureType) => void;+}) {+ const { t } = useTranslation();+ const label = t("pdfTextEditor.inspector.accessibility.tagLabel", "Tag");+ return pickable(tag) ? (+ <Field label={label}>+ <TagPicker+ types={TEXT_BLOCK_TYPES}+ current={tag.kind === "tagged" ? tag.block : null}+ placeholder={tagText(t, tag)}+ onSetTag={onSetTag}+ label={label}+ testId="pdf-editor-text-tag-picker"+ />+ </Field>+ ) : (+ <StatRow+ label={label}+ value={<span data-testid="pdf-editor-text-tag">{tagText(t, tag)}</span>}+ />+ );+}++/** The language the selected text's blocks are read in; "Mixed" when they differ. */+function TextLanguageField({ control }: { control: TextLanguageControl }) {+ const { t } = useTranslation();+ const label = t("pdfTextEditor.inspector.language.label", "Language");+ const { language } = control;+ return (+ <Field+ label={label}+ hint={t(+ "pdfTextEditor.inspector.language.textHint",+ "Screen readers switch voice and pronunciation to this language.",+ )}+ >+ <LanguagePicker+ own={language?.own ?? null}+ inherited={language?.inherited ?? null}+ placeholder={+ language+ ? t(+ "pdfTextEditor.inspector.language.placeholder",+ "Select language",+ )+ : t("pdfTextEditor.inspector.language.mixed", "Mixed")+ }+ onChange={control.onSet}+ label={label}+ testId="pdf-editor-text-language-picker"+ />+ </Field>+ );+}+/** The tags marking parts of the text, numbered in reading order; the one picked opens its controls. */function InnerTagList({ inner }: { inner: InnerTagsControl }) {const { t } = useTranslation();@@ -91,6 +146,7 @@ function InnerTagList({ inner }: { inner: InnerTagsControl }) {active={inner.active === index}onSelect={() => inner.onSelect(index)}onSet={(type) => inner.onSet(index, type)}+ onSetLanguage={(lang) => inner.onSetLanguage(index, lang)}/>))}</Stack>@@ -104,12 +160,14 @@ function InnerTagRow({active,onSelect,onSet,+ onSetLanguage,}: {number: number;innerTag: InnerTag;active: boolean;onSelect: () => void;onSet: (type: StructureType | null) => void;+ onSetLanguage: (lang: string | null) => void;}) {const text = innerTag.text.replace(/\s+/g, " ").trim();return (@@ -129,7 +187,12 @@ function InnerTagRow({</span></button>{active && (- <InnerTagControls number={number} innerTag={innerTag} onSet={onSet} />+ <InnerTagControls+ number={number}+ innerTag={innerTag}+ onSet={onSet}+ onSetLanguage={onSetLanguage}+ />)}</div>);@@ -139,10 +202,12 @@ function InnerTagControls({number,innerTag,onSet,+ onSetLanguage,}: {number: number;innerTag: InnerTag;onSet: (type: StructureType | null) => void;+ onSetLanguage: (lang: string | null) => void;}) {const { t } = useTranslation();const removeLabel = t(@@ -150,34 +215,52 @@ function InnerTagControls({"Remove tag",);return (- <Group gap={4} wrap="nowrap" mt={4}>- <Box style={{ flex: 1, minWidth: 0 }}>- <TagPicker- types={innerTag.types}- current={innerTag.role}- placeholder={blockName(t, innerTag.role)}- onSetTag={onSet}- label={t(- "pdfTextEditor.inspector.accessibility.innerTagLabel",- "Tag {{number}}",- { number },- )}- testId="pdf-editor-inner-tag-picker"- />- </Box>- {innerTag.removable && (- <ActionIcon- variant="tertiary"- size="sm"- aria-label={removeLabel}- title={removeLabel}- onClick={() => onSet(null)}- data-testid="pdf-editor-inner-tag-remove"- >- <Icon name="trash" size={14} />- </ActionIcon>- )}- </Group>+ <Stack gap={4} mt={4}>+ <Group gap={4} wrap="nowrap">+ <Box style={{ flex: 1, minWidth: 0 }}>+ <TagPicker+ types={innerTag.types}+ current={innerTag.role}+ placeholder={blockName(t, innerTag.role)}+ onSetTag={onSet}+ label={t(+ "pdfTextEditor.inspector.accessibility.innerTagLabel",+ "Tag {{number}}",+ { number },+ )}+ testId="pdf-editor-inner-tag-picker"+ />+ </Box>+ {innerTag.removable && (+ <ActionIcon+ variant="tertiary"+ size="sm"+ aria-label={removeLabel}+ title={removeLabel}+ onClick={() => onSet(null)}+ data-testid="pdf-editor-inner-tag-remove"+ >+ <Icon name="trash" size={14} />+ </ActionIcon>+ )}+ </Group>+ <LanguagePicker+ own={innerTag.language.own}+ inherited={innerTag.language.inherited}+ placeholder={t(+ "pdfTextEditor.inspector.language.placeholder",+ "Select language",+ )}+ onChange={onSetLanguage}+ label={t(+ "pdfTextEditor.inspector.language.innerLabel",+ "Tag {{number}} language",+ { number },+ )}+ testId="pdf-editor-inner-tag-language-picker"+ disabled={!innerTag.languageEditable}+ />+ </Stack>);}@@ -206,6 +289,37 @@ function NewTagPicker({ inner }: { inner: InnerTagsControl }) {);}+/**+ * A picker marking the characters selected in the text as a Span in another+ * language, shown while some are and can take one.+ */+function NewLanguagePicker({ inner }: { inner: InnerTagsControl }) {+ const { t } = useTranslation();+ const onPick = inner.onLanguageSelection;+ if (!onPick) return null;+ const label = t(+ "pdfTextEditor.inspector.language.selectedText",+ "Selected text language",+ );+ return (+ <Field label={label}>+ <LanguagePicker+ own={null}+ inherited={null}+ placeholder={t(+ "pdfTextEditor.inspector.language.placeholder",+ "Select language",+ )}+ onChange={(lang) => {+ if (lang) onPick(lang);+ }}+ label={label}+ testId="pdf-editor-new-language-picker"+ />+ </Field>+ );+}+function pickable(tag: TextTag): boolean {if (tag.kind === "tagged") return tag.cannotRetag === null;return tag.kind === "untagged" && tag.taggable;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/languagesInUse.ts b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/languagesInUse.tsnew file mode 100644index 0000000000..41dccf26cc--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/languagesInUse.ts@@ -0,0 +1,4 @@+import { createContext } from "react";++/** The languages the open document is read in, which every language picker lists first. */+export const LanguagesInUse = createContext<readonly string[]>([]);diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentLanguage.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentLanguage.tsnew file mode 100644index 0000000000..b864f175f1--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentLanguage.ts@@ -0,0 +1,40 @@+import { useCallback, useMemo } from "react";+import { ACCESSIBILITY_EDITING } from "@editor/constants/featureFlags";+import { SetDocumentLanguageCommand } from "@editor/tools/pdfTextEditor/commands/SetDocumentLanguageCommand";+import type {+ EditorStore,+ EditorViewState,+} from "@editor/tools/pdfTextEditor/store/EditorStore";++/** The document's language and a way to change it. */+export interface DocumentLanguageControl {+ /** Null when the file names none, so a screen reader guesses. */+ language: string | null;+ /** False when the save cannot write it, as for an encrypted file. */+ editable: boolean;+ onSet: (lang: string | null) => void;+}++/** The open document's language control; null when accessibility editing is off or nothing is open. */+export function useDocumentLanguage(+ store: EditorStore,+ state: EditorViewState,+): DocumentLanguageControl | null {+ const onSet = useCallback(+ (lang: string | null) =>+ store.dispatch(new SetDocumentLanguageCommand({ lang })),+ [store],+ );+ const doc = store.document;+ return useMemo(+ () =>+ ACCESSIBILITY_EDITING && doc && state.hasDocument+ ? {+ language: state.documentLanguage,+ editable: doc.cannotSetDocumentLanguage() === null,+ onSet,+ }+ : null,+ [doc, state.hasDocument, state.documentLanguage, onSet],+ );+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsxindex 7b2045588f..f2740ba6e4 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorOcr.test.tsx@@ -55,6 +55,8 @@ function makeDoc(encrypted = false): EditorDocument {module: { FPDF_GetSecurityHandlerRevision: () => (encrypted ? 6 : -1) },pageCount: 0,loadedPages: () => [],+ documentLanguage: () => null,+ languagesInUse: () => [],dispose: vi.fn(),} as unknown as EditorDocument;}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.tsindex 4a4eeb5ead..cf882d95eb 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts@@ -2,12 +2,18 @@ import { useCallback, useMemo } from "react";import { ACCESSIBILITY_EDITING } from "@editor/constants/featureFlags";import { RetagInnerCommand } from "@editor/tools/pdfTextEditor/commands/RetagInnerCommand";import { RetagTextCommand } from "@editor/tools/pdfTextEditor/commands/RetagTextCommand";+import { SetInnerLanguageCommand } from "@editor/tools/pdfTextEditor/commands/SetInnerLanguageCommand";+import {+ SetTextLanguageCommand,+ type LanguageTarget,+} from "@editor/tools/pdfTextEditor/commands/SetTextLanguageCommand";import { TagTextCommand } from "@editor/tools/pdfTextEditor/commands/TagTextCommand";import {rangeTagTypes,TagTextRangeCommand,} from "@editor/tools/pdfTextEditor/commands/TagTextRangeCommand";import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";+import type { TextLanguage } from "@editor/tools/pdfTextEditor/model/languageTag";import type {EditorStore,EditorViewState,@@ -35,6 +41,17 @@ export interface InnerTagsControl {/** What the characters selected inside the run can be tagged as; null when nothing new is selected. */newTagTypes: readonly StructureType[] | null;onTagSelection: (type: StructureType) => void;+ /** Sets the language of tag `index`, or clears it with null. */+ onSetLanguage: (index: number, lang: string | null) => void;+ /** Tags the characters selected inside the run as a Span in `lang`; null when they cannot take one. */+ onLanguageSelection: ((lang: string) => void) | null;+}++/** The language the selected text's blocks are read in, and a way to change it. */+export interface TextLanguageControl {+ /** The language the blocks share; undefined when they differ. */+ language: TextLanguage | undefined;+ onSet: (lang: string | null) => void;}/**@@ -50,6 +67,13 @@ export function useTextAccessibility() {// One memo over the pages: a retag changes no snapshot of the run, only// republishes them.+ const languageTargets = useMemo(+ () =>+ store.document+ ? textLanguageTargets(store.document, state, selection)+ : null,+ [store, state, selection],+ );const { run, tag, inner, newTagTypes } = useMemo(() => {const doc = store.document;const selected =@@ -155,6 +179,40 @@ export function useTextAccessibility([store, run, selection.textRange],);+ const setInnerLanguage = useCallback(+ (index: number, lang: string | null) => {+ const picked = inner[index];+ if (!run || !picked) return;+ store.dispatch(+ new SetInnerLanguageCommand({+ pageIndex: run.pageIndex,+ key: picked.key,+ lang,+ }),+ );+ },+ [store, run, inner],+ );++ const spansSelection = newTagTypes?.includes("Span") ?? false;+ const setSelectionLanguage = useCallback(+ (lang: string) => {+ const range = selection.textRange;+ if (!run || !range) return;+ store.dispatch(+ new TagTextRangeCommand({+ pageIndex: run.pageIndex,+ runId: run.id,+ ...range,+ as: "Span",+ lang,+ }),+ );+ store.selection.setTextRange(run.id, null);+ },+ [store, run, selection.textRange],+ );+const innerControl = useMemo((): InnerTagsControl => ({tags: inner,@@ -163,6 +221,8 @@ export function useTextAccessibility(onSet: setInnerTag,newTagTypes,onTagSelection: tagSelectedText,+ onSetLanguage: setInnerLanguage,+ onLanguageSelection: spansSelection ? setSelectionLanguage : null,}),[inner,@@ -171,10 +231,63 @@ export function useTextAccessibility(setInnerTag,newTagTypes,tagSelectedText,+ setInnerLanguage,+ spansSelection,+ setSelectionLanguage,],);- return { tag, setTag, inner: innerControl };+ const language = useMemo((): TextLanguageControl | null => {+ const doc = store.document;+ if (!doc || !languageTargets) return null;+ const [first, ...rest] = languageTargets.map(({ pageIndex, mcid }) =>+ doc.textLanguage(pageIndex, mcid),+ );+ const shared = rest.every(+ (l) => l?.own === first?.own && l?.inherited === first?.inherited,+ );+ return {+ language: shared && first ? first : undefined,+ onSet: (lang) =>+ store.dispatch(+ new SetTextLanguageCommand({ targets: languageTargets, lang }),+ ),+ };+ // state.pages: a language change republishes the pages, not the targets.+ }, [store, languageTargets, state.pages]);++ return { tag, setTag, inner: innerControl, language };+}++/**+ * The text the selection's runs are tagged as, for setting their blocks'+ * language; null unless only runs are selected and every one can take one.+ */+function textLanguageTargets(+ doc: EditorDocument,+ state: EditorViewState,+ selection: SelectionState,+): LanguageTarget[] | null {+ if (+ !ACCESSIBILITY_EDITING ||+ selection.runIds.length === 0 ||+ selection.imageIds.length > 0 ||+ selection.shapeIds.length > 0+ ) {+ return null;+ }+ const ids = new Set(selection.runIds);+ const runs = state.pages+ .flatMap((page) => page.runs)+ .filter((r) => ids.has(r.id));+ const targets = runs.flatMap((r) =>+ r.mcid !== undefined &&+ !r.inForm &&+ doc.structure(r.pageIndex).cannotSetLanguage(r.mcid) === null+ ? [{ pageIndex: r.pageIndex, mcid: r.mcid }]+ : [],+ );+ return targets.length > 0 && targets.length === ids.size ? targets : null;}function sameRange(a: TextRange, b: TextRange | null): boolean {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.tsindex 5ff808eaf8..6f77b5fa3d 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts@@ -529,6 +529,7 @@ export function useToolbarController(textTag: textA11y.tag,onSetTextTag: textA11y.setTag,innerTextTags: textA11y.inner,+ textLanguage: textA11y.language,selectionAllLocked,hasRunSelection: selection.runIds.length > 0,hasImageSelection: selection.imageIds.length > 0,diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.tsindex 6a91c3e4d5..dee72a2e99 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts@@ -8,9 +8,17 @@ import { Page } from "@editor/tools/pdfTextEditor/model/Page";import {PageStructure,isInlineType,+ type ReadOnlyReason,} from "@editor/tools/pdfTextEditor/model/PageStructure";+import {+ effectiveLanguage,+ type TextLanguage,+} from "@editor/tools/pdfTextEditor/model/languageTag";import type { StructureEdit } from "@editor/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits";-import { readPageStructure } from "@editor/tools/pdfTextEditor/pdfium/PdfiumStructureReader";+import {+ readPageStructure,+ readString,+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumStructureReader";import { carriedMcids } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";import {readFileStructure,@@ -54,6 +62,15 @@ export class EditorDocument {string,{ pageIndex: number; mcid: number; type: StructureType }>();+ /** Unsaved /Lang changes to the file's blocks, by block key, held here as retags are. */+ private readonly blockLangs = new Map<+ string,+ { pageIndex: number; mcid: number; lang: string | null }+ >();+ /** The catalog /Lang as the file has it; null when it has none. */+ private readonly fileDocumentLang: string | null;+ /** The session's catalog /Lang; undefined when unchanged. */+ private documentLangEdit: string | null | undefined;/** The file's own structure tree; null when only PDFium's view is available. */private readonly fileStructure: FileStructure | null;private readonly ownedFonts: Map<string, FontRef>;@@ -76,6 +93,7 @@ export class EditorDocument {this.docPtr = docPtr;this.openedBytes = openedBytes;this.fileStructure = fileStructure;+ this.fileDocumentLang = readCatalogLang(module, docPtr);this.pageCache = new Map();this.ownedFonts = new Map();this._disposed = false;@@ -270,6 +288,151 @@ export class EditorDocument {}}+ /** The language the document is read in, as the session has it; null when unknown. */+ documentLanguage(): string | null {+ return this.documentLangEdit === undefined+ ? this.fileDocumentLang+ : this.documentLangEdit;+ }++ /** Why the save cannot write the document's language, or null when it can. */+ cannotSetDocumentLanguage(): ReadOnlyReason | null {+ return this.encrypted() ? "encrypted" : null;+ }++ /** Set or, with null, remove the document's language. Throws when cannotSetDocumentLanguage refuses it. */+ setDocumentLanguage(lang: string | null): void {+ const blocker = this.cannotSetDocumentLanguage();+ if (blocker) throw new Error(`The document language is ${blocker}`);+ this.documentLangEdit = lang === this.fileDocumentLang ? undefined : lang;+ }++ /** The unsaved document language, for the save; undefined when unchanged. */+ documentLanguageEdit(): string | null | undefined {+ return this.documentLangEdit;+ }++ /**+ * Every language the document is read in as the session has it: its own+ * and each element's. An element's from the file is left out once the+ * session changes it; one PDFium alone reads is left out unless set here.+ */+ languagesInUse(): string[] {+ const edited = new Map<string, string | null>();+ for (const structure of this.structureCache.values()) {+ for (const [key, lang] of structure.ownLangEdits()) edited.set(key, lang);+ }+ for (const [key, { lang }] of this.blockLangs) edited.set(key, lang);+ const fromFile = [...(this.fileStructure?.languages ?? [])].map(+ ([key, { lang }]) => (edited.has(key) ? null : lang),+ );+ return [+ ...new Set(+ [this.documentLanguage(), ...fromFile, ...edited.values()].filter(+ (lang): lang is string => lang !== null,+ ),+ ),+ ];+ }++ /**+ * The language of the block the text `mcid` marks belongs to; null when no+ * element owns it.+ */+ textLanguage(pageIndex: number, mcid: number): TextLanguage | null {+ const block = this.structure(pageIndex).block(mcid);+ if (!block) return null;+ const structure = this.structure(pageIndex);+ // An added block's parent is chosen by the save, so it is read as the+ // document's.+ if (structure.addedBlockMcid(block.key) !== null) {+ return {+ own: structure.ownLang(block.key),+ inherited: this.documentLanguage(),+ };+ }+ const file = this.fileStructure?.languages.get(block.key);+ const edit = this.blockLangs.get(block.key);+ return {+ own: edit ? edit.lang : (file?.lang ?? null),+ inherited: this.inheritedLanguage(+ pageIndex,+ block.key,+ this.documentLanguage(),+ ),+ };+ }++ /**+ * The language of element `key`, one marking part of the text `mcid`+ * marks, read inside that text's block. Throws when the page has no such+ * element.+ */+ innerLanguage(pageIndex: number, mcid: number, key: string): TextLanguage {+ const block = this.textLanguage(pageIndex, mcid);+ return {+ own: this.structure(pageIndex).ownLang(key),+ inherited: this.inheritedLanguage(+ pageIndex,+ key,+ block ? effectiveLanguage(block) : this.documentLanguage(),+ ),+ };+ }++ private inheritedLanguage(+ pageIndex: number,+ key: string,+ fallback: string | null,+ ): string | null {+ const languages = this.fileStructure?.languages;+ const element = languages?.get(key);+ if (!languages || !element) return fallback;+ const edits = this.structure(pageIndex).ownLangEdits();+ const seen = new Set([key]);+ let parent = element.parent;+ while (parent !== null && !seen.has(parent)) {+ seen.add(parent);+ const ancestor = languages.get(parent);+ if (!ancestor) break;+ const blockEdit = this.blockLangs.get(parent);+ const lang = blockEdit+ ? blockEdit.lang+ : edits.has(parent)+ ? edits.get(parent)!+ : ancestor.lang;+ if (lang !== null) return lang;+ parent = ancestor.parent;+ }+ return this.documentLanguage();+ }++ /**+ * Set or, with null, remove the /Lang of the block the text `mcid` marks+ * belongs to. Throws when cannotRetag refuses the block, or the page's+ * save cannot write it.+ */+ setTextLanguage(pageIndex: number, mcid: number, lang: string | null): void {+ const structure = this.structure(pageIndex);+ const blocker = structure.cannotSetLanguage(mcid);+ if (blocker) {+ throw new Error(`MCID ${mcid} cannot take a language: ${blocker}`);+ }+ const block = structure.block(mcid)!;+ if (structure.addedBlockMcid(block.key) !== null) {+ structure.setOwnLang(block.key, lang);+ return;+ }+ const fileLang = this.fileStructure?.languages.get(block.key)?.lang ?? null;+ if (lang === fileLang) {+ this.blockLangs.delete(block.key);+ } else {+ // The save climbs from the element owning this to the same block.+ const address = structure.fileMcid(mcid)!;+ this.blockLangs.set(block.key, { pageIndex, mcid: address, lang });+ }+ }+/** True when the catalog marks the file as tagged (ISO 32000-1 14.7.1). */isTagged(): boolean {try {@@ -298,6 +461,14 @@ export class EditorDocument {decorative: false,}),);+ const blockLangs = [...this.blockLangs.values()].map(+ ({ pageIndex, mcid, lang }) => ({+ pageIndex,+ mcid,+ blockLang: lang,+ decorative: false,+ }),+ );return [...[...this.structureCache].flatMap(([pageIndex, structure]) => [...structure.pendingEdits().map((edit) => ({ pageIndex, ...edit })),@@ -307,10 +478,17 @@ export class EditorDocument {ownType: type,decorative: false,})),+ ...structure.langEdits().map(({ mcid, lang }) => ({+ pageIndex,+ mcid,+ lang,+ decorative: false,+ })),...this.addedElementEdits(pageIndex, structure),...this.cutEdits(pageIndex, structure),]),...retags,+ ...blockLangs,];}@@ -338,6 +516,7 @@ export class EditorDocument {pageIndex,mcid: element.mcid,alt: element.alt,+ lang: element.lang,decorative: false,newElement: { type: element.type, after },},@@ -357,7 +536,7 @@ export class EditorDocument {const cuts = structure.cutElements();if (!page || cuts.length === 0) return [];const carried = carriedMcids(this.module, page.pagePtr);- return cuts.flatMap(({ mcid, type, alt, cut }) => {+ return cuts.flatMap(({ mcid, type, alt, lang, cut }) => {if (!carried.has(mcid)) return [];const kept = (part: number | null) =>part !== null && carried.has(part) ? part : null;@@ -368,6 +547,7 @@ export class EditorDocument {pageIndex,mcid,alt,+ lang,decorative: false,cut: { type, from: cut.from, before, after },},@@ -429,6 +609,18 @@ export class EditorDocument {}}+/** The catalog /Lang; null when absent, empty, or unreadable. */+function readCatalogLang(+ module: WrappedPdfiumModule,+ docPtr: number,+): string | null {+ try {+ return readString(module, docPtr, module.FPDFCatalog_GetLanguage) || null;+ } catch {+ return null;+ }+}+interface OutlineBlock {key: string;/** Null for an untyped block. */diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.tsindex 566d0d4b00..91c268151e 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/PageStructure.ts@@ -9,6 +9,8 @@ export interface StructureElement extends StructureRole {key: string;alt: string | null;actualText: string | null;+ /** Its own /Lang, as the file has it; null for none. */+ lang: string | null;/*** The MCIDs the element owns on this page. The PDFium fallback cannot tell* pages apart, so there it can also list other pages' MCIDs.@@ -219,6 +221,8 @@ export interface CutElement {/** Null once removed: the save gives the text back to the element it was cut from. */type: StructureType | null;alt: string | null;+ /** Null to read it in the language of the element it was cut from. */+ lang: string | null;cut: ContentCut;}@@ -242,6 +246,15 @@ export interface AddedElement {type: StructureType;/** The /Alt to save; null for none. */alt: string | null;+ /** The /Lang to save; null for none. */+ lang: string | null;+}++/** A change to the /Lang of one of the file's elements marking part of a block's text. */+export interface ElementLanguageEdit {+ mcid: number;+ /** Null removes it. */+ lang: string | null;}/**@@ -271,6 +284,12 @@ export class PageStructure {* block owns no content of its own on the page to stand for it.*/private readonly standIns = new Map<string, StructureElement>();+ /**+ * The session's /Lang for elements by key: the file's inner elements and+ * the elements it adds. A file block's is held by the document, since a+ * block can span pages.+ */+ private readonly langs = new Map<string, string | null>();/** Why the save cannot write descriptions for this page, or null when it can. */readonly readOnly: ReadOnlyReason | null;@@ -328,6 +347,16 @@ export class PageStructure {return null;}+ /**+ * Why the block the text `mcid` marks belongs to cannot take a language,+ * or null when it can. Any block can: a list item or table cell in another+ * language is as common as a paragraph.+ */+ cannotSetLanguage(mcid: number): RetagBlocker | null {+ if (!this.element(mcid)) return "untagged";+ return this.readOnly;+ }+/** Why the content `mcid` marks cannot take a description, or null when it can. */cannotDescribe(mcid: number): DescriptionBlocker | null {const el = this.element(mcid);@@ -473,6 +502,7 @@ export class PageStructure {type,alt: null,actualText: null,+ lang: null,mcids: [mcid],onlyMarkedContent: true,key,@@ -483,12 +513,13 @@ export class PageStructure {return element;}- /** Drop an added element, its description, and the cut it was made by. */+ /** Drop an added element, its description and language, and the cut it was made by. */removeElement(mcid: number): void {const element = this.added.get(mcid);if (!element && !this.cuts.has(mcid)) return;this.added.delete(mcid);this.byMcid.delete(mcid);+ this.langs.delete(addedKey(mcid));if (element) this.edits.delete(element);const cut = this.cuts.get(mcid)?.cut;this.cuts.delete(mcid);@@ -508,6 +539,7 @@ export class PageStructure {mcid,type: this.added.get(mcid)?.type ?? null,alt: this.alt(mcid),+ lang: this.langs.get(addedKey(mcid)) ?? null,cut,}));}@@ -626,6 +658,7 @@ export class PageStructure {...el.block,alt: null,actualText: null,+ lang: null,mcids: el.mcids,onlyMarkedContent: true,block: el.block,@@ -635,7 +668,56 @@ export class PageStructure {}private addedElement(mcid: number): AddedElement {- return { mcid, type: this.added.get(mcid)!.type, alt: this.alt(mcid) };+ return {+ mcid,+ type: this.added.get(mcid)!.type,+ alt: this.alt(mcid),+ lang: this.langs.get(addedKey(mcid)) ?? null,+ };+ }++ /**+ * The /Lang element `key` has as the session has it: one marking part of a+ * block's text, or one the session added. Throws when the page has no such+ * element.+ */+ ownLang(key: string): string | null {+ if (this.langs.has(key)) return this.langs.get(key)!;+ if (this.addedMcid(key) !== null) return null;+ return this.fileElement(key).lang;+ }++ /**+ * Set or, with null, remove element `key`'s /Lang. Throws as ownLang does,+ * and for a page whose save cannot write it.+ */+ setOwnLang(key: string, lang: string | null): void {+ if (this.readOnly) throw new Error(`The page is ${this.readOnly}`);+ const added = this.addedMcid(key) !== null;+ if (!added && lang === this.fileElement(key).lang) this.langs.delete(key);+ else this.langs.set(key, lang);+ }++ /** The /Lang the session set, by element key, over the file's. */+ ownLangEdits(): ReadonlyMap<string, string | null> {+ return this.langs;+ }++ /** Changes to the /Lang of the file's elements, but those the session removed, for the save. */+ langEdits(): ElementLanguageEdit[] {+ return this.elements.flatMap((el) =>+ this.langs.has(el.key) && this.innerChanges.get(el) !== null+ ? [{ mcid: el.mcids[0], lang: this.langs.get(el.key)! }]+ : [],+ );+ }++ /** The MCID of the element the session added as `key`, cut or not; null for the file's. */+ private addedMcid(key: string): number | null {+ for (const mcid of [...this.added.keys(), ...this.cuts.keys()]) {+ if (addedKey(mcid) === key) return mcid;+ }+ return null;}/** The MCID of the element the session added that is block `key`; null for a block the file has. */diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/languageTag.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/languageTag.tsnew file mode 100644index 0000000000..26db7596d1--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/languageTag.ts@@ -0,0 +1,44 @@+/**+ * Natural-language tags as /Lang holds them (ISO 32000-1 14.9.2): BCP 47+ * (RFC 5646), the tag a screen reader picks its voice and pronunciation by.+ */++// The syntax PDF/UA validators check every /Lang against (veraPDF PDF/UA-1+// rule 7.2-29, PDF/UA-2 8.4.4-2). It admits "" no more than a reader does.+const LANG_SYNTAX = /^[a-zA-Z]{1,8}(?:-[a-zA-Z0-9]{1,8})*$/;++/**+ * The tag in canonical form ("EN-ie" -> "en-IE"), or null when it is not a+ * well-formed BCP 47 tag. Well-formed only: a registered but unlikely tag+ * such as "en-FR" passes.+ */+export function canonicalLanguageTag(tag: string): string | null {+ const trimmed = tag.trim();+ if (!LANG_SYNTAX.test(trimmed)) return null;+ try {+ return Intl.getCanonicalLocales(trimmed)[0] ?? null;+ } catch {+ return null;+ }+}++/**+ * The tag in canonical form, or as given when it is not well-formed, so two+ * spellings of one tag compare equal while a malformed one is kept to show.+ */+export function comparableLanguageTag(tag: string): string {+ return canonicalLanguageTag(tag) ?? tag;+}++/** The language text is read in, and where that comes from. */+export interface TextLanguage {+ /** The tag set on the element itself, as the session has it; null when it sets none. */+ own: string | null;+ /** What the text is read in without `own`: an ancestor's tag, else the document's; null when unknown. */+ inherited: string | null;+}++/** The tag text is read in: its own, else the one it inherits; null when unknown. */+export function effectiveLanguage(language: TextLanguage): string | null {+ return language.own ?? language.inherited;+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addElements.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addElements.tsindex cab8468be5..83b5d7a345 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addElements.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/addElements.ts@@ -25,6 +25,8 @@ export interface NewElement {mcid: number;type: StructureType;alt: string | null;+ /** Its /Lang; null to read it in its parent's language. */+ lang: string | null;/*** The MCID of the content the element reads after: it goes after the* block holding that, or before the block holding the page's first tagged@@ -85,13 +87,12 @@ export async function addElements(continue;}bodies.set(place.parent, joined);- const alt =- element.alt === null ? "" : ` /Alt ${encodeTextString(element.alt)}`;const id = element.type === "Note" ? ` /ID ${noteId(num)}` : "";bodies.set(num,`<< /Type /StructElem /S /${element.type} /P ${indirectRef(pdf, place.parent)} ` +- `/Pg ${indirectRef(pdf, pageNum)} /K ${element.mcid}${alt}${id} >>`,+ `/Pg ${indirectRef(pdf, pageNum)} /K ${element.mcid}` ++ `${textEntry("Alt", element.alt)}${textEntry("Lang", element.lang)}${id} >>`,);while (slots.length < element.mcid) slots.push("null");slots[element.mcid] = `${num} 0 R`;@@ -99,6 +100,11 @@ export async function addElements(return failed;}+/** ` /Key (value)` for a new element's dictionary; empty for null. */+export function textEntry(key: string, value: string | null): string {+ return value === null ? "" : ` /${key} ${encodeTextString(value)}`;+}+/*** After the block holding MCID `after`; else before the block holding the* page's first tagged content; else last in the document's top element, for adiff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.tsindex f85d8a168f..771a394c83 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits.ts@@ -37,6 +37,10 @@ export interface StructureEdit {type?: StructureType;/** The new /S of the element itself; null removes it, its content joining its parent. */ownType?: StructureType | null;+ /** The new /Lang of the element itself; null removes it, absent leaves it. */+ lang?: string | null;+ /** As `lang`, for the block the element belongs to, as `type` is. */+ blockLang?: string | null;/** Turn the element's content into an artifact and drop the element, its /Alt with it. */decorative: boolean;/**@@ -119,7 +123,8 @@ export async function applyStructureEdits(unwraps.push({ edit, owner });continue;}- const target = edit.type ? nodes.blockOf(owner) : owner;+ const ofBlock = edit.type !== undefined || edit.blockLang !== undefined;+ const target = ofBlock ? nodes.blockOf(owner) : owner;const body = bodies.get(target) ?? pdf.objectBody(target);const updated = body === null ? null : edited(pdf, body, edit, target);if (updated === null) {@@ -152,6 +157,7 @@ export async function applyStructureEdits(...edit,type: edit.cut!.type,alt: edit.alt ?? null,+ lang: edit.lang ?? null,cut: edit.cut!,})),bodies,@@ -170,6 +176,7 @@ export async function applyStructureEdits(...edit,...edit.newElement!,alt: edit.alt ?? null,+ lang: edit.lang ?? null,})),bodies,parentTree,@@ -201,7 +208,7 @@ export async function applyStructureEdits(return out;}-/** The element's body with `edit`'s /Alt and /S applied; null when it is not a dictionary. */+/** The element's body with `edit`'s /Alt, /Lang and /S applied; null when it is not a dictionary. */function edited(pdf: RawPdf,body: string,@@ -211,10 +218,11 @@ function edited(let out: string | null = body;const type = edit.type ?? edit.ownType;if (edit.alt !== undefined) {- out =- edit.alt === null- ? removeDictEntry(out, "Alt")- : setDictEntry(out, "Alt", encodeTextString(edit.alt));+ out = withTextEntry(out, "Alt", edit.alt);+ }+ const lang = edit.blockLang !== undefined ? edit.blockLang : edit.lang;+ if (out !== null && lang !== undefined) {+ out = withTextEntry(out, "Lang", lang);}if (out !== null && type) {out = setDictEntry(out, "S", `/${type}`);@@ -225,6 +233,17 @@ function edited(return out;}+/** The body with text-string entry `key` set to `value`, or removed for null. */+function withTextEntry(+ body: string,+ key: string,+ value: string | null,+): string | null {+ return value === null+ ? removeDictEntry(body, key)+ : setDictEntry(body, key, encodeTextString(value));+}+/** The structure element's object number, or why it cannot be found. */function elementFor(pdf: RawPdf,diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/cutElements.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/cutElements.tsindex 25d3373805..4c2702d4c5 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/cutElements.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/cutElements.ts@@ -13,7 +13,10 @@ import {type ParentTreeWriter,type PageSites,} from "@editor/tools/pdfTextEditor/pdfdoc/markedContent";-import { noteId } from "@editor/tools/pdfTextEditor/pdfdoc/passes/addElements";+import {+ noteId,+ textEntry,+} from "@editor/tools/pdfTextEditor/pdfdoc/passes/addElements";import {indirectRef,referencedObject,@@ -35,6 +38,8 @@ export interface NewCut {/** Null for a cut the session removed. */type: StructureType | null;alt: string | null;+ /** Its /Lang; null to read it in the language of the element it was cut from. */+ lang: string | null;cut: ContentCut;}@@ -217,8 +222,11 @@ function splitOwner(return "the element it was cut from has no parent to split it in";}+ // A sibling no longer inherits the owner's language, so it takes the+ // owner's own: a heading cut from a French paragraph is still French.+ const ownerLang = pdf.resolve(ownerBody, "Lang");const num = unusedObjectNumber(pdf, bodies);- bodies.set(num, newElement(pdf, cut, num, parent, plan.pageNum));+ bodies.set(num, newElement(pdf, cut, num, parent, plan.pageNum, ownerLang));setSlot(slots, cut.mcid, num);const added = [indirectRef(pdf, num)];let kept = after;@@ -228,10 +236,11 @@ function splitOwner(if (reason) return reason;const page =plan.ownerPage === null ? "" : ` /Pg ${indirectRef(pdf, plan.ownerPage)}`;+ const lang = ownerLang === null ? "" : ` /Lang ${ownerLang.trim()}`;bodies.set(rest,`<< /Type /StructElem /S /${pdf.dictName(ownerBody, "S")} ` +- `/P ${indirectRef(pdf, parent)}${page} /K [${after.join(" ")}] >>`,+ `/P ${indirectRef(pdf, parent)}${page} /K [${after.join(" ")}]${lang} >>`,);added.push(indirectRef(pdf, rest));kept = before;@@ -261,6 +270,9 @@ function retagOwner(const kid = mcidKid(pdf, cut.mcid, plan.ownerPage, plan.pageNum);let body = setDictEntry(plan.ownerBody, "S", `/${cut.type}`);body = body && setDictEntry(body, "K", `[${kid}]`);+ if (body && cut.lang !== null) {+ body = setDictEntry(body, "Lang", encodeTextString(cut.lang));+ }if (body && cut.type === "Note" && !pdf.valueSpan(body, "ID")) {body = setDictEntry(body, "ID", noteId(plan.owner));}@@ -316,18 +328,25 @@ function kidPage(return pdf.dictRef(body, "Pg") ?? ownerPage;}+/** `ownerLang` is the serialised /Lang a split-off cut keeps when it has none of its own. */function newElement(pdf: RawPdf,- { type, mcid, alt }: TypedCut,+ { type, mcid, alt, lang }: TypedCut,num: number,parent: number,pageNum: number,+ ownerLang: string | null = null,): string {- const altEntry = alt === null ? "" : ` /Alt ${encodeTextString(alt)}`;const id = type === "Note" ? ` /ID ${noteId(num)}` : "";+ const langEntry =+ lang === null+ ? ownerLang === null+ ? ""+ : ` /Lang ${ownerLang.trim()}`+ : textEntry("Lang", lang);return (`<< /Type /StructElem /S /${type} /P ${indirectRef(pdf, parent)} ` +- `/Pg ${indirectRef(pdf, pageNum)} /K ${mcid}${altEntry}${id} >>`+ `/Pg ${indirectRef(pdf, pageNum)} /K ${mcid}${textEntry("Alt", alt)}${langEntry}${id} >>`);}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/setDocumentLanguage.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/setDocumentLanguage.tsnew file mode 100644index 0000000000..3c4dc5dded--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/setDocumentLanguage.ts@@ -0,0 +1,39 @@+import {+ RawPdf,+ removeDictEntry,+ setDictEntry,+} from "@editor/tools/pdfTextEditor/pdfdoc/raw";+import {+ appendRevision,+ plainObject,+} from "@editor/tools/pdfTextEditor/pdfdoc/revision";+import { encodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString";++/**+ * Set the catalog's /Lang, the language every text in the document is read+ * in unless an element or marked content says otherwise (ISO 32000-1+ * 14.9.2), as an appended revision; null removes it. Untagged files take it+ * too. Throws when the file cannot be read or extended, or is encrypted,+ * whose strings this cannot encrypt.+ */+export async function setDocumentLanguage(+ bytes: Uint8Array,+ lang: string | null,+): Promise<Uint8Array> {+ const pdf = await RawPdf.parse(bytes);+ if (!pdf) throw new Error("The file could not be read");+ if (pdf.encrypted) throw new Error("The file is encrypted");+ const catalog = pdf.objectBody(pdf.rootNum);+ const updated =+ catalog === null+ ? null+ : lang === null+ ? removeDictEntry(catalog, "Lang")+ : setDictEntry(catalog, "Lang", encodeTextString(lang));+ if (updated === null) throw new Error("The catalog is not a dictionary");+ const out = appendRevision(pdf, [+ { num: pdf.rootNum, body: plainObject(updated) },+ ]);+ if (!out) throw new Error("The file cannot be extended");+ return out;+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.tsindex c778f420c2..14e5e1f05f 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts@@ -33,6 +33,14 @@ export interface FileBlock extends StructureRole {mcids: number[];}+/** An element's /Lang, and its nearest ancestor's. */+export interface ElementLanguage {+ lang: string | null;+ inheritedLang: string | null;+ /** Parent element key; null at the top of the structure tree. */+ parent: string | null;+}+export interface FileStructure {/*** Every page with /StructParents, keyed by page index, its elements each@@ -44,6 +52,8 @@ export interface FileStructure {pages: Map<number, FilePageStructure>;/** Every block element, in the tree's reading order. */blocks: FileBlock[];+ /** By element key, for every element a page or block names. */+ languages: Map<string, ElementLanguage>;}/**@@ -95,10 +105,16 @@ export async function readFileStructure(slotCount: items.length,});});- return {- pages: byPage,- blocks: readBlocks(pdf, rootBody, nodeFor, byPage),- };+ const blocks = readBlocks(pdf, rootBody, nodeFor, byPage);+ const languages = new Map<string, ElementLanguage>();+ for (const [num, { lang, inheritedLang, parent }] of nodes.readNodes()) {+ languages.set(String(num), {+ lang,+ inheritedLang,+ parent: parent === null ? null : String(parent),+ });+ }+ return { pages: byPage, blocks, languages };}/** Block elements in the depth-first /K order a reader follows. */@@ -163,6 +179,7 @@ function readElement(key: String(num),alt: text("Alt"),actualText: text("ActualText"),+ lang: node.lang,onlyMarkedContent: ownsOnlyMarkedContent(pdf, body),};}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/structureNodes.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/structureNodes.tsindex d3a00343b6..7e67951bf3 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/structureNodes.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/structureNodes.ts@@ -8,11 +8,16 @@ import {type StructureType,} from "@editor/tools/pdfTextEditor/model/structureTypes";import type { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";+import { decodeTextString } from "@editor/tools/pdfTextEditor/pdfdoc/textString";export interface ElementNode extends StructureRole {block: StructureBlock;/** The parent element's object number; null at the top of the tree. */parent: number | null;+ /** Its own /Lang; null when it has none, or an empty one, which means unknown. */+ lang: string | null;+ /** The nearest ancestor's /Lang: what its content is read in without its own. */+ inheritedLang: string | null;}/**@@ -67,6 +72,8 @@ export class StructureNodes {...role,block: containingBlock({ key: String(num), ...role }, parent),parent: parent ? parentNum : null,+ lang: this.ownLang(body),+ inheritedLang: parent ? (parent.lang ?? parent.inheritedLang) : null,};this.nodes.set(num, node);return node;@@ -93,6 +100,16 @@ export class StructureNodes {}}+ /** Every element read so far, by object number. */+ *readNodes(): Generator<[number, ElementNode]> {+ for (const [num, node] of this.nodes) if (node) yield [num, node];+ }++ private ownLang(body: string): string | null {+ const value = this.pdf.resolve(body, "Lang");+ return (value === null ? null : decodeTextString(value.trim())) || null;+ }+/** Follow /RoleMap (ISO 32000-1 14.8.4) until a type it does not remap. */private applyRoleMap(type: string): string {let current = type;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumStructureReader.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumStructureReader.tsindex d07d8218c2..03ff9db42b 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumStructureReader.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumStructureReader.ts@@ -6,7 +6,7 @@ import {} from "@editor/tools/pdfTextEditor/model/PageStructure";import { structureRole } from "@editor/tools/pdfTextEditor/model/structureTypes";-type StringGetter = (el: number, buf: number, len: number) => number;+type StringGetter = (handle: number, buf: number, len: number) => number;/** Bound on tree depth: a cyclic /K would otherwise recurse forever. */const MAX_DEPTH = 64;@@ -44,6 +44,7 @@ export function readPageStructure(...role,alt: readString(m, el, m.FPDF_StructElement_GetAltText),actualText: readString(m, el, m.FPDF_StructElement_GetActualText),+ lang: readString(m, el, m.FPDF_StructElement_GetLang) || null,mcids,// PDFium does not expose the kids' kinds; the fallback is read-only anyway.onlyMarkedContent: false,@@ -68,17 +69,20 @@ export function readPageStructure(return out;}-/** Null when the entry is absent, which PDFium reports as length 0. */-function readString(+/**+ * A string PDFium copies out as UTF-16LE through a (handle, buffer, length)+ * getter. Null when the entry is absent, which PDFium reports as length 0.+ */+export function readString(m: WrappedPdfiumModule,- el: number,+ handle: number,get: StringGetter,): string | null {- const len = get(el, 0, 0);+ const len = get(handle, 0, 0);if (len <= 0) return null;const buf = m.pdfium.wasmExports.malloc(len);try {- get(el, buf, len);+ get(handle, buf, len);return readUtf16(m, buf, len);} finally {m.pdfium.wasmExports.free(buf);diff --git a/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts b/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.tsindex fc5b3e11b9..2705561eb4 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts@@ -67,6 +67,10 @@ export interface EditorViewState {pages: PageSnapshot[];/** Document-level dirty bit (any page dirty). */dirty: boolean;+ /** The catalog /Lang as the session has it; null when unknown. */+ documentLanguage: string | null;+ /** Every language the document is read in: its own and each element's. */+ languagesInUse: string[];/** Async lifecycle markers. */loading: boolean;/** True once the first page's bitmap has actually painted in PageView. */@@ -106,6 +110,8 @@ const INITIAL: EditorViewState = {pageCount: 0,pages: [],dirty: false,+ documentLanguage: null,+ languagesInUse: [],loading: false,firstPageRendered: false,progress: null,@@ -305,6 +311,8 @@ export class EditorStore {pageCount: doc.pageCount,pages: [],dirty: false,+ documentLanguage: doc.documentLanguage(),+ languagesInUse: doc.languagesInUse(),loading: false,firstPageRendered: false,error: null,@@ -564,8 +572,16 @@ export class EditorStore {/** Re-read the model into a fresh page-snapshot array and publish it. */resnapshot(): void {if (!this.doc) return;- let changed = false;const doc = this.doc;+ const documentLanguage = doc.documentLanguage();+ if (documentLanguage !== this.state.documentLanguage) {+ this.patch({ documentLanguage });+ }+ const languagesInUse = doc.languagesInUse();+ if (languagesInUse.join() !== this.state.languagesInUse.join()) {+ this.patch({ languagesInUse });+ }+ let changed = false;const pages: PageSnapshot[] = this.state.pages.map((p) => {const live = doc.page(p.pageIndex);if (live.revision === p.revision) return p;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.tsindex 82eb2e825c..da82de76d7 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts@@ -5,6 +5,7 @@ import {applyStructureEdits,} from "@editor/tools/pdfTextEditor/pdfdoc/passes/applyStructureEdits";import { repairStructure } from "@editor/tools/pdfTextEditor/pdfdoc/passes/repairStructure";+import { setDocumentLanguage } from "@editor/tools/pdfTextEditor/pdfdoc/passes/setDocumentLanguage";import { preserveShadings } from "@editor/tools/pdfTextEditor/pdfdoc/passes/preserveShadings";import { PdfiumSave } from "@editor/tools/pdfTextEditor/pdfium/PdfiumSave";import {@@ -21,6 +22,7 @@ export async function exportToBlob(filename: string;}> {const structureEdits = doc.structureEdits();+ const documentLanguage = doc.documentLanguageEdit();// A signed document is appended to rather than rewritten, so the bytes the// signature covers are still there and still verify for their revision.const incremental = documentIsSigned(doc);@@ -30,7 +32,7 @@ export async function exportToBlob(// starting from what we opened keeps the file byte-identical. Rewriting it// changed the bytes of 8 of this suite's 10 fixtures and inflated the small// ones by up to 35% - for no edit at all.- if (structureEdits.length === 0) {+ if (structureEdits.length === 0 && documentLanguage === undefined) {return {blob: pdfBlob(doc.openedBytes),filename: exportName(sourceName),@@ -47,15 +49,14 @@ export async function exportToBlob(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 },- );+ throw accessibilitySaveFailed(err);+ }+ if (documentLanguage !== undefined) {+ try {+ bytes = await setDocumentLanguage(bytes, documentLanguage);+ } catch (err) {+ throw accessibilitySaveFailed(err);+ }}// After the edits: when the content an element described was deleted, the@@ -83,6 +84,18 @@ export async function exportToBlob(return { blob: pdfBlob(bytes), filename: exportName(sourceName) };}+function accessibilitySaveFailed(cause: unknown): Error {+ // It names pages and MCIDs: for a bug report, not for the user.+ console.error(cause);+ return 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 },+ );+}+async function serializeEdits(doc: EditorDocument,incremental: boolean,diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/languageOptions.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/languageOptions.tsnew file mode 100644index 0000000000..1e3e2ab52f--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/languageOptions.ts@@ -0,0 +1,152 @@+import {+ isOptionsGroup,+ type ComboboxItem,+ type ComboboxParsedItem,+ type OptionsFilter,+} from "@mantine/core";+import {+ canonicalLanguageTag,+ comparableLanguageTag,+} from "@editor/tools/pdfTextEditor/model/languageTag";+import { getAllLanguageDefinitions } from "@editor/utils/languageMapping";++/**+ * Regional variants offered beside each language's own tag: only those that+ * change how text is read. RFC 5646 4.1 advises a region only then, and a+ * screen reader picks its voice by the language.+ */+const REGIONAL_TAGS: readonly string[] = [+ "en-AU",+ "en-CA",+ "en-GB",+ "en-IE",+ "en-NZ",+ "en-US",+ "en-ZA",+ "es-ES",+ "es-MX",+ "fr-BE",+ "fr-CA",+ "fr-CH",+ "de-AT",+ "de-CH",+ "pt-BR",+ "pt-PT",+ "zh-Hans",+ "zh-Hant",+];++/**+ * The languages offered for text, as BCP 47 tags: every language the app+ * can OCR, by its own tag, plus REGIONAL_TAGS. Shared with OCR so the app has+ * one list of the languages it supports.+ */+export const OFFERED_LANGUAGE_TAGS: readonly string[] = [+ ...new Set([+ ...getAllLanguageDefinitions().flatMap(({ browserCodes }) =>+ browserCodes.length > 0 ? [browserCodes[0]] : [],+ ),+ ...REGIONAL_TAGS,+ ]),+];++/** The tag's name in `uiLang` ("French", "English (Ireland)"); the tag itself where the browser has none. */+export function languageName(tag: string, uiLang: string): string {+ try {+ return new Intl.DisplayNames([uiLang], { type: "language" }).of(tag) ?? tag;+ } catch {+ return tag;+ }+}++export interface LanguageOption {+ tag: string;+ label: string;+}++export interface LanguageOptions {+ /** The languages in `inUse`, sorted by label. */+ inUse: LanguageOption[];+ /** Every other language offered, sorted by label. */+ others: LanguageOption[];+}++/**+ * The offered languages, split into those the document uses and the rest,+ * plus `current`, the file's own tag, and the tag `typed` names when either+ * is one the list lacks, so a language the list lacks can still be picked by+ * its code. Tags are compared in canonical form, so the options hold+ * `comparableLanguageTag(current)`, not `current`.+ */+export function languageOptions(+ current: string | null,+ uiLang: string,+ typed = "",+ inUse: readonly string[] = [],+): LanguageOptions {+ const used = inUse.map(comparableLanguageTag);+ const tags = new Set([+ ...OFFERED_LANGUAGE_TAGS,+ ...used,+ ...[+ current === null ? null : comparableLanguageTag(current),+ typedLanguageTag(typed),+ ].filter((tag): tag is string => tag !== null),+ ]);+ const sorted = (keep: (tag: string) => boolean) =>+ [...tags]+ .filter(keep)+ .map((tag) => ({ tag, label: optionLabel(tag, uiLang) }))+ .sort((a, b) => a.label.localeCompare(b.label, uiLang));+ return {+ inUse: sorted((tag) => used.includes(tag)),+ others: sorted((tag) => !used.includes(tag)),+ };+}++/**+ * The options a search shows: those whose label contains it, and those+ * whose tag starts with the code it names, so editing the code in a shown+ * "Spanish (es)" to "Spanish (es-MX)" finds Mexican Spanish.+ */+export const filterLanguages: OptionsFilter = ({ options, search }) => {+ const words = search.trim().toLowerCase();+ const code = searchedCode(search);+ // A deprecated code is offered as the tag it stands for ("iw" as "he").+ const codes = [code, canonicalLanguageTag(code) ?? ""]+ .filter((c) => c !== "")+ .map((c) => c.toLowerCase());+ const matches = ({ value, label }: ComboboxItem) =>+ label.toLowerCase().includes(words) ||+ codes.some((c) => value.toLowerCase().startsWith(c));+ return options.flatMap((option): ComboboxParsedItem[] => {+ if (!isOptionsGroup(option)) return matches(option) ? [option] : [];+ const items = option.items.filter(matches);+ return items.length > 0 ? [{ ...option, items }] : [];+ });+};++/**+ * The language code a search names: the one in an option label's+ * parentheses with anything typed after them ("Spanish (es)-MX" -> "es-MX"),+ * else the whole search.+ */+function searchedCode(search: string): string {+ const labelled = /\(([^()]*)\)\s*([^\s()]*)$/.exec(search.trim());+ return labelled ? labelled[1] + labelled[2] : search.trim();+}++// A primary language subtag of 5-8 letters is reserved for registration+// (RFC 5646 2.2.1) and none is registered, so "French" is well-formed but+// names no language. Typed codes must be ISO 639's 2 or 3 letters.+const TYPED_LANGUAGE_CODE = /^[a-z]{2,3}(?:-|$)/i;++function typedLanguageTag(typed: string): string | null {+ const code = searchedCode(typed);+ return TYPED_LANGUAGE_CODE.test(code) ? canonicalLanguageTag(code) : null;+}++function optionLabel(tag: string, uiLang: string): string {+ const name = languageName(tag, uiLang);+ return name === tag ? tag : `${name} (${tag})`;+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.tsindex 4b3b1e36e1..4a6a816a0c 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/textAccessibility.ts@@ -5,6 +5,7 @@ import type {RetagBlocker,} from "@editor/tools/pdfTextEditor/model/PageStructure";import type { StructureRole } from "@editor/tools/pdfTextEditor/model/structureTypes";+import type { TextLanguage } from "@editor/tools/pdfTextEditor/model/languageTag";import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";import { innermostMcid } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";import type { TextRunSnapshot } from "@editor/tools/pdfTextEditor/types";@@ -66,6 +67,9 @@ export interface InnerTag extends InnerOptions {start: number;end: number;role: StructureRole;+ language: TextLanguage;+ /** False when the save cannot write the page's tags. */+ languageEditable: boolean;}/** The run's inner tags in reading order, as the session has them. */@@ -84,7 +88,20 @@ export function innerTags(if (!role) return [];const options = structure.innerOptions(element.key);const text = run.text.slice(start, end);- return [{ key: element.key, text, start, end, role, ...options }];+ const language = doc.innerLanguage(run.pageIndex, run.mcid!, element.key);+ const languageEditable = structure.readOnly === null;+ return [+ {+ key: element.key,+ text,+ start,+ end,+ role,+ language,+ languageEditable,+ ...options,+ },+ ];},);}diff --git a/frontend/src/editor/core/ui/Select.tsx b/frontend/src/editor/core/ui/Select.tsxindex 30ad0ed70d..86a4a6bab3 100644--- a/frontend/src/editor/core/ui/Select.tsx+++ b/frontend/src/editor/core/ui/Select.tsx@@ -1,6 +1,7 @@import type React from "react";import {Select as MantineSelect,+ type OptionsFilter,type SelectProps as MantineSelectProps,} from "@mantine/core";import { useInputAria } from "@editor/ui/ariaForwarding";@@ -17,23 +18,38 @@ const SUI_INPUT_VARS = {"--input-height-md": "2.25rem",} as React.CSSProperties;+// On the input, not the wrapper: Mantine sets --input-color on the input itself.+const MUTED_INPUT = { color: "var(--c-text-muted)" };+export interface SelectOption {value: string;label: string;disabled?: boolean;}+/** Options listed under a heading. */+export interface SelectOptionGroup {+ group: string;+ options: SelectOption[];+}+export type SelectSize = "sm" | "md";export interface SelectProps {// Data- options: SelectOption[];+ options: SelectOption[] | SelectOptionGroup[];value?: string | null;onChange?: (value: string | null) => void;defaultValue?: string;// Behavioursearchable?: boolean;+ /** Called with the text typed into a searchable select. */+ onSearchChange?: (search: string) => void;+ /** Which options a search shows; by default those whose label contains it. */+ filter?: OptionsFilter;+ /** False keeps picking the selected option from clearing it. */+ allowDeselect?: boolean;clearable?: boolean;placeholder?: string;nothingFoundMessage?: React.ReactNode;@@ -58,6 +74,8 @@ export interface SelectProps {// SUI — invalid applies error styling; FormField renders the message itself.inputSize?: SelectSize;invalid?: boolean;+ /** Shows the value in the muted text colour, for a value the field has by default. */+ muted?: boolean;}type PassthroughProps = Omit<@@ -67,6 +85,9 @@ type PassthroughProps = Omit<| "onChange"| "defaultValue"| "searchable"+ | "onSearchChange"+ | "filter"+ | "allowDeselect"| "clearable"| "placeholder"| "nothingFoundMessage"@@ -95,11 +116,15 @@ type PassthroughProps = Omit<export function Select({inputSize = "md",invalid,+ muted,options,value,onChange,defaultValue,searchable,+ onSearchChange,+ filter,+ allowDeselect,clearable,placeholder,nothingFoundMessage,@@ -123,6 +148,9 @@ export function Select({onChange,defaultValue,searchable,+ onSearchChange,+ filter,+ allowDeselect,clearable,placeholder,nothingFoundMessage,@@ -142,7 +170,11 @@ export function Select({return (<MantineSelect- data={options}+ data={options.map((option) =>+ "group" in option+ ? { group: option.group, items: option.options }+ : option,+ )}size={inputSize}// Boolean error applies invalid styling without rendering Mantine's own// message element — FormField owns the visible error text.@@ -154,7 +186,10 @@ export function Select({wrapper: "sui-mantine-wrapper",dropdown: "sui-mantine-dropdown",}}- styles={{ wrapper: SUI_INPUT_VARS }}+ styles={{+ wrapper: SUI_INPUT_VARS,+ input: muted ? MUTED_INPUT : undefined,+ }}{...passthroughProps}/>);