version: 2
This commit is contained in:
@@ -1,5 +1,11 @@
|
||||
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' ||
|
||||
@@ -41,3 +47,40 @@ export function removeLocalStorage(key: string): void {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user