55 lines
1.6 KiB
TypeScript
55 lines
1.6 KiB
TypeScript
import { useEffect, useState } from 'react'
|
|
import { buildSheetIndex, type SheetIndex } from '@/services/sheetIndex'
|
|
import { bundledSheetProvider, type SheetProvider } from './provider'
|
|
|
|
/**
|
|
* The reference sheet of a species for the current session, loaded once
|
|
* through the provider and indexed. `none` means the build carries no sheet
|
|
* (production bundle without SHEET_BUNDLE=draft) or no sheet for the species.
|
|
*/
|
|
|
|
export type SheetState =
|
|
| { status: 'loading' }
|
|
| { status: 'none' }
|
|
| { status: 'ready'; index: SheetIndex }
|
|
|
|
let provider: SheetProvider = bundledSheetProvider
|
|
const cache = new Map<string, Promise<SheetIndex | null>>()
|
|
|
|
/** Test seam: swap the provider and forget loaded sheets. */
|
|
export function setSheetProvider(next: SheetProvider): void {
|
|
provider = next
|
|
cache.clear()
|
|
}
|
|
|
|
export function loadSheetIndex(speciesId: string): Promise<SheetIndex | null> {
|
|
let pending = cache.get(speciesId)
|
|
if (!pending) {
|
|
pending = provider
|
|
.getReferenceSheet(speciesId)
|
|
.then((sheet) => (sheet ? buildSheetIndex(sheet) : null))
|
|
cache.set(speciesId, pending)
|
|
}
|
|
return pending
|
|
}
|
|
|
|
export function useSheet(speciesId: string | undefined): SheetState {
|
|
const [state, setState] = useState<SheetState>({ status: 'loading' })
|
|
useEffect(() => {
|
|
let cancelled = false
|
|
if (!speciesId) {
|
|
setState({ status: 'none' })
|
|
return
|
|
}
|
|
setState({ status: 'loading' })
|
|
loadSheetIndex(speciesId).then((index) => {
|
|
if (cancelled) return
|
|
setState(index ? { status: 'ready', index } : { status: 'none' })
|
|
})
|
|
return () => {
|
|
cancelled = true
|
|
}
|
|
}, [speciesId])
|
|
return state
|
|
}
|