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.
This commit is contained in:
1 parent
b047d352c1
commit
f58a49f7fc
2 files changed
+75
-15
No files matched your search
+17
-15
@@ -36,8 +36,24 @@ function emptyObservation(): Observation {
|
||||
}
|
||||
}
|
||||
|
||||
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) => ({
|
||||
report: null,
|
||||
// Restore the per-tab draft so a page refresh never loses the session.
|
||||
report: readPersistedDraft(),
|
||||
activeObservationIndex: 0,
|
||||
|
||||
initReport: (draft) =>
|
||||
@@ -140,8 +156,6 @@ export const useReportStore = create<ReportStore>((set) => ({
|
||||
reset: () => set({ report: null, activeObservationIndex: 0 }),
|
||||
}))
|
||||
|
||||
const DRAFT_KEY = 'osteo:draft'
|
||||
|
||||
useReportStore.subscribe((state) => {
|
||||
if (typeof sessionStorage === 'undefined') return
|
||||
if (state.report) {
|
||||
@@ -150,15 +164,3 @@ useReportStore.subscribe((state) => {
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user