A drawer component for React.
feat: support parent container (#413)
Emil Kowalski11fbb7e79bcf
diff --git a/README.md b/README.mdindex f8eb899..830d9b7 100644--- a/README.md+++ b/README.md@@ -88,6 +88,33 @@ const [open, setOpen] = React.useState(false);</Drawer.Root>```+### Custom Container++Customize the element that your drawer portals into. By default, drawer will be appended to `document.body`.++```tsx+import React from 'react';+import { Drawer } from 'vaul';++export default () => {+ const [container, setContainer] = React.useState(null);++ return (+ <div>+ <Drawer.Root container={container}>+ <Drawer.Trigger />+ <Drawer.Portal>+ <Drawer.Overlay />+ <Drawer.Content>...</Drawer.Content>+ </Drawer.Portal>+ </Drawer.Root>+ // Drawer will be rendered inside this div.+ <div ref={setContainer} />+ </div>+ );+};+```+### TriggerThe button that opens the dialog. [Props](https://www.radix-ui.com/docs/primitives/components/dialog#trigger).diff --git a/src/context.ts b/src/context.tsindex f1b0d9a..4718739 100644--- a/src/context.ts+++ b/src/context.ts@@ -27,6 +27,7 @@ interface DrawerContextValue {shouldScaleBackground: boolean;setBackgroundColorOnScale: boolean;noBodyStyles: boolean;+ container?: HTMLElement | null;}export const DrawerContext = React.createContext<DrawerContextValue>({@@ -55,6 +56,7 @@ export const DrawerContext = React.createContext<DrawerContextValue>({shouldScaleBackground: false,setBackgroundColorOnScale: true,noBodyStyles: false,+ container: null,});export const useDrawerContext = () => {diff --git a/src/index.tsx b/src/index.tsxindex 68c35dc..bcfc556 100644--- a/src/index.tsx+++ b/src/index.tsx@@ -1,13 +1,13 @@'use client';import * as DialogPrimitive from '@radix-ui/react-dialog';-import React, { useEffect } from 'react';+import React from 'react';import { DrawerContext, useDrawerContext } from './context';import './style.css';import { usePreventScroll, isInput, isIOS } from './use-prevent-scroll';import { useComposedRefs } from './use-composed-refs';import { useSnapPoints } from './use-snap-points';-import { set, reset, getTranslate, dampenValue, isVertical } from './helpers';+import { set, getTranslate, dampenValue, isVertical } from './helpers';import {TRANSITIONS,VELOCITY_THRESHOLD,@@ -53,6 +53,7 @@ export type DialogProps = {direction?: 'top' | 'bottom' | 'left' | 'right';defaultOpen?: boolean;repositionInputs?: boolean;+ container?: HTMLElement | null;} & (WithFadeFromProps | WithoutFadeFromProps);export function Root({@@ -77,6 +78,7 @@ export function Root({direction = 'bottom',defaultOpen = false,repositionInputs = true,+ container,}: DialogProps) {const [isOpen = false, setIsOpen] = useControllableState({defaultProp: defaultOpen,@@ -123,6 +125,7 @@ export function Root({overlayRef,onSnapPointChange,direction,+ container,});usePreventScroll({@@ -136,6 +139,7 @@ export function Root({function onPress(event: React.PointerEvent<HTMLDivElement>) {if (!dismissible && !snapPoints) return;if (drawerRef.current && !drawerRef.current.contains(event.target as Node)) return;+drawerHeightRef.current = drawerRef.current?.getBoundingClientRect().height || 0;setIsDragging(true);dragStartTime.current = new Date();@@ -181,11 +185,7 @@ export function Root({}// Disallow dragging if drawer was scrolled within `scrollLockTimeout`- if (- lastTimeDragPrevented.current &&- date.getTime() - lastTimeDragPrevented.current.getTime() < scrollLockTimeout &&- swipeAmount === 0- ) {+ if (date.getTime() - lastTimeDragPrevented.current?.getTime() < scrollLockTimeout && swipeAmount === 0) {lastTimeDragPrevented.current = date;return false;}@@ -225,6 +225,7 @@ export function Root({if (!drawerRef.current) {return;}+// We need to know how much of the drawer has been dragged in percentages so that we can transform background accordinglyif (isDragging) {const directionMultiplier = direction === 'bottom' || direction === 'right' ? 1 : -1;@@ -632,6 +633,7 @@ export function Root({shouldScaleBackground,setBackgroundColorOnScale,noBodyStyles,+ container,}}>{children}@@ -666,7 +668,7 @@ export type ContentProps = React.ComponentPropsWithoutRef<typeof DialogPrimitive};export const Content = React.forwardRef<HTMLDivElement, ContentProps>(function (- { onOpenAutoFocus, onPointerDownOutside, onAnimationEnd, style, ...rest },+ { onPointerDownOutside, onAnimationEnd, style, ...rest },ref,) {const {@@ -680,6 +682,7 @@ export const Content = React.forwardRef<HTMLDivElement, ContentProps>(function (isOpen,direction,snapPoints,+ container,} = useDrawerContext();// Needed to use transition instead of animationsconst [delayedSnapPoints, setDelayedSnapPoints] = React.useState(false);@@ -713,7 +716,7 @@ export const Content = React.forwardRef<HTMLDivElement, ContentProps>(function (return true;};- useEffect(() => {+ React.useEffect(() => {if (hasSnapPoints) {window.requestAnimationFrame(() => {setDelayedSnapPoints(true);@@ -727,6 +730,7 @@ export const Content = React.forwardRef<HTMLDivElement, ContentProps>(function (data-vaul-drawer=""data-vaul-delayed-snap-points={delayedSnapPoints ? 'true' : 'false'}data-vaul-snap-points={isOpen && hasSnapPoints ? 'true' : 'false'}+ data-vaul-custom-container={container ? 'true' : 'false'}{...rest}ref={composedRef}style={@@ -737,14 +741,6 @@ export const Content = React.forwardRef<HTMLDivElement, ContentProps>(function (} as React.CSSProperties): style}- onOpenAutoFocus={(e) => {- if (onOpenAutoFocus) {- onOpenAutoFocus(e);- } else {- e.preventDefault();- drawerRef.current?.focus();- }- }}onPointerDown={(event) => {rest.onPointerDown?.(event);pointerStartRef.current = { x: event.clientX, y: event.clientY };@@ -830,13 +826,22 @@ export function NestedRoot({ onDrag, onOpenChange, ...rest }: DialogProps) {);}+type PortalProps = React.ComponentPropsWithoutRef<typeof DialogPrimitive.Portal>;++export function Portal(props: PortalProps) {+ const context = useDrawerContext();+ const { container = context.container, ...portalProps } = props;++ return <DialogPrimitive.Portal container={container} {...portalProps} />;+}+export const Drawer = {Root,NestedRoot,Content,Overlay,Trigger: DialogPrimitive.Trigger,- Portal: DialogPrimitive.Portal,+ Portal,Close: DialogPrimitive.Close,Title: DialogPrimitive.Title,Description: DialogPrimitive.Description,diff --git a/src/style.css b/src/style.cssindex dbae8a0..50b1cab 100644--- a/src/style.css+++ b/src/style.css@@ -101,7 +101,7 @@opacity: 1;}-[data-vaul-drawer]::after {+[data-vaul-drawer]:not([data-vaul-custom-container='true'])::after {content: '';position: absolute;background: inherit;diff --git a/src/use-snap-points.ts b/src/use-snap-points.tsindex dbaab31..adb868c 100644--- a/src/use-snap-points.ts+++ b/src/use-snap-points.ts@@ -13,6 +13,7 @@ export function useSnapPoints({fadeFromIndex,onSnapPointChange,direction = 'bottom',+ container,}: {activeSnapPointProp?: number | string | null;setActiveSnapPointProp?(snapPoint: number | null | string): void;@@ -22,6 +23,7 @@ export function useSnapPoints({overlayRef: React.RefObject<HTMLDivElement>;onSnapPointChange(activeSnapPointIndex: number): void;direction?: DrawerDirection;+ container?: HTMLElement | null | undefined;}) {const [activeSnapPoint, setActiveSnapPoint] = useControllableState<string | number | null>({prop: activeSnapPointProp,@@ -68,8 +70,14 @@ export function useSnapPoints({[snapPoints, activeSnapPoint],);- const snapPointsOffset = React.useMemo(- () =>+ const snapPointsOffset = React.useMemo(() => {+ const containerSize = container+ ? { width: container.getBoundingClientRect().width, height: container.getBoundingClientRect().height }+ : typeof window !== 'undefined'+ ? { width: window.innerWidth, height: window.innerHeight }+ : { width: 0, height: 0 };++ return (snapPoints?.map((snapPoint) => {const isPx = typeof snapPoint === 'string';let snapPointAsNumber = 0;@@ -79,26 +87,24 @@ export function useSnapPoints({}if (isVertical(direction)) {- const height = isPx ? snapPointAsNumber : windowDimensions ? snapPoint * windowDimensions.innerHeight : 0;+ const height = isPx ? snapPointAsNumber : windowDimensions ? snapPoint * containerSize.height : 0;if (windowDimensions) {- return direction === 'bottom'- ? windowDimensions.innerHeight - height- : -windowDimensions.innerHeight + height;+ return direction === 'bottom' ? containerSize.height - height : -containerSize.height + height;}return height;}- const width = isPx ? snapPointAsNumber : windowDimensions ? snapPoint * windowDimensions.innerWidth : 0;+ const width = isPx ? snapPointAsNumber : windowDimensions ? snapPoint * containerSize.width : 0;if (windowDimensions) {- return direction === 'right' ? windowDimensions.innerWidth - width : -windowDimensions.innerWidth + width;+ return direction === 'right' ? containerSize.width - width : -containerSize.width + width;}return width;- }) ?? [],- [snapPoints, windowDimensions],- );+ }) ?? []+ );+ }, [snapPoints, windowDimensions, container]);const activeSnapPointOffset = React.useMemo(() => (activeSnapPointIndex !== null ? snapPointsOffset?.[activeSnapPointIndex] : null),diff --git a/test/src/app/globals.css b/test/src/app/globals.cssindex aa83206..a94fb7c 100644--- a/test/src/app/globals.css+++ b/test/src/app/globals.css@@ -4,7 +4,7 @@body,main {- min-height: 500vh;+ /* min-height: 500vh; */}html {diff --git a/test/src/app/parent-container/page.tsx b/test/src/app/parent-container/page.tsxnew file mode 100644index 0000000..40bc8fa--- /dev/null+++ b/test/src/app/parent-container/page.tsx@@ -0,0 +1,70 @@+'use client';+import clsx from 'clsx';+import { useState } from 'react';+import { Drawer } from 'vaul';++export default function Page() {+ return (+ <div className="h-screen flex flex-col gap-20 overflow-auto py-20">+ <Default />+ <WithNested />+ </div>+ );+}++function Default() {+ const [parent, setParent] = useState<HTMLDivElement | null>(null);++ return (+ <div className="flex flex-col items-center gap-10">+ <h1 className="text-3xl font-semibold">Default</h1>+ <div+ ref={setParent}+ className="bg-zinc-200 w-[440px] h-[400px] rounded-lg relative flex justify-center items-center overflow-hidden"+ >+ <Drawer.Root container={parent}>+ <Drawer.Trigger>Open Drawer</Drawer.Trigger>+ <Drawer.Portal>+ <Drawer.Overlay className="absolute inset-0 bg-black/40" />+ <Drawer.Content className="absolute bg-zinc-100 inset-x-0 rounded-t-[10px] bottom-0 h-[56%] p-6">+ <Drawer.Title>Unstyled drawer for React.</Drawer.Title>+ </Drawer.Content>+ </Drawer.Portal>+ </Drawer.Root>+ </div>+ </div>+ );+}++function WithNested() {+ const [parent, setParent] = useState<HTMLDivElement | null>(null);++ return (+ <div className="flex flex-col items-center gap-10">+ <h1 className="text-3xl font-semibold">With Nested</h1>+ <div+ ref={setParent}+ className="bg-zinc-200 w-[440px] h-[400px] rounded-lg relative flex justify-center items-center overflow-hidden"+ >+ <Drawer.Root>+ <Drawer.Trigger>Open Drawer</Drawer.Trigger>+ <Drawer.Portal container={parent}>+ <Drawer.Overlay className="absolute inset-0 bg-black/40" />+ <Drawer.Content className="absolute bg-zinc-100 inset-x-0 rounded-t-[10px] bottom-0 h-[56%] p-6">+ <Drawer.Title>Unstyled drawer for React.</Drawer.Title>+ <Drawer.NestedRoot container={parent}>+ <Drawer.Trigger>Open nested drawer</Drawer.Trigger>+ <Drawer.Portal>+ <Drawer.Overlay className="absolute inset-0 bg-black/40" />+ <Drawer.Content className="absolute bg-zinc-100 inset-x-0 rounded-t-[10px] bottom-0 h-[56%] p-6">+ <Drawer.Title>Unstyled drawer for React.</Drawer.Title>+ </Drawer.Content>+ </Drawer.Portal>+ </Drawer.NestedRoot>+ </Drawer.Content>+ </Drawer.Portal>+ </Drawer.Root>+ </div>+ </div>+ );+}diff --git a/test/src/app/without-scaled-background/page.tsx b/test/src/app/without-scaled-background/page.tsxindex 21610f7..10f16ef 100644--- a/test/src/app/without-scaled-background/page.tsx+++ b/test/src/app/without-scaled-background/page.tsx@@ -5,9 +5,12 @@ import { Drawer } from 'vaul';export default function Page() {const [open, setOpen] = useState(false);+ const [parent, setParent] = useState<HTMLDivElement | null>(null);+return (<div className="w-screen h-screen bg-white p-8 flex justify-center items-center" data-vaul-drawer-wrapper="">- <Drawer.Root open={open} onOpenChange={setOpen}>+ <div className="w-[50vw] h-[50vh] relative" ref={setParent} />+ <Drawer.Root open={open} onOpenChange={setOpen} container={parent}><Drawer.Trigger asChild><button data-testid="trigger" className="text-2xl">Open Drawerdiff --git a/website/src/app/components/hero.tsx b/website/src/app/components/hero.tsxindex 239b63e..59298e9 100644--- a/website/src/app/components/hero.tsx+++ b/website/src/app/components/hero.tsx@@ -52,7 +52,7 @@ export function Hero() {</Drawer.Trigger><Drawer.Portal><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">+ <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 outline-none"><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" /><div className="max-w-md mx-auto">