A drawer component for React.
Smoother safari transition (#51)
Emil Kowalskiaa4d4400b98a
diff --git a/src/bezier-easing.ts b/src/bezier-easing.tsnew file mode 100644index 0000000..16f0bf4--- /dev/null+++ b/src/bezier-easing.ts@@ -0,0 +1,116 @@+/**+ * https://github.com/gre/bezier-easing+ * BezierEasing - use bezier curve for transition easing function+ * by Gaëtan Renaudeau 2014 - 2015 – MIT License+ */++// These values are established by empiricism with tests (tradeoff: performance VS precision)+var NEWTON_ITERATIONS = 4;+var NEWTON_MIN_SLOPE = 0.001;+var SUBDIVISION_PRECISION = 0.0000001;+var SUBDIVISION_MAX_ITERATIONS = 10;++var kSplineTableSize = 11;+var kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);++var float32ArraySupported = typeof Float32Array === 'function';++function A(aA1, aA2) {+ return 1.0 - 3.0 * aA2 + 3.0 * aA1;+}+function B(aA1, aA2) {+ return 3.0 * aA2 - 6.0 * aA1;+}+function C(aA1) {+ return 3.0 * aA1;+}++// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.+function calcBezier(aT, aA1, aA2) {+ return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;+}++// Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2.+function getSlope(aT, aA1, aA2) {+ return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);+}++function binarySubdivide(aX, aA, aB, mX1, mX2) {+ var currentX,+ currentT,+ i = 0;+ do {+ currentT = aA + (aB - aA) / 2.0;+ currentX = calcBezier(currentT, mX1, mX2) - aX;+ if (currentX > 0.0) {+ aB = currentT;+ } else {+ aA = currentT;+ }+ } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);+ return currentT;+}++function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) {+ for (var i = 0; i < NEWTON_ITERATIONS; ++i) {+ var currentSlope = getSlope(aGuessT, mX1, mX2);+ if (currentSlope === 0.0) {+ return aGuessT;+ }+ var currentX = calcBezier(aGuessT, mX1, mX2) - aX;+ aGuessT -= currentX / currentSlope;+ }+ return aGuessT;+}++function LinearEasing(x) {+ return x;+}++export function bezier(mX1, mY1, mX2, mY2) {+ if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) {+ throw new Error('bezier x values must be in [0, 1] range');+ }++ if (mX1 === mY1 && mX2 === mY2) {+ return LinearEasing;+ }++ // Precompute samples table+ var sampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);+ for (var i = 0; i < kSplineTableSize; ++i) {+ sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);+ }++ function getTForX(aX) {+ var intervalStart = 0.0;+ var currentSample = 1;+ var lastSample = kSplineTableSize - 1;++ for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {+ intervalStart += kSampleStepSize;+ }+ --currentSample;++ // Interpolate to provide an initial guess for t+ var dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);+ var guessForT = intervalStart + dist * kSampleStepSize;++ var initialSlope = getSlope(guessForT, mX1, mX2);+ if (initialSlope >= NEWTON_MIN_SLOPE) {+ return newtonRaphsonIterate(aX, guessForT, mX1, mX2);+ } else if (initialSlope === 0.0) {+ return guessForT;+ } else {+ return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);+ }+ }++ return function BezierEasing(x) {+ // Because JavaScript number are imprecise, we should guarantee the extremes are right.+ if (x === 0 || x === 1) {+ return x;+ }+ return calcBezier(getTForX(x), mY1, mY2);+ };+};diff --git a/src/context.ts b/src/context.tsindex 48bcaec..697b3aa 100644--- a/src/context.ts+++ b/src/context.ts@@ -14,6 +14,7 @@ interface DrawerContextValue {isOpen: boolean;setIsAnimating: (o: boolean) => void;keyboardIsOpen: React.MutableRefObject<boolean>;+ experimentalSafariThemeAnimation: boolean;}export const DrawerContext = React.createContext<DrawerContextValue | undefined>(undefined);diff --git a/src/index.tsx b/src/index.tsxindex cc4c5a2..206c7e5 100644--- a/src/index.tsx+++ b/src/index.tsx@@ -523,6 +523,7 @@ function Root({onNestedRelease,keyboardIsOpen,setIsAnimating,+ experimentalSafariThemeAnimation,}}>{children}@@ -533,10 +534,18 @@ function Root({const Overlay = React.forwardRef<HTMLDivElement, React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>>(function ({ children, ...rest }, ref) {- const { overlayRef, onRelease } = useDrawerContext();+ const { overlayRef, onRelease, experimentalSafariThemeAnimation } = useDrawerContext();const composedRef = useComposedRefs(ref, overlayRef);- return <DialogPrimitive.Overlay onMouseUp={onRelease} ref={composedRef} vaul-overlay="" {...rest} />;+ return (+ <DialogPrimitive.Overlay+ onMouseUp={onRelease}+ ref={composedRef}+ vaul-overlay=""+ vaul-theme-transition={experimentalSafariThemeAnimation ? 'true' : 'false'}+ {...rest}+ />+ );},);diff --git a/src/style.css b/src/style.cssindex 8f8e4c2..2a39928 100644--- a/src/style.css+++ b/src/style.css@@ -27,10 +27,18 @@animation: show-overlay 0.5s cubic-bezier(0.32, 0.72, 0, 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][vaul-theme-transition='true'][data-state='closed'] {+ animation: hide-theme-overlay 0.5s cubic-bezier(0.32, 0.72, 0, 1) forwards;+}+/* This will allow us to not animate via animation, but still benefit from delaying unmount via Radix. */@keyframes fake-animation {from {@@ -77,6 +85,24 @@}}+@keyframes show-theme-overlay {+ from {+ background: var(--vaul-overlay-background-start);+ }+ to {+ background: var(--vaul-overlay-background-end);+ }+}++@keyframes hide-theme-overlay {+ from {+ background: var(--vaul-overlay-background-end);+ }+ to {+ background: var(--vaul-overlay-background-start);+ }+}+@media (hover: hover) and (pointer: fine) {[vaul-drawer] {user-select: none;diff --git a/src/use-safari-theme-color.ts b/src/use-safari-theme-color.tsindex f818556..67c506d 100644--- a/src/use-safari-theme-color.ts+++ b/src/use-safari-theme-color.ts@@ -1,6 +1,9 @@-import React from 'react';+import React, { useCallback } from 'react';+import { bezier } from './bezier-easing';import { isIOS, isSafari } from './use-prevent-scroll';+const bezierEasing = bezier(0.32, 0.72, 0, 1);+type RGB = [number, number, number];function extractRGBA(str: string): [number, number, number, number] {@@ -23,8 +26,8 @@ function getNonTrasparentOverlayColor(rgbaStr: string, background: RGB): RGB {return rgb;}-function easeOutExpo(t: number): number {- return t === 1 ? 1 : 1 - Math.pow(2, -10 * t);+function easing(t: number): number {+ return bezierEasing(t);}function interpolateColor(color1: number[], color2: number[], factor: number, linear: boolean) {@@ -34,7 +37,7 @@ function interpolateColor(color1: number[], color2: number[], factor: number, lilet result = color1.slice();for (let i = 0; i < 3; i++) {const delta = color2[i] - color1[i];- const newColorComponent = linear ? color1[i] + factor * delta : color1[i] + easeOutExpo(factor) * delta;+ const newColorComponent = linear ? color1[i] + factor * delta : color1[i] + easing(factor) * delta;result[i] = Math.round(newColorComponent);if (result[i] < 0) result[i] = 0;if (result[i] > 255) result[i] = 255;@@ -47,7 +50,7 @@ function interpolateColors(color1: number[], color2: number[], steps: number, liinterpolatedColorArray = [];for (let i = 0; i < steps; i++) {- interpolatedColorArray.push(interpolateColor(color1, color2, stepFactor * i, linear));+ interpolatedColorArray.push(interpolateColor(color1, color2, stepFactor * i, Boolean(linear)));}return interpolatedColorArray;@@ -58,105 +61,126 @@ export function useSafariThemeColor(isOpen: boolean,shouldAnimate: boolean,) {- const [backgroundColor, setBackgroundColor] = React.useState<RGB | null>(null);- const [nonTransparentOverlayColor, setNonTransparentOverlayColor] = React.useState<RGB | null>(null);+ const [backgroundColor, setBackgroundColor] = React.useState<RGB | null>([255, 255, 255]);+ const [overlayColor, setOverlayColor] = React.useState<RGB | null>([153, 153, 153]);const [releaseExit, setReleaseExit] = React.useState<boolean>(false);const [initialMetaThemeColor, setInitialMetaThemeColor] = React.useState<string | null>(null);+ const [metaElement, setMetaElement] = React.useState<HTMLMetaElement | null>(null);const shouldRun = React.useMemo(() => isIOS() && isSafari() && shouldAnimate, [shouldAnimate]);const interpolatedColorsEnter = React.useMemo(- () =>- backgroundColor && nonTransparentOverlayColor- ? interpolateColors(backgroundColor, nonTransparentOverlayColor, 50)- : null,- [nonTransparentOverlayColor, backgroundColor],+ () => (backgroundColor && overlayColor ? interpolateColors(backgroundColor, overlayColor, 50) : null),+ [overlayColor, backgroundColor],);const interpolatedColorsExit = React.useMemo(- () =>- backgroundColor && nonTransparentOverlayColor- ? interpolateColors(nonTransparentOverlayColor, backgroundColor, 50)- : null,- [nonTransparentOverlayColor, backgroundColor],+ () => (backgroundColor && overlayColor ? interpolateColors(overlayColor, backgroundColor, 50) : null),+ [overlayColor, backgroundColor],);- const linearInterpolation = React.useMemo(- () =>- backgroundColor && nonTransparentOverlayColor- ? interpolateColors(nonTransparentOverlayColor, backgroundColor, 50, true)- : null,- [nonTransparentOverlayColor, backgroundColor],+ const interpolatedColorsLinear = React.useMemo(+ () => (backgroundColor && overlayColor ? interpolateColors(overlayColor, backgroundColor, 50, true) : null),+ [overlayColor, backgroundColor],);React.useEffect(() => {if (!shouldRun) return;- requestAnimationFrame(() => {- if (overlay.current) {- const overlayColor = getComputedStyle(overlay.current).getPropertyValue('background-color');- const backgroundColor = getComputedStyle(document.documentElement)- .getPropertyValue('--vaul-theme-color')- .split(',')- .map((c) => Number(c));- const nonTransparentOverlayColor = getNonTrasparentOverlayColor(overlayColor, backgroundColor as RGB);- setBackgroundColor(backgroundColor as RGB);- setNonTransparentOverlayColor(nonTransparentOverlayColor);- }- });- }, [isOpen, shouldRun, overlay]);+ const documentElementStyle = getComputedStyle(document.documentElement);+ const backgroundColor = documentElementStyle+ .getPropertyValue('--vaul-overlay-background')+ .split(',')+ .map((c) => Number(c));++ const overlayColor = documentElementStyle.getPropertyValue('--vaul-overlay-background-end');++ const nonTransparentOverlayColor = getNonTrasparentOverlayColor(overlayColor, backgroundColor as RGB);++ setBackgroundColor(backgroundColor as RGB);+ setOverlayColor(nonTransparentOverlayColor);+ }, [shouldRun]);React.useEffect(() => {if (!shouldRun) return;- if (overlay.current && interpolatedColorsEnter && interpolatedColorsExit && !releaseExit) {- let metaThemeColor = document.querySelector('meta[name="theme-color"]');-- if (- drawer.current.style.transform === 'translateY(0px)' &&- drawer.current.getAttribute('vaul-clicked-outside') !== 'true'- ) {- // It's resetting, so don't apply these styles- return;- }+ if (!initialMetaThemeColor) {+ let metaThemeColor: HTMLMetaElement | null = document.querySelector('meta[name="theme-color"]');- if (!metaThemeColor) {+ if (metaThemeColor) {+ setInitialMetaThemeColor(metaThemeColor.getAttribute('content'));+ } else {metaThemeColor = document.createElement('meta');- // @ts-ignoremetaThemeColor.name = 'theme-color';document.getElementsByTagName('head')[0].appendChild(metaThemeColor);- } else if (!initialMetaThemeColor) {- setInitialMetaThemeColor(metaThemeColor.getAttribute('content'));}+ setMetaElement(metaThemeColor);+ }+ }, [initialMetaThemeColor, shouldRun]);++ const animate = useCallback(+ (colors: number[][]): number => {+ let start: number;+ let frameId: number;++ function draw(timeStamp: number) {+ if (!start) start = timeStamp;+ const elapsed = timeStamp - start;+ // dividing by 10 will give us a total time of 500.+ const index = Math.floor(elapsed / 10);++ if (overlay.current && colors && !releaseExit) {+ if (+ drawer.current.style.transform === 'translateY(0px)' &&+ drawer.current.getAttribute('vaul-clicked-outside') !== 'true'+ ) {+ // It's resetting, so don't apply these styles+ return;+ }++ if (index < colors.length) {+ const currentColor = colors[index];+ metaElement?.setAttribute('content', `rgb(${currentColor.join(',')})`);- const timer = isOpen ? 10.5 : 8;+ if (index === colors.length - 1 && initialMetaThemeColor && !isOpen) {+ metaElement?.setAttribute('content', initialMetaThemeColor as string);+ }- for (let i = 0; i < interpolatedColorsEnter.length; i++) {- setTimeout(() => {- const currentColor = isOpen ? interpolatedColorsEnter[i] : interpolatedColorsExit[i];- metaThemeColor.setAttribute('content', `rgb(${currentColor.join(',')})`);- if (i === interpolatedColorsEnter.length - 1 && initialMetaThemeColor && !isOpen) {- metaThemeColor.setAttribute('content', initialMetaThemeColor as string);+ frameId = requestAnimationFrame(draw);}- }, i * timer);+ }}- }++ frameId = requestAnimationFrame(draw);+ return frameId;+ },+ [drawer, isOpen, metaElement, releaseExit, initialMetaThemeColor, overlay],+ );++ React.useEffect(() => {+ if (!shouldRun || !interpolatedColorsEnter || !interpolatedColorsExit) return;++ const frameId = animate(isOpen ? interpolatedColorsEnter : interpolatedColorsExit);if (isOpen) {setReleaseExit(false);}- }, [isOpen, interpolatedColorsEnter, interpolatedColorsExit, releaseExit, drawer, overlay, shouldRun]);++ return () => {+ if (frameId) cancelAnimationFrame(frameId);+ };+ }, [isOpen, shouldRun, animate, interpolatedColorsEnter, interpolatedColorsExit]);function onDrag(percentageDragged: number) {const metaThemeColor = document.querySelector('meta[name="theme-color"]');- if (!shouldRun || !metaThemeColor) return;+ if (!shouldRun || !metaThemeColor || !interpolatedColorsLinear) return;// Calculate the index of the color array by mapping the proportion to the array length- let colorIndex = Math.floor(percentageDragged * linearInterpolation.length);+ let colorIndex = Math.floor(percentageDragged * interpolatedColorsLinear.length);// Ensure colorIndex is between 0 and array length - 1- colorIndex = Math.max(0, Math.min(linearInterpolation.length - 1, colorIndex));+ colorIndex = Math.max(0, Math.min(interpolatedColorsLinear.length - 1, colorIndex));// Get the color- const color = linearInterpolation[colorIndex];+ const color = interpolatedColorsLinear[colorIndex];// Set the meta theme colormetaThemeColor.setAttribute('content', `rgb(${color.join(',')})`);@@ -167,26 +191,16 @@ export function useSafariThemeColor(if (!metaThemeColor || !shouldRun) return;setReleaseExit(true);- // Get the current meta theme color and create color steps from it to nonTransparentOverlayColor with non-linear interpolation to ensure same easing as overlay.+ // Get the current meta theme color and create color steps from it to overlayColor with non-linear interpolation to ensure same easing as overlay.const rgbValues = metaThemeColor.getAttribute('content').match(/\d+/g).map(Number);- let colorSteps = interpolateColors(rgbValues, nonTransparentOverlayColor as RGB, 50);+ let colorSteps = interpolateColors(rgbValues, overlayColor as RGB, 50);- if (!isOpen) {+ if (!isOpen && backgroundColor) {colorSteps = interpolateColors(rgbValues, backgroundColor, 50);}- for (let i = 0; i < interpolatedColorsEnter.length; i++) {- setTimeout(() => {- const currentColor = colorSteps[i];-- metaThemeColor.setAttribute('content', `rgb(${currentColor.join(',')})`);-- if (i === interpolatedColorsEnter.length - 1 && initialMetaThemeColor && !isOpen) {- metaThemeColor.setAttribute('content', initialMetaThemeColor as string);- }- }, i * 10.5);- }+ animate(colorSteps);}return { onDrag, onRelease };diff --git a/website/src/app/globals.css b/website/src/app/globals.cssindex 68f9bc6..a14d6f9 100644--- a/website/src/app/globals.css+++ b/website/src/app/globals.css@@ -3,7 +3,9 @@@tailwind utilities;:root {- --vaul-theme-color: 255, 255, 255;+ --vaul-overlay-background: 255, 255, 255;+ --vaul-overlay-background-start: rgba(0, 0, 0, 0);+ --vaul-overlay-background-end: rgba(0, 0, 0, 0.4);}html,