Skip to content

Commit

Permalink
Merge pull request #984 from PaloAltoNetworks/fix-code-snippet-scroll
Browse files Browse the repository at this point in the history
Use scrollLeft to avoid scrolling entire page to active code tab
  • Loading branch information
sserrata authored Oct 4, 2024
2 parents 0063174 + 1337735 commit 6f7b058
Showing 1 changed file with 22 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,19 +44,34 @@ function TabList({
tabValues,
}: CodeTabsProps & ReturnType<typeof useTabs>) {
const tabRefs = useRef<(HTMLLIElement | null)[]>([]);
const tabsScrollContainerRef = useRef<any>();
const { blockElementScrollPositionUntilNextRender } =
useScrollPositionBlocker();

useEffect(() => {
const activeTab = tabRefs.current.find(
(tab) => tab?.getAttribute("aria-selected") === "true"
);
if (activeTab) {
activeTab.scrollIntoView({
behavior: "auto",
block: "center",
inline: "start",
});

if (activeTab && tabsScrollContainerRef.current) {
const container = tabsScrollContainerRef.current;
const containerRect = container.getBoundingClientRect();
const activeTabRect = activeTab.getBoundingClientRect();

// Calculate the distance to scroll to align active tab to the left
const glowOffset = 3;
const scrollOffset =
activeTabRect.left -
containerRect.left +
container.scrollLeft -
glowOffset;

// Check if the active tab is not already at the left position

if (Math.abs(scrollOffset - container.scrollLeft) > 4) {
// Adjust the scroll of the container
container.scrollLeft = scrollOffset;
}
}
}, []);

Expand Down Expand Up @@ -139,6 +154,7 @@ function TabList({
},
className
)}
ref={tabsScrollContainerRef}
>
{tabValues.map(({ value, label, attributes }) => (
<li
Expand Down

0 comments on commit 6f7b058

Please sign in to comment.