Debian Codegraph @

node/@patternfly/react-core/src/components/Slider/Slider.tsx

raw
1 import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2 import styles from '@patternfly/react-styles/css/components/Slider/slider';
3 import { css } from '@patternfly/react-styles';
4 import { SliderStep } from './SliderStep';
5 import { InputGroup, InputGroupText, InputGroupItem } from '../InputGroup';
6 import { TextInput } from '../TextInput';
7 import { Tooltip } from '../Tooltip';
8 import cssSliderValue from '@patternfly/react-tokens/dist/esm/c_slider_value';
9 import cssFormControlWidthChars from '@patternfly/react-tokens/dist/esm/c_slider__value_c_form_control_width_chars';
10 import { getLanguageDirection } from '../../helpers/util';
11
12 /** Properties for creating custom steps in a slider. These properties should be passed in as
13 * an object within an array to the slider component's customSteps property.
14 */
15 export interface SliderStepObject {
16 /** Flag to hide the label. */
17 isLabelHidden?: boolean;
18 /** The display label for the step value. This is also used for the aria-valuetext attribute. */
19 label: string;
20 /** Value of the step. This value is a percentage of the slider where the tick is drawn. */
21 value: number;
22 }
23
24 export type SliderOnChangeEvent =
25 | React.MouseEvent
26 | React.KeyboardEvent
27 | React.FormEvent<HTMLInputElement>
28 | React.TouchEvent
29 | React.FocusEvent<HTMLInputElement>;
30
31 /** The main slider component. */
32 export interface SliderProps extends Omit<React.HTMLProps<HTMLDivElement>, 'onChange'> {
33 /** Flag indicating if the slider is discrete for custom steps. This will cause the slider
34 * to snap to the closest value.
35 */
36 areCustomStepsContinuous?: boolean;
37 /** One or more id's to use for the slider thumb's accessible description. */
38 'aria-describedby'?: string;
39 /** One or more id's to use for the slider thumb's accessible label. */
40 'aria-labelledby'?: string;
41 /** Additional classes added to the slider. */
42 className?: string;
43 /** Array of custom slider step objects (value and label of each step) for the slider. */
44 customSteps?: SliderStepObject[];
45 /* Adds a tooltip over the slider thumb containing the current value. */
46 hasTooltipOverThumb?: boolean;
47 /** Accessible label for the input field. */
48 inputAriaLabel?: string;
49 /** Text label that is place after the input field. */
50 inputLabel?: string | number;
51 /** Position of the input. Note "right" is deprecated. Use "end" instead*/
52 inputPosition?: 'aboveThumb' | 'right' | 'end';
53 /** Value displayed in the input field. */
54 inputValue?: number;
55 /** Adds disabled styling, and disables the slider and the input component if present. */
56 isDisabled?: boolean;
57 /** Flag to show value input field. */
58 isInputVisible?: boolean;
59 /** @deprecated Use startActions instead. Actions placed at the start of the slider. */
60 leftActions?: React.ReactNode;
61 /** Actions placed at the start of the slider. */
62 startActions?: React.ReactNode;
63 /** The maximum permitted value. */
64 max?: number;
65 /** The minimum permitted value. */
66 min?: number;
67 /** Value change callback. This is called when the slider value changes. */
68 onChange?: (
69 event: SliderOnChangeEvent,
70 value: number,
71 inputValue?: number,
72 setLocalInputValue?: React.Dispatch<React.SetStateAction<number>>
73 ) => void;
74 /** @deprecated Use endActions instead. Actions placed to the right of the slider. */
75 rightActions?: React.ReactNode;
76 /** Actions placed at the end of the slider. */
77 endActions?: React.ReactNode;
78 /** Flag to indicate if boundaries should be shown for slider that does not have custom steps. */
79 showBoundaries?: boolean;
80 /** Flag to indicate if ticks should be shown for slider that does not have custom steps. */
81 showTicks?: boolean;
82 /** The step interval. */
83 step?: number;
84 /* Accessible label for the slider thumb. */
85 thumbAriaLabel?: string;
86 /** Current value of the slider. */
87 value?: number;
88 }
89
90 const getPercentage = (current: number, max: number) => (100 * current) / max;
91
92 export const Slider: React.FunctionComponent<SliderProps> = ({
93 className,
94 value = 0,
95 customSteps,
96 areCustomStepsContinuous = false,
97 isDisabled = false,
98 isInputVisible = false,
99 inputValue = 0,
100 inputLabel,
101 inputAriaLabel = 'Slider value input',
102 thumbAriaLabel = 'Value',
103 hasTooltipOverThumb = false,
104 inputPosition = 'end',
105 onChange,
106 leftActions,
107 startActions,
108 rightActions,
109 endActions,
110 step = 1,
111 min = 0,
112 max = 100,
113 showTicks = false,
114 showBoundaries = true,
115 'aria-describedby': ariaDescribedby,
116 'aria-labelledby': ariaLabelledby,
117 ...props
118 }: SliderProps) => {
119 const sliderRailRef = useRef<HTMLDivElement>(undefined);
120 const thumbRef = useRef<HTMLDivElement>(undefined);
121
122 const [localValue, setValue] = useState(value);
123 const [localInputValue, setLocalInputValue] = useState(inputValue);
124
125 let isRTL: boolean;
126
127 useEffect(() => {
128 isRTL = getLanguageDirection(sliderRailRef.current) === 'rtl';
129 });
130
131 useEffect(() => {
132 setValue(value);
133 }, [value]);
134
135 useEffect(() => {
136 setLocalInputValue(inputValue);
137 }, [inputValue]);
138
139 let diff = 0;
140 let snapValue: number;
141
142 // calculate style value percentage
143 const stylePercent = ((localValue - min) * 100) / (max - min);
144 const style = { [cssSliderValue.name]: `${stylePercent}%` } as React.CSSProperties;
145 const widthChars = useMemo(() => localInputValue.toString().length, [localInputValue]);
146 const inputStyle = { [cssFormControlWidthChars.name]: widthChars } as React.CSSProperties;
147
148 const onChangeHandler = (_event: React.FormEvent<HTMLInputElement>, value: string) => {
149 setLocalInputValue(Number(value));
150 };
151
152 const handleKeyPressOnInput = (event: React.KeyboardEvent) => {
153 if (event.key === 'Enter') {
154 event.preventDefault();
155 if (onChange) {
156 onChange(event, localValue, localInputValue, setLocalInputValue);
157 }
158 }
159 };
160
161 const onInputFocus = (e: any) => {
162 e.stopPropagation();
163 };
164
165 const onThumbClick = () => {
166 thumbRef.current.focus();
167 };
168
169 const onBlur = (event: React.FocusEvent<HTMLInputElement>) => {
170 if (onChange) {
171 onChange(event, localValue, localInputValue, setLocalInputValue);
172 }
173 };
174
175 const findAriaTextValue = () => {
176 if (!areCustomStepsContinuous && customSteps) {
177 const matchingStep = customSteps.find((stepObj) => stepObj.value === localValue);
178 if (matchingStep) {
179 return matchingStep.label;
180 }
181 }
182 // For continuous steps default to showing 2 decimals in tooltip
183 // Consider making it configurable via a property
184 return Number(Number(localValue).toFixed(2)).toString();
185 };
186
187 const handleThumbDragEnd = () => {
188 document.removeEventListener('mousemove', callbackThumbMove);
189 document.removeEventListener('mouseup', callbackThumbUp);
190 document.removeEventListener('touchmove', callbackThumbMove);
191 document.removeEventListener('touchend', callbackThumbUp);
192 document.removeEventListener('touchcancel', callbackThumbUp);
193 };
194
195 const handleMouseDown = (e: React.MouseEvent) => {
196 e.stopPropagation();
197 e.preventDefault();
198
199 if (isRTL) {
200 diff = thumbRef.current.getBoundingClientRect().right - e.clientX;
201 } else {
202 diff = e.clientX - thumbRef.current.getBoundingClientRect().left;
203 }
204
205 document.addEventListener('mousemove', callbackThumbMove);
206 document.addEventListener('mouseup', callbackThumbUp);
207 };
208
209 const handleTouchStart = (e: React.TouchEvent) => {
210 e.stopPropagation();
211
212 if (isRTL) {
213 diff = thumbRef.current.getBoundingClientRect().right - e.touches[0].clientX;
214 } else {
215 diff = e.touches[0].clientX - thumbRef.current.getBoundingClientRect().left;
216 }
217
218 document.addEventListener('touchmove', callbackThumbMove, { passive: false });
219 document.addEventListener('touchend', callbackThumbUp);
220 document.addEventListener('touchcancel', callbackThumbUp);
221 };
222
223 const onSliderRailClick = (e: any) => {
224 handleThumbMove(e);
225 if (snapValue && !areCustomStepsContinuous) {
226 thumbRef.current.style.setProperty(cssSliderValue.name, `${snapValue}%`);
227 setValue(snapValue);
228 if (onChange) {
229 onChange(e, snapValue);
230 }
231 }
232 };
233
234 const handleThumbMove = (e: any) => {
235 if (e.type === 'touchmove') {
236 e.preventDefault();
237 e.stopImmediatePropagation();
238 }
239
240 const clientPosition = e.touches && e.touches.length ? e.touches[0].clientX : e.clientX;
241 let newPosition;
242
243 if (isRTL) {
244 newPosition = sliderRailRef.current.getBoundingClientRect().right - clientPosition - diff;
245 } else {
246 newPosition = clientPosition - diff - sliderRailRef.current.getBoundingClientRect().left;
247 }
248
249 const end = sliderRailRef.current.offsetWidth - thumbRef.current.offsetWidth;
250
251 const start = 0;
252
253 if (newPosition < start) {
254 newPosition = 0;
255 }
256
257 if (newPosition > end) {
258 newPosition = end;
259 }
260
261 const newPercentage = getPercentage(newPosition, end);
262
263 thumbRef.current.style.setProperty(cssSliderValue.name, `${newPercentage}%`);
264 // convert percentage to value
265 const newValue = Math.round(((newPercentage * (max - min)) / 100 + min) * 100) / 100;
266 setValue(newValue);
267
268 if (!customSteps) {
269 // snap to new value if not custom steps
270 snapValue = Math.round((Math.round((newValue - min) / step) * step + min) * 100) / 100;
271 thumbRef.current.style.setProperty(cssSliderValue.name, `${snapValue}%`);
272 setValue(snapValue);
273 }
274
275 /* If custom steps are discrete, snap to closest step value */
276 if (!areCustomStepsContinuous && customSteps) {
277 let percentage = newPercentage;
278 if (customSteps[customSteps.length - 1].value !== 100) {
279 percentage = (newPercentage * (max - min)) / 100 + min;
280 }
281 const stepIndex = customSteps.findIndex((stepObj) => stepObj.value >= percentage);
282 if (customSteps[stepIndex].value === percentage) {
283 snapValue = customSteps[stepIndex].value;
284 } else {
285 const midpoint = (customSteps[stepIndex].value + customSteps[stepIndex - 1].value) / 2;
286 if (midpoint > percentage) {
287 snapValue = customSteps[stepIndex - 1].value;
288 } else {
289 snapValue = customSteps[stepIndex].value;
290 }
291 }
292 setValue(snapValue);
293 }
294
295 // Call onchange callback
296 if (onChange) {
297 if (snapValue !== undefined) {
298 onChange(e, snapValue);
299 } else {
300 onChange(e, newValue);
301 }
302 }
303 };
304
305 const callbackThumbMove = useCallback(handleThumbMove, [min, max, customSteps, onChange]);
306 const callbackThumbUp = useCallback(handleThumbDragEnd, [min, max, customSteps, onChange]);
307
308 const handleThumbKeys = (e: React.KeyboardEvent) => {
309 const key = e.key;
310 if (key !== 'ArrowLeft' && key !== 'ArrowRight') {
311 return;
312 }
313 e.preventDefault();
314 let newValue: number = localValue;
315 if (!areCustomStepsContinuous && customSteps) {
316 const stepIndex = customSteps.findIndex((stepObj) => stepObj.value === localValue);
317 if (key === 'ArrowRight') {
318 if (isRTL) {
319 if (stepIndex - 1 >= 0) {
320 newValue = customSteps[stepIndex - 1].value;
321 }
322 } else {
323 if (stepIndex + 1 < customSteps.length) {
324 {
325 newValue = customSteps[stepIndex + 1].value;
326 }
327 }
328 }
329 } else if (key === 'ArrowLeft') {
330 if (isRTL) {
331 if (stepIndex + 1 < customSteps.length) {
332 {
333 newValue = customSteps[stepIndex + 1].value;
334 }
335 }
336 } else {
337 if (stepIndex - 1 >= 0) {
338 newValue = customSteps[stepIndex - 1].value;
339 }
340 }
341 }
342 } else {
343 if (key === 'ArrowRight') {
344 if (isRTL) {
345 newValue = localValue - step >= min ? localValue - step : min;
346 } else {
347 newValue = localValue + step <= max ? localValue + step : max;
348 }
349 } else if (key === 'ArrowLeft') {
350 if (isRTL) {
351 newValue = localValue + step <= max ? localValue + step : max;
352 } else {
353 newValue = localValue - step >= min ? localValue - step : min;
354 }
355 }
356 }
357
358 if (newValue !== localValue) {
359 thumbRef.current.style.setProperty(cssSliderValue.name, `${newValue}%`);
360 setValue(newValue);
361 if (onChange) {
362 onChange(e, newValue);
363 }
364 }
365 };
366
367 const displayInput = () => {
368 const textInput = (
369 <TextInput
370 isDisabled={isDisabled}
371 type="number"
372 value={localInputValue}
373 aria-label={inputAriaLabel}
374 onKeyDown={handleKeyPressOnInput}
375 onChange={onChangeHandler}
376 onClick={onInputFocus}
377 onFocus={onInputFocus}
378 onBlur={onBlur}
379 />
380 );
381 if (inputLabel) {
382 return (
383 <InputGroup>
384 <InputGroupItem isFill>{textInput}</InputGroupItem>
385 <InputGroupText isDisabled={isDisabled}>{inputLabel}</InputGroupText>
386 </InputGroup>
387 );
388 } else {
389 return textInput;
390 }
391 };
392
393 const getStepValue = (val: number, min: number, max: number) => ((val - min) * 100) / (max - min);
394 const buildSteps = () => {
395 const builtSteps = [];
396 for (let i = min; i <= max; i = i + step) {
397 const stepValue = getStepValue(i, min, max);
398
399 // If boundaries but not ticks just generate the needed steps
400 // so that we don't pollute them DOM with empty divs
401 if (!showTicks && showBoundaries && i !== min && i !== max) {
402 continue;
403 }
404
405 builtSteps.push(
406 <SliderStep
407 key={i}
408 value={stepValue}
409 label={i.toString()}
410 isTickHidden={!showTicks}
411 isLabelHidden={(i === min || i === max) && showBoundaries ? false : true}
412 isActive={i <= localValue}
413 />
414 );
415 }
416 return builtSteps;
417 };
418
419 const thumbComponent = (
420 <div
421 className={css(styles.sliderThumb)}
422 ref={thumbRef}
423 tabIndex={isDisabled ? -1 : 0}
424 role="slider"
425 aria-valuemin={customSteps ? customSteps[0].value : min}
426 aria-valuemax={customSteps ? customSteps[customSteps.length - 1].value : max}
427 aria-valuenow={localValue}
428 aria-valuetext={findAriaTextValue()}
429 aria-label={thumbAriaLabel}
430 aria-disabled={isDisabled}
431 aria-describedby={ariaDescribedby}
432 aria-labelledby={ariaLabelledby}
433 onMouseDown={!isDisabled ? handleMouseDown : null}
434 onTouchStart={!isDisabled ? handleTouchStart : null}
435 onKeyDown={!isDisabled ? handleThumbKeys : null}
436 onClick={!isDisabled ? onThumbClick : null}
437 />
438 );
439
440 return (
441 <div
442 className={css(styles.slider, className, isDisabled && styles.modifiers.disabled)}
443 style={{ ...style, ...inputStyle }}
444 {...props}
445 >
446 {(leftActions || startActions) && <div className={css(styles.sliderActions)}>{leftActions || startActions}</div>}
447 <div className={css(styles.sliderMain)}>
448 <div className={css(styles.sliderRail)} ref={sliderRailRef} onClick={!isDisabled ? onSliderRailClick : null}>
449 <div className={css(styles.sliderRailTrack)} />
450 </div>
451 {customSteps && (
452 <div className={css(styles.sliderSteps)} aria-hidden="true">
453 {customSteps.map((stepObj) => {
454 const minValue = customSteps[0].value;
455 const maxValue = customSteps[customSteps.length - 1].value;
456 const stepValue = getStepValue(stepObj.value, minValue, maxValue);
457
458 return (
459 <SliderStep
460 key={stepObj.value}
461 value={stepValue}
462 label={stepObj.label}
463 isLabelHidden={stepObj.isLabelHidden}
464 isActive={stepObj.value <= localValue}
465 />
466 );
467 })}
468 </div>
469 )}
470 {!customSteps && (showTicks || showBoundaries) && (
471 <div className={css(styles.sliderSteps)} aria-hidden="true">
472 {buildSteps()}
473 </div>
474 )}
475 {hasTooltipOverThumb ? (
476 <Tooltip
477 className={css('pf-v6-m-tabular-nums')}
478 triggerRef={thumbRef}
479 entryDelay={0}
480 content={findAriaTextValue()}
481 >
482 {thumbComponent}
483 </Tooltip>
484 ) : (
485 thumbComponent
486 )}
487 {isInputVisible && inputPosition === 'aboveThumb' && (
488 <div className={css(styles.sliderValue, styles.modifiers.floating)}>{displayInput()}</div>
489 )}
490 </div>
491 {isInputVisible && (inputPosition === 'right' || inputPosition === 'end') && (
492 <div className={css(styles.sliderValue)}>{displayInput()}</div>
493 )}
494 {(rightActions || endActions) && <div className={css(styles.sliderActions)}>{rightActions || endActions}</div>}
495 </div>
496 );
497 };
498 Slider.displayName = 'Slider';