Untitled

Anonymous
Plain Text
10/08/2025 11:16 AM
31.4 KB
24
Indexable
Never
import { useEffect, useMemo, useRef, useState } from 'react';
import ApexSankey from 'apexsankey';
import API from 'contexts/Api';
import {
    Box,
    Chip,
    // Divider,
    FormControl,
    IconButton,
    ListItemText,
    MenuItem,
    Paper,
    Popover,
    Select,
    Skeleton,
    Stack,
    Button,
    Tooltip,
    // Switch,
    Typography
} from '@mui/material';
import { InfoCircleOutlined, ExclamationCircleFilled } from '@ant-design/icons';
import TuneIcon from '@mui/icons-material/Tune';

// -------------------------------------------------------------
// IndustrialElectricitySankeyChart
// Senior-grade, supports classic and Plant→Flow→Sink layouts.
// Handles intermediate nodes, role-based colors, filters and warnings.
// -------------------------------------------------------------

const IndustrialElectricitySankeyChart = () => {
    // API data & UI state
    const [sankeyData, setSankeyData] = useState(null);
    const [facilities, setFacilities] = useState([]);
    const [selectedFacilityId, setSelectedFacilityId] = useState('');

    // Controls
    const [selectedMonth, setSelectedMonth] = useState(getDefaultMonth());
    const [layout, setLayout] = useState('classic'); // 'classic' | 'plant_flow_bridge'
    const [allocation, setAllocation] = useState('measured'); // measured | priority_self_consume | proportional
    const [granularity, setGranularity] = useState('aggregated'); // aggregated | plant_type | plant | meter (classic only)
    // const [preferFacts, setPreferFacts] = useState(true);
    // const [showResidual, setShowResidual] = useState(true);
    const [bridgeFlows, setBridgeFlows] = useState([
        'consumed_internal',
        'auxiliary',
        'exported',
        'sold_to_third'
    ]); // only for bridge layout

    const [loading, setLoading] = useState(true);
    const [errorMsg, setErrorMsg] = useState('');
    const [anchorEl, setAnchorEl] = useState(null);
    const [filtersAnchorEl, setFiltersAnchorEl] = useState(null);
    const open = Boolean(anchorEl);
    const filtersOpen = Boolean(filtersAnchorEl);

    // Keep a ref to clear the canvas on updates
    const containerRef = useRef(null);

    // Month options: last 12 months (YYYY-MM + short label)
    const monthOptions = useMemo(() => buildRecentMonths(12), []);

    // UI: info popover
    const handlePopoverOpen = (event) => setAnchorEl(event.currentTarget);
    const handlePopoverClose = () => setAnchorEl(null);

    // UI: filters popover
    const handleFiltersOpen = (event) => setFiltersAnchorEl(event.currentTarget);
    const handleFiltersClose = () => setFiltersAnchorEl(null);

    // Fetch facilities once
    useEffect(() => {
        let cancelled = false;
        (async () => {
            try {
                const res = await API.get(`${window.TENANT_URL}/assets/facilities`);
                if (cancelled) return;
                const data = Array.isArray(res?.data) ? res.data : [];
                setFacilities(data);
                if (data.length > 0) {
                    setSelectedFacilityId(data[0].facility_id);
                }
            } catch (err) {
                // If this fails, everything else is pain anyway
                setErrorMsg('Cannot load facilities.');
                console.error(err);
            }
        })();
        return () => {
            cancelled = true;
        };
    }, []);

    // Fetch Sankey each time filters change
    useEffect(() => {
        if (!selectedFacilityId || !selectedMonth) return;

        let cancelled = false;
        (async () => {
            setLoading(true);
            setErrorMsg('');
            try {
                const params = new URLSearchParams();
                params.set('month', selectedMonth);
                params.set('facility_id', selectedFacilityId);
                params.set('allocation', allocation);
                params.set('source_granularity', granularity);
                // params.set('prefer_facts', String(preferFacts));
                // params.set('show_residual', String(showResidual));
                // layout mapping
                if (layout === 'plant_flow_bridge') {
                    params.set('layout', 'plant_flow_bridge');
                    // flows repeated param
                    (bridgeFlows || []).forEach(f => params.append('flows', f));
                }
                const url = `${window.TENANT_URL}/analytics/industrial-energy/analytics/sankey?${params.toString()}`;
                const response = await API.get(url);
                if (cancelled) return;

                const apiData = response?.data;
                const transformed = transformApiPayloadToApexSankey(apiData);
                setSankeyData(transformed);
            } catch (err) {
                setErrorMsg('Failed to load Sankey data.');
                console.error(err);
            } finally {
                if (!cancelled) setLoading(false);
            }
        })();

        return () => {
            cancelled = true;
        };
    }, [selectedFacilityId, selectedMonth, layout, allocation, granularity, bridgeFlows]);

    // Render sankey when data changes
    useEffect(() => {
        if (!sankeyData) return;

        // Compute a dynamic height so big node sets don't look like canned sardines
        const dynamicHeight = Math.max(320, Math.min(700, 160 + (sankeyData.nodes?.length || 0) * 12));

        const options = {
            toolbox: { show: false },
            height: dynamicHeight,
            fontSize: '14px',
            fontWeight: 500,
            canvasStyle: 'background: white',
            spacing: 28,
            nodeWidth: 26
        };

        const container = containerRef.current;
        if (container) {
            // Clear previous render
            container.innerHTML = '';
            const sankey = new ApexSankey(container, options);
            sankey.render(sankeyData);
        }

        // Nothing to clean beyond wiping container on next render
    }, [sankeyData]);

    // Derive meta and warnings for UI hints
    const meta = sankeyData?.meta || {};
    const warnings = meta?.warnings || [];
    // const descriptions = meta?.descriptions || {};

    // Check if there are warnings to show in badge
    const hasWarnings = warnings.length > 0;

    return (
        <Box sx={{ width: '100%', height: '100%' }}>
            {/* Header and controls */}
            <Stack direction="row" alignItems="center" justifyContent="space-between" px={2} pt={1}>
                <Stack direction="row" alignItems="center" spacing={1}>
                    <Typography variant="h5" sx={{ fontWeight: 600 }}>Energy Flow</Typography>
                    <IconButton
                        color="primary"
                        onClick={handlePopoverOpen}
                        aria-describedby="energy_flow-sankey-popover"
                        sx={{
                            borderRadius: '50px',
                            width: 30,
                            height: 30,
                            '&:hover': { backgroundColor: '#1890ff', color: 'white' }
                        }}
                    >
                        <InfoCircleOutlined />
                    </IconButton>
                </Stack>

                {/* Primary selectors - now only the Filters button */}
                <Stack direction="row" spacing={1} flexWrap="wrap" justifyContent="flex-end" alignItems="center">
                    {hasWarnings && (
                        <Tooltip title={warnings.join(', ')}>
                            <ExclamationCircleFilled style={{ color: '#d97706', fontSize: '16px', position: 'absolute', top: '25px', right: '10px', zIndex: '1' }} />
                        </Tooltip>
                    )}
                    <Button
                        variant="outlined"
                        startIcon={<TuneIcon />}
                        onClick={handleFiltersOpen}
                        sx={{
                            borderColor: 'divider',
                            color: 'text.primary',
                            position: 'relative',
                            '&:hover': {
                                borderColor: 'divider',
                            }
                        }}
                    >
                        Filters
                    </Button>
                </Stack>
            </Stack>

            {/* Filters Popover */}
            <Popover
                id="filters-popover"
                open={filtersOpen}
                anchorEl={filtersAnchorEl}
                onClose={handleFiltersClose}
                anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
                transformOrigin={{ vertical: 'top', horizontal: 'left' }}
                sx={{ ml: -4 }}
                PaperProps={{
                    sx: {
                        borderRadius: 2,
                        p: 2,
                        width: 300
                    }
                }}
            >
                <Stack spacing={2}>

                    {/* Facility Selector */}
                    <FormControl size="small" fullWidth>
                        <Typography variant="body2" sx={{ mb: 1, fontWeight: 500 }}>
                            Facility
                        </Typography>
                        <Select
                            displayEmpty
                            value={selectedFacilityId}
                            onChange={(e) => setSelectedFacilityId(e.target.value)}
                            renderValue={(selected) => {
                                const sel = facilities.find(f => f.facility_id === selected);
                                return (
                                    <Box sx={{ textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}>
                                        {sel ? sel.name : 'Select Facility'}
                                    </Box>
                                );
                            }}
                        >
                            {facilities.map((f) => (
                                <MenuItem key={f.facility_id} value={f.facility_id}>
                                    <ListItemText primary={f.name} />
                                </MenuItem>
                            ))}
                        </Select>
                    </FormControl>

                    {/* Month Selector */}
                    <FormControl size="small" fullWidth>
                        <Typography variant="body2" sx={{ mb: 1, fontWeight: 500 }}>
                            Month
                        </Typography>
                        <Select
                            displayEmpty
                            value={selectedMonth}
                            onChange={(e) => setSelectedMonth(e.target.value)}
                            renderValue={(selected) => {
                                const m = monthOptions.find(x => x.value === selected);
                                return <Box sx={{ textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}>
                                    {m ? m.label : 'Month'}
                                </Box>;
                            }}
                        >
                            {monthOptions.map((m) => (
                                <MenuItem key={m.value} value={m.value}>
                                    <ListItemText primary={m.label} />
                                </MenuItem>
                            ))}
                        </Select>
                    </FormControl>

                    {/* Layout Selector */}
                    <FormControl size="small" fullWidth>
                        <Stack direction="row" alignItems="center" gap={1} mb={1}>
                            <Typography variant="body2" sx={{ fontWeight: 500 }}>
                                Layout
                            </Typography>
                            <Tooltip title={
                                <>
                                    <Typography variant='caption'>Cambia la struttura logica del grafico.</Typography>
                                    <Typography variant='h6' color="primary">Standard</Typography>
                                    <Typography variant='caption'>Sorgenti (produzione + rete) → Usi (consumi, export, vendite).</Typography>
                                    <Typography variant='h6' color="primary">Plant Flow Bridge</Typography>
                                    <Typography variant='caption'>Mostra tre livelli: Impianti → Flussi → Usi.
                                        Serve per analizzare le performance o i ruoli dei singoli plant.</Typography>
                                    <Typography variant='h6' color="primary">Role Flow Bridge</Typography>
                                    <Typography variant='caption'>Mostra quattro livelli: Produzione / Import → Ruoli → Flussi → Sink finali.</Typography>
                                </>
                            }
                                placement="right"
                            >
                                <InfoCircleOutlined style={{ color: '#1890ff' }} />
                            </Tooltip>
                        </Stack>
                        <Select
                            value={layout}
                            onChange={(e) => setLayout(e.target.value)}
                            renderValue={(selected) => (
                                <Box sx={{ textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}>
                                    {selected === 'classic' ? 'Classic layout' : 'Plant → Flow → Sink'}
                                </Box>
                            )}
                        >
                            <MenuItem value="classic"><ListItemText primary="Classic layout" /></MenuItem>
                            <MenuItem value="plant_flow_bridge"><ListItemText primary="Plant → Flow → Sink" /></MenuItem>
                        </Select>
                    </FormControl>

                    {/* Allocation Selector */}
                    <FormControl size="small" fullWidth>
                        <Stack direction="row" alignItems="center" gap={1} mb={1}>
                            <Typography variant="body2" sx={{ fontWeight: 500 }}>
                                Allocation Method
                            </Typography>
                            <Tooltip title={
                                <>
                                    <Typography variant='caption'>Metodo con cui viene distribuita l’energia prodotta tra i diversi usi del sito.</Typography>
                                    <Typography variant='h6' color="primary">Misurata / Proporzionale</Typography>
                                    <Typography variant='caption'>Ogni sorgente (produzione e rete) alimenta i sink in proporzione ai loro consumi misurati.
                                        È il metodo più fedele ai dati reali.</Typography>
                                    <Typography variant='h6' color="primary">Priorità autoconsumo</Typography>
                                    <Typography variant='caption'>L’energia prodotta viene destinata prima ai consumi interni e agli ausiliari, poi all’export o alla vendita.
                                        Simula uno scenario di massimizzazione dell’autoconsumo.</Typography>
                                </>
                            }
                                placement="right"
                            >
                                <InfoCircleOutlined style={{ color: '#1890ff' }} />
                            </Tooltip>
                        </Stack>
                        <Select
                            value={allocation}
                            onChange={(e) => setAllocation(e.target.value)}
                            renderValue={(selected) => (
                                <Box sx={{ textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}>
                                    {selected === 'measured' ? 'Measured/Proportional' :
                                        selected === 'priority_self_consume' ? 'Priority self-consume' :
                                            'Proportional (alias)'}
                                </Box>
                            )}
                        >
                            <MenuItem value="measured"><ListItemText primary="Measured/Proportional" /></MenuItem>
                            <MenuItem value="priority_self_consume"><ListItemText primary="Priority self-consume" /></MenuItem>
                            <MenuItem value="proportional"><ListItemText primary="Proportional (alias)" /></MenuItem>
                        </Select>
                    </FormControl>

                    {/* Granularity Selector (only for classic layout) */}
                    <FormControl size="small" fullWidth>
                        <Stack direction="row" alignItems="center" gap={1} mb={1}>
                            <Typography variant="body2" sx={{ fontWeight: 500 }}>
                                Granularity
                            </Typography>
                            <Tooltip title={
                                <>
                                    <Typography variant='caption'>Livello di dettaglio con cui mostrare le sorgenti di energia nel grafico.</Typography>
                                    <Typography variant='h6' color="primary">Aggregata</Typography>
                                    <Typography variant='caption'>un solo nodo per tutta la produzione interna.</Typography>
                                    <Typography variant='h6' color="primary">Per tecnologia</Typography>
                                    <Typography variant='caption'>un nodo per ciascun tipo di impianto (fotovoltaico, motore, turbina, ecc.).
                                        Per impianto: un nodo per ogni plant.</Typography>
                                    <Typography variant='h6' color="primary">Per contatore</Typography>
                                    <Typography variant='caption'>un nodo per ogni meter.</Typography>
                                </>
                            }
                                placement="right"
                            >
                                <InfoCircleOutlined style={{ color: '#1890ff' }} />
                            </Tooltip>
                        </Stack>
                        <Select
                            value={granularity}
                            onChange={(e) => setGranularity(e.target.value)}
                            renderValue={(selected) => (
                                <Box sx={{ textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}>
                                    {selected === 'aggregated' ? 'Aggregated' :
                                        selected === 'plant_type' ? 'Plant type' :
                                            selected === 'plant' ? 'Plant' : 'Meter'}
                                </Box>
                            )}
                        >
                            <MenuItem value="aggregated"><ListItemText primary="Aggregated" /></MenuItem>
                            <MenuItem value="plant_type"><ListItemText primary="Plant type" /></MenuItem>
                            <MenuItem value="plant"><ListItemText primary="Plant" /></MenuItem>
                            <MenuItem value="meter"><ListItemText primary="Meter" /></MenuItem>
                        </Select>
                    </FormControl>

                    {/* Bridge Flows Selector (only for bridge layout) */}
                    <FormControl size="small" fullWidth>
                        <Typography variant="body2" sx={{ mb: 1, fontWeight: 500 }}>
                            Flow Types
                        </Typography>
                        <Select
                            multiple
                            value={bridgeFlows}
                            onChange={(e) => setBridgeFlows(e.target.value)}
                            renderValue={(selected) => (
                                <Box sx={{ textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}>
                                    <Stack direction="row" spacing={0.5} flexWrap="wrap">
                                        {selected.map((s) => (
                                            <Chip
                                                key={s}
                                                size="small"
                                                label={prettyFlowLabel(s)}
                                                sx={{
                                                    maxWidth: 100,
                                                    fontSize: '8px',
                                                    '& .MuiChip-label': {
                                                        textOverflow: 'ellipsis',
                                                        overflow: 'hidden',
                                                        whiteSpace: 'nowrap'
                                                    }
                                                }}
                                            />
                                        ))}
                                    </Stack>
                                </Box>
                            )}
                        >
                            {['consumed_internal', 'auxiliary', 'exported', 'sold_to_third'].map((f) => (
                                <MenuItem key={f} value={f}>
                                    <ListItemText primary={prettyFlowLabel(f)} />
                                </MenuItem>
                            ))}
                        </Select>
                    </FormControl>

                    {/* Toggles section (commented out for now) */}
                    {/* <Divider />
                    <Typography variant="body2" sx={{ fontWeight: 500 }}>
                        Advanced Options
                    </Typography>
                    
                    <Stack spacing={1}>
                        <Tooltip title="Prefer monthly roll-ups where available">
                            <Stack direction="row" alignItems="center" justifyContent="space-between">
                                <Typography variant="body2">Prefer facts</Typography>
                                <Switch size="small" checked={preferFacts} onChange={(e) => setPreferFacts(e.target.checked)} />
                            </Stack>
                        </Tooltip>

                        <Tooltip title="Show residual sink to close minor gaps">
                            <Stack direction="row" alignItems="center" justifyContent="space-between">
                                <Typography variant="body2">Show residual</Typography>
                                <Switch size="small" checked={showResidual} onChange={(e) => setShowResidual(e.target.checked)} />
                            </Stack>
                        </Tooltip>
                    </Stack> */}
                </Stack>
            </Popover>

            {/* Info popover uses API descriptions when present */}
            <Popover
                id="energy_flow-sankey-popover"
                open={open}
                anchorEl={anchorEl}
                onClose={handlePopoverClose}
                anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
                transformOrigin={{ vertical: 'top', horizontal: 'center' }}
                PaperProps={{ sx: { borderRadius: 2 } }}
            >
                <Paper sx={{ p: 2.5, bgcolor: 'background.paper', maxWidth: 420, border: '1px solid', borderColor: 'divider' }}>
                    <Typography variant="h6" sx={{ fontWeight: 700, mb: 1 }}>
                        Energy Flow
                    </Typography>
                    <Typography variant="body2" sx={{ color: 'text.secondary', lineHeight: 1.5 }}>
                        Mostra come l’energia prodotta e importata viene distribuita tra i diversi usi del sito (consumi interni, ausiliari, export, vendite).
                        Se compare un “residuo”, significa che parte dei dati non è coperta o che c’è un disallineamento tra sorgenti e consumi.
                    </Typography>
                </Paper>
            </Popover>

            {/* Warnings */}
            {/* {warnings.length > 0 && (
                <Stack direction="row" spacing={1} alignItems="center" px={2} py={1}>
                    <WarningOutlined style={{ color: '#d97706' }} />
                    <Stack direction="row" spacing={0.5} flexWrap="wrap">
                        {warnings.map((w, idx) => (
                            <Chip key={idx} size="small" label={w} sx={{ bgcolor: '#fff7ed', borderColor: '#ffedd5', borderWidth: 1, borderStyle: 'solid' }} />
                        ))}
                    </Stack>
                </Stack>
            )} */}

            {/* Legend */}
            <Stack direction="row" gap={1} p={2} alignItems="center" justifyContent="center" flexWrap="wrap">
                <LegendSwatch color="#2563eb" label="Sources" />
                <LegendSwatch color="#f59e0b" label="Flow groups" />
                <LegendSwatch color="#10b981" label="Sinks" />
                <LegendSwatch color="#0ea5e9" label="Grid import" />
                <LegendSwatch color="#dc2626" label="Unserved demand" />
                <LegendSwatch color="#7c3aed" label="Residual" />
            </Stack>

            {/* Chart area */}
            {loading ? (
                <Box sx={{ p: 2 }}>
                    <Skeleton variant="rounded" width="100%" height={240} />
                </Box>
            ) : errorMsg ? (
                <Box sx={{ p: 2 }}>
                    <Paper sx={{ p: 2, border: '1px solid', borderColor: 'divider' }}>
                        <Typography variant="body2" sx={{ color: 'text.secondary' }}>{errorMsg}</Typography>
                    </Paper>
                </Box>
            ) : (sankeyData?.nodes?.length || 0) === 0 ? (
                <Box sx={{ p: 2 }}>
                    <Paper sx={{ p: 2, border: '1px solid', borderColor: 'divider' }}>
                        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                            No data for the selected filters.
                        </Typography>
                    </Paper>
                </Box>
            ) : (
                <Box id="sankey-container" ref={containerRef} sx={{ width: '100%', height: '100%', minHeight: 320 }} />
            )}
        </Box>
    );
};

export default IndustrialElectricitySankeyChart;

/* =========================
   Helpers (pure functions)
   ========================= */

/** Build last N months list with `{value:'YYYY-MM', label:'Mon YYYY'}` */
function buildRecentMonths(n = 12) {
    const out = [];
    const now = new Date();
    // Start from current month, go back n-1
    for (let i = 0; i < n; i++) {
        const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - i, 1));
        const y = d.getUTCFullYear();
        const m = String(d.getUTCMonth() + 1).padStart(2, '0');
        const value = `${y}-${m}`;
        const label = d.toLocaleString('en-US', { month: 'short', year: 'numeric', timeZone: 'UTC' });
        out.push({ value, label });
    }
    return out;
}

/** Default month is November 2024 */
function getDefaultMonth() {
    return '2024-11';
}

/** Pretty label for FlowKind values */
function prettyFlowLabel(f) {
    switch (f) {
        case 'consumed_internal': return 'Internal';
        case 'auxiliary': return 'Auxiliary';
        case 'exported': return 'Export';
        case 'sold_to_third': return 'Sold to third';
        default: return f;
    }
}

/**
 * Transform backend EnergySankey payload into ApexSankey format.
 * - Includes ALL nodes: sources, intermediates, sinks.
 * - Assigns role-based colors with special overrides.
 * - Copies meta so we can surface warnings/notes.
 */
function transformApiPayloadToApexSankey(apiData) {
    if (!apiData || !Array.isArray(apiData.nodes)) {
        return { nodes: [], edges: [], meta: { warnings: ['Invalid API payload'] } };
    }

    // Build a quick label map from API
    const labelMap = {};
    apiData.nodes.forEach(n => { labelMap[n.id] = n.label || n.id; });
    // Merge meta.labels if present
    if (apiData?.meta?.labels) {
        Object.assign(labelMap, apiData.meta.labels);
    }

    // Classify kind: trust API node.kind, otherwise infer from id
    const classifyKind = (node) => {
        if (node?.kind) return node.kind;
        const id = String(node?.id || '');
        if (id.startsWith('flow::')) return 'intermediate';
        if (id.startsWith('prod::') || id.startsWith('plant::') || id === 'grid_import') return 'source';
        // Standard sinks
        const sinkIds = new Set(['internal', 'aux', 'export', 'sold', 'unmetered_residual', 'unserved_demand']);
        if (sinkIds.has(id)) return id === 'unserved_demand' ? 'intermediate' : 'sink';
        // Default to sink to avoid floating islands
        return 'sink';
    };

    // Role palettes
    const sourcesPalette = ['#1e40af', '#1d4ed8', '#2563eb', '#3b82f6', '#60a5fa', '#93c5fd'];
    const flowPalette = ['#b45309', '#d97706', '#f59e0b', '#fbbf24'];
    const sinksPalette = ['#065f46', '#047857', '#059669', '#10b981', '#34d399'];

    // Special overrides for well-known nodes
    const special = {
        grid_import: '#0ea5e9',
        unmetered_residual: '#7c3aed',
        unserved_demand: '#dc2626'
    };

    let sIdx = 0, fIdx = 0, kIdx = 0;

    const nodes = apiData.nodes.map((n) => {
        const kind = classifyKind(n);
        let color = '#94a3b8'; // fallback slate
        const id = String(n.id);

        if (special[id]) {
            color = special[id];
        } else if (kind === 'source') {
            color = sourcesPalette[sIdx % sourcesPalette.length];
            sIdx++;
        } else if (kind === 'intermediate') {
            color = flowPalette[fIdx % flowPalette.length];
            fIdx++;
        } else if (kind === 'sink') {
            color = sinksPalette[kIdx % sinksPalette.length];
            kIdx++;
        }

        return {
            id,
            title: labelMap[id] || id,
            color
        };
    });

    // Edges: copy as-is
    const edges = Array.isArray(apiData.links)
        ? apiData.links.map(l => ({ source: l.source, target: l.target, value: l.value }))
        : [];

    return {
        nodes,
        edges,
        meta: {
            warnings: apiData?.meta?.warnings || [],
            descriptions: apiData?.meta?.descriptions || {}
        }
    };
}

/** Tiny color swatch legend item */
function LegendSwatch({ color, label }) {
    return (
        <Stack direction="row" spacing={1} alignItems="center">
            <Box sx={{ width: 10, height: 10, borderRadius: '25px', bgcolor: color, border: '1px solid rgba(0,0,0,0.1)' }} />
            <Typography variant="caption" sx={{ color: 'text.secondary' }}>{label}</Typography>
        </Stack>
    );
}
Editor is loading...
Leave a Comment