5 Commits

Author SHA1 Message Date
lyf
80ac62a5ff 修正讲解音频时长显示
Some checks failed
CI / verify (push) Has been cancelled
- 未加载媒体元数据时默认显示零时长
- 使用音频文件真实媒体时长更新播放器
- 避免使用不准确的接口时长覆盖播放器显示
- 补充音频时长回归测试

Made-with: Proma
2026-08-31 17:15:27 +08:00
lyf
5de005e011 优化编号讲解布局与返回流程
- 将讲解编号置于标题上方并增强辨识度
- 编号详情返回后保留输入界面并清空原编号
- 增加页面栈丢失时恢复编号输入页的兜底逻辑
- 补充编号布局和返回流程回归测试

Made-with: Proma
2026-08-31 17:00:42 +08:00
lyf
1c908dfc1a 展示展厅讲解对象编号
Some checks failed
CI / verify (push) Has been cancelled
- 接入目录分页接口返回的 externalCode 字段
- 在讲解对象标题下方统一展示编号
- 保留空编号对象的原有布局并补充回归测试

Made-with: Proma
2026-08-27 11:31:10 +08:00
lyf
ed52d22b63 修复讲解语音切换后播放器未刷新
- 暂停时切换语言或男女声同步刷新音轨、时长和进度
- 保持暂停状态,播放中继续自动切换新音轨
- 补充语音切换播放器刷新回归测试

Made-with: Proma
2026-08-27 11:00:45 +08:00
lyf
130f155bdf 接入编号讲解后端查询
Some checks failed
CI / verify (push) Has been cancelled
- 使用真实讲解编号解析接口替换本地演示映射
- 成功后复用现有详情页并自动播放讲解
- 增加查询状态、业务错误提示和相关测试

Made-with: Proma
2026-08-25 18:01:20 +08:00
21 changed files with 757 additions and 59 deletions

View File

@@ -25,7 +25,7 @@ VITE_PUBLIC_LEGACY_AUDIO_HOST=
# Vite 开发服务器代理目标,只由 vite.config.ts 读取。
# /engine 由 public/engine 本地静态资源提供,保持和大屏端一致,不再代理到地图管理端。
DEV_PROXY_APP_API_TARGET=http://localhost:48080
DEV_PROXY_APP_API_TARGET=https://guide.whaoyue.com:4433
DEV_PROXY_ENGINE_TARGET=
DEV_PROXY_SDK_TARGET=
DEV_PROXY_MUSEUM_ASSETS_TARGET=http://1.92.206.90:9000

View File

@@ -30,6 +30,7 @@
<text class="stop-cover-fallback">{{ stop.name.slice(0, 1) }}</text>
</view>
<view class="stop-copy">
<text v-if="stop.externalCode" class="stop-code">编号{{ stop.externalCode }}</text>
<text class="stop-name">{{ stop.name }}</text>
</view>
<view class="stop-status"><text class="stop-status-text">{{ availabilityLabel(stop) }}</text></view>
@@ -54,6 +55,7 @@ import GuideLoadingState from '@/components/navigation/GuideLoadingState.vue'
export interface ExplainGuideStopCatalogItem {
id: string
name: string
externalCode?: string
hallId?: string
hallName?: string
floorId?: string
@@ -153,6 +155,6 @@ const handleScroll = (event: Event) => { const target = event.target as HTMLElem
.header-back { position: absolute; left: 12px; top: 10px; width: 44px; height: 44px; display: flex; align-items: center; }.header-back-icon { width: 20px; height: 20px; position: relative; } .header-back-icon::before { content: ''; position: absolute; left: 3px; top: 4px; width: 10px; height: 10px; border-left: 1.5px solid #262421; border-bottom: 1.5px solid #262421; transform: rotate(45deg); }
.header-back-text { display: none; }.header-title { max-width: calc(100% - 152px); padding: 0 8px; font-size: 18px; line-height: 26px; font-weight: 700; color: #262421; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.explain-scroll { height: 100%; padding: 80px 16px calc(16px + env(safe-area-inset-bottom)); box-sizing: border-box; background: #f7f9f2; }.host-navigation .explain-scroll { padding-top: 16px; }
.stop-list { display: flex; width: 100%; min-width: 0; flex-direction: column; gap: 4px; }.stop-card { width: 100%; min-width: 0; height: 80px; padding: 8px 0; display: flex; align-items: center; gap: 12px; box-sizing: border-box; overflow: hidden; border: 0; border-bottom: 1px solid #dbded4; border-radius: 0; background: transparent; }.stop-card:active { background: rgba(227, 235, 201, 0.4); }.stop-cover { flex: 0 0 64px; width: 64px; height: 64px; overflow: hidden; border-radius: 6px; background: #f5f5ed; }.stop-cover-fallback { font-size: 22px; line-height: 28px; color: #a9b29b; }.stop-copy { min-width: 0; display: flex; flex: 1; overflow: hidden; }.stop-name { display: -webkit-box; max-height: 40px; font-size: 14px; line-height: 20px; font-weight: 700; color: #262421; overflow: hidden; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }.stop-status { flex: 0 0 44px; width: 44px; height: 24px; display: flex; align-items: center; justify-content: center; border-radius: 12px; background: #e3ebc9; }.stop-status-text { font-size: 11px; line-height: 16px; color: #262421; white-space: nowrap; }
.stop-list { display: flex; width: 100%; min-width: 0; flex-direction: column; gap: 4px; }.stop-card { width: 100%; min-width: 0; min-height: 80px; padding: 8px 0; display: flex; align-items: center; gap: 12px; box-sizing: border-box; overflow: hidden; border: 0; border-bottom: 1px solid #dbded4; border-radius: 0; background: transparent; }.stop-card:active { background: rgba(227, 235, 201, 0.4); }.stop-cover { flex: 0 0 64px; width: 64px; height: 64px; overflow: hidden; border-radius: 6px; background: #f5f5ed; }.stop-cover-fallback { font-size: 22px; line-height: 28px; color: #a9b29b; }.stop-copy { min-width: 0; display: flex; flex: 1; flex-direction: column; justify-content: center; gap: 3px; overflow: hidden; }.stop-code { display: block; overflow: hidden; font-size: 13px; line-height: 18px; font-weight: 700; color: #68725d; text-overflow: ellipsis; white-space: nowrap; }.stop-name { display: -webkit-box; max-height: 40px; font-size: 14px; line-height: 20px; font-weight: 700; color: #262421; overflow: hidden; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }.stop-code + .stop-name { margin-top: 1px; }.stop-status { flex: 0 0 44px; width: 44px; height: 24px; display: flex; align-items: center; justify-content: center; border-radius: 12px; background: #e3ebc9; }.stop-status-text { font-size: 11px; line-height: 16px; color: #262421; white-space: nowrap; }
.state-block { margin: 34px 0; padding: 22px 16px; box-sizing: border-box; text-align: center; border: 1px solid #e4e6df; border-radius: 8px; background: #fff; }.state-block.error { border-color: #e5c2c2; background: #fff7f7; }.state-title,.state-desc { display: block; }.state-title { font-size: 15px; line-height: 21px; font-weight: 700; color: #141412; }.state-desc { margin-top: 6px; font-size: 12px; line-height: 18px; color: #68725d; }.state-retry { margin-top: 12px; padding: 0 14px; font-size: 13px; line-height: 32px; color: #141412; background: #e0df00; border: 0; border-radius: 6px; }.load-more-state { min-height: 52px; padding: 12px 16px calc(12px + env(safe-area-inset-bottom)); text-align: center; }
</style>

View File

@@ -33,6 +33,24 @@
</view>
<template v-else>
<view v-if="stage === 'hall'" class="code-entry-section">
<button class="code-entry-button" @tap="openCodeEntry">
<view class="code-entry-icon" aria-hidden="true">
<view class="headphone-band" />
<view class="headphone-ear left" />
<view class="headphone-ear right" />
</view>
<view class="code-entry-copy">
<text class="code-entry-title">编号讲解</text>
<text class="code-entry-desc">输入展品旁的编号直接收听讲解</text>
</view>
</button>
</view>
<view v-if="stage === 'hall'" class="hall-section-heading">
<text class="hall-section-title">按展厅选择</text>
</view>
<view v-if="stage === 'hall' && filteredHalls.length" class="hall-list hall-overview-list">
<view
v-for="(hall, index) in filteredHalls"
@@ -178,6 +196,45 @@
</view>
</template>
</scroll-view>
<view v-if="codeEntryVisible" class="code-entry-overlay" @tap="closeCodeEntry">
<view class="code-entry-sheet" @tap.stop>
<view class="code-entry-content">
<text class="code-entry-sheet-title">输入讲解编号</text>
<text class="code-entry-sheet-desc">请输入展品旁标注的 4 位编号</text>
<view class="code-digit-fields" :class="{ error: codeEntryError }">
<view
v-for="index in 4"
:key="index"
class="code-digit-cell"
:class="{ active: codeEntryValue.length === index - 1 }"
>
<text class="code-digit-value">{{ codeEntryValue[index - 1] || '' }}</text>
</view>
<input
v-if="codeEntryVisible"
class="code-entry-native-input"
:value="codeEntryValue"
type="number"
inputmode="numeric"
confirm-type="go"
maxlength="4"
:focus="codeEntryVisible && !codeSubmitting"
:disabled="codeSubmitting"
@input="handleCodeEntryInput"
@confirm="submitCodeEntry"
/>
</view>
<text v-if="codeEntryError" class="code-entry-error">{{ codeEntryError }}</text>
<text v-else class="code-entry-hint">请输入展品标签上的四位编号</text>
<button
class="code-entry-action primary"
:disabled="codeEntryValue.length !== 4 || codeSubmitting"
@tap="submitCodeEntry"
>{{ codeSubmitting ? '正在查询' : '开始讲解' }}</button>
</view>
</view>
</view>
</view>
</template>
@@ -234,6 +291,7 @@ const props = withDefaults(defineProps<{
error?: string
loadMoreError?: string
forceInternalHeader?: boolean
codeSubmitting?: boolean
}>(), {
halls: () => [],
businessUnits: () => [],
@@ -245,11 +303,13 @@ const props = withDefaults(defineProps<{
hasMore: false,
error: '',
loadMoreError: '',
forceInternalHeader: false
forceInternalHeader: false,
codeSubmitting: false
})
const emit = defineEmits<{
hallClick: [hallId: string]
codeSubmit: [code: string]
businessUnitClick: [unitId: string]
guideStopClick: [stop: ExplainGuideStopSelectItem]
back: []
@@ -261,6 +321,9 @@ const HALL_PREVIEW_BASE = '/static/icons/halls/portal-icons'
const HALL_PREVIEW_EAGER_COUNT = 4
const loadedHallPreviewIds = ref(new Set<string>())
const failedHallPreviewIds = ref(new Set<string>())
const codeEntryVisible = ref(false)
const codeEntryValue = ref('')
const codeEntryError = ref('')
const hallPreviewMap: Record<string, string> = {
宇宙厅: `${HALL_PREVIEW_BASE}/universe.png`,
@@ -292,6 +355,7 @@ const showInternalHeader = computed(() => props.forceInternalHeader || !shouldUs
const headerTitle = computed(() => {
if (props.stage === 'stop') return props.selectedHallName || '讲解对象'
if (props.stage === 'unit') return props.selectedHallName || '讲解单元'
if (codeEntryVisible.value) return '编号讲解'
return '免费讲解'
})
const loadingTitle = computed(() => {
@@ -355,6 +419,46 @@ const handleHallClick = (hallId: string) => {
emit('hallClick', hallId)
}
const openCodeEntry = () => {
codeEntryError.value = ''
codeEntryVisible.value = true
}
const closeCodeEntry = () => {
codeEntryVisible.value = false
codeEntryValue.value = ''
codeEntryError.value = ''
}
const handleCodeEntryInput = (event: Event) => {
const inputEvent = event as Event & { detail?: { value?: string } }
codeEntryValue.value = (inputEvent.detail?.value || '')
.replace(/\D/g, '')
.slice(0, 4)
codeEntryError.value = ''
}
const submitCodeEntry = () => {
if (props.codeSubmitting) return
const code = codeEntryValue.value
if (code.length !== 4) {
codeEntryError.value = '请输入完整的 4 位讲解编号'
return
}
emit('codeSubmit', code)
}
const showCodeEntryError = (message: string) => {
codeEntryError.value = message
}
const completeCodeEntry = () => {
codeEntryValue.value = ''
codeEntryError.value = ''
}
defineExpose({ openCodeEntry, showCodeEntryError, completeCodeEntry })
const handleBusinessUnitClick = (unitId: string) => {
emit('businessUnitClick', unitId)
}
@@ -382,6 +486,10 @@ const handleScroll = (event: Event) => {
}
const handleBack = () => {
if (codeEntryVisible.value) {
closeCodeEntry()
return
}
emit('back')
}
</script>
@@ -405,6 +513,64 @@ const handleBack = () => {
padding: 76px 16px 16px;
}
.code-entry-section {
padding-bottom: 10px;
}
.code-entry-button {
position: relative;
width: 100%;
min-height: 82px;
margin: 0;
padding: 13px 72px;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
color: #171713;
border: 1px solid #cfd4c7;
border-radius: 8px;
background: #ffffff;
box-shadow: 0 3px 10px rgba(36, 49, 42, 0.06);
}
.code-entry-button::after { border: 0; }
.code-entry-button:active { background: #f0f3e8; }
.code-entry-icon { position: absolute; left: 28px; top: 50%; width: 44px; height: 44px; border-radius: 8px; background: #e0e100; transform: translateY(-50%); }
.headphone-band { position: absolute; left: 10px; top: 9px; width: 24px; height: 23px; box-sizing: border-box; border: 3px solid #171713; border-bottom: 0; border-radius: 14px 14px 0 0; }
.headphone-ear { position: absolute; top: 25px; width: 7px; height: 11px; border-radius: 3px; background: #171713; }
.headphone-ear.left { left: 8px; }
.headphone-ear.right { right: 8px; }
.code-entry-copy { width: 100%; min-width: 0; text-align: center; }
.code-entry-title, .code-entry-desc { display: block; }
.code-entry-title { font-size: 17px; line-height: 23px; font-weight: 700; color: #171713; }
.code-entry-desc { margin-top: 3px; font-size: 12px; line-height: 18px; color: #68725d; }
.hall-section-heading { height: 30px; display: flex; align-items: center; justify-content: center; }
.hall-section-title { font-size: 13px; line-height: 19px; font-weight: 600; color: #68725d; }
.code-entry-overlay { position: absolute; z-index: 3000; top: 64px; right: 0; bottom: 0; left: 0; background: #f7f9f2; }
.code-entry-sheet { position: absolute; inset: 0; padding: 24px 24px calc(24px + env(safe-area-inset-bottom)); box-sizing: border-box; background: #f7f9f2; }
.code-entry-content { width: min(100%, 330px); min-height: 100%; margin: 0 auto; display: flex; flex-direction: column; align-items: center; justify-content: center; box-sizing: border-box; transform: translateY(-28px); }
.code-entry-sheet-title, .code-entry-sheet-desc, .code-entry-error, .code-entry-demo { display: block; text-align: center; }
.code-entry-sheet-title { font-size: 22px; line-height: 30px; font-weight: 700; color: #171713; }
.code-entry-sheet-desc { margin-top: 8px; font-size: 14px; line-height: 20px; color: #68725d; }
.code-entry-action::after { border: 0; }
.code-digit-fields { position: relative; width: 100%; margin-top: 32px; display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; }
.code-digit-cell { height: 68px; display: flex; align-items: center; justify-content: center; box-sizing: border-box; border: 1.5px solid #aeb5a5; border-radius: 6px; background: #ffffff; }
.code-digit-cell.active { border-color: #777d00; box-shadow: 0 0 0 1px #e0e100 inset; }
.code-digit-fields.error .code-digit-cell { border-color: #b63f3f; }
.code-digit-value { font-size: 30px; line-height: 36px; font-weight: 700; color: #171713; }
.code-entry-native-input { position: absolute; inset: 0; width: 100%; height: 68px; opacity: 0.01; color: transparent; caret-color: transparent; }
.code-entry-error, .code-entry-hint { min-height: 19px; margin-top: 10px; font-size: 12px; line-height: 19px; }
.code-entry-error { color: #a62f2f; }
.code-entry-hint { color: #7a8271; }
.code-entry-action { width: 100%; height: 48px; margin: 28px 0 0; padding: 0 12px; font-size: 15px; line-height: 48px; font-weight: 700; border: 0; border-radius: 6px; }
.code-entry-action.primary { color: #171713; background: #e0e100; }
.code-entry-action.primary[disabled] { color: #909489; background: #e4e6df; opacity: 1; }
.explain-hall-select.host-navigation .code-entry-overlay { top: 0; }
.explain-scroll.stop-stage {
padding-bottom: 0;
}
@@ -906,13 +1072,23 @@ const handleBack = () => {
}
.explain-scroll.hall-stage {
padding: 88px 16px 24px;
padding: 88px 16px 12px;
overflow: hidden;
}
.hall-overview-list {
// Keep the eight-hall overview balanced on tall phones while preserving a
// fixed minimum row height for compact screens.
grid-auto-rows: max(138px, calc((100vh - 148px) / 4));
grid-template-rows: repeat(4, minmax(0, 1fr));
grid-auto-rows: minmax(0, 1fr);
height: calc(100vh - 222px);
gap: 10px 12px;
}
.hall-overview-card {
min-height: 0;
}
.explain-hall-select.host-navigation .hall-overview-list {
height: calc(100vh - 146px);
}
.hall-overview-card {

View File

@@ -74,9 +74,10 @@ const isAutoplayBlocked = (err: unknown) => {
const syncAudioDuration = () => {
if (!audioElement) return
duration.value = Number.isFinite(audioElement.duration)
? audioElement.duration
: currentAudio.value?.duration || 0
const mediaDuration = audioElement.duration
duration.value = Number.isFinite(mediaDuration) && mediaDuration > 0
? mediaDuration
: 0
}
const ensureAudioElement = () => {
@@ -180,7 +181,7 @@ const stopPlayback = () => {
loading.value = false
pendingLanguage.value = ''
currentTime.value = 0
duration.value = currentAudio.value?.duration || 0
duration.value = 0
}
const updateDetailRouteLanguage = (route: string | undefined, lang: AudioLanguage) => {
@@ -205,6 +206,31 @@ const toSwitchedAudioItem = (
supportedLanguages: currentAudio.value?.supportedLanguages
})
const prepare = (audio: AudioItem, options: GlobalAudioPlayOptions = {}) => {
const preservedMode = options.displayMode || displayMode.value
stopAudioElement()
currentAudio.value = audio
currentSource.value = options.source || currentSource.value
retryOnError = options.retryOnError || retryOnError
visible.value = true
displayMode.value = preservedMode
playing.value = false
loading.value = false
error.value = audio.audioUrl ? '' : '当前语言暂无语音讲解'
currentTime.value = 0
duration.value = 0
if (audio.audioUrl) {
const element = ensureAudioElement()
if (element) {
element.src = audio.audioUrl
element.load()
element.playbackRate = playbackRate.value
element.muted = muted.value
}
}
}
const play = async (audio: AudioItem, options: GlobalAudioPlayOptions = {}) => {
if (!audio.audioUrl) {
const preservedMode = options.displayMode || displayMode.value
@@ -246,7 +272,7 @@ const play = async (audio: AudioItem, options: GlobalAudioPlayOptions = {}) => {
if (isNewAudio) {
currentTime.value = 0
duration.value = audio.duration || 0
duration.value = 0
}
if (element.getAttribute('src') !== audio.audioUrl) {
@@ -500,6 +526,7 @@ export const useGlobalAudioPlayer = () => ({
closeVersion,
hasAudio: computed(() => Boolean(currentAudio.value)),
play,
prepare,
pause,
resume,
stop,

View File

@@ -147,6 +147,8 @@ export interface BackendCatalogStopItem {
mapX?: number | string | null
mapY?: number | string | null
name?: string | null
/** 馆方讲解编号,按字符串返回以保留前导零。 */
externalCode?: string | null
guideLevel?: string | null
description?: string | null
sort?: number | null
@@ -350,6 +352,7 @@ export const toCatalogGuideStop = (
return {
id,
name: firstText(source.name, `讲解点${id}`),
externalCode: firstText(source.externalCode) || undefined,
hallId: hall?.id,
hallName: hall?.name,
floorId: stringifyId(source.floorId) || hall?.floorId,

View File

@@ -243,6 +243,8 @@ export interface MuseumExhibit {
export interface ExplainGuideStop {
id: string
name: string
/** 馆方讲解编号,来自目录接口 externalCode必须按字符串保留。 */
externalCode?: string
hallId?: string
hallName?: string
floorId?: string

View File

@@ -246,6 +246,8 @@ const detailTextLoadedByLanguage = ref<Record<AudioLanguage, boolean>>({
'en-US': false
})
const shouldUseHostNavigation = computed(() => isEmbeddedInWechatMiniProgram())
const shouldAutoplayOnEntry = ref(false)
const enteredByGuideCode = ref(false)
const isAudioLanguage = (value: unknown): value is AudioLanguage => (
value === 'zh-CN' || value === 'yue-HK' || value === 'en-US'
@@ -372,14 +374,9 @@ const formatDetailAudioTime = (seconds?: number) => {
return `${minutes}:${remainSeconds.toString().padStart(2, '0')}`
}
const detailAudioDurationSeconds = computed(() => {
if (!isCurrentDetailAudioTarget.value) return exhibit.value.audio.duration || 0
return globalAudioPlayer.duration.value
|| globalAudioPlayer.currentAudio.value?.duration
|| exhibit.value.audio.duration
|| 0
})
const detailAudioDurationSeconds = computed(() => (
isCurrentDetailAudioTarget.value ? globalAudioPlayer.duration.value : 0
))
const detailAudioCurrentSeconds = computed(() => (
isCurrentDetailAudioTarget.value ? globalAudioPlayer.currentTime.value : 0
))
@@ -531,6 +528,10 @@ onLoad(async (options: any = {}) => {
return
}
const rawLang = Array.isArray(options.lang) ? options.lang[0] : options.lang
const rawAutoplay = Array.isArray(options.autoplay) ? options.autoplay[0] : options.autoplay
const rawEntry = Array.isArray(options.entry) ? options.entry[0] : options.entry
shouldAutoplayOnEntry.value = rawAutoplay === '1' || rawAutoplay === 'true'
enteredByGuideCode.value = rawEntry === 'code'
const lang = typeof rawLang === 'string'
? normalizeGuideAudioLanguage(rawLang)
: 'zh-CN'
@@ -545,6 +546,18 @@ onLoad(async (options: any = {}) => {
poiId: Array.isArray(options.poiId) ? options.poiId[0] : options.poiId
}
await loadExplainDetail(detailEntryRequest.value, lang)
if (shouldAutoplayOnEntry.value) {
shouldAutoplayOnEntry.value = false
try {
await handlePlayAudio()
} catch (error) {
console.warn('自动播放讲解失败,将等待用户手动播放:', error)
uni.showToast({
title: '点击底部播放键开始讲解',
icon: 'none'
})
}
}
} catch (error) {
console.error('讲解详情加载失败:', error)
detailState.value = 'error'
@@ -680,10 +693,10 @@ const handleLanguageChange = async (lang: AudioLanguage, options: { syncAudio?:
}
}
void loadFullDetailTextForLanguage(request, lang, exhibit.value)
if (shouldContinueAudio) {
// The player must become actionable before resuming with the new language track.
if (options.syncAudio !== false && isCurrentDetailAudioTarget.value) {
// 语言切换后立即刷新播放器;原先暂停时不会更新音轨,导致组件仍显示旧内容。
languageSwitchLoading.value = false
await handlePlayAudio()
await handlePlayAudio({ autoplay: shouldContinueAudio })
}
} catch (error) {
if (requestSequence !== languageSwitchSequence) return
@@ -715,11 +728,12 @@ const handleLanguageChange = async (lang: AudioLanguage, options: { syncAudio?:
const handleToggleDetailAudioVoice = async () => {
if (audioDockState.value !== 'playable' || !canSwitchDetailAudioVoice.value) return
const shouldContinueAudio = isCurrentDetailAudioTarget.value && globalAudioPlayer.playing.value
const hasCurrentDetailAudio = isCurrentDetailAudioTarget.value
const shouldContinueAudio = hasCurrentDetailAudio && globalAudioPlayer.playing.value
selectedAudioGender.value = currentDetailAudioGender.value === 'male' ? 'female' : 'male'
if (shouldContinueAudio) {
await handlePlayAudio()
if (hasCurrentDetailAudio) {
await handlePlayAudio({ autoplay: shouldContinueAudio })
}
}
@@ -806,24 +820,30 @@ const refreshCurrentAudioOnce = async (message: string) => {
return null
}
const detailAudioPlayOptions = (audio: AudioItem) => ({
source: {
exhibitId: exhibit.value.id,
stopId: currentAudioTarget.value.stopId,
lang: selectedAudioLanguage.value,
channelCode: selectedDetailAudioOption.value?.channelCode,
voiceGender: currentDetailAudioGender.value,
audioOptions: activeDetailAudioOptions.value,
title: audio.name,
detailRoute: buildDetailRoute()
},
retryOnError: refreshCurrentAudioOnce,
displayMode: 'mini' as const
})
const playDetailAudio = async (audio: AudioItem) => {
await globalAudioPlayer.play(audio, {
source: {
exhibitId: exhibit.value.id,
stopId: currentAudioTarget.value.stopId,
lang: selectedAudioLanguage.value,
channelCode: selectedDetailAudioOption.value?.channelCode,
voiceGender: currentDetailAudioGender.value,
audioOptions: activeDetailAudioOptions.value,
title: audio.name,
detailRoute: buildDetailRoute()
},
retryOnError: refreshCurrentAudioOnce,
displayMode: 'mini'
})
await globalAudioPlayer.play(audio, detailAudioPlayOptions(audio))
}
const handlePlayAudio = async (options: { forceRefresh?: boolean } = {}) => {
const prepareDetailAudio = (audio: AudioItem) => {
globalAudioPlayer.prepare(audio, detailAudioPlayOptions(audio))
}
const handlePlayAudio = async (options: { forceRefresh?: boolean; autoplay?: boolean } = {}) => {
if (audioDockState.value === 'unavailable' || audioDockState.value === 'loading') return
if (audioDockState.value === 'failed' && !options.forceRefresh) {
@@ -844,7 +864,8 @@ const handlePlayAudio = async (options: { forceRefresh?: boolean } = {}) => {
? await refreshCurrentAudioOnce(globalAudioPlayer.error.value)
: null
if (refreshedAudio) {
await playDetailAudio(refreshedAudio)
if (options.autoplay === false) prepareDetailAudio(refreshedAudio)
else await playDetailAudio(refreshedAudio)
return
}
@@ -880,6 +901,10 @@ const handlePlayAudio = async (options: { forceRefresh?: boolean } = {}) => {
const audio = toAudioItem(selection)
if (!audio) return
if (options.autoplay === false) {
prepareDetailAudio(audio)
return
}
await playDetailAudio(audio)
}
@@ -908,6 +933,16 @@ const decodeRouteParam = (value: string) => {
return decoded
}
const fallbackToCodeEntry = () => {
const url = '/pages/explain/list?codeEntry=1'
uni.redirectTo({
url,
fail: () => {
uni.reLaunch({ url })
}
})
}
const fallbackToExplainObjectList = () => {
const hallId = detailEntryRequest.value?.hallId || exhibit.value.hallId
const hallName = decodeRouteParam(detailEntryRequest.value?.hallName || exhibit.value.hallName || '讲解')
@@ -930,15 +965,27 @@ type ExplainDetailPageStackEntry = {
const returnToExplainObjectList = () => {
closeDetailAudioOnExit()
const pages = getCurrentPages()
const previousPage = pages[pages.length - 2] as ExplainDetailPageStackEntry | undefined
if (enteredByGuideCode.value) {
if (previousPage?.route === 'pages/explain/list' || previousPage?.route === 'pages/index/index') {
uni.navigateBack({
delta: 1,
fail: fallbackToCodeEntry
})
return
}
fallbackToCodeEntry()
return
}
// H5 history can omit intermediate uni-app pages after a refresh or deep link.
if (typeof window !== 'undefined' && window.location.hash.startsWith('#/')) {
fallbackToExplainObjectList()
return
}
const pages = getCurrentPages()
const previousPage = pages[pages.length - 2] as ExplainDetailPageStackEntry | undefined
if (previousPage?.route === 'pages/explain/guide-stop-list') {
uni.navigateBack({
delta: 1,

View File

@@ -43,6 +43,7 @@ let disposed = false
const toGuideStopItems = (stops: ExplainGuideStop[]): ExplainGuideStopCatalogItem[] => stops.map((stop) => ({
id: stop.id,
name: stop.name,
externalCode: stop.externalCode,
hallId: stop.hallId,
hallName: stop.hallName,
floorId: stop.floorId,

View File

@@ -8,11 +8,14 @@
>
<view class="explain-all-page">
<ExplainHallSelect
ref="hallSelectRef"
:halls="explainHallItems"
stage="hall"
:loading="explainLoading"
:error="explainError"
:code-submitting="codeSubmitting"
@hall-click="handleExplainHallClick"
@code-submit="handleExplainCodeSubmit"
@retry="loadExplainHalls"
@back="handleBack"
/>
@@ -21,7 +24,7 @@
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue'
import { onBackPress, onLoad } from '@dcloudio/uni-app'
import GuidePageFrame from '@/components/navigation/GuidePageFrame.vue'
import ExplainHallSelect, {
@@ -41,12 +44,15 @@ import {
} from '@/utils/guideTopTabs'
import { isEmbeddedInWechatMiniProgram } from '@/utils/hostEnvironment'
import { explainGuideStopListUrl } from '@/utils/explainNavigation'
import { explainCodeDetailUrl, explainCodeErrorMessage } from '@/utils/explainCodeEntry'
import { returnToWechatMiniProgram } from '@/services/WechatMiniProgramBridgeService'
import { syncHostNavigationTitle } from '@/utils/hostNavigationTitle'
const explainHallItems = ref<ExplainHallSelectItem[]>([])
const explainLoading = ref(false)
const explainError = ref('')
const hallSelectRef = ref<InstanceType<typeof ExplainHallSelect> | null>(null)
const codeSubmitting = ref(false)
let explainLoadPromise: Promise<void> | null = null
const normalizeExplainKeyword = (value?: string) => (value || '').trim().toLowerCase()
@@ -236,10 +242,14 @@ const loadExplainHalls = async () => {
return explainLoadPromise
}
onLoad(() => {
onLoad((options: any = {}) => {
if (shouldUseHostNavigation.value) syncHostNavigationTitle('免费讲解')
pushExplainListHistory()
void loadExplainHalls()
const codeEntry = Array.isArray(options.codeEntry) ? options.codeEntry[0] : options.codeEntry
if (codeEntry === '1' || codeEntry === 'true') {
nextTick(() => hallSelectRef.value?.openCodeEntry())
}
})
onMounted(() => {
@@ -270,6 +280,21 @@ const handleExplainHallClick = (hallId: string) => {
})
}
const handleExplainCodeSubmit = async (code: string) => {
if (codeSubmitting.value) return
codeSubmitting.value = true
try {
const target = await explainUseCase.resolveExplainCode(code)
// 保留编号输入页,详情返回时让用户可以继续输入下一个编号。
hallSelectRef.value?.completeCodeEntry()
uni.navigateTo({ url: explainCodeDetailUrl(target) })
} catch (error) {
hallSelectRef.value?.showCodeEntryError(explainCodeErrorMessage(error))
} finally {
codeSubmitting.value = false
}
}
</script>
<style scoped lang="scss">

View File

@@ -247,11 +247,14 @@
<view v-else-if="currentTab === 'explain'" class="explain-page">
<ExplainHallSelect
ref="explainHallSelectRef"
:halls="explainHallItems"
stage="hall"
:loading="explainLoading"
:error="explainError"
:code-submitting="codeSubmitting"
@hall-click="handleExplainHallClick"
@code-submit="handleExplainCodeSubmit"
@retry="loadExplainHalls"
@back="handleExplainBack"
/>
@@ -308,6 +311,7 @@ import ExplainHallSelect, {
type ExplainHallSelectItem
} from '@/components/explain/ExplainHallSelect.vue'
import { explainGuideStopListUrl } from '@/utils/explainNavigation'
import { explainCodeDetailUrl, explainCodeErrorMessage } from '@/utils/explainCodeEntry'
import {
getLastGuideLocationPreviewUrl,
isGuideTopTab,
@@ -1013,6 +1017,8 @@ const selectedGuidePoiActions = computed(() => {
})
const explainHallItems = ref<ExplainHallSelectItem[]>([])
const explainHallSelectRef = ref<InstanceType<typeof ExplainHallSelect> | null>(null)
const codeSubmitting = ref(false)
const explainLoading = ref(false)
const explainError = ref('')
let explainLoadPromise: Promise<void> | null = null
@@ -2574,6 +2580,21 @@ const handleExplainHallClick = async (hallId: string) => {
})
}
const handleExplainCodeSubmit = async (code: string) => {
if (codeSubmitting.value) return
codeSubmitting.value = true
try {
const target = await explainUseCase.resolveExplainCode(code)
// 保留编号输入页,详情返回时让用户可以继续输入下一个编号。
explainHallSelectRef.value?.completeCodeEntry()
uni.navigateTo({ url: explainCodeDetailUrl(target) })
} catch (error) {
explainHallSelectRef.value?.showCodeEntryError(explainCodeErrorMessage(error))
} finally {
codeSubmitting.value = false
}
}
const handleExplainBack = () => {
currentTab.value = 'guide'
syncTopTabToUrl('guide')

View File

@@ -1,10 +1,13 @@
import { dataSourceConfig } from '@/config/dataSource'
import {
toGuideStopDetail,
toGuideStopInfo,
type BackendGuideStopDetail,
type BackendGuideStopInfo,
type GuideAudioLanguage,
type GuideAudioVersion,
type GuideStopDetail
type GuideStopDetail,
type GuideStopInfo
} from '@/data/adapters/guideStopInfoAdapter'
export type AudioLanguage = GuideAudioLanguage
@@ -16,6 +19,7 @@ export interface GetStopDetailOptions {
export interface AudioPlayInfoRepository {
getStopDetail(stopId: string, options?: GetStopDetailOptions): Promise<GuideStopDetail>
getStopInfoByCode(code: string, lang?: AudioLanguage): Promise<GuideStopInfo>
clearCache(stopId?: string): void
}
@@ -25,6 +29,19 @@ interface GuideStopDetailResponse {
data?: BackendGuideStopDetail
}
interface GuideStopInfoResponse {
code: number
msg?: string
data?: BackendGuideStopInfo
}
export class GuideApiError extends Error {
constructor(message: string, readonly code?: number) {
super(message)
this.name = 'GuideApiError'
}
}
interface CacheEntry<T> {
value: T
expiresAt: number
@@ -119,6 +136,25 @@ export class DefaultAudioPlayInfoRepository implements AudioPlayInfoRepository {
}
}
async getStopInfoByCode(code: string, lang: AudioLanguage = dataSourceConfig.audioLanguage): Promise<GuideStopInfo> {
const normalizedCode = String(code || '').trim()
if (!normalizedCode) throw new GuideApiError('讲解编号不能为空', 1020007000)
const params = new URLSearchParams({ code: normalizedCode, lang })
const response = await requestJson<GuideStopInfoResponse>(
`${resolveAppApiBaseUrl()}/gis/guide/stop/info-by-code?${params.toString()}`
)
if (response.code !== 0 || !response.data) {
throw new GuideApiError(response.msg || '编号讲解查询失败', response.code)
}
return toGuideStopInfo(response.data, {
targetType: 'STOP',
targetId: '',
lang
})
}
async getStopDetail(stopId: string, options: GetStopDetailOptions = {}): Promise<GuideStopDetail> {
const normalizedStopId = String(stopId || '').trim()
if (!normalizedStopId) throw new Error('讲解点 ID 不能为空')
@@ -137,9 +173,7 @@ export class DefaultAudioPlayInfoRepository implements AudioPlayInfoRepository {
`${resolveAppApiBaseUrl()}/gis/guide/stops/${encodeURIComponent(normalizedStopId)}?${params.toString()}`
).then((response) => {
if (response.code !== 0 || !response.data) {
const error = new Error(response.msg || '讲解点详情加载失败')
;(error as Error & { code?: number }).code = response.code
throw error
throw new GuideApiError(response.msg || '讲解点详情加载失败', response.code)
}
const detail = toGuideStopDetail(response.data)
if (epoch === this.epoch) this.setCached(normalizedStopId, version, detail)

View File

@@ -78,6 +78,11 @@ export interface ExplainHallSummary {
guideStopCount: number
}
export interface ExplainCodeResolution {
code: string
stopId: string
}
export class ExplainUseCase {
constructor(
private readonly explain: ExplainRepository = explainRepository,
@@ -273,6 +278,15 @@ export class ExplainUseCase {
})
}
async resolveExplainCode(code: string, lang: AudioLanguage = dataSourceConfig.audioLanguage as AudioLanguage): Promise<ExplainCodeResolution> {
const stopInfo = await this.audioPlayInfo.getStopInfoByCode(code, lang)
const stopId = stopInfo.resolvedStopId || stopInfo.playTargetId || stopInfo.targetId
if (!stopInfo.available || !stopId) {
throw new Error('该编号的讲解内容暂不可用')
}
return { code: code.trim(), stopId }
}
async enterExplainDetail(request: ExplainDetailEntryRequest) {
const stopId = this.resolveDetailStopId(request)
if (!stopId) throw new Error('讲解点 ID 不能为空')

View File

@@ -0,0 +1,31 @@
export interface ExplainCodeEntryTarget {
code: string
stopId: string
hallName?: string
}
export const normalizeExplainCode = (code: string) => code.trim()
export const explainCodeErrorMessage = (error: unknown) => {
const code = error && typeof error === 'object' && 'code' in error
? Number((error as { code?: unknown }).code)
: undefined
if (code === 1020007000) return '请输入有效的 4 位讲解编号'
if (code === 1020007001) return '未找到该讲解编号,请确认后重试'
if (code === 1020007002) return '该编号的讲解内容暂不可用'
if (code === 429) return '查询过于频繁,请稍后再试'
return '编号查询失败,请检查网络后重试'
}
export const explainCodeDetailUrl = (target: ExplainCodeEntryTarget) => {
const params = new URLSearchParams({
id: target.stopId,
stopId: target.stopId,
tab: 'explain',
autoplay: '1',
entry: 'code',
guideCode: target.code
})
if (target.hallName) params.set('hallName', target.hallName)
return `/pages/exhibit/detail?${params.toString()}`
}

View File

@@ -68,6 +68,58 @@ describe('DefaultAudioPlayInfoRepository unified stop detail', () => {
expect(request).toHaveBeenCalledTimes(2)
})
it('resolves a museum code through info-by-code and preserves the code string', async () => {
const requestUrls: string[] = []
vi.stubGlobal('uni', {
request: ({ url, success }: { url: string, success: (response: unknown) => void }) => {
requestUrls.push(url)
success({
statusCode: 200,
data: {
code: 0,
data: {
available: true,
targetType: 'STOP',
targetId: '865546652298080256',
resolvedStopId: '865546652298080256',
lang: 'zh-CN',
title: '手持折射望远镜',
imageStatus: 'READY',
playTargetType: 'STOP',
playTargetId: '865546652298080256',
hasAudio: true,
supportedLanguages: ['zh-CN', 'yue-HK'],
audioStatus: 'READY'
}
}
})
}
})
const repository = new DefaultAudioPlayInfoRepository()
const result = await repository.getStopInfoByCode('0101', 'zh-CN')
expect(requestUrls).toEqual([
'/app-api/gis/guide/stop/info-by-code?code=0101&lang=zh-CN'
])
expect(result.resolvedStopId).toBe('865546652298080256')
expect(result.title).toBe('手持折射望远镜')
})
it('preserves info-by-code business error codes', async () => {
vi.stubGlobal('uni', {
request: ({ success }: { success: (response: unknown) => void }) => {
success({ statusCode: 200, data: { code: 1020007001, msg: '馆方讲解点编号不存在', data: null } })
}
})
const repository = new DefaultAudioPlayInfoRepository()
await expect(repository.getStopInfoByCode('9999')).rejects.toMatchObject({
message: '馆方讲解点编号不存在',
code: 1020007001
})
})
it('surfaces a business missing-detail response as a detail error', async () => {
vi.stubGlobal('uni', {
request: ({ success }: { success: (response: unknown) => void }) => {

View File

@@ -26,7 +26,7 @@ describe('BackendExplainContentProvider hall stop paging', () => {
data: {
total: 30,
list: pageNo === '1'
? [{ stopId: 'stop-1', name: '对象一', imageStatus: 'READY', coverImageUrl: '/one.jpg', outlineId: 'outline-1', linkedExhibits: [] }]
? [{ stopId: 'stop-1', name: '对象一', externalCode: '0231', imageStatus: 'READY', coverImageUrl: '/one.jpg', outlineId: 'outline-1', linkedExhibits: [] }]
: [{ stopId: 'stop-2', name: '对象二', imageStatus: 'MISSING', outlineId: 'outline-1', linkedExhibits: [] }]
}
}
@@ -38,7 +38,7 @@ describe('BackendExplainContentProvider hall stop paging', () => {
])
expect(first).toMatchObject({ total: 30, pageNo: 1, pageSize: 20, hasMore: true })
expect(first.items[0]).toMatchObject({ id: 'stop-1', stopId: 'stop-1', hallName: '恐龙厅', outlineId: 'outline-1' })
expect(first.items[0]).toMatchObject({ id: 'stop-1', stopId: 'stop-1', externalCode: '0231', hallName: '恐龙厅', outlineId: 'outline-1' })
expect(second.items.map((item) => item.id)).toEqual(['stop-2'])
expect(requests.filter((url) => url.includes('/stops/page'))).toHaveLength(2)
expect(requests.some((url) => url.includes('/outlines'))).toBe(false)

View File

@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({
loadExplainDetailText: vi.fn(),
selectAudioForExplainDetail: vi.fn(),
play: vi.fn(),
prepare: vi.fn(),
pause: vi.fn(),
resume: vi.fn(),
close: vi.fn(),
@@ -61,8 +62,15 @@ vi.mock('@/usecases/guideUseCase', () => ({
vi.mock('@/composables/useGlobalAudioPlayer', () => ({
useGlobalAudioPlayer: () => ({
...audioState,
isCurrentSource: () => false,
isCurrentSource: (source: { stopId?: string, lang?: string, channelCode?: string }) => Boolean(
audioState.currentAudio.value
&& audioState.currentSource.value
&& audioState.currentSource.value.stopId === source.stopId
&& (!source.lang || audioState.currentSource.value.lang === source.lang)
&& (!source.channelCode || audioState.currentSource.value.channelCode === source.channelCode)
),
play: mocks.play,
prepare: mocks.prepare,
pause: mocks.pause,
resume: mocks.resume,
switchLanguage: vi.fn(),
@@ -164,7 +172,7 @@ describe('讲解详情音频优先布局', () => {
expect(wrapper.get('.content-section').classes()).toContain('is-english')
expect(wrapper.find('.section-title').exists()).toBe(false)
expect(wrapper.get('.section-text').text()).toContain('detailed English narration')
expect(wrapper.get('.detail-audio-time').text()).toBe('0:00 / 1:21')
expect(wrapper.get('.detail-audio-time').text()).toBe('0:00 / 0:00')
expect(wrapper.get('.detail-audio-speed').attributes('aria-label')).toBe('播放速度 1.0倍')
})
@@ -256,6 +264,26 @@ describe('讲解详情音频优先布局', () => {
}), expect.objectContaining({ displayMode: 'mini' }))
})
it('编号入口加载详情后自动发起一次播放', async () => {
mount(ExhibitDetail, {
global: { stubs: { GuidePageFrame: GuidePageFrameStub } }
})
await mocks.onLoadHandler?.({
id: exhibit.id,
stopId: 'stop-1',
autoplay: '1',
entry: 'code'
})
await flushPromises()
expect(mocks.play).toHaveBeenCalledTimes(1)
expect(mocks.play).toHaveBeenCalledWith(
expect.objectContaining({ audioUrl: exhibit.audioUrl }),
expect.objectContaining({ displayMode: 'mini' })
)
})
it('加载中使用同一高度底栏和不确定进度', async () => {
audioState.currentAudio.value = { id: 'audio-1' }
audioState.currentSource.value = { targetType: 'STOP', targetId: 'stop-1', lang: 'en-US' }
@@ -326,6 +354,81 @@ describe('讲解详情音频优先布局', () => {
}))
})
it('暂停时切换语言立即刷新播放器但不自动播放', async () => {
const bilingualExhibit = {
...exhibit,
audioLanguage: 'en-US',
audioOptions: [
{ channelCode: 'standard.zh-CN.female', version: 'standard', languageCode: 'zh-CN', gender: 'female', playUrl: '/assets/zh-female.mp3', duration: 50 },
{ channelCode: 'standard.en-US.female', version: 'standard', languageCode: 'en-US', gender: 'female', playUrl: '/assets/en-female.mp3', duration: 80 }
]
}
mocks.enterExplainDetail.mockResolvedValue(bilingualExhibit)
mocks.selectAudioForExplainDetail.mockImplementation(async (data: { audioLanguage: string }) => {
const option = bilingualExhibit.audioOptions.find((item) => item.languageCode === data.audioLanguage)!
return {
playable: true,
exhibit: bilingualExhibit,
media: { id: option.channelCode, url: option.playUrl, duration: option.duration, language: option.languageCode },
playInfo: { title: exhibit.name }
}
})
audioState.currentAudio.value = { id: 'standard.en-US.female', audioUrl: '/assets/en-female.mp3' }
audioState.currentSource.value = { stopId: 'stop-1', lang: 'en-US', channelCode: 'standard.en-US.female' }
audioState.playing.value = false
const wrapper = mount(ExhibitDetail, {
global: { stubs: { GuidePageFrame: GuidePageFrameStub } }
})
await mocks.onLoadHandler?.({ id: exhibit.id, stopId: 'stop-1', lang: 'en-US' })
await flushPromises()
await wrapper.findAll('.language-option').find((button) => button.text() === '中文')!.trigger('tap')
await flushPromises()
expect(mocks.prepare).toHaveBeenCalledWith(
expect.objectContaining({ audioUrl: '/assets/zh-female.mp3', language: 'zh-CN', duration: 50 }),
expect.objectContaining({ source: expect.objectContaining({ lang: 'zh-CN', channelCode: 'standard.zh-CN.female' }) })
)
expect(mocks.play).not.toHaveBeenCalled()
})
it('暂停时切换男女声立即刷新播放器但不自动播放', async () => {
const voiceExhibit = {
...exhibit,
audioOptions: [
{ channelCode: 'standard.en-US.female', version: 'standard', languageCode: 'en-US', gender: 'female', playUrl: '/assets/en-female.mp3', duration: 80 },
{ channelCode: 'standard.en-US.male', version: 'standard', languageCode: 'en-US', gender: 'male', playUrl: '/assets/en-male.mp3', duration: 75 }
]
}
mocks.enterExplainDetail.mockResolvedValue(voiceExhibit)
mocks.selectAudioForExplainDetail.mockImplementation(async (_data: unknown, options: { voiceGender?: string }) => {
const option = voiceExhibit.audioOptions.find((item) => item.gender === options.voiceGender)!
return {
playable: true,
exhibit: voiceExhibit,
media: { id: option.channelCode, url: option.playUrl, duration: option.duration, language: option.languageCode },
playInfo: { title: exhibit.name }
}
})
audioState.currentAudio.value = { id: 'standard.en-US.female', audioUrl: '/assets/en-female.mp3' }
audioState.currentSource.value = { stopId: 'stop-1', lang: 'en-US', channelCode: 'standard.en-US.female' }
audioState.playing.value = false
const wrapper = mount(ExhibitDetail, {
global: { stubs: { GuidePageFrame: GuidePageFrameStub } }
})
await mocks.onLoadHandler?.({ id: exhibit.id, stopId: 'stop-1', lang: 'en-US' })
await flushPromises()
await wrapper.get('.detail-audio-voice').trigger('tap')
await flushPromises()
expect(mocks.prepare).toHaveBeenCalledWith(
expect.objectContaining({ audioUrl: '/assets/en-male.mp3', duration: 75 }),
expect.objectContaining({ source: expect.objectContaining({ voiceGender: 'male', channelCode: 'standard.en-US.male' }) })
)
expect(mocks.play).not.toHaveBeenCalled()
})
it('播放器单行提供倍速循环和男女声切换', async () => {
mocks.enterExplainDetail.mockResolvedValue({
...exhibit,
@@ -362,6 +465,40 @@ describe('讲解详情音频优先布局', () => {
expect(mocks.toggleMute).not.toHaveBeenCalled()
})
it('编号入口详情返回时回到原编号输入页', async () => {
vi.stubGlobal('getCurrentPages', vi.fn(() => [
{ route: 'pages/explain/list', options: {} },
{ route: 'pages/exhibit/detail', options: { entry: 'code' } }
]))
const wrapper = mount(ExhibitDetail, {
global: { stubs: { GuidePageFrame: GuidePageFrameStub } }
})
await mocks.onLoadHandler?.({ id: exhibit.id, stopId: 'stop-1', entry: 'code' })
await flushPromises()
wrapper.getComponent(GuidePageFrameStub).vm.$emit('back')
await flushPromises()
expect(uni.navigateBack).toHaveBeenCalledWith(expect.objectContaining({ delta: 1 }))
expect(uni.redirectTo).not.toHaveBeenCalled()
})
it('编号入口详情丢失页面栈时回退到自动打开的编号输入页', async () => {
const wrapper = mount(ExhibitDetail, {
global: { stubs: { GuidePageFrame: GuidePageFrameStub } }
})
await mocks.onLoadHandler?.({ id: exhibit.id, stopId: 'stop-1', entry: 'code' })
await flushPromises()
wrapper.getComponent(GuidePageFrameStub).vm.$emit('back')
await flushPromises()
expect(uni.navigateBack).not.toHaveBeenCalled()
expect(uni.redirectTo).toHaveBeenCalledWith(expect.objectContaining({
url: '/pages/explain/list?codeEntry=1'
}))
})
it('上一页是讲解对象列表时使用页面栈返回', async () => {
vi.stubGlobal('getCurrentPages', vi.fn(() => [
{ route: 'pages/explain/guide-stop-list', options: {} },

View File

@@ -0,0 +1,34 @@
import { describe, expect, it } from 'vitest'
import {
explainCodeDetailUrl,
explainCodeErrorMessage,
normalizeExplainCode
} from '@/utils/explainCodeEntry'
describe('讲解编号入口', () => {
it('清理首尾空格但保留编号前导零', () => {
expect(normalizeExplainCode(' 0231 ')).toBe('0231')
})
it.each([
[1020007000, '请输入有效的 4 位讲解编号'],
[1020007001, '未找到该讲解编号,请确认后重试'],
[1020007002, '该编号的讲解内容暂不可用'],
[429, '查询过于频繁,请稍后再试']
])('将业务错误码 %s 转换为明确提示', (code, message) => {
expect(explainCodeErrorMessage({ code })).toBe(message)
})
it('未知错误使用网络重试提示', () => {
expect(explainCodeErrorMessage(new Error('offline'))).toBe('编号查询失败,请检查网络后重试')
})
it('详情路由携带讲解点和自动播放意图', () => {
const url = explainCodeDetailUrl({ code: '1001', stopId: '865546652298080256' })
expect(url.split('?')[0]).toBe('/pages/exhibit/detail')
expect(url).toContain('stopId=865546652298080256')
expect(url).toContain('autoplay=1')
expect(url).toContain('entry=code')
expect(url).toContain('guideCode=1001')
})
})

View File

@@ -5,7 +5,7 @@ import { describe, expect, it } from 'vitest'
import ExplainGuideStopCatalog from '@/components/explain/ExplainGuideStopCatalog.vue'
const stops = [
{ id: 'ready', name: '一个很长很长很长很长很长的讲解对象名称', coverImageUrl: '/cover.jpg', audioStatus: 'READY', hasAudio: true, hasTextRecord: true },
{ id: 'ready', name: '一个很长很长很长很长很长的讲解对象名称', externalCode: '0231', coverImageUrl: '/cover.jpg', audioStatus: 'READY', hasAudio: true, hasTextRecord: true },
{ id: 'text', name: '图文对象', hasTextRecord: true },
{ id: 'none', name: '无内容对象' }
]
@@ -22,6 +22,11 @@ describe('ExplainGuideStopCatalog', () => {
expect(wrapper.findAll('.stop-status')).toHaveLength(3)
expect(wrapper.text()).toContain('讲解')
expect(wrapper.text()).toContain('图文')
expect(wrapper.get('.stop-code').text()).toBe('编号0231')
expect(wrapper.findAll('.stop-code')).toHaveLength(1)
const readyCopy = wrapper.get('.stop-card .stop-copy')
expect(readyCopy.element.firstElementChild?.classList.contains('stop-code')).toBe(true)
expect(readyCopy.element.lastElementChild?.classList.contains('stop-name')).toBe(true)
expect(wrapper.text()).not.toContain('暂无内容')
expect(wrapper.find('.hall-arrow').exists()).toBe(false)
expect(wrapper.find('.stop-name').classes()).toContain('stop-name')

View File

@@ -67,6 +67,56 @@ describe('讲解展厅选择列表', () => {
expect(wrapper.emitted('hallClick')).toEqual([['hall-evolution']])
})
it('展厅阶段可输入讲解编号并保留前导零', async () => {
const wrapper = mount(ExplainHallSelect, {
props: { stage: 'hall' }
})
expect(wrapper.get('.code-entry-title').text()).toBe('编号讲解')
expect(wrapper.get('.hall-section-title').text()).toBe('按展厅选择')
expect(wrapper.find('.code-entry-arrow').exists()).toBe(false)
await wrapper.get('.code-entry-button').trigger('tap')
expect(wrapper.get('.header-title').text()).toBe('编号讲解')
expect(wrapper.find('.code-entry-close').exists()).toBe(false)
expect(wrapper.get('.code-entry-sheet-title').text()).toBe('输入讲解编号')
expect(wrapper.findAll('.code-digit-cell')).toHaveLength(4)
expect(wrapper.text()).toContain('请输入展品标签上的四位编号')
await wrapper.get('.code-entry-native-input').trigger('input', { detail: { value: '02a' } })
expect(wrapper.get('.code-entry-action.primary').attributes('disabled')).toBeDefined()
await wrapper.get('.code-entry-native-input').trigger('confirm')
expect(wrapper.get('.code-entry-error').text()).toBe('请输入完整的 4 位讲解编号')
await wrapper.get('.code-entry-native-input').trigger('input', { detail: { value: '0231' } })
expect(wrapper.findAll('.code-digit-value').map((item) => item.text())).toEqual(['0', '2', '3', '1'])
await wrapper.get('.code-entry-action.primary').trigger('tap')
expect(wrapper.emitted('codeSubmit')).toEqual([['0231']])
expect(wrapper.find('.code-entry-sheet').exists()).toBe(true)
wrapper.vm.completeCodeEntry()
await wrapper.vm.$nextTick()
expect(wrapper.find('.code-entry-sheet').exists()).toBe(true)
expect(wrapper.findAll('.code-digit-value').map((item) => item.text())).toEqual(['', '', '', ''])
await wrapper.setProps({ codeSubmitting: true })
expect(wrapper.get('.code-entry-native-input').attributes('disabled')).toBeDefined()
expect(wrapper.get('.code-entry-action.primary').text()).toBe('正在查询')
wrapper.vm.showCodeEntryError('未找到该讲解编号,请确认后重试')
await wrapper.vm.$nextTick()
expect(wrapper.get('.code-entry-error').text()).toBe('未找到该讲解编号,请确认后重试')
await wrapper.get('.header-back').trigger('tap')
expect(wrapper.find('.code-entry-sheet').exists()).toBe(false)
expect(wrapper.get('.header-title').text()).toBe('免费讲解')
expect(wrapper.emitted('back')).toBeUndefined()
await wrapper.get('.header-back').trigger('tap')
expect(wrapper.emitted('back')).toEqual([[]])
})
it('展厅阶段使用完整展厅卡片资源', () => {
const wrapper = mount(ExplainHallSelect, {
props: {
@@ -84,9 +134,9 @@ describe('讲解展厅选择列表', () => {
const card = wrapper.get('.hall-overview-card')
expect(wrapper.get('.header-title').text()).toBe('免费讲解')
expect(card.attributes('style')).toContain('--hall-card-color: #d9b06c')
expect(card.attributes('style')).toContain('--hall-card-color: #bb965a')
expect(card.get('.hall-full-card-image').attributes('src'))
.toBe('/static/icons/halls/custom-cards/dinosaur.png')
.toBe('/static/icons/halls/portal-icons/dinosaur.png')
expect(card.find('.hall-overview-copy').exists()).toBe(false)
expect(card.find('.hall-go-entry').exists()).toBe(false)
})

View File

@@ -33,11 +33,28 @@ const createUseCase = (detail: GuideStopDetail) => {
getExhibitById: vi.fn().mockResolvedValue(null),
listExplainExhibits: vi.fn().mockResolvedValue([])
} as unknown as ExplainRepository
const audio = { getStopDetail: vi.fn().mockResolvedValue(detail) } as unknown as AudioPlayInfoRepository
const audio = {
getStopDetail: vi.fn().mockResolvedValue(detail),
getStopInfoByCode: vi.fn().mockResolvedValue({
available: true,
resolvedStopId: 'resolved-stop-1',
playTargetId: 'resolved-stop-1',
targetId: 'resolved-stop-1'
})
} as unknown as AudioPlayInfoRepository
return { useCase: new ExplainUseCase(explain, audio), explain, audio }
}
describe('ExplainUseCase unified stop detail', () => {
it('resolves the museum code to the backend stop ID', async () => {
const { useCase, audio } = createUseCase(createDetail())
const result = await useCase.resolveExplainCode('1001', 'zh-CN')
expect(audio.getStopInfoByCode).toHaveBeenCalledWith('1001', 'zh-CN')
expect(result).toEqual({ code: '1001', stopId: 'resolved-stop-1' })
})
it('uses stopId once in remote mode without requesting a catalog fallback', async () => {
const originalMode = dataSourceConfig.explainContentMode
Object.assign(dataSourceConfig, { explainContentMode: 'remote' })

View File

@@ -20,6 +20,26 @@ describe('全局讲解播放器语言切换', () => {
vi.unstubAllGlobals()
})
it('媒体元数据加载前忽略接口时长,加载后使用音频真实时长', () => {
const audio = document.createElement('audio')
vi.spyOn(window, 'Audio').mockImplementation(() => audio)
player.prepare({
id: 'duration-audio',
name: '时长测试',
audioUrl: '/museum-assets/audio/duration.mp3',
duration: 28,
language: 'zh-CN'
})
expect(player.duration.value).toBe(0)
Object.defineProperty(audio, 'duration', { configurable: true, value: 54.974938 })
audio.dispatchEvent(new Event('loadedmetadata'))
expect(player.duration.value).toBeCloseTo(54.974938)
})
it('切换到粤语时只从当前统一详情的音轨数组选择,不产生额外 HTTP 请求', async () => {
const request = vi.fn()
vi.stubGlobal('uni', { request, showToast: vi.fn() })