Skip to content

Commit

Permalink
fix(useBodyScrollLock): correctly restore styles (#1950)
Browse files Browse the repository at this point in the history
  • Loading branch information
sofiushko authored Nov 14, 2024
1 parent 60a8b92 commit b41a53a
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions src/hooks/useBodyScrollLock/useBodyScrollLock.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
import React from 'react';

import get from 'lodash/get';
const PROPERTY_PADDING_RIGHT = 'padding-right';
const PROPERTY_PADDING_BOTTOM = 'padding-bottom';
const PROPERTY_OVERFLOW = 'overflow';

const STORED_BODY_STYLE_KEYS = [
PROPERTY_OVERFLOW,
PROPERTY_PADDING_RIGHT,
PROPERTY_PADDING_BOTTOM,
] as const;

const STORED_BODY_STYLE_KEYS = ['overflow', 'paddingRight', 'paddingBottom'] as const;
type StoredBodyStyleKeys = (typeof STORED_BODY_STYLE_KEYS)[number];
type StoredBodyStyle = Partial<Pick<CSSStyleDeclaration, StoredBodyStyleKeys>>;
type StoredBodyStyle = Partial<Record<StoredBodyStyleKeys, string>>;

function getStoredStyles(): StoredBodyStyle {
const styles: StoredBodyStyle = {};

for (const property of STORED_BODY_STYLE_KEYS) {
styles[property] = get(document.body.style, property);
styles[property] = document.body.style.getPropertyValue(property);
}

return styles;
Expand Down Expand Up @@ -53,21 +60,27 @@ function setBodyStyles() {

storedBodyStyle = getStoredStyles();

document.body.style.overflow = 'hidden';
document.body.style.setProperty(PROPERTY_OVERFLOW, 'hidden');

if (yScrollbarWidth) {
document.body.style.paddingRight = `${bodyPadding.right + yScrollbarWidth}px`;
document.body.style.setProperty(
PROPERTY_PADDING_RIGHT,
`${bodyPadding.right + yScrollbarWidth}px`,
);
}
if (xScrollbarWidth) {
document.body.style.paddingBottom = `${bodyPadding.bottom + xScrollbarWidth}px`;
document.body.style.setProperty(
PROPERTY_PADDING_BOTTOM,
`${bodyPadding.bottom + xScrollbarWidth}px`,
);
}
}

function restoreBodyStyles() {
for (const property of STORED_BODY_STYLE_KEYS) {
const storedProperty = storedBodyStyle[property];
if (storedProperty) {
document.body.style[property] = storedProperty;
document.body.style.setProperty(property, storedProperty);
} else {
document.body.style.removeProperty(property);
}
Expand Down

0 comments on commit b41a53a

Please sign in to comment.