Skip to content

Commit

Permalink
fix(useBodyScrollLock): avoid settings unrelated styles (#1832)
Browse files Browse the repository at this point in the history
  • Loading branch information
StepanKirichenko authored Oct 15, 2024
1 parent c587116 commit 9d7fd36
Showing 1 changed file with 26 additions and 6 deletions.
32 changes: 26 additions & 6 deletions src/hooks/useBodyScrollLock/useBodyScrollLock.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,29 @@
import React from 'react';

import get from 'lodash/get';

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

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

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

return styles;
}

export interface UseBodyScrollLockProps {
enabled: boolean;
}

export type BodyScrollLockProps = UseBodyScrollLockProps;

let locks = 0;
let storedBodyStyle: string | undefined;
let storedBodyStyle: StoredBodyStyle = {};

export function useBodyScrollLock({enabled}: UseBodyScrollLockProps) {
React.useLayoutEffect(() => {
Expand Down Expand Up @@ -35,7 +51,8 @@ function setBodyStyles() {
const xScrollbarWidth = getXScrollbarWidth();
const bodyPadding = getBodyComputedPadding();

storedBodyStyle = document.body.style.cssText;
storedBodyStyle = getStoredStyles();

document.body.style.overflow = 'hidden';

if (yScrollbarWidth) {
Expand All @@ -47,10 +64,13 @@ function setBodyStyles() {
}

function restoreBodyStyles() {
if (storedBodyStyle) {
document.body.style.cssText = storedBodyStyle;
} else {
document.body.removeAttribute('style');
for (const property of STORED_BODY_STYLE_KEYS) {
const storedProperty = storedBodyStyle[property];
if (storedProperty) {
document.body.style[property] = storedProperty;
} else {
document.body.style.removeProperty(property);
}
}
}

Expand Down

0 comments on commit 9d7fd36

Please sign in to comment.