umami/components/metrics/Legend.js

53 lines
1.3 KiB
JavaScript
Raw Normal View History

2023-04-19 20:41:31 +02:00
import { useEffect } from 'react';
import { StatusLight } from 'react-basics';
2022-01-14 09:39:27 +01:00
import { colord } from 'colord';
2020-10-15 07:09:00 +02:00
import classNames from 'classnames';
import useLocale from 'hooks/useLocale';
2022-01-06 10:45:53 +01:00
import useForceUpdate from 'hooks/useForceUpdate';
2020-10-15 07:09:00 +02:00
import styles from './Legend.module.css';
2023-04-21 17:00:42 +02:00
export function Legend({ chart }) {
const { locale } = useLocale();
2020-10-15 07:09:00 +02:00
const forceUpdate = useForceUpdate();
2023-04-19 20:41:31 +02:00
const handleClick = index => {
2020-10-15 07:09:00 +02:00
const meta = chart.getDatasetMeta(index);
meta.hidden = meta.hidden === null ? !chart.data.datasets[index].hidden : null;
chart.update();
forceUpdate();
2023-04-19 20:41:31 +02:00
};
useEffect(() => {
forceUpdate();
}, [locale]);
2020-10-15 07:09:00 +02:00
if (!chart?.legend?.legendItems.find(({ text }) => text)) {
return null;
}
return (
<div className={styles.legend}>
2022-01-06 10:45:53 +01:00
{chart.legend.legendItems.map(({ text, fillStyle, datasetIndex, hidden }) => {
2022-01-14 09:39:27 +01:00
const color = colord(fillStyle);
2022-01-06 10:45:53 +01:00
return (
<div
key={text}
className={classNames(styles.label, { [styles.hidden]: hidden })}
onClick={() => handleClick(datasetIndex)}
>
2023-02-02 03:39:54 +01:00
<StatusLight color={color.alpha(color.alpha() + 0.2).toHex()}>
<span className={locale}>{text}</span>
</StatusLight>
2022-01-06 10:45:53 +01:00
</div>
);
})}
2020-10-15 07:09:00 +02:00
</div>
);
}
2023-04-21 17:00:42 +02:00
export default Legend;