feat(editor+pdf): per-zone PDF sections + collapsible findings pickers

PDF
---
The flat single-line "CONSTATS" section bundled every selected leaf
from every zone plus the free-text additions on one line, which got
hard to read as soon as an observation touched more than one zone.

The export now groups catalog findings by their JSON `zoneId` and
emits one section per zone, labelled with the zone's French name
("CONSTATS — SPHÉNOÏDE", "CONSTATS — ARTICULATION TEMPORO-MANDIBULAIRE
(ATM)", …). Free-text additions move to a dedicated "CONSTATS LIBRES"
section directly below.

The catalog tree is loaded once at the top of exportReportToPdf and
threaded through to addObservationPage, so the per-zone label lookup
costs nothing extra per observation.

Editor
------
Inside an expanded observation, each available zone's
FindingsTreePicker is now wrapped in an accordion header that mirrors
the ObservationCard expand/collapse semantics:

- Click a zone header → that picker opens and any other picker on the
  card closes.
- Click an open zone header → it collapses.
- Each header shows a selected-count badge and a ▼/▲ caret.

Default state is "all closed" so the card stays compact when the user
expands a new observation. Motion-based height/opacity transition
matches the observation card body animation for visual consistency.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Bastien ChanotandClaude committed 2026-05-20 05:07:03 +02:00
1 parent 1e12f2252f
commit de40c5f91e
3 files changed
+145 -33

No files matched your search

+79 -21
View File
@@ -1,4 +1,4 @@
import { useMemo } from 'react'
import { useMemo, useState } from 'react'
import type {
Observation,
ObservationZone,
@@ -66,6 +66,11 @@ export default function ObservationCard({
onOpenVertebraPicker,
onRemoveZone,
}: ObservationCardProps) {
// Per-zone picker accordion — only one tree picker open at a time,
// matching the observation-card accordion semantics. Closed by default
// so the card stays compact when first expanded.
const [expandedZoneId, setExpandedZoneId] = useState<string | null>(null)
const zoneCount = observation.zones.length
const findingCount =
observation.findings.length + observation.freeTextFindings.length
@@ -262,26 +267,79 @@ export default function ObservationCard({
: 'Aucun référentiel disponible pour ces zones. Utilisez le texte libre ci-dessous.'}
</p>
) : (
<div className="space-y-4">
{zonesWithTree.map(({ tree }) => (
<div
key={tree.id}
className="rounded-xl border border-[var(--color-border)] p-3 bg-[var(--color-surface)]"
>
<div className="text-xs uppercase tracking-wide text-[var(--color-ink-muted)] mb-2">
{tree.name_fr}
</div>
<FindingsTreePicker
zoneId={tree.id}
tree={tree}
selected={observation.findings}
onChange={(next) =>
onChange({ ...observation, findings: next })
}
/>
</div>
))}
</div>
<ul className="space-y-2">
{zonesWithTree.map(({ tree }) => {
const expanded = expandedZoneId === tree.id
const selectedCount = observation.findings.filter(
(f) => f.zoneId === tree.id,
).length
return (
<li
key={tree.id}
className={[
'rounded-xl border bg-[var(--color-surface)] transition',
expanded
? 'border-[var(--color-accent)] ring-1 ring-[var(--color-accent)]'
: 'border-[var(--color-border)]',
].join(' ')}
>
<button
type="button"
onClick={() =>
setExpandedZoneId(expanded ? null : tree.id)
}
aria-expanded={expanded}
aria-controls={`findings-zone-${tree.id}`}
className="w-full flex items-center justify-between gap-2 px-3 py-2 text-left rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/40"
>
<span className="flex items-center gap-2">
<span className="text-sm font-medium text-[var(--color-ink)]">
{tree.name_fr}
</span>
{selectedCount > 0 && (
<span
aria-label={`${selectedCount} constat${selectedCount > 1 ? 's' : ''} sélectionné${selectedCount > 1 ? 's' : ''}`}
className="inline-flex items-center justify-center min-w-[20px] h-[20px] px-1.5 rounded-full text-[11px] font-semibold bg-[var(--color-accent)] text-white"
>
{selectedCount}
</span>
)}
</span>
<span
aria-hidden="true"
className="text-[var(--color-ink-muted)]"
>
{expanded ? '▲' : '▼'}
</span>
</button>
<AnimatePresence initial={false}>
{expanded && (
<motion.div
key="picker-body"
id={`findings-zone-${tree.id}`}
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.18, ease: 'easeOut' }}
className="overflow-hidden"
>
<div className="px-3 pb-3 pt-1 border-t border-[var(--color-border)]">
<FindingsTreePicker
zoneId={tree.id}
tree={tree}
selected={observation.findings}
onChange={(next) =>
onChange({ ...observation, findings: next })
}
/>
</div>
</motion.div>
)}
</AnimatePresence>
</li>
)
})}
</ul>
)}
</section>
+32 -1
View File
@@ -1,5 +1,6 @@
import { PDFDocument } from 'pdf-lib'
import type { Report } from '@/domain/schema/report'
import type { SpeciesFindings } from '@/domain/schema/findings'
import { embedFonts } from './fonts'
import { addObservationPage } from './render/observationPage'
import { addConclusionPage } from './render/conclusionPage'
@@ -46,6 +47,27 @@ export async function buildZoneLabels(report: Report): Promise<Map<string, strin
return labels
}
/**
* Loads the parsed findings catalog for a species so the PDF renderer
* can resolve a Finding's `zoneId` (JSON catalog key) back to its
* human-readable zone name. Returns null if the species lacks a
* catalog or the lazy import fails — the PDF still renders, but
* per-zone groups fall back to the raw zoneId.
*/
async function loadSpeciesFindings(
speciesId: string,
): Promise<SpeciesFindings | null> {
const species = getSpecies(speciesId)
if (!species) return null
try {
const m = await species.findings()
return m.default
} catch (err) {
console.warn(`loadSpeciesFindings: failed for ${speciesId}`, err)
return null
}
}
export async function exportReportToPdf(report: Report): Promise<Uint8Array> {
const pdfDoc = await PDFDocument.create()
pdfDoc.setTitle(`Bilan ostéo — ${report.animal.name}`)
@@ -56,9 +78,18 @@ export async function exportReportToPdf(report: Report): Promise<Uint8Array> {
const fonts = await embedFonts(pdfDoc)
const zoneLabels = await buildZoneLabels(report)
const findingsTree = await loadSpeciesFindings(report.animal.speciesId)
for (let i = 0; i < report.observations.length; i += 1) {
await addObservationPage(pdfDoc, report, report.observations[i], i, fonts, zoneLabels)
await addObservationPage(
pdfDoc,
report,
report.observations[i],
i,
fonts,
zoneLabels,
findingsTree,
)
}
await addConclusionPage(pdfDoc, report, fonts)
+34 -11
View File
@@ -1,7 +1,8 @@
import { rgb, PageSizes, type PDFDocument, type PDFFont } from 'pdf-lib'
import type { EmbeddedFonts } from '@/pdf/fonts'
import type { Report } from '@/domain/schema/report'
import type { Observation } from '@/domain/schema/observation'
import type { Finding, Observation } from '@/domain/schema/observation'
import type { SpeciesFindings } from '@/domain/schema/findings'
import { drawHeader } from './header'
import { rasterizeSvg } from './svgToPng'
import { loadSvg } from '@/anatomy/svgLoader'
@@ -94,6 +95,7 @@ export async function addObservationPage(
obsIndex: number,
fonts: EmbeddedFonts,
zoneLabels: Map<string, string>,
findingsTree: SpeciesFindings | null,
): Promise<void> {
const page = pdfDoc.addPage(PageSizes.A4)
const { width, height } = page.getSize()
@@ -195,16 +197,37 @@ export async function addObservationPage(
const sections: Array<{ label: string; value: string }> = [
{ label: 'ZONES', value: zonesText || '—' },
]
const findingLabels = [
...observation.findings.map((f) =>
f.requiresVetReferral
? `⚠ ${f.labelFrSnapshot}`
: f.labelFrSnapshot,
),
...observation.freeTextFindings,
]
if (findingLabels.length) {
sections.push({ label: 'CONSTATS', value: findingLabels.join(' · ') })
// Group catalog findings by their JSON zoneId so each zone gets its
// own labelled section. Preserves first-seen order so the on-screen
// pick order survives the export.
const findingsByZone = new Map<string, Finding[]>()
for (const f of observation.findings) {
const list = findingsByZone.get(f.zoneId)
if (list) {
list.push(f)
} else {
findingsByZone.set(f.zoneId, [f])
}
}
for (const [zoneId, group] of findingsByZone) {
const zoneName = findingsTree?.zones[zoneId]?.name_fr ?? zoneId
const value = group
.map((f) =>
f.requiresVetReferral ? `⚠ ${f.labelFrSnapshot}` : f.labelFrSnapshot,
)
.join(' · ')
sections.push({
label: `CONSTATS — ${zoneName.toUpperCase()}`,
value,
})
}
if (observation.freeTextFindings.length) {
sections.push({
label: 'CONSTATS LIBRES',
value: observation.freeTextFindings.join(' · '),
})
}
if (observation.severity) {
sections.push({ label: 'SÉVÉRITÉ', value: observation.severity })