Skip to content

Commit

Permalink
fix: query selectors should never have empty id (#1515)
Browse files Browse the repository at this point in the history
  • Loading branch information
abvthecity committed Sep 20, 2024
1 parent f5f1f87 commit d47b39d
Showing 1 changed file with 17 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,15 @@ export function useTableOfContentsObserver(ids: string[], setActiveId: (id: stri
const intersectionTop = scrollY + rootTop;
const intersectionBottom = scrollY + rootTop + clientHeight;

// when the user scrolls to the very top of the page, set the anchorInView to the first anchor
if (scrollY === 0) {
const firstAnchor = ids[0];
if (firstAnchor) {
setActiveId(firstAnchor);
}
return;
}

// when the user scrolls to the very bottom of the page, set the anchorInView to the last anchor
const lastAnchor = ids[ids.length - 1];
if (scrollHeight - clientHeight <= scrollY) {
Expand Down Expand Up @@ -99,9 +108,14 @@ export function useTableOfContentsObserver(ids: string[], setActiveId: (id: stri
const scrollY = root instanceof Document ? window.scrollY : root.scrollTop;
const top = root instanceof Document ? 0 : root.getBoundingClientRect().top;
try {
idToYRef.current = Array.from(document.querySelectorAll(ids.map(toIdQuerySelector).join(", "))).reduce<
Record<string, number>
>((prev, curr) => {
idToYRef.current = Array.from(
document.querySelectorAll(
ids
.filter((id) => id.trim().length > 0)
.map(toIdQuerySelector)
.join(", "),
),
).reduce<Record<string, number>>((prev, curr) => {
prev[curr.id] = curr.getBoundingClientRect().top + scrollY - top;
return prev;
}, {});
Expand Down

0 comments on commit d47b39d

Please sign in to comment.