forked from zillow/react-slider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
react-slider.js
800 lines (664 loc) · 24.1 KB
/
react-slider.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['react'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('react'));
} else {
root.ReactSlider = factory(root.React);
}
}(this, function (React) {
/**
* To prevent text selection while dragging.
* http://stackoverflow.com/questions/5429827/how-can-i-prevent-text-element-selection-with-cursor-drag
*/
function pauseEvent(e) {
if (e.stopPropagation) e.stopPropagation();
if (e.preventDefault) e.preventDefault();
e.cancelBubble = true;
e.returnValue = false;
return false;
}
function stopPropagation(e) {
if (e.stopPropagation) e.stopPropagation();
e.cancelBubble = true;
}
/**
* Spreads `count` values equally between `min` and `max`.
*/
function linspace(min, max, count) {
var range = (max - min) / (count - 1);
var res = [];
for (var i = 0; i < count; i++) {
res.push(min + range * i);
}
return res;
}
function ensureArray(x) {
return x == null ? [] : Array.isArray(x) ? x : [x];
}
function undoEnsureArray(x) {
return x != null && x.length === 1 ? x[0] : x;
}
// undoEnsureArray(ensureArray(x)) === x
var ReactSlider = React.createClass({
displayName: 'ReactSlider',
propTypes: {
/**
* The minimum value of the slider.
*/
min: React.PropTypes.number,
/**
* The maximum value of the slider.
*/
max: React.PropTypes.number,
/**
* Value to be added or subtracted on each step the slider makes.
* Must be greater than zero.
* `max - min` should be evenly divisible by the step value.
*/
step: React.PropTypes.number,
/**
* The minimal distance between any pair of handles.
* Must be positive, but zero means they can sit on top of each other.
*/
minDistance: React.PropTypes.number,
/**
* Determines the initial positions of the handles and the number of handles if the component has no children.
*
* If a number is passed a slider with one handle will be rendered.
* If an array is passed each value will determine the position of one handle.
* The values in the array must be sorted.
* If the component has children, the length of the array must match the number of children.
*/
defaultValue: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.arrayOf(React.PropTypes.number)
]),
/**
* Like `defaultValue` but for [controlled components](http://facebook.github.io/react/docs/forms.html#controlled-components).
*/
value: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.arrayOf(React.PropTypes.number)
]),
/**
* Determines whether the slider moves horizontally (from left to right) or vertically (from top to bottom).
*/
orientation: React.PropTypes.oneOf(['horizontal', 'vertical']),
/**
* The css class set on the slider node.
*/
className: React.PropTypes.string,
/**
* The css class set on each handle node.
*
* In addition each handle will receive a numbered css class of the form `${handleClassName}-${i}`,
* e.g. `handle-0`, `handle-1`, ...
*/
handleClassName: React.PropTypes.string,
/**
* The css class set on the handle that is currently being moved.
*/
handleActiveClassName: React.PropTypes.string,
/**
* If `true` bars between the handles will be rendered.
*/
withBars: React.PropTypes.bool,
/**
* The css class set on the bars between the handles.
* In addition bar fragment will receive a numbered css class of the form `${barClassName}-${i}`,
* e.g. `bar-0`, `bar-1`, ...
*/
barClassName: React.PropTypes.string,
/**
* If `true` the active handle will push other handles
* within the constraints of `min`, `max`, `step` and `minDistance`.
*/
pearling: React.PropTypes.bool,
/**
* If `true` the handles can't be moved.
*/
disabled: React.PropTypes.bool,
/**
* Disables handle move when clicking the slider bar
*/
snapDragDisabled: React.PropTypes.bool,
/**
* Inverts the slider.
*/
invert: React.PropTypes.bool,
/**
* Callback called before starting to move a handle.
*/
onBeforeChange: React.PropTypes.func,
/**
* Callback called on every value change.
*/
onChange: React.PropTypes.func,
/**
* Callback called only after moving a handle has ended.
*/
onAfterChange: React.PropTypes.func,
/**
* Callback called when the the slider is clicked (handle or bars).
* Receives the value at the clicked position as argument.
*/
onSliderClick: React.PropTypes.func
},
getDefaultProps: function () {
return {
min: 0,
max: 100,
step: 1,
minDistance: 0,
defaultValue: 0,
orientation: 'horizontal',
className: 'slider',
handleClassName: 'handle',
handleActiveClassName: 'active',
barClassName: 'bar',
withBars: false,
pearling: false,
disabled: false,
snapDragDisabled: false,
invert: false
};
},
getInitialState: function () {
var value = this._or(ensureArray(this.props.value), ensureArray(this.props.defaultValue));
// reused throughout the component to store results of iterations over `value`
this.tempArray = value.slice();
// array for storing resize timeouts ids
this.pendingResizeTimeouts = [];
var zIndices = [];
for (var i = 0; i < value.length; i++) {
value[i] = this._trimAlignValue(value[i], this.props);
zIndices.push(i);
}
return {
index: -1,
upperBound: 0,
sliderLength: 0,
value: value,
zIndices: zIndices
};
},
// Keep the internal `value` consistent with an outside `value` if present.
// This basically allows the slider to be a controlled component.
componentWillReceiveProps: function (newProps) {
var value = this._or(ensureArray(newProps.value), this.state.value);
// ensure the array keeps the same size as `value`
this.tempArray = value.slice();
for (var i = 0; i < value.length; i++) {
this.state.value[i] = this._trimAlignValue(value[i], newProps);
}
if (this.state.value.length > value.length)
this.state.value.length = value.length;
// If an upperBound has not yet been determined (due to the component being hidden
// during the mount event, or during the last resize), then calculate it now
if (this.state.upperBound === 0) {
this._handleResize();
}
},
// Check if the arity of `value` or `defaultValue` matches the number of children (= number of custom handles).
// If no custom handles are provided, just returns `value` if present and `defaultValue` otherwise.
// If custom handles are present but neither `value` nor `defaultValue` are applicable the handles are spread out
// equally.
// TODO: better name? better solution?
_or: function (value, defaultValue) {
var count = React.Children.count(this.props.children);
switch (count) {
case 0:
return value.length > 0 ? value : defaultValue;
case value.length:
return value;
case defaultValue.length:
return defaultValue;
default:
if (value.length !== count || defaultValue.length !== count) {
console.warn(this.constructor.displayName + ": Number of values does not match number of children.");
}
return linspace(this.props.min, this.props.max, count);
}
},
componentDidMount: function () {
window.addEventListener('resize', this._handleResize);
this._handleResize();
},
componentWillUnmount: function () {
this._clearPendingResizeTimeouts();
window.removeEventListener('resize', this._handleResize);
},
getValue: function () {
return undoEnsureArray(this.state.value);
},
_handleResize: function () {
// setTimeout of 0 gives element enough time to have assumed its new size if it is being resized
var resizeTimeout = window.setTimeout(function() {
// drop this timeout from pendingResizeTimeouts to reduce memory usage
this.pendingResizeTimeouts.shift();
var slider = this.refs.slider;
var handle = this.refs.handle0;
var rect = null;
if (typeof(slider) != 'undefined' && slider != null) {
if (typeof(slider.getBoundingClientRect) != 'undefined') {
rect = slider.getBoundingClientRect();
} else if (typeof(slider.getDOMNode) == 'function' && typeof(slider.getDOMNode().getBoundingClientRect) == 'function') {
rect = slider.getDOMNode().getBoundingClientRect();
}
}
var size = this._sizeKey();
var sliderMax = rect[this._posMaxKey()];
var sliderMin = rect[this._posMinKey()];
this.setState({
upperBound: slider[size] - handle[size],
sliderLength: Math.abs(sliderMax - sliderMin),
handleSize: handle[size],
sliderStart: this.props.invert ? sliderMax : sliderMin
});
}.bind(this), 0);
this.pendingResizeTimeouts.push(resizeTimeout);
},
// clear all pending timeouts to avoid error messages after unmounting
_clearPendingResizeTimeouts: function() {
do {
var nextTimeout = this.pendingResizeTimeouts.shift();
clearTimeout(nextTimeout);
} while (this.pendingResizeTimeouts.length);
},
// calculates the offset of a handle in pixels based on its value.
_calcOffset: function (value) {
var ratio = (value - this.props.min) / (this.props.max - this.props.min);
return ratio * this.state.upperBound;
},
// calculates the value corresponding to a given pixel offset, i.e. the inverse of `_calcOffset`.
_calcValue: function (offset) {
var ratio = offset / this.state.upperBound;
return ratio * (this.props.max - this.props.min) + this.props.min;
},
_buildHandleStyle: function (offset, i) {
var style = {
position: 'absolute',
willChange: this.state.index >= 0 ? this._posMinKey() : '',
zIndex: this.state.zIndices.indexOf(i) + 1
};
style[this._posMinKey()] = offset + 'px';
return style;
},
_buildBarStyle: function (min, max) {
var obj = {
position: 'absolute',
willChange: this.state.index >= 0 ? this._posMinKey() + ',' + this._posMaxKey() : ''
};
obj[this._posMinKey()] = min;
obj[this._posMaxKey()] = max;
return obj;
},
_getClosestIndex: function (pixelOffset) {
var minDist = Number.MAX_VALUE;
var closestIndex = -1;
var value = this.state.value;
var l = value.length;
for (var i = 0; i < l; i++) {
var offset = this._calcOffset(value[i]);
var dist = Math.abs(pixelOffset - offset);
if (dist < minDist) {
minDist = dist;
closestIndex = i;
}
}
return closestIndex;
},
_calcOffsetFromPosition: function (position) {
var pixelOffset = position - this.state.sliderStart;
if (this.props.invert) pixelOffset = this.state.sliderLength - pixelOffset;
pixelOffset -= (this.state.handleSize / 2);
return pixelOffset;
},
// Snaps the nearest handle to the value corresponding to `position` and calls `callback` with that handle's index.
_forceValueFromPosition: function (position, callback) {
var pixelOffset = this._calcOffsetFromPosition(position);
var closestIndex = this._getClosestIndex(pixelOffset);
var nextValue = this._trimAlignValue(this._calcValue(pixelOffset));
var value = this.state.value.slice(); // Clone this.state.value since we'll modify it temporarily
value[closestIndex] = nextValue;
// Prevents the slider from shrinking below `props.minDistance`
for (var i = 0; i < value.length - 1; i += 1) {
if (value[i + 1] - value[i] < this.props.minDistance) return;
}
this.setState({value: value}, callback.bind(this, closestIndex));
},
_getMousePosition: function (e) {
return [
e['page' + this._axisKey()],
e['page' + this._orthogonalAxisKey()]
];
},
_getTouchPosition: function (e) {
var touch = e.touches[0];
return [
touch['page' + this._axisKey()],
touch['page' + this._orthogonalAxisKey()]
];
},
_getMouseEventMap: function () {
return {
'mousemove': this._onMouseMove,
'mouseup': this._onMouseUp
}
},
_getTouchEventMap: function () {
return {
'touchmove': this._onTouchMove,
'touchend': this._onTouchEnd
}
},
// create the `mousedown` handler for the i-th handle
_createOnMouseDown: function (i) {
return function (e) {
if (this.props.disabled) return;
var position = this._getMousePosition(e);
this._start(i, position[0]);
this._addHandlers(this._getMouseEventMap());
pauseEvent(e);
}.bind(this);
},
// create the `touchstart` handler for the i-th handle
_createOnTouchStart: function (i) {
return function (e) {
if (this.props.disabled || e.touches.length > 1) return;
var position = this._getTouchPosition(e);
this.startPosition = position;
this.isScrolling = undefined; // don't know yet if the user is trying to scroll
this._start(i, position[0]);
this._addHandlers(this._getTouchEventMap());
stopPropagation(e);
}.bind(this);
},
_addHandlers: function (eventMap) {
for (var key in eventMap) {
document.addEventListener(key, eventMap[key], false);
}
},
_removeHandlers: function (eventMap) {
for (var key in eventMap) {
document.removeEventListener(key, eventMap[key], false);
}
},
_start: function (i, position) {
// if activeElement is body window will lost focus in IE9
if (document.activeElement && document.activeElement != document.body) {
document.activeElement.blur();
}
this.hasMoved = false;
this._fireChangeEvent('onBeforeChange');
var zIndices = this.state.zIndices;
zIndices.splice(zIndices.indexOf(i), 1); // remove wherever the element is
zIndices.push(i); // add to end
this.setState({
startValue: this.state.value[i],
startPosition: position,
index: i,
zIndices: zIndices
});
},
_onMouseUp: function () {
this._onEnd(this._getMouseEventMap());
},
_onTouchEnd: function () {
this._onEnd(this._getTouchEventMap());
},
_onEnd: function (eventMap) {
this._removeHandlers(eventMap);
this.setState({index: -1}, this._fireChangeEvent.bind(this, 'onAfterChange'));
},
_onMouseMove: function (e) {
var position = this._getMousePosition(e);
this._move(position[0]);
},
_onTouchMove: function (e) {
if (e.touches.length > 1) return;
var position = this._getTouchPosition(e);
if (typeof this.isScrolling === 'undefined') {
var diffMainDir = position[0] - this.startPosition[0];
var diffScrollDir = position[1] - this.startPosition[1];
this.isScrolling = Math.abs(diffScrollDir) > Math.abs(diffMainDir);
}
if (this.isScrolling) {
this.setState({index: -1});
return;
}
pauseEvent(e);
this._move(position[0]);
},
_move: function (position) {
this.hasMoved = true;
var props = this.props;
var state = this.state;
var index = state.index;
var value = state.value;
var length = value.length;
var oldValue = value[index];
var diffPosition = position - state.startPosition;
if (props.invert) diffPosition *= -1;
var diffValue = diffPosition / (state.sliderLength - state.handleSize) * (props.max - props.min);
var newValue = this._trimAlignValue(state.startValue + diffValue);
var minDistance = props.minDistance;
// if "pearling" (= handles pushing each other) is disabled,
// prevent the handle from getting closer than `minDistance` to the previous or next handle.
if (!props.pearling) {
if (index > 0) {
var valueBefore = value[index - 1];
if (newValue < valueBefore + minDistance) {
newValue = valueBefore + minDistance;
}
}
if (index < length - 1) {
var valueAfter = value[index + 1];
if (newValue > valueAfter - minDistance) {
newValue = valueAfter - minDistance;
}
}
}
value[index] = newValue;
// if "pearling" is enabled, let the current handle push the pre- and succeeding handles.
if (props.pearling && length > 1) {
if (newValue > oldValue) {
this._pushSucceeding(value, minDistance, index);
this._trimSucceeding(length, value, minDistance, props.max);
}
else if (newValue < oldValue) {
this._pushPreceding(value, minDistance, index);
this._trimPreceding(length, value, minDistance, props.min);
}
}
// Normally you would use `shouldComponentUpdate`, but since the slider is a low-level component,
// the extra complexity might be worth the extra performance.
if (newValue !== oldValue) {
this.setState({value: value}, this._fireChangeEvent.bind(this, 'onChange'));
}
},
_pushSucceeding: function (value, minDistance, index) {
var i, padding;
for (i = index, padding = value[i] + minDistance;
value[i + 1] != null && padding > value[i + 1];
i++, padding = value[i] + minDistance) {
value[i + 1] = this._alignValue(padding);
}
},
_trimSucceeding: function (length, nextValue, minDistance, max) {
for (var i = 0; i < length; i++) {
var padding = max - i * minDistance;
if (nextValue[length - 1 - i] > padding) {
nextValue[length - 1 - i] = padding;
}
}
},
_pushPreceding: function (value, minDistance, index) {
var i, padding;
for (i = index, padding = value[i] - minDistance;
value[i - 1] != null && padding < value[i - 1];
i--, padding = value[i] - minDistance) {
value[i - 1] = this._alignValue(padding);
}
},
_trimPreceding: function (length, nextValue, minDistance, min) {
for (var i = 0; i < length; i++) {
var padding = min + i * minDistance;
if (nextValue[i] < padding) {
nextValue[i] = padding;
}
}
},
_axisKey: function () {
var orientation = this.props.orientation;
if (orientation === 'horizontal') return 'X';
if (orientation === 'vertical') return 'Y';
},
_orthogonalAxisKey: function () {
var orientation = this.props.orientation;
if (orientation === 'horizontal') return 'Y';
if (orientation === 'vertical') return 'X';
},
_posMinKey: function () {
var orientation = this.props.orientation;
if (orientation === 'horizontal') return this.props.invert ? 'right' : 'left';
if (orientation === 'vertical') return this.props.invert ? 'bottom' : 'top';
},
_posMaxKey: function () {
var orientation = this.props.orientation;
if (orientation === 'horizontal') return this.props.invert ? 'left' : 'right';
if (orientation === 'vertical') return this.props.invert ? 'top' : 'bottom';
},
_sizeKey: function () {
var orientation = this.props.orientation;
if (orientation === 'horizontal') return 'clientWidth';
if (orientation === 'vertical') return 'clientHeight';
},
_trimAlignValue: function (val, props) {
return this._alignValue(this._trimValue(val, props), props);
},
_trimValue: function (val, props) {
props = props || this.props;
if (val <= props.min) val = props.min;
if (val >= props.max) val = props.max;
return val;
},
_alignValue: function (val, props) {
props = props || this.props;
var valModStep = (val - props.min) % props.step;
var alignValue = val - valModStep;
if (Math.abs(valModStep) * 2 >= props.step) {
alignValue += (valModStep > 0) ? props.step : (-props.step);
}
return parseFloat(alignValue.toFixed(5));
},
_renderHandle: function (style, child, i) {
var className = this.props.handleClassName + ' ' +
(this.props.handleClassName + '-' + i) + ' ' +
(this.state.index === i ? this.props.handleActiveClassName : '');
return (
React.createElement('div', {
ref: 'handle' + i,
key: 'handle' + i,
className: className,
style: style,
onMouseDown: this._createOnMouseDown(i),
onTouchStart: this._createOnTouchStart(i)
},
child
)
);
},
_renderHandles: function (offset) {
var length = offset.length;
var styles = this.tempArray;
for (var i = 0; i < length; i++) {
styles[i] = this._buildHandleStyle(offset[i], i);
}
var res = this.tempArray;
var renderHandle = this._renderHandle;
if (React.Children.count(this.props.children) > 0) {
React.Children.forEach(this.props.children, function (child, i) {
res[i] = renderHandle(styles[i], child, i);
});
} else {
for (i = 0; i < length; i++) {
res[i] = renderHandle(styles[i], null, i);
}
}
return res;
},
_renderBar: function (i, offsetFrom, offsetTo) {
return (
React.createElement('div', {
key: 'bar' + i,
ref: 'bar' + i,
className: this.props.barClassName + ' ' + this.props.barClassName + '-' + i,
style: this._buildBarStyle(offsetFrom, this.state.upperBound - offsetTo)
})
);
},
_renderBars: function (offset) {
var bars = [];
var lastIndex = offset.length - 1;
bars.push(this._renderBar(0, 0, offset[0]));
for (var i = 0; i < lastIndex; i++) {
bars.push(this._renderBar(i + 1, offset[i], offset[i + 1]));
}
bars.push(this._renderBar(lastIndex + 1, offset[lastIndex], this.state.upperBound));
return bars;
},
_onSliderMouseDown: function (e) {
if (this.props.disabled) return;
this.hasMoved = false;
if (!this.props.snapDragDisabled) {
var position = this._getMousePosition(e);
this._forceValueFromPosition(position[0], function (i) {
this._fireChangeEvent('onChange');
this._start(i, position[0]);
this._addHandlers(this._getMouseEventMap());
}.bind(this));
}
pauseEvent(e);
},
_onSliderClick: function (e) {
if (this.props.disabled) return;
if (this.props.onSliderClick && !this.hasMoved) {
var position = this._getMousePosition(e);
var valueAtPos = this._trimAlignValue(this._calcValue(this._calcOffsetFromPosition(position[0])));
this.props.onSliderClick(valueAtPos);
}
},
_fireChangeEvent: function (event) {
if (this.props[event]) {
this.props[event](undoEnsureArray(this.state.value));
}
},
render: function () {
var state = this.state;
var props = this.props;
var offset = this.tempArray;
var value = state.value;
var l = value.length;
for (var i = 0; i < l; i++) {
offset[i] = this._calcOffset(value[i], i);
}
var bars = props.withBars ? this._renderBars(offset) : null;
var handles = this._renderHandles(offset);
return (
React.createElement('div', {
ref: 'slider',
style: {position: 'relative'},
className: props.className + (props.disabled ? ' disabled' : ''),
onMouseDown: this._onSliderMouseDown,
onClick: this._onSliderClick
},
bars,
handles
)
);
}
});
return ReactSlider;
}));