Skip to content

Commit 9ee869a

Browse files
committed
Switch to compound component pattern
1 parent 97c834c commit 9ee869a

File tree

7 files changed

+210
-212
lines changed

7 files changed

+210
-212
lines changed

projects/js-packages/charts/src/components/line-chart/line-chart-annotations-overlay.tsx

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
import { DataContext } from '@visx/xychart';
22
import { useEffect, useState, useCallback } from 'react';
3-
import { useChartContext } from '../../providers/chart-context';
3+
import { useLineChartContext } from './line-chart-context';
44
import styles from './line-chart.module.scss';
55
import type { AxisScale } from '@visx/axis';
66
import type { FC, ReactNode } from 'react';
77

88
interface LineChartAnnotationsProps {
9-
chartId: string;
109
children?: ReactNode;
1110
}
1211

@@ -15,17 +14,8 @@ interface ScaleData {
1514
yScale: AxisScale< number >;
1615
}
1716

18-
const LineChartAnnotationsOverlay: FC< LineChartAnnotationsProps > = ( { chartId, children } ) => {
19-
const { getChartData } = useChartContext();
20-
21-
let chartData = null;
22-
if ( chartId ) {
23-
chartData = getChartData( chartId );
24-
}
25-
26-
const chartRef = chartData?.chartRef;
27-
const chartWidth = chartData?.chartWidth || 0;
28-
const chartHeight = chartData?.chartHeight || 0;
17+
const LineChartAnnotationsOverlay: FC< LineChartAnnotationsProps > = ( { children } ) => {
18+
const { chartRef, chartWidth, chartHeight } = useLineChartContext();
2919

3020
const [ scales, setScales ] = useState< ScaleData | null >( null );
3121
const [ scalesStable, setScalesStable ] = useState< boolean >( false );
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { createContext, useContext } from 'react';
2+
3+
export interface LineChartRef {
4+
getScales: () => { xScale: unknown; yScale: unknown } | null;
5+
getChartDimensions: () => {
6+
width: number;
7+
height: number;
8+
margin: { top?: number; right?: number; bottom?: number; left?: number };
9+
};
10+
}
11+
12+
// Local context for LineChart implicit state sharing
13+
export interface LineChartContextValue {
14+
chartId: string;
15+
chartRef: React.RefObject< LineChartRef >;
16+
chartWidth: number;
17+
chartHeight: number;
18+
}
19+
20+
export const LineChartContext = createContext< LineChartContextValue | null >( null );
21+
22+
export const useLineChartContext = (): LineChartContextValue => {
23+
const context = useContext( LineChartContext );
24+
if ( ! context ) {
25+
throw new Error( 'useLineChartContext must be used within a LineChart component' );
26+
}
27+
return context;
28+
};

0 commit comments

Comments
 (0)