Skip to content

Commit

Permalink
fix: use ponyfill to ensure to scroll to proper section based on URL …
Browse files Browse the repository at this point in the history
…hash on mount

use ponyfill to ensure to scroll to proper section based on URL hash on mount,
see https://rb.gy/p3zql

#1183
  • Loading branch information
acd02 committed Aug 8, 2023
1 parent e9b0039 commit 3fa0bc2
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 48 deletions.
22 changes: 13 additions & 9 deletions documentation/helpers/ToC/index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { cva, cx } from 'class-variance-authority'
import { useEffect, useState } from 'react'
import scrollIntoView from 'scroll-into-view-if-needed'

import { useActiveAnchor } from './useActiveAnchor'
import { usePerformanceObserver } from './usePerformanceObserver'
import { scrollToAnchor } from './utils'

const itemStyle = cva(['block', 'py-sm', ['hover:bg-[#F2F6FF]']], {
Expand All @@ -29,17 +29,21 @@ export const ToC = () => {
setHeadings([...(document.querySelectorAll<HTMLHeadingElement>('h2, h3') || [])])
}, [])

usePerformanceObserver({
callback() {
const scrollTarget = headings.find(
({ id }) => id === window.top?.location.hash.replace('#', '')
)
// scroll to the targeted section based on the URL hash on mount
useEffect(() => {
const scrollTarget = headings.find(
({ id }) => id === window.top?.location.hash.replace('#', '')
)

if (!scrollTarget) return

scrollTarget?.scrollIntoView({
setTimeout(() => {
scrollIntoView(scrollTarget, {
block: 'start',
behavior: 'smooth',
})
},
})
}, 500)
}, [headings])

const activeAnchor = useActiveAnchor(headings)
const activeIndex = headings.findIndex(heading => heading.id === activeAnchor?.id)
Expand Down
39 changes: 0 additions & 39 deletions documentation/helpers/ToC/usePerformanceObserver.ts

This file was deleted.

28 changes: 28 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"@nx/devkit": "^16.5.3",
"@nx/eslint-plugin": "^16.5.3",
"@radix-ui/react-switch": "*",
"scroll-into-view-if-needed": "^3.0.10",
"@spark-ui/cli-utils": "*",
"@storybook/addon-a11y": "^7.1.1",
"@storybook/addon-actions": "^7.1.1",
Expand Down

0 comments on commit 3fa0bc2

Please sign in to comment.