#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
Add a Check PDF accessibility tool (#8863)
EthanHealy0110f420d4266c
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ua/AccessibilityIssue.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ua/AccessibilityIssue.javaindex 0c2a86ad99..2a2f5caa3d 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ua/AccessibilityIssue.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ua/AccessibilityIssue.java@@ -1,5 +1,7 @@package stirling.software.proprietary.model.api.ua;+import java.util.List;+import io.swagger.v3.oas.annotations.media.Schema;import lombok.Data;@@ -35,4 +37,32 @@ public class AccessibilityIssue {@Schema(description = "True when the converter can fix this without human input")private boolean autoFixable;++ @Schema(description = "The validator's message for the first occurrence, with its arguments")+ private String errorMessage;++ @Schema(description = "The validator's rule categories, e.g. structure, font, alt-text")+ private List<String> tags = List.of();++ @Schema(description = "The validator's object type the rule applies to, e.g. SEFigure")+ private String object;++ @Schema(description = "The validator's test expression, for support and debugging")+ private String test;++ @Schema(description = "Clauses of other standards the rule cites, e.g. ISO 32000-1:2008 14.7")+ private List<String> references = List.of();++ @Schema(+ description =+ "One-based pages the issue occurs on, from the first 100 occurrences the"+ + " validator keeps; empty when it recorded no page, as for"+ + " document-level rules and tag-tree elements. See pagesComplete.")+ private List<Integer> pages = List.of();++ @Schema(+ description =+ "False when the issue occurs more often than the validator kept, so pages"+ + " lists only some of the pages it occurs on")+ private boolean pagesComplete = true;}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ua/AccessibilityReport.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ua/AccessibilityReport.javaindex bc810635d1..c08f7ee02a 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ua/AccessibilityReport.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ua/AccessibilityReport.java@@ -26,6 +26,13 @@ public class AccessibilityReport {@Schema(description = "Whether every automated check passed")private boolean passesAutomatedChecks;+ @Schema(+ description =+ "Why the validator could not run, or null when it did. When set, issues and"+ + " checks describe that failure rather than the document, so no"+ + " score or pass/fail can be drawn from them.")+ private String validationError;+@Schema(description = "Automated checks that failed, grouped by rule")private List<AccessibilityIssue> issues = List.of();@@ -48,6 +55,22 @@ public class AccessibilityReport {@Schema(description = "Document-level facts that drive most failures")private Summary summary = new Summary();+ @Schema(description = "How many automated checks ran and how many failed")+ private Checks checks = new Checks();++ @Data+ @Schema(+ description =+ "Check counts from the validator. A check is one rule applied to one object, so"+ + " the counts scale with document size; rules count each rule once.")+ public static class Checks {+ private int total;+ private int failed;+ private int passed;+ private int rulesInProfile;+ private int rulesFailed;+ }+@Data@Schema(description = "Quick document-level facts")public static class Summary {diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ua/UaValidationResult.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ua/UaValidationResult.javaindex 5e494c35be..ff18f67d4b 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ua/UaValidationResult.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ua/UaValidationResult.java@@ -5,12 +5,18 @@ import java.util.List;import io.swagger.v3.oas.annotations.media.Schema;/**- * Outcome of validating against one PDF/UA profile. compliant means every automated check passed,- * which is not the same as usable by assistive technology; totalFailures is ungrouped.+ * One PDF/UA validation; compliant means every automated check passed, not that the file is usable.+ * validationError is set when veraPDF could not run, and then the counts and issues say nothing.*/@Schema(description = "Result of validating a document against a PDF/UA profile")public record UaValidationResult(- String profile, boolean compliant, List<AccessibilityIssue> issues, int totalFailures) {+ String profile,+ boolean compliant,+ List<AccessibilityIssue> issues,+ int totalFailures,+ int totalChecks,+ int rulesInProfile,+ String validationError) {public boolean hasIssues() {return !issues.isEmpty();diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolKeyRegistry.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolKeyRegistry.javaindex c03f0c3c46..a3e6c29342 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolKeyRegistry.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolKeyRegistry.java@@ -66,6 +66,7 @@ public class ToolKeyRegistry {"changeMetadata","overlayPdfs","getPdfInfo",+ "checkAccessibility","validateSignature","timestampPdf","replaceColor",diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/ua/AccessibilityAuditService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/ua/AccessibilityAuditService.javaindex 869d489a04..071ff7c14b 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/ua/AccessibilityAuditService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/ua/AccessibilityAuditService.java@@ -61,7 +61,9 @@ public class AccessibilityAuditService {UaValidationResult validation = validationService.validate(pdfBytes, profile);report.setIssues(validation.issues());report.setPassesAutomatedChecks(validation.compliant());+ report.setValidationError(validation.validationError());report.setHumanChecks(HUMAN_CHECKS);+ report.setChecks(checksOf(validation));int fixable = 0;int needsInput = 0;@@ -84,6 +86,16 @@ public class AccessibilityAuditService {return report;}+ private static AccessibilityReport.Checks checksOf(UaValidationResult validation) {+ AccessibilityReport.Checks checks = new AccessibilityReport.Checks();+ checks.setTotal(validation.totalChecks());+ checks.setFailed(validation.totalFailures());+ checks.setPassed(Math.max(0, validation.totalChecks() - validation.totalFailures()));+ checks.setRulesInProfile(validation.rulesInProfile());+ checks.setRulesFailed(validation.issues().size());+ return checks;+ }+/*** Rejects before the expensive pass. An unreadable file is left to the report itself to say.*/diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/ua/PdfUaValidationService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/ua/PdfUaValidationService.javaindex 18d9fcaee7..e79f597a8a 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/ua/PdfUaValidationService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/ua/PdfUaValidationService.java@@ -5,6 +5,10 @@ import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;+import java.util.Set;+import java.util.TreeSet;+import java.util.regex.Matcher;+import java.util.regex.Pattern;import org.springframework.stereotype.Service;import org.verapdf.gf.foundry.VeraGreenfieldFoundryProvider;@@ -14,6 +18,10 @@ import org.verapdf.pdfa.PDFAValidator;import org.verapdf.pdfa.flavours.PDFAFlavour;import org.verapdf.pdfa.results.TestAssertion;import org.verapdf.pdfa.results.ValidationResult;+import org.verapdf.pdfa.validation.profiles.Reference;+import org.verapdf.pdfa.validation.profiles.Rule;+import org.verapdf.pdfa.validation.profiles.RuleId;+import org.verapdf.pdfa.validation.profiles.ValidationProfile;import jakarta.annotation.PostConstruct;@@ -34,6 +42,15 @@ public class PdfUaValidationService {/** Plain-English text and remediability for the clauses users actually hit. */private static final Map<String, ClauseInfo> CLAUSES = buildClauseTable();+ /**+ * Failures kept per rule, the sample pages come from; totals stay exact. -1 would keep 10,000+ * in all, letting the first rules checked crowd out the rest.+ */+ private static final int MAX_FAILURES_KEPT_PER_RULE = 100;++ /** veraPDF locations name a page as {@code pages[n]}, zero-based, in the object context. */+ private static final Pattern PAGE_IN_CONTEXT = Pattern.compile("pages\\[(\\d+)\\]");+record ClauseInfo(String message, boolean autoFixable) {}@PostConstruct@@ -51,7 +68,10 @@ public class PdfUaValidationService {Foundries.defaultInstance().createParser(new ByteArrayInputStream(pdfBytes), flavour)) {- PDFAValidator validator = Foundries.defaultInstance().createValidator(flavour, false);+ PDFAValidator validator =+ Foundries.defaultInstance()+ .createValidator(+ flavour, MAX_FAILURES_KEPT_PER_RULE, false, true, false);ValidationResult result = validator.validate(parser);return toResult(profile, result);@@ -61,7 +81,8 @@ public class PdfUaValidationService {issue.setMessage("Validation could not run: " + e.getMessage());issue.setSeverity("error");issue.setClause("n/a");- return new UaValidationResult(profile.displayName(), false, List.of(issue), 0);+ return new UaValidationResult(+ profile.displayName(), false, List.of(issue), 0, 0, 0, issue.getMessage());}}@@ -101,6 +122,9 @@ public class PdfUaValidationService {*/private static UaValidationResult toResult(PdfUaProfile profile, ValidationResult result) {Map<String, AccessibilityIssue> grouped = new LinkedHashMap<>();+ Map<String, Set<Integer>> pagesByKey = new LinkedHashMap<>();+ Map<String, RuleId> ruleIdByKey = new LinkedHashMap<>();+ ValidationProfile validationProfile = result.getValidationProfile();int total = 0;for (TestAssertion assertion : result.getTestAssertions()) {@@ -112,6 +136,9 @@ public class PdfUaValidationService {assertion.getRuleId() != null ? assertion.getRuleId().getClause() : "unknown";int test = assertion.getRuleId() != null ? assertion.getRuleId().getTestNumber() : 0;String key = clause + "-" + test;+ if (assertion.getRuleId() != null) {+ ruleIdByKey.putIfAbsent(key, assertion.getRuleId());+ }AccessibilityIssue issue =grouped.computeIfAbsent(@@ -127,17 +154,96 @@ public class PdfUaValidationService {created.setTechnicalMessage(assertion.getMessage());created.setAutoFixable(info != null && info.autoFixable());created.setSpecification(profile.displayName());+ created.setErrorMessage(assertion.getErrorMessage());+ describeRule(created, validationProfile, assertion);return created;});issue.setOccurrences(issue.getOccurrences() + 1);if (issue.getLocation() == null && assertion.getLocation() != null) {issue.setLocation(assertion.getLocation().toString());}+ Integer page = pageOf(assertion);+ if (page != null) {+ pagesByKey.computeIfAbsent(key, k -> new TreeSet<>()).add(page);+ }}+ pagesByKey.forEach((key, pages) -> grouped.get(key).setPages(List.copyOf(pages)));+ total = applyFullFailureCounts(grouped, ruleIdByKey, result.getFailedChecks(), total);List<AccessibilityIssue> issues = new ArrayList<>(grouped.values());+ int rulesInProfile = validationProfile != null ? validationProfile.getRules().size() : 0;return new UaValidationResult(- profile.displayName(), result.isCompliant() && total == 0, issues, total);+ profile.displayName(),+ result.isCompliant() && total == 0,+ issues,+ total,+ result.getTotalAssertions(),+ rulesInProfile,+ null);+ }++ /**+ * Swaps logged counts for veraPDF's per-rule totals and marks capped page lists incomplete,+ * since it logs at most 100 assertions per rule. Returns the corrected total.+ */+ static int applyFullFailureCounts(+ Map<String, AccessibilityIssue> grouped,+ Map<String, RuleId> ruleIdByKey,+ Map<RuleId, Integer> failedChecks,+ int loggedTotal) {+ if (failedChecks == null || failedChecks.isEmpty()) {+ return loggedTotal;+ }+ int total = 0;+ for (Map.Entry<String, AccessibilityIssue> entry : grouped.entrySet()) {+ AccessibilityIssue issue = entry.getValue();+ RuleId ruleId = ruleIdByKey.get(entry.getKey());+ Integer count = ruleId == null ? null : failedChecks.get(ruleId);+ if (count != null && count > issue.getOccurrences()) {+ issue.setOccurrences(count);+ issue.setPagesComplete(false);+ }+ total += issue.getOccurrences();+ }+ return total;+ }++ private static void describeRule(+ AccessibilityIssue issue,+ ValidationProfile validationProfile,+ TestAssertion assertion) {+ if (validationProfile == null || assertion.getRuleId() == null) {+ return;+ }+ Rule rule = validationProfile.getRuleByRuleId(assertion.getRuleId());+ if (rule == null) {+ return;+ }+ issue.setTags(rule.getTagsSet() != null ? List.copyOf(rule.getTagsSet()) : List.of());+ issue.setObject(rule.getObject());+ issue.setTest(rule.getTest());+ if (rule.getReferences() != null) {+ issue.setReferences(+ rule.getReferences().stream()+ .map(PdfUaValidationService::formatReference)+ .toList());+ }+ }++ private static String formatReference(Reference reference) {+ String clause = reference.getClause();+ return clause == null || clause.isBlank()+ ? reference.getSpecification()+ : reference.getSpecification() + " " + clause;+ }++ /** One-based page of an assertion, or null for a document-level one. */+ static Integer pageOf(TestAssertion assertion) {+ if (assertion.getLocation() == null || assertion.getLocation().getContext() == null) {+ return null;+ }+ Matcher matcher = PAGE_IN_CONTEXT.matcher(assertion.getLocation().getContext());+ return matcher.find() ? Integer.parseInt(matcher.group(1)) + 1 : null;}/**diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/ua/PdfUaServicesTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/ua/PdfUaServicesTest.javaindex 19ff7ba589..1e0027c208 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/ua/PdfUaServicesTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/ua/PdfUaServicesTest.java@@ -4,11 +4,15 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import java.io.ByteArrayOutputStream;import java.io.IOException;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;import org.apache.pdfbox.Loader;import org.apache.pdfbox.pdmodel.PDDocument;@@ -26,9 +30,15 @@ import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.Nested;import org.junit.jupiter.api.Test;+import org.verapdf.pdfa.flavours.PDFAFlavour;+import org.verapdf.pdfa.results.TestAssertion;+import org.verapdf.pdfa.results.ValidationResults;+import org.verapdf.pdfa.validation.profiles.Profiles;+import org.verapdf.pdfa.validation.profiles.RuleId;import stirling.software.common.service.CustomPDFDocumentFactory;import stirling.software.common.service.PdfMetadataService;+import stirling.software.proprietary.model.api.ua.AccessibilityIssue;import stirling.software.proprietary.model.api.ua.AccessibilityReport;import stirling.software.proprietary.model.api.ua.PdfUaConversionOutcome;import stirling.software.proprietary.model.api.ua.UaValidationResult;@@ -75,6 +85,38 @@ class PdfUaServicesTest {}}+ private static byte[] textOnEveryPage(int pages) throws IOException {+ try (PDDocument document = new PDDocument()) {+ PDType1Font font = new PDType1Font(Standard14Fonts.FontName.HELVETICA);+ for (int i = 0; i < pages; i++) {+ PDPage page = new PDPage(PDRectangle.A4);+ document.addPage(page);+ try (PDPageContentStream cs = new PDPageContentStream(document, page)) {+ cs.beginText();+ cs.setFont(font, 12);+ cs.newLineAtOffset(50, 700);+ cs.showText("Page " + (i + 1));+ cs.endText();+ }+ }+ ByteArrayOutputStream out = new ByteArrayOutputStream();+ document.save(out);+ return out.toByteArray();+ }+ }++ private static TestAssertion assertionAt(String context) {+ return ValidationResults.assertionFromValues(+ 0,+ Profiles.defaultRuleId(),+ TestAssertion.Status.FAILED,+ "",+ ValidationResults.locationFromValues("PDDocument", context),+ context,+ null,+ List.of());+ }+private static byte[] manyPages(int pages) throws IOException {try (PDDocument document = new PDDocument()) {for (int i = 0; i < pages; i++) {@@ -122,6 +164,69 @@ class PdfUaServicesTest {validation.validate("not a pdf".getBytes(), PdfUaProfile.UA1);assertFalse(result.compliant());assertFalse(result.issues().isEmpty());+ assertNotNull(result.validationError(), "a failed run must say it did not validate");+ }++ @Test+ @DisplayName("a run that completes carries no validation error")+ void completedRunHasNoValidationError() throws Exception {+ UaValidationResult result = validation.validate(unembeddedFontPdf(), PdfUaProfile.UA1);+ assertNull(result.validationError());+ }++ @Test+ @DisplayName("past the kept-failure cap, counts stay exact and pages become a sample")+ void countsEveryFailureBeyondTheCap() throws Exception {+ UaValidationResult result = validation.validate(textOnEveryPage(150), PdfUaProfile.UA1);+ AccessibilityIssue perPage =+ result.issues().stream()+ .filter(issue -> issue.getOccurrences() >= 150)+ .findFirst()+ .orElseThrow(() -> new AssertionError("no rule failed on every page"));+ assertTrue(perPage.getPages().size() <= 100, "pages come from the kept failures");+ assertFalse(perPage.isPagesComplete(), "a sampled page list must say so");+ assertEquals(+ result.totalFailures(),+ result.issues().stream().mapToInt(AccessibilityIssue::getOccurrences).sum());+ }++ @Test+ @DisplayName("a page in the object context is reported one-based")+ void pageOfReadsTheContext() {+ assertEquals(+ 3,+ PdfUaValidationService.pageOf(+ assertionAt(+ "root/document[0]/pages[2](7 0 obj PDPage)/contentStream[0]")));+ assertNull(+ PdfUaValidationService.pageOf(+ assertionAt(+ "root/document[0]/StructTreeRoot[0](3 0 obj PDStructTreeRoot)")));+ }++ @Test+ @DisplayName("veraPDF's own per-rule totals replace the capped logged counts")+ void fullCountsReplaceLoggedCounts() {+ RuleId capped =+ Profiles.ruleIdFromValues(PDFAFlavour.Specification.ISO_14289_1, "7.1", 3);+ AccessibilityIssue cappedIssue = new AccessibilityIssue();+ cappedIssue.setOccurrences(100);+ AccessibilityIssue unlisted = new AccessibilityIssue();+ unlisted.setOccurrences(4);+ Map<String, AccessibilityIssue> grouped = new LinkedHashMap<>();+ grouped.put("7.1-3", cappedIssue);+ grouped.put("n/a-0", unlisted);++ int total =+ PdfUaValidationService.applyFullFailureCounts(+ grouped, Map.of("7.1-3", capped), Map.of(capped, 250), 104);++ assertEquals(250, cappedIssue.getOccurrences());+ assertFalse(cappedIssue.isPagesComplete());+ assertEquals(+ 4, unlisted.getOccurrences(), "a rule veraPDF did not total keeps its count");+ assertTrue(unlisted.isPagesComplete());+ assertEquals(254, total);}@Test@@ -138,6 +243,20 @@ class PdfUaServicesTest {@DisplayName("auditing")class Auditing {+ @Test+ @DisplayName("a file the validator cannot read is reported as unchecked")+ void unreadableFileIsUnchecked() throws Exception {+ AccessibilityReport report = audit.audit("not a pdf".getBytes(), PdfUaProfile.UA1);+ assertNotNull(report.getValidationError());+ assertFalse(report.isPassesAutomatedChecks());+ }++ @Test+ @DisplayName("a validated file has no validation error")+ void validatedFileHasNoError() throws Exception {+ assertNull(audit.audit(unembeddedFontPdf(), PdfUaProfile.UA1).getValidationError());+ }+@Test@DisplayName("reports the document facts that drive most failures")void reportsSummary() throws Exception {diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.tomlindex 5529268bf8..865d7dddc3 100644--- a/frontend/public/locales/en-US/translation.toml+++ b/frontend/public/locales/en-US/translation.toml@@ -3270,6 +3270,248 @@ processing = "Processing ({{outcome}})..."unsupported_capability = "Unsupported capability: {{capability}}"usage_limit_reached = "You've reached your usage limit. Check your plan options to keep going."+[checkAccessibility]+aboutRow = "About {{label}}"+checking = "Checking..."+clauseRef = "{{profile}} §{{clauses}}"+download = "Download accessibility report"+fileFailed = "failed"+pickFile = "Show results for"+submit = "Check accessibility"++[checkAccessibility.category]+altText = "Alternative text"+fonts = "Fonts"+language = "Language"+links = "Links & annotations"+metadata = "Metadata & settings"+structure = "Tags & structure"++[checkAccessibility.categoryTip]+altText = "Images need a short text description for screen readers to read out instead."+fonts = "Fonts need to be in the file, with every character linked to real text, so the text can be read aloud and copied."+language = "Screen readers need to know the document's language to pronounce it correctly."+links = "Links, comments and form fields need tags and descriptions, and a tab order that follows the page."+metadata = "The title, PDF/UA declaration and other settings that assistive technology reads from the file."+structure = "Tags tell screen readers what each part of a page is, such as a heading, list or table, and the order to read it in."++[checkAccessibility.checks]+label = "{{passed}} of {{total}} checks passed"++[checkAccessibility.error]+download = "The accessibility report could not be created. Try again."+fileTitle = "This file could not be checked"+partial = "Some files could not be checked."++[checkAccessibility.facts]+declares = "Declares PDF/UA"+displaysTitle = "Shows its title"+fonts = "Fonts embedded"+language = "Declares a language"+notEncrypted = "Not encrypted"+tagged = "Tagged"+title = "Has a title"++[checkAccessibility.factTip]+declares = "The file's metadata says it follows PDF/UA."+displaysTitle = "PDF readers show the title, not the file name, when the file opens."+fonts = "Every font the text uses is included in the file."+language = "The file says which language its text is in."+notEncrypted = "The file isn't encrypted. Encryption can stop assistive technology reading it."+tagged = "The file has tags describing its structure. Without them, screen readers only get plain text."+title = "The file has a title in its metadata."++[checkAccessibility.figures]+summary_one = "{{count}} image needs a description (page {{pages}})"+summary_other = "{{count}} images need a description (pages {{pages}})"++[checkAccessibility.issue]+appliesTo = "Applies to"+clauseValue = "{{spec}} §{{clause}}, test {{test}}"+details = "Details"+instances_one = "{{count}} instance"+instances_other = "{{count}} instances"+onPages_one = "Page {{pages}}"+onPages_other = "Pages {{pages}}"+onPagesPartial_one = "Page {{pages}} (list may be incomplete)"+onPagesPartial_other = "Pages {{pages}} (list may be incomplete)"+pages = "Pages"+pagesPartialValue = "{{pages}} (only the first occurrences record a page, so this list may be incomplete)"+requirement = "Requirement"+rule = "Rule"+standard = "Standard"+where = "Where"++[checkAccessibility.manual]+clearAll = "Clear all"+done = "Done"+inProgress = "In progress"+markAllDone = "Mark all as done"+tip = "Things only a person can judge, such as reading order and whether image descriptions make sense. Tick each one once you've checked it, and your ticks go into the downloaded report."+title = "Manual checks"++[checkAccessibility.objects]+annotation = "An annotation"+bookmark = "A bookmark"+character = "A character in a font"+contentPiece = "A piece of page content"+document = "The document"+drawing = "A drawing"+figure = "A figure"+file = "The file itself"+font = "A font"+form = "The form"+formField = "A form field"+link = "A link"+markedContent = "Marked page content"+metadata = "The document metadata"+page = "A page"+properties = "The document properties"+tag = "A {{name}} tag"+tagTree = "The tag tree"+textPiece = "A piece of text"+translatedMetadata = "A metadata entry with translations"++[checkAccessibility.pdf]+continued = "{{name}} (continued)"+footer = "Checked with Stirling PDF"+page = "Page {{n}}"+title = "Accessibility report"++[checkAccessibility.result]+fail = "Fail"+failSummary = "Screen readers may not be able to read all of this document."+partial = "Partial"+partialSummary = "Screen readers can read this document, but some checks fail."+pass = "Pass"+passSummary = "Passes every automated PDF/UA check."++[checkAccessibility.rules]+annotationLanguage = "Comment or link text doesn't have a language set, so screen readers don't know which language to read it in. Set the document's language to fix this."+annotationNoDescription = "A comment, link or drawing has no text description, so screen readers have nothing to announce."+annotationNotTagged = "A comment or drawing isn't tagged as an annotation, so screen readers can't reach it in reading order."+artifactInsideTagged = "Something marked as decoration sits inside tagged content, so it is both read and skipped."+bookmarkLanguage = "The bookmarks don't have a language set, so screen readers don't know which language to read them in. Set the document's language to fix this."+conformancePrefix = "The PDF/UA declaration in the metadata uses the wrong prefix, so PDF readers may not recognise it."+contentLanguage = "The text doesn't have a language set, so screen readers don't know which language to read it in. Set the document's language to fix this."+customTagNotMapped = "A tag uses a custom name that isn't linked to a standard tag, so screen readers don't know what it is."+figureNoAlt = "An image is tagged as a figure but has no description, so screen reader users won't know what it shows."+fontMissingGlyphs = "An included font is missing some of the characters the document uses."+fontNotEmbedded = "A font isn't included in the file, so the text may look different, or be read differently, on another computer."+formFieldNotTagged = "A form field isn't tagged as part of a form, so screen readers may not find it."+genericHeading = "A heading uses the H tag, which has no level. PDF/UA-2 needs H1 to H6 so screen reader users can tell how headings nest."+glyphWidths = "A font's character widths in the file don't match the font itself, so text may be spaced wrongly."+headingSkipped = "Heading levels skip a step, for example from Heading 1 straight to Heading 3, which makes moving between headings confusing."+linkNoDescription = "A link has no description, so screen readers can only read out its address, or nothing."+linkNotTagged = "A link isn't tagged as a link, so screen readers won't announce it as one."+metadataLanguage = "The metadata, such as the title, doesn't have a language set, so screen readers don't know which language to read it in. Set the document's language to fix this."+noConformanceClaim = "The file doesn't say it follows PDF/UA. Its metadata needs a PDF/UA identification entry."+noDocumentTag = "The tags need a single Document tag at the top, with everything else inside it."+noLanguage = "The document doesn't say which language it is in, so screen readers may read it in the wrong language."+noMetadataStream = "The file has no XMP metadata, which is where PDF/UA keeps the document's title and conformance details."+noTags = "The file has no tags at all, so screen readers can't tell headings, paragraphs, lists or tables apart, or read them in the right order."+notdefGlyph = "The text uses a \"missing character\" placeholder, which shows as a blank or a box and can't be read aloud."+noteTag = "The file uses the Note tag, which PDF/UA-2 replaces with FENote for footnotes and endnotes."+noTitle = "The document has no title in its metadata."+notMarkedTagged = "The file isn't flagged as tagged, so assistive technology may ignore the tags it has."+notPdf2Tags = "PDF/UA-2 needs the tags a PDF 2.0 file uses. These look like PDF 1.7 tags, which usually means the file was tagged for PDF/UA-1."+noUnicode = "Some characters can't be turned into readable text, so screen readers and copy and paste may get them wrong."+replacementTextLanguage = "Some replacement text doesn't have a language set, so screen readers don't know which language to read it in. Set the document's language to fix this."+standardTagRemapped = "A standard tag is linked to a custom tag, so screen readers lose its meaning."+symbolicEncoding = "A symbol font carries an encoding it shouldn't, so its characters may come out as the wrong letters."+tabOrder = "A page with links or comments doesn't set its tab order to follow the document, so keyboard users may jump around the page."+taggedInsideArtifact = "Tagged content sits inside something marked as decoration, so screen readers may skip it."+titleNotDisplayed = "PDF readers will show the file name instead of the document's title. The file needs its \"display document title\" setting turned on."+untaggedContent = "Something on the page is neither tagged as content nor marked as decoration, so screen readers can't tell whether to read it. This is often a background image, header, footer or page number."++[checkAccessibility.ruleTitles]+annotationLanguage = "No language for comments or links"+annotationNoDescription = "Comment, link or drawing without a description"+annotationNotTagged = "Comment or drawing not tagged"+artifactInsideTagged = "Decoration inside tagged content"+bookmarkLanguage = "No language for bookmarks"+conformancePrefix = "PDF/UA declaration written incorrectly"+contentLanguage = "No language for text"+customTagNotMapped = "Custom tag with no standard meaning"+figureNoAlt = "Image without a description"+fontMissingGlyphs = "Font missing characters"+fontNotEmbedded = "Font not embedded"+formFieldNotTagged = "Form field not tagged"+genericHeading = "Heading without a level"+glyphWidths = "Font character widths don't match"+headingSkipped = "Heading level skipped"+linkNoDescription = "Link without a description"+linkNotTagged = "Link not tagged"+metadataLanguage = "No language for metadata"+noConformanceClaim = "Doesn't declare PDF/UA"+noDocumentTag = "Tags don't start with a Document tag"+noLanguage = "No document language"+noMetadataStream = "No XMP metadata"+noTags = "No tags"+notdefGlyph = "Missing-character placeholder used"+noteTag = "Uses the Note tag"+noTitle = "No document title"+notMarkedTagged = "Not flagged as tagged"+notPdf2Tags = "Tags aren't PDF 2.0 tags"+noUnicode = "Characters that can't be read as text"+replacementTextLanguage = "No language for replacement text"+standardTagRemapped = "Standard tag turned into a custom one"+symbolicEncoding = "Symbol font has the wrong encoding"+tabOrder = "Tab order doesn't follow the document"+taggedInsideArtifact = "Tagged content hidden as decoration"+titleNotDisplayed = "Title isn't shown when opened"+untaggedContent = "Content that isn't tagged"++[checkAccessibility.score]+issues_one = "{{count}} issue"+issues_other = "{{count}} issues"+noIssues = "No issues found"+subtitle_one = "{{profile}} - {{count}} page"+subtitle_other = "{{profile}} - {{count}} pages"++[checkAccessibility.sections]+breakdown = "Breakdown"++[checkAccessibility.status]+checking = "Checking {{current}} of {{total}}..."+complete = "Check complete"++[checkAccessibility.steps]+results = "Results"+standard = "Standard"++[checkAccessibility.tooltip.header]+title = "Which standard to check"++[checkAccessibility.tooltip.ua1]+text = "The first version of PDF/UA, published in 2012 as ISO 14289-1, for PDF 1.7 files."+title = "PDF/UA-1"++[checkAccessibility.tooltip.ua2]+text = "The newer version, published in 2024 as ISO 14289-2, for PDF 2.0 files. A PDF 1.7 file checked against it fails the rules that only apply to PDF 2.0."+title = "PDF/UA-2"++[checkAccessibility.where]+annotation = "Annotation {{n}}"+bookmarks = "Bookmarks"+character = "A character in {{font}}"+contentItem = "Content item {{n}}"+drawingStep = "Drawing step {{n}}"+embeddedGraphic = "Embedded graphic"+font = "Font {{name}}"+metadata = "Document metadata"+page = "Page {{n}}"+piece = "Piece {{n}}"+tag = "{{tag}} tag"+tagTree = "Tag tree"+wholeDocument = "Whole document"++[checkAccessibility.where.properties]+author = "Author"+description = "Description"+pdfUaPart = "PDF/UA part"+title = "Title"+[classification.families]correspondence = "Correspondence"education = "Education"@@ -5711,6 +5953,11 @@ desc = "Change document restrictions and permissions"tags = "permissions,restrictions,rights,access control,allow,deny,printing,copying,editing,modify permissions,security settings,user rights"title = "Change Permissions"+[home.checkAccessibility]+desc = "Score a PDF against PDF/UA and see what blocks screen readers, without changing it"+tags = "accessibility,a11y,PDF/UA,screen reader,WCAG,Section 508,veraPDF,tagged PDF,alt text,accessibility checker,accessibility report,compliance,UA"+title = "Check PDF accessibility"+[home.classify]desc = "Identify what kind of document this is and tag it."title = "Classify"diff --git a/frontend/public/og-metadata.json b/frontend/public/og-metadata.jsonindex f9b99d156f..84ffd60edf 100644--- a/frontend/public/og-metadata.json+++ b/frontend/public/og-metadata.json@@ -235,6 +235,11 @@"title": "PDF Info and Metadata Viewer - Stirling PDF","description": "Grabs any and all information possible on PDFs"},+ "checkAccessibility": {+ "image": "/og_images/home.png",+ "title": "Check PDF accessibility - Stirling PDF",+ "description": "Score a PDF against PDF/UA and see what blocks screen readers, without changing it"+ },"validateSignature": {"image": "/og_images/validate-pdf-signature.png","title": "Validate PDF Signature - Stirling PDF",@@ -823,6 +828,7 @@"/change-metadata": "changeMetadata","/overlay-pdfs": "overlayPdfs","/get-pdf-info": "getPdfInfo",+ "/check-accessibility": "checkAccessibility","/validate-signature": "validateSignature","/timestamp-pdf": "timestampPdf","/replace-color": "replaceColor",@@ -869,6 +875,7 @@"/auto-size-split-pdf": "split","/annotations": "annotate","/replace-color-pdf": "replaceColor",+ "/accessibility-report": "checkAccessibility","/show-js": "showJS","/pdf-organizer": "reorganizePages","/multi-page-layout": "pageLayout",@@ -970,6 +977,7 @@"/add-watermark": "/watermark","/auto-split-pdf": "/split","/auto-size-split-pdf": "/split",+ "/accessibility-report": "/check-accessibility","/pdf-organizer": "/reorganize-pages","/multi-page-layout": "/page-layout","/extract-page": "/extract-pages",diff --git a/frontend/public/og-metadata.saas.json b/frontend/public/og-metadata.saas.jsonindex f2f24b6773..f0b4862b0f 100644--- a/frontend/public/og-metadata.saas.json+++ b/frontend/public/og-metadata.saas.json@@ -236,6 +236,11 @@"title": "PDF Info and Metadata Viewer - Stirling PDF","description": "Grabs any and all information possible on PDFs"},+ "checkAccessibility": {+ "image": "/og_images/home.png",+ "title": "Check PDF accessibility - Stirling PDF",+ "description": "Score a PDF against PDF/UA and see what blocks screen readers, without changing it"+ },"validateSignature": {"image": "/og_images/validate-pdf-signature.png","title": "Validate PDF Signature - Stirling PDF",@@ -831,6 +836,7 @@"/change-metadata": "changeMetadata","/overlay-pdfs": "overlayPdfs","/get-pdf-info": "getPdfInfo",+ "/check-accessibility": "checkAccessibility","/validate-signature": "validateSignature","/timestamp-pdf": "timestampPdf","/replace-color": "replaceColor",@@ -877,6 +883,7 @@"/auto-size-split-pdf": "split","/annotations": "annotate","/replace-color-pdf": "replaceColor",+ "/accessibility-report": "checkAccessibility","/show-js": "showJS","/pdf-organizer": "reorganizePages","/multi-page-layout": "pageLayout",@@ -979,6 +986,7 @@"/add-watermark": "/watermark","/auto-split-pdf": "/split","/auto-size-split-pdf": "/split",+ "/accessibility-report": "/check-accessibility","/pdf-organizer": "/reorganize-pages","/multi-page-layout": "/page-layout","/extract-page": "/extract-pages",diff --git a/frontend/src/editor/core/components/tools/RightSidebar.tsx b/frontend/src/editor/core/components/tools/RightSidebar.tsxindex a9d4ee77ce..d713714734 100644--- a/frontend/src/editor/core/components/tools/RightSidebar.tsx+++ b/frontend/src/editor/core/components/tools/RightSidebar.tsx@@ -20,6 +20,7 @@ import {useIsFullscreenExpanded,} from "@editor/components/tools/FullscreenToolPanel";import { useToolPanelGeometry } from "@editor/hooks/tools/useToolPanelGeometry";+import { useToolPanelWidth } from "@editor/hooks/useToolPanelSize";import "@editor/components/tools/ToolPanel.css";/**@@ -104,7 +105,7 @@ export default function RightSidebar() {transitionProperty: "transform",};- const expandedWidth = "18.5rem";+ const expandedWidth = useToolPanelWidth();return (<div@@ -123,7 +124,9 @@ export default function RightSidebar() {opacity: 1,transition: "opacity 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94)",height: "100%",- width: isMobile ? "100%" : expandedWidth,+ // Fills the panel rather than matching its width, so content reflows as the+ // panel animates between sizes instead of snapping to the target first.+ width: "100%",maxWidth: isMobile ? "44rem" : undefined,marginInline: isMobile ? "auto" : undefined,flexShrink: 0,diff --git a/frontend/src/editor/core/components/tools/ToolPanel.css b/frontend/src/editor/core/components/tools/ToolPanel.cssindex 6a46d8bdc5..70133d82b7 100644--- a/frontend/src/editor/core/components/tools/ToolPanel.css+++ b/frontend/src/editor/core/components/tools/ToolPanel.css@@ -884,3 +884,13 @@column-width: 14rem;}}++/* Holds whatever a tool pins with ToolPanelFooter; takes no space while empty. */+.tool-panel__footer {+ flex-shrink: 0;+ background: var(--c-surface);+}++.tool-panel__footer:empty {+ display: none;+}diff --git a/frontend/src/editor/core/components/tools/ToolPanel.tsx b/frontend/src/editor/core/components/tools/ToolPanel.tsxindex a2d05cc362..de7255a30c 100644--- a/frontend/src/editor/core/components/tools/ToolPanel.tsx+++ b/frontend/src/editor/core/components/tools/ToolPanel.tsx@@ -1,9 +1,11 @@+import { useState } from "react";import { ScrollArea } from "@mantine/core";import { useTranslation } from "react-i18next";import { useToolWorkflow } from "@editor/contexts/ToolWorkflowContext";import ToolPicker from "@editor/components/tools/ToolPicker";import SearchResults from "@editor/components/tools/SearchResults";import ToolRenderer from "@editor/components/tools/ToolRenderer";+import { ToolPanelFooterTarget } from "@editor/components/tools/ToolPanelFooter";import ToolSearch from "@editor/components/tools/toolPicker/ToolSearch";import { ToolPanelViewerBar } from "@editor/components/tools/ToolPanelViewerBar";import { openSuperSearch } from "@editor/components/shared/superSearch/openSuperSearch";@@ -54,6 +56,7 @@ export default function ToolPanel({setPreviewFile,} = useToolWorkflow();const selectTool = onToolSelect ?? handleToolSelect;+ const [footer, setFooter] = useState<HTMLDivElement | null>(null);// Only offer the filter over the list itself; once a tool is open the panel// belongs to that tool. Deriving the results branch from the same flag keeps@@ -118,19 +121,24 @@ export default function ToolPanel({/></div>) : (- <div className="flex-1 min-h-0 overflow-hidden">- <ScrollArea h="100%">- {selectedToolKey ? (- <ToolRenderer- selectedToolKey={selectedToolKey}- onPreviewFile={setPreviewFile}- />- ) : (- <div className="tool-panel__placeholder">- {t("toolPanel.placeholder", "Choose a tool to get started")}- </div>- )}- </ScrollArea>+ <div className="flex-1 min-h-0 overflow-hidden flex flex-col">+ <div className="flex-1 min-h-0 overflow-hidden">+ <ScrollArea h="100%">+ {selectedToolKey ? (+ <ToolPanelFooterTarget value={footer}>+ <ToolRenderer+ selectedToolKey={selectedToolKey}+ onPreviewFile={setPreviewFile}+ />+ </ToolPanelFooterTarget>+ ) : (+ <div className="tool-panel__placeholder">+ {t("toolPanel.placeholder", "Choose a tool to get started")}+ </div>+ )}+ </ScrollArea>+ </div>+ <div ref={setFooter} className="tool-panel__footer" /></div>)}</>diff --git a/frontend/src/editor/core/components/tools/ToolPanelFooter.tsx b/frontend/src/editor/core/components/tools/ToolPanelFooter.tsxnew file mode 100644index 0000000000..ede61fec8a--- /dev/null+++ b/frontend/src/editor/core/components/tools/ToolPanelFooter.tsx@@ -0,0 +1,16 @@+import { createContext, useContext, type ReactNode } from "react";+import { createPortal } from "react-dom";++const ToolPanelFooterContext = createContext<HTMLElement | null>(null);++/** Supplies the element below the tool panel's scroll area that ToolPanelFooter renders into. */+export const ToolPanelFooterTarget = ToolPanelFooterContext.Provider;++/**+ * Pins its children to the bottom of the tool panel, outside the scrolling content, so they stay+ * put however tall the tool is. Renders in place where no panel footer is provided.+ */+export function ToolPanelFooter({ children }: { children: ReactNode }) {+ const target = useContext(ToolPanelFooterContext);+ return target ? createPortal(children, target) : <>{children}</>;+}diff --git a/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityAreaItem.tsx b/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityAreaItem.tsxnew file mode 100644index 0000000000..03f02df547--- /dev/null+++ b/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityAreaItem.tsx@@ -0,0 +1,92 @@+import { useId, useState } from "react";+import { useTranslation } from "react-i18next";+import { Icon, type IconName } from "@editor/ui/Icon";+import { BreakdownRow } from "@editor/components/tools/checkAccessibility/AccessibilityBreakdownRow";+import { AccessibilityIssueItem } from "@editor/components/tools/checkAccessibility/AccessibilityIssueItem";+import {+ categoryLabel,+ categoryReference,+ categoryTip,+} from "@editor/utils/accessibilityReportContent";+import type {+ AccessibilityArea,+ AccessibilityCategoryId,+} from "@editor/utils/accessibilityAssessment";++const CATEGORY_ICON: Record<AccessibilityCategoryId, IconName> = {+ structure: "layers",+ altText: "image",+ language: "globe",+ metadata: "file-text",+ fonts: "type",+ links: "link",+};++interface AccessibilityAreaItemProps {+ area: AccessibilityArea;+ /** The report's profile, e.g. "PDF/UA-1", for the tooltip's clause reference. */+ profile: string;+ /** Shown under the issues, such as how many images need a description. */+ note: string | null;+}++/** One breakdown area: its result, and its issues behind a toggle when there is anything to show. */+export function AccessibilityAreaItem({+ area,+ profile,+ note,+}: AccessibilityAreaItemProps) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);+ const bodyId = useId();+ const passes = area.issues.length === 0;+ const expandable = !passes || note !== null;++ return (+ <li className="a11y-area">+ <BreakdownRow+ icon={CATEGORY_ICON[area.id]}+ label={categoryLabel(t, area.id)}+ tip={categoryTip(t, area.id)}+ reference={categoryReference(t, profile, area.id)}+ status={passes ? "pass" : "fail"}+ toggle={+ expandable+ ? {+ open,+ controls: bodyId,+ onToggle: () => setOpen((value) => !value),+ }+ : undefined+ }+ />+ {expandable && (+ <div+ id={bodyId}+ className="sui-collapsible__body"+ data-open={open}+ inert={!open}+ >+ <div className="sui-collapsible__body-inner a11y-area__body">+ {!passes && (+ <div className="a11y-issues">+ {area.issues.map((issue) => (+ <AccessibilityIssueItem+ key={`${issue.clause}-${issue.testNumber}`}+ issue={issue}+ />+ ))}+ </div>+ )}+ {note && (+ <p className="a11y-note a11y-inline">+ <Icon name="image" size={14} />+ {note}+ </p>+ )}+ </div>+ </div>+ )}+ </li>+ );+}diff --git a/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityBreakdownRow.tsx b/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityBreakdownRow.tsxnew file mode 100644index 0000000000..e49a485ad6--- /dev/null+++ b/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityBreakdownRow.tsx@@ -0,0 +1,122 @@+import type { ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { Chip, type ChipAccent } from "@editor/ui/Chip";+import { Icon, type IconName } from "@editor/ui/Icon";+import { Tooltip } from "@editor/components/shared/Tooltip";++export type BreakdownStatus = "pass" | "fail" | "inProgress" | "done";++const STATUS_ACCENT: Record<BreakdownStatus, ChipAccent> = {+ pass: "success",+ fail: "danger",+ inProgress: "warning",+ done: "success",+};++/** Every status word stacked in one cell, so each pill is as wide as the longest in any language. */+function StatusWord({ status }: { status: BreakdownStatus }) {+ const { t } = useTranslation();+ const words: Record<BreakdownStatus, string> = {+ pass: t("checkAccessibility.result.pass", "Pass"),+ fail: t("checkAccessibility.result.fail", "Fail"),+ inProgress: t("checkAccessibility.manual.inProgress", "In progress"),+ done: t("checkAccessibility.manual.done", "Done"),+ };+ return (+ <span className="a11y-result-word">+ {(Object.keys(words) as BreakdownStatus[]).map((key) => (+ <span+ key={key}+ data-active={key === status}+ aria-hidden={key !== status}+ >+ {words[key]}+ </span>+ ))}+ </span>+ );+}++interface BreakdownRowProps {+ icon: IconName;+ label: string;+ tip: string;+ /** The standard's clauses the row covers, shown under the tip. */+ reference?: string | null;+ status: BreakdownStatus;+ /** Turns the label into a toggle for the details below the row. */+ toggle?: { open: boolean; controls: string; onToggle: () => void };+}++export function BreakdownRow({+ icon,+ label,+ tip,+ reference,+ status,+ toggle,+}: BreakdownRowProps) {+ const { t } = useTranslation();+ const content: ReactNode = (+ <>+ <Icon name={icon} size={16} />+ <span className="a11y-breakdown__label">{label}</span>+ </>+ );+ return (+ <div className="a11y-area__row">+ {toggle ? (+ <button+ type="button"+ className="a11y-area__toggle a11y-area__toggle--button"+ aria-expanded={toggle.open}+ aria-controls={toggle.controls}+ onClick={toggle.onToggle}+ >+ <Icon+ name="chevron-down"+ size={16}+ strokeWidth={2}+ className="a11y-area__chevron"+ />+ {content}+ </button>+ ) : (+ <span className="a11y-area__toggle">+ <span className="a11y-area__chevron" />+ {content}+ </span>+ )}+ <Tooltip+ content={+ <span className="a11y-tip">+ {tip}+ {reference && (+ <span className="a11y-tip__reference">{reference}</span>+ )}+ </span>+ }+ position="top"+ maxWidth={280}+ arrow+ >+ <button+ type="button"+ className="a11y-area__info"+ aria-label={t("checkAccessibility.aboutRow", "About {{label}}", {+ label,+ })}+ >+ <Icon name="info" size={14} />+ </button>+ </Tooltip>+ <Chip+ className="a11y-area__status"+ accent={STATUS_ACCENT[status]}+ size="xs"+ >+ <StatusWord status={status} />+ </Chip>+ </div>+ );+}diff --git a/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityIssueItem.tsx b/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityIssueItem.tsxnew file mode 100644index 0000000000..668c0030b1--- /dev/null+++ b/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityIssueItem.tsx@@ -0,0 +1,56 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { Collapsible } from "@editor/ui/Collapsible";+import { DataRow } from "@editor/ui/DataRow";+import type { AccessibilityIssue } from "@editor/types/checkAccessibility";+import { describeIssue } from "@editor/utils/accessibilityReportContent";++const LABEL_WIDTH = "6rem";++interface AccessibilityIssueItemProps {+ issue: AccessibilityIssue;+}++export function AccessibilityIssueItem({ issue }: AccessibilityIssueItemProps) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);+ const [showDetails, setShowDetails] = useState(false);+ const { title, summary, explanation, details } = describeIssue(t, issue);++ return (+ <div className="a11y-issue" data-testid="a11y-issue">+ <Collapsible+ open={open}+ onToggle={() => setOpen((value) => !value)}+ header={+ <span className="a11y-issue__head">+ <span className="a11y-issue__title">{title}</span>+ {summary && <span className="a11y-issue__meta">{summary}</span>}+ </span>+ }+ >+ <div className="a11y-issue__body">+ {explanation && <p className="a11y-issue__rule">{explanation}</p>}+ <Collapsible+ open={showDetails}+ onToggle={() => setShowDetails((value) => !value)}+ header={t("checkAccessibility.issue.details", "Details")}+ >+ <div className="a11y-issue__technical">+ {details.map((detail) => (+ <DataRow+ key={detail.label}+ label={detail.label}+ labelWidth={LABEL_WIDTH}+ align="top"+ >+ {detail.value}+ </DataRow>+ ))}+ </div>+ </Collapsible>+ </div>+ </Collapsible>+ </div>+ );+}diff --git a/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityManualChecks.tsx b/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityManualChecks.tsxnew file mode 100644index 0000000000..a9fef07f0e--- /dev/null+++ b/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityManualChecks.tsx@@ -0,0 +1,76 @@+import { useId, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@editor/ui/Button";+import { Checkbox } from "@editor/ui/Checkbox";+import { BreakdownRow } from "@editor/components/tools/checkAccessibility/AccessibilityBreakdownRow";++interface AccessibilityManualChecksProps {+ checks: string[];+ /** Indexes into `checks` the user has ticked. */+ ticked: ReadonlySet<number>;+ onToggle: (index: number) => void;+ /** Ticks every check, or clears them all when `done` is false. */+ onSetAll: (done: boolean) => void;+}++/** The checks a person has to make, as a breakdown row whose ticks go into the downloaded report. */+export function AccessibilityManualChecks({+ checks,+ ticked,+ onToggle,+ onSetAll,+}: AccessibilityManualChecksProps) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(true);+ const bodyId = useId();+ const allDone = ticked.size === checks.length;++ return (+ <li className="a11y-area">+ <BreakdownRow+ icon="user-check"+ label={t("checkAccessibility.manual.title", "Manual checks")}+ tip={t(+ "checkAccessibility.manual.tip",+ "Things only a person can judge, such as reading order and whether image descriptions make sense. Tick each one once you've checked it, and your ticks go into the downloaded report.",+ )}+ status={allDone ? "done" : "inProgress"}+ toggle={{+ open,+ controls: bodyId,+ onToggle: () => setOpen((value) => !value),+ }}+ />+ <div+ id={bodyId}+ className="sui-collapsible__body"+ data-open={open}+ inert={!open}+ >+ <div className="sui-collapsible__body-inner a11y-area__body">+ <ul className="a11y-manual">+ {checks.map((check, index) => (+ <li key={check}>+ <Checkbox+ label={check}+ checked={ticked.has(index)}+ onChange={() => onToggle(index)}+ />+ </li>+ ))}+ </ul>+ <Button+ className="a11y-manual__all"+ variant="secondary"+ size="sm"+ onClick={() => onSetAll(!allDone)}+ >+ {allDone+ ? t("checkAccessibility.manual.clearAll", "Clear all")+ : t("checkAccessibility.manual.markAllDone", "Mark all as done")}+ </Button>+ </div>+ </div>+ </li>+ );+}diff --git a/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityReportView.tsx b/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityReportView.tsxnew file mode 100644index 0000000000..73d3fb9e92--- /dev/null+++ b/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityReportView.tsx@@ -0,0 +1,122 @@+import { useMemo } from "react";+import { useTranslation } from "react-i18next";+import { Card } from "@editor/ui/Card";+import type { IconName } from "@editor/ui/Icon";+import { SectionHeader } from "@editor/ui/SectionHeader";+import { ChecksRing } from "@editor/components/tools/checkAccessibility/ChecksRing";+import { AccessibilityAreaItem } from "@editor/components/tools/checkAccessibility/AccessibilityAreaItem";+import { BreakdownRow } from "@editor/components/tools/checkAccessibility/AccessibilityBreakdownRow";+import { AccessibilityManualChecks } from "@editor/components/tools/checkAccessibility/AccessibilityManualChecks";+import {+ basicLabel,+ basicReference,+ basicTip,+ checksLabel,+ figuresSummary,+ resultLabel,+ resultSummary,+} from "@editor/utils/accessibilityReportContent";+import type { AccessibilityReport } from "@editor/types/checkAccessibility";+import {+ assessAccessibilityReport,+ type AccessibilityBasicId,+} from "@editor/utils/accessibilityAssessment";++const BASIC_ICON: Record<AccessibilityBasicId, IconName> = {+ tagged: "tags",+ title: "file-pen",+ displaysTitle: "eye",+ language: "globe",+ fonts: "type",+ declares: "shield-check",+ notEncrypted: "lock-open",+};++interface AccessibilityReportViewProps {+ report: AccessibilityReport;+ /** Indexes into `report.humanChecks` the user has ticked. */+ manualTicked: ReadonlySet<number>;+ onToggleManual: (index: number) => void;+ onSetAllManual: (done: boolean) => void;+}++export function AccessibilityReportView({+ report,+ manualTicked,+ onToggleManual,+ onSetAllManual,+}: AccessibilityReportViewProps) {+ const { t } = useTranslation();+ const { result, areas, basics, checks } = useMemo(+ () => assessAccessibilityReport(report),+ [report],+ );+ const figures = figuresSummary(t, report);++ return (+ <div className="a11y-report" data-testid="a11y-report">+ <Card padding="default" className="a11y-hero">+ <ChecksRing+ passed={checks.passed}+ total={checks.total}+ result={result}+ label={checksLabel(t, checks)}+ />+ <div className="a11y-hero__text">+ <span className={`a11y-hero__result a11y-result--${result}`}>+ {resultLabel(t, result)}+ </span>+ <span className="a11y-hero__summary">{resultSummary(t, result)}</span>+ <span className="a11y-hero__sub">+ {t(+ "checkAccessibility.score.subtitle",+ "{{profile}} - {{count}} pages",+ { profile: report.profile, count: report.summary.pages },+ )}+ {" - "}+ {report.issues.length === 0+ ? t("checkAccessibility.score.noIssues", "No issues found")+ : t("checkAccessibility.score.issues", "{{count}} issues", {+ count: report.issues.length,+ })}+ </span>+ </div>+ </Card>++ <section className="a11y-section">+ <SectionHeader+ title={t("checkAccessibility.sections.breakdown", "Breakdown")}+ />+ <ul className="a11y-breakdown">+ {areas.map((area) => (+ <AccessibilityAreaItem+ key={area.id}+ area={area}+ profile={report.profile}+ note={area.id === "altText" ? figures : null}+ />+ ))}+ {basics.map((basic) => (+ <li key={basic.id} className="a11y-area">+ <BreakdownRow+ icon={BASIC_ICON[basic.id]}+ label={basicLabel(t, basic.id)}+ tip={basicTip(t, basic.id)}+ reference={basicReference(t, report.profile, basic.id)}+ status={basic.ok ? "pass" : "fail"}+ />+ </li>+ ))}+ {report.humanChecks.length > 0 && (+ <AccessibilityManualChecks+ checks={report.humanChecks}+ ticked={manualTicked}+ onToggle={onToggleManual}+ onSetAll={onSetAllManual}+ />+ )}+ </ul>+ </section>+ </div>+ );+}diff --git a/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityResults.tsx b/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityResults.tsxnew file mode 100644index 0000000000..85d1f1949e--- /dev/null+++ b/frontend/src/editor/core/components/tools/checkAccessibility/AccessibilityResults.tsx@@ -0,0 +1,175 @@+import { useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { Banner } from "@editor/ui/Banner";+import { Button } from "@editor/ui/Button";+import { Icon } from "@editor/ui/Icon";+import { Select } from "@editor/ui/Select";+import { Spinner } from "@editor/ui/Spinner";+import { downloadFile } from "@editor/services/downloadService";+import { ToolPanelFooter } from "@editor/components/tools/ToolPanelFooter";+import { AccessibilityReportView } from "@editor/components/tools/checkAccessibility/AccessibilityReportView";+import type { CheckAccessibilityOperationHook } from "@editor/hooks/tools/checkAccessibility/useCheckAccessibilityOperation";+import { createAccessibilityReportPdf } from "@editor/hooks/tools/checkAccessibility/accessibilityReportPdf";+import { assessAccessibilityReport } from "@editor/utils/accessibilityAssessment";+import { resultLabel } from "@editor/utils/accessibilityReportContent";+import type { FileId } from "@editor/types/file";+import type { AccessibilityReportEntry } from "@editor/types/checkAccessibility";+import "@editor/components/tools/checkAccessibility/CheckAccessibility.css";++const NO_TICKS: ReadonlySet<number> = new Set();++interface AccessibilityResultsProps {+ operation: CheckAccessibilityOperationHook;+ /** Falls back to the first report when this file is not in the run. */+ selectedFileId: FileId | null;+ onSelectFile: (fileId: FileId) => void;+}++export function AccessibilityResults({+ operation,+ selectedFileId,+ onSelectFile,+}: AccessibilityResultsProps) {+ const { t } = useTranslation();+ const { results, isLoading, status } = operation;++ const options = useMemo(+ () =>+ results.map((entry) => ({+ value: entry.fileId,+ label: entry.report+ ? `${entry.fileName} - ${resultLabel(t, assessAccessibilityReport(entry.report).result)}`+ : `${entry.fileName} - ${t("checkAccessibility.fileFailed", "failed")}`,+ })),+ [results, t],+ );++ const [manualTicks, setManualTicks] = useState<+ Partial<Record<FileId, ReadonlySet<number>>>+ >({});+ // A new run starts a new checklist: the ticks were for the files as they were checked.+ useEffect(() => {+ if (isLoading) setManualTicks({});+ }, [isLoading]);+ const toggleManual = (fileId: FileId, index: number) =>+ setManualTicks((current) => {+ const next = new Set(current[fileId]);+ if (!next.delete(index)) next.add(index);+ return { ...current, [fileId]: next };+ });++ const [buildingPdf, setBuildingPdf] = useState(false);+ const [downloadFailed, setDownloadFailed] = useState(false);++ const downloadReportPdf = async (entry: AccessibilityReportEntry) => {+ setBuildingPdf(true);+ setDownloadFailed(false);+ try {+ const pdf = await createAccessibilityReportPdf(+ entry,+ t,+ manualTicks[entry.fileId] ?? NO_TICKS,+ );+ await downloadFile({ data: pdf, filename: pdf.name });+ } catch (error) {+ console.warn("[checkAccessibility] PDF report failed", error);+ setDownloadFailed(true);+ } finally {+ setBuildingPdf(false);+ }+ };++ const selected =+ results.find((entry) => entry.fileId === selectedFileId) ?? results[0];++ if (!selected) {+ return isLoading ? (+ <div className="a11y-loading">+ <Spinner size="sm" />+ <span>{status}</span>+ </div>+ ) : null;+ }++ return (+ <div className="a11y-results" data-testid="a11y-results">+ {(results.length > 1 || isLoading) && (+ <div className="a11y-picker">+ <Select+ aria-label={t("checkAccessibility.pickFile", "Show results for")}+ options={options}+ value={selected.fileId}+ onChange={(value) => {+ const entry = results.find((item) => item.fileId === value);+ if (entry) onSelectFile(entry.fileId);+ }}+ allowDeselect={false}+ searchable={results.length > 6}+ />+ {isLoading && (+ <div className="a11y-loading">+ <Spinner size="sm" />+ <span>{status}</span>+ </div>+ )}+ </div>+ )}++ {selected.report ? (+ <AccessibilityReportView+ key={selected.fileId}+ report={selected.report}+ manualTicked={manualTicks[selected.fileId] ?? NO_TICKS}+ onToggleManual={(index) => toggleManual(selected.fileId, index)}+ onSetAllManual={(done) =>+ setManualTicks((current) => ({+ ...current,+ [selected.fileId]: new Set(+ done+ ? selected.report?.humanChecks.map((_, index) => index)+ : [],+ ),+ }))+ }+ />+ ) : (+ <Banner+ tone="danger"+ title={t(+ "checkAccessibility.error.fileTitle",+ "This file could not be checked",+ )}+ description={selected.error}+ />+ )}++ {!isLoading && (+ <ToolPanelFooter>+ <div className="a11y-download">+ {downloadFailed && (+ <Banner+ tone="danger"+ title={t(+ "checkAccessibility.error.download",+ "The accessibility report could not be created. Try again.",+ )}+ onDismiss={() => setDownloadFailed(false)}+ />+ )}+ <Button+ fullWidth+ loading={buildingPdf}+ leftSection={<Icon name="download" size={16} />}+ onClick={() => void downloadReportPdf(selected)}+ >+ {t(+ "checkAccessibility.download",+ "Download accessibility report",+ )}+ </Button>+ </div>+ </ToolPanelFooter>+ )}+ </div>+ );+}diff --git a/frontend/src/editor/core/components/tools/checkAccessibility/CheckAccessibility.css b/frontend/src/editor/core/components/tools/checkAccessibility/CheckAccessibility.cssnew file mode 100644index 0000000000..b15b1a25c1--- /dev/null+++ b/frontend/src/editor/core/components/tools/checkAccessibility/CheckAccessibility.css@@ -0,0 +1,340 @@+.a11y-results,+.a11y-report {+ display: flex;+ flex-direction: column;+ gap: 1rem;+ min-width: 0;+}++.a11y-picker {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++.a11y-loading {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ font-size: 0.75rem;+ color: var(--c-text-muted);+}++.a11y-hero {+ display: flex;+ align-items: center;+ gap: 1rem;+}++.a11y-hero__text {+ display: flex;+ flex-direction: column;+ gap: 0.375rem;+ min-width: 0;+}++.a11y-hero__result {+ font-size: 1.125rem;+ font-weight: 650;+ line-height: 1.25;+}++.a11y-hero__summary {+ font-size: 0.8125rem;+ color: var(--c-text);+}++.a11y-hero__sub {+ font-size: 0.75rem;+ color: var(--c-text-muted);+}++.a11y-ring {+ position: relative;+ flex-shrink: 0;+}++.a11y-ring__track {+ stroke: var(--c-border-subtle);+}++.a11y-ring__value {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: baseline;+ justify-content: center;+ padding-top: 2.45rem;+ font-variant-numeric: tabular-nums;+}++.a11y-ring__number {+ font-size: 1.875rem;+ font-weight: 700;+ line-height: 1;+ color: var(--c-text);+}++.a11y-ring__out-of {+ margin-left: 0.125rem;+ font-size: 0.8125rem;+ color: var(--c-text-subtle);+}++.a11y-result--pass {+ color: var(--c-success);+}++.a11y-result--partial {+ color: var(--c-warning);+}++.a11y-result--fail {+ color: var(--c-danger);+}++.a11y-inline {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+}++.a11y-note {+ margin: 0;+ font-size: 0.75rem;+ line-height: 1.5;+ color: var(--c-text-muted);+}++.a11y-section {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+}++.a11y-breakdown {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+ margin: 0;+ padding: 0;+ list-style: none;+}++.a11y-breakdown__label {+ font-size: 0.8125rem;+ color: var(--c-text);+}++.a11y-area__row {+ display: flex;+ align-items: center;+ gap: 0.375rem;+}++.a11y-area__toggle {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+ min-width: 0;+ padding: 0;+ border: 0;+ background: none;+ font: inherit;+ text-align: left;+ color: var(--c-text-muted);+}++.a11y-area__toggle--button {+ cursor: pointer;+}++.a11y-area__toggle--button:hover .a11y-breakdown__label {+ color: var(--c-accent-fg, var(--c-primary));+}++.a11y-area__toggle--button:focus-visible {+ outline: 2px solid var(--c-primary);+ outline-offset: 2px;+ border-radius: var(--radius-sm);+}++/* Passing rows keep an empty chevron slot so every label lines up. */+.a11y-area__chevron {+ flex-shrink: 0;+ width: 16px;+ color: var(--c-text-subtle);+ transform: rotate(-90deg);+ transition: transform 0.2s ease;+}++.a11y-area__toggle[aria-expanded="true"] .a11y-area__chevron {+ transform: rotate(0deg);+}++.a11y-tip__reference {+ display: block;+ margin-top: 0.375rem;+ font-size: 0.75em;+ opacity: 0.75;+}++.a11y-area__info {+ display: inline-flex;+ padding: 0;+ border: 0;+ background: none;+ color: var(--c-text-subtle);+ cursor: pointer;+}++.a11y-area__info:focus-visible {+ outline: 2px solid var(--c-primary);+ outline-offset: 2px;+ border-radius: var(--radius-sm);+}++.a11y-area__status {+ margin-left: auto;+}++/* Spaced with a child margin: padding on the clipped inner would show while collapsed. */+.a11y-area__body {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ padding-top: 0;+}++.a11y-area__body > :first-child {+ margin-top: 0.5rem;+}++.a11y-issues {+ display: flex;+ flex-direction: column;+ border: 1px solid var(--c-border-subtle);+ border-radius: var(--radius-md);+ background: var(--c-surface);+}++.a11y-issue {+ padding: 0.625rem 0.75rem;+}++.a11y-issue + .a11y-issue {+ border-top: 1px solid var(--c-border-subtle);+}++.a11y-issue .sui-collapsible__head {+ align-self: stretch;+ align-items: flex-start;+ width: 100%;+ text-align: left;+ font-weight: 500;+ color: var(--c-text);+}++/* Same reason as .a11y-area__body: the inner's padding would show while collapsed. */+.a11y-issue .sui-collapsible__body-inner {+ padding-top: 0;+}++.a11y-issue .sui-collapsible__chevron {+ margin-top: 0.125rem;+ flex-shrink: 0;+}++.a11y-issue__head {+ display: flex;+ flex-direction: column;+ gap: 0.375rem;+ min-width: 0;+}++.a11y-issue__title {+ font-size: 0.8125rem;+ line-height: 1.4;+ overflow-wrap: anywhere;+}++.a11y-issue__meta {+ font-size: 0.75rem;+ font-weight: 400;+ color: var(--c-text-muted);+}++.a11y-issue__rule {+ margin: 0;+ font-size: 0.75rem;+ line-height: 1.5;+ color: var(--c-text-muted);+}++.a11y-issue__technical {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++.a11y-issue__body {+ display: flex;+ flex-direction: column;+ gap: 0.75rem;+ margin-top: 0.625rem;+ padding-left: 1.375rem;+}++/* Stacks every result word in one cell and shows only the active one, so pills share a width. */+.a11y-result-word {+ display: inline-grid;+ text-align: center;+}++.a11y-result-word > span {+ grid-area: 1 / 1;+}++.a11y-result-word > span[data-active="false"] {+ visibility: hidden;+}++.a11y-manual__all {+ align-self: flex-start;+ margin-left: 1.5rem;+}++/* Indented to line up with the row labels, past the chevron. */+.a11y-manual {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ margin: 0;+ padding: 0 0 0 1.5rem;+ list-style: none;+}++.a11y-manual li {+ display: flex;+ align-items: flex-start;+ gap: 0.5rem;+ font-size: 0.75rem;+ line-height: 1.45;+ color: var(--c-text-muted);+}++.a11y-issue__body .sui-collapsible__head {+ align-self: flex-start;+ width: auto;+ font-size: 0.75rem;+ font-weight: 600;+ color: var(--c-text-muted);+}++/* Inset to line up with the report, which sits inside the flow's padding and scrollbar gutter. */+.a11y-download {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ padding: 0.75rem 1rem 0.75rem 1.5rem;+}diff --git a/frontend/src/editor/core/components/tools/checkAccessibility/ChecksRing.tsx b/frontend/src/editor/core/components/tools/checkAccessibility/ChecksRing.tsxnew file mode 100644index 0000000000..f699a7b9e4--- /dev/null+++ b/frontend/src/editor/core/components/tools/checkAccessibility/ChecksRing.tsx@@ -0,0 +1,94 @@+import { useEffect, useState } from "react";+import type { AccessibilityResult } from "@editor/utils/accessibilityAssessment";++const SIZE = 112;+const STROKE = 10;+const RADIUS = (SIZE - STROKE) / 2;+const CIRCUMFERENCE = 2 * Math.PI * RADIUS;+const DURATION_MS = 1100;++const RESULT_COLOR: Record<AccessibilityResult, string> = {+ pass: "var(--c-success)",+ partial: "var(--c-warning)",+ fail: "var(--c-danger)",+};++const easeOutCubic = (t: number) => 1 - Math.pow(1 - t, 3);++const prefersReducedMotion = () =>+ typeof window !== "undefined" &&+ window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;++/** Counts from 0 to `target` on mount and whenever `target` changes. */+function useCountUp(target: number): number {+ const [value, setValue] = useState(0);++ useEffect(() => {+ if (prefersReducedMotion()) {+ setValue(target);+ return;+ }+ let frame = 0;+ const start = performance.now();+ const tick = (now: number) => {+ const progress = Math.min(1, (now - start) / DURATION_MS);+ setValue(target * easeOutCubic(progress));+ if (progress < 1) frame = requestAnimationFrame(tick);+ };+ setValue(0);+ frame = requestAnimationFrame(tick);+ return () => cancelAnimationFrame(frame);+ }, [target]);++ return value;+}++interface ChecksRingProps {+ passed: number;+ total: number;+ result: AccessibilityResult;+ label: string;+}++export function ChecksRing({ passed, total, result, label }: ChecksRingProps) {+ const animated = useCountUp(passed);+ const offset = CIRCUMFERENCE * (1 - (total > 0 ? animated / total : 0));++ return (+ <div+ className="a11y-ring"+ role="img"+ aria-label={label}+ style={{ width: SIZE, height: SIZE }}+ >+ {/* icon-lint-allow: runtime-generated-svg -- ring arc length is computed from the checks passed */}+ <svg viewBox={`0 0 ${SIZE} ${SIZE}`} width={SIZE} height={SIZE}>+ <circle+ className="a11y-ring__track"+ cx={SIZE / 2}+ cy={SIZE / 2}+ r={RADIUS}+ strokeWidth={STROKE}+ fill="none"+ />+ <circle+ cx={SIZE / 2}+ cy={SIZE / 2}+ r={RADIUS}+ strokeWidth={STROKE}+ fill="none"+ strokeLinecap="round"+ strokeDasharray={CIRCUMFERENCE}+ strokeDashoffset={offset}+ transform={`rotate(-90 ${SIZE / 2} ${SIZE / 2})`}+ style={{ stroke: RESULT_COLOR[result] }}+ opacity={animated > 0 ? 1 : 0}+ />+ </svg>+ <div className="a11y-ring__value" aria-hidden="true">+ <span className="a11y-ring__number">{Math.round(animated)}</span>+ <span className="a11y-ring__out-of">/{total}</span>+ </div>+ </div>+ );+}diff --git a/frontend/src/editor/core/components/tooltips/useCheckAccessibilityTips.ts b/frontend/src/editor/core/components/tooltips/useCheckAccessibilityTips.tsnew file mode 100644index 0000000000..41071697df--- /dev/null+++ b/frontend/src/editor/core/components/tooltips/useCheckAccessibilityTips.ts@@ -0,0 +1,31 @@+import { useTranslation } from "react-i18next";+import { TooltipContent } from "@editor/types/tips";++export const useCheckAccessibilityTips = (): TooltipContent => {+ const { t } = useTranslation();++ return {+ header: {+ title: t(+ "checkAccessibility.tooltip.header.title",+ "Which standard to check",+ ),+ },+ tips: [+ {+ title: t("checkAccessibility.tooltip.ua1.title", "PDF/UA-1"),+ description: t(+ "checkAccessibility.tooltip.ua1.text",+ "The first version of PDF/UA, published in 2012 as ISO 14289-1, for PDF 1.7 files.",+ ),+ },+ {+ title: t("checkAccessibility.tooltip.ua2.title", "PDF/UA-2"),+ description: t(+ "checkAccessibility.tooltip.ua2.text",+ "The newer version, published in 2024 as ISO 14289-2, for PDF 2.0 files. A PDF 1.7 file checked against it fails the rules that only apply to PDF 2.0.",+ ),+ },+ ],+ };+};diff --git a/frontend/src/editor/core/data/useTranslatedToolRegistry.tsx b/frontend/src/editor/core/data/useTranslatedToolRegistry.tsxindex f63e8a6acd..5f4993980a 100644--- a/frontend/src/editor/core/data/useTranslatedToolRegistry.tsx+++ b/frontend/src/editor/core/data/useTranslatedToolRegistry.tsx@@ -445,6 +445,23 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {automationSettings: null,maxFiles: 1,},+ checkAccessibility: {+ icon: <Icon name="universal-access" size="1.5rem" />,+ name: t("home.checkAccessibility.title", "Check PDF accessibility"),+ component: lazy(() => import("@editor/tools/CheckAccessibility")),+ description: t(+ "home.checkAccessibility.desc",+ "Score a PDF against PDF/UA and see what blocks screen readers, without changing it",+ ),+ categoryId: ToolCategoryId.STANDARD_TOOLS,+ subcategoryId: SubcategoryId.VERIFICATION,+ maxFiles: -1,+ endpoints: ["accessibility-report"],+ synonyms: getSynonyms(t, "checkAccessibility"),+ // Reports rather than transforming the PDF, so it has no automation step.+ supportsAutomate: false,+ automationSettings: null,+ },validateSignature: {icon: <Icon name="badge-check" size="1.5rem" />,name: t("home.validateSignature.title", "Validate PDF Signature"),diff --git a/frontend/src/editor/core/hooks/tools/checkAccessibility/accessibilityReportPdf.ts b/frontend/src/editor/core/hooks/tools/checkAccessibility/accessibilityReportPdf.tsnew file mode 100644index 0000000000..050e36dcae--- /dev/null+++ b/frontend/src/editor/core/hooks/tools/checkAccessibility/accessibilityReportPdf.ts@@ -0,0 +1,647 @@+import type { TFunction } from "i18next";+import {+ PdfiumDocument,+ StandardFonts,+ rgb,+ type PdfiumColor,+} from "@editor/services/pdfiumDocBuilder";+import {+ colorPalette,+ statusTextColor as statusText,+} from "@editor/services/reportPdf/reportPalette";+import { wrapText } from "@editor/services/reportPdf/reportText";+import {+ LETTER_PAGE,+ ReportWriter,+ type ReportLayout,+ type TextStyle,+} from "@editor/services/reportPdf/ReportWriter";+import {+ type AccessibilityIssue,+ type AccessibilityReport,+ type AccessibilityReportEntry,+} from "@editor/types/checkAccessibility";+import {+ assessAccessibilityReport,+ type AccessibilityAssessment,+ type AccessibilityResult,+} from "@editor/utils/accessibilityAssessment";+import {+ basicLabel,+ categoryLabel,+ describeIssue,+ figuresSummary,+ resultLabel,+ resultSummary,+} from "@editor/utils/accessibilityReportContent";++/**+ * Lays out one file's report on US Letter. Every size is in PDF points: the type scale and the+ * spacing below set the whole layout, and the rest is derived from them.+ */+const LAYOUT: ReportLayout = {+ pageWidth: LETTER_PAGE.width,+ pageHeight: LETTER_PAGE.height,+ marginX: 48,+ marginTop: 48,+ marginBottom: 56,+};+const PAGE_WIDTH = LAYOUT.pageWidth;+const PAGE_HEIGHT = LAYOUT.pageHeight;+const MARGIN_X = LAYOUT.marginX;+const CONTENT_WIDTH = PAGE_WIDTH - MARGIN_X * 2;+const CONTENT_RIGHT = MARGIN_X + CONTENT_WIDTH;++const TYPE = {+ heading: 9,+ fileName: 18,+ result: 18,+ body: 10,+ rowLabel: 10.5,+ explanation: 9.5,+ meta: 9,+ detail: 8.5,+ pill: 7.5,+ ringNumber: 16,+ ringOutOf: 8,+} as const;++const SPACE = { xxs: 2, xs: 3, sm: 4, md: 8, lg: 14, xl: 20 } as const;++// Must match ReportWriter's line height, which moves y by this much per line it draws.+const lineHeight = (size: number) => size * 1.35;++const INDENT = 14;+const DETAIL_LABEL_WIDTH = 84;+const HEADER_BOTTOM_PADDING = 18;+const RESULT_CARD_HEIGHT = 84;+const RESULT_CARD_INSET = 18;+const RING = { radius: 25, stroke: 6, segments: 120 } as const;+const PILL = { height: 12, padding: 6, tint: 0.14, borderTint: 0.55 } as const;+const CHECKBOX = { size: 8, border: 0.75 } as const;++const resultColor = (result: AccessibilityResult): PdfiumColor =>+ result === "pass"+ ? statusText.success+ : result === "partial"+ ? statusText.warning+ : statusText.danger;++/** `color` laid over white at `amount`, for the soft fills the on-screen chips use. */+const tint = (color: PdfiumColor, amount: number): PdfiumColor =>+ rgb(+ 1 - (1 - color._r) * amount,+ 1 - (1 - color._g) * amount,+ 1 - (1 - color._b) * amount,+ );++/** Height a section heading needs with at least one row under it, so it never ends a page. */+const SECTION_HEADING_KEEP = 40;++function sectionHeading(writer: ReportWriter, title: string) {+ writer.ensure(SECTION_HEADING_KEEP);+ writer.y -= SPACE.lg;+ const style: TextStyle = {+ font: writer.boldFont,+ size: TYPE.heading,+ color: colorPalette.textMuted,+ };+ writer.text(title.toUpperCase(), MARGIN_X, style);+ writer.rule(writer.y + SPACE.xxs);+ writer.y -= SPACE.md;+}++function drawHeader(+ writer: ReportWriter,+ t: TFunction,+ fileName: string,+ subtitle: string | null,+) {+ const nameLines = wrapText(+ fileName,+ writer.boldFont,+ TYPE.fileName,+ CONTENT_WIDTH,+ ).slice(0, 2);+ const bandHeight =+ LAYOUT.marginTop ++ lineHeight(TYPE.body) ++ SPACE.xxs ++ nameLines.length * lineHeight(TYPE.fileName) ++ (subtitle ? lineHeight(TYPE.body) : 0) ++ HEADER_BOTTOM_PADDING;+ writer.rect(+ 0,+ PAGE_HEIGHT,+ PAGE_WIDTH,+ bandHeight,+ colorPalette.headerBackground,+ );+ writer.text(+ t("checkAccessibility.pdf.title", "Accessibility report"),+ MARGIN_X,+ { font: writer.font, size: TYPE.body, color: colorPalette.accent },+ );+ writer.y -= SPACE.xxs;+ for (const line of nameLines) {+ writer.text(line, MARGIN_X, {+ font: writer.boldFont,+ size: TYPE.fileName,+ color: colorPalette.textPrimary,+ });+ }+ if (subtitle) {+ writer.text(subtitle, MARGIN_X, {+ font: writer.font,+ size: TYPE.body,+ color: colorPalette.textMuted,+ });+ }+ writer.y = PAGE_HEIGHT - bandHeight - SPACE.xl;+}++/** An arc clockwise from 12 o'clock, drawn as short overlapping strokes. */+function drawArc(+ writer: ReportWriter,+ cx: number,+ cy: number,+ fraction: number,+ color: PdfiumColor,+) {+ const segments = Math.ceil(RING.segments * fraction);+ const step = (2 * Math.PI * fraction) / segments;+ // Overlap neighbours so their square ends leave no gaps on the outside of the curve.+ const overlap = step * 0.25;+ const point = (angle: number) => ({+ x: cx + RING.radius * Math.sin(angle),+ y: cy + RING.radius * Math.cos(angle),+ });+ for (let index = 0; index < segments; index++) {+ writer.currentPage.drawLine({+ start: point(Math.max(0, index * step - overlap)),+ end: point((index + 1) * step),+ thickness: RING.stroke,+ color,+ });+ }+}++function drawChecksRing(+ writer: ReportWriter,+ cx: number,+ cy: number,+ assessment: AccessibilityAssessment,+) {+ const { passed, total } = assessment.checks;+ drawArc(writer, cx, cy, 1, colorPalette.boxBorder);+ if (passed > 0) {+ drawArc(writer, cx, cy, passed / total, resultColor(assessment.result));+ }+ const number = String(passed);+ const outOf = `/${total}`;+ const numberWidth = writer.boldFont.widthOfTextAtSize(+ number,+ TYPE.ringNumber,+ );+ const width =+ numberWidth + 1 + writer.font.widthOfTextAtSize(outOf, TYPE.ringOutOf);+ const left = cx - width / 2;+ // Cap height is about 0.7 of the size, so this centres the digits on the ring.+ const baseline = cy - TYPE.ringNumber * 0.35;+ writer.currentPage.drawText(number, {+ x: left,+ y: baseline,+ size: TYPE.ringNumber,+ font: writer.boldFont,+ color: colorPalette.textPrimary,+ });+ writer.currentPage.drawText(outOf, {+ x: left + numberWidth + 1,+ y: baseline,+ size: TYPE.ringOutOf,+ font: writer.font,+ color: colorPalette.textMuted,+ });+}++function drawResult(+ writer: ReportWriter,+ t: TFunction,+ report: AccessibilityReport,+ assessment: AccessibilityAssessment,+) {+ const { result } = assessment;+ const top = writer.y;+ writer.rect(+ MARGIN_X,+ top,+ CONTENT_WIDTH,+ RESULT_CARD_HEIGHT,+ colorPalette.boxBackground,+ colorPalette.boxBorder,+ );+ const ringLeft = MARGIN_X + RESULT_CARD_INSET;+ drawChecksRing(+ writer,+ ringLeft + RING.radius,+ top - RESULT_CARD_HEIGHT / 2,+ assessment,+ );+ const textX = ringLeft + RING.radius * 2 + RING.stroke + SPACE.lg;+ const textWidth = CONTENT_RIGHT - SPACE.lg - textX;+ const lines: Array<{ text: string; style: TextStyle }> = [+ {+ text: resultLabel(t, result),+ style: {+ font: writer.boldFont,+ size: TYPE.result,+ color: resultColor(result),+ },+ },+ ...wrapText(resultSummary(t, result), writer.font, TYPE.body, textWidth)+ .slice(0, 2)+ .map((text) => ({+ text,+ style: {+ font: writer.font,+ size: TYPE.body,+ color: colorPalette.textPrimary,+ },+ })),+ {+ text:+ report.issues.length === 0+ ? t("checkAccessibility.score.noIssues", "No issues found")+ : t("checkAccessibility.score.issues", "{{count}} issues", {+ count: report.issues.length,+ }),+ style: {+ font: writer.font,+ size: TYPE.meta,+ color: colorPalette.textMuted,+ },+ },+ ];+ const textHeight = lines.reduce(+ (height, line) => height + lineHeight(line.style.size),+ 0,+ );+ writer.y = top - (RESULT_CARD_HEIGHT - textHeight) / 2;+ for (const line of lines) writer.text(line.text, textX, line.style);+ writer.y = top - RESULT_CARD_HEIGHT - SPACE.md;+}++type RowStatus = "pass" | "fail" | "inProgress" | "done";++const statusWord = (t: TFunction, status: RowStatus) =>+ ({+ pass: t("checkAccessibility.result.pass", "Pass"),+ fail: t("checkAccessibility.result.fail", "Fail"),+ inProgress: t("checkAccessibility.manual.inProgress", "In progress"),+ done: t("checkAccessibility.manual.done", "Done"),+ })[status];++const STATUS_COLORS: Record<+ RowStatus,+ { base: PdfiumColor; text: PdfiumColor }+> = {+ pass: { base: colorPalette.success, text: statusText.success },+ done: { base: colorPalette.success, text: statusText.success },+ fail: { base: colorPalette.danger, text: statusText.danger },+ inProgress: { base: colorPalette.warning, text: statusText.warning },+};++/** Wide enough for the longest status word, so every pill matches in any language. */+function pillWidth(writer: ReportWriter, t: TFunction): number {+ const statuses: RowStatus[] = ["pass", "fail", "inProgress", "done"];+ return (+ Math.max(+ ...statuses.map((status) =>+ writer.boldFont.widthOfTextAtSize(statusWord(t, status), TYPE.pill),+ ),+ ) ++ PILL.padding * 2+ );+}++/** A soft pill like the on-screen chips, with its label centred; `left` is its left edge. */+function drawPill(+ writer: ReportWriter,+ t: TFunction,+ left: number,+ width: number,+ status: RowStatus,+) {+ const { base, text } = STATUS_COLORS[status];+ const label = statusWord(t, status);+ const bottom = writer.y - PILL.height + 1;+ writer.currentPage.drawRectangle({+ x: left,+ y: bottom,+ width,+ height: PILL.height,+ color: tint(base, PILL.tint),+ borderColor: tint(base, PILL.borderTint),+ borderWidth: 0.75,+ });+ const textWidth = writer.boldFont.widthOfTextAtSize(label, TYPE.pill);+ writer.currentPage.drawText(label, {+ x: left + (width - textWidth) / 2,+ y: bottom + (PILL.height - TYPE.pill * 0.7) / 2,+ size: TYPE.pill,+ font: writer.boldFont,+ color: text,+ });+}++/** A checkbox whose top sits at the current line; ticked boxes are filled with a white tick. */+function drawCheckbox(writer: ReportWriter, left: number, ticked: boolean) {+ const top = writer.y - (lineHeight(TYPE.body) - CHECKBOX.size) / 2;+ const page = writer.currentPage;+ page.drawRectangle({+ x: left,+ y: top - CHECKBOX.size,+ width: CHECKBOX.size,+ height: CHECKBOX.size,+ color: ticked ? colorPalette.accent : rgb(1, 1, 1),+ borderColor: ticked ? colorPalette.accent : colorPalette.textMuted,+ borderWidth: CHECKBOX.border,+ });+ if (!ticked) return;+ const unit = CHECKBOX.size / 8;+ const tick = { thickness: 1.2, color: rgb(1, 1, 1) };+ page.drawLine({+ start: { x: left + 1.8 * unit, y: top - 4.2 * unit },+ end: { x: left + 3.4 * unit, y: top - 5.8 * unit },+ ...tick,+ });+ page.drawLine({+ start: { x: left + 3.4 * unit, y: top - 5.8 * unit },+ end: { x: left + 6.4 * unit, y: top - 2.4 * unit },+ ...tick,+ });+}++/** The checks a person has to make, as the last breakdown row with the user's ticks under it. */+function drawManualChecks(+ writer: ReportWriter,+ t: TFunction,+ report: AccessibilityReport,+ ticked: ReadonlySet<number>,+) {+ if (report.humanChecks.length === 0) return;+ const style: TextStyle = {+ font: writer.font,+ size: TYPE.body,+ color: colorPalette.textPrimary,+ };+ writer.ensure(lineHeight(TYPE.rowLabel) + SPACE.md + lineHeight(style.size));+ rowDivider(writer);+ drawRowHeading(+ writer,+ t,+ t("checkAccessibility.manual.title", "Manual checks"),+ ticked.size === report.humanChecks.length ? "done" : "inProgress",+ );+ writer.y -= SPACE.sm;+ const boxX = MARGIN_X + INDENT;+ const textX = boxX + CHECKBOX.size + SPACE.md;+ report.humanChecks.forEach((check, index) => {+ const lines = wrapText(+ check,+ style.font,+ style.size,+ CONTENT_RIGHT - textX,+ );+ lines.forEach((line, lineIndex) => {+ writer.ensure(lineHeight(style.size));+ if (lineIndex === 0) drawCheckbox(writer, boxX, ticked.has(index));+ writer.text(line, textX, style);+ });+ writer.y -= SPACE.xs;+ });+}++function drawIssue(+ writer: ReportWriter,+ t: TFunction,+ issue: AccessibilityIssue,+) {+ const x = MARGIN_X + INDENT;+ const width = CONTENT_RIGHT - x;+ const content = describeIssue(t, issue);+ // The title, summary and first line of explanation, so a title never ends a page.+ writer.ensure(+ lineHeight(TYPE.rowLabel) ++ lineHeight(TYPE.meta) ++ lineHeight(TYPE.explanation),+ );+ writer.paragraph(content.title, x, width, {+ font: writer.boldFont,+ size: TYPE.rowLabel,+ color: colorPalette.textPrimary,+ });+ if (content.summary) {+ writer.paragraph(content.summary, x, width, {+ font: writer.font,+ size: TYPE.meta,+ color: colorPalette.textMuted,+ });+ }+ if (content.explanation) {+ writer.y -= SPACE.xs;+ writer.paragraph(content.explanation, x, width, {+ font: writer.font,+ size: TYPE.explanation,+ color: colorPalette.textPrimary,+ });+ }+ writer.y -= SPACE.sm;+ const detailStyle: TextStyle = {+ font: writer.font,+ size: TYPE.detail,+ color: colorPalette.textPrimary,+ };+ for (const detail of content.details) {+ const lines = wrapText(+ detail.value,+ writer.font,+ detailStyle.size,+ width - DETAIL_LABEL_WIDTH,+ );+ lines.forEach((line, lineIndex) => {+ writer.ensure(lineHeight(detailStyle.size));+ if (lineIndex === 0) {+ writer.currentPage.drawText(detail.label, {+ x,+ y: writer.y - detailStyle.size,+ size: detailStyle.size,+ font: writer.font,+ color: colorPalette.textMuted,+ });+ }+ writer.text(line, x + DETAIL_LABEL_WIDTH, detailStyle);+ });+ }+ writer.y -= SPACE.md;+}++/** A breakdown row's label with its status pill at the right edge. */+function drawRowHeading(+ writer: ReportWriter,+ t: TFunction,+ label: string,+ status: RowStatus,+) {+ const pill = pillWidth(writer, t);+ drawPill(writer, t, CONTENT_RIGHT - pill, pill, status);+ writer.text(label, MARGIN_X, {+ font: writer.boldFont,+ size: TYPE.rowLabel,+ color: colorPalette.textPrimary,+ });+}++function rowDivider(writer: ReportWriter) {+ writer.rule(writer.y + SPACE.sm);+ writer.y -= SPACE.sm;+}++function drawBreakdown(+ writer: ReportWriter,+ t: TFunction,+ report: AccessibilityReport,+ { areas, basics }: AccessibilityAssessment,+) {+ sectionHeading(+ writer,+ t("checkAccessibility.sections.breakdown", "Breakdown"),+ );+ const figures = figuresSummary(t, report);+ const rowHeight = lineHeight(TYPE.rowLabel) + SPACE.md;+ areas.forEach((area, areaIndex) => {+ const passes = area.issues.length === 0;+ const note = area.id === "altText" ? figures : null;+ // A failing area keeps its first issue's title with it.+ writer.ensure(passes && !note ? rowHeight : rowHeight * 3);+ if (areaIndex > 0) rowDivider(writer);+ drawRowHeading(+ writer,+ t,+ categoryLabel(t, area.id),+ passes ? "pass" : "fail",+ );+ writer.y -= SPACE.sm;+ area.issues.forEach((issue, index) => {+ if (index > 0) {+ writer.ensure(SPACE.md);+ writer.currentPage.drawLine({+ start: { x: MARGIN_X + INDENT, y: writer.y + SPACE.xs },+ end: { x: CONTENT_RIGHT, y: writer.y + SPACE.xs },+ thickness: 0.5,+ color: colorPalette.boxBorder,+ });+ writer.y -= SPACE.sm;+ }+ drawIssue(writer, t, issue);+ });+ if (note) {+ writer.paragraph(note, MARGIN_X + INDENT, CONTENT_WIDTH - INDENT, {+ font: writer.font,+ size: TYPE.meta,+ color: colorPalette.textMuted,+ });+ writer.y -= SPACE.sm;+ }+ writer.y -= SPACE.sm;+ });+ for (const basic of basics) {+ writer.ensure(rowHeight);+ rowDivider(writer);+ drawRowHeading(+ writer,+ t,+ basicLabel(t, basic.id),+ basic.ok ? "pass" : "fail",+ );+ writer.y -= SPACE.md;+ }+}++function drawFailedEntry(+ writer: ReportWriter,+ t: TFunction,+ entry: AccessibilityReportEntry,+) {+ writer.paragraph(+ t("checkAccessibility.error.fileTitle", "This file could not be checked"),+ MARGIN_X,+ CONTENT_WIDTH,+ { font: writer.boldFont, size: 12, color: statusText.danger },+ );+ if (entry.error) {+ writer.paragraph(entry.error, MARGIN_X, CONTENT_WIDTH, {+ font: writer.font,+ size: TYPE.body,+ color: colorPalette.textPrimary,+ });+ }+}++/** "Report.pdf" -> "Report-accessibility-report.pdf". */+export function accessibilityReportPdfName(fileName: string): string {+ return `${fileName.replace(/\.pdf$/i, "")}-accessibility-report.pdf`;+}++/**+ * One file's on-screen report as a PDF, with the manual checks the user ticked. Text is set in the+ * standard Helvetica fonts, so characters outside WinAnsi do not render.+ */+export async function createAccessibilityReportPdf(+ entry: AccessibilityReportEntry,+ t: TFunction,+ manualTicked: ReadonlySet<number>,+): Promise<File> {+ const doc = await PdfiumDocument.create();+ const writer = new ReportWriter(doc, {+ layout: LAYOUT,+ regular: await doc.embedFont(StandardFonts.Helvetica),+ bold: await doc.embedFont(StandardFonts.HelveticaBold),+ footerText: t("checkAccessibility.pdf.footer", "Checked with Stirling PDF"),+ pageLabel: (n) => t("checkAccessibility.pdf.page", "Page {{n}}", { n }),+ });++ writer.startSection(+ t("checkAccessibility.pdf.continued", "{{name}} (continued)", {+ name: entry.fileName,+ }),+ );+ const report = entry.report;+ drawHeader(+ writer,+ t,+ entry.fileName,+ report+ ? t(+ "checkAccessibility.score.subtitle",+ "{{profile}} - {{count}} pages",+ { profile: report.profile, count: report.summary.pages },+ )+ : null,+ );+ if (report) {+ const assessment = assessAccessibilityReport(report);+ drawResult(writer, t, report, assessment);+ drawBreakdown(writer, t, report, assessment);+ drawManualChecks(writer, t, report, manualTicked);+ } else {+ drawFailedEntry(writer, t, entry);+ }++ const bytes = await doc.save();+ return new File(+ [bytes.slice().buffer],+ accessibilityReportPdfName(entry.fileName),+ { type: "application/pdf" },+ );+}diff --git a/frontend/src/editor/core/hooks/tools/checkAccessibility/useCheckAccessibilityOperation.test.ts b/frontend/src/editor/core/hooks/tools/checkAccessibility/useCheckAccessibilityOperation.test.tsnew file mode 100644index 0000000000..416f88b387--- /dev/null+++ b/frontend/src/editor/core/hooks/tools/checkAccessibility/useCheckAccessibilityOperation.test.ts@@ -0,0 +1,173 @@+import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";+import { act, renderHook, waitFor } from "@testing-library/react";++vi.mock("@editor/services/apiClient", () => ({+ default: { post: vi.fn() },+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (_key: string, fallback?: string) => fallback ?? _key,+ }),+}));++import apiClient from "@editor/services/apiClient";+import { createStirlingFile } from "@editor/types/fileContext";+import { useCheckAccessibilityOperation } from "@editor/hooks/tools/checkAccessibility/useCheckAccessibilityOperation";+import { defaultParameters } from "@editor/hooks/tools/checkAccessibility/useCheckAccessibilityParameters";+import type { AccessibilityReport } from "@editor/types/checkAccessibility";++function pdf(name: string) {+ return createStirlingFile(+ new File(["%PDF-1.7"], name, { type: "application/pdf" }),+ );+}++function report(overrides: Partial<AccessibilityReport> = {}) {+ return {+ profile: "PDF/UA-1",+ tagged: true,+ declaresConformance: true,+ passesAutomatedChecks: true,+ issues: [],+ humanChecks: [],+ automaticallyFixable: 0,+ needsInput: 0,+ figuresNeedingDescription: [],+ summary: {+ pages: 1,+ hasTitle: true,+ displaysDocTitle: true,+ hasLanguage: true,+ allFontsEmbedded: true,+ unembeddedFonts: 0,+ figures: 0,+ encrypted: false,+ },+ ...overrides,+ } satisfies AccessibilityReport;+}++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((r) => {+ resolve = r;+ });+ return { promise, resolve };+}++describe("useCheckAccessibilityOperation", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("treats a report the validator could not produce as a failed file", async () => {+ (apiClient.post as Mock).mockResolvedValue({+ data: report({+ passesAutomatedChecks: false,+ validationError: "Validation could not run: bad xref",+ }),+ });+ const { result } = renderHook(() => useCheckAccessibilityOperation());++ await act(() =>+ result.current.executeOperation(defaultParameters, [pdf("a.pdf")]),+ );++ expect(result.current.results).toHaveLength(1);+ expect(result.current.results[0].report).toBeNull();+ expect(result.current.results[0].error).toBe(+ "Validation could not run: bad xref",+ );+ expect(result.current.errorMessage).toBe(+ "Some files could not be checked.",+ );+ });++ it("keeps a cancelled run from resuming beside the run that replaced it", async () => {+ const stalled = deferred<{ data: AccessibilityReport }>();+ (apiClient.post as Mock)+ .mockReturnValueOnce(stalled.promise)+ .mockResolvedValue({ data: report() });+ const { result } = renderHook(() => useCheckAccessibilityOperation());++ let firstRun!: Promise<void>;+ act(() => {+ firstRun = result.current.executeOperation(defaultParameters, [+ pdf("old-1.pdf"),+ pdf("old-2.pdf"),+ ]);+ });+ await waitFor(() => expect(result.current.isLoading).toBe(true));+ act(() => result.current.cancelOperation());++ await act(() =>+ result.current.executeOperation(defaultParameters, [pdf("new.pdf")]),+ );+ await act(async () => {+ stalled.resolve({ data: report() });+ await firstRun;+ });++ expect(result.current.results.map((entry) => entry.fileName)).toEqual([+ "new.pdf",+ ]);+ expect(apiClient.post).toHaveBeenCalledTimes(2);+ expect(result.current.isLoading).toBe(false);+ });+ it("stops loading when results are reset mid-run", async () => {+ const stalled = deferred<{ data: AccessibilityReport }>();+ (apiClient.post as Mock).mockReturnValueOnce(stalled.promise);+ const { result } = renderHook(() => useCheckAccessibilityOperation());++ let run!: Promise<void>;+ act(() => {+ run = result.current.executeOperation(defaultParameters, [pdf("a.pdf")]);+ });+ await waitFor(() => expect(result.current.isLoading).toBe(true));+ act(() => result.current.resetResults());+ expect(result.current.isLoading).toBe(false);++ await act(async () => {+ stalled.resolve({ data: report() });+ await run;+ });+ expect(result.current.isLoading).toBe(false);+ expect(result.current.results).toEqual([]);+ });++ it("aborts the request in flight and checks no more files once unmounted", async () => {+ const stalled = deferred<{ data: AccessibilityReport }>();+ (apiClient.post as Mock).mockReturnValueOnce(stalled.promise);+ const { result, unmount } = renderHook(() =>+ useCheckAccessibilityOperation(),+ );++ let run!: Promise<void>;+ act(() => {+ run = result.current.executeOperation(defaultParameters, [+ pdf("a.pdf"),+ pdf("b.pdf"),+ ]);+ });+ await waitFor(() => expect(apiClient.post).toHaveBeenCalledTimes(1));+ const { signal } = (apiClient.post as Mock).mock.calls[0][2] as {+ signal: AbortSignal;+ };+ unmount();+ expect(signal.aborted).toBe(true);++ stalled.resolve({ data: report() });+ await run;+ expect(apiClient.post).toHaveBeenCalledTimes(1);+ });++ it("leaves files empty so the next selection change clears the report", async () => {+ (apiClient.post as Mock).mockResolvedValue({ data: report() });+ const { result } = renderHook(() => useCheckAccessibilityOperation());+ await act(() =>+ result.current.executeOperation(defaultParameters, [pdf("a.pdf")]),+ );+ expect(result.current.results).toHaveLength(1);+ expect(result.current.files).toEqual([]);+ });+});diff --git a/frontend/src/editor/core/hooks/tools/checkAccessibility/useCheckAccessibilityOperation.ts b/frontend/src/editor/core/hooks/tools/checkAccessibility/useCheckAccessibilityOperation.tsnew file mode 100644index 0000000000..0ad8c5baa9--- /dev/null+++ b/frontend/src/editor/core/hooks/tools/checkAccessibility/useCheckAccessibilityOperation.ts@@ -0,0 +1,179 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import apiClient from "@editor/services/apiClient";+import { ToolOperationHook } from "@editor/hooks/tools/shared/useToolOperation";+import type { StirlingFile } from "@editor/types/fileContext";+import { extractErrorMessage } from "@editor/utils/toolErrorHandler";+import type {+ AccessibilityReport,+ AccessibilityReportEntry,+} from "@editor/types/checkAccessibility";+import type { CheckAccessibilityParameters } from "@editor/hooks/tools/checkAccessibility/useCheckAccessibilityParameters";++const NO_FILES: File[] = [];++export interface CheckAccessibilityOperationHook extends ToolOperationHook<CheckAccessibilityParameters> {+ results: AccessibilityReportEntry[];+}++/**+ * Reports on each file in turn without changing it. `files` stays empty: a file there makes+ * useBaseTool skip the next selection change, which would leave the old report on screen.+ */+export const useCheckAccessibilityOperation =+ (): CheckAccessibilityOperationHook => {+ const { t } = useTranslation();+ const [isLoading, setIsLoading] = useState(false);+ const [status, setStatus] = useState("");+ const [errorMessage, setErrorMessage] = useState<string | null>(null);+ const [results, setResults] = useState<AccessibilityReportEntry[]>([]);+ // Each run takes the next id; a run whose id is no longer current was cancelled or replaced+ // and must not touch state, or a cancelled run could resume beside the run that replaced it.+ const currentRun = useRef(0);+ const runAbort = useRef<AbortController | null>(null);++ /** Stops the current run, including the request in flight, so it is not billed for nothing. */+ const stopRun = useCallback(() => {+ currentRun.current += 1;+ runAbort.current?.abort();+ runAbort.current = null;+ }, []);++ useEffect(() => stopRun, [stopRun]);++ const resetResults = useCallback(() => {+ stopRun();+ // The run this just invalidated may no longer touch state, so it cannot clear loading itself.+ setIsLoading(false);+ setResults([]);+ setStatus("");+ setErrorMessage(null);+ }, [stopRun]);++ const clearError = useCallback(() => setErrorMessage(null), []);++ const executeOperation = useCallback(+ async (+ params: CheckAccessibilityParameters,+ selectedFiles: StirlingFile[],+ ) => {+ if (selectedFiles.length === 0) {+ setErrorMessage(t("noFileSelected", "No file loaded"));+ return;+ }++ stopRun();+ const run = currentRun.current;+ const abort = new AbortController();+ runAbort.current = abort;+ const isCurrent = () => run === currentRun.current;+ setIsLoading(true);+ setErrorMessage(null);+ setResults([]);++ const collected: AccessibilityReportEntry[] = [];+ try {+ for (const [index, file] of selectedFiles.entries()) {+ if (!isCurrent()) return;+ setStatus(+ t(+ "checkAccessibility.status.checking",+ "Checking {{current}} of {{total}}...",+ {+ current: index + 1,+ total: selectedFiles.length,+ },+ ),+ );++ const formData = new FormData();+ formData.append("fileInput", file);+ formData.append("profile", params.profile);+ try {+ const { data } = await apiClient.post<AccessibilityReport>(+ "/api/v1/security/accessibility-report",+ formData,+ { signal: abort.signal },+ );+ // A report the validator could not produce describes the failure, not the file,+ // so scoring it would grade a document nothing has checked.+ collected.push({+ fileId: file.fileId,+ fileName: file.name,+ report: data.validationError ? null : data,+ error: data.validationError ?? null,+ });+ } catch (error) {+ collected.push({+ fileId: file.fileId,+ fileName: file.name,+ report: null,+ error: extractErrorMessage(error),+ });+ }+ if (!isCurrent()) return;+ // Publishing as each file lands lets the first report render while the rest run.+ setResults([...collected]);+ }++ if (collected.some((entry) => entry.error)) {+ setErrorMessage(+ t(+ "checkAccessibility.error.partial",+ "Some files could not be checked.",+ ),+ );+ }+ setStatus(t("checkAccessibility.status.complete", "Check complete"));+ } finally {+ if (isCurrent()) {+ runAbort.current = null;+ setIsLoading(false);+ }+ }+ },+ [stopRun, t],+ );++ const cancelOperation = useCallback(() => {+ if (!isLoading) return;+ stopRun();+ setIsLoading(false);+ setStatus(t("operationCancelled", "Operation cancelled"));+ }, [isLoading, stopRun, t]);++ const undoOperation = useCallback(async () => {+ resetResults();+ }, [resetResults]);++ return useMemo<CheckAccessibilityOperationHook>(+ () => ({+ files: NO_FILES,+ thumbnails: [],+ isGeneratingThumbnails: false,+ downloadUrl: null,+ downloadFilename: "",+ isLoading,+ status,+ errorMessage,+ progress: null,+ executeOperation,+ resetResults,+ clearError,+ cancelOperation,+ undoOperation,+ results,+ }),+ [+ cancelOperation,+ clearError,+ errorMessage,+ executeOperation,+ isLoading,+ resetResults,+ results,+ status,+ undoOperation,+ ],+ );+ };diff --git a/frontend/src/editor/core/hooks/tools/checkAccessibility/useCheckAccessibilityParameters.ts b/frontend/src/editor/core/hooks/tools/checkAccessibility/useCheckAccessibilityParameters.tsnew file mode 100644index 0000000000..5652331ac8--- /dev/null+++ b/frontend/src/editor/core/hooks/tools/checkAccessibility/useCheckAccessibilityParameters.ts@@ -0,0 +1,26 @@+import { BaseParameters } from "@editor/types/parameters";+import {+ useBaseParameters,+ BaseParametersHook,+} from "@editor/hooks/tools/shared/useBaseParameters";++export type AccessibilityProfile = "ua1" | "ua2";++export interface CheckAccessibilityParameters extends BaseParameters {+ profile: AccessibilityProfile;+}++export const defaultParameters: CheckAccessibilityParameters = {+ profile: "ua1",+};++export type CheckAccessibilityParametersHook =+ BaseParametersHook<CheckAccessibilityParameters>;++export const useCheckAccessibilityParameters =+ (): CheckAccessibilityParametersHook => {+ return useBaseParameters({+ defaultParameters,+ endpointName: "accessibility-report",+ });+ };diff --git a/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/CenteredMessageSection.ts b/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/CenteredMessageSection.tsindex 0f2d7930aa..c9ce83a4bd 100644--- a/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/CenteredMessageSection.ts+++ b/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/CenteredMessageSection.ts@@ -1,6 +1,6 @@import { PdfiumFont, PdfiumPage, rgb } from "@editor/services/pdfiumDocBuilder";-import { wrapText } from "@editor/hooks/tools/validateSignature/utils/pdfText";-import { colorPalette } from "@editor/hooks/tools/validateSignature/utils/pdfPalette";+import { wrapText } from "@editor/services/reportPdf/reportText";+import { colorPalette } from "@editor/services/reportPdf/reportPalette";interface DrawCenteredMessageOptions {page: PdfiumPage;diff --git a/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/FieldBoxSection.ts b/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/FieldBoxSection.tsindex 62a446e802..086b0bf5ea 100644--- a/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/FieldBoxSection.ts+++ b/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/FieldBoxSection.ts@@ -1,6 +1,6 @@import { PdfiumFont, PdfiumPage } from "@editor/services/pdfiumDocBuilder";-import { wrapText } from "@editor/hooks/tools/validateSignature/utils/pdfText";-import { colorPalette } from "@editor/hooks/tools/validateSignature/utils/pdfPalette";+import { wrapText } from "@editor/services/reportPdf/reportText";+import { colorPalette } from "@editor/services/reportPdf/reportPalette";interface FieldBoxOptions {page: PdfiumPage;diff --git a/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/SignatureSection.ts b/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/SignatureSection.tsindex 6d82c0d355..d4db935177 100644--- a/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/SignatureSection.ts+++ b/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/SignatureSection.ts@@ -5,10 +5,8 @@ import { drawFieldBox } from "@editor/hooks/tools/validateSignature/outputtedPDFimport { drawStatusBadge } from "@editor/hooks/tools/validateSignature/outputtedPDFSections/StatusBadgeSection";import { computeSignatureStatus } from "@editor/hooks/tools/validateSignature/utils/signatureStatus";import { formatDate } from "@editor/hooks/tools/validateSignature/utils/pdfText";-import {- colorPalette,- statusKindToPdfColor,-} from "@editor/hooks/tools/validateSignature/utils/pdfPalette";+import { colorPalette } from "@editor/services/reportPdf/reportPalette";+import { statusKindToPdfColor } from "@editor/hooks/tools/validateSignature/utils/pdfPalette";interface DrawSignatureSectionOptions {page: PdfiumPage;diff --git a/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/SummarySection.ts b/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/SummarySection.tsindex d4a4f91835..42cecfb1bb 100644--- a/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/SummarySection.ts+++ b/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/SummarySection.ts@@ -10,7 +10,7 @@ import {drawThumbnailImage,drawThumbnailPlaceholder,} from "@editor/hooks/tools/validateSignature/outputtedPDFSections/ThumbnailSection";-import { colorPalette } from "@editor/hooks/tools/validateSignature/utils/pdfPalette";+import { colorPalette } from "@editor/services/reportPdf/reportPalette";import { formatFileSize } from "@editor/hooks/tools/validateSignature/utils/pdfText";interface DrawSummarySectionOptions {diff --git a/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/ThumbnailSection.ts b/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/ThumbnailSection.tsindex cfff1446b2..7bef4c4daf 100644--- a/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/ThumbnailSection.ts+++ b/frontend/src/editor/core/hooks/tools/validateSignature/outputtedPDFSections/ThumbnailSection.ts@@ -3,7 +3,7 @@ import {PdfiumPage,PdfiumImage,} from "@editor/services/pdfiumDocBuilder";-import { colorPalette } from "@editor/hooks/tools/validateSignature/utils/pdfPalette";+import { colorPalette } from "@editor/services/reportPdf/reportPalette";export const drawThumbnailPlaceholder = (page: PdfiumPage,diff --git a/frontend/src/editor/core/hooks/tools/validateSignature/signatureReportPdf.ts b/frontend/src/editor/core/hooks/tools/validateSignature/signatureReportPdf.tsindex f40c0f0e1c..59cabc07af 100644--- a/frontend/src/editor/core/hooks/tools/validateSignature/signatureReportPdf.ts+++ b/frontend/src/editor/core/hooks/tools/validateSignature/signatureReportPdf.ts@@ -6,7 +6,8 @@ import {import type { TFunction } from "i18next";import { SignatureValidationReportEntry } from "@editor/types/validateSignature";import { REPORT_PDF_FILENAME } from "@editor/hooks/tools/validateSignature/utils/signatureUtils";-import { colorPalette } from "@editor/hooks/tools/validateSignature/utils/pdfPalette";+import { colorPalette } from "@editor/services/reportPdf/reportPalette";+import { LETTER_PAGE } from "@editor/services/reportPdf/ReportWriter";import {startReportPage,createThumbnailLoader,@@ -16,8 +17,8 @@ import { drawCenteredMessage } from "@editor/hooks/tools/validateSignature/outpuimport { drawSummarySection } from "@editor/hooks/tools/validateSignature/outputtedPDFSections/SummarySection";import { drawSignatureSection } from "@editor/hooks/tools/validateSignature/outputtedPDFSections/SignatureSection";-const PAGE_WIDTH = 612;-const PAGE_HEIGHT = 792;+const PAGE_WIDTH = LETTER_PAGE.width;+const PAGE_HEIGHT = LETTER_PAGE.height;const MARGIN_X = 52;const MARGIN_Y = 22;const CONTENT_WIDTH = PAGE_WIDTH - MARGIN_X * 2;diff --git a/frontend/src/editor/core/hooks/tools/validateSignature/utils/pdfPageHelpers.ts b/frontend/src/editor/core/hooks/tools/validateSignature/utils/pdfPageHelpers.tsindex f88ac88231..a37d393c36 100644--- a/frontend/src/editor/core/hooks/tools/validateSignature/utils/pdfPageHelpers.ts+++ b/frontend/src/editor/core/hooks/tools/validateSignature/utils/pdfPageHelpers.ts@@ -4,7 +4,7 @@ import {PdfiumImage,} from "@editor/services/pdfiumDocBuilder";import type { TFunction } from "i18next";-import { colorPalette } from "@editor/hooks/tools/validateSignature/utils/pdfPalette";+import { colorPalette } from "@editor/services/reportPdf/reportPalette";interface StartPageParams {doc: PdfiumDocument;diff --git a/frontend/src/editor/core/hooks/tools/validateSignature/utils/pdfPalette.ts b/frontend/src/editor/core/hooks/tools/validateSignature/utils/pdfPalette.tsindex b9a3661faf..9b6d3cc49b 100644--- a/frontend/src/editor/core/hooks/tools/validateSignature/utils/pdfPalette.ts+++ b/frontend/src/editor/core/hooks/tools/validateSignature/utils/pdfPalette.ts@@ -1,100 +1,6 @@-import { rgb } from "@editor/services/pdfiumDocBuilder";+import { colorPalette } from "@editor/services/reportPdf/reportPalette";import type { SignatureStatusKind } from "@editor/hooks/tools/validateSignature/utils/signatureStatus";-type RgbTuple = [number, number, number];--const defaultLightPalette: Record<- | "headerBackground"- | "accent"- | "textPrimary"- | "textMuted"- | "boxBackground"- | "boxBorder"- | "warning"- | "danger"- | "success"- | "neutral",- RgbTuple-> = {- headerBackground: [239, 246, 255],- accent: [59, 130, 246],- textPrimary: [30, 41, 59],- textMuted: [100, 116, 139],- boxBackground: [248, 250, 252],- boxBorder: [226, 232, 240],- warning: [234, 179, 8],- danger: [248, 113, 113],- success: [34, 197, 94],- neutral: [148, 163, 184],-};--const toRgb = ([r, g, b]: RgbTuple) => rgb(r / 255, g / 255, b / 255);--/**- * Utility function to get CSS variable values and convert them to RGB format.- * Falls back to sensible defaults when the CSS variable cannot be resolved.- */-function getCssVariableAsRgb(variableName: string, fallback: RgbTuple) {- if (typeof window === "undefined") {- return toRgb(fallback);- }-- const value = getComputedStyle(document.documentElement)- .getPropertyValue(variableName)- .trim();-- if (!value) {- console.warn(`CSS variable ${variableName} not found, using fallback`);- return toRgb(fallback);- }-- const [r, g, b] = value.split(" ").map(Number);-- if ([r, g, b].some((component) => Number.isNaN(component))) {- console.warn(`Invalid CSS variable format for ${variableName}: ${value}`);- return toRgb(fallback);- }-- return rgb(r / 255, g / 255, b / 255);-}--export const colorPalette = {- headerBackground: getCssVariableAsRgb(- "--pdf-light-header-bg",- defaultLightPalette.headerBackground,- ),- accent: getCssVariableAsRgb("--pdf-light-accent", defaultLightPalette.accent),- textPrimary: getCssVariableAsRgb(- "--pdf-light-text-primary",- defaultLightPalette.textPrimary,- ),- textMuted: getCssVariableAsRgb(- "--pdf-light-text-muted",- defaultLightPalette.textMuted,- ),- boxBackground: getCssVariableAsRgb(- "--pdf-light-box-bg",- defaultLightPalette.boxBackground,- ),- boxBorder: getCssVariableAsRgb(- "--pdf-light-box-border",- defaultLightPalette.boxBorder,- ),- warning: getCssVariableAsRgb(- "--pdf-light-warning",- defaultLightPalette.warning,- ),- danger: getCssVariableAsRgb("--pdf-light-danger", defaultLightPalette.danger),- success: getCssVariableAsRgb(- "--pdf-light-success",- defaultLightPalette.success,- ),- neutral: getCssVariableAsRgb(- "--pdf-light-neutral",- defaultLightPalette.neutral,- ),-};-export const statusKindToPdfColor = (kind: SignatureStatusKind) => {switch (kind) {case "valid":diff --git a/frontend/src/editor/core/hooks/tools/validateSignature/utils/pdfText.ts b/frontend/src/editor/core/hooks/tools/validateSignature/utils/pdfText.tsindex bdc0d52d66..4264266512 100644--- a/frontend/src/editor/core/hooks/tools/validateSignature/utils/pdfText.ts+++ b/frontend/src/editor/core/hooks/tools/validateSignature/utils/pdfText.ts@@ -1,44 +1,3 @@-import { PdfiumFont } from "@editor/services/pdfiumDocBuilder";--export const wrapText = (- text: string,- font: PdfiumFont,- fontSize: number,- maxWidth: number,-): string[] => {- const lines: string[] = [];- const paragraphs = text.split(/\r?\n/);-- paragraphs.forEach((paragraph) => {- const trimmed = paragraph.trim();- if (trimmed.length === 0) {- lines.push("");- return;- }-- const words = trimmed.split(/\s+/);- let currentLine = "";- words.forEach((word) => {- const tentative =- currentLine.length > 0 ? `${currentLine} ${word}` : word;- const width = font.widthOfTextAtSize(tentative, fontSize);- if (width <= maxWidth) {- currentLine = tentative;- } else {- if (currentLine.length > 0) {- lines.push(currentLine);- }- currentLine = word;- }- });- if (currentLine.length > 0) {- lines.push(currentLine);- }- });-- return lines;-};-export const formatFileSize = (bytes?: number | null) => {if (!bytes || bytes <= 0) return "--";const units = ["B", "KB", "MB", "GB"];diff --git a/frontend/src/editor/core/hooks/tools/validateSignature/utils/reportStatus.ts b/frontend/src/editor/core/hooks/tools/validateSignature/utils/reportStatus.tsindex 6b8863343e..4a313a082e 100644--- a/frontend/src/editor/core/hooks/tools/validateSignature/utils/reportStatus.ts+++ b/frontend/src/editor/core/hooks/tools/validateSignature/utils/reportStatus.ts@@ -1,6 +1,6 @@import type { TFunction } from "i18next";import { SignatureValidationReportEntry } from "@editor/types/validateSignature";-import { colorPalette } from "@editor/hooks/tools/validateSignature/utils/pdfPalette";+import { colorPalette } from "@editor/services/reportPdf/reportPalette";export const deriveEntryStatus = (entry: Pick<SignatureValidationReportEntry, "error" | "signatures">,diff --git a/frontend/src/editor/core/hooks/useToolPanelSize.test.ts b/frontend/src/editor/core/hooks/useToolPanelSize.test.tsnew file mode 100644index 0000000000..8d957e2cac--- /dev/null+++ b/frontend/src/editor/core/hooks/useToolPanelSize.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from "vitest";+import { renderHook, waitFor } from "@testing-library/react";+import {+ TOOL_PANEL_WIDTHS,+ useToolPanelSize,+ useToolPanelWidth,+} from "@editor/hooks/useToolPanelSize";++describe("useToolPanelSize", () => {+ it("widens the panel while mounted and restores sm on unmount", async () => {+ const width = renderHook(() => useToolPanelWidth());+ expect(width.result.current).toBe(TOOL_PANEL_WIDTHS.sm);++ const request = renderHook(() => useToolPanelSize("lg"));+ await waitFor(() =>+ expect(width.result.current).toBe(TOOL_PANEL_WIDTHS.lg),+ );++ request.unmount();+ await waitFor(() =>+ expect(width.result.current).toBe(TOOL_PANEL_WIDTHS.sm),+ );+ });++ it("keeps the incoming tool's size when one tool replaces another", async () => {+ const width = renderHook(() => useToolPanelWidth());+ const outgoing = renderHook(() => useToolPanelSize("md"));+ await waitFor(() =>+ expect(width.result.current).toBe(TOOL_PANEL_WIDTHS.md),+ );++ outgoing.unmount();+ const incoming = renderHook(() => useToolPanelSize("lg"));+ await waitFor(() =>+ expect(width.result.current).toBe(TOOL_PANEL_WIDTHS.lg),+ );+ incoming.unmount();+ await waitFor(() =>+ expect(width.result.current).toBe(TOOL_PANEL_WIDTHS.sm),+ );+ });+});diff --git a/frontend/src/editor/core/hooks/useToolPanelSize.ts b/frontend/src/editor/core/hooks/useToolPanelSize.tsnew file mode 100644index 0000000000..51695293de--- /dev/null+++ b/frontend/src/editor/core/hooks/useToolPanelSize.ts@@ -0,0 +1,41 @@+import { useEffect, useSyncExternalStore } from "react";++export type ToolPanelSize = "sm" | "md" | "lg";++/** md and lg are sm grown by 25% and 50%, rounded to whole rems. */+export const TOOL_PANEL_WIDTHS: Record<ToolPanelSize, string> = {+ sm: "18.5rem",+ md: "23rem",+ lg: "28rem",+};++let currentSize: ToolPanelSize = "sm";+const listeners = new Set<() => void>();++const subscribe = (listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+};++/** Sets the desktop tool panel width until something sets it again. */+export function setToolPanelSize(size: ToolPanelSize): void {+ if (size === currentSize) return;+ currentSize = size;+ listeners.forEach((listener) => listener());+}++/**+ * Holds the tool panel at `size` while mounted, then returns it to sm. React runs an outgoing+ * tool's cleanup before the incoming tool's effect, so the incoming tool's size wins.+ */+export function useToolPanelSize(size: ToolPanelSize): void {+ useEffect(() => {+ setToolPanelSize(size);+ return () => setToolPanelSize("sm");+ }, [size]);+}++/** The desktop tool panel's current width, as a CSS length. */+export function useToolPanelWidth(): string {+ return TOOL_PANEL_WIDTHS[useSyncExternalStore(subscribe, () => currentSize)];+}diff --git a/frontend/src/editor/core/icons/icons.ts b/frontend/src/editor/core/icons/icons.tsindex eb9dc07979..84e0f2f393 100644--- a/frontend/src/editor/core/icons/icons.ts+++ b/frontend/src/editor/core/icons/icons.ts@@ -383,6 +383,7 @@ import SinglePage from "@editor/icons/svg/stirling/single-page.svg?react";import StirlingMark from "@editor/icons/svg/stirling/stirling-mark.svg?react";import StirlingMarkThinking from "@editor/icons/svg/stirling/stirling-mark-thinking.svg?react";import StirlingTile from "@editor/icons/svg/stirling/stirling-tile.svg?react";+import UniversalAccess from "@editor/icons/svg/stirling/universal-access.svg?react";import UsersPlus from "@editor/icons/svg/stirling/users-plus.svg?react";import Watermark from "@editor/icons/svg/stirling/watermark.svg?react";@@ -816,6 +817,7 @@ export const ICONS = {"stirling-mark": { Component: StirlingMark, kind: "brand" },"stirling-mark-thinking": { Component: StirlingMarkThinking, kind: "brand" },"stirling-tile": { Component: StirlingTile, kind: "brand" },+ "universal-access": { Component: UniversalAccess, kind: "stirling" },"users-plus": { Component: UsersPlus, kind: "stirling" },watermark: { Component: Watermark, kind: "stirling" },apple: { Component: Apple, kind: "brand" },diff --git a/frontend/src/editor/core/icons/svg/stirling/universal-access.svg b/frontend/src/editor/core/icons/svg/stirling/universal-access.svgnew file mode 100644index 0000000000..f0e2bb8802--- /dev/null+++ b/frontend/src/editor/core/icons/svg/stirling/universal-access.svg@@ -0,0 +1,7 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">+ <circle cx="12" cy="12" r="9" />+ <circle cx="12" cy="6.75" r="1.25" />+ <path d="m7.5 9.75 4.5 1.25 4.5-1.25" />+ <path d="M12 11v3" />+ <path d="m9.75 18 2.25-4 2.25 4" />+</svg>diff --git a/frontend/src/editor/core/services/pdfiumDocBuilder.ts b/frontend/src/editor/core/services/pdfiumDocBuilder.tsindex 38c4590c77..2f4edf7f02 100644--- a/frontend/src/editor/core/services/pdfiumDocBuilder.ts+++ b/frontend/src/editor/core/services/pdfiumDocBuilder.ts@@ -76,7 +76,8 @@ export class PdfiumFont {*/widthOfTextAtSize(text: string, fontSize: number): number {const ctx = this._getCtx();- ctx.font = `${fontSize}px "${this._cssFontFamily()}"`;+ // Unquoted: quoting the list makes one unknown family, measured in a fallback font.+ ctx.font = `${fontSize}px ${this._cssFontFamily()}`;return ctx.measureText(text).width;}diff --git a/frontend/src/editor/core/services/reportPdf/ReportWriter.test.ts b/frontend/src/editor/core/services/reportPdf/ReportWriter.test.tsnew file mode 100644index 0000000000..834c6a4bb3--- /dev/null+++ b/frontend/src/editor/core/services/reportPdf/ReportWriter.test.ts@@ -0,0 +1,125 @@+import { describe, expect, it } from "vitest";+import {+ rgb,+ type PdfiumDocument,+ type PdfiumFont,+} from "@editor/services/pdfiumDocBuilder";+import {+ LETTER_PAGE,+ ReportWriter,+ type ReportLayout,+} from "@editor/services/reportPdf/ReportWriter";++interface DrawnText {+ page: number;+ text: string;+ x: number;+ y: number;+}++/** Records drawn text per page; each character is half the font size wide. */+function fakeDocument() {+ const drawn: DrawnText[] = [];+ let pages = 0;+ const doc = {+ addPage: () => {+ const page = ++pages;+ return {+ drawText: (text: string, options: { x: number; y: number }) =>+ drawn.push({ page, text, x: options.x, y: options.y }),+ drawRectangle: () => {},+ drawLine: () => {},+ };+ },+ getPageCount: () => pages,+ };+ return {+ doc: doc as unknown as PdfiumDocument,+ drawn,+ pageCount: () => pages,+ };+}++const font = {+ widthOfTextAtSize: (text: string, size: number) => text.length * size * 0.5,+} as unknown as PdfiumFont;++const BLACK = rgb(0, 0, 0);++const layout: ReportLayout = {+ pageWidth: LETTER_PAGE.width,+ pageHeight: LETTER_PAGE.height,+ marginX: 50,+ marginTop: 40,+ marginBottom: 60,+};++function writerFor(doc: PdfiumDocument) {+ return new ReportWriter(doc, {+ layout,+ regular: font,+ bold: font,+ footerText: "Footer",+ pageLabel: (n) => `Page ${n}`,+ });+}++describe("ReportWriter", () => {+ it("opens a section on a new page below the top margin, with its footer", () => {+ const { doc, drawn } = fakeDocument();+ const writer = writerFor(doc);++ writer.startSection("Report (continued)");++ expect(writer.y).toBe(layout.pageHeight - layout.marginTop);+ expect(drawn).toContainEqual({ page: 1, text: "Footer", x: 50, y: 30 });+ const label = drawn.find((d) => d.text === "Page 1");+ expect(label).toBeDefined();+ // Right-aligned: "Page 1" is 6 chars at size 8, so 24pt wide.+ expect(label!.x).toBe(layout.pageWidth - layout.marginX - 24);+ });++ it("moves below each line by the line height", () => {+ const { doc } = fakeDocument();+ const writer = writerFor(doc);+ writer.startSection("");+ const top = writer.y;++ writer.text("Hello", 50, { font, size: 10, color: BLACK });++ expect(writer.y).toBeCloseTo(top - 13.5);+ });++ it("breaks a long paragraph onto a new page that opens with the continuation title", () => {+ const { doc, drawn, pageCount } = fakeDocument();+ const writer = writerFor(doc);+ writer.startSection("Report (continued)");+ const words = Array.from({ length: 2000 }, (_, i) => `word${i}`).join(" ");++ writer.paragraph(words, 50, writer.contentWidth, {+ font,+ size: 10,+ color: BLACK,+ });++ expect(pageCount()).toBeGreaterThan(1);+ expect(drawn).toContainEqual(+ expect.objectContaining({ page: 2, text: "Report (continued)" }),+ );+ expect(drawn).toContainEqual(+ expect.objectContaining({ page: 2, text: "Page 2" }),+ );+ const body = drawn.filter((d) => d.text.startsWith("word"));+ expect(body.every((d) => d.y >= layout.marginBottom - 10)).toBe(true);+ });++ it("stays on the page while the block fits above the footer", () => {+ const { doc, pageCount } = fakeDocument();+ const writer = writerFor(doc);+ writer.startSection("");++ writer.ensure(writer.y - layout.marginBottom);++ expect(pageCount()).toBe(1);+ });+});diff --git a/frontend/src/editor/core/services/reportPdf/ReportWriter.ts b/frontend/src/editor/core/services/reportPdf/ReportWriter.tsnew file mode 100644index 0000000000..709a881a40--- /dev/null+++ b/frontend/src/editor/core/services/reportPdf/ReportWriter.ts@@ -0,0 +1,180 @@+import {+ PdfiumDocument,+ PdfiumFont,+ PdfiumPage,+ type PdfiumColor,+} from "@editor/services/pdfiumDocBuilder";+import { colorPalette } from "@editor/services/reportPdf/reportPalette";+import { wrapText } from "@editor/services/reportPdf/reportText";++/** US Letter in PDF points, the page every generated report uses. */+export const LETTER_PAGE = { width: 612, height: 792 } as const;++/** Page geometry in PDF points. The footer sits halfway into the bottom margin. */+export interface ReportLayout {+ pageWidth: number;+ pageHeight: number;+ marginX: number;+ marginTop: number;+ marginBottom: number;+}++export interface TextStyle {+ font: PdfiumFont;+ size: number;+ color: PdfiumColor;+}++export interface ReportWriterOptions {+ layout: ReportLayout;+ regular: PdfiumFont;+ bold: PdfiumFont;+ /** Drawn bottom-left on every page. */+ footerText: string;+ /** Drawn bottom-right on every page, given the one-based page number. */+ pageLabel: (pageNumber: number) => string;+}++const LINE_HEIGHT = 1.35;++/**+ * Lays a report down pages, starting a new one before a block would reach the footer. y is the top+ * of the next block in PDF points from the page bottom, and callers move it down as they draw.+ */+export class ReportWriter {+ y = 0;+ readonly layout: ReportLayout;+ private page!: PdfiumPage;+ private continuationTitle = "";+ private readonly doc: PdfiumDocument;+ private readonly options: ReportWriterOptions;++ constructor(doc: PdfiumDocument, options: ReportWriterOptions) {+ this.doc = doc;+ this.options = options;+ this.layout = options.layout;+ }++ get font() {+ return this.options.regular;+ }++ get boldFont() {+ return this.options.bold;+ }++ get currentPage() {+ return this.page;+ }++ get contentWidth() {+ return this.layout.pageWidth - this.layout.marginX * 2;+ }++ /** Starts a new page; pages that `ensure` adds after it open with `continuationTitle`. */+ startSection(continuationTitle: string) {+ this.continuationTitle = continuationTitle;+ this.addPage();+ }++ /** Moves to a new page when fewer than `height` points remain above the footer. */+ ensure(height: number) {+ if (this.y - height < this.layout.marginBottom) {+ this.addPage();+ this.text(this.continuationTitle, this.layout.marginX, {+ font: this.options.bold,+ size: 9,+ color: colorPalette.textMuted,+ });+ this.y -= 10;+ }+ }++ /** Draws one line with its top at the current y and moves below it. */+ text(value: string, x: number, style: TextStyle) {+ this.page.drawText(value, {+ x,+ y: this.y - style.size,+ size: style.size,+ font: style.font,+ color: style.color,+ });+ this.y -= style.size * LINE_HEIGHT;+ }++ /** Wraps `value` to `width`, breaking pages between lines. */+ paragraph(value: string, x: number, width: number, style: TextStyle) {+ for (const line of wrapText(value, style.font, style.size, width)) {+ this.ensure(style.size * LINE_HEIGHT);+ this.text(line, x, style);+ }+ }++ /** Draws one line ending at `right`, leaving y where it was. */+ textRight(value: string, right: number, style: TextStyle) {+ const width = style.font.widthOfTextAtSize(value, style.size);+ this.page.drawText(value, {+ x: right - width,+ y: this.y - style.size,+ size: style.size,+ font: style.font,+ color: style.color,+ });+ }++ rect(+ x: number,+ top: number,+ width: number,+ height: number,+ color: PdfiumColor,+ borderColor?: PdfiumColor,+ ) {+ this.page.drawRectangle({+ x,+ y: top - height,+ width,+ height,+ color,+ borderColor,+ borderWidth: borderColor ? 0.75 : undefined,+ });+ }++ /** A full-width divider at `y`. */+ rule(y: number) {+ this.page.drawLine({+ start: { x: this.layout.marginX, y },+ end: { x: this.layout.marginX + this.contentWidth, y },+ thickness: 0.75,+ color: colorPalette.boxBorder,+ });+ }++ private addPage() {+ const { pageWidth, pageHeight, marginX, marginTop, marginBottom } =+ this.layout;+ this.page = this.doc.addPage([pageWidth, pageHeight]);+ this.y = pageHeight - marginTop;+ const footer: TextStyle = {+ font: this.options.regular,+ size: 8,+ color: colorPalette.textMuted,+ };+ const footerY = marginBottom / 2;+ this.page.drawText(this.options.footerText, {+ x: marginX,+ y: footerY,+ ...footer,+ });+ const pageLabel = this.options.pageLabel(this.doc.getPageCount());+ this.page.drawText(pageLabel, {+ x:+ marginX ++ this.contentWidth -+ this.options.regular.widthOfTextAtSize(pageLabel, footer.size),+ y: footerY,+ ...footer,+ });+ }+}diff --git a/frontend/src/editor/core/services/reportPdf/reportPalette.ts b/frontend/src/editor/core/services/reportPdf/reportPalette.tsnew file mode 100644index 0000000000..21fc258e57--- /dev/null+++ b/frontend/src/editor/core/services/reportPdf/reportPalette.ts@@ -0,0 +1,102 @@+import { rgb } from "@editor/services/pdfiumDocBuilder";++type RgbTuple = [number, number, number];++const defaultLightPalette: Record<+ | "headerBackground"+ | "accent"+ | "textPrimary"+ | "textMuted"+ | "boxBackground"+ | "boxBorder"+ | "warning"+ | "danger"+ | "success"+ | "neutral",+ RgbTuple+> = {+ headerBackground: [239, 246, 255],+ accent: [59, 130, 246],+ textPrimary: [30, 41, 59],+ textMuted: [100, 116, 139],+ boxBackground: [248, 250, 252],+ boxBorder: [226, 232, 240],+ warning: [234, 179, 8],+ danger: [248, 113, 113],+ success: [34, 197, 94],+ neutral: [148, 163, 184],+};++const toRgb = ([r, g, b]: RgbTuple) => rgb(r / 255, g / 255, b / 255);++/** Reads an "R G B" CSS variable, or the fallback when it is unset or malformed. */+function getCssVariableAsRgb(variableName: string, fallback: RgbTuple) {+ if (typeof window === "undefined") {+ return toRgb(fallback);+ }++ const value = getComputedStyle(document.documentElement)+ .getPropertyValue(variableName)+ .trim();++ if (!value) {+ console.warn(`CSS variable ${variableName} not found, using fallback`);+ return toRgb(fallback);+ }++ const [r, g, b] = value.split(" ").map(Number);++ if ([r, g, b].some((component) => Number.isNaN(component))) {+ console.warn(`Invalid CSS variable format for ${variableName}: ${value}`);+ return toRgb(fallback);+ }++ return rgb(r / 255, g / 255, b / 255);+}++export const colorPalette = {+ headerBackground: getCssVariableAsRgb(+ "--pdf-light-header-bg",+ defaultLightPalette.headerBackground,+ ),+ accent: getCssVariableAsRgb("--pdf-light-accent", defaultLightPalette.accent),+ textPrimary: getCssVariableAsRgb(+ "--pdf-light-text-primary",+ defaultLightPalette.textPrimary,+ ),+ textMuted: getCssVariableAsRgb(+ "--pdf-light-text-muted",+ defaultLightPalette.textMuted,+ ),+ boxBackground: getCssVariableAsRgb(+ "--pdf-light-box-bg",+ defaultLightPalette.boxBackground,+ ),+ boxBorder: getCssVariableAsRgb(+ "--pdf-light-box-border",+ defaultLightPalette.boxBorder,+ ),+ warning: getCssVariableAsRgb(+ "--pdf-light-warning",+ defaultLightPalette.warning,+ ),+ danger: getCssVariableAsRgb("--pdf-light-danger", defaultLightPalette.danger),+ success: getCssVariableAsRgb(+ "--pdf-light-success",+ defaultLightPalette.success,+ ),+ neutral: getCssVariableAsRgb(+ "--pdf-light-neutral",+ defaultLightPalette.neutral,+ ),+};++/**+ * Status colours dark enough for text on a white page. The palette's status colours are badge+ * fills and fall below text contrast there.+ */+export const statusTextColor = {+ success: toRgb([21, 128, 61]),+ warning: toRgb([161, 98, 7]),+ danger: toRgb([185, 28, 28]),+};diff --git a/frontend/src/editor/core/services/reportPdf/reportText.ts b/frontend/src/editor/core/services/reportPdf/reportText.tsnew file mode 100644index 0000000000..eda9c5dcaf--- /dev/null+++ b/frontend/src/editor/core/services/reportPdf/reportText.ts@@ -0,0 +1,41 @@+import { PdfiumFont } from "@editor/services/pdfiumDocBuilder";++/** Breaks text into lines no wider than maxWidth; each newline in the input starts a new line. */+export const wrapText = (+ text: string,+ font: PdfiumFont,+ fontSize: number,+ maxWidth: number,+): string[] => {+ const lines: string[] = [];+ const paragraphs = text.split(/\r?\n/);++ paragraphs.forEach((paragraph) => {+ const trimmed = paragraph.trim();+ if (trimmed.length === 0) {+ lines.push("");+ return;+ }++ const words = trimmed.split(/\s+/);+ let currentLine = "";+ words.forEach((word) => {+ const tentative =+ currentLine.length > 0 ? `${currentLine} ${word}` : word;+ const width = font.widthOfTextAtSize(tentative, fontSize);+ if (width <= maxWidth) {+ currentLine = tentative;+ } else {+ if (currentLine.length > 0) {+ lines.push(currentLine);+ }+ currentLine = word;+ }+ });+ if (currentLine.length > 0) {+ lines.push(currentLine);+ }+ });++ return lines;+};diff --git a/frontend/src/editor/core/tests/stubbed/all-tool-pages-load.spec.ts b/frontend/src/editor/core/tests/stubbed/all-tool-pages-load.spec.tsindex 4658444184..61624cfe79 100644--- a/frontend/src/editor/core/tests/stubbed/all-tool-pages-load.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/all-tool-pages-load.spec.ts@@ -64,6 +64,7 @@ const TOOL_IDS = ["changeMetadata","overlayPdfs","getPdfInfo",+ "checkAccessibility","validateSignature","timestampPdf","replaceColor",diff --git a/frontend/src/editor/core/tools/CheckAccessibility.tsx b/frontend/src/editor/core/tools/CheckAccessibility.tsxnew file mode 100644index 0000000000..9cacde81b7--- /dev/null+++ b/frontend/src/editor/core/tools/CheckAccessibility.tsx@@ -0,0 +1,103 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { createToolFlow } from "@editor/components/tools/shared/createToolFlow";+import { useBaseTool } from "@editor/hooks/tools/shared/useBaseTool";+import { useToolPanelSize } from "@editor/hooks/useToolPanelSize";+import { BaseToolProps, ToolComponent } from "@editor/types/tool";+import { Select } from "@editor/ui/Select";+import {+ defaultParameters,+ useCheckAccessibilityParameters,+ type AccessibilityProfile,+} from "@editor/hooks/tools/checkAccessibility/useCheckAccessibilityParameters";+import {+ useCheckAccessibilityOperation,+ type CheckAccessibilityOperationHook,+} from "@editor/hooks/tools/checkAccessibility/useCheckAccessibilityOperation";+import { AccessibilityResults } from "@editor/components/tools/checkAccessibility/AccessibilityResults";+import type { FileId } from "@editor/types/file";+import { useCheckAccessibilityTips } from "@editor/components/tooltips/useCheckAccessibilityTips";++const PROFILE_OPTIONS: { value: AccessibilityProfile; label: string }[] = [+ { value: "ua1", label: "PDF/UA-1" },+ { value: "ua2", label: "PDF/UA-2 (PDF 2.0)" },+];++const CheckAccessibility = (props: BaseToolProps) => {+ const { t } = useTranslation();+ useToolPanelSize("lg");+ const base = useBaseTool(+ "checkAccessibility",+ useCheckAccessibilityParameters,+ useCheckAccessibilityOperation,+ props,+ );+ const operation = base.operation as CheckAccessibilityOperationHook;+ const hasReports = operation.results.length > 0;+ const [selectedFileId, setSelectedFileId] = useState<FileId | null>(null);+ const profileTips = useCheckAccessibilityTips();++ return createToolFlow({+ files: {+ selectedFiles: base.selectedFiles,+ isCollapsed: hasReports,+ },+ steps: [+ {+ title: t("checkAccessibility.steps.standard", "Standard"),+ isCollapsed: hasReports,+ onCollapsedClick: base.handleSettingsReset,+ tooltip: profileTips,+ content: (+ <Select+ aria-label={t("checkAccessibility.steps.standard", "Standard")}+ options={PROFILE_OPTIONS}+ value={base.params.parameters.profile}+ onChange={(value) =>+ value &&+ base.params.updateParameter(+ "profile",+ value as AccessibilityProfile,+ )+ }+ allowDeselect={false}+ disabled={operation.isLoading}+ />+ ),+ },+ {+ title: t("checkAccessibility.steps.results", "Results"),+ isVisible: hasReports || operation.isLoading,+ isCollapsed: false,+ content: (+ <AccessibilityResults+ operation={operation}+ selectedFileId={selectedFileId}+ onSelectFile={setSelectedFileId}+ />+ ),+ },+ ],+ executeButton: {+ text: t("checkAccessibility.submit", "Check accessibility"),+ loadingText: t("checkAccessibility.checking", "Checking..."),+ onClick: base.handleExecute,+ endpointEnabled: base.endpointEnabled,+ paramsValid: base.params.validateParameters(),+ isVisible: !hasReports || operation.isLoading,+ testId: "check-accessibility-submit",+ },+ review: {+ isVisible: false,+ operation: base.operation,+ title: t("checkAccessibility.steps.results", "Results"),+ onUndo: base.handleUndo,+ },+ });+};++const CheckAccessibilityTool = CheckAccessibility as ToolComponent;+CheckAccessibilityTool.tool = () => useCheckAccessibilityOperation;+CheckAccessibilityTool.getDefaultParameters = () => ({ ...defaultParameters });++export default CheckAccessibilityTool;diff --git a/frontend/src/editor/core/types/checkAccessibility.ts b/frontend/src/editor/core/types/checkAccessibility.tsnew file mode 100644index 0000000000..58538837f7--- /dev/null+++ b/frontend/src/editor/core/types/checkAccessibility.ts@@ -0,0 +1,79 @@+import type { FileId } from "@editor/types/file";++/**+ * Wire shape of `/api/v1/security/accessibility-report`, mirroring the backend's+ * AccessibilityReport. Optional fields are ones an older backend omits.+ */+export interface AccessibilityIssue {+ clause: string;+ testNumber: string;+ message: string;+ technicalMessage?: string | null;+ severity: string;+ specification?: string | null;+ location?: string | null;+ occurrences: number;+ autoFixable: boolean;+ errorMessage?: string | null;+ tags?: string[];+ object?: string | null;+ test?: string | null;+ references?: string[];+ pages?: number[];+ /** False when `pages` lists only some of the pages the issue occurs on. */+ pagesComplete?: boolean;+}++export interface AccessibilityFigure {+ key: string;+ page: number;+ kind: string;+ x: number;+ y: number;+ width: number;+ height: number;+ existingAlt?: string | null;+}++export interface AccessibilitySummary {+ pages: number;+ hasTitle: boolean;+ displaysDocTitle: boolean;+ hasLanguage: boolean;+ allFontsEmbedded: boolean;+ unembeddedFonts: number;+ figures: number;+ encrypted: boolean;+}++export interface AccessibilityChecks {+ total: number;+ failed: number;+ passed: number;+ rulesInProfile: number;+ rulesFailed: number;+}++export interface AccessibilityReport {+ profile: string;+ tagged: boolean;+ declaresConformance: boolean;+ passesAutomatedChecks: boolean;+ /** Set when the validator could not run; the rest of the report then describes that failure. */+ validationError?: string | null;+ issues: AccessibilityIssue[];+ humanChecks: string[];+ automaticallyFixable: number;+ needsInput: number;+ figuresNeedingDescription: AccessibilityFigure[];+ summary: AccessibilitySummary;+ checks?: AccessibilityChecks;+}++/** One file's outcome: a report, or the error that stopped it. */+export interface AccessibilityReportEntry {+ fileId: FileId;+ fileName: string;+ report: AccessibilityReport | null;+ error: string | null;+}diff --git a/frontend/src/editor/core/types/toolId.ts b/frontend/src/editor/core/types/toolId.tsindex 20a5b06188..616af4bf0f 100644--- a/frontend/src/editor/core/types/toolId.ts+++ b/frontend/src/editor/core/types/toolId.ts@@ -53,6 +53,7 @@ export const CORE_REGULAR_TOOL_IDS = ["changeMetadata","overlayPdfs","getPdfInfo",+ "checkAccessibility","validateSignature","timestampPdf","replaceColor",diff --git a/frontend/src/editor/core/utils/accessibilityAssessment.test.ts b/frontend/src/editor/core/utils/accessibilityAssessment.test.tsnew file mode 100644index 0000000000..5310ed3c3f--- /dev/null+++ b/frontend/src/editor/core/utils/accessibilityAssessment.test.ts@@ -0,0 +1,149 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import {+ assessAccessibilityReport,+ categoryOf,+} from "@editor/utils/accessibilityAssessment";+import type {+ AccessibilityIssue,+ AccessibilityReport,+} from "@editor/types/checkAccessibility";++const issue = (clause: string, tags: string[]): AccessibilityIssue => ({+ clause,+ testNumber: "1",+ message: "",+ severity: "error",+ occurrences: 1,+ autoFixable: false,+ tags,+});++const report = (+ issues: AccessibilityIssue[],+ overrides: Partial<AccessibilityReport> = {},+): AccessibilityReport => ({+ profile: "PDF/UA-1",+ tagged: true,+ declaresConformance: true,+ passesAutomatedChecks: issues.length === 0,+ issues,+ humanChecks: [],+ automaticallyFixable: 0,+ needsInput: 0,+ figuresNeedingDescription: [],+ summary: {+ pages: 1,+ hasTitle: true,+ displaysDocTitle: true,+ hasLanguage: true,+ allFontsEmbedded: true,+ unembeddedFonts: 0,+ figures: 0,+ encrypted: false,+ },+ ...overrides,+});++describe("categoryOf", () => {+ it("puts the language of alternative text under language", () => {+ expect(categoryOf(issue("7.2", ["lang", "alt-text"]))).toBe("language");+ });++ it("puts a missing annotation description under links", () => {+ expect(categoryOf(issue("7.18.1", ["annotation", "alt-text"]))).toBe(+ "links",+ );+ });++ it("puts tab order under links", () => {+ expect(categoryOf(issue("7.18.3", ["page"]))).toBe("links");+ });++ it("puts a PDF/UA-2 figure nesting rule under structure", () => {+ expect(+ categoryOf(issue("Table 5. TR-Figure", ["structure", "figure"])),+ ).toBe("structure");+ });++ it("puts a table rule under structure", () => {+ expect(categoryOf(issue("7.5", ["structure", "table"]))).toBe("structure");+ });++ it("falls back to structure when the backend sends no tags", () => {+ expect(categoryOf({ ...issue("7.1", []), tags: undefined })).toBe(+ "structure",+ );+ });+});++describe("assessAccessibilityReport", () => {+ it("passes a tagged file with no failing rules", () => {+ const { result, areas } = assessAccessibilityReport(report([]));+ expect(result).toBe("pass");+ expect(areas.every((area) => area.issues.length === 0)).toBe(true);+ });++ it("fails when screen readers may miss content", () => {+ expect(+ assessAccessibilityReport(report([issue("7.1", ["structure"])])).result,+ ).toBe("fail");+ expect(+ assessAccessibilityReport(report([issue("7.3", ["alt-text"])])).result,+ ).toBe("fail");+ expect(+ assessAccessibilityReport(report([], { tagged: false })).result,+ ).toBe("fail");+ });++ it("is partial when veraPDF reports a failure no rule explains", () => {+ expect(+ assessAccessibilityReport(report([], { passesAutomatedChecks: false }))+ .result,+ ).toBe("partial");+ });++ it("is partial when a basic fails though no rule does", () => {+ expect(+ assessAccessibilityReport(+ report([], { summary: { ...report([]).summary, encrypted: true } }),+ ).result,+ ).toBe("partial");+ });++ it("is partial when only other areas fail", () => {+ const { result, areas } = assessAccessibilityReport(+ report([issue("7.1", ["metadata"]), issue("7.21", ["font"])]),+ );+ expect(result).toBe("partial");+ expect(+ areas.filter((area) => area.issues.length > 0).map((area) => area.id),+ ).toEqual(["metadata", "fonts"]);+ });++ it("counts every basic and area when nothing overlaps", () => {+ expect(assessAccessibilityReport(report([])).checks).toEqual({+ passed: 13,+ total: 13,+ });+ });++ it("leaves out a failing basic its failing area already counts", () => {+ const { checks, basics } = assessAccessibilityReport(+ report([issue("7.1", ["structure"]), issue("7.1", ["metadata"])], {+ tagged: false,+ summary: { ...report([]).summary, hasTitle: false },+ }),+ );+ expect(basics.map((basic) => basic.id)).not.toContain("tagged");+ expect(basics.map((basic) => basic.id)).not.toContain("title");+ expect(checks).toEqual({ passed: 9, total: 11 });+ });++ it("counts a failing basic whose area passes", () => {+ const { checks } = assessAccessibilityReport(+ report([], { summary: { ...report([]).summary, hasLanguage: false } }),+ );+ expect(checks).toEqual({ passed: 12, total: 13 });+ });+});diff --git a/frontend/src/editor/core/utils/accessibilityAssessment.ts b/frontend/src/editor/core/utils/accessibilityAssessment.tsnew file mode 100644index 0000000000..7d406d7957--- /dev/null+++ b/frontend/src/editor/core/utils/accessibilityAssessment.ts@@ -0,0 +1,155 @@+import type {+ AccessibilityIssue,+ AccessibilityReport,+} from "@editor/types/checkAccessibility";++export type AccessibilityCategoryId =+ | "structure"+ | "altText"+ | "language"+ | "fonts"+ | "links"+ | "metadata";++/** Display order. */+const CATEGORY_ORDER: readonly AccessibilityCategoryId[] = [+ "structure",+ "altText",+ "language",+ "metadata",+ "fonts",+ "links",+];++/**+ * Rules carry several tags, so each goes to the first category its tags match. Order matters: a+ * rule about the language or description of an annotation is fixed there, not in the alt text.+ */+const TAG_PRECEDENCE: ReadonlyArray<{+ category: AccessibilityCategoryId;+ tags: readonly string[];+}> = [+ { category: "language", tags: ["lang"] },+ { category: "links", tags: ["annotation", "page"] },+ { category: "altText", tags: ["alt-text"] },+ { category: "fonts", tags: ["font"] },+ {+ category: "structure",+ tags: [+ "structure",+ "table",+ "list",+ "heading",+ "toc",+ "note",+ "artifact",+ "figure",+ "caption",+ ],+ },+ { category: "metadata", tags: ["metadata", "syntax"] },+];++/** Failures here keep screen readers from the content itself, not just from details about it. */+const BLOCKING_CATEGORIES: ReadonlySet<AccessibilityCategoryId> = new Set([+ "structure",+ "altText",+]);++export function categoryOf(issue: AccessibilityIssue): AccessibilityCategoryId {+ const tags = issue.tags ?? [];+ for (const { category, tags: matching } of TAG_PRECEDENCE) {+ if (tags.some((tag) => matching.includes(tag))) return category;+ }+ return "structure";+}++export type AccessibilityResult = "pass" | "partial" | "fail";++export interface AccessibilityArea {+ id: AccessibilityCategoryId;+ issues: AccessibilityIssue[];+}++export type AccessibilityBasicId =+ | "tagged"+ | "title"+ | "displaysTitle"+ | "language"+ | "fonts"+ | "declares"+ | "notEncrypted";++/** The area whose rules also catch each basic, so a basic failing there is reported only once. */+const BASIC_AREA: Record<AccessibilityBasicId, AccessibilityCategoryId | null> =+ {+ tagged: "structure",+ title: "metadata",+ displaysTitle: "metadata",+ language: "language",+ fonts: "fonts",+ declares: "metadata",+ notEncrypted: null,+ };++export interface AccessibilityBasic {+ id: AccessibilityBasicId;+ ok: boolean;+}++export interface AccessibilityAssessment {+ result: AccessibilityResult;+ /** Every area in display order; an area passes when it has no issues. */+ areas: AccessibilityArea[];+ /** Basics the breakdown does not already report: a failing basic is left out when its area fails. */+ basics: AccessibilityBasic[];+ /** The basics and areas above, together. */+ checks: { passed: number; total: number };+}++function documentBasics(report: AccessibilityReport): AccessibilityBasic[] {+ const { summary } = report;+ return [+ { id: "tagged", ok: report.tagged },+ { id: "title", ok: summary.hasTitle },+ { id: "displaysTitle", ok: summary.displaysDocTitle },+ { id: "language", ok: summary.hasLanguage },+ { id: "fonts", ok: summary.allFontsEmbedded },+ { id: "declares", ok: report.declaresConformance },+ { id: "notEncrypted", ok: !summary.encrypted },+ ];+}++/**+ * Fail when the file is untagged or a blocking area fails, since screen readers may then miss+ * content. Pass only when no area or basic fails and veraPDF agrees; anything else is partial.+ */+export function assessAccessibilityReport(+ report: AccessibilityReport,+): AccessibilityAssessment {+ const areas = CATEGORY_ORDER.map((id) => ({+ id,+ issues: report.issues.filter((issue) => categoryOf(issue) === id),+ }));+ const failing = areas.filter((area) => area.issues.length > 0);+ const allBasics = documentBasics(report);+ const result: AccessibilityResult =+ !report.tagged || failing.some((area) => BLOCKING_CATEGORIES.has(area.id))+ ? "fail"+ : failing.length === 0 &&+ report.passesAutomatedChecks &&+ allBasics.every((basic) => basic.ok)+ ? "pass"+ : "partial";+ const failingIds = new Set(failing.map((area) => area.id));+ const basics = allBasics.filter((basic) => {+ const area = BASIC_AREA[basic.id];+ return basic.ok || area === null || !failingIds.has(area);+ });+ const checks = {+ passed:+ basics.filter((basic) => basic.ok).length + areas.length - failing.length,+ total: basics.length + areas.length,+ };+ return { result, areas, basics, checks };+}diff --git a/frontend/src/editor/core/utils/accessibilityPlainLanguage.test.ts b/frontend/src/editor/core/utils/accessibilityPlainLanguage.test.tsnew file mode 100644index 0000000000..9fc3151460--- /dev/null+++ b/frontend/src/editor/core/utils/accessibilityPlainLanguage.test.ts@@ -0,0 +1,138 @@+import { describe, expect, it } from "vitest";+import type { TFunction } from "i18next";+import type { AccessibilityIssue } from "@editor/types/checkAccessibility";+import {+ describeLocation,+ describeObject,+ explainRule,+ ruleTitle,+} from "@editor/utils/accessibilityPlainLanguage";++const t = ((_key: string, fallback: string, values?: Record<string, unknown>) =>+ fallback.replace(/\{\{(\w+)\}\}/g, (_, name: string) =>+ String(values?.[name] ?? ""),+ )) as unknown as TFunction;++const wrap = (context: string) =>+ `Location [level=CosDocument, context=${context}]`;++function issue(overrides: Partial<AccessibilityIssue>): AccessibilityIssue {+ return {+ clause: "7.1",+ testNumber: "3",+ specification: "PDF/UA-1",+ message: "",+ severity: "error",+ occurrences: 1,+ autoFixable: false,+ ...overrides,+ };+}++describe("explainRule", () => {+ it("explains a known PDF/UA-1 rule by clause and test", () => {+ expect(explainRule(t, issue({ clause: "7.1", testNumber: "3" }))).toMatch(+ /neither tagged as content nor marked as decoration/,+ );+ expect(explainRule(t, issue({ clause: "7.1", testNumber: "10" }))).toMatch(+ /show the file name instead of the document's title/,+ );+ });++ it("returns null for an unknown rule or another standard", () => {+ expect(+ explainRule(t, issue({ clause: "7.99", testNumber: "1" })),+ ).toBeNull();+ expect(+ explainRule(+ t,+ issue({+ specification: "PDF/UA-2",+ clause: "7.1",+ testNumber: "3",+ }),+ ),+ ).toBeNull();+ });+});++describe("ruleTitle", () => {+ it("names a known PDF/UA-1 rule by clause and test", () => {+ expect(ruleTitle(t, issue({ clause: "7.1", testNumber: "11" }))).toBe(+ "No tags",+ );+ expect(ruleTitle(t, issue({ clause: "7.3", testNumber: "1" }))).toBe(+ "Image without a description",+ );+ });++ it("returns null for an unknown rule or another standard", () => {+ expect(ruleTitle(t, issue({ clause: "7.99", testNumber: "1" }))).toBeNull();+ expect(+ ruleTitle(t, issue({ specification: "PDF/UA-2", clause: "7.1" })),+ ).toBeNull();+ });+});++describe("describeObject", () => {+ it.each([+ ["SESimpleContentItem", "A piece of page content"],+ ["PDTrueTypeFont", "A font"],+ ["PDType0Font", "A font"],+ ["PDLinkAnnot", "A link"],+ ["PDFreeTextAnnot", "An annotation"],+ ["SETable", "A Table tag"],+ ["MainXMPPackage", "The document metadata"],+ ["PDSomethingNew", "Something new"],+ ])("%s → %s", (object, expected) => {+ expect(describeObject(t, object)).toBe(expected);+ });+});++describe("describeLocation", () => {+ it.each([+ [+ "root/document[0]/pages[0](9 0 obj PDPage)/contentStream[0](85 0 obj PDSemanticContentStream)/content[0]/contentItem[0]",+ "Page 1 › Content item 1",+ ],+ [+ "root/document[0]/pages[2](10 0 obj PDPage)/contentStream[0](1808 0 obj PDSemanticContentStream)/content[0]/contentItem[2]",+ "Page 3 › Content item 1 › Piece 3",+ ],+ [+ "root/document[0]/pages[0](3 0 obj PDPage)/contentStream[0](8 0 obj PDSemanticContentStream)/operators[7]/font[0](Helvetica-Bold)",+ "Page 1 › Drawing step 8 › Font Helvetica-Bold",+ ],+ [+ "root/document[0]/pages[2](10 0 obj PDPage)/contentStream[0](1808 0 obj PDSemanticContentStream)/operators[27]/usedGlyphs[0](OFSJNI+Times-Bold OFSJNI+Times-Bold 55 0 0 true)",+ "Page 3 › Drawing step 28 › A character in Times-Bold",+ ],+ [+ "root/document[0]/pages[116](1117 0 obj PDPage)/contentStream[0](1118 0 obj PDSemanticContentStream)/operators[617]/xObject[0]/contentStream[0](2113 0 obj PDSemanticContentStream)/operators[10]/font[0](ArialMT)",+ "Page 117 › Drawing step 618 › Embedded graphic › Drawing step 11 › Font ArialMT",+ ],+ [+ "root/document[0]/pages[3](11 0 obj PDPage)/annots[1](22 0 obj PDInkAnnot)",+ "Page 4 › Annotation 2",+ ],+ [+ "root/document[0]/StructTreeRoot[0](33 0 obj PDStructTreeRoot)/K[0](34 0 obj SEDocument Document)/K[0](41 0 obj SEFigure Figure)",+ "Tag tree › Document tag › Figure tag",+ ],+ [+ "root/document[0]/metadata[0](102 0 obj PDMetadata)/XMPPackage[0]/Properties[10](http://purl.org/dc/elements/1.1/ - dc:title)",+ "Document metadata › Title",+ ],+ ["root/document[0]/Outlines[0](outline 2570 0)", "Bookmarks"],+ ["root/document[0]", "Whole document"],+ ["root", "Whole document"],+ ])("%s", (context, expected) => {+ expect(describeLocation(t, wrap(context))).toBe(expected);+ });++ it("accepts a bare context without veraPDF's wrapper", () => {+ expect(+ describeLocation(t, "root/document[0]/pages[4](13 0 obj PDPage)"),+ ).toBe("Page 5");+ });+});diff --git a/frontend/src/editor/core/utils/accessibilityPlainLanguage.ts b/frontend/src/editor/core/utils/accessibilityPlainLanguage.tsnew file mode 100644index 0000000000..55b0e2b619--- /dev/null+++ b/frontend/src/editor/core/utils/accessibilityPlainLanguage.ts@@ -0,0 +1,412 @@+import type { TFunction } from "i18next";+import type { AccessibilityIssue } from "@editor/types/checkAccessibility";++/**+ * Turns veraPDF's vocabulary into plain language: what a failing rule means, what it failed on and+ * where. It only rewords the report; nothing here changes what veraPDF found.+ */++/**+ * ISO 14289-1 rules as `<clause>-<test>`, mapped to their translation key. Covers the rules real+ * documents fail most; any other rule falls back to veraPDF's own requirement text.+ */+const UA1_RULE_KEYS: Record<string, string> = {+ "5-1": "noConformanceClaim",+ "5-3": "conformancePrefix",+ "5-4": "conformancePrefix",+ "5-5": "conformancePrefix",+ "6.2-1": "notMarkedTagged",+ "7.1-1": "artifactInsideTagged",+ "7.1-2": "taggedInsideArtifact",+ "7.1-3": "untaggedContent",+ "7.1-8": "noMetadataStream",+ "7.1-9": "noTitle",+ "7.1-10": "titleNotDisplayed",+ "7.1-11": "noTags",+ "7.2-2": "bookmarkLanguage",+ "7.2-24": "annotationLanguage",+ "7.2-30": "replacementTextLanguage",+ "7.2-33": "metadataLanguage",+ "7.2-34": "contentLanguage",+ "7.3-1": "figureNoAlt",+ "7.4.2-1": "headingSkipped",+ "7.18.1-1": "annotationNotTagged",+ "7.18.1-2": "annotationNoDescription",+ "7.18.3-1": "tabOrder",+ "7.18.4-1": "formFieldNotTagged",+ "7.18.5-1": "linkNotTagged",+ "7.18.5-2": "linkNoDescription",+ "7.21.4.1-1": "fontNotEmbedded",+ "7.21.4.1-2": "fontMissingGlyphs",+ "7.21.5-1": "glyphWidths",+ "7.21.6-3": "symbolicEncoding",+ "7.21.7-1": "noUnicode",+ "7.21.8-1": "notdefGlyph",+};++/** The same for ISO 14289-2, whose clauses are numbered differently. */+const UA2_RULE_KEYS: Record<string, string> = {+ "5-1": "noConformanceClaim",+ "5-3": "conformancePrefix",+ "5-4": "conformancePrefix",+ "6.2-1": "notMarkedTagged",+ "8.2.1-1": "noTags",+ "8.2.2-1": "untaggedContent",+ "8.2.4-1": "customTagNotMapped",+ "8.2.4-4": "standardTagRemapped",+ "8.2.5.2-1": "noDocumentTag",+ "8.2.5.2-2": "notPdf2Tags",+ "8.2.5.12-1": "genericHeading",+ "8.2.5.14-1": "noteTag",+ "8.2.5.20-1": "linkNotTagged",+ "8.2.5.28.2-1": "figureNoAlt",+ "8.4.4-1": "noLanguage",+ "8.4.5.5.1-1": "fontNotEmbedded",+ "8.4.5.5.1-2": "fontMissingGlyphs",+ "8.4.5.6-1": "glyphWidths",+ "8.4.5.8-1": "noUnicode",+ "8.4.5.9-1": "notdefGlyph",+ "8.9.2.3-1": "annotationNotTagged",+ "8.9.3.3-1": "tabOrder",+ "8.10.1-1": "formFieldNotTagged",+ "8.11.1-1": "noTitle",+ "8.11.1-2": "noMetadataStream",+ "8.11.2-1": "titleNotDisplayed",+};++const RULE_DEFAULTS: Record<string, string> = {+ noConformanceClaim:+ "The file doesn't say it follows PDF/UA. Its metadata needs a PDF/UA identification entry.",+ conformancePrefix:+ "The PDF/UA declaration in the metadata uses the wrong prefix, so PDF readers may not recognise it.",+ notMarkedTagged:+ "The file isn't flagged as tagged, so assistive technology may ignore the tags it has.",+ artifactInsideTagged:+ "Something marked as decoration sits inside tagged content, so it is both read and skipped.",+ taggedInsideArtifact:+ "Tagged content sits inside something marked as decoration, so screen readers may skip it.",+ untaggedContent:+ "Something on the page is neither tagged as content nor marked as decoration, so screen readers can't tell whether to read it. This is often a background image, header, footer or page number.",+ noMetadataStream:+ "The file has no XMP metadata, which is where PDF/UA keeps the document's title and conformance details.",+ noTitle: "The document has no title in its metadata.",+ titleNotDisplayed:+ 'PDF readers will show the file name instead of the document\'s title. The file needs its "display document title" setting turned on.',+ noTags:+ "The file has no tags at all, so screen readers can't tell headings, paragraphs, lists or tables apart, or read them in the right order.",+ noDocumentTag:+ "The tags need a single Document tag at the top, with everything else inside it.",+ notPdf2Tags:+ "PDF/UA-2 needs the tags a PDF 2.0 file uses. These look like PDF 1.7 tags, which usually means the file was tagged for PDF/UA-1.",+ customTagNotMapped:+ "A tag uses a custom name that isn't linked to a standard tag, so screen readers don't know what it is.",+ standardTagRemapped:+ "A standard tag is linked to a custom tag, so screen readers lose its meaning.",+ noteTag:+ "The file uses the Note tag, which PDF/UA-2 replaces with FENote for footnotes and endnotes.",+ genericHeading:+ "A heading uses the H tag, which has no level. PDF/UA-2 needs H1 to H6 so screen reader users can tell how headings nest.",+ noLanguage:+ "The document doesn't say which language it is in, so screen readers may read it in the wrong language.",+ bookmarkLanguage:+ "The bookmarks don't have a language set, so screen readers don't know which language to read them in. Set the document's language to fix this.",+ annotationLanguage:+ "Comment or link text doesn't have a language set, so screen readers don't know which language to read it in. Set the document's language to fix this.",+ replacementTextLanguage:+ "Some replacement text doesn't have a language set, so screen readers don't know which language to read it in. Set the document's language to fix this.",+ metadataLanguage:+ "The metadata, such as the title, doesn't have a language set, so screen readers don't know which language to read it in. Set the document's language to fix this.",+ contentLanguage:+ "The text doesn't have a language set, so screen readers don't know which language to read it in. Set the document's language to fix this.",+ figureNoAlt:+ "An image is tagged as a figure but has no description, so screen reader users won't know what it shows.",+ headingSkipped:+ "Heading levels skip a step, for example from Heading 1 straight to Heading 3, which makes moving between headings confusing.",+ annotationNotTagged:+ "A comment or drawing isn't tagged as an annotation, so screen readers can't reach it in reading order.",+ annotationNoDescription:+ "A comment, link or drawing has no text description, so screen readers have nothing to announce.",+ tabOrder:+ "A page with links or comments doesn't set its tab order to follow the document, so keyboard users may jump around the page.",+ formFieldNotTagged:+ "A form field isn't tagged as part of a form, so screen readers may not find it.",+ linkNotTagged:+ "A link isn't tagged as a link, so screen readers won't announce it as one.",+ linkNoDescription:+ "A link has no description, so screen readers can only read out its address, or nothing.",+ fontNotEmbedded:+ "A font isn't included in the file, so the text may look different, or be read differently, on another computer.",+ fontMissingGlyphs:+ "An included font is missing some of the characters the document uses.",+ glyphWidths:+ "A font's character widths in the file don't match the font itself, so text may be spaced wrongly.",+ symbolicEncoding:+ "A symbol font carries an encoding it shouldn't, so its characters may come out as the wrong letters.",+ noUnicode:+ "Some characters can't be turned into readable text, so screen readers and copy and paste may get them wrong.",+ notdefGlyph:+ 'The text uses a "missing character" placeholder, which shows as a blank or a box and can\'t be read aloud.',+};++const RULE_TITLE_DEFAULTS: Record<string, string> = {+ noConformanceClaim: "Doesn't declare PDF/UA",+ conformancePrefix: "PDF/UA declaration written incorrectly",+ notMarkedTagged: "Not flagged as tagged",+ artifactInsideTagged: "Decoration inside tagged content",+ taggedInsideArtifact: "Tagged content hidden as decoration",+ untaggedContent: "Content that isn't tagged",+ noMetadataStream: "No XMP metadata",+ noTitle: "No document title",+ titleNotDisplayed: "Title isn't shown when opened",+ noTags: "No tags",+ noDocumentTag: "Tags don't start with a Document tag",+ notPdf2Tags: "Tags aren't PDF 2.0 tags",+ customTagNotMapped: "Custom tag with no standard meaning",+ standardTagRemapped: "Standard tag turned into a custom one",+ noteTag: "Uses the Note tag",+ genericHeading: "Heading without a level",+ noLanguage: "No document language",+ bookmarkLanguage: "No language for bookmarks",+ annotationLanguage: "No language for comments or links",+ replacementTextLanguage: "No language for replacement text",+ metadataLanguage: "No language for metadata",+ contentLanguage: "No language for text",+ figureNoAlt: "Image without a description",+ headingSkipped: "Heading level skipped",+ annotationNotTagged: "Comment or drawing not tagged",+ annotationNoDescription: "Comment, link or drawing without a description",+ tabOrder: "Tab order doesn't follow the document",+ formFieldNotTagged: "Form field not tagged",+ linkNotTagged: "Link not tagged",+ linkNoDescription: "Link without a description",+ fontNotEmbedded: "Font not embedded",+ fontMissingGlyphs: "Font missing characters",+ glyphWidths: "Font character widths don't match",+ symbolicEncoding: "Symbol font has the wrong encoding",+ noUnicode: "Characters that can't be read as text",+ notdefGlyph: "Missing-character placeholder used",+};++function knownRuleKey(issue: AccessibilityIssue): string | null {+ // The report names the profile ("PDF/UA-1"), not the ISO part.+ const keys =+ issue.specification === "PDF/UA-1"+ ? UA1_RULE_KEYS+ : issue.specification === "PDF/UA-2"+ ? UA2_RULE_KEYS+ : null;+ return keys?.[`${issue.clause}-${issue.testNumber}`] ?? null;+}++/** A short plain-language name for the failing rule, or null when the rule is not one we know. */+export function ruleTitle(+ t: TFunction,+ issue: AccessibilityIssue,+): string | null {+ const key = knownRuleKey(issue);+ return key+ ? t(`checkAccessibility.ruleTitles.${key}`, RULE_TITLE_DEFAULTS[key])+ : null;+}++/** A plain-language account of what the failing rule means, or null when the rule is not one we know. */+export function explainRule(+ t: TFunction,+ issue: AccessibilityIssue,+): string | null {+ const key = knownRuleKey(issue);+ return key ? t(`checkAccessibility.rules.${key}`, RULE_DEFAULTS[key]) : null;+}++const OBJECT_KEYS: Record<string, string> = {+ CosDocument: "file",+ CosInfo: "properties",+ PDDocument: "document",+ PDPage: "page",+ PDMetadata: "metadata",+ MainXMPPackage: "metadata",+ XMPPackage: "metadata",+ XMPLangAlt: "translatedMetadata",+ PDOutline: "bookmark",+ PDStructTreeRoot: "tagTree",+ PDAcroForm: "form",+ PDFormField: "formField",+ PDWidgetAnnot: "formField",+ PDLinkAnnot: "link",+ PDInkAnnot: "drawing",+ Glyph: "character",+ SEMarkedContent: "markedContent",+ SESimpleContentItem: "contentPiece",+ SETextItem: "textPiece",+ SEFigure: "figure",+};++const OBJECT_DEFAULTS: Record<string, string> = {+ file: "The file itself",+ properties: "The document properties",+ document: "The document",+ page: "A page",+ metadata: "The document metadata",+ translatedMetadata: "A metadata entry with translations",+ bookmark: "A bookmark",+ tagTree: "The tag tree",+ form: "The form",+ formField: "A form field",+ link: "A link",+ drawing: "A drawing",+ annotation: "An annotation",+ font: "A font",+ character: "A character in a font",+ markedContent: "Marked page content",+ contentPiece: "A piece of page content",+ textPiece: "A piece of text",+ figure: "A figure",+ tag: "A {{name}} tag",+};++/** "SEFigure" → "A figure", "PDTrueTypeFont" → "A font"; unknown names are split into words. */+export function describeObject(t: TFunction, object: string): string {+ const key =+ OBJECT_KEYS[object] ??+ (/^PD\w*Font$/.test(object) ? "font" : undefined) ??+ (/^PD\w*Annot$/.test(object) ? "annotation" : undefined);+ if (key) return t(`checkAccessibility.objects.${key}`, OBJECT_DEFAULTS[key]);+ if (/^SE[A-Z]/.test(object)) {+ return t("checkAccessibility.objects.tag", OBJECT_DEFAULTS.tag, {+ name: object.slice(2),+ });+ }+ return splitWords(object.replace(/^(PD|Cos|SE)(?=[A-Z])/, ""));+}++interface Segment {+ name: string;+ index: number | null;+ detail: string | null;+}++/** veraPDF contexts nest object descriptions in parentheses that may themselves contain slashes. */+function splitPath(context: string): string[] {+ const parts: string[] = [];+ let depth = 0;+ let current = "";+ for (const char of context) {+ if (char === "(") depth += 1;+ if (char === ")") depth = Math.max(0, depth - 1);+ if (char === "/" && depth === 0) {+ parts.push(current);+ current = "";+ continue;+ }+ current += char;+ }+ parts.push(current);+ return parts.filter(Boolean);+}++function parseSegment(raw: string): Segment {+ const match = /^([A-Za-z]+)(?:\[(\d+)\])?(?:\((.*)\))?$/.exec(raw);+ if (!match) return { name: raw, index: null, detail: null };+ return {+ name: match[1],+ index: match[2] === undefined ? null : Number(match[2]),+ detail: match[3] ?? null,+ };+}++function splitWords(name: string): string {+ const words = name.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase();+ return words.charAt(0).toUpperCase() + words.slice(1);+}++const METADATA_PROPERTIES: Record<string, { key: string; fallback: string }> = {+ "dc:title": { key: "title", fallback: "Title" },+ "dc:description": { key: "description", fallback: "Description" },+ "dc:creator": { key: "author", fallback: "Author" },+ "pdfuaid:part": { key: "pdfUaPart", fallback: "PDF/UA part" },+};++function describeSegment(+ t: TFunction,+ segment: Segment,+ previous: Segment | null,+): string | null {+ const position = (segment.index ?? 0) + 1;+ const lastWord = segment.detail?.trim().split(/\s+/).pop() ?? "";+ switch (segment.name) {+ case "root":+ case "document":+ case "contentStream":+ case "XMPPackage":+ return null;+ case "pages":+ return t("checkAccessibility.where.page", "Page {{n}}", { n: position });+ case "content":+ return t("checkAccessibility.where.contentItem", "Content item {{n}}", {+ n: position,+ });+ case "contentItem":+ return previous?.name === "content" && position === 1+ ? null+ : t("checkAccessibility.where.piece", "Piece {{n}}", { n: position });+ case "operators":+ return t("checkAccessibility.where.drawingStep", "Drawing step {{n}}", {+ n: position,+ });+ case "xObject":+ return t("checkAccessibility.where.embeddedGraphic", "Embedded graphic");+ case "font":+ return t("checkAccessibility.where.font", "Font {{name}}", {+ name: segment.detail ?? "",+ });+ case "usedGlyphs":+ return t(+ "checkAccessibility.where.character",+ "A character in {{font}}",+ {+ font: (segment.detail?.split(/\s+/)[0] ?? "").replace(+ /^[A-Z]{6}\+/,+ "",+ ),+ },+ );+ case "annots":+ return t("checkAccessibility.where.annotation", "Annotation {{n}}", {+ n: position,+ });+ case "StructTreeRoot":+ return t("checkAccessibility.where.tagTree", "Tag tree");+ case "K":+ return t("checkAccessibility.where.tag", "{{tag}} tag", {+ tag: lastWord,+ });+ case "metadata":+ return t("checkAccessibility.where.metadata", "Document metadata");+ case "Properties": {+ const property = segment.detail?.split(" - ").pop()?.trim() ?? "";+ const known = METADATA_PROPERTIES[property];+ return known+ ? t(`checkAccessibility.where.properties.${known.key}`, known.fallback)+ : property;+ }+ case "Outlines":+ return t("checkAccessibility.where.bookmarks", "Bookmarks");+ default:+ return splitWords(segment.name);+ }+}++/**+ * The first place a rule failed, as a short trail such as "Page 3 › Annotation 2". Accepts both+ * veraPDF's bare context and its `Location [level=…, context=…]` wrapper.+ */+export function describeLocation(t: TFunction, location: string): string {+ const context = /context=(.*)\]\s*$/.exec(location)?.[1] ?? location;+ const segments = splitPath(context).map(parseSegment);+ const parts = segments+ .map((segment, i) => describeSegment(t, segment, segments[i - 1] ?? null))+ .filter((part): part is string => !!part);+ return parts.length > 0+ ? parts.join(" › ")+ : t("checkAccessibility.where.wholeDocument", "Whole document");+}diff --git a/frontend/src/editor/core/utils/accessibilityReportContent.test.ts b/frontend/src/editor/core/utils/accessibilityReportContent.test.tsnew file mode 100644index 0000000000..4a2cca08c2--- /dev/null+++ b/frontend/src/editor/core/utils/accessibilityReportContent.test.ts@@ -0,0 +1,110 @@+import { describe, expect, it } from "vitest";+import type { TFunction } from "i18next";+import type { AccessibilityIssue } from "@editor/types/checkAccessibility";+import {+ describeIssue,+ formatPageRanges,+} from "@editor/utils/accessibilityReportContent";++const t = ((_key: string, fallback: string, values?: Record<string, unknown>) =>+ fallback.replace(/\{\{(\w+)\}\}/g, (_, name: string) =>+ String(values?.[name] ?? ""),+ )) as unknown as TFunction;++function issue(overrides: Partial<AccessibilityIssue>): AccessibilityIssue {+ return {+ clause: "7.1",+ testNumber: "3",+ specification: "PDF/UA-1",+ message: "Fallback message",+ severity: "error",+ occurrences: 1,+ autoFixable: false,+ ...overrides,+ };+}++describe("formatPageRanges", () => {+ it("collapses consecutive pages into ranges", () => {+ expect(formatPageRanges([1, 2, 3, 5, 7, 8])).toBe("1-3, 5, 7-8");+ expect(formatPageRanges([])).toBe("");+ });+});++describe("describeIssue", () => {+ it("leads with the plain title and keeps veraPDF's requirement in the details", () => {+ const content = describeIssue(+ t,+ issue({+ errorMessage: "Content is neither marked as Artifact nor tagged",+ technicalMessage: "Content shall be marked as Artifact",+ occurrences: 4,+ pages: [1, 2, 3],+ object: "SESimpleContentItem",+ }),+ );+ expect(content.title).toBe("Content that isn't tagged");+ expect(content.summary).toBe("Pages 1-3 - 4 instances");+ expect(content.details.map((detail) => detail.label)).toEqual([+ "Rule",+ "Applies to",+ "Pages",+ "Requirement",+ ]);+ });++ it("says when the page list covers only some occurrences", () => {+ const content = describeIssue(+ t,+ issue({ occurrences: 1200, pages: [1, 2, 3, 4], pagesComplete: false }),+ );+ expect(content.summary).toBe(+ "Pages 1-4 (list may be incomplete) - 1200 instances",+ );+ expect(content.details).toContainEqual({+ label: "Pages",+ value:+ "1-4 (only the first occurrences record a page, so this list may be incomplete)",+ });+ });++ it("shows where a one-off issue is rather than a page range", () => {+ const content = describeIssue(+ t,+ issue({+ location: "root/document[0]/pages[4](13 0 obj PDPage)",+ pages: [5],+ }),+ );+ expect(content.details).toContainEqual({ label: "Where", value: "Page 5" });+ });++ it("falls back to veraPDF's message for a rule without a plain title", () => {+ const content = describeIssue(+ t,+ issue({ clause: "7.99", errorMessage: "Something veraPDF said" }),+ );+ expect(content.title).toBe("Something veraPDF said");+ });++ it("gives no location when the validator recorded no page", () => {+ const content = describeIssue(t, issue({ occurrences: 12, pages: [] }));+ expect(content.summary).toBe("12 instances");+ expect(content.details.map((detail) => detail.label)).not.toContain(+ "Pages",+ );+ });++ it("explains PDF/UA-2 rules in plain language", () => {+ const content = describeIssue(+ t,+ issue({+ specification: "PDF/UA-2",+ clause: "8.2.5.2",+ testNumber: "2",+ errorMessage: "namespace URI = null",+ }),+ );+ expect(content.title).toBe("Tags aren't PDF 2.0 tags");+ });+});diff --git a/frontend/src/editor/core/utils/accessibilityReportContent.ts b/frontend/src/editor/core/utils/accessibilityReportContent.tsnew file mode 100644index 0000000000..429c4fb648--- /dev/null+++ b/frontend/src/editor/core/utils/accessibilityReportContent.ts@@ -0,0 +1,359 @@+import type { TFunction } from "i18next";+import type {+ AccessibilityIssue,+ AccessibilityReport,+} from "@editor/types/checkAccessibility";+import type {+ AccessibilityBasicId,+ AccessibilityCategoryId,+ AccessibilityResult,+} from "@editor/utils/accessibilityAssessment";+import {+ describeLocation,+ describeObject,+ explainRule,+ ruleTitle,+} from "@editor/utils/accessibilityPlainLanguage";++/**+ * The words of an accessibility report, shared by the on-screen report and its PDF so the two+ * always say the same thing.+ */++/** "1, 2, 3, 5, 7, 8" -> "1-3, 5, 7-8". Input must be sorted ascending. */+export function formatPageRanges(pages: number[]): string {+ const ranges: string[] = [];+ let start = pages[0];+ let previous = pages[0];+ for (const page of pages.slice(1)) {+ if (page === previous + 1) {+ previous = page;+ continue;+ }+ ranges.push(start === previous ? `${start}` : `${start}-${previous}`);+ start = page;+ previous = page;+ }+ if (start !== undefined) {+ ranges.push(start === previous ? `${start}` : `${start}-${previous}`);+ }+ return ranges.join(", ");+}++export const categoryLabel = (t: TFunction, id: AccessibilityCategoryId) =>+ ({+ structure: t("checkAccessibility.category.structure", "Tags & structure"),+ altText: t("checkAccessibility.category.altText", "Alternative text"),+ language: t("checkAccessibility.category.language", "Language"),+ metadata: t("checkAccessibility.category.metadata", "Metadata & settings"),+ fonts: t("checkAccessibility.category.fonts", "Fonts"),+ links: t("checkAccessibility.category.links", "Links & annotations"),+ })[id];++export const categoryTip = (t: TFunction, id: AccessibilityCategoryId) =>+ ({+ structure: t(+ "checkAccessibility.categoryTip.structure",+ "Tags tell screen readers what each part of a page is, such as a heading, list or table, and the order to read it in.",+ ),+ altText: t(+ "checkAccessibility.categoryTip.altText",+ "Images need a short text description for screen readers to read out instead.",+ ),+ language: t(+ "checkAccessibility.categoryTip.language",+ "Screen readers need to know the document's language to pronounce it correctly.",+ ),+ metadata: t(+ "checkAccessibility.categoryTip.metadata",+ "The title, PDF/UA declaration and other settings that assistive technology reads from the file.",+ ),+ fonts: t(+ "checkAccessibility.categoryTip.fonts",+ "Fonts need to be in the file, with every character linked to real text, so the text can be read aloud and copied.",+ ),+ links: t(+ "checkAccessibility.categoryTip.links",+ "Links, comments and form fields need tags and descriptions, and a tab order that follows the page.",+ ),+ })[id];++export const resultLabel = (t: TFunction, result: AccessibilityResult) =>+ ({+ pass: t("checkAccessibility.result.pass", "Pass"),+ partial: t("checkAccessibility.result.partial", "Partial"),+ fail: t("checkAccessibility.result.fail", "Fail"),+ })[result];++export const resultSummary = (t: TFunction, result: AccessibilityResult) =>+ ({+ pass: t(+ "checkAccessibility.result.passSummary",+ "Passes every automated PDF/UA check.",+ ),+ partial: t(+ "checkAccessibility.result.partialSummary",+ "Screen readers can read this document, but some checks fail.",+ ),+ fail: t(+ "checkAccessibility.result.failSummary",+ "Screen readers may not be able to read all of this document.",+ ),+ })[result];++export const basicLabel = (t: TFunction, id: AccessibilityBasicId) =>+ ({+ tagged: t("checkAccessibility.facts.tagged", "Tagged"),+ title: t("checkAccessibility.facts.title", "Has a title"),+ displaysTitle: t(+ "checkAccessibility.facts.displaysTitle",+ "Shows its title",+ ),+ language: t("checkAccessibility.facts.language", "Declares a language"),+ fonts: t("checkAccessibility.facts.fonts", "Fonts embedded"),+ declares: t("checkAccessibility.facts.declares", "Declares PDF/UA"),+ notEncrypted: t("checkAccessibility.facts.notEncrypted", "Not encrypted"),+ })[id];++export const basicTip = (t: TFunction, id: AccessibilityBasicId) =>+ ({+ tagged: t(+ "checkAccessibility.factTip.tagged",+ "The file has tags describing its structure. Without them, screen readers only get plain text.",+ ),+ title: t(+ "checkAccessibility.factTip.title",+ "The file has a title in its metadata.",+ ),+ displaysTitle: t(+ "checkAccessibility.factTip.displaysTitle",+ "PDF readers show the title, not the file name, when the file opens.",+ ),+ language: t(+ "checkAccessibility.factTip.language",+ "The file says which language its text is in.",+ ),+ fonts: t(+ "checkAccessibility.factTip.fonts",+ "Every font the text uses is included in the file.",+ ),+ declares: t(+ "checkAccessibility.factTip.declares",+ "The file's metadata says it follows PDF/UA.",+ ),+ notEncrypted: t(+ "checkAccessibility.factTip.notEncrypted",+ "The file isn't encrypted. Encryption can stop assistive technology reading it.",+ ),+ })[id];++/**+ * The clauses each row covers, from the veraPDF rules the row groups. Must follow+ * TAG_PRECEDENCE and BASIC_AREA in accessibilityAssessment, which decide that grouping.+ */+const AREA_CLAUSES: Record<string, Record<AccessibilityCategoryId, string>> = {+ "PDF/UA-1": {+ structure: "7.1, 7.4, 7.5, 7.9",+ altText: "7.3, 7.7",+ language: "7.2",+ metadata: "5, 6.2, 7.1",+ fonts: "7.21",+ links: "7.18",+ },+ "PDF/UA-2": {+ structure: "8.2",+ altText: "8.2.5.28, 8.4.3",+ language: "8.4.4",+ metadata: "5, 6.2, 8.11",+ fonts: "8.4.5",+ links: "8.9, 8.10",+ },+};++const BASIC_CLAUSES: Record<+ string,+ Partial<Record<AccessibilityBasicId, string>>+> = {+ "PDF/UA-1": {+ tagged: "7.1",+ title: "7.1",+ displaysTitle: "7.1",+ language: "7.2",+ fonts: "7.21.4",+ declares: "5",+ notEncrypted: "7.16",+ },+ "PDF/UA-2": {+ tagged: "8.2.1",+ title: "8.11.1",+ displaysTitle: "8.11.2",+ language: "8.4.4",+ fonts: "8.4.5.5",+ declares: "5",+ },+};++function clauseReference(+ t: TFunction,+ profile: string,+ clauses: string | undefined,+): string | null {+ return clauses+ ? t("checkAccessibility.clauseRef", "{{profile}} §{{clauses}}", {+ profile,+ clauses,+ })+ : null;+}++/** e.g. "PDF/UA-1 §7.21"; null for a profile the tool has no clause list for. */+export const categoryReference = (+ t: TFunction,+ profile: string,+ id: AccessibilityCategoryId,+) => clauseReference(t, profile, AREA_CLAUSES[profile]?.[id]);++export const basicReference = (+ t: TFunction,+ profile: string,+ id: AccessibilityBasicId,+) => clauseReference(t, profile, BASIC_CLAUSES[profile]?.[id]);++export const checksLabel = (+ t: TFunction,+ checks: { passed: number; total: number },+) =>+ t(+ "checkAccessibility.checks.label",+ "{{passed}} of {{total}} checks passed",+ checks,+ );++export function figuresSummary(+ t: TFunction,+ report: AccessibilityReport,+): string | null {+ const figures = report.figuresNeedingDescription;+ if (figures.length === 0) return null;+ const pages = [...new Set(figures.map((figure) => figure.page))].sort(+ (a, b) => a - b,+ );+ return t(+ "checkAccessibility.figures.summary",+ "{{count}} images need a description (pages {{pages}})",+ {+ count: figures.length,+ pages: formatPageRanges(pages),+ },+ );+}++export interface IssueDetail {+ label: string;+ value: string;+}++export interface IssueContent {+ title: string;+ /** Where the issue was found and how often, e.g. "Pages 1-3 - 12 instances"; null when unknown. */+ summary: string | null;+ explanation: string | null;+ details: IssueDetail[];+}++export function describeIssue(+ t: TFunction,+ issue: AccessibilityIssue,+): IssueContent {+ const reportedTitle =+ issue.errorMessage?.trim() || issue.technicalMessage || issue.message;+ const plainTitle = ruleTitle(t, issue);+ const pages = issue.pages ?? [];+ const pageList = formatPageRanges(pages);+ // The validator records pages for only some occurrences of a frequent failure.+ const pagesPartial = issue.pagesComplete === false;+ // Tag-tree elements and document-level rules have no page, so an empty list says nothing.+ const where =+ pages.length === 0+ ? null+ : pagesPartial+ ? t(+ "checkAccessibility.issue.onPagesPartial",+ "Pages {{pages}} (list may be incomplete)",+ { pages: pageList, count: pages.length },+ )+ : t("checkAccessibility.issue.onPages", "Pages {{pages}}", {+ pages: pageList,+ count: pages.length,+ });+ const instances =+ issue.occurrences > 1+ ? t("checkAccessibility.issue.instances", "{{count}} instances", {+ count: issue.occurrences,+ })+ : null;+ const summary =+ [where, instances].filter((part) => part !== null).join(" - ") || null;+ const plainExplanation = explainRule(t, issue);+ const requirement =+ issue.technicalMessage && issue.technicalMessage !== reportedTitle+ ? issue.technicalMessage+ : null;++ const details: IssueDetail[] = [+ {+ label: t("checkAccessibility.issue.rule", "Rule"),+ value: t(+ "checkAccessibility.issue.clauseValue",+ "{{spec}} §{{clause}}, test {{test}}",+ {+ spec: issue.specification ?? "",+ clause: issue.clause,+ test: issue.testNumber,+ },+ ),+ },+ ];+ if (issue.object) {+ details.push({+ label: t("checkAccessibility.issue.appliesTo", "Applies to"),+ value: describeObject(t, issue.object),+ });+ }+ if (issue.occurrences === 1 && issue.location) {+ details.push({+ label: t("checkAccessibility.issue.where", "Where"),+ value: describeLocation(t, issue.location),+ });+ } else if (pages.length > 0) {+ details.push({+ label: t("checkAccessibility.issue.pages", "Pages"),+ value: pagesPartial+ ? t(+ "checkAccessibility.issue.pagesPartialValue",+ "{{pages}} (only the first occurrences record a page, so this list may be incomplete)",+ { pages: pageList },+ )+ : pageList,+ });+ }+ if (plainExplanation && requirement) {+ details.push({+ label: t("checkAccessibility.issue.requirement", "Requirement"),+ value: requirement,+ });+ }+ if (issue.references && issue.references.length > 0) {+ details.push({+ label: t("checkAccessibility.issue.standard", "Standard"),+ value: issue.references.join("; "),+ });+ }++ return {+ title: plainTitle ?? reportedTitle,+ summary,+ explanation: plainExplanation ?? requirement,+ details,+ };+}diff --git a/frontend/src/editor/core/utils/urlMapping.ts b/frontend/src/editor/core/utils/urlMapping.tsindex 2ad235a7f2..a1202a7a65 100644--- a/frontend/src/editor/core/utils/urlMapping.ts+++ b/frontend/src/editor/core/utils/urlMapping.ts@@ -86,6 +86,8 @@ export const URL_TO_TOOL_MAP: Record<string, ToolId> = {// Metadata and info"/change-metadata": "changeMetadata","/get-pdf-info": "getPdfInfo",+ "/check-accessibility": "checkAccessibility",+ "/accessibility-report": "checkAccessibility","/add-attachments": "addAttachments","/create-portfolio": "createPortfolio",diff --git a/frontend/src/editor/proprietary/utils/creditCosts.ts b/frontend/src/editor/proprietary/utils/creditCosts.tsindex c12a7c8e48..66785abaa6 100644--- a/frontend/src/editor/proprietary/utils/creditCosts.ts+++ b/frontend/src/editor/proprietary/utils/creditCosts.ts@@ -50,6 +50,7 @@ export const TOOL_CREDIT_COSTS: Partial<Record<ToolId, number>> = {compare: CREDIT_COSTS.SMALL,addAttachments: CREDIT_COSTS.SMALL,getPdfInfo: CREDIT_COSTS.MEDIUM,+ checkAccessibility: CREDIT_COSTS.LARGE,validateSignature: CREDIT_COSTS.SMALL,read: CREDIT_COSTS.SMALL,