Skip to content

Commit

Permalink
fix(utils): skip wasn't working on empty anchors/prefix
Browse files Browse the repository at this point in the history
closes #125
  • Loading branch information
pixelass committed Dec 4, 2019
1 parent 9f09ade commit c596fe6
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 18 deletions.
5 changes: 3 additions & 2 deletions guide/creating-plugins/src/skip.tsx
Expand Up @@ -3,16 +3,17 @@ import { assert, scrollTo } from "@stickyroll/utils";
import React from "react";

export const SkipBase = props => {
const glue = props.prefix === "" ? "" : "/";
const handleClick = (e): void => {
e.preventDefault();
scrollTo(`${props.prefix}/skip`, e.target as HTMLAnchorElement, {
scrollTo(`${props.prefix}${glue}skip`, e.target as HTMLAnchorElement, {
noFocus: true,
noHash: true
});
};

return (
<a href={`#${props.prefix}/skip`} onClick={handleClick}>
<a href={`#${props.prefix}${glue}skip`} onClick={handleClick}>
Skip
</a>
);
Expand Down
30 changes: 14 additions & 16 deletions packages/utils/src/scroll-to.ts
Expand Up @@ -19,26 +19,24 @@ export const scrollTo = (
target: HTMLElement,
options: IScrollToOptions = {}
): void => {
if (!options.noHash) {
window.location.hash = hash;
}
const {hash: currentHash} = window.location
const currentHashTarget = currentHash.split("/").reverse()[0];

const el = document.getElementById(hash);
if (!options.noFocus) {
target.focus();
}

// Attempted to implement smooth scrolling if the page changes by one position.
// The page jumps in several state changes
// @todo Fix unless a browser bug exists.
// const index = parseInt(hash.split("/").reverse()[0], 10) - 1;
// const diff = Math.abs(index - page);
// document.documentElement.style["scroll-behavior"] = diff > 1 ? "auto" : "smooth";

const hashTarget = hash.split("/").reverse()[0];
const wasSkip = currentHashTarget === "skip";
const isSkip = hashTarget === "skip";
const index = isSkip ? -1 : parseInt(hashTarget, 10);
const currentIndex = wasSkip ? -1 : parseInt(currentHashTarget, 10);
const diff = index > 0 && currentIndex > 0 ? Math.abs(index - currentIndex) : -1;
const shouldJump = isSkip || (diff !== 1);
document.documentElement.style["scroll-behavior"] = shouldJump ? "auto" : "smooth";
el.scrollIntoView(true);

// Optionally if Element.scrollIntoView does not return the expected result.
// const {top: tEl} = el.getBoundingClientRect();
// const {top: tBody} = document.body.getBoundingClientRect();
// const offset = tEl - tBody;
// window.scrollTo(0, offset);
if (!options.noHash) {
window.location.hash = hash;
}
};

0 comments on commit c596fe6

Please sign in to comment.