Debian Codegraph @

node/@patternfly/react-core/dist/esm/components/Slider/Slider.js

raw
1 import { __rest } from "tslib";
2 import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3 import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
4 import styles from '@patternfly/react-styles/css/components/Slider/slider.mjs';
5 import { css } from '@patternfly/react-styles';
6 import { SliderStep } from './SliderStep';
7 import { InputGroup, InputGroupText, InputGroupItem } from '../InputGroup';
8 import { TextInput } from '../TextInput';
9 import { Tooltip } from '../Tooltip';
10 import cssSliderValue from '@patternfly/react-tokens/dist/esm/c_slider_value';
11 import cssFormControlWidthChars from '@patternfly/react-tokens/dist/esm/c_slider__value_c_form_control_width_chars';
12 import { getLanguageDirection } from '../../helpers/util';
13 const getPercentage = (current, max) => (100 * current) / max;
14 export const Slider = (_a) => {
15 var { className, value = 0, customSteps, areCustomStepsContinuous = false, isDisabled = false, isInputVisible = false, inputValue = 0, inputLabel, inputAriaLabel = 'Slider value input', thumbAriaLabel = 'Value', hasTooltipOverThumb = false, inputPosition = 'end', onChange, leftActions, startActions, rightActions, endActions, step = 1, min = 0, max = 100, showTicks = false, showBoundaries = true, 'aria-describedby': ariaDescribedby, 'aria-labelledby': ariaLabelledby } = _a, props = __rest(_a, ["className", "value", "customSteps", "areCustomStepsContinuous", "isDisabled", "isInputVisible", "inputValue", "inputLabel", "inputAriaLabel", "thumbAriaLabel", "hasTooltipOverThumb", "inputPosition", "onChange", "leftActions", "startActions", "rightActions", "endActions", "step", "min", "max", "showTicks", "showBoundaries", 'aria-describedby', 'aria-labelledby']);
16 const sliderRailRef = useRef(undefined);
17 const thumbRef = useRef(undefined);
18 const [localValue, setValue] = useState(value);
19 const [localInputValue, setLocalInputValue] = useState(inputValue);
20 let isRTL;
21 useEffect(() => {
22 isRTL = getLanguageDirection(sliderRailRef.current) === 'rtl';
23 });
24 useEffect(() => {
25 setValue(value);
26 }, [value]);
27 useEffect(() => {
28 setLocalInputValue(inputValue);
29 }, [inputValue]);
30 let diff = 0;
31 let snapValue;
32 // calculate style value percentage
33 const stylePercent = ((localValue - min) * 100) / (max - min);
34 const style = { [cssSliderValue.name]: `${stylePercent}%` };
35 const widthChars = useMemo(() => localInputValue.toString().length, [localInputValue]);
36 const inputStyle = { [cssFormControlWidthChars.name]: widthChars };
37 const onChangeHandler = (_event, value) => {
38 setLocalInputValue(Number(value));
39 };
40 const handleKeyPressOnInput = (event) => {
41 if (event.key === 'Enter') {
42 event.preventDefault();
43 if (onChange) {
44 onChange(event, localValue, localInputValue, setLocalInputValue);
45 }
46 }
47 };
48 const onInputFocus = (e) => {
49 e.stopPropagation();
50 };
51 const onThumbClick = () => {
52 thumbRef.current.focus();
53 };
54 const onBlur = (event) => {
55 if (onChange) {
56 onChange(event, localValue, localInputValue, setLocalInputValue);
57 }
58 };
59 const findAriaTextValue = () => {
60 if (!areCustomStepsContinuous && customSteps) {
61 const matchingStep = customSteps.find((stepObj) => stepObj.value === localValue);
62 if (matchingStep) {
63 return matchingStep.label;
64 }
65 }
66 // For continuous steps default to showing 2 decimals in tooltip
67 // Consider making it configurable via a property
68 return Number(Number(localValue).toFixed(2)).toString();
69 };
70 const handleThumbDragEnd = () => {
71 document.removeEventListener('mousemove', callbackThumbMove);
72 document.removeEventListener('mouseup', callbackThumbUp);
73 document.removeEventListener('touchmove', callbackThumbMove);
74 document.removeEventListener('touchend', callbackThumbUp);
75 document.removeEventListener('touchcancel', callbackThumbUp);
76 };
77 const handleMouseDown = (e) => {
78 e.stopPropagation();
79 e.preventDefault();
80 if (isRTL) {
81 diff = thumbRef.current.getBoundingClientRect().right - e.clientX;
82 }
83 else {
84 diff = e.clientX - thumbRef.current.getBoundingClientRect().left;
85 }
86 document.addEventListener('mousemove', callbackThumbMove);
87 document.addEventListener('mouseup', callbackThumbUp);
88 };
89 const handleTouchStart = (e) => {
90 e.stopPropagation();
91 if (isRTL) {
92 diff = thumbRef.current.getBoundingClientRect().right - e.touches[0].clientX;
93 }
94 else {
95 diff = e.touches[0].clientX - thumbRef.current.getBoundingClientRect().left;
96 }
97 document.addEventListener('touchmove', callbackThumbMove, { passive: false });
98 document.addEventListener('touchend', callbackThumbUp);
99 document.addEventListener('touchcancel', callbackThumbUp);
100 };
101 const onSliderRailClick = (e) => {
102 handleThumbMove(e);
103 if (snapValue && !areCustomStepsContinuous) {
104 thumbRef.current.style.setProperty(cssSliderValue.name, `${snapValue}%`);
105 setValue(snapValue);
106 if (onChange) {
107 onChange(e, snapValue);
108 }
109 }
110 };
111 const handleThumbMove = (e) => {
112 if (e.type === 'touchmove') {
113 e.preventDefault();
114 e.stopImmediatePropagation();
115 }
116 const clientPosition = e.touches && e.touches.length ? e.touches[0].clientX : e.clientX;
117 let newPosition;
118 if (isRTL) {
119 newPosition = sliderRailRef.current.getBoundingClientRect().right - clientPosition - diff;
120 }
121 else {
122 newPosition = clientPosition - diff - sliderRailRef.current.getBoundingClientRect().left;
123 }
124 const end = sliderRailRef.current.offsetWidth - thumbRef.current.offsetWidth;
125 const start = 0;
126 if (newPosition < start) {
127 newPosition = 0;
128 }
129 if (newPosition > end) {
130 newPosition = end;
131 }
132 const newPercentage = getPercentage(newPosition, end);
133 thumbRef.current.style.setProperty(cssSliderValue.name, `${newPercentage}%`);
134 // convert percentage to value
135 const newValue = Math.round(((newPercentage * (max - min)) / 100 + min) * 100) / 100;
136 setValue(newValue);
137 if (!customSteps) {
138 // snap to new value if not custom steps
139 snapValue = Math.round((Math.round((newValue - min) / step) * step + min) * 100) / 100;
140 thumbRef.current.style.setProperty(cssSliderValue.name, `${snapValue}%`);
141 setValue(snapValue);
142 }
143 /* If custom steps are discrete, snap to closest step value */
144 if (!areCustomStepsContinuous && customSteps) {
145 let percentage = newPercentage;
146 if (customSteps[customSteps.length - 1].value !== 100) {
147 percentage = (newPercentage * (max - min)) / 100 + min;
148 }
149 const stepIndex = customSteps.findIndex((stepObj) => stepObj.value >= percentage);
150 if (customSteps[stepIndex].value === percentage) {
151 snapValue = customSteps[stepIndex].value;
152 }
153 else {
154 const midpoint = (customSteps[stepIndex].value + customSteps[stepIndex - 1].value) / 2;
155 if (midpoint > percentage) {
156 snapValue = customSteps[stepIndex - 1].value;
157 }
158 else {
159 snapValue = customSteps[stepIndex].value;
160 }
161 }
162 setValue(snapValue);
163 }
164 // Call onchange callback
165 if (onChange) {
166 if (snapValue !== undefined) {
167 onChange(e, snapValue);
168 }
169 else {
170 onChange(e, newValue);
171 }
172 }
173 };
174 const callbackThumbMove = useCallback(handleThumbMove, [min, max, customSteps, onChange]);
175 const callbackThumbUp = useCallback(handleThumbDragEnd, [min, max, customSteps, onChange]);
176 const handleThumbKeys = (e) => {
177 const key = e.key;
178 if (key !== 'ArrowLeft' && key !== 'ArrowRight') {
179 return;
180 }
181 e.preventDefault();
182 let newValue = localValue;
183 if (!areCustomStepsContinuous && customSteps) {
184 const stepIndex = customSteps.findIndex((stepObj) => stepObj.value === localValue);
185 if (key === 'ArrowRight') {
186 if (isRTL) {
187 if (stepIndex - 1 >= 0) {
188 newValue = customSteps[stepIndex - 1].value;
189 }
190 }
191 else {
192 if (stepIndex + 1 < customSteps.length) {
193 {
194 newValue = customSteps[stepIndex + 1].value;
195 }
196 }
197 }
198 }
199 else if (key === 'ArrowLeft') {
200 if (isRTL) {
201 if (stepIndex + 1 < customSteps.length) {
202 {
203 newValue = customSteps[stepIndex + 1].value;
204 }
205 }
206 }
207 else {
208 if (stepIndex - 1 >= 0) {
209 newValue = customSteps[stepIndex - 1].value;
210 }
211 }
212 }
213 }
214 else {
215 if (key === 'ArrowRight') {
216 if (isRTL) {
217 newValue = localValue - step >= min ? localValue - step : min;
218 }
219 else {
220 newValue = localValue + step <= max ? localValue + step : max;
221 }
222 }
223 else if (key === 'ArrowLeft') {
224 if (isRTL) {
225 newValue = localValue + step <= max ? localValue + step : max;
226 }
227 else {
228 newValue = localValue - step >= min ? localValue - step : min;
229 }
230 }
231 }
232 if (newValue !== localValue) {
233 thumbRef.current.style.setProperty(cssSliderValue.name, `${newValue}%`);
234 setValue(newValue);
235 if (onChange) {
236 onChange(e, newValue);
237 }
238 }
239 };
240 const displayInput = () => {
241 const textInput = (_jsx(TextInput, { isDisabled: isDisabled, type: "number", value: localInputValue, "aria-label": inputAriaLabel, onKeyDown: handleKeyPressOnInput, onChange: onChangeHandler, onClick: onInputFocus, onFocus: onInputFocus, onBlur: onBlur }));
242 if (inputLabel) {
243 return (_jsxs(InputGroup, { children: [_jsx(InputGroupItem, { isFill: true, children: textInput }), _jsx(InputGroupText, { isDisabled: isDisabled, children: inputLabel })] }));
244 }
245 else {
246 return textInput;
247 }
248 };
249 const getStepValue = (val, min, max) => ((val - min) * 100) / (max - min);
250 const buildSteps = () => {
251 const builtSteps = [];
252 for (let i = min; i <= max; i = i + step) {
253 const stepValue = getStepValue(i, min, max);
254 // If boundaries but not ticks just generate the needed steps
255 // so that we don't pollute them DOM with empty divs
256 if (!showTicks && showBoundaries && i !== min && i !== max) {
257 continue;
258 }
259 builtSteps.push(_jsx(SliderStep, { value: stepValue, label: i.toString(), isTickHidden: !showTicks, isLabelHidden: (i === min || i === max) && showBoundaries ? false : true, isActive: i <= localValue }, i));
260 }
261 return builtSteps;
262 };
263 const thumbComponent = (_jsx("div", { className: css(styles.sliderThumb), ref: thumbRef, tabIndex: isDisabled ? -1 : 0, role: "slider", "aria-valuemin": customSteps ? customSteps[0].value : min, "aria-valuemax": customSteps ? customSteps[customSteps.length - 1].value : max, "aria-valuenow": localValue, "aria-valuetext": findAriaTextValue(), "aria-label": thumbAriaLabel, "aria-disabled": isDisabled, "aria-describedby": ariaDescribedby, "aria-labelledby": ariaLabelledby, onMouseDown: !isDisabled ? handleMouseDown : null, onTouchStart: !isDisabled ? handleTouchStart : null, onKeyDown: !isDisabled ? handleThumbKeys : null, onClick: !isDisabled ? onThumbClick : null }));
264 return (_jsxs("div", Object.assign({ className: css(styles.slider, className, isDisabled && styles.modifiers.disabled), style: Object.assign(Object.assign({}, style), inputStyle) }, props, { children: [(leftActions || startActions) && _jsx("div", { className: css(styles.sliderActions), children: leftActions || startActions }), _jsxs("div", { className: css(styles.sliderMain), children: [_jsx("div", { className: css(styles.sliderRail), ref: sliderRailRef, onClick: !isDisabled ? onSliderRailClick : null, children: _jsx("div", { className: css(styles.sliderRailTrack) }) }), customSteps && (_jsx("div", { className: css(styles.sliderSteps), "aria-hidden": "true", children: customSteps.map((stepObj) => {
265 const minValue = customSteps[0].value;
266 const maxValue = customSteps[customSteps.length - 1].value;
267 const stepValue = getStepValue(stepObj.value, minValue, maxValue);
268 return (_jsx(SliderStep, { value: stepValue, label: stepObj.label, isLabelHidden: stepObj.isLabelHidden, isActive: stepObj.value <= localValue }, stepObj.value));
269 }) })), !customSteps && (showTicks || showBoundaries) && (_jsx("div", { className: css(styles.sliderSteps), "aria-hidden": "true", children: buildSteps() })), hasTooltipOverThumb ? (_jsx(Tooltip, { className: css('pf-v6-m-tabular-nums'), triggerRef: thumbRef, entryDelay: 0, content: findAriaTextValue(), children: thumbComponent })) : (thumbComponent), isInputVisible && inputPosition === 'aboveThumb' && (_jsx("div", { className: css(styles.sliderValue, styles.modifiers.floating), children: displayInput() }))] }), isInputVisible && (inputPosition === 'right' || inputPosition === 'end') && (_jsx("div", { className: css(styles.sliderValue), children: displayInput() })), (rightActions || endActions) && _jsx("div", { className: css(styles.sliderActions), children: rightActions || endActions })] })));
270 };
271 Slider.displayName = 'Slider';
272 //# sourceMappingURL=Slider.js.map