import type { ChangeEvent } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { imports } from '../api'; import type { ImportedItem, ImportKind } from '../api'; import { useToast } from '../ui'; /** Detail page path of an imported item. */ export function importedItemPath(item: ImportedItem): string { return `/${item.kind}s/${item.id}`; } /** * Returns a file input `onChange` handler that imports the chosen YAML file * through the central import. When the file holds exactly one item of `kind` * (e.g. a scenario export with its environment), opens that item; otherwise * opens the import page with the full result. */ export function useImportFile(kind: ImportKind) { const navigate = useNavigate(); const toast = useToast(); const { t } = useTranslation(); return async (e: ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; e.target.value = ''; try { const result = await imports.yaml(await file.text()); const own = result.imported.filter((item) => item.kind === kind); if (own.length === 1) { if (result.imported.length > 1) { toast.success(t('import.imported_count', { count: result.imported.length })); } navigate(importedItemPath(own[0])); } else { navigate('/import', { state: { results: [{ fileName: file.name, result }] } }); } } catch { // error toast is already emitted by the API client } }; }