umami/src/components/metrics/MetricCard.tsx

69 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-03-10 04:42:55 +00:00
import classNames from 'classnames';
import { Icon, Icons } from 'react-basics';
2023-10-12 07:03:10 +00:00
import { useSpring, animated } from '@react-spring/web';
import { formatNumber } from 'lib/format';
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;
format?: 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,
format = 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) => {
2020-09-01 04:11:53 +00:00
const props = useSpring({ x: Number(value) || 0, from: { x: 0 } });
const changeProps = useSpring({ x: Number(change) || 0, from: { x: 0 } });
const prevProps = useSpring({ x: Number(value - change) || 0, from: { x: 0 } });
const positive = change * (reverseColors ? -1 : 1) >= 0;
const negative = change * (reverseColors ? -1 : 1) < 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-05-22 04:15:31 +00:00
<animated.div className={styles.value} title={props?.x as any}>
{props?.x?.to(x => format(x))}
</animated.div>
{showChange && (
<div
className={classNames(styles.change, {
[styles.positive]: positive,
[styles.negative]: negative,
2024-05-23 07:58:31 +00:00
[styles.hide]: ~~change === 0,
})}
>
2024-05-24 02:35:29 +00:00
<Icon rotate={positive || reverseColors ? -45 : 45} size={showPrevious ? 'md' : 'xs'}>
<Icons.ArrowRight />
</Icon>
<animated.span title={changeProps?.x as any}>
{changeProps?.x?.to(x => format(Math.abs(x)))}
</animated.span>
</div>
)}
{showPrevious && (
<animated.div className={classNames(styles.value, styles.prev)} title={prevProps?.x as any}>
{prevProps?.x?.to(x => format(x))}
</animated.div>
)}
2020-07-30 03:09:41 +00:00
</div>
);
};
export default MetricCard;