Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add drag to closes handle when press on a rail #86

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions examples/react/basic/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
29 changes: 29 additions & 0 deletions packages/ranger/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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,
Expand Down