Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/swiper-lifecycle/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
bundle.js
42 changes: 42 additions & 0 deletions examples/swiper-lifecycle/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# H5 Swiper 生命周期手工复现

用于验证 PR #19353 / Issue #19522。直接使用编译后的 Stencil 组件和真实 Swiper,不修改实例内部字段。

## 准备

按仓库贡献指南安装依赖,构建 `@tarojs/components`。随后在仓库根目录执行:

```sh
pnpm --filter @tarojs/components exec esbuild ../../examples/swiper-lifecycle/index.js --bundle --format=iife --outfile=../../examples/swiper-lifecycle/bundle.js
```

使用 Chrome 打开本目录的 `index.html`,或通过已有静态服务访问。`bundle.js` 是本地产物,不提交。

## 操作顺序

1. 点击「挂载三图」,等待轮播开始。
2. 点击「卸载保留节点」。宿主从文档移除,仍保留引用。
3. 点击「切换 circular」,将其改为 false;等待页面状态更新。
4. 再次点击「切换 circular」,改回 true;等待页面状态更新。
5. 点击「追加一图」。
6. 在修复分支中继续点击「重新挂载」。

## 已观察结果

基线:main `4a1ea09a1b0`,Taro 4.3.0 / Swiper 11.1.15 / Stencil 2.22.3,Chrome。

- 卸载后旧实例仍自动播放。
- 断开期间切换 circular 会触发 reset,以全局选择器重建实例;节点不在文档中,构造出的实例没有有效 wrapper。
- 追加节点时抛出 `TypeError: Cannot read properties of undefined (reading 'children')`,堆栈为 `elementChildren → recalcSlides → loopDestroy → beforeDomOperation → appendChild`。

PR 分支:同一操作顺序没有捕获到异常;旧实例被销毁,重新挂载后四张图和 autoplay 恢复。

这是 H5 自定义元素脱离文档后仍被更新的复现,未证明 React 页面所有卸载方式都会执行后续操作,也不是线上 Taro 3.5.7 / Swiper 6 的完整用户操作还原。`getSwiperTranslate → loopFix → autoplay` 原始堆栈尚未复现。

## 自动化回归

`packages/taro-components/__tests__/swiper-lifecycle.spec.tsx` 使用现有 `newSpecPage` 和 Swiper mock 覆盖 11 个生命周期场景。最初 5 个场景在 main 基线失败;本轮新增索引覆盖回归,并将失效节点用例对齐真实 slidesEl 路径,两个针对用例在本轮修复前失败、修复后通过。当前 18 个 Swiper 用例及 7 个快照通过,新增旧实例事件隔离和子节点更新期间事件抑制回归。mock 场景与上面的真实浏览器结果分别记录。

当前实现仅在属性更新、外部子节点更新及连接/断开入口管理实例;不依赖 componentDidRender 重建。实例初始化成功后才保存引用,current 恢复索引显式传入 reset,不再维护额外 pending 标志。

脱离文档期间更新 `currentItemId` 的回归分别覆盖 circular 开启和关闭,以及最新值为空字符串的情况;连续更新只应用最新目标,应用后再次重连应保留用户后来滑到的位置。临时移除重连后的目标应用逻辑时,这 3 个新增用例全部失败;恢复修复后通过。mock 按真实循环初始化写入 `data-swiper-slide-index`,循环快照同步更新。
6 changes: 6 additions & 0 deletions examples/swiper-lifecycle/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<!doctype html><meta charset="utf-8"><title>Swiper 手工复现 — H5 生命周期</title>
<style>body{font:16px system-ui;margin:32px;max-width:900px}button{padding:12px;margin:6px}taro-swiper-core{display:block;width:600px;height:200px}taro-swiper-item-core{display:block;height:200px;text-align:center;line-height:200px;background:#d6e9f1}pre{white-space:pre-wrap;background:#eee;padding:16px}</style>
<h1>Swiper 手工复现 — H5 生命周期</h1><p>Taro main 4.3.0 / Swiper 11.1.15。此页用于手工演示生命周期。请分别使用 main 基线及 PR 分支构建产物验证。</p>
<button id="mount">1. 挂载三图</button><button id="detach">2. 卸载保留节点</button><button id="circular">3. 切换 circular</button><button id="autoplay">4. 切换 autoplay</button><button id="add">5. 追加一图</button><button id="reconnect">6. 重新挂载</button>
<div id="stage"></div><p id="state">尚未挂载</p><pre id="log"></pre>
<script src="./bundle.js"></script>
19 changes: 19 additions & 0 deletions examples/swiper-lifecycle/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { defineCustomElement } from '../../packages/taro-components/dist/components/taro-swiper-core.js'

defineCustomElement()

let host, instance, events=0;
const stage=document.getElementById('stage'), output=document.getElementById('log');
const log=s=>{output.textContent+=s+'\n'};
window.addEventListener('error',e=>log('ERROR: '+e.message+'\n'+(e.error?.stack||'')));
window.addEventListener('unhandledrejection',e=>log('REJECTION: '+(e.reason?.stack||e.reason)));
const originalError=console.error;console.error=(...args)=>{log('CONSOLE ERROR: '+args.map(x=>x?.stack||String(x)).join(' '));originalError(...args)};
const slide=n=>{const item=document.createElement('taro-swiper-item-core');item.className='swiper-slide';item.setAttribute('item-id',String(n));item.textContent='图片 '+n;return item};
const action=(id,fn)=>document.getElementById(id).onclick=()=>{try{fn()}catch(e){log('ERROR: '+e.stack)}};
action('mount',()=>{if(host){log('已有节点,请刷新页面重做');return}host=document.createElement('taro-swiper-core');host.circular=true;host.autoplay=true;host.interval=400;host.duration=100;for(let n=1;n<=3;n++)host.appendChild(slide(n));host.addEventListener('change',()=>events++);stage.appendChild(host);log('挂载三图 circular=true autoplay=true')});
action('detach',()=>{host.remove();log('卸载,保留节点引用')});
action('circular',()=>{host.circular=!host.circular;log('circular='+host.circular)});
action('autoplay',()=>{host.autoplay=!host.autoplay;log('autoplay='+host.autoplay)});
action('add',()=>{host.appendChild(slide(4));log('追加一图')});
action('reconnect',()=>{stage.appendChild(host);log('重新挂载同一节点')});
setInterval(()=>{if(!host)return;const current=host.querySelector('.swiper-container')?.swiper;if(current)instance=current;document.getElementById('state').textContent=JSON.stringify({connected:host.isConnected,circular:host.circular,autoplay:host.autoplay,initialized:instance?.initialized,destroyed:instance?.destroyed,running:instance?.autoplay?.running,realIndex:instance?.realIndex,events})},500);
65 changes: 56 additions & 9 deletions packages/taro-components/__mocks__/swiper/bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,26 @@ import { SwiperOptions } from 'swiper/types/swiper-options'
import type ISwiper from 'swiper/types/swiper-class'

export default class Swiper implements ISwiper {
initialized = false

constructor (el: string | HTMLElement, options: SwiperOptions = {}) {
this.params = options
this.el = typeof el === 'string' ? document.querySelector(el) as HTMLElement : el
this.realIndex = options.initialSlide || 0
this.activeIndex = this.realIndex
this.destroyed = false
this.autoplay = {
running: false,
paused: false,
timeLeft: 0,
start: () => { this.autoplay.running = true },
stop: () => { this.autoplay.running = false },
pause: () => { this.autoplay.paused = true },
resume: () => { this.autoplay.paused = false },
} as AutoplayMethods
if (options.init !== false) this.init()
}

originalParams: SwiperOptions
loopedSlides: number | null
snapIndex: number
Expand All @@ -44,12 +64,27 @@ export default class Swiper implements ISwiper {
throw new Error('Method not implemented.')
}

loopFix (): void {}

loopDestroy (): void {
throw new Error('Method not implemented.')
// Swiper 11 的 recalcSlides 从 slidesEl 读取子节点
Array.from(this.slidesEl.children)
}

init (el?: HTMLElement | undefined): ISwiper {
throw new Error('Method not implemented.')
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.slidesEl = this.wrapperEl
this.slides = Array.from(this.slidesEl.querySelectorAll('taro-swiper-item-core'))
if (this.params.loop) {
this.slides.forEach((slide, index) => slide.setAttribute('data-swiper-slide-index', String(index)))
}
this.initialized = true
if (this.params.autoplay) this.autoplay.start()
this.params.on?.init?.call(this, this)
return this
}

creativeEffect: CreativeEffectMethods
Expand All @@ -58,6 +93,9 @@ export default class Swiper implements ISwiper {
params: SwiperOptions
el: HTMLElement
wrapperEl: HTMLElement
slidesEl: HTMLElement
slidesGrid: number[]
slidesSizesGrid: number[]
slides
width: number
height: number
Expand All @@ -82,17 +120,21 @@ export default class Swiper implements ISwiper {

setProgress (progress: number, speed?: number | undefined): void {}

slideNext (speed?: number | undefined, runCallbacks?: boolean | undefined): void {}
slideNext (speed?: number | undefined, runCallbacks?: boolean | undefined): boolean { return true }

slidePrev (speed?: number | undefined, runCallbacks?: boolean | undefined): boolean { return true }

slidePrev (speed?: number | undefined, runCallbacks?: boolean | undefined): void {}
slideTo (index: number, speed?: number | undefined, runCallbacks?: boolean | undefined): boolean { return true }

slideTo (index: number, speed?: number | undefined, runCallbacks?: boolean | undefined): void {}
slideToLoop (index: number, speed?: number | undefined, runCallbacks?: boolean | undefined): ISwiper { return this }

slideToLoop (index: number, speed?: number | undefined, runCallbacks?: boolean | undefined): void {}
slideReset (speed?: number | undefined, runCallbacks?: boolean | undefined): boolean { return true }

slideReset (speed?: number | undefined, runCallbacks?: boolean | undefined): void {}
slideToClosest (speed?: number | undefined, runCallbacks?: boolean | undefined): boolean { return true }

slideToClosest (speed?: number | undefined, runCallbacks?: boolean | undefined): void {}
minTranslate (): number { return 0 }

maxTranslate (): number { return 0 }

updateAutoHeight (speed?: number | undefined): void {}

Expand All @@ -112,7 +154,12 @@ export default class Swiper implements ISwiper {

attachEvents (): void {}

destroy (deleteInstance?: boolean | undefined, cleanStyles?: boolean | undefined): void {}
destroy (deleteInstance?: boolean | undefined, cleanStyles?: boolean | undefined): void {
if (this.params.loop) this.loopDestroy()
this.autoplay.stop()
this.initialized = false
this.destroyed = true
}

appendSlide (slides: string | HTMLElement | string[] | HTMLElement[]): void {}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,15 +98,15 @@ exports[`Swiper should be circular 1`] = `
.taro-swiper-2 > .swiper-container > .swiper-pagination { display: none;font-size: 0; }
</style>
<div class="swiper-wrapper">
<taro-swiper-item-core class="swiper-slide">
<taro-swiper-item-core class="swiper-slide" data-swiper-slide-index="0">
<!---->
<div></div>
</taro-swiper-item-core>
<taro-swiper-item-core class="swiper-slide">
<taro-swiper-item-core class="swiper-slide" data-swiper-slide-index="1">
<!---->
<div></div>
</taro-swiper-item-core>
<taro-swiper-item-core class="swiper-slide">
<taro-swiper-item-core class="swiper-slide" data-swiper-slide-index="2">
<!---->
<div></div>
</taro-swiper-item-core>
Expand Down
Loading
Loading