/** * The carousel behaviour of NativeSwiper: what its `speed`, `autoplay`, `hasPagination`, `loop`, `settleAfterDrag` and * `slideChanged` props ask for. NativeSwiper builds one only when its `carousel` prop hands it this class * (`carousel={NativeSwiperCarousel}`), so a page loads this file only through a carousel that does: a plain rail neither * runs nor downloads it. * * Swiper 12 is the model (the carousels that use these props ran on it before). A move runs as Swiper's did: a CSS * `transform` transition of `speed` ms on the `ease` curve, which the browser's compositor runs — no script runs per * frame. Autoplay waits `delay` from the end of each move and rewinds from the last slide, rests while the mouse is on * the carousel and while the page is hidden, and resumes with the time that was left. Finger swipes stay the browser's * own scrolling; the carousel only learns where they settle. */ export interface NativeSwiperAutoplay { delay: number; /** Stop for good once the visitor swipes or drags (Swiper's option); otherwise rest during the gesture. */ disableOnInteraction?: boolean; /** Rest while the mouse is on the carousel. */ pauseOnMouseEnter?: boolean; } export interface NativeSwiperSlideChangedArgs { activeIndex: number; previousIndex: number; } export type NativeSwiperEvent = 'slideChange' | 'paginationUpdate'; /** What `NativeSwiper.getSwiperInstance()` hands out — the part of a Swiper instance its carousels used. */ export interface NativeSwiperHandle { /** The `.nativeswiper-container`. */ readonly el: HTMLElement; readonly slides: HTMLElement[]; readonly activeIndex: number; readonly params: { pagination: { clickable: boolean } | false }; readonly pagination: { el: HTMLElement | null; bullets: HTMLElement[] }; readonly autoplay: { readonly running: boolean; readonly paused: boolean; start: () => void; stop: () => void }; on: (event: NativeSwiperEvent, handler: () => void) => void; off: (event: NativeSwiperEvent, handler: () => void) => void; slideTo: (index: number, speed?: number) => void; slideNext: () => void; slidePrev: () => void; } export interface NativeSwiperCarouselOptions { container: HTMLElement; wrapper: HTMLElement; slideGap: number; /** Duration of a move, ms. */ speed: number; autoplay?: NativeSwiperAutoplay; pagination: { clickable: boolean } | false; loop: boolean; settleAfterDrag: boolean; /** The active slide changed: NativeSwiper redraws its bullets and calls its `slideChanged`. */ activeIndexChanged: (args: NativeSwiperSlideChangedArgs) => void; } /** A flick: the pointer's last speed (px per 20 ms) above which a drag carries on to the next slide. */ const FLICK_VELOCITY = 2; /** Where `scrollend` is unknown (older Safari), a scroll counts as settled this long after its last `scroll` event. */ const SETTLE_DELAY = 120; /** Read once: the DOM typings always declare `onscrollend`, so an inline `in` check would narrow `window` to `never`. */ const SCROLLEND_SUPPORTED = typeof window !== 'undefined' && 'onscrollend' in window; export class NativeSwiperCarousel implements NativeSwiperHandle { readonly el: HTMLElement; readonly autoplay: NativeSwiperHandle['autoplay']; private readonly wrapper: HTMLElement; private readonly options: NativeSwiperCarouselOptions; private readonly handlers = new Map void>>(); private index = 0; private destroyed = false; private animating = false; /** The slides a move carries, each running its transition back to its place. */ private moving: HTMLElement[] = []; /** Where the move under way put the offset: a scroll that leaves it is the visitor's. */ private moveTarget = 0; private moveTimer = 0; /** Puts the slide a wrap-around moved back in its place, if one is under way. */ private finishWrap: (() => void) | null = null; private syncButtons: (() => void) | null = null; private userScrolling = false; private settleTimer = 0; private running = false; private paused = false; private timer = 0; private timeLeft = 0; private timerStartedAt: number | null = null; private pausedByPointer = false; private pausedByGesture = false; private pausedByHidden = false; constructor(options: NativeSwiperCarouselOptions) { this.options = options; this.el = options.container; this.wrapper = options.wrapper; // Live getters (a caller may keep the object and read `running` later), with arrow functions so `this` stays bound. this.autoplay = Object.defineProperties({ start: (): void => this.startAutoplay(), stop: (): void => this.stopAutoplay(), }, { running: { get: (): boolean => this.running, enumerable: true }, paused: { get: (): boolean => this.paused, enumerable: true }, }) as NativeSwiperHandle['autoplay']; this.wrapper.addEventListener( 'scroll', this.onScroll, { passive: true }, ); this.wrapper.addEventListener('scrollend', this.onScrollEnd); if (options.autoplay != null) { this.wrapper.addEventListener('pointerdown', this.onInteractionStart); this.wrapper.addEventListener( 'touchstart', this.onInteractionStart, { passive: true }, ); this.wrapper.addEventListener( 'wheel', this.onWheel, { passive: true }, ); window.addEventListener('pointerup', this.onInteractionEnd); window.addEventListener('touchend', this.onInteractionEnd); window.addEventListener('touchcancel', this.onInteractionEnd); document.addEventListener('visibilitychange', this.onVisibilityChange); if (options.autoplay.pauseOnMouseEnter) { this.el.addEventListener('pointerenter', this.onPointerEnter); this.el.addEventListener('pointerleave', this.onPointerLeave); } this.startAutoplay(); } } get slides(): HTMLElement[] { return Array.from(this.wrapper.children) as HTMLElement[]; } get activeIndex(): number { return this.index; } get params(): NativeSwiperHandle['params'] { return { pagination: this.options.pagination }; } get pagination(): NativeSwiperHandle['pagination'] { const el = Array.from(this.el.children).find(child => child.classList.contains('nativeswiper-pagination')) as HTMLElement | undefined; return { el: el ?? null, bullets: el == null ? [] : Array.from(el.children) as HTMLElement[], }; } /** Whether the arrows wrap around (they are then never disabled). */ get loops(): boolean { return this.options.loop; } get settlesAfterDrag(): boolean { return this.options.settleAfterDrag; } /** NativeSwiper hands over the provider's arrow-state update once the provider exists. */ attachButtons(sync: () => void): void { this.syncButtons = sync; } on(event: NativeSwiperEvent, handler: () => void): void { if (!this.handlers.has(event)) { this.handlers.set(event, new Set()); } this.handlers.get(event)!.add(handler); } off(event: NativeSwiperEvent, handler: () => void): void { this.handlers.get(event)?.delete(handler); } emit(event: NativeSwiperEvent): void { for (const handler of [...(this.handlers.get(event) ?? [])]) { handler(); } } slideTo(index: number, speed: number = this.options.speed): void { if (this.destroyed) { return; } // The move under way stops first: its slides, still translated, widen the scroll range the target is clamped to. this.beginMove(); const target = Math.max(0, Math.min(Math.round(index), this.maxIndex())); this.setIndex(target); this.animateMove( this.offsetOf(target), speed, () => this.moveEnded(), ); } slideNext(): void { if (this.destroyed) { return; } // A click during a move reads the rail with that move stopped (see `slideTo`). this.interrupt(); if (this.index < this.maxIndex()) { this.slideTo(this.index + 1); return; } if (this.options.loop && this.slides.length > 1) { this.loopAround('forward'); } } slidePrev(): void { if (this.destroyed) { return; } this.interrupt(); if (this.index > 0) { this.slideTo(this.index - 1); return; } if (this.options.loop && this.slides.length > 1) { this.loopAround('backward'); } } /** * The visitor took over (a drag, a finger, a wheel) or another move begins: the move under way stops where it shows — * the offset takes over what is left of the slides' translation — and a wrap-around first puts its slide back. A settle * that will not finish gives the snap back here — a new drag puts `dragging` straight back on. */ interrupt(): void { if (this.moving.length > 0) { const shown = this.wrapper.scrollLeft - this.translationOf(this.moving[0]); this.stopMove(); this.wrapper.scrollLeft = shown; } this.finishWrap?.(); this.finishWrap = null; this.animating = false; this.el.classList.remove('nativeswiper-animating'); if (this.options.settleAfterDrag) { this.wrapper.classList.remove('dragging'); } } /** * `settleAfterDrag`: the provider let go of a mouse / touch drag. A flick carries on one slide in its direction from * the slide the drag began on; any other drag ends on the nearest slide. The `dragging` class goes as the move begins * (the move holds the rail meanwhile), so snapping is back once it is done. * * @param velocity the pointer's last speed as the provider measures it: px per 20 ms, negative towards the next slide. */ settleAfterDrag(velocity: number): void { if (this.destroyed) { return; } let target = this.indexAt(this.wrapper.scrollLeft); if (Math.abs(velocity) >= FLICK_VELOCITY) { target = Math.max(0, Math.min(this.index + (velocity < 0 ? 1 : -1), this.maxIndex())); } this.beginMove(); this.setIndex(target); this.animateMove( this.offsetOf(target), this.options.speed, () => this.moveEnded(), ); } destroy(): void { if (this.destroyed) { return; } this.destroyed = true; this.stopAutoplay(); this.stopMove(); window.clearTimeout(this.settleTimer); this.finishWrap = null; this.syncButtons = null; this.handlers.clear(); this.wrapper.removeEventListener('scroll', this.onScroll); this.wrapper.removeEventListener('scrollend', this.onScrollEnd); this.wrapper.removeEventListener('pointerdown', this.onInteractionStart); this.wrapper.removeEventListener('touchstart', this.onInteractionStart); this.wrapper.removeEventListener('wheel', this.onWheel); window.removeEventListener('pointerup', this.onInteractionEnd); window.removeEventListener('touchend', this.onInteractionEnd); window.removeEventListener('touchcancel', this.onInteractionEnd); document.removeEventListener('visibilitychange', this.onVisibilityChange); this.el.removeEventListener('pointerenter', this.onPointerEnter); this.el.removeEventListener('pointerleave', this.onPointerLeave); } // --- Geometry: uniform slides, as the provider assumes --- private step(): number { const first = this.wrapper.children[0] as HTMLElement | undefined; return (first?.offsetWidth ?? 0) + this.options.slideGap; } private maxScrollLeft(): number { return Math.max(0, this.wrapper.scrollWidth - this.wrapper.clientWidth); } /** The last slide a move can reach: the one whose offset first meets the end of the scroll range. */ private maxIndex(): number { const step = this.step(); if (step <= 0 || this.slides.length === 0) { return 0; } return Math.max(0, Math.min(this.slides.length - 1, Math.ceil(this.maxScrollLeft() / step - 0.001))); } private offsetOf(index: number): number { return Math.min(index * this.step(), this.maxScrollLeft()); } private indexAt(scrollLeft: number): number { const step = this.step(); if (step <= 0) { return 0; } if (scrollLeft >= this.maxScrollLeft() - 1) { return this.maxIndex(); } return Math.max(0, Math.min(Math.round(scrollLeft / step), this.maxIndex())); } private setIndex(index: number): void { if (index === this.index) { return; } const previousIndex = this.index; this.index = index; // Swiper resets a resting autoplay's time left on a slide change: the slide a visitor swipes to gets its whole delay. if (this.paused) { this.timeLeft = this.options.autoplay!.delay; } this.options.activeIndexChanged({ activeIndex: index, previousIndex }); this.emit('slideChange'); } // --- Moves --- private beginMove(): void { this.interrupt(); window.clearTimeout(this.timer); this.timer = 0; this.timerStartedAt = null; } /** * Moves the view to the offset `to` over `duration` ms the way Swiper moved its track: a CSS `transform` transition on * the `ease` curve, which the browser's compositor runs — no script runs per frame, so a busy page does not stutter it. * The offset jumps to `to` at once, held (no smooth scrolling, no snap); the slides the view passes start translated * by that jump, so nothing moves yet, and their transition back to their place is the move. `drawn` lists the slides * in the order they are drawn (a wrap-around draws one at the other end). */ private animateMove( to: number, duration: number, done: () => void, drawn: HTMLElement[] = this.slides, ): void { const from = this.wrapper.scrollLeft; const moving = duration > 0 && Math.abs(to - from) >= 1 ? this.slidesBetween( drawn, from, to, ) : []; // Held for a jump too (Swiper's 0 ms move): the wrapper's own `scroll-behavior: smooth` would animate the write. this.el.classList.add('nativeswiper-animating'); this.wrapper.scrollLeft = to; if (moving.length === 0) { this.endMove(done); return; } for (const slide of moving) { slide.style.transition = 'none'; slide.style.transform = `translate3d(${to - from}px, 0, 0)`; } // A transition runs from a computed value: computing the start now gives it one. this.translationOf(moving[0]); for (const slide of moving) { slide.style.transition = `transform ${duration}ms ease`; slide.style.transform = 'translate3d(0, 0, 0)'; } this.moving = moving; this.moveTarget = to; this.animating = true; this.moveTimer = window.setTimeout(() => this.endMove(done), duration); } /** * The move is over: the slides drop their transition and `done` runs, still held — it may move the offset (a * wrap-around's jump back to the real slide) — and the hold goes after it, unless `done` began another move. */ private endMove(done: () => void): void { this.stopMove(); this.animating = false; done(); if (!this.animating) { this.el.classList.remove('nativeswiper-animating'); } } private stopMove(): void { window.clearTimeout(this.moveTimer); this.moveTimer = 0; for (const slide of this.moving) { slide.style.removeProperty('transition'); slide.style.removeProperty('transform'); } this.moving = []; } /** * The slides the view passes on its way from `from` to `to`, with one more on each side so nothing at the view's * edges (a card's shadow) stays behind. The rest are out of view the whole move, so they stay put. */ private slidesBetween( drawn: HTMLElement[], from: number, to: number, ): HTMLElement[] { const step = this.step(); const width = step - this.options.slideGap; const start = Math.min(from, to) - step; const end = Math.max(from, to) + this.wrapper.clientWidth + step; return drawn.filter((_slide, index) => index * step < end && index * step + width > start); } /** The x translation a slide shows now — mid-transition, how far the compositor has carried it. */ private translationOf(slide: HTMLElement): number { const transform = getComputedStyle(slide).transform; const matrix = /^matrix(3d)?\(([^)]*)\)$/.exec(transform); if (matrix != null) { return Number.parseFloat(matrix[2].split(',')[matrix[1] ? 12 : 4]); } // A browser reports a matrix; jsdom reports the value as declared. const translate = /translate(?:3d|X)?\(\s*(-?[\d.]+)/.exec(transform); return translate == null ? 0 : Number.parseFloat(translate[1]); } /** * `loop` past an end. A view of one slide wraps round seamlessly ({@link wrap}); a view of several rewinds to the other * end, as Swiper's `rewind`: the wrap draws one slide at the other end, and the view would jump once its move ended. */ private loopAround(direction: 'forward' | 'backward'): void { if (this.maxIndex() < this.slides.length - 1) { this.slideTo(direction === 'forward' ? 0 : this.maxIndex()); return; } this.wrap(direction); } /** * `loop` arrows: past the last slide the first follows, before the first the last. The slide is drawn at the other end * with flex `order` and the offset moved by one step in the same frame, so nothing jumps; the move then runs one slide * on, and once it is done the slide goes back and the offset lands on its real place. * * The gap moves with it: the slides' margin follows the DOM (`:not(:last-child)`), not `order`, so while the slide is * drawn at the other end, the slide before the seam takes a gap and the one drawn last drops its own — every slide * keeps its step, as Swiper's did (it gave every slide its margin). */ private wrap(direction: 'forward' | 'backward'): void { const slides = this.slides; const lastIndex = slides.length - 1; const moved = direction === 'forward' ? slides[0] : slides[lastIndex]; const beforeSeam = direction === 'forward' ? slides[lastIndex] : moved; const drawnLast = direction === 'forward' ? moved : slides[lastIndex - 1]; const step = this.step(); const landing = direction === 'forward' ? 0 : lastIndex; this.beginMove(); // Snap off before the layout changes. this.el.classList.add('nativeswiper-animating'); moved.style.order = direction === 'forward' ? '1' : '-1'; beforeSeam.style.marginRight = `${this.options.slideGap}px`; drawnLast.style.marginRight = '0px'; this.wrapper.scrollLeft = direction === 'forward' ? this.wrapper.scrollLeft - step : this.wrapper.scrollLeft + step; this.finishWrap = () => { moved.style.order = ''; beforeSeam.style.removeProperty('margin-right'); drawnLast.style.removeProperty('margin-right'); this.wrapper.scrollLeft = this.offsetOf(landing); }; this.setIndex(landing); this.animateMove( direction === 'forward' ? Math.min(lastIndex * step, this.maxScrollLeft()) : 0, this.options.speed, () => { this.finishWrap?.(); this.finishWrap = null; this.moveEnded(); }, direction === 'forward' ? [ ...slides.slice(1), moved, ] : [ moved, ...slides.slice(0, lastIndex), ], ); } private moveEnded(): void { this.syncButtons?.(); if (!this.running) { return; } if (this.pausedByGesture) { this.pausedByGesture = false; this.resumeAutoplay(); return; } if (this.pausedByPointer || this.pausedByHidden) { this.paused = true; this.timeLeft = this.options.autoplay!.delay; return; } this.schedule(this.options.autoplay!.delay); } // --- A visitor's scroll --- private onScroll = (): void => { if (this.destroyed) { return; } if (this.animating) { // A move's own jump lands here once. Any other offset is the visitor's — a finger, a wheel, a trackpad — and takes // the rail over where it shows, as Swiper gave way to the first touch move; a tap that does not scroll leaves it. if (Math.abs(this.wrapper.scrollLeft - this.moveTarget) <= 1) { return; } this.interrupt(); } this.userScrolling = true; if (!SCROLLEND_SUPPORTED) { window.clearTimeout(this.settleTimer); this.settleTimer = window.setTimeout(this.onScrollEnd, SETTLE_DELAY); } }; private onScrollEnd = (): void => { if (this.animating || this.destroyed) { return; } this.userScrolling = false; this.setIndex(this.indexAt(this.wrapper.scrollLeft)); this.syncButtons?.(); if (this.pausedByGesture) { this.pausedByGesture = false; this.resumeAutoplay(); } }; // --- Autoplay --- private startAutoplay(): void { if (this.destroyed || this.options.autoplay == null) { return; } this.running = true; this.paused = false; this.pausedByGesture = false; this.schedule(this.options.autoplay.delay); } private stopAutoplay(): void { this.running = false; this.paused = false; window.clearTimeout(this.timer); this.timer = 0; this.timerStartedAt = null; } private schedule(ms: number): void { window.clearTimeout(this.timer); this.paused = false; this.timeLeft = ms; this.timerStartedAt = performance.now(); this.timer = window.setTimeout(this.autoplayStep, ms); } private autoplayStep = (): void => { this.timer = 0; this.timerStartedAt = null; if (!this.running || this.paused || this.destroyed) { return; } if (this.maxIndex() === 0) { this.schedule(this.options.autoplay!.delay); return; } if (this.index < this.maxIndex() || this.options.loop) { this.slideNext(); } else { this.slideTo(0); } }; /** Rests with the time that is left. */ private pauseAutoplay(): void { if (!this.running || this.paused) { return; } this.paused = true; window.clearTimeout(this.timer); this.timer = 0; if (this.timerStartedAt != null) { this.timeLeft = Math.max(0, this.timeLeft - (performance.now() - this.timerStartedAt)); } this.timerStartedAt = null; } /** Goes on with the time that was left — unless the mouse is still on the carousel or the page is hidden. */ private resumeAutoplay(): void { if (!this.running || !this.paused || this.pausedByPointer || this.pausedByHidden || this.destroyed) { return; } this.schedule(this.timeLeft); } private onPointerEnter = (e: PointerEvent): void => { if (e.pointerType !== 'mouse') { return; } this.pausedByPointer = true; if (!this.animating) { this.pauseAutoplay(); } }; private onPointerLeave = (e: PointerEvent): void => { if (e.pointerType !== 'mouse') { return; } this.pausedByPointer = false; if (!this.pausedByGesture) { this.resumeAutoplay(); } }; private onVisibilityChange = (): void => { if (document.visibilityState === 'hidden') { this.pausedByHidden = true; this.pauseAutoplay(); return; } if (this.pausedByHidden) { this.pausedByHidden = false; this.resumeAutoplay(); } }; /** A finger, a pressed mouse button or a sideways wheel on the rail: the visitor is moving it. */ private onInteractionStart = (): void => { if (!this.running) { return; } if (this.options.autoplay?.disableOnInteraction) { this.stopAutoplay(); return; } if (!this.paused) { this.pauseAutoplay(); this.pausedByGesture = true; } }; private onWheel = (e: WheelEvent): void => { if (Math.abs(e.deltaX) > Math.abs(e.deltaY)) { this.onInteractionStart(); } }; /** Let go without scrolling (a tap): nothing settles, so the rest ends here. */ private onInteractionEnd = (): void => { if (this.pausedByGesture && !this.userScrolling && !this.animating) { this.pausedByGesture = false; this.resumeAutoplay(); } }; }