From 2007e0891e29e60c82f36f090e1daca029808bf1 Mon Sep 17 00:00:00 2001 From: Alex Golovanov Date: Wed, 29 Jan 2025 13:03:06 +0300 Subject: [PATCH] perf: scroll to active tab instead of last added --- .../src/DismissibleTab/DismissibleTabBar.tsx | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/app/client/packages/design-system/ads/src/DismissibleTab/DismissibleTabBar.tsx b/app/client/packages/design-system/ads/src/DismissibleTab/DismissibleTabBar.tsx index 707d92232634..08e1dfc145f3 100644 --- a/app/client/packages/design-system/ads/src/DismissibleTab/DismissibleTabBar.tsx +++ b/app/client/packages/design-system/ads/src/DismissibleTab/DismissibleTabBar.tsx @@ -1,6 +1,5 @@ import React, { useEffect, useRef, useState } from "react"; import { noop } from "lodash"; -import { usePrevious } from "@mantine/hooks"; import { ScrollArea } from "../ScrollArea"; @@ -31,9 +30,6 @@ export const DismissibleTabBar = ({ const sentinelLeftRef = useRef(null); const sentinelRightRef = useRef(null); - const totalChildren = React.Children.count(children); - const prevTotalChildren = usePrevious(totalChildren) ?? totalChildren; - const handleAdd = disableAdd ? noop : onTabAdd; useEffect(function observeSticky() { @@ -69,17 +65,23 @@ export const DismissibleTabBar = ({ }, []); useEffect( - function scrollAddedTabIntoView() { - const element = sentinelRightRef.current; - - if (element && totalChildren > prevTotalChildren) { - element.scrollIntoView({ - inline: "center", - behavior: "smooth", - }); - } + function debouncedScrollActiveTabIntoView() { + const timerId = setTimeout(() => { + // accessing active tab with a document query is a bit hacky, but it's more performant than keeping a map of refs and cloning children + const activeTab = document.querySelector(".editor-tab.active"); + + if (activeTab) { + activeTab.scrollIntoView({ + behavior: "smooth", + block: "nearest", + inline: "center", + }); + } + }, 100); + + return () => clearTimeout(timerId); }, - [totalChildren, prevTotalChildren], + [children], ); return (