source: node_modules/recharts/lib/component/Text.js

Last change on this file was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago

Added visualizations

  • Property mode set to 100644
File size: 10.3 KB
Line 
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.getWordsByLines = exports.Text = void 0;
7exports.isValidTextAnchor = isValidTextAnchor;
8exports.textDefaultProps = void 0;
9var _react = _interopRequireWildcard(require("react"));
10var React = _react;
11var _clsx = require("clsx");
12var _DataUtils = require("../util/DataUtils");
13var _Global = require("../util/Global");
14var _DOMUtils = require("../util/DOMUtils");
15var _ReduceCSSCalc = require("../util/ReduceCSSCalc");
16var _svgPropertiesAndEvents = require("../util/svgPropertiesAndEvents");
17var _resolveDefaultProps2 = require("../util/resolveDefaultProps");
18var _isWellBehavedNumber = require("../util/isWellBehavedNumber");
19var _excluded = ["x", "y", "lineHeight", "capHeight", "fill", "scaleToFit", "textAnchor", "verticalAnchor"],
20 _excluded2 = ["dx", "dy", "angle", "className", "breakAll"];
21function _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); }
22function _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); }
23function _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; }
24function _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; }
25var BREAKING_SPACES = /[ \f\n\r\t\v\u2028\u2029]+/;
26var calculateWordWidths = _ref => {
27 var {
28 children,
29 breakAll,
30 style
31 } = _ref;
32 try {
33 var words = [];
34 if (!(0, _DataUtils.isNullish)(children)) {
35 if (breakAll) {
36 words = children.toString().split('');
37 } else {
38 words = children.toString().split(BREAKING_SPACES);
39 }
40 }
41 var wordsWithComputedWidth = words.map(word => ({
42 word,
43 width: (0, _DOMUtils.getStringSize)(word, style).width
44 }));
45 var spaceWidth = breakAll ? 0 : (0, _DOMUtils.getStringSize)('\u00A0', style).width;
46 return {
47 wordsWithComputedWidth,
48 spaceWidth
49 };
50 } catch (_unused) {
51 return null;
52 }
53};
54
55/**
56 * @inline
57 */
58
59function isValidTextAnchor(value) {
60 return value === 'start' || value === 'middle' || value === 'end' || value === 'inherit';
61}
62
63/**
64 * @inline
65 */
66
67/**
68 * @inline
69 */
70
71var calculate = (words, lineWidth, spaceWidth, scaleToFit) => words.reduce((result, _ref2) => {
72 var {
73 word,
74 width
75 } = _ref2;
76 var currentLine = result[result.length - 1];
77 if (currentLine && width != null && (lineWidth == null || scaleToFit || currentLine.width + width + spaceWidth < Number(lineWidth))) {
78 // Word can be added to an existing line
79 currentLine.words.push(word);
80 currentLine.width += width + spaceWidth;
81 } else {
82 // Add first word to line or word is too long to scaleToFit on existing line
83 var newLine = {
84 words: [word],
85 width
86 };
87 result.push(newLine);
88 }
89 return result;
90}, []);
91var findLongestLine = words => words.reduce((a, b) => a.width > b.width ? a : b);
92var suffix = '…';
93var checkOverflow = (text, index, breakAll, style, maxLines, lineWidth, spaceWidth, scaleToFit) => {
94 var tempText = text.slice(0, index);
95 var words = calculateWordWidths({
96 breakAll,
97 style,
98 children: tempText + suffix
99 });
100 if (!words) {
101 return [false, []];
102 }
103 var result = calculate(words.wordsWithComputedWidth, lineWidth, spaceWidth, scaleToFit);
104 var doesOverflow = result.length > maxLines || findLongestLine(result).width > Number(lineWidth);
105 return [doesOverflow, result];
106};
107var calculateWordsByLines = (_ref3, initialWordsWithComputedWith, spaceWidth, lineWidth, scaleToFit) => {
108 var {
109 maxLines,
110 children,
111 style,
112 breakAll
113 } = _ref3;
114 var shouldLimitLines = (0, _DataUtils.isNumber)(maxLines);
115 var text = String(children);
116 var originalResult = calculate(initialWordsWithComputedWith, lineWidth, spaceWidth, scaleToFit);
117 if (!shouldLimitLines || scaleToFit) {
118 return originalResult;
119 }
120 var overflows = originalResult.length > maxLines || findLongestLine(originalResult).width > Number(lineWidth);
121 if (!overflows) {
122 return originalResult;
123 }
124 var start = 0;
125 var end = text.length - 1;
126 var iterations = 0;
127 var trimmedResult;
128 while (start <= end && iterations <= text.length - 1) {
129 var middle = Math.floor((start + end) / 2);
130 var prev = middle - 1;
131 var [doesPrevOverflow, result] = checkOverflow(text, prev, breakAll, style, maxLines, lineWidth, spaceWidth, scaleToFit);
132 var [doesMiddleOverflow] = checkOverflow(text, middle, breakAll, style, maxLines, lineWidth, spaceWidth, scaleToFit);
133 if (!doesPrevOverflow && !doesMiddleOverflow) {
134 start = middle + 1;
135 }
136 if (doesPrevOverflow && doesMiddleOverflow) {
137 end = middle - 1;
138 }
139 if (!doesPrevOverflow && doesMiddleOverflow) {
140 trimmedResult = result;
141 break;
142 }
143 iterations++;
144 }
145
146 // Fallback to originalResult (result without trimming) if we cannot find the
147 // where to trim. This should not happen :tm:
148 return trimmedResult || originalResult;
149};
150var getWordsWithoutCalculate = children => {
151 var words = !(0, _DataUtils.isNullish)(children) ? children.toString().split(BREAKING_SPACES) : [];
152 return [{
153 words,
154 width: undefined
155 }];
156};
157var getWordsByLines = _ref4 => {
158 var {
159 width,
160 scaleToFit,
161 children,
162 style,
163 breakAll,
164 maxLines
165 } = _ref4;
166 // Only perform calculations if using features that require them (multiline, scaleToFit)
167 if ((width || scaleToFit) && !_Global.Global.isSsr) {
168 var wordsWithComputedWidth, spaceWidth;
169 var wordWidths = calculateWordWidths({
170 breakAll,
171 children,
172 style
173 });
174 if (wordWidths) {
175 var {
176 wordsWithComputedWidth: wcw,
177 spaceWidth: sw
178 } = wordWidths;
179 wordsWithComputedWidth = wcw;
180 spaceWidth = sw;
181 } else {
182 return getWordsWithoutCalculate(children);
183 }
184 return calculateWordsByLines({
185 breakAll,
186 children,
187 maxLines,
188 style
189 }, wordsWithComputedWidth, spaceWidth, width, Boolean(scaleToFit));
190 }
191 return getWordsWithoutCalculate(children);
192};
193exports.getWordsByLines = getWordsByLines;
194var DEFAULT_FILL = '#808080';
195var textDefaultProps = exports.textDefaultProps = {
196 angle: 0,
197 breakAll: false,
198 // Magic number from d3
199 capHeight: '0.71em',
200 fill: DEFAULT_FILL,
201 lineHeight: '1em',
202 scaleToFit: false,
203 textAnchor: 'start',
204 // Maintain compat with existing charts / default SVG behavior
205 verticalAnchor: 'end',
206 x: 0,
207 y: 0
208};
209var Text = exports.Text = /*#__PURE__*/(0, _react.forwardRef)((outsideProps, ref) => {
210 var _resolveDefaultProps = (0, _resolveDefaultProps2.resolveDefaultProps)(outsideProps, textDefaultProps),
211 {
212 x: propsX,
213 y: propsY,
214 lineHeight,
215 capHeight,
216 fill,
217 scaleToFit,
218 textAnchor,
219 verticalAnchor
220 } = _resolveDefaultProps,
221 props = _objectWithoutProperties(_resolveDefaultProps, _excluded);
222 var wordsByLines = (0, _react.useMemo)(() => {
223 return getWordsByLines({
224 breakAll: props.breakAll,
225 children: props.children,
226 maxLines: props.maxLines,
227 scaleToFit,
228 style: props.style,
229 width: props.width
230 });
231 }, [props.breakAll, props.children, props.maxLines, scaleToFit, props.style, props.width]);
232 var {
233 dx,
234 dy,
235 angle,
236 className,
237 breakAll
238 } = props,
239 textProps = _objectWithoutProperties(props, _excluded2);
240 if (!(0, _DataUtils.isNumOrStr)(propsX) || !(0, _DataUtils.isNumOrStr)(propsY) || wordsByLines.length === 0) {
241 return null;
242 }
243 var x = Number(propsX) + ((0, _DataUtils.isNumber)(dx) ? dx : 0);
244 var y = Number(propsY) + ((0, _DataUtils.isNumber)(dy) ? dy : 0);
245 if (!(0, _isWellBehavedNumber.isWellBehavedNumber)(x) || !(0, _isWellBehavedNumber.isWellBehavedNumber)(y)) {
246 return null;
247 }
248 var startDy;
249 switch (verticalAnchor) {
250 case 'start':
251 startDy = (0, _ReduceCSSCalc.reduceCSSCalc)("calc(".concat(capHeight, ")"));
252 break;
253 case 'middle':
254 startDy = (0, _ReduceCSSCalc.reduceCSSCalc)("calc(".concat((wordsByLines.length - 1) / 2, " * -").concat(lineHeight, " + (").concat(capHeight, " / 2))"));
255 break;
256 default:
257 startDy = (0, _ReduceCSSCalc.reduceCSSCalc)("calc(".concat(wordsByLines.length - 1, " * -").concat(lineHeight, ")"));
258 break;
259 }
260 var transforms = [];
261 var firstLine = wordsByLines[0];
262 if (scaleToFit && firstLine != null) {
263 var lineWidth = firstLine.width;
264 var {
265 width
266 } = props;
267 transforms.push("scale(".concat((0, _DataUtils.isNumber)(width) && (0, _DataUtils.isNumber)(lineWidth) ? width / lineWidth : 1, ")"));
268 }
269 if (angle) {
270 transforms.push("rotate(".concat(angle, ", ").concat(x, ", ").concat(y, ")"));
271 }
272 if (transforms.length) {
273 textProps.transform = transforms.join(' ');
274 }
275 return /*#__PURE__*/React.createElement("text", _extends({}, (0, _svgPropertiesAndEvents.svgPropertiesAndEvents)(textProps), {
276 ref: ref,
277 x: x,
278 y: y,
279 className: (0, _clsx.clsx)('recharts-text', className),
280 textAnchor: textAnchor,
281 fill: fill.includes('url') ? DEFAULT_FILL : fill
282 }), wordsByLines.map((line, index) => {
283 var words = line.words.join(breakAll ? '' : ' ');
284 return (
285 /*#__PURE__*/
286 // duplicate words will cause duplicate keys which is why we add the array index here
287 React.createElement("tspan", {
288 x: x,
289 dy: index === 0 ? startDy : lineHeight,
290 key: "".concat(words, "-").concat(index)
291 }, words)
292 );
293 }));
294});
295Text.displayName = 'Text';
Note: See TracBrowser for help on using the repository browser.