diff --git a/src/app/routes/EditorRoute.tsx b/src/app/routes/EditorRoute.tsx index 2bbcbefa..2ceab1eb 100644 --- a/src/app/routes/EditorRoute.tsx +++ b/src/app/routes/EditorRoute.tsx @@ -19,6 +19,7 @@ import { writeCachedPractitioner } from '@/state/practitionerCache' import { getSpecies } from '@/domain/species/registry' import { loadSvg } from '@/anatomy/svgLoader' import { parseSvgBones } from '@/anatomy/svgConvention' +import { distributeVertebraeToZones } from '@/lib/spineZones' import type { Bone, BoneState } from '@/anatomy/types' import type { Observation, ObservationZone } from '@/domain/schema/observation' import type { SpeciesFindings } from '@/domain/schema/findings' @@ -438,8 +439,14 @@ export default function EditorRoute() { setVertebraTarget(null) return } - const next = [...fresh.zones] - next[vertebraTarget] = { ...next[vertebraTarget], vertebrae } + // Vertebrae picked in another region tab spawn/merge the matching + // spine zone, so the SVG highlights it and its findings picker shows. + const next = distributeVertebraeToZones( + fresh.zones, + vertebraTarget, + vertebrae, + bones, + ) updateObservation(activeIndex, { ...fresh, zones: next }) setVertebraTarget(null) }} diff --git a/src/components/observation/VertebraPicker.tsx b/src/components/observation/VertebraPicker.tsx index bc0b4175..1c94f065 100644 --- a/src/components/observation/VertebraPicker.tsx +++ b/src/components/observation/VertebraPicker.tsx @@ -6,6 +6,8 @@ import type { Vertebra, VertebralRegion } from '@/domain/schema/observation' import type { VertebralFormula } from '@/domain/species/types' import { useT } from '@/i18n/useT' +export { regionFromLabel } from '@/lib/spineZones' + const REGIONS: VertebralRegion[] = ['C', 'T', 'L', 'S', 'Cd'] const REGION_KEY: Record = { C: 'vertebra.region.C', @@ -15,24 +17,6 @@ const REGION_KEY: Record = { Cd: 'vertebra.region.Cd', } -/** - * Infers the matching vertebral region from a free-form anatomical label - * (zone name in FR or EN). Matches on substring roots, case-insensitive, - * accent-insensitive. Returns undefined when no root matches. - */ -export function regionFromLabel(label: string): VertebralRegion | undefined { - const norm = label - .normalize('NFD') - .replace(/\p{Diacritic}/gu, '') - .toLowerCase() - if (norm.includes('cervic')) return 'C' - if (norm.includes('thorac') || norm.includes('dors')) return 'T' - if (norm.includes('lombair') || norm.includes('lumbar')) return 'L' - if (norm.includes('sacral') || norm.includes('sacre')) return 'S' - if (norm.includes('caudal') || norm.includes('coccyg')) return 'Cd' - return undefined -} - export interface VertebraPickerProps { open: boolean onClose: () => void diff --git a/src/lib/spineZones.ts b/src/lib/spineZones.ts new file mode 100644 index 00000000..6dd5e791 --- /dev/null +++ b/src/lib/spineZones.ts @@ -0,0 +1,122 @@ +import type { + ObservationZone, + Vertebra, + VertebralRegion, +} from '@/domain/schema/observation' +import type { Bone } from '@/anatomy/types' + +/** + * Infers the matching vertebral region from a free-form anatomical label + * (zone name in FR or EN). Matches on substring roots, case-insensitive, + * accent-insensitive. Returns undefined when no root matches. + */ +export function regionFromLabel(label: string): VertebralRegion | undefined { + const norm = label + .normalize('NFD') + .replace(/\p{Diacritic}/gu, '') + .toLowerCase() + if (norm.includes('cervic')) return 'C' + if (norm.includes('thorac') || norm.includes('dors')) return 'T' + if (norm.includes('lombair') || norm.includes('lumbar')) return 'L' + if (norm.includes('sacral') || norm.includes('sacre')) return 'S' + if (norm.includes('caudal') || norm.includes('coccyg')) return 'Cd' + return undefined +} + +/** + * Finds the spine-zone boneId whose label maps to the given vertebral region. + * Spine zones are the SVG elements flagged data-anno-special="vertebral-precision". + * Returns undefined when the SVG exposes no zone for that region. + */ +export function findSpineZoneId( + region: VertebralRegion, + bones: Map, +): string | undefined { + for (const [id, bone] of bones) { + if (bone.special !== 'vertebral-precision') continue + const r = regionFromLabel(bone.fr) ?? regionFromLabel(bone.en) + if (r === region) return id + } + return undefined +} + +const key = (v: Vertebra) => `${v.region}${v.index}` + +/** Set union of two vertebra lists, keyed by region+index, preserving order. */ +function unionVertebrae(base: Vertebra[], extra: Vertebra[]): Vertebra[] { + const seen = new Set(base.map(key)) + const out = [...base] + for (const v of extra) { + if (seen.has(key(v))) continue + seen.add(key(v)) + out.push(v) + } + return out +} + +/** + * Spreads vertebrae confirmed in the picker across one spine zone per region. + * + * The picker is anchored on the clicked zone (targetIndex) but lets the user + * switch region tabs. Vertebrae picked in another region must behave as if the + * matching spine zone was also selected: it gets created if missing so the SVG + * highlights it and its findings picker appears. + * + * The target region is replaced (the picker was seeded with its full set, so + * unchecking deselects). Other regions are merged additively so a side-tab pick + * never wipes a pre-existing zone the picker did not display. + * + * Returns a new zones array; the original is not mutated. + */ +export function distributeVertebraeToZones( + zones: ObservationZone[], + targetIndex: number, + vertebrae: Vertebra[], + bones: Map, +): ObservationZone[] { + const target = zones[targetIndex] + if (!target) return zones + + const targetBone = bones.get(target.boneId) + const targetRegion = + regionFromLabel(targetBone?.fr ?? '') ?? regionFromLabel(targetBone?.en ?? '') + + // Unknown target region: cannot split safely — keep all vertebrae on target. + if (!targetRegion) { + const next = [...zones] + next[targetIndex] = { ...target, vertebrae } + return next + } + + const byRegion = new Map() + for (const v of vertebrae) { + byRegion.set(v.region, [...(byRegion.get(v.region) ?? []), v]) + } + + const next = [...zones] + const unmapped: Vertebra[] = [] + + for (const [region, regionVerts] of byRegion) { + if (region === targetRegion) continue + const zoneId = findSpineZoneId(region, bones) + if (!zoneId) { + unmapped.push(...regionVerts) + continue + } + const idx = next.findIndex((z) => z.boneId === zoneId && !z.detailSourceId) + if (idx >= 0) { + next[idx] = { + ...next[idx], + vertebrae: unionVertebrae(next[idx].vertebrae ?? [], regionVerts), + } + } else { + next.push({ boneId: zoneId, vertebrae: regionVerts }) + } + } + + next[targetIndex] = { + ...target, + vertebrae: [...(byRegion.get(targetRegion) ?? []), ...unmapped], + } + return next +} diff --git a/tests/unit/lib.spineZones.test.ts b/tests/unit/lib.spineZones.test.ts new file mode 100644 index 00000000..d3a3b1e7 --- /dev/null +++ b/tests/unit/lib.spineZones.test.ts @@ -0,0 +1,87 @@ +import { describe, it, expect } from 'vitest' +import { + findSpineZoneId, + distributeVertebraeToZones, +} from '@/lib/spineZones' +import type { Bone } from '@/anatomy/types' +import type { ObservationZone, Vertebra } from '@/domain/schema/observation' + +function spine(id: string, fr: string, en: string): Bone { + return { id, fr, en, category: 'zone-colonne', special: 'vertebral-precision', els: [] } +} + +const BONES = new Map([ + ['z-c', spine('z-c', 'Vertèbres cervicales', 'Cervical Vertebrae')], + ['z-t', spine('z-t', 'Vertèbres thoraciques', 'Thoracic Vertebrae')], + ['z-l', spine('z-l', 'Vertèbres lombaires', 'Lumbar Vertebrae')], + ['z-s', spine('z-s', 'Vertèbres sacrales', 'Sacral Vertebrae')], + ['z-cd', spine('z-cd', 'Vertèbres caudales', 'Coccygeal Vertebrae')], + ['z-shoulder', { id: 'z-shoulder', fr: 'Épaule', en: 'Shoulder', category: 'zone', els: [] }], +]) + +const v = (region: Vertebra['region'], index: number): Vertebra => ({ region, index }) + +describe('findSpineZoneId', () => { + it('maps each region to its spine zone', () => { + expect(findSpineZoneId('C', BONES)).toBe('z-c') + expect(findSpineZoneId('T', BONES)).toBe('z-t') + expect(findSpineZoneId('L', BONES)).toBe('z-l') + expect(findSpineZoneId('S', BONES)).toBe('z-s') + expect(findSpineZoneId('Cd', BONES)).toBe('z-cd') + }) + + it('returns undefined when no spine zone exists for a region', () => { + const only = new Map([['z-l', BONES.get('z-l')!]]) + expect(findSpineZoneId('C', only)).toBeUndefined() + }) +}) + +describe('distributeVertebraeToZones', () => { + it('keeps same-region vertebrae on the target zone', () => { + const zones: ObservationZone[] = [{ boneId: 'z-l' }] + const next = distributeVertebraeToZones(zones, 0, [v('L', 1), v('L', 2)], BONES) + expect(next).toHaveLength(1) + expect(next[0].vertebrae).toEqual([v('L', 1), v('L', 2)]) + }) + + it('spawns a new zone for cross-region vertebrae', () => { + const zones: ObservationZone[] = [{ boneId: 'z-l' }] + const next = distributeVertebraeToZones(zones, 0, [v('L', 1), v('C', 3)], BONES) + expect(next).toHaveLength(2) + expect(next[0]).toEqual({ boneId: 'z-l', vertebrae: [v('L', 1)] }) + expect(next[1]).toEqual({ boneId: 'z-c', vertebrae: [v('C', 3)] }) + }) + + it('merges (does not wipe) a pre-existing other-region zone', () => { + const zones: ObservationZone[] = [ + { boneId: 'z-l', vertebrae: [v('L', 1)] }, + { boneId: 'z-c', vertebrae: [v('C', 2)] }, + ] + const next = distributeVertebraeToZones(zones, 0, [v('L', 1), v('C', 4)], BONES) + expect(next).toHaveLength(2) + expect(next[0].vertebrae).toEqual([v('L', 1)]) + expect(next[1].vertebrae).toEqual([v('C', 2), v('C', 4)]) + }) + + it('replaces the target region so deselection within it sticks', () => { + const zones: ObservationZone[] = [{ boneId: 'z-l', vertebrae: [v('L', 1), v('L', 2)] }] + const next = distributeVertebraeToZones(zones, 0, [v('L', 1)], BONES) + expect(next[0].vertebrae).toEqual([v('L', 1)]) + }) + + it('falls back to dumping all vertebrae on a non-spine target zone', () => { + const zones: ObservationZone[] = [{ boneId: 'z-shoulder' }] + const next = distributeVertebraeToZones(zones, 0, [v('L', 1), v('C', 2)], BONES) + expect(next).toHaveLength(1) + expect(next[0].vertebrae).toEqual([v('L', 1), v('C', 2)]) + }) + + it('routes vertebrae of an unmapped region back onto the target zone', () => { + const noCervical = new Map(BONES) + noCervical.delete('z-c') + const zones: ObservationZone[] = [{ boneId: 'z-l' }] + const next = distributeVertebraeToZones(zones, 0, [v('L', 1), v('C', 2)], noCervical) + expect(next).toHaveLength(1) + expect(next[0].vertebrae).toEqual([v('L', 1), v('C', 2)]) + }) +})