Skip to content

armgit / vaul

Public Imported from GitHub
0

A drawer component for React.

feat: drawer handle component (#182)

GSMTe2cfd4df6970
diff --git a/README.md b/README.md
index 7d2cdca..f77ae33 100644
--- a/README.md
+++ b/README.md
@@ -21,6 +21,7 @@ function MyComponent() {
<Drawer.Trigger>Open</Drawer.Trigger>
<Drawer.Portal>
<Drawer.Content>
+ <Drawer.Handle />
<p>Content</p>
</Drawer.Content>
<Drawer.Overlay />
@@ -54,13 +55,15 @@ Additional props:
`closeThreshold`: Number between 0 and 1 that determines when the drawer should be closed. Example: threshold of 0.5 would close the drawer if the user swiped for 50% of the height of the drawer or more.
-`scrollLockTimeout`: Duration for which the drawer is not draggable after scrolling content inside of the drawer. Defaults to 500ms
+`scrollLockTimeout`: Duration for which the drawer is not draggable after scrolling content inside of the drawer. Defaults to 500ms.
`snapPoints`: Array of numbers from 0 to 100 that corresponds to % of the screen a given snap point should take up. Should go from least visible. Example `[0.2, 0.5, 0.8]`. You can also use px values, which doesn't take screen height into account.
`fadeFromIndex`: Index of a `snapPoint` from which the overlay fade should be applied. Defaults to the last snap point.
-`modal`: When `false`it allows to interact with elements outside of the drawer without closing it. Defaults to`true`.
+`modal`: When `false` it allows to interact with elements outside of the drawer without closing it. Defaults to `true`.
+
+`handleOnly`: When `true` only allows the drawer to be dragged by the `<Drawer.Handle />` component. Defaults to `false`.
`direction`: Direction of the drawer. Can be `top` or `bottom`, `left`, `right`. Defaults to `bottom`.
@@ -94,6 +97,10 @@ An optional accessible description to be announced when the dialog is opened. [P
The button that closes the dialog. [Props](https://www.radix-ui.com/docs/primitives/components/dialog#close).
+### Handle
+
+A drag hint (also known as grabber). Shows people that they can drag the drawer to resize it; they can also tap it to cycle through the snap points, and double tap quickly to close the drawer. Set `preventCycle={true}` to stop this behavior. If you want to change the handle's hit area you can do so by styling the `[vaul-handle-hitarea]` selector (Defaults to 44x44 on mobile devices).
+
### Portal
Portals your drawer into the body.
diff --git a/src/context.ts b/src/context.ts
index c4c7743..97e24de 100644
--- a/src/context.ts
+++ b/src/context.ts
@@ -12,7 +12,9 @@ interface DrawerContextValue {
onNestedOpenChange: (o: boolean) => void;
onNestedRelease: (event: React.PointerEvent<HTMLDivElement>, open: boolean) => void;
dismissible: boolean;
+ handleOnly: boolean;
isOpen: boolean;
+ isDragging: boolean;
keyboardIsOpen: React.MutableRefObject<boolean>;
snapPointsOffset: number[] | null;
snapPoints?: (number | string)[] | null;
@@ -40,7 +42,9 @@ export const DrawerContext = React.createContext<DrawerContextValue>({
onNestedRelease: () => {},
openProp: undefined,
dismissible: false,
+ handleOnly: false,
isOpen: false,
+ isDragging: false,
keyboardIsOpen: { current: false },
snapPointsOffset: null,
snapPoints: null,
diff --git a/src/index.tsx b/src/index.tsx
index c53736c..c947aa9 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -45,6 +45,7 @@ type DialogProps = {
scrollLockTimeout?: number;
fixed?: boolean;
dismissible?: boolean;
+ handleOnly?: boolean;
onDrag?: (event: React.PointerEvent<HTMLDivElement>, percentageDragged: number) => void;
onRelease?: (event: React.PointerEvent<HTMLDivElement>, open: boolean) => void;
modal?: boolean;
@@ -67,6 +68,7 @@ function Root({
closeThreshold = CLOSE_THRESHOLD,
scrollLockTimeout = SCROLL_LOCK_TIMEOUT,
dismissible = true,
+ handleOnly = false,
fadeFromIndex = snapPoints && snapPoints.length - 1,
activeSnapPoint: activeSnapPointProp,
setActiveSnapPoint: setActiveSnapPointProp,
@@ -741,7 +743,9 @@ function Root({
onRelease,
onDrag,
dismissible,
+ handleOnly,
isOpen,
+ isDragging,
shouldFade,
closeDrawer,
onNestedDrag,
@@ -760,6 +764,114 @@ function Root({
);
}
+type HandleProps = React.ComponentPropsWithoutRef<'div'> & {
+ preventCycle?: boolean;
+};
+
+const LONG_HANDLE_PRESS_TIMEOUT = 250;
+const DOUBLE_TAP_TIMEOUT = 120;
+
+const Handle = React.forwardRef<HTMLDivElement, HandleProps>(function (
+ { preventCycle = false, children, ...rest },
+ ref,
+) {
+ const {
+ visible,
+ closeDrawer,
+ isDragging,
+ snapPoints,
+ activeSnapPoint,
+ setActiveSnapPoint,
+ dismissible,
+ handleOnly,
+ onPress,
+ onDrag,
+ } = useDrawerContext();
+
+ const closeTimeoutIdRef = React.useRef<number | null>(null);
+ const shouldCancelInteractionRef = React.useRef(false);
+
+ function handleStartCycle() {
+ // Stop if this is the second click of a double click
+ if (shouldCancelInteractionRef.current) {
+ handleCancelInteraction();
+ return;
+ }
+ window.setTimeout(() => {
+ handleCycleSnapPoints();
+ }, DOUBLE_TAP_TIMEOUT);
+ }
+
+ function handleCycleSnapPoints() {
+ // Prevent accidental taps while resizing drawer
+ if (isDragging || preventCycle || shouldCancelInteractionRef.current) {
+ handleCancelInteraction();
+ return;
+ }
+ // Make sure to clear the timeout id if the user releases the handle before the cancel timeout
+ handleCancelInteraction();
+
+ if ((!snapPoints || snapPoints.length === 0) && dismissible) {
+ closeDrawer();
+ return;
+ }
+
+ const isLastSnapPoint = activeSnapPoint === snapPoints[snapPoints.length - 1];
+ if (isLastSnapPoint && dismissible) {
+ closeDrawer();
+ return;
+ }
+
+ const currentSnapIndex = snapPoints.findIndex((point) => point === activeSnapPoint);
+ if (currentSnapIndex === -1) return; // activeSnapPoint not found in snapPoints
+ const nextSnapPoint = snapPoints[currentSnapIndex + 1];
+ setActiveSnapPoint(nextSnapPoint);
+ }
+
+ function handleStartInteraction() {
+ closeTimeoutIdRef.current = window.setTimeout(() => {
+ // Cancel click interaction on a long press
+ shouldCancelInteractionRef.current = true;
+ }, LONG_HANDLE_PRESS_TIMEOUT);
+ }
+
+ function handleCancelInteraction() {
+ window.clearTimeout(closeTimeoutIdRef.current);
+ shouldCancelInteractionRef.current = false;
+ }
+
+ return (
+ <div
+ onClick={handleStartCycle}
+ onDoubleClick={() => {
+ shouldCancelInteractionRef.current = true;
+ closeDrawer();
+ }}
+ onPointerCancel={handleCancelInteraction}
+ onPointerDown={(e) => {
+ if (handleOnly) onPress(e);
+ handleStartInteraction();
+ }}
+ onPointerMove={(e) => {
+ if (handleOnly) onDrag(e);
+ }}
+ // onPointerUp is already handled by the content component
+ ref={ref}
+ vaul-drawer-visible={visible ? 'true' : 'false'}
+ vaul-handle=""
+ aria-hidden="true"
+ {...rest}
+ >
+ {/* Expand handle's hit area beyond what's visible to ensure a 44x44 tap target for touch devices */}
+ <span vaul-handle-hitarea="" aria-hidden="true">
+ {children}
+ </span>
+ </div>
+ );
+});
+
+Handle.displayName = 'Drawer.Handle';
+
const Overlay = React.forwardRef<HTMLDivElement, React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>>(
function ({ children, ...rest }, ref) {
const { overlayRef, snapPoints, onRelease, shouldFade, isOpen, visible } = useDrawerContext();
@@ -804,6 +916,7 @@ const Content = React.forwardRef<HTMLDivElement, ContentProps>(function (
openProp,
onOpenChange,
setVisible,
+ handleOnly,
direction,
} = useDrawerContext();
const composedRef = useComposedRefs(ref, drawerRef);
@@ -863,6 +976,7 @@ const Content = React.forwardRef<HTMLDivElement, ContentProps>(function (
}
}}
onPointerDown={(event) => {
+ if (handleOnly) return;
rest.onPointerDown?.(event);
pointerStartRef.current = { x: event.clientX, y: event.clientY };
onPress(event);
@@ -885,6 +999,7 @@ const Content = React.forwardRef<HTMLDivElement, ContentProps>(function (
closeDrawer();
}}
onPointerMove={(event) => {
+ if (handleOnly) return;
rest.onPointerMove?.(event);
if (!pointerStartRef.current) return;
const yPosition = event.clientY - pointerStartRef.current.y;
@@ -944,6 +1059,7 @@ export const Drawer = {
Root,
NestedRoot,
Content,
+ Handle,
Overlay,
Trigger: DialogPrimitive.Trigger,
Portal: DialogPrimitive.Portal,
diff --git a/src/style.css b/src/style.css
index c0b2970..cbe8717 100644
--- a/src/style.css
+++ b/src/style.css
@@ -98,6 +98,38 @@
width: 200%;
}
+[vaul-handle] {
+ display: block;
+ position: relative;
+ opacity: 0.8;
+ margin-left: auto;
+ margin-right: auto;
+ height: 5px;
+ width: 56px;
+ border-radius: 1rem;
+ touch-action: pan-y;
+ cursor: grab;
+}
+
+[vaul-handle]:hover,
+[vaul-handle]:active {
+ opacity: 1;
+}
+
+[vaul-handle]:active {
+ cursor: grabbing;
+}
+
+[vaul-handle-hitarea] {
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ transform: translate(-50%, -50%);
+ width: max(100%, 2.75rem); /* 44px */
+ height: max(100%, 2.75rem); /* 44px */
+ touch-action: inherit;
+}
+
[vaul-overlay][vaul-snap-points='true']:not([vaul-snap-points-overlay='true']):not([data-state='closed']) {
opacity: 0;
}
@@ -113,3 +145,16 @@
to {
}
}
+
+@media (hover: hover) and (pointer: fine) {
+ [vaul-drawer] {
+ user-select: none;
+ }
+}
+
+@media (pointer: fine) {
+ [vaul-handle-hitarea]: {
+ width: 100%;
+ height: 100%;
+ }
+}
diff --git a/src/use-snap-points.ts b/src/use-snap-points.ts
index 6fe8e26..9e7ca72 100644
--- a/src/use-snap-points.ts
+++ b/src/use-snap-points.ts
@@ -114,13 +114,15 @@ export function useSnapPoints({
);
React.useEffect(() => {
- if (activeSnapPointProp) {
- const newIndex = snapPoints?.findIndex((snapPoint) => snapPoint === activeSnapPointProp) ?? -1;
+ if (activeSnapPoint || activeSnapPointProp) {
+ const newIndex =
+ snapPoints?.findIndex((snapPoint) => snapPoint === activeSnapPointProp || snapPoint === activeSnapPoint) ??
+ -1;
if (snapPointsOffset && newIndex !== -1 && typeof snapPointsOffset[newIndex] === 'number') {
snapToPoint(snapPointsOffset[newIndex] as number);
}
}
- }, [activeSnapPointProp, snapPoints, snapPointsOffset, snapToPoint]);
+ }, [activeSnapPoint, activeSnapPointProp, snapPoints, snapPointsOffset, snapToPoint]);
function onRelease({
draggedDistance,
diff --git a/test/src/app/with-handle/page.tsx b/test/src/app/with-handle/page.tsx
new file mode 100644
index 0000000..09b4979
--- /dev/null
+++ b/test/src/app/with-handle/page.tsx
@@ -0,0 +1,156 @@
+'use client';
+
+import { clsx } from 'clsx';
+import { useState } from 'react';
+import { Drawer } from 'vaul';
+
+const snapPoints = ['148px', '355px'];
+
+export default function Page() {
+ const [snap, setSnap] = useState<number | string | null>(snapPoints[0]);
+
+ const activeSnapPointIndex = snapPoints.indexOf(snap as string);
+
+ return (
+ <div className="w-screen h-screen bg-white p-8 flex justify-center items-center">
+ <div data-testid="active-snap-index">{activeSnapPointIndex}</div>
+ <Drawer.Root open snapPoints={snapPoints} activeSnapPoint={snap} setActiveSnapPoint={setSnap}>
+ <Drawer.Trigger asChild>
+ <button data-testid="trigger">Open Drawer</button>
+ </Drawer.Trigger>
+ <Drawer.Overlay className="fixed inset-0 bg-black/40" />
+ <Drawer.Portal>
+ <Drawer.Content
+ data-testid="content"
+ className="fixed flex flex-col bg-white border border-gray-200 border-b-none rounded-t-[10px] bottom-0 left-0 right-0 h-full max-h-[97%] mx-[-1px]"
+ >
+ <Drawer.Handle data-testid="handle" className="bg-gray-300 mb-8" />
+ <div
+ className={clsx('flex flex-col max-w-md mx-auto w-full p-4 pt-5', {
+ 'overflow-y-auto': snap === 1,
+ 'overflow-hidden': snap !== 1,
+ })}
+ >
+ <div className="flex items-center">
+ <svg
+ className="text-yellow-400 h-5 w-5 flex-shrink-0"
+ viewBox="0 0 20 20"
+ fill="currentColor"
+ aria-hidden="true"
+ >
+ <path
+ fill-rule="evenodd"
+ d="M10.868 2.884c-.321-.772-1.415-.772-1.736 0l-1.83 4.401-4.753.381c-.833.067-1.171 1.107-.536 1.651l3.62 3.102-1.106 4.637c-.194.813.691 1.456 1.405 1.02L10 15.591l4.069 2.485c.713.436 1.598-.207 1.404-1.02l-1.106-4.637 3.62-3.102c.635-.544.297-1.584-.536-1.65l-4.752-.382-1.831-4.401z"
+ clip-rule="evenodd"
+ ></path>
+ </svg>
+ <svg
+ className="text-yellow-400 h-5 w-5 flex-shrink-0"
+ viewBox="0 0 20 20"
+ fill="currentColor"
+ aria-hidden="true"
+ >
+ <path
+ fill-rule="evenodd"
+ d="M10.868 2.884c-.321-.772-1.415-.772-1.736 0l-1.83 4.401-4.753.381c-.833.067-1.171 1.107-.536 1.651l3.62 3.102-1.106 4.637c-.194.813.691 1.456 1.405 1.02L10 15.591l4.069 2.485c.713.436 1.598-.207 1.404-1.02l-1.106-4.637 3.62-3.102c.635-.544.297-1.584-.536-1.65l-4.752-.382-1.831-4.401z"
+ clip-rule="evenodd"
+ ></path>
+ </svg>
+ <svg
+ className="text-yellow-400 h-5 w-5 flex-shrink-0"
+ viewBox="0 0 20 20"
+ fill="currentColor"
+ aria-hidden="true"
+ >
+ <path
+ fill-rule="evenodd"
+ d="M10.868 2.884c-.321-.772-1.415-.772-1.736 0l-1.83 4.401-4.753.381c-.833.067-1.171 1.107-.536 1.651l3.62 3.102-1.106 4.637c-.194.813.691 1.456 1.405 1.02L10 15.591l4.069 2.485c.713.436 1.598-.207 1.404-1.02l-1.106-4.637 3.62-3.102c.635-.544.297-1.584-.536-1.65l-4.752-.382-1.831-4.401z"
+ clip-rule="evenodd"
+ ></path>
+ </svg>
+ <svg
+ className="text-yellow-400 h-5 w-5 flex-shrink-0"
+ viewBox="0 0 20 20"
+ fill="currentColor"
+ aria-hidden="true"
+ >
+ <path
+ fill-rule="evenodd"
+ d="M10.868 2.884c-.321-.772-1.415-.772-1.736 0l-1.83 4.401-4.753.381c-.833.067-1.171 1.107-.536 1.651l3.62 3.102-1.106 4.637c-.194.813.691 1.456 1.405 1.02L10 15.591l4.069 2.485c.713.436 1.598-.207 1.404-1.02l-1.106-4.637 3.62-3.102c.635-.544.297-1.584-.536-1.65l-4.752-.382-1.831-4.401z"
+ clip-rule="evenodd"
+ ></path>
+ </svg>
+ <svg
+ className="text-gray-300 h-5 w-5 flex-shrink-0"
+ viewBox="0 0 20 20"
+ fill="currentColor"
+ aria-hidden="true"
+ >
+ <path
+ fill-rule="evenodd"
+ d="M10.868 2.884c-.321-.772-1.415-.772-1.736 0l-1.83 4.401-4.753.381c-.833.067-1.171 1.107-.536 1.651l3.62 3.102-1.106 4.637c-.194.813.691 1.456 1.405 1.02L10 15.591l4.069 2.485c.713.436 1.598-.207 1.404-1.02l-1.106-4.637 3.62-3.102c.635-.544.297-1.584-.536-1.65l-4.752-.382-1.831-4.401z"
+ clip-rule="evenodd"
+ ></path>
+ </svg>
+ </div>{' '}
+ <h1 className="text-2xl mt-2 font-medium">The Hidden Details</h1>
+ <p className="text-sm mt-1 text-gray-600 mb-6">2 modules, 27 hours of video</p>
+ <p className="text-gray-600">
+ The world of user interface design is an intricate landscape filled with hidden details and nuance. In
+ this course, you will learn something cool. To the untrained eye, a beautifully designed UI.
+ </p>
+ <button className="bg-black text-gray-50 mt-8 rounded-md h-[48px] flex-shrink-0 font-medium">
+ Buy for $199
+ </button>
+ <div className="mt-12">
+ <h2 className="text-xl font-medium">Module 01. The Details</h2>
+ <div className="space-y-4 mt-4">
+ <div>
+ <span className="block">Layers of UI</span>
+ <span className="text-gray-600">A basic introduction to Layers of Design.</span>
+ </div>
+ <div>
+ <span className="block">Typography</span>
+ <span className="text-gray-600">The fundamentals of type.</span>
+ </div>
+ <div>
+ <span className="block">UI Animations</span>
+ <span className="text-gray-600">Going through the right easings and durations.</span>
+ </div>
+ </div>
+ </div>
+ <div className="mt-12">
+ <figure>
+ <blockquote className="font-serif">
+ “I especially loved the hidden details video. That was so useful, learned a lot by just reading it.
+ Can&rsquo;t wait for more course content!”
+ </blockquote>
+ <figcaption>
+ <span className="text-sm text-gray-600 mt-2 block">Yvonne Ray, Frontend Developer</span>
+ </figcaption>
+ </figure>
+ </div>
+ <div className="mt-12">
+ <h2 className="text-xl font-medium">Module 02. The Process</h2>
+ <div className="space-y-4 mt-4">
+ <div>
+ <span className="block">Build</span>
+ <span className="text-gray-600">Create cool components to practice.</span>
+ </div>
+ <div>
+ <span className="block">User Insight</span>
+ <span className="text-gray-600">Find out what users think and fine-tune.</span>
+ </div>
+ <div>
+ <span className="block">Putting it all together</span>
+ <span className="text-gray-600">Let&apos;s build an app together and apply everything.</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </Drawer.Content>
+ </Drawer.Portal>
+ </Drawer.Root>
+ </div>
+ );
+}
diff --git a/test/tests/with-handle.spec.ts b/test/tests/with-handle.spec.ts
new file mode 100644
index 0000000..1104ada
--- /dev/null
+++ b/test/tests/with-handle.spec.ts
@@ -0,0 +1,32 @@
+import { test, expect } from '@playwright/test';
+import { ANIMATION_DURATION } from './constants';
+
+test.beforeEach(async ({ page }) => {
+ await page.goto('/with-handle');
+});
+
+test.describe('With handle', () => {
+ test('click should cycle to the next snap point', async ({ page }) => {
+ await page.waitForTimeout(ANIMATION_DURATION);
+
+ await expect(page.getByTestId('content')).toBeVisible();
+ await expect(page.getByTestId('active-snap-index')).toHaveText('0');
+
+ await page.getByTestId('handle').click();
+ await expect(page.getByTestId('active-snap-index')).toHaveText('1');
+
+ await page.getByTestId('handle').click();
+ await expect(page.getByTestId('content')).not.toBeVisible();
+ });
+
+ test('double click should close the drawer', async ({ page }) => {
+ await page.waitForTimeout(ANIMATION_DURATION);
+
+ await expect(page.getByTestId('content')).toBeVisible();
+ await expect(page.getByTestId('active-snap-index')).toHaveText('0');
+ await page.getByTestId('handle').dispatchEvent("dblclick");
+
+ await page.waitForTimeout(ANIMATION_DURATION);
+ await expect(page.getByTestId('content')).not.toBeVisible();
+ });
+});
diff --git a/website/src/app/components/hero.tsx b/website/src/app/components/hero.tsx
index 7bf02f4..c2dc262 100644
--- a/website/src/app/components/hero.tsx
+++ b/website/src/app/components/hero.tsx
@@ -53,7 +53,7 @@ export function Hero() {
<Drawer.Overlay className="fixed inset-0 bg-black/40" />
<Drawer.Content className="bg-gray-100 flex flex-col rounded-t-[10px] h-full mt-24 max-h-[96%] 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-gray-300 mb-8" />
+ <Drawer.Handle className="bg-gray-300 mb-8" />
<div className="max-w-md mx-auto">
<Drawer.Title className="font-medium mb-4">Drawer for React.</Drawer.Title>
<p className="text-gray-600 mb-2">