UNPKG

2.66 kBJavaScriptView Raw
1// Based on https://github.com/react-bootstrap/dom-helpers/blob/master/src/util/inDOM.js
2var inDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
3var cachedType;
4export function _setScrollType(type) {
5 cachedType = type;
6}
7// Based on the jquery plugin https://github.com/othree/jquery.rtl-scroll-type
8export function detectScrollType() {
9 if (cachedType) {
10 return cachedType;
11 }
12 if (!inDOM || !window.document.body) {
13 return 'indeterminate';
14 }
15 var dummy = window.document.createElement('div');
16 dummy.appendChild(document.createTextNode('ABCD'));
17 dummy.dir = 'rtl';
18 dummy.style.fontSize = '14px';
19 dummy.style.width = '4px';
20 dummy.style.height = '1px';
21 dummy.style.position = 'absolute';
22 dummy.style.top = '-1000px';
23 dummy.style.overflow = 'scroll';
24 document.body.appendChild(dummy);
25 cachedType = 'reverse';
26 if (dummy.scrollLeft > 0) {
27 cachedType = 'default';
28 }
29 else {
30 dummy.scrollLeft = 2;
31 if (dummy.scrollLeft < 2) {
32 cachedType = 'negative';
33 }
34 }
35 document.body.removeChild(dummy);
36 return cachedType;
37}
38// Based on https://stackoverflow.com/a/24394376
39export function getNormalizedScrollLeft(element, direction) {
40 var scrollLeft = element.scrollLeft;
41 // Perform the calculations only when direction is rtl to avoid messing up the ltr behavior
42 if (direction !== 'rtl') {
43 return scrollLeft;
44 }
45 var type = detectScrollType();
46 if (type === 'indeterminate') {
47 return Number.NaN;
48 }
49 switch (type) {
50 case 'negative':
51 return element.scrollWidth - element.clientWidth + scrollLeft;
52 case 'reverse':
53 return element.scrollWidth - element.clientWidth - scrollLeft;
54 }
55 return scrollLeft;
56}
57export function setNormalizedScrollLeft(element, scrollLeft, direction) {
58 // Perform the calculations only when direction is rtl to avoid messing up the ltr behavior
59 if (direction !== 'rtl') {
60 element.scrollLeft = scrollLeft;
61 return;
62 }
63 var type = detectScrollType();
64 if (type === 'indeterminate') {
65 return;
66 }
67 switch (type) {
68 case 'negative':
69 element.scrollLeft = element.clientWidth - element.scrollWidth + scrollLeft;
70 break;
71 case 'reverse':
72 element.scrollLeft = element.scrollWidth - element.clientWidth - scrollLeft;
73 break;
74 default:
75 element.scrollLeft = scrollLeft;
76 break;
77 }
78}