|
1
|
"use client" |
|
2
|
|
|
3
|
import { useEffect } from "react" |
|
4
|
import { useScrollController } from "docs-ui" |
|
5
|
|
|
6
|
type ScrollToSectionProps = { |
|
7
|
slug: string |
|
8
|
} |
|
9
|
|
|
10
|
/** |
|
11
|
* Scrolls the intro section with the given heading `id` into view on load, |
|
12
|
* used by the intro-section pages (`/[area]/[section]`) which render the full |
|
13
|
* intro content and focus one section. |
|
14
|
*/ |
|
15
|
const ScrollToSection = ({ slug }: ScrollToSectionProps) => { |
|
16
|
const { scrollToElement, scrollableElement } = useScrollController() |
|
17
|
|
|
18
|
useEffect(() => { |
|
19
|
if (!scrollableElement) { |
|
20
|
return |
|
21
|
} |
|
22
|
|
|
23
|
let cancelled = false |
|
24
|
const attempt = (tries = 0) => { |
|
25
|
if (cancelled) { |
|
26
|
return |
|
27
|
} |
|
28
|
const el = document.getElementById(slug) |
|
29
|
if (el) { |
|
30
|
scrollToElement((el.offsetParent as HTMLElement) || el) |
|
31
|
} else if (tries < 20) { |
|
32
|
setTimeout(() => attempt(tries + 1), 100) |
|
33
|
} |
|
34
|
} |
|
35
|
attempt() |
|
36
|
|
|
37
|
return () => { |
|
38
|
cancelled = true |
|
39
|
} |
|
40
|
}, [slug, scrollableElement]) |
|
41
|
|
|
42
|
return null |
|
43
|
} |
|
44
|
|
|
45
|
export default ScrollToSection |