fix: calculate distance to button using rect & container scroll offset

This commit is contained in:
Tanner Reits
2024-10-18 16:10:19 -04:00
parent c4c89ae005
commit 88b9af9a44

View File

@ -246,6 +246,16 @@ export class Segment implements ComponentInterface {
this.valueBeforeGesture = undefined; this.valueBeforeGesture = undefined;
} }
private distanceToButton(index: number) {
const buttons = this.getButtons();
const button = buttons[index];
const buttonRect = button.getBoundingClientRect();
const segmentRect = this.el.getBoundingClientRect();
return this.el.scrollLeft + buttonRect.x - segmentRect.x;
}
private addIntersectionObserver() { private addIntersectionObserver() {
if ( if (
typeof (window as any) !== 'undefined' && typeof (window as any) !== 'undefined' &&
@ -279,9 +289,7 @@ export class Segment implements ComponentInterface {
const activeButtonStyles = getComputedStyle(buttons[activeButtonIndex]); const activeButtonStyles = getComputedStyle(buttons[activeButtonIndex]);
const indicator = this.el.shadowRoot!.querySelector('.segment-indicator') as HTMLDivElement | null; const indicator = this.el.shadowRoot!.querySelector('.segment-indicator') as HTMLDivElement | null;
if (indicator) { if (indicator) {
const startingX = buttons const startingX = this.distanceToButton(activeButtonIndex);
.slice(0, activeButtonIndex)
.reduce((acc, ref) => acc + ref.getBoundingClientRect().width, 0);
indicator.style.width = `${activeButtonPosition.width}px`; indicator.style.width = `${activeButtonPosition.width}px`;
indicator.style.left = `${startingX}px`; indicator.style.left = `${startingX}px`;
@ -491,12 +499,8 @@ export class Segment implements ComponentInterface {
indicator.style.width = `${width - indicatorPadding}px`; indicator.style.width = `${width - indicatorPadding}px`;
// Translate the indicator based on the scroll distance // Translate the indicator based on the scroll distance
const distanceToNextButton = buttons const distanceToNextButton = this.distanceToButton(nextIndex);
.slice(0, nextIndex) const distanceToCurrentButton = this.distanceToButton(currentIndex);
.reduce((acc, ref) => acc + ref.getBoundingClientRect().width, 0);
const distanceToCurrentButton = buttons
.slice(0, currentIndex)
.reduce((acc, ref) => acc + ref.getBoundingClientRect().width, 0);
indicator.style.left = indicator.style.left =
scrollDistance > 0 scrollDistance > 0