-
Notifications
You must be signed in to change notification settings - Fork 918
/
Copy pathSlider.tsx
722 lines (649 loc) · 25.7 KB
/
Slider.tsx
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
import * as React from 'react';
import { clamp } from '@radix-ui/number';
import { composeEventHandlers } from '@radix-ui/primitive';
import { useComposedRefs } from '@radix-ui/react-compose-refs';
import { createContextScope } from '@radix-ui/react-context';
import { useControllableState } from '@radix-ui/react-use-controllable-state';
import { useDirection } from '@radix-ui/react-direction';
import { usePrevious } from '@radix-ui/react-use-previous';
import { useSize } from '@radix-ui/react-use-size';
import { Primitive } from '@radix-ui/react-primitive';
import { createCollection } from '@radix-ui/react-collection';
import type * as Radix from '@radix-ui/react-primitive';
import type { Scope } from '@radix-ui/react-context';
type Direction = 'ltr' | 'rtl';
const PAGE_KEYS = ['PageUp', 'PageDown'];
const ARROW_KEYS = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'];
const BACK_KEYS: Record<Direction, string[]> = {
ltr: ['ArrowDown', 'Home', 'ArrowLeft', 'PageDown'],
rtl: ['ArrowDown', 'Home', 'ArrowRight', 'PageDown'],
};
/* -------------------------------------------------------------------------------------------------
* Slider
* -----------------------------------------------------------------------------------------------*/
const SLIDER_NAME = 'Slider';
const [Collection, useCollection, createCollectionScope] =
createCollection<SliderThumbElement>(SLIDER_NAME);
type ScopedProps<P> = P & { __scopeSlider?: Scope };
const [createSliderContext, createSliderScope] = createContextScope(SLIDER_NAME, [
createCollectionScope,
]);
type SliderContextValue = {
disabled?: boolean;
min: number;
max: number;
values: number[];
valueIndexToChangeRef: React.MutableRefObject<number>;
thumbs: Set<SliderThumbElement>;
orientation: SliderProps['orientation'];
};
const [SliderProvider, useSliderContext] = createSliderContext<SliderContextValue>(SLIDER_NAME);
type SliderElement = SliderHorizontalElement | SliderVerticalElement;
interface SliderProps
extends Omit<
SliderHorizontalProps | SliderVerticalProps,
keyof SliderOrientationPrivateProps | 'defaultValue'
> {
name?: string;
disabled?: boolean;
orientation?: React.AriaAttributes['aria-orientation'];
dir?: Direction;
min?: number;
max?: number;
step?: number;
minStepsBetweenThumbs?: number;
value?: number[];
defaultValue?: number[];
onValueChange?(value: number[]): void;
}
const Slider = React.forwardRef<SliderElement, SliderProps>(
(props: ScopedProps<SliderProps>, forwardedRef) => {
const {
name,
min = 0,
max = 100,
step = 1,
orientation = 'horizontal',
disabled = false,
minStepsBetweenThumbs = 0,
defaultValue = [min],
value,
onValueChange = () => {},
...sliderProps
} = props;
const [slider, setSlider] = React.useState<HTMLSpanElement | null>(null);
const composedRefs = useComposedRefs(forwardedRef, (node) => setSlider(node));
const thumbRefs = React.useRef<SliderContextValue['thumbs']>(new Set());
const valueIndexToChangeRef = React.useRef<number>(0);
const isHorizontal = orientation === 'horizontal';
// We set this to true by default so that events bubble to forms without JS (SSR)
const isFormControl = slider ? Boolean(slider.closest('form')) : true;
const SliderOrientation = isHorizontal ? SliderHorizontal : SliderVertical;
const [values = [], setValues] = useControllableState({
prop: value,
defaultProp: defaultValue,
onChange: (value) => {
const thumbs = [...thumbRefs.current];
thumbs[valueIndexToChangeRef.current]?.focus();
onValueChange(value);
},
});
function handleSlideStart(value: number) {
const closestIndex = getClosestValueIndex(values, value);
updateValues(value, closestIndex);
}
function handleSlideMove(value: number) {
updateValues(value, valueIndexToChangeRef.current);
}
function updateValues(value: number, atIndex: number) {
const decimalCount = getDecimalCount(step);
const snapToStep = roundValue(Math.round((value - min) / step) * step + min, decimalCount);
const nextValue = clamp(snapToStep, [min, max]);
setValues((prevValues = []) => {
const nextValues = getNextSortedValues(prevValues, nextValue, atIndex);
if (hasMinStepsBetweenValues(nextValues, minStepsBetweenThumbs * step)) {
valueIndexToChangeRef.current = nextValues.indexOf(nextValue);
return String(nextValues) === String(prevValues) ? prevValues : nextValues;
} else {
return prevValues;
}
});
}
return (
<SliderProvider
scope={props.__scopeSlider}
disabled={disabled}
min={min}
max={max}
valueIndexToChangeRef={valueIndexToChangeRef}
thumbs={thumbRefs.current}
values={values}
orientation={orientation}
>
<Collection.Provider scope={props.__scopeSlider}>
<Collection.Slot scope={props.__scopeSlider}>
<SliderOrientation
aria-disabled={disabled}
data-disabled={disabled ? '' : undefined}
{...sliderProps}
ref={composedRefs}
min={min}
max={max}
onSlideStart={disabled ? undefined : handleSlideStart}
onSlideMove={disabled ? undefined : handleSlideMove}
onHomeKeyDown={() => !disabled && updateValues(min, 0)}
onEndKeyDown={() => !disabled && updateValues(max, values.length - 1)}
onStepKeyDown={({ event, direction: stepDirection }) => {
if (!disabled) {
const isPageKey = PAGE_KEYS.includes(event.key);
const isSkipKey = isPageKey || (event.shiftKey && ARROW_KEYS.includes(event.key));
const multiplier = isSkipKey ? 10 : 1;
const atIndex = valueIndexToChangeRef.current;
const value = values[atIndex];
const stepInDirection = step * multiplier * stepDirection;
updateValues(value + stepInDirection, atIndex);
}
}}
/>
</Collection.Slot>
</Collection.Provider>
{isFormControl &&
values.map((value, index) => (
<BubbleInput
key={index}
name={name ? name + (values.length > 1 ? '[]' : '') : undefined}
value={value}
/>
))}
</SliderProvider>
);
}
);
Slider.displayName = SLIDER_NAME;
/* -------------------------------------------------------------------------------------------------
* SliderHorizontal
* -----------------------------------------------------------------------------------------------*/
const [SliderOrientationProvider, useSliderOrientationContext] = createSliderContext<{
startEdge: 'bottom' | 'left' | 'right';
endEdge: 'top' | 'right' | 'left';
size: keyof NonNullable<ReturnType<typeof useSize>>;
direction: number;
}>(SLIDER_NAME, {
startEdge: 'left',
endEdge: 'right',
size: 'width',
direction: 1,
});
type SliderOrientationPrivateProps = {
min: number;
max: number;
onSlideStart?(value: number): void;
onSlideMove?(value: number): void;
onHomeKeyDown(event: React.KeyboardEvent): void;
onEndKeyDown(event: React.KeyboardEvent): void;
onStepKeyDown(step: { event: React.KeyboardEvent; direction: number }): void;
};
interface SliderOrientationProps
extends Omit<SliderImplProps, keyof SliderImplPrivateProps>,
SliderOrientationPrivateProps {}
type SliderHorizontalElement = SliderImplElement;
interface SliderHorizontalProps extends SliderOrientationProps {
dir?: Direction;
}
const SliderHorizontal = React.forwardRef<SliderHorizontalElement, SliderHorizontalProps>(
(props: ScopedProps<SliderHorizontalProps>, forwardedRef) => {
const { min, max, dir, onSlideStart, onSlideMove, onStepKeyDown, ...sliderProps } = props;
const [slider, setSlider] = React.useState<SliderImplElement | null>(null);
const composedRefs = useComposedRefs(forwardedRef, (node) => setSlider(node));
const rectRef = React.useRef<ClientRect>();
const direction = useDirection(dir);
const isDirectionLTR = direction === 'ltr';
function getValueFromPointer(pointerPosition: number) {
const rect = rectRef.current || slider!.getBoundingClientRect();
const input: [number, number] = [0, rect.width];
const output: [number, number] = isDirectionLTR ? [min, max] : [max, min];
const value = linearScale(input, output);
rectRef.current = rect;
return value(pointerPosition - rect.left);
}
return (
<SliderOrientationProvider
scope={props.__scopeSlider}
startEdge={isDirectionLTR ? 'left' : 'right'}
endEdge={isDirectionLTR ? 'right' : 'left'}
direction={isDirectionLTR ? 1 : -1}
size="width"
>
<SliderImpl
dir={direction}
data-orientation="horizontal"
{...sliderProps}
ref={composedRefs}
style={{
...sliderProps.style,
['--radix-slider-thumb-transform' as any]: 'translateX(-50%)',
}}
onSlideStart={(event) => {
const value = getValueFromPointer(event.clientX);
onSlideStart?.(value);
}}
onSlideMove={(event) => {
const value = getValueFromPointer(event.clientX);
onSlideMove?.(value);
}}
onSlideEnd={() => (rectRef.current = undefined)}
onStepKeyDown={(event) => {
const isBackKey = BACK_KEYS[direction].includes(event.key);
onStepKeyDown?.({ event, direction: isBackKey ? -1 : 1 });
}}
/>
</SliderOrientationProvider>
);
}
);
/* -------------------------------------------------------------------------------------------------
* SliderVertical
* -----------------------------------------------------------------------------------------------*/
type SliderVerticalElement = SliderImplElement;
interface SliderVerticalProps extends SliderOrientationProps {}
const SliderVertical = React.forwardRef<SliderVerticalElement, SliderVerticalProps>(
(props: ScopedProps<SliderVerticalProps>, forwardedRef) => {
const { min, max, onSlideStart, onSlideMove, onStepKeyDown, ...sliderProps } = props;
const sliderRef = React.useRef<SliderImplElement>(null);
const ref = useComposedRefs(forwardedRef, sliderRef);
const rectRef = React.useRef<ClientRect>();
function getValueFromPointer(pointerPosition: number) {
const rect = rectRef.current || sliderRef.current!.getBoundingClientRect();
const input: [number, number] = [0, rect.height];
const output: [number, number] = [max, min];
const value = linearScale(input, output);
rectRef.current = rect;
return value(pointerPosition - rect.top);
}
return (
<SliderOrientationProvider
scope={props.__scopeSlider}
startEdge="bottom"
endEdge="top"
size="height"
direction={1}
>
<SliderImpl
data-orientation="vertical"
{...sliderProps}
ref={ref}
style={{
...sliderProps.style,
['--radix-slider-thumb-transform' as any]: 'translateY(50%)',
}}
onSlideStart={(event) => {
const value = getValueFromPointer(event.clientY);
onSlideStart?.(value);
}}
onSlideMove={(event) => {
const value = getValueFromPointer(event.clientY);
onSlideMove?.(value);
}}
onSlideEnd={() => (rectRef.current = undefined)}
onStepKeyDown={(event) => {
const isBackKey = BACK_KEYS.ltr.includes(event.key);
onStepKeyDown?.({ event, direction: isBackKey ? -1 : 1 });
}}
/>
</SliderOrientationProvider>
);
}
);
/* -------------------------------------------------------------------------------------------------
* SliderImpl
* -----------------------------------------------------------------------------------------------*/
type SliderImplElement = React.ElementRef<typeof Primitive.span>;
type PrimitiveDivProps = Radix.ComponentPropsWithoutRef<typeof Primitive.div>;
type SliderImplPrivateProps = {
onSlideStart(event: React.PointerEvent): void;
onSlideMove(event: React.PointerEvent): void;
onSlideEnd(event: React.PointerEvent): void;
onHomeKeyDown(event: React.KeyboardEvent): void;
onEndKeyDown(event: React.KeyboardEvent): void;
onStepKeyDown(event: React.KeyboardEvent): void;
};
interface SliderImplProps extends PrimitiveDivProps, SliderImplPrivateProps {}
const SliderImpl = React.forwardRef<SliderImplElement, SliderImplProps>(
(props: ScopedProps<SliderImplProps>, forwardedRef) => {
const {
__scopeSlider,
onSlideStart,
onSlideMove,
onSlideEnd,
onHomeKeyDown,
onEndKeyDown,
onStepKeyDown,
...sliderProps
} = props;
const context = useSliderContext(SLIDER_NAME, __scopeSlider);
return (
<Primitive.span
{...sliderProps}
ref={forwardedRef}
onKeyDown={composeEventHandlers(props.onKeyDown, (event) => {
if (event.key === 'Home') {
onHomeKeyDown(event);
// Prevent scrolling to page start
event.preventDefault();
} else if (event.key === 'End') {
onEndKeyDown(event);
// Prevent scrolling to page end
event.preventDefault();
} else if (PAGE_KEYS.concat(ARROW_KEYS).includes(event.key)) {
onStepKeyDown(event);
// Prevent scrolling for directional key presses
event.preventDefault();
}
})}
onPointerDown={composeEventHandlers(props.onPointerDown, (event) => {
const target = event.target as HTMLElement;
target.setPointerCapture(event.pointerId);
// Prevent browser focus behaviour because we focus a thumb manually when values change.
event.preventDefault();
// Touch devices have a delay before focusing so won't focus if touch immediately moves
// away from target (sliding). We want thumb to focus regardless.
if (context.thumbs.has(target)) {
target.focus();
} else {
onSlideStart(event);
}
})}
onPointerMove={composeEventHandlers(props.onPointerMove, (event) => {
const target = event.target as HTMLElement;
if (target.hasPointerCapture(event.pointerId)) onSlideMove(event);
})}
onPointerUp={composeEventHandlers(props.onPointerUp, (event) => {
const target = event.target as HTMLElement;
if (target.hasPointerCapture(event.pointerId)) {
target.releasePointerCapture(event.pointerId);
onSlideEnd(event);
}
})}
/>
);
}
);
/* -------------------------------------------------------------------------------------------------
* SliderTrack
* -----------------------------------------------------------------------------------------------*/
const TRACK_NAME = 'SliderTrack';
type SliderTrackElement = React.ElementRef<typeof Primitive.span>;
type PrimitiveSpanProps = Radix.ComponentPropsWithoutRef<typeof Primitive.span>;
interface SliderTrackProps extends PrimitiveSpanProps {}
const SliderTrack = React.forwardRef<SliderTrackElement, SliderTrackProps>(
(props: ScopedProps<SliderTrackProps>, forwardedRef) => {
const { __scopeSlider, ...trackProps } = props;
const context = useSliderContext(TRACK_NAME, __scopeSlider);
return (
<Primitive.span
data-disabled={context.disabled ? '' : undefined}
data-orientation={context.orientation}
{...trackProps}
ref={forwardedRef}
/>
);
}
);
SliderTrack.displayName = TRACK_NAME;
/* -------------------------------------------------------------------------------------------------
* SliderRange
* -----------------------------------------------------------------------------------------------*/
const RANGE_NAME = 'SliderRange';
type SliderRangeElement = React.ElementRef<typeof Primitive.span>;
interface SliderRangeProps extends PrimitiveSpanProps {}
const SliderRange = React.forwardRef<SliderRangeElement, SliderRangeProps>(
(props: ScopedProps<SliderRangeProps>, forwardedRef) => {
const { __scopeSlider, ...rangeProps } = props;
const context = useSliderContext(RANGE_NAME, __scopeSlider);
const orientation = useSliderOrientationContext(RANGE_NAME, __scopeSlider);
const ref = React.useRef<HTMLSpanElement>(null);
const composedRefs = useComposedRefs(forwardedRef, ref);
const valuesCount = context.values.length;
const percentages = context.values.map((value) =>
convertValueToPercentage(value, context.min, context.max)
);
const offsetStart = valuesCount > 1 ? Math.min(...percentages) : 0;
const offsetEnd = 100 - Math.max(...percentages);
return (
<Primitive.span
data-orientation={context.orientation}
data-disabled={context.disabled ? '' : undefined}
{...rangeProps}
ref={composedRefs}
style={{
...props.style,
[orientation.startEdge]: offsetStart + '%',
[orientation.endEdge]: offsetEnd + '%',
}}
/>
);
}
);
SliderRange.displayName = RANGE_NAME;
/* -------------------------------------------------------------------------------------------------
* SliderThumb
* -----------------------------------------------------------------------------------------------*/
const THUMB_NAME = 'SliderThumb';
type SliderThumbElement = SliderThumbImplElement;
interface SliderThumbProps extends Omit<SliderThumbImplProps, 'index'> {}
const SliderThumb = React.forwardRef<SliderThumbElement, SliderThumbProps>(
(props: ScopedProps<SliderThumbProps>, forwardedRef) => {
const getItems = useCollection(props.__scopeSlider);
const [thumb, setThumb] = React.useState<SliderThumbImplElement | null>(null);
const composedRefs = useComposedRefs(forwardedRef, (node) => setThumb(node));
const index = React.useMemo(
() => (thumb ? getItems().findIndex((item) => item.ref.current === thumb) : -1),
[getItems, thumb]
);
return <SliderThumbImpl {...props} ref={composedRefs} index={index} />;
}
);
type SliderThumbImplElement = React.ElementRef<typeof Primitive.span>;
interface SliderThumbImplProps extends PrimitiveSpanProps {
index: number;
}
const SliderThumbImpl = React.forwardRef<SliderThumbImplElement, SliderThumbImplProps>(
(props: ScopedProps<SliderThumbImplProps>, forwardedRef) => {
const { __scopeSlider, index, ...thumbProps } = props;
const context = useSliderContext(THUMB_NAME, __scopeSlider);
const orientation = useSliderOrientationContext(THUMB_NAME, __scopeSlider);
const [thumb, setThumb] = React.useState<HTMLSpanElement | null>(null);
const composedRefs = useComposedRefs(forwardedRef, (node) => setThumb(node));
const size = useSize(thumb);
// We cast because index could be `-1` which would return undefined
const value = context.values[index] as number | undefined;
const percent =
value === undefined ? 0 : convertValueToPercentage(value, context.min, context.max);
const label = getLabel(index, context.values.length);
const orientationSize = size?.[orientation.size];
const thumbInBoundsOffset = orientationSize
? getThumbInBoundsOffset(orientationSize, percent, orientation.direction)
: 0;
React.useEffect(() => {
if (thumb) {
context.thumbs.add(thumb);
return () => {
context.thumbs.delete(thumb);
};
}
}, [thumb, context.thumbs]);
return (
<span
style={{
transform: 'var(--radix-slider-thumb-transform)',
position: 'absolute',
[orientation.startEdge]: `calc(${percent}% + ${thumbInBoundsOffset}px)`,
}}
>
<Collection.ItemSlot scope={props.__scopeSlider}>
<Primitive.span
role="slider"
aria-label={props['aria-label'] || label}
aria-valuemin={context.min}
aria-valuenow={value}
aria-valuemax={context.max}
aria-orientation={context.orientation}
data-orientation={context.orientation}
data-disabled={context.disabled ? '' : undefined}
tabIndex={context.disabled ? undefined : 0}
{...thumbProps}
ref={composedRefs}
/**
* There will be no value on initial render while we work out the index so we hide thumbs
* without a value, otherwise SSR will render them in the wrong position before they
* snap into the correct position during hydration which would be visually jarring for
* slower connections.
*/
style={value === undefined ? { display: 'none' } : props.style}
onFocus={composeEventHandlers(props.onFocus, () => {
context.valueIndexToChangeRef.current = index;
})}
/>
</Collection.ItemSlot>
</span>
);
}
);
SliderThumb.displayName = THUMB_NAME;
/* -----------------------------------------------------------------------------------------------*/
const BubbleInput = (props: Radix.ComponentPropsWithoutRef<'input'>) => {
const { value, ...inputProps } = props;
const ref = React.useRef<HTMLInputElement>(null);
const prevValue = usePrevious(value);
// Bubble value change to parents (e.g form change event)
React.useEffect(() => {
const input = ref.current!;
const inputProto = window.HTMLInputElement.prototype;
const descriptor = Object.getOwnPropertyDescriptor(inputProto, 'value') as PropertyDescriptor;
const setValue = descriptor.set;
if (prevValue !== value && setValue) {
const event = new Event('input', { bubbles: true });
setValue.call(input, value);
input.dispatchEvent(event);
}
}, [prevValue, value]);
/**
* We purposefully do not use `type="hidden"` here otherwise forms that
* wrap it will not be able to access its value via the FormData API.
*
* We purposefully do not add the `value` attribute here to allow the value
* to be set programatically and bubble to any parent form `onChange` event.
* Adding the `value` will cause React to consider the programatic
* dispatch a duplicate and it will get swallowed.
*/
return <input style={{ display: 'none' }} {...inputProps} ref={ref} defaultValue={value} />;
};
function getNextSortedValues(prevValues: number[] = [], nextValue: number, atIndex: number) {
const nextValues = [...prevValues];
nextValues[atIndex] = nextValue;
return nextValues.sort((a, b) => a - b);
}
function convertValueToPercentage(value: number, min: number, max: number) {
const maxSteps = max - min;
const percentPerStep = 100 / maxSteps;
return percentPerStep * (value - min);
}
/**
* Returns a label for each thumb when there are two or more thumbs
*/
function getLabel(index: number, totalValues: number) {
if (totalValues > 2) {
return `Value ${index + 1} of ${totalValues}`;
} else if (totalValues === 2) {
return ['Minimum', 'Maximum'][index];
} else {
return undefined;
}
}
/**
* Given a `values` array and a `nextValue`, determine which value in
* the array is closest to `nextValue` and return its index.
*
* @example
* // returns 1
* getClosestValueIndex([10, 30], 25);
*/
function getClosestValueIndex(values: number[], nextValue: number) {
if (values.length === 1) return 0;
const distances = values.map((value) => Math.abs(value - nextValue));
const closestDistance = Math.min(...distances);
return distances.indexOf(closestDistance);
}
/**
* Offsets the thumb centre point while sliding to ensure it remains
* within the bounds of the slider when reaching the edges
*/
function getThumbInBoundsOffset(width: number, left: number, direction: number) {
const halfWidth = width / 2;
const halfPercent = 50;
const offset = linearScale([0, halfPercent], [0, halfWidth]);
return (halfWidth - offset(left) * direction) * direction;
}
/**
* Gets an array of steps between each value.
*
* @example
* // returns [1, 9]
* getStepsBetweenValues([10, 11, 20]);
*/
function getStepsBetweenValues(values: number[]) {
return values.slice(0, -1).map((value, index) => values[index + 1] - value);
}
/**
* Verifies the minimum steps between all values is greater than or equal
* to the expected minimum steps.
*
* @example
* // returns false
* hasMinStepsBetweenValues([1,2,3], 2);
*
* @example
* // returns true
* hasMinStepsBetweenValues([1,2,3], 1);
*/
function hasMinStepsBetweenValues(values: number[], minStepsBetweenValues: number) {
if (minStepsBetweenValues > 0) {
const stepsBetweenValues = getStepsBetweenValues(values);
const actualMinStepsBetweenValues = Math.min(...stepsBetweenValues);
return actualMinStepsBetweenValues >= minStepsBetweenValues;
}
return true;
}
// https://github.com/tmcw-up-for-adoption/simple-linear-scale/blob/master/index.js
function linearScale(input: readonly [number, number], output: readonly [number, number]) {
return (value: number) => {
if (input[0] === input[1] || output[0] === output[1]) return output[0];
const ratio = (output[1] - output[0]) / (input[1] - input[0]);
return output[0] + ratio * (value - input[0]);
};
}
function getDecimalCount(value: number) {
return (String(value).split('.')[1] || '').length;
}
function roundValue(value: number, decimalCount: number) {
const rounder = Math.pow(10, decimalCount);
return Math.round(value * rounder) / rounder;
}
const Root = Slider;
const Track = SliderTrack;
const Range = SliderRange;
const Thumb = SliderThumb;
export {
createSliderScope,
//
Slider,
SliderTrack,
SliderRange,
SliderThumb,
//
Root,
Track,
Range,
Thumb,
};
export type { SliderProps, SliderTrackProps, SliderRangeProps, SliderThumbProps };