Permalink
Browse files

🐛 `@phenomic/plugin-renderer-react`: Handle scroll like it should (to…

… top or to the hash if any)
  • Loading branch information...
MoOx committed May 11, 2018
1 parent 1b68eff commit d4824c531073e31fa1b74f45bbdaf7db1ba642e3
@@ -0,0 +1,38 @@
// @flow
const lookForElement = (id: string) => {
// id=
const element = document.getElementById(id);
if (element) return element;
// name=
const elementsSet = document.getElementsByName(id);
if (elementsSet.length) return elementsSet[0];
};
let retryTimeout = null;
let retryCount = 0;
const retryDelay = 100;
const retryMax = 1000; // 1000 * retryDelay = retry during 10s in case of slow network
// @todo instead of doing a max number of tries, we could imagine trying every
// x previous delay x 2 (; previous delay = delay x 2)
const moveToHash = (id: string) => {
if (id === "") return;
const element = lookForElement(id);
if (!element && retryCount < retryMax) {
retryTimeout = setTimeout(() => {
retryCount++;
moveToHash(id);
}, retryDelay);
}
if (element) element.scrollIntoView();
};
export default (hash: string) => {
retryCount = 1;
if (retryTimeout) {
clearTimeout(retryTimeout);
}
moveToHash(hash.replace(/^#/, ""));
};
@@ -3,6 +3,8 @@ import * as React from "react";
import PropTypes from "prop-types";
import cx from "classnames";
import moveToHash from "./Link.hash.js";
const BASENAME = process.env.PHENOMIC_APP_BASENAME || "/";
const origin = url =>
@@ -53,6 +55,11 @@ const goToUrl = (event: SyntheticEvent<HTMLAnchorElement>, router: Object) => {
// react-router v4
// $FlowFixMe well it's hard to support 2 APIs ?
router.history.push(route);
// react-router doesn't handle the scroll
// so we scroll to top or move to the hash
if (!hash) window.scrollTo(0, 0);
else moveToHash(hash);
}
};

0 comments on commit d4824c5

Please sign in to comment.