Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Export accessibility review comparison as HTML (#1234)

Earl Co825674433135
diff --git a/crates/automation/src/a11y.rs b/crates/automation/src/a11y.rs
index e5181394d..ac30694a8 100644
--- a/crates/automation/src/a11y.rs
+++ b/crates/automation/src/a11y.rs
@@ -58,6 +58,74 @@ pub(crate) fn report_json(r: &Report) -> Value {
})
}
+fn html_escape(value: &str) -> String {
+ value.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;").replace('\'', "&#39;")
+}
+
+/// A self-contained, human-readable view of the same evidence as the JSON review record.
+fn review_html(record: &Value) -> Result<String> {
+ let str_at = |value: &Value, key: &str| -> Result<String> {
+ value.get(key).and_then(Value::as_str).map(html_escape).ok_or_else(|| failed(format!("review record is missing {key}")))
+ };
+ let count = |value: &Value, key: &str| -> Result<u64> {
+ value.get(key).and_then(Value::as_u64).ok_or_else(|| failed(format!("review record is missing {key}")))
+ };
+ let before = &record["before"];
+ let after = &record["after"];
+ let mut html = format!(
+ "<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><title>Accessibility review</title><style>\
+ body{{font:15px/1.5 system-ui,sans-serif;max-width:1100px;margin:2rem auto;padding:0 1rem;color:#1d1d1f}}\
+ table{{border-collapse:collapse;width:100%;margin:1rem 0}}th,td{{border:1px solid #aaa;padding:.45rem;text-align:left;vertical-align:top}}\
+ th{{background:#f2f2f2}}.hash{{overflow-wrap:anywhere;font-family:monospace}}\
+ </style></head><body><main><h1>Accessibility review</h1><p>Record created: {}</p>\n",
+ str_at(record, "date")?
+ );
+ html.push_str("<h2>Before and after</h2><table><caption>Accessibility checker outcomes</caption><thead><tr><th scope=\"col\">Version</th><th scope=\"col\">Document</th><th scope=\"col\">Passed</th><th scope=\"col\">Failed</th><th scope=\"col\">Needs manual check</th><th scope=\"col\">Skipped</th></tr></thead><tbody>");
+ for (label, version) in [("Before", before), ("After", after)] {
+ let summary = &version["summary"];
+ html.push_str(&format!(
+ "<tr><th scope=\"row\">{label}</th><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>",
+ str_at(version, "name")?,
+ count(summary, "passed")?,
+ count(summary, "failed")?,
+ count(summary, "manual")?,
+ count(summary, "skipped")?
+ ));
+ }
+ html.push_str("</tbody></table>");
+ html.push_str(&format!(
+ "<p>Before SHA-256: <span class=\"hash\">{}</span><br>After SHA-256: <span class=\"hash\">{}</span></p>",
+ str_at(before, "sha256")?,
+ str_at(after, "sha256")?
+ ));
+ html.push_str("<h2>Rule comparison</h2><table><caption>Before and after checker results</caption><thead><tr><th scope=\"col\">Rule</th><th scope=\"col\">Before</th><th scope=\"col\">Before findings</th><th scope=\"col\">After</th><th scope=\"col\">After findings</th><th scope=\"col\">Change</th></tr></thead><tbody>");
+ let rules = record["rules"].as_array().ok_or_else(|| failed("review record is missing rules"))?;
+ for row in rules {
+ let id = row["rule"].as_str().ok_or_else(|| failed("review record has a rule without an id"))?;
+ let name = Rule::from_id(id).map(Rule::name).unwrap_or(id);
+ let old = &row["before"];
+ let new = &row["after"];
+ let old_status = str_at(old, "status")?;
+ let new_status = str_at(new, "status")?;
+ let old_findings = count(old, "findings")?;
+ let new_findings = count(new, "findings")?;
+ let changed = old_status != new_status || old_findings != new_findings;
+ html.push_str(&format!(
+ "<tr><th scope=\"row\">{}</th><td>{old_status}</td><td>{old_findings}</td><td>{new_status}</td><td>{new_findings}</td><td>{}</td></tr>",
+ html_escape(name),
+ if changed { "Changed" } else { "Unchanged" }
+ ));
+ }
+ html.push_str("</tbody></table><h2>Still requiring review</h2><ul>");
+ for id in record["review_required"].as_array().ok_or_else(|| failed("review record is missing review_required"))? {
+ let id = id.as_str().ok_or_else(|| failed("review record has an invalid review_required entry"))?;
+ html.push_str(&format!("<li>{}</li>", html_escape(Rule::from_id(id).map(Rule::name).unwrap_or(id))));
+ }
+ html.push_str("</ul>");
+ html.push_str(&format!("<p>{}</p></main></body></html>\n", str_at(record, "note")?));
+ Ok(html)
+}
+
impl Automation {
fn a11y_options(&self, a: &Args) -> Result<Options> {
let mut o = Options::default();
@@ -107,7 +175,7 @@ impl Automation {
Ok(out)
}
- pub(crate) fn a11y_review_record(&self, a: &Args) -> Result<Value> {
+ fn review_record_value(&self, a: &Args) -> Result<Value> {
let id = |key| -> Result<DocId> {
let n = u64::try_from(a.int(key)?).map_err(|_| ToolError::InvalidArgs(format!("{key} must be positive")))?;
if n == 0 {
@@ -173,12 +241,25 @@ impl Automation {
"review_required": review_required,
"note": "Automated checks cover only part of accessibility. Review remaining findings manually and validate the final PDF independently.",
});
+ Ok(record)
+ }
+
+ pub(crate) fn a11y_review_record(&self, a: &Args) -> Result<Value> {
+ let record = self.review_record_value(a)?;
let path = self.resolve(a.str("path")?, true)?;
let bytes = serde_json::to_vec_pretty(&record).map_err(failed)?;
write_atomic(&path, &bytes)?;
Ok(json!({ "path": path.to_string_lossy(), "record": record }))
}
+ pub(crate) fn a11y_review_html(&self, a: &Args) -> Result<Value> {
+ let record = self.review_record_value(a)?;
+ let html = review_html(&record)?;
+ let path = self.resolve(a.str("path")?, true)?;
+ write_atomic(&path, html.as_bytes())?;
+ Ok(json!({ "path": path.to_string_lossy(), "record": record }))
+ }
+
pub(crate) fn a11y_fix(&mut self, a: &Args) -> Result<Value> {
let id = a.str("rule")?;
let rule = Rule::from_id(id).ok_or_else(|| ToolError::InvalidArgs(format!("unknown rule {id:?}")))?;
@@ -658,3 +739,23 @@ impl Automation {
Ok(json!({ "enabled": self.session.javascript() }))
}
}
+
+#[cfg(test)]
+mod review_html_tests {
+ use super::*;
+
+ #[test]
+ fn document_names_are_escaped_in_review_html() {
+ let record = json!({
+ "date": "2026-10-12",
+ "before": { "name": "<script>alert('x')</script>.pdf", "sha256": "a", "summary": { "passed": 0, "failed": 1, "manual": 0, "skipped": 0 } },
+ "after": { "name": "safe.pdf", "sha256": "b", "summary": { "passed": 1, "failed": 0, "manual": 0, "skipped": 0 } },
+ "rules": [{ "rule": "primary-language", "before": { "status": "failed", "findings": 1 }, "after": { "status": "passed", "findings": 0 } }],
+ "review_required": [],
+ "note": "Review independently.",
+ });
+ let html = review_html(&record).unwrap();
+ assert!(html.contains("&lt;script&gt;alert(&#39;x&#39;)&lt;/script&gt;.pdf"));
+ assert!(!html.contains("<script>"));
+ }
+}
diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs
index 53da3a078..725f394e6 100644
--- a/crates/automation/src/lib.rs
+++ b/crates/automation/src/lib.rs
@@ -736,6 +736,7 @@ impl Automation {
"ocr_recognize_files" => self.ocr_recognize_files(&a)?,
"accessibility_report" => self.a11y_report(&a)?,
"accessibility_review_record" => self.a11y_review_record(&a)?,
+ "accessibility_review_html" => self.a11y_review_html(&a)?,
"accessibility_fix" => self.a11y_fix(&a)?,
"accessibility_figures" => self.accessibility_figures(&a)?,
"accessibility_set_alt" => self.accessibility_set_alt(&a)?,
diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs
index d56d976fe..6cdc4eca3 100644
--- a/crates/automation/src/tools.rs
+++ b/crates/automation/src/tools.rs
@@ -882,6 +882,17 @@ pub fn tools() -> Vec<ToolDef> {
}),
&["before", "after", "path"],
)),
+ t("accessibility_review_html", "Accessibility review summary", "Compare two open versions of a PDF and write a self-contained HTML summary of the same evidence as accessibility_review_record: document hashes, outcome counts, rule changes, and rules still requiring review. Does not change either PDF or claim accessibility compliance.")
+ .destructive()
+ .with(schema(
+ json!({
+ "before": doc(),
+ "after": doc(),
+ "path": { "type": "string" },
+ "all": { "type": "boolean", "description": "Include rules that are off by default (colour contrast)." },
+ }),
+ &["before", "after", "path"],
+ )),
t("accessibility_fix", "Fix an accessibility problem", "Apply the checker's automatic fix for a rule: primary-language (value: the language, e.g. en-US), title (value: the title; default the current title or file name; also shows it in the title bar) or tab-order (every page tabs in structure order). Returns the rule's new status. Undoable.")
.with(schema(json!({ "doc": doc(), "rule": { "type": "string", "enum": ["primary-language", "title", "tab-order"] }, "value": { "type": "string" } }), &["doc", "rule"])),
t("accessibility_figures", "List figures", "The tagged figures (Figure elements, through the role map) in document order: figure number, page, alternate text and where the figure is drawn (top-left-origin points).")
diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rs
index 420eb41eb..eca4f9abf 100644
--- a/crates/automation/tests/automation.rs
+++ b/crates/automation/tests/automation.rs
@@ -1805,13 +1805,28 @@ fn accessibility_review_record_compares_two_versions_without_changing_them() {
assert_eq!(language["before"]["status"], "failed");
assert_eq!(language["after"]["status"], "passed");
assert!(file["review_required"].as_array().unwrap().iter().any(|r| r == "tagged-pdf"));
+ let html_output = ok(&mut a, "accessibility_review_html", json!({ "before": before, "after": after, "path": "review.html" }));
+ assert_eq!(html_output["record"], file);
+ let html = std::fs::read_to_string(dir.join("review.html")).unwrap();
+ assert!(html.contains("<html lang=\"en\">") && html.contains("Accessibility checker outcomes"));
+ assert!(html.contains("Primary language") && html.contains("<td>Changed</td>"));
+ assert!(html.contains("Still requiring review") && html.contains("Tagged PDF"));
+ assert!(html.contains(file["before"]["sha256"].as_str().unwrap()));
+ assert!(html.contains("validate the final PDF independently"));
assert_eq!(std::fs::read(dir.join("a.pdf")).unwrap(), source);
assert!(matches!(
a.call("accessibility_review_record", &json!({ "before": before, "after": before, "path": "same.json" })),
Err(ToolError::InvalidArgs(_))
));
assert!(!dir.join("same.json").exists());
+ assert!(matches!(
+ a.call("accessibility_review_html", &json!({ "before": before, "after": before, "path": "same.html" })),
+ Err(ToolError::InvalidArgs(_))
+ ));
+ assert!(!dir.join("same.html").exists());
assert!(a.call("accessibility_review_record", &json!({ "before": before, "after": after, "path": "../escape.json" })).is_err());
+ assert!(a.call("accessibility_review_html", &json!({ "before": before, "after": after, "path": "../escape.html" })).is_err());
+ assert!(!dir.parent().unwrap().join("escape.html").exists());
}
#[test]
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index 0ad5e2c67..4015a231d 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -8401,9 +8401,9 @@ tier = "P1"
milestone = "M12"
status = "shipped"
commands = ["a11y.report"]
-tools = ["accessibility_report"]
-evidence = ["crates/a11y/src/tests.rs::rules_have_ids_and_the_report_lists_them", "crates/ui-egui/tests/accessibility.rs::checking_fixing_skipping_and_reporting", "crates/automation/tests/automation.rs::accessibility_check_report_and_fixes_through_tools"]
-notes = "HTML report: summary counts and a table per category with descriptions and findings"
+tools = ["accessibility_report", "accessibility_review_record", "accessibility_review_html"]
+evidence = ["crates/a11y/src/tests.rs::rules_have_ids_and_the_report_lists_them", "crates/ui-egui/tests/accessibility.rs::checking_fixing_skipping_and_reporting", "crates/automation/tests/automation.rs::accessibility_check_report_and_fixes_through_tools", "crates/automation/tests/automation.rs::accessibility_review_record_compares_two_versions_without_changing_them", "crates/automation/src/a11y.rs::document_names_are_escaped_in_review_html"]
+notes = "HTML checker report: summary counts and a table per category with descriptions and findings. Headless comparison of two open versions exports the same before-and-after evidence as JSON or accessible, self-contained HTML with hashes, rule changes, and remaining review items."
[[feature]]
id = "a11y.checker-fix"