recharts
Version:
React charts
718 lines (699 loc) • 32.1 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Text = void 0;
exports.getTextBackgroundRect = getTextBackgroundRect;
exports.getTextPathBackgroundGeometry = getTextPathBackgroundGeometry;
exports.getWordsByLines = void 0;
exports.isRenderableText = isRenderableText;
exports.isValidTextAnchor = isValidTextAnchor;
exports.resolveBackgroundPadding = resolveBackgroundPadding;
exports.textDefaultProps = void 0;
var _react = _interopRequireWildcard(require("react"));
var React = _react;
var _clsx = require("../util/clsx");
var _DataUtils = require("../util/DataUtils");
var _Global = require("../util/Global");
var _DOMUtils = require("../util/DOMUtils");
var _ReduceCSSCalc = require("../util/ReduceCSSCalc");
var _svgPropertiesAndEvents = require("../util/svgPropertiesAndEvents");
var _isWellBehavedNumber = require("../util/isWellBehavedNumber");
var _useId = require("../util/useId");
var _useBackwardsCompatibleTheme = require("../theme/useBackwardsCompatibleTheme");
var _resolveDefaultProps = require("../util/resolveDefaultProps");
var _cssStylesToSvgStyles = require("../theme/cssStylesToSvgStyles");
var _pageBackground = require("../theme/pageBackground");
var _labelBackgroundZIndex = require("../zIndex/labelBackgroundZIndex");
var _ZIndexLayer = require("../zIndex/ZIndexLayer");
var _excluded = ["x", "y", "lineHeight", "capHeight", "scaleToFit", "textAnchor", "verticalAnchor", "style", "textPath", "background", "halo"],
_excluded2 = ["angle", "dx", "dy", "className", "breakAll"],
_excluded3 = ["startOffset"],
_excluded4 = ["padding", "className"],
_excluded5 = ["fillOpacity", "stroke", "strokeOpacity", "strokeWidth"];
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
var BREAKING_SPACES = /[ \f\n\r\t\v\u2028\u2029]+/;
/*
* A single lazily-created segmenter instance: constructing Intl.Segmenter is
* measurably more expensive than segmenting with an existing one.
* Availability itself is re-checked on every call so environments without
* Intl.Segmenter (e.g. Firefox before 125) always take the fallback.
*/
var cachedGraphemeSegmenter;
var getGraphemeSegmenter = () => {
var SegmenterImpl = typeof Intl === 'undefined' ? undefined : Intl.Segmenter;
if (typeof SegmenterImpl !== 'function') {
return null;
}
if (cachedGraphemeSegmenter === undefined) {
cachedGraphemeSegmenter = new SegmenterImpl(undefined, {
granularity: 'grapheme'
});
}
return cachedGraphemeSegmenter;
};
/**
* Splits text into grapheme clusters (user-perceived characters) so that `breakAll`
* wrapping and `maxLines` truncation never tear a cluster apart: ZWJ sequences,
* combining marks, regional indicators and emoji modifiers stay together.
* Falls back to code-point splitting (`Array.from`) when Intl.Segmenter is not
* available (e.g. Firefox before 125), which preserves the previous behavior.
*/
var splitIntoGraphemes = text => {
var segmenter = getGraphemeSegmenter();
if (segmenter == null) {
return Array.from(text);
}
return Array.from(segmenter.segment(text), graphemeSegment => graphemeSegment.segment);
};
var calculateWordWidths = _ref => {
var children = _ref.children,
breakAll = _ref.breakAll,
style = _ref.style;
try {
var words = [];
if (!(0, _DataUtils.isNullish)(children)) {
if (breakAll) {
words = splitIntoGraphemes(children.toString());
} else {
words = children.toString().split(BREAKING_SPACES);
}
}
var wordsWithComputedWidth = words.map(word => ({
word,
width: (0, _DOMUtils.getStringSize)(word, style).width
}));
var spaceWidth = breakAll ? 0 : (0, _DOMUtils.getStringSize)('\u00A0', style).width;
return {
wordsWithComputedWidth,
spaceWidth
};
} catch (_unused) {
return null;
}
};
/**
* @inline
* @public
*/
function isValidTextAnchor(value) {
return value === 'start' || value === 'middle' || value === 'end' || value === 'inherit';
}
/**
* @inline
* @public
*/
/**
* @inline
* @public
*/
function isRenderableText(val) {
return (0, _DataUtils.isNullish)(val) || typeof val === 'string' || typeof val === 'number' || typeof val === 'boolean';
}
/**
* Props of the shape that is drawn behind the text.
* Accepts the usual SVG `<rect>` attributes, such as `fill`, `fillOpacity`, `stroke`, `rx` and `className`.
* Straight text uses a rectangle; text on a path uses a stroked copy of that path.
* The position and size are measured from the rendered text.
*
* @since 3.11
* @public
*/
/**
* Props of the halo (text outline) drawn around the letters, as a lighter alternative to `background`.
* Accepts a subset of the SVG `<text>` stroke attributes.
*
* @since 3.11
*/
/**
* @public
*/
var calculate = (words, lineWidth, spaceWidth, scaleToFit) => words.reduce((result, _ref2) => {
var word = _ref2.word,
width = _ref2.width;
var currentLine = result[result.length - 1];
if (currentLine && width != null && (lineWidth == null || scaleToFit || currentLine.width + width + spaceWidth < Number(lineWidth))) {
// Word can be added to an existing line
currentLine.words.push(word);
currentLine.width += width + spaceWidth;
} else {
// Add first word to line or word is too long to scaleToFit on existing line
var newLine = {
words: [word],
width
};
result.push(newLine);
}
return result;
}, []);
var findLongestLine = words => words.reduce((a, b) => a.width > b.width ? a : b);
var suffix = '…';
var checkOverflow = (text, index, breakAll, style, maxLines, lineWidth, spaceWidth, scaleToFit) => {
var tempText = text.slice(0, index).join('');
var words = calculateWordWidths({
breakAll,
style,
children: tempText + suffix
});
if (!words) {
return [false, []];
}
var result = calculate(words.wordsWithComputedWidth, lineWidth, spaceWidth, scaleToFit);
var doesOverflow = result.length > maxLines || findLongestLine(result).width > Number(lineWidth);
return [doesOverflow, result];
};
var calculateWordsByLines = (_ref3, initialWordsWithComputedWith, spaceWidth, lineWidth, scaleToFit) => {
var maxLines = _ref3.maxLines,
children = _ref3.children,
style = _ref3.style,
breakAll = _ref3.breakAll;
var shouldLimitLines = (0, _DataUtils.isNumber)(maxLines);
var originalResult = calculate(initialWordsWithComputedWith, lineWidth, spaceWidth, scaleToFit);
if (!shouldLimitLines || scaleToFit || originalResult.length === 0) {
return originalResult;
}
var overflows = originalResult.length > maxLines || findLongestLine(originalResult).width > Number(lineWidth);
if (!overflows) {
return originalResult;
}
var text = splitIntoGraphemes(String(children));
var start = 0;
var end = text.length - 1;
// Keep the last fitting prefix, including the final candidate in the search range.
var trimmedResult;
while (start <= end) {
var middle = Math.floor((start + end) / 2);
var _checkOverflow = checkOverflow(text, middle, breakAll, style, maxLines, lineWidth, spaceWidth, scaleToFit),
_checkOverflow2 = _slicedToArray(_checkOverflow, 2),
doesOverflow = _checkOverflow2[0],
result = _checkOverflow2[1];
if (doesOverflow) {
end = middle - 1;
} else {
trimmedResult = result;
start = middle + 1;
}
}
// Fallback to originalResult (result without trimming) if we cannot find the
// where to trim. This should not happen :tm:
return trimmedResult || originalResult;
};
var getWordsWithoutCalculate = children => {
var words = !(0, _DataUtils.isNullish)(children) ? children.toString().split(BREAKING_SPACES) : [];
return [{
words,
width: undefined
}];
};
var getWordsByLines = _ref4 => {
var width = _ref4.width,
scaleToFit = _ref4.scaleToFit,
children = _ref4.children,
style = _ref4.style,
breakAll = _ref4.breakAll,
maxLines = _ref4.maxLines;
// Only perform calculations if using features that require them (multiline, scaleToFit)
if ((width || scaleToFit) && !_Global.Global.isSsr) {
var wordsWithComputedWidth, spaceWidth;
var wordWidths = calculateWordWidths({
breakAll,
children,
style
});
if (wordWidths) {
var wcw = wordWidths.wordsWithComputedWidth,
sw = wordWidths.spaceWidth;
wordsWithComputedWidth = wcw;
spaceWidth = sw;
} else {
return getWordsWithoutCalculate(children);
}
return calculateWordsByLines({
breakAll,
children,
maxLines,
style
}, wordsWithComputedWidth, spaceWidth, width, Boolean(scaleToFit));
}
return getWordsWithoutCalculate(children);
};
exports.getWordsByLines = getWordsByLines;
var DEFAULT_FILL = '#808080';
var defaultLegacyThemeProps = {
fill: DEFAULT_FILL
};
/**
* Without a theme, charts are designed for a white background.
*/
var defaultLegacyBackgroundProps = {
fill: '#fff'
};
var defaultBackgroundPadding = {
x: 4,
y: 2
};
var defaultBackgroundRadius = 4;
function selectBackgroundFill(theme) {
var pageBackground = (0, _pageBackground.getEffectivePageBackground)(theme);
return typeof pageBackground === 'string' ? {
fill: pageBackground
} : undefined;
}
/**
* Without a theme, charts are designed for a white background.
*/
var defaultLegacyHaloStroke = {
stroke: '#fff'
};
var defaultHaloStrokeWidth = 3;
var defaultHaloStrokeLinejoin = 'round';
function selectHaloStroke(theme) {
var pageBackground = (0, _pageBackground.getEffectivePageBackground)(theme);
return typeof pageBackground === 'string' ? {
stroke: pageBackground
} : undefined;
}
/**
* The geometry of the text bounding box, in the text's own coordinate system.
*/
function resolveBackgroundPadding(padding) {
var _padding$x, _padding$y;
if ((0, _DataUtils.isNumber)(padding)) {
return {
x: padding,
y: padding
};
}
return {
x: (_padding$x = padding === null || padding === void 0 ? void 0 : padding.x) !== null && _padding$x !== void 0 ? _padding$x : defaultBackgroundPadding.x,
y: (_padding$y = padding === null || padding === void 0 ? void 0 : padding.y) !== null && _padding$y !== void 0 ? _padding$y : defaultBackgroundPadding.y
};
}
/**
* Returns the rectangle of the text background, or null if there is no text to put a background behind.
* @param textBox bounding box of the text element
* @param padding padding around the text
* @returns background rectangle
*/
function getTextBackgroundRect(textBox, padding) {
if (textBox.width <= 0 || textBox.height <= 0) {
return null;
}
var _resolveBackgroundPad = resolveBackgroundPadding(padding),
paddingX = _resolveBackgroundPad.x,
paddingY = _resolveBackgroundPad.y;
return {
x: textBox.x - paddingX,
y: textBox.y - paddingY,
width: textBox.width + 2 * paddingX,
height: textBox.height + 2 * paddingY
};
}
function getTextPathBackgroundGeometry(metrics, padding, textAnchor) {
var pathLength = metrics.pathLength,
textLength = metrics.textLength,
textHeight = metrics.textHeight,
startOffset = metrics.startOffset;
if (pathLength <= 0 || textLength <= 0 || textHeight <= 0) {
return null;
}
var _resolveBackgroundPad2 = resolveBackgroundPadding(padding),
paddingX = _resolveBackgroundPad2.x,
paddingY = _resolveBackgroundPad2.y;
var anchorOffset = 0;
if (textAnchor === 'middle') {
anchorOffset = textLength / 2;
} else if (textAnchor === 'end') {
anchorOffset = textLength;
}
var unclampedStart = startOffset - anchorOffset - paddingX;
var unclampedEnd = startOffset - anchorOffset + textLength + paddingX;
var start = Math.max(0, Math.min(pathLength, unclampedStart));
var end = Math.max(0, Math.min(pathLength, unclampedEnd));
if (end <= start) {
return null;
}
return {
start,
length: end - start,
strokeWidth: textHeight + 2 * paddingY
};
}
function isSameTextBox(a, b) {
return a != null && a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
}
function isSameTextPathMetrics(a, b) {
return a != null && a.pathLength === b.pathLength && a.textLength === b.textLength && a.textHeight === b.textHeight && a.startOffset === b.startOffset;
}
function resolveTextPathStartOffset(textPathNode, startOffset, pathLength) {
var _textPathNode$startOf;
var resolvedOffset = (_textPathNode$startOf = textPathNode.startOffset) === null || _textPathNode$startOf === void 0 ? void 0 : _textPathNode$startOf.baseVal.value;
if ((0, _isWellBehavedNumber.isWellBehavedNumber)(resolvedOffset)) {
return resolvedOffset;
}
if ((0, _DataUtils.isNumber)(startOffset)) {
return startOffset;
}
if (typeof startOffset === 'string') {
var parsedOffset = Number.parseFloat(startOffset);
if (Number.isFinite(parsedOffset)) {
return startOffset.trim().endsWith('%') ? parsedOffset / 100 * pathLength : parsedOffset;
}
}
return 0;
}
function resolveTextPathHeight(textPathNode, textNode) {
var fontSize = Number.parseFloat(window.getComputedStyle(textPathNode).fontSize);
return Number.isFinite(fontSize) && fontSize > 0 ? fontSize : textNode.getBBox().height;
}
function resolveBackgroundStrokeWidth(strokeWidth) {
if (strokeWidth == null) {
return 1;
}
var parsedStrokeWidth = (0, _DataUtils.isNumber)(strokeWidth) ? strokeWidth : Number.parseFloat(strokeWidth);
return Number.isFinite(parsedStrokeWidth) ? Math.max(0, parsedStrokeWidth) : 1;
}
function resolveBackgroundSettings(background) {
if (background === true) {
return {};
}
if (background == null || background === false) {
return undefined;
}
return background;
}
function resolveHaloSettings(halo) {
if (halo === true) {
return {};
}
if (halo == null || halo === false) {
return undefined;
}
return halo;
}
var textDefaultProps = exports.textDefaultProps = {
angle: 0,
breakAll: false,
// Magic number from d3
capHeight: '0.71em',
lineHeight: '1em',
scaleToFit: false,
textAnchor: 'start',
// Maintain compat with existing charts / default SVG behavior
verticalAnchor: 'end',
x: 0,
y: 0
};
/**
* @public
*/
var Text = exports.Text = /*#__PURE__*/(0, _react.forwardRef)((outsideProps, ref) => {
var _haloSettings$strokeW, _haloSettings$strokeL, _ref7, _backgroundRectProps$;
var typography = (0, _useBackwardsCompatibleTheme.useBackwardsCompatibleTheme)(theme => theme.typography, {
fill: outsideProps.fill
}, defaultLegacyThemeProps);
var propsWithDefaults = (0, _resolveDefaultProps.resolveDefaultProps)(outsideProps, textDefaultProps);
var textPathId = (0, _useId.useId)();
var propsX = propsWithDefaults.x,
propsY = propsWithDefaults.y,
lineHeight = propsWithDefaults.lineHeight,
capHeight = propsWithDefaults.capHeight,
scaleToFit = propsWithDefaults.scaleToFit,
textAnchor = propsWithDefaults.textAnchor,
verticalAnchor = propsWithDefaults.verticalAnchor,
propsStyle = propsWithDefaults.style,
textPath = propsWithDefaults.textPath,
background = propsWithDefaults.background,
halo = propsWithDefaults.halo,
props = _objectWithoutProperties(propsWithDefaults, _excluded);
// Here it is important to actually remove these three props, and not put them to DOM
var angle = props.angle,
dx = props.dx,
dy = props.dy,
className = props.className,
breakAll = props.breakAll,
textProps = _objectWithoutProperties(props, _excluded2);
var startOffset = textProps.startOffset,
textElementProps = _objectWithoutProperties(textProps, _excluded3);
var width = textProps.width;
var x = Number(propsX) + ((0, _DataUtils.isNumber)(dx) ? dx : 0);
var y = Number(propsY) + ((0, _DataUtils.isNumber)(dy) ? dy : 0);
var styleTemp = (0, _react.useMemo)(() => {
return (0, _cssStylesToSvgStyles.cssStylesToSvgStyles)(_objectSpread(_objectSpread({}, typography), propsStyle));
}, [propsStyle, typography]);
var wordsByLines = (0, _react.useMemo)(() => {
return getWordsByLines({
breakAll: props.breakAll,
children: props.children,
maxLines: props.maxLines,
scaleToFit,
style: styleTemp,
width: props.width
});
}, [props.breakAll, props.children, props.maxLines, scaleToFit, styleTemp, props.width]);
var svgTransforms = (0, _react.useMemo)(() => {
var transformsMemo = [];
var firstLine = wordsByLines[0];
if (scaleToFit && firstLine != null) {
var lineWidth = firstLine.width;
transformsMemo.push("scale(".concat((0, _DataUtils.isNumber)(width) && (0, _DataUtils.isNumber)(lineWidth) ? width / lineWidth : 1, ")"));
}
if (angle && textPath == null) {
/*
* textPath-driven labels are rotated using CSS transforms
* to keep previous behavior unchanged.
*/
transformsMemo.push("rotate(".concat(angle, ", ").concat(x, ", ").concat(y, ")"));
}
return transformsMemo;
}, [scaleToFit, wordsByLines, width, angle, x, y, textPath]);
var styleFinal = (0, _react.useMemo)(() => {
/*
* If the Text is driven by a textPath then we apply CSS rotations
* where we can set transform-box: 'fill-box'
*/
var cssTransforms = angle && textPath != null ? "rotate(".concat(angle, "deg)") : undefined;
var temp = cssTransforms != null ? {
transform: cssTransforms,
transformOrigin: 'center',
transformBox: 'fill-box'
} : {};
return _objectSpread(_objectSpread({}, temp), styleTemp);
}, [styleTemp, angle, textPath]);
var haloSettings = resolveHaloSettings(halo);
var haloStroke = (0, _useBackwardsCompatibleTheme.useBackwardsCompatibleTheme)(selectHaloStroke, {
stroke: haloSettings === null || haloSettings === void 0 ? void 0 : haloSettings.stroke
}, defaultLegacyHaloStroke);
var haloProps = haloSettings == null ? undefined : {
stroke: haloStroke.stroke,
strokeWidth: (_haloSettings$strokeW = haloSettings.strokeWidth) !== null && _haloSettings$strokeW !== void 0 ? _haloSettings$strokeW : defaultHaloStrokeWidth,
strokeLinejoin: (_haloSettings$strokeL = haloSettings.strokeLinejoin) !== null && _haloSettings$strokeL !== void 0 ? _haloSettings$strokeL : defaultHaloStrokeLinejoin,
strokeOpacity: haloSettings.strokeOpacity,
paintOrder: 'stroke fill'
};
var backgroundSettings = resolveBackgroundSettings(background);
var backgroundFill = (0, _useBackwardsCompatibleTheme.useBackwardsCompatibleTheme)(selectBackgroundFill, {
fill: backgroundSettings === null || backgroundSettings === void 0 ? void 0 : backgroundSettings.fill
}, defaultLegacyBackgroundProps);
var labelZIndex = (0, _labelBackgroundZIndex.useLabelZIndex)();
var backgroundLayer = labelZIndex == null ? undefined : (0, _labelBackgroundZIndex.getLabelBackgroundZIndex)(labelZIndex, background);
var textRef = (0, _react.useRef)(null);
var textPathRef = (0, _react.useRef)(null);
var textPathDefinitionRef = (0, _react.useRef)(null);
var setTextRef = (0, _react.useCallback)(node => {
textRef.current = node;
if (typeof ref === 'function') {
ref(node);
} else if (ref != null) {
// forwarding the element to a ref object is the purpose of this callback
// eslint-disable-next-line no-param-reassign
ref.current = node;
}
}, [ref]);
var _useState = (0, _react.useState)(null),
_useState2 = _slicedToArray(_useState, 2),
textBox = _useState2[0],
setTextBox = _useState2[1];
var _useState3 = (0, _react.useState)(null),
_useState4 = _slicedToArray(_useState3, 2),
textPathMetrics = _useState4[0],
setTextPathMetrics = _useState4[1];
var hasBackground = backgroundSettings != null;
/*
* The background is sized from the rendered text, so that it follows the actual font, line breaks and anchors.
* This runs after every render because any prop or style can change the size of the text.
* The state update is skipped when the box stays the same, so this does not loop.
*/
// eslint-disable-next-line react-hooks/exhaustive-deps
(0, _react.useLayoutEffect)(() => {
var node = textRef.current;
if (!hasBackground || node == null || typeof node.getBBox !== 'function') {
return;
}
try {
if (textPath != null) {
var textPathNode = textPathRef.current;
var pathNode = textPathDefinitionRef.current;
if (textPathNode == null || pathNode == null || typeof textPathNode.getComputedTextLength !== 'function' || typeof pathNode.getTotalLength !== 'function') {
return;
}
var pathLength = pathNode.getTotalLength();
var nextMetrics = {
pathLength,
textLength: textPathNode.getComputedTextLength(),
textHeight: resolveTextPathHeight(textPathNode, node),
startOffset: resolveTextPathStartOffset(textPathNode, startOffset, pathLength)
};
if (!isSameTextPathMetrics(textPathMetrics, nextMetrics)) {
setTextPathMetrics(nextMetrics);
}
return;
}
var _node$getBBox = node.getBBox(),
boxX = _node$getBBox.x,
boxY = _node$getBBox.y,
boxWidth = _node$getBBox.width,
boxHeight = _node$getBBox.height;
var nextBox = {
x: boxX,
y: boxY,
width: boxWidth,
height: boxHeight
};
if (!isSameTextBox(textBox, nextBox)) {
setTextBox(nextBox);
}
} catch (_unused2) {
// SVG measurement can fail when the element is detached or unsupported by the renderer.
}
});
if (!(0, _DataUtils.isNumOrStr)(propsX) || !(0, _DataUtils.isNumOrStr)(propsY) || wordsByLines.length === 0) {
return null;
}
if (!(0, _isWellBehavedNumber.isWellBehavedNumber)(x) || !(0, _isWellBehavedNumber.isWellBehavedNumber)(y)) {
return null;
}
var startDy;
switch (verticalAnchor) {
case 'start':
startDy = (0, _ReduceCSSCalc.reduceCSSCalc)("calc(".concat(capHeight, ")"));
break;
case 'middle':
startDy = (0, _ReduceCSSCalc.reduceCSSCalc)("calc(".concat((wordsByLines.length - 1) / 2, " * -").concat(lineHeight, " + (").concat(capHeight, " / 2))"));
break;
default:
startDy = (0, _ReduceCSSCalc.reduceCSSCalc)("calc(".concat(wordsByLines.length - 1, " * -").concat(lineHeight, ")"));
break;
}
var transform = svgTransforms.length > 0 ? svgTransforms.join(' ') : undefined;
var textElement = /*#__PURE__*/React.createElement("text", _extends({
transform: transform
}, (0, _svgPropertiesAndEvents.svgPropertiesAndEvents)(textElementProps), haloProps, {
style: styleFinal,
ref: setTextRef,
x: x,
y: y,
className: (0, _clsx.clsx)('recharts-text', className),
textAnchor: textAnchor
}), textPath == null ? wordsByLines.map((line, index) => {
var words = line.words.join(breakAll ? '' : ' ');
return (
/*#__PURE__*/
// duplicate words will cause duplicate keys which is why we add the array index here
React.createElement("tspan", {
x: x,
dy: index === 0 ? startDy : lineHeight,
key: "".concat(words, "-").concat(index)
}, words)
);
}) : /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("defs", null, /*#__PURE__*/React.createElement("path", {
ref: textPathDefinitionRef,
id: textPathId,
d: textPath
})), /*#__PURE__*/React.createElement("textPath", {
ref: textPathRef,
xlinkHref: "#".concat(textPathId),
startOffset: startOffset
}, props.children)));
if (backgroundSettings == null) {
return textElement;
}
var padding = backgroundSettings.padding,
backgroundClassName = backgroundSettings.className,
backgroundRectProps = _objectWithoutProperties(backgroundSettings, _excluded4);
var renderInBackgroundLayer = backgroundElement => backgroundLayer == null ? backgroundElement : /*#__PURE__*/React.createElement(_ZIndexLayer.ZIndexLayer, {
zIndex: backgroundLayer
}, backgroundElement);
if (textPath != null) {
var _ref5, _backgroundPathProps$, _ref6, _backgroundPathProps$2;
var fillOpacity = backgroundRectProps.fillOpacity,
outlineStroke = backgroundRectProps.stroke,
outlineStrokeOpacity = backgroundRectProps.strokeOpacity,
configuredOutlineWidth = backgroundRectProps.strokeWidth,
backgroundPathProps = _objectWithoutProperties(backgroundRectProps, _excluded5);
var backgroundPath = textPathMetrics == null ? null : getTextPathBackgroundGeometry(textPathMetrics, padding, textAnchor);
var outlineWidth = resolveBackgroundStrokeWidth(configuredOutlineWidth);
var hasOutline = outlineStroke != null && outlineStroke !== 'none' && outlineWidth > 0;
var _backgroundElement = backgroundPath != null && textPathMetrics != null && /*#__PURE__*/React.createElement(React.Fragment, null, hasOutline && /*#__PURE__*/React.createElement("path", _extends({}, (0, _svgPropertiesAndEvents.svgPropertiesAndEvents)(backgroundPathProps), {
pointerEvents: (_ref5 = (_backgroundPathProps$ = backgroundPathProps.pointerEvents) !== null && _backgroundPathProps$ !== void 0 ? _backgroundPathProps$ : styleFinal.pointerEvents) !== null && _ref5 !== void 0 ? _ref5 : props.pointerEvents,
d: textPath,
fill: "none",
stroke: outlineStroke,
strokeOpacity: outlineStrokeOpacity,
strokeWidth: backgroundPath.strokeWidth + 2 * outlineWidth,
strokeLinecap: "round",
strokeDasharray: "".concat(backgroundPath.length, "px ").concat(textPathMetrics.pathLength, "px"),
strokeDashoffset: "".concat(-backgroundPath.start, "px"),
className: (0, _clsx.clsx)('recharts-text-background', 'recharts-text-path-background-outline', backgroundClassName)
})), /*#__PURE__*/React.createElement("path", _extends({}, (0, _svgPropertiesAndEvents.svgPropertiesAndEvents)(backgroundPathProps), {
pointerEvents: (_ref6 = (_backgroundPathProps$2 = backgroundPathProps.pointerEvents) !== null && _backgroundPathProps$2 !== void 0 ? _backgroundPathProps$2 : styleFinal.pointerEvents) !== null && _ref6 !== void 0 ? _ref6 : props.pointerEvents,
d: textPath,
fill: "none",
stroke: backgroundFill.fill,
strokeOpacity: fillOpacity,
strokeWidth: backgroundPath.strokeWidth,
strokeLinecap: "round",
strokeDasharray: "".concat(backgroundPath.length, "px ").concat(textPathMetrics.pathLength, "px"),
strokeDashoffset: "".concat(-backgroundPath.start, "px"),
className: (0, _clsx.clsx)('recharts-text-background', 'recharts-text-path-background', backgroundClassName)
})));
return /*#__PURE__*/React.createElement("g", {
className: "recharts-text-with-background"
}, renderInBackgroundLayer(_backgroundElement), textElement);
}
var backgroundRect = textBox == null ? null : getTextBackgroundRect(textBox, padding);
var backgroundElement = backgroundRect != null && /*#__PURE__*/React.createElement("rect", _extends({
rx: defaultBackgroundRadius
}, (0, _svgPropertiesAndEvents.svgPropertiesAndEvents)(backgroundRectProps), {
pointerEvents: (_ref7 = (_backgroundRectProps$ = backgroundRectProps.pointerEvents) !== null && _backgroundRectProps$ !== void 0 ? _backgroundRectProps$ : styleFinal.pointerEvents) !== null && _ref7 !== void 0 ? _ref7 : props.pointerEvents,
fill: backgroundFill.fill,
className: (0, _clsx.clsx)('recharts-text-background', backgroundClassName),
transform: transform,
x: backgroundRect.x,
y: backgroundRect.y,
width: backgroundRect.width,
height: backgroundRect.height
}));
/*
* The group is rendered even before the text is measured,
* so that the text element keeps its place in the tree and React does not re-mount it.
*/
return /*#__PURE__*/React.createElement("g", {
className: "recharts-text-with-background"
}, renderInBackgroundLayer(backgroundElement), textElement);
});
Text.displayName = 'Text';