文件
OmniCard/mpuniapp/pages/template/search-header-long-list/search-header-long-list.uvue

399 行
12 KiB
Plaintext

<template>
<scroll-view ref="pageScrollView" class="page" :bounces="false"
@startnestedscroll="onStartNestedScroll" @nestedprescroll="onNestedPreScroll"
:refresher-triggered="refresherTriggered" refresher-enabled="true" @refresherrefresh="onRefresherrefresh">
<view ref="header" class="search-bar">
<input placeholder="搜索..." :maxlength="-1"/>
</view>
<view class="swiper-list">
<scroll-view ref="tabScroll" class="swiper-tabs" direction="horizontal" :show-scrollbar="false">
<view class="flex-row" style="align-self: flex-start;">
<text ref="swipertab" class="swiper-tabs-item" :class="swiperIndex==index ? 'swiper-tabs-item-active' : ''"
v-for="(item, index) in swiperList" :key="index" @click="onTabClick(index)">
{{item.name}}
</text>
</view>
<view ref="indicator" class="swiper-tabs-indicator"></view>
</scroll-view>
<swiper ref="swiper" class="swiper-view" :current="swiperIndex" @transition="onSwiperTransition"
@animationfinish="onSwiperAnimationfinish">
<swiper-item class="swiper-item" v-for="(item, index) in swiperList" :key="index">
<long-page ref="longPageRef" :type="item.type" :preload="item.preload"></long-page>
</swiper-item>
</swiper>
</view>
</scroll-view>
</template>
<script setup lang="uts">
/**
* @description: 支持顶部搜索区域和横向分栏切换的长列表页面,列表内容随标签切换按需加载。
* @logic: 页面先展示搜索框和横向标签栏,再通过 swiper 切换不同分类的长列表,并联动更新下划线指示器位置。
* @optimization: 每个标签页只在首次切换到时触发数据加载,同时复用同一套指示器插值逻辑,减少初始渲染和切换开销。
*/
import longPage from './long-list-page.uvue';
type SwiperTabsItem = {
x : number,
w : number
}
type SwiperViewItem = {
id : string, // 唯一字符串
type : string,
name : string,
preload : boolean,
}
type JestTabsPageState = {
swiperIndex : number,
animationFinishIndex : number,
tabCount : number,
currentType : string,
currentName : string,
currentPreload : boolean,
}
/**
* 根据权重在两个值之间执行线性插值.
* @constructor
* @param {number} value1 - 第一个值,该值应为下限.
* @param {number} value2 - 第二个值,该值应为上限.
* @param {number} amount - 应介于 0 和 1 之间,指示内插的权重.
* @returns {number} 内插值
*/
function lerpNumber(value1 : number, value2 : number, amount : number) : number {
return (value1 + (value2 - value1) * amount)
}
// 响应式变量
const swiperList = ref<SwiperViewItem[]>([
{
id: 'updated', // 唯一字符串
type: 'UpdatedDate',
name: '最新上架',
preload: true
},
{
id: 'free',
type: 'FreeHot',
name: '免费热榜',
preload: false
},
{
id: 'payment',
type: 'PaymentHot',
name: '付费热榜',
preload: false
},
{
id: 'hot',
type: 'HotList',
name: '热门总榜',
preload: false
}
])
const swiperIndex = ref(0)
const pageScrollView = ref<UniScrollViewElement|null>(null)
const header = ref<UniElement|null>(null)
const tabScroll = ref<UniScrollViewElement|null>(null)
const indicator = ref<UniElement|null>(null)
const swiper = ref<UniSwiperElement|null>(null)
const swipertab = ref<UniTextElement[]|null>(null)
const longPageRef = ref<ComponentPublicInstance[]|null>(null)
let headerHeight = 0
let animationFinishIndex = 0
let swiperWidth = 0
let swiperTabsRect: SwiperTabsItem[] = []
// 自动化测试中记录程序化切页的目标索引,避免立即读状态时拿到旧值。
let jestTargetSwiperIndex = -1
// 仅在自动化测试程序化切页时启用旧 animationfinish 事件保护。
let isTestFinishGuardEnabled = false
function onStartNestedScroll() : boolean {
return true
}
function onNestedPreScroll(event : NestedPreScrollEvent) {
const deltaY = event.deltaY
const scrollTop = pageScrollView.value!.scrollTop
// 优先处理父容器滚动,父容器不能滚动时滚动子
if (deltaY > 0) {
// 向上滚动,如果父容器 header scrollTop < offsetHeight,先滚动父容器
if (scrollTop < headerHeight) {
const difference = headerHeight - scrollTop - deltaY
if (difference > 0) {
pageScrollView.value!.scrollBy(event.deltaX, deltaY)
event.consumed(event.deltaX, deltaY)
} else {
const top : number = deltaY + difference
event.consumed(event.deltaX, top.toFloat())
pageScrollView.value!.scrollBy(event.deltaX, top.toFloat())
}
}
} else if (deltaY < 0) {
// 向下滚动,如果父容器 scrollTop > 0,通知子被父容器消耗,然后滚动到 0
if (scrollTop > 0) {
event.consumed(event.deltaX, deltaY)
pageScrollView.value!.scrollBy(event.deltaX, deltaY)
}
}
}
function updateTabIndicator(current_index : number, move_to_index : number, percentage : number) {
const current_size = swiperTabsRect[current_index]
const move_to_size = swiperTabsRect[move_to_index]
// 计算指示线 左边距 和 宽度 在移动过程中的线性值
const indicator_line_x = lerpNumber(current_size.x, move_to_size.x, percentage)
const indicator_line_w = lerpNumber(current_size.w, move_to_size.w, percentage)
// 更新指示线
// #ifdef APP
const x = indicator_line_x + indicator_line_w / 2
indicator.value?.style?.setProperty('transform', `translateX(${x}px) scaleX(${indicator_line_w})`)
// #endif
// #ifdef WEB || MP
// TODO chrome windows系统 transform scaleX渲染bug
const x = indicator_line_x
indicator.value?.style?.setProperty('width', `${indicator_line_w}px`)
indicator.value?.style?.setProperty('transform', `translateX(${x}px)`)
// #endif
// 滚动到水平中心位置
const scroll_x = x - swiperWidth / 2
// app 平台后续支持 scrollTo()
// #ifndef MP-WEIXIN
tabScroll.value!.scrollLeft = scroll_x
// #endif
// #ifdef MP-WEIXIN
tabScroll.value!.scrollTo({
left: scroll_x
})
// #endif
}
function initSwiperItemData(index : number) {
if (index < 0 || index >= swiperList.value.length) {
return
}
if (!swiperList.value[index].preload) {
swiperList.value[index].preload = true;
(longPageRef.value as ComponentPublicInstance[])[index].$callMethod('loadData', null)
}
}
function onSwiperTransition(e : SwiperTransitionEvent) {
// 微信 skyline 每项完成触发 Animationfinish,偏移值重置
// 微信 webview 全部完成触发 Animationfinish,偏移值累加
// 在滑动到下一个项的过程中,再次反向滑动,偏移值递减
// uni-app-x 和微信 webview 行为一致
const offset_x = e.detail.dx
// 计算当前索引并重置差异
const current_offset_x = offset_x % swiperWidth
const current_offset_i = offset_x / swiperWidth
const current_index = animationFinishIndex + parseInt(current_offset_i + '')
// 计算目标索引及边界检查
let move_to_index = current_index
if (current_offset_x > 0 && move_to_index < swiperList.value.length - 1) {
move_to_index += 1
} else if (current_offset_x < 0 && move_to_index > 0) {
move_to_index -= 1
}
// 计算偏移百分比
const percentage = Math.abs(current_offset_x) / swiperWidth
// 通知更新指示线
if (current_index != move_to_index) {
updateTabIndicator(current_index, move_to_index, percentage)
}
// 首次可见时初始化数据
initSwiperItemData(move_to_index)
}
async function cacheTabItemsSize() {
swiperTabsRect.length = 0;
const tabs = swipertab.value as UniElement[]
for (let i = 0; i < tabs.length; i++) {
const element = tabs[i];
// #ifdef MP
const rect = await element.getBoundingClientRectAsync()!
const x = rect.left
const w = rect.width
// #endif
// #ifndef MP
const x = element.offsetLeft
const w = element.offsetWidth
// #endif
swiperTabsRect.push({
x,
w
} as SwiperTabsItem)
}
}
function setSwiperIndex(index : number, updateIndicator : boolean) {
if (swiperIndex.value === index) {
return
}
swiperIndex.value = index
initSwiperItemData(index)
if (updateIndicator) {
updateTabIndicator(index, index, 1)
}
}
function onTabClick(index : number) {
jestTargetSwiperIndex = -1
isTestFinishGuardEnabled = false
setSwiperIndex(index, false)
}
function onSwiperAnimationfinish(e : SwiperAnimationFinishEvent) {
// 自动化测试程序化切页时,忽略晚到的旧完成事件,避免把目标索引回写成旧值。
if (isTestFinishGuardEnabled && jestTargetSwiperIndex >= 0 && e.detail.current != jestTargetSwiperIndex) {
return
}
isTestFinishGuardEnabled = false
jestTargetSwiperIndex = -1
setSwiperIndex(e.detail.current, true)
animationFinishIndex = e.detail.current
}
onReady(() => {
headerHeight = (header.value as UniElement).offsetHeight
swiper.value!.getBoundingClientRectAsync()!.then((res : DOMRect) : Promise<void> => {
swiperWidth = res.width
return cacheTabItemsSize()
}).then(() => {
updateTabIndicator(swiperIndex.value, swiperIndex.value, 1)
});
})
const refresherTriggered = ref(false);
function onRefresherrefresh(e : UniRefresherEvent) {
refresherTriggered.value = true;
(longPageRef.value as ComponentPublicInstance[])[swiperIndex.value].$callMethod('refreshData', () => {
refresherTriggered.value = false;
})
}
// 自动化测试辅助
function jest_prepareMockData() : boolean {
const pageRefs = longPageRef.value
if (pageRefs == null || pageRefs.length == 0) {
return false
}
for (let i = 0; i < pageRefs.length; i++) {
pageRefs[i].$callMethod('jest_useMockData', i == swiperIndex.value)
swiperList.value[i].preload = i == swiperIndex.value
}
return true
}
function jest_setSwiperCurrent(index : number) : boolean {
if (index < 0 || index >= swiperList.value.length) {
return false
}
isTestFinishGuardEnabled = true
jestTargetSwiperIndex = index
swiperIndex.value = index
initSwiperItemData(index)
updateTabIndicator(index, index, 1)
animationFinishIndex = index
return true
}
function jest_getState() : JestTabsPageState {
const currentIndex = jestTargetSwiperIndex >= 0 ? jestTargetSwiperIndex : swiperIndex.value
const currentItem = swiperList.value[currentIndex]
return {
swiperIndex: currentIndex,
animationFinishIndex: animationFinishIndex,
tabCount: swiperList.value.length,
currentType: currentItem.type,
currentName: currentItem.name,
currentPreload: currentItem.preload,
} as JestTabsPageState
}
function jest_getListState(index : number) : UTSJSONObject | null {
if (index < 0 || index >= swiperList.value.length || longPageRef.value == null) {
return null
}
return longPageRef.value[index].$callMethod('jest_getState', null) as UTSJSONObject | null
}
defineExpose({
jest_prepareMockData,
jest_setSwiperCurrent,
jest_getState,
jest_getListState,
})
</script>
<style>
.flex-row {
flex-direction: row;
}
.page {
flex: 1;
}
.search-bar {
padding: 10px;
}
.swiper-list {
height: 100%;
/* #ifdef WEB */
flex: 1;
/* #endif */
}
.swiper-tabs {
background-color: #ffffff;
flex-direction: column;
}
.swiper-tabs-item {
color: #555;
font-size: 16px;
padding: 12px 25px;
white-space: nowrap;
}
.swiper-tabs-item-active {
color: #007AFF;
}
.swiper-tabs-indicator {
width: 1px;
height: 2px;
background-color: #007AFF;
}
.swiper-view {
flex: 1;
}
.swiper-item {
/* flex: 1; harmony 高度异常 */
height: 100%;
}
</style>