-
Notifications
You must be signed in to change notification settings - Fork 331
/
Copy pathslider.tsx
190 lines (172 loc) · 5.43 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
import React, {
RefObject,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react'
import useTheme from '../use-theme'
import useDrag, { DraggingEvent } from '../utils/use-drag'
import useCurrentState from '../utils/use-current-state'
import SliderDot from './slider-dot'
import SliderMark from './slider-mark'
import { getColors } from './styles'
import { NormalTypes } from '../utils/prop-types'
import useScale, { withScale } from '../use-scale'
import useClasses from '../use-classes'
export type SliderTypes = NormalTypes
interface Props {
hideValue?: boolean
value?: number
type?: SliderTypes
initialValue?: number
step?: number
max?: number
min?: number
disabled?: boolean
showMarkers?: boolean
onChange?: (val: number) => void
className?: string
}
const defaultProps = {
hideValue: false,
type: 'default' as SliderTypes,
initialValue: 0,
step: 1,
min: 0,
max: 100,
disabled: false,
showMarkers: false,
className: '',
}
type NativeAttrs = Omit<React.HTMLAttributes<any>, keyof Props>
export type SliderProps = Props & NativeAttrs
const getRefWidth = (elementRef: RefObject<HTMLElement> | null): number => {
if (!elementRef || !elementRef.current) return 0
const rect = elementRef.current.getBoundingClientRect()
return rect.width || rect.right - rect.left
}
const getValue = (
max: number,
min: number,
step: number,
offsetX: number,
railWidth: number,
): number => {
if (offsetX < 0) return min
if (offsetX > railWidth) return max
const widthForEachStep = (railWidth / (max - min)) * step
if (widthForEachStep <= 0) return min
const slideDistance = Math.round(offsetX / widthForEachStep) * step + min
return Number.isInteger(slideDistance)
? slideDistance
: Number.parseFloat(slideDistance.toFixed(1))
}
const SliderComponent: React.FC<React.PropsWithChildren<SliderProps>> = ({
hideValue,
disabled,
type,
step,
max,
min,
initialValue,
value: customValue,
onChange,
className,
showMarkers,
...props
}: React.PropsWithChildren<SliderProps> & typeof defaultProps) => {
const theme = useTheme()
const { SCALES } = useScale()
const [value, setValue] = useState<number>(initialValue)
const [, setSliderWidth, sideWidthRef] = useCurrentState<number>(0)
const [, setLastDargOffset, lastDargOffsetRef] = useCurrentState<number>(0)
const [isClick, setIsClick] = useState<boolean>(false)
const sliderRef = useRef<HTMLDivElement>(null)
const dotRef = useRef<HTMLDivElement>(null)
const currentRatio = useMemo(
() => ((value - min) / (max - min)) * 100,
[value, max, min],
)
const setLastOffsetManually = (val: number) => {
const width = getRefWidth(sliderRef)
const shouldOffset = ((val - min) / (max - min)) * width
setLastDargOffset(shouldOffset)
}
const updateValue = useCallback(
offset => {
const currentValue = getValue(max, min, step, offset, sideWidthRef.current)
setValue(currentValue)
onChange && onChange(currentValue)
},
[max, min, step, sideWidthRef],
)
const { bg } = useMemo(() => getColors(theme.palette, type), [theme.palette, type])
const dragHandler = (event: DraggingEvent) => {
if (disabled) return
const currentOffset = event.currentX - event.startX
const offset = currentOffset + lastDargOffsetRef.current
updateValue(offset)
}
const dragStartHandler = () => {
setIsClick(false)
setSliderWidth(getRefWidth(sliderRef))
}
const dragEndHandler = (event: DraggingEvent) => {
if (disabled) return
const offset = event.currentX - event.startX
const currentOffset = offset + lastDargOffsetRef.current
const boundOffset =
currentOffset < 0 ? 0 : Math.min(currentOffset, sideWidthRef.current)
setLastDargOffset(boundOffset)
}
const clickHandler = (event: React.MouseEvent<HTMLDivElement>) => {
if (disabled) return
if (!sliderRef || !sliderRef.current) return
setIsClick(true)
setSliderWidth(getRefWidth(sliderRef))
const clickOffset = event.clientX - sliderRef.current.getBoundingClientRect().x
setLastDargOffset(clickOffset)
updateValue(clickOffset)
}
useDrag(dotRef, dragHandler, dragStartHandler, dragEndHandler)
useEffect(() => {
if (customValue === undefined) return
if (customValue === value) return
setValue(customValue)
}, [customValue, value])
useEffect(() => {
initialValue && setLastOffsetManually(initialValue)
}, [])
return (
<div
className={useClasses('slider', className)}
onClick={clickHandler}
ref={sliderRef}
{...props}
>
<SliderDot disabled={disabled} ref={dotRef} isClick={isClick} left={currentRatio}>
{hideValue || value}
</SliderDot>
{showMarkers && <SliderMark max={max} min={min} step={step} />}
<style jsx>{`
.slider {
border-radius: 50px;
background-color: ${disabled ? theme.palette.accents_2 : bg};
position: relative;
cursor: ${disabled ? 'not-allow' : 'pointer'};
--slider-font-size: ${SCALES.font(1)};
width: ${SCALES.width(1, '100%')};
height: ${SCALES.height(0.5)};
padding: ${SCALES.pt(0)} ${SCALES.pr(0)} ${SCALES.pb(0)} ${SCALES.pl(0)};
margin: ${SCALES.mt(0)} ${SCALES.mr(0)} ${SCALES.mb(0)} ${SCALES.ml(0)};
}
`}</style>
</div>
)
}
SliderComponent.defaultProps = defaultProps
SliderComponent.displayName = 'GeistSlider'
const Slider = withScale(SliderComponent)
export default Slider