fix(app): rescue copy importable, trapping draft held, replace confirmed
The JSON rescue copy could not be restored in the app, a draft that traps the engine left the tab on a reload screen and spent a recovery on every read, and an unsaved or in-progress report could be lost by a reload outside the editor or by New report / Import without warning. Home import reads the copy (content-sniffed, 16 MiB cap, strict UTF-8) through the core's draft.restore before any session change; a trapping (draft, archive) pair is held in the resolution panel and only re-read on Retry; ReplaceSessionDialog guards New report and Import; the beforeunload guard is app-wide while unsaved. Supersedes BDR-055's "never held" for `internal` only.
This commit is contained in:
1 parent
9464651140
commit
9bd9acaf58
22 files changed
+1090
-68
No files matched your search
@@ -16,6 +16,7 @@ import ResetPasswordRoute from './routes/auth/ResetPasswordRoute'
|
||||
import AuthCallbackRoute from './routes/auth/AuthCallbackRoute'
|
||||
import DashboardRoute from './routes/app/DashboardRoute'
|
||||
import AccountRoute from './routes/app/AccountRoute'
|
||||
import { useUnsavedGuard } from './useUnsavedGuard'
|
||||
|
||||
/** The local tool: unchanged routes, no account needed, shared footer. */
|
||||
function LocalToolShell() {
|
||||
@@ -58,6 +59,8 @@ export function AppRoutes() {
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
// The store is not a context: one call above the route tree guards every page.
|
||||
useUnsavedGuard()
|
||||
return (
|
||||
<ConfigProvider>
|
||||
<AuthProvider>
|
||||
|
||||
@@ -20,7 +20,6 @@ import HeldSessionPanel from '@/components/report/HeldSessionPanel'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import Button from '@/components/ui/Button'
|
||||
import {
|
||||
isUnsaved,
|
||||
useReportStore,
|
||||
type ActionResult,
|
||||
type HeldText,
|
||||
@@ -76,7 +75,6 @@ export default function EditorRoute() {
|
||||
// Without a report yet (draft restore), the default species' sheet carries the migration map.
|
||||
const sheet = useSheet(report?.animal.speciesId ?? DEFAULT_SPECIES_ID)
|
||||
const stopped = useCoreStopped()
|
||||
const unsaved = isUnsaved(store)
|
||||
|
||||
const [detailViewId, setDetailViewId] = useState<string | null>(null)
|
||||
const [vertebraTarget, setVertebraTarget] = useState<VertebraTarget | null>(
|
||||
@@ -137,17 +135,6 @@ export default function EditorRoute() {
|
||||
navigate('/')
|
||||
}, [report, sheet, store, navigate, t, restoreAttempt])
|
||||
|
||||
// The report lives only in this tab's memory: the browser asks before a reload or a close.
|
||||
useEffect(() => {
|
||||
if (!unsaved) return
|
||||
const guard = (event: BeforeUnloadEvent) => {
|
||||
event.preventDefault()
|
||||
event.returnValue = ''
|
||||
}
|
||||
window.addEventListener('beforeunload', guard)
|
||||
return () => window.removeEventListener('beforeunload', guard)
|
||||
}, [unsaved])
|
||||
|
||||
const retryRestore = useCallback(() => setRestoreAttempt((n) => n + 1), [])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -288,7 +275,11 @@ export default function EditorRoute() {
|
||||
restoreOptions.current = { replaceOriginal: true }
|
||||
retryRestore()
|
||||
}}
|
||||
onRetry={retryRestore}
|
||||
onRetry={() => {
|
||||
// The one explicit way to read a draft the engine trapped on again.
|
||||
restoreOptions.current = { retryTrapped: true }
|
||||
retryRestore()
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -7,15 +7,23 @@ import type {
|
||||
import AppHeader from '@/components/brand/AppHeader'
|
||||
import HomeSpaceLink from '@/components/brand/HomeSpaceLink'
|
||||
import { CoreStoppedBanner } from '@/components/report/CoreStoppedNotice'
|
||||
import ReplaceSessionDialog from '@/components/report/ReplaceSessionDialog'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Card from '@/components/ui/Card'
|
||||
import {
|
||||
importAttachment,
|
||||
ImportError,
|
||||
MAX_ATTACHMENT_BYTES,
|
||||
MAX_PDF_BYTES,
|
||||
readAttachment,
|
||||
readRescueCopy,
|
||||
} from '@/pdf/import'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import {
|
||||
isSessionInProgress,
|
||||
useReportStore,
|
||||
type ImportedSession,
|
||||
} from '@/state/reportStore'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet'
|
||||
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
|
||||
import { useT } from '@/i18n/useT'
|
||||
@@ -107,11 +115,50 @@ function importErrorMessage(err: unknown, t: Translate): string {
|
||||
return t('home.import.error_no_attachment')
|
||||
case 'lone_surrogate':
|
||||
return t('home.import.error_lone_surrogate')
|
||||
case 'invalid_copy':
|
||||
return t('home.import.error_invalid_copy')
|
||||
case 'core_unavailable':
|
||||
return coreFailureMessage(t, 'home.import.error_core_unavailable')
|
||||
}
|
||||
}
|
||||
|
||||
/** What a picked file read into: the session to open and the alert lines to show after. */
|
||||
interface ImportRead {
|
||||
session: ImportedSession
|
||||
index: SheetIndex
|
||||
lines: string[]
|
||||
}
|
||||
|
||||
const SNIFF_BYTES = 1024
|
||||
const PDF_MAGIC = '%PDF-'
|
||||
|
||||
/** First non-blank byte of the head, after an optional UTF-8 byte order mark. */
|
||||
function firstContentByte(head: Uint8Array): number | undefined {
|
||||
const start = head[0] === 0xef && head[1] === 0xbb && head[2] === 0xbf ? 3 : 0
|
||||
return head.slice(start).find((b) => ![0x20, 0x09, 0x0a, 0x0d].includes(b))
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes by content, from the first KiB only: a PDF starts with its magic, a rescue copy
|
||||
* is JSON (an object) or is named as such; anything else goes the PDF path and its error.
|
||||
*/
|
||||
function isRescueCopy(file: File, head: Uint8Array): boolean {
|
||||
const start = new TextDecoder('latin1').decode(head.slice(0, PDF_MAGIC.length))
|
||||
if (start === PDF_MAGIC) return false
|
||||
if (firstContentByte(head) === 0x7b) return true
|
||||
return file.name.toLowerCase().endsWith('.json') || file.type === 'application/json'
|
||||
}
|
||||
|
||||
/** The copy's text, refused (never altered) when it is over the cap or not valid UTF-8. */
|
||||
async function readCopyText(file: File): Promise<string> {
|
||||
if (file.size > MAX_ATTACHMENT_BYTES) throw new ImportError('invalid_copy')
|
||||
try {
|
||||
return new TextDecoder('utf-8', { fatal: true }).decode(await file.arrayBuffer())
|
||||
} catch {
|
||||
throw new ImportError('invalid_copy')
|
||||
}
|
||||
}
|
||||
|
||||
export default function HomeRoute() {
|
||||
const navigate = useNavigate()
|
||||
const fileRef = useRef<HTMLInputElement | null>(null)
|
||||
@@ -120,10 +167,11 @@ export default function HomeRoute() {
|
||||
const sheet = useSheetAvailability(DEFAULT_SPECIES_ID)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [confirmingReplace, setConfirmingReplace] = useState(false)
|
||||
const t = useT()
|
||||
|
||||
/** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */
|
||||
async function importFile(file: File) {
|
||||
/** A Faunosteo PDF: its attachment, read and rebased by the core on the loaded sheet. */
|
||||
async function readPdf(file: File): Promise<ImportRead> {
|
||||
// The engine refuses the same size; checking first keeps a huge file out of memory.
|
||||
if (file.size > MAX_PDF_BYTES) throw new ImportError('invalid_pdf')
|
||||
const bytes = new Uint8Array(await file.arrayBuffer())
|
||||
@@ -131,20 +179,43 @@ 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)
|
||||
const opened = hydrateImport(
|
||||
{ report: rebase.report, archive: outcome.archive },
|
||||
return {
|
||||
session: { report: rebase.report, archive: outcome.archive },
|
||||
index,
|
||||
)
|
||||
lines: importMessages(outcome, rebase, t),
|
||||
}
|
||||
}
|
||||
|
||||
/** A rescue copy: read before any session change, so a refusal leaves the tab untouched. */
|
||||
async function readCopy(file: File): Promise<ImportRead> {
|
||||
const text = await readCopyText(file)
|
||||
const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
|
||||
if (!index) throw new ImportError('core_unavailable')
|
||||
const rebase = readRescueCopy(text, index)
|
||||
const count = String(rebase.unresolvedZones + rebase.unresolvedFindings)
|
||||
return {
|
||||
session: { report: rebase.report, archive: null },
|
||||
index,
|
||||
lines: rebase.rebased ? [t('editor.draft_rebased').replace('{count}', count)] : [],
|
||||
}
|
||||
}
|
||||
|
||||
/** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */
|
||||
async function importFile(file: File) {
|
||||
const head = new Uint8Array(await file.slice(0, SNIFF_BYTES).arrayBuffer())
|
||||
const read = isRescueCopy(file, head) ? await readCopy(file) : await readPdf(file)
|
||||
const opened = hydrateImport(read.session, read.index)
|
||||
// A tab text that could not be set aside would be overwritten: resolve it first.
|
||||
if (!opened.ok) {
|
||||
// A core failure reading the tab's draft is an engine error, not a held text.
|
||||
if (opened.reason !== 'held') throw new ImportError('core_unavailable')
|
||||
window.alert(t('session.held_blocked'))
|
||||
window.alert(
|
||||
t(opened.engine ? 'session.held_blocked_engine' : 'session.held_blocked'),
|
||||
)
|
||||
navigate('/editor')
|
||||
return
|
||||
}
|
||||
const lines = importMessages(outcome, rebase, t)
|
||||
if (lines.length > 0) window.alert(lines.join('\n\n'))
|
||||
if (read.lines.length > 0) window.alert(read.lines.join('\n\n'))
|
||||
navigate('/editor')
|
||||
}
|
||||
|
||||
@@ -208,14 +279,18 @@ export default function HomeRoute() {
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="application/pdf,.pdf"
|
||||
accept="application/pdf,.pdf,application/json,.json"
|
||||
className="hidden"
|
||||
onChange={onPickFile}
|
||||
/>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="lg"
|
||||
onClick={() => fileRef.current?.click()}
|
||||
onClick={() =>
|
||||
isSessionInProgress()
|
||||
? setConfirmingReplace(true)
|
||||
: fileRef.current?.click()
|
||||
}
|
||||
disabled={busy || sheet.status !== 'ready'}
|
||||
>
|
||||
{busy ? t('home.import.loading') : t('home.import.cta')}
|
||||
@@ -224,6 +299,16 @@ export default function HomeRoute() {
|
||||
</Card>
|
||||
</div>
|
||||
</section>
|
||||
<ReplaceSessionDialog
|
||||
open={confirmingReplace}
|
||||
onCancel={() => setConfirmingReplace(false)}
|
||||
onOpen={() => navigate('/editor')}
|
||||
onConfirm={() => {
|
||||
// The picker opens inside this click: a later call loses the user activation.
|
||||
fileRef.current?.click()
|
||||
setConfirmingReplace(false)
|
||||
}}
|
||||
/>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import PractitionerForm from '@/components/report/PractitionerForm'
|
||||
import AnimalForm from '@/components/report/AnimalForm'
|
||||
import AppHeader from '@/components/brand/AppHeader'
|
||||
import { CoreStoppedBanner } from '@/components/report/CoreStoppedNotice'
|
||||
import ReplaceSessionDialog from '@/components/report/ReplaceSessionDialog'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Input from '@/components/ui/Input'
|
||||
import Label from '@/components/ui/Label'
|
||||
@@ -13,7 +14,7 @@ import {
|
||||
readCachedPractitioner,
|
||||
writeCachedPractitioner,
|
||||
} from '@/state/practitionerCache'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { isSessionInProgress, useReportStore } from '@/state/reportStore'
|
||||
import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { coreFailureMessage } from '@/core/failure'
|
||||
@@ -35,6 +36,7 @@ export default function NewReportRoute() {
|
||||
})
|
||||
const [owner, setOwner] = useState<Owner>({ name: '' })
|
||||
const [date, setDate] = useState(todayIso())
|
||||
const [confirmingReplace, setConfirmingReplace] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const cached = readCachedPractitioner()
|
||||
@@ -47,8 +49,14 @@ export default function NewReportRoute() {
|
||||
owner.name.trim() &&
|
||||
sheet.status === 'ready'
|
||||
|
||||
async function submit() {
|
||||
function submit() {
|
||||
if (!canSubmit || sheet.status !== 'ready') return
|
||||
if (isSessionInProgress()) setConfirmingReplace(true)
|
||||
else void createReport()
|
||||
}
|
||||
|
||||
async function createReport() {
|
||||
if (sheet.status !== 'ready') return
|
||||
writeCachedPractitioner(practitioner)
|
||||
// The loaded sheet lets the store read a draft this page never opened before replacing it.
|
||||
const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
|
||||
@@ -71,7 +79,9 @@ export default function NewReportRoute() {
|
||||
)
|
||||
if (created.ok) navigate('/editor')
|
||||
else if (created.reason === 'held') {
|
||||
window.alert(t('session.held_blocked'))
|
||||
window.alert(
|
||||
t(created.engine ? 'session.held_blocked_engine' : 'session.held_blocked'),
|
||||
)
|
||||
navigate('/editor')
|
||||
} else window.alert(coreFailureMessage(t))
|
||||
}
|
||||
@@ -129,6 +139,15 @@ export default function NewReportRoute() {
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<ReplaceSessionDialog
|
||||
open={confirmingReplace}
|
||||
onCancel={() => setConfirmingReplace(false)}
|
||||
onOpen={() => navigate('/editor')}
|
||||
onConfirm={() => {
|
||||
setConfirmingReplace(false)
|
||||
void createReport()
|
||||
}}
|
||||
/>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useEffect } from 'react'
|
||||
import { isUnsaved, useReportStore } from '@/state/reportStore'
|
||||
|
||||
/**
|
||||
* The report lives only in this tab's memory while the tab's storage refuses its writes:
|
||||
* on any page, the browser asks before a reload, a close or a full-page redirect.
|
||||
*/
|
||||
export function useUnsavedGuard(): void {
|
||||
const unsaved = useReportStore(isUnsaved)
|
||||
useEffect(() => {
|
||||
if (!unsaved) return
|
||||
const guard = (event: BeforeUnloadEvent) => {
|
||||
event.preventDefault()
|
||||
event.returnValue = ''
|
||||
}
|
||||
window.addEventListener('beforeunload', guard)
|
||||
return () => window.removeEventListener('beforeunload', guard)
|
||||
}, [unsaved])
|
||||
}
|
||||
Reference in new issue
Block a user