|
1 | 1 | import warning from 'warning';
|
2 | 2 |
|
3 |
| -let scrollbarSize; |
| 3 | +let scrollbarVerticalSize; |
| 4 | +let scrollbarHorizontalSize; |
4 | 5 |
|
5 | 6 | // Measure scrollbar width for padding body during modal show/hide
|
6 | 7 | const scrollbarMeasure = {
|
7 | 8 | position: 'absolute',
|
8 | 9 | top: '-9999px',
|
9 | 10 | width: '50px',
|
10 | 11 | height: '50px',
|
11 |
| - overflow: 'scroll', |
12 | 12 | };
|
13 | 13 |
|
14 | 14 | export function measureScrollbar(direction = 'vertical') {
|
15 | 15 | if (typeof document === 'undefined' || typeof window === 'undefined') {
|
16 | 16 | return 0;
|
17 | 17 | }
|
18 |
| - if (scrollbarSize) { |
19 |
| - return scrollbarSize; |
| 18 | + const isVertical = direction === 'vertical'; |
| 19 | + if (isVertical && scrollbarVerticalSize) { |
| 20 | + return scrollbarVerticalSize; |
| 21 | + } else if (!isVertical && scrollbarHorizontalSize) { |
| 22 | + return scrollbarHorizontalSize; |
20 | 23 | }
|
21 | 24 | const scrollDiv = document.createElement('div');
|
22 | 25 | Object.keys(scrollbarMeasure).forEach(scrollProp => {
|
23 | 26 | scrollDiv.style[scrollProp] = scrollbarMeasure[scrollProp];
|
24 | 27 | });
|
| 28 | + // Append related overflow style |
| 29 | + if (isVertical) { |
| 30 | + scrollDiv.style.overflowY = 'scroll'; |
| 31 | + } else { |
| 32 | + scrollDiv.style.overflowX = 'scroll'; |
| 33 | + } |
25 | 34 | document.body.appendChild(scrollDiv);
|
26 | 35 | let size = 0;
|
27 |
| - if (direction === 'vertical') { |
| 36 | + if (isVertical) { |
28 | 37 | size = scrollDiv.offsetWidth - scrollDiv.clientWidth;
|
29 |
| - } else if (direction === 'horizontal') { |
| 38 | + scrollbarVerticalSize = size; |
| 39 | + } else if (!isVertical) { |
30 | 40 | size = scrollDiv.offsetHeight - scrollDiv.clientHeight;
|
| 41 | + scrollbarHorizontalSize = size; |
31 | 42 | }
|
32 | 43 |
|
33 | 44 | document.body.removeChild(scrollDiv);
|
34 |
| - scrollbarSize = size; |
35 |
| - return scrollbarSize; |
| 45 | + return size; |
36 | 46 | }
|
37 | 47 |
|
38 | 48 | export function debounce(func, wait, immediate) {
|
|
0 commit comments