umami/src/components/metrics/MetricCard.tsx

63 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-03-10 04:42:55 +00:00
import classNames from 'classnames';
2023-10-12 07:03:10 +00:00
import { useSpring, animated } from '@react-spring/web';
import { formatNumber } from 'lib/format';
2024-05-27 00:26:15 +00:00
import ChangeLabel from 'components/metrics/ChangeLabel';
import styles from './MetricCard.module.css';
2023-12-03 11:07:03 +00:00
export interface MetricCardProps {
value: number;
previousValue?: number;
2023-12-03 11:07:03 +00:00
change?: number;
label?: string;
2023-12-03 11:07:03 +00:00
reverseColors?: boolean;
2024-05-27 04:30:03 +00:00
formatValue?: typeof formatNumber;
showLabel?: boolean;
showChange?: boolean;
showPrevious?: boolean;
2023-12-03 11:07:03 +00:00
className?: string;
}
2023-04-21 15:00:42 +00:00
export const MetricCard = ({
value = 0,
change = 0,
label,
reverseColors = false,
2024-05-27 04:30:03 +00:00
formatValue = formatNumber,
showLabel = true,
2024-05-23 07:58:31 +00:00
showChange = false,
showPrevious = false,
2023-04-10 03:22:28 +00:00
className,
2023-12-03 11:07:03 +00:00
}: MetricCardProps) => {
2024-05-27 04:30:03 +00:00
const diff = value - change;
const pct = ((value - diff) / diff) * 100;
2020-09-01 04:11:53 +00:00
const props = useSpring({ x: Number(value) || 0, from: { x: 0 } });
2024-05-27 04:30:03 +00:00
const changeProps = useSpring({ x: Number(pct) || 0, from: { x: 0 } });
const prevProps = useSpring({ x: Number(diff) || 0, from: { x: 0 } });
2020-07-30 03:09:41 +00:00
return (
<div className={classNames(styles.card, className, showPrevious && styles.compare)}>
{showLabel && <div className={styles.label}>{label}</div>}
2024-06-21 06:26:36 +00:00
<animated.div className={styles.value} title={value?.toString()}>
2024-05-27 04:30:03 +00:00
{props?.x?.to(x => formatValue(x))}
2024-05-22 04:15:31 +00:00
</animated.div>
{showChange && (
2024-05-28 04:23:06 +00:00
<ChangeLabel
className={styles.change}
value={change}
title={formatValue(change)}
reverseColors={reverseColors}
>
<animated.span>{changeProps?.x?.to(x => `${Math.abs(~~x)}%`)}</animated.span>
2024-05-27 00:26:15 +00:00
</ChangeLabel>
)}
{showPrevious && (
2024-05-28 04:23:06 +00:00
<animated.div className={classNames(styles.value, styles.prev)} title={diff.toString()}>
2024-05-27 04:30:03 +00:00
{prevProps?.x?.to(x => formatValue(x))}
</animated.div>
)}
2020-07-30 03:09:41 +00:00
</div>
);
};
export default MetricCard;