Skip to content

Commit a223132

Browse files
authored
feat: scroll into view highlighted legend item (#35)
* feat: scroll into view highlighted legend item * fix: remove whole page scroll behavior
1 parent 69fba1a commit a223132

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/internal/components/chart-legend/index.tsx

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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) {

src/internal/components/chart-legend/styles.scss

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212
@include styles.styles-reset;
1313
@include styles.default-text-style;
1414

15+
overflow: auto;
16+
max-height: inherit;
17+
1518
&:focus {
1619
outline: none;
1720
}

0 commit comments

Comments
 (0)