2024-01-12 14:04:45 -07:00
|
|
|
import { useMemo } from 'react';
|
|
|
|
|
2024-01-12 17:21:40 -07:00
|
|
|
import { convertToGraphData } from './graph-utils';
|
2024-01-12 14:04:45 -07:00
|
|
|
import { chartDefaults } from './graph-config';
|
2024-01-12 17:21:40 -07:00
|
|
|
import { GraphData, GraphProps, XValue, YAxisData } from './graph-types';
|
2024-01-12 14:04:45 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
interface useGraphDataInterface {
|
2024-01-12 17:21:40 -07:00
|
|
|
xValues: Array<XValue>;
|
|
|
|
yData: {
|
2024-01-12 14:04:45 -07:00
|
|
|
data: {
|
|
|
|
value: number;
|
|
|
|
}[];
|
|
|
|
svg: {
|
|
|
|
fill: string;
|
|
|
|
};
|
|
|
|
}[];
|
|
|
|
yAxisLeftLabels: YAxisData;
|
|
|
|
yAxisRightLabels: YAxisData;
|
2024-01-12 17:21:40 -07:00
|
|
|
defaultProps: Partial<GraphProps>;
|
2024-01-12 14:04:45 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// this version assumes string values for X, this isn't necessarily the case
|
2024-01-12 17:21:40 -07:00
|
|
|
// convertToGraphData is specifically tailored to bar/group bar graphs
|
2024-01-12 14:04:45 -07:00
|
|
|
// ultimately this component could be used by any x & y axis graph types (line/bar/scatter)
|
2024-01-12 17:21:40 -07:00
|
|
|
export const useGraphData = (graphData: GraphData, props: Partial<GraphProps>): useGraphDataInterface => {
|
2024-01-12 14:04:45 -07:00
|
|
|
const { yAxisProps = {}, ...otherProps } = props;
|
|
|
|
const defaultProps = {
|
|
|
|
...chartDefaults,
|
|
|
|
...otherProps,
|
|
|
|
// assign default values for yAxisProps + spread to override with values coming from props
|
|
|
|
yAxisProps: {
|
|
|
|
maxLeftYAxisValue: Math.max(...(graphData.yValues[0]?.values ?? [0])),
|
|
|
|
maxRightYAxisValue:
|
|
|
|
graphData.yValues.length > 1 ? Math.max(...graphData.yValues[1]?.values) : undefined,
|
|
|
|
formatRightYAxisLabel: yAxisProps.formatRightYAxisLabel,
|
|
|
|
formatLeftYAxisLabel: yAxisProps.formatLeftYAxisLabel,
|
|
|
|
selectedLeftYAxisLabel: graphData.yValues[0]?.key,
|
|
|
|
selectedRightYAxisLabel: graphData.yValues[1]?.key,
|
|
|
|
...yAxisProps
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-01-12 17:21:40 -07:00
|
|
|
const { yData, yAxisLeftLabels, yAxisRightLabels, xValues } = useMemo(
|
2024-01-18 17:21:01 -07:00
|
|
|
() => convertToGraphData(graphData, { ...defaultProps.yAxisProps, includeColors: defaultProps.includeColors, barColors: defaultProps.barColors}),
|
|
|
|
[graphData, defaultProps.yAxisProps, defaultProps.includeColors, defaultProps.barColors]
|
2024-01-12 14:04:45 -07:00
|
|
|
);
|
|
|
|
|
|
|
|
return {
|
|
|
|
xValues,
|
2024-01-12 17:21:40 -07:00
|
|
|
yData,
|
2024-01-12 14:04:45 -07:00
|
|
|
yAxisLeftLabels,
|
|
|
|
yAxisRightLabels,
|
|
|
|
defaultProps
|
|
|
|
};
|
|
|
|
};
|