|
| 1 | +import { useEffect } from 'react'; |
| 2 | +import merge from 'lodash/merge'; |
| 3 | + |
| 4 | +import { useObjectDependency } from '@leafygreen-ui/hooks'; |
| 5 | +import { useDarkMode } from '@leafygreen-ui/leafygreen-provider'; |
| 6 | +import { Theme } from '@leafygreen-ui/lib'; |
| 7 | +import { spacing } from '@leafygreen-ui/tokens'; |
| 8 | + |
| 9 | +import { useChartContext } from '../ChartContext'; |
| 10 | +import { type EChartOptions } from '../Echart'; |
| 11 | + |
| 12 | +import { getAxisOptions, unsetAxisOptions } from './Axis'; |
| 13 | +import { XAxisProps } from './XAxis.types'; |
| 14 | + |
| 15 | +const getXAxisOptions = ( |
| 16 | + theme: Theme, |
| 17 | + props: XAxisProps, |
| 18 | +): Omit<EChartOptions, 'series'> => { |
| 19 | + const axisOptions = merge(getAxisOptions(theme, props), { |
| 20 | + axisLabel: { |
| 21 | + align: 'center', |
| 22 | + margin: spacing[400], |
| 23 | + }, |
| 24 | + nameTextStyle: { |
| 25 | + lineHeight: spacing[400], |
| 26 | + padding: [spacing[200], 0, 0, 0], |
| 27 | + }, |
| 28 | + nameGap: spacing[1000], |
| 29 | + }); |
| 30 | + |
| 31 | + return { |
| 32 | + xAxis: axisOptions, |
| 33 | + grid: { |
| 34 | + bottom: props.label |
| 35 | + ? spacing[1200] // Pushes out to make room for the label |
| 36 | + : spacing[400], // Default bottom spacing |
| 37 | + }, |
| 38 | + }; |
| 39 | +}; |
| 40 | + |
| 41 | +/** |
| 42 | + * React component that can render an x-axis on a parent chart. |
| 43 | + * |
| 44 | + * This is done by updating the parent chart's canvas configuration received via context. |
| 45 | + * |
| 46 | + * ``` |
| 47 | + * <Chart> |
| 48 | + * <XAxis |
| 49 | + * type="time", |
| 50 | + * label="My X-Axis Data", |
| 51 | + * formatter="{value}GB" |
| 52 | + * /> |
| 53 | + * </Chart> |
| 54 | + */ |
| 55 | +export function XAxis(props: XAxisProps) { |
| 56 | + const { |
| 57 | + chart: { ready, updateOptions }, |
| 58 | + } = useChartContext(); |
| 59 | + const { theme } = useDarkMode(); |
| 60 | + const propsDep = useObjectDependency(props); |
| 61 | + |
| 62 | + useEffect(() => { |
| 63 | + if (!ready) return; |
| 64 | + |
| 65 | + updateOptions(getXAxisOptions(theme, propsDep)); |
| 66 | + |
| 67 | + return () => { |
| 68 | + /** |
| 69 | + * Hides the axis when the component is unmounted. |
| 70 | + */ |
| 71 | + updateOptions({ |
| 72 | + xAxis: { ...unsetAxisOptions }, |
| 73 | + grid: { bottom: spacing[400] }, // Reset the grid bottom spacing |
| 74 | + }); |
| 75 | + }; |
| 76 | + }, [ready, theme, updateOptions, propsDep]); |
| 77 | + |
| 78 | + return null; |
| 79 | +} |
0 commit comments