73 lines
2.0 KiB
JavaScript

import { Utils } from 'arm-common';
import p from 'prop-types';
import React, { useLayoutEffect, useMemo, useState } from 'react';
import { HBox } from 'arm-core-layouts';
import { ChartContainer, getRoot, useAm5, useAm5Colors } from '../Am5.jsx';
import PieChartLegend from './PieChartLegend.jsx';
const classNamePrefix = 'armu_ai_chatbot-pie-chart';
export default function PieChart(props) {
const { id, xAxis, yAxis } = props;
const [chartId] = useState(id || Utils.uuid(classNamePrefix));
const am5 = useAm5();
const am5Colors = useAm5Colors();
const data = useMemo(() => {
if (props.data?.length){
const data = [...props.data];
data.sort((a, b) => b[yAxis] - a[yAxis]);
return data;
}
return [];
}, [props.data])
useLayoutEffect(() => {
if (am5 && data) {
const root = getRoot(chartId);
const chart = root.container.children.push(am5percent.PieChart.new(root, {
layout: root.verticalLayout,
innerRadius: am5.percent(85)
}));
const series = chart.series.push(am5percent.PieSeries.new(root, {
valueField: yAxis,
categoryField: xAxis
}));
series.labels.template.set("visible", false);
series.ticks.template.set("visible", false);
series.set("colors", am5.ColorSet.new(root, {
colors: am5Colors
}));
series.data.setAll(data);
}
}, [am5, data]);
return (
<HBox className={classNamePrefix}>
<ChartContainer id={chartId} className={`${classNamePrefix}-chart`}/>
<PieChartLegend enableTotal xAxis={xAxis} yAxis={yAxis} data={data} />
</HBox>
);
}
PieChart.defaultProps = {
id: '',
xAxis: '',
yAxis: '',
data: null
}
PieChart.propTypes = {
id: p.string,
xAxis: p.string.isRequired,
yAxis: p.string.isRequired,
data: p.arrayOf(p.object).isRequired
}