react-navi
Version:
A batteries-included router for react.
56 lines • 1.8 kB
JavaScript
import * as React from 'react';
export var HashScrollContext = React.createContext('auto');
export function HashScroll(props) {
if (!props.behavior) {
return React.createElement(React.Fragment, null, props.children);
}
return (React.createElement(HashScrollContext.Provider, { value: props.behavior }, props.children));
}
function smoothScroll(left, top) {
try {
window.scroll({
top: top,
left: left,
behavior: 'smooth',
});
}
catch (e) {
window.scroll(left, top);
}
}
var behaviors = {
none: function () { },
auto: function (hash) {
if (hash) {
var id = document.getElementById(hash.slice(1));
if (id) {
var _a = id.getBoundingClientRect(), top_1 = _a.top, left = _a.left;
window.scroll(left + window.pageXOffset, top_1 + window.pageYOffset);
}
}
else {
window.scroll(0, 0);
}
},
smooth: function (hash) {
if (hash) {
var id = document.getElementById(hash.slice(1));
if (id) {
var _a = id.getBoundingClientRect(), top_2 = _a.top, left = _a.left;
smoothScroll(left + window.pageXOffset, top_2 + window.pageYOffset);
// Focus the element, as default behavior is cancelled.
// https://css-tricks.com/snippets/jquery/smooth-scrolling/
id.focus();
}
}
else {
smoothScroll(0, 0);
}
},
};
export function scrollToHash(hash, behavior) {
if (behavior === void 0) { behavior = 'auto'; }
var fn = typeof behavior === 'string' ? behaviors[behavior] : behavior;
fn(hash);
}
//# sourceMappingURL=HashScroll.js.map