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 line animation #12892

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
41 changes: 26 additions & 15 deletions packages/x-charts/src/internals/useAnimatedPath.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,40 @@
import * as React from 'react';
import { interpolateString } from 'd3-interpolate';
import { useSpring, to } from '@react-spring/web';

function usePrevious<T>(value: T) {
const ref = React.useRef<T | null>(null);
React.useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
import { useSpringRef, useSpring, to } from '@react-spring/web';

// Taken from Nivo
export const useAnimatedPath = (path: string, skipAnimation?: boolean) => {
const previousPath = usePrevious(path);
const interpolator = React.useMemo(
() => (previousPath ? interpolateString(previousPath, path) : () => path),
[previousPath, path],
);
const previousPathRef = React.useRef<string | null>(null);
const currentPathRef = React.useRef<string | null>(path);

const api = useSpringRef();

React.useEffect(() => {
if (previousPathRef.current !== path) {
// Only start the animation if the previouse path is different.
// Avoid re-animating if the props is updated with the same value.u
api.start();
}
if (currentPathRef.current !== path) {
previousPathRef.current = currentPathRef.current;
currentPathRef.current = path;
}
}, [api, path]);

const { value } = useSpring({
ref: api,
from: { value: 0 },
to: { value: 1 },
reset: true,
immediate: skipAnimation,
});

return to([value], interpolator);
const interpolation = (t: number) => {
if (previousPathRef.current === null) {
return path;
}
return interpolateString(previousPathRef.current, path)(t);
Copy link
Contributor

Choose a reason for hiding this comment

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

Keeping interpolateString(...) in a useMemo like it was before would be nice, it seems to do a bit of initialization work. If this runs on every frame and there's many charts animating at once, it could run less smoothly.

};

return to([value], interpolation);
};