UNPKG

35.1 kBJavaScriptView Raw
1"use strict";
2
3var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
5Object.defineProperty(exports, "__esModule", {
6 value: true
7});
8exports.default = exports.styles = void 0;
9
10var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
11
12var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
13
14var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
15
16var _react = _interopRequireDefault(require("react"));
17
18var _propTypes = _interopRequireDefault(require("prop-types"));
19
20var _clsx = _interopRequireDefault(require("clsx"));
21
22var _utils = require("@material-ui/utils");
23
24var _withStyles = _interopRequireDefault(require("../styles/withStyles"));
25
26var _useTheme = _interopRequireDefault(require("../styles/useTheme"));
27
28var _colorManipulator = require("../styles/colorManipulator");
29
30var _focusVisible = require("../utils/focusVisible");
31
32var _useEventCallback = _interopRequireDefault(require("../utils/useEventCallback"));
33
34var _useForkRef = _interopRequireDefault(require("../utils/useForkRef"));
35
36var _capitalize = _interopRequireDefault(require("../utils/capitalize"));
37
38var _ValueLabel = _interopRequireDefault(require("./ValueLabel"));
39
40function asc(a, b) {
41 return a - b;
42}
43
44function clamp(value, min, max) {
45 return Math.min(Math.max(min, value), max);
46}
47
48function findClosest(values, currentValue) {
49 var _values$reduce = values.reduce(function (acc, value, index) {
50 var distance = Math.abs(currentValue - value);
51
52 if (acc === null || distance < acc.distance || distance === acc.distance) {
53 return {
54 distance: distance,
55 index: index
56 };
57 }
58
59 return acc;
60 }, null),
61 closestIndex = _values$reduce.index;
62
63 return closestIndex;
64}
65
66function trackFinger(event, touchId) {
67 if (touchId.current !== undefined && event.changedTouches) {
68 for (var i = 0; i < event.changedTouches.length; i += 1) {
69 var touch = event.changedTouches[i];
70
71 if (touch.identifier === touchId.current) {
72 return {
73 x: touch.clientX,
74 y: touch.clientY
75 };
76 }
77 }
78
79 return false;
80 }
81
82 return {
83 x: event.clientX,
84 y: event.clientY
85 };
86}
87
88function valueToPercent(value, min, max) {
89 return (value - min) * 100 / (max - min);
90}
91
92function percentToValue(percent, min, max) {
93 return (max - min) * percent + min;
94}
95
96function getDecimalPrecision(num) {
97 // This handles the case when num is very small (0.00000001), js will turn this into 1e-8.
98 // When num is bigger than 1 or less than -1 it won't get converted to this notation so it's fine.
99 if (Math.abs(num) < 1) {
100 var parts = num.toExponential().split('e-');
101 var matissaDecimalPart = parts[0].split('.')[1];
102 return (matissaDecimalPart ? matissaDecimalPart.length : 0) + parseInt(parts[1], 10);
103 }
104
105 var decimalPart = num.toString().split('.')[1];
106 return decimalPart ? decimalPart.length : 0;
107}
108
109function roundValueToStep(value, step, min) {
110 var nearest = Math.round((value - min) / step) * step + min;
111 return Number(nearest.toFixed(getDecimalPrecision(step)));
112}
113
114function setValueIndex(_ref) {
115 var values = _ref.values,
116 source = _ref.source,
117 newValue = _ref.newValue,
118 index = _ref.index;
119
120 // Performance shortcut
121 if (values[index] === newValue) {
122 return source;
123 }
124
125 var output = (0, _toConsumableArray2.default)(values);
126 output[index] = newValue;
127 return output;
128}
129
130function focusThumb(_ref2) {
131 var sliderRef = _ref2.sliderRef,
132 activeIndex = _ref2.activeIndex,
133 setActive = _ref2.setActive;
134
135 if (!sliderRef.current.contains(document.activeElement) || Number(document.activeElement.getAttribute('data-index')) !== activeIndex) {
136 sliderRef.current.querySelector("[data-index=\"".concat(activeIndex, "\"]")).focus();
137 }
138
139 if (setActive) {
140 setActive(activeIndex);
141 }
142}
143
144var axisProps = {
145 horizontal: {
146 offset: function offset(percent) {
147 return {
148 left: "".concat(percent, "%")
149 };
150 },
151 leap: function leap(percent) {
152 return {
153 width: "".concat(percent, "%")
154 };
155 }
156 },
157 'horizontal-reverse': {
158 offset: function offset(percent) {
159 return {
160 right: "".concat(percent, "%")
161 };
162 },
163 leap: function leap(percent) {
164 return {
165 width: "".concat(percent, "%")
166 };
167 }
168 },
169 vertical: {
170 offset: function offset(percent) {
171 return {
172 bottom: "".concat(percent, "%")
173 };
174 },
175 leap: function leap(percent) {
176 return {
177 height: "".concat(percent, "%")
178 };
179 }
180 }
181};
182var defaultMarks = [];
183
184var Identity = function Identity(x) {
185 return x;
186};
187
188var styles = function styles(theme) {
189 return {
190 /* Styles applied to the root element. */
191 root: {
192 height: 2,
193 width: '100%',
194 boxSizing: 'content-box',
195 padding: '13px 0',
196 display: 'inline-block',
197 position: 'relative',
198 cursor: 'pointer',
199 touchAction: 'none',
200 color: theme.palette.primary.main,
201 WebkitTapHighlightColor: 'transparent',
202 '&$disabled': {
203 pointerEvents: 'none',
204 cursor: 'default',
205 color: theme.palette.grey[400]
206 },
207 '&$vertical': {
208 width: 2,
209 height: '100%',
210 padding: '0 13px'
211 },
212 // The primary input mechanism of the device includes a pointing device of limited accuracy.
213 '@media (pointer: coarse)': {
214 // Reach 42px touch target, about ~8mm on screen.
215 padding: '20px 0',
216 '&$vertical': {
217 padding: '0 20px'
218 }
219 }
220 },
221
222 /* Styles applied to the root element if `color="primary"`. */
223 colorPrimary: {// TODO v5, move the style here
224 },
225
226 /* Styles applied to the root element if `color="secondary"`. */
227 colorSecondary: {
228 color: theme.palette.secondary.main
229 },
230
231 /* Styles applied to the root element if `marks` is provided with at least one label. */
232 marked: {
233 marginBottom: 20,
234 '&$vertical': {
235 marginBottom: 'auto',
236 marginRight: 20
237 }
238 },
239
240 /* Pseudo-class applied to the root element if `orientation="vertical"`. */
241 vertical: {},
242
243 /* Pseudo-class applied to the root and thumb element if `disabled={true}`. */
244 disabled: {},
245
246 /* Styles applied to the rail element. */
247 rail: {
248 display: 'block',
249 position: 'absolute',
250 width: '100%',
251 height: 2,
252 borderRadius: 1,
253 backgroundColor: 'currentColor',
254 opacity: 0.38,
255 '$vertical &': {
256 height: '100%',
257 width: 2
258 }
259 },
260
261 /* Styles applied to the track element. */
262 track: {
263 display: 'block',
264 position: 'absolute',
265 height: 2,
266 borderRadius: 1,
267 backgroundColor: 'currentColor',
268 '$vertical &': {
269 width: 2
270 }
271 },
272
273 /* Styles applied to the track element if `track={false}`. */
274 trackFalse: {
275 '& $track': {
276 display: 'none'
277 }
278 },
279
280 /* Styles applied to the track element if `track="inverted"`. */
281 trackInverted: {
282 '& $track': {
283 backgroundColor: // Same logic as the LinearProgress track color
284 theme.palette.type === 'light' ? (0, _colorManipulator.lighten)(theme.palette.primary.main, 0.62) : (0, _colorManipulator.darken)(theme.palette.primary.main, 0.5)
285 },
286 '& $rail': {
287 opacity: 1
288 }
289 },
290
291 /* Styles applied to the thumb element. */
292 thumb: {
293 position: 'absolute',
294 width: 12,
295 height: 12,
296 marginLeft: -6,
297 marginTop: -5,
298 boxSizing: 'border-box',
299 borderRadius: '50%',
300 outline: 0,
301 backgroundColor: 'currentColor',
302 display: 'flex',
303 alignItems: 'center',
304 justifyContent: 'center',
305 transition: theme.transitions.create(['box-shadow'], {
306 duration: theme.transitions.duration.shortest
307 }),
308 '&::after': {
309 position: 'absolute',
310 content: '""',
311 borderRadius: '50%',
312 // reach 42px hit target (2 * 15 + thumb diameter)
313 left: -15,
314 top: -15,
315 right: -15,
316 bottom: -15
317 },
318 '&$focusVisible,&:hover': {
319 boxShadow: "0px 0px 0px 8px ".concat((0, _colorManipulator.fade)(theme.palette.primary.main, 0.16)),
320 '@media (hover: none)': {
321 boxShadow: 'none'
322 }
323 },
324 '&$active': {
325 boxShadow: "0px 0px 0px 14px ".concat((0, _colorManipulator.fade)(theme.palette.primary.main, 0.16))
326 },
327 '&$disabled': {
328 width: 8,
329 height: 8,
330 marginLeft: -4,
331 marginTop: -3,
332 '&:hover': {
333 boxShadow: 'none'
334 }
335 },
336 '$vertical &': {
337 marginLeft: -5,
338 marginBottom: -6
339 },
340 '$vertical &$disabled': {
341 marginLeft: -3,
342 marginBottom: -4
343 }
344 },
345
346 /* Styles applied to the thumb element if `color="primary"`. */
347 thumbColorPrimary: {// TODO v5, move the style here
348 },
349
350 /* Styles applied to the thumb element if `color="secondary"`. */
351 thumbColorSecondary: {
352 '&$focusVisible,&:hover': {
353 boxShadow: "0px 0px 0px 8px ".concat((0, _colorManipulator.fade)(theme.palette.secondary.main, 0.16))
354 },
355 '&$active': {
356 boxShadow: "0px 0px 0px 14px ".concat((0, _colorManipulator.fade)(theme.palette.secondary.main, 0.16))
357 }
358 },
359
360 /* Pseudo-class applied to the thumb element if it's active. */
361 active: {},
362
363 /* Pseudo-class applied to the thumb element if keyboard focused. */
364 focusVisible: {},
365
366 /* Styles applied to the thumb label element. */
367 valueLabel: {},
368
369 /* Styles applied to the mark element. */
370 mark: {
371 position: 'absolute',
372 width: 2,
373 height: 2,
374 borderRadius: 1,
375 backgroundColor: 'currentColor'
376 },
377
378 /* Styles applied to the mark element if active (depending on the value). */
379 markActive: {
380 backgroundColor: theme.palette.background.paper,
381 opacity: 0.8
382 },
383
384 /* Styles applied to the mark label element. */
385 markLabel: (0, _extends2.default)({}, theme.typography.body2, {
386 color: theme.palette.text.secondary,
387 position: 'absolute',
388 top: 26,
389 transform: 'translateX(-50%)',
390 whiteSpace: 'nowrap',
391 '$vertical &': {
392 top: 'auto',
393 left: 26,
394 transform: 'translateY(50%)'
395 },
396 '@media (pointer: coarse)': {
397 top: 40,
398 '$vertical &': {
399 left: 31
400 }
401 }
402 }),
403
404 /* Styles applied to the mark label element if active (depending on the value). */
405 markLabelActive: {
406 color: theme.palette.text.primary
407 }
408 };
409};
410
411exports.styles = styles;
412
413var Slider = _react.default.forwardRef(function Slider(props, ref) {
414 var ariaLabel = props['aria-label'],
415 ariaLabelledby = props['aria-labelledby'],
416 ariaValuetext = props['aria-valuetext'],
417 classes = props.classes,
418 className = props.className,
419 _props$color = props.color,
420 color = _props$color === void 0 ? 'primary' : _props$color,
421 _props$component = props.component,
422 Component = _props$component === void 0 ? 'span' : _props$component,
423 defaultValue = props.defaultValue,
424 _props$disabled = props.disabled,
425 disabled = _props$disabled === void 0 ? false : _props$disabled,
426 getAriaLabel = props.getAriaLabel,
427 getAriaValueText = props.getAriaValueText,
428 _props$marks = props.marks,
429 marksProp = _props$marks === void 0 ? defaultMarks : _props$marks,
430 _props$max = props.max,
431 max = _props$max === void 0 ? 100 : _props$max,
432 _props$min = props.min,
433 min = _props$min === void 0 ? 0 : _props$min,
434 name = props.name,
435 onChange = props.onChange,
436 onChangeCommitted = props.onChangeCommitted,
437 onMouseDown = props.onMouseDown,
438 _props$orientation = props.orientation,
439 orientation = _props$orientation === void 0 ? 'horizontal' : _props$orientation,
440 _props$step = props.step,
441 step = _props$step === void 0 ? 1 : _props$step,
442 _props$ThumbComponent = props.ThumbComponent,
443 ThumbComponent = _props$ThumbComponent === void 0 ? 'span' : _props$ThumbComponent,
444 _props$track = props.track,
445 track = _props$track === void 0 ? 'normal' : _props$track,
446 valueProp = props.value,
447 _props$ValueLabelComp = props.ValueLabelComponent,
448 ValueLabelComponent = _props$ValueLabelComp === void 0 ? _ValueLabel.default : _props$ValueLabelComp,
449 _props$valueLabelDisp = props.valueLabelDisplay,
450 valueLabelDisplay = _props$valueLabelDisp === void 0 ? 'off' : _props$valueLabelDisp,
451 _props$valueLabelForm = props.valueLabelFormat,
452 valueLabelFormat = _props$valueLabelForm === void 0 ? Identity : _props$valueLabelForm,
453 other = (0, _objectWithoutProperties2.default)(props, ["aria-label", "aria-labelledby", "aria-valuetext", "classes", "className", "color", "component", "defaultValue", "disabled", "getAriaLabel", "getAriaValueText", "marks", "max", "min", "name", "onChange", "onChangeCommitted", "onMouseDown", "orientation", "step", "ThumbComponent", "track", "value", "ValueLabelComponent", "valueLabelDisplay", "valueLabelFormat"]);
454 var theme = (0, _useTheme.default)();
455
456 var touchId = _react.default.useRef(); // We can't use the :active browser pseudo-classes.
457 // - The active state isn't triggered when clicking on the rail.
458 // - The active state isn't transfered when inversing a range slider.
459
460
461 var _React$useState = _react.default.useState(-1),
462 active = _React$useState[0],
463 setActive = _React$useState[1];
464
465 var _React$useState2 = _react.default.useState(-1),
466 open = _React$useState2[0],
467 setOpen = _React$useState2[1];
468
469 var _React$useRef = _react.default.useRef(valueProp != null),
470 isControlled = _React$useRef.current;
471
472 var _React$useState3 = _react.default.useState(defaultValue),
473 valueState = _React$useState3[0],
474 setValueState = _React$useState3[1];
475
476 var valueDerived = isControlled ? valueProp : valueState;
477
478 if (process.env.NODE_ENV !== 'production') {
479 // eslint-disable-next-line react-hooks/rules-of-hooks
480 _react.default.useEffect(function () {
481 if (isControlled !== (valueProp != null)) {
482 console.error(["Material-UI: A component is changing ".concat(isControlled ? 'a ' : 'an un', "controlled Slider to be ").concat(isControlled ? 'un' : '', "controlled."), 'Elements should not switch from uncontrolled to controlled (or vice versa).', 'Decide between using a controlled or uncontrolled Slider ' + 'element for the lifetime of the component.', 'More info: https://fb.me/react-controlled-components'].join('\n'));
483 }
484 }, [valueProp, isControlled]);
485 }
486
487 var range = Array.isArray(valueDerived);
488
489 var instanceRef = _react.default.useRef();
490
491 var values = range ? (0, _toConsumableArray2.default)(valueDerived).sort(asc) : [valueDerived];
492 values = values.map(function (value) {
493 return clamp(value, min, max);
494 });
495 var marks = marksProp === true && step !== null ? (0, _toConsumableArray2.default)(Array(Math.floor((max - min) / step) + 1)).map(function (_, index) {
496 return {
497 value: min + step * index
498 };
499 }) : marksProp;
500 instanceRef.current = {
501 source: valueDerived // Keep track of the input value to leverage immutable state comparison.
502
503 };
504
505 var _useIsFocusVisible = (0, _focusVisible.useIsFocusVisible)(),
506 isFocusVisible = _useIsFocusVisible.isFocusVisible,
507 onBlurVisible = _useIsFocusVisible.onBlurVisible,
508 focusVisibleRef = _useIsFocusVisible.ref;
509
510 var _React$useState4 = _react.default.useState(-1),
511 focusVisible = _React$useState4[0],
512 setFocusVisible = _React$useState4[1];
513
514 var sliderRef = _react.default.useRef();
515
516 var handleFocusRef = (0, _useForkRef.default)(focusVisibleRef, sliderRef);
517 var handleRef = (0, _useForkRef.default)(ref, handleFocusRef);
518 var handleFocus = (0, _useEventCallback.default)(function (event) {
519 var index = Number(event.currentTarget.getAttribute('data-index'));
520
521 if (isFocusVisible(event)) {
522 setFocusVisible(index);
523 }
524
525 setOpen(index);
526 });
527 var handleBlur = (0, _useEventCallback.default)(function () {
528 if (focusVisible !== -1) {
529 setFocusVisible(-1);
530 onBlurVisible();
531 }
532
533 setOpen(-1);
534 });
535 var handleMouseOver = (0, _useEventCallback.default)(function (event) {
536 var index = Number(event.currentTarget.getAttribute('data-index'));
537 setOpen(index);
538 });
539 var handleMouseLeave = (0, _useEventCallback.default)(function () {
540 setOpen(-1);
541 });
542 var handleKeyDown = (0, _useEventCallback.default)(function (event) {
543 var index = Number(event.currentTarget.getAttribute('data-index'));
544 var value = values[index];
545 var tenPercents = (max - min) / 10;
546 var marksValues = marks.map(function (mark) {
547 return mark.value;
548 });
549 var marksIndex = marksValues.indexOf(value);
550 var newValue;
551
552 switch (event.key) {
553 case 'Home':
554 newValue = min;
555 break;
556
557 case 'End':
558 newValue = max;
559 break;
560
561 case 'PageUp':
562 if (step) {
563 newValue = value + tenPercents;
564 }
565
566 break;
567
568 case 'PageDown':
569 if (step) {
570 newValue = value - tenPercents;
571 }
572
573 break;
574
575 case 'ArrowRight':
576 case 'ArrowUp':
577 if (step) {
578 newValue = value + step;
579 } else {
580 newValue = marksValues[marksIndex + 1] || marksValues[marksValues.length - 1];
581 }
582
583 break;
584
585 case 'ArrowLeft':
586 case 'ArrowDown':
587 if (step) {
588 newValue = value - step;
589 } else {
590 newValue = marksValues[marksIndex - 1] || marksValues[0];
591 }
592
593 break;
594
595 default:
596 return;
597 } // Prevent scroll of the page
598
599
600 event.preventDefault();
601
602 if (step) {
603 newValue = roundValueToStep(newValue, step, min);
604 }
605
606 newValue = clamp(newValue, min, max);
607
608 if (range) {
609 var previousValue = newValue;
610 newValue = setValueIndex({
611 values: values,
612 source: valueDerived,
613 newValue: newValue,
614 index: index
615 }).sort(asc);
616 focusThumb({
617 sliderRef: sliderRef,
618 activeIndex: newValue.indexOf(previousValue)
619 });
620 }
621
622 if (!isControlled) {
623 setValueState(newValue);
624 }
625
626 setFocusVisible(index);
627
628 if (onChange) {
629 onChange(event, newValue);
630 }
631
632 if (onChangeCommitted) {
633 onChangeCommitted(event, newValue);
634 }
635 });
636
637 var previousIndex = _react.default.useRef();
638
639 var axis = orientation;
640
641 if (theme.direction === 'rtl' && orientation !== "vertical") {
642 axis += '-reverse';
643 }
644
645 var getFingerNewValue = _react.default.useCallback(function (_ref3) {
646 var finger = _ref3.finger,
647 _ref3$move = _ref3.move,
648 move = _ref3$move === void 0 ? false : _ref3$move,
649 values2 = _ref3.values,
650 source = _ref3.source;
651 var slider = sliderRef.current;
652
653 var _slider$getBoundingCl = slider.getBoundingClientRect(),
654 width = _slider$getBoundingCl.width,
655 height = _slider$getBoundingCl.height,
656 bottom = _slider$getBoundingCl.bottom,
657 left = _slider$getBoundingCl.left;
658
659 var percent;
660
661 if (axis.indexOf('vertical') === 0) {
662 percent = (bottom - finger.y) / height;
663 } else {
664 percent = (finger.x - left) / width;
665 }
666
667 if (axis.indexOf('-reverse') !== -1) {
668 percent = 1 - percent;
669 }
670
671 var newValue;
672 newValue = percentToValue(percent, min, max);
673
674 if (step) {
675 newValue = roundValueToStep(newValue, step, min);
676 } else {
677 var marksValues = marks.map(function (mark) {
678 return mark.value;
679 });
680 var closestIndex = findClosest(marksValues, newValue);
681 newValue = marksValues[closestIndex];
682 }
683
684 newValue = clamp(newValue, min, max);
685 var activeIndex = 0;
686
687 if (range) {
688 if (!move) {
689 activeIndex = findClosest(values2, newValue);
690 } else {
691 activeIndex = previousIndex.current;
692 }
693
694 var previousValue = newValue;
695 newValue = setValueIndex({
696 values: values2,
697 source: source,
698 newValue: newValue,
699 index: activeIndex
700 }).sort(asc);
701 activeIndex = newValue.indexOf(previousValue);
702 previousIndex.current = activeIndex;
703 }
704
705 return {
706 newValue: newValue,
707 activeIndex: activeIndex
708 };
709 }, [max, min, axis, range, step, marks]);
710
711 var handleTouchMove = (0, _useEventCallback.default)(function (event) {
712 var finger = trackFinger(event, touchId);
713
714 if (!finger) {
715 return;
716 }
717
718 var _getFingerNewValue = getFingerNewValue({
719 finger: finger,
720 move: true,
721 values: values,
722 source: valueDerived
723 }),
724 newValue = _getFingerNewValue.newValue,
725 activeIndex = _getFingerNewValue.activeIndex;
726
727 focusThumb({
728 sliderRef: sliderRef,
729 activeIndex: activeIndex,
730 setActive: setActive
731 });
732
733 if (!isControlled) {
734 setValueState(newValue);
735 }
736
737 if (onChange) {
738 onChange(event, newValue);
739 }
740 });
741 var handleTouchEnd = (0, _useEventCallback.default)(function (event) {
742 var finger = trackFinger(event, touchId);
743
744 if (!finger) {
745 return;
746 }
747
748 var _getFingerNewValue2 = getFingerNewValue({
749 finger: finger,
750 values: values,
751 source: valueDerived
752 }),
753 newValue = _getFingerNewValue2.newValue;
754
755 setActive(-1);
756
757 if (event.type === 'touchend') {
758 setOpen(-1);
759 }
760
761 if (onChangeCommitted) {
762 onChangeCommitted(event, newValue);
763 }
764
765 touchId.current = undefined;
766 document.body.removeEventListener('mousemove', handleTouchMove);
767 document.body.removeEventListener('mouseup', handleTouchEnd); // eslint-disable-next-line no-use-before-define
768
769 document.body.removeEventListener('mouseenter', handleMouseEnter);
770 document.body.removeEventListener('touchmove', handleTouchMove);
771 document.body.removeEventListener('touchend', handleTouchEnd);
772 });
773 var handleMouseEnter = (0, _useEventCallback.default)(function (event) {
774 // If the slider was being interacted with but the mouse went off the window
775 // and then re-entered while unclicked then end the interaction.
776 if (event.buttons === 0) {
777 handleTouchEnd(event);
778 }
779 });
780 var handleTouchStart = (0, _useEventCallback.default)(function (event) {
781 // Workaround as Safari has partial support for touchAction: 'none'.
782 event.preventDefault();
783 var touch = event.changedTouches[0];
784
785 if (touch != null) {
786 // A number that uniquely identifies the current finger in the touch session.
787 touchId.current = touch.identifier;
788 }
789
790 var finger = trackFinger(event, touchId);
791
792 var _getFingerNewValue3 = getFingerNewValue({
793 finger: finger,
794 values: values,
795 source: valueDerived
796 }),
797 newValue = _getFingerNewValue3.newValue,
798 activeIndex = _getFingerNewValue3.activeIndex;
799
800 focusThumb({
801 sliderRef: sliderRef,
802 activeIndex: activeIndex,
803 setActive: setActive
804 });
805
806 if (!isControlled) {
807 setValueState(newValue);
808 }
809
810 if (onChange) {
811 onChange(event, newValue);
812 }
813
814 document.body.addEventListener('touchmove', handleTouchMove);
815 document.body.addEventListener('touchend', handleTouchEnd);
816 });
817
818 _react.default.useEffect(function () {
819 var slider = sliderRef.current;
820 slider.addEventListener('touchstart', handleTouchStart);
821 return function () {
822 slider.removeEventListener('touchstart', handleTouchStart);
823 document.body.removeEventListener('mousemove', handleTouchMove);
824 document.body.removeEventListener('mouseup', handleTouchEnd);
825 document.body.removeEventListener('mouseenter', handleMouseEnter);
826 document.body.removeEventListener('touchmove', handleTouchMove);
827 document.body.removeEventListener('touchend', handleTouchEnd);
828 };
829 }, [handleMouseEnter, handleTouchEnd, handleTouchMove, handleTouchStart]);
830
831 if (process.env.NODE_ENV !== 'production') {
832 // eslint-disable-next-line react-hooks/rules-of-hooks
833 _react.default.useEffect(function () {
834 if (isControlled !== (valueProp != null)) {
835 console.error(["Material-UI: A component is changing ".concat(isControlled ? 'a ' : 'an un', "controlled Slider to be ").concat(isControlled ? 'un' : '', "controlled."), 'Elements should not switch from uncontrolled to controlled (or vice versa).', 'Decide between using a controlled or uncontrolled Slider ' + 'element for the lifetime of the component.', 'More info: https://fb.me/react-controlled-components'].join('\n'));
836 }
837 }, [valueProp, isControlled]);
838 }
839
840 var handleMouseDown = (0, _useEventCallback.default)(function (event) {
841 if (onMouseDown) {
842 onMouseDown(event);
843 }
844
845 event.preventDefault();
846 var finger = trackFinger(event, touchId);
847
848 var _getFingerNewValue4 = getFingerNewValue({
849 finger: finger,
850 values: values,
851 source: valueDerived
852 }),
853 newValue = _getFingerNewValue4.newValue,
854 activeIndex = _getFingerNewValue4.activeIndex;
855
856 focusThumb({
857 sliderRef: sliderRef,
858 activeIndex: activeIndex,
859 setActive: setActive
860 });
861
862 if (!isControlled) {
863 setValueState(newValue);
864 }
865
866 if (onChange) {
867 onChange(event, newValue);
868 }
869
870 document.body.addEventListener('mousemove', handleTouchMove);
871 document.body.addEventListener('mouseenter', handleMouseEnter);
872 document.body.addEventListener('mouseup', handleTouchEnd);
873 });
874 var trackOffset = valueToPercent(range ? values[0] : min, min, max);
875 var trackLeap = valueToPercent(values[values.length - 1], min, max) - trackOffset;
876 var trackStyle = (0, _extends2.default)({}, axisProps[axis].offset(trackOffset), {}, axisProps[axis].leap(trackLeap));
877 return _react.default.createElement(Component, (0, _extends2.default)({
878 ref: handleRef,
879 className: (0, _clsx.default)(classes.root, classes["color".concat((0, _capitalize.default)(color))], className, disabled && classes.disabled, marks.length > 0 && marks.some(function (mark) {
880 return mark.label;
881 }) && classes.marked, track === false && classes.trackFalse, {
882 vertical: classes.vertical
883 }[orientation], {
884 inverted: classes.trackInverted
885 }[track]),
886 onMouseDown: handleMouseDown
887 }, other), _react.default.createElement("span", {
888 className: classes.rail
889 }), _react.default.createElement("span", {
890 className: classes.track,
891 style: trackStyle
892 }), _react.default.createElement("input", {
893 value: values.join(','),
894 name: name,
895 type: "hidden"
896 }), marks.map(function (mark) {
897 var percent = valueToPercent(mark.value, min, max);
898 var style = axisProps[axis].offset(percent);
899 var markActive;
900
901 if (track === false) {
902 markActive = values.indexOf(mark.value) !== -1;
903 } else {
904 var isMarkActive = range ? mark.value >= values[0] && mark.value <= values[values.length - 1] : mark.value <= values[0];
905 markActive = isMarkActive && track === 'normal' || !isMarkActive && track === 'inverted';
906 }
907
908 return _react.default.createElement(_react.default.Fragment, {
909 key: mark.value
910 }, _react.default.createElement("span", {
911 style: style,
912 className: (0, _clsx.default)(classes.mark, markActive && classes.markActive)
913 }), _react.default.createElement("span", {
914 "aria-hidden": true,
915 style: style,
916 className: (0, _clsx.default)(classes.markLabel, markActive && classes.markLabelActive)
917 }, mark.label));
918 }), values.map(function (value, index) {
919 var percent = valueToPercent(value, min, max);
920 var style = axisProps[axis].offset(percent);
921 return _react.default.createElement(ValueLabelComponent, {
922 key: index,
923 valueLabelFormat: valueLabelFormat,
924 valueLabelDisplay: valueLabelDisplay,
925 className: classes.valueLabel,
926 value: typeof valueLabelFormat === 'function' ? valueLabelFormat(value, index) : valueLabelFormat,
927 index: index,
928 open: open === index || active === index || valueLabelDisplay === 'on',
929 disabled: disabled
930 }, _react.default.createElement(ThumbComponent, {
931 className: (0, _clsx.default)(classes.thumb, classes["thumbColor".concat((0, _capitalize.default)(color))], active === index && classes.active, disabled && classes.disabled, focusVisible === index && classes.focusVisible),
932 tabIndex: disabled ? null : 0,
933 role: "slider",
934 style: style,
935 "data-index": index,
936 "aria-label": getAriaLabel ? getAriaLabel(index) : ariaLabel,
937 "aria-labelledby": ariaLabelledby,
938 "aria-orientation": orientation,
939 "aria-valuemax": max,
940 "aria-valuemin": min,
941 "aria-valuenow": value,
942 "aria-valuetext": getAriaValueText ? getAriaValueText(value, index) : ariaValuetext,
943 onKeyDown: handleKeyDown,
944 onFocus: handleFocus,
945 onBlur: handleBlur,
946 onMouseOver: handleMouseOver,
947 onMouseLeave: handleMouseLeave
948 }));
949 }));
950});
951
952process.env.NODE_ENV !== "production" ? Slider.propTypes = {
953 /**
954 * The label of the slider.
955 */
956 'aria-label': (0, _utils.chainPropTypes)(_propTypes.default.string, function (props) {
957 var range = Array.isArray(props.value || props.defaultValue);
958
959 if (range && props['aria-label'] != null) {
960 return new Error('Material-UI: you need to use the `getAriaLabel` prop instead of `aria-label` when using a range slider.');
961 }
962
963 return null;
964 }),
965
966 /**
967 * The id of the element containing a label for the slider.
968 */
969 'aria-labelledby': _propTypes.default.string,
970
971 /**
972 * A string value that provides a user-friendly name for the current value of the slider.
973 */
974 'aria-valuetext': (0, _utils.chainPropTypes)(_propTypes.default.string, function (props) {
975 var range = Array.isArray(props.value || props.defaultValue);
976
977 if (range && props['aria-valuetext'] != null) {
978 return new Error('Material-UI: you need to use the `getAriaValueText` prop instead of `aria-valuetext` when using a range slider.');
979 }
980
981 return null;
982 }),
983
984 /**
985 * Override or extend the styles applied to the component.
986 * See [CSS API](#css) below for more details.
987 */
988 classes: _propTypes.default.object.isRequired,
989
990 /**
991 * @ignore
992 */
993 className: _propTypes.default.string,
994
995 /**
996 * The color of the component. It supports those theme colors that make sense for this component.
997 */
998 color: _propTypes.default.oneOf(['primary', 'secondary']),
999
1000 /**
1001 * The component used for the root node.
1002 * Either a string to use a DOM element or a component.
1003 */
1004 component: _propTypes.default.elementType,
1005
1006 /**
1007 * The default element value. Use when the component is not controlled.
1008 */
1009 defaultValue: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.arrayOf(_propTypes.default.number)]),
1010
1011 /**
1012 * If `true`, the slider will be disabled.
1013 */
1014 disabled: _propTypes.default.bool,
1015
1016 /**
1017 * Accepts a function which returns a string value that provides a user-friendly name for the thumb labels of the slider.
1018 *
1019 * @param {number} index The thumb label's index to format.
1020 * @returns {string}
1021 */
1022 getAriaLabel: _propTypes.default.func,
1023
1024 /**
1025 * Accepts a function which returns a string value that provides a user-friendly name for the current value of the slider.
1026 *
1027 * @param {number} value The thumb label's value to format.
1028 * @param {number} index The thumb label's index to format.
1029 * @returns {string}
1030 */
1031 getAriaValueText: _propTypes.default.func,
1032
1033 /**
1034 * Marks indicate predetermined values to which the user can move the slider.
1035 * If `true` the marks will be spaced according the value of the `step` prop.
1036 * If an array, it should contain objects with `value` and an optional `label` keys.
1037 */
1038 marks: _propTypes.default.oneOfType([_propTypes.default.bool, _propTypes.default.array]),
1039
1040 /**
1041 * The maximum allowed value of the slider.
1042 * Should not be equal to min.
1043 */
1044 max: _propTypes.default.number,
1045
1046 /**
1047 * The minimum allowed value of the slider.
1048 * Should not be equal to max.
1049 */
1050 min: _propTypes.default.number,
1051
1052 /**
1053 * Name attribute of the hidden `input` element.
1054 */
1055 name: _propTypes.default.string,
1056
1057 /**
1058 * Callback function that is fired when the slider's value changed.
1059 *
1060 * @param {object} event The event source of the callback.
1061 * @param {any} value The new value.
1062 */
1063 onChange: _propTypes.default.func,
1064
1065 /**
1066 * Callback function that is fired when the `mouseup` is triggered.
1067 *
1068 * @param {object} event The event source of the callback.
1069 * @param {any} value The new value.
1070 */
1071 onChangeCommitted: _propTypes.default.func,
1072
1073 /**
1074 * @ignore
1075 */
1076 onMouseDown: _propTypes.default.func,
1077
1078 /**
1079 * The slider orientation.
1080 */
1081 orientation: _propTypes.default.oneOf(['horizontal', 'vertical']),
1082
1083 /**
1084 * The granularity with which the slider can step through values. (A "discrete" slider.)
1085 * The `min` prop serves as the origin for the valid values.
1086 * We recommend (max - min) to be evenly divisible by the step.
1087 *
1088 * When step is `null`, the thumb can only be slid onto marks provided with the `marks` prop.
1089 */
1090 step: _propTypes.default.number,
1091
1092 /**
1093 * The component used to display the value label.
1094 */
1095 ThumbComponent: _propTypes.default.elementType,
1096
1097 /**
1098 * The track presentation:
1099 *
1100 * - `normal` the track will render a bar representing the slider value.
1101 * - `inverted` the track will render a bar representing the remaining slider value.
1102 * - `false` the track will render without a bar.
1103 */
1104 track: _propTypes.default.oneOf(['normal', false, 'inverted']),
1105
1106 /**
1107 * The value of the slider.
1108 * For ranged sliders, provide an array with two values.
1109 */
1110 value: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.arrayOf(_propTypes.default.number)]),
1111
1112 /**
1113 * The value label component.
1114 */
1115 ValueLabelComponent: _propTypes.default.elementType,
1116
1117 /**
1118 * Controls when the value label is displayed:
1119 *
1120 * - `auto` the value label will display when the thumb is hovered or focused.
1121 * - `on` will display persistently.
1122 * - `off` will never display.
1123 */
1124 valueLabelDisplay: _propTypes.default.oneOf(['on', 'auto', 'off']),
1125
1126 /**
1127 * The format function the value label's value.
1128 *
1129 * When a function is provided, it should have the following signature:
1130 *
1131 * - {number} value The value label's value to format
1132 * - {number} index The value label's index to format
1133 */
1134 valueLabelFormat: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.func])
1135} : void 0;
1136
1137var _default = (0, _withStyles.default)(styles, {
1138 name: 'MuiSlider'
1139})(Slider);
1140
1141exports.default = _default;
\No newline at end of file