Files
faunosteo/apps/app/src/sheets/useSheet.ts
T
bchanot 6d1cce6e06 feat(app): R4.3b/c import worker, client, controller; HomeRoute on the disposable worker
Protocol v1 (task → ready → result | failed with phase and kind), the worker entry with
the glue bundled statically and the page's compiled Module posted, the file streamed into
the module's memory; client with start and task timers (paused while hidden), settle-once,
terminate always, error events never masked; module-level controller (one import at a
time, cancel on leaving Home, worker chunk prefetched once the engine is loaded); the
settlement mapped to the B.1.8 messages (OD-5: a trap, a timeout or an unreadable file is
« Erreur de lecture du PDF. », never a corrupt PDF). HomeRoute keeps its routing and size
pre-checks, loads its own index after acceptance, drops a result when the session changed.
Tests: handler and client in-process, the corpus message test (O8 51, O7 stored inputs,
O2/O3/Step 5), the six existing suites migrated to the real worker logic.
2026-10-18 18:10:42 +02:00

164 lines
5.3 KiB
TypeScript

import { useEffect, useState } from 'react'
import type { SheetIndexData } from '@faunosteo/core-wasm/types'
import { coreRuntime } from '@/core/runtime'
import { prefetchImportWorker } from '@/core/worker/controller'
import { SheetOps } from '@/core/sheetOps'
import { SheetIndex } from '@/services/sheetIndex'
import {
availabilityOf,
bundledSheetProvider,
type SheetAvailability,
type SheetProvider,
} from './provider'
/**
* The reference sheet of a species for the current session. `useSheet` loads it into the
* core (the editor, the import): `none` means the build carries no sheet (production
* bundle without SHEET_BUNDLE=draft) or none for the species; `core_unavailable` means the
* module could not be loaded (CSP, network, old browser) and `invalid_sheet` that the
* bundled payload was refused, both with a `retry`. `useSheetAvailability` reads the
* payload alone, without the core, for the pages that only offer to start a report.
*/
export type SheetLoad =
| { status: 'none' }
| { status: 'ready'; index: SheetIndex }
| { status: 'core_unavailable' }
| { status: 'invalid_sheet' }
export type SheetState =
| { status: 'loading' }
| { status: 'none' }
| { status: 'ready'; index: SheetIndex }
| { status: 'core_unavailable'; retry: () => void }
| { status: 'invalid_sheet'; retry: () => void }
let provider: SheetProvider = bundledSheetProvider
/** Settled loads only (`ready`, `none`): a failure is never remembered. */
const cache = new Map<string, Promise<SheetLoad>>()
/** Test seam: swap the provider and forget loaded sheets. */
export function setSheetProvider(next: SheetProvider): void {
provider = next
cache.clear()
}
async function loadIntoCore(speciesId: string): Promise<SheetLoad> {
const bundle = await provider.getReferenceSheet(speciesId)
if (!bundle) return { status: 'none' }
if (!(await coreRuntime().ready())) return { status: 'core_unavailable' }
const session = coreRuntime().sheet(JSON.stringify(bundle))
const data = session.call<SheetIndexData>('index_data', '')
if (data.ok) {
const index = new SheetIndex(data.value, new SheetOps(session))
// The engine is loaded: warm the import worker's chunk for a later offline import.
prefetchImportWorker()
return { status: 'ready', index }
}
return {
status:
data.kind === 'invalid_sheet' ? 'invalid_sheet' : 'core_unavailable',
}
}
/** The species' sheet in the core; failures are retried on the next call. */
export function loadSheet(speciesId: string): Promise<SheetLoad> {
let pending = cache.get(speciesId)
if (!pending) {
pending = loadIntoCore(speciesId).catch(
(): SheetLoad => ({ status: 'core_unavailable' }),
)
cache.set(speciesId, pending)
void pending.then((load) => {
const settled = load.status === 'ready' || load.status === 'none'
if (!settled) cache.delete(speciesId)
})
}
return pending
}
/**
* The bundled payload as the text the core's `SheetHandle` reads, for the import worker
* (R4.3): the same text the page's own session was built from. Null without a sheet.
*/
export async function loadSheetBundleText(
speciesId: string,
): Promise<string | null> {
const bundle = await provider.getReferenceSheet(speciesId)
return bundle ? JSON.stringify(bundle) : null
}
/** The ready index, or null (tests and callers that need the sheet or nothing). */
export async function loadSheetIndex(
speciesId: string,
): Promise<SheetIndex | null> {
const load = await loadSheet(speciesId)
return load.status === 'ready' ? load.index : null
}
export function useSheet(speciesId: string | undefined): SheetState {
const [state, setState] = useState<SheetState>({ status: 'loading' })
const [attempt, setAttempt] = useState(0)
useEffect(() => {
let cancelled = false
if (!speciesId) {
setState({ status: 'none' })
return
}
setState({ status: 'loading' })
const retry = () => {
void coreRuntime()
.retry()
.finally(() => setAttempt((n) => n + 1))
}
void loadSheet(speciesId).then((load) => {
if (cancelled) return
if (load.status === 'ready' || load.status === 'none') setState(load)
else if (load.status === 'invalid_sheet')
setState({ status: load.status, retry })
else setState({ status: 'core_unavailable', retry })
})
return () => {
cancelled = true
}
}, [speciesId, attempt])
return state
}
export type SheetAvailabilityState =
| { status: 'loading' }
| { status: 'none' }
| { status: 'ready'; sheet: SheetAvailability }
/** Whether the build carries a sheet for the species, without loading the core. */
export function useSheetAvailability(
speciesId: string | undefined,
): SheetAvailabilityState {
const [state, setState] = useState<SheetAvailabilityState>({
status: 'loading',
})
useEffect(() => {
let cancelled = false
if (!speciesId) {
setState({ status: 'none' })
return
}
void provider
.getReferenceSheet(speciesId)
.then((bundle) => {
if (cancelled) return
setState(
bundle
? { status: 'ready', sheet: availabilityOf(bundle) }
: { status: 'none' },
)
})
// A failed chunk load leaves the page loading, as before R2; a reload fetches again.
.catch(() => undefined)
return () => {
cancelled = true
}
}, [speciesId])
return state
}