umami/components/metrics/Legend.js

46 lines
1.2 KiB
JavaScript
Raw Normal View History

2020-10-15 07:09:00 +02:00
import React from 'react';
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 Dot from 'components/common/Dot';
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';
export default function Legend({ chart }) {
const { locale } = useLocale();
2020-10-15 07:09:00 +02:00
const forceUpdate = useForceUpdate();
function handleClick(index) {
const meta = chart.getDatasetMeta(index);
meta.hidden = meta.hidden === null ? !chart.data.datasets[index].hidden : null;
chart.update();
forceUpdate();
}
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)}
>
2022-01-14 09:39:27 +01:00
<Dot color={color.alpha(color.alpha() + 0.2).toHex()} />
2022-01-06 10:45:53 +01:00
<span className={locale}>{text}</span>
</div>
);
})}
2020-10-15 07:09:00 +02:00
</div>
);
}