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

[charts] Fix LineChart not properly animating when hydrating #14355

Merged
merged 14 commits into from
Aug 29, 2024
Merged
26 changes: 20 additions & 6 deletions packages/x-charts/src/LineChart/AnimatedArea.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import * as React from 'react';
import PropTypes from 'prop-types';
import { styled } from '@mui/material/styles';
import { animated, useSpring } from '@react-spring/web';
import { animated, useTransition } from '@react-spring/web';
import { color as d3Color } from '@mui/x-charts-vendor/d3-color';
import { useAnimatedPath } from '../internals/useAnimatedPath';
import { cleanId } from '../internals/cleanId';
import type { AreaElementOwnerState } from './AreaElement';
import { useChartId, useDrawingArea } from '../hooks';
import { useStringInterpolator } from '../internals/useStringInterpolator';

export const AreaElementPath = styled(animated.path, {
name: 'MuiAreaElement',
Expand Down Expand Up @@ -47,11 +47,21 @@ function AnimatedArea(props: AnimatedAreaProps) {
const { left, top, right, bottom, width, height } = useDrawingArea();
const chartId = useChartId();

const path = useAnimatedPath(d, skipAnimation);
const stringInterpolator = useStringInterpolator(d);

const { animatedWidth } = useSpring({
const transitionAppear = useTransition([1], {
from: { animatedWidth: left },
to: { animatedWidth: width + left + right },
enter: { animatedWidth: width + left + right },
leave: { animatedWidth: left },
reset: false,
immediate: skipAnimation,
});

const transitionChange = useTransition([stringInterpolator], {
from: { value: 0 },
to: { value: 1 },
enter: { value: 1 },
reset: false,
immediate: skipAnimation,
});
Expand All @@ -60,10 +70,14 @@ function AnimatedArea(props: AnimatedAreaProps) {
return (
<React.Fragment>
<clipPath id={clipId}>
<animated.rect x={0} y={0} width={animatedWidth} height={top + height + bottom} />
{transitionAppear((style) => (
<animated.rect x={0} y={0} width={style.animatedWidth} height={top + height + bottom} />
))}
</clipPath>
<g clipPath={`url(#${clipId})`}>
<AreaElementPath {...other} ownerState={ownerState} d={path} />
{transitionChange((style, interpolator) => (
<AreaElementPath {...other} ownerState={ownerState} d={style.value.to(interpolator)} />
))}
</g>
</React.Fragment>
);
Expand Down
26 changes: 20 additions & 6 deletions packages/x-charts/src/LineChart/AnimatedLine.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import * as React from 'react';
import PropTypes from 'prop-types';
import { animated, useSpring } from '@react-spring/web';
import { animated, useTransition } from '@react-spring/web';
import { color as d3Color } from '@mui/x-charts-vendor/d3-color';
import { styled } from '@mui/material/styles';
import { useAnimatedPath } from '../internals/useAnimatedPath';
import { cleanId } from '../internals/cleanId';
import type { LineElementOwnerState } from './LineElement';
import { useChartId } from '../hooks/useChartId';
import { useDrawingArea } from '../hooks/useDrawingArea';
import { useStringInterpolator } from '../internals/useStringInterpolator';

export const LineElementPath = styled(animated.path, {
name: 'MuiLineElement',
Expand Down Expand Up @@ -50,11 +50,21 @@ function AnimatedLine(props: AnimatedLineProps) {
const { left, top, bottom, width, height, right } = useDrawingArea();
const chartId = useChartId();

const path = useAnimatedPath(d, skipAnimation);
const stringInterpolator = useStringInterpolator(d);

const { animatedWidth } = useSpring({
const transitionAppear = useTransition([1], {
from: { animatedWidth: left },
to: { animatedWidth: width + left + right },
enter: { animatedWidth: width + left + right },
leave: { animatedWidth: left },
reset: false,
immediate: skipAnimation,
});

const transitionChange = useTransition([stringInterpolator], {
from: { value: 0 },
to: { value: 1 },
enter: { value: 1 },
reset: false,
immediate: skipAnimation,
});
Expand All @@ -63,10 +73,14 @@ function AnimatedLine(props: AnimatedLineProps) {
return (
<React.Fragment>
<clipPath id={clipId}>
<animated.rect x={0} y={0} width={animatedWidth} height={top + height + bottom} />
{transitionAppear((style) => (
<animated.rect x={0} y={0} width={style.animatedWidth} height={top + height + bottom} />
))}
</clipPath>
<g clipPath={`url(#${clipId})`}>
<LineElementPath {...other} ownerState={ownerState} d={path} />
{transitionChange((style, interpolator) => (
<LineElementPath {...other} ownerState={ownerState} d={style.value.to(interpolator)} />
))}
</g>
</React.Fragment>
);
Expand Down
185 changes: 95 additions & 90 deletions packages/x-charts/src/LineChart/AreaPlot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,99 +38,104 @@ const useAggregatedData = () => {
const seriesData = useLineSeries();
const axisData = useCartesianContext();

if (seriesData === undefined) {
return [];
}

const { series, stackingGroups } = seriesData;
const { xAxis, yAxis, xAxisIds, yAxisIds } = axisData;
const defaultXAxisId = xAxisIds[0];
const defaultYAxisId = yAxisIds[0];

return stackingGroups.flatMap(({ ids: groupIds }) => {
return [...groupIds]
.reverse() // Revert stacked area for a more pleasant animation
.map((seriesId) => {
const {
xAxisId: xAxisIdProp,
yAxisId: yAxisIdProp,
xAxisKey = defaultXAxisId,
yAxisKey = defaultYAxisId,
stackedData,
data,
connectNulls,
baseline,
} = series[seriesId];

const xAxisId = xAxisIdProp ?? xAxisKey;
const yAxisId = yAxisIdProp ?? yAxisKey;

const xScale = getValueToPositionMapper(xAxis[xAxisId].scale);
const yScale = yAxis[yAxisId].scale;
const xData = xAxis[xAxisId].data;

const gradientUsed: [AxisId, 'x' | 'y'] | undefined =
(yAxis[yAxisId].colorScale && [yAxisId, 'y']) ||
(xAxis[xAxisId].colorScale && [xAxisId, 'x']) ||
undefined;

if (process.env.NODE_ENV !== 'production') {
if (xData === undefined) {
throw new Error(
`MUI X: ${
xAxisId === DEFAULT_X_AXIS_KEY
? 'The first `xAxis`'
: `The x-axis with id "${xAxisId}"`
} should have data property to be able to display a line plot.`,
);
}
if (xData.length < stackedData.length) {
throw new Error(
`MUI X: The data length of the x axis (${xData.length} items) is lower than the length of series (${stackedData.length} items).`,
);
}
}

const areaPath = d3Area<{
x: any;
y: [number, number];
}>()
.x((d) => xScale(d.x))
.defined((_, i) => connectNulls || data[i] != null)
.y0((d) => {
if (typeof baseline === 'number') {
return yScale(baseline)!;
}
if (baseline === 'max') {
return yScale.range()[1];
// This memo prevents odd line chart behavior when hydrating.
const allData = React.useMemo(() => {
if (seriesData === undefined) {
return [];
}

const { series, stackingGroups } = seriesData;
const { xAxis, yAxis, xAxisIds, yAxisIds } = axisData;
const defaultXAxisId = xAxisIds[0];
const defaultYAxisId = yAxisIds[0];

return stackingGroups.flatMap(({ ids: groupIds }) => {
return [...groupIds]
.reverse() // Revert stacked area for a more pleasant animation
.map((seriesId) => {
const {
xAxisId: xAxisIdProp,
yAxisId: yAxisIdProp,
xAxisKey = defaultXAxisId,
yAxisKey = defaultYAxisId,
stackedData,
data,
connectNulls,
baseline,
} = series[seriesId];

const xAxisId = xAxisIdProp ?? xAxisKey;
const yAxisId = yAxisIdProp ?? yAxisKey;

const xScale = getValueToPositionMapper(xAxis[xAxisId].scale);
const yScale = yAxis[yAxisId].scale;
const xData = xAxis[xAxisId].data;

const gradientUsed: [AxisId, 'x' | 'y'] | undefined =
(yAxis[yAxisId].colorScale && [yAxisId, 'y']) ||
(xAxis[xAxisId].colorScale && [xAxisId, 'x']) ||
undefined;

if (process.env.NODE_ENV !== 'production') {
if (xData === undefined) {
throw new Error(
`MUI X: ${
xAxisId === DEFAULT_X_AXIS_KEY
? 'The first `xAxis`'
: `The x-axis with id "${xAxisId}"`
} should have data property to be able to display a line plot.`,
);
}
if (baseline === 'min') {
return yScale.range()[0];
if (xData.length < stackedData.length) {
throw new Error(
`MUI X: The data length of the x axis (${xData.length} items) is lower than the length of series (${stackedData.length} items).`,
);
}
}

const value = d.y && yScale(d.y[0])!;
if (Number.isNaN(value)) {
return yScale.range()[0];
}
return value;
})
.y1((d) => d.y && yScale(d.y[1])!);

const curve = getCurveFactory(series[seriesId].curve);
const formattedData = xData?.map((x, index) => ({ x, y: stackedData[index] })) ?? [];
const d3Data = connectNulls
? formattedData.filter((_, i) => data[i] != null)
: formattedData;

const d = areaPath.curve(curve)(d3Data) || '';
return {
...series[seriesId],
gradientUsed,
d,
seriesId,
};
});
});
const areaPath = d3Area<{
x: any;
y: [number, number];
}>()
.x((d) => xScale(d.x))
.defined((_, i) => connectNulls || data[i] != null)
.y0((d) => {
if (typeof baseline === 'number') {
return yScale(baseline)!;
}
if (baseline === 'max') {
return yScale.range()[1];
}
if (baseline === 'min') {
return yScale.range()[0];
}

const value = d.y && yScale(d.y[0])!;
if (Number.isNaN(value)) {
return yScale.range()[0];
}
return value;
})
.y1((d) => d.y && yScale(d.y[1])!);

const curve = getCurveFactory(series[seriesId].curve);
const formattedData = xData?.map((x, index) => ({ x, y: stackedData[index] })) ?? [];
const d3Data = connectNulls
? formattedData.filter((_, i) => data[i] != null)
: formattedData;

const d = areaPath.curve(curve)(d3Data) || '';
return {
...series[seriesId],
gradientUsed,
d,
seriesId,
};
});
});
}, [seriesData, axisData]);

return allData;
};

/**
Expand Down
Loading