@revenuecat/purchases-ui-js
Version:
Web components for Paywalls. Powered by RevenueCat
58 lines (57 loc) • 2.14 kB
JavaScript
export function mapPageAlignment(alignment) {
switch (alignment) {
case "top":
return "flex-start";
case "center":
return "center";
case "bottom":
return "flex-end";
}
}
export function clamp(value, min, max) {
return Math.max(min, Math.min(value, max));
}
/**
* Advance one page when the drag passed this fraction of a page's width,
* matching the iOS SDK carousel. A shorter drag snaps back to the page the
* gesture started on.
*/
export const PAGE_ADVANCE_THRESHOLD = 0.2;
/**
* Decides which page a swipe settles on when the pointer is released.
*
* Distance-based (not velocity-based), mirroring the iOS SDK's `handleDragEnd`:
* a drag past `PAGE_ADVANCE_THRESHOLD` of a page's width advances exactly one
* page in the swipe direction regardless of speed; a shorter drag stays put.
* Non-loop carousels clamp at their first and last page; loop carousels may
* return an index just outside `[0, pageCount)` so the caller can animate into
* a clone before normalizing.
*
* @param startPage Page the gesture started on.
* @param dragDistance Signed change in slider translation (negative = finger
* moved left / next page).
* @param pageWidth Width of a single page in px.
* @param pageCount Total number of real pages.
* @param loop Whether the carousel loops.
*/
export function getSwipeTargetPage({ startPage, dragDistance, pageWidth, pageCount, loop, advanceThreshold = PAGE_ADVANCE_THRESHOLD, }) {
const threshold = pageWidth * advanceThreshold;
let page = startPage;
if (dragDistance < -threshold) {
// Finger moved left, content shifts left: next page.
page += 1;
}
else if (dragDistance > threshold) {
// Finger moved right: previous page.
page -= 1;
}
return loop ? page : clamp(page, 0, pageCount - 1);
}
export function getTranslation(element) {
if (element === null) {
return 0;
}
const style = window.getComputedStyle(element);
const trasform = new WebKitCSSMatrix(style.transform);
return trasform.m41;
}