react-navi
Version:
A batteries-included router for react.
67 lines • 2.23 kB
JavaScript
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));
exports.HashScrollContext = React.createContext('auto');
function HashScroll(props) {
if (!props.behavior) {
return React.createElement(React.Fragment, null, props.children);
}
return (React.createElement(exports.HashScrollContext.Provider, { value: props.behavior }, props.children));
}
exports.HashScroll = HashScroll;
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);
}
},
};
function scrollToHash(hash, behavior) {
if (behavior === void 0) { behavior = 'auto'; }
var fn = typeof behavior === 'string' ? behaviors[behavior] : behavior;
fn(hash);
}
exports.scrollToHash = scrollToHash;
//# sourceMappingURL=HashScroll.js.map
;