refactor(anatomy): adapt parser to new SVG convention (categories + single-element)

User dropped new Horse.svg / Horse_head.svg that follow a simpler
convention:

- Categories renamed to longer human strings:
    articulation       → articulations
    charniere          → charni-res-vert-brales
    spine-zone         → zone-colonne
    cadran-crane       → cadrans-du-cr-ne
    head, os-overlay   → dropped (head zone is now category="os" + data-anno-opens-detail)
    os                 → unchanged
- No more hitbox / visible class split; multiple elements may still share
  the same data-anno-id but they all carry the same role.
- Trigger-only zones (`data-anno-opens-detail="head"`) may omit
  `data-anno-name-fr/en`.

Changes:
- `Bone` now exposes a single `els: Element[]` instead of `hitboxEls +
  visibleEls`.
- `parseSvgBones` accepts annotations without fr/en labels (defaults to
  empty string) but still rejects unknown or missing categories.
- The "interactive vs decorative" filter is gone — every parsed
  annotation is interactive, since the new SVGs only annotate the
  clickable zones.
- Vertebra-picker trigger: `bone.category === 'zone-colonne'`
  (EditorRoute + ObservationCard).
- PDF colorisation in `observationPage.colorizedSvgString` writes the
  accent fill to every `els[]` entry (no more hitbox dual-pass).
- Dead `src/components/observation/ObservationEditor.tsx` removed (its
  body lives inside ObservationCard since the accordion refactor).
- Tests rewritten for the new vocabulary; synthetic fixture uses the new
  categories, real-SVG test asserts 18 + 9 unique zones.

92/92 tests 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-19 04:06:26 +02:00
1 parent 1109e33383
commit cad94a49db
10 files changed
+325 -428

No files matched your search

+47 -63
View File
@@ -2,35 +2,34 @@ import { SvgConventionError } from './types'
import type { Bone, BoneCategory } from './types'
const VALID_CATEGORIES: readonly BoneCategory[] = [
'articulation',
'charniere',
'spine-zone',
'articulations',
'charni-res-vert-brales',
'zone-colonne',
'cadrans-du-cr-ne',
'os',
'os-overlay',
'head',
'cadran-crane',
]
export function isValidCategory(value: string): value is BoneCategory {
return (VALID_CATEGORIES as readonly string[]).includes(value)
}
function classList(el: Element): string[] {
return (el.getAttribute('class') ?? '').split(/\s+/).filter(Boolean)
}
export function validateBoneElement(el: Element): void {
const boneId = el.getAttribute('data-anno-id') ?? ''
for (const attr of ['data-anno-name-fr', 'data-anno-name-en', 'data-anno-category']) {
if (!el.getAttribute(attr)) {
throw new SvgConventionError(
`Element data-anno-id="${boneId}" missing attribute ${attr}`,
boneId,
attr,
)
}
if (!boneId) {
throw new SvgConventionError(
'Element with missing data-anno-id',
boneId,
'data-anno-id',
)
}
const cat = el.getAttribute('data-anno-category') ?? ''
if (!cat) {
throw new SvgConventionError(
`Element data-anno-id="${boneId}" missing attribute data-anno-category`,
boneId,
'data-anno-category',
)
}
if (!isValidCategory(cat)) {
throw new SvgConventionError(
`Element data-anno-id="${boneId}" has unknown data-anno-category="${cat}"`,
@@ -41,72 +40,57 @@ 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).
* Parses an SVG document and returns a map of `data-anno-id` → Bone.
*
* Decorative elements (e.g. individual vertebrae paths, teeth, malar bone)
* carry `data-anno-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.
* Every element carrying `data-anno-id` is collected. Multiple elements
* may share the same id (hitbox + visible pattern, or layered shapes);
* they end up grouped under the same Bone with all elements in `els`.
*
* Throws `SvgConventionError` if any required attribute is missing or
* `data-anno-category` is unknown. `data-anno-name-fr/en` are optional —
* trigger-only zones (those carrying `data-anno-opens-detail`) typically
* skip them.
*/
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 raw = new Map<string, Bone>()
const map = new Map<string, Bone>()
const all = svgRoot.querySelectorAll<Element>('[data-anno-id]')
all.forEach((el) => {
validateBoneElement(el)
const id = el.getAttribute('data-anno-id') as string
const fr = el.getAttribute('data-anno-name-fr') as string
const en = el.getAttribute('data-anno-name-en') as string
const fr = el.getAttribute('data-anno-name-fr') ?? ''
const en = el.getAttribute('data-anno-name-en') ?? ''
const category = el.getAttribute('data-anno-category') as BoneCategory
const opensDetail = el.getAttribute('data-anno-opens-detail') ?? undefined
const classes = classList(el)
const isHitbox = classes.includes('hitbox')
const opensDetail =
el.getAttribute('data-anno-opens-detail') ?? undefined
const existing = raw.get(id)
const existing = map.get(id)
if (existing) {
if (isHitbox) existing.hitboxEls.push(el)
else existing.visibleEls.push(el)
if (opensDetail && !existing.opensDetail) existing.opensDetail = opensDetail
existing.els.push(el)
if (opensDetail && !existing.opensDetail) {
existing.opensDetail = opensDetail
}
// Prefer the first non-empty label we see.
if (!existing.fr && fr) existing.fr = fr
if (!existing.en && en) existing.en = en
} else {
raw.set(id, {
map.set(id, {
id,
fr,
en,
category,
opensDetail,
hitboxEls: isHitbox ? [el] : [],
visibleEls: isHitbox ? [] : [el],
els: [el],
})
}
})
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
return map
}
/**
* Walks up from `event.target` to find the nearest element carrying
* `data-anno-id`. Returns null when the click did not land on an
* annotated element.
*/
export function getBoneIdFromEvent(event: Event): string | null {
let node = event.target as Element | null
while (node && node.nodeType === 1) {
+21 -14
View File
@@ -1,27 +1,34 @@
/** Valid data-anno-category values per the SVG convention. */
/**
* Valid data-anno-category values per the SVG convention.
*
* Categories are scoped to the kind of anatomical structure each
* annotation represents. Adding a new value here is the only place to
* touch when the source SVGs introduce one.
*/
export type BoneCategory =
| 'articulation'
| 'charniere'
| 'spine-zone'
| 'articulations'
| 'charni-res-vert-brales'
| 'zone-colonne'
| 'cadrans-du-cr-ne'
| 'os'
| 'os-overlay'
| 'head'
| 'cadran-crane'
/** A logical bone as parsed from an SVG — groups hitbox + visible elements. */
/**
* Logical annotation as parsed from an SVG. All DOM elements sharing the
* same `data-anno-id` are grouped into one Bone. `id` is the persisted
* identifier surfaced in the report JSON contract
* (`ObservationZone.boneId`); keep it stable across SVG renames.
*/
export interface Bone {
id: string
/** French label from data-anno-name-fr */
/** French label from data-anno-name-fr — may be empty for opens-detail-only triggers */
fr: string
/** English label from data-anno-name-en */
/** English label from data-anno-name-en — may be empty */
en: string
category: BoneCategory
/** Detail popup id from data-anno-opens-detail, if present */
opensDetail?: string
/** Elements with class containing "hitbox" */
hitboxEls: Element[]
/** Elements with class containing "visible" */
visibleEls: Element[]
/** All DOM elements carrying this annotation (used for colorization) */
els: Element[]
}
/** Visual state applied to SVG elements for multi-observation colorization. */
+1 -1
View File
@@ -119,7 +119,7 @@ export default function EditorRoute() {
: [...activeObs.zones, newZone]
updateObservation(activeIndex, { ...activeObs, zones: nextZones })
if (!exists && bone.category === 'spine-zone') {
if (!exists && bone.category === 'zone-colonne') {
setVertebraTarget(nextZones.length - 1)
}
}
@@ -187,7 +187,7 @@ export default function ObservationCard({
<ul className="flex flex-wrap gap-2">
{observation.zones.map((z, i) => {
const b = bones.get(z.boneId)
const isSpine = b?.category === 'spine-zone'
const isSpine = b?.category === 'zone-colonne'
return (
<li key={`${z.boneId}-${i}`}>
<Badge tone="accent" className="gap-2">
@@ -1,126 +0,0 @@
import { useMemo } from 'react'
import type { Observation, ObservationZone, Vertebra } from '@/domain/schema/observation'
import type { Pathology } from '@/domain/schema/pathology'
import type { Bone } from '@/anatomy/types'
import Label from '@/components/ui/Label'
import Textarea from '@/components/ui/Textarea'
import Badge from '@/components/ui/Badge'
import PathologyPicker from './PathologyPicker'
import FreeTextPathologyInput from './FreeTextPathologyInput'
import SeveritySelector from './SeveritySelector'
export interface ObservationEditorProps {
observation: Observation
bones: Map<string, Bone>
speciesId: string
pathologyPool: Pathology[]
onChange: (next: Observation) => void
onOpenVertebraPicker: (zoneIndex: number) => void
onRemoveZone: (zoneIndex: number) => void
}
function describeZone(z: ObservationZone, bones: Map<string, Bone>): string {
const b = bones.get(z.boneId)
const label = b?.fr ?? z.boneId
if (z.vertebrae?.length) {
const vs = z.vertebrae.map((v: Vertebra) => `${v.region}${v.index}`).join(', ')
return `${label} (${vs})`
}
return label
}
export default function ObservationEditor({
observation,
bones,
speciesId,
pathologyPool,
onChange,
onOpenVertebraPicker,
onRemoveZone,
}: ObservationEditorProps) {
const zoneBoneIds = useMemo(
() => observation.zones.map((z) => z.boneId),
[observation.zones],
)
return (
<div className="space-y-6">
<section>
<Label>Zones sélectionnées</Label>
{observation.zones.length === 0 ? (
<p className="text-sm text-[var(--color-ink-muted)]">
Cliquez sur les zones du schéma pour les ajouter à cette observation.
</p>
) : (
<ul className="flex flex-wrap gap-2">
{observation.zones.map((z, i) => {
const b = bones.get(z.boneId)
const isSpine = b?.category === 'spine-zone'
return (
<li key={`${z.boneId}-${i}`}>
<Badge tone="accent" className="gap-2">
{describeZone(z, bones)}
{isSpine && (
<button
type="button"
onClick={() => onOpenVertebraPicker(i)}
className="underline text-xs text-[var(--color-accent-strong)]"
>
Préciser…
</button>
)}
<button
type="button"
aria-label={`Retirer ${b?.fr ?? z.boneId}`}
onClick={() => onRemoveZone(i)}
className="ml-1 text-[var(--color-accent-strong)]"
>
✕
</button>
</Badge>
</li>
)
})}
</ul>
)}
</section>
<section>
<Label>Pathologies (référence)</Label>
<PathologyPicker
pool={pathologyPool}
speciesId={speciesId}
boneIds={zoneBoneIds}
selected={observation.pathologyIds}
onChange={(ids) => onChange({ ...observation, pathologyIds: ids })}
/>
</section>
<section>
<Label>Pathologies (texte libre)</Label>
<FreeTextPathologyInput
items={observation.freeTextPathologies}
onChange={(items) => onChange({ ...observation, freeTextPathologies: items })}
/>
</section>
<section>
<Label>Sévérité</Label>
<SeveritySelector
value={observation.severity}
onChange={(s) => onChange({ ...observation, severity: s })}
/>
</section>
<section>
<Label htmlFor="obs-comment">Commentaire</Label>
<Textarea
id="obs-comment"
value={observation.comment}
onChange={(e) => onChange({ ...observation, comment: e.target.value })}
placeholder="Notes cliniques détaillées…"
/>
</section>
</div>
)
}
+2 -6
View File
@@ -22,13 +22,9 @@ async function colorizedSvgString(
.forEach((z) => {
const bone = bones.get(z.boneId)
if (!bone) return
bone.visibleEls.forEach((el) => {
bone.els.forEach((el) => {
el.setAttribute('fill', '#b85a3f')
el.setAttribute('fill-opacity', '0.85')
})
bone.hitboxEls.forEach((el) => {
el.setAttribute('fill', '#b85a3f')
el.setAttribute('fill-opacity', '0.4')
el.setAttribute('fill-opacity', '0.65')
})
})
return new XMLSerializer().serializeToString(root)