Skip to content
Open
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
25 changes: 21 additions & 4 deletions packages/mui-utils/src/getScrollbarSize/getScrollbarSize.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,24 @@
// A change of the browser zoom change the scrollbar size.
// Credit https://github.com/twbs/bootstrap/blob/488fd8afc535ca3a6ad4dc581f5e89217b6a36ac/js/src/util/scrollbar.js#L14-L18
// Credit https://github.com/twbs/bootstrap/blob/0907244256d923807c3a4e55f4ea606b9558d0ca/js/modal.js#L214-L221
// and https://github.com/twbs/bootstrap/blob/0907244256d923807c3a4e55f4ea606b9558d0ca/less/modals.less#L122-L128
export default function getScrollbarSize(win: Window = window): number {
// https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth#usage_notes
const documentWidth = win.document.documentElement.clientWidth;
return win.innerWidth - documentWidth;
const scrollDiv = win.document.createElement('div');

scrollDiv.style.setProperty('position', 'absolute');
scrollDiv.style.setProperty('top', '-9999px');
scrollDiv.style.setProperty('width', '50px');
scrollDiv.style.setProperty('height', '50px');
scrollDiv.style.setProperty('overflow', 'scroll');
// Invert the zoom level to get 100% sized scrollbars for the element
scrollDiv.style.setProperty('zoom', `${1 / win.devicePixelRatio}`);

win.document.body.append(scrollDiv);

const unZoomedScrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;

win.document.body.removeChild(scrollDiv);

const zoomedScrollbarWidth = unZoomedScrollbarWidth / win.devicePixelRatio;

return zoomedScrollbarWidth;
}
Loading