Add the A4 report designer and fix band layout

Brings in the A4 (millimetre) report designer alongside the existing
matrix editor, migrates the frontend from react-scripts to Vite/Vitest,
and fixes four defects found while using the A4 band tools.

Layout — layout.js now implements the standard banded-report model:
everything prints where it was drawn, and a band growing per data row is
the only thing that moves anything. Previously `paginate` re-flowed every
band from the top margin, so a band placed halfway down the page
previewed at the top, and `header` was treated as a page header and
hoisted above the statics drawn before it. A header is a COLUMN header:
it prints in place and repeats only on a continuation page. Statics now
take part too — one drawn below a band keeps its drawn gap as that band
grows, and follows onto the next page rather than vanishing when pushed
past the bottom margin. The displacement is keyed on the band's design
bottom, not on an instance's laid-out y: every row of a band shares one
design position, so keying on the instance measured the gap from row 1
and let the static overlap rows 2..n.

Band children — a child's x is relative to its band, as its y already
was. layout() emitted it raw, so a field printed measured from the paper
edge instead of the band's left margin. Instances now carry bandX.

Band placement — a band's x comes from the page margins, so creation
takes only the click's Y (the factory's x was being overwritten by the
spread order) and dragging is locked to the vertical axis. Bands render
as a strip, with top/bottom rules only, matching the matrix editor.
fromApiReport reflows on load so reports saved with a stray x straighten
themselves. Matrix bands are constrained to vertical too.

Drag lifecycle — useElementDrag re-subscribed its document listeners on
every render during a drag, because the effect depended on an unmemoized
onDrag. Each re-subscribe removed the mouseup listener before adding the
next, measured as add/remove/add/remove/add across two mousemoves, and a
release landing in that gap was lost: the element kept following the
cursor until the next click. Snapping made it routine, since a held
guide stops x/y changing and leaves the guide overlay's render sitting
between the move and the release. onDrag and dragData now go through
refs so the effect depends on [isDragging] alone.

Note: the matrix editor has no test coverage, so its band constraint is
verified by reading only. The A4 suite is 201 passing tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-09-20 12:52:20 +03:00
parent ddc128dba4
commit 122480cd46
76 changed files with 11286 additions and 15322 deletions
+151 -14
View File
@@ -32,6 +32,8 @@ export default function Main() {
const [error, setError] = useState('');
const [isSaving, setIsSaving] = useState(false);
const [showNoticeReport, setShowNoticeReport] = useState(false);
const [isPrinting, setIsPrinting] = useState(false);
const [showDesignMenu, setShowDesignMenu] = useState(false);
const [showManualForm, setShowManualForm] = useState(false);
const [manualForm, setManualForm] = useState({ value: '', note: '' });
@@ -103,7 +105,7 @@ export default function Main() {
// closed tab would stop the scale). The UI only supplies the string.
useEffect(() => {
if (!selectedProtocol) return;
const serialUrl = process.env.REACT_APP_SERIAL_URL || 'http://localhost:5000';
const serialUrl = import.meta.env.VITE_SERIAL_URL || 'http://localhost:5000';
fetch(serialUrl + '/poll', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -331,6 +333,103 @@ export default function Main() {
};
}, [selectedVehicle, netWeight, definitions, entries]);
// Look up the saved notice report by name. Server-side filter — ?name= is a
// real filter now that django-filter is configured, replacing the old
// fetch-every-report-then-.find() pattern.
const fetchNoticeReport = async () => {
const res = await api.get('/api/reports/?name=notice_report');
return (res.data.results || res.data || [])[0] || null;
};
// Warm the A4 print chunk on hover/focus, so the click handler's dynamic
// import resolves from cache instead of blocking on a network round-trip
// between the operator's click and window.print(). Cheap insurance: the
// print dialog is not gated behind transient user activation the way
// window.open is, but the shorter the gap the less there is to go wrong on
// a slow station. Failure is ignored — the click path imports it anyway.
const prefetchA4Print = () => {
import('./ReportEditor/a4/print/printReport').catch(() => {});
};
// Print Notice is kind-aware: an A4 report goes straight to the browser
// print dialog (where "Save as PDF" is a destination), a matrix report opens
// the existing on-screen modal exactly as before.
const handlePrintNotice = async () => {
if (isPrinting) return;
setIsPrinting(true);
try {
const report = await fetchNoticeReport();
if (!report) {
setError('Report "notice_report" not found. Create it in the Report Editor first.');
return;
}
if (report.kind === 'a4') {
// Lazy so Main.jsx does not pull the A4 print tree into the
// main bundle for operators who never print an A4 notice.
const { printA4Report } = await import('./ReportEditor/a4/print/printReport');
await printA4Report(report, vehicleReportData);
} else {
setShowNoticeReport(true);
}
} catch (err) {
console.error('Failed to print notice:', err);
setError('Failed to load the notice report');
} finally {
setIsPrinting(false);
}
};
// Design Notice routes to the editor that can actually edit the saved
// report. A matrix report opened in the mm editor would read its character
// coordinates as millimetres, so the kind decides the route, not a default.
const handleDesignNotice = async () => {
const state = { reportName: 'notice_report', vehicleData: vehicleReportData };
try {
const report = await fetchNoticeReport();
navigate(report?.kind === 'a4' ? '/report-editor-a4' : '/report-editor', { state });
} catch (err) {
// Nothing saved yet, or the lookup failed — the matrix editor is the
// existing default and pre-fills the name so Save creates it.
console.error('Failed to resolve notice report kind:', err);
navigate('/report-editor', { state });
}
};
/**
* Open a chosen editor regardless of what is saved.
*
* The automatic route above is right for editing an existing notice; this is
* for deliberately starting the OTHER kind. Opening a report in the wrong
* editor reinterprets its coordinates — character cells as millimetres, or
* the reverse — so a mismatch is confirmed rather than done silently.
*/
const handleDesignAs = async (kind) => {
setShowDesignMenu(false);
const state = { reportName: 'notice_report', vehicleData: vehicleReportData };
const route = kind === 'a4' ? '/report-editor-a4' : '/report-editor';
let saved = null;
try {
saved = await fetchNoticeReport();
} catch (err) {
console.error('Failed to resolve notice report kind:', err);
}
if (saved && saved.kind !== kind) {
const savedLabel = saved.kind === 'a4' ? 'A4' : 'matrix';
const targetLabel = kind === 'a4' ? 'A4' : 'matrix';
const ok = window.confirm(
`"notice_report" is saved as a ${savedLabel} report.\n\n` +
`Opening it in the ${targetLabel} editor will read its positions in the ` +
`wrong units, and saving would overwrite the ${savedLabel} layout.\n\n` +
`Open the ${targetLabel} editor anyway?`
);
if (!ok) return;
}
navigate(route, { state });
};
return (
<div>
<Header />
@@ -584,21 +683,59 @@ export default function Main() {
<div className="weight-card-value">{netWeight} kg</div>
<button
className="weight-set-btn"
onClick={() => setShowNoticeReport(true)}
onClick={handlePrintNotice}
onMouseEnter={prefetchA4Print}
onFocus={prefetchA4Print}
disabled={isPrinting}
>
Print Notice
</button>
<button
className="weight-set-btn"
onClick={() => navigate('/report-editor', {
state: {
reportName: 'notice_report',
vehicleData: vehicleReportData,
}
})}
>
Design Notice
{isPrinting ? 'Preparing...' : 'Print Notice'}
</button>
{/* Split button: the main action routes by
the saved report's kind; the caret opens
an explicit choice for starting the other
kind. */}
<div className="design-notice-split">
<button
className="weight-set-btn design-notice-main"
onClick={handleDesignNotice}
>
Design Notice
</button>
<button
className="weight-set-btn design-notice-caret"
onClick={() => setShowDesignMenu(v => !v)}
aria-haspopup="menu"
aria-expanded={showDesignMenu}
title="Choose which editor to open"
>
▾
</button>
{showDesignMenu && (
<>
{/* Click-away closes the menu. */}
<div
className="design-notice-backdrop"
onClick={() => setShowDesignMenu(false)}
/>
<div className="design-notice-menu" role="menu">
<button
role="menuitem"
onClick={() => handleDesignAs('matrix')}
>
<strong>Matrix editor</strong>
<span>Character grid · dot-matrix printer</span>
</button>
<button
role="menuitem"
onClick={() => handleDesignAs('a4')}
>
<strong>A4 editor</strong>
<span>Millimetres · laser printer &amp; PDF</span>
</button>
</div>
</>
)}
</div>
</div>
)}
</div>