@mui/x-charts
Version:
The community edition of MUI X Charts components.
305 lines (302 loc) • 9.96 kB
JavaScript
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
const _excluded = ["skipAnimation", "onItemClick", "borderRadius", "barLabel"];
import * as React from 'react';
import PropTypes from 'prop-types';
import { styled } from '@mui/material/styles';
import { barElementClasses } from "./barElementClasses.js";
import { BarElement } from "./BarElement.js";
import getColor from "./seriesConfig/getColor.js";
import { useChartId, useDrawingArea, useXAxes, useYAxes } from "../hooks/index.js";
import { BarClipPath } from "./BarClipPath.js";
import { BarLabelPlot } from "./BarLabel/BarLabelPlot.js";
import { checkScaleErrors } from "./checkScaleErrors.js";
import { useBarSeriesContext } from "../hooks/useBarSeries.js";
import { useSkipAnimation } from "../hooks/useSkipAnimation.js";
import { useInternalIsZoomInteracting } from "../internals/plugins/featurePlugins/useChartCartesianAxis/useInternalIsZoomInteracting.js";
/**
* Solution of the equations
* W = barWidth * N + offset * (N-1)
* offset / (offset + barWidth) = r
* @param bandWidth The width available to place bars.
* @param numberOfGroups The number of bars to place in that space.
* @param gapRatio The ratio of the gap between bars over the bar width.
* @returns The bar width and the offset between bars.
*/
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
function getBandSize({
bandWidth: W,
numberOfGroups: N,
gapRatio: r
}) {
if (r === 0) {
return {
barWidth: W / N,
offset: 0
};
}
const barWidth = W / (N + (N - 1) * r);
const offset = r * barWidth;
return {
barWidth,
offset
};
}
const useAggregatedData = () => {
const seriesData = useBarSeriesContext() ?? {
series: {},
stackingGroups: [],
seriesOrder: []
};
const drawingArea = useDrawingArea();
const chartId = useChartId();
const {
series,
stackingGroups
} = seriesData;
const {
xAxis,
xAxisIds
} = useXAxes();
const {
yAxis,
yAxisIds
} = useYAxes();
const defaultXAxisId = xAxisIds[0];
const defaultYAxisId = yAxisIds[0];
const masks = {};
const data = stackingGroups.flatMap(({
ids: groupIds
}, groupIndex) => {
const xMin = drawingArea.left;
const xMax = drawingArea.left + drawingArea.width;
const yMin = drawingArea.top;
const yMax = drawingArea.top + drawingArea.height;
return groupIds.flatMap(seriesId => {
const xAxisId = series[seriesId].xAxisId ?? defaultXAxisId;
const yAxisId = series[seriesId].yAxisId ?? defaultYAxisId;
const xAxisConfig = xAxis[xAxisId];
const yAxisConfig = yAxis[yAxisId];
const verticalLayout = series[seriesId].layout === 'vertical';
checkScaleErrors(verticalLayout, seriesId, series[seriesId], xAxisId, xAxis, yAxisId, yAxis);
const baseScaleConfig = verticalLayout ? xAxisConfig : yAxisConfig;
const xScale = xAxisConfig.scale;
const yScale = yAxisConfig.scale;
const colorGetter = getColor(series[seriesId], xAxis[xAxisId], yAxis[yAxisId]);
const bandWidth = baseScaleConfig.scale.bandwidth();
const {
barWidth,
offset
} = getBandSize({
bandWidth,
numberOfGroups: stackingGroups.length,
gapRatio: baseScaleConfig.barGapRatio
});
const barOffset = groupIndex * (barWidth + offset);
const {
stackedData,
data: currentSeriesData,
layout
} = series[seriesId];
return baseScaleConfig.data.map((baseValue, dataIndex) => {
if (currentSeriesData[dataIndex] == null) {
return null;
}
const values = stackedData[dataIndex];
const valueCoordinates = values.map(v => verticalLayout ? yScale(v) : xScale(v));
const minValueCoord = Math.round(Math.min(...valueCoordinates));
const maxValueCoord = Math.round(Math.max(...valueCoordinates));
const stackId = series[seriesId].stack;
const result = {
seriesId,
dataIndex,
layout,
x: verticalLayout ? xScale(baseValue) + barOffset : minValueCoord,
y: verticalLayout ? minValueCoord : yScale(baseValue) + barOffset,
xOrigin: xScale(0) ?? 0,
yOrigin: yScale(0) ?? 0,
height: verticalLayout ? maxValueCoord - minValueCoord : barWidth,
width: verticalLayout ? barWidth : maxValueCoord - minValueCoord,
color: colorGetter(dataIndex),
value: currentSeriesData[dataIndex],
maskId: `${chartId}_${stackId || seriesId}_${groupIndex}_${dataIndex}`
};
if (result.x > xMax || result.x + result.width < xMin || result.y > yMax || result.y + result.height < yMin) {
return null;
}
if (!masks[result.maskId]) {
masks[result.maskId] = {
id: result.maskId,
width: 0,
height: 0,
hasNegative: false,
hasPositive: false,
layout: result.layout,
xOrigin: xScale(0),
yOrigin: yScale(0),
x: 0,
y: 0
};
}
const mask = masks[result.maskId];
mask.width = result.layout === 'vertical' ? result.width : mask.width + result.width;
mask.height = result.layout === 'vertical' ? mask.height + result.height : result.height;
mask.x = Math.min(mask.x === 0 ? Infinity : mask.x, result.x);
mask.y = Math.min(mask.y === 0 ? Infinity : mask.y, result.y);
mask.hasNegative = mask.hasNegative || (result.value ?? 0) < 0;
mask.hasPositive = mask.hasPositive || (result.value ?? 0) > 0;
return result;
}).filter(rectangle => rectangle !== null);
});
});
return {
completedData: data,
masksData: Object.values(masks)
};
};
const BarPlotRoot = styled('g', {
name: 'MuiBarPlot',
slot: 'Root'
})({
[`& .${barElementClasses.root}`]: {
transition: 'opacity 0.2s ease-in, fill 0.2s ease-in'
}
});
/**
* Demos:
*
* - [Bars](https://mui.com/x/react-charts/bars/)
* - [Bar demonstration](https://mui.com/x/react-charts/bar-demo/)
* - [Stacking](https://mui.com/x/react-charts/stacking/)
*
* API:
*
* - [BarPlot API](https://mui.com/x/api/charts/bar-plot/)
*/
function BarPlot(props) {
const {
completedData,
masksData
} = useAggregatedData();
const {
skipAnimation: inSkipAnimation,
onItemClick,
borderRadius,
barLabel
} = props,
other = _objectWithoutPropertiesLoose(props, _excluded);
const isZoomInteracting = useInternalIsZoomInteracting();
const skipAnimation = useSkipAnimation(isZoomInteracting || inSkipAnimation);
const withoutBorderRadius = !borderRadius || borderRadius <= 0;
return /*#__PURE__*/_jsxs(BarPlotRoot, {
children: [!withoutBorderRadius && masksData.map(({
id,
x,
y,
width,
height,
hasPositive,
hasNegative,
layout
}) => {
return /*#__PURE__*/_jsx(BarClipPath, {
maskId: id,
borderRadius: borderRadius,
hasNegative: hasNegative,
hasPositive: hasPositive,
layout: layout,
x: x,
y: y,
width: width,
height: height,
skipAnimation: skipAnimation ?? false
}, id);
}), completedData.map(({
seriesId,
dataIndex,
color,
maskId,
layout,
x,
xOrigin,
y,
yOrigin,
width,
height
}) => {
const barElement = /*#__PURE__*/_jsx(BarElement, _extends({
id: seriesId,
dataIndex: dataIndex,
color: color,
skipAnimation: skipAnimation ?? false,
layout: layout ?? 'vertical',
x: x,
xOrigin: xOrigin,
y: y,
yOrigin: yOrigin,
width: width,
height: height
}, other, {
onClick: onItemClick && (event => {
onItemClick(event, {
type: 'bar',
seriesId,
dataIndex
});
})
}), `${seriesId}-${dataIndex}`);
if (withoutBorderRadius) {
return barElement;
}
return /*#__PURE__*/_jsx("g", {
clipPath: `url(#${maskId})`,
children: barElement
}, `${seriesId}-${dataIndex}`);
}), barLabel && /*#__PURE__*/_jsx(BarLabelPlot, _extends({
bars: completedData,
skipAnimation: skipAnimation,
barLabel: barLabel
}, other))]
});
}
process.env.NODE_ENV !== "production" ? BarPlot.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the TypeScript types and run "pnpm proptypes" |
// ----------------------------------------------------------------------
/**
* If provided, the function will be used to format the label of the bar.
* It can be set to 'value' to display the current value.
* @param {BarItem} item The item to format.
* @param {BarLabelContext} context data about the bar.
* @returns {string} The formatted label.
*/
barLabel: PropTypes.oneOfType([PropTypes.oneOf(['value']), PropTypes.func]),
/**
* Defines the border radius of the bar element.
*/
borderRadius: PropTypes.number,
/**
* Callback fired when a bar item is clicked.
* @param {React.MouseEvent<SVGElement, MouseEvent>} event The event source of the callback.
* @param {BarItemIdentifier} barItemIdentifier The bar item identifier.
*/
onItemClick: PropTypes.func,
/**
* If `true`, animations are skipped.
* @default undefined
*/
skipAnimation: PropTypes.bool,
/**
* The props used for each component slot.
* @default {}
*/
slotProps: PropTypes.object,
/**
* Overridable component slots.
* @default {}
*/
slots: PropTypes.object
} : void 0;
export { BarPlot };