umami/components/RankingsChart.js

94 lines
2.4 KiB
JavaScript
Raw Normal View History

2020-08-01 04:05:14 +02:00
import React, { useState, useEffect, useMemo } from 'react';
import { useSpring, animated } from 'react-spring';
import classNames from 'classnames';
import { get } from 'lib/web';
2020-08-01 12:34:56 +02:00
import { percentFilter } from 'lib/filters';
2020-08-01 04:05:14 +02:00
import styles from './RankingsChart.module.css';
export default function RankingsChart({
title,
websiteId,
startDate,
endDate,
type,
2020-08-01 05:37:29 +02:00
heading,
2020-08-01 04:05:14 +02:00
className,
2020-08-01 05:37:29 +02:00
dataFilter,
animate = true,
2020-08-01 12:34:56 +02:00
onDataLoad = () => {},
2020-08-01 04:05:14 +02:00
}) {
const [data, setData] = useState();
2020-08-01 06:56:25 +02:00
const rankings = useMemo(() => {
if (data) {
return (dataFilter ? dataFilter(data) : data).filter((e, i) => i < 10);
}
return [];
}, [data]);
2020-08-01 04:05:14 +02:00
async function loadData() {
2020-08-01 12:34:56 +02:00
const data = await get(`/api/website/${websiteId}/rankings`, {
start_at: +startDate,
end_at: +endDate,
type,
});
const updated = percentFilter(data);
setData(updated);
onDataLoad(updated);
2020-08-01 04:05:14 +02:00
}
useEffect(() => {
if (websiteId) {
loadData();
}
}, [websiteId, startDate, endDate, type]);
if (!data) {
return null;
2020-08-01 04:05:14 +02:00
}
return (
<div className={classNames(styles.container, className)}>
2020-08-01 05:37:29 +02:00
<div className={styles.header}>
<div className={styles.title}>{title}</div>
<div className={styles.heading}>{heading}</div>
</div>
{rankings.map(({ x, y, z }) =>
animate ? (
<AnimatedRow key={x} label={x} value={y} percent={z} />
) : (
<Row key={x} label={x} value={y} percent={z} />
),
)}
2020-08-01 04:05:14 +02:00
</div>
);
}
const Row = ({ label, value, percent }) => (
<div className={styles.row}>
<div className={styles.label}>{label}</div>
<div className={styles.value}>{value.toFixed(0)}</div>
<div className={styles.percent}>
<div>{`${percent.toFixed(0)}%`}</div>
<div className={styles.bar} style={{ width: percent }} />
</div>
</div>
);
const AnimatedRow = ({ label, value, percent }) => {
2020-08-02 06:20:52 +02:00
const props = useSpring({ width: percent, y: value, from: { width: 0, y: 0 } });
2020-08-01 04:05:14 +02:00
return (
<div className={styles.row}>
<div className={styles.label}>{label}</div>
2020-08-02 06:20:52 +02:00
<animated.div className={styles.value}>{props.y.interpolate(n => n.toFixed(0))}</animated.div>
2020-08-01 05:37:29 +02:00
<div className={styles.percent}>
2020-08-01 12:34:56 +02:00
<animated.div>{props.width.interpolate(n => `${n.toFixed(0)}%`)}</animated.div>
2020-08-02 06:20:52 +02:00
<animated.div className={styles.bar} style={{ width: props.width }} />
2020-08-01 05:37:29 +02:00
</div>
2020-08-01 04:05:14 +02:00
</div>
);
};