fix(segmentation): Fixed the manual scrolling of the segments list and implemented automatic scrolling to the active segment. (#5510)

The height of the list container is now calculated based on a parent div instead of itself.
DataRow component now has a forward ref to allow for automatic scrolling.

Added better detection to the useDynamicMaxHeight hook for when to recalculate the max height using intersection observers.

The useEffect for scrolling a segment into view used to be excessively called to the point
where it was auto scrolling after the user manually scrolled. The auto scroll useEffect is
now dependent on the segment index changing which should only happen once per active segment change.
This commit is contained in:
Joe Boccanfuso 2025-10-21 11:58:23 -04:00 committed by GitHub
parent cf0b561a49
commit 1df4f843fe
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 472 additions and 359 deletions

View File

@ -1,4 +1,4 @@
import React, { useState, useRef } from 'react'; import React, { useState } from 'react';
import { Button } from '../../components/Button/Button'; import { Button } from '../../components/Button/Button';
import { import {
DropdownMenu, DropdownMenu,
@ -107,7 +107,9 @@ interface DataRowProps {
children?: React.ReactNode; children?: React.ReactNode;
} }
const DataRowComponent: React.FC<DataRowProps> = ({ const DataRowComponent = React.forwardRef<HTMLDivElement, DataRowProps>(
(
{
number, number,
title, title,
colorHex, colorHex,
@ -124,27 +126,20 @@ const DataRowComponent: React.FC<DataRowProps> = ({
disableEditing = false, disableEditing = false,
className, className,
children, children,
}) => { },
ref
) => {
const [isDropdownOpen, setIsDropdownOpen] = useState(false); const [isDropdownOpen, setIsDropdownOpen] = useState(false);
const isTitleLong = title?.length > 25; const isTitleLong = title?.length > 25;
const rowRef = useRef<HTMLDivElement>(null);
// Extract Status components from children // Extract Status components from children
const statusComponents = React.Children.toArray(children).filter( const statusComponents = React.Children.toArray(children).filter(
child => child =>
React.isValidElement(child) && React.isValidElement(child) &&
child.type && child.type &&
(child.type as any).displayName?.startsWith('DataRow.Status') (child.type as React.ComponentType).displayName?.startsWith('DataRow.Status')
); );
// useEffect(() => {
// if (isSelected && rowRef.current) {
// setTimeout(() => {
// rowRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
// }, 200);
// }
// }, [isSelected]);
const handleAction = (action: string, e: React.MouseEvent) => { const handleAction = (action: string, e: React.MouseEvent) => {
e.stopPropagation(); e.stopPropagation();
switch (action) { switch (action) {
@ -229,7 +224,7 @@ const DataRowComponent: React.FC<DataRowProps> = ({
return ( return (
<div <div
ref={rowRef} ref={ref}
className={cn('flex flex-col', !isVisible && 'opacity-60', className)} className={cn('flex flex-col', !isVisible && 'opacity-60', className)}
> >
<div <div
@ -314,7 +309,9 @@ const DataRowComponent: React.FC<DataRowProps> = ({
</Button> </Button>
{/* Lock Icon (if needed) */} {/* Lock Icon (if needed) */}
{isLocked && !disableEditing && <Icons.Lock className="text-muted-foreground h-6 w-6" />} {isLocked && !disableEditing && (
<Icons.Lock className="text-muted-foreground h-6 w-6" />
)}
{/* Status Components */} {/* Status Components */}
{statusComponents} {statusComponents}
@ -405,7 +402,10 @@ const DataRowComponent: React.FC<DataRowProps> = ({
)} )}
</div> </div>
); );
}; }
);
DataRowComponent.displayName = 'DataRow';
interface StatusProps { interface StatusProps {
children: React.ReactNode; children: React.ReactNode;
@ -490,7 +490,7 @@ Status.Success = StatusSuccess;
Status.Error = StatusError; Status.Error = StatusError;
Status.Info = StatusInfo; Status.Info = StatusInfo;
const DataRow = DataRowComponent as React.FC<DataRowProps> & { const DataRow = DataRowComponent as typeof DataRowComponent & {
Status: typeof Status; Status: typeof Status;
}; };

View File

@ -1,4 +1,4 @@
import React from 'react'; import React, { useEffect } from 'react';
import { ScrollArea, DataRow } from '../../components'; import { ScrollArea, DataRow } from '../../components';
import { HoverCard, HoverCardTrigger, HoverCardContent } from '../../components/HoverCard'; import { HoverCard, HoverCardTrigger, HoverCardContent } from '../../components/HoverCard';
import { useSegmentationTableContext, useSegmentationExpanded } from './contexts'; import { useSegmentationTableContext, useSegmentationExpanded } from './contexts';
@ -23,6 +23,11 @@ export const SegmentationSegments = ({ children = null }: { children?: React.Rea
let segmentation; let segmentation;
let representation; let representation;
const activeSegmentRef = React.useRef<{
element: HTMLElement | null;
index: number | null;
}>({ element: null, index: null });
try { try {
// Try to use the SegmentationExpanded context if available // Try to use the SegmentationExpanded context if available
const segmentationInfo = useSegmentationExpanded('SegmentationSegments'); const segmentationInfo = useSegmentationExpanded('SegmentationSegments');
@ -38,23 +43,61 @@ export const SegmentationSegments = ({ children = null }: { children?: React.Rea
} }
const segments = Object.values(representation.segments); const segments = Object.values(representation.segments);
// Find the active segment to scroll to it when it changes
const activeSegment = segments.find(segment => {
if (!segment) {
return false;
}
const segmentFromSegmentation = segmentation.segments[segment.segmentIndex];
return segmentFromSegmentation?.active;
});
const isActiveSegmentation = segmentation.segmentationId === activeSegmentationId; const isActiveSegmentation = segmentation.segmentationId === activeSegmentationId;
const { ref: scrollableContainerRef, maxHeight } = useDynamicMaxHeight(segments); const { ref: scrollableContainerRef, maxHeight } = useDynamicMaxHeight(segments);
useEffect(() => {
const activeSegmentIndex = activeSegmentRef.current.index;
if (!activeSegmentIndex || activeSegmentIndex !== activeSegment?.segmentIndex) {
return;
}
const activeSegmentElement = activeSegmentRef.current.element;
if (!activeSegmentElement) {
return;
}
// Check if the active segment is already visible.
const activeSegmentElementBounds = activeSegmentElement.getBoundingClientRect();
const scrollableContainerRect = scrollableContainerRef.current.getBoundingClientRect();
if (
activeSegmentElementBounds.top > scrollableContainerRect.top &&
activeSegmentElementBounds.bottom < scrollableContainerRect.bottom
) {
// The active segment is already visible, so we don't need to scroll.
return;
}
activeSegmentElement.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}, [activeSegment?.segmentIndex, scrollableContainerRef]);
if (!representation || !segmentation) { if (!representation || !segmentation) {
return null; return null;
} }
return ( return (
<div ref={scrollableContainerRef}>
<ScrollArea <ScrollArea
className={`bg-bkg-low space-y-px`} className={`bg-bkg-low space-y-px`}
showArrows={true} showArrows={
> scrollableContainerRef?.current
<div ? scrollableContainerRef?.current?.offsetHeight >= parseFloat(maxHeight)
ref={scrollableContainerRef} : false
style={{ maxHeight: maxHeight }} }
> >
<div style={{ maxHeight: maxHeight }}>
{segments.map(segment => { {segments.map(segment => {
if (!segment) { if (!segment) {
return null; return null;
@ -74,8 +117,22 @@ export const SegmentationSegments = ({ children = null }: { children?: React.Rea
const cssColor = `rgb(${color[0]},${color[1]},${color[2]})`; const cssColor = `rgb(${color[0]},${color[1]},${color[2]})`;
const hasStats = segmentFromSegmentation.cachedStats?.namedStats; const hasStats = segmentFromSegmentation.cachedStats?.namedStats;
const segmentRowRef = (element: HTMLElement) => {
if (!active) {
return;
}
if (element) {
activeSegmentRef.current = { element, index: segmentIndex };
} else {
activeSegmentRef.current = { element: null, index: null };
}
};
const DataRowComponent = ( const DataRowComponent = (
<DataRow <DataRow
ref={segmentRowRef}
key={segmentIndex} key={segmentIndex}
number={showSegmentIndex ? segmentIndex : null} number={showSegmentIndex ? segmentIndex : null}
title={label} title={label}
@ -95,7 +152,9 @@ export const SegmentationSegments = ({ children = null }: { children?: React.Rea
representation.type representation.type
) )
} }
onToggleLocked={() => onToggleSegmentLock(segmentation.segmentationId, segmentIndex)} onToggleLocked={() =>
onToggleSegmentLock(segmentation.segmentationId, segmentIndex)
}
onSelect={() => onSegmentClick(segmentation.segmentationId, segmentIndex)} onSelect={() => onSegmentClick(segmentation.segmentationId, segmentIndex)}
onRename={() => onSegmentEdit(segmentation.segmentationId, segmentIndex)} onRename={() => onSegmentEdit(segmentation.segmentationId, segmentIndex)}
onDelete={() => onSegmentDelete(segmentation.segmentationId, segmentIndex)} onDelete={() => onSegmentDelete(segmentation.segmentationId, segmentIndex)}
@ -140,6 +199,7 @@ export const SegmentationSegments = ({ children = null }: { children?: React.Rea
})} })}
</div> </div>
</ScrollArea> </ScrollArea>
</div>
); );
}; };

View File

@ -1,5 +1,29 @@
import { useRef, useState, useEffect, RefObject } from 'react'; import { useRef, useState, useEffect, RefObject } from 'react';
const _getMovementIntersectionObserver = ({
callback,
rootMargin,
threshold,
}: {
callback: () => void;
rootMargin: string;
threshold: number[];
}): IntersectionObserver => {
return new IntersectionObserver(
entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
callback();
}
});
},
{
threshold,
rootMargin,
}
);
};
/** /**
* Calculates the maximum height for an element based on its position * Calculates the maximum height for an element based on its position
* relative to the bottom of the viewport. * relative to the bottom of the viewport.
@ -31,20 +55,49 @@ export function useDynamicMaxHeight(
} }
}; };
// Calculate initially // Two intersection observers to trigger a recalculation when the target element
// Use requestAnimationFrame to ensure layout is stable after initial render // moves up or down. One for moving up and one for moving down.
const rafId = requestAnimationFrame(calculateMaxHeight); // Note that with this approach we don't need to use a resize observer nor
// a window resize listener.
// Recalculate on window resize // The trick is to use a margin for the IntersectionObserver to detect movement.
window.addEventListener('resize', calculateMaxHeight); // See more below.
const rootMarginHeight = maxHeight === '100vh' ? `${window.innerHeight}px` : `${maxHeight}`;
// Note that we use a fine grained threshold because we don't know how
// much it will move and we want any movement to trigger the intersection observer.
const threshold = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0];
// The trick here is to use the calculated maxHeight as the root margin height
// so that any movement of the target element down (i.e. "out of the" viewport)
// will trigger the intersection observer.
const moveDownIntersectionObserver = _getMovementIntersectionObserver({
callback: calculateMaxHeight,
rootMargin: `0px 0px ${rootMarginHeight} 0px`,
threshold,
});
// The trick here is to use the calculated maxHeight as the negative
// root margin height so that any movement of the target element up
// (i.e. "into the" viewport) will trigger the intersection observer.
const moveUpIntersectionObserver = _getMovementIntersectionObserver({
callback: calculateMaxHeight,
rootMargin: `0px 0px -${rootMarginHeight} 0px`,
threshold,
});
if (ref.current) {
moveUpIntersectionObserver.observe(ref.current);
moveDownIntersectionObserver.observe(ref.current);
}
// Cleanup listener and requestAnimationFrame on component unmount // Cleanup listener and requestAnimationFrame on component unmount
return () => { return () => {
window.removeEventListener('resize', calculateMaxHeight); moveUpIntersectionObserver.disconnect();
cancelAnimationFrame(rafId); moveDownIntersectionObserver.disconnect();
}; };
// Dependencies: buffer, minHeight, and data. // Dependencies: buffer, minHeight, and data.
}, [data, buffer, minHeight]); }, [data, buffer, minHeight, maxHeight]);
return { ref, maxHeight }; return { ref, maxHeight };
} }