Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

fix: blog auto scroll post app router migration for blog (#41220)

Jonathan Summers-Muir0956558eeaaa
diff --git a/apps/www/app/blog/[slug]/BlogPostClient.tsx b/apps/www/app/blog/[slug]/BlogPostClient.tsx
index 8a70fad252e..8da4126fae2 100644
--- a/apps/www/app/blog/[slug]/BlogPostClient.tsx
+++ b/apps/www/app/blog/[slug]/BlogPostClient.tsx
@@ -9,6 +9,7 @@ import { CMS_SITE_ORIGIN } from 'lib/constants'
import { isNotNullOrUndefined } from 'lib/helpers'
import { generateTocFromMarkdown } from 'lib/toc'
import { convertRichTextToMarkdown } from '~/lib/cms/convertRichTextToMarkdown'
+import useActiveAnchors from 'hooks/useActiveAnchors'
import type { Blog, BlogData, CMSAuthor, PostReturnType, ProcessedBlogData } from 'types/post'
@@ -27,6 +28,10 @@ type BlogPostPageProps = {
export default function BlogPostClient(props: BlogPostPageProps) {
const isDraftMode = props.isDraftMode
const [previewData] = useState<ProcessedBlogData>(props.blog)
+
+ // Enable scroll-to-anchor functionality and TOC highlighting
+ useActiveAnchors()
+
const [processedToc, setProcessedToc] = useState<{ content: string; json: any[] } | null>(null)
const shouldUseLivePreview = isDraftMode && 'isCMS' in props.blog && props.blog.isCMS
diff --git a/apps/www/hooks/useActiveAnchors.tsx b/apps/www/hooks/useActiveAnchors.tsx
index dbea06b8611..f851394abb0 100644
--- a/apps/www/hooks/useActiveAnchors.tsx
+++ b/apps/www/hooks/useActiveAnchors.tsx
@@ -1,33 +1,69 @@
'use client'
-import { useRouter } from 'next/router'
import { useEffect, useRef } from 'react'
import { isBrowser, stripEmojis } from '~/lib/helpers'
-const useActiveAnchors = (
- anchorsQuerySelector: string = 'h2',
- tocQuerySelector: string = '.prose-toc a',
- offset: number = 200
-) => {
- const router = useRouter()
- const anchors = useRef<NodeListOf<HTMLHeadingElement> | null>(null)
- const toc = useRef<NodeListOf<HTMLHeadingElement> | null>(null)
-
- const handleScroll = () => {
- const pageYOffset = window.pageYOffset
- let newActiveAnchor: string = ''
-
- anchors.current?.forEach((anchor) => {
- if (pageYOffset >= anchor.offsetTop - offset) {
+interface UseActiveAnchorsOptions {
+ /** CSS selector for heading elements to track */
+ anchorsSelector?: string
+ /** CSS selector for TOC anchor links */
+ tocSelector?: string
+ /** Pixel offset from top of viewport for activation threshold */
+ offset?: number
+}
+
+/**
+ * Hook to handle Table of Contents (TOC) functionality for blog posts.
+ *
+ * Provides two main features:
+ * 1. **TOC highlighting**: Highlights the active TOC link based on scroll position
+ * by adding/removing the `toc-animate` CSS class.
+ * 2. **Hash scrolling**: Smoothly scrolls to the target heading when the page
+ * loads with a URL hash (e.g., `/blog/post#section-name`).
+ *
+ * @param options - Configuration options for the hook
+ *
+ * @example
+ * ```tsx
+ * // Basic usage with defaults
+ * useActiveAnchors()
+ *
+ * // Custom selectors and offset
+ * useActiveAnchors({
+ * anchorsSelector: 'h2, h3',
+ * tocSelector: '.custom-toc a',
+ * offset: 150
+ * })
+ * ```
+ */
+const useActiveAnchors = (options: UseActiveAnchorsOptions = {}): void => {
+ const { anchorsSelector = 'h2', tocSelector = '.prose-toc a', offset = 200 } = options
+
+ const anchorsRef = useRef<NodeListOf<HTMLHeadingElement> | null>(null)
+ const tocRef = useRef<NodeListOf<HTMLAnchorElement> | null>(null)
+
+ /**
+ * Scroll event handler that determines which heading is currently in view
+ * and updates the corresponding TOC link with the `toc-animate` class.
+ */
+ const handleScroll = (): void => {
+ const scrollY = window.scrollY
+ let newActiveAnchor = ''
+
+ // Find the heading that's currently scrolled past
+ anchorsRef.current?.forEach((anchor) => {
+ if (scrollY >= anchor.offsetTop - offset) {
newActiveAnchor = anchor.id
}
})
- toc.current?.forEach((link) => {
+ // Update TOC link styles based on active heading
+ tocRef.current?.forEach((link) => {
link.classList.remove('toc-animate')
- // Need to decodeURI the href to get emojis, then strip them off and remove "--""
- // to make toc hrefs and content headings ids match
+ // Normalize both href and heading id for comparison:
+ // - Decode URI to handle emojis
+ // - Strip emojis and dashes to handle edge cases
const sanitizedHref = stripEmojis(
decodeURI(link.getAttribute('href') ?? '').replace('#', '')
).replaceAll('-', '')
@@ -39,19 +75,39 @@ const useActiveAnchors = (
})
}
+ /**
+ * Handles initial scroll to anchor when page loads with a URL hash.
+ * This is necessary because dynamically loaded content may not exist
+ * when the browser's native hash scrolling occurs.
+ */
+ const handleHashScroll = (): void => {
+ if (!window.location.hash) return
+
+ const targetId = window.location.hash.slice(1)
+ const targetElement = document.getElementById(targetId)
+
+ if (targetElement) {
+ targetElement.scrollIntoView({ behavior: 'smooth' })
+ }
+ }
+
useEffect(() => {
- if (!isBrowser || !router.isReady) return
- anchors.current = document.querySelectorAll(anchorsQuerySelector)
- toc.current = document.querySelectorAll(tocQuerySelector)
+ if (!isBrowser) return
+ // Query and cache heading elements and TOC links
+ anchorsRef.current = document.querySelectorAll(anchorsSelector)
+ tocRef.current = document.querySelectorAll(tocSelector)
+
+ // Scroll to hash target on initial load
+ handleHashScroll()
+
+ // Listen for scroll to update active TOC link
window.addEventListener('scroll', handleScroll)
return () => {
window.removeEventListener('scroll', handleScroll)
}
- }, [router])
-
- return null
+ }, [anchorsSelector, tocSelector, offset])
}
export default useActiveAnchors