/
ReactSlider.jsx
1027 lines (880 loc) · 32 KB
/
ReactSlider.jsx
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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React from 'react';
import PropTypes from 'prop-types';
/**
* 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 && e.stopPropagation) {
e.stopPropagation();
}
if (e && e.preventDefault) {
e.preventDefault();
}
return false;
}
function stopPropagation(e) {
if (e.stopPropagation) {
e.stopPropagation();
}
}
function sanitizeInValue(x) {
if (x == null) {
return [];
}
return Array.isArray(x) ? x.slice() : [x];
}
function prepareOutValue(x) {
return x !== null && x.length === 1 ? x[0] : x.slice();
}
function trimSucceeding(length, nextValue, minDistance, max) {
for (let i = 0; i < length; i += 1) {
const padding = max - i * minDistance;
if (nextValue[length - 1 - i] > padding) {
// eslint-disable-next-line no-param-reassign
nextValue[length - 1 - i] = padding;
}
}
}
function trimPreceding(length, nextValue, minDistance, min) {
for (let i = 0; i < length; i += 1) {
const padding = min + i * minDistance;
if (nextValue[i] < padding) {
// eslint-disable-next-line no-param-reassign
nextValue[i] = padding;
}
}
}
function addHandlers(eventMap) {
Object.keys(eventMap).forEach(key => {
if (typeof document !== 'undefined') {
document.addEventListener(key, eventMap[key], false);
}
});
}
function removeHandlers(eventMap) {
Object.keys(eventMap).forEach(key => {
if (typeof document !== 'undefined') {
document.removeEventListener(key, eventMap[key], false);
}
});
}
class ReactSlider extends React.Component {
static displayName = 'ReactSlider';
static propTypes = {
/**
* The minimum value of the slider.
*/
min: PropTypes.number,
/**
* The maximum value of the slider.
*/
max: 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: PropTypes.number,
/**
* The result of the function is the value to be added or subtracted
* when the `Page Up` or `Page Down` keys are pressed.
*
* The current `step` value will be passed as the only argument.
* By default, paging will modify `step` by a factor of 10.
*/
pageFn: PropTypes.func,
/**
* The minimal distance between any pair of thumbs.
* Must be positive, but zero means they can sit on top of each other.
*/
minDistance: PropTypes.number,
/**
* Determines the initial positions of the thumbs and the number of thumbs.
*
* If a number is passed a slider with one thumb will be rendered.
* If an array is passed each value will determine the position of one thumb.
* The values in the array must be sorted.
*/
defaultValue: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.number)]),
/**
* Like `defaultValue` but for
* [controlled components](http://facebook.github.io/react/docs/forms.html#controlled-components).
*/
// eslint-disable-next-line zillow/react/require-default-props
value: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.number)]),
/**
* Determines whether the slider moves horizontally (from left to right)
* or vertically (from top to bottom).
*/
orientation: PropTypes.oneOf(['horizontal', 'vertical']),
/**
* The css class set on the slider node.
*/
className: PropTypes.string,
/**
* The css class set on each thumb node.
*
* In addition each thumb will receive a numbered css class of the form
* `${thumbClassName}-${i}`, e.g. `thumb-0`, `thumb-1`, ...
*/
thumbClassName: PropTypes.string,
/**
* The css class set on the thumb that is currently being moved.
*/
thumbActiveClassName: PropTypes.string,
/**
* If `true` tracks between the thumbs will be rendered.
*/
withTracks: PropTypes.bool,
/**
* The css class set on the tracks between the thumbs.
* In addition track fragment will receive a numbered css class of the form
* `${trackClassName}-${i}`, e.g. `track-0`, `track-1`, ...
*/
trackClassName: PropTypes.string,
/**
* If `true` the active thumb will push other thumbs
* within the constraints of `min`, `max`, `step` and `minDistance`.
*/
pearling: PropTypes.bool,
/**
* If `true` the thumbs can't be moved.
*/
disabled: PropTypes.bool,
/**
* Disables thumb move when clicking the slider track
*/
snapDragDisabled: PropTypes.bool,
/**
* Inverts the slider.
*/
invert: PropTypes.bool,
/**
* Callback called before starting to move a thumb. The callback will only be called if the
* action will result in a change. The function will be called with one argument,
* the initial value(s).
*/
// eslint-disable-next-line max-len
// eslint-disable-next-line zillow/react/require-default-props, zillow/react/no-unused-prop-types
onBeforeChange: PropTypes.func,
/**
* Callback called on every value change.
* The function will be called with one argument, the new value(s).
*/
// eslint-disable-next-line max-len
// eslint-disable-next-line zillow/react/require-default-props, zillow/react/no-unused-prop-types
onChange: PropTypes.func,
/**
* Callback called only after moving a thumb has ended. The callback will only be called if
* the action resulted in a change. The function will be called with one argument,
* the result value(s).
*/
// eslint-disable-next-line max-len
// eslint-disable-next-line zillow/react/require-default-props, zillow/react/no-unused-prop-types
onAfterChange: PropTypes.func,
/**
* Callback called when the the slider is clicked (thumb or tracks).
* Receives the value at the clicked position as argument.
*/
// eslint-disable-next-line zillow/react/require-default-props
onSliderClick: PropTypes.func,
/**
* aria-label for screen-readers to apply to the thumbs.
* Use an array for more than one thumb.
* The length of the array must match the number of thumbs in the value array.
*/
// eslint-disable-next-line zillow/react/require-default-props
ariaLabel: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
/**
* aria-valuetext for screen-readers.
* Can be a static string, or a function that returns a string.
* The function will be passed a single argument,
* an object with the following properties:
*
* state => `Value: ${state.value}`
*
* - `state.index` {`number`} the index of the thumb
* - `state.value` {`number` | `array`} the current value state
* - `state.valueNow` {`number`} the value of the thumb (i.e. aria-valuenow)
*/
// eslint-disable-next-line zillow/react/require-default-props
ariaValuetext: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
/**
* Provide a custom render function for the track node.
* The render function will be passed two arguments,
* an object with props that should be added to your handle node,
* and an object with track and slider state:
*
* (props, state) => <div {...props} />
*
* - `props` {`object`} props to be spread into your track node
* - `state.index` {`number`} the index of the track
* - `state.value` {`number` | `array`} the current value state
*/
renderTrack: PropTypes.func,
/**
* Provide a custom render function for dynamic thumb content.
* The render function will be passed two arguments,
* an object with props that should be added to your thumb node,
* and an object with thumb and slider state:
*
* (props, state) => <div {...props} />
*
* - `props` {`object`} props to be spread into your thumb node
* - `state.index` {`number`} the index of the thumb
* - `state.value` {`number` | `array`} the current value state
* - `state.valueNow` {`number`} the value of the thumb (i.e. aria-valuenow)
*/
// eslint-disable-next-line zillow/react/require-default-props
renderThumb: PropTypes.func,
};
static defaultProps = {
min: 0,
max: 100,
step: 1,
pageFn: step => step * 10,
minDistance: 0,
defaultValue: 0,
orientation: 'horizontal',
className: 'slider',
thumbClassName: 'thumb',
thumbActiveClassName: 'active',
trackClassName: 'track',
withTracks: true,
pearling: false,
disabled: false,
snapDragDisabled: false,
invert: false,
renderThumb: props => <div {...props} />,
renderTrack: props => <div {...props} />,
};
constructor(props) {
super(props);
let value = sanitizeInValue(props.value);
if (!value.length) {
value = sanitizeInValue(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 = [];
const zIndices = [];
for (let i = 0; i < value.length; i += 1) {
value[i] = this.trimAlignValue(value[i], props);
zIndices.push(i);
}
this.state = {
index: -1,
upperBound: 0,
sliderLength: 0,
value,
zIndices,
};
}
componentDidMount() {
if (typeof window !== 'undefined') {
window.addEventListener('resize', this.handleResize);
this.resize();
}
}
// Keep the internal `value` consistent with an outside `value` if present.
// This basically allows the slider to be a controlled component.
UNSAFE_componentWillReceiveProps(newProps) {
let value = sanitizeInValue(newProps.value);
if (!value.length) {
// eslint-disable-next-line prefer-destructuring
value = this.state.value;
}
// ensure the array keeps the same size as `value`
this.tempArray = value.slice();
for (let i = 0; i < value.length; i += 1) {
this.state.value[i] = this.trimAlignValue(value[i], newProps);
}
if (this.state.value.length > value.length) {
this.state.value.length = value.length;
}
}
componentDidUpdate() {
// 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.resize();
}
}
componentWillUnmount() {
this.clearPendingResizeTimeouts();
if (typeof window !== 'undefined') {
window.removeEventListener('resize', this.handleResize);
}
}
onKeyUp = () => {
this.onEnd();
};
onMouseUp = () => {
this.onEnd(this.getMouseEventMap());
};
onTouchEnd = () => {
this.onEnd(this.getTouchEventMap());
};
onBlur = () => {
this.setState({ index: -1 }, this.onEnd(this.getKeyDownEventMap()));
};
onEnd(eventMap) {
if (eventMap) {
removeHandlers(eventMap);
}
if (this.hasMoved) {
this.fireChangeEvent('onAfterChange');
}
this.hasMoved = false;
}
onMouseMove = e => {
const position = this.getMousePosition(e);
const diffPosition = this.getDiffPosition(position[0]);
const newValue = this.getValueFromPosition(diffPosition);
this.move(newValue);
};
onTouchMove = e => {
if (e.touches.length > 1) {
return;
}
const position = this.getTouchPosition(e);
if (typeof this.isScrolling === 'undefined') {
const diffMainDir = position[0] - this.startPosition[0];
const diffScrollDir = position[1] - this.startPosition[1];
this.isScrolling = Math.abs(diffScrollDir) > Math.abs(diffMainDir);
}
if (this.isScrolling) {
this.setState({ index: -1 });
return;
}
const diffPosition = this.getDiffPosition(position[0]);
const newValue = this.getValueFromPosition(diffPosition);
this.move(newValue);
};
onKeyDown = e => {
if (e.ctrlKey || e.shiftKey || e.altKey) {
return;
}
switch (e.key) {
case 'ArrowLeft':
case 'ArrowDown':
case 'Left':
case 'Down':
e.preventDefault();
this.moveDownByStep();
break;
case 'ArrowRight':
case 'ArrowUp':
case 'Right':
case 'Up':
e.preventDefault();
this.moveUpByStep();
break;
case 'Home':
e.preventDefault();
this.move(this.props.min);
break;
case 'End':
e.preventDefault();
this.move(this.props.max);
break;
case 'PageDown':
e.preventDefault();
this.moveDownByStep(this.props.pageFn(this.props.step));
break;
case 'PageUp':
e.preventDefault();
this.moveUpByStep(this.props.pageFn(this.props.step));
break;
default:
}
};
onSliderMouseDown = e => {
// do nothing if disabled or right click
if (this.props.disabled || e.button === 2) {
return;
}
this.hasMoved = false;
if (!this.props.snapDragDisabled) {
const position = this.getMousePosition(e);
this.forceValueFromPosition(position[0], i => {
this.start(i, position[0]);
this.fireChangeEvent('onChange');
addHandlers(this.getMouseEventMap());
});
}
pauseEvent(e);
};
onSliderClick = e => {
if (this.props.disabled) {
return;
}
if (this.props.onSliderClick && !this.hasMoved) {
const position = this.getMousePosition(e);
const valueAtPos = this.trimAlignValue(
this.calcValue(this.calcOffsetFromPosition(position[0]))
);
this.props.onSliderClick(valueAtPos);
}
};
getValue() {
return prepareOutValue(this.state.value);
}
getClosestIndex(pixelOffset) {
let minDist = Number.MAX_VALUE;
let closestIndex = -1;
const { value } = this.state;
const l = value.length;
for (let i = 0; i < l; i += 1) {
const offset = this.calcOffset(value[i]);
const dist = Math.abs(pixelOffset - offset);
if (dist < minDist) {
minDist = dist;
closestIndex = i;
}
}
return closestIndex;
}
getMousePosition(e) {
return [e[`page${this.axisKey()}`], e[`page${this.orthogonalAxisKey()}`]];
}
getTouchPosition(e) {
const touch = e.touches[0];
return [touch[`page${this.axisKey()}`], touch[`page${this.orthogonalAxisKey()}`]];
}
getKeyDownEventMap() {
return {
keydown: this.onKeyDown,
keyup: this.onKeyUp,
focusout: this.onBlur,
};
}
getMouseEventMap() {
return {
mousemove: this.onMouseMove,
mouseup: this.onMouseUp,
};
}
getTouchEventMap() {
return {
touchmove: this.onTouchMove,
touchend: this.onTouchEnd,
};
}
getValueFromPosition(position) {
const diffValue =
(position / (this.state.sliderLength - this.state.thumbSize)) *
(this.props.max - this.props.min);
return this.trimAlignValue(this.state.startValue + diffValue);
}
getDiffPosition(position) {
let diffPosition = position - this.state.startPosition;
if (this.props.invert) {
diffPosition *= -1;
}
return diffPosition;
}
// create the `keydown` handler for the i-th thumb
createOnKeyDown = i => e => {
if (this.props.disabled) {
return;
}
this.start(i);
addHandlers(this.getKeyDownEventMap());
pauseEvent(e);
};
// create the `mousedown` handler for the i-th thumb
createOnMouseDown = i => e => {
// do nothing if disabled or right click
if (this.props.disabled || e.button === 2) {
return;
}
const position = this.getMousePosition(e);
this.start(i, position[0]);
addHandlers(this.getMouseEventMap());
pauseEvent(e);
};
// create the `touchstart` handler for the i-th thumb
createOnTouchStart = i => e => {
if (this.props.disabled || e.touches.length > 1) {
return;
}
const position = this.getTouchPosition(e);
this.startPosition = position;
// don't know yet if the user is trying to scroll
this.isScrolling = undefined;
this.start(i, position[0]);
addHandlers(this.getTouchEventMap());
stopPropagation(e);
};
handleResize = () => {
// setTimeout of 0 gives element enough time to have assumed its new size if
// it is being resized
const resizeTimeout = window.setTimeout(() => {
// drop this timeout from pendingResizeTimeouts to reduce memory usage
this.pendingResizeTimeouts.shift();
this.resize();
}, 0);
this.pendingResizeTimeouts.push(resizeTimeout);
};
resize() {
const { slider, thumb0: thumb } = this;
if (!slider || !thumb) {
return;
}
const sizeKey = this.sizeKey();
// For the slider size, we want to use the client width/height, excluding any borders
const sliderRect = slider.getBoundingClientRect();
const sliderSize = slider[sizeKey];
const sliderMax = sliderRect[this.posMaxKey()];
const sliderMin = sliderRect[this.posMinKey()];
// For the thumb size, we want to use the outer width/height, including any borders
const thumbRect = thumb.getBoundingClientRect();
const thumbSize = thumbRect[sizeKey.replace('client', '').toLowerCase()];
const upperBound = sliderSize - thumbSize;
const sliderLength = Math.abs(sliderMax - sliderMin);
if (
this.state.upperBound !== upperBound ||
this.state.sliderLength !== sliderLength ||
this.state.thumbSize !== thumbSize
) {
this.setState({
upperBound,
sliderLength,
thumbSize,
});
}
}
// calculates the offset of a thumb in pixels based on its value.
calcOffset(value) {
const range = this.props.max - this.props.min;
if (range === 0) {
return 0;
}
const ratio = (value - this.props.min) / range;
return ratio * this.state.upperBound;
}
// calculates the value corresponding to a given pixel offset, i.e. the inverse of `calcOffset`.
calcValue(offset) {
const ratio = offset / this.state.upperBound;
return ratio * (this.props.max - this.props.min) + this.props.min;
}
calcOffsetFromPosition(position) {
const { slider } = this;
const sliderRect = slider.getBoundingClientRect();
const sliderMax = sliderRect[this.posMaxKey()];
const sliderMin = sliderRect[this.posMinKey()];
// The `position` value passed in is the mouse position based on the window height.
// The slider bounding rect is based on the viewport, so we must add the window scroll
// offset to normalize the values.
const windowOffset = window[`page${this.axisKey()}Offset`];
const sliderStart = windowOffset + (this.props.invert ? sliderMax : sliderMin);
let pixelOffset = position - sliderStart;
if (this.props.invert) {
pixelOffset = this.state.sliderLength - pixelOffset;
}
pixelOffset -= this.state.thumbSize / 2;
return pixelOffset;
}
// Snaps the nearest thumb to the value corresponding to `position`
// and calls `callback` with that thumb's index.
forceValueFromPosition(position, callback) {
const pixelOffset = this.calcOffsetFromPosition(position);
const closestIndex = this.getClosestIndex(pixelOffset);
const nextValue = this.trimAlignValue(this.calcValue(pixelOffset));
// Clone this.state.value since we'll modify it temporarily
// eslint-disable-next-line zillow/react/no-access-state-in-setstate
const value = this.state.value.slice();
value[closestIndex] = nextValue;
// Prevents the slider from shrinking below `props.minDistance`
for (let i = 0; i < value.length - 1; i += 1) {
if (value[i + 1] - value[i] < this.props.minDistance) {
return;
}
}
this.setState({ value }, callback.bind(this, closestIndex));
}
// clear all pending timeouts to avoid error messages after unmounting
clearPendingResizeTimeouts() {
do {
const nextTimeout = this.pendingResizeTimeouts.shift();
clearTimeout(nextTimeout);
} while (this.pendingResizeTimeouts.length);
}
start(i, position) {
const thumbRef = this[`thumb${i}`];
if (thumbRef) {
thumbRef.focus();
}
this.hasMoved = false;
const { zIndices } = this.state;
// remove wherever the element is
zIndices.splice(zIndices.indexOf(i), 1);
// add to end
zIndices.push(i);
this.setState(prevState => ({
startValue: prevState.value[i],
startPosition: position !== undefined ? position : prevState.startPosition,
index: i,
zIndices,
}));
}
moveUpByStep(step = this.props.step) {
const oldValue = this.state.value[this.state.index];
const newValue = oldValue + step;
this.move(Math.min(newValue, this.props.max));
}
moveDownByStep(step = this.props.step) {
const oldValue = this.state.value[this.state.index];
const newValue = oldValue - step;
this.move(Math.max(newValue, this.props.min));
}
move(newValue) {
const { index, value } = this.state;
const { length } = value;
// Short circuit if the value is not changing
const oldValue = value[index];
if (newValue === oldValue) {
return;
}
// Trigger only before the first movement
if (!this.hasMoved) {
this.fireChangeEvent('onBeforeChange');
}
this.hasMoved = true;
// if "pearling" (= thumbs pushing each other) is disabled,
// prevent the thumb from getting closer than `minDistance` to the previous or next thumb.
const { pearling, max, min, minDistance } = this.props;
if (!pearling) {
if (index > 0) {
const valueBefore = value[index - 1];
if (newValue < valueBefore + minDistance) {
// eslint-disable-next-line no-param-reassign
newValue = valueBefore + minDistance;
}
}
if (index < length - 1) {
const valueAfter = value[index + 1];
if (newValue > valueAfter - minDistance) {
// eslint-disable-next-line no-param-reassign
newValue = valueAfter - minDistance;
}
}
}
value[index] = newValue;
// if "pearling" is enabled, let the current thumb push the pre- and succeeding thumbs.
if (pearling && length > 1) {
if (newValue > oldValue) {
this.pushSucceeding(value, minDistance, index);
trimSucceeding(length, value, minDistance, max);
} else if (newValue < oldValue) {
this.pushPreceding(value, minDistance, index);
trimPreceding(length, value, minDistance, min);
}
}
// Normally you would use `shouldComponentUpdate`,
// but since the slider is a low-level component,
// the extra complexity might be worth the extra performance.
this.setState({ value }, this.fireChangeEvent.bind(this, 'onChange'));
}
pushSucceeding(value, minDistance, index) {
let i;
let padding;
for (
i = index, padding = value[i] + minDistance;
value[i + 1] !== null && padding > value[i + 1];
i += 1, padding = value[i] + minDistance
) {
// eslint-disable-next-line no-param-reassign
value[i + 1] = this.alignValue(padding);
}
}
pushPreceding(value, minDistance, index) {
for (
let i = index, padding = value[i] - minDistance;
value[i - 1] !== null && padding < value[i - 1];
i -= 1, padding = value[i] - minDistance
) {
// eslint-disable-next-line no-param-reassign
value[i - 1] = this.alignValue(padding);
}
}
axisKey() {
if (this.props.orientation === 'vertical') {
return 'Y';
}
// Defaults to 'horizontal';
return 'X';
}
orthogonalAxisKey() {
if (this.props.orientation === 'vertical') {
return 'X';
}
// Defaults to 'horizontal'
return 'Y';
}
posMinKey() {
if (this.props.orientation === 'vertical') {
return this.props.invert ? 'bottom' : 'top';
}
// Defaults to 'horizontal'
return this.props.invert ? 'right' : 'left';
}
posMaxKey() {
if (this.props.orientation === 'vertical') {
return this.props.invert ? 'top' : 'bottom';
}
// Defaults to 'horizontal'
return this.props.invert ? 'left' : 'right';
}
sizeKey() {
if (this.props.orientation === 'vertical') {
return 'clientHeight';
}
// Defaults to 'horizontal'
return 'clientWidth';
}
trimAlignValue(val, props) {
return this.alignValue(this.trimValue(val, props), props);
}
trimValue(val, props = this.props) {
let trimmed = val;
if (trimmed <= props.min) {
trimmed = props.min;
}
if (trimmed >= props.max) {
trimmed = props.max;
}
return trimmed;
}
alignValue(val, props = this.props) {
const valModStep = (val - props.min) % props.step;
let alignValue = val - valModStep;
if (Math.abs(valModStep) * 2 >= props.step) {
alignValue += valModStep > 0 ? props.step : -props.step;
}
return parseFloat(alignValue.toFixed(5));
}
fireChangeEvent(event) {
if (this.props[event]) {
this.props[event](prepareOutValue(this.state.value));
}
}
buildThumbStyle(offset, i) {
const style = {
position: 'absolute',
touchAction: 'none',
willChange: this.state.index >= 0 ? this.posMinKey() : '',
zIndex: this.state.zIndices.indexOf(i) + 1,
};
style[this.posMinKey()] = `${offset}px`;
return style;
}
buildTrackStyle(min, max) {
const obj = {
position: 'absolute',
willChange: this.state.index >= 0 ? `${this.posMinKey()},${this.posMaxKey()}` : '',
};
obj[this.posMinKey()] = min;
obj[this.posMaxKey()] = max;
return obj;
}
renderThumb = (style, i) => {
const className = `${this.props.thumbClassName} ${this.props.thumbClassName}-${i} ${
this.state.index === i ? this.props.thumbActiveClassName : ''
}`;
const props = {
'ref': r => {
this[`thumb${i}`] = r;
},
'key': `${this.props.thumbClassName}-${i}`,
className,
style,
'onMouseDown': this.createOnMouseDown(i),
'onTouchStart': this.createOnTouchStart(i),
'onFocus': this.createOnKeyDown(i),
'tabIndex': 0,
'role': 'slider',
'aria-orientation': this.props.orientation,
'aria-valuenow': this.state.value[i],
'aria-valuemin': this.props.min,
'aria-valuemax': this.props.max,
'aria-label': Array.isArray(this.props.ariaLabel)
? this.props.ariaLabel[i]
: this.props.ariaLabel,
};
const state = {
index: i,
value: prepareOutValue(this.state.value),
valueNow: this.state.value[i],
};
if (this.props.ariaValuetext) {
props['aria-valuetext'] =
typeof this.props.ariaValuetext === 'string'
? this.props.ariaValuetext
: this.props.ariaValuetext(state);
}
return this.props.renderThumb(props, state);
};
renderThumbs(offset) {
const { length } = offset;
const styles = this.tempArray;
for (let i = 0; i < length; i += 1) {
styles[i] = this.buildThumbStyle(offset[i], i);
}
const res = [];
for (let i = 0; i < length; i += 1) {
res[i] = this.renderThumb(styles[i], i);
}
return res;
}
renderTrack = (i, offsetFrom, offsetTo) => {
const props = {
key: `${this.props.trackClassName}-${i}`,
className: `${this.props.trackClassName} ${this.props.trackClassName}-${i}`,
style: this.buildTrackStyle(offsetFrom, this.state.upperBound - offsetTo),
};
const state = {
index: i,
value: prepareOutValue(this.state.value),
};
return this.props.renderTrack(props, state);
};
renderTracks(offset) {
const tracks = [];
const lastIndex = offset.length - 1;
tracks.push(this.renderTrack(0, 0, offset[0]));
for (let i = 0; i < lastIndex; i += 1) {
tracks.push(this.renderTrack(i + 1, offset[i], offset[i + 1]));
}
tracks.push(this.renderTrack(lastIndex + 1, offset[lastIndex], this.state.upperBound));
return tracks;
}
render() {
const offset = this.tempArray;