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>() /** 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 { 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('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 { 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 { 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 { const load = await loadSheet(speciesId) return load.status === 'ready' ? load.index : null } export function useSheet(speciesId: string | undefined): SheetState { const [state, setState] = useState({ 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({ 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 }