Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[v3] consider navbar height for the anchor intersection observer #3249

Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/red-squids-enjoy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'nextra-theme-docs': patch
---

Consider the navbar height when setting the root margin for the active anchor intersection observer
2 changes: 0 additions & 2 deletions packages/nextra-theme-docs/src/constants.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ import { getGitIssueUrl, useGitEditUrl } from './utils'

export const DEFAULT_LOCALE = 'en-US'

export const IS_BROWSER = typeof window !== 'undefined'

export type DocsThemeConfig = z.infer<typeof themeSchema>
export type PartialDocsThemeConfig = z.infer<typeof publicThemeSchema>

Expand Down
20 changes: 15 additions & 5 deletions packages/nextra-theme-docs/src/contexts/active-anchor.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type { Dispatch, ReactElement, ReactNode, SetStateAction } from 'react'
import { createContext, useContext, useRef, useState } from 'react'
import { IS_BROWSER } from '../constants'
import { createContext, useContext, useEffect, useRef, useState } from 'react'

type ActiveAnchor = Record<
string,
Expand Down Expand Up @@ -43,7 +42,13 @@ export const ActiveAnchorProvider = ({
}): ReactElement => {
const [activeAnchor, setActiveAnchor] = useState<ActiveAnchor>({})
const observerRef = useRef<IntersectionObserver | null>(null)
if (IS_BROWSER && !observerRef.current) {

useEffect(() => {
if (observerRef.current) return
const nextraContentEl = document.querySelector<HTMLElement>('.nextra-content')
const rootMarginTop = nextraContentEl
? `${0 - nextraContentEl.offsetTop}px`
: '0px'
observerRef.current = new IntersectionObserver(
entries => {
setActiveAnchor(f => {
Expand Down Expand Up @@ -91,11 +96,16 @@ export const ActiveAnchorProvider = ({
})
},
{
rootMargin: '0px 0px -50%',
rootMargin: `${rootMarginTop} 0px -50%`,
threshold: [0, 1]
}
)
}

return () => {
observerRef.current?.disconnect()
observerRef.current = null
}
}, [])
return (
<ActiveAnchorContext.Provider value={activeAnchor}>
<SetActiveAnchorContext.Provider value={setActiveAnchor}>
Expand Down
Loading