Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add DeclarativeChart in v9 #33919

Draft
wants to merge 1 commit into
base: usr/agupta/stable-V9
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
add declarative chart in v9
  • Loading branch information
krkshitij committed Feb 27, 2025
commit e5fbb96f2704ce16ce6e87fa35202111cb8e9ad1
41 changes: 41 additions & 0 deletions packages/charts/react-charts/library/etc/react-charts.api.md
Original file line number Diff line number Diff line change
@@ -72,6 +72,8 @@ export interface CartesianChartProps {
// @deprecated
chartLabel?: string;
className?: string;
// (undocumented)
componentRef?: React_2.RefObject<Chart>;
customDateTimeFormatter?: (dateTime: Date) => string;
customProps?: (dataPointCalloutProps: any) => ChartPopoverProps;
dateLocalizeOptions?: Intl.DateTimeFormatOptions;
@@ -158,6 +160,12 @@ export interface CartesianChartStyles {
yAxis?: string;
}

// @public (undocumented)
export interface Chart {
// (undocumented)
chartContainer: HTMLElement | null;
}

// @public
export type ChartDataMode = 'default' | 'fraction' | 'percentage';

@@ -355,6 +363,16 @@ export const DataVizPalette: {
highSuccess: string;
};

// @public
export const DeclarativeChart: React_2.FunctionComponent<DeclarativeChartProps>;

// @public
export interface DeclarativeChartProps extends React_2.RefAttributes<HTMLDivElement> {
chartSchema: Schema;
componentRef?: React_2.RefObject<IDeclarativeChart>;
onSchemaChange?: (eventData: Schema) => void;
}

// @public (undocumented)
export const DonutChart: React_2.FunctionComponent<DonutChartProps>;

@@ -505,6 +523,24 @@ export interface HorizontalDataPoint {
y: number;
}

// @public (undocumented)
export interface IDeclarativeChart {
// (undocumented)
exportAsImage: (opts?: ImageExportOptions) => Promise<string>;
}

// @public (undocumented)
export interface ImageExportOptions {
// (undocumented)
background?: string;
// (undocumented)
height?: number;
// (undocumented)
scale?: number;
// (undocumented)
width?: number;
}

// @public
export interface Legend {
action?: VoidFunction;
@@ -766,6 +802,11 @@ export interface RefArrayData {
refElement?: SVGGElement;
}

// @public
export interface Schema {
plotlySchema: any;
}

// @public (undocumented)
export const Shape: React_2.FunctionComponent<ShapeProps>;

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './components/DeclarativeChart/index';
Original file line number Diff line number Diff line change
@@ -154,6 +154,14 @@ const CartesianChartBase: React.FunctionComponent<ModifiedCartesianChartProps> =
}
});

React.useImperativeHandle(
props.componentRef,
() => ({
chartContainer: chartContainer.current ?? null,
}),
[],
);

/**
* Dedicated function to return the Callout JSX Element , which can further be used to only call this when
* only the calloutprops and charthover props changes.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from 'react';
import { LegendsProps } from '../Legends/index';
import { AccessibilityProps, Margins } from '../../types/index';
import { AccessibilityProps, Chart, Margins } from '../../types/index';
import { ChartTypes, XAxisTypes, YAxisType } from '../../utilities/index';
import { TimeLocaleDefinition } from 'd3-time-format';
import { ChartPopoverProps } from './ChartPopover.types';
@@ -437,6 +437,8 @@ export interface CartesianChartProps {
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
customProps?: (dataPointCalloutProps: any) => ChartPopoverProps;

componentRef?: React.RefObject<Chart>;
}

export interface YValueHover {
Original file line number Diff line number Diff line change
@@ -0,0 +1,271 @@
/* eslint-disable @typescript-eslint/naming-convention */
import * as React from 'react';
import { DonutChart } from '../DonutChart/index';
// import { VerticalStackedBarChart } from '../VerticalStackedBarChart/index';
import { PlotData, PlotlySchema } from './PlotlySchema';
import {
isArrayOrTypedArray,
isDateArray,
isNumberArray,
isMonthArray,
sanitizeJson,
updateXValues,
transformPlotlyJsonToDonutProps,
// transformPlotlyJsonToVSBCProps,
transformPlotlyJsonToScatterChartProps,
// transformPlotlyJsonToHorizontalBarWithAxisProps,
// transformPlotlyJsonToHeatmapProps,
// transformPlotlyJsonToSankeyProps,
// transformPlotlyJsonToGaugeProps,
// transformPlotlyJsonToGVBCProps,
transformPlotlyJsonToVBCProps,
// isLineData,
} from './PlotlySchemaAdapter';
import { LineChart, LineChartProps } from '../LineChart/index';
// import { HorizontalBarChartWithAxis } from '../HorizontalBarChartWithAxis/index';
// import { AreaChart, IAreaChartProps } from '../AreaChart/index';
// import { HeatMapChart } from '../HeatMapChart/index';
// import { SankeyChart } from '../SankeyChart/SankeyChart';
// import { GaugeChart } from '../GaugeChart/index';
// import { GroupedVerticalBarChart } from '../GroupedVerticalBarChart/index';
import { VerticalBarChart } from '../VerticalBarChart/index';
import { ImageExportOptions, toImage } from './imageExporter';
import { Chart } from '../../types/index';
import { tokens } from '@fluentui/react-theme';

/**
* DeclarativeChart schema.
* {@docCategory DeclarativeChart}
*/
export interface Schema {
/**
* Plotly schema represented as JSON object
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
plotlySchema: any;
}

/**
* DeclarativeChart props.
* {@docCategory DeclarativeChart}
*/
export interface DeclarativeChartProps extends React.RefAttributes<HTMLDivElement> {
/**
* The schema representing the chart data, layout and configuration
*/
chartSchema: Schema;

/**
* Callback when an event occurs
*/
onSchemaChange?: (eventData: Schema) => void;

/**
* Optional callback to access the IDeclarativeChart interface. Use this instead of ref for accessing
* the public methods and properties of the component.
*/
componentRef?: React.RefObject<IDeclarativeChart>;
}

/**
* {@docCategory DeclarativeChart}
*/
export interface IDeclarativeChart {
exportAsImage: (opts?: ImageExportOptions) => Promise<string>;
}

const useColorMapping = () => {
const colorMap = React.useRef(new Map<string, string>());
return colorMap;
};

/**
* DeclarativeChart component.
* {@docCategory DeclarativeChart}
*/
export const DeclarativeChart: React.FunctionComponent<DeclarativeChartProps> = React.forwardRef<
HTMLDivElement,
DeclarativeChartProps
>((props, forwardedRef) => {
const { plotlySchema } = sanitizeJson(props.chartSchema);
const plotlyInput = plotlySchema as PlotlySchema;
let { selectedLegends } = plotlySchema;
const colorMap = useColorMapping();
// const theme = useTheme();
const isDarkTheme = false;
const chartRef = React.useRef<Chart>(null);

if (!isArrayOrTypedArray(selectedLegends)) {
selectedLegends = [];
}

const [activeLegends, setActiveLegends] = React.useState<string[]>(selectedLegends);
const onActiveLegendsChange = (keys: string[]) => {
setActiveLegends(keys);
if (props.onSchemaChange) {
props.onSchemaChange({ plotlySchema: { plotlyInput, selectedLegends: keys } });
}
};

React.useEffect(() => {
// eslint-disable-next-line @typescript-eslint/no-shadow
const { plotlySchema } = sanitizeJson(props.chartSchema);
// eslint-disable-next-line @typescript-eslint/no-shadow
const { selectedLegends } = plotlySchema;
setActiveLegends(selectedLegends ?? []);
}, [props.chartSchema]);

const multiSelectLegendProps = {
canSelectMultipleLegends: true,
onChange: onActiveLegendsChange,
selectedLegends: activeLegends,
};

const commonProps = {
legendProps: multiSelectLegendProps,
componentRef: chartRef,
// calloutProps: { layerProps: { eventBubblingEnabled: true } },
};

const checkAndRenderChart = (
renderChartJsx: (chartProps: LineChartProps /*| IAreaChartProps*/) => JSX.Element,
isAreaChart: boolean = false,
) => {
// let fallbackVSBC = false;
const xValues = (plotlyInput.data[0] as PlotData).x;
const isXDate = isDateArray(xValues);
const isXNumber = isNumberArray(xValues);
const isXMonth = isMonthArray(xValues);
if (isXDate || isXNumber) {
const chartProps: LineChartProps /*| IAreaChartProps*/ = {
...transformPlotlyJsonToScatterChartProps(
{ data: plotlyInput.data, layout: plotlyInput.layout },
isAreaChart,
colorMap,
isDarkTheme,
),
...commonProps,
};
return renderChartJsx(chartProps);
} else if (isXMonth) {
const updatedData = plotlyInput.data.map((dataPoint: PlotData) => ({
...dataPoint,
x: updateXValues(dataPoint.x),
}));
const chartProps: LineChartProps /*| IAreaChartProps*/ = {
...transformPlotlyJsonToScatterChartProps(
{ data: updatedData, layout: plotlyInput.layout },
isAreaChart,
colorMap,
isDarkTheme,
),
...commonProps,
};
return renderChartJsx(chartProps);
}
// Unsupported schema, render as VerticalStackedBarChart
// fallbackVSBC = true;
// return (
// <VerticalStackedBarChart
// {...transformPlotlyJsonToVSBCProps(plotlySchema, colorMap, isDarkTheme, fallbackVSBC)}
// {...commonProps}
// />
// );
throw new Error(`Unsupported chart type :${plotlyInput.data[0]?.type}`);
};

const exportAsImage = React.useCallback((opts?: ImageExportOptions) => {
return toImage(chartRef.current?.chartContainer, {
background: tokens.colorNeutralBackground1,
scale: 5,
...opts,
});
}, []);

React.useImperativeHandle(
props.componentRef,
() => ({
exportAsImage,
}),
[exportAsImage],
);

switch (plotlyInput.data[0].type) {
case 'pie':
return <DonutChart {...transformPlotlyJsonToDonutProps(plotlySchema, colorMap, isDarkTheme)} {...commonProps} />;
case 'bar':
// const orientation = plotlyInput.data[0].orientation;
// if (orientation === 'h' && isNumberArray((plotlyInput.data[0] as PlotData).x)) {
// return (
// <HorizontalBarChartWithAxis
// {...transformPlotlyJsonToHorizontalBarWithAxisProps(plotlySchema, colorMap, isDarkTheme)}
// {...commonProps}
// />
// );
// } else {
// const containsLines = plotlyInput.data.some(
// series => series.type === 'scatter' || isLineData(series as Partial<PlotData>),
// );
// if (['group', 'overlay'].includes(plotlySchema?.layout?.barmode) && !containsLines) {
// return (
// <GroupedVerticalBarChart
// {...transformPlotlyJsonToGVBCProps(plotlySchema, colorMap, isDarkTheme)}
// {...commonProps}
// />
// );
// }
// return (
// <VerticalStackedBarChart
// {...transformPlotlyJsonToVSBCProps(plotlySchema, colorMap, isDarkTheme)}
// {...commonProps}
// />
// );
// }
throw new Error(`Unsupported chart type :${plotlyInput.data[0]?.type}`);
case 'scatter':
if (plotlyInput.data[0].mode === 'markers') {
throw new Error(`Unsupported chart - type :${plotlyInput.data[0]?.type}, mode: ${plotlyInput.data[0]?.mode}`);
}
const isAreaChart = plotlyInput.data.some(
(series: PlotData) => series.fill === 'tonexty' || series.fill === 'tozeroy',
);
const renderChartJsx = (chartProps: LineChartProps /*| IAreaChartProps*/) => {
// if (isAreaChart) {
// return <AreaChart {...chartProps} />;
// }
return <LineChart {...chartProps} />;
};
return checkAndRenderChart(renderChartJsx, isAreaChart);
case 'heatmap':
// return <HeatMapChart {...transformPlotlyJsonToHeatmapProps(plotlySchema)} {...commonProps} legendProps={{}} />;
throw new Error(`Unsupported chart type :${plotlyInput.data[0]?.type}`);
case 'sankey':
// return (
// <SankeyChart {...transformPlotlyJsonToSankeyProps(plotlySchema, colorMap, isDarkTheme)} {...commonProps} />
// );
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lets delete the commented out code.

throw new Error(`Unsupported chart type :${plotlyInput.data[0]?.type}`);
case 'indicator':
case 'gauge':
// if (plotlyInput.data?.[0]?.mode?.includes('gauge') || plotlyInput.data?.[0]?.type === 'gauge') {
// return (
// <GaugeChart {...transformPlotlyJsonToGaugeProps(plotlySchema, colorMap, isDarkTheme)} {...commonProps} />
// );
// }
throw new Error(`Unsupported chart - type: ${plotlyInput.data[0]?.type}, mode: ${plotlyInput.data[0]?.mode}`);
case 'histogram':
return (
<VerticalBarChart {...transformPlotlyJsonToVBCProps(plotlySchema, colorMap, isDarkTheme)} {...commonProps} />
);
default:
const xValues = (plotlyInput.data[0] as PlotData).x;
const yValues = (plotlyInput.data[0] as PlotData).y;
if (xValues && yValues && xValues.length > 0 && yValues.length > 0) {
const renderLineChartJsx = (chartProps: LineChartProps) => {
return <LineChart {...chartProps} />;
};
return checkAndRenderChart(renderLineChartJsx);
}
throw new Error(`Unsupported chart type :${plotlyInput.data[0]?.type}`);
}
});
DeclarativeChart.displayName = 'DeclarativeChart';
Loading
Oops, something went wrong.
Loading
Oops, something went wrong.