umami/components/metrics/DataTable.js

106 lines
2.8 KiB
JavaScript
Raw Normal View History

import { useState } from 'react';
import { FixedSizeList } from 'react-window';
import { useSpring, animated, config } from 'react-spring';
import classNames from 'classnames';
import { FormattedMessage } from 'react-intl';
import NoData from 'components/common/NoData';
import { formatNumber, formatLongNumber } from 'lib/format';
import styles from './DataTable.module.css';
export default function DataTable({
2023-02-15 11:27:18 +01:00
data = [],
title,
metric,
className,
renderLabel,
2020-10-13 01:31:51 +02:00
height,
animate = true,
2020-10-11 10:33:26 +02:00
virtualize = false,
showPercentage = true,
}) {
const [format, setFormat] = useState(true);
const formatFunc = format ? formatLongNumber : formatNumber;
const handleSetFormat = () => setFormat(state => !state);
const getRow = row => {
const { x: label, y: value, z: percent } = row;
return (
<AnimatedRow
key={label}
label={
renderLabel
? renderLabel(row)
: label ?? <FormattedMessage id="label.unknown" defaultMessage="Unknown" />
}
value={value}
percent={percent}
2020-10-11 10:33:26 +02:00
animate={animate && !virtualize}
format={formatFunc}
onClick={handleSetFormat}
showPercentage={showPercentage}
/>
);
};
const Row = ({ index, style }) => {
return <div style={style}>{getRow(data[index])}</div>;
};
return (
<div className={classNames(styles.table, className)}>
<div className={styles.header}>
<div className={styles.title}>{title}</div>
<div className={styles.metric} onClick={handleSetFormat}>
{metric}
</div>
</div>
2020-10-13 01:31:51 +02:00
<div className={styles.body} style={{ height }}>
{data?.length === 0 && <NoData />}
2020-10-11 10:33:26 +02:00
{virtualize && data.length > 0 ? (
<FixedSizeList height={height} itemCount={data.length} itemSize={30}>
{Row}
</FixedSizeList>
) : (
data.map(row => getRow(row))
)}
</div>
</div>
);
}
const AnimatedRow = ({
label,
value = 0,
percent,
animate,
format,
onClick,
showPercentage = true,
}) => {
const props = useSpring({
width: percent,
y: value,
from: { width: 0, y: 0 },
config: animate ? config.default : { duration: 0 },
});
return (
<div className={styles.row}>
<div className={styles.label}>{label}</div>
<div className={styles.value} onClick={onClick}>
2023-03-10 00:18:54 +01:00
<animated.div className={styles.value}>{props.y?.to(format)}</animated.div>
</div>
{showPercentage && (
<div className={styles.percent}>
2023-03-10 00:18:54 +01:00
<animated.div className={styles.bar} style={{ width: props.width.to(n => `${n}%`) }} />
<animated.span className={styles.percentValue}>
2023-03-10 00:18:54 +01:00
{props.width.to(n => `${n.toFixed(0)}%`)}
</animated.span>
</div>
)}
</div>
);
};