fix(v2): unify anchor behavior (#2162)

* fix(v2): unify anchor behavior

* fix(v2): use activeElement

* fix(v2): add support for sticky header

* Fix highlighted anchor if non-hidable navbar enabled
This commit is contained in:
Alexey Pyltsyn 2020-01-23 19:06:51 +03:00 committed by GitHub
parent c0c0ad6661
commit 155539421b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 57 additions and 28 deletions

View file

@ -8,16 +8,34 @@
/* eslint-disable jsx-a11y/anchor-has-content, jsx-a11y/anchor-is-valid */
import React from 'react';
import classnames from 'classnames';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import './styles.css';
import styles from './styles.module.css';
const Heading = Tag =>
function TargetComponent({id, ...props}) {
const {
siteConfig: {
themeConfig: {navbar: {hideOnScroll = false} = {}} = {},
} = {},
} = useDocusaurusContext();
const Heading = Tag => ({id, ...props}) => {
if (!id) {
return <Tag {...props} />;
}
return (
<Tag {...props}>
<a aria-hidden="true" tabIndex="-1" className="anchor" id={id} />
<a
aria-hidden="true"
tabIndex="-1"
className={classnames('anchor', {
[styles.enhancedAnchor]: !hideOnScroll,
})}
id={id}
/>
<a
aria-hidden="true"
tabIndex="-1"
@ -29,6 +47,6 @@ const Heading = Tag => ({id, ...props}) => {
{props.children}
</Tag>
);
};
};
export default Heading;

View file

@ -8,13 +8,8 @@
.anchor {
display: block;
position: relative;
top: -5rem;
}
@media only screen and (max-width: 735px) {
.anchor {
top: -10rem;
}
top: -0.5rem;
outline: none;
}
.hash-link {

View file

@ -0,0 +1,7 @@
.enhancedAnchor:target:before {
content: '';
display: block;
height: var(--ifm-navbar-height);
margin: calc(var(--ifm-navbar-height) * -1) 0 0;
visibility: hidden;
}

View file

@ -21,13 +21,22 @@ const useHideableNavbar = hideOnScroll => {
const handleScroll = () => {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const documentHeight = document.documentElement.scrollHeight - navbarHeight;
const windowHeight = window.innerHeight;
if (scrollTop < navbarHeight) {
return;
}
const focusedElement = document.activeElement;
if (focusedElement && /^#/.test(window.location.hash)) {
setIsNavbarVisible(false);
focusedElement.blur();
return;
}
const documentHeight = document.documentElement.scrollHeight - navbarHeight;
const windowHeight = window.innerHeight;
if (lastScrollTop && scrollTop > lastScrollTop) {
setIsNavbarVisible(false);
} else if (scrollTop + windowHeight < documentHeight) {