UNPKG

@bluecateng/pelagos-charts

Version:
94 lines 3.13 kB
import { useCallback } from 'react'; import PropTypes from 'prop-types'; import identity from 'lodash-es/identity'; import { useRandomId } from '@bluecateng/pelagos'; import { colorPropType } from './ChartPropTypes'; import getDefaultClass from './getDefaultClass'; import getColorClass from './getColorClass'; import getColorVariant from './getColorVariant'; import './Chart.less'; import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; const Legend = ({ id, className, groups, formatter = identity, direction = 'horizontal', clickable, selected, color, getBgClass = getDefaultClass, onClick, onChange }) => { id = useRandomId(id); const { groupCount: colorGroupCount, option: colorOption } = { groupCount: null, option: 1, ...(color == null ? void 0 : color.pairing) }; const colorVariant = getColorVariant(colorGroupCount, groups.length); const someSelected = selected && selected.length !== 0 && selected.length !== groups.length; const handleKeyDown = useCallback(event => { if (event.key === ' ') { event.preventDefault(); event.target.click(); } }, []); const handleClick = useCallback(event => { const li = event.target.closest('li'); if (li) { li.firstChild.focus(); const group = li.dataset.group; if (onClick) { onClick(group, +li.dataset.index); } if (onChange) { onChange(selected.includes(group) ? selected.filter(g => g !== group) : selected.length === groups.length - 1 ? [] : [...selected, group]); } } }, [groups.length, onChange, onClick, selected]); return /*#__PURE__*/_jsx("ul", { id: id, className: `Chart Chart__legend ${direction}${clickable ? ' clickable' : ''}${someSelected ? ' some-selected' : ''}${className ? ` ${className}` : ''}`, "aria-label": /* TODO translate */`Data groups`, onKeyDown: clickable ? handleKeyDown : null, onClick: clickable ? handleClick : null, children: groups.map((group, index) => { const labelId = `${id}-${index}`; const checked = !selected || selected.length === 0 || selected.includes(group); return /*#__PURE__*/_jsxs("li", { "data-group": group, "data-index": index, children: [/*#__PURE__*/_jsx("div", { className: `Chart__legendCheck ${checked ? getBgClass(group, null, null, getColorClass('bg', colorVariant, colorOption, index)) : ''}`, tabIndex: clickable ? 0 : -1, role: "checkbox", "aria-checked": checked, "aria-labelledby": labelId }), /*#__PURE__*/_jsx("p", { id: labelId, "aria-hidden": true, children: formatter(group) })] }, group); }) }); }; Legend.propTypes = { id: PropTypes.string, className: PropTypes.string, groups: PropTypes.array, formatter: PropTypes.func, direction: PropTypes.oneOf(['horizontal', 'vertical']), clickable: PropTypes.bool, selected: PropTypes.array, color: colorPropType, getBgClass: PropTypes.func, onClick: PropTypes.func, onChange: PropTypes.func }; export default Legend;