From d47b39da63683b38d8be473e15acca7b7e60c488 Mon Sep 17 00:00:00 2001 From: Andrew Jiang Date: Fri, 20 Sep 2024 12:18:49 +1000 Subject: [PATCH] fix: query selectors should never have empty id (#1515) --- .../useTableOfContentsObserver.ts | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/packages/ui/app/src/components/table-of-contents/useTableOfContentsObserver.ts b/packages/ui/app/src/components/table-of-contents/useTableOfContentsObserver.ts index e5f49a185d..5a60f91f9e 100644 --- a/packages/ui/app/src/components/table-of-contents/useTableOfContentsObserver.ts +++ b/packages/ui/app/src/components/table-of-contents/useTableOfContentsObserver.ts @@ -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) { @@ -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 - >((prev, curr) => { + idToYRef.current = Array.from( + document.querySelectorAll( + ids + .filter((id) => id.trim().length > 0) + .map(toIdQuerySelector) + .join(", "), + ), + ).reduce>((prev, curr) => { prev[curr.id] = curr.getBoundingClientRect().top + scrollY - top; return prev; }, {});