A drawer component for React.
Add usePositionFixed hook (#436)
Emil Kowalskif246d9ea5271
diff --git a/src/index.tsx b/src/index.tsxindex 72af83a..14277d1 100644--- a/src/index.tsx+++ b/src/index.tsx@@ -21,6 +21,7 @@ import {import { DrawerDirection } from './types';import { useControllableState } from './use-controllable-state';import { useScaleBackground } from './use-scale-background';+import { usePositionFixed } from './use-position-fixed';export interface WithFadeFromProps {snapPoints: (number | string)[];@@ -58,6 +59,7 @@ export type DialogProps = {snapToSequentialPoint?: boolean;container?: HTMLElement | null;onAnimationEnd?: (open: boolean) => void;+ preventScrollRestoration?: boolean;} & (WithFadeFromProps | WithoutFadeFromProps);export function Root({@@ -79,11 +81,13 @@ export function Root({fixed,modal = true,onClose,+ nested,noBodyStyles,direction = 'bottom',defaultOpen = false,disablePreventScroll = true,snapToSequentialPoint = false,+ preventScrollRestoration = false,repositionInputs = true,onAnimationEnd,container,@@ -94,6 +98,10 @@ export function Root({onChange: (o: boolean) => {onOpenChange?.(o);+ if (!o) {+ restorePositionSetting();+ }+setTimeout(() => {onAnimationEnd?.(o);}, TRANSITIONS.DURATION * 1000);@@ -154,6 +162,15 @@ export function Root({!isOpen || isDragging || !modal || justReleased || !hasBeenOpened || !repositionInputs || !disablePreventScroll,});+ const { restorePositionSetting } = usePositionFixed({+ isOpen,+ modal,+ nested,+ hasBeenOpened,+ preventScrollRestoration,+ noBodyStyles,+ });+function getScale() {return (window.innerWidth - WINDOW_TOP_OFFSET) / window.innerWidth;}@@ -173,7 +190,7 @@ export function Root({// Ensure we maintain correct pointer capture even when going outside of the drawer(event.target as HTMLElement).setPointerCapture(event.pointerId);- pointerStart.current = isVertical(direction) ? event.clientY : event.clientX;+ pointerStart.current = isVertical(direction) ? event.pageY : event.pageX;}function shouldDrag(el: EventTarget, isDraggingInDirection: boolean) {@@ -212,12 +229,12 @@ export function Root({return false;}- if (isDraggingInDirection) {- lastTimeDragPrevented.current = date;+ // if (isDraggingInDirection) {+ // lastTimeDragPrevented.current = date;- // We are dragging down so we should allow scrolling- return false;- }+ // // We are dragging down so we should allow scrolling+ // return false;+ // }// Keep climbing up the DOM tree as long as there's a parentwhile (element) {@@ -252,7 +269,7 @@ export function Root({if (isDragging) {const directionMultiplier = direction === 'bottom' || direction === 'right' ? 1 : -1;const draggedDistance =- (pointerStart.current - (isVertical(direction) ? event.clientY : event.clientX)) * directionMultiplier;+ (pointerStart.current - (isVertical(direction) ? event.pageY : event.pageX)) * directionMultiplier;const isDraggingInDirection = draggedDistance > 0;// Pre condition for disallowing dragging in the close direction.@@ -489,7 +506,7 @@ export function Root({if (dragStartTime.current === null) return;const timeTaken = dragEndTime.current.getTime() - dragStartTime.current.getTime();- const distMoved = pointerStart.current - (isVertical(direction) ? event.clientY : event.clientX);+ const distMoved = pointerStart.current - (isVertical(direction) ? event.pageY : event.pageX);const velocity = Math.abs(distMoved) / timeTaken;if (velocity > 0.05) {@@ -765,7 +782,7 @@ export const Content = React.forwardRef<HTMLDivElement, ContentProps>(function (onPointerDown={(event) => {if (handleOnly) return;rest.onPointerDown?.(event);- pointerStartRef.current = { x: event.clientX, y: event.clientY };+ pointerStartRef.current = { x: event.pageX, y: event.pageY };onPress(event);}}onPointerDownOutside={(e) => {@@ -790,8 +807,8 @@ export const Content = React.forwardRef<HTMLDivElement, ContentProps>(function (if (handleOnly) return;rest.onPointerMove?.(event);if (!pointerStartRef.current) return;- const yPosition = event.clientY - pointerStartRef.current.y;- const xPosition = event.clientX - pointerStartRef.current.x;+ const yPosition = event.pageY - pointerStartRef.current.y;+ const xPosition = event.pageX - pointerStartRef.current.x;const swipeStartThreshold = event.pointerType === 'touch' ? 10 : 2;const delta = { x: xPosition, y: yPosition };@@ -867,7 +884,7 @@ export const Handle = React.forwardRef<HTMLDivElement, HandleProps>(function (}const isLastSnapPoint = activeSnapPoint === snapPoints[snapPoints.length - 1];-+if (isLastSnapPoint && dismissible) {closeDrawer();return;diff --git a/src/use-position-fixed.ts b/src/use-position-fixed.tsnew file mode 100644index 0000000..4a6efc2--- /dev/null+++ b/src/use-position-fixed.ts@@ -0,0 +1,131 @@+import React from 'react';+import { isSafari } from './use-prevent-scroll';++let previousBodyPosition: Record<string, string> | null = null;++/**+ * This hook is necessary to prevent buggy behavior on iOS devices (need to test on Android).+ * I won't get into too much detail about what bugs it solves, but so far I've found that setting the body to `position: fixed` is the most reliable way to prevent those bugs.+ * Issues that this hook solves:+ * https://github.com/emilkowalski/vaul/issues/435+ * https://github.com/emilkowalski/vaul/issues/433+ * And more that I discovered, but were just not reported.+ */++export function usePositionFixed({+ isOpen,+ modal,+ nested,+ hasBeenOpened,+ preventScrollRestoration,+ noBodyStyles,+}: {+ isOpen: boolean;+ modal: boolean;+ nested: boolean;+ hasBeenOpened: boolean;+ preventScrollRestoration: boolean;+ noBodyStyles: boolean;+}) {+ const [activeUrl, setActiveUrl] = React.useState(() => (typeof window !== 'undefined' ? window.location.href : ''));+ const scrollPos = React.useRef(0);++ const setPositionFixed = React.useCallback(() => {+ // All browsers on iOS will return true here.+ if (!isSafari()) return;++ // If previousBodyPosition is already set, don't set it again.+ if (previousBodyPosition === null && isOpen && !noBodyStyles) {+ previousBodyPosition = {+ position: document.body.style.position,+ top: document.body.style.top,+ left: document.body.style.left,+ height: document.body.style.height,+ right: 'unset',+ };++ // Update the dom inside an animation frame+ const { scrollX, innerHeight } = window;++ document.body.style.setProperty('position', 'fixed', 'important');+ Object.assign(document.body.style, {+ top: `${-scrollPos.current}px`,+ left: `${-scrollX}px`,+ right: '0px',+ height: 'auto',+ });++ window.setTimeout(+ () =>+ window.requestAnimationFrame(() => {+ // Attempt to check if the bottom bar appeared due to the position change+ const bottomBarHeight = innerHeight - window.innerHeight;+ if (bottomBarHeight && scrollPos.current >= innerHeight) {+ // Move the content further up so that the bottom bar doesn't hide it+ document.body.style.top = `${-(scrollPos.current + bottomBarHeight)}px`;+ }+ }),+ 300,+ );+ }+ }, [isOpen]);++ const restorePositionSetting = React.useCallback(() => {+ // All browsers on iOS will return true here.+ if (!isSafari()) return;++ if (previousBodyPosition !== null && !noBodyStyles) {+ // Convert the position from "px" to Int+ const y = -parseInt(document.body.style.top, 10);+ const x = -parseInt(document.body.style.left, 10);++ // Restore styles+ Object.assign(document.body.style, previousBodyPosition);++ window.requestAnimationFrame(() => {+ if (preventScrollRestoration && activeUrl !== window.location.href) {+ setActiveUrl(window.location.href);+ return;+ }++ window.scrollTo(x, y);+ });++ previousBodyPosition = null;+ }+ }, [activeUrl]);++ React.useEffect(() => {+ function onScroll() {+ scrollPos.current = window.scrollY;+ }++ onScroll();++ window.addEventListener('scroll', onScroll);++ return () => {+ window.removeEventListener('scroll', onScroll);+ };+ }, []);++ React.useEffect(() => {+ if (nested || !hasBeenOpened) return;+ // This is needed to force Safari toolbar to show **before** the drawer starts animating to prevent a gnarly shift from happening+ if (isOpen) {+ // avoid for standalone mode (PWA)+ const isStandalone = window.matchMedia('(display-mode: standalone)').matches;+ !isStandalone && setPositionFixed();++ if (!modal) {+ window.setTimeout(() => {+ restorePositionSetting();+ }, 500);+ }+ } else {+ restorePositionSetting();+ }+ }, [isOpen, hasBeenOpened, activeUrl, modal, nested, setPositionFixed, restorePositionSetting]);++ return { restorePositionSetting };+}diff --git a/src/use-scale-background.ts b/src/use-scale-background.tsindex 502de9c..8529088 100644--- a/src/use-scale-background.ts+++ b/src/use-scale-background.ts@@ -23,7 +23,7 @@ export function useScaleBackground() {if (!wrapper) return;- const bodyAndWrapperCleanup = chain(+ chain(setBackgroundColorOnScale && !noBodyStyles ? assignStyle(document.body, { background: 'black' }) : noop,assignStyle(wrapper, {transformOrigin: isVertical(direction) ? 'top' : 'left',@@ -48,8 +48,6 @@ export function useScaleBackground() {return () => {wrapperStylesCleanup();timeoutIdRef.current = window.setTimeout(() => {- bodyAndWrapperCleanup();-if (initialBackgroundColor) {document.body.style.background = initialBackgroundColor;} else {diff --git a/test/src/app/globals.css b/test/src/app/globals.cssindex a94fb7c..aa83206 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/open-another-drawer/page.tsx b/test/src/app/open-another-drawer/page.tsxnew file mode 100644index 0000000..3cd4c60--- /dev/null+++ b/test/src/app/open-another-drawer/page.tsx@@ -0,0 +1,207 @@+'use client';++import { Drawer } from 'vaul';+import { useState } from 'react';++export function MyDrawer({+ open,+ setOpen,+ setOpen2,+}: {+ open: boolean;+ setOpen: (open: boolean) => void;+ setOpen2: (open: boolean) => void;+}) {+ return (+ <Drawer.Root open={open}>+ <Drawer.Trigger asChild onClick={() => setOpen(true)}>+ <button>Open Drawer</button>+ </Drawer.Trigger>+ <Drawer.Portal>+ <Drawer.Overlay className="fixed inset-0 bg-black/40" />+ <Drawer.Content className="bg-zinc-100 flex flex-col rounded-t-[10px] 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>++ <button+ type="button"+ onClick={() => {+ setOpen2(true);+ setOpen(false);+ }}+ className="rounded-md mb-6 w-full bg-gray-900 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-gray-800 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-600"+ >+ Open new drawer and close this+ </button>+ </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"+ stroke-linecap="round"+ stroke-linejoin="round"+ stroke-width="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"+ >+ <svg+ fill="none"+ height="16"+ stroke="currentColor"+ stroke-linecap="round"+ stroke-linejoin="round"+ stroke-width="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>+ </Drawer.Portal>+ </Drawer.Root>+ );+}++export function MyDrawer2({ open, setOpen }: { open: boolean; setOpen: (open: boolean) => void }) {+ return (+ <Drawer.Root open={open}>+ <Drawer.Portal>+ <Drawer.Overlay className="fixed inset-0 bg-black/40" />+ <Drawer.Content className="bg-zinc-100 flex flex-col rounded-t-[10px] 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-6">+ It uses{' '}+ <a+ href="https://www.radix-ui.com/docs/primitives/components/dialog"+ className="underline"+ target="_blank"+ >+ Radix’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>++ <button+ type="button"+ onClick={() => {+ setOpen(false);+ }}+ className="rounded-md mb-6 w-full bg-gray-900 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-gray-800 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-600"+ >+ Close this+ </button>+ </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"+ stroke-linecap="round"+ stroke-linejoin="round"+ stroke-width="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"+ >+ <svg+ fill="none"+ height="16"+ stroke="currentColor"+ stroke-linecap="round"+ stroke-linejoin="round"+ stroke-width="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>+ </Drawer.Portal>+ </Drawer.Root>+ );+}++export default function Home() {+ const [open, setOpen] = useState(false);+ const [open2, setOpen2] = useState(false);++ return (+ <div className="bg-zinc-100 space-y-10">+ <p className="pb-[120vh] bg-zinc-600 text-white font-bold">scroll down</p>+ <MyDrawer open={open} setOpen={setOpen} setOpen2={setOpen2} />+ <MyDrawer2 open={open2} setOpen={setOpen2} />+ <p className="py-32 bg-zinc-800">scroll down</p>+ </div>+ );+}