feat(离线): 界面离线可看 —— GET 响应本地缓存 + 同步凭证持久化 (离线不清库) + 左上角离线徽标 (与 Windows 外壳分支同源)
This commit is contained in:
+126
-3
@@ -1,13 +1,121 @@
|
|||||||
// API 调用封装: 自动带 JWT、401 自动清 token、抛统一错误
|
// API 调用封装: 自动带 JWT、401 自动清 token、抛统一错误
|
||||||
|
// 0.2.1 离线支持:
|
||||||
|
// - GET 请求成功后把响应写入本地缓存 (localStorage), 离线/网络失败时回退缓存 (界面仍有数据)
|
||||||
|
// - 写请求 (POST/PUT/DELETE) 仍要求在线 (任务模块的离线写走 PowerSync 上传队列)
|
||||||
|
// - 统一在线/离线状态订阅, 供 UI 显示离线标识
|
||||||
const TOKEN_KEY = 'iboard_token'
|
const TOKEN_KEY = 'iboard_token'
|
||||||
const REMEMBER_KEY = 'iboard_remember'
|
const REMEMBER_KEY = 'iboard_remember'
|
||||||
|
const UID_KEY = 'iboard_uid'
|
||||||
|
|
||||||
// API 基址:
|
// API 基址:
|
||||||
// - 默认相对路径 `/api` (web dev: Vite 代理; web prod: 同源 Express 一起托管)
|
// - 默认相对路径 `/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_BASE = (import.meta.env.VITE_API_BASE || '').replace(/\/+$/, '')
|
||||||
const API_PREFIX = API_BASE ? API_BASE + '/api' : '/api'
|
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() {
|
export function getToken() {
|
||||||
return localStorage.getItem(TOKEN_KEY) || ''
|
return localStorage.getItem(TOKEN_KEY) || ''
|
||||||
}
|
}
|
||||||
@@ -27,7 +135,6 @@ export function setRememberFlag(v) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 当前用户 id (0.2.1 离线写入需要 ownerId/creatorId, 本地库无法即时从服务端获取)
|
// 当前用户 id (0.2.1 离线写入需要 ownerId/creatorId, 本地库无法即时从服务端获取)
|
||||||
const UID_KEY = 'iboard_uid'
|
|
||||||
export function getCurrentUserId() {
|
export function getCurrentUserId() {
|
||||||
return localStorage.getItem(UID_KEY) || ''
|
return localStorage.getItem(UID_KEY) || ''
|
||||||
}
|
}
|
||||||
@@ -42,7 +149,10 @@ export function getApiBase() {
|
|||||||
|
|
||||||
export async function api(path, { method = 'GET', body, headers = {} } = {}) {
|
export async function api(path, { method = 'GET', body, headers = {} } = {}) {
|
||||||
const token = getToken()
|
const token = getToken()
|
||||||
const res = await fetch(API_PREFIX + path, {
|
const isRead = method === 'GET'
|
||||||
|
let res
|
||||||
|
try {
|
||||||
|
res = await fetch(API_PREFIX + path, {
|
||||||
method,
|
method,
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
@@ -51,6 +161,18 @@ export async function api(path, { method = 'GET', body, headers = {} } = {}) {
|
|||||||
},
|
},
|
||||||
body: body ? JSON.stringify(body) : undefined,
|
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) {
|
if (res.status === 401) {
|
||||||
setToken('')
|
setToken('')
|
||||||
const data = await res.json().catch(() => ({}))
|
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(() => ({}))
|
const data = await res.json().catch(() => ({}))
|
||||||
if (!res.ok) throw new Error(data.error || '请求失败 (' + res.status + ')')
|
if (!res.ok) throw new Error(data.error || '请求失败 (' + res.status + ')')
|
||||||
|
if (isRead) writeCache(path, data)
|
||||||
return data
|
return data
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { createContext, useContext, useEffect, useState } from 'react'
|
import { createContext, useContext, useEffect, useState } from 'react'
|
||||||
import { api, getToken, setToken, setRememberFlag, setCurrentUserId } from '../api/client.js'
|
import { api, getToken, setToken, setRememberFlag, setCurrentUserId, clearApiCache } from '../api/client.js'
|
||||||
import { disconnectAndClearPowersync } from '../lib/powersync/db.js'
|
import { disconnectAndClearPowersync } from '../lib/powersync/db.js'
|
||||||
|
|
||||||
const AuthContext = createContext(null)
|
const AuthContext = createContext(null)
|
||||||
@@ -51,6 +51,8 @@ export function AuthProvider({ children }) {
|
|||||||
setRememberFlag(false)
|
setRememberFlag(false)
|
||||||
setUser(null)
|
setUser(null)
|
||||||
setCurrentUserId('')
|
setCurrentUserId('')
|
||||||
|
try { clearApiCache() } catch { /* ignore */ }
|
||||||
|
try { localStorage.removeItem('iboard_ps_cred') } catch { /* ignore */ }
|
||||||
// 断开同步并清空本地 SQLite (0.2.1 离线编辑)
|
// 断开同步并清空本地 SQLite (0.2.1 离线编辑)
|
||||||
try { await disconnectAndClearPowersync() } catch { /* ignore */ }
|
try { await disconnectAndClearPowersync() } catch { /* ignore */ }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { Outlet, useLocation } from 'react-router-dom'
|
import { Outlet, useLocation } from 'react-router-dom'
|
||||||
import BottomNav from '../components/BottomNav.jsx'
|
import BottomNav from '../components/BottomNav.jsx'
|
||||||
|
import { isOffline, subscribeOffline } from '../api/client.js'
|
||||||
|
|
||||||
// 移动端应用外壳
|
// 移动端应用外壳
|
||||||
// - 顶部安全区: 用 --safe-top 撑开 (由 main.jsx 的 calibrateSafeTop 实测校准)
|
// - 顶部安全区: 用 --safe-top 撑开 (由 main.jsx 的 calibrateSafeTop 实测校准)
|
||||||
// - 中间 <main>: flex:1 可滚动主区
|
// - 中间 <main>: flex:1 可滚动主区
|
||||||
// - 底部 TabBar: antd-mobile TabBar 自带底部安全区
|
// - 底部 TabBar: antd-mobile TabBar 自带底部安全区
|
||||||
|
// - 左上角离线标识 (0.2.1): 离线或服务不可达时显示, 请求恢复后自动隐藏
|
||||||
//
|
//
|
||||||
// 注意: 这里不再用 antd-mobile 的 <SafeArea position="top" />.
|
// 注意: 这里不再用 antd-mobile 的 <SafeArea position="top" />.
|
||||||
// 它只是一个空 div, 高度完全依赖 env(safe-area-inset-top); 而 Android WebView
|
// 它只是一个空 div, 高度完全依赖 env(safe-area-inset-top); 而 Android WebView
|
||||||
@@ -22,9 +24,19 @@ export default function MobileShell() {
|
|||||||
return () => clearTimeout(t)
|
return () => clearTimeout(t)
|
||||||
}, [location.pathname])
|
}, [location.pathname])
|
||||||
|
|
||||||
|
// 离线状态 (窗口左上角标识)
|
||||||
|
const [offline, setOfflineState] = useState(isOffline())
|
||||||
|
useEffect(() => subscribeOffline(setOfflineState), [])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="app-root">
|
<div className="app-root">
|
||||||
<div className="app-safe-top" aria-hidden="true" />
|
<div className="app-safe-top" aria-hidden="true" />
|
||||||
|
{offline && (
|
||||||
|
<div className="offline-badge" title="当前离线:显示本地缓存数据">
|
||||||
|
<span className="offline-dot" />
|
||||||
|
<span className="offline-text">离线</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<main className="app-main">
|
<main className="app-main">
|
||||||
<div className={'page-transition' + (animating ? ' active' : '')}>
|
<div className={'page-transition' + (animating ? ' active' : '')}>
|
||||||
<Outlet />
|
<Outlet />
|
||||||
|
|||||||
@@ -3,17 +3,33 @@
|
|||||||
// Web SDK 无需基类, 实现 fetchCredentials / uploadData 两个方法即可
|
// Web SDK 无需基类, 实现 fetchCredentials / uploadData 两个方法即可
|
||||||
import { api, getToken } from '../../api/client.js'
|
import { api, getToken } from '../../api/client.js'
|
||||||
|
|
||||||
|
// 上次成功的同步凭证: 离线时复用, 避免 SDK 因"凭证不可用"清空本地库
|
||||||
|
const CRED_KEY = 'iboard_ps_cred'
|
||||||
|
|
||||||
export class IBoardConnector {
|
export class IBoardConnector {
|
||||||
async fetchCredentials() {
|
async fetchCredentials() {
|
||||||
// 未登录: 返回 null 让 SDK 保持断开 (登录后由页面触发 connect)
|
// 未登录: 返回 null 让 SDK 保持断开 (登录后由页面触发 connect)
|
||||||
if (!getToken()) return null
|
if (!getToken()) return null
|
||||||
|
try {
|
||||||
const { token, endpoint } = await api('/powersync/token', { method: 'POST' })
|
const { token, endpoint } = await api('/powersync/token', { method: 'POST' })
|
||||||
// VITE_POWERSYNC_URL: 打包端 (Tauri 外壳等) 可覆盖服务端下发的同步地址
|
// VITE_POWERSYNC_URL: 打包端 (Tauri 外壳等) 可覆盖服务端下发的同步地址
|
||||||
return { endpoint: import.meta.env.VITE_POWERSYNC_URL || endpoint || '', token }
|
const ep = import.meta.env.VITE_POWERSYNC_URL || endpoint || ''
|
||||||
|
if (ep && token) {
|
||||||
|
try { localStorage.setItem(CRED_KEY, JSON.stringify({ endpoint: ep, token, ts: Date.now() })) } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
return { endpoint: ep, token }
|
||||||
|
} catch {
|
||||||
|
// 离线 / 服务不可达: 复用上次凭证 (本地库数据继续可读, 联网后自动恢复同步)
|
||||||
|
try {
|
||||||
|
const cached = JSON.parse(localStorage.getItem(CRED_KEY) || 'null')
|
||||||
|
if (cached?.endpoint && cached?.token) return { endpoint: cached.endpoint, token: cached.token }
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
return null
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async invalidateCredentials() {
|
async invalidateCredentials() {
|
||||||
// 凭证不缓存, 每次向业务后端现取
|
// 交给 SDK: 下次 fetchCredentials 会重新尝试取新凭证 (离线时回退缓存)
|
||||||
}
|
}
|
||||||
|
|
||||||
async uploadData(database) {
|
async uploadData(database) {
|
||||||
|
|||||||
@@ -70,6 +70,35 @@ input, textarea, select { font: inherit; }
|
|||||||
background: var(--color-bg);
|
background: var(--color-bg);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 离线标识 (0.2.1): 窗口左上角, 仅在离线/服务不可达时出现 */
|
||||||
|
.offline-badge {
|
||||||
|
position: fixed;
|
||||||
|
top: calc(var(--safe-top) + 4px);
|
||||||
|
left: 6px;
|
||||||
|
z-index: 120;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
padding: 2px 6px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: rgba(255, 77, 79, 0.12);
|
||||||
|
border: 1px solid rgba(255, 77, 79, 0.35);
|
||||||
|
color: #cf1322;
|
||||||
|
font-size: 10px;
|
||||||
|
line-height: 1;
|
||||||
|
font-weight: 600;
|
||||||
|
pointer-events: none;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
.offline-dot {
|
||||||
|
width: 6px;
|
||||||
|
height: 6px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: #ff4d4f;
|
||||||
|
box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.18);
|
||||||
|
}
|
||||||
|
.offline-text { letter-spacing: 1px; }
|
||||||
|
|
||||||
.app-main {
|
.app-main {
|
||||||
flex: 1 1 auto;
|
flex: 1 1 auto;
|
||||||
min-height: 0;
|
min-height: 0;
|
||||||
|
|||||||
Reference in New Issue
Block a user