UNPKG

22.6 kBJavaScriptView Raw
1function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
2
3import _isFunction from "lodash/isFunction";
4import _range from "lodash/range";
5
6function _extends() { _extends = Object.assign || 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); }
7
8function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
9
10function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
11
12function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
13
14function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
15
16function _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, descriptor.key, descriptor); } }
17
18function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
19
20function _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 } }); if (superClass) _setPrototypeOf(subClass, superClass); }
21
22function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
23
24function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
25
26function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
27
28function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
29
30function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
31
32function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
33
34/**
35 * @fileOverview Brush
36 */
37import React, { PureComponent, Children } from 'react';
38import classNames from 'classnames';
39import { scalePoint } from 'd3-scale';
40import { Layer } from '../container/Layer';
41import { Text } from '../component/Text';
42import { getValueByDataKey } from '../util/ChartUtils';
43import { isNumber } from '../util/DataUtils';
44import { generatePrefixStyle } from '../util/CssPrefixUtils';
45import { filterProps } from '../util/types';
46
47var createScale = function createScale(_ref) {
48 var data = _ref.data,
49 startIndex = _ref.startIndex,
50 endIndex = _ref.endIndex,
51 x = _ref.x,
52 width = _ref.width,
53 travellerWidth = _ref.travellerWidth;
54
55 if (!data || !data.length) {
56 return {};
57 }
58
59 var len = data.length;
60 var scale = scalePoint().domain(_range(0, len)).range([x, x + width - travellerWidth]);
61 var scaleValues = scale.domain().map(function (entry) {
62 return scale(entry);
63 });
64 return {
65 isTextActive: false,
66 isSlideMoving: false,
67 isTravellerMoving: false,
68 startX: scale(startIndex),
69 endX: scale(endIndex),
70 scale: scale,
71 scaleValues: scaleValues
72 };
73};
74
75var isTouch = function isTouch(e) {
76 return e.changedTouches && !!e.changedTouches.length;
77};
78
79export var Brush = /*#__PURE__*/function (_PureComponent) {
80 _inherits(Brush, _PureComponent);
81
82 var _super = _createSuper(Brush);
83
84 function Brush(props) {
85 var _this;
86
87 _classCallCheck(this, Brush);
88
89 _this = _super.call(this, props);
90 _this.leaveTimer = void 0;
91 _this.travellerDragStartHandlers = void 0;
92
93 _this.handleDrag = function (e) {
94 if (_this.leaveTimer) {
95 clearTimeout(_this.leaveTimer);
96 _this.leaveTimer = null;
97 }
98
99 if (_this.state.isTravellerMoving) {
100 _this.handleTravellerMove(e);
101 } else if (_this.state.isSlideMoving) {
102 _this.handleSlideDrag(e);
103 }
104 };
105
106 _this.handleTouchMove = function (e) {
107 if (e.changedTouches != null && e.changedTouches.length > 0) {
108 _this.handleDrag(e.changedTouches[0]);
109 }
110 };
111
112 _this.handleDragEnd = function () {
113 _this.setState({
114 isTravellerMoving: false,
115 isSlideMoving: false
116 });
117
118 _this.detachDragEndListener();
119 };
120
121 _this.handleLeaveWrapper = function () {
122 if (_this.state.isTravellerMoving || _this.state.isSlideMoving) {
123 _this.leaveTimer = window.setTimeout(_this.handleDragEnd, _this.props.leaveTimeOut);
124 }
125 };
126
127 _this.handleEnterSlideOrTraveller = function () {
128 _this.setState({
129 isTextActive: true
130 });
131 };
132
133 _this.handleLeaveSlideOrTraveller = function () {
134 _this.setState({
135 isTextActive: false
136 });
137 };
138
139 _this.handleSlideDragStart = function (e) {
140 var event = isTouch(e) ? e.changedTouches[0] : e;
141
142 _this.setState({
143 isTravellerMoving: false,
144 isSlideMoving: true,
145 slideMoveStartX: event.pageX
146 });
147
148 _this.attachDragEndListener();
149 };
150
151 _this.travellerDragStartHandlers = {
152 startX: _this.handleTravellerDragStart.bind(_assertThisInitialized(_this), 'startX'),
153 endX: _this.handleTravellerDragStart.bind(_assertThisInitialized(_this), 'endX')
154 };
155 _this.state = {};
156 return _this;
157 }
158
159 _createClass(Brush, [{
160 key: "componentWillUnmount",
161 value: function componentWillUnmount() {
162 if (this.leaveTimer) {
163 clearTimeout(this.leaveTimer);
164 this.leaveTimer = null;
165 }
166
167 this.detachDragEndListener();
168 }
169 }, {
170 key: "getIndex",
171 value: function getIndex(_ref2) {
172 var startX = _ref2.startX,
173 endX = _ref2.endX;
174 var scaleValues = this.state.scaleValues;
175 var _this$props = this.props,
176 gap = _this$props.gap,
177 data = _this$props.data;
178 var lastIndex = data.length - 1;
179 var min = Math.min(startX, endX);
180 var max = Math.max(startX, endX);
181 var minIndex = Brush.getIndexInRange(scaleValues, min);
182 var maxIndex = Brush.getIndexInRange(scaleValues, max);
183 return {
184 startIndex: minIndex - minIndex % gap,
185 endIndex: maxIndex === lastIndex ? lastIndex : maxIndex - maxIndex % gap
186 };
187 }
188 }, {
189 key: "getTextOfTick",
190 value: function getTextOfTick(index) {
191 var _this$props2 = this.props,
192 data = _this$props2.data,
193 tickFormatter = _this$props2.tickFormatter,
194 dataKey = _this$props2.dataKey;
195 var text = getValueByDataKey(data[index], dataKey, index);
196 return _isFunction(tickFormatter) ? tickFormatter(text, index) : text;
197 }
198 }, {
199 key: "attachDragEndListener",
200 value: function attachDragEndListener() {
201 window.addEventListener('mouseup', this.handleDragEnd, true);
202 window.addEventListener('touchend', this.handleDragEnd, true);
203 }
204 }, {
205 key: "detachDragEndListener",
206 value: function detachDragEndListener() {
207 window.removeEventListener('mouseup', this.handleDragEnd, true);
208 window.removeEventListener('touchend', this.handleDragEnd, true);
209 }
210 }, {
211 key: "handleSlideDrag",
212 value: function handleSlideDrag(e) {
213 var _this$state = this.state,
214 slideMoveStartX = _this$state.slideMoveStartX,
215 startX = _this$state.startX,
216 endX = _this$state.endX;
217 var _this$props3 = this.props,
218 x = _this$props3.x,
219 width = _this$props3.width,
220 travellerWidth = _this$props3.travellerWidth,
221 startIndex = _this$props3.startIndex,
222 endIndex = _this$props3.endIndex,
223 onChange = _this$props3.onChange;
224 var delta = e.pageX - slideMoveStartX;
225
226 if (delta > 0) {
227 delta = Math.min(delta, x + width - travellerWidth - endX, x + width - travellerWidth - startX);
228 } else if (delta < 0) {
229 delta = Math.max(delta, x - startX, x - endX);
230 }
231
232 var newIndex = this.getIndex({
233 startX: startX + delta,
234 endX: endX + delta
235 });
236
237 if ((newIndex.startIndex !== startIndex || newIndex.endIndex !== endIndex) && onChange) {
238 onChange(newIndex);
239 }
240
241 this.setState({
242 startX: startX + delta,
243 endX: endX + delta,
244 slideMoveStartX: e.pageX
245 });
246 }
247 }, {
248 key: "handleTravellerDragStart",
249 value: function handleTravellerDragStart(id, e) {
250 var event = isTouch(e) ? e.changedTouches[0] : e;
251 this.setState({
252 isSlideMoving: false,
253 isTravellerMoving: true,
254 movingTravellerId: id,
255 brushMoveStartX: event.pageX
256 });
257 this.attachDragEndListener();
258 }
259 }, {
260 key: "handleTravellerMove",
261 value: function handleTravellerMove(e) {
262 var _this$setState;
263
264 var _this$state2 = this.state,
265 brushMoveStartX = _this$state2.brushMoveStartX,
266 movingTravellerId = _this$state2.movingTravellerId,
267 endX = _this$state2.endX,
268 startX = _this$state2.startX;
269 var prevValue = this.state[movingTravellerId];
270 var _this$props4 = this.props,
271 x = _this$props4.x,
272 width = _this$props4.width,
273 travellerWidth = _this$props4.travellerWidth,
274 onChange = _this$props4.onChange,
275 gap = _this$props4.gap,
276 data = _this$props4.data;
277 var params = {
278 startX: this.state.startX,
279 endX: this.state.endX
280 };
281 var delta = e.pageX - brushMoveStartX;
282
283 if (delta > 0) {
284 delta = Math.min(delta, x + width - travellerWidth - prevValue);
285 } else if (delta < 0) {
286 delta = Math.max(delta, x - prevValue);
287 }
288
289 params[movingTravellerId] = prevValue + delta;
290 var newIndex = this.getIndex(params);
291 var startIndex = newIndex.startIndex,
292 endIndex = newIndex.endIndex;
293
294 var isFullGap = function isFullGap() {
295 var lastIndex = data.length - 1;
296
297 if (movingTravellerId === 'startX' && (endX > startX ? startIndex % gap === 0 : endIndex % gap === 0) || endX < startX && endIndex === lastIndex || movingTravellerId === 'endX' && (endX > startX ? endIndex % gap === 0 : startIndex % gap === 0) || endX > startX && endIndex === lastIndex) {
298 return true;
299 }
300
301 return false;
302 };
303
304 this.setState((_this$setState = {}, _defineProperty(_this$setState, movingTravellerId, prevValue + delta), _defineProperty(_this$setState, "brushMoveStartX", e.pageX), _this$setState), function () {
305 if (onChange) {
306 if (isFullGap()) {
307 onChange(newIndex);
308 }
309 }
310 });
311 }
312 }, {
313 key: "renderBackground",
314 value: function renderBackground() {
315 var _this$props5 = this.props,
316 x = _this$props5.x,
317 y = _this$props5.y,
318 width = _this$props5.width,
319 height = _this$props5.height,
320 fill = _this$props5.fill,
321 stroke = _this$props5.stroke;
322 return /*#__PURE__*/React.createElement("rect", {
323 stroke: stroke,
324 fill: fill,
325 x: x,
326 y: y,
327 width: width,
328 height: height
329 });
330 }
331 }, {
332 key: "renderPanorama",
333 value: function renderPanorama() {
334 var _this$props6 = this.props,
335 x = _this$props6.x,
336 y = _this$props6.y,
337 width = _this$props6.width,
338 height = _this$props6.height,
339 data = _this$props6.data,
340 children = _this$props6.children,
341 padding = _this$props6.padding;
342 var chartElement = Children.only(children);
343
344 if (!chartElement) {
345 return null;
346 }
347
348 return /*#__PURE__*/React.cloneElement(chartElement, {
349 x: x,
350 y: y,
351 width: width,
352 height: height,
353 margin: padding,
354 compact: true,
355 data: data
356 });
357 }
358 }, {
359 key: "renderTravellerLayer",
360 value: function renderTravellerLayer(travellerX, id) {
361 var _this$props7 = this.props,
362 y = _this$props7.y,
363 travellerWidth = _this$props7.travellerWidth,
364 height = _this$props7.height,
365 traveller = _this$props7.traveller;
366 var x = Math.max(travellerX, this.props.x);
367
368 var travellerProps = _objectSpread(_objectSpread({}, filterProps(this.props)), {}, {
369 x: x,
370 y: y,
371 width: travellerWidth,
372 height: height
373 });
374
375 return /*#__PURE__*/React.createElement(Layer, {
376 className: "recharts-brush-traveller",
377 onMouseEnter: this.handleEnterSlideOrTraveller,
378 onMouseLeave: this.handleLeaveSlideOrTraveller,
379 onMouseDown: this.travellerDragStartHandlers[id],
380 onTouchStart: this.travellerDragStartHandlers[id],
381 style: {
382 cursor: 'col-resize'
383 }
384 }, Brush.renderTraveller(traveller, travellerProps));
385 }
386 }, {
387 key: "renderSlide",
388 value: function renderSlide(startX, endX) {
389 var _this$props8 = this.props,
390 y = _this$props8.y,
391 height = _this$props8.height,
392 stroke = _this$props8.stroke,
393 travellerWidth = _this$props8.travellerWidth;
394 var x = Math.min(startX, endX) + travellerWidth;
395 var width = Math.max(Math.abs(endX - startX) - travellerWidth, 0);
396 return /*#__PURE__*/React.createElement("rect", {
397 className: "recharts-brush-slide",
398 onMouseEnter: this.handleEnterSlideOrTraveller,
399 onMouseLeave: this.handleLeaveSlideOrTraveller,
400 onMouseDown: this.handleSlideDragStart,
401 onTouchStart: this.handleSlideDragStart,
402 style: {
403 cursor: 'move'
404 },
405 stroke: "none",
406 fill: stroke,
407 fillOpacity: 0.2,
408 x: x,
409 y: y,
410 width: width,
411 height: height
412 });
413 }
414 }, {
415 key: "renderText",
416 value: function renderText() {
417 var _this$props9 = this.props,
418 startIndex = _this$props9.startIndex,
419 endIndex = _this$props9.endIndex,
420 y = _this$props9.y,
421 height = _this$props9.height,
422 travellerWidth = _this$props9.travellerWidth,
423 stroke = _this$props9.stroke;
424 var _this$state3 = this.state,
425 startX = _this$state3.startX,
426 endX = _this$state3.endX;
427 var offset = 5;
428 var attrs = {
429 pointerEvents: 'none',
430 fill: stroke
431 };
432 return /*#__PURE__*/React.createElement(Layer, {
433 className: "recharts-brush-texts"
434 }, /*#__PURE__*/React.createElement(Text, _extends({
435 textAnchor: "end",
436 verticalAnchor: "middle",
437 x: Math.min(startX, endX) - offset,
438 y: y + height / 2
439 }, attrs), this.getTextOfTick(startIndex)), /*#__PURE__*/React.createElement(Text, _extends({
440 textAnchor: "start",
441 verticalAnchor: "middle",
442 x: Math.max(startX, endX) + travellerWidth + offset,
443 y: y + height / 2
444 }, attrs), this.getTextOfTick(endIndex)));
445 }
446 }, {
447 key: "render",
448 value: function render() {
449 var _this$props10 = this.props,
450 data = _this$props10.data,
451 className = _this$props10.className,
452 children = _this$props10.children,
453 x = _this$props10.x,
454 y = _this$props10.y,
455 width = _this$props10.width,
456 height = _this$props10.height,
457 alwaysShowText = _this$props10.alwaysShowText;
458 var _this$state4 = this.state,
459 startX = _this$state4.startX,
460 endX = _this$state4.endX,
461 isTextActive = _this$state4.isTextActive,
462 isSlideMoving = _this$state4.isSlideMoving,
463 isTravellerMoving = _this$state4.isTravellerMoving;
464
465 if (!data || !data.length || !isNumber(x) || !isNumber(y) || !isNumber(width) || !isNumber(height) || width <= 0 || height <= 0) {
466 return null;
467 }
468
469 var layerClass = classNames('recharts-brush', className);
470 var isPanoramic = React.Children.count(children) === 1;
471 var style = generatePrefixStyle('userSelect', 'none');
472 return /*#__PURE__*/React.createElement(Layer, {
473 className: layerClass,
474 onMouseMove: this.handleDrag,
475 onMouseLeave: this.handleLeaveWrapper,
476 onTouchMove: this.handleTouchMove,
477 style: style
478 }, this.renderBackground(), isPanoramic && this.renderPanorama(), this.renderSlide(startX, endX), this.renderTravellerLayer(startX, 'startX'), this.renderTravellerLayer(endX, 'endX'), (isTextActive || isSlideMoving || isTravellerMoving || alwaysShowText) && this.renderText());
479 }
480 }], [{
481 key: "renderDefaultTraveller",
482 value: function renderDefaultTraveller(props) {
483 var x = props.x,
484 y = props.y,
485 width = props.width,
486 height = props.height,
487 stroke = props.stroke;
488 var lineY = Math.floor(y + height / 2) - 1;
489 return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("rect", {
490 x: x,
491 y: y,
492 width: width,
493 height: height,
494 fill: stroke,
495 stroke: "none"
496 }), /*#__PURE__*/React.createElement("line", {
497 x1: x + 1,
498 y1: lineY,
499 x2: x + width - 1,
500 y2: lineY,
501 fill: "none",
502 stroke: "#fff"
503 }), /*#__PURE__*/React.createElement("line", {
504 x1: x + 1,
505 y1: lineY + 2,
506 x2: x + width - 1,
507 y2: lineY + 2,
508 fill: "none",
509 stroke: "#fff"
510 }));
511 }
512 }, {
513 key: "renderTraveller",
514 value: function renderTraveller(option, props) {
515 var rectangle;
516
517 if ( /*#__PURE__*/React.isValidElement(option)) {
518 rectangle = /*#__PURE__*/React.cloneElement(option, props);
519 } else if (_isFunction(option)) {
520 rectangle = option(props);
521 } else {
522 rectangle = Brush.renderDefaultTraveller(props);
523 }
524
525 return rectangle;
526 }
527 }, {
528 key: "getDerivedStateFromProps",
529 value: function getDerivedStateFromProps(nextProps, prevState) {
530 var data = nextProps.data,
531 width = nextProps.width,
532 x = nextProps.x,
533 travellerWidth = nextProps.travellerWidth,
534 updateId = nextProps.updateId,
535 startIndex = nextProps.startIndex,
536 endIndex = nextProps.endIndex;
537
538 if (data !== prevState.prevData || updateId !== prevState.prevUpdateId) {
539 return _objectSpread({
540 prevData: data,
541 prevTravellerWidth: travellerWidth,
542 prevUpdateId: updateId,
543 prevX: x,
544 prevWidth: width
545 }, data && data.length ? createScale({
546 data: data,
547 width: width,
548 x: x,
549 travellerWidth: travellerWidth,
550 startIndex: startIndex,
551 endIndex: endIndex
552 }) : {
553 scale: null,
554 scaleValues: null
555 });
556 }
557
558 if (prevState.scale && (width !== prevState.prevWidth || x !== prevState.prevX || travellerWidth !== prevState.prevTravellerWidth)) {
559 prevState.scale.range([x, x + width - travellerWidth]);
560 var scaleValues = prevState.scale.domain().map(function (entry) {
561 return prevState.scale(entry);
562 });
563 return {
564 prevData: data,
565 prevTravellerWidth: travellerWidth,
566 prevUpdateId: updateId,
567 prevX: x,
568 prevWidth: width,
569 startX: prevState.scale(nextProps.startIndex),
570 endX: prevState.scale(nextProps.endIndex),
571 scaleValues: scaleValues
572 };
573 }
574
575 return null;
576 }
577 }, {
578 key: "getIndexInRange",
579 value: function getIndexInRange(range, x) {
580 var len = range.length;
581 var start = 0;
582 var end = len - 1;
583
584 while (end - start > 1) {
585 var middle = Math.floor((start + end) / 2);
586
587 if (range[middle] > x) {
588 end = middle;
589 } else {
590 start = middle;
591 }
592 }
593
594 return x >= range[end] ? end : start;
595 }
596 }]);
597
598 return Brush;
599}(PureComponent);
600Brush.displayName = 'Brush';
601Brush.defaultProps = {
602 height: 40,
603 travellerWidth: 5,
604 gap: 1,
605 fill: '#fff',
606 stroke: '#666',
607 padding: {
608 top: 1,
609 right: 1,
610 bottom: 1,
611 left: 1
612 },
613 leaveTimeOut: 1000,
614 alwaysShowText: false
615};
\No newline at end of file