fix(segment): properly move the indicator when direction starts out on the left

This commit is contained in:
Brandy Carney
2024-09-24 19:54:44 -04:00
parent d811221750
commit 699ce9779f
2 changed files with 19 additions and 6 deletions

View File

@@ -10,6 +10,7 @@ import { Component, Element, Event, Host, Listen, Method, Prop, h } from '@stenc
shadow: true,
})
export class SegmentView implements ComponentInterface {
private initialScrollLeft = 0;
private previousScrollLeft = 0;
@Element() el!: HTMLElement;
@@ -23,12 +24,17 @@ export class SegmentView implements ComponentInterface {
@Listen('scroll')
handleScroll(ev: Event) {
const { initialScrollLeft, previousScrollLeft } = this;
const { scrollLeft, offsetWidth } = ev.target as HTMLElement;
const scrollDirection = scrollLeft > this.previousScrollLeft ? 'right' : 'left';
const scrollDirection = scrollLeft > previousScrollLeft ? 'right' : 'left';
this.previousScrollLeft = scrollLeft;
const scrollDistance = scrollLeft;
let scrollDistance = scrollLeft;
if (scrollDirection === 'left') {
scrollDistance = initialScrollLeft - scrollLeft;
}
// Emit the scroll direction and distance
this.ionSegmentViewScroll.emit({
@@ -55,6 +61,11 @@ export class SegmentView implements ComponentInterface {
}
}
@Listen('touchstart')
handleTouchStart() {
this.initialScrollLeft = this.el.scrollLeft;
}
/**
* This method is used to programmatically set the displayed segment content
* in the segment view. Calling this method will update the `value` of the

View File

@@ -372,15 +372,17 @@ export class Segment implements ComponentInterface {
// Calculate the potential transform value based on scroll direction
const transformValue = scrollDirection === 'left' ? -scrollDistance : scrollDistance;
// Calculate the max allowed transformation (indicator should not move beyond the segment boundaries)
const maxTransform = segmentRect.width - buttonRect.width;
const minTransform = 0;
// Calculate the max and min allowed transformations based on the scroll direction
const maxTransform = scrollDirection === 'left' ? 0 : segmentRect.width - buttonRect.width;
const minTransform = scrollDirection === 'left' ?
-(segmentRect.width - buttonRect.width) : 0;
// Clamp the transform value to ensure it doesn't go out of bounds
const clampedTransform = Math.max(minTransform, Math.min(transformValue, maxTransform));
// Apply the clamped transform value to the indicator element
indicatorEl.style.transform = `translate3d(${clampedTransform}px, 0, 0)`;
const transform = `translate3d(${clampedTransform}px, 0, 0)`;
indicatorEl.style.setProperty('transform', transform);
}
}
}