fix(store): hold session texts whose set-aside fails, never overwrite them

This commit is contained in:
bchanot committed 2026-10-14 23:11:59 +02:00
1 parent 1312b366b1
commit e34b7f282e
19 files changed
+1093 -86

No files matched your search

+46 -4
View File
@@ -15,10 +15,14 @@ import EditInfosDialog, {
} from '@/components/report/EditInfosDialog'
import DisclaimerDialog from '@/components/report/DisclaimerDialog'
import CoreUnavailable from '@/components/report/CoreUnavailable'
import HeldSessionPanel from '@/components/report/HeldSessionPanel'
import Notice from '@/components/ui/Notice'
import Button from '@/components/ui/Button'
import {
useReportStore,
type ActionResult,
type HeldText,
type RestoreOptions,
type RestoreResult,
} from '@/state/reportStore'
import { writeCachedPractitioner } from '@/state/practitionerCache'
@@ -77,6 +81,13 @@ export default function EditorRoute() {
)
// The core failed while reading the draft: stay here, keep the draft, offer a retry.
const [restoreFailed, setRestoreFailed] = useState(false)
// Texts that could not be set aside: the resolution panel replaces the editor.
const [held, setHeld] = useState<HeldText[] | null>(null)
// Each resolution step (retry, deletion, confirmed replacement) runs the restore again.
const [restoreAttempt, setRestoreAttempt] = useState(0)
const restoreOptions = useRef<RestoreOptions>({})
// The attempt that ended held: the effect runs again on every render, the restore must not.
const heldAttempt = useRef<number | null>(null)
const [disclaimer, setDisclaimer] = useState<string | null>(null)
const [exporting, setExporting] = useState(false)
const [editDraft, setEditDraft] = useState<Identity | null>(null)
@@ -91,17 +102,25 @@ export default function EditorRoute() {
// A draft rebased on another sheet is announced with its unresolved count,
// an unreadable one is set aside. While the core cannot run, nothing is
// read or written and the page stays on the degraded notice (no redirect).
// A text that could not be set aside stays in place behind the resolution panel.
useEffect(() => {
if (report) return
if (sheet.status === 'core_unavailable' || sheet.status === 'invalid_sheet')
return
if (sheet.status === 'ready') {
const result = store.restoreDraft(sheet.index)
// Nothing could be read or set aside: stay, keep the draft where it is.
if (result?.kind === 'core_unavailable' || result?.kind === 'unreadable_kept') {
if (heldAttempt.current === restoreAttempt) return
const result = store.restoreDraft(sheet.index, restoreOptions.current)
restoreOptions.current = {}
if (result?.kind === 'core_unavailable') {
setRestoreFailed(true)
return
}
if (result?.kind === 'held') {
heldAttempt.current = restoreAttempt
setHeld(result.held)
return
}
setHeld(null)
const alert = result ? restoreAlert(result, t) : null
if (alert && !rebaseAlerted.current) {
rebaseAlerted.current = true
@@ -110,7 +129,9 @@ export default function EditorRoute() {
}
if (sheet.status !== 'loading' && !useReportStore.getState().report)
navigate('/')
}, [report, sheet, store, navigate, t])
}, [report, sheet, store, navigate, t, restoreAttempt])
const retryRestore = useCallback(() => setRestoreAttempt((n) => n + 1), [])
useEffect(() => {
if (sheet.status !== 'ready' || typeof sessionStorage === 'undefined')
@@ -238,6 +259,22 @@ export default function EditorRoute() {
if (restoreFailed) {
return <CoreUnavailable onRetry={() => window.location.reload()} />
}
if (held && !report) {
return (
<HeldSessionPanel
held={held}
onDiscard={(text) => {
store.discardSessionText(text)
retryRestore()
}}
onOpenAdapted={() => {
restoreOptions.current = { replaceOriginal: true }
retryRestore()
}}
onRetry={retryRestore}
/>
)
}
if (!report) return null
if (sheet.status === 'loading') {
return (
@@ -262,6 +299,11 @@ export default function EditorRoute() {
})
}
/>
{store.saveFailed && (
<Notice tone="error" className="mx-4 sm:mx-6 mt-4">
{t('editor.save_failed')}
</Notice>
)}
<div className="flex-1 grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-4 sm:gap-6 p-4 sm:p-6">
<section className="border border-[var(--color-border)] rounded-2xl bg-[var(--color-surface)] overflow-hidden max-h-[55vh] lg:max-h-none flex flex-col">
<AnatomyCanvas
+10 -1
View File
@@ -129,7 +129,16 @@ export default function HomeRoute() {
const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
if (!index) throw new ImportError('core_unavailable')
const { read: outcome, rebase } = importAttachment(attachment, index)
hydrateImport({ report: rebase.report, archive: outcome.archive })
const opened = hydrateImport(
{ report: rebase.report, archive: outcome.archive },
index,
)
// A tab text that could not be set aside would be overwritten: resolve it first.
if (!opened.ok) {
window.alert(t('session.held_blocked'))
navigate('/editor')
return
}
const lines = importMessages(outcome, rebase, t)
if (lines.length > 0) window.alert(lines.join('\n\n'))
navigate('/editor')
+9 -4
View File
@@ -13,8 +13,7 @@ import {
writeCachedPractitioner,
} from '@/state/practitionerCache'
import { useReportStore } from '@/state/reportStore'
import { useSheetAvailability } from '@/sheets/useSheet'
import { coreRuntime } from '@/core/runtime'
import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet'
import { useT } from '@/i18n/useT'
/** The one species this build ships a sheet for. */
@@ -49,7 +48,9 @@ export default function NewReportRoute() {
async function submit() {
if (!canSubmit || sheet.status !== 'ready') return
writeCachedPractitioner(practitioner)
if (!(await coreRuntime().ready())) {
// The loaded sheet lets the store read a draft this page never opened before replacing it.
const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
if (!index) {
window.alert(t('sheet.core_unavailable'))
return
}
@@ -64,9 +65,13 @@ export default function NewReportRoute() {
recommendations: '',
},
sheet.sheet.ref,
index,
)
if (created.ok) navigate('/editor')
else window.alert(t('core.action_failed'))
else if (created.reason === 'held') {
window.alert(t('session.held_blocked'))
navigate('/editor')
} else window.alert(t('core.action_failed'))
}
return (
@@ -0,0 +1,145 @@
import { useState } from 'react'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import Notice from '@/components/ui/Notice'
import { todayIso } from '@/lib/dates'
import { readSessionText, type SessionText } from '@/state/persistence'
import type { HeldText } from '@/state/reportStore'
import { useT } from '@/i18n/useT'
export interface HeldSessionPanelProps {
held: readonly HeldText[]
/** Removes the text from the tab; called only after the practitioner confirmed. */
onDiscard: (text: SessionText) => void
/** Opens the rebased draft, replacing its original; called only after confirmation. */
onOpenAdapted: () => void
onRetry: () => void
}
type Pending = { action: 'discard'; text: SessionText } | { action: 'open' }
const FILE_STEM: Record<SessionText, string> = {
draft: 'faunosteo-brouillon',
archive: 'faunosteo-archive',
}
/** Saves the stored text verbatim (it is JSON.stringify output: ASCII escapes, lossless). */
function downloadCopy(text: SessionText): void {
const raw = readSessionText(text)
if (raw === null) return
const url = URL.createObjectURL(new Blob([raw], { type: 'application/json' }))
const a = document.createElement('a')
a.href = url
a.download = `${FILE_STEM[text]}-${todayIso()}.json`
a.click()
URL.revokeObjectURL(url)
}
function rowLabelKey(item: HeldText): string {
return `session.held.${item.text}_${item.reason}`
}
/**
* Resolution of the session texts the store holds in place because their safety copy
* failed (STEP R2 maintenance B): one row per text, a copy to download, an explicit
* deletion or replacement behind a confirmation, a retry. Nothing happens on its own.
*/
export default function HeldSessionPanel({
held,
onDiscard,
onOpenAdapted,
onRetry,
}: HeldSessionPanelProps) {
const t = useT()
const [pending, setPending] = useState<Pending | null>(null)
function confirm() {
if (!pending) return
if (pending.action === 'discard') onDiscard(pending.text)
else onOpenAdapted()
setPending(null)
}
return (
<main className="p-4 sm:p-6 space-y-4 max-w-2xl">
<Notice tone="error">{t('session.held.notice')}</Notice>
<ul className="space-y-3">
{held.map((item) => (
<li
key={item.text}
className="rounded-lg border border-[var(--color-border)] p-3 space-y-2"
data-testid={`held-${item.text}`}
>
<p className="text-sm">
{t(rowLabelKey(item)).replace(
'{size}',
t('session.held.size_kb').replace(
'{n}',
String(Math.max(1, Math.ceil(item.bytes / 1024))),
),
)}
</p>
<div className="flex flex-wrap gap-2">
<Button variant="secondary" onClick={() => downloadCopy(item.text)}>
{t(
item.reason === 'pre_rebase'
? 'session.held.download_original'
: 'session.held.download',
)}
</Button>
{item.reason === 'pre_rebase' ? (
<Button variant="ghost" onClick={() => setPending({ action: 'open' })}>
{t('session.held.open_adapted')}
</Button>
) : (
<Button
variant="ghost"
onClick={() => setPending({ action: 'discard', text: item.text })}
>
{t('session.held.discard')}
</Button>
)}
</div>
</li>
))}
</ul>
<div className="flex justify-end">
<Button onClick={onRetry}>{t('session.held.retry')}</Button>
</div>
<Dialog
open={pending !== null}
onClose={() => setPending(null)}
title={t(
pending?.action === 'open'
? 'session.held.open_title'
: `session.held.discard_title_${pending?.action === 'discard' ? pending.text : 'draft'}`,
)}
size="sm"
>
<p className="text-sm text-[var(--color-ink-muted)]">
{t(
pending?.action === 'open'
? 'session.held.open_body'
: 'session.held.discard_body',
)}
</p>
<div className="mt-4 flex justify-end gap-2">
<Button type="button" variant="ghost" onClick={() => setPending(null)}>
{t('common.cancel')}
</Button>
<Button
type="button"
variant={pending?.action === 'open' ? 'primary' : 'danger'}
onClick={confirm}
>
{t(
pending?.action === 'open'
? 'session.held.open_confirm'
: 'session.held.discard_confirm',
)}
</Button>
</div>
</Dialog>
</main>
)
}
+40
View File
@@ -82,6 +82,46 @@ export const en: Dict = {
'Draft restored on an anatomical sheet different from the one it was created on. Items not found: {count} (kept with their labels).',
'editor.draft_quarantined':
"This tab's draft could not be read by this version of Faunosteo. It was set aside, not deleted.",
'editor.save_failed':
"This tab's storage is full: your latest changes are no longer saved in the tab. Export the PDF to keep them.",
'session.held.notice':
"Some data in this tab could not be set aside in the browser's storage (not enough space, or the slot is taken). It is kept as it is; nothing was deleted. Until it is resolved, no report can be created or imported in this tab.",
'session.held.draft_unreadable':
"Draft this version cannot read ({size})",
'session.held.draft_pre_rebase':
"Draft to adapt to the current anatomical sheet; its original could not be set aside ({size})",
'session.held.archive_unreadable':
"Archive of the imported report, unreadable ({size})",
'session.held.archive_companion':
"Archive of the imported report that goes with this draft ({size})",
'session.held.size_kb':
"{n} KB",
'session.held.download':
"Download a copy",
'session.held.download_original':
"Download the original",
'session.held.discard':
"Delete permanently…",
'session.held.open_adapted':
"Open the adapted version…",
'session.held.retry':
"Retry",
'session.held.discard_title_draft':
"Delete this draft permanently?",
'session.held.discard_title_archive':
"Delete this archive permanently?",
'session.held.discard_body':
"This text will be erased from this tab and cannot be recovered. Download a copy first to keep it.",
'session.held.discard_confirm':
"Delete",
'session.held.open_title':
"Open the adapted version?",
'session.held.open_body':
"The original will be replaced in this tab by the version adapted to the current anatomical sheet (items not found are kept with their labels). Download the original first to keep it.",
'session.held.open_confirm':
"Open",
'session.held_blocked':
"A draft in this tab must be recovered or deleted first: it could not be set aside and would be overwritten. The editor will open to resolve it.",
'editor.edit_infos': 'Edit info',
'editor.edit_dialog_title': 'Edit information',
'editor.disclaimer_title': 'Legal scope of animal osteopathy',
+40
View File
@@ -88,6 +88,46 @@ export const fr: Dict = {
'Brouillon restauré sur une fiche anatomique différente de celle où il a été créé. Éléments non retrouvés : {count} (conservés avec leurs libellés).',
'editor.draft_quarantined':
"Le brouillon de cet onglet n'a pas pu être relu par cette version de Faunosteo. Il a été mis de côté, pas supprimé.",
'editor.save_failed':
"L'espace de stockage de cet onglet est plein : vos dernières modifications ne sont plus enregistrées dans l'onglet. Exportez le PDF pour les conserver.",
'session.held.notice':
"Des données de cet onglet n'ont pas pu être mises de côté dans le stockage du navigateur (espace insuffisant ou emplacement occupé). Elles sont conservées telles quelles ; rien n'a été supprimé. Tant qu'elles ne sont pas résolues, aucun bilan ne peut être créé ou importé dans cet onglet.",
'session.held.draft_unreadable':
"Brouillon illisible par cette version ({size})",
'session.held.draft_pre_rebase':
"Brouillon à adapter à la fiche anatomique actuelle ; son original n'a pas pu être mis de côté ({size})",
'session.held.archive_unreadable':
"Archive du bilan importé, illisible ({size})",
'session.held.archive_companion':
"Archive du bilan importé qui accompagne ce brouillon ({size})",
'session.held.size_kb':
"{n} Ko",
'session.held.download':
"Télécharger une copie",
'session.held.download_original':
"Télécharger l'original",
'session.held.discard':
"Supprimer définitivement…",
'session.held.open_adapted':
"Ouvrir la version adaptée…",
'session.held.retry':
"Réessayer",
'session.held.discard_title_draft':
"Supprimer définitivement ce brouillon ?",
'session.held.discard_title_archive':
"Supprimer définitivement cette archive ?",
'session.held.discard_body':
"Ce texte sera effacé de cet onglet et ne pourra pas être récupéré. Téléchargez d'abord une copie pour le garder.",
'session.held.discard_confirm':
"Supprimer",
'session.held.open_title':
"Ouvrir la version adaptée ?",
'session.held.open_body':
"L'original sera remplacé dans cet onglet par la version adaptée à la fiche anatomique actuelle (les éléments non retrouvés sont conservés avec leurs libellés). Téléchargez d'abord l'original pour le garder.",
'session.held.open_confirm':
"Ouvrir",
'session.held_blocked':
"Un brouillon de cet onglet doit d'abord être récupéré ou supprimé : il n'a pas pu être mis de côté et serait écrasé. L'éditeur va s'ouvrir pour le résoudre.",
'editor.edit_infos': 'Modifier les infos',
'editor.edit_dialog_title': 'Modifier les informations',
'editor.disclaimer_title': "Périmètre légal de l'ostéopathie animale",
+68 -20
View File
@@ -14,12 +14,13 @@ import type { Report, ReportArchiveEnvelope } from '@faunosteo/core-wasm/types'
export interface ReportPersistence {
/** The raw draft text, null when there is none. */
loadText(): string | null
save(report: Report | null): void
/** Writes (or removes, for null) the draft; false when the storage refused the write. */
save(report: Report | null): boolean
}
export interface ArchivePersistence {
loadText(): string | null
save(archive: ReportArchiveEnvelope | null): void
save(archive: ReportArchiveEnvelope | null): boolean
}
export const DRAFT_KEY = 'osteo:draft'
@@ -38,25 +39,49 @@ function storage(): Storage | null {
return typeof sessionStorage === 'undefined' ? null : sessionStorage
}
function writeOrRemove(key: string, value: unknown): void {
/** A refused write (quota) leaves the previous value in place, as the Storage API does. */
function writeOrRemove(key: string, value: unknown): boolean {
const store = storage()
if (!store) return
if (!store) return false
if (value === null) {
store.removeItem(key)
return
return true
}
try {
store.setItem(key, JSON.stringify(value))
return true
} catch (err) {
// Quota exceeded: the session goes on, only the mirror is lost.
if (import.meta.env.DEV) console.warn(`${key} not saved`, err)
return false
}
}
/**
* Writes `raw` into an empty quarantine slot; a slot already holding another text is
* never replaced (that earlier text would be lost). Answers whether `raw` is now in
* the slot and whether this call wrote it (so a failed pair can undo its own copy).
*/
function copyToSlot(
store: Storage,
slot: QuarantineSlot,
raw: string,
): 'written' | 'present' | 'refused' {
const current = store.getItem(QUARANTINE_KEYS[slot])
if (current === raw) return 'present'
if (current !== null) return 'refused'
try {
store.setItem(QUARANTINE_KEYS[slot], raw)
return 'written'
} catch (err) {
if (import.meta.env.DEV) console.warn(`${slot} not set aside`, err)
return 'refused'
}
}
/**
* Copies `raw` into its quarantine slot, then removes `source` (when given)
* only if that copy succeeded: a full storage keeps the text where it was.
* Returns whether the text is now in quarantine.
* only if that copy succeeded: a full storage or an occupied slot keeps the
* text where it was. Returns whether the text is now in quarantine.
*/
export function quarantine(
slot: QuarantineSlot,
@@ -65,26 +90,49 @@ export function quarantine(
): boolean {
const store = storage()
if (!store) return false
try {
store.setItem(QUARANTINE_KEYS[slot], raw)
} catch (err) {
if (import.meta.env.DEV) console.warn(`${slot} not set aside`, err)
return false
}
if (copyToSlot(store, slot, raw) === 'refused') return false
if (source) store.removeItem(source)
return true
}
/**
* Sets an unreadable draft aside together with the archive kept beside it, so a
* later session never removes that archive on its own. Both copies or neither:
* when one fails, the copy this call wrote is undone and both texts stay in place.
*/
export function quarantineSession(draft: string, archive: string | null): boolean {
const store = storage()
if (!store) return false
const draftCopy = copyToSlot(store, 'draft', draft)
if (draftCopy === 'refused') return false
if (archive !== null && copyToSlot(store, 'archive', archive) === 'refused') {
if (draftCopy === 'written') store.removeItem(QUARANTINE_KEYS.draft)
return false
}
store.removeItem(DRAFT_KEY)
if (archive !== null) store.removeItem(ARCHIVE_KEY)
return true
}
/** The session texts a resolution may download or remove, by their kind. */
export const SESSION_KEYS = { draft: DRAFT_KEY, archive: ARCHIVE_KEY } as const
export type SessionText = keyof typeof SESSION_KEYS
export function readSessionText(text: SessionText): string | null {
return storage()?.getItem(SESSION_KEYS[text]) ?? null
}
/** Removes a session text: only ever called on the practitioner's confirmed request. */
export function removeSessionText(text: SessionText): void {
storage()?.removeItem(SESSION_KEYS[text])
}
export const sessionStoragePersistence: ReportPersistence = {
loadText: () => storage()?.getItem(DRAFT_KEY) ?? null,
save(report) {
writeOrRemove(DRAFT_KEY, report)
},
save: (report) => writeOrRemove(DRAFT_KEY, report),
}
export const sessionStorageArchivePersistence: ArchivePersistence = {
loadText: () => storage()?.getItem(ARCHIVE_KEY) ?? null,
save(archive) {
writeOrRemove(ARCHIVE_KEY, archive)
},
save: (archive) => writeOrRemove(ARCHIVE_KEY, archive),
}
+144 -26
View File
@@ -18,12 +18,14 @@ import { nowIso } from '@/lib/dates'
import type { SheetIndex } from '@/services/sheetIndex'
import {
ARCHIVE_KEY,
DRAFT_KEY,
quarantine,
quarantineSession,
removeSessionText,
sessionStorageArchivePersistence,
sessionStoragePersistence,
type ArchivePersistence,
type ReportPersistence,
type SessionText,
} from './persistence'
/**
@@ -37,6 +39,9 @@ import {
* The per-tab draft is mirrored through the persistence adapter and restored
* once the sheet is known; the archive an import brought along is kept
* beside the report and written only when the session starts or ends.
* A session text this page has not read, or whose safety copy failed, is
* never removed or overwritten implicitly: restore holds it, and a new
* session (new report, import) is refused until the practitioner resolves it.
*/
export type { NewReportDraft }
@@ -48,6 +53,26 @@ export interface ImportedSession {
export interface ActionResult {
ok: boolean
/** Refused because a session text is held (it could not be set aside and would be lost). */
reason?: 'held'
}
/**
* A session text kept in place because its safety copy failed (storage full, or the
* quarantine slot already holds an earlier text): `unreadable` by this build, the
* archive `companion` of an unreadable draft, or a draft whose `pre_rebase` original
* could not be kept before the rebase replaces it.
*/
export interface HeldText {
text: SessionText
reason: 'unreadable' | 'companion' | 'pre_rebase'
/** UTF-8 size of the stored text, for the resolution panel. */
bytes: number
}
export interface RestoreOptions {
/** The practitioner confirmed that the rebased draft may replace its original. */
replaceOriginal?: boolean
}
/** What a draft restore did; `null` from the action when there was nothing to restore. */
@@ -56,10 +81,10 @@ export type RestoreResult =
/** The draft is unreadable by this build: set aside, verbatim, under a quarantine key. */
| { kind: 'quarantined' }
/**
* The draft is unreadable but could not be set aside (storage full): it stays in
* `osteo:draft`, and the caller must not start anything that would overwrite it.
* Texts that could not be set aside stay where they are, nothing is opened, and the
* store refuses any new session until they are resolved.
*/
| { kind: 'unreadable_kept' }
| { kind: 'held'; held: HeldText[] }
/** The core failed: nothing read, nothing written, the draft is where it was. */
| { kind: 'core_unavailable' }
@@ -68,15 +93,27 @@ export interface ReportStore {
/** The envelope of the imported archive, as exported; null otherwise. */
archive: ReportArchiveEnvelope | null
activeObservationIndex: number
initReport: (draft: NewReportDraft, sheet: SheetRef) => ActionResult
/** Opens an imported report (read and rebased by the core) with its archive. */
hydrateImport: (session: ImportedSession) => void
/** The last draft mirror write was refused (storage full): the tab's copy is stale. */
saveFailed: boolean
/** Starts a report; refused (`held`) while an unread session text cannot be set aside. */
initReport: (
draft: NewReportDraft,
sheet: SheetRef,
index: SheetIndex,
) => ActionResult
/** Opens an imported report (read and rebased by the core) with its archive; same guard. */
hydrateImport: (session: ImportedSession, index: SheetIndex) => ActionResult
/**
* Restores the per-tab draft on the loaded sheet, rebasing it when it was
* written on another revision; a no-op (null) when a report is already open
* or there is no draft.
* or there is nothing to restore.
*/
restoreDraft: (index: SheetIndex) => RestoreResult | null
restoreDraft: (
index: SheetIndex,
options?: RestoreOptions,
) => RestoreResult | null
/** Removes a held session text, on the practitioner's confirmed request; no-op once a report is open. */
discardSessionText: (text: SessionText) => void
addObservation: () => ActionResult
removeObservation: (index: number) => ActionResult
moveObservationUp: (index: number) => ActionResult
@@ -93,13 +130,14 @@ export interface ReportStore {
}
type Patch = Partial<
Pick<ReportStore, 'report' | 'archive' | 'activeObservationIndex'>
Pick<ReportStore, 'report' | 'archive' | 'activeObservationIndex' | 'saveFailed'>
>
type Setter = (fn: (s: ReportStore) => Patch | ReportStore) => void
type Getter = () => ReportStore
const OK: ActionResult = { ok: true }
const FAILED: ActionResult = { ok: false }
const HELD: ActionResult = { ok: false, reason: 'held' }
function onReport(set: Setter, update: (r: Report, s: ReportStore) => Patch) {
set((s) => (s.report ? update(s.report, s) : s))
@@ -134,37 +172,94 @@ const UNREADABLE_DRAFT_KINDS: ReadonlySet<string> = new Set([
'lone_surrogate',
])
/** Reads the draft through the core; unreadable content goes to quarantine, never away. */
function utf8Bytes(text: string): number {
return new TextEncoder().encode(text).length
}
function held(text: SessionText, reason: HeldText['reason'], raw: string): HeldText {
return { text, reason, bytes: utf8Bytes(raw) }
}
type Restored = { result: RestoreResult; patch?: Patch } | null
/** An archive with no draft beside it can never be restored: set it aside, or hold it. */
function restoreOrphanArchive(archiveText: string | null): Restored {
if (archiveText === null || quarantine('archive', archiveText, ARCHIVE_KEY)) return null
return { result: { kind: 'held', held: [held('archive', 'companion', archiveText)] } }
}
/** An unreadable draft goes to quarantine with its archive, never away; else both are held. */
function setAsideUnreadable(draft: string, archiveText: string | null): Restored {
if (quarantineSession(draft, archiveText)) return { result: { kind: 'quarantined' } }
const kept = [held('draft', 'unreadable', draft)]
if (archiveText !== null) kept.push(held('archive', 'companion', archiveText))
return { result: { kind: 'held', held: kept } }
}
/**
* Reads the draft through the core. Unreadable content goes to quarantine, never away;
* a text whose safety copy fails is held in place and nothing is opened (opening would
* let the mirror overwrite the draft, or a later session remove the archive).
*/
function restore(
index: SheetIndex,
persistence: ReportPersistence,
archives: ArchivePersistence,
): { result: RestoreResult; patch?: Patch } | null {
options: RestoreOptions,
): Restored {
const draft = persistence.loadText()
if (draft === null) return null
const archiveText = archives.loadText()
if (draft === null) return restoreOrphanArchive(archiveText)
const outcome = index.ops.restoreDraft(draft, archiveText)
if (!outcome.ok) {
// Only an unreadable draft is set aside; a core or sheet failure leaves it in place.
if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) {
return { result: { kind: 'core_unavailable' } }
}
const setAside = quarantine('draft', draft, DRAFT_KEY)
return { result: { kind: setAside ? 'quarantined' : 'unreadable_kept' } }
return setAsideUnreadable(draft, archiveText)
}
const { rebase, archive, archiveRejected } = outcome.value
const kept: HeldText[] = []
if (archiveRejected && archiveText !== null) {
quarantine('archive', archiveText, ARCHIVE_KEY)
if (!quarantine('archive', archiveText, ARCHIVE_KEY)) {
kept.push(held('archive', 'unreadable', archiveText))
}
}
if (rebase.rebased && rebase.unresolvedZones + rebase.unresolvedFindings > 0) {
quarantine('draftPreRebase', draft)
const flagged = rebase.unresolvedZones + rebase.unresolvedFindings > 0
if (rebase.rebased && flagged && !options.replaceOriginal) {
if (!quarantine('draftPreRebase', draft)) {
kept.push(held('draft', 'pre_rebase', draft))
}
}
if (kept.length > 0) return { result: { kind: 'held', held: kept } }
return {
result: { kind: 'restored', rebase },
patch: { report: rebase.report, archive, activeObservationIndex: 0 },
}
}
/**
* Before a new session replaces texts this page never read: an unreadable draft (and its
* archive) or an unreadable archive is set aside first; a readable draft is replaced as
* before. False when something could not be set aside, or could not even be read.
*/
function releaseUnreadSession(
index: SheetIndex,
persistence: ReportPersistence,
archives: ArchivePersistence,
): boolean {
const draft = persistence.loadText()
const archiveText = archives.loadText()
if (draft === null) return restoreOrphanArchive(archiveText) === null
const outcome = index.ops.restoreDraft(draft, archiveText)
if (!outcome.ok) {
if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) return false
return quarantineSession(draft, archiveText)
}
if (!outcome.value.archiveRejected || archiveText === null) return true
return quarantine('archive', archiveText, ARCHIVE_KEY)
}
export function createReportStore(
persistence: ReportPersistence,
archives: ArchivePersistence,
@@ -175,12 +270,19 @@ export function createReportStore(
return { ...patch, archive }
}
/** A new session may start: either one is open (its texts are this store's), or none is left unread. */
const mayStartSession = (index: SheetIndex) =>
store.getState().report !== null ||
releaseUnreadSession(index, persistence, archives)
const store = create<ReportStore>((set, get) => ({
report: null,
archive: null,
activeObservationIndex: 0,
saveFailed: false,
initReport: (draft, sheet) => {
initReport: (draft, sheet, index) => {
if (!mayStartSession(index)) return HELD
const outcome = reportOps.newReport({
draft,
sheet,
@@ -193,17 +295,25 @@ export function createReportStore(
return OK
},
hydrateImport: ({ report, archive }) =>
set(withArchive({ report, activeObservationIndex: 0 }, archive)),
hydrateImport: ({ report, archive }, index) => {
if (!mayStartSession(index)) return HELD
set(withArchive({ report, activeObservationIndex: 0 }, archive))
return OK
},
restoreDraft: (index) => {
restoreDraft: (index, options = {}) => {
if (get().report) return null
const restored = restore(index, persistence, archives)
const restored = restore(index, persistence, archives, options)
if (!restored) return null
if (restored.patch) set(restored.patch)
return restored.result
},
discardSessionText: (text) => {
if (get().report) return
removeSessionText(text)
},
addObservation: () =>
applyCore(
set,
@@ -265,10 +375,18 @@ export function createReportStore(
delete rest.nextAppointment
return { report: next ? { ...rest, nextAppointment: next } : rest }
}),
reset: () =>
set(withArchive({ report: null, activeObservationIndex: 0 }, null)),
// Ends the open session only: with none open, the tab's texts are not this store's.
reset: () => {
if (!get().report) return
set(withArchive({ report: null, activeObservationIndex: 0 }, null))
},
}))
store.subscribe((state) => persistence.save(state.report))
// The mirror follows the report only: an unrelated change never writes or removes the draft.
store.subscribe((state, prev) => {
if (state.report === prev.report) return
const failed = !persistence.save(state.report)
if (failed !== state.saveFailed) store.setState({ saveFailed: failed })
})
return store
}