Skip to content
Merged
Prev Previous commit
Next Next commit
fix(components): preserve pending swiper current and validate slides …
…element
  • Loading branch information
wangfangjie authored and Single-Dancer committed Oct 19, 2026
commit 91f0abe7f78d1a947fd0de8228c95f61a0bdabb7
2 changes: 1 addition & 1 deletion examples/swiper-lifecycle/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@ PR 分支:同一操作顺序没有捕获到异常;旧实例被销毁,重

## 自动化回归

`packages/taro-components/__tests__/swiper-lifecycle.spec.tsx` 使用现有 `newSpecPage` 和 Swiper mock 覆盖 5 个生命周期场景。main 基线均失败,修复后通过。mock 场景与上面的真实浏览器结果分别记录。
`packages/taro-components/__tests__/swiper-lifecycle.spec.tsx` 使用现有 `newSpecPage` 和 Swiper mock 覆盖 6 个生命周期场景。最初 5 个场景在 main 基线失败;本轮新增索引覆盖回归,并将失效节点用例对齐真实 slidesEl 路径,两个针对用例在本轮修复前失败、修复后通过。当前 13 个 Swiper 用例及 7 个快照通过。mock 场景与上面的真实浏览器结果分别记录。
9 changes: 6 additions & 3 deletions packages/taro-components/__mocks__/swiper/bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export default class Swiper implements ISwiper {
} as AutoplayMethods
if (options.init !== false) this.init()
}

originalParams: SwiperOptions
loopedSlides: number | null
snapIndex: number
Expand All @@ -64,16 +65,17 @@ export default class Swiper implements ISwiper {
}

loopDestroy (): void {
// 保留真实 Swiper 对无效 wrapper 的访问,用于验证生命周期保护
Array.from(this.wrapperEl.children)
// Swiper 11 的 recalcSlides 从 slidesEl 读取子节点
Array.from(this.slidesEl.children)
}

init (el?: HTMLElement | undefined): ISwiper {
if (el) this.el = el
if (!this.el) return this
this.wrapperEl = this.el.querySelector('.swiper-wrapper') as HTMLElement
if (!this.wrapperEl) return this
this.slides = Array.from(this.wrapperEl.querySelectorAll('taro-swiper-item-core'))
this.slidesEl = this.wrapperEl
this.slides = Array.from(this.slidesEl.querySelectorAll('taro-swiper-item-core'))
this.initialized = true
if (this.params.autoplay) this.autoplay.start()
this.params.on?.init?.call(this, this)
Expand Down Expand Up @@ -148,6 +150,7 @@ export default class Swiper implements ISwiper {
attachEvents (): void {}

destroy (deleteInstance?: boolean | undefined, cleanStyles?: boolean | undefined): void {
if (this.initialized && this.params.loop) this.loopDestroy()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

destroy (deleteInstance?: boolean | undefined, cleanStyles?: boolean | undefined): void {
  if (this.params.loop) this.loopDestroy()
  this.autoplay.stop()
  this.initialized = false
  this.destroyed = true
}
  • 去掉 this.initialized && 这个额外判断,因为真实 Swiper 的 destroy() 只看 params.loop,不看 initialized。

-loopDestroy mock 内部读取 this.slidesEl.children,slidesEl 在初始化失败时是 undefined,这样回归用例才能真实暴露“初始化失败 + destroy 二次抛错”的场景,而不是被 mock 静默护住。

  • 如果 mock loopDestroy 保持现在的 Array.from(this.slidesEl.children) 行为,同步把 mock 类中 slidesEl 的声明改成 slidesEl: HTMLElement | undefined,这样 TS 不会因为新的调用形态报错。

this.autoplay.stop()
this.initialized = false
this.destroyed = true
Expand Down
33 changes: 29 additions & 4 deletions packages/taro-components/__tests__/swiper-lifecycle.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { h } from '@stencil/core'
import { newSpecPage, SpecPage } from '@stencil/core/testing'

import { Swiper } from '../src/components/swiper/swiper'
import SwiperJS from '../__mocks__/swiper/bundle'
import { Swiper } from '../src/components/swiper/swiper'

type SwiperComponent = Omit<Swiper, never> & { swiper: SwiperJS }

Expand Down Expand Up @@ -48,6 +48,8 @@ describe('Swiper lifecycle', () => {
const loopDestroy = jest.spyOn(previous, 'loopDestroy')
page.root!.remove()
await page.waitForChanges()
expect(loopDestroy).toHaveBeenCalledTimes(1)
loopDestroy.mockClear()

page.root!.circular = false
page.root!.current = 2
Expand Down Expand Up @@ -108,13 +110,13 @@ describe('Swiper lifecycle', () => {
expect(instance.destroyed).toBe(true)
})

it('skips loopDestroy and recovers when the current wrapper becomes invalid', async () => {
it('skips loopDestroy and recovers when slidesEl becomes invalid', async () => {
const component = await mount()
const instance = component.swiper
const loopDestroy = jest.spyOn(instance, 'loopDestroy')
jest.useFakeTimers()
// 模拟 DOM 更新期间实例持有的 wrapper 已经失效,不直接改组件状态
instance.wrapperEl = undefined as unknown as HTMLElement
// 仅让真实循环方法访问的节点失效,验证 wrapper 仍存在时也受到保护
instance.slidesEl = undefined as unknown as HTMLElement
const child = page.doc.createElement('taro-swiper-item-core')
child.className = 'swiper-slide'

Expand All @@ -129,4 +131,27 @@ describe('Swiper lifecycle', () => {
expect(component.swiper.autoplay.running).toBe(true)
expect(component.swiper.wrapperEl.contains(child)).toBe(true)
})

it('preserves pending current through invalid-instance recovery and later saves the active slide', async () => {
const component = await mount()
const instance = component.swiper
instance.realIndex = 1
instance.wrapperEl = undefined as unknown as HTMLElement
instance.slidesEl = undefined as unknown as HTMLElement

page.root!.current = 2
await page.waitForChanges()

expect(component.swiper).not.toBe(instance)
expect(component.swiper.realIndex).toBe(2)

// 待应用索引生效后,普通卸载仍应保存用户后来滑到的位置
component.swiper.realIndex = 1
page.root!.remove()
await page.waitForChanges()
page.doc.body.appendChild(page.root!)
await page.waitForChanges()

expect(component.swiper.realIndex).toBe(1)
})
})
14 changes: 11 additions & 3 deletions packages/taro-components/src/components/swiper/swiper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export class Swiper implements ComponentInterface {
// dom 变化是否由外部引起,因为 swiper 的循环模式也会引起 dom 的变化。如果不是由外部引起的 dom 变化,就不需要重新初始化 swiper
#domChangeByOutSide = false
#lastSwiperActiveIndex = 0
#hasPendingCurrent = false
#didLoad = false
#container: HTMLElement | null = null
#sizeTimer: ReturnType<typeof setTimeout>
Expand All @@ -30,7 +31,7 @@ export class Swiper implements ComponentInterface {
private isSwiperReady (swiper = this.swiper): swiper is SwiperInstance {
return !!(this.el?.isConnected && swiper && swiper === this.swiper &&
!swiper.destroyed && swiper.initialized && swiper.el === this.#container &&
swiper.wrapperEl?.parentElement === this.#container)
swiper.wrapperEl?.parentElement === this.#container && swiper.slidesEl === swiper.wrapperEl)
}

@Element() el: HTMLElement
Expand Down Expand Up @@ -133,6 +134,7 @@ export class Swiper implements ComponentInterface {
const swiper = this.swiper
if (!this.isSwiperReady(swiper)) {
this.#lastSwiperActiveIndex = n
this.#hasPendingCurrent = true
return
}
if (n === swiper.realIndex) return
Expand Down Expand Up @@ -336,11 +338,16 @@ export class Swiper implements ComponentInterface {
this.observer = null
const swiper = this.swiper
if (swiper && !swiper.destroyed) {
this.#lastSwiperActiveIndex = swiper.realIndex
// 失效期间收到的 current 优先于旧实例的实际位置
if (!this.#hasPendingCurrent) this.#lastSwiperActiveIndex = swiper.realIndex
// 先切断回调对旧实例的引用,再停止自动播放和销毁实例
this.swiper = null
swiper.autoplay?.stop()
if (swiper.initialized && swiper.wrapperEl) swiper.destroy()
if (swiper.initialized && swiper.wrapperEl) {
// slidesEl 失效时跳过循环节点还原,仍释放实例的事件和观察器
if (!swiper.slidesEl) swiper.params.loop = false
swiper.destroy()
}
}
this.swiper = null
this.swiperWrapper = null
Expand Down Expand Up @@ -466,6 +473,7 @@ export class Swiper implements ComponentInterface {
this.destroySwiper()
return
}
this.#hasPendingCurrent = false

// Note: 这里是拦截了 swiper 的 minTranslate 和 maxTranslate 方法,手动修复了 loop 模式下的 margin 问题
// 因为这两个属性会影响滑动到哪个位置进行 fixloop
Expand Down