|
2 | 2 | import { Box, css, Flex, Text, VStack } from '@devup-ui/react' |
3 | 3 | import Link from 'next/link' |
4 | 4 | import { usePathname } from 'next/navigation' |
5 | | -import { useMemo } from 'react' |
| 5 | +import { useEffect, useState } from 'react' |
6 | 6 |
|
7 | 7 | function IndexMenu({ |
8 | 8 | children, |
@@ -44,25 +44,36 @@ export function RightIndex() { |
44 | 44 | return <RightIndexInner key={pathname} editUrl={editUrl} /> |
45 | 45 | } |
46 | 46 |
|
| 47 | +type MenuItem = { |
| 48 | + text: string |
| 49 | + sub: boolean |
| 50 | + onClick: () => void |
| 51 | +} |
| 52 | + |
47 | 53 | function RightIndexInner({ editUrl }: { editUrl: string }) { |
48 | | - const menus = useMemo(() => { |
49 | | - if (typeof document === 'undefined') return [] |
50 | | - const elements = document.querySelectorAll( |
51 | | - '.markdown-body h1, .markdown-body h2', |
52 | | - ) |
53 | | - const menus = [] |
54 | | - for (let i = 0; i < elements.length; i++) { |
55 | | - const element = elements[i] |
56 | | - const text = element.textContent! |
57 | | - menus.push({ |
58 | | - text, |
59 | | - sub: element.tagName === 'H2', |
60 | | - onClick: () => { |
61 | | - element.scrollIntoView({ behavior: 'smooth' }) |
62 | | - }, |
63 | | - }) |
| 54 | + const [menus, setMenus] = useState<MenuItem[]>([]) |
| 55 | + |
| 56 | + useEffect(() => { |
| 57 | + const updateMenus = () => { |
| 58 | + const elements = document.querySelectorAll( |
| 59 | + '.markdown-body h1, .markdown-body h2', |
| 60 | + ) |
| 61 | + const newMenus: MenuItem[] = [] |
| 62 | + for (let i = 0; i < elements.length; i++) { |
| 63 | + const element = elements[i] |
| 64 | + const text = element.textContent! |
| 65 | + newMenus.push({ |
| 66 | + text, |
| 67 | + sub: element.tagName === 'H2', |
| 68 | + onClick: () => { |
| 69 | + element.scrollIntoView({ behavior: 'smooth' }) |
| 70 | + }, |
| 71 | + }) |
| 72 | + } |
| 73 | + setMenus(newMenus) |
64 | 74 | } |
65 | | - return menus |
| 75 | + |
| 76 | + requestAnimationFrame(updateMenus) |
66 | 77 | }, []) |
67 | 78 |
|
68 | 79 | return ( |
|
0 commit comments