修复讲解展厅列表返回导览首页
Some checks failed
CI / verify (push) Has been cancelled

This commit is contained in:
lyf
2026-07-14 15:23:19 +08:00
parent ec4c3e36cd
commit 04c6ccd40b
2 changed files with 210 additions and 54 deletions

View File

@@ -21,7 +21,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue' import { computed, onMounted, onUnmounted, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app' import { onBackPress, onLoad } from '@dcloudio/uni-app'
import GuidePageFrame from '@/components/navigation/GuidePageFrame.vue' import GuidePageFrame from '@/components/navigation/GuidePageFrame.vue'
import ExplainHallSelect, { import ExplainHallSelect, {
type ExplainHallSelectItem type ExplainHallSelectItem
@@ -33,6 +33,7 @@ import type {
MuseumHall MuseumHall
} from '@/domain/museum' } from '@/domain/museum'
import { import {
guideTopTabUrl,
navigateToGuideTopTab, navigateToGuideTopTab,
type GuideTopTab type GuideTopTab
} from '@/utils/guideTopTabs' } from '@/utils/guideTopTabs'
@@ -68,13 +69,71 @@ const buildExplainHallItems = (
const shouldUseHostNavigation = computed(() => isEmbeddedInWechatMiniProgram()) const shouldUseHostNavigation = computed(() => isEmbeddedInWechatMiniProgram())
const GUIDE_HOME_URL = '/pages/index/index?tab=guide'
type ExplainListHistoryState = { type ExplainListHistoryState = {
museumGuidePage?: 'explain-list' museumGuidePage?: 'explain-list'
[key: string]: unknown [key: string]: unknown
} }
let explainListHistoryPushed = false let explainListHistoryPushed = false
let returningFromExplainListHistory = false let isReturningToGuideHome = false
type PageStackEntry = {
route?: string
options?: {
tab?: string | string[]
}
}
const getPageStack = () => (
typeof getCurrentPages === 'function' ? getCurrentPages() as PageStackEntry[] : []
)
const guideHomeUrl = () => (
shouldUseHostNavigation.value ? guideTopTabUrl('guide') : GUIDE_HOME_URL
)
const showGuideHomeReturnError = () => {
isReturningToGuideHome = false
uni.showToast({
title: '返回导览首页失败,请重试',
icon: 'none'
})
}
const reLaunchGuideHome = () => {
uni.reLaunch({
url: guideHomeUrl(),
fail: showGuideHomeReturnError
})
}
const returnToGuideHome = () => {
if (isReturningToGuideHome) return
isReturningToGuideHome = true
const pages = getPageStack()
const previousPage = pages.length > 1 ? pages[pages.length - 2] : null
const previousRoute = previousPage?.route || ''
const previousTab = Array.isArray(previousPage?.options?.tab)
? previousPage.options.tab[0]
: previousPage?.options?.tab
const canNavigateBackToGuideHome = (
previousRoute === 'pages/index/index'
&& (!previousTab || previousTab === 'guide')
)
if (canNavigateBackToGuideHome) {
uni.navigateBack({
delta: 1,
fail: reLaunchGuideHome
})
return
}
reLaunchGuideHome()
}
const isExplainListHistoryState = (state: unknown): state is ExplainListHistoryState => ( const isExplainListHistoryState = (state: unknown): state is ExplainListHistoryState => (
Boolean( Boolean(
@@ -85,7 +144,7 @@ const isExplainListHistoryState = (state: unknown): state is ExplainListHistoryS
) )
const pushExplainListHistory = () => { const pushExplainListHistory = () => {
if (!shouldUseHostNavigation.value || typeof window === 'undefined') return if (typeof window === 'undefined' || getPageStack().length > 1) return
if (explainListHistoryPushed) return if (explainListHistoryPushed) return
if (isExplainListHistoryState(window.history.state)) { if (isExplainListHistoryState(window.history.state)) {
@@ -101,7 +160,8 @@ const pushExplainListHistory = () => {
} }
const handleExplainListHistoryPopState = (event: PopStateEvent) => { const handleExplainListHistoryPopState = (event: PopStateEvent) => {
if (!shouldUseHostNavigation.value || returningFromExplainListHistory) return if (isReturningToGuideHome) return
if (!explainListHistoryPushed) return
if (isExplainListHistoryState(event.state)) { if (isExplainListHistoryState(event.state)) {
explainListHistoryPushed = true explainListHistoryPushed = true
@@ -109,8 +169,7 @@ const handleExplainListHistoryPopState = (event: PopStateEvent) => {
} }
explainListHistoryPushed = false explainListHistoryPushed = false
returningFromExplainListHistory = true returnToGuideHome()
navigateToGuideTopTab('explain')
} }
const loadExplainHalls = async () => { const loadExplainHalls = async () => {
@@ -153,26 +212,12 @@ onUnmounted(() => {
window.removeEventListener('popstate', handleExplainListHistoryPopState) window.removeEventListener('popstate', handleExplainListHistoryPopState)
}) })
const handleBack = () => { onBackPress(() => {
if (shouldUseHostNavigation.value) { returnToGuideHome()
navigateToGuideTopTab('explain') return true
return })
}
uni.navigateBack({ const handleBack = returnToGuideHome
delta: 1,
fail: () => {
uni.redirectTo({
url: '/pages/index/index?tab=explain',
fail: () => {
uni.reLaunch({
url: '/pages/index/index?tab=explain'
})
}
})
}
})
}
const handleTopTabChange = (tab: GuideTopTab) => { const handleTopTabChange = (tab: GuideTopTab) => {
navigateToGuideTopTab(tab) navigateToGuideTopTab(tab)

View File

@@ -10,12 +10,16 @@ const hostEnvironmentMocks = vi.hoisted(() => ({
})) }))
const testState = vi.hoisted(() => ({ const testState = vi.hoisted(() => ({
onLoadHandler: null as null | (() => void) onLoadHandler: null as null | (() => void),
onBackPressHandler: null as null | (() => boolean)
})) }))
vi.mock('@dcloudio/uni-app', () => ({ vi.mock('@dcloudio/uni-app', () => ({
onLoad: (handler: () => void) => { onLoad: (handler: () => void) => {
testState.onLoadHandler = handler testState.onLoadHandler = handler
},
onBackPress: (handler: () => boolean) => {
testState.onBackPressHandler = handler
} }
})) }))
@@ -32,7 +36,8 @@ vi.mock('@/usecases/explainUseCase', () => ({
const GuidePageFrameStub = defineComponent({ const GuidePageFrameStub = defineComponent({
name: 'GuidePageFrame', name: 'GuidePageFrame',
template: '<main><slot /></main>' emits: ['back'],
template: '<main><button data-testid="frame-back" @click="$emit(\'back\')">顶部返回</button><slot /></main>'
}) })
const ExplainHallSelectStub = defineComponent({ const ExplainHallSelectStub = defineComponent({
@@ -53,13 +58,15 @@ const mountExplainList = () => mount(ExplainListPage, {
beforeEach(() => { beforeEach(() => {
hostEnvironmentMocks.embeddedInWechatMiniProgram = false hostEnvironmentMocks.embeddedInWechatMiniProgram = false
testState.onLoadHandler = null testState.onLoadHandler = null
testState.onBackPressHandler = null
window.location.hash = '#/pages/explain/list' window.location.hash = '#/pages/explain/list'
window.history.replaceState({}, '', window.location.href) window.history.replaceState({}, '', window.location.href)
vi.stubGlobal('uni', { vi.stubGlobal('uni', {
navigateBack: vi.fn(), navigateBack: vi.fn(),
redirectTo: vi.fn(), reLaunch: vi.fn(),
reLaunch: vi.fn() showToast: vi.fn()
}) })
vi.stubGlobal('getCurrentPages', vi.fn(() => []))
}) })
afterEach(() => { afterEach(() => {
@@ -68,39 +75,110 @@ afterEach(() => {
}) })
describe('讲解展厅列表返回', () => { describe('讲解展厅列表返回', () => {
it('微信内嵌时不调用 navigateBack并保留宿主标识返回首页讲解 Tab', async () => { it('首页通过内部页面栈进入时,顶部返回使用 navigateBack 回到导览首页', async () => {
hostEnvironmentMocks.embeddedInWechatMiniProgram = true vi.stubGlobal('getCurrentPages', vi.fn(() => [
window.location.hash = '#/pages/explain/list?embedded=wechat-mini-program&weapp=1&mini-program=1' { route: 'pages/index/index', options: { tab: 'guide' } },
window.history.replaceState({}, '', window.location.href) { route: 'pages/explain/list', options: {} }
]))
const wrapper = mountExplainList() const wrapper = mountExplainList()
const pushState = vi.spyOn(window.history, 'pushState')
testState.onLoadHandler?.() testState.onLoadHandler?.()
await flushPromises() await flushPromises()
await wrapper.get('[data-testid="explain-list-back"]').trigger('click') await wrapper.get('[data-testid="frame-back"]').trigger('click')
expect(pushState).toHaveBeenCalledWith( expect(uni.navigateBack).toHaveBeenCalledWith(expect.objectContaining({ delta: 1 }))
expect.objectContaining({ museumGuidePage: 'explain-list' }), expect(uni.reLaunch).not.toHaveBeenCalled()
'',
window.location.href
)
expect(uni.navigateBack).not.toHaveBeenCalled()
expect(uni.reLaunch).toHaveBeenCalledTimes(1)
const url = vi.mocked(uni.reLaunch).mock.calls[0]?.[0]?.url || ''
const query = new URLSearchParams(url.split('?')[1])
expect(url.split('?')[0]).toBe('/pages/index/index')
expect(query.get('tab')).toBe('explain')
expect(query.get('embedded')).toBe('wechat-mini-program')
expect(query.get('weapp')).toBe('1')
expect(query.get('mini-program')).toBe('1')
wrapper.unmount() wrapper.unmount()
}) })
it('微信内嵌浏览器返回时回到首页讲解 Tab', async () => { it('页面栈只有展厅列表时使用 reLaunch 回到导览首页', async () => {
const wrapper = mountExplainList()
await wrapper.get('[data-testid="explain-list-back"]').trigger('click')
expect(uni.navigateBack).not.toHaveBeenCalled()
expect(uni.reLaunch).toHaveBeenCalledWith(expect.objectContaining({
url: '/pages/index/index?tab=guide'
}))
wrapper.unmount()
})
it('上一页不是首页时使用 reLaunch避免回到不相关页面', async () => {
vi.stubGlobal('getCurrentPages', vi.fn(() => [
{ route: 'pages/search/index', options: {} },
{ route: 'pages/explain/list', options: {} }
]))
const wrapper = mountExplainList()
await wrapper.get('[data-testid="explain-list-back"]').trigger('click')
expect(uni.navigateBack).not.toHaveBeenCalled()
expect(uni.reLaunch).toHaveBeenCalledWith(expect.objectContaining({
url: '/pages/index/index?tab=guide'
}))
wrapper.unmount()
})
it('上一页是首页但不是导览 Tab 时重启到导览首页', async () => {
vi.stubGlobal('getCurrentPages', vi.fn(() => [
{ route: 'pages/index/index', options: { tab: 'explain' } },
{ route: 'pages/explain/list', options: {} }
]))
const wrapper = mountExplainList()
await wrapper.get('[data-testid="explain-list-back"]').trigger('click')
expect(uni.navigateBack).not.toHaveBeenCalled()
expect(uni.reLaunch).toHaveBeenCalledWith(expect.objectContaining({
url: '/pages/index/index?tab=guide'
}))
wrapper.unmount()
})
it('navigateBack 失败后重启到导览首页', async () => {
vi.stubGlobal('getCurrentPages', vi.fn(() => [
{ route: 'pages/index/index', options: { tab: 'guide' } },
{ route: 'pages/explain/list', options: {} }
]))
vi.stubGlobal('uni', {
navigateBack: vi.fn((options: { fail?: () => void }) => options.fail?.()),
reLaunch: vi.fn(),
showToast: vi.fn()
})
const wrapper = mountExplainList()
await wrapper.get('[data-testid="explain-list-back"]').trigger('click')
expect(uni.reLaunch).toHaveBeenCalledWith(expect.objectContaining({
url: '/pages/index/index?tab=guide'
}))
wrapper.unmount()
})
it('重启导览首页失败时显示明确提示', async () => {
vi.stubGlobal('uni', {
navigateBack: vi.fn(),
reLaunch: vi.fn((options: { fail?: () => void }) => options.fail?.()),
showToast: vi.fn()
})
const wrapper = mountExplainList()
await wrapper.get('[data-testid="explain-list-back"]').trigger('click')
expect(uni.showToast).toHaveBeenCalledWith({
title: '返回导览首页失败,请重试',
icon: 'none'
})
wrapper.unmount()
})
it('根栈只创建一条历史标记,浏览器返回会回到导览首页', async () => {
hostEnvironmentMocks.embeddedInWechatMiniProgram = true hostEnvironmentMocks.embeddedInWechatMiniProgram = true
window.location.hash = '#/pages/explain/list?embedded=wechat-mini-program&weapp=1' window.location.hash = '#/pages/explain/list?embedded=wechat-mini-program&weapp=1'
window.history.replaceState({}, '', window.location.href) window.history.replaceState({}, '', window.location.href)
const wrapper = mountExplainList() const wrapper = mountExplainList()
const pushState = vi.spyOn(window.history, 'pushState')
testState.onLoadHandler?.()
testState.onLoadHandler?.() testState.onLoadHandler?.()
await flushPromises() await flushPromises()
@@ -108,22 +186,55 @@ describe('讲解展厅列表返回', () => {
await flushPromises() await flushPromises()
expect(uni.navigateBack).not.toHaveBeenCalled() expect(uni.navigateBack).not.toHaveBeenCalled()
expect(pushState).toHaveBeenCalledTimes(1)
const url = vi.mocked(uni.reLaunch).mock.calls[0]?.[0]?.url || '' const url = vi.mocked(uni.reLaunch).mock.calls[0]?.[0]?.url || ''
const query = new URLSearchParams(url.split('?')[1]) const query = new URLSearchParams(url.split('?')[1])
expect(url.split('?')[0]).toBe('/pages/index/index') expect(url.split('?')[0]).toBe('/pages/index/index')
expect(query.get('tab')).toBe('explain') expect(query.get('tab')).toBe('guide')
expect(query.get('embedded')).toBe('wechat-mini-program') expect(query.get('embedded')).toBe('wechat-mini-program')
expect(query.get('weapp')).toBe('1') expect(query.get('weapp')).toBe('1')
wrapper.unmount() wrapper.unmount()
}) })
it('普通 H5 保持原有 navigateBack 行为', async () => { it('普通 H5 浏览器返回也会回到导览首页,且不调用 history.back', async () => {
const historyBack = vi.spyOn(window.history, 'back')
const wrapper = mountExplainList() const wrapper = mountExplainList()
testState.onLoadHandler?.()
await wrapper.get('[data-testid="explain-list-back"]').trigger('click') window.dispatchEvent(new PopStateEvent('popstate', { state: {} }))
await flushPromises()
expect(uni.navigateBack).toHaveBeenCalledWith(expect.objectContaining({ delta: 1 })) expect(uni.reLaunch).toHaveBeenCalledWith(expect.objectContaining({
url: '/pages/index/index?tab=guide'
}))
expect(historyBack).not.toHaveBeenCalled()
wrapper.unmount()
})
it('正常内部页面栈不创建历史标记,并保留框架原有浏览器返回', async () => {
vi.stubGlobal('getCurrentPages', vi.fn(() => [
{ route: 'pages/index/index', options: { tab: 'guide' } },
{ route: 'pages/explain/list', options: {} }
]))
const wrapper = mountExplainList()
const pushState = vi.spyOn(window.history, 'pushState')
testState.onLoadHandler?.()
window.dispatchEvent(new PopStateEvent('popstate', { state: {} }))
await flushPromises()
expect(pushState).not.toHaveBeenCalled()
expect(uni.reLaunch).not.toHaveBeenCalled() expect(uni.reLaunch).not.toHaveBeenCalled()
wrapper.unmount() wrapper.unmount()
}) })
it('平台返回事件复用同一返回策略并阻止默认退出', () => {
const wrapper = mountExplainList()
expect(testState.onBackPressHandler?.()).toBe(true)
expect(uni.reLaunch).toHaveBeenCalledWith(expect.objectContaining({
url: '/pages/index/index?tab=guide'
}))
wrapper.unmount()
})
}) })