diff --git a/examples/react/basic/src/main.tsx b/examples/react/basic/src/main.tsx index 5e58f96..4bd909b 100644 --- a/examples/react/basic/src/main.tsx +++ b/examples/react/basic/src/main.tsx @@ -34,6 +34,8 @@ function App() { boxShadow: 'inset 0 1px 2px rgba(0,0,0,.6)', borderRadius: '2px', }} + onMouseDown={rangerInstance.handleRailPress} + onTouchStart={rangerInstance.handleRailPress} > {rangerInstance .handles() diff --git a/packages/ranger/src/index.ts b/packages/ranger/src/index.ts index 84f4116..b75b4aa 100644 --- a/packages/ranger/src/index.ts +++ b/packages/ranger/src/index.ts @@ -115,6 +115,22 @@ export class Ranger<TTrackElement = unknown> { } } + getClosesValueIndex = (percentage: number): number => { + let closesValueIndex = -1 + let distanceBuffer = -1 + + this.options.values.forEach((value, index) => { + const diff = this.getPercentageForValue(value) - percentage + const distance = Math.abs(diff) + if (closesValueIndex === -1 || distance < distanceBuffer) { + closesValueIndex = index + distanceBuffer = distance + } + }) + + return closesValueIndex + } + roundToStep = (val: number) => { const { min, max } = this.options @@ -217,6 +233,19 @@ export class Ranger<TTrackElement = unknown> { document.addEventListener('touchend', handleRelease) } + handleRailPress = (e: any) => { + const clientX = + e.type === 'touchmove' ? e.changedTouches[0].clientX : e.clientX + const value = this.getValueForClientX(clientX) + const percentageForValue = this.getPercentageForValue(value) + const activeHandleIndex = this.getClosesValueIndex(percentageForValue) + + this.activeHandleIndex = activeHandleIndex + + this.handleDrag(e) + this.handlePress(e, activeHandleIndex) + } + getPercentageForValue = (val: number) => this.options.interpolator.getPercentageForValue( val,