Files
faunosteo/src/state/reportStore.ts
T
Bastien ChanotandClaude Opus 4.7 e8c29c1fdf fix(editor,pdf): accordion observation cards + seed 1 obs + native SVG rasterization
Three issues from manual QA:

1. UX restructure — observations are now an accordion list. Each card has
   a header that's always visible (title + chips + chevron + action
   buttons) and a body that expands inline showing zones / pathologies /
   severity / comment. Click the header (or the chevron) to toggle.
   ObservationEditor has been merged into ObservationCard so each card
   owns its own details. Only one observation is expanded at a time; the
   chevron on the active card collapses everything. EditorRoute uses
   activeObservationIndex === -1 to represent "all collapsed".

2. App used to start with 2 observations instead of 1. Root cause:
   EditorRoute had a "seed first observation" useEffect that fired twice
   under React 19 StrictMode in dev, both invocations seeing length=0 and
   queueing addObservation(). Fixed by moving the seed into the store's
   initReport (synchronous, one-shot) and removing the useEffect entirely.
   Store tests updated to assert the seed behaviour (90/90 pass).

3. PDF export still failed with "The input is not a PNG file!" — canvg
   was returning bytes that pdf-lib rejected at embedPng(). Switched
   rasterizeSvg to the browser-native pipeline: serialize the SVG into a
   Blob URL, load it with an Image element, drawImage onto a 2D canvas,
   then toBlob → PNG bytes (with a toDataURL fallback). Validates the
   PNG signature before returning. Tree-shaking dropped canvg from the
   bundle (979 kB → 874 kB JS).

Tests updated for the new initReport behaviour and the new svgToPng
pipeline (Image mock + dataURL fallback case). lint + typecheck + build
all clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 23:32:01 +02:00

151 lines
4.2 KiB
TypeScript

import { create } from 'zustand'
import { ReportSchema, type Report } from '@/domain/schema/report'
import type { Observation } from '@/domain/schema/observation'
import { generateId } from '@/lib/id'
import { nowIso } from '@/lib/dates'
export interface ReportStore {
report: Report | null
activeObservationIndex: number
initReport: (draft: Omit<Report, 'id' | 'createdAt' | 'version'>) => void
hydrateReport: (report: Report) => void
addObservation: () => void
removeObservation: (index: number) => void
moveObservationUp: (index: number) => void
moveObservationDown: (index: number) => void
updateObservation: (index: number, obs: Observation) => void
setActiveObservation: (index: number) => void
setConclusion: (text: string) => void
setRecommendations: (text: string) => void
setNextAppointment: (next: Report['nextAppointment']) => void
reset: () => void
}
function emptyObservation(): Observation {
return {
id: generateId(),
zones: [],
pathologyIds: [],
freeTextPathologies: [],
comment: '',
}
}
export const useReportStore = create<ReportStore>((set) => ({
report: null,
activeObservationIndex: 0,
initReport: (draft) =>
set({
report: {
...draft,
version: 1,
id: generateId(),
createdAt: nowIso(),
observations:
draft.observations.length === 0
? [emptyObservation()]
: draft.observations,
},
activeObservationIndex: 0,
}),
hydrateReport: (report) => set({ report, activeObservationIndex: 0 }),
addObservation: () =>
set((s) => {
if (!s.report) return s
const obs = emptyObservation()
const observations = [...s.report.observations, obs]
return {
report: { ...s.report, observations },
activeObservationIndex: observations.length - 1,
}
}),
removeObservation: (index) =>
set((s) => {
if (!s.report) return s
const observations = s.report.observations.filter((_, i) => i !== index)
const active = Math.min(
s.activeObservationIndex,
Math.max(0, observations.length - 1),
)
return {
report: { ...s.report, observations },
activeObservationIndex: active,
}
}),
moveObservationUp: (index) =>
set((s) => {
if (!s.report || index <= 0) return s
const observations = [...s.report.observations]
;[observations[index - 1], observations[index]] = [
observations[index],
observations[index - 1],
]
return { report: { ...s.report, observations } }
}),
moveObservationDown: (index) =>
set((s) => {
if (!s.report || index >= s.report.observations.length - 1) return s
const observations = [...s.report.observations]
;[observations[index], observations[index + 1]] = [
observations[index + 1],
observations[index],
]
return { report: { ...s.report, observations } }
}),
updateObservation: (index, obs) =>
set((s) => {
if (!s.report) return s
const observations = s.report.observations.map((o, i) =>
i === index ? obs : o,
)
return { report: { ...s.report, observations } }
}),
setActiveObservation: (index) => set({ activeObservationIndex: index }),
setConclusion: (text) =>
set((s) => (s.report ? { report: { ...s.report, conclusion: text } } : s)),
setRecommendations: (text) =>
set((s) =>
s.report ? { report: { ...s.report, recommendations: text } } : s,
),
setNextAppointment: (next) =>
set((s) =>
s.report ? { report: { ...s.report, nextAppointment: next } } : s,
),
reset: () => set({ report: null, activeObservationIndex: 0 }),
}))
const DRAFT_KEY = 'osteo:draft'
useReportStore.subscribe((state) => {
if (typeof sessionStorage === 'undefined') return
if (state.report) {
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(state.report))
} else {
sessionStorage.removeItem(DRAFT_KEY)
}
})
export function readPersistedDraft(): Report | null {
if (typeof sessionStorage === 'undefined') return null
const raw = sessionStorage.getItem(DRAFT_KEY)
if (!raw) return null
try {
const parsed = ReportSchema.safeParse(JSON.parse(raw))
return parsed.success ? parsed.data : null
} catch {
return null
}
}