Files
faunosteo/src/state/reportStore.ts
T
Bastien Chanot f58a49f7fc feat(store): restore sessionStorage draft on store init
B-3: the osteo:draft mirror was write-only — a page refresh at
/editor bounced to home and lost the session despite the advertised
auto-save. Store now initializes report from readPersistedDraft()
(per-tab sessionStorage: refresh keeps the session, closing the tab
drops it; reset still clears). TDD: 4 new tests incl. refresh
simulation via module re-import — 178/178 green.
2026-07-12 16:25:21 +02:00

167 lines
4.9 KiB
TypeScript

import { create } from 'zustand'
import { ReportSchema, type Report } from '@/domain/schema/report'
import type { Observation } from '@/domain/schema/observation'
import type { Practitioner } from '@/domain/schema/practitioner'
import type { Animal, Owner } from '@/domain/schema/animal'
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
setPractitioner: (next: Practitioner) => void
setAnimal: (next: Animal) => void
setOwner: (next: Owner) => void
setConclusion: (text: string) => void
setRecommendations: (text: string) => void
setNextAppointment: (next: Report['nextAppointment']) => void
reset: () => void
}
function emptyObservation(): Observation {
return {
id: generateId(),
zones: [],
findings: [],
freeTextFindings: [],
comment: '',
}
}
const DRAFT_KEY = 'osteo:draft'
/** Reads the auto-saved draft back from sessionStorage (null if absent/invalid). */
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
}
}
export const useReportStore = create<ReportStore>((set) => ({
// Restore the per-tab draft so a page refresh never loses the session.
report: readPersistedDraft(),
activeObservationIndex: 0,
initReport: (draft) =>
set({
report: {
...draft,
version: 2,
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 }),
setPractitioner: (next) =>
set((s) => (s.report ? { report: { ...s.report, practitioner: next } } : s)),
setAnimal: (next) =>
set((s) => (s.report ? { report: { ...s.report, animal: next } } : s)),
setOwner: (next) =>
set((s) => (s.report ? { report: { ...s.report, owner: next } } : s)),
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 }),
}))
useReportStore.subscribe((state) => {
if (typeof sessionStorage === 'undefined') return
if (state.report) {
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(state.report))
} else {
sessionStorage.removeItem(DRAFT_KEY)
}
})