add animations

This commit is contained in:
Nate Kelley 2025-04-02 16:45:16 -06:00
parent 26db7bb1df
commit 526f5f6d14
No known key found for this signature in database
GPG Key ID: FD90372AB8D98B4F
3 changed files with 20 additions and 12 deletions

View File

@ -1,7 +1,9 @@
import { AnimationOptions, AnimationSpec } from 'chart.js';
export const barDelayAnimation = (props?: { dataDelay?: number; datasetDelay?: number }) => {
const { dataDelay = 200, datasetDelay = 100 } = props || {};
const MAX_DELAY = 1200;
export const barDelayAnimation = (props?: { maxDelay?: number }) => {
const { maxDelay = MAX_DELAY } = props || {};
let delayed = false;
return {
onComplete: () => {
@ -9,13 +11,20 @@ export const barDelayAnimation = (props?: { dataDelay?: number; datasetDelay?: n
},
delay: (context) => {
let delay = 0;
const dataIndex = context.dataIndex;
const datasetIndex = context.datasetIndex;
const numberOfDatasets = context.chart.data.datasets.length;
const numberOfDataPoints = context.chart.data.datasets[context.datasetIndex].data.length;
const numberOfDataPoints = context.chart.data.datasets[datasetIndex]?.data.length || 1;
if (context.type === 'data' && context.mode === 'default' && !delayed) {
delay = context.dataIndex * dataDelay + context.datasetIndex * datasetDelay;
// Ensure the maximum delay is 1000ms
delay = Math.min(delay, 1000);
// Calculate a scaling factor to distribute delays evenly, with max total delay of 1500ms
const totalSegments = numberOfDatasets * numberOfDataPoints - 1; // -1 because first element has 0 delay
const scalingFactor = totalSegments > 0 ? maxDelay / totalSegments : 0;
// Calculate position in overall sequence (dataset index * points per dataset + datapoint index)
const sequencePosition = datasetIndex * numberOfDataPoints + dataIndex;
delay = sequencePosition * scalingFactor;
}
return delay;
}

View File

@ -23,7 +23,6 @@ import {
LINE_DECIMATION_THRESHOLD,
TOOLTIP_THRESHOLD
} from '../../../config';
import { barDelayAnimation } from '../../core/animations/barDelayAnimation';
import { useAnimations } from './useAnimations';
interface UseOptionsProps {
@ -202,7 +201,6 @@ export const useOptions = ({
return {
indexAxis: isHorizontalBar ? 'y' : 'x',
animation,
backgroundColor: colors,
borderColor: colors,
scales,
@ -220,10 +218,11 @@ export const useOptions = ({
samples: LINE_DECIMATION_SAMPLES
}
},
animation,
...chartOptions
} satisfies ChartProps<ChartJSChartType>['options'];
}, [
animate,
animation,
colors,
scales,
interaction,
@ -235,8 +234,7 @@ export const useOptions = ({
isHorizontalBar,
goalLinesAnnotations,
trendlineAnnotations,
tooltipOptions,
animate
tooltipOptions
]);
return options;

View File

@ -1 +1,2 @@
https://andrew-dev-p.github.io/chartjs-showcase/drill-down-bar.html
https://github.com/Pecacheu/chartjs-filter-plugin