Commit 0e7aaa95 by 李伟康

chore: 升级版本至2.26.7,修复离线素材问题并优化缓存

- 更新manifest.json版本号从2.26.6到2.26.7
- 为完成接待弹框新增关闭事件回调与可见状态管理
- 移除权益详情页冗余的sourceOnline状态,简化素材加载逻辑
- 优化素材图片缓存工具,避免重复下载并完善错误处理机制
- 新增弹框展示时延迟页面刷新,关闭后自动补刷的逻辑
1 parent 1871c760
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
ref="formRef" ref="formRef"
@cancel="cancel" @cancel="cancel"
@confirm="submit" @confirm="submit"
@close="handleClose"
:cancelBtnText="`${step == 1 ? '取消' : '上一步'}`" :cancelBtnText="`${step == 1 ? '取消' : '上一步'}`"
:confirmBtnText="`${sceneType == 0 ? (step == 1 ? '下一步' : '完成接待') : '完成接待'}`" :confirmBtnText="`${sceneType == 0 ? (step == 1 ? '下一步' : '完成接待') : '完成接待'}`"
:title="`${step == 1 ? '客户信息完善' : '结果反馈'}`" :title="`${step == 1 ? '客户信息完善' : '结果反馈'}`"
...@@ -160,6 +161,8 @@ export default { ...@@ -160,6 +161,8 @@ export default {
data () { data () {
return { return {
step: 1, step: 1,
// 完成接待弹框是否处于打开状态,供外层决定是否需要延时刷新。
visible: false,
formObject: [ formObject: [
{ {
label: "车主姓名", label: "车主姓名",
...@@ -277,6 +280,11 @@ export default { ...@@ -277,6 +280,11 @@ export default {
this.receptionStatus = -1 this.receptionStatus = -1
this.$refs.formRef.close() this.$refs.formRef.close()
}, },
// 弹框实际关闭(取消、右上角关闭或提交后收起)时同步状态并通知外层。
handleClose () {
this.visible = false
this.$emit('close')
},
check (all = false) { check (all = false) {
let flag = true let flag = true
try { try {
...@@ -362,6 +370,7 @@ export default { ...@@ -362,6 +370,7 @@ export default {
} }
this.step = step this.step = step
this.$refs.formRef.open() this.$refs.formRef.open()
this.visible = true
this.updateViewKey = Date.now() this.updateViewKey = Date.now()
}) })
}, },
......
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
"name" : "展业助手", "name" : "展业助手",
"appid" : "__UNI__D3BD3DF", "appid" : "__UNI__D3BD3DF",
"description" : "", "description" : "",
"versionName" : "2.26.6", "versionName" : "2.26.7",
"versionCode" : 2266, "versionCode" : 2267,
"transformPx" : false, "transformPx" : false,
"sassImplementationName" : "node-sass", "sassImplementationName" : "node-sass",
/* 5+App特有相关 */ /* 5+App特有相关 */
......
...@@ -97,6 +97,7 @@ ...@@ -97,6 +97,7 @@
<finish-step <finish-step
ref="stepRef" ref="stepRef"
@submit="done" @submit="done"
@close="handleFinishStepClose"
:titleTips="finishTips" :titleTips="finishTips"
/> />
<informationEntry <informationEntry
...@@ -178,7 +179,6 @@ export default { ...@@ -178,7 +179,6 @@ export default {
loadedIndexes: [], loadedIndexes: [],
longImagePopupVisible: false, longImagePopupVisible: false,
brandPopupVisible: false, brandPopupVisible: false,
sourceOnline: true,
offlineReadyId: '' offlineReadyId: ''
} }
}, },
...@@ -250,7 +250,7 @@ export default { ...@@ -250,7 +250,7 @@ export default {
return this.renderList[this.currentIndex] || {} return this.renderList[this.currentIndex] || {}
}, },
longImageUrl () { longImageUrl () {
if (!this.sourceOnline && String(this.offlineReadyId) !== String(this.id)) return '' if (String(this.offlineReadyId) !== String(this.id)) return ''
const item = this.currentMaterial || {} const item = this.currentMaterial || {}
const matched = this.getMatchedMaterialDetail(item) const matched = this.getMatchedMaterialDetail(item)
...@@ -348,7 +348,7 @@ export default { ...@@ -348,7 +348,7 @@ export default {
this.offlineReadyId = '' this.offlineReadyId = ''
} }
if (!this.pageToolList.length) this.pageToolList = this.toolList if (!this.pageToolList.length) this.pageToolList = this.toolList
if (newval && !this.sourceOnline && this._offlineSource) return this.loadOfflineMaterial(newval) if (newval && this._offlineSource) return this.loadOfflineMaterial(newval)
if (newval && oldval !== undefined && !oldval) return this.setPageData() if (newval && oldval !== undefined && !oldval) return this.setPageData()
} }
}, },
...@@ -406,10 +406,18 @@ export default { ...@@ -406,10 +406,18 @@ export default {
this.showPayPage = false this.showPayPage = false
this.closeLongImagePopup() this.closeLongImagePopup()
this.$refs.toolRef.hide() this.$refs.toolRef.hide()
// 提交完成接待后页面即将重置,不再补做被延后的刷新。
this._pendingPageData = false
this.$refs.stepRef.close() this.$refs.stepRef.close()
this.receptionTrackLeave() this.receptionTrackLeave()
this.$emit('done', e) this.$emit('done', e)
}, },
// 用户关闭完成接待弹框后,补一次弹框期间被延后的素材刷新。
handleFinishStepClose () {
if (!this._pendingPageData) return
this._pendingPageData = false
this.setPageData()
},
/**切换素材 */ /**切换素材 */
choose (e) { choose (e) {
this.closeLongImagePopup() this.closeLongImagePopup()
...@@ -584,6 +592,11 @@ export default { ...@@ -584,6 +592,11 @@ export default {
// }, // },
async setPageData (networkStatus) { async setPageData (networkStatus) {
// 完成接待弹框打开期间不刷新素材,避免弹框上下文被重渲染打断;关闭后再补一次。
if (this.$refs.stepRef?.visible) {
this._pendingPageData = true
return
}
const startedAt = Date.now() const startedAt = Date.now()
const previousSource = this._offlineSource const previousSource = this._offlineSource
this._offlineSource = null this._offlineSource = null
...@@ -601,7 +614,6 @@ export default { ...@@ -601,7 +614,6 @@ export default {
const online = typeof networkStatus === 'boolean' ? networkStatus : await materialCache.getNetworkStatus() const online = typeof networkStatus === 'boolean' ? networkStatus : await materialCache.getNetworkStatus()
if (!isCurrent()) return if (!isCurrent()) return
const networkMs = Date.now() - startedAt const networkMs = Date.now() - startedAt
this.sourceOnline = online
const storageName = materialCache.getSourceKey(shopMerchantId, sceneType, params) const storageName = materialCache.getSourceKey(shopMerchantId, sceneType, params)
let resolvedKey = storageName let resolvedKey = storageName
// 同品牌切车系复用轻量基础配置,图片仍按本次素材 ID / 车系的 key 查找。 // 同品牌切车系复用轻量基础配置,图片仍按本次素材 ID / 车系的 key 查找。
...@@ -622,9 +634,9 @@ export default { ...@@ -622,9 +634,9 @@ export default {
// 保留诊断信息,避免离线时将整包 base64 输出到控制台。 // 保留诊断信息,避免离线时将整包 base64 输出到控制台。
console.log('setPageData cache', { id: data.id, modules: data.moduleList.length, tools: data.toolList.length, online, networkMs, baseMs: Date.now() - startedAt - networkMs, reused: !!reuseBase }) 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) const target = this.getSourceTarget(data)
if (!online) this._offlineSource = { key: resolvedKey, requestedKey: storageName, base: data, carKey, requestId } this._offlineSource = { key: resolvedKey, requestedKey: storageName, base: data, carKey, requestId, online }
this.setViewInfo(data) // 先从缓存中获取数据 this.setViewInfo(data) // 先从缓存中获取数据
if (!online && target) await this.loadOfflineMaterial(target.id) if (target) await this.loadOfflineMaterial(target.id)
} else { } else {
this.useCarConfig = false this.useCarConfig = false
this.moduleList = [] this.moduleList = []
...@@ -633,8 +645,13 @@ export default { ...@@ -633,8 +645,13 @@ export default {
} }
if (!online) return if (!online) return
try { try {
let requestData = await uni.$api.systemApi.getSoureData(shopMerchantId, sceneType, params) const requestData = await uni.$api.systemApi.getSoureData(shopMerchantId, sceneType, params)
if (isCurrent() && requestData) this.setViewInfo(requestData) if (!isCurrent() || !requestData) return
// 接口返回不走原始 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)
} catch (error) { } catch (error) {
// 保留已展示的缓存;过期请求不能修改当前车型。 // 保留已展示的缓存;过期请求不能修改当前车型。
} }
...@@ -648,13 +665,15 @@ export default { ...@@ -648,13 +665,15 @@ export default {
}, },
async loadOfflineMaterial (materialId = this.id) { async loadOfflineMaterial (materialId = this.id) {
const source = this._offlineSource const source = this._offlineSource
if (!source || this.sourceOnline || !this.id) return if (!source || !this.id) return
const imageRequestId = this._offlineImageRequestId = (this._offlineImageRequestId || 0) + 1 const imageRequestId = this._offlineImageRequestId = (this._offlineImageRequestId || 0) + 1
const isCurrent = () => this._offlineSource === source && !this.sourceOnline && !!this.id && const isCurrent = () => this._offlineSource === source && !!this.id &&
!this._sourceDisposed && source.requestId === this._sourceRequestId && imageRequestId === this._offlineImageRequestId !this._sourceDisposed && source.requestId === this._sourceRequestId && imageRequestId === this._offlineImageRequestId
this.offlineReadyId = '' this.offlineReadyId = ''
const display = await materialCache.hydrateSourceImages(source.key, source.base, { const display = await materialCache.hydrateSourceImages(source.key, source.base, {
moduleIds: [materialId], toolIds: [materialId], carKey: source.carKey, isCurrent, moduleIds: [materialId], toolIds: [materialId], carKey: source.carKey, isCurrent,
// 在线时缺失的图片按需补齐,避免渲染出原始 URL。
allowDownload: source.online !== false,
onMetrics: metrics => { if (isCurrent()) console.log('setPageData images', { materialId, carKey: source.carKey, ...metrics }) } onMetrics: metrics => { if (isCurrent()) console.log('setPageData images', { materialId, carKey: source.carKey, ...metrics }) }
}) })
if (!isCurrent() || !display) return if (!isCurrent() || !display) return
...@@ -673,11 +692,12 @@ export default { ...@@ -673,11 +692,12 @@ export default {
}, },
async loadOfflineTools (visible) { async loadOfflineTools (visible) {
const source = this._offlineSource const source = this._offlineSource
if (!visible || !source || this.sourceOnline || !this.id) return if (!visible || !source || !this.id) return
const isCurrent = () => this._offlineSource === source && !this.sourceOnline && !!this.id && const isCurrent = () => this._offlineSource === source && !!this.id &&
!this._sourceDisposed && source.requestId === this._sourceRequestId && this.$refs.toolRef?.show === false !this._sourceDisposed && source.requestId === this._sourceRequestId && this.$refs.toolRef?.show === false
const display = await materialCache.hydrateSourceImages(source.key, source.base, { const display = await materialCache.hydrateSourceImages(source.key, source.base, {
moduleIds: [], toolIds: source.base.toolList.map(item => item.id), carKey: source.carKey, isCurrent moduleIds: [], toolIds: source.base.toolList.map(item => item.id), carKey: source.carKey, isCurrent,
allowDownload: source.online !== false
}) })
if (display && isCurrent()) this.applyOfflineTools(display.toolList) if (display && isCurrent()) this.applyOfflineTools(display.toolList)
}, },
...@@ -689,7 +709,8 @@ export default { ...@@ -689,7 +709,8 @@ export default {
this.receptionTrackLeave() this.receptionTrackLeave()
// 使用 Object.freeze 冻结大对象,提升性能 // 使用 Object.freeze 冻结大对象,提升性能
this.moduleList = Object.freeze(moduleList) this.moduleList = Object.freeze(moduleList)
this.pageToolList = Object.freeze(this.sourceOnline ? toolList : toolList.map(item => ({ // 统一走 base64:工具图标先置空,等 hydrate 补齐后再展示,避免直接消耗在线地址。
this.pageToolList = Object.freeze(toolList.map(item => ({
...item, shortTitleUrl: /^https?:\/\//i.test(item.shortTitleUrl || '') ? '' : item.shortTitleUrl ...item, shortTitleUrl: /^https?:\/\//i.test(item.shortTitleUrl || '') ? '' : item.shortTitleUrl
}))) })))
this.useCarConfig = true this.useCarConfig = true
...@@ -718,17 +739,13 @@ export default { ...@@ -718,17 +739,13 @@ export default {
// 即使 loadedIndexes 里有,如果距离太远,也要销毁内容以释放内存 // 即使 loadedIndexes 里有,如果距离太远,也要销毁内容以释放内存
shouldRenderContent(index) { shouldRenderContent(index) {
const current = this.currentIndex const current = this.currentIndex
// 配置素材统一走 base64:只挂载已按 key 补齐的当前素材,其他素材被选中时再读取。
if (this.useCarConfig) return index === current && String(this.offlineReadyId) === String(this.id)
// 配置未就绪时展示的是兜底素材列表,不依赖图片缓存,保留当前页及其左右邻居。
const len = this.renderList.length const len = this.renderList.length
// 离线仅挂载已按 key 补齐的当前素材,其他素材被选中时再读取。
if (!this.sourceOnline) return index === current && String(this.offlineReadyId) === String(this.id)
// 基础范围:当前页的前后一页
if (Math.abs(index - current) <= 1) return true if (Math.abs(index - current) <= 1) return true
// 循环边界处理
if (current === 0 && index === len - 1) return true if (current === 0 && index === len - 1) return true
if (current === len - 1 && index === 0) return true if (current === len - 1 && index === 0) return true
return false return false
}, },
// 判断组件是否应该实际渲染(配合 v-if) // 判断组件是否应该实际渲染(配合 v-if)
......
...@@ -3,8 +3,13 @@ const md5 = require('../lib/md5.js') ...@@ -3,8 +3,13 @@ const md5 = require('../lib/md5.js')
// 基础缓存换版本,在线首次升级也不会读到旧缓存中的整包 base64。 // 基础缓存换版本,在线首次升级也不会读到旧缓存中的整包 base64。
const SOURCE_PREFIX = 'source_v2_' const SOURCE_PREFIX = 'source_v2_'
const IMAGE_PREFIX = 'material_base64_' const IMAGE_PREFIX = 'material_base64_'
const URL_PREFIX = 'material_url_'
const imageGenerations = new Map() const imageGenerations = new Map()
const writeQueues = new Map() const writeQueues = new Map()
// 同一张图片(素材 ID + 位置 + URL 指纹)只转换一次,首屏补齐与后台批量缓存共用同一个 Promise。
const pendingConversions = new Map()
// 本次运行已转换成功的位置记录,避免后台任务重复下载刚被首屏补齐的图片。
const convertedSlots = new Map()
const downloadQueue = [] const downloadQueue = []
let activeDownloads = 0 let activeDownloads = 0
const imageReadQueue = [] const imageReadQueue = []
...@@ -32,6 +37,11 @@ function imageKey(sourceKey, id, slotKey) { ...@@ -32,6 +37,11 @@ function imageKey(sourceKey, id, slotKey) {
return `${IMAGE_PREFIX}${sourceKey.slice(SOURCE_PREFIX.length)}_${id}_${slotKey}` return `${IMAGE_PREFIX}${sourceKey.slice(SOURCE_PREFIX.length)}_${id}_${slotKey}`
} }
// 位置 => 该位置上次成功转换时使用的 URL,用于判断接口地址是否变化。
function urlKey(sourceKey) {
return `${URL_PREFIX}${sourceKey.slice(SOURCE_PREFIX.length)}`
}
function getNetworkStatus() { function getNetworkStatus() {
return new Promise(resolve => { return new Promise(resolve => {
uni.getNetworkType({ uni.getNetworkType({
...@@ -142,7 +152,7 @@ function readImage(key, isCurrent, metrics) { ...@@ -142,7 +152,7 @@ function readImage(key, isCurrent, metrics) {
// 同一个 key 的异步写入串行执行,避免较早发起的写入较晚完成。 // 同一个 key 的异步写入串行执行,避免较早发起的写入较晚完成。
function write(key, data, shouldWrite = () => true) { function write(key, data, shouldWrite = () => true) {
const previous = writeQueues.get(key) || Promise.resolve() const previous = writeQueues.get(key) || Promise.resolve()
const pending = previous.catch(() => {}).then(() => { const pending = previous.catch(() => { }).then(() => {
if (!shouldWrite()) return if (!shouldWrite()) return
return new Promise((resolve, reject) => uni.setStorage({ return new Promise((resolve, reject) => uni.setStorage({
key, data, key, data,
...@@ -186,7 +196,12 @@ function imageSlots(item, kind, options = {}) { ...@@ -186,7 +196,12 @@ function imageSlots(item, kind, options = {}) {
) )
function add(path, value) { function add(path, value) {
if (Array.isArray(options.fields) && (path.length !== 1 || !options.fields.includes(path[0]))) return if (Array.isArray(options.fields) && (path.length !== 1 || !options.fields.includes(path[0]))) return
if (isRemote(value)) slots.push({ path, url: value, key: md5(JSON.stringify([kind, path, value])) }) if (isRemote(value)) slots.push({
path, url: value,
// key 含 URL 指纹,用于定位图片;name 只标识位置,用于比对接口 URL 与缓存 URL。
key: md5(JSON.stringify([kind, path, value])),
name: md5(JSON.stringify([kind, path]))
})
} }
function fields(value, path, names) { function fields(value, path, names) {
if (!value || typeof value !== 'object') return if (!value || typeof value !== 'object') return
...@@ -195,18 +210,27 @@ function imageSlots(item, kind, options = {}) { ...@@ -195,18 +210,27 @@ function imageSlots(item, kind, options = {}) {
fields(item, [], ['thumbnail', 'homeEntranceCover', 'contentPicUrl', 'shortTitleUrl', 'carIcon', 'productPoster']) fields(item, [], ['thumbnail', 'homeEntranceCover', 'contentPicUrl', 'shortTitleUrl', 'carIcon', 'productPoster'])
if (Array.isArray(options.fields)) return slots if (Array.isArray(options.fields)) return slots
const views = item.receptionSourceDetailList const views = item.receptionSourceDetailList
// ThreeGuarantees 按 tab 位置取图(views[activeIndex] / views[tabIndex]),
// 这个位置无法由车系推断,必须枚举全部键;其余组件只取当前车系或 detailUrl / bgUrl。
const restrictViewKeys = hasCarKey &&
!/^threeguarantee/i.test(String(item.componentName || '').replace(/[^a-z]/gi, ''))
if (Array.isArray(views)) { if (Array.isArray(views)) {
views.forEach((view, index) => fields(view, ['receptionSourceDetailList', index], ['detailUrl', 'bgUrl'])) views.forEach((view, index) => {
const path = ['receptionSourceDetailList', index]
// 位置直接存图片地址时同样要缓存,否则组件读到的仍是在线地址。
if (isRemote(view)) add(path, view)
else fields(view, path, ['detailUrl', 'bgUrl'])
})
} else if (views && typeof views === 'object') { } else if (views && typeof views === 'object') {
const keys = hasCarKey ? [...new Set(['detailUrl', 'bgUrl', String(options.carKey)])] : Object.keys(views) const keys = restrictViewKeys ? [...new Set(['detailUrl', 'bgUrl', String(options.carKey)])] : Object.keys(views)
keys.forEach(key => add(['receptionSourceDetailList', key], views[key])) keys.forEach(key => add(['receptionSourceDetailList', key], views[key]))
} else add(['receptionSourceDetailList'], views) } else add(['receptionSourceDetailList'], views)
;['screenList', 'materialDetailList'].forEach(name => { ;['screenList', 'materialDetailList'].forEach(name => {
if (Array.isArray(item[name])) item[name].forEach((entry, index) => { if (Array.isArray(item[name])) item[name].forEach((entry, index) => {
if (name === 'materialDetailList' && !matchesCar(entry)) return if (name === 'materialDetailList' && !matchesCar(entry)) return
fields(entry, [name, index], ['url', 'detailUrl', 'bgUrl', 'contentPicUrl', 'homeEntranceCover', 'thumbnail']) fields(entry, [name, index], ['url', 'detailUrl', 'bgUrl', 'contentPicUrl', 'homeEntranceCover', 'thumbnail'])
})
}) })
})
function caseImages(value, path) { function caseImages(value, path) {
if (!value || typeof value !== 'object') return if (!value || typeof value !== 'object') return
Object.keys(value).forEach(key => { Object.keys(value).forEach(key => {
...@@ -220,50 +244,74 @@ function imageSlots(item, kind, options = {}) { ...@@ -220,50 +244,74 @@ function imageSlots(item, kind, options = {}) {
function materialGroups(data) { function materialGroups(data) {
const groups = new Map() const groups = new Map()
;['moduleList', 'toolList'].forEach(kind => { ;['moduleList', 'toolList'].forEach(kind => {
;(data[kind] || []).forEach(item => { ; (data[kind] || []).forEach(item => {
if (!item || !hasId(item.id)) return if (!item || !hasId(item.id)) return
const id = String(item.id) const id = String(item.id)
if (!groups.has(id)) groups.set(id, []) if (!groups.has(id)) groups.set(id, [])
groups.get(id).push({ item, slots: imageSlots(item, kind) }) groups.get(id).push({ item, slots: imageSlots(item, kind) })
})
}) })
})
return groups return groups
} }
// 诊断用:枚举补齐后仍是在线图片地址的字段路径,确认还有哪些图片位置没被缓存覆盖。
function remoteImagePaths(items) {
const found = []
const walk = (value, path) => {
if (typeof value === 'string') {
if (/(^https?:\/\/).+\.(png|jpe?g|webp|gif|bmp|svg|avif)([?#]|$)/i.test(value)) found.push(path.join('.'))
return
}
if (!value || typeof value !== 'object') return
Object.keys(value).forEach(key => walk(value[key], [...path, key]))
}
items.forEach((item, index) => walk(item, [index]))
return [...new Set(found)]
}
// 直接根据当前素材 ID、图片位置和 URL 算出 key,不枚举 storage 或读取其他素材图片。 // 直接根据当前素材 ID、图片位置和 URL 算出 key,不枚举 storage 或读取其他素材图片。
async function hydrateSourceImages(key, base, options = {}) { async function hydrateSourceImages(key, base, options = {}) {
const isCurrent = options.isCurrent || (() => true) const isCurrent = options.isCurrent || (() => true)
const start = Date.now() const start = Date.now()
const metrics = { storageReads: 0, memoryHits: 0, sharedReads: 0, imageHits: 0, missingImages: 0, requestedImages: 0, bytes: 0 } const metrics = { storageReads: 0, memoryHits: 0, sharedReads: 0, imageHits: 0, missingImages: 0, downloadedImages: 0, requestedImages: 0, bytes: 0, leftoverUrls: [] }
if (!isCurrent() || !isSource(base)) return null if (!isCurrent() || !isSource(base)) return null
const display = { ...base } const display = { ...base }
const hydrated = []
const pending = [] const pending = []
;['moduleList', 'toolList'].forEach(kind => { ;['moduleList', 'toolList'].forEach(kind => {
const ids = options[kind === 'moduleList' ? 'moduleIds' : 'toolIds'] const ids = options[kind === 'moduleList' ? 'moduleIds' : 'toolIds']
const selected = Array.isArray(ids) ? new Set(ids.map(String)) : null const selected = Array.isArray(ids) ? new Set(ids.map(String)) : null
display[kind] = base[kind].map(item => { display[kind] = base[kind].map(item => {
if (!item || !hasId(item.id) || (selected && !selected.has(String(item.id)))) return item if (!item || !hasId(item.id) || (selected && !selected.has(String(item.id)))) return item
const slots = imageSlots(item, kind, options) const slots = imageSlots(item, kind, options)
if (!slots.length) return item if (!slots.length) return item
// 只复制本次要展示的素材,其他条目保留轻量基础数据。 // 只复制本次要展示的素材,其他条目保留轻量基础数据。
const clone = JSON.parse(JSON.stringify(item)) const clone = JSON.parse(JSON.stringify(item))
slots.forEach(slot => { hydrated.push(clone)
metrics.requestedImages++ slots.forEach(slot => {
pending.push(readImage(imageKey(key, item.id, slot.key), isCurrent, metrics).then(image => { metrics.requestedImages++
if (!isCurrent()) return pending.push(readImage(imageKey(key, item.id, slot.key), isCurrent, metrics).then(async image => {
if (!image) { metrics.missingImages++; return } if (!isCurrent()) return
metrics.imageHits++ // 首屏可能早于后台图片转换完成:缺失的位置按需补齐,保证渲染的是 base64 而不是在线 URL。
metrics.bytes += image.length * 2 if (!image && options.allowDownload) {
let target = clone metrics.downloadedImages++
slot.path.slice(0, -1).forEach(part => { target = target[part] }) image = await convertSlotImage(key, item.id, slot)
target[slot.path[slot.path.length - 1]] = image if (!isCurrent()) return
})) }
if (!image) { metrics.missingImages++; return }
metrics.imageHits++
metrics.bytes += image.length * 2
let target = clone
slot.path.slice(0, -1).forEach(part => { target = target[part] })
target[slot.path[slot.path.length - 1]] = image
}))
})
return clone
}) })
return clone
}) })
})
await Promise.all(pending) await Promise.all(pending)
metrics.leftoverUrls = remoteImagePaths(hydrated).slice(0, 10)
metrics.durationMs = Date.now() - start metrics.durationMs = Date.now() - start
metrics.cancelled = !isCurrent() metrics.cancelled = !isCurrent()
if (typeof options.onMetrics === 'function') options.onMetrics(metrics) if (typeof options.onMetrics === 'function') options.onMetrics(metrics)
...@@ -301,6 +349,10 @@ async function readSourceCache(key, online = true, options = {}) { ...@@ -301,6 +349,10 @@ async function readSourceCache(key, online = true, options = {}) {
function downloadImage(url) { function downloadImage(url) {
return new Promise(resolve => { return new Promise(resolve => {
const fail = reason => {
console.warn('素材图片下载失败', { url, reason })
return ''
}
uni.request({ uni.request({
url, method: 'GET', responseType: 'arraybuffer', timeout: 15000, url, method: 'GET', responseType: 'arraybuffer', timeout: 15000,
success: res => { success: res => {
...@@ -310,10 +362,12 @@ function downloadImage(url) { ...@@ -310,10 +362,12 @@ function downloadImage(url) {
const extension = url.split(/[?#]/)[0].match(/\.(png|jpe?g|webp|gif|bmp|svg|avif)$/i)?.[1].toLowerCase() const extension = url.split(/[?#]/)[0].match(/\.(png|jpe?g|webp|gif|bmp|svg|avif)$/i)?.[1].toLowerCase()
const fallbackType = extension ? `image/${({ jpg: 'jpeg', svg: 'svg+xml' })[extension] || extension}` : '' const fallbackType = extension ? `image/${({ jpg: 'jpeg', svg: 'svg+xml' })[extension] || extension}` : ''
const mime = declaredType || fallbackType const mime = declaredType || fallbackType
if (res.statusCode < 200 || res.statusCode >= 300 || !/^image\/[\w.+-]+$/.test(mime) || !res.data?.byteLength) return resolve('') if (res.statusCode < 200 || res.statusCode >= 300) return resolve(fail(`status:${res.statusCode}`))
try { resolve(`data:${mime};base64,${uni.arrayBufferToBase64(res.data)}`) } catch (error) { resolve('') } if (!/^image\/[\w.+-]+$/.test(mime)) return resolve(fail(`type:${mime || 'unknown'}`))
if (!res.data?.byteLength) return resolve(fail('empty'))
try { resolve(`data:${mime};base64,${uni.arrayBufferToBase64(res.data)}`) } catch (error) { resolve(fail('base64')) }
}, },
fail: () => resolve('') fail: error => resolve(fail(error?.errMsg || 'request'))
}) })
}) })
} }
...@@ -337,25 +391,79 @@ function enqueueImage(url, isCurrent) { ...@@ -337,25 +391,79 @@ function enqueueImage(url, isCurrent) {
}) })
} }
// 下载并转换单个槽位,成功后写入 storage,并把「位置 => URL」记录到本次运行的映射里。
// key 由素材 ID、图片位置和 URL 指纹共同决定,同一次下载的调用方共享结果,不会重复请求。
function convertSlotImage(key, id, slot) {
const target = imageKey(key, id, slot.key)
const pending = pendingConversions.get(target)
if (pending) return pending
const task = enqueueImage(slot.url, () => true).then(async image => {
if (!isImage(image)) {
console.warn('素材图片转换失败', slot.url)
return ''
}
let persisted = true
try {
await write(target, image, () => true)
} catch (error) {
// 本地存储写失败(配额或单键超限)不影响本次渲染,base64 仍需留在内存里供读取。
persisted = false
console.warn('素材图片写入本地缓存失败,本次仅存内存', target)
}
if (persisted) {
let slots = convertedSlots.get(key)
if (!slots) {
slots = new Map()
convertedSlots.set(key, slots)
}
slots.set(`${id}_${slot.name}`, slot.url)
}
rememberImage(target, image)
return image
}).catch(() => '')
pendingConversions.set(target, task)
const cleanup = () => { if (pendingConversions.get(target) === task) pendingConversions.delete(target) }
task.then(cleanup, cleanup)
return task
}
async function cacheMaterialImages(key, base) { async function cacheMaterialImages(key, base) {
const generation = (imageGenerations.get(key) || 0) + 1 const generation = (imageGenerations.get(key) || 0) + 1
imageGenerations.set(key, generation) imageGenerations.set(key, generation)
const isCurrent = () => imageGenerations.get(key) === generation const isCurrent = () => imageGenerations.get(key) === generation
// 只读取位置与 URL 的轻量记录,不读回图片 base64。
const cachedUrls = await read(urlKey(key))
const urls = cachedUrls && typeof cachedUrls === 'object' ? { ...cachedUrls } : {}
let urlsChanged = false
const results = await Promise.all([...materialGroups(base)].flatMap(([id, entries]) => const results = await Promise.all([...materialGroups(base)].flatMap(([id, entries]) =>
entries.flatMap(entry => entry.slots).map(async slot => { entries.flatMap(entry => entry.slots).map(async slot => {
const image = await enqueueImage(slot.url, isCurrent) // 素材 ID + 位置,才是本次要比对 URL 的槽位。
if (!isCurrent() || !isImage(image)) return false const slotName = `${id}_${slot.name}`
try { // 同一素材位置上接口 URL 与缓存 URL 一致时,图片已转换过,跳过下载和 base64 转换。
// 每张图独立写入,部分下载失败不会覆盖其他已成功缓存的图片。 const recorded = urls[slotName] === slot.url
// 在线不需要读回旧 base64 来合并记录。 if (recorded || convertedSlots.get(key)?.get(slotName) === slot.url) {
await write(imageKey(key, id, slot.key), image, isCurrent) // 首屏补齐过的位置补记到 storage,下次冷启动同样能跳过。
return isCurrent() if (!recorded) {
} catch (error) { urls[slotName] = slot.url
console.warn('素材图片缓存写入失败', id) urlsChanged = true
return false }
return true
} }
const image = await convertSlotImage(key, id, slot)
if (!isCurrent() || !image) return false
// 转换成功后才记录 URL,下载或写入失败时下次仍会重试。
urls[slotName] = slot.url
urlsChanged = true
return true
}) })
)) ))
if (urlsChanged && isCurrent()) {
try {
await write(urlKey(key), urls, isCurrent)
} catch (error) {
console.warn('素材图片 URL 记录写入失败', key)
}
}
if (isCurrent() && results.every(Boolean)) { if (isCurrent() && results.every(Boolean)) {
// 图片全部落盘后才能结束迁移,基础缓存写入成功不代表离线图片已就绪。 // 图片全部落盘后才能结束迁移,基础缓存写入成功不代表离线图片已就绪。
await new Promise(resolve => uni.removeStorage({ await new Promise(resolve => uni.removeStorage({
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!