diff options
author | 2021-06-11 16:33:36 -0400 | |
---|---|---|
committer | 2021-06-11 16:33:36 -0400 | |
commit | 7d719ff75d75143f0dfe54dd00bab53e2a27aa2b (patch) | |
tree | a002aa5391c79955d77d2edc198200946da640ef /docs-www/src/components/DocSidebar.tsx | |
parent | 8d72862a98852e340d0484e3a0fdba2380568c2c (diff) | |
download | astro-7d719ff75d75143f0dfe54dd00bab53e2a27aa2b.tar.gz astro-7d719ff75d75143f0dfe54dd00bab53e2a27aa2b.tar.zst astro-7d719ff75d75143f0dfe54dd00bab53e2a27aa2b.zip |
Create initial docs site (#389)
* create initial docs site
* change copy for title and header to say Astro Docs
* create initial docs site
* remove text merge changes
* change workspaceRoot and remove yarn.lock from docs-www
* add docs-www to workspace
Co-authored-by: Kitto Khrangtong <kitto@queensboro.com>
Diffstat (limited to 'docs-www/src/components/DocSidebar.tsx')
-rw-r--r-- | docs-www/src/components/DocSidebar.tsx | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/docs-www/src/components/DocSidebar.tsx b/docs-www/src/components/DocSidebar.tsx new file mode 100644 index 000000000..076d460cc --- /dev/null +++ b/docs-www/src/components/DocSidebar.tsx @@ -0,0 +1,61 @@ +import type { FunctionalComponent } from 'preact'; +import { h } from 'preact'; +import { useState, useEffect, useRef } from 'preact/hooks'; +import EditOnGithub from './EditOnGithub'; + +const DocSidebar: FunctionalComponent<{ headers: any[]; editHref: string }> = ({ headers = [], editHref }) => { + const itemOffsets = useRef([]); + const [activeId, setActiveId] = useState<string>(undefined); + + useEffect(() => { + const getItemOffsets = () => { + const titles = document.querySelectorAll('article :is(h2, h3, h4)'); + itemOffsets.current = Array.from(titles).map((title) => ({ + id: title.id, + topOffset: title.getBoundingClientRect().top + window.scrollY, + })); + }; + + const onScroll = () => { + const itemIndex = itemOffsets.current.findIndex((item) => item.topOffset > window.scrollY + window.innerHeight / 3); + if (itemIndex === 0) { + setActiveId(undefined); + } else if (itemIndex === -1) { + setActiveId(itemOffsets.current[itemOffsets.current.length - 1].id); + } else { + setActiveId(itemOffsets.current[itemIndex - 1].id); + } + }; + + getItemOffsets(); + window.addEventListener('resize', getItemOffsets); + window.addEventListener('scroll', onScroll); + + return () => { + window.removeEventListener('resize', getItemOffsets); + window.removeEventListener('scroll', onScroll); + }; + }, []); + + return ( + <nav> + <div> + <h4>Contents</h4> + <ul> + {headers + .filter(({ depth }) => depth > 1 && depth < 5) + .map((header) => ( + <li class={`header-link depth-${header.depth} ${activeId === header.slug ? 'active' : ''}`.trim()}> + <a href={`#${header.slug}`}>{header.text}</a> + </li> + ))} + </ul> + </div> + <div> + <EditOnGithub href={editHref} /> + </div> + </nav> + ); +}; + +export default DocSidebar; |