87 lines
3.1 KiB
TypeScript
87 lines
3.1 KiB
TypeScript
import { ElMessage } from 'element-plus'
|
|
|
|
/** localStorage 用量阈值:2,000,000 UTF-16 码元(≈4MB 字节,按字面 4M 码元 ≈8MB 会撞浏览器 ~5MB 配额) */
|
|
const LOCAL_STORAGE_SIZE_THRESHOLD = 2_000_000
|
|
|
|
/** 去重门控:已提示且用量未回落到阈值下 ⇒ 不重弹(流式每轮 flush 都会触发检查) */
|
|
let quotaWarningShown = false
|
|
|
|
function notifyStorageError(action: string, key: string, error: unknown): void {
|
|
const isQuotaExceeded = error instanceof DOMException && (
|
|
error.name === 'QuotaExceededError' ||
|
|
error.name === 'NS_ERROR_DOM_QUOTA_REACHED' ||
|
|
error.code === 22 ||
|
|
error.code === 1014
|
|
)
|
|
|
|
const message = isQuotaExceeded
|
|
? '本地存储空间不足,保存失败。建议删除部分历史会话、减少图片附件或导出备份后清理数据。'
|
|
: `${action}失败:${key}`
|
|
|
|
ElMessage.error(message)
|
|
console.error(`${action}本地存储失败: ${key}`, error)
|
|
}
|
|
|
|
export function loadLocalStorage<T>(key: string, defaultValue: T): T {
|
|
try {
|
|
const rawValue = localStorage.getItem(key)
|
|
return rawValue ? (JSON.parse(rawValue) as T) : defaultValue
|
|
} catch (error) {
|
|
notifyStorageError('读取', key, error)
|
|
return defaultValue
|
|
}
|
|
}
|
|
|
|
export function saveLocalStorage<T>(key: string, value: T): void {
|
|
try {
|
|
localStorage.setItem(key, JSON.stringify(value))
|
|
} catch (error) {
|
|
notifyStorageError('保存', key, error)
|
|
}
|
|
}
|
|
|
|
export function removeLocalStorage(key: string): void {
|
|
try {
|
|
localStorage.removeItem(key)
|
|
} catch (error) {
|
|
notifyStorageError('删除', key, error)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 估算 localStorage 用量(改造清单附 1 原文:UTF-16 码元计数,key.length + value.length)。
|
|
* 估算本身很便宜(遍历所有键取 length),正常用量下零可感知开销。
|
|
*/
|
|
export function getLocalStorageSize(): number {
|
|
let total = 0
|
|
for (let i = 0; i < localStorage.length; i++) {
|
|
const key = localStorage.key(i)
|
|
const value = key === null ? null : localStorage.getItem(key)
|
|
// 计算键和值的字符长度(UTF-16 编码单元)
|
|
total += (key?.length ?? 0) + (value?.length ?? 0)
|
|
}
|
|
return total
|
|
}
|
|
|
|
/**
|
|
* 会话持久化写入成功后调用:超阈值提示一次,引导删除**其它**历史会话(不引导删当前会话)。
|
|
* 去重:提示后只要用量没回落到阈值下就不重弹;回落 ⇒ 复位门控,再超可再提示。
|
|
* 与 notifyStorageError 的 QuotaExceededError 分支不冲突(那是写入失败时的兜底,本函数是写入成功后的提前预警)。
|
|
*/
|
|
export function checkLocalStorageUsage(): void {
|
|
try {
|
|
const used = getLocalStorageSize()
|
|
if (used < LOCAL_STORAGE_SIZE_THRESHOLD) {
|
|
quotaWarningShown = false
|
|
return
|
|
}
|
|
if (quotaWarningShown) return
|
|
quotaWarningShown = true
|
|
const usedMb = (used * 2 / 1024 / 1024).toFixed(1)
|
|
ElMessage.warning(`本地存储用量已接近浏览器上限(约 ${usedMb}MB)。建议删除其它历史会话以释放空间;当前会话不受影响。`)
|
|
} catch (error) {
|
|
// 估算失败不影响持久化主流程
|
|
console.error('估算 localStorage 用量失败', error)
|
|
}
|
|
}
|