Skip to content

Commit

Permalink
perf: scroll to active tab instead of last added
Browse files Browse the repository at this point in the history
  • Loading branch information
alex-golovanov committed Jan 29, 2025
1 parent 3c6c283 commit 2007e08
Showing 1 changed file with 16 additions and 14 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React, { useEffect, useRef, useState } from "react";
import { noop } from "lodash";
import { usePrevious } from "@mantine/hooks";

import { ScrollArea } from "../ScrollArea";

Expand Down Expand Up @@ -31,9 +30,6 @@ export const DismissibleTabBar = ({
const sentinelLeftRef = useRef<HTMLDivElement | null>(null);
const sentinelRightRef = useRef<HTMLDivElement | null>(null);

const totalChildren = React.Children.count(children);
const prevTotalChildren = usePrevious(totalChildren) ?? totalChildren;

const handleAdd = disableAdd ? noop : onTabAdd;

useEffect(function observeSticky() {
Expand Down Expand Up @@ -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 (
Expand Down

0 comments on commit 2007e08

Please sign in to comment.