import type { NativeSwiperAutoplay, NativeSwiperCarousel, NativeSwiperHandle, NativeSwiperSlideChangedArgs } from './native-swiper-carousel'; import { Comment, Fragment, markRaw, Text } from 'vue'; import { Prop, toNative } from 'vue-facing-decorator'; import TsxComponent, { Component } from '../../app/vuetsx'; import { PortalUtils } from '../../common/utils/utils'; import './css/native-swiper.css'; export type { NativeSwiperAutoplay, NativeSwiperEvent, NativeSwiperHandle, NativeSwiperSlideChangedArgs } from './native-swiper-carousel'; type NavigationMode = 'single' | 'page' | number; interface NavigationConfig { nextEl: () => HTMLElement | null; prevEl: () => HTMLElement | null; mode?: NavigationMode; } interface NativeSwiperArgs { navigation?: NavigationConfig; cssClass?: string; fadeLeftEnabled?: boolean; fadeRightEnabled?: boolean; showNavButtons?: boolean; /** * Keep the browser's scroll snap on a narrow touch device, where a rail otherwise scrolls freely * (`nativeswiper-nosnap`) — for a rail that must land on one slide at a time (the phone Gopass Cards deck). * Still no drag machinery there: the provider stays `fadeOnly`. */ snapOnTouch?: boolean; /** * `1`: each slide spans the rail (one slide per view); a larger number: that many slides span it, the gaps between them * included; `'auto'` (default): each slide keeps its own width. */ slidesPerView?: 'auto' | number; /** The gap between slides, px (default 10). */ spaceBetween?: number; /** * The carousel controller class — `NativeSwiperCarousel` from `./native-swiper-carousel`. With it the props below * make the rail a carousel; without it they do nothing and the rail runs exactly the code above. It is a prop, not an * import of this file, so that a page whose rails are no carousels never downloads it. */ carousel?: typeof NativeSwiperCarousel; // Carousel props — Swiper 12 is the model: the carousels that use them ran on it before. /** Duration of a move (arrows, bullets, autoplay, `slideTo`), ms, on the CSS `ease` curve (default 300). */ speed?: number; autoplay?: NativeSwiperAutoplay; /** One bullet per slide under the rail, the active one marked. */ hasPagination?: boolean; /** A bullet click moves to its slide. */ clickable?: boolean; /** * The arrows wrap around: past the last slide comes the first, before the first the last; with several slides in view * they rewind to the other end instead (Swiper's `rewind`). Swipes stop at the ends. */ loop?: boolean; /** A mouse / touch drag ends on a slide (the nearest, or the next one in a flick's direction) instead of coasting. */ settleAfterDrag?: boolean; slideChanged?: (e: NativeSwiperSlideChangedArgs) => void; } /** The slides a slot renders: element and component vnodes, through fragments; comments and text are no slides. */ const countSlides = (nodes: unknown): number => { if (nodes == null || typeof nodes !== 'object') { return 0; } if (Array.isArray(nodes)) { return nodes.reduce((sum: number, node) => sum + countSlides(node), 0); } const type = (nodes as { type?: unknown }).type; if (type === Fragment) { return countSlides((nodes as { children?: unknown }).children); } return type === Comment || type === Text ? 0 : 1; }; /** * PERF-08 — whether the viewport is narrower than 800 px, the width below which a touch phone keeps native snap * scrolling instead of the drag-bound rail ({@link NativeSwiper.shouldBindSwiper}). * * Read through a media query, never `window.innerWidth`: on a page with a viewport meta Chrome lays out the whole * document before it answers `innerWidth`, and every rail asked from `mounted`, right after its section's DOM went in. * On the homepage of a mid-range phone that was three full style + layout passes (~300 ms) inside the task that renders * the product sections. A media query answers from the viewport size alone. `(min-width: 800px)` is the exact complement * of `innerWidth < 800`: both measure the viewport including a scrollbar, and the shop pins `initial-scale=1`. */ export class NativeSwiperViewport { static readonly WIDE_QUERY = '(min-width: 800px)'; static isNarrow(): boolean { if (typeof window.matchMedia !== 'function') { return window.innerWidth < 800; } return !window.matchMedia(NativeSwiperViewport.WIDE_QUERY).matches; } } @Component class NativeSwiper extends TsxComponent implements NativeSwiperArgs { @Prop() navigation?: NavigationConfig; @Prop() cssClass?: string; @Prop() fadeLeftEnabled?: boolean; @Prop() fadeRightEnabled?: boolean; @Prop({ default: false }) showNavButtons: boolean; @Prop({ default: false }) snapOnTouch: boolean; @Prop() slidesPerView?: 'auto' | number; @Prop() spaceBetween?: number; @Prop() carousel?: typeof NativeSwiperCarousel; @Prop() speed?: number; @Prop() autoplay?: NativeSwiperAutoplay; @Prop({ default: false }) hasPagination: boolean; @Prop({ default: false }) clickable: boolean; @Prop({ default: false }) loop: boolean; @Prop({ default: false }) settleAfterDrag: boolean; @Prop() slideChanged?: (e: NativeSwiperSlideChangedArgs) => void; swiper: NativeSwiperProvider; _bindSwiper: boolean = null; /** Only with `carousel`; kept raw (never a reactive proxy). */ controller: NativeSwiperCarousel | null = null; /** The slide the bullets mark. */ activeSlideIndex: number = 0; mounted() { const shouldBind = this.shouldBindSwiper(); this._bindSwiper = shouldBind; const fadeOnly = !shouldBind; const Carousel = this.carousel; // Built now, not with the provider below: a parent's `mounted()` (which runs after this one) reads the handle. if (Carousel) { const container = this.getContainerEl(); this.controller = markRaw(new Carousel({ container, wrapper: container.querySelector('.nativeswiper-wrapper') as HTMLElement, slideGap: this.getSlideGap(), speed: this.speed ?? 300, autoplay: this.autoplay, pagination: this.hasPagination ? { clickable: this.clickable } : false, loop: this.loop, settleAfterDrag: this.settleAfterDrag, activeIndexChanged: e => this.activeIndexChanged(e), })); } if (this.swiper == null) { this.$nextTick(() => { const container = this.showNavButtons ? this.$refs.swiperContainer as HTMLElement : this.$el; // QA_AT-450 — resolved in BOTH modes. `fadeOnly` still skips the drag / // momentum / scrollend wiring below, but the prev/next buttons must stay // clickable on small touch devices where consumers keep them visible // (product-recommendations-section renders its arrows at every breakpoint). const prevBtn = this.showNavButtons ? this.$refs.navPrev as HTMLElement : this.navigation?.prevEl(); const nextBtn = this.showNavButtons ? this.$refs.navNext as HTMLElement : this.navigation?.nextEl(); this.swiper = new NativeSwiperProvider({ container, slideGap: this.getSlideGap(), prevBtn, nextBtn, navigationMode: this.navigation?.mode ?? 'single', fadeLeftEnabled: this.fadeLeftEnabled, fadeRightEnabled: this.fadeRightEnabled, fadeOnly, scrollByPage: this.showNavButtons, carousel: this.controller, }); this.controller?.attachButtons(() => this.swiper?.applyButtonState()); }); } } updated() { // The bullets were redrawn (the active one, or their count): `CarouselA11y`-style helpers label them again. if (this.hasPagination) { this.controller?.emit('paginationUpdate'); } } /** The carousel handle (a Swiper-like subset) — `null` for a rail without `carousel`, and in a server render. */ getSwiperInstance(): NativeSwiperHandle | null { return this.controller ?? null; } private getSlideGap(): number { return this.spaceBetween ?? 10; } private getContainerEl(): HTMLElement { return this.showNavButtons ? this.$refs.swiperContainer as HTMLElement : this.$el as HTMLElement; } private activeIndexChanged(e: NativeSwiperSlideChangedArgs): void { this.activeSlideIndex = e.activeIndex; this.slideChanged?.(e); } private bulletClicked(index: number): void { if (this.clickable) { this.controller?.slideTo(index); } } beforeUnmount() { this.controller?.destroy(); this.controller = null; if (this.swiper != null) { this.swiper.destroy(); this.swiper = null; } } private getWrapperEl(): HTMLElement | null { const container = this.showNavButtons ? this.$refs.swiperContainer as HTMLElement : this.$el as HTMLElement; return (container?.querySelector('.nativeswiper-wrapper') as HTMLElement) ?? null; } scrollToStart() { this.scrollToIndex(0); } /** * GOBO-369 — brings the slide at `index` into horizontal view. * * `NativeSwiperProvider.scrollToIndex` is only available once the provider is * bound, and `shouldBindSwiper()` deliberately skips binding on small touch * devices (native snap scrolling takes over there). This falls back to * scrolling the wrapper to the slide's own offset, so callers get the same * behaviour on every device — mirroring what `scrollToStart` already did for * index 0. */ scrollToIndex(index: number, behavior: ScrollBehavior = 'smooth' as const) { // A carousel moves on its own clock: `speed` for a smooth move, at once otherwise. if (this.controller) { this.controller.slideTo(index, behavior === 'smooth' ? undefined : 0); return; } if (this.swiper) { this.swiper.scrollToIndex(index, behavior); return; } const wrapper = this.getWrapperEl(); const slide = wrapper?.children?.[index] as HTMLElement | undefined; if (!wrapper || !slide) { return; } // Rect-based rather than offsetLeft: the wrapper is statically positioned, // so it is not the slides' offsetParent and offsetLeft would be measured // against an unrelated ancestor. const left = slide.getBoundingClientRect().left - wrapper.getBoundingClientRect().left + wrapper.scrollLeft; wrapper.scrollTo({ left, behavior }); } /** * Re-applies the provider's prev/next `disabled` rule NOW, in every binding mode. * * The provider itself only updates on `scrollend` (after a smooth scroll settles), * which shows the prev arrow with a visible delay when leaving the first slide. A * consumer that wants the arrows to follow the scroll LIVE (the peek rails, driven * from `MeasuredRailDots`' `scrolled` callback) calls this instead of keeping its * own copy of the rule — so there is exactly one place that decides it. */ syncNavButtons(): void { this.swiper?.applyButtonState(); } shouldBindSwiper() { if (!PortalUtils.treatAsMobileDevice()) { return true; } if (PortalUtils.isTouchDevice()) { if (NativeSwiperViewport.isNarrow()) { return false; } } return true; } getCssClass(): string { return `nativeswiper-container ${this.getModeCssClass()}${this.getPerViewCssClass()}${this.cssClass ? ` ${this.cssClass}` : ''}`; } /** `slidesPerView`: one slide spans the rail, or several (their count in `--nativeswiper-slides-per-view`). */ private getPerViewCssClass(): string { if (this.slidesPerView === 1) { return ' nativeswiper-one-per-view'; } return this.hasSeveralPerView() ? ' nativeswiper-per-view' : ''; } private hasSeveralPerView(): boolean { return typeof this.slidesPerView === 'number' && this.slidesPerView > 1; } /** * `spaceBetween` reaches the slides' margin, and a `slidesPerView` count their width, through variables; without either * the container carries no style. */ private getContainerStyle(): Record | undefined { const style: Record = {}; if (this.spaceBetween != null) { style['--nativeswiper-slide-gap'] = `${this.spaceBetween}px`; } if (this.hasSeveralPerView()) { style['--nativeswiper-slides-per-view'] = String(this.slidesPerView); } return Object.keys(style).length > 0 ? style : undefined; } /** The drag rail when bound; otherwise a touch phone's native scroll — snapping only when `snapOnTouch` asks for it. */ private getModeCssClass(): string { if (this._bindSwiper) { return 'nativeswiper-bound'; } return this.snapOnTouch ? 'nativeswiper-snap-touch' : 'nativeswiper-nosnap'; } /** Swiper's bullets, one per slide; counted from the slot so a server render draws them too. */ private renderPagination(slides: unknown) { const active = this.activeSlideIndex ?? 0; return (
{Array.from({ length: countSlides(slides) }, (_unused, index) => ( this.bulletClicked(index)} /> ))}
); } render(h) { const slides = this.$slots.default?.(); const swiperContainer = (
{slides}
{this.hasPagination && this.renderPagination(slides)}
); if (this.showNavButtons) { return (
{swiperContainer}
); } return swiperContainer; } } class NativeSwiperProvider { private container: HTMLElement; private wrapper: HTMLElement; private prevBtn: HTMLButtonElement; private nextBtn: HTMLButtonElement; private slideGap: number = 10; private clickThreshold: number = 5; private currentIndex: number = 0; private isDragging = false; private startPos = 0; private startScrollLeft = 0; private draggedDistance = 0; private momentumID = 0; private velocity = 0; private lastPos = 0; private lastTime = 0; private resizeObserver?: ResizeObserver; private fadeLeftEnabled = false; private fadeRightEnabled = false; private fadingEnabled = false; private fadeOnly: boolean = false; private fadeUpdateScheduled: boolean = false; private navigationMode: NavigationMode = 'single'; private scrollByPage: boolean = false; /** * GP_BG-213 — the slide a `scrollToIndex` smooth scroll is still heading to; `null` once it settles * (`scrollend`) or a drag takes over. `currentIndex` only moves on `scrollend`, so a second prev/next * click DURING the animation started from the same slide as the first one, and two quick clicks * advanced a single card. Bound mode only: fadeOnly reads the live offset and has no `scrollend` wiring. */ private pendingIndex: number | null = null; /** * The carousel controller of a rail given `carousel`: it takes the arrows, settles a drag (`settleAfterDrag`) and * keeps the arrows' `disabled` state in every mode, as Swiper did. `null` for every other rail — none of the paths * below that check it changes for them. */ private carousel: NativeSwiperCarousel | null = null; constructor(args: { container: HTMLElement; prevBtn?: HTMLElement; nextBtn?: HTMLElement; slideGap?: number; fadeOnly?: boolean; fadeLeftEnabled?: boolean; fadeRightEnabled?: boolean; navigationMode?: NavigationMode; scrollByPage?: boolean; carousel?: NativeSwiperCarousel | null; }) { this.container = args.container; if (!this.container) { return; } this.carousel = args.carousel ?? null; this.wrapper = this.container.querySelector('.nativeswiper-wrapper'); this.prevBtn = args.prevBtn as HTMLButtonElement; this.nextBtn = args.nextBtn as HTMLButtonElement; this.slideGap = args.slideGap ?? 10; this.clickThreshold = 5; // Pixels to distinguish a click from a drag this.fadeOnly = !!args.fadeOnly; this.fadeRightEnabled = args.fadeRightEnabled ?? false; this.fadeLeftEnabled = args.fadeLeftEnabled ?? false; this.navigationMode = args.navigationMode ?? 'single'; this.scrollByPage = args.scrollByPage ?? false; if (this.fadeLeftEnabled || this.fadeRightEnabled) { this.fadingEnabled = true; } // State properties this.currentIndex = 0; this.isDragging = false; this.startPos = 0; this.startScrollLeft = 0; this.draggedDistance = 0; this.momentumID = 0; this.velocity = 0; this.lastPos = 0; this.lastTime = 0; // Pre-bind event handlers this.handleDragStart = this.handleDragStart.bind(this); this.handleDragMove = this.handleDragMove.bind(this); this.handleDragEnd = this.handleDragEnd.bind(this); this.updateCurrentIndex = this.updateCurrentIndex.bind(this); this.momentumScroll = this.momentumScroll.bind(this); this.bindEvents(); // PERF-08 — the first fade state comes from the ResizeObserver's initial notification, which the browser delivers // after its next layout and before that frame paints. Reading the rail's scroll geometry here forced a layout inside // the task that mounted the rail, and the fade write that followed dirtied the style the next rail's reads needed: // one style + layout pass per rail on the homepage. Without a ResizeObserver the state is still set right away. // The bound rail's first arrow state comes from that notification too: a frame callback runs BEFORE the browser lays // the page out, so its read forced a layout, and its arrow write made the next rail's read force another. if (!this.observeResize()) { this.updateFadeState(); // Defer initial button update to ensure layout is complete if (!this.fadeOnly) { requestAnimationFrame(() => this.updateButtons()); } else if (this.carousel) { requestAnimationFrame(() => this.applyButtonState()); } } } // --- Getters for dynamic properties --- get slides() { return [...this.wrapper.children]; } get slidesVisible() { const wrapperWidth = this.wrapper.offsetWidth; const slideWidth = this.getSlideWidth(); return slideWidth > 0 ? Math.floor(wrapperWidth / slideWidth) : 0; } get navigationStep(): number { if (typeof this.navigationMode === 'number') { return this.navigationMode; } if (this.navigationMode === 'page') { return Math.max(1, this.slidesVisible); } return 1; // 'single' } // --- Public API --- scrollToIndex(index, behavior: ScrollBehavior = 'smooth' as const) { const newIndex = Math.max(0, Math.min(index, this.slides.length - this.slidesVisible)); const scrollAmount = newIndex * this.getSlideStep(); // A scroll that does not move fires no `scrollend`, so it must leave no target behind. const maxScrollLeft = this.wrapper.scrollWidth - this.wrapper.clientWidth; const moves = Math.abs(Math.min(scrollAmount, maxScrollLeft) - this.wrapper.scrollLeft) >= 1; this.pendingIndex = !this.fadeOnly && moves ? newIndex : null; this.wrapper.scrollTo({ left: scrollAmount, behavior }); } // --- Internal Methods --- getSlideWidth() { return (this.slides[0] as HTMLElement)?.offsetWidth || 0; } /** * Horizontal distance from the start of one slide to the start of the next — * the single home for the slide-step formula, shared by `scrollToIndex` (index * to offset) and `getScrolledIndex` (offset back to index). */ private getSlideStep(): number { return this.getSlideWidth() + this.slideGap; } updateButtons() { // `this.wrapper` is null after `destroy()` (or before it mounts); a deferred // rAF (constructor) or a pending ResizeObserver callback can still fire here, // so guard against reading scrollWidth on null (fixes a mobile console error). if (this.fadeOnly || this.wrapper == null) { return; } this.applyButtonState(); this.updateFadeState(); } /** * THE prev/next `disabled` rule — the single home for it. `updateButtons` applies it * on the provider's own triggers (bound mode only); `NativeSwiper.syncNavButtons` * lets a consumer apply it live from a scroll listener, in either mode. */ applyButtonState(): void { if (this.wrapper == null) { return; } const maxScrollLeft = this.wrapper.scrollWidth - this.wrapper.clientWidth; // A carousel with nothing to scroll hides its arrows, as Swiper's `swiper-button-lock` did; a plain rail keeps them. if (this.carousel) { this.prevBtn?.classList.toggle('nativeswiper-button-lock', maxScrollLeft <= 0); this.nextBtn?.classList.toggle('nativeswiper-button-lock', maxScrollLeft <= 0); } // A `loop` carousel's arrows wrap around: there is always a next and a previous slide. if (this.carousel?.loops) { if (this.prevBtn != null) { this.prevBtn.disabled = false; } if (this.nextBtn != null) { this.nextBtn.disabled = false; } return; } if (this.prevBtn != null) { this.prevBtn.disabled = this.wrapper.scrollLeft <= 0; } if (this.nextBtn != null) { this.nextBtn.disabled = maxScrollLeft <= 0 || this.wrapper.scrollLeft >= maxScrollLeft - 1; } } /** * Slide index implied by the wrapper's live scroll offset. `null` when the slide * width is not measurable yet (empty / unlaid-out wrapper) or the wrapper is * already gone — `destroy()` nulls it, and `getSlideWidth()` reads through * `this.slides` (`this.wrapper.children`), so the null check must come first. */ private getScrolledIndex(): number | null { if (this.wrapper == null || this.getSlideWidth() <= 0) { return null; } return Math.round(this.wrapper.scrollLeft / this.getSlideStep()); } updateCurrentIndex() { this.pendingIndex = null; const index = this.getScrolledIndex(); if (index == null) { return; } this.currentIndex = index; this.updateButtons(); } /** * QA_AT-450 — base index for prev/next clicks. When the provider is bound, * `currentIndex` is kept fresh by the `scrollend` listener. In fadeOnly mode * (small touch devices — native swiping, no drag/scrollend wiring) that * listener is never attached and `currentIndex` would stay 0 forever, so read * the live scroll offset instead. While a smooth scroll is still in flight the * base is the slide it is heading to (GP_BG-213, see {@link pendingIndex}). */ private getNavBaseIndex(): number { if (this.fadeOnly) { return this.getScrolledIndex() ?? 0; } return this.pendingIndex ?? this.currentIndex; } // --- Event Handling --- bindEvents() { if (this.fadingEnabled) { this.wrapper.addEventListener( 'scroll', () => { if (this.fadeUpdateScheduled) { return; } this.fadeUpdateScheduled = true; requestAnimationFrame(() => { this.fadeUpdateScheduled = false; this.updateFadeState(); }); }, { passive: true }, ); } // QA_AT-450 — nav clicks are wired BEFORE the fadeOnly bail-out. In fadeOnly // mode (small touch devices) the drag/momentum/scrollend machinery below is // deliberately skipped, but the arrows are still rendered and tappable, so // they must move the wrapper. Programmatic `scrollTo`/`scrollBy` with an // explicit `behavior` animates even under `nativeswiper-nosnap`. // // Both closures are anonymous and `destroy()` never unbinds them, while it DOES // null `wrapper`. For `navigation`-prop consumers the arrow elements belong to // the parent and can outlive this swiper, so a late click must be a no-op rather // than deref a dead wrapper (`scrollToIndex` → `this.slides`, `navigationStep` → // `offsetWidth`, and the `scrollByPage` branch all read through it). if (this.prevBtn != null) { this.prevBtn.addEventListener('click', () => { if (this.wrapper == null) { return; } if (this.carousel) { this.carousel.slidePrev(); return; } if (this.scrollByPage) { this.wrapper.scrollBy({ left: -this.wrapper.clientWidth * 0.8, behavior: 'smooth' }); } else { this.scrollToIndex(this.getNavBaseIndex() - this.navigationStep); } }); } if (this.nextBtn != null) { this.nextBtn.addEventListener('click', () => { if (this.wrapper == null) { return; } if (this.carousel) { this.carousel.slideNext(); return; } if (this.scrollByPage) { this.wrapper.scrollBy({ left: this.wrapper.clientWidth * 0.8, behavior: 'smooth' }); } else { this.scrollToIndex(this.getNavBaseIndex() + this.navigationStep); } }); } if (this.fadeOnly) { return; } this.wrapper.addEventListener('scrollend', this.updateCurrentIndex); this.wrapper.addEventListener('mousedown', this.handleDragStart); this.wrapper.addEventListener('mousemove', this.handleDragMove); window.addEventListener('mouseup', this.handleDragEnd); this.wrapper.addEventListener('dragstart', e => e.preventDefault()); this.wrapper.addEventListener( 'touchstart', this.handleDragStart, { passive: false }, ); this.wrapper.addEventListener( 'touchmove', this.handleDragMove, { passive: false }, ); window.addEventListener('touchend', this.handleDragEnd); window.addEventListener('touchcancel', this.handleDragEnd); } // --- Drag and Momentum Logic --- handleDragStart(e) { if (e.button !== 0) { if (e.button === 1) { this.isDragging = false; this.wrapper.classList.add('dragging'); return; } this.isDragging = false; return; } this.isDragging = true; // The user takes over: a programmatic target still in flight is abandoned. this.pendingIndex = null; this.carousel?.interrupt(); this.startPos = e.pageX; this.draggedDistance = 0; this.startScrollLeft = this.wrapper.scrollLeft; this.wrapper.classList.add('dragging'); cancelAnimationFrame(this.momentumID); this.velocity = 0; this.lastTime = performance.now(); this.lastPos = this.startPos; } private updateFadeState() { if (!this.fadingEnabled || !this.container || !this.wrapper) { return; } const maxScrollLeft = this.wrapper.scrollWidth - this.wrapper.clientWidth; if (maxScrollLeft <= 0) { this.container.classList.remove('nativeswiper-fade-active'); this.container.style.setProperty('--nativeswiper-fade-left', '0'); this.container.style.setProperty('--nativeswiper-fade-right', '0'); return; } this.container.classList.add('nativeswiper-fade-active'); const leftVisible = !this.fadeLeftEnabled ? '0' : this.wrapper.scrollLeft > 0 ? '1' : '0'; const rightVisible = !this.fadeRightEnabled ? '0' : this.wrapper.scrollLeft < maxScrollLeft ? '1' : '0'; this.container.style.setProperty('--nativeswiper-fade-left', leftVisible); this.container.style.setProperty('--nativeswiper-fade-right', rightVisible); } /** Watches the rail's size; false when there is nothing to watch with (no ResizeObserver, no wrapper). */ private observeResize(): boolean { if (typeof ResizeObserver === 'undefined' || !this.wrapper) { return false; } this.resizeObserver = new ResizeObserver(() => { // A pending resize callback can fire after teardown — bail if the wrapper // is already gone so updateButtons/updateFadeState never touch null. if (this.wrapper == null) { return; } if (!this.fadeOnly) { this.updateButtons(); } else if (this.carousel) { this.applyButtonState(); } this.updateFadeState(); }); this.resizeObserver.observe(this.wrapper); return true; } handleDragMove(e) { if (!this.isDragging) { return; } const currentPos = e.pageX; const diff = currentPos - this.startPos; this.draggedDistance = Math.abs(diff); // *** NEW: Only prevent default if it's a real drag *** // This prevents the click event from being suppressed on tiny mouse movements. if (this.draggedDistance > this.clickThreshold) { e.preventDefault(); // Prevents text selection } this.wrapper.scrollLeft = this.startScrollLeft - diff; this.updateFadeState(); // Calculate velocity for momentum const now = performance.now(); const elapsed = now - this.lastTime; if (elapsed > 20) { const distance = currentPos - this.lastPos; this.velocity = (distance / elapsed) * 20; // Velocity multiplier this.lastPos = currentPos; this.lastTime = now; } } handleDragEnd() { if (!this.isDragging) { return; } this.isDragging = false; // `settleAfterDrag`: no coasting — the carousel moves on to a slide and gives the snap back. if (this.carousel?.settlesAfterDrag) { this.carousel.settleAfterDrag(this.velocity); } else { this.momentumID = requestAnimationFrame(this.momentumScroll); } // Prevent click if dragged more than the threshold if (this.draggedDistance > this.clickThreshold) { const preventClick = (evt) => { evt.preventDefault(); evt.stopPropagation(); this.wrapper.removeEventListener( 'click', preventClick, { capture: true }, ); }; this.wrapper.addEventListener( 'click', preventClick, { capture: true }, ); } } momentumScroll() { if (Math.abs(this.velocity) < 0.2) { // this.wrapper.classList.remove('dragging'); return; } this.wrapper.scrollLeft -= this.velocity; this.velocity *= 0.95; // Damping factor this.updateFadeState(); this.momentumID = requestAnimationFrame(this.momentumScroll); } snapTo(targetScrollLeft) { const currentScroll = this.wrapper.scrollLeft; const distance = targetScrollLeft - currentScroll; // If we are very close to the target, stop the animation. if (Math.abs(distance) < 10) { this.wrapper.scrollLeft = targetScrollLeft; // Set the final, precise position this.wrapper.classList.remove('dragging'); // NOW it's safe to re-enable CSS snap // The browser's 'scrollend' event will fire, updating the index and buttons. return; } // Move a fraction of the remaining distance each frame. // This creates a smooth ease-out animation. this.wrapper.scrollLeft += distance * 0.15; // The easing factor (0.15) can be adjusted // Continue the animation on the next frame. this.momentumID = requestAnimationFrame(() => this.snapTo(targetScrollLeft)); } destroy() { if (this.momentumID) { cancelAnimationFrame(this.momentumID); this.momentumID = 0; } if (this.resizeObserver) { this.resizeObserver.disconnect(); this.resizeObserver = undefined; } if (this.wrapper) { this.wrapper.removeEventListener('mousedown', this.handleDragStart); this.wrapper.removeEventListener('mousemove', this.handleDragMove); this.wrapper.removeEventListener('scrollend', this.updateCurrentIndex); this.wrapper.removeEventListener('touchstart', this.handleDragStart); this.wrapper.removeEventListener('touchmove', this.handleDragMove); } window.removeEventListener('mouseup', this.handleDragEnd); window.removeEventListener('touchend', this.handleDragEnd); window.removeEventListener('touchcancel', this.handleDragEnd); this.container = null; this.wrapper = null; this.prevBtn = null; this.nextBtn = null; } } export default toNative(NativeSwiper);