Skip to content

armgit / vaul

Public Imported from GitHub
0

A drawer component for React.

Support top/bottom/left/right drawer direction (#187)

David Young8f2b1ee9515f
diff --git a/README.md b/README.md
index fd24846..7144fdd 100644
--- a/README.md
+++ b/README.md
@@ -60,6 +60,8 @@ Additional props:
`modal`: When `false`it allows to interact with elements outside of the drawer without closing it. Defaults to`true`.
+`direction`: Direction of the drawer. Can be `top` or `bottom`, `left`, `right`. Defaults to `bottom`.
+
`preventScrollRestoration`: When `true` it prevents scroll restoration when the drawer is closed after a navigation happens inside of it. Defaults to `true`.
### Trigger
diff --git a/src/context.ts b/src/context.ts
index 4b9113b..c4c7743 100644
--- a/src/context.ts
+++ b/src/context.ts
@@ -1,4 +1,5 @@
import React from 'react';
+import { DrawerDirection } from './types';
interface DrawerContextValue {
drawerRef: React.RefObject<HTMLDivElement>;
@@ -24,6 +25,7 @@ interface DrawerContextValue {
setVisible: (o: boolean) => void;
openProp?: boolean;
onOpenChange?: (o: boolean) => void;
+ direction?: DrawerDirection;
}
export const DrawerContext = React.createContext<DrawerContextValue>({
@@ -50,6 +52,7 @@ export const DrawerContext = React.createContext<DrawerContextValue>({
visible: false,
closeDrawer: () => {},
setVisible: () => {},
+ direction: 'bottom',
});
export const useDrawerContext = () => React.useContext(DrawerContext);
diff --git a/src/helpers.ts b/src/helpers.ts
index e954d25..f72f32e 100644
--- a/src/helpers.ts
+++ b/src/helpers.ts
@@ -1,3 +1,5 @@
+import { DrawerDirection } from './types';
+
interface Style {
[key: string]: string;
}
@@ -54,15 +56,32 @@ export function reset(el: Element | HTMLElement | null, prop?: string) {
}
}
-export function getTranslateY(element: HTMLElement): number | null {
+export const isVertical = (direction: DrawerDirection) => {
+ switch (direction) {
+ case 'top':
+ case 'bottom':
+ return true;
+ case 'left':
+ case 'right':
+ return false;
+ default:
+ return direction satisfies never;
+ }
+};
+
+export function getTranslate(element: HTMLElement, direction: DrawerDirection): number | null {
const style = window.getComputedStyle(element);
const transform =
// @ts-ignore
style.transform || style.webkitTransform || style.mozTransform;
let mat = transform.match(/^matrix3d\((.+)\)$/);
- if (mat) return parseFloat(mat[1].split(', ')[13]);
+ if (mat) {
+ // https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/matrix3d
+ return parseFloat(mat[1].split(', ')[isVertical(direction) ? 13 : 12]);
+ }
+ // https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/matrix
mat = transform.match(/^matrix\((.+)\)$/);
- return mat ? parseFloat(mat[1].split(', ')[5]) : null;
+ return mat ? parseFloat(mat[1].split(', ')[isVertical(direction) ? 5 : 4]) : null;
}
export function dampenValue(v: number) {
diff --git a/src/index.tsx b/src/index.tsx
index 3f6c167..28f3104 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -8,7 +8,7 @@ import { usePreventScroll, isInput, isIOS } from './use-prevent-scroll';
import { useComposedRefs } from './use-composed-refs';
import { usePositionFixed } from './use-position-fixed';
import { useSnapPoints } from './use-snap-points';
-import { set, reset, getTranslateY, dampenValue } from './helpers';
+import { set, reset, getTranslate, dampenValue, isVertical } from './helpers';
import { TRANSITIONS, VELOCITY_THRESHOLD } from './constants';
const CLOSE_THRESHOLD = 0.25;
@@ -49,6 +49,7 @@ type DialogProps = {
modal?: boolean;
nested?: boolean;
onClose?: () => void;
+ direction?: 'top' | 'bottom' | 'left' | 'right';
preventScrollRestoration?: boolean;
} & (WithFadeFromProps | WithoutFadeFromProps);
@@ -60,7 +61,7 @@ function Root({
onDrag: onDragProp,
onRelease: onReleaseProp,
snapPoints,
- nested,
+ nested = false,
closeThreshold = CLOSE_THRESHOLD,
scrollLockTimeout = SCROLL_LOCK_TIMEOUT,
dismissible = true,
@@ -70,6 +71,7 @@ function Root({
fixed,
modal = true,
onClose,
+ direction = 'bottom',
preventScrollRestoration = true,
}: DialogProps) {
const [isOpen = false, setIsOpen] = React.useState<boolean>(false);
@@ -86,7 +88,7 @@ function Root({
const lastTimeDragPrevented = React.useRef<Date | null>(null);
const isAllowedToDrag = React.useRef<boolean>(false);
const nestedOpenChangeTimer = React.useRef<NodeJS.Timeout | null>(null);
- const pointerStartY = React.useRef(0);
+ const pointerStart = React.useRef(0);
const keyboardIsOpen = React.useRef(false);
const previousDiffFromInitial = React.useRef(0);
const drawerRef = React.useRef<HTMLDivElement>(null);
@@ -115,6 +117,7 @@ function Root({
fadeFromIndex,
overlayRef,
onSnapPointChange,
+ direction,
});
usePreventScroll({
@@ -147,13 +150,13 @@ function Root({
// Ensure we maintain correct pointer capture even when going outside of the drawer
(event.target as HTMLElement).setPointerCapture(event.pointerId);
- pointerStartY.current = event.screenY;
+ pointerStart.current = isVertical(direction) ? event.screenY : event.screenX;
}
- function shouldDrag(el: EventTarget, isDraggingDown: boolean) {
+ function shouldDrag(el: EventTarget, isDraggingInDirection: boolean) {
let element = el as HTMLElement;
const highlightedText = window.getSelection()?.toString();
- const swipeAmount = drawerRef.current ? getTranslateY(drawerRef.current) : null;
+ const swipeAmount = drawerRef.current ? getTranslate(drawerRef.current, direction) : null;
const date = new Date();
// Allow scrolling when animating
@@ -161,8 +164,10 @@ function Root({
return false;
}
- if (swipeAmount > 0) {
- return true;
+ if (swipeAmount !== null) {
+ if (direction === 'bottom' || direction === 'right' ? swipeAmount > 0 : swipeAmount < 0) {
+ return true;
+ }
}
// Don't drag if there's highlighted text
@@ -180,7 +185,7 @@ function Root({
return false;
}
- if (isDraggingDown) {
+ if (isDraggingInDirection) {
lastTimeDragPrevented.current = date;
// We are dragging down so we should allow scrolling
@@ -212,15 +217,20 @@ function Root({
}
function onDrag(event: React.PointerEvent<HTMLDivElement>) {
+ if (!drawerRef.current) {
+ return;
+ }
// We need to know how much of the drawer has been dragged in percentages so that we can transform background accordingly
if (isDragging) {
- const draggedDistance = pointerStartY.current - event.screenY;
- const isDraggingDown = draggedDistance > 0;
+ const directionMultiplier = direction === 'bottom' || direction === 'right' ? 1 : -1;
+ const draggedDistance =
+ (pointerStart.current - (isVertical(direction) ? event.screenY : event.screenX)) * directionMultiplier;
+ const isDraggingInDirection = draggedDistance > 0;
// Disallow dragging down to close when first snap point is the active one and dismissible prop is set to false.
if (snapPoints && activeSnapPointIndex === 0 && !dismissible) return;
- if (!isAllowedToDrag.current && !shouldDrag(event.target, isDraggingDown)) return;
+ if (!isAllowedToDrag.current && !shouldDrag(event.target, isDraggingInDirection)) return;
drawerRef.current.classList.add(DRAG_CLASS);
// If shouldDrag gave true once after pressing down on the drawer, we set isAllowedToDrag to true and it will remain true until we let go, there's no reason to disable dragging mid way, ever, and that's the solution to it
isAllowedToDrag.current = true;
@@ -237,11 +247,14 @@ function Root({
}
// Run this only if snapPoints are not defined or if we are at the last snap point (highest one)
- if (isDraggingDown && !snapPoints) {
+ if (isDraggingInDirection && !snapPoints) {
const dampenedDraggedDistance = dampenValue(draggedDistance);
+ const translateValue = Math.min(dampenedDraggedDistance * -1, 0) * directionMultiplier;
set(drawerRef.current, {
- transform: `translate3d(0, ${Math.min(dampenedDraggedDistance * -1, 0)}px, 0)`,
+ transform: isVertical(direction)
+ ? `translate3d(0, ${translateValue}px, 0)`
+ : `translate3d(${translateValue}px, 0, 0)`,
});
return;
}
@@ -251,7 +264,7 @@ function Root({
const wrapper = document.querySelector('[vaul-drawer-wrapper]');
let percentageDragged = absDraggedDistance / drawerHeightRef.current;
- const snapPointPercentageDragged = getSnapPointsPercentageDragged(absDraggedDistance, isDraggingDown);
+ const snapPointPercentageDragged = getSnapPointsPercentageDragged(absDraggedDistance, isDraggingInDirection);
if (snapPointPercentageDragged !== null) {
percentageDragged = snapPointPercentageDragged;
@@ -277,13 +290,15 @@ function Root({
const scaleValue = Math.min(getScale() + percentageDragged * (1 - getScale()), 1);
const borderRadiusValue = 8 - percentageDragged * 8;
- const translateYValue = Math.max(0, 14 - percentageDragged * 14);
+ const translateValue = Math.max(0, 14 - percentageDragged * 14);
set(
wrapper,
{
borderRadius: `${borderRadiusValue}px`,
- transform: `scale(${scaleValue}) translate3d(0, ${translateYValue}px, 0)`,
+ transform: isVertical(direction)
+ ? `scale(${scaleValue}) translate3d(0, ${translateValue}px, 0)`
+ : `scale(${scaleValue}) translate3d(${translateValue}px, 0, 0)`,
transition: 'none',
},
true,
@@ -291,8 +306,12 @@ function Root({
}
if (!snapPoints) {
+ const translateValue = absDraggedDistance * directionMultiplier;
+
set(drawerRef.current, {
- transform: `translate3d(0, ${absDraggedDistance}px, 0)`,
+ transform: isVertical(direction)
+ ? `translate3d(0, ${translateValue}px, 0)`
+ : `translate3d(${translateValue}px, 0, 0)`,
});
}
}
@@ -367,7 +386,9 @@ function Root({
onClose?.();
set(drawerRef.current, {
- transform: `translate3d(0, 100%, 0)`,
+ transform: isVertical(direction)
+ ? `translate3d(0, ${direction === 'bottom' ? '100%' : '-100%'}, 0)`
+ : `translate3d(${direction === 'right' ? '100%' : '-100%'}, 0, 0)`,
transition: `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
});
@@ -425,7 +446,7 @@ function Root({
function resetDrawer() {
if (!drawerRef.current) return;
const wrapper = document.querySelector('[vaul-drawer-wrapper]');
- const currentSwipeAmount = getTranslateY(drawerRef.current);
+ const currentSwipeAmount = getTranslate(drawerRef.current, direction);
set(drawerRef.current, {
transform: 'translate3d(0, 0, 0)',
@@ -444,8 +465,15 @@ function Root({
{
borderRadius: `${BORDER_RADIUS}px`,
overflow: 'hidden',
- transform: `scale(${getScale()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,
- transformOrigin: 'top',
+ ...(isVertical(direction)
+ ? {
+ transform: `scale(${getScale()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,
+ transformOrigin: 'top',
+ }
+ : {
+ transform: `scale(${getScale()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,
+ transformOrigin: 'left',
+ }),
transitionProperty: 'transform, border-radius',
transitionDuration: `${TRANSITIONS.DURATION}s`,
transitionTimingFunction: `cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
@@ -465,14 +493,14 @@ function Root({
isAllowedToDrag.current = false;
setIsDragging(false);
dragEndTime.current = new Date();
- const swipeAmount = getTranslateY(drawerRef.current);
+ const swipeAmount = getTranslate(drawerRef.current, direction);
if (!shouldDrag(event.target, false) || !swipeAmount || Number.isNaN(swipeAmount)) return;
if (dragStartTime.current === null) return;
const timeTaken = dragEndTime.current.getTime() - dragStartTime.current.getTime();
- const distMoved = pointerStartY.current - event.screenY;
+ const distMoved = pointerStart.current - (isVertical(direction) ? event.screenY : event.screenX);
const velocity = Math.abs(distMoved) / timeTaken;
if (velocity > 0.05) {
@@ -485,8 +513,9 @@ function Root({
}
if (snapPoints) {
+ const directionMultiplier = direction === 'bottom' || direction === 'right' ? 1 : -1;
onReleaseSnapPoints({
- draggedDistance: distMoved,
+ draggedDistance: distMoved * directionMultiplier,
closeDrawer,
velocity,
dismissible,
@@ -496,7 +525,7 @@ function Root({
}
// Moved upwards, don't do anything
- if (distMoved > 0) {
+ if (direction === 'bottom' || direction === 'right' ? distMoved > 0 : distMoved < 0) {
resetDrawer();
onReleaseProp?.(event, true);
return;
@@ -529,7 +558,7 @@ function Root({
}, [isOpen]);
React.useEffect(() => {
- if (visible) {
+ if (drawerRef.current && visible) {
// Find all scrollable elements inside our drawer and assign a class to it so that we can disable overflow when dragging to prevent pointermove not being captured
const children = drawerRef?.current?.querySelectorAll('*');
children?.forEach((child: Element) => {
@@ -558,8 +587,15 @@ function Root({
set(wrapper, {
borderRadius: `${BORDER_RADIUS}px`,
overflow: 'hidden',
- transform: `scale(${getScale()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,
- transformOrigin: 'top',
+ ...(isVertical(direction)
+ ? {
+ transform: `scale(${getScale()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,
+ transformOrigin: 'top',
+ }
+ : {
+ transform: `scale(${getScale()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,
+ transformOrigin: 'left',
+ }),
transitionProperty: 'transform, border-radius',
transitionDuration: `${TRANSITIONS.DURATION}s`,
transitionTimingFunction: `cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
@@ -592,9 +628,12 @@ function Root({
if (!o && drawerRef.current) {
nestedOpenChangeTimer.current = setTimeout(() => {
+ const translateValue = getTranslate(drawerRef.current as HTMLElement, direction);
set(drawerRef.current, {
transition: 'none',
- transform: `translate3d(0, ${getTranslateY(drawerRef.current as HTMLElement)}px, 0)`,
+ transform: isVertical(direction)
+ ? `translate3d(0, ${translateValue}px, 0)`
+ : `translate3d(${translateValue}px, 0, 0)`,
});
}, 500);
}
@@ -602,24 +641,31 @@ function Root({
function onNestedDrag(event: React.PointerEvent<HTMLDivElement>, percentageDragged: number) {
if (percentageDragged < 0) return;
- const initialScale = (window.innerWidth - NESTED_DISPLACEMENT) / window.innerWidth;
+
+ const initialDim = isVertical(direction) ? window.innerHeight : window.innerWidth;
+ const initialScale = (initialDim - NESTED_DISPLACEMENT) / initialDim;
const newScale = initialScale + percentageDragged * (1 - initialScale);
- const newY = -NESTED_DISPLACEMENT + percentageDragged * NESTED_DISPLACEMENT;
+ const newTranslate = -NESTED_DISPLACEMENT + percentageDragged * NESTED_DISPLACEMENT;
set(drawerRef.current, {
- transform: `scale(${newScale}) translate3d(0, ${newY}px, 0)`,
+ transform: isVertical(direction)
+ ? `scale(${newScale}) translate3d(0, ${newTranslate}px, 0)`
+ : `scale(${newScale}) translate3d(${newTranslate}px, 0, 0)`,
transition: 'none',
});
}
function onNestedRelease(event: React.PointerEvent<HTMLDivElement>, o: boolean) {
- const scale = o ? (window.innerWidth - NESTED_DISPLACEMENT) / window.innerWidth : 1;
- const y = o ? -NESTED_DISPLACEMENT : 0;
+ const dim = isVertical(direction) ? window.innerHeight : window.innerWidth;
+ const scale = o ? (dim - NESTED_DISPLACEMENT) / dim : 1;
+ const translate = o ? -NESTED_DISPLACEMENT : 0;
if (o) {
set(drawerRef.current, {
transition: `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
- transform: `scale(${scale}) translate3d(0, ${y}px, 0)`,
+ transform: isVertical(direction)
+ ? `scale(${scale}) translate3d(0, ${translate}px, 0)`
+ : `scale(${scale}) translate3d(${translate}px, 0, 0)`,
});
}
}
@@ -667,6 +713,7 @@ function Root({
openProp,
modal,
snapPointsOffset,
+ direction,
}}
>
{children}
@@ -719,6 +766,7 @@ const Content = React.forwardRef<HTMLDivElement, ContentProps>(function (
openProp,
onOpenChange,
setVisible,
+ direction,
} = useDrawerContext();
const composedRef = useComposedRefs(ref, drawerRef);
@@ -734,7 +782,7 @@ const Content = React.forwardRef<HTMLDivElement, ContentProps>(function (
onOpenAutoFocus(e);
} else {
e.preventDefault();
- drawerRef.current.focus();
+ drawerRef.current?.focus();
}
}}
onPointerDown={onPress}
@@ -768,6 +816,7 @@ const Content = React.forwardRef<HTMLDivElement, ContentProps>(function (
}
{...rest}
vaul-drawer=""
+ vaul-drawer-direction={direction}
vaul-drawer-visible={visible ? 'true' : 'false'}
/>
);
diff --git a/src/style.css b/src/style.css
index 336ed70..06ab26a 100644
--- a/src/style.css
+++ b/src/style.css
@@ -1,17 +1,55 @@
[vaul-drawer] {
touch-action: none;
- transform: translate3d(0, 100%, 0);
transition: transform 0.5s cubic-bezier(0.32, 0.72, 0, 1);
}
-.vaul-dragging .vaul-scrollable {
+[vaul-drawer][vaul-drawer-direction='bottom'] {
+ transform: translate3d(0, 100%, 0);
+}
+
+[vaul-drawer][vaul-drawer-direction='top'] {
+ transform: translate3d(0, -100%, 0);
+}
+
+[vaul-drawer][vaul-drawer-direction='left'] {
+ transform: translate3d(-100%, 0, 0);
+}
+
+[vaul-drawer][vaul-drawer-direction='right'] {
+ transform: translate3d(100%, 0, 0);
+}
+
+.vaul-dragging .vaul-scrollable [vault-drawer-direction='top'] {
+ overflow-y: hidden !important;
+}
+.vaul-dragging .vaul-scrollable [vault-drawer-direction='bottom'] {
overflow-y: hidden !important;
}
-[vaul-drawer][vaul-drawer-visible='true'] {
+.vaul-dragging .vaul-scrollable [vault-drawer-direction='left'] {
+ overflow-x: hidden !important;
+}
+
+.vaul-dragging .vaul-scrollable [vault-drawer-direction='right'] {
+ overflow-x: hidden !important;
+}
+
+[vaul-drawer][vaul-drawer-visible='true'][vaul-drawer-direction='top'] {
+ transform: translate3d(0, var(--snap-point-height, 0), 0);
+}
+
+[vaul-drawer][vaul-drawer-visible='true'][vaul-drawer-direction='bottom'] {
transform: translate3d(0, var(--snap-point-height, 0), 0);
}
+[vaul-drawer][vaul-drawer-visible='true'][vaul-drawer-direction='left'] {
+ transform: translate3d(var(--snap-point-height, 0), 0, 0);
+}
+
+[vaul-drawer][vaul-drawer-visible='true'][vaul-drawer-direction='right'] {
+ transform: translate3d(var(--snap-point-height, 0), 0, 0);
+}
+
[vaul-overlay] {
opacity: 0;
transition: opacity 0.5s cubic-bezier(0.32, 0.72, 0, 1);
@@ -24,14 +62,42 @@
[vaul-drawer]::after {
content: '';
position: absolute;
- top: 100%;
background: inherit;
background-color: inherit;
+}
+
+[vaul-drawer][vaul-drawer-direction='top']::after {
+ top: initial;
+ bottom: 100%;
+ left: 0;
+ right: 0;
+ height: 200%;
+}
+
+[vaul-drawer][vaul-drawer-direction='bottom']::after {
+ top: 100%;
+ bottom: initial;
left: 0;
right: 0;
height: 200%;
}
+[vaul-drawer][vaul-drawer-direction='left']::after {
+ left: initial;
+ right: 100%;
+ top: 0;
+ bottom: 0;
+ width: 200%;
+}
+
+[vaul-drawer][vaul-drawer-direction='right']::after {
+ left: 100%;
+ right: initial;
+ top: 0;
+ bottom: 0;
+ width: 200%;
+}
+
[vaul-overlay][vaul-snap-points='true']:not([vaul-snap-points-overlay='true']):not([data-state='closed']) {
opacity: 0;
}
diff --git a/src/types.ts b/src/types.ts
index f766331..c30cd68 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -1,3 +1,4 @@
+export type DrawerDirection = 'top' | 'bottom' | 'left' | 'right';
export interface SnapPoint {
fraction: number;
height: number;
diff --git a/src/use-prevent-scroll.ts b/src/use-prevent-scroll.ts
index fc6f69b..d46f2b7 100644
--- a/src/use-prevent-scroll.ts
+++ b/src/use-prevent-scroll.ts
@@ -83,7 +83,7 @@ const nonTextInputTypes = new Set([
// The number of active usePreventScroll calls. Used to determine whether to revert back to the original page style/scroll position
let preventScrollCount = 0;
-let restore;
+let restore: () => void;
/**
* Prevents scrolling on the document body on mount, and
diff --git a/src/use-snap-points.ts b/src/use-snap-points.ts
index 461ab8f..064f45e 100644
--- a/src/use-snap-points.ts
+++ b/src/use-snap-points.ts
@@ -1,7 +1,8 @@
import React from 'react';
-import { set } from './helpers';
+import { set, isVertical } from './helpers';
import { TRANSITIONS, VELOCITY_THRESHOLD } from './constants';
import { useControllableState } from './use-controllable-state';
+import { DrawerDirection } from './types';
export function useSnapPoints({
activeSnapPointProp,
@@ -11,6 +12,7 @@ export function useSnapPoints({
overlayRef,
fadeFromIndex,
onSnapPointChange,
+ direction = 'bottom',
}: {
activeSnapPointProp?: number | string | null;
setActiveSnapPointProp?(snapPoint: number | null | string): void;
@@ -19,6 +21,7 @@ export function useSnapPoints({
drawerRef: React.RefObject<HTMLDivElement>;
overlayRef: React.RefObject<HTMLDivElement>;
onSnapPointChange(activeSnapPointIndex: number): void;
+ direction?: DrawerDirection;
}) {
const [activeSnapPoint, setActiveSnapPoint] = useControllableState<string | number | null>({
prop: activeSnapPointProp,
@@ -55,13 +58,22 @@ export function useSnapPoints({
snapPointAsNumber = parseInt(snapPoint, 10);
}
- const height = isPx ? snapPointAsNumber : hasWindow ? snapPoint * window.innerHeight : 0;
+ if (isVertical(direction)) {
+ const height = isPx ? snapPointAsNumber : hasWindow ? snapPoint * window.innerHeight : 0;
+
+ if (hasWindow) {
+ return direction === 'bottom' ? window.innerHeight - height : -window.innerHeight + height;
+ }
+
+ return height;
+ }
+ const width = isPx ? snapPointAsNumber : hasWindow ? snapPoint * window.innerWidth : 0;
if (hasWindow) {
- return window.innerHeight - height;
+ return direction === 'right' ? window.innerWidth - width : -window.innerWidth + width;
}
- return height;
+ return width;
}) ?? [],
[snapPoints],
);
@@ -72,12 +84,12 @@ export function useSnapPoints({
);
const snapToPoint = React.useCallback(
- (height: number) => {
- const newSnapPointIndex = snapPointsOffset?.findIndex((snapPointHeight) => snapPointHeight === height) ?? null;
+ (dimension: number) => {
+ const newSnapPointIndex = snapPointsOffset?.findIndex((snapPointDim) => snapPointDim === dimension) ?? null;
onSnapPointChange(newSnapPointIndex);
set(drawerRef.current, {
transition: `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
- transform: `translate3d(0, ${height}px, 0)`,
+ transform: isVertical(direction) ? `translate3d(0, ${dimension}px, 0)` : `translate3d(${dimension}px, 0, 0)`,
});
if (
@@ -123,7 +135,10 @@ export function useSnapPoints({
}) {
if (fadeFromIndex === undefined) return;
- const currentPosition = activeSnapPointOffset - draggedDistance;
+ const currentPosition =
+ direction === 'bottom' || direction === 'right'
+ ? activeSnapPointOffset ?? 0 - draggedDistance
+ : activeSnapPointOffset ?? 0 + draggedDistance;
const isOverlaySnapPoint = activeSnapPointIndex === fadeFromIndex - 1;
const isFirst = activeSnapPointIndex === 0;
const hasDraggedUp = draggedDistance > 0;
@@ -152,7 +167,8 @@ export function useSnapPoints({
return Math.abs(curr - currentPosition) < Math.abs(prev - currentPosition) ? curr : prev;
});
- if (velocity > VELOCITY_THRESHOLD && Math.abs(draggedDistance) < window.innerHeight * 0.4) {
+ const dim = isVertical(direction) ? window.innerHeight : window.innerWidth;
+ if (velocity > VELOCITY_THRESHOLD && Math.abs(draggedDistance) < dim * 0.4) {
const dragDirection = hasDraggedUp ? 1 : -1; // 1 = up, -1 = down
// Don't do anything if we swipe upwards while being on the last snap point
@@ -176,13 +192,16 @@ export function useSnapPoints({
function onDrag({ draggedDistance }: { draggedDistance: number }) {
if (activeSnapPointOffset === null) return;
- const newYValue = activeSnapPointOffset - draggedDistance;
+ const newValue =
+ direction === 'bottom' || direction === 'right'
+ ? activeSnapPointOffset - draggedDistance
+ : activeSnapPointOffset + draggedDistance;
// Don't do anything if we exceed the last(highest) snap point
if (newYValue < snapPointsOffset[snapPointsOffset.length - 1]) return;
set(drawerRef.current, {
- transform: `translate3d(0, ${newYValue}px, 0)`,
+ transform: isVertical(direction) ? `translate3d(0, ${newValue}px, 0)` : `translate3d(${newValue}px, 0, 0)`,
});
}
diff --git a/test/src/app/with-scaled-background/page.tsx b/test/src/app/with-scaled-background/page.tsx
index b56e7e2..435e59a 100644
--- a/test/src/app/with-scaled-background/page.tsx
+++ b/test/src/app/with-scaled-background/page.tsx
@@ -1,11 +1,86 @@
'use client';
+import { useState } from 'react';
+import clsx from 'clsx';
import { Drawer } from 'vaul';
+import { DrawerDirection } from 'vaul/src/types';
+
+const CenteredContent = () => {
+ return (
+ <div className="max-w-md mx-auto">
+ <Drawer.Title className="font-medium mb-4">Unstyled drawer for React.</Drawer.Title>
+ <p className="text-zinc-600 mb-2">
+ This component can be used as a replacement for a Dialog on mobile and tablet devices.
+ </p>
+ <p className="text-zinc-600 mb-8">
+ It uses{' '}
+ <a href="https://www.radix-ui.com/docs/primitives/components/dialog" className="underline" target="_blank">
+ Radix&apos;s Dialog primitive
+ </a>{' '}
+ under the hood and is inspired by{' '}
+ <a href="https://twitter.com/devongovett/status/1674470185783402496" className="underline" target="_blank">
+ this tweet.
+ </a>
+ </p>
+ </div>
+ );
+};
+
+const DrawerContent = ({ drawerDirection }: { drawerDirection: DrawerDirection }) => {
+ return (
+ <Drawer.Content
+ data-testid="content"
+ className={clsx({
+ 'bg-zinc-100 flex fixed p-6': true,
+ 'rounded-t-[10px] flex-col h-[50%] bottom-0 left-0 right-0': drawerDirection === 'bottom',
+ 'rounded-b-[10px] flex-col h-[50%] top-0 left-0 right-0': drawerDirection === 'top',
+ 'rounded-r-[10px] flex-row w-[50%] left-0 top-0 bottom-0': drawerDirection === 'left',
+ 'rounded-l-[10px] flex-row w-[50%] right-0 top-0 bottom-0': drawerDirection === 'right',
+ })}
+ >
+ <div
+ className={clsx({
+ 'w-full h-full flex rounded-full gap-8': true,
+ 'flex-col': drawerDirection === 'bottom',
+ 'flex-col-reverse': drawerDirection === 'top',
+ 'flex-row-reverse': drawerDirection === 'left',
+ 'flex-row ': drawerDirection === 'right',
+ })}
+ >
+ <div
+ className={clsx({
+ 'rounded-full bg-zinc-300': true,
+ 'mx-auto w-12 h-1.5': drawerDirection === 'top' || drawerDirection === 'bottom',
+ 'my-auto h-12 w-1.5': drawerDirection === 'left' || drawerDirection === 'right',
+ })}
+ />
+ <div className="grid place-content-center w-full h-full">
+ <CenteredContent />
+ </div>
+ </div>
+ </Drawer.Content>
+ );
+};
export default function Page() {
+ const [direction, setDirection] = useState<DrawerDirection>('bottom');
+
return (
- <div className="w-screen h-screen bg-white p-8 flex justify-center items-center" vaul-drawer-wrapper="">
- <Drawer.Root shouldScaleBackground>
+ <div
+ className="w-screen h-screen bg-white p-8 flex flex-col gap-2 justify-center items-center"
+ vaul-drawer-wrapper=""
+ >
+ <select
+ value={direction}
+ className="border-zinc-300 border-2 px-4 py-1 rounded-lg"
+ onChange={(e) => setDirection(e.target.value as DrawerDirection)}
+ >
+ <option value="top">Top</option>
+ <option value="bottom">Bottom</option>
+ <option value="left">Left</option>
+ <option value="right">Right</option>
+ </select>
+ <Drawer.Root shouldScaleBackground direction={direction}>
<Drawer.Trigger asChild>
<button data-testid="trigger" className="text-2xl">
Open Drawer
@@ -13,88 +88,7 @@ export default function Page() {
</Drawer.Trigger>
<Drawer.Portal>
<Drawer.Overlay data-testid="overlay" className="fixed inset-0 bg-black/40" />
- <Drawer.Content
- data-testid="content"
- className="bg-zinc-100 flex flex-col rounded-t-[10px] h-[96%] mt-24 fixed bottom-0 left-0 right-0"
- >
- <div className="p-4 bg-white rounded-t-[10px] flex-1">
- <div className="mx-auto w-12 h-1.5 flex-shrink-0 rounded-full bg-zinc-300 mb-8" />
- <div className="max-w-md mx-auto">
- <Drawer.Title className="font-medium mb-4">Unstyled drawer for React.</Drawer.Title>
- <p className="text-zinc-600 mb-2">
- This component can be used as a replacement for a Dialog on mobile and tablet devices.
- </p>
- <p className="text-zinc-600 mb-8">
- It uses{' '}
- <a
- href="https://www.radix-ui.com/docs/primitives/components/dialog"
- className="underline"
- target="_blank"
- >
- Radix&apos;s Dialog primitive
- </a>{' '}
- under the hood and is inspired by{' '}
- <a
- href="https://twitter.com/devongovett/status/1674470185783402496"
- className="underline"
- target="_blank"
- >
- this tweet.
- </a>
- </p>
- </div>
- </div>
- <div className="p-4 bg-zinc-100 border-t border-zinc-200 mt-auto">
- <div className="flex gap-6 justify-end max-w-md mx-auto">
- <a
- className="text-xs text-zinc-600 flex items-center gap-0.25"
- href="https://github.com/emilkowalski/vaul"
- target="_blank"
- >
- GitHub
- <svg
- fill="none"
- height="16"
- stroke="currentColor"
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth="2"
- viewBox="0 0 24 24"
- width="16"
- aria-hidden="true"
- className="w-3 h-3 ml-1"
- >
- <path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"></path>
- <path d="M15 3h6v6"></path>
- <path d="M10 14L21 3"></path>
- </svg>
- </a>
- <a
- className="text-xs text-zinc-600 flex items-center gap-0.25"
- href="https://twitter.com/emilkowalski_"
- target="_blank"
- >
- Twitter
- <svg
- fill="none"
- height="16"
- stroke="currentColor"
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth="2"
- viewBox="0 0 24 24"
- width="16"
- aria-hidden="true"
- className="w-3 h-3 ml-1"
- >
- <path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"></path>
- <path d="M15 3h6v6"></path>
- <path d="M10 14L21 3"></path>
- </svg>
- </a>
- </div>
- </div>
- </Drawer.Content>
+ <DrawerContent drawerDirection={direction} />
</Drawer.Portal>
</Drawer.Root>
</div>