diff --git a/pages/home/index.ts b/pages/home/index.ts index 2c991ba..80d6c37 100644 --- a/pages/home/index.ts +++ b/pages/home/index.ts @@ -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())}` +} diff --git a/utils/token.ts b/utils/token.ts index 604fe84..6c99ecb 100644 --- a/utils/token.ts +++ b/utils/token.ts @@ -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(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 + } +}