Skip to content

Commit

Permalink
🐛 partial fix for glitchy sidebar behaviour
Browse files Browse the repository at this point in the history
  • Loading branch information
ikesau committed Oct 28, 2023
1 parent 90d0efe commit cd85188
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
19 changes: 16 additions & 3 deletions site/TableOfContents.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ interface TableOfContentsData {
headings: TocHeading[]
pageTitle: string
hideSubheadings?: boolean
headingLevels?: {
primary: number
secondary: number
}
}

const isRecordTopViewport = (record: IntersectionObserverEntry) => {
Expand All @@ -34,9 +38,16 @@ export const TableOfContents = ({
headings,
pageTitle,
hideSubheadings,
// Original WP articles used a hierarchy of h2 and h3 headings
// New Gdoc articles use a hierarchy of h1 and h2 headings
headingLevels = {
primary: 2,
secondary: 3,
},
}: TableOfContentsData) => {
const [isOpen, setIsOpen] = useState(false)
const [activeHeading, setActiveHeading] = useState("")
const { primary, secondary } = headingLevels
const tocRef = useRef<HTMLElement>(null)

const toggleIsOpen = () => {
Expand Down Expand Up @@ -108,9 +119,11 @@ export const TableOfContents = ({

let contentHeadings = null
if (hideSubheadings) {
contentHeadings = document.querySelectorAll("h2")
contentHeadings = document.querySelectorAll(`h${secondary}`)
} else {
contentHeadings = document.querySelectorAll("h2, h3")
contentHeadings = document.querySelectorAll(
`h${primary}, h${secondary}`
)
}
contentHeadings.forEach((contentHeading) => {
observer.observe(contentHeading)
Expand All @@ -119,7 +132,7 @@ export const TableOfContents = ({
return () => observer.disconnect()
}
return
}, [headings, hideSubheadings])
}, [headings, hideSubheadings, primary, secondary])

return (
<div className={TOC_WRAPPER_CLASSNAME}>
Expand Down
1 change: 1 addition & 0 deletions site/gdocs/OwidGdoc.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ export function OwidGdoc({
{hasSidebarToc && content.toc ? (
<TableOfContents
headings={content.toc}
headingLevels={{ primary: 1, secondary: 2 }}
pageTitle={content.title || ""}
/>
) : null}
Expand Down

0 comments on commit cd85188

Please sign in to comment.