Skip to content

Commit 51ba854

Browse files
committed
docs(toc): add onClick logic to properly handle scrollTo with navbarHeight
1 parent db7fa99 commit 51ba854

File tree

1 file changed

+23
-11
lines changed
  • apps/website/src/components/toc

1 file changed

+23
-11
lines changed

apps/website/src/components/toc/toc.tsx

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {
2+
$,
23
QwikIntrinsicElements,
34
component$,
45
useSignal,
@@ -18,7 +19,7 @@ export const DashboardTableOfContents = component$(
1819

1920
return (
2021
<div class="space-y-2">
21-
<p class="font-medium">On This Page</p>
22+
<div class="font-medium">On This Page</div>
2223
<Tree headings={headings} activeItem={activeHeading.value} />
2324
</div>
2425
);
@@ -29,16 +30,15 @@ const useActiveItem = (itemIds: string[]) => {
2930
const activeId = useSignal<string>();
3031

3132
useVisibleTask$(({ cleanup }) => {
32-
const observer = new IntersectionObserver(
33-
(entries) => {
34-
entries.forEach((entry) => {
35-
if (entry.isIntersecting) {
36-
activeId.value = entry.target.id;
37-
}
38-
});
39-
},
40-
{ rootMargin: `0% 0% -80% 0%` },
41-
);
33+
const observer = new IntersectionObserver((entries) => {
34+
entries.forEach((entry) => {
35+
if (entry.isIntersecting) {
36+
console.log('entry: ', entry.isIntersecting, entry.target.id);
37+
activeId.value = entry.target.id;
38+
}
39+
});
40+
});
41+
console.log('observer: ', observer);
4242

4343
itemIds.forEach((id) => {
4444
const element = document.getElementById(id);
@@ -67,13 +67,25 @@ type TreeProps = QwikIntrinsicElements['ul'] & {
6767
};
6868

6969
const Tree = component$<TreeProps>(({ headings, level = 1, activeItem }) => {
70+
console.log('level: ', level);
7071
return headings.length > 0 && level < 3 ? (
7172
<ul class={cn('m-0 list-none', { 'pl-4': level !== 1 })}>
7273
{headings.map((heading) => {
7374
return (
7475
<li key={heading.id} class={cn('mt-0 pt-2')}>
7576
<a
7677
href={`#${heading.id}`}
78+
onClick$={[
79+
$(() => {
80+
const element = document.getElementById(heading.id);
81+
if (element) {
82+
const navbarHeight = 90;
83+
const elementPosition =
84+
element.getBoundingClientRect().top + window.scrollY - navbarHeight;
85+
window.scrollTo({ top: elementPosition, behavior: 'auto' });
86+
}
87+
}),
88+
]}
7789
class={cn(
7890
heading.level > 2 ? 'ml-4' : null,
7991
'inline-block no-underline transition-colors hover:text-foreground',

0 commit comments

Comments
 (0)