CartesianAxis.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.CartesianAxis = void 0;
  6. var _react = _interopRequireWildcard(require("react"));
  7. var _isFunction = _interopRequireDefault(require("lodash/isFunction"));
  8. var _get = _interopRequireDefault(require("lodash/get"));
  9. var _clsx = _interopRequireDefault(require("clsx"));
  10. var _ShallowEqual = require("../util/ShallowEqual");
  11. var _Layer = require("../container/Layer");
  12. var _Text = require("../component/Text");
  13. var _Label = require("../component/Label");
  14. var _DataUtils = require("../util/DataUtils");
  15. var _types = require("../util/types");
  16. var _ReactUtils = require("../util/ReactUtils");
  17. var _getTicks = require("./getTicks");
  18. var _excluded = ["viewBox"],
  19. _excluded2 = ["viewBox"],
  20. _excluded3 = ["ticks"];
  21. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  22. function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
  23. function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; }
  24. function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
  25. function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
  26. 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; }
  27. 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; }
  28. function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
  29. function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } } return target; }
  30. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
  32. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  33. function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
  34. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
  35. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  36. function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
  37. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  38. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
  39. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40. function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  41. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
  42. 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); } /**
  43. * @fileOverview Cartesian Axis
  44. */
  45. /** The orientation of the axis in correspondence to the chart */
  46. /** A unit to be appended to a value */
  47. /** The formatter function of tick */
  48. var CartesianAxis = exports.CartesianAxis = /*#__PURE__*/function (_Component) {
  49. function CartesianAxis(props) {
  50. var _this;
  51. _classCallCheck(this, CartesianAxis);
  52. _this = _callSuper(this, CartesianAxis, [props]);
  53. _this.state = {
  54. fontSize: '',
  55. letterSpacing: ''
  56. };
  57. return _this;
  58. }
  59. _inherits(CartesianAxis, _Component);
  60. return _createClass(CartesianAxis, [{
  61. key: "shouldComponentUpdate",
  62. value: function shouldComponentUpdate(_ref, nextState) {
  63. var viewBox = _ref.viewBox,
  64. restProps = _objectWithoutProperties(_ref, _excluded);
  65. // props.viewBox is sometimes generated every time -
  66. // check that specially as object equality is likely to fail
  67. var _this$props = this.props,
  68. viewBoxOld = _this$props.viewBox,
  69. restPropsOld = _objectWithoutProperties(_this$props, _excluded2);
  70. return !(0, _ShallowEqual.shallowEqual)(viewBox, viewBoxOld) || !(0, _ShallowEqual.shallowEqual)(restProps, restPropsOld) || !(0, _ShallowEqual.shallowEqual)(nextState, this.state);
  71. }
  72. }, {
  73. key: "componentDidMount",
  74. value: function componentDidMount() {
  75. var htmlLayer = this.layerReference;
  76. if (!htmlLayer) return;
  77. var tick = htmlLayer.getElementsByClassName('recharts-cartesian-axis-tick-value')[0];
  78. if (tick) {
  79. this.setState({
  80. fontSize: window.getComputedStyle(tick).fontSize,
  81. letterSpacing: window.getComputedStyle(tick).letterSpacing
  82. });
  83. }
  84. }
  85. /**
  86. * Calculate the coordinates of endpoints in ticks
  87. * @param {Object} data The data of a simple tick
  88. * @return {Object} (x1, y1): The coordinate of endpoint close to tick text
  89. * (x2, y2): The coordinate of endpoint close to axis
  90. */
  91. }, {
  92. key: "getTickLineCoord",
  93. value: function getTickLineCoord(data) {
  94. var _this$props2 = this.props,
  95. x = _this$props2.x,
  96. y = _this$props2.y,
  97. width = _this$props2.width,
  98. height = _this$props2.height,
  99. orientation = _this$props2.orientation,
  100. tickSize = _this$props2.tickSize,
  101. mirror = _this$props2.mirror,
  102. tickMargin = _this$props2.tickMargin;
  103. var x1, x2, y1, y2, tx, ty;
  104. var sign = mirror ? -1 : 1;
  105. var finalTickSize = data.tickSize || tickSize;
  106. var tickCoord = (0, _DataUtils.isNumber)(data.tickCoord) ? data.tickCoord : data.coordinate;
  107. switch (orientation) {
  108. case 'top':
  109. x1 = x2 = data.coordinate;
  110. y2 = y + +!mirror * height;
  111. y1 = y2 - sign * finalTickSize;
  112. ty = y1 - sign * tickMargin;
  113. tx = tickCoord;
  114. break;
  115. case 'left':
  116. y1 = y2 = data.coordinate;
  117. x2 = x + +!mirror * width;
  118. x1 = x2 - sign * finalTickSize;
  119. tx = x1 - sign * tickMargin;
  120. ty = tickCoord;
  121. break;
  122. case 'right':
  123. y1 = y2 = data.coordinate;
  124. x2 = x + +mirror * width;
  125. x1 = x2 + sign * finalTickSize;
  126. tx = x1 + sign * tickMargin;
  127. ty = tickCoord;
  128. break;
  129. default:
  130. x1 = x2 = data.coordinate;
  131. y2 = y + +mirror * height;
  132. y1 = y2 + sign * finalTickSize;
  133. ty = y1 + sign * tickMargin;
  134. tx = tickCoord;
  135. break;
  136. }
  137. return {
  138. line: {
  139. x1: x1,
  140. y1: y1,
  141. x2: x2,
  142. y2: y2
  143. },
  144. tick: {
  145. x: tx,
  146. y: ty
  147. }
  148. };
  149. }
  150. }, {
  151. key: "getTickTextAnchor",
  152. value: function getTickTextAnchor() {
  153. var _this$props3 = this.props,
  154. orientation = _this$props3.orientation,
  155. mirror = _this$props3.mirror;
  156. var textAnchor;
  157. switch (orientation) {
  158. case 'left':
  159. textAnchor = mirror ? 'start' : 'end';
  160. break;
  161. case 'right':
  162. textAnchor = mirror ? 'end' : 'start';
  163. break;
  164. default:
  165. textAnchor = 'middle';
  166. break;
  167. }
  168. return textAnchor;
  169. }
  170. }, {
  171. key: "getTickVerticalAnchor",
  172. value: function getTickVerticalAnchor() {
  173. var _this$props4 = this.props,
  174. orientation = _this$props4.orientation,
  175. mirror = _this$props4.mirror;
  176. var verticalAnchor = 'end';
  177. switch (orientation) {
  178. case 'left':
  179. case 'right':
  180. verticalAnchor = 'middle';
  181. break;
  182. case 'top':
  183. verticalAnchor = mirror ? 'start' : 'end';
  184. break;
  185. default:
  186. verticalAnchor = mirror ? 'end' : 'start';
  187. break;
  188. }
  189. return verticalAnchor;
  190. }
  191. }, {
  192. key: "renderAxisLine",
  193. value: function renderAxisLine() {
  194. var _this$props5 = this.props,
  195. x = _this$props5.x,
  196. y = _this$props5.y,
  197. width = _this$props5.width,
  198. height = _this$props5.height,
  199. orientation = _this$props5.orientation,
  200. mirror = _this$props5.mirror,
  201. axisLine = _this$props5.axisLine;
  202. var props = _objectSpread(_objectSpread(_objectSpread({}, (0, _ReactUtils.filterProps)(this.props, false)), (0, _ReactUtils.filterProps)(axisLine, false)), {}, {
  203. fill: 'none'
  204. });
  205. if (orientation === 'top' || orientation === 'bottom') {
  206. var needHeight = +(orientation === 'top' && !mirror || orientation === 'bottom' && mirror);
  207. props = _objectSpread(_objectSpread({}, props), {}, {
  208. x1: x,
  209. y1: y + needHeight * height,
  210. x2: x + width,
  211. y2: y + needHeight * height
  212. });
  213. } else {
  214. var needWidth = +(orientation === 'left' && !mirror || orientation === 'right' && mirror);
  215. props = _objectSpread(_objectSpread({}, props), {}, {
  216. x1: x + needWidth * width,
  217. y1: y,
  218. x2: x + needWidth * width,
  219. y2: y + height
  220. });
  221. }
  222. return /*#__PURE__*/_react["default"].createElement("line", _extends({}, props, {
  223. className: (0, _clsx["default"])('recharts-cartesian-axis-line', (0, _get["default"])(axisLine, 'className'))
  224. }));
  225. }
  226. }, {
  227. key: "renderTicks",
  228. value:
  229. /**
  230. * render the ticks
  231. * @param {Array} ticks The ticks to actually render (overrides what was passed in props)
  232. * @param {string} fontSize Fontsize to consider for tick spacing
  233. * @param {string} letterSpacing Letterspacing to consider for tick spacing
  234. * @return {ReactComponent} renderedTicks
  235. */
  236. function renderTicks(ticks, fontSize, letterSpacing) {
  237. var _this2 = this;
  238. var _this$props6 = this.props,
  239. tickLine = _this$props6.tickLine,
  240. stroke = _this$props6.stroke,
  241. tick = _this$props6.tick,
  242. tickFormatter = _this$props6.tickFormatter,
  243. unit = _this$props6.unit;
  244. var finalTicks = (0, _getTicks.getTicks)(_objectSpread(_objectSpread({}, this.props), {}, {
  245. ticks: ticks
  246. }), fontSize, letterSpacing);
  247. var textAnchor = this.getTickTextAnchor();
  248. var verticalAnchor = this.getTickVerticalAnchor();
  249. var axisProps = (0, _ReactUtils.filterProps)(this.props, false);
  250. var customTickProps = (0, _ReactUtils.filterProps)(tick, false);
  251. var tickLineProps = _objectSpread(_objectSpread({}, axisProps), {}, {
  252. fill: 'none'
  253. }, (0, _ReactUtils.filterProps)(tickLine, false));
  254. var items = finalTicks.map(function (entry, i) {
  255. var _this2$getTickLineCoo = _this2.getTickLineCoord(entry),
  256. lineCoord = _this2$getTickLineCoo.line,
  257. tickCoord = _this2$getTickLineCoo.tick;
  258. var tickProps = _objectSpread(_objectSpread(_objectSpread(_objectSpread({
  259. textAnchor: textAnchor,
  260. verticalAnchor: verticalAnchor
  261. }, axisProps), {}, {
  262. stroke: 'none',
  263. fill: stroke
  264. }, customTickProps), tickCoord), {}, {
  265. index: i,
  266. payload: entry,
  267. visibleTicksCount: finalTicks.length,
  268. tickFormatter: tickFormatter
  269. });
  270. return /*#__PURE__*/_react["default"].createElement(_Layer.Layer, _extends({
  271. className: "recharts-cartesian-axis-tick",
  272. key: "tick-".concat(entry.value, "-").concat(entry.coordinate, "-").concat(entry.tickCoord)
  273. }, (0, _types.adaptEventsOfChild)(_this2.props, entry, i)), tickLine && /*#__PURE__*/_react["default"].createElement("line", _extends({}, tickLineProps, lineCoord, {
  274. className: (0, _clsx["default"])('recharts-cartesian-axis-tick-line', (0, _get["default"])(tickLine, 'className'))
  275. })), tick && CartesianAxis.renderTickItem(tick, tickProps, "".concat((0, _isFunction["default"])(tickFormatter) ? tickFormatter(entry.value, i) : entry.value).concat(unit || '')));
  276. });
  277. return /*#__PURE__*/_react["default"].createElement("g", {
  278. className: "recharts-cartesian-axis-ticks"
  279. }, items);
  280. }
  281. }, {
  282. key: "render",
  283. value: function render() {
  284. var _this3 = this;
  285. var _this$props7 = this.props,
  286. axisLine = _this$props7.axisLine,
  287. width = _this$props7.width,
  288. height = _this$props7.height,
  289. ticksGenerator = _this$props7.ticksGenerator,
  290. className = _this$props7.className,
  291. hide = _this$props7.hide;
  292. if (hide) {
  293. return null;
  294. }
  295. var _this$props8 = this.props,
  296. ticks = _this$props8.ticks,
  297. noTicksProps = _objectWithoutProperties(_this$props8, _excluded3);
  298. var finalTicks = ticks;
  299. if ((0, _isFunction["default"])(ticksGenerator)) {
  300. finalTicks = ticks && ticks.length > 0 ? ticksGenerator(this.props) : ticksGenerator(noTicksProps);
  301. }
  302. if (width <= 0 || height <= 0 || !finalTicks || !finalTicks.length) {
  303. return null;
  304. }
  305. return /*#__PURE__*/_react["default"].createElement(_Layer.Layer, {
  306. className: (0, _clsx["default"])('recharts-cartesian-axis', className),
  307. ref: function ref(_ref2) {
  308. _this3.layerReference = _ref2;
  309. }
  310. }, axisLine && this.renderAxisLine(), this.renderTicks(finalTicks, this.state.fontSize, this.state.letterSpacing), _Label.Label.renderCallByParent(this.props));
  311. }
  312. }], [{
  313. key: "renderTickItem",
  314. value: function renderTickItem(option, props, value) {
  315. var tickItem;
  316. var combinedClassName = (0, _clsx["default"])(props.className, 'recharts-cartesian-axis-tick-value');
  317. if ( /*#__PURE__*/_react["default"].isValidElement(option)) {
  318. tickItem = /*#__PURE__*/_react["default"].cloneElement(option, _objectSpread(_objectSpread({}, props), {}, {
  319. className: combinedClassName
  320. }));
  321. } else if ((0, _isFunction["default"])(option)) {
  322. tickItem = option(_objectSpread(_objectSpread({}, props), {}, {
  323. className: combinedClassName
  324. }));
  325. } else {
  326. tickItem = /*#__PURE__*/_react["default"].createElement(_Text.Text, _extends({}, props, {
  327. className: "recharts-cartesian-axis-tick-value"
  328. }), value);
  329. }
  330. return tickItem;
  331. }
  332. }]);
  333. }(_react.Component);
  334. _defineProperty(CartesianAxis, "displayName", 'CartesianAxis');
  335. _defineProperty(CartesianAxis, "defaultProps", {
  336. x: 0,
  337. y: 0,
  338. width: 0,
  339. height: 0,
  340. viewBox: {
  341. x: 0,
  342. y: 0,
  343. width: 0,
  344. height: 0
  345. },
  346. // The orientation of axis
  347. orientation: 'bottom',
  348. // The ticks
  349. ticks: [],
  350. stroke: '#666',
  351. tickLine: true,
  352. axisLine: true,
  353. tick: true,
  354. mirror: false,
  355. minTickGap: 5,
  356. // The width or height of tick
  357. tickSize: 6,
  358. tickMargin: 2,
  359. interval: 'preserveEnd'
  360. });