A drawer component for React.
Add snap points (#68)
Emil Kowalski97947910bf73
diff --git a/src/constants.ts b/src/constants.tsnew file mode 100644index 0000000..fd6a10c--- /dev/null+++ b/src/constants.ts@@ -0,0 +1,6 @@+export const TRANSITIONS = {+ DURATION: 0.5,+ EASE: [0.32, 0.72, 0, 1],+};++export const VELOCITY_THRESHOLD = 0.4;diff --git a/src/context.ts b/src/context.tsindex 697b3aa..ed4267c 100644--- a/src/context.ts+++ b/src/context.ts@@ -15,6 +15,11 @@ interface DrawerContextValue {setIsAnimating: (o: boolean) => void;keyboardIsOpen: React.MutableRefObject<boolean>;experimentalSafariThemeAnimation: boolean;+ snapPointHeights: number[] | null;+ snapPoints: number[] | null;+ shouldFade: boolean;+ activeSnapPoint: number | null;+ setActiveSnapPoint: (o: number | null) => void;}export const DrawerContext = React.createContext<DrawerContextValue | undefined>(undefined);diff --git a/src/helpers.ts b/src/helpers.tsnew file mode 100644index 0000000..179c912--- /dev/null+++ b/src/helpers.ts@@ -0,0 +1,70 @@+interface Style {+ [key: string]: string;+}++const cache = new WeakMap();++export function isInView(el: HTMLElement): boolean {+ const rect = el.getBoundingClientRect();++ if (!window.visualViewport) return false;++ return (+ rect.top >= 0 &&+ rect.left >= 0 &&+ // Need + 40 for safari detection+ rect.bottom <= window.visualViewport.height + 40 &&+ rect.right <= window.visualViewport.width+ );+}++export function set(el?: Element | HTMLElement | null, styles?: Style, ignoreCache = false) {+ if (!el || !(el instanceof HTMLElement) || !styles) return;+ let originalStyles: Style = {};++ Object.entries(styles).forEach(([key, value]: [string, string]) => {+ if (key.startsWith('--')) {+ el.style.setProperty(key, value);+ return;+ }++ originalStyles[key] = (el.style as any)[key];+ (el.style as any)[key] = value;+ });++ if (ignoreCache) return;+ cache.set(el, originalStyles);+}++export function reset(el: Element | HTMLElement | null, prop?: string) {+ if (!el || !(el instanceof HTMLElement)) return;+ let originalStyles = cache.get(el);++ if (!originalStyles) {+ (el.style as any) = {};+ return;+ }++ if (prop) {+ (el.style as any)[prop] = originalStyles[prop];+ } else {+ Object.entries(originalStyles).forEach(([key, value]) => {+ (el.style as any)[key] = value;+ });+ }+}++export function getTranslateY(element: HTMLElement): 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]);+ mat = transform.match(/^matrix\((.+)\)$/);+ return mat ? parseFloat(mat[1].split(', ')[5]) : null;+}++export function dampenValue(v: number) {+ return 8 * (Math.log(v + 1) - 2);+}diff --git a/src/index.tsx b/src/index.tsxindex d273802..37e27dd 100644--- a/src/index.tsx+++ b/src/index.tsx@@ -9,94 +9,35 @@ import { usePreventScroll, isInput } from './use-prevent-scroll';import { useComposedRefs } from './use-composed-refs';import { useSafariThemeColor } from './use-safari-theme-color';import { usePositionFixed } from './use-position-fixed';+import { useSnapPoints } from './use-snap-points';+import { set, reset, getTranslateY, isInView, dampenValue } from './helpers';+import { TRANSITIONS, VELOCITY_THRESHOLD } from './constants';const CLOSE_THRESHOLD = 0.25;const SCROLL_LOCK_TIMEOUT = 500;-const TRANSITIONS = {- DURATION: 0.5,- EASE: [0.32, 0.72, 0, 1],-};-const ANIMATION_DURATION = 501;const BORDER_RADIUS = 8;-const VELOCITY_THRESHOLD = 0.4;-const NESTED_DISPLACEMENT = 16;const WINDOW_TOP_OFFSET = 26;-const cache = new WeakMap();--interface Style {- [key: string]: string;-}--function isInView(el: HTMLElement): boolean {- const rect = el.getBoundingClientRect();-- if (!window.visualViewport) return false;-- return (- rect.top >= 0 &&- rect.left >= 0 &&- // Need + 40 for safari detection- rect.bottom <= window.visualViewport.height + 40 &&- rect.right <= window.visualViewport.width- );-}--function set(el?: Element | HTMLElement | null, styles?: Style, ignoreCache = false) {- if (!el || !(el instanceof HTMLElement) || !styles) return;- let originalStyles: Style = {};-- Object.entries(styles).forEach(([key, value]: [string, string]) => {- if (key.startsWith('--')) {- el.style.setProperty(key, value);- return;- }-- originalStyles[key] = (el.style as any)[key];- (el.style as any)[key] = value;- });-- if (ignoreCache) return;- cache.set(el, originalStyles);-}--function reset(el: Element | HTMLElement | null, prop?: string) {- if (!el || !(el instanceof HTMLElement)) return;- let originalStyles = cache.get(el);-- if (!originalStyles) {- (el.style as any) = {};- return;- }-- if (prop) {- (el.style as any)[prop] = originalStyles[prop];- } else {- Object.entries(originalStyles).forEach(([key, value]) => {- (el.style as any)[key] = value;- });- }-}+type WithFadeFromProps = {+ snapPoints: number[];+ fadeFromIndex: number;+};-function getTranslateY(element: HTMLElement): 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]);- mat = transform.match(/^matrix\((.+)\)$/);- return mat ? parseFloat(mat[1].split(', ')[5]) : null;-}+type WithoutFadeFromProps = {+ snapPoints?: number[];+ fadeFromIndex?: never;+};-interface DialogProps {+type DialogProps = {+ activeSnapPoint?: number | null;+ setActiveSnapPoint?(snapPoint: number | null): void;children?: React.ReactNode;open?: boolean;defaultOpen?: boolean;@@ -108,7 +49,7 @@ interface DialogProps {onDrag?(event: React.PointerEvent<HTMLDivElement>, percentageDragged: number): void;onRelease?(event: React.PointerEvent<HTMLDivElement>, open: boolean): void;experimentalSafariThemeAnimation?: boolean;-}+} & (WithFadeFromProps | WithoutFadeFromProps);function Root({open: openProp,@@ -119,9 +60,13 @@ function Root({onDrag: onDragProp,onRelease: onReleaseProp,experimentalSafariThemeAnimation,+ snapPoints,closeThreshold = CLOSE_THRESHOLD,scrollLockTimeout = SCROLL_LOCK_TIMEOUT,dismissible = true,+ fadeFromIndex = snapPoints?.length - 1,+ activeSnapPoint: activeSnapPointProp,+ setActiveSnapPoint: setActiveSnapPointProp,}: DialogProps) {const [isOpen = false, setIsOpen] = useControllableState({prop: openProp,@@ -145,6 +90,23 @@ function Root({isOpen,experimentalSafariThemeAnimation,);+ const {+ activeSnapPoint,+ activeSnapPointIndex,+ setActiveSnapPoint,+ onRelease: onReleaseSnapPoints,+ snapPointHeights,+ onDrag: onDragSnapPoints,+ shouldFade,+ getPercentageDragged: getSnapPointsPercentageDragged,+ } = useSnapPoints({+ snapPoints,+ activeSnapPointProp,+ setActiveSnapPointProp,+ drawerRef: drawerRef,+ fadeFromIndex,+ overlayRef: overlayRef,+ });usePreventScroll({isDisabled: !isOpen || isDragging || isAnimating,@@ -240,9 +202,13 @@ function Root({transition: 'none',});- // Allow dragging upwards up to 40px- if (draggedDistance > 0) {- const dampenedDraggedDistance = 8 * (Math.log(draggedDistance + 1) - 2);+ if (snapPoints) {+ onDragSnapPoints({ draggedDistance });+ }++ // Run this only if snapPoints are not defined or if we are at the last snap point (highest one)+ if (draggedDistance > 0 && !snapPoints) {+ const dampenedDraggedDistance = dampenValue(draggedDistance);set(drawerRef.current, {transform: `translateY(${Math.min(dampenedDraggedDistance * -1, 0)}px)`,@@ -254,17 +220,27 @@ function Root({const absDraggedDistance = Math.abs(draggedDistance);const wrapper = document.querySelector('[vaul-drawer-wrapper]');- const percentageDragged = absDraggedDistance / drawerHeight;+ let percentageDragged = absDraggedDistance / drawerHeight;+ const snapPointPercentageDragged = getSnapPointsPercentageDragged(absDraggedDistance, isDraggingDown);++ if (snapPointPercentageDragged !== null) {+ percentageDragged = snapPointPercentageDragged;+ }+const opacityValue = 1 - percentageDragged;- changeThemeColorOnDrag(percentageDragged);- onDragProp?.(event, percentageDragged);- set(- overlayRef.current,- {- opacity: `${opacityValue}`,- },- true,- );++ if (shouldFade || activeSnapPointIndex === fadeFromIndex - 1) {+ changeThemeColorOnDrag(percentageDragged);+ onDragProp?.(event, percentageDragged);+ set(+ overlayRef.current,+ {+ opacity: `${opacityValue}`,+ transition: 'none',+ },+ true,+ );+ }if (wrapper && overlayRef.current && shouldScaleBackground) {// Calculate percentageDragged as a fraction (0 to 1)@@ -284,9 +260,11 @@ function Root({);}- set(drawerRef.current, {- transform: `translateY(${absDraggedDistance}px)`,- });+ if (!snapPoints) {+ set(drawerRef.current, {+ transform: `translateY(${absDraggedDistance}px)`,+ });+ }}}@@ -309,7 +287,7 @@ function Root({}previousDiffFromInitial.current = diffFromInitial;- // We don't have to change the height if the input is in view, when we are here we are in the opened keyboard state so we can accuretly check if the input is in view+ // We don't have to change the height if the input is in view, when we are here we are in the opened keyboard state so we can correctly check if the input is in viewif (drawerHeight > visualViewportHeight || keyboardIsOpen.current) {const height = drawerRef.current?.getBoundingClientRect().height;let newDrawerHeight = height;@@ -346,7 +324,7 @@ function Root({const opacityValue = overlayRef.current?.style.opacity || 1;set(overlayRef.current, {- '--opacity-from': `${opacityValue}`,+ '--opacity-from': `${shouldFade ? opacityValue : 0}`,});}}@@ -410,6 +388,11 @@ function Root({const distMoved = pointerStartY.current - y;const velocity = Math.abs(distMoved) / timeTaken;+ if (snapPoints) {+ onReleaseSnapPoints({ draggedDistance: distMoved, closeDrawer, velocity });+ return;+ }+// Moved upwards, don't do anythingif (distMoved > 0) {resetDrawer();@@ -522,11 +505,17 @@ function Root({<DialogPrimitive.Rootopen={isOpen}onOpenChange={(o) => {+ if (!o && snapPoints) {+ closeDrawer();+ }setIsOpen(o);}}><DrawerContext.Providervalue={{+ activeSnapPoint,+ snapPoints,+ setActiveSnapPoint,drawerRef,overlayRef,onAnimationStart,@@ -535,11 +524,13 @@ function Root({onDrag,dismissible,isOpen,+ shouldFade,onNestedDrag,onNestedOpenChange,onNestedRelease,keyboardIsOpen,setIsAnimating,+ snapPointHeights,experimentalSafariThemeAnimation,}}>@@ -551,15 +542,19 @@ function Root({const Overlay = React.forwardRef<HTMLDivElement, React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>>(function ({ children, ...rest }, ref) {- const { overlayRef, onRelease, experimentalSafariThemeAnimation } = useDrawerContext();+ const { overlayRef, snapPoints, onRelease, experimentalSafariThemeAnimation, shouldFade, isOpen } =+ useDrawerContext();const composedRef = useComposedRefs(ref, overlayRef);+ const hasSnapPoints = snapPoints && snapPoints.length > 0;return (<DialogPrimitive.OverlayonMouseUp={onRelease}ref={composedRef}vaul-overlay=""+ vaul-snap-points={isOpen && hasSnapPoints ? 'true' : 'false'}vaul-theme-transition={experimentalSafariThemeAnimation ? 'true' : 'false'}+ vaul-snap-points-overlay={isOpen && shouldFade ? 'true' : 'false'}{...rest}/>);@@ -573,7 +568,7 @@ type ContentProps = React.ComponentPropsWithoutRef<typeof DialogPrimitive.Conten};const Content = React.forwardRef<HTMLDivElement, ContentProps>(function (- { children, onOpenAutoFocus, onPointerDownOutside, onAnimationEnd, ...rest },+ { children, onOpenAutoFocus, onPointerDownOutside, onAnimationEnd, style, ...rest },ref,) {const {@@ -586,6 +581,9 @@ const Content = React.forwardRef<HTMLDivElement, ContentProps>(function (isOpen,keyboardIsOpen,setIsAnimating,+ snapPointHeights,+ setActiveSnapPoint,+ snapPoints,} = useDrawerContext();const composedRef = useComposedRefs(ref, drawerRef);const animationEndTimer = React.useRef<NodeJS.Timeout>(null);@@ -599,6 +597,9 @@ const Content = React.forwardRef<HTMLDivElement, ContentProps>(function (animationEndTimer.current = setTimeout(() => {setIsAnimating(false);onAnimationEnd?.(isOpen);+ if (snapPoints && !isOpen) {+ setActiveSnapPoint(snapPoints[0]);+ }}, ANIMATION_DURATION);onAnimationStart(e);}}@@ -626,6 +627,14 @@ const Content = React.forwardRef<HTMLDivElement, ContentProps>(function (onPointerDownOutside?.(e);}}ref={composedRef}+ style={+ snapPointHeights+ ? ({+ '--snap-point-height': `${snapPointHeights[0]}px`,+ ...style,+ } as React.CSSProperties)+ : style+ }{...rest}vaul-drawer="">diff --git a/src/style.css b/src/style.cssindex 2a39928..e640854 100644--- a/src/style.css+++ b/src/style.css@@ -2,6 +2,7 @@will-change: transform;touch-action: none;animation: show-dialog 0.5s cubic-bezier(0.32, 0.72, 0, 1);+ transform: translateY(var(--snap-point-height, 0));}[vaul-drawer]::after {@@ -23,16 +24,25 @@animation: fake-animation 0.5s cubic-bezier(0.32, 0.72, 0, 1) forwards;}-[vaul-overlay] {+[vaul-overlay]:not([vaul-snap-points='true']) {animation: show-overlay 0.5s cubic-bezier(0.32, 0.72, 0, 1);}+[vaul-overlay][vaul-snap-points='true']:not([vaul-snap-points-overlay='true']):not([data-state='closed']) {+ opacity: 0;+}++[vaul-overlay][vaul-snap-points-overlay='true'] {+ opacity: 1;+}+[vaul-overlay][vaul-theme-transition='true'] {animation: show-theme-overlay 0.5s cubic-bezier(0.32, 0.72, 0, 1);}-[vaul-overlay][data-state='closed'] {- animation: hide-overlay 0.5s cubic-bezier(0.32, 0.72, 0, 1) forwards;+[vaul-overlay][data-state='closed']:not([vaul-snap-points='true']),+[vaul-overlay][data-state='closed'][vaul-snap-points-overlay='true'] {+ animation: hide-overlay 0.5s cubic-bezier(0.32, 0.72, 0, 1);}[vaul-overlay][vaul-theme-transition='true'][data-state='closed'] {@@ -42,10 +52,8 @@/* This will allow us to not animate via animation, but still benefit from delaying unmount via Radix. */@keyframes fake-animation {from {- opacity: 1;}to {- opacity: 1;}}@@ -54,7 +62,7 @@transform: translateY(100%);}to {- transform: translateY(0);+ transform: translateY(var(--snap-point-height, 0));}}diff --git a/src/types.ts b/src/types.tsnew file mode 100644index 0000000..f766331--- /dev/null+++ b/src/types.ts@@ -0,0 +1,4 @@+export interface SnapPoint {+ fraction: number;+ height: number;+}diff --git a/src/use-snap-points.ts b/src/use-snap-points.tsnew file mode 100644index 0000000..3fc44ed--- /dev/null+++ b/src/use-snap-points.ts@@ -0,0 +1,190 @@+import React from 'react';+import { dampenValue, set } from './helpers';+import { TRANSITIONS, VELOCITY_THRESHOLD } from './constants';+import { useControllableState } from './use-controllable-state';++export function useSnapPoints({+ activeSnapPointProp,+ setActiveSnapPointProp,+ snapPoints,+ drawerRef,+ overlayRef,+ fadeFromIndex,+}: {+ activeSnapPointProp?: number | null;+ setActiveSnapPointProp?(snapPoint: number | null): void;+ snapPoints?: number[];+ fadeFromIndex: number;+ drawerRef: React.RefObject<HTMLDivElement>;+ overlayRef: React.RefObject<HTMLDivElement>;+}) {+ const [activeSnapPoint, setActiveSnapPoint] = useControllableState({+ prop: activeSnapPointProp,+ defaultProp: snapPoints?.[0],+ onChange: setActiveSnapPointProp,+ });++ const hasWindow = typeof window !== 'undefined';+ const isLastSnapPoint = React.useMemo(+ () => activeSnapPoint === snapPoints?.[snapPoints.length - 1] ?? null,+ [snapPoints, activeSnapPoint],+ );++ const shouldFade =+ (snapPoints && snapPoints.length > 0 && snapPoints[fadeFromIndex] === activeSnapPoint) || !snapPoints;++ const activeSnapPointIndex = React.useMemo(+ () => snapPoints?.findIndex((snapPoint) => snapPoint === activeSnapPoint) ?? null,+ [snapPoints, activeSnapPoint],+ );++ const snapPointHeights = React.useMemo(+ () => snapPoints?.map((snapPoint) => hasWindow && window.innerHeight - snapPoint * window.innerHeight) ?? null,+ [snapPoints],+ );++ const activeSnapPointHeight = React.useMemo(+ () => snapPointHeights?.[activeSnapPointIndex] ?? null,+ [snapPointHeights, activeSnapPoint],+ );++ function snapToPoint(height: number) {+ const newSnapPointIndex = snapPointHeights?.findIndex((snapPointHeight) => snapPointHeight === height) ?? null;++ set(drawerRef.current, {+ transition: `transform ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,+ transform: `translateY(${height}px)`,+ });++ if (newSnapPointIndex !== snapPointHeights.length - 1 && newSnapPointIndex !== fadeFromIndex) {+ set(overlayRef.current, {+ transition: `opacity ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,+ opacity: '0',+ });+ } else {+ set(overlayRef.current, {+ transition: `opacity ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,+ opacity: '1',+ });+ }++ setActiveSnapPoint(snapPoints?.[newSnapPointIndex] ?? null);+ }++ React.useEffect(() => {+ if (activeSnapPointProp) {+ const newIndex = snapPoints?.findIndex((snapPoint) => snapPoint === activeSnapPointProp) ?? null;+ snapToPoint(snapPointHeights[newIndex]);+ }+ }, [activeSnapPointProp]);++ function onRelease({+ draggedDistance,+ closeDrawer,+ velocity,+ }: {+ draggedDistance: number;+ closeDrawer: () => void;+ velocity: number;+ }) {+ const currentPosition = activeSnapPointHeight - draggedDistance;+ const isOverlaySnapPoint = activeSnapPointIndex === fadeFromIndex - 1;+ const isFirst = activeSnapPointIndex === 0;++ if (isOverlaySnapPoint) {+ set(overlayRef.current, {+ transition: `opacity ${TRANSITIONS.DURATION}s cubic-bezier(${TRANSITIONS.EASE.join(',')})`,+ });+ }++ if (velocity > 2 && draggedDistance < 0) {+ closeDrawer();+ return;+ }++ if (velocity > 2 && draggedDistance > 0) {+ snapToPoint(snapPointHeights[snapPoints.length - 1]);+ return;+ }++ if (velocity > VELOCITY_THRESHOLD) {+ // -1 = down, 1 = up, might need a better name+ const dragDirection = draggedDistance > 0 ? 1 : -1;+ // Don't do anything if we swipe upwards while being on the last snap point+ if (dragDirection > 0 && isLastSnapPoint) return;++ if (isFirst && dragDirection < 0) {+ closeDrawer();+ }++ snapToPoint(snapPointHeights[activeSnapPointIndex + dragDirection]);+ return;+ }++ // Find the closest snap point to the current position+ const closestSnapPoint = snapPointHeights?.reduce((prev, curr) => {+ return Math.abs(curr - currentPosition) < Math.abs(prev - currentPosition) ? curr : prev;+ });++ snapToPoint(closestSnapPoint);+ }++ function onDrag({ draggedDistance }: { draggedDistance: number }) {+ const newYValue = activeSnapPointHeight - draggedDistance;++ if (isLastSnapPoint && newYValue < activeSnapPointHeight) {+ const dampenedDraggedDistance = dampenValue(draggedDistance);++ set(drawerRef.current, {+ transform: `translateY(${Math.min(activeSnapPointHeight - dampenedDraggedDistance, activeSnapPointHeight)}px)`,+ });+ return;+ }++ set(drawerRef.current, {+ transform: `translateY(${newYValue}px)`,+ });+ }++ function getPercentageDragged(absDraggedDistance: number, isDraggingDown: boolean) {+ if (!snapPoints) return null;+ // If this is true we are dragging to a snap point that is supposed to have an overlay+ const isOverlaySnapPoint = activeSnapPointIndex === fadeFromIndex - 1;+ const isOverlaySnapPointOrHigher = activeSnapPointIndex >= fadeFromIndex;++ if (isOverlaySnapPointOrHigher && isDraggingDown) {+ return 0;+ }++ // Don't animate, but still use this one if we are dragging away from the overlaySnapPoint+ if (isOverlaySnapPoint && !isDraggingDown) return 1;+ if (!shouldFade && !isOverlaySnapPoint) return null;+ // Either fadeFrom index or the one before+ const targetSnapPointIndex = isOverlaySnapPoint ? activeSnapPointIndex + 1 : activeSnapPointIndex - 1;++ // Get the distance from overlaySnapPoint to the one before or vice-versa to calculate the opacity percentage accordingly+ const snapPointDistance = isOverlaySnapPoint+ ? snapPointHeights[targetSnapPointIndex] - snapPointHeights[targetSnapPointIndex - 1]+ : snapPointHeights[targetSnapPointIndex + 1] - snapPointHeights[targetSnapPointIndex];++ const percentageDragged = absDraggedDistance / Math.abs(snapPointDistance);++ if (isOverlaySnapPoint) {+ return 1 - percentageDragged;+ } else {+ return percentageDragged;+ }+ }++ return {+ isLastSnapPoint,+ activeSnapPoint,+ shouldFade,+ getPercentageDragged,+ setActiveSnapPoint,+ activeSnapPointIndex,+ onRelease,+ onDrag,+ snapPointHeights,+ };+}