feat(usage): 首页今日使用时长本地缓存
进入首页先渲染缓存,网络返回后覆盖并回写;缓存按 SN+日期绑定自动失效。
This commit is contained in:
1 parent
4540c04d6c
commit
6eb7dcbdd6
2 files changed
+39
-2
No files matched your search
+18
-2
@@ -16,7 +16,7 @@ import {
|
||||
toggleDeveloperMode
|
||||
} from '../../utils/api'
|
||||
import { ensureLogin } from '../../utils/auth'
|
||||
import { getDeviceSn, saveDeviceSn } from '../../utils/token'
|
||||
import { getDeviceSn, saveDeviceSn, saveUsageTodayCache, getUsageTodayCache } from '../../utils/token'
|
||||
import { toGcj02 } from '../../utils/coord'
|
||||
import { showTodo } from '../../utils/todo'
|
||||
import { syncTabBar } from '../../utils/tab-bar'
|
||||
@@ -312,8 +312,17 @@ Page({
|
||||
})
|
||||
},
|
||||
|
||||
/** 今日使用时长:总时长 + 应用占比(取 Top3) */
|
||||
/** 今日使用时长:总时长 + 应用占比(取 Top3)。先渲染本地缓存,再拉网络覆盖。 */
|
||||
async loadUsage(sn: string) {
|
||||
const today = dayKey(new Date())
|
||||
const cached = getUsageTodayCache<{ total: number; items: UsageItem[] }>(sn, today)
|
||||
if (cached) {
|
||||
this.setData({
|
||||
usageTotal: formatUsageDuration(cached.total),
|
||||
usageRingPercent: cached.items.length ? cached.items[0].percent : 0,
|
||||
usageItems: cached.items
|
||||
})
|
||||
}
|
||||
try {
|
||||
const day = await getUsageDay(sn)
|
||||
const total = Number(day.totalMs) || 0
|
||||
@@ -329,6 +338,7 @@ Page({
|
||||
usageRingPercent: items.length ? items[0].percent : 0,
|
||||
usageItems: items
|
||||
})
|
||||
saveUsageTodayCache(sn, today, { total, items })
|
||||
} catch {
|
||||
this.setData({ usageTotal: '—', usageRingPercent: 0, usageItems: [] })
|
||||
}
|
||||
@@ -541,3 +551,9 @@ function formatUsageDuration(ms: number): string {
|
||||
if (seconds >= 60) return `${Math.floor(seconds / 60)}m`
|
||||
return `${seconds}s`
|
||||
}
|
||||
|
||||
/** 本地日期键 yyyy-MM-dd */
|
||||
function dayKey(time: Date): string {
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${time.getFullYear()}-${pad(time.getMonth() + 1)}-${pad(time.getDate())}`
|
||||
}
|
||||
@@ -51,3 +51,24 @@ export function getDeviceSn(): string {
|
||||
export function saveDeviceSn(sn: string): void {
|
||||
wx.setStorageSync(KEY_DEVICE, sn)
|
||||
}
|
||||
|
||||
const KEY_USAGE_TODAY = 'ttstd_usage_today'
|
||||
|
||||
/** 首页今日使用时长缓存(sn+日期 绑定,跨天/换设备自动失效) */
|
||||
export function saveUsageTodayCache(sn: string, date: string, value: unknown): void {
|
||||
try {
|
||||
wx.setStorageSync(KEY_USAGE_TODAY, { sn, date, value })
|
||||
} catch {
|
||||
// 存储失败忽略,不影响主流程
|
||||
}
|
||||
}
|
||||
|
||||
export function getUsageTodayCache<T>(sn: string, date: string): T | null {
|
||||
try {
|
||||
const cached = wx.getStorageSync<{ sn?: string; date?: string; value?: T }>(KEY_USAGE_TODAY)
|
||||
if (!cached || cached.sn !== sn || cached.date !== date) return null
|
||||
return cached.value ?? null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user