Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fix(report): use literal document IDs for PDF controls
Address the PDF viewer item in #476. Keep canvases, load/error messages, page labels and navigation controls reachable for document IDs containing spaces or CSS punctuation.

AI-assisted implementation with independent code review. Offline regression cases reproduce 12 failures on dev and all 16 pass here. Full suite: 4117 passed, 13 skipped, 1 xfailed. Safari DOM check passes all 16 cases with PDF.js stubbed; real PDF decoding is not newly tested.
  • Loading branch information
mangeshraut712 committed Nov 9, 2026
commit a91ab9e061c63d714ade5f2a1cfea2a3df32b9f6
12 changes: 12 additions & 0 deletions src/stickler/reporting/html/interactive/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Interactive HTML reports

`main.js` is embedded in reports with individual results. It filters document
metrics and controls the image/PDF gallery. PDF.js supplies loading and rendering.

Document IDs are data, not CSS selectors. Resolve PDF canvases, loading/error
messages and page controls with `document.getElementById`; keep the original IDs
so documents containing spaces or punctuation remain distinct.

The offline PDF behavior tests live in `tests/reporting/html/test_pdf_document_ids.py`.
They require Node.js and stub the DOM and PDF.js, so they do not prove browser
rendering or real PDF decoding.
15 changes: 8 additions & 7 deletions src/stickler/reporting/html/interactive/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -526,9 +526,10 @@ const updateDocumentButtonState = () => {
};

const loadPDF = (url, canvasId, loadingId, errorId) => {
const canvas = getElement(`#${canvasId}`);
const loading = getElement(`#${loadingId}`);
const error = getElement(`#${errorId}`);
// Document IDs may contain CSS syntax, so use literal DOM ID lookups.
const canvas = document.getElementById(canvasId);
const loading = document.getElementById(loadingId);
const error = document.getElementById(errorId);

if (!canvas || !loading || !error) return;

Expand Down Expand Up @@ -590,10 +591,10 @@ const renderPDFPage = (docId, pageNum) => {
pdfInfo.canvas.width = scaledViewport.width;

page.render({ canvasContext: pdfInfo.context, viewport: scaledViewport }).promise.then(() => {
const loading = getElement(`#pdf-loading-${docId}`);
const loading = document.getElementById(`pdf-loading-${docId}`);
if (loading) loading.style.display = 'none';
pdfInfo.canvas.style.display = 'block';
setText(`#page-info-${docId}`, `Page ${pageNum} of ${pdfInfo.doc.numPages}`);
setText(document.getElementById(`page-info-${docId}`), `Page ${pageNum} of ${pdfInfo.doc.numPages}`);
});
});
};
Expand All @@ -616,8 +617,8 @@ const updateNavigationButtons = (docId) => {
const pdfInfo = window.pdfData?.[docId];
if (!pdfInfo) return;

const prevBtn = getElement(`#prev-${docId}`);
const nextBtn = getElement(`#next-${docId}`);
const prevBtn = document.getElementById(`prev-${docId}`);
const nextBtn = document.getElementById(`next-${docId}`);

if (prevBtn) prevBtn.disabled = (pdfInfo.currentPage <= 1);
if (nextBtn) nextBtn.disabled = (pdfInfo.currentPage >= pdfInfo.doc.numPages);
Expand Down
1 change: 1 addition & 0 deletions tests/reporting/html/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Tests for `src/stickler/reporting/html/`, whose own README documents the module.
| `test_html_reporter.py` | `HTMLReporter` orchestration and file output |
| `test_visualization_engine.py` | the chart and gauge fragments |
| `test_report_config.py` | `ReportConfig` validation |
| `test_pdf_document_ids.py` | PDF loading, navigation and failure display for literal document IDs, using the Node.js DOM/PDF.js adapter in `pdf_document_ids.cjs`; skips when Node.js is absent |
| `test_output_validation.py` | well-formedness and escaping of the emitted HTML |
| `test_html_non_match_records.py` | the non-match section driven end to end, no mocks |

Expand Down
89 changes: 89 additions & 0 deletions tests/reporting/html/pdf_document_ids.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// Offline PDF viewer contract test. This is a DOM adapter, not a browser.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');

const [, , source, docId, failure] = process.argv;
const elements = new Map();
const makeElement = () => ({
style: {}, children: [], listeners: {}, disabled: false,
appendChild(child) {
child.parentElement = this;
this.children.push(child);
if (child.id) elements.set(child.id, child);
},
addEventListener(name, handler) { this.listeners[name] = handler; },
getContext() { return {}; }
});
const document = {
addEventListener() {},
createElement: makeElement,
getElementById: id => elements.get(id) || null,
// Only simple ID selectors are supported. Raw punctuation is not an ID lookup.
querySelector: selector => /^#[\p{L}\p{N}_-]+$/u.test(selector) ? elements.get(selector.slice(1)) || null : null
};
const container = makeElement();
for (const prefix of ['pdf-canvas-', 'pdf-loading-', 'pdf-error-']) {
const element = makeElement();
element.id = prefix + docId;
element.style.display = prefix === 'pdf-loading-' ? 'block' : 'none';
container.appendChild(element);
}
const rendered = [];
const loads = [];
const pdf = {
numPages: 2,
getPage: async pageNumber => ({
getViewport: ({scale}) => ({width: 400 * scale, height: 600 * scale}),
render: () => ({promise: Promise.resolve().then(() => rendered.push(pageNumber))})
})
};
const context = vm.createContext({
document,
window: {},
console: {error() {}},
pdfjsLib: {
getDocument(options) {
loads.push(options);
return {promise: failure === 'True' ? Promise.reject(new Error('load failed')) : Promise.resolve(pdf)};
}
}
});
vm.runInContext(fs.readFileSync(source, 'utf8'), context);
context.args = ['fixture.pdf', 'pdf-canvas-' + docId, 'pdf-loading-' + docId, 'pdf-error-' + docId];
const settle = () => new Promise(resolve => setImmediate(resolve));

(async () => {
vm.runInContext('loadPDF(...args)', context);
await settle();
assert.equal(loads.length, 1, 'the PDF loader should be reached for this document ID');
assert.equal(loads[0].isEvalSupported, false);
assert.equal(elements.get('pdf-loading-' + docId).style.display, 'none');
const canvas = elements.get('pdf-canvas-' + docId);
if (failure === 'True') {
assert.equal(elements.get('pdf-error-' + docId).style.display, 'block');
assert.equal(canvas.style.display, 'none');
assert.deepEqual(rendered, []);
return;
}
assert.equal(canvas.style.display, 'block');
assert.deepEqual(rendered, [1]);
const prev = elements.get('prev-' + docId);
const next = elements.get('next-' + docId);
const info = elements.get('page-info-' + docId);
assert.equal(info.textContent, 'Page 1 of 2');
assert.equal(prev.disabled, true);
assert.equal(next.disabled, false);
next.listeners.click();
await settle();
assert.deepEqual(rendered, [1, 2]);
assert.equal(info.textContent, 'Page 2 of 2');
assert.equal(prev.disabled, false);
assert.equal(next.disabled, true);
prev.listeners.click();
await settle();
assert.deepEqual(rendered, [1, 2, 1]);
assert.equal(info.textContent, 'Page 1 of 2');
assert.equal(prev.disabled, true);
assert.equal(next.disabled, false);
})().catch(error => { console.error(error); process.exitCode = 1; });
34 changes: 34 additions & 0 deletions tests/reporting/html/test_pdf_document_ids.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""Exercise the PDF viewer with literal document IDs in Node's VM.

The DOM adapter models ID lookup, not rendering or the browser's CSS parser.
PDF.js is stubbed so loading, page completion, navigation and failure display
can run offline. The browser counterpart is still needed for visual rendering.
"""

import shutil
import subprocess
from pathlib import Path

import pytest

NODE = shutil.which("node")
ROOT = Path(__file__).resolve().parents[3]
SCRIPT = ROOT / "src/stickler/reporting/html/interactive/main.js"
HARNESS = Path(__file__).with_name("pdf_document_ids.cjs")


@pytest.mark.skipif(NODE is None, reason="PDF viewer behavior tests require Node.js")
@pytest.mark.parametrize(
"doc_id",
["invoice_1", "invoice_1.pdf", "inv 001", "a:b", "a[b]", 'a"b', "a#b", "請求書"],
)
@pytest.mark.parametrize("fails_to_load", [False, True])
def test_pdf_viewer_uses_literal_document_ids(doc_id, fails_to_load):
result = subprocess.run(
[NODE, str(HARNESS), str(SCRIPT), doc_id, str(fails_to_load)],
capture_output=True,
text=True,
check=False,
timeout=10,
)
assert result.returncode == 0, result.stdout + result.stderr