-
-
Notifications
You must be signed in to change notification settings - Fork 345
Expand file tree
/
Copy pathuse-scale-background.ts
More file actions
60 lines (52 loc) · 2.32 KB
/
use-scale-background.ts
File metadata and controls
60 lines (52 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import React, { useMemo } from 'react';
import { useDrawerContext } from './context';
import { assignStyle, chain, isVertical, reset } from './helpers';
import { BORDER_RADIUS, TRANSITIONS, WINDOW_TOP_OFFSET } from './constants';
const noop = () => () => {};
export function useScaleBackground() {
const { direction, isOpen, shouldScaleBackground, setBackgroundColorOnScale, noBodyStyles } = useDrawerContext();
const timeoutIdRef = React.useRef<number | null>(null);
const initialBackgroundColor = useMemo(() => document.body.style.backgroundColor, []);
function getScale(wrapper: HTMLElement) {
return (wrapper.offsetHeight - WINDOW_TOP_OFFSET) / wrapper.offsetHeight;
}
React.useEffect(() => {
if (isOpen && shouldScaleBackground) {
if (timeoutIdRef.current) clearTimeout(timeoutIdRef.current);
const wrapper =
(document.querySelector('[data-vaul-drawer-wrapper]') as HTMLElement) ||
(document.querySelector('[vaul-drawer-wrapper]') as HTMLElement);
if (!wrapper) return;
chain(
setBackgroundColorOnScale && !noBodyStyles ? assignStyle(document.body, { background: 'black' }) : noop,
assignStyle(wrapper, {
transformOrigin: isVertical(direction) ? 'top' : 'left',
transitionProperty: 'transform, border-radius',
transitionDuration: `${TRANSITIONS.DURATION}s`,
transitionTimingFunction: `cubic-bezier(${TRANSITIONS.EASE.join(',')})`,
}),
);
const wrapperStylesCleanup = assignStyle(wrapper, {
borderRadius: `${BORDER_RADIUS}px`,
overflow: 'hidden',
...(isVertical(direction)
? {
transform: `scale(${getScale(wrapper)}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,
}
: {
transform: `scale(${getScale(wrapper)}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,
}),
});
return () => {
wrapperStylesCleanup();
timeoutIdRef.current = window.setTimeout(() => {
if (initialBackgroundColor) {
document.body.style.background = initialBackgroundColor;
} else {
document.body.style.removeProperty('background');
}
}, TRANSITIONS.DURATION * 1000);
};
}
}, [isOpen, shouldScaleBackground, initialBackgroundColor]);
}