diff --git a/src/state/reportStore.ts b/src/state/reportStore.ts index 7e8f8868..17ac081b 100644 --- a/src/state/reportStore.ts +++ b/src/state/reportStore.ts @@ -116,3 +116,25 @@ export const useReportStore = create((set) => ({ 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 { + return JSON.parse(raw) as Report + } catch { + return null + } +} diff --git a/tests/unit/state.draftMirror.test.ts b/tests/unit/state.draftMirror.test.ts new file mode 100644 index 00000000..688cbe98 --- /dev/null +++ b/tests/unit/state.draftMirror.test.ts @@ -0,0 +1,35 @@ +import { describe, it, expect, beforeEach } from 'vitest' +import { useReportStore } from '@/state/reportStore' + +const STORAGE_KEY = 'osteo:draft' + +const draft = { + date: '2026-05-18', + practitioner: { name: 'Dr. Dupont' }, + animal: { speciesId: 'equine', name: 'Mistral' }, + owner: { name: 'Jean Martin' }, + observations: [], + conclusion: '', + recommendations: '', +} + +beforeEach(() => { + useReportStore.getState().reset() + sessionStorage.clear() +}) + +describe('reportStore sessionStorage mirror', () => { + it('mirrors the report on every change', () => { + useReportStore.getState().initReport(draft) + const raw = sessionStorage.getItem(STORAGE_KEY) + expect(raw).not.toBeNull() + const parsed = JSON.parse(raw!) + expect(parsed.practitioner.name).toBe('Dr. Dupont') + }) + + it('clears the mirror on reset', () => { + useReportStore.getState().initReport(draft) + useReportStore.getState().reset() + expect(sessionStorage.getItem(STORAGE_KEY)).toBeNull() + }) +})