Merge remote-tracking branch 'mmalmi/main'
This commit is contained in:
@ -10,6 +10,34 @@ export interface ModalProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
let scrollbarWidth: number | null = null;
|
||||
|
||||
const getScrollbarWidth = () => {
|
||||
if (scrollbarWidth !== null) {
|
||||
return scrollbarWidth;
|
||||
}
|
||||
|
||||
const outer = document.createElement("div");
|
||||
outer.style.visibility = "hidden";
|
||||
outer.style.width = "100px";
|
||||
|
||||
document.body.appendChild(outer);
|
||||
|
||||
const widthNoScroll = outer.offsetWidth;
|
||||
outer.style.overflow = "scroll";
|
||||
|
||||
const inner = document.createElement("div");
|
||||
inner.style.width = "100%";
|
||||
outer.appendChild(inner);
|
||||
|
||||
const widthWithScroll = inner.offsetWidth;
|
||||
|
||||
outer.parentNode?.removeChild(outer);
|
||||
|
||||
scrollbarWidth = widthNoScroll - widthWithScroll;
|
||||
return scrollbarWidth;
|
||||
};
|
||||
|
||||
export default function Modal(props: ModalProps) {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape" && props.onClose) {
|
||||
@ -19,10 +47,13 @@ export default function Modal(props: ModalProps) {
|
||||
|
||||
useEffect(() => {
|
||||
document.body.classList.add("scroll-lock");
|
||||
document.body.style.paddingRight = `${getScrollbarWidth()}px`;
|
||||
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
|
||||
return () => {
|
||||
document.body.classList.remove("scroll-lock");
|
||||
document.body.style.paddingRight = "";
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, []);
|
||||
|
Reference in New Issue
Block a user