feat(离线): 界面离线可看 —— GET 响应本地缓存 + 同步凭证持久化 (离线不清库) + 左上角离线徽标 (与 Windows 外壳分支同源)

This commit is contained in:
jif2.zhang
2026-10-26 16:05:59 +08:00
parent 9f16db4286
commit f34c8c3bae
5 changed files with 199 additions and 17 deletions
+135 -12
View File
@@ -1,13 +1,121 @@
// API 调用封装: 自动带 JWT、401 自动清 token、抛统一错误
// 0.2.1 离线支持:
// - GET 请求成功后把响应写入本地缓存 (localStorage), 离线/网络失败时回退缓存 (界面仍有数据)
// - 写请求 (POST/PUT/DELETE) 仍要求在线 (任务模块的离线写走 PowerSync 上传队列)
// - 统一在线/离线状态订阅, 供 UI 显示离线标识
const TOKEN_KEY = 'iboard_token'
const REMEMBER_KEY = 'iboard_remember'
const UID_KEY = 'iboard_uid'
// API 基址:
// - 默认相对路径 `/api` (web dev: Vite 代理; web prod: 同源 Express 一起托管)
// - 打包 Android 时设 VITE_API_BASE=http://bh.vps.honor3.com:3001 走外网后端
// - 打包 Android / Windows 外壳时设 VITE_API_BASE=http://bh.vps.honor3.com:3001 走外网后端
const API_BASE = (import.meta.env.VITE_API_BASE || '').replace(/\/+$/, '')
const API_PREFIX = API_BASE ? API_BASE + '/api' : '/api'
// ---------- 在线/离线状态 (网络事件 + 请求结果联动) ----------
let offline = typeof navigator !== 'undefined' ? navigator.onLine === false : false
const offlineListeners = new Set()
export function isOffline() {
return offline
}
function setOffline(next) {
if (offline === next) return
offline = next
offlineListeners.forEach((cb) => {
try { cb(next) } catch { /* ignore */ }
})
}
if (typeof window !== 'undefined') {
window.addEventListener('online', () => setOffline(false))
window.addEventListener('offline', () => setOffline(true))
}
/** 订阅在线/离线变化, 返回取消函数 */
export function subscribeOffline(cb) {
offlineListeners.add(cb)
return () => offlineListeners.delete(cb)
}
// ---------- GET 响应本地缓存 ----------
// 目的: 任何界面只要成功访问过一次, 离线时都能展示上次的数据
const CACHE_PREFIX = 'iboard_cache:'
const CACHE_TOTAL_LIMIT = 3 * 1024 * 1024 // 约 3MB (localStorage 通常 5MB)
const CACHE_ENTRY_LIMIT = 512 * 1024 // 单条上限, 超大响应不缓存
function cacheKey(path) {
return CACHE_PREFIX + path
}
function readCache(path) {
try {
const raw = localStorage.getItem(cacheKey(path))
if (!raw) return null
const parsed = JSON.parse(raw)
if (!parsed || typeof parsed !== 'object' || !('data' in parsed)) return null
return parsed
} catch {
return null
}
}
function cacheSizeUsed() {
let total = 0
try {
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i)
if (k && k.startsWith(CACHE_PREFIX)) total += (localStorage.getItem(k) || '').length
}
} catch { /* ignore */ }
return total
}
function evictOldest(needBytes) {
try {
const entries = []
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i)
if (!k || !k.startsWith(CACHE_PREFIX)) continue
let ts = 0
try { ts = JSON.parse(localStorage.getItem(k) || '{}').ts || 0 } catch { /* ignore */ }
entries.push({ k, ts })
}
entries.sort((a, b) => a.ts - b.ts)
let used = cacheSizeUsed()
for (const e of entries) {
if (used + needBytes <= CACHE_TOTAL_LIMIT) break
used -= (localStorage.getItem(e.k) || '').length
localStorage.removeItem(e.k)
}
} catch { /* ignore */ }
}
function writeCache(path, data) {
try {
const payload = JSON.stringify({ ts: Date.now(), data })
if (payload.length > CACHE_ENTRY_LIMIT) return // 过大不缓存
evictOldest(payload.length)
localStorage.setItem(cacheKey(path), payload)
} catch {
// 配额满等异常: 静默失败, 不影响主流程
}
}
/** 清空所有 GET 缓存 (退出登录时调用) */
export function clearApiCache() {
try {
const keys = []
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i)
if (k && k.startsWith(CACHE_PREFIX)) keys.push(k)
}
keys.forEach((k) => localStorage.removeItem(k))
} catch { /* ignore */ }
}
export function getToken() {
return localStorage.getItem(TOKEN_KEY) || ''
}
@@ -27,7 +135,6 @@ export function setRememberFlag(v) {
}
// 当前用户 id (0.2.1 离线写入需要 ownerId/creatorId, 本地库无法即时从服务端获取)
const UID_KEY = 'iboard_uid'
export function getCurrentUserId() {
return localStorage.getItem(UID_KEY) || ''
}
@@ -42,15 +149,30 @@ export function getApiBase() {
export async function api(path, { method = 'GET', body, headers = {} } = {}) {
const token = getToken()
const res = await fetch(API_PREFIX + path, {
method,
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: 'Bearer ' + token } : {}),
...headers,
},
body: body ? JSON.stringify(body) : undefined,
})
const isRead = method === 'GET'
let res
try {
res = await fetch(API_PREFIX + path, {
method,
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: 'Bearer ' + token } : {}),
...headers,
},
body: body ? JSON.stringify(body) : undefined,
})
} catch {
// 网络层失败: 离线 / 服务不可达
setOffline(true)
if (isRead) {
const cached = readCache(path)
if (cached) return cached.data
throw new Error('当前离线,且该界面尚无本地缓存')
}
throw new Error('当前离线,修改操作需要联网后重试')
}
setOffline(false)
if (res.status === 401) {
setToken('')
const data = await res.json().catch(() => ({}))
@@ -59,5 +181,6 @@ export async function api(path, { method = 'GET', body, headers = {} } = {}) {
}
const data = await res.json().catch(() => ({}))
if (!res.ok) throw new Error(data.error || '请求失败 (' + res.status + ')')
if (isRead) writeCache(path, data)
return data
}
}