Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(useBodyScrollLock): correctly restore styles #1950

Merged
merged 2 commits into from
Nov 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading