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 'reverse' option to wheel gesture #660

Open
wants to merge 1 commit 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
33 changes: 33 additions & 0 deletions documentation/pages/docs/code/examples.js
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,39 @@ const limitFn = (b, y) =>

const closestLimit = (x, y) => Math.max(limitFn(xBounds, x), limitFn(yBounds, y))

export function Reverse({ setActive }) {
const [isReversed, setIsReversed] = useState(true)
const [{ x, y }, api] = useSpring(() => ({ x: 85, y: 51 }))
const [position] = useState({ x: 85, y: 51 })

const ref = useRef()
useWheel(
({ down, offset: [x, y] }, memo = position) => {
setActive && setActive(down)
api.start({ x: memo.x + x, y: memo.y + y, immediate: true })
},
{
preventDefault: true,
target: ref,
eventOptions: { passive: false },
reverse: isReversed
}
)
return (
<>
<div className={styles.ui}>
<label>
<input type="checkbox" checked={isReversed} onChange={(e) => setIsReversed(e.target.checked)} />
Use `reverse`
</label>
</div>
<div ref={ref} className={styles.limits}>
<animated.div className={styles.wheel} style={{ x, y }} />
</div>
</>
)
}

export function Rubberband({ setActive }) {
const [{ x, y }, api] = useSpring(() => ({ x: 0, y: 0 }))
const bind = useDrag(
Expand Down
7 changes: 7 additions & 0 deletions documentation/pages/docs/code/styles.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@
user-select: none;
}

.wheel {
background: #91c9f9;
border-radius: 16px;
height: 80px;
width: 80px;
}

.overlay {
position: fixed;
top: 0;
Expand Down
9 changes: 9 additions & 0 deletions documentation/pages/docs/options.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ Here are all options that can be applied to gestures.
| [`swipe.duration`](#swipeduration) | **drag** | The maximum duration in milliseconds that a swipe is detected. |
| `keyboardDisplacement` | **drag** | The distance (in `pixels`) emulated by arrow keys. Default is `10`. |
| `mouseOnly` | **hover, move** | Set to `false` if you want your `hover` or `move` handlers to be triggered on non-mouse events. This is a useful option in case you want to perform logic on touch-enabled devices. |
| [`reverse`](#reverse) | **wheel** | If `true`, inverts the direction of wheel scrolling to mimic natural touchpad gestures. |

## Options explained

Expand Down Expand Up @@ -435,6 +436,14 @@ On desktop, you should be able to drag the torus as you would expect without del

This can optionally be used together with `preventScroll`. This defines the axis/axes in which scrolling is permitted, unless the user taps and holds on the element for the specified duration. Afterwhich, all scrolling is blocked. Depending on the complexity of the nesting of the element, you may need to assign the property `touch-action: pan-x`, `touch-action: pan-y`, or both, to the element to allow for the correct behavior.

### reverse

<Specs types="boolean" defaultValue="false" />

When set to `true`, the `reverse` option inverses the direction of the wheel gesture. This can be useful in scenarios where the default gesture direction does not align with the intended interaction design. For example, in a carousel, setting `reverse` to `true` would mean swiping left would move to the next item, and swiping right would move to the previous item, which is the opposite of the default behavior.

<Code id="Reverse" />

### rubberband

<Specs types={['boolean', 'number', 'vector']} defaultValue="[0,0]" />
Expand Down
5 changes: 4 additions & 1 deletion packages/core/src/config/wheelConfigResolver.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { coordinatesConfigResolver } from './coordinatesConfigResolver'

export const wheelConfigResolver = coordinatesConfigResolver
export const wheelConfigResolver = {
...coordinatesConfigResolver,
reverse: (value = false) => value
}
4 changes: 3 additions & 1 deletion packages/core/src/engines/WheelEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ export class WheelEngine extends CoordinatesEngine<'wheel'> {

wheelChange(event: WheelEvent) {
const state = this.state
const { reverse } = this.config

state._delta = wheelValues(event)
V.addTo(state._movement, state._delta)
reverse ? V.subTo(state._movement, state._delta) : V.addTo(state._movement, state._delta)

// _movement rolls back to when it passed the bounds.
clampStateInternalMovementToBounds(state)
Expand Down
11 changes: 9 additions & 2 deletions packages/core/src/types/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,13 @@ export type MoveConfig = CoordinatesConfig<'move'> & MoveAndHoverMouseOnly

export type HoverConfig = MoveAndHoverMouseOnly

export type WheelConfig = {
/**
* If true, inverts the direction of wheel scrolling to mimic natural touchpad gestures.
*/
reverse?: boolean
}

export type DragConfig = Omit<CoordinatesConfig<'drag'>, 'axisThreshold' | 'bounds'> & {
/**
* If true, the component won't trigger your drag logic if the user just clicked on the component.
Expand Down Expand Up @@ -235,14 +242,14 @@ export type DragConfig = Omit<CoordinatesConfig<'drag'>, 'axisThreshold' | 'boun

export type UserDragConfig = GenericOptions & DragConfig
export type UserPinchConfig = GenericOptions & PinchConfig
export type UserWheelConfig = GenericOptions & CoordinatesConfig<'wheel'>
export type UserWheelConfig = GenericOptions & WheelConfig & CoordinatesConfig<'wheel'>
export type UserScrollConfig = GenericOptions & CoordinatesConfig<'scroll'>
export type UserMoveConfig = GenericOptions & MoveConfig
export type UserHoverConfig = GenericOptions & HoverConfig

export type UserGestureConfig = GenericOptions & {
drag?: DragConfig
wheel?: CoordinatesConfig<'wheel'>
wheel?: WheelConfig & CoordinatesConfig<'wheel'>
scroll?: CoordinatesConfig<'scroll'>
move?: MoveConfig
pinch?: PinchConfig
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/types/internalConfig.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { GestureKey, CoordinatesKey, ModifierKey } from './config'
import { GestureKey, CoordinatesKey, ModifierKey, WheelConfig } from './config'
import { State } from './state'
import { PointerType, Vector2 } from './utils'

Expand Down Expand Up @@ -66,7 +66,7 @@ type MoveAndHoverMouseOnly = {
export type InternalConfig = {
shared: InternalGenericOptions
drag?: InternalDragOptions
wheel?: InternalCoordinatesOptions<'wheel'>
wheel?: InternalCoordinatesOptions<'wheel'> & WheelConfig
scroll?: InternalCoordinatesOptions<'scroll'>
move?: InternalCoordinatesOptions<'move'> & MoveAndHoverMouseOnly
hover?: InternalCoordinatesOptions<'hover'> & MoveAndHoverMouseOnly
Expand Down
9 changes: 9 additions & 0 deletions test/wheel.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,15 @@ describe.each([
expect(getByTestId(`${prefix}wheel-movement`)).toHaveTextContent('13,0')
await waitFor(() => expect(getByTestId(`${prefix}wheel-wheeling`)).toHaveTextContent('false'))
})

test('applying reverse SHOULD inverse wheel directions', async () => {
rerender(<Component gestures={['Wheel']} config={{ wheel: { reverse: true } }} />)
fireEvent.wheel(element, { deltaX: -3, deltaY: 10 })
fireEvent.wheel(element, { deltaX: 4, deltaY: -6 })
expect(getByTestId(`${prefix}wheel-movement`)).toHaveTextContent('-1,-4')
await waitFor(() => expect(getByTestId(`${prefix}wheel-wheeling`)).toHaveTextContent('false'))
})

test('disabling all gestures should prevent state from updating', async () => {
rerender(<Component gestures={['Wheel']} config={{ enabled: false }} />)
fireEvent.wheel(element)
Expand Down