Files
NetMapper2026/frontend/src/pages/InventoryPage.tsx
T

73 lines
2.2 KiB
TypeScript
Raw Normal View History

import { useEffect, useState } from 'react';
import { InventoryTree } from '../components/inventory/InventoryTree';
import { NodeContextPanel } from '../components/inventory/NodeContextPanel';
import { fetchInventoryTree, fetchNodeContext } from '../lib/inventoryApi';
import type { InventoryTreeNode, NodeContext } from '../types/inventory';
import '../components/inventory/inventory.css';
function findFirstNode(nodes: InventoryTreeNode[]): string | null {
for (const node of nodes) {
if (node.id) return node.id;
}
return null;
}
export function InventoryPage() {
const [nodes, setNodes] = useState<InventoryTreeNode[]>([]);
const [selectedId, setSelectedId] = useState<string | null>(null);
const [context, setContext] = useState<NodeContext | null>(null);
const [loadingTree, setLoadingTree] = useState(true);
const [loadingContext, setLoadingContext] = useState(false);
const [error, setError] = useState<string | null>(null);
const loadContext = async (id: string) => {
setSelectedId(id);
setLoadingContext(true);
try {
const item = await fetchNodeContext(id);
setContext(item);
} catch (err) {
setError(err instanceof Error ? err.message : 'Errore sconosciuto');
} finally {
setLoadingContext(false);
}
};
useEffect(() => {
let active = true;
setLoadingTree(true);
fetchInventoryTree()
.then((items) => {
if (!active) return;
setNodes(items);
const first = findFirstNode(items);
if (first) loadContext(first);
})
.catch((err: Error) => {
if (!active) return;
setError(err.message);
})
.finally(() => {
if (active) setLoadingTree(false);
});
return () => {
active = false;
};
}, []);
if (loadingTree) {
return <div className="inventory-empty">Caricamento inventory...</div>;
}
if (error) {
return <div className="inventory-error">Errore inventory: {error}</div>;
}
return (
<div className="inventory-layout">
<InventoryTree nodes={nodes} selectedId={selectedId} onSelect={loadContext} />
<NodeContextPanel context={context} loading={loadingContext} onNavigateNode={loadContext} />
</div>
);
}