Commit 8c0d8801 by chenwq

fix: 优化车型素材加载逻辑,支持渐进式加载和后台补齐

1 parent e6bd1afe
......@@ -213,7 +213,7 @@ export default {
if (this.clickFlga) uni.hideLoading()
this.clickFlga = false
},
handleSelect(item) {
async handleSelect(item) {
this.cancelPendingRequests()
const customerInfo = { ...this.$store.state.user.customerInfo },
{ selectItem, linkage } = this
......@@ -225,6 +225,12 @@ export default {
oneCarBrand: selectItem.carBrand,
oneCarBrandId: selectItem.carBrandId
})
// 页面刷新会重建当前素材组件;必须先让车系弹窗完成关闭,不能把浮层遗留到新页面里。
this.$refs.carBoxVisible?.close()
this.$refs.carBrandListVisible?.close()
this.carBrandListOff = false
this.$store.dispatch('setCarBrandOpenStatus', false)
await this.$nextTick()
if (linkage) {
uni.$logger.local.info(`选择车:
carModel:${item.name},
......@@ -237,10 +243,6 @@ export default {
this.$store.dispatch('setCurrentCarInfo', selectItem)
this.$store.dispatch('updateViewKey')
}
this.$refs.carBoxVisible?.close();
this.$refs.carBrandListVisible?.close();
this.carBrandListOff = false
this.$store.dispatch('setCarBrandOpenStatus', false)
this.$emit('select', {
...item,
...selectItem
......
......@@ -69,6 +69,9 @@
</view>
</view>
</template>
<view v-if="materialLoading" class="material-loading-mask" @click.stop>
正在加载车型素材…
</view>
<template v-if="type != 'preview'">
<template v-if="backZindex">
<tool-box
......@@ -179,7 +182,8 @@ export default {
loadedIndexes: [],
longImagePopupVisible: false,
brandPopupVisible: false,
offlineReadyId: ''
offlineReadyId: '',
materialLoading: false
}
},
computed: {
......@@ -348,7 +352,10 @@ export default {
this.offlineReadyId = ''
}
if (!this.pageToolList.length) this.pageToolList = this.toolList
if (newval && this._offlineSource) return this.loadOfflineMaterial(newval)
if (newval && this._offlineSource) {
if (String(this.offlineReadyId) === String(newval)) return
return this.loadOfflineMaterial(newval)
}
if (newval && oldval !== undefined && !oldval) return this.setPageData()
}
},
......@@ -599,8 +606,11 @@ export default {
}
const startedAt = Date.now()
const previousSource = this._offlineSource
const keepVisible = this.hasVisibleMaterial()
this._offlineSource = null
this.offlineReadyId = ''
if (!keepVisible) this.offlineReadyId = ''
if (keepVisible) this.startMaterialLoading()
else this.materialLoading = false
const requestId = this._sourceRequestId = (this._sourceRequestId || 0) + 1
const isCurrent = () => !!this.id && !this._sourceDisposed && !this._isDestroyed && requestId === this._sourceRequestId
const { shopMerchantId, sceneType, currentCarInfo } = this,
......@@ -635,13 +645,18 @@ export default {
console.log('setPageData cache', { id: data.id, modules: data.moduleList.length, tools: data.toolList.length, online, networkMs, baseMs: Date.now() - startedAt - networkMs, reused: !!reuseBase })
const target = this.getSourceTarget(data)
this._offlineSource = { key: resolvedKey, requestedKey: storageName, base: data, carKey, requestId, online }
this.setViewInfo(data) // 先从缓存中获取数据
if (target) await this.loadOfflineMaterial(target.id)
if (!keepVisible) this.setViewInfo(data)
if (target) await this.loadOfflineMaterial(target.id, { deferViewInfo: keepVisible, criticalOnly: keepVisible })
else this.finishMaterialLoading()
} else {
this.useCarConfig = false
this.moduleList = []
this.pageToolList = this.toolList || []
this.currentMediaId = this.mediaId
if (!keepVisible) {
this.useCarConfig = false
this.moduleList = []
this.pageToolList = this.toolList || []
this.currentMediaId = this.mediaId
}
// 有旧内容但本地没有新车型缓存时,继续显示提示并等待在线数据。
if (!online && keepVisible) this.finishMaterialLoading()
}
if (!online) return
try {
......@@ -650,10 +665,14 @@ export default {
// 接口返回不走原始 URL,改为和缓存一致:以接口数据为源补齐 base64 后再渲染。
this._offlineSource = { key: storageName, requestedKey: storageName, base: requestData, carKey, requestId, online: true }
const target = this.getSourceTarget(requestData)
this.setViewInfo(requestData)
if (target) await this.loadOfflineMaterial(target.id)
const keepVisibleForNetwork = this.hasVisibleMaterial()
if (!keepVisibleForNetwork) this.setViewInfo(requestData)
if (target) await this.loadOfflineMaterial(target.id, { deferViewInfo: keepVisibleForNetwork, criticalOnly: keepVisibleForNetwork })
else this.finishMaterialLoading()
} catch (error) {
// 保留已展示的缓存;过期请求不能修改当前车型。
// 当前请求失败后结束提示,避免弱网下提示一直停留。
if (isCurrent()) this.finishMaterialLoading()
}
},
getSourceTarget (data) {
......@@ -663,26 +682,66 @@ export default {
const previous = (this.renderList || []).find(item => item.id == this.id)
return modules.find(item => item.detailTitle == previous?.detailTitle) || modules[0]
},
async loadOfflineMaterial (materialId = this.id) {
hasVisibleMaterial () {
return this.useCarConfig && this.moduleList.length > 0 && !!this.offlineReadyId
},
startMaterialLoading () {
const minimumVisibleMs = 280
this._materialLoadingToken = (this._materialLoadingToken || 0) + 1
this._materialLoadingStartedAt = Date.now()
this._minimumMaterialLoadingMs = minimumVisibleMs
this.materialLoading = true
},
finishMaterialLoading () {
if (!this.materialLoading) return
const token = this._materialLoadingToken
const elapsed = Date.now() - (this._materialLoadingStartedAt || 0)
const delay = Math.max(0, (this._minimumMaterialLoadingMs || 0) - elapsed)
const hide = () => {
if (token === this._materialLoadingToken) this.materialLoading = false
}
if (delay) setTimeout(hide, delay)
else hide()
},
async loadOfflineMaterial (materialId = this.id, { deferViewInfo = false, criticalOnly = false } = {}) {
const source = this._offlineSource
if (!source || !this.id) return
const imageRequestId = this._offlineImageRequestId = (this._offlineImageRequestId || 0) + 1
const isCurrent = () => this._offlineSource === source && !!this.id &&
!this._sourceDisposed && source.requestId === this._sourceRequestId && imageRequestId === this._offlineImageRequestId
this.offlineReadyId = ''
if (!deferViewInfo) this.offlineReadyId = ''
const display = await materialCache.hydrateSourceImages(source.key, source.base, {
moduleIds: [materialId], toolIds: [materialId], carKey: source.carKey, isCurrent,
moduleIds: [materialId], toolIds: criticalOnly ? [] : [materialId], carKey: source.carKey, isCurrent,
maxImages: criticalOnly ? 1 : undefined,
hideUnloadedImages: criticalOnly,
// 在线时缺失的图片按需补齐,避免渲染出原始 URL。
allowDownload: source.online !== false,
onMetrics: metrics => { if (isCurrent()) console.log('setPageData images', { materialId, carKey: source.carKey, ...metrics }) }
})
if (!isCurrent() || !display) return
this.moduleList = Object.freeze(display.moduleList)
if (deferViewInfo) {
// 先标记新素材已就绪,避免更新当前素材 ID 时触发重复读取并打断切换。
this.offlineReadyId = materialId
this.setViewInfo(display)
} else this.moduleList = Object.freeze(display.moduleList)
this.applyOfflineTools(display.toolList)
this.offlineReadyId = materialId
this.finishMaterialLoading()
if (criticalOnly) this.loadRemainingOfflineMaterial(materialId, source, imageRequestId)
// 文件夹已打开时才需要补齐工具图标,不占用当前素材的首图读取。
if (this.$refs.toolRef?.show === false) this.loadOfflineTools(true)
},
async loadRemainingOfflineMaterial (materialId, source, imageRequestId) {
const isCurrent = () => this._offlineSource === source && !!this.id &&
!this._sourceDisposed && source.requestId === this._sourceRequestId && imageRequestId === this._offlineImageRequestId
const display = await materialCache.hydrateSourceImages(source.key, source.base, {
moduleIds: [materialId], toolIds: [materialId], carKey: source.carKey, isCurrent,
allowDownload: source.online !== false
})
if (!display || !isCurrent()) return
this.moduleList = Object.freeze(display.moduleList)
this.applyOfflineTools(display.toolList)
},
applyOfflineTools (tools) {
const previous = new Map((this.pageToolList || []).map(item => [String(item.id), item.shortTitleUrl]))
this.pageToolList = Object.freeze(tools.map(item => ({
......@@ -887,6 +946,19 @@ export default {
pointer-events: auto;
}
}
.material-loading-mask {
position: fixed;
left: 50%;
top: toRpx(64);
transform: translateX(-50%);
z-index: 12;
padding: toRpx(12) toRpx(28);
border-radius: toRpx(32);
color: #ffffff;
font-size: toRpx(26);
line-height: toRpx(36);
background: rgba(0, 0, 0, 0.56);
}
.pen-box {
position: fixed;
right: toRpx(40);
......
......@@ -193,6 +193,39 @@ async function run() {
})
assert.equal(switchedDisplay.moduleList[0].contentPicUrl, '_doc/uniapp_save/material-2.jpg')
assert.equal(uni.calls.removeSavedFile, 1, '清理过期文件时不应误删新文件')
// 车型切换的首屏只读取一张关键图片,剩余图片留给后台补齐,不能阻塞页面替换。
global.uni = createUni()
delete require.cache[modulePath]
const progressiveCache = require(modulePath)
const progressiveKey = progressiveCache.getSourceKey('shop-5', 'scene-1', { brandId: 10, subBrandId: 20 })
const multiImageSource = {
id: 'source-5',
moduleList: [{
id: 501,
thumbnail: 'https://example.test/thumb.jpg',
contentPicUrl: 'https://example.test/content.jpg',
receptionSourceDetailList: [{ detailUrl: 'https://example.test/detail.jpg' }]
}],
toolList: []
}
await progressiveCache.cacheMaterialImages(progressiveKey, multiImageSource)
progressiveCache.clearImageMemory()
const firstScreen = await progressiveCache.hydrateSourceImages(progressiveKey, multiImageSource, {
moduleIds: [501], toolIds: [], maxImages: 1, hideUnloadedImages: true, isCurrent: () => true
})
const firstModule = firstScreen.moduleList[0]
const firstSavedCount = [firstModule.thumbnail, firstModule.contentPicUrl, firstModule.receptionSourceDetailList[0].detailUrl]
.filter(value => value.startsWith('_doc/uniapp_save/')).length
assert.equal(firstSavedCount, 1, '首屏只应读取一张关键图片')
assert.ok([firstModule.thumbnail, firstModule.contentPicUrl, firstModule.receptionSourceDetailList[0].detailUrl]
.filter(value => !value.startsWith('_doc/uniapp_save/')).every(value => value === ''), '未准备好的图片不应直接使用网络链接')
const fullScreen = await progressiveCache.hydrateSourceImages(progressiveKey, multiImageSource, {
moduleIds: [501], toolIds: [], isCurrent: () => true
})
const fullModule = fullScreen.moduleList[0]
assert.ok([fullModule.thumbnail, fullModule.contentPicUrl, fullModule.receptionSourceDetailList[0].detailUrl]
.every(value => value.startsWith('_doc/uniapp_save/')), '后台补齐时应恢复全部图片')
console.log('PASS material file cache')
}
......
......@@ -333,6 +333,8 @@ function remoteImagePaths(items) {
// 直接根据当前素材 ID、图片位置和 URL 算出 key,不枚举 storage 或读取其他素材图片。
async function hydrateSourceImages(key, base, options = {}) {
const isCurrent = options.isCurrent || (() => true)
const maxImages = Number.isFinite(options.maxImages) ? Math.max(0, options.maxImages) : Infinity
let remainingImages = maxImages
const start = Date.now()
const metrics = { storageReads: 0, memoryHits: 0, sharedReads: 0, imageHits: 0, missingImages: 0, downloadedImages: 0, requestedImages: 0, pathBytes: 0, leftoverUrls: [] }
if (!isCurrent() || !isSource(base)) return null
......@@ -344,10 +346,31 @@ async function hydrateSourceImages(key, base, options = {}) {
const selected = Array.isArray(ids) ? new Set(ids.map(String)) : null
display[kind] = base[kind].map(item => {
if (!item || !hasId(item.id) || (selected && !selected.has(String(item.id)))) return item
const slots = imageSlots(item, kind, options)
const allSlots = imageSlots(item, kind, options)
// 首屏只等待最能代表当前素材的图片;其余图片由后续后台读取补齐。
const slots = remainingImages === Infinity ? allSlots : allSlots
.sort((a, b) => {
const priority = ['detailUrl', 'contentPicUrl', 'bgUrl', 'homeEntranceCover', 'thumbnail', 'shortTitleUrl']
const getPriority = slot => {
const index = priority.indexOf(slot.path[slot.path.length - 1])
return index < 0 ? priority.length : index
}
return getPriority(a) - getPriority(b)
})
.slice(0, remainingImages)
remainingImages -= slots.length
if (!slots.length) return item
// 只复制本次要展示的素材,其他条目保留轻量基础数据。
const clone = JSON.parse(JSON.stringify(item))
// 首屏渐进加载时,未准备好的网络图片不能直接交给组件,避免组件绕过文件缓存自行发起请求。
if (options.hideUnloadedImages) {
const selectedKeys = new Set(slots.map(slot => slot.key))
allSlots.filter(slot => !selectedKeys.has(slot.key)).forEach(slot => {
let target = clone
slot.path.slice(0, -1).forEach(part => { target = target[part] })
target[slot.path[slot.path.length - 1]] = ''
})
}
hydrated.push(clone)
slots.forEach(slot => {
metrics.requestedImages++
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!