forked from flyingant/react-scroll-to-component-ssr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
32 lines (30 loc) · 1.34 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var ReactDOM = require('react-dom');
var scroll = require('ssr-scroll-to');
function calculateScrollOffset(element, offset, alignment) {
var body = document.body,
html = document.documentElement;
var elementRect = element.getBoundingClientRect();
var clientHeight = html.clientHeight;
var documentHeight = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
offset = offset || 0; // additional offset to top
var scrollPosition;
switch(alignment) {
case 'top': scrollPosition = elementRect.top; break;
case 'middle': scrollPosition = elementRect.bottom - clientHeight / 2 - elementRect.height / 2; break;
case 'bottom': scrollPosition = elementRect.bottom - clientHeight; break;
default: scrollPosition = elementRect.bottom - clientHeight / 2 - elementRect.height / 2; break; //defaul to middle
}
var maxScrollPosition = documentHeight - clientHeight;
return Math.min(scrollPosition + offset + window.pageYOffset,
maxScrollPosition);
}
module.exports = function (ref, options) {
options = options || {
offset: 0,
align: 'middle'
};
var element = ReactDOM.findDOMNode(ref);
if (element === null) return 0;
return scroll(0, calculateScrollOffset(element, options.offset, options.align), options);
};