Momentum
The speed of a pointer just before release, how far a flick coasts, and the rubber band past an edge.
Reach for them for a flick, a momentum scroll, a snap target or a pull past the end of a list. The helpers are pure: no DOM at import time or in the call path, so they run on the server and in tests. Each result below is computed when the page is built, by running the call shown.
Import
import {
createVelocityTracker,
projectDistance,
rubberBand,
type VelocityTracker,
type VelocityTrackerOptions,
} from '@ecopages/radiant-ui/helpers';Velocity tracker
createVelocityTracker({ horizon, staleAfter, maxSpeed }) collects timed values of one coordinate with add(time, value) and reports velocity(time) in units per ms, signed. The speed is measured from the oldest sample within horizon (100 ms) of the newest to the newest, so it is the speed just before the query, not an average since the press. A gap of more than staleAfter (40 ms) between samples drops the ones before it, a query that long after the last sample reads 0, and the result is capped at maxSpeed (8) either way. reset() starts a new gesture. Use one tracker per axis, fed event.timeStamp and a client coordinate on the press, every move and the release.
const x = createVelocityTracker();
x.add(0, 200); // the press, then a 400 ms rest
x.add(410, 190);
x.add(430, 170); // the release
x.velocity(430); // -1| Call | Result |
|---|---|
tracker.velocity(430) // after the calls above | -1 |
SwipeController feeds two trackers and passes the release velocity to resolveSwipeDirection, so a flick after a pause still counts.
Projection and rubber band
projectDistance(velocity, decay) is how far a motion released at velocity coasts when each ms keeps decay (0.998 by default, a normal momentum scroll) of the speed. rubberBand(distance, dimension, constant) damps a drag past an edge so it never reaches dimension; a lower constant (0.55 by default) resists more.
| Call | Result |
|---|---|
projectDistance(1) | 498.99999999999955 |
projectDistance(-0.5, 0.99) | -49.49999999999996 |
rubberBand(100, 400) | 48.35164835164836 |
rubberBand(-100, 400) | -48.35164835164836 |