Compare commits

...

2 Commits

Author SHA1 Message Date
lyf
7caa671fe9 统一首页导览快捷按钮文案
Some checks failed
CI / verify (push) Has been cancelled
2026-07-14 11:08:36 +08:00
lyf
1f72926f58 修复微信内嵌返回层级 2026-07-14 10:58:41 +08:00
5 changed files with 424 additions and 56 deletions

View File

@@ -20,11 +20,10 @@
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import GuidePageFrame from '@/components/navigation/GuidePageFrame.vue'
import ExplainHallSelect, {
type ExplainBusinessUnitSelectItem,
type ExplainHallSelectItem
} from '@/components/explain/ExplainHallSelect.vue'
import {
@@ -69,53 +68,49 @@ const buildExplainHallItems = (
const shouldUseHostNavigation = computed(() => isEmbeddedInWechatMiniProgram())
const explainBusinessUnitItems = computed<ExplainBusinessUnitSelectItem[]>(() => (
[]))
type ExplainHistoryState = {
museumExplainList?: boolean
type ExplainListHistoryState = {
museumGuidePage?: 'explain-list'
[key: string]: unknown
}
let syncingExplainHistory = false
let applyingExplainHistory = false
let explainListHistoryPushed = false
let returningFromExplainListHistory = false
const currentExplainHistoryState = (): ExplainHistoryState => ({
museumExplainList: true
})
const isExplainListHistoryState = (state: unknown): state is ExplainListHistoryState => (
Boolean(
state
&& typeof state === 'object'
&& (state as ExplainListHistoryState).museumGuidePage === 'explain-list'
)
)
const writeExplainHistoryState = (replace = false) => {
const pushExplainListHistory = () => {
if (!shouldUseHostNavigation.value || typeof window === 'undefined') return
if (explainListHistoryPushed) return
syncingExplainHistory = true
const state = currentExplainHistoryState()
const url = window.location.href
if (replace) {
window.history.replaceState(state, '', url)
} else {
window.history.pushState(state, '', url)
if (isExplainListHistoryState(window.history.state)) {
explainListHistoryPushed = true
return
}
window.setTimeout(() => {
syncingExplainHistory = false
}, 0)
window.history.pushState({
...(window.history.state || {}),
museumGuidePage: 'explain-list'
} satisfies ExplainListHistoryState, '', window.location.href)
explainListHistoryPushed = true
}
const applyExplainHistoryState = async (state: ExplainHistoryState | null) => {
if (!state?.museumExplainList || applyingExplainHistory) return
const handleExplainListHistoryPopState = (event: PopStateEvent) => {
if (!shouldUseHostNavigation.value || returningFromExplainListHistory) return
applyingExplainHistory = true
applyingExplainHistory = false
}
if (isExplainListHistoryState(event.state)) {
explainListHistoryPushed = true
return
}
const handleExplainHistoryPopState = (event: PopStateEvent) => {
if (syncingExplainHistory) return
void applyExplainHistoryState((event.state || null) as ExplainHistoryState | null)
}
const replaceExplainStageHistory = () => {
writeExplainHistoryState(true)
explainListHistoryPushed = false
returningFromExplainListHistory = true
navigateToGuideTopTab('explain')
}
const loadExplainHalls = async () => {
@@ -144,21 +139,26 @@ const loadExplainHalls = async () => {
}
onLoad(() => {
replaceExplainStageHistory()
pushExplainListHistory()
void loadExplainHalls()
if (typeof window !== 'undefined') {
window.addEventListener('popstate', handleExplainHistoryPopState)
}
})
onUnload(() => {
if (typeof window !== 'undefined') {
window.removeEventListener('popstate', handleExplainHistoryPopState)
}
onMounted(() => {
if (typeof window === 'undefined') return
window.addEventListener('popstate', handleExplainListHistoryPopState)
})
onUnmounted(() => {
if (typeof window === 'undefined') return
window.removeEventListener('popstate', handleExplainListHistoryPopState)
})
const handleBack = () => {
if (shouldUseHostNavigation.value) {
navigateToGuideTopTab('explain')
return
}
uni.navigateBack({
delta: 1,
fail: () => {

View File

@@ -136,7 +136,7 @@
<view class="guide-quick-icon-floor top"></view>
<view class="guide-quick-icon-floor bottom"></view>
</view>
<text class="guide-quick-action-text">{{ indoorQuickActionLabel }}</text>
<text class="guide-quick-action-text">导览</text>
</view>
<view
class="guide-quick-action"
@@ -307,6 +307,7 @@ import {
isGuideTopTab,
type GuideTopTab
} from '@/utils/guideTopTabs'
import { isEmbeddedInWechatMiniProgram } from '@/utils/hostEnvironment'
import {
guideUseCase
} from '@/usecases/guideUseCase'
@@ -418,7 +419,7 @@ const guideMapShellRef = ref<{
} | null>(null)
const homeSearchPanelRef = ref<{
collapseHomePanel?: () => void
resetSearchState?: () => void
resetSearchState?: () => Promise<void> | void
returnToCollapsedAfterDetail?: () => Promise<void>
restoreResultListScroll?: () => Promise<void>
} | null>(null)
@@ -430,6 +431,14 @@ let searchTargetFocusRequestId = 0
let pendingCollapseSearchAfterDetail = false
let pendingSearchDetailFocusRequest: TargetPoiFocusRequestViewModel | null = null
type PoiSearchOverlayHistoryState = {
museumGuideOverlay?: 'poi-search'
[key: string]: unknown
}
let poiSearchHistoryPushed = false
let removingPoiSearchHistory = false
let launchOverlayFallbackTimer: ReturnType<typeof setTimeout> | null = null
let launchOverlayFadeTimer: ReturnType<typeof setTimeout> | null = null
let launchOverlayHideDelayTimer: ReturnType<typeof setTimeout> | null = null
@@ -662,9 +671,6 @@ const guideQuickActiveAction = computed<'indoor' | 'arrival' | 'explain'>(() =>
if (showArrivalPanel.value) return 'arrival'
return is3DMode.value ? 'indoor' : 'arrival'
})
const indoorQuickActionLabel = computed(() => (
is3DMode.value && indoorView.value !== 'overview' ? '外观' : '馆内'
))
const toRoutePointOption = (target: GuideRouteTarget): RoutePointOption => ({
poiId: target.poiId,
@@ -725,6 +731,87 @@ const syncTopTabToUrl = (tabId: GuideTopTab) => {
}
}
const isPoiSearchOverlayHistoryState = (state: unknown): state is PoiSearchOverlayHistoryState => (
Boolean(
state
&& typeof state === 'object'
&& (state as PoiSearchOverlayHistoryState).museumGuideOverlay === 'poi-search'
)
)
const canManagePoiSearchOverlayHistory = () => (
typeof window !== 'undefined'
&& isIndexHashRoute()
&& isEmbeddedInWechatMiniProgram()
)
const removePoiSearchOverlayFromCurrentHistoryState = () => {
if (!canManagePoiSearchOverlayHistory()) return
if (!isPoiSearchOverlayHistoryState(window.history.state)) return
const nextState = { ...window.history.state }
delete nextState.museumGuideOverlay
window.history.replaceState(nextState, '', window.location.href)
}
const pushPoiSearchOverlayHistory = () => {
if (!canManagePoiSearchOverlayHistory() || !homeSearchExpanded.value) return
if (poiSearchHistoryPushed) return
if (isPoiSearchOverlayHistoryState(window.history.state)) {
poiSearchHistoryPushed = true
return
}
window.history.pushState({
...(window.history.state || {}),
museumGuideOverlay: 'poi-search'
} satisfies PoiSearchOverlayHistoryState, '', window.location.href)
poiSearchHistoryPushed = true
}
const removePoiSearchOverlayHistory = () => {
if (!canManagePoiSearchOverlayHistory() || !poiSearchHistoryPushed) return
if (!isPoiSearchOverlayHistoryState(window.history.state)) {
poiSearchHistoryPushed = false
return
}
poiSearchHistoryPushed = false
removingPoiSearchHistory = true
window.history.back()
}
const collapsePoiSearchAfterHistoryBack = async () => {
homeSearchPanelRef.value?.collapseHomePanel?.()
await homeSearchPanelRef.value?.resetSearchState?.()
clearHomeSearchMapState()
selectedGuidePoi.value = null
isPoiCardCollapsed.value = false
homeSearchExpanded.value = false
}
const handlePoiSearchHistoryPopState = (event: PopStateEvent) => {
if (!canManagePoiSearchOverlayHistory()) return
if (removingPoiSearchHistory) {
removingPoiSearchHistory = false
poiSearchHistoryPushed = false
if (homeSearchExpanded.value) pushPoiSearchOverlayHistory()
return
}
if (!homeSearchExpanded.value) return
if (isPoiSearchOverlayHistoryState(event.state)) {
poiSearchHistoryPushed = true
return
}
poiSearchHistoryPushed = false
void collapsePoiSearchAfterHistoryBack()
}
const loadTopTabData = (tabId: GuideTopTab) => {
if (tabId === 'explain') {
void loadExplainHalls()
@@ -786,7 +873,9 @@ onMounted(() => {
if (typeof window === 'undefined') return
syncTopTabFromHash()
removePoiSearchOverlayFromCurrentHistoryState()
window.addEventListener('hashchange', syncTopTabFromHash)
window.addEventListener('popstate', handlePoiSearchHistoryPopState)
})
onUnmounted(() => {
@@ -800,6 +889,7 @@ onUnmounted(() => {
if (typeof window === 'undefined') return
window.removeEventListener('hashchange', syncTopTabFromHash)
window.removeEventListener('popstate', handlePoiSearchHistoryPopState)
})
onLoad((options: any = {}) => {
@@ -1412,6 +1502,12 @@ const handleExplainQuickTap = () => {
const handleHomeSearchExpandedChange = (expanded: boolean) => {
homeSearchExpanded.value = expanded
if (expanded) {
pushPoiSearchOverlayHistory()
return
}
removePoiSearchOverlayHistory()
}
const clearHomeSearchMapState = () => {

View File

@@ -1,5 +1,12 @@
export type GuideTopTab = 'guide' | 'explain'
export const GUIDE_LOCATION_PREVIEW_STORAGE_KEY = 'museum-guide:last-location-preview-url'
const HOST_NAVIGATION_QUERY_KEYS = [
'embedded',
'embed',
'host',
'weapp',
'mini-program'
]
export const GUIDE_TOP_TABS: Array<{ id: GuideTopTab; label: string }> = [
{ id: 'guide', label: '馆内' },
@@ -10,7 +17,32 @@ export const isGuideTopTab = (value: unknown): value is GuideTopTab => {
return value === 'guide' || value === 'explain'
}
export const guideTopTabUrl = (tab: GuideTopTab) => `/pages/index/index?tab=${tab}`
const getHostNavigationQueryParams = () => {
if (typeof window === 'undefined') return new URLSearchParams()
const searchParams = new URLSearchParams(window.location.search)
const hash = window.location.hash || ''
const hashQueryStart = hash.indexOf('?')
if (hashQueryStart >= 0) {
const hashParams = new URLSearchParams(hash.slice(hashQueryStart + 1))
hashParams.forEach((value, key) => {
if (!searchParams.has(key)) searchParams.set(key, value)
})
}
const hostParams = new URLSearchParams()
HOST_NAVIGATION_QUERY_KEYS.forEach((key) => {
const value = searchParams.get(key)
if (value !== null) hostParams.set(key, value)
})
return hostParams
}
export const guideTopTabUrl = (tab: GuideTopTab) => {
const params = new URLSearchParams({ tab })
getHostNavigationQueryParams().forEach((value, key) => params.set(key, value))
return `/pages/index/index?${params.toString()}`
}
export const saveLastGuideLocationPreviewUrl = (url: string) => {
if (typeof window === 'undefined' || !url) return

View File

@@ -0,0 +1,129 @@
// @vitest-environment happy-dom
import { defineComponent } from 'vue'
import { flushPromises, mount } from '@vue/test-utils'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import ExplainListPage from '@/pages/explain/list.vue'
const hostEnvironmentMocks = vi.hoisted(() => ({
embeddedInWechatMiniProgram: false
}))
const testState = vi.hoisted(() => ({
onLoadHandler: null as null | (() => void)
}))
vi.mock('@dcloudio/uni-app', () => ({
onLoad: (handler: () => void) => {
testState.onLoadHandler = handler
}
}))
vi.mock('@/utils/hostEnvironment', () => ({
isEmbeddedInWechatMiniProgram: () => hostEnvironmentMocks.embeddedInWechatMiniProgram
}))
vi.mock('@/usecases/explainUseCase', () => ({
explainUseCase: {
loadExplainHalls: async () => [],
loadExplainHallSummaries: async () => ({})
}
}))
const GuidePageFrameStub = defineComponent({
name: 'GuidePageFrame',
template: '<main><slot /></main>'
})
const ExplainHallSelectStub = defineComponent({
name: 'ExplainHallSelect',
emits: ['back'],
template: '<button data-testid="explain-list-back" @click="$emit(\'back\')">返回</button>'
})
const mountExplainList = () => mount(ExplainListPage, {
global: {
stubs: {
GuidePageFrame: GuidePageFrameStub,
ExplainHallSelect: ExplainHallSelectStub
}
}
})
beforeEach(() => {
hostEnvironmentMocks.embeddedInWechatMiniProgram = false
testState.onLoadHandler = null
window.location.hash = '#/pages/explain/list'
window.history.replaceState({}, '', window.location.href)
vi.stubGlobal('uni', {
navigateBack: vi.fn(),
redirectTo: vi.fn(),
reLaunch: vi.fn()
})
})
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
describe('讲解展厅列表返回', () => {
it('微信内嵌时不调用 navigateBack并保留宿主标识返回首页讲解 Tab', async () => {
hostEnvironmentMocks.embeddedInWechatMiniProgram = true
window.location.hash = '#/pages/explain/list?embedded=wechat-mini-program&weapp=1&mini-program=1'
window.history.replaceState({}, '', window.location.href)
const wrapper = mountExplainList()
const pushState = vi.spyOn(window.history, 'pushState')
testState.onLoadHandler?.()
await flushPromises()
await wrapper.get('[data-testid="explain-list-back"]').trigger('click')
expect(pushState).toHaveBeenCalledWith(
expect.objectContaining({ museumGuidePage: 'explain-list' }),
'',
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()
})
it('微信内嵌浏览器返回时回到首页讲解 Tab', async () => {
hostEnvironmentMocks.embeddedInWechatMiniProgram = true
window.location.hash = '#/pages/explain/list?embedded=wechat-mini-program&weapp=1'
window.history.replaceState({}, '', window.location.href)
const wrapper = mountExplainList()
testState.onLoadHandler?.()
await flushPromises()
window.dispatchEvent(new PopStateEvent('popstate', { state: {} }))
await flushPromises()
expect(uni.navigateBack).not.toHaveBeenCalled()
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')
wrapper.unmount()
})
it('普通 H5 保持原有 navigateBack 行为', async () => {
const wrapper = mountExplainList()
await wrapper.get('[data-testid="explain-list-back"]').trigger('click')
expect(uni.navigateBack).toHaveBeenCalledWith(expect.objectContaining({ delta: 1 }))
expect(uni.reLaunch).not.toHaveBeenCalled()
wrapper.unmount()
})
})

View File

@@ -10,9 +10,14 @@ const testState = vi.hoisted(() => ({
searchUnmountCount: 0,
searchRestoreCount: 0,
searchCollapseAfterDetailCount: 0,
searchResetCount: 0,
onShowHandler: null as null | (() => Promise<void> | void)
}))
const hostEnvironmentMocks = vi.hoisted(() => ({
embeddedInWechatMiniProgram: false
}))
vi.mock('@dcloudio/uni-app', () => ({
onLoad: vi.fn(),
onShow: (handler: () => Promise<void> | void) => {
@@ -20,6 +25,10 @@ vi.mock('@dcloudio/uni-app', () => ({
}
}))
vi.mock('@/utils/hostEnvironment', () => ({
isEmbeddedInWechatMiniProgram: () => hostEnvironmentMocks.embeddedInWechatMiniProgram
}))
const floors = [
{ id: 'L1', label: '1F', order: 1 },
{ id: 'L2', label: '2F', order: 2 }
@@ -100,7 +109,9 @@ const PoiSearchPanelStub = defineComponent({
},
methods: {
collapseHomePanel() {},
resetSearchState() {},
resetSearchState() {
testState.searchResetCount += 1
},
returnToCollapsedAfterDetail() {
testState.searchCollapseAfterDetailCount += 1
},
@@ -152,10 +163,12 @@ const mountIndex = async () => {
}
beforeEach(() => {
hostEnvironmentMocks.embeddedInWechatMiniProgram = false
testState.searchMountCount = 0
testState.searchUnmountCount = 0
testState.searchRestoreCount = 0
testState.searchCollapseAfterDetailCount = 0
testState.searchResetCount = 0
testState.onShowHandler = null
window.history.replaceState({}, '', '/#/pages/index/index?tab=guide')
vi.stubGlobal('uni', {
@@ -168,10 +181,96 @@ beforeEach(() => {
})
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
describe('首页搜索与地图闭环', () => {
it('微信内嵌展开搜索只写入一条覆盖层历史记录', async () => {
hostEnvironmentMocks.embeddedInWechatMiniProgram = true
window.location.hash = '#/pages/index/index?tab=guide&embedded=wechat-mini-program'
window.history.replaceState({}, '', window.location.href)
const wrapper = await mountIndex()
const search = wrapper.getComponent(PoiSearchPanelStub)
const pushState = vi.spyOn(window.history, 'pushState')
search.vm.$emit('expanded-change', true)
await flushPromises()
expect(pushState).toHaveBeenCalledTimes(1)
expect(pushState).toHaveBeenLastCalledWith(
expect.objectContaining({ museumGuideOverlay: 'poi-search' }),
'',
window.location.href
)
search.vm.$emit('expanded-change', true)
await flushPromises()
expect(pushState).toHaveBeenCalledTimes(1)
wrapper.unmount()
})
it('微信内嵌搜索返回消费 popstate 并回到首页收缩态', async () => {
hostEnvironmentMocks.embeddedInWechatMiniProgram = true
window.location.hash = '#/pages/index/index?tab=guide&embedded=wechat-mini-program'
window.history.replaceState({}, '', window.location.href)
const wrapper = await mountIndex()
const search = wrapper.getComponent(PoiSearchPanelStub)
const currentUrl = window.location.href
search.vm.$emit('expanded-change', true)
await flushPromises()
window.dispatchEvent(new PopStateEvent('popstate', { state: {} }))
await flushPromises()
expect(testState.searchResetCount).toBeGreaterThan(0)
expect(window.location.href).toBe(currentUrl)
expect(wrapper.getComponent(GuideMapShellStub).props('visiblePoiIds')).toBeNull()
wrapper.unmount()
})
it('微信内嵌搜索多次展开和收缩不会累积覆盖层历史', async () => {
hostEnvironmentMocks.embeddedInWechatMiniProgram = true
window.location.hash = '#/pages/index/index?tab=guide&embedded=wechat-mini-program'
window.history.replaceState({}, '', window.location.href)
const wrapper = await mountIndex()
const search = wrapper.getComponent(PoiSearchPanelStub)
let currentHistoryState: Record<string, unknown> = {}
vi.spyOn(window.history, 'state', 'get').mockImplementation(() => currentHistoryState)
const pushState = vi.spyOn(window.history, 'pushState').mockImplementation((state) => {
currentHistoryState = state as Record<string, unknown>
})
const historyBack = vi.spyOn(window.history, 'back').mockImplementation(() => {
currentHistoryState = {}
window.dispatchEvent(new PopStateEvent('popstate', { state: {} }))
})
search.vm.$emit('expanded-change', true)
search.vm.$emit('expanded-change', false)
await flushPromises()
search.vm.$emit('expanded-change', true)
search.vm.$emit('expanded-change', false)
await flushPromises()
expect(pushState).toHaveBeenCalledTimes(2)
expect(historyBack).toHaveBeenCalledTimes(2)
expect(currentHistoryState).not.toMatchObject({ museumGuideOverlay: 'poi-search' })
wrapper.unmount()
})
it('普通 H5 展开搜索不写入覆盖层历史,也不消费浏览器返回', async () => {
const wrapper = await mountIndex()
const search = wrapper.getComponent(PoiSearchPanelStub)
const pushState = vi.spyOn(window.history, 'pushState')
search.vm.$emit('expanded-change', true)
window.dispatchEvent(new PopStateEvent('popstate', { state: {} }))
await flushPromises()
expect(pushState).not.toHaveBeenCalled()
expect(testState.searchResetCount).toBe(0)
wrapper.unmount()
})
it('同步首页标签时保留内嵌宿主参数', async () => {
window.location.hash = '#/pages/index/index?tab=guide&embedded=wechat-mini-program'
@@ -180,14 +279,26 @@ describe('首页搜索与地图闭环', () => {
expect(window.location.hash).toBe('#/pages/index/index?tab=guide&embedded=wechat-mini-program')
})
it('首页暂不展示来馆入口及其到馆面板', async () => {
it('首页暂不展示来馆入口,导览快捷按钮文案固定且保留原切换行为', async () => {
const wrapper = await mountIndex()
const map = wrapper.getComponent(GuideMapShellStub)
const guideAction = wrapper.findAll('.guide-quick-action')[0]
expect(wrapper.text()).not.toContain('来馆')
expect(wrapper.findAll('.guide-quick-action').map((item) => item.text())).toEqual([
'馆内',
'导览',
'讲解'
])
await guideAction.trigger('tap')
await flushPromises()
expect(map.props('indoorView')).toBe('floor')
expect(wrapper.findAll('.guide-quick-action')[0]?.text()).toBe('导览')
await guideAction.trigger('tap')
await flushPromises()
expect(map.props('indoorView')).toBe('overview')
expect(wrapper.findAll('.guide-quick-action')[0]?.text()).toBe('导览')
})
it('向搜索面板传入当前楼层,并将分类结果 ID 精确传给地图', async () => {