@mui/x-charts
Version:
The community edition of MUI X Charts components.
347 lines (343 loc) • 11.8 kB
JavaScript
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
const _excluded = ["scale", "tickNumber", "reverse"];
import * as React from 'react';
import PropTypes from 'prop-types';
import useSlotProps from '@mui/utils/useSlotProps';
import composeClasses from '@mui/utils/composeClasses';
import { useThemeProps, useTheme, styled } from '@mui/material/styles';
import { useRtl } from '@mui/system/RtlProvider';
import { useIsHydrated } from "../hooks/useIsHydrated.js";
import { getStringSize } from "../internals/domUtils.js";
import { useTicks } from "../hooks/useTicks.js";
import { getAxisUtilityClass } from "../ChartsAxis/axisClasses.js";
import { AxisRoot } from "../internals/components/AxisSharedComponents.js";
import { ChartsText } from "../ChartsText/index.js";
import { useMounted } from "../hooks/useMounted.js";
import { useDrawingArea } from "../hooks/useDrawingArea.js";
import { isInfinity } from "../internals/isInfinity.js";
import { isBandScale } from "../internals/isBandScale.js";
import { useChartContext } from "../context/ChartProvider/useChartContext.js";
import { useXAxes } from "../hooks/useAxis.js";
import { getDefaultBaseline, getDefaultTextAnchor } from "../ChartsText/defaultTextPlacement.js";
import { invertTextAnchor } from "../internals/invertTextAnchor.js";
import { shortenLabels } from "./shortenLabels.js";
import { getVisibleLabels } from "./getVisibleLabels.js";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const useUtilityClasses = ownerState => {
const {
classes,
position,
id
} = ownerState;
const slots = {
root: ['root', 'directionX', position, `id-${id}`],
line: ['line'],
tickContainer: ['tickContainer'],
tick: ['tick'],
tickLabel: ['tickLabel'],
label: ['label']
};
return composeClasses(slots, getAxisUtilityClass, classes);
};
/* Gap between a tick and its label. */
const TICK_LABEL_GAP = 3;
/* Gap between the axis label and tick labels. */
const AXIS_LABEL_TICK_LABEL_GAP = 4;
const XAxisRoot = styled(AxisRoot, {
name: 'MuiChartsXAxis',
slot: 'Root'
})({});
const defaultProps = {
disableLine: false,
disableTicks: false,
tickSize: 6,
tickLabelMinGap: 4
};
/**
* Demos:
*
* - [Axis](https://mui.com/x/react-charts/axis/)
*
* API:
*
* - [ChartsXAxis API](https://mui.com/x/api/charts/charts-x-axis/)
*/
function ChartsXAxis(inProps) {
const {
xAxis,
xAxisIds
} = useXAxes();
const _xAxis = xAxis[inProps.axisId ?? xAxisIds[0]],
{
scale: xScale,
tickNumber,
reverse
} = _xAxis,
settings = _objectWithoutPropertiesLoose(_xAxis, _excluded);
const isMounted = useMounted();
const themedProps = useThemeProps({
props: _extends({}, settings, inProps),
name: 'MuiChartsXAxis'
});
const defaultizedProps = _extends({}, defaultProps, themedProps);
const {
position,
disableLine,
disableTicks,
tickLabelStyle,
label,
labelStyle,
tickSize: tickSizeProp,
valueFormatter,
slots,
slotProps,
tickInterval,
tickLabelInterval,
tickPlacement,
tickLabelPlacement,
tickLabelMinGap,
sx,
offset,
height: axisHeight
} = defaultizedProps;
const theme = useTheme();
const isRtl = useRtl();
const classes = useUtilityClasses(defaultizedProps);
const drawingArea = useDrawingArea();
const {
left,
top,
width,
height
} = drawingArea;
const {
instance
} = useChartContext();
const isHydrated = useIsHydrated();
const tickSize = disableTicks ? 4 : tickSizeProp;
const positionSign = position === 'bottom' ? 1 : -1;
const Line = slots?.axisLine ?? 'line';
const Tick = slots?.axisTick ?? 'line';
const TickLabel = slots?.axisTickLabel ?? ChartsText;
const Label = slots?.axisLabel ?? ChartsText;
const defaultTextAnchor = getDefaultTextAnchor((position === 'bottom' ? 0 : 180) - (tickLabelStyle?.angle ?? 0));
const defaultDominantBaseline = getDefaultBaseline((position === 'bottom' ? 0 : 180) - (tickLabelStyle?.angle ?? 0));
const axisTickLabelProps = useSlotProps({
elementType: TickLabel,
externalSlotProps: slotProps?.axisTickLabel,
additionalProps: {
style: _extends({}, theme.typography.caption, {
fontSize: 12,
lineHeight: 1.25,
textAnchor: isRtl ? invertTextAnchor(defaultTextAnchor) : defaultTextAnchor,
dominantBaseline: defaultDominantBaseline
}, tickLabelStyle)
},
className: classes.tickLabel,
ownerState: {}
});
const xTicks = useTicks({
scale: xScale,
tickNumber,
valueFormatter,
tickInterval,
tickPlacement,
tickLabelPlacement,
direction: 'x'
});
const visibleLabels = getVisibleLabels(xTicks, {
tickLabelStyle: axisTickLabelProps.style,
tickLabelInterval,
tickLabelMinGap,
reverse,
isMounted,
isXInside: instance.isXInside
});
const axisLabelProps = useSlotProps({
elementType: Label,
externalSlotProps: slotProps?.axisLabel,
additionalProps: {
style: _extends({}, theme.typography.body1, {
lineHeight: 1,
fontSize: 14,
textAnchor: 'middle',
dominantBaseline: position === 'bottom' ? 'text-after-edge' : 'text-before-edge'
}, labelStyle)
},
ownerState: {}
});
const domain = xScale.domain();
const ordinalAxis = isBandScale(xScale);
// Skip axis rendering if no data is available
// - The domain is an empty array for band/point scales.
// - The domains contains Infinity for continuous scales.
// - The position is set to 'none'.
if (ordinalAxis && domain.length === 0 || !ordinalAxis && domain.some(isInfinity) || position === 'none') {
return null;
}
const labelHeight = label ? getStringSize(label, axisLabelProps.style).height : 0;
const labelRefPoint = {
x: left + width / 2,
y: positionSign * axisHeight
};
/* If there's an axis title, the tick labels have less space to render */
const tickLabelsMaxHeight = Math.max(0, axisHeight - (label ? labelHeight + AXIS_LABEL_TICK_LABEL_GAP : 0) - tickSize - TICK_LABEL_GAP);
const tickLabels = isHydrated ? shortenLabels(visibleLabels, drawingArea, tickLabelsMaxHeight, isRtl, axisTickLabelProps.style) : new Map(Array.from(visibleLabels).map(item => [item, item.formattedValue]));
return /*#__PURE__*/_jsxs(XAxisRoot, {
transform: `translate(0, ${position === 'bottom' ? top + height + offset : top - offset})`,
className: classes.root,
sx: sx,
children: [!disableLine && /*#__PURE__*/_jsx(Line, _extends({
x1: left,
x2: left + width,
className: classes.line
}, slotProps?.axisLine)), xTicks.map((item, index) => {
const {
offset: tickOffset,
labelOffset
} = item;
const xTickLabel = labelOffset ?? 0;
const yTickLabel = positionSign * (tickSize + TICK_LABEL_GAP);
const showTick = instance.isXInside(tickOffset);
const tickLabel = tickLabels.get(item);
const showTickLabel = visibleLabels.has(item);
return /*#__PURE__*/_jsxs("g", {
transform: `translate(${tickOffset}, 0)`,
className: classes.tickContainer,
children: [!disableTicks && showTick && /*#__PURE__*/_jsx(Tick, _extends({
y2: positionSign * tickSize,
className: classes.tick
}, slotProps?.axisTick)), tickLabel !== undefined && showTickLabel && /*#__PURE__*/_jsx(TickLabel, _extends({
x: xTickLabel,
y: yTickLabel
}, axisTickLabelProps, {
text: tickLabel
}))]
}, index);
}), label && /*#__PURE__*/_jsx("g", {
className: classes.label,
children: /*#__PURE__*/_jsx(Label, _extends({}, labelRefPoint, axisLabelProps, {
text: label
}))
})]
});
}
process.env.NODE_ENV !== "production" ? ChartsXAxis.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the TypeScript types and run "pnpm proptypes" |
// ----------------------------------------------------------------------
axis: PropTypes.oneOf(['x']),
/**
* The id of the axis to render.
* If undefined, it will be the first defined axis.
*/
axisId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* If true, the axis line is disabled.
* @default false
*/
disableLine: PropTypes.bool,
/**
* If true, the ticks are disabled.
* @default false
*/
disableTicks: PropTypes.bool,
/**
* The fill color of the axis text.
* @default 'currentColor'
*/
fill: PropTypes.string,
/**
* The label of the axis.
*/
label: PropTypes.string,
/**
* The style applied to the axis label.
*/
labelStyle: PropTypes.object,
/**
* The props used for each component slot.
* @default {}
*/
slotProps: PropTypes.object,
/**
* Overridable component slots.
* @default {}
*/
slots: PropTypes.object,
/**
* The stroke color of the axis line.
* @default 'currentColor'
*/
stroke: PropTypes.string,
sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),
/**
* Defines which ticks are displayed.
* Its value can be:
* - 'auto' In such case the ticks are computed based on axis scale and other parameters.
* - a filtering function of the form `(value, index) => boolean` which is available only if the axis has "point" scale.
* - an array containing the values where ticks should be displayed.
* @see See {@link https://mui.com/x/react-charts/axis/#fixed-tick-positions}
* @default 'auto'
*/
tickInterval: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.array, PropTypes.func]),
/**
* Defines which ticks get its label displayed. Its value can be:
* - 'auto' In such case, labels are displayed if they do not overlap with the previous one.
* - a filtering function of the form (value, index) => boolean. Warning: the index is tick index, not data ones.
* @default 'auto'
*/
tickLabelInterval: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.func]),
/**
* The minimum gap in pixels between two tick labels.
* If two tick labels are closer than this minimum gap, one of them will be hidden.
* @default 4
*/
tickLabelMinGap: PropTypes.number,
/**
* The placement of ticks label. Can be the middle of the band, or the tick position.
* Only used if scale is 'band'.
* @default 'middle'
*/
tickLabelPlacement: PropTypes.oneOf(['middle', 'tick']),
/**
* The style applied to ticks text.
*/
tickLabelStyle: PropTypes.object,
/**
* Maximal step between two ticks.
* When using time data, the value is assumed to be in ms.
* Not supported by categorical axis (band, points).
*/
tickMaxStep: PropTypes.number,
/**
* Minimal step between two ticks.
* When using time data, the value is assumed to be in ms.
* Not supported by categorical axis (band, points).
*/
tickMinStep: PropTypes.number,
/**
* The number of ticks. This number is not guaranteed.
* Not supported by categorical axis (band, points).
*/
tickNumber: PropTypes.number,
/**
* The placement of ticks in regard to the band interval.
* Only used if scale is 'band'.
* @default 'extremities'
*/
tickPlacement: PropTypes.oneOf(['end', 'extremities', 'middle', 'start']),
/**
* The size of the ticks.
* @default 6
*/
tickSize: PropTypes.number
} : void 0;
export { ChartsXAxis };