Skip to content

Commit

Permalink
feat: add preventBodyScroll to utils
Browse files Browse the repository at this point in the history
  • Loading branch information
jigsawye committed Apr 2, 2019
1 parent d426099 commit 33eec3a
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 1 deletion.
8 changes: 8 additions & 0 deletions packages/tailor-ui-utils/src/__tests__/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { mergeEventProps, preventBodyScroll } from '..';

describe('index', () => {
it('should export all components', () => {
expect(mergeEventProps).toBeDefined();
expect(preventBodyScroll).toBeDefined();
});
});
3 changes: 2 additions & 1 deletion packages/tailor-ui-utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { default as mergeEventProps } from './mergeEventProps';
export { default as mergeEventProps } from './merge-event-props';
export { default as preventBodyScroll } from './prevent-body-scroll';
35 changes: 35 additions & 0 deletions packages/tailor-ui-utils/src/prevent-body-scroll.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Reference: https://github.com/segmentio/evergreen/blob/master/src/lib/prevent-body-scroll.js
let previousOverflow: string;
let previousPaddingRight: string;

/**
* Toggle the body scroll / overflow and additional styling
* necessary to preserve scroll position and body width (scrollbar replacement)
*
* @param {boolean} preventScroll - whether or not to prevent body scrolling
*/
const preventBodyScroll = (preventScroll: boolean) => {
const { width } = document.body.getBoundingClientRect();

/** Apply or remove overflow style */
if (preventScroll) {
previousOverflow = document.body.style.overflow || '';
document.body.style.overflow = 'hidden';
} else {
document.body.style.overflow = previousOverflow || '';
}

/** Get the _new width_ of the body (this will tell us the scrollbar width) */
const newWidth = document.body.getBoundingClientRect().width;
const scrollBarWidth = newWidth - width;

/** If there's a diff due to scrollbars, then account for it with padding */
if (preventScroll) {
previousPaddingRight = document.body.style.paddingRight || '';
document.body.style.paddingRight = `${Math.max(0, scrollBarWidth || 0)}px`;
} else {
document.body.style.paddingRight = previousPaddingRight || '';
}
};

export default preventBodyScroll;

0 comments on commit 33eec3a

Please sign in to comment.