Skip to content

Commit

Permalink
Chart theme HOC
Browse files Browse the repository at this point in the history
  • Loading branch information
bmingles committed Nov 1, 2023
1 parent 9b97a3f commit f91c2c5
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 16 deletions.
50 changes: 50 additions & 0 deletions packages/chart/src/ChartThemeProviderUtils.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/* eslint-disable react/jsx-props-no-spreading */
import {
ComponentType,
ForwardedRef,
forwardRef,
PropsWithoutRef,
RefAttributes,
useContext,
} from 'react';
import { ChartTheme } from './ChartTheme';

import {
ChartThemeContext,
ChartThemeContextValue,
} from './ChartThemeProvider';

/**
* Hook to get the current `ChartThemeContextValue`.
*/
export function useChartTheme(): ChartThemeContextValue | null {
return useContext(ChartThemeContext);
}

export function withChartTheme<P extends object, T>(
Component: ComponentType<P & { chartTheme: ChartTheme }>
): React.ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>> & {
WrappedComponent?: ComponentType<P & { chartTheme: ChartTheme }>;
} {
function WithChartTheme(props: P, ref: ForwardedRef<T>): JSX.Element {
const chartTheme = useChartTheme();

if (chartTheme == null) {
throw new Error(
'ChartTheme is null, did you forget to wrap your component in a ChartThemeProvider?'
);
}

return <Component ref={ref} {...props} chartTheme={chartTheme} />;
}

const WithChartThemeForwardRef: React.ForwardRefExoticComponent<
PropsWithoutRef<P> & RefAttributes<T>
> & {
WrappedComponent?: ComponentType<P & { chartTheme: ChartTheme }>;
} = forwardRef(WithChartTheme);

WithChartThemeForwardRef.WrappedComponent = Component;

return WithChartThemeForwardRef;
}
2 changes: 1 addition & 1 deletion packages/chart/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ export { default as MockChartModel } from './MockChartModel';
export { default as Plot } from './plotly/Plot';
export * from './ChartTheme';
export * from './ChartThemeProvider';
export * from './useChartTheme';
export * from './ChartThemeProviderUtils';
export { default as isFigureChartModel } from './isFigureChartModel';
15 changes: 0 additions & 15 deletions packages/chart/src/useChartTheme.ts

This file was deleted.

0 comments on commit f91c2c5

Please sign in to comment.