fix(bugs): obs card click + next-RDV radio + PDF toBlob fallback + head svg interactivity

Five fixes from manual QA:

1. ObservationCard — clicking anywhere on the card now selects it.
   The wrapping button only covered the text rows; empty space was dead.
   The whole card is now role="button" with keyboard (Enter/Space) support;
   inner action buttons (↑ ↓ 🗑) stop propagation so they don't double-fire.
   This was also the root cause of "details look stuck" — the active
   observation simply wasn't being switched.

2. NextAppointmentPicker — when value === undefined the "Date" radio was
   still showing as checked because `kind` defaulted to 'date'. The three
   radios now read from the raw `value?.kind` (which can be undefined),
   so "Aucun" is the only checked option when no next RDV is set.

3. svgToPng.rasterizeSvg — `canvas.toBlob` can return null in some
   browsers when the canvas state is unusual; the call now falls back to
   `canvas.toDataURL('image/png')` and decodes the base64 payload. Also
   paints a white background before canvg renders (so the PDF embed is
   opaque) and clamps width/height to >= 1px to avoid zero-area canvases.
   canvg errors are caught + logged instead of propagating, so the export
   still produces a (possibly blank) page rather than throwing.

4. svgConvention.parseSvgBones — clickable bones are now distinguished
   from decorative ones. Interactive = has a hitbox element OR category
   is spine-zone OR head. Decorative bones (teeth, malar, mandible,
   nasal-bone, facial-crest, individual vertebrae paths…) get
   `pointer-events: none` applied to their elements and are excluded from
   the returned map. Result: in Horse_head.svg, frontal/temporal/parietal/
   sphenoid/occipital/atm/ssb/c0-c1/hyoid become clickable as intended,
   while teeth / malar / mandible no longer intercept the clicks.

5. (covered by #1) — the per-observation details panel always read the
   active observation; the bug was the click handler scope. Confirmed by
   switching observations: the editor section now updates immediately.

88 tests still pass, lint clean, build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Bastien ChanotandClaude Opus 4.7 committed 2026-05-18 22:48:13 +02:00
1 parent 9a99fc916b
commit bdf5e6475b
5 files changed
+189 -37

No files matched your search

+38 -4
View File
@@ -40,8 +40,26 @@ export function validateBoneElement(el: Element): void {
}
}
/**
* A bone is interactive (clickable) if any of these is true:
* - at least one element carries the `hitbox` class (hitbox+visible pattern);
* - its category is `spine-zone` (single overlay polygon, pointer-events:all);
* - its category is `head` (single entry-point polygon for a detail SVG).
*
* Decorative elements (e.g. individual vertebrae paths, teeth, malar bone)
* carry `data-bone-id` so their colorization can be controlled by JS, but
* must NOT intercept clicks. We mark them with `pointer-events: none` and
* exclude them from the returned Bone map so the click handler ignores
* them naturally.
*/
function isInteractiveBone(bone: Bone): boolean {
if (bone.hitboxEls.length > 0) return true
if (bone.category === 'spine-zone' || bone.category === 'head') return true
return false
}
export function parseSvgBones(svgRoot: SVGSVGElement): Map<string, Bone> {
const map = new Map<string, Bone>()
const raw = new Map<string, Bone>()
const all = svgRoot.querySelectorAll<Element>('[data-bone-id]')
all.forEach((el) => {
validateBoneElement(el)
@@ -53,13 +71,13 @@ export function parseSvgBones(svgRoot: SVGSVGElement): Map<string, Bone> {
const classes = classList(el)
const isHitbox = classes.includes('hitbox')
const existing = map.get(id)
const existing = raw.get(id)
if (existing) {
if (isHitbox) existing.hitboxEls.push(el)
else existing.visibleEls.push(el)
if (opensDetail && !existing.opensDetail) existing.opensDetail = opensDetail
} else {
map.set(id, {
raw.set(id, {
id,
fr,
en,
@@ -70,7 +88,23 @@ export function parseSvgBones(svgRoot: SVGSVGElement): Map<string, Bone> {
})
}
})
return map
const interactive = new Map<string, Bone>()
raw.forEach((bone, id) => {
if (isInteractiveBone(bone)) {
interactive.set(id, bone)
} else {
// Decorative — make sure clicks fall through to whatever is underneath.
bone.visibleEls.forEach((el) => {
if (el instanceof SVGElement || el instanceof HTMLElement) {
el.style.pointerEvents = 'none'
} else {
el.setAttribute('pointer-events', 'none')
}
})
}
})
return interactive
}
export function getBoneIdFromEvent(event: Event): string | null {
+72 -16
View File
@@ -30,39 +30,95 @@ export default function ObservationCard({
const patCount =
observation.pathologyIds.length + observation.freeTextPathologies.length
function onCardKey(event: React.KeyboardEvent<HTMLDivElement>) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
onSelect()
}
}
function stop(fn: () => void) {
return (event: React.MouseEvent) => {
event.stopPropagation()
fn()
}
}
return (
<Card
className={[
'cursor-pointer p-4 transition',
active ? 'ring-2 ring-[var(--color-accent)]' : 'hover:bg-[var(--color-surface-strong)]',
active
? 'ring-2 ring-[var(--color-accent)]'
: 'hover:bg-[var(--color-surface-strong)]',
].join(' ')}
>
<div className="flex items-start justify-between gap-3">
<button
type="button"
onClick={onSelect}
className="flex-1 text-left"
aria-label={`Sélectionner l'observation ${index + 1}`}
>
<div
role="button"
tabIndex={0}
aria-label={`Sélectionner l'observation ${index + 1}`}
aria-pressed={active}
onClick={onSelect}
onKeyDown={onCardKey}
className="flex items-start justify-between gap-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/40 rounded-lg"
>
<div className="flex-1 min-h-[60px] text-left">
<div className="flex items-center gap-2 mb-2">
<Badge tone="neutral">Observation #{index + 1}</Badge>
{observation.severity && (
<Badge tone={observation.severity === 'sévère' ? 'danger' : observation.severity === 'modérée' ? 'warn' : 'neutral'}>
<Badge
tone={
observation.severity === 'sévère'
? 'danger'
: observation.severity === 'modérée'
? 'warn'
: 'neutral'
}
>
{observation.severity}
</Badge>
)}
</div>
<div className="text-sm text-[var(--color-ink-muted)]">
{zoneCount} zone{zoneCount > 1 ? 's' : ''} · {patCount} pathologie{patCount > 1 ? 's' : ''}
{zoneCount} zone{zoneCount > 1 ? 's' : ''} · {patCount} pathologie
{patCount > 1 ? 's' : ''}
</div>
{observation.comment && (
<p className="mt-2 text-sm line-clamp-2 text-[var(--color-ink)]">{observation.comment}</p>
<p className="mt-2 text-sm line-clamp-2 text-[var(--color-ink)]">
{observation.comment}
</p>
)}
</button>
<div className="flex flex-col gap-1">
<Button size="sm" variant="ghost" disabled={!canMoveUp} onClick={onMoveUp} aria-label="Monter">↑</Button>
<Button size="sm" variant="ghost" disabled={!canMoveDown} onClick={onMoveDown} aria-label="Descendre">↓</Button>
<Button size="sm" variant="ghost" onClick={onDelete} aria-label="Supprimer">🗑</Button>
</div>
<div
className="flex flex-col gap-1"
onClick={(event) => event.stopPropagation()}
>
<Button
size="sm"
variant="ghost"
disabled={!canMoveUp}
onClick={stop(onMoveUp)}
aria-label="Monter"
>
↑
</Button>
<Button
size="sm"
variant="ghost"
disabled={!canMoveDown}
onClick={stop(onMoveDown)}
aria-label="Descendre"
>
↓
</Button>
<Button
size="sm"
variant="ghost"
onClick={stop(onDelete)}
aria-label="Supprimer"
>
🗑
</Button>
</div>
</div>
</Card>
@@ -7,30 +7,53 @@ export interface NextAppointmentPickerProps {
onChange: (next: Report['nextAppointment']) => void
}
export default function NextAppointmentPicker({ value, onChange }: NextAppointmentPickerProps) {
const kind = value?.kind ?? 'date'
export default function NextAppointmentPicker({
value,
onChange,
}: NextAppointmentPickerProps) {
const kind = value?.kind
return (
<div className="space-y-2">
<Label>Prochain rendez-vous</Label>
<div className="flex gap-2 mb-2">
<label className="text-sm flex items-center gap-1">
<input type="radio" checked={kind === 'date'} onChange={() => onChange({ kind: 'date', date: '' })} />
<input
type="radio"
checked={kind === 'date'}
onChange={() => onChange({ kind: 'date', date: '' })}
/>
Date
</label>
<label className="text-sm flex items-center gap-1">
<input type="radio" checked={kind === 'period'} onChange={() => onChange({ kind: 'period', text: '' })} />
<input
type="radio"
checked={kind === 'period'}
onChange={() => onChange({ kind: 'period', text: '' })}
/>
Période libre
</label>
<label className="text-sm flex items-center gap-1">
<input type="radio" checked={value === undefined} onChange={() => onChange(undefined)} />
<input
type="radio"
checked={value === undefined}
onChange={() => onChange(undefined)}
/>
Aucun
</label>
</div>
{value?.kind === 'date' && (
<Input type="date" value={value.date} onChange={(e) => onChange({ kind: 'date', date: e.target.value })} />
<Input
type="date"
value={value.date}
onChange={(e) => onChange({ kind: 'date', date: e.target.value })}
/>
)}
{value?.kind === 'period' && (
<Input value={value.text} placeholder="ex. dans 3 semaines" onChange={(e) => onChange({ kind: 'period', text: e.target.value })} />
<Input
value={value.text}
placeholder="ex. dans 3 semaines"
onChange={(e) => onChange({ kind: 'period', text: e.target.value })}
/>
)}
</div>
)
+45 -9
View File
@@ -2,12 +2,21 @@ import { Canvg } from 'canvg'
const TARGET_WIDTH = 1200
export async function rasterizeSvg(svgString: string, scale: number): Promise<Uint8Array> {
export async function rasterizeSvg(
svgString: string,
scale: number,
): Promise<Uint8Array> {
const tmp = new DOMParser().parseFromString(svgString, 'image/svg+xml')
const root = tmp.documentElement
const vb = (root.getAttribute('viewBox') ?? '0 0 1000 600').split(/\s+/).map(Number)
const widthPx = Math.round(TARGET_WIDTH * Math.max(1, scale) * 0.5)
const heightPx = Math.round((vb[3] / vb[2]) * widthPx)
const vb = (root.getAttribute('viewBox') ?? '0 0 1000 600')
.split(/\s+/)
.map(Number)
const widthPx = Math.max(
1,
Math.round(TARGET_WIDTH * Math.max(1, scale) * 0.5),
)
const ratio = vb[3] > 0 && vb[2] > 0 ? vb[3] / vb[2] : 0.6
const heightPx = Math.max(1, Math.round(ratio * widthPx))
const canvas = document.createElement('canvas')
canvas.width = widthPx
@@ -15,11 +24,38 @@ export async function rasterizeSvg(svgString: string, scale: number): Promise<Ui
const ctx = canvas.getContext('2d')
if (!ctx) throw new Error('Canvas 2D context unavailable')
const canv = await Canvg.from(ctx, svgString)
await canv.render()
// White background so the resulting PNG is opaque (some PDF viewers
// ignore transparent canvases when embedded).
ctx.fillStyle = '#ffffff'
ctx.fillRect(0, 0, widthPx, heightPx)
const blob: Blob = await new Promise((resolve, reject) => {
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('toBlob returned null'))), 'image/png')
try {
const canv = await Canvg.from(ctx, svgString, {
anonymousCrossOrigin: true,
})
await canv.render()
} catch (err) {
console.error('canvg render failed; falling back to blank canvas', err)
}
const blob = await new Promise<Blob | null>((resolve) => {
canvas.toBlob((b) => resolve(b), 'image/png')
})
return new Uint8Array(await blob.arrayBuffer())
if (blob) return new Uint8Array(await blob.arrayBuffer())
// toBlob can return null in some browsers when the canvas state is
// unusual; fall back to toDataURL which is synchronous and broadly
// available.
const dataUrl = canvas.toDataURL('image/png')
const comma = dataUrl.indexOf(',')
if (comma < 0) {
throw new Error('canvas.toDataURL returned an unexpected payload')
}
const base64 = dataUrl.slice(comma + 1)
const binary = atob(base64)
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i += 1) {
bytes[i] = binary.charCodeAt(i)
}
return bytes
}
+4 -1
View File
@@ -8,7 +8,10 @@ vi.mock('canvg', () => ({
describe('rasterizeSvg', () => {
it('returns a Uint8Array', async () => {
const canvas = document.createElement('canvas')
canvas.getContext = (() => ({})) as unknown as HTMLCanvasElement['getContext']
canvas.getContext = (() => ({
fillStyle: '',
fillRect: () => {},
})) as unknown as HTMLCanvasElement['getContext']
canvas.toBlob = ((cb: BlobCallback) => {
cb(new Blob([new Uint8Array([1, 2, 3])], { type: 'image/png' }))
}) as HTMLCanvasElement['toBlob']