fix(editor): honest stopped state when the draft is unsaved; no dead retry
0279953 chose the stopped message from CoreRuntime.stopped alone: it
promised the report was kept even when the tab's storage refused the
draft (export, the banner's advice, needs the core), four surfaces still
offered a retry that could not work, and a failed recovery below the cap
was a dead end since nothing called retry().
The runtime restarts a failed recovery on the next call (compiled module
reused, cap still counts traps) and notifies status listeners. One
CoreStoppedNotice on the editor, Home, New report and the full-page
notice: reload when saved, else core.stopped_unsaved with a core-free
copy download (also on the storage-full banner) and a beforeunload
guard. Export, import and new report say the stopped message; a core
failure reading an unread draft is FAILED, not held. ESLint census of
the failure keys; core.stopped says "plusieurs erreurs".
This commit is contained in:
1 parent
0279953e9e
commit
6371523f8c
24 files changed
+839
-83
No files matched your search
@@ -14,11 +14,13 @@ import EditInfosDialog, {
|
||||
type Identity,
|
||||
} from '@/components/report/EditInfosDialog'
|
||||
import DisclaimerDialog from '@/components/report/DisclaimerDialog'
|
||||
import CoreStoppedNotice, { CopyReportButton } from '@/components/report/CoreStoppedNotice'
|
||||
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 {
|
||||
isUnsaved,
|
||||
useReportStore,
|
||||
type ActionResult,
|
||||
type HeldText,
|
||||
@@ -37,6 +39,7 @@ import type { RebaseOutcome } from '@faunosteo/core-wasm/types'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
|
||||
import { coreFailureMessage } from '@/core/failure'
|
||||
import { useCoreStopped } from '@/core/runtime'
|
||||
|
||||
const DISCLAIMER_FLAG = 'osteo:disclaimer-shown'
|
||||
|
||||
@@ -72,6 +75,8 @@ export default function EditorRoute() {
|
||||
const { report, activeObservationIndex: activeIndex } = store
|
||||
// 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>(
|
||||
@@ -132,6 +137,17 @@ 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(() => {
|
||||
@@ -248,7 +264,7 @@ export default function EditorRoute() {
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('PDF export failed', err)
|
||||
window.alert(t('editor.export_failed'))
|
||||
window.alert(coreFailureMessage(t, 'editor.export_failed'))
|
||||
} finally {
|
||||
setExporting(false)
|
||||
}
|
||||
@@ -300,10 +316,17 @@ export default function EditorRoute() {
|
||||
})
|
||||
}
|
||||
/>
|
||||
{store.saveFailed && (
|
||||
<Notice tone="error" className="mx-4 sm:mx-6 mt-4">
|
||||
{t('editor.save_failed')}
|
||||
</Notice>
|
||||
{stopped ? (
|
||||
<CoreStoppedNotice className="mx-4 sm:mx-6 mt-4" />
|
||||
) : (
|
||||
store.saveFailed && (
|
||||
<Notice tone="error" className="mx-4 sm:mx-6 mt-4">
|
||||
<p>{t('editor.save_failed')}</p>
|
||||
<div className="mt-2">
|
||||
<CopyReportButton />
|
||||
</div>
|
||||
</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">
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import AppHeader from '@/components/brand/AppHeader'
|
||||
import HomeSpaceLink from '@/components/brand/HomeSpaceLink'
|
||||
import { CoreStoppedBanner } from '@/components/report/CoreStoppedNotice'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Card from '@/components/ui/Card'
|
||||
import {
|
||||
@@ -18,6 +19,7 @@ import { useReportStore } from '@/state/reportStore'
|
||||
import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet'
|
||||
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { coreFailureMessage } from '@/core/failure'
|
||||
|
||||
type Translate = ReturnType<typeof useT>
|
||||
|
||||
@@ -106,7 +108,7 @@ function importErrorMessage(err: unknown, t: Translate): string {
|
||||
case 'lone_surrogate':
|
||||
return t('home.import.error_lone_surrogate')
|
||||
case 'core_unavailable':
|
||||
return t('home.import.error_core_unavailable')
|
||||
return coreFailureMessage(t, 'home.import.error_core_unavailable')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,6 +137,8 @@ export default function HomeRoute() {
|
||||
)
|
||||
// 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'))
|
||||
navigate('/editor')
|
||||
return
|
||||
@@ -166,6 +170,7 @@ export default function HomeRoute() {
|
||||
<AppHeader>
|
||||
<HomeSpaceLink />
|
||||
</AppHeader>
|
||||
<CoreStoppedBanner className="mx-4 sm:mx-6 mt-4" />
|
||||
<section className="flex-1 grid place-items-center px-4 sm:px-6">
|
||||
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
|
||||
{noSheet && (
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { Animal, Owner, Practitioner } from '@faunosteo/core-wasm/types'
|
||||
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 Button from '@/components/ui/Button'
|
||||
import Input from '@/components/ui/Input'
|
||||
import Label from '@/components/ui/Label'
|
||||
@@ -52,7 +53,7 @@ export default function NewReportRoute() {
|
||||
// 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'))
|
||||
window.alert(coreFailureMessage(t, 'sheet.core_unavailable'))
|
||||
return
|
||||
}
|
||||
const created = initReport(
|
||||
@@ -79,6 +80,7 @@ export default function NewReportRoute() {
|
||||
<main className="min-h-screen">
|
||||
<AppHeader />
|
||||
<div className="max-w-3xl mx-auto px-4 sm:px-6 py-6 sm:py-8 space-y-6 sm:space-y-8">
|
||||
<CoreStoppedBanner />
|
||||
<h1 className="font-serif text-2xl sm:text-3xl">
|
||||
{t('new_report.title')}
|
||||
</h1>
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { buildViewSvg, type ViewFailure, type ViewStates } from '@/anatomy/drawing'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { coreRuntime, useCoreStopped } from '@/core/runtime'
|
||||
import { stoppedMessageKey } from '@/core/failure'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { isUnsaved, useReportStore } from '@/state/reportStore'
|
||||
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
@@ -17,7 +20,7 @@ export interface AnatomyCanvasProps {
|
||||
|
||||
const ANNOTATED = '[data-anno-id]'
|
||||
|
||||
/** Only an engine that can still recover offers a retry. */
|
||||
/** `engine_stopped` is replaced at render by the stopped text that fits the save state. */
|
||||
const FAILURE_MESSAGE: Record<ViewFailure, string> = {
|
||||
engine: 'sheet.core_unavailable',
|
||||
engine_stopped: 'core.stopped',
|
||||
@@ -34,7 +37,8 @@ function annotatedTarget(event: Event): Element | null {
|
||||
* the core (R3), rebuilt when the view changes and restyled in place when the
|
||||
* selection changes (the restyle runs right after every build). Clicks are
|
||||
* delegated on `data-anno-id`. When the engine cannot run, the canvas shows the
|
||||
* degraded notice with a retry; when the view itself cannot be drawn (a drawing
|
||||
* degraded notice with a retry (none once the engine stopped for good: the page's stopped
|
||||
* notice holds the buttons); when the view itself cannot be drawn (a drawing
|
||||
* refused or impossible to compose), a notice without retry: nothing would change.
|
||||
*/
|
||||
export default function AnatomyCanvas({
|
||||
@@ -52,6 +56,17 @@ export default function AnatomyCanvas({
|
||||
// Each retry builds again; a failed build leaves the canvas empty behind the notice.
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
const [failure, setFailure] = useState<ViewFailure | null>(null)
|
||||
// Derived at render: an engine failure shown while the engine stops becomes the stopped text.
|
||||
const stopped = useCoreStopped()
|
||||
const unsaved = useReportStore(isUnsaved)
|
||||
const engineStopped = failure === 'engine_stopped' || (failure === 'engine' && stopped)
|
||||
|
||||
// A failed recovery below the cap needs the runtime restarted before the view is built again.
|
||||
const retryEngine = useCallback(() => {
|
||||
void coreRuntime()
|
||||
.retry()
|
||||
.finally(() => setAttempt((n) => n + 1))
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const host = svgRef.current
|
||||
@@ -140,11 +155,11 @@ export default function AnatomyCanvas({
|
||||
{failure && (
|
||||
<div className="absolute inset-0 grid place-items-center p-4">
|
||||
<div className="space-y-3 max-w-sm">
|
||||
<Notice tone="error">{t(FAILURE_MESSAGE[failure])}</Notice>
|
||||
{failure === 'engine' && (
|
||||
<Button onClick={() => setAttempt((n) => n + 1)}>
|
||||
{t('sheet.core_retry')}
|
||||
</Button>
|
||||
<Notice tone="error">
|
||||
{t(engineStopped ? stoppedMessageKey(unsaved) : FAILURE_MESSAGE[failure])}
|
||||
</Notice>
|
||||
{failure === 'engine' && !engineStopped && (
|
||||
<Button onClick={retryEngine}>{t('sheet.core_retry')}</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useCoreStopped } from '@/core/runtime'
|
||||
import { downloadJson } from '@/lib/download'
|
||||
import { isUnsaved, useReportStore } from '@/state/reportStore'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/**
|
||||
* Saves the in-memory report as JSON. It needs no engine: this is the rescue copy when the
|
||||
* tab's storage refused the last write and the PDF export cannot run.
|
||||
*/
|
||||
export function CopyReportButton() {
|
||||
const t = useT()
|
||||
const report = useReportStore((s) => s.report)
|
||||
if (!report) return null
|
||||
return (
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => downloadJson(JSON.stringify(report), 'faunosteo-brouillon')}
|
||||
>
|
||||
{t('session.held.download')}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export interface CoreStoppedNoticeProps {
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* The final state of the engine (three recoveries spent), never a retry: reload the page
|
||||
* when the tab's copy of the report is saved; when it is not, the text says so and offers
|
||||
* the copy instead of the reload (a reload would lose the latest edits).
|
||||
*/
|
||||
export default function CoreStoppedNotice({ className = '' }: CoreStoppedNoticeProps) {
|
||||
const t = useT()
|
||||
const unsaved = useReportStore(isUnsaved)
|
||||
return (
|
||||
<Notice tone="error" className={className}>
|
||||
<p>{t(unsaved ? 'core.stopped_unsaved' : 'core.stopped')}</p>
|
||||
<div className="mt-2">
|
||||
{unsaved ? (
|
||||
<CopyReportButton />
|
||||
) : (
|
||||
<Button variant="secondary" onClick={() => window.location.reload()}>
|
||||
{t('core.reload')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</Notice>
|
||||
)
|
||||
}
|
||||
|
||||
/** The notice on the pages that run the core, shown only once the engine stopped. */
|
||||
export function CoreStoppedBanner({ className = '' }: CoreStoppedNoticeProps) {
|
||||
return useCoreStopped() ? <CoreStoppedNotice className={className} /> : null
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import Button from '@/components/ui/Button'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import CoreStoppedNotice from '@/components/report/CoreStoppedNotice'
|
||||
import { useCoreStopped } from '@/core/runtime'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface CoreUnavailableProps {
|
||||
@@ -8,10 +10,19 @@ export interface CoreUnavailableProps {
|
||||
|
||||
/**
|
||||
* Degraded state of the sheet pages when the core module cannot run (CSP, network, an old
|
||||
* browser, a refused sheet): the session data stays where it is, the practitioner retries.
|
||||
* browser, a refused sheet): the session data stays where it is, the practitioner retries. Once the engine
|
||||
* stopped for good, the stopped notice replaces the retry, which could not work.
|
||||
*/
|
||||
export default function CoreUnavailable({ onRetry }: CoreUnavailableProps) {
|
||||
const t = useT()
|
||||
const stopped = useCoreStopped()
|
||||
if (stopped) {
|
||||
return (
|
||||
<main className="p-6 max-w-xl">
|
||||
<CoreStoppedNotice />
|
||||
</main>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<main className="p-6 space-y-3 max-w-xl">
|
||||
<Notice tone="error">{t('sheet.core_unavailable')}</Notice>
|
||||
|
||||
@@ -2,7 +2,7 @@ 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 { downloadJson } from '@/lib/download'
|
||||
import { readSessionText, type SessionText } from '@/state/persistence'
|
||||
import type { HeldText } from '@/state/reportStore'
|
||||
import { useT } from '@/i18n/useT'
|
||||
@@ -18,30 +18,15 @@ export interface HeldSessionPanelProps {
|
||||
|
||||
type Pending = { action: 'discard'; text: SessionText } | { action: 'open' }
|
||||
|
||||
const REVOKE_DELAY_MS = 30_000
|
||||
|
||||
const FILE_STEM: Record<SessionText, string> = {
|
||||
draft: 'faunosteo-brouillon',
|
||||
archive: 'faunosteo-archive',
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the stored text verbatim. It is JSON.stringify output, whose lone surrogates are
|
||||
* `\uXXXX` escapes, so the UTF-8 Blob is lossless. This copy may be the last one before
|
||||
* a deletion: the anchor is attached while clicked and the URL revoked later, since some
|
||||
* engines (WebKit) cancel a download whose URL is revoked at once.
|
||||
*/
|
||||
/** Saves the stored text verbatim (it is JSON.stringify output). */
|
||||
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`
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
setTimeout(() => URL.revokeObjectURL(url), REVOKE_DELAY_MS)
|
||||
if (raw !== null) downloadJson(raw, FILE_STEM[text])
|
||||
}
|
||||
|
||||
function rowLabelKey(item: HeldText): string {
|
||||
|
||||
@@ -1,11 +1,22 @@
|
||||
import type { useT } from '@/i18n/useT'
|
||||
import { isUnsaved, useReportStore } from '@/state/reportStore'
|
||||
import { coreStopped } from './runtime'
|
||||
|
||||
/** The stopped text: the unsaved variant when the tab's copy of the report is stale. */
|
||||
export function stoppedMessageKey(unsaved: boolean): string {
|
||||
return unsaved ? 'core.stopped_unsaved' : 'core.stopped'
|
||||
}
|
||||
|
||||
/**
|
||||
* The alert after a core action failed: "try again" while a retry can work; once the engine
|
||||
* stopped after its three recoveries, the clear final state (reload the page, the report is
|
||||
* kept in the tab) instead of a retry that cannot succeed (owner decision 2026-10-15).
|
||||
* The alert after a core action failed: the fallback ("try again") while a retry can work;
|
||||
* once the engine stopped after its three recoveries, the clear final state instead of a
|
||||
* retry that cannot succeed (owner decision 2026-10-15). Callers with their own fallback
|
||||
* key pass it; this file is the only place that names these keys in a `t()` call.
|
||||
*/
|
||||
export function coreFailureMessage(t: ReturnType<typeof useT>): string {
|
||||
return t(coreStopped() ? 'core.stopped' : 'core.action_failed')
|
||||
export function coreFailureMessage(
|
||||
t: ReturnType<typeof useT>,
|
||||
fallbackKey = 'core.action_failed',
|
||||
): string {
|
||||
if (!coreStopped()) return t(fallbackKey)
|
||||
return t(stoppedMessageKey(isUnsaved(useReportStore.getState())))
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useSyncExternalStore } from 'react'
|
||||
import glueUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm.js?url'
|
||||
import wasmUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm_bg.wasm?url'
|
||||
import {
|
||||
@@ -39,6 +40,16 @@ export function coreStopped(): boolean {
|
||||
return runtime?.stopped ?? false
|
||||
}
|
||||
|
||||
/** Subscribes to the runtime's status changes (stable identity for `useSyncExternalStore`). */
|
||||
export function subscribeCore(listener: () => void): () => void {
|
||||
return coreRuntime().subscribe(listener)
|
||||
}
|
||||
|
||||
/** Whether the engine stopped for good on this page; re-renders when it does. */
|
||||
export function useCoreStopped(): boolean {
|
||||
return useSyncExternalStore(subscribeCore, coreStopped)
|
||||
}
|
||||
|
||||
/** The page's runtime, created on first use. */
|
||||
export function coreRuntime(): CoreRuntime {
|
||||
runtime ??= new CoreRuntime(browserSource)
|
||||
|
||||
@@ -14,7 +14,7 @@ import type {
|
||||
/**
|
||||
* The sheet-bound rules of the editor, run by the core on the session's sheet (R2): one
|
||||
* call per user action or load, never in a render. Each returns the core's outcome; the
|
||||
* caller stops on `ok: false` (nothing is written, the action shows `core.action_failed`).
|
||||
* caller stops on `ok: false` (nothing is written, the action shows `coreFailureMessage`).
|
||||
*/
|
||||
|
||||
export interface FindingToggle {
|
||||
|
||||
@@ -202,7 +202,10 @@ export const en: Dict = {
|
||||
"Faunosteo's computation engine could not be loaded. Your session data is kept.",
|
||||
'sheet.core_retry': 'Retry',
|
||||
'core.stopped':
|
||||
"Faunosteo's computation engine stopped after several successive errors. Reload the page to start it again: your report is kept in this tab.",
|
||||
"Faunosteo's computation engine stopped after several errors. Reload the page to start it again: your report is kept in this tab.",
|
||||
'core.stopped_unsaved':
|
||||
"Faunosteo's computation engine stopped after several errors, and this tab's storage is full: your latest changes are not saved and would be lost if you reload the page. Download a copy before reloading.",
|
||||
'core.reload': 'Reload the page',
|
||||
'canvas.view_unavailable':
|
||||
"This anatomical view cannot be displayed: its drawing was refused by the safety checks or could not be composed. Your report is not changed.",
|
||||
'core.action_failed':
|
||||
|
||||
@@ -216,7 +216,10 @@ export const fr: Dict = {
|
||||
"Le moteur de calcul de Faunosteo n'a pas pu être chargé. Vos données de session sont conservées.",
|
||||
'sheet.core_retry': 'Réessayer',
|
||||
'core.stopped':
|
||||
"Le moteur de calcul de Faunosteo s'est arrêté après plusieurs erreurs successives. Rechargez la page pour le relancer : votre bilan est conservé dans cet onglet.",
|
||||
"Le moteur de calcul de Faunosteo s'est arrêté après plusieurs erreurs. Rechargez la page pour le relancer : votre bilan est conservé dans cet onglet.",
|
||||
'core.stopped_unsaved':
|
||||
"Le moteur de calcul de Faunosteo s'est arrêté après plusieurs erreurs, et l'espace de stockage de cet onglet est plein : vos dernières modifications ne sont pas enregistrées et seraient perdues en rechargeant la page. Téléchargez une copie avant de recharger.",
|
||||
'core.reload': 'Recharger la page',
|
||||
'canvas.view_unavailable':
|
||||
"Cette vue anatomique ne peut pas être affichée : son dessin a été refusé par les contrôles de sécurité ou n'a pas pu être composé. Votre bilan n'est pas modifié.",
|
||||
'core.action_failed':
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { todayIso } from '@/lib/dates'
|
||||
|
||||
const REVOKE_DELAY_MS = 30_000
|
||||
|
||||
/**
|
||||
* Saves `raw` as `<stem>-<date>.json`. A lone surrogate in a JSON.stringify output is a
|
||||
* `\uXXXX` escape, so the UTF-8 Blob is lossless. This copy may be the last one before a
|
||||
* deletion: the anchor is attached while clicked and the URL revoked later, since some
|
||||
* engines (WebKit) cancel a download whose URL is revoked at once.
|
||||
*/
|
||||
export function downloadJson(raw: string, stem: string): void {
|
||||
const url = URL.createObjectURL(new Blob([raw], { type: 'application/json' }))
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `${stem}-${todayIso()}.json`
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
setTimeout(() => URL.revokeObjectURL(url), REVOKE_DELAY_MS)
|
||||
}
|
||||
@@ -141,6 +141,10 @@ const OK: ActionResult = { ok: true }
|
||||
const FAILED: ActionResult = { ok: false }
|
||||
const HELD: ActionResult = { ok: false, reason: 'held' }
|
||||
|
||||
/** The tab's storage refused the last write: the in-memory report is the only copy. */
|
||||
export const isUnsaved = (s: Pick<ReportStore, 'saveFailed' | 'report'>): boolean =>
|
||||
s.saveFailed && s.report !== null
|
||||
|
||||
function onReport(set: Setter, update: (r: Report, s: ReportStore) => Patch) {
|
||||
set((s) => (s.report ? update(s.report, s) : s))
|
||||
}
|
||||
@@ -243,23 +247,24 @@ function restore(
|
||||
/**
|
||||
* 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.
|
||||
* before. HELD when something could not be set aside; FAILED when the core could not even
|
||||
* read the draft (not a held text: nothing is set aside, nothing is written).
|
||||
*/
|
||||
function releaseUnreadSession(
|
||||
index: SheetIndex,
|
||||
persistence: ReportPersistence,
|
||||
archives: ArchivePersistence,
|
||||
): boolean {
|
||||
): ActionResult {
|
||||
const draft = persistence.loadText()
|
||||
const archiveText = archives.loadText()
|
||||
if (draft === null) return restoreOrphanArchive(archiveText) === null
|
||||
if (draft === null) return restoreOrphanArchive(archiveText) === null ? OK : HELD
|
||||
const outcome = index.ops.restoreDraft(draft, archiveText)
|
||||
if (!outcome.ok) {
|
||||
if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) return false
|
||||
return quarantineSession(draft, archiveText)
|
||||
if (!UNREADABLE_DRAFT_KINDS.has(outcome.kind)) return FAILED
|
||||
return quarantineSession(draft, archiveText) ? OK : HELD
|
||||
}
|
||||
if (!outcome.value.archiveRejected || archiveText === null) return true
|
||||
return quarantine('archive', archiveText, ARCHIVE_KEY)
|
||||
if (!outcome.value.archiveRejected || archiveText === null) return OK
|
||||
return quarantine('archive', archiveText, ARCHIVE_KEY) ? OK : HELD
|
||||
}
|
||||
|
||||
export function createReportStore(
|
||||
@@ -278,9 +283,10 @@ export function createReportStore(
|
||||
}
|
||||
|
||||
/** 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 mayStartSession = (index: SheetIndex): ActionResult =>
|
||||
store.getState().report !== null
|
||||
? OK
|
||||
: releaseUnreadSession(index, persistence, archives)
|
||||
|
||||
const store = create<ReportStore>((set, get) => ({
|
||||
report: null,
|
||||
@@ -289,7 +295,8 @@ export function createReportStore(
|
||||
saveFailed: false,
|
||||
|
||||
initReport: (draft, sheet, index) => {
|
||||
if (!mayStartSession(index)) return HELD
|
||||
const may = mayStartSession(index)
|
||||
if (!may.ok) return may
|
||||
const outcome = reportOps.newReport({
|
||||
draft,
|
||||
sheet,
|
||||
@@ -303,7 +310,8 @@ export function createReportStore(
|
||||
},
|
||||
|
||||
hydrateImport: ({ report, archive }, index) => {
|
||||
if (!mayStartSession(index)) return HELD
|
||||
const may = mayStartSession(index)
|
||||
if (!may.ok) return may
|
||||
set(withArchive({ report, activeObservationIndex: 0 }, archive))
|
||||
return OK
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user