railbird-gql/component/charts/use-graph-data.ts
2024-01-15 11:50:20 -08:00

58 lines
1.8 KiB
TypeScript

import { useMemo } from 'react';
import { convertToBarData } from './graph-utils';
import { chartDefaults } from './graph-config';
import { GraphData, Props, YAxisData } from './graph-types';
interface useGraphDataInterface {
xValues: Array<string>;
barData: {
data: {
value: number;
}[];
svg: {
fill: string;
};
}[];
yAxisLeftLabels: YAxisData;
yAxisRightLabels: YAxisData;
defaultProps: Partial<Props>;
}
// this version assumes string values for X, this isn't necessarily the case
// convertToBarData is specifically tailored to bar/group bar graphs
// ultimately this component could be used by any x & y axis graph types (line/bar/scatter)
export const useGraphData = (graphData: GraphData, props: Partial<Props>): useGraphDataInterface => {
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
}
};
const { barData, yAxisLeftLabels, yAxisRightLabels, xValues } = useMemo(
() => convertToBarData(graphData, defaultProps.yAxisProps),
[graphData, defaultProps.yAxisProps]
);
return {
xValues,
barData,
yAxisLeftLabels,
yAxisRightLabels,
defaultProps
};
};