UNPKG

2.52 kBJavaScriptView Raw
1/* eslint-disable no-param-reassign */
2import { removeCSS, updateCSS } from "./Dom/dynamicCSS";
3var cached;
4function measureScrollbarSize(ele) {
5 var randomId = "rc-scrollbar-measure-".concat(Math.random().toString(36).substring(7));
6 var measureEle = document.createElement('div');
7 measureEle.id = randomId;
8
9 // Create Style
10 var measureStyle = measureEle.style;
11 measureStyle.position = 'absolute';
12 measureStyle.left = '0';
13 measureStyle.top = '0';
14 measureStyle.width = '100px';
15 measureStyle.height = '100px';
16 measureStyle.overflow = 'scroll';
17
18 // Clone Style if needed
19 var fallbackWidth;
20 var fallbackHeight;
21 if (ele) {
22 var targetStyle = getComputedStyle(ele);
23 measureStyle.scrollbarColor = targetStyle.scrollbarColor;
24 measureStyle.scrollbarWidth = targetStyle.scrollbarWidth;
25
26 // Set Webkit style
27 var webkitScrollbarStyle = getComputedStyle(ele, '::-webkit-scrollbar');
28 var width = parseInt(webkitScrollbarStyle.width, 10);
29 var height = parseInt(webkitScrollbarStyle.height, 10);
30
31 // Try wrap to handle CSP case
32 try {
33 var widthStyle = width ? "width: ".concat(webkitScrollbarStyle.width, ";") : '';
34 var heightStyle = height ? "height: ".concat(webkitScrollbarStyle.height, ";") : '';
35 updateCSS("\n#".concat(randomId, "::-webkit-scrollbar {\n").concat(widthStyle, "\n").concat(heightStyle, "\n}"), randomId);
36 } catch (e) {
37 // Can't wrap, just log error
38 console.error(e);
39
40 // Get from style directly
41 fallbackWidth = width;
42 fallbackHeight = height;
43 }
44 }
45 document.body.appendChild(measureEle);
46
47 // Measure. Get fallback style if provided
48 var scrollWidth = ele && fallbackWidth && !isNaN(fallbackWidth) ? fallbackWidth : measureEle.offsetWidth - measureEle.clientWidth;
49 var scrollHeight = ele && fallbackHeight && !isNaN(fallbackHeight) ? fallbackHeight : measureEle.offsetHeight - measureEle.clientHeight;
50
51 // Clean up
52 document.body.removeChild(measureEle);
53 removeCSS(randomId);
54 return {
55 width: scrollWidth,
56 height: scrollHeight
57 };
58}
59export default function getScrollBarSize(fresh) {
60 if (typeof document === 'undefined') {
61 return 0;
62 }
63 if (fresh || cached === undefined) {
64 cached = measureScrollbarSize();
65 }
66 return cached.width;
67}
68export function getTargetScrollBarSize(target) {
69 if (typeof document === 'undefined' || !target || !(target instanceof Element)) {
70 return {
71 width: 0,
72 height: 0
73 };
74 }
75 return measureScrollbarSize(target);
76}
\No newline at end of file