Skip to content

Commit

Permalink
[charts] Fix LineChart transition stopping before completion (#14366)
Browse files Browse the repository at this point in the history
  • Loading branch information
JCQuintas authored Aug 28, 2024
1 parent 8e82705 commit 97afd65
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 17 deletions.
2 changes: 1 addition & 1 deletion packages/x-charts/src/LineChart/MarkElement.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ function MarkElement(props: MarkElementProps) {
});
const { axis } = React.useContext(InteractionContext);

const position = useSpring({ x, y, immediate: skipAnimation });
const position = useSpring({ to: { x, y }, immediate: skipAnimation });
const ownerState = {
id,
classes: innerClasses,
Expand Down
45 changes: 29 additions & 16 deletions packages/x-charts/src/internals/useAnimatedPath.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,42 @@
import * as React from 'react';
import { interpolateString } from '@mui/x-charts-vendor/d3-interpolate';
import { useSpring, to } from '@react-spring/web';
import { useSpring } from '@react-spring/web';

function usePrevious<T>(value: T) {
const ref = React.useRef<T | null>(null);
React.useEffect(() => {
ref.current = value;
}, [value]);
const ref = React.useRef<{ currentPath: T; previousPath?: T }>({
currentPath: value,
previousPath: undefined,
});
if (ref.current.currentPath !== value) {
ref.current = {
currentPath: value,
previousPath: ref.current.currentPath,
};
}

return ref.current;
}

// Taken from Nivo
export const useAnimatedPath = (path: string, skipAnimation?: boolean) => {
const previousPath = usePrevious(path);
const memoryRef = usePrevious(path);

const interpolator = React.useMemo(
() => (previousPath ? interpolateString(previousPath, path) : () => path),
[previousPath, path],
() =>
memoryRef.previousPath
? interpolateString(memoryRef.previousPath, memoryRef.currentPath)
: () => memoryRef.currentPath,
[memoryRef.currentPath, memoryRef.previousPath],
);

const { value } = useSpring({
from: { value: 0 },
to: { value: 1 },
reset: true,
immediate: skipAnimation,
});
const [{ value }] = useSpring(
{
from: { value: 0 },
to: { value: 1 },
reset: true,
immediate: skipAnimation,
},
[memoryRef.currentPath],
);

return to([value], interpolator);
return value.to(interpolator);
};

0 comments on commit 97afd65

Please sign in to comment.