docs: scroll to widget on load, fix widget navigation history (#3441)

This commit is contained in:
Erez Rokah 2020-03-19 16:07:21 +02:00 committed by GitHub
parent 9087da5850
commit a4a036fe05
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 16 additions and 10 deletions

View File

@ -4,4 +4,4 @@
publish = "dist/"
[build.environment]
NODE_VERSION = "8"
NODE_VERSION = "12"

View File

@ -1,4 +1,4 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useRef } from 'react';
import styled from '@emotion/styled';
import WidgetDoc from './widget-doc';
@ -21,20 +21,26 @@ const WidgetsContent = styled.div`
border-radius: 4px;
`;
const Widgets = ({ widgets }) => {
const Widgets = ({ widgets, location }) => {
const initialLoadRef = useRef(true);
const navRef = useRef(null);
const [currentWidget, setWidget] = useState(null);
useEffect(() => {
const hash = window.location.hash ? window.location.hash.replace('#', '') : '';
const hash = location.hash ? location.hash.replace('#', '') : '';
const widgetsContainHash = widgets.edges.some(w => w.node.frontmatter.title === hash);
if (widgetsContainHash) {
return setWidget(hash);
setWidget(hash);
if (initialLoadRef.current) {
navRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
} else {
setWidget(widgets.edges[0].node.frontmatter.title);
}
setWidget(widgets.edges[0].node.frontmatter.title);
}, []);
initialLoadRef.current = false;
}, [widgets, location.hash]);
const handleWidgetChange = (event, title) => {
event.preventDefault();
@ -46,7 +52,7 @@ const Widgets = ({ widgets }) => {
return (
<section>
<WidgetsNav>
<WidgetsNav ref={navRef}>
{widgets.edges.map(({ node }) => {
const { label, title } = node.frontmatter;
return (

View File

@ -48,7 +48,7 @@ export const DocsTemplate = ({
{filename && <EditLink collection={`docs_${group}`} filename={filename} />}
<h1>{title}</h1>
<Markdown body={body} html={html} />
{showWidgets && <Widgets widgets={widgets} />}
{showWidgets && <Widgets widgets={widgets} location={location} />}
</article>
</SidebarLayout>
</Container>