@@ -45,7 +45,36 @@ export const ChartLegend = ({
4545 const containerRef = useRef < HTMLDivElement > ( null ) ;
4646 const segmentsRef = useRef < Record < number , HTMLElement > > ( [ ] ) ;
4747 const highlightControl = useMemo ( ( ) => new DebouncedCall ( ) , [ ] ) ;
48+ const scrollIntoViewControl = useMemo ( ( ) => new DebouncedCall ( ) , [ ] ) ;
4849 const [ selectedIndex , setSelectedIndex ] = useState < number > ( 0 ) ;
50+
51+ useEffect ( ( ) => {
52+ const highlightedIndex = items . findIndex ( ( item ) => item . highlighted ) ;
53+ if ( highlightedIndex === - 1 ) {
54+ return ;
55+ }
56+
57+ scrollIntoViewControl . cancelPrevious ( ) ;
58+ scrollIntoViewControl . call ( ( ) => {
59+ const container = containerRef . current ;
60+ const element = segmentsRef . current ?. [ highlightedIndex ] ;
61+ if ( ! container || ! element ) {
62+ return ;
63+ }
64+
65+ const elementRect = element . getBoundingClientRect ( ) ;
66+ const containerRect = container . getBoundingClientRect ( ) ;
67+ const isVisible = elementRect . top >= containerRect . top && elementRect . bottom <= containerRect . bottom ;
68+
69+ if ( ! isVisible ) {
70+ const elementCenter = elementRect . top + elementRect . height / 2 ;
71+ const containerCenter = containerRect . top + containerRect . height / 2 ;
72+ const top = container . scrollTop + ( elementCenter - containerCenter ) ;
73+ container . scrollTo ( { top, behavior : "smooth" } ) ;
74+ }
75+ } , 100 ) ;
76+ } , [ items , scrollIntoViewControl ] ) ;
77+
4978 const showHighlight = ( itemId : string ) => {
5079 const item = items . find ( ( item ) => item . id === itemId ) ;
5180 if ( item ?. visible ) {
0 commit comments