mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 07:49:19 +08:00
update: 升级vben5.5.9到5.7.0
This commit is contained in:
@@ -1,14 +0,0 @@
|
||||
import { defineBuildConfig } from 'unbuild';
|
||||
|
||||
export default defineBuildConfig({
|
||||
clean: true,
|
||||
declaration: true,
|
||||
entries: [
|
||||
'src/store',
|
||||
'src/constants/index',
|
||||
'src/utils/index',
|
||||
'src/color/index',
|
||||
'src/cache/index',
|
||||
'src/global-state',
|
||||
],
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vben-core/shared",
|
||||
"version": "5.5.9",
|
||||
"version": "5.7.0",
|
||||
"homepage": "https://github.com/vbenjs/vue-vben-admin",
|
||||
"bugs": "https://github.com/vbenjs/vue-vben-admin/issues",
|
||||
"repository": {
|
||||
@@ -11,8 +11,8 @@
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "pnpm unbuild",
|
||||
"stub": "pnpm unbuild --stub"
|
||||
"build": "pnpm exec tsdown",
|
||||
"stub": "pnpm run build"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
@@ -22,31 +22,37 @@
|
||||
"./constants": {
|
||||
"types": "./src/constants/index.ts",
|
||||
"development": "./src/constants/index.ts",
|
||||
"production": "./src/constants/index.ts",
|
||||
"default": "./dist/constants/index.mjs"
|
||||
},
|
||||
"./utils": {
|
||||
"types": "./src/utils/index.ts",
|
||||
"development": "./src/utils/index.ts",
|
||||
"production": "./src/utils/index.ts",
|
||||
"default": "./dist/utils/index.mjs"
|
||||
},
|
||||
"./color": {
|
||||
"types": "./src/color/index.ts",
|
||||
"development": "./src/color/index.ts",
|
||||
"production": "./src/color/index.ts",
|
||||
"default": "./dist/color/index.mjs"
|
||||
},
|
||||
"./cache": {
|
||||
"types": "./src/cache/index.ts",
|
||||
"development": "./src/cache/index.ts",
|
||||
"production": "./src/cache/index.ts",
|
||||
"default": "./dist/cache/index.mjs"
|
||||
},
|
||||
"./store": {
|
||||
"types": "./src/store.ts",
|
||||
"development": "./src/store.ts",
|
||||
"production": "./src/store.ts",
|
||||
"default": "./dist/store.mjs"
|
||||
},
|
||||
"./global-state": {
|
||||
"types": "./src/global-state.ts",
|
||||
"development": "./src/global-state.ts",
|
||||
"production": "./src/global-state.ts",
|
||||
"default": "./dist/global-state.mjs"
|
||||
}
|
||||
},
|
||||
@@ -85,19 +91,14 @@
|
||||
"clsx": "catalog:",
|
||||
"dayjs": "catalog:",
|
||||
"defu": "catalog:",
|
||||
"es-toolkit": "catalog:",
|
||||
"lodash.clonedeep": "catalog:",
|
||||
"lodash.get": "catalog:",
|
||||
"lodash.isequal": "catalog:",
|
||||
"lodash.set": "catalog:",
|
||||
"nprogress": "catalog:",
|
||||
"tailwind-merge": "catalog:",
|
||||
"theme-colors": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/lodash.clonedeep": "catalog:",
|
||||
"@types/lodash.get": "catalog:",
|
||||
"@types/lodash.isequal": "catalog:",
|
||||
"@types/lodash.set": "catalog:",
|
||||
"@types/nprogress": "catalog:"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,418 @@
|
||||
# Cache 模块
|
||||
|
||||
基于**策略模式**的异步存储管理方案,支持多种存储后端(localStorage、IndexedDB、Memory),提供统一的 API 接口。
|
||||
|
||||
## 架构设计
|
||||
|
||||
```shell
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ StorageManager │
|
||||
│ ┌─────────────┐ ┌───────────────────────┐ │
|
||||
│ │ Prefix 隔离 │ │ TTL 过期管理 │ │
|
||||
│ └─────────────┘ └───────────────────────┘ │
|
||||
├───────────────────────────────────────────────┤
|
||||
│ IStorageDriver │
|
||||
├──────────┬─────────────────┬──────────────────┤
|
||||
│ Local │ IndexedDB │ Memory │
|
||||
│ Storage │ Driver │ Driver │
|
||||
│ Driver │ │ │
|
||||
└──────────┴─────────────────┴──────────────────┘
|
||||
```
|
||||
|
||||
**分层职责:**
|
||||
|
||||
| 层级 | 职责 |
|
||||
| ---------------- | -------------------------------------------- |
|
||||
| `StorageManager` | 命名空间前缀隔离、TTL 过期检查、统一对外 API |
|
||||
| `IStorageDriver` | 纯粹的 KV 存取抽象接口 |
|
||||
| 各 Driver 实现 | 对接具体存储引擎,不感知前缀和 TTL |
|
||||
|
||||
---
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 基本使用(默认 localStorage)
|
||||
|
||||
```typescript
|
||||
import { StorageManager } from '@vben-core/shared/cache';
|
||||
|
||||
const cache = new StorageManager({ prefix: 'myapp' });
|
||||
// 使用 IndexedDB
|
||||
//new StorageManager({ driver: new IndexedDBDriver(), prefix: 'app' });
|
||||
|
||||
// 使用 sessionStorage
|
||||
//new StorageManager({ driver: new LocalStorageDriver({ storageType: 'sessionStorage' }), prefix: 'app' });
|
||||
|
||||
// 测试环境
|
||||
//new StorageManager({ driver: new MemoryStorageDriver(), prefix: 'test' });
|
||||
|
||||
// 存储数据
|
||||
await cache.setItem('user', { name: '张三', age: 28 });
|
||||
|
||||
// 读取数据
|
||||
const user = await cache.getItem('user');
|
||||
// => { name: '张三', age: 28 }
|
||||
|
||||
// 带默认值读取
|
||||
const settings = await cache.getItem('settings', { theme: 'light' });
|
||||
// 如果不存在,返回 { theme: 'light' }
|
||||
|
||||
// 删除数据
|
||||
await cache.removeItem('user');
|
||||
|
||||
// 清除当前前缀下所有数据
|
||||
await cache.clear();
|
||||
```
|
||||
|
||||
### 带 TTL 过期
|
||||
|
||||
```typescript
|
||||
const cache = new StorageManager({ prefix: 'session' });
|
||||
|
||||
// 设置 5 分钟后过期(TTL 单位为毫秒)
|
||||
await cache.setItem('token', 'abc123', 5 * 60 * 1000);
|
||||
|
||||
// 5 分钟内可以正常读取
|
||||
const token = await cache.getItem('token');
|
||||
// => 'abc123'
|
||||
|
||||
// 5 分钟后自动返回 null(惰性删除)
|
||||
const expiredToken = await cache.getItem('token');
|
||||
// => null
|
||||
|
||||
// 主动清理所有过期项
|
||||
await cache.clearExpiredItems();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 存储驱动
|
||||
|
||||
### LocalStorageDriver(默认)
|
||||
|
||||
基于浏览器 `localStorage` 或 `sessionStorage`,数据持久化存储。
|
||||
|
||||
```typescript
|
||||
import { LocalStorageDriver, StorageManager } from '@vben-core/shared/cache';
|
||||
|
||||
// 使用 localStorage(默认)
|
||||
const cache = new StorageManager({
|
||||
driver: new LocalStorageDriver(),
|
||||
prefix: 'app',
|
||||
});
|
||||
|
||||
// 使用 sessionStorage
|
||||
const sessionCache = new StorageManager({
|
||||
driver: new LocalStorageDriver({ storageType: 'sessionStorage' }),
|
||||
prefix: 'app',
|
||||
});
|
||||
```
|
||||
|
||||
**特点:**
|
||||
|
||||
- 同步 API 用 async 包装,保持接口统一
|
||||
- 自动处理 JSON 序列化/反序列化
|
||||
- 数据损坏时自动清除并返回 null
|
||||
- 存储上限约 5-10MB(视浏览器而定)
|
||||
|
||||
**适用场景:** 用户偏好设置、小型配置数据、Token 存储
|
||||
|
||||
---
|
||||
|
||||
### IndexedDBDriver
|
||||
|
||||
基于浏览器 IndexedDB,支持大容量结构化数据存储。
|
||||
|
||||
```typescript
|
||||
import {IndexedDBDriver, StorageManager} from '@vben-core/shared/cache';
|
||||
|
||||
const cache = new StorageManager({
|
||||
driver: new IndexedDBDriver({
|
||||
dbName: 'my-app-db', // 数据库名称,默认 'vben-storage'
|
||||
dbVersion: 1, // 数据库版本,默认 1
|
||||
storeName: 'cache-store', // 对象存储名称,默认 'kv-store'
|
||||
}),
|
||||
prefix: 'data',
|
||||
});
|
||||
|
||||
// 存储大量数据
|
||||
await cache.setItem('table-data', largeDataArray);
|
||||
|
||||
// 存储二进制友好的结构(IndexedDB 原生支持)
|
||||
await cache.setItem('config', {
|
||||
columns: [...],
|
||||
filters: [...],
|
||||
pagination: {page: 1, size: 20},
|
||||
});
|
||||
```
|
||||
|
||||
**特点:**
|
||||
|
||||
- 懒初始化:首次操作时自动打开数据库,无需手动调用 `init()`
|
||||
- 存储容量大(通常数百 MB 到 GB 级别)
|
||||
- 支持结构化克隆(可存储 Date、RegExp、Blob 等复杂类型)
|
||||
- 天然异步,不阻塞主线程
|
||||
|
||||
**适用场景:** 离线数据缓存、大型表格数据、文件/图片缓存、复杂业务数据
|
||||
|
||||
---
|
||||
|
||||
### MemoryStorageDriver
|
||||
|
||||
基于内存 Map,数据不持久化,页面刷新即丢失。
|
||||
|
||||
```typescript
|
||||
import { MemoryStorageDriver, StorageManager } from '@vben-core/shared/cache';
|
||||
|
||||
const cache = new StorageManager({
|
||||
driver: new MemoryStorageDriver(),
|
||||
prefix: 'test',
|
||||
});
|
||||
```
|
||||
|
||||
**特点:**
|
||||
|
||||
- 读写速度最快
|
||||
- 无浏览器 API 依赖
|
||||
- 数据随页面生命周期销毁
|
||||
|
||||
**适用场景:** 单元测试、SSR 服务端渲染、临时运行时缓存
|
||||
|
||||
---
|
||||
|
||||
## API 参考
|
||||
|
||||
### StorageManager
|
||||
|
||||
#### 构造函数
|
||||
|
||||
```typescript
|
||||
new StorageManager(options?: StorageManagerOptions)
|
||||
```
|
||||
|
||||
| 参数 | 类型 | 默认值 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| `driver` | `IStorageDriver` | `new LocalStorageDriver()` | 存储驱动实例 |
|
||||
| `prefix` | `string` | `''` | 键前缀,用于命名空间隔离 |
|
||||
|
||||
#### 方法
|
||||
|
||||
| 方法 | 签名 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `getItem` | `getItem<T>(key: string, defaultValue?: T \| null): Promise<T \| null>` | 获取存储项,过期或不存在返回默认值 |
|
||||
| `setItem` | `setItem<T>(key: string, value: T, ttl?: number): Promise<void>` | 设置存储项,可选 TTL(毫秒) |
|
||||
| `removeItem` | `removeItem(key: string): Promise<void>` | 删除指定存储项 |
|
||||
| `clear` | `clear(): Promise<void>` | 清除当前前缀下所有存储项 |
|
||||
| `clearExpiredItems` | `clearExpiredItems(): Promise<void>` | 主动清理所有过期项 |
|
||||
|
||||
---
|
||||
|
||||
### IStorageDriver 接口
|
||||
|
||||
自定义驱动需要实现此接口:
|
||||
|
||||
```typescript
|
||||
interface IStorageDriver {
|
||||
clear(): Promise<void>;
|
||||
|
||||
getItem<T>(key: string): Promise<null | T>;
|
||||
|
||||
keys(): Promise<string[]>;
|
||||
|
||||
removeItem(key: string): Promise<void>;
|
||||
|
||||
setItem<T>(key: string, value: T): Promise<void>;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 高级用法
|
||||
|
||||
### 自定义 Driver
|
||||
|
||||
```typescript
|
||||
import type { IStorageDriver } from '@vben-core/shared/cache';
|
||||
|
||||
class CookieStorageDriver implements IStorageDriver {
|
||||
async getItem<T>(key: string): Promise<null | T> {
|
||||
const value = getCookie(key);
|
||||
return value ? JSON.parse(value) : null;
|
||||
}
|
||||
|
||||
async setItem<T>(key: string, value: T): Promise<void> {
|
||||
setCookie(key, JSON.stringify(value));
|
||||
}
|
||||
|
||||
async removeItem(key: string): Promise<void> {
|
||||
deleteCookie(key);
|
||||
}
|
||||
|
||||
async clear(): Promise<void> {
|
||||
clearAllCookies();
|
||||
}
|
||||
|
||||
async keys(): Promise<string[]> {
|
||||
return getAllCookieNames();
|
||||
}
|
||||
}
|
||||
|
||||
// 使用自定义 Driver
|
||||
const cache = new StorageManager({
|
||||
driver: new CookieStorageDriver(),
|
||||
prefix: 'ck',
|
||||
});
|
||||
```
|
||||
|
||||
### 根据环境动态选择 Driver
|
||||
|
||||
```typescript
|
||||
import {
|
||||
IndexedDBDriver,
|
||||
LocalStorageDriver,
|
||||
MemoryStorageDriver,
|
||||
StorageManager,
|
||||
} from '@vben-core/shared/cache';
|
||||
|
||||
function createStorageManager(prefix: string) {
|
||||
// SSR 环境使用内存驱动
|
||||
if (typeof window === 'undefined') {
|
||||
return new StorageManager({
|
||||
driver: new MemoryStorageDriver(),
|
||||
prefix,
|
||||
});
|
||||
}
|
||||
|
||||
// 大数据场景使用 IndexedDB
|
||||
if (needsLargeStorage()) {
|
||||
return new StorageManager({
|
||||
driver: new IndexedDBDriver({ dbName: `${prefix}-db` }),
|
||||
prefix,
|
||||
});
|
||||
}
|
||||
|
||||
// 默认使用 localStorage
|
||||
return new StorageManager({ prefix });
|
||||
}
|
||||
```
|
||||
|
||||
### 命名空间隔离
|
||||
|
||||
```typescript
|
||||
// 不同模块使用不同前缀,互不干扰
|
||||
const userCache = new StorageManager({ prefix: 'user' });
|
||||
const configCache = new StorageManager({ prefix: 'config' });
|
||||
|
||||
await userCache.setItem('profile', { name: '张三' });
|
||||
await configCache.setItem('profile', { theme: 'dark' });
|
||||
|
||||
// 各自独立
|
||||
await userCache.getItem('profile'); // => { name: '张三' }
|
||||
await configCache.getItem('profile'); // => { theme: 'dark' }
|
||||
|
||||
// 只清除 user 前缀的数据
|
||||
await userCache.clear();
|
||||
await configCache.getItem('profile'); // => { theme: 'dark' }(不受影响)
|
||||
```
|
||||
|
||||
### 定时清理过期数据
|
||||
|
||||
```typescript
|
||||
const cache = new StorageManager({ prefix: 'app' });
|
||||
|
||||
// 应用启动时清理一次
|
||||
await cache.clearExpiredItems();
|
||||
|
||||
// 或者定时清理(每 10 分钟)
|
||||
setInterval(
|
||||
async () => {
|
||||
await cache.clearExpiredItems();
|
||||
},
|
||||
10 * 60 * 1000,
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 数据存储格式
|
||||
|
||||
`StorageManager` 在 Driver 层存储的数据结构为:
|
||||
|
||||
```typescript
|
||||
interface StorageItem<T> {
|
||||
expiry?: number; // 过期时间戳(毫秒),undefined 表示永不过期
|
||||
value: T; // 实际业务数据
|
||||
}
|
||||
```
|
||||
|
||||
实际存储的 key 格式为:`{prefix}-{key}`
|
||||
|
||||
例如 `prefix = 'app'`,`key = 'user'`,则实际存储键为 `app-user`。
|
||||
|
||||
---
|
||||
|
||||
## 过期策略
|
||||
|
||||
采用**惰性删除 + 主动清理**双重策略:
|
||||
|
||||
| 策略 | 触发时机 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 惰性删除 | 调用 `getItem` 时 | 读取时检查过期,过期则删除并返回默认值 |
|
||||
| 主动清理 | 调用 `clearExpiredItems` 时 | 遍历所有带前缀的 key,删除已过期项 |
|
||||
|
||||
---
|
||||
|
||||
## 各 Driver 对比
|
||||
|
||||
| 特性 | LocalStorageDriver | IndexedDBDriver | MemoryStorageDriver |
|
||||
| ---------- | ------------------- | ---------------- | ------------------- |
|
||||
| 持久化 | ✅ | ✅ | ❌ |
|
||||
| 容量 | 5-10 MB | 数百 MB+ | 受内存限制 |
|
||||
| 速度 | 快(同步) | 中等(异步 I/O) | 最快 |
|
||||
| 数据类型 | 仅 JSON 可序列化 | 结构化克隆 | 任意 JS 对象 |
|
||||
| 浏览器支持 | 所有现代浏览器 | 所有现代浏览器 | 任意环境 |
|
||||
| 阻塞主线程 | 是 | 否 | 否 |
|
||||
| 适用场景 | 配置、Token、小数据 | 离线缓存、大数据 | 测试、SSR |
|
||||
|
||||
---
|
||||
|
||||
## 在项目中的使用
|
||||
|
||||
本项目中 `StorageManager` 主要被 `PreferenceManager` 消费,用于持久化用户偏好设置:
|
||||
|
||||
```typescript
|
||||
// packages/@core/preferences/src/preferences.ts
|
||||
class PreferenceManager {
|
||||
private cache: StorageManager;
|
||||
|
||||
constructor() {
|
||||
this.cache = new StorageManager();
|
||||
this.state = reactive<Preferences>({ ...defaultPreferences });
|
||||
}
|
||||
|
||||
initPreferences = async ({ namespace }) => {
|
||||
// 用应用命名空间重新初始化
|
||||
this.cache = new StorageManager({ prefix: namespace });
|
||||
|
||||
// 从缓存加载偏好设置
|
||||
const cached = await this.cache.getItem<Preferences>('preferences');
|
||||
// ...
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **所有方法都是异步的** — 即使底层是同步的 localStorage,API 也返回 Promise,确保切换 Driver 时无需改动调用方。
|
||||
|
||||
2. **TTL 单位是毫秒** — `setItem('key', value, 60000)` 表示 60 秒后过期。
|
||||
|
||||
3. **IndexedDB 懒初始化** — 不需要手动调用 `init()` 或 `open()`,首次操作时自动打开数据库连接并复用。
|
||||
|
||||
4. **前缀隔离是逻辑隔离** — `clear()` 只清除当前前缀下的数据,不影响其他前缀或无前缀的数据。
|
||||
|
||||
5. **错误处理** — LocalStorageDriver 在 JSON 解析失败时自动清除损坏数据; `PreferenceManager.saveToCache` 内部 try-catch 防止未捕获异常。
|
||||
|
||||
6. **IndexedDB 版本升级** — 如果需要修改 objectStore 结构,需要递增 `dbVersion`。当前实现在 `upgradeneeded` 事件中自动创建 objectStore。
|
||||
+56
-63
@@ -1,5 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { MemoryStorageDriver } from '../memory-storage-driver';
|
||||
import { StorageManager } from '../storage-manager';
|
||||
|
||||
describe('storageManager', () => {
|
||||
@@ -7,123 +8,115 @@ describe('storageManager', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
localStorage.clear();
|
||||
storageManager = new StorageManager({
|
||||
driver: new MemoryStorageDriver(),
|
||||
prefix: 'test_',
|
||||
});
|
||||
});
|
||||
|
||||
it('should set and get an item', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
const user = storageManager.getItem('user');
|
||||
it('should set and get an item', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 30, name: 'John Doe' });
|
||||
});
|
||||
|
||||
it('should return default value if item does not exist', () => {
|
||||
const user = storageManager.getItem('nonexistent', {
|
||||
it('should return default value if item does not exist', async () => {
|
||||
const user = await storageManager.getItem('nonexistent', {
|
||||
age: 0,
|
||||
name: 'Default User',
|
||||
});
|
||||
expect(user).toEqual({ age: 0, name: 'Default User' });
|
||||
});
|
||||
|
||||
it('should remove an item', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
storageManager.removeItem('user');
|
||||
const user = storageManager.getItem('user');
|
||||
it('should remove an item', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
await storageManager.removeItem('user');
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toBeNull();
|
||||
});
|
||||
|
||||
it('should clear all items with the prefix', () => {
|
||||
storageManager.setItem('user1', { age: 30, name: 'John Doe' });
|
||||
storageManager.setItem('user2', { age: 25, name: 'Jane Doe' });
|
||||
storageManager.clear();
|
||||
expect(storageManager.getItem('user1')).toBeNull();
|
||||
expect(storageManager.getItem('user2')).toBeNull();
|
||||
it('should clear all items with the prefix', async () => {
|
||||
await storageManager.setItem('user1', { age: 30, name: 'John Doe' });
|
||||
await storageManager.setItem('user2', { age: 25, name: 'Jane Doe' });
|
||||
await storageManager.clear();
|
||||
expect(await storageManager.getItem('user1')).toBeNull();
|
||||
expect(await storageManager.getItem('user2')).toBeNull();
|
||||
});
|
||||
|
||||
it('should clear expired items', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
|
||||
it('should clear expired items', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
|
||||
vi.advanceTimersByTime(1001); // 快进时间
|
||||
storageManager.clearExpiredItems();
|
||||
const user = storageManager.getItem('user');
|
||||
await storageManager.clearExpiredItems();
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toBeNull();
|
||||
});
|
||||
|
||||
it('should not clear non-expired items', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' }, 10_000); // 10秒过期
|
||||
it('should not clear non-expired items', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' }, 10_000); // 10秒过期
|
||||
vi.advanceTimersByTime(5000); // 快进时间
|
||||
storageManager.clearExpiredItems();
|
||||
const user = storageManager.getItem('user');
|
||||
await storageManager.clearExpiredItems();
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 30, name: 'John Doe' });
|
||||
});
|
||||
|
||||
it('should handle JSON parse errors gracefully', () => {
|
||||
localStorage.setItem('test_user', '{ invalid JSON }');
|
||||
const user = storageManager.getItem('user', {
|
||||
age: 0,
|
||||
name: 'Default User',
|
||||
});
|
||||
expect(user).toEqual({ age: 0, name: 'Default User' });
|
||||
});
|
||||
it('should return null for non-existent items without default value', () => {
|
||||
const user = storageManager.getItem('nonexistent');
|
||||
it('should return null for non-existent items without default value', async () => {
|
||||
const user = await storageManager.getItem('nonexistent');
|
||||
expect(user).toBeNull();
|
||||
});
|
||||
|
||||
it('should overwrite existing items', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
storageManager.setItem('user', { age: 25, name: 'Jane Doe' });
|
||||
const user = storageManager.getItem('user');
|
||||
it('should overwrite existing items', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
await storageManager.setItem('user', { age: 25, name: 'Jane Doe' });
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 25, name: 'Jane Doe' });
|
||||
});
|
||||
|
||||
it('should handle items without expiry correctly', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
it('should handle items without expiry correctly', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
vi.advanceTimersByTime(5000);
|
||||
const user = storageManager.getItem('user');
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 30, name: 'John Doe' });
|
||||
});
|
||||
|
||||
it('should remove expired items when accessed', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
|
||||
it('should remove expired items when accessed', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
|
||||
vi.advanceTimersByTime(1001); // 快进时间
|
||||
const user = storageManager.getItem('user');
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toBeNull();
|
||||
});
|
||||
|
||||
it('should not remove non-expired items when accessed', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' }, 10_000); // 10秒过期
|
||||
it('should not remove non-expired items when accessed', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' }, 10_000); // 10秒过期
|
||||
vi.advanceTimersByTime(5000); // 快进时间
|
||||
const user = storageManager.getItem('user');
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 30, name: 'John Doe' });
|
||||
});
|
||||
|
||||
it('should handle multiple items with different expiry times', () => {
|
||||
storageManager.setItem('user1', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
|
||||
storageManager.setItem('user2', { age: 25, name: 'Jane Doe' }, 2000); // 2秒过期
|
||||
it('should handle multiple items with different expiry times', async () => {
|
||||
await storageManager.setItem('user1', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
|
||||
await storageManager.setItem('user2', { age: 25, name: 'Jane Doe' }, 2000); // 2秒过期
|
||||
vi.advanceTimersByTime(1500); // 快进时间
|
||||
storageManager.clearExpiredItems();
|
||||
const user1 = storageManager.getItem('user1');
|
||||
const user2 = storageManager.getItem('user2');
|
||||
await storageManager.clearExpiredItems();
|
||||
const user1 = await storageManager.getItem('user1');
|
||||
const user2 = await storageManager.getItem('user2');
|
||||
expect(user1).toBeNull();
|
||||
expect(user2).toEqual({ age: 25, name: 'Jane Doe' });
|
||||
});
|
||||
|
||||
it('should handle items with no expiry', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
it('should handle items with no expiry', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
vi.advanceTimersByTime(10_000); // 快进时间
|
||||
storageManager.clearExpiredItems();
|
||||
const user = storageManager.getItem('user');
|
||||
await storageManager.clearExpiredItems();
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 30, name: 'John Doe' });
|
||||
});
|
||||
|
||||
it('should clear all items correctly', () => {
|
||||
storageManager.setItem('user1', { age: 30, name: 'John Doe' });
|
||||
storageManager.setItem('user2', { age: 25, name: 'Jane Doe' });
|
||||
storageManager.clear();
|
||||
const user1 = storageManager.getItem('user1');
|
||||
const user2 = storageManager.getItem('user2');
|
||||
it('should clear all items correctly', async () => {
|
||||
await storageManager.setItem('user1', { age: 30, name: 'John Doe' });
|
||||
await storageManager.setItem('user2', { age: 25, name: 'Jane Doe' });
|
||||
await storageManager.clear();
|
||||
const user1 = await storageManager.getItem('user1');
|
||||
const user2 = await storageManager.getItem('user2');
|
||||
expect(user1).toBeNull();
|
||||
expect(user2).toBeNull();
|
||||
});
|
||||
|
||||
@@ -1 +1,5 @@
|
||||
export * from './indexeddb-driver';
|
||||
export * from './local-storage-driver';
|
||||
export * from './memory-storage-driver';
|
||||
export * from './storage-manager';
|
||||
export type * from './types';
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import type { IStorageDriver } from './types';
|
||||
|
||||
interface IndexedDBDriverOptions {
|
||||
/** 数据库名称 */
|
||||
dbName?: string;
|
||||
/** 数据库版本 */
|
||||
dbVersion?: number;
|
||||
/** 对象存储名称 */
|
||||
storeName?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* IndexedDB 驱动
|
||||
* 采用懒初始化模式,首次操作时自动打开数据库
|
||||
*/
|
||||
class IndexedDBDriver implements IStorageDriver {
|
||||
private dbName: string;
|
||||
private dbPromise: null | Promise<IDBDatabase> = null;
|
||||
private dbVersion: number;
|
||||
private storeName: string;
|
||||
|
||||
constructor({
|
||||
dbName = 'vben-storage',
|
||||
dbVersion = 1,
|
||||
storeName = 'kv-store',
|
||||
}: IndexedDBDriverOptions = {}) {
|
||||
this.dbName = dbName;
|
||||
this.dbVersion = dbVersion;
|
||||
this.storeName = storeName;
|
||||
}
|
||||
|
||||
async clear(): Promise<void> {
|
||||
const db = await this.getDB();
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(this.storeName, 'readwrite');
|
||||
const store = tx.objectStore(this.storeName);
|
||||
store.clear();
|
||||
|
||||
tx.addEventListener('complete', () => resolve());
|
||||
tx.addEventListener('error', () => reject(tx.error));
|
||||
tx.addEventListener('abort', () =>
|
||||
reject(tx.error ?? new Error('Transaction aborted')),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async getItem<T>(key: string): Promise<null | T> {
|
||||
const db = await this.getDB();
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(this.storeName, 'readonly');
|
||||
const store = tx.objectStore(this.storeName);
|
||||
const request = store.get(key);
|
||||
|
||||
request.addEventListener('success', () =>
|
||||
resolve(request.result ?? null),
|
||||
);
|
||||
request.addEventListener('error', () => reject(request.error));
|
||||
});
|
||||
}
|
||||
|
||||
async keys(): Promise<string[]> {
|
||||
const db = await this.getDB();
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(this.storeName, 'readonly');
|
||||
const store = tx.objectStore(this.storeName);
|
||||
const request = store.getAllKeys();
|
||||
|
||||
request.addEventListener('success', () =>
|
||||
resolve(request.result.map(String)),
|
||||
);
|
||||
request.addEventListener('error', () => reject(request.error));
|
||||
});
|
||||
}
|
||||
|
||||
async removeItem(key: string): Promise<void> {
|
||||
const db = await this.getDB();
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(this.storeName, 'readwrite');
|
||||
const store = tx.objectStore(this.storeName);
|
||||
store.delete(key);
|
||||
|
||||
tx.addEventListener('complete', () => resolve());
|
||||
tx.addEventListener('error', () => reject(tx.error));
|
||||
tx.addEventListener('abort', () =>
|
||||
reject(tx.error ?? new Error('Transaction aborted')),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async setItem(key: string, value: unknown): Promise<void> {
|
||||
const db = await this.getDB();
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(this.storeName, 'readwrite');
|
||||
const store = tx.objectStore(this.storeName);
|
||||
store.put(value, key);
|
||||
|
||||
tx.addEventListener('complete', () => resolve());
|
||||
tx.addEventListener('error', () => reject(tx.error));
|
||||
tx.addEventListener('abort', () =>
|
||||
reject(tx.error ?? new Error('Transaction aborted')),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 懒初始化:首次调用时打开数据库,后续复用同一个 Promise
|
||||
*/
|
||||
private getDB(): Promise<IDBDatabase> {
|
||||
if (!this.dbPromise) {
|
||||
this.dbPromise = this.openDB().catch((error) => {
|
||||
// allow retry on next call
|
||||
this.dbPromise = null;
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
return this.dbPromise;
|
||||
}
|
||||
|
||||
private openDB(): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(this.dbName, this.dbVersion);
|
||||
|
||||
request.addEventListener('upgradeneeded', () => {
|
||||
const db = request.result;
|
||||
if (!db.objectStoreNames.contains(this.storeName)) {
|
||||
db.createObjectStore(this.storeName);
|
||||
}
|
||||
});
|
||||
|
||||
request.addEventListener('success', () => resolve(request.result));
|
||||
request.addEventListener('error', () => reject(request.error));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export { IndexedDBDriver };
|
||||
export type { IndexedDBDriverOptions };
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { IStorageDriver } from './types';
|
||||
|
||||
type StorageType = 'localStorage' | 'sessionStorage';
|
||||
|
||||
interface LocalStorageDriverOptions {
|
||||
/** 使用 localStorage 还是 sessionStorage */
|
||||
storageType?: StorageType;
|
||||
}
|
||||
|
||||
/**
|
||||
* LocalStorage / SessionStorage 驱动
|
||||
* 用 async 包装同步 API,保持接口统一
|
||||
*/
|
||||
class LocalStorageDriver implements IStorageDriver {
|
||||
private storage: Storage;
|
||||
|
||||
constructor({
|
||||
storageType = 'localStorage',
|
||||
}: LocalStorageDriverOptions = {}) {
|
||||
if (typeof window === 'undefined') {
|
||||
// eslint-disable-next-line unicorn/prefer-type-error -- not a type check, it's an environment check
|
||||
throw new Error(
|
||||
'LocalStorageDriver is not available in non-browser environments. Use MemoryStorageDriver instead.',
|
||||
);
|
||||
}
|
||||
this.storage =
|
||||
storageType === 'localStorage'
|
||||
? window.localStorage
|
||||
: window.sessionStorage;
|
||||
}
|
||||
|
||||
async clear(): Promise<void> {
|
||||
this.storage.clear();
|
||||
}
|
||||
|
||||
async getItem<T>(key: string): Promise<null | T> {
|
||||
const raw = this.storage.getItem(key);
|
||||
if (raw === null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(raw) as T;
|
||||
} catch {
|
||||
// 数据损坏,清除并返回 null
|
||||
this.storage.removeItem(key);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async keys(): Promise<string[]> {
|
||||
const result: string[] = [];
|
||||
for (let i = 0; i < this.storage.length; i++) {
|
||||
const key = this.storage.key(i);
|
||||
if (key !== null) {
|
||||
result.push(key);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async removeItem(key: string): Promise<void> {
|
||||
this.storage.removeItem(key);
|
||||
}
|
||||
|
||||
async setItem(key: string, value: unknown): Promise<void> {
|
||||
this.storage.setItem(key, JSON.stringify(value));
|
||||
}
|
||||
}
|
||||
|
||||
export { LocalStorageDriver };
|
||||
export type { LocalStorageDriverOptions };
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { IStorageDriver } from './types';
|
||||
|
||||
/**
|
||||
* 内存存储驱动
|
||||
* 适用于测试环境和 SSR 场景,数据不持久化
|
||||
*/
|
||||
class MemoryStorageDriver implements IStorageDriver {
|
||||
private store = new Map<string, unknown>();
|
||||
|
||||
async clear(): Promise<void> {
|
||||
this.store.clear();
|
||||
}
|
||||
|
||||
async getItem<T>(key: string): Promise<null | T> {
|
||||
const value = this.store.get(key);
|
||||
return (value as T) ?? null;
|
||||
}
|
||||
|
||||
async keys(): Promise<string[]> {
|
||||
return [...this.store.keys()];
|
||||
}
|
||||
|
||||
async removeItem(key: string): Promise<void> {
|
||||
this.store.delete(key);
|
||||
}
|
||||
|
||||
async setItem(key: string, value: unknown): Promise<void> {
|
||||
this.store.set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
export { MemoryStorageDriver };
|
||||
@@ -1,53 +1,54 @@
|
||||
type StorageType = 'localStorage' | 'sessionStorage';
|
||||
import type {
|
||||
IStorageDriver,
|
||||
StorageItem,
|
||||
StorageManagerOptions,
|
||||
} from './types';
|
||||
|
||||
interface StorageManagerOptions {
|
||||
prefix?: string;
|
||||
storageType?: StorageType;
|
||||
}
|
||||
|
||||
interface StorageItem<T> {
|
||||
expiry?: number;
|
||||
value: T;
|
||||
}
|
||||
import { LocalStorageDriver } from './local-storage-driver';
|
||||
import { MemoryStorageDriver } from './memory-storage-driver';
|
||||
|
||||
/**
|
||||
* 存储管理器(策略模式)
|
||||
* - prefix(命名空间隔离)在此层处理
|
||||
* - TTL(过期机制)在此层处理
|
||||
* - Driver 只负责纯粹的 KV 存取
|
||||
*/
|
||||
class StorageManager {
|
||||
private driver: IStorageDriver;
|
||||
private prefix: string;
|
||||
private storage: Storage;
|
||||
|
||||
constructor({
|
||||
prefix = '',
|
||||
storageType = 'localStorage',
|
||||
}: StorageManagerOptions = {}) {
|
||||
constructor({ driver, prefix = '' }: StorageManagerOptions = {}) {
|
||||
this.driver = driver || this.createDefaultDriver();
|
||||
this.prefix = prefix;
|
||||
this.storage =
|
||||
storageType === 'localStorage'
|
||||
? window.localStorage
|
||||
: window.sessionStorage;
|
||||
if (!this.prefix && this.driver instanceof LocalStorageDriver) {
|
||||
console.warn(
|
||||
'[StorageManager] empty prefix combined with LocalStorageDriver — clear()/keys() will affect every localStorage entry.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除所有带前缀的存储项
|
||||
*/
|
||||
clear(): void {
|
||||
const keysToRemove: string[] = [];
|
||||
for (let i = 0; i < this.storage.length; i++) {
|
||||
const key = this.storage.key(i);
|
||||
if (key && key.startsWith(this.prefix)) {
|
||||
keysToRemove.push(key);
|
||||
}
|
||||
}
|
||||
keysToRemove.forEach((key) => this.storage.removeItem(key));
|
||||
async clear(): Promise<void> {
|
||||
const allKeys = await this.driver.keys();
|
||||
const fullPrefix = this.prefix ? `${this.prefix}-` : '';
|
||||
const prefixedKeys = allKeys.filter((key) => key.startsWith(fullPrefix));
|
||||
await Promise.all(prefixedKeys.map((key) => this.driver.removeItem(key)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除所有过期的存储项
|
||||
*/
|
||||
clearExpiredItems(): void {
|
||||
for (let i = 0; i < this.storage.length; i++) {
|
||||
const key = this.storage.key(i);
|
||||
if (key && key.startsWith(this.prefix)) {
|
||||
const shortKey = key.replace(this.prefix, '');
|
||||
this.getItem(shortKey); // 调用 getItem 方法检查并移除过期项
|
||||
async clearExpiredItems(): Promise<void> {
|
||||
const allKeys = await this.driver.keys();
|
||||
const fullPrefix = this.prefix ? `${this.prefix}-` : '';
|
||||
const prefixedKeys = allKeys.filter((key) => key.startsWith(fullPrefix));
|
||||
|
||||
for (const fullKey of prefixedKeys) {
|
||||
const raw = await this.driver.getItem<StorageItem<unknown>>(fullKey);
|
||||
if (raw && raw.expiry && Date.now() > raw.expiry) {
|
||||
await this.driver.removeItem(fullKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,36 +57,47 @@ class StorageManager {
|
||||
* 获取存储项
|
||||
* @param key 键
|
||||
* @param defaultValue 当项不存在或已过期时返回的默认值
|
||||
* @returns 值,如果项已过期或解析错误则返回默认值
|
||||
* @returns 值,如果项已过期则返回默认值
|
||||
*/
|
||||
getItem<T>(key: string, defaultValue: null | T = null): null | T {
|
||||
async getItem<T>(
|
||||
key: string,
|
||||
defaultValue: null | T = null,
|
||||
): Promise<null | T> {
|
||||
const fullKey = this.getFullKey(key);
|
||||
const itemStr = this.storage.getItem(fullKey);
|
||||
if (!itemStr) {
|
||||
const raw = await this.driver.getItem<StorageItem<T>>(fullKey);
|
||||
|
||||
if (!raw) {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
try {
|
||||
const item: StorageItem<T> = JSON.parse(itemStr);
|
||||
if (item.expiry && Date.now() > item.expiry) {
|
||||
this.storage.removeItem(fullKey);
|
||||
return defaultValue;
|
||||
}
|
||||
return item.value;
|
||||
} catch (error) {
|
||||
console.error(`Error parsing item with key "${fullKey}":`, error);
|
||||
this.storage.removeItem(fullKey); // 如果解析失败,删除该项
|
||||
// TTL 检查
|
||||
if (raw.expiry && Date.now() > raw.expiry) {
|
||||
await this.driver.removeItem(fullKey);
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
return raw.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前前缀下的所有存储键(已去除前缀部分)
|
||||
*/
|
||||
async keys(): Promise<string[]> {
|
||||
const allKeys = await this.driver.keys();
|
||||
const fullPrefix = this.prefix ? `${this.prefix}-` : '';
|
||||
if (!fullPrefix) return allKeys;
|
||||
return allKeys
|
||||
.filter((key) => key.startsWith(fullPrefix))
|
||||
.map((key) => key.slice(fullPrefix.length));
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除存储项
|
||||
* @param key 键
|
||||
*/
|
||||
removeItem(key: string): void {
|
||||
async removeItem(key: string): Promise<void> {
|
||||
const fullKey = this.getFullKey(key);
|
||||
this.storage.removeItem(fullKey);
|
||||
await this.driver.removeItem(fullKey);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -94,24 +106,40 @@ class StorageManager {
|
||||
* @param value 值
|
||||
* @param ttl 存活时间(毫秒)
|
||||
*/
|
||||
setItem<T>(key: string, value: T, ttl?: number): void {
|
||||
async setItem(key: string, value: unknown, ttl?: number): Promise<void> {
|
||||
const fullKey = this.getFullKey(key);
|
||||
const expiry = ttl ? Date.now() + ttl : undefined;
|
||||
const item: StorageItem<T> = { expiry, value };
|
||||
try {
|
||||
this.storage.setItem(fullKey, JSON.stringify(item));
|
||||
} catch (error) {
|
||||
console.error(`Error setting item with key "${fullKey}":`, error);
|
||||
}
|
||||
const item: StorageItem<unknown> = { expiry, value };
|
||||
await this.driver.setItem(fullKey, item);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取完整的存储键
|
||||
* 根据运行环境创建默认驱动:
|
||||
* - 浏览器环境(window.localStorage 可用)→ LocalStorageDriver
|
||||
* - SSR / Node 环境 → MemoryStorageDriver
|
||||
*/
|
||||
private createDefaultDriver(): IStorageDriver {
|
||||
try {
|
||||
if (typeof window !== 'undefined' && window.localStorage) {
|
||||
return new LocalStorageDriver();
|
||||
}
|
||||
} catch (error) {
|
||||
// localStorage access denied (e.g. Safari private mode)
|
||||
console.warn(
|
||||
'localStorage is not accessible, falling back to MemoryStorageDriver:',
|
||||
error,
|
||||
);
|
||||
}
|
||||
return new MemoryStorageDriver();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取完整的存储键(带前缀)
|
||||
* @param key 原始键
|
||||
* @returns 带前缀的完整键
|
||||
*/
|
||||
private getFullKey(key: string): string {
|
||||
return `${this.prefix}-${key}`;
|
||||
return this.prefix ? `${this.prefix}-${key}` : key;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+34
-12
@@ -1,17 +1,39 @@
|
||||
type StorageType = 'localStorage' | 'sessionStorage';
|
||||
/**
|
||||
* 存储驱动接口(策略模式核心抽象)
|
||||
* 所有存储实现(localStorage、IndexedDB、Memory 等)都需要实现此接口
|
||||
* Driver 层只负责纯粹的 KV 存取,不感知 TTL 和前缀
|
||||
*/
|
||||
interface IStorageDriver {
|
||||
/** 清除所有存储项 */
|
||||
clear(): Promise<void>;
|
||||
|
||||
interface StorageValue<T> {
|
||||
data: T;
|
||||
expiry: null | number;
|
||||
/** 获取存储项 */
|
||||
getItem<T>(key: string): Promise<null | T>;
|
||||
|
||||
/** 获取所有 key */
|
||||
keys(): Promise<string[]>;
|
||||
|
||||
/** 移除存储项 */
|
||||
removeItem(key: string): Promise<void>;
|
||||
|
||||
/** 设置存储项 */
|
||||
setItem(key: string, value: unknown): Promise<void>;
|
||||
}
|
||||
|
||||
interface IStorageCache {
|
||||
clear(): void;
|
||||
getItem<T>(key: string): null | T;
|
||||
key(index: number): null | string;
|
||||
length(): number;
|
||||
removeItem(key: string): void;
|
||||
setItem<T>(key: string, value: T, expiryInMinutes?: number): void;
|
||||
/**
|
||||
* 带 TTL 的存储项包装结构
|
||||
* TTL 逻辑由 StorageManager 统一管理,Driver 层不感知
|
||||
*/
|
||||
interface StorageItem<T> {
|
||||
expiry?: number;
|
||||
value: T;
|
||||
}
|
||||
|
||||
export type { IStorageCache, StorageType, StorageValue };
|
||||
interface StorageManagerOptions {
|
||||
/** 存储驱动实例 */
|
||||
driver?: IStorageDriver;
|
||||
/** 键前缀,用于命名空间隔离 */
|
||||
prefix?: string;
|
||||
}
|
||||
|
||||
export type { IStorageDriver, StorageItem, StorageManagerOptions };
|
||||
|
||||
@@ -19,8 +19,12 @@ export const VBEN_LOGO_URL =
|
||||
*/
|
||||
export const VBEN_PREVIEW_URL = 'https://www.vben.pro';
|
||||
|
||||
export const VBEN_ANTDV_NEXT_PREVIEW_URL = 'https://antdv-next.vben.pro';
|
||||
|
||||
export const VBEN_ELE_PREVIEW_URL = 'https://ele.vben.pro';
|
||||
|
||||
export const VBEN_NAIVE_PREVIEW_URL = 'https://naive.vben.pro';
|
||||
|
||||
export const VBEN_ANT_PREVIEW_URL = 'https://ant.vben.pro';
|
||||
|
||||
export const VBEN_TD_PREVIEW_URL = 'https://tdesign.vben.pro';
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import dayjs from 'dayjs';
|
||||
import timezone from 'dayjs/plugin/timezone.js';
|
||||
import utc from 'dayjs/plugin/utc.js';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
formatDate,
|
||||
formatDateTime,
|
||||
getCurrentTimezone,
|
||||
getSystemTimezone,
|
||||
isDate,
|
||||
isDayjsObject,
|
||||
setCurrentTimezone,
|
||||
} from '../date';
|
||||
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
|
||||
describe('dateUtils', () => {
|
||||
const sampleISO = '2024-10-30T12:34:56Z';
|
||||
const sampleTimestamp = Date.parse(sampleISO);
|
||||
|
||||
beforeEach(() => {
|
||||
// 重置时区
|
||||
dayjs.tz.setDefault();
|
||||
setCurrentTimezone(); // 重置为系统默认
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// formatDate
|
||||
// ===============================
|
||||
describe('formatDate', () => {
|
||||
it('should format a valid ISO date string', () => {
|
||||
const formatted = formatDate(sampleISO, 'YYYY/MM/DD');
|
||||
expect(formatted).toMatch(/2024\/10\/30/);
|
||||
});
|
||||
|
||||
it('should format a timestamp correctly', () => {
|
||||
const formatted = formatDate(sampleTimestamp);
|
||||
expect(formatted).toMatch(/2024-10-30/);
|
||||
});
|
||||
|
||||
it('should format a Date object', () => {
|
||||
const formatted = formatDate(new Date(sampleISO));
|
||||
expect(formatted).toMatch(/2024-10-30/);
|
||||
});
|
||||
|
||||
it('should format a dayjs object', () => {
|
||||
const formatted = formatDate(dayjs(sampleISO));
|
||||
expect(formatted).toMatch(/2024-10-30/);
|
||||
});
|
||||
|
||||
it('should return original input if date is invalid', () => {
|
||||
const invalid = 'not-a-date';
|
||||
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
const formatted = formatDate(invalid);
|
||||
expect(formatted).toBe(invalid);
|
||||
expect(spy).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('should apply given format', () => {
|
||||
const formatted = formatDate(sampleISO, 'YYYY-MM-DD HH:mm');
|
||||
expect(formatted).toMatch(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}/);
|
||||
});
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// formatDateTime
|
||||
// ===============================
|
||||
describe('formatDateTime', () => {
|
||||
it('should format date into full datetime', () => {
|
||||
const result = formatDateTime(sampleISO);
|
||||
expect(result).toMatch(/2024-10-30 \d{2}:\d{2}:\d{2}/);
|
||||
});
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// isDate
|
||||
// ===============================
|
||||
describe('isDate', () => {
|
||||
it('should return true for Date instances', () => {
|
||||
expect(isDate(new Date())).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for non-Date values', () => {
|
||||
expect(isDate('2024-10-30')).toBe(false);
|
||||
expect(isDate(null)).toBe(false);
|
||||
expect(isDate(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// isDayjsObject
|
||||
// ===============================
|
||||
describe('isDayjsObject', () => {
|
||||
it('should return true for dayjs objects', () => {
|
||||
expect(isDayjsObject(dayjs())).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for other values', () => {
|
||||
expect(isDayjsObject(new Date())).toBe(false);
|
||||
expect(isDayjsObject('string')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// getSystemTimezone
|
||||
// ===============================
|
||||
describe('getSystemTimezone', () => {
|
||||
it('should return a valid IANA timezone string', () => {
|
||||
const tz = getSystemTimezone();
|
||||
expect(typeof tz).toBe('string');
|
||||
expect(tz).toMatch(/^[A-Z]+\/[A-Z_]+/i);
|
||||
});
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// setCurrentTimezone / getCurrentTimezone
|
||||
// ===============================
|
||||
describe('setCurrentTimezone & getCurrentTimezone', () => {
|
||||
it('should set and retrieve the current timezone', () => {
|
||||
setCurrentTimezone('Asia/Shanghai');
|
||||
expect(getCurrentTimezone()).toBe('Asia/Shanghai');
|
||||
});
|
||||
|
||||
it('should reset to system timezone when called with no args', () => {
|
||||
const guessed = getSystemTimezone();
|
||||
setCurrentTimezone();
|
||||
expect(getCurrentTimezone()).toBe(guessed);
|
||||
});
|
||||
|
||||
it('should update dayjs default timezone', () => {
|
||||
setCurrentTimezone('America/New_York');
|
||||
const d = dayjs('2024-01-01T00:00:00Z');
|
||||
// 校验时区转换生效(小时变化)
|
||||
expect(d.tz().format('HH')).not.toBe('00');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -116,11 +116,11 @@ describe('getElementVisibleRect', () => {
|
||||
} as HTMLElement;
|
||||
|
||||
expect(getElementVisibleRect(element)).toEqual({
|
||||
bottom: 800,
|
||||
bottom: 0,
|
||||
height: 0,
|
||||
left: 1100,
|
||||
right: 1000,
|
||||
top: 900,
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 0,
|
||||
width: 0,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { loadScript } from '../resources';
|
||||
|
||||
const testJsPath =
|
||||
'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js';
|
||||
|
||||
describe('loadScript', () => {
|
||||
beforeEach(() => {
|
||||
// 每个测试前清空 head,保证环境干净
|
||||
@@ -12,18 +9,14 @@ describe('loadScript', () => {
|
||||
});
|
||||
|
||||
it('should resolve when the script loads successfully', async () => {
|
||||
const promise = loadScript(testJsPath);
|
||||
// happy-dom v20+ auto-fires 'load' via handleDisabledFileLoadingAsSuccess
|
||||
const promise = loadScript('/test-script.js');
|
||||
|
||||
// 此时脚本元素已被创建并插入
|
||||
const script = document.querySelector(
|
||||
`script[src="${testJsPath}"]`,
|
||||
'script[src="/test-script.js"]',
|
||||
) as HTMLScriptElement;
|
||||
expect(script).toBeTruthy();
|
||||
|
||||
// 模拟加载成功
|
||||
script.dispatchEvent(new Event('load'));
|
||||
|
||||
// 等待 promise resolve
|
||||
await expect(promise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
@@ -45,37 +38,44 @@ describe('loadScript', () => {
|
||||
});
|
||||
|
||||
it('should reject when the script fails to load', async () => {
|
||||
let capturedScript: HTMLScriptElement | null = null;
|
||||
|
||||
// 拦截 append,捕获 script 元素但不插入 DOM,
|
||||
// 防止 happy-dom v20+ 自动触发 load 事件
|
||||
const appendSpy = vi
|
||||
.spyOn(document.head, 'append')
|
||||
.mockImplementation((...nodes) => {
|
||||
for (const node of nodes) {
|
||||
if (node instanceof HTMLScriptElement) {
|
||||
capturedScript = node;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const promise = loadScript('error.js');
|
||||
|
||||
const script = document.querySelector(
|
||||
'script[src="error.js"]',
|
||||
) as HTMLScriptElement;
|
||||
expect(script).toBeTruthy();
|
||||
appendSpy.mockRestore();
|
||||
|
||||
// 模拟加载失败
|
||||
script.dispatchEvent(new Event('error'));
|
||||
expect(capturedScript).toBeTruthy();
|
||||
if (!capturedScript) {
|
||||
throw new Error('Expected the captured script element to exist');
|
||||
}
|
||||
capturedScript.dispatchEvent(new Event('error'));
|
||||
|
||||
await expect(promise).rejects.toThrow('Failed to load script: error.js');
|
||||
});
|
||||
|
||||
it('should handle multiple concurrent calls and only insert one script tag', async () => {
|
||||
const p1 = loadScript(testJsPath);
|
||||
const p2 = loadScript(testJsPath);
|
||||
|
||||
const script = document.querySelector(
|
||||
`script[src="${testJsPath}"]`,
|
||||
) as HTMLScriptElement;
|
||||
expect(script).toBeTruthy();
|
||||
|
||||
// 触发一次 load,两个 promise 都应该 resolve
|
||||
script.dispatchEvent(new Event('load'));
|
||||
const p1 = loadScript('/test-script.js');
|
||||
const p2 = loadScript('/test-script.js');
|
||||
|
||||
// happy-dom v20+ auto-fires 'load',两个 promise 都应该 resolve
|
||||
await expect(p1).resolves.toBeUndefined();
|
||||
await expect(p2).resolves.toBeUndefined();
|
||||
|
||||
// 只插入一次
|
||||
const scripts = document.head.querySelectorAll(
|
||||
`script[src="${testJsPath}"]`,
|
||||
'script[src="/test-script.js"]',
|
||||
);
|
||||
expect(scripts).toHaveLength(1);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { createStack, Stack } from '../stack';
|
||||
|
||||
describe('stack', () => {
|
||||
let stack: Stack<number>;
|
||||
|
||||
beforeEach(() => {
|
||||
stack = new Stack<number>();
|
||||
});
|
||||
|
||||
it('push & size should work', () => {
|
||||
stack.push(1, 2);
|
||||
|
||||
expect(stack.size).toBe(2);
|
||||
});
|
||||
|
||||
it('peek should return top element without removing it', () => {
|
||||
stack.push(1, 2);
|
||||
|
||||
expect(stack.peek()).toBe(2);
|
||||
expect(stack.size).toBe(2);
|
||||
});
|
||||
|
||||
it('pop should remove and return top element', () => {
|
||||
stack.push(1, 2);
|
||||
|
||||
expect(stack.pop()).toBe(2);
|
||||
expect(stack.size).toBe(1);
|
||||
expect(stack.peek()).toBe(1);
|
||||
});
|
||||
|
||||
it('pop on empty stack should return undefined', () => {
|
||||
expect(stack.pop()).toBeUndefined();
|
||||
expect(stack.peek()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('clear should remove all elements', () => {
|
||||
stack.push(1, 2);
|
||||
|
||||
stack.clear();
|
||||
|
||||
expect(stack.size).toBe(0);
|
||||
expect(stack.peek()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('toArray should return a shallow copy', () => {
|
||||
stack.push(1, 2);
|
||||
|
||||
const arr = stack.toArray();
|
||||
arr.push(3);
|
||||
|
||||
expect(stack.size).toBe(2);
|
||||
expect(stack.toArray()).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it('dedup should remove existing item before push', () => {
|
||||
stack.push(1, 2, 1);
|
||||
|
||||
expect(stack.toArray()).toEqual([2, 1]);
|
||||
expect(stack.size).toBe(2);
|
||||
});
|
||||
|
||||
it('dedup = false should allow duplicate items', () => {
|
||||
const s = new Stack<number>(false);
|
||||
|
||||
s.push(1, 1, 1);
|
||||
|
||||
expect(s.toArray()).toEqual([1, 1, 1]);
|
||||
expect(s.size).toBe(3);
|
||||
});
|
||||
|
||||
it('remove should delete all matching items', () => {
|
||||
stack.push(1, 2, 1);
|
||||
|
||||
stack.remove(1);
|
||||
|
||||
expect(stack.toArray()).toEqual([2]);
|
||||
expect(stack.size).toBe(1);
|
||||
});
|
||||
|
||||
it('maxSize should limit stack capacity', () => {
|
||||
const s = new Stack<number>(true, 3);
|
||||
|
||||
s.push(1, 2, 3, 4);
|
||||
|
||||
expect(s.toArray()).toEqual([2, 3, 4]);
|
||||
expect(s.size).toBe(3);
|
||||
});
|
||||
|
||||
it('dedup + maxSize should work together', () => {
|
||||
const s = new Stack<number>(true, 3);
|
||||
|
||||
s.push(1, 2, 3, 2); // 去重并重新入栈
|
||||
|
||||
expect(s.toArray()).toEqual([1, 3, 2]);
|
||||
expect(s.size).toBe(3);
|
||||
});
|
||||
|
||||
it('createStack should create a stack instance', () => {
|
||||
const s = createStack<number>(true, 2);
|
||||
|
||||
s.push(1, 2, 3);
|
||||
|
||||
expect(s.toArray()).toEqual([2, 3]);
|
||||
});
|
||||
});
|
||||
@@ -34,7 +34,9 @@ describe('stateHandler', () => {
|
||||
}, 10);
|
||||
|
||||
// 等待过程中,期望 Promise 被 reject
|
||||
await expect(handler.waitForCondition()).rejects.toThrow();
|
||||
await expect(handler.waitForCondition()).rejects.toThrow(
|
||||
'Condition was set to false',
|
||||
);
|
||||
expect(handler.isConditionTrue()).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -138,8 +138,10 @@ describe('getNestedValue', () => {
|
||||
expect(result).toBe(2);
|
||||
});
|
||||
|
||||
it('should return the entire object if path is empty', () => {
|
||||
expect(() => getNestedValue(data, '')()).toThrow();
|
||||
it('should throw if path is empty', () => {
|
||||
expect(() => getNestedValue(data, '')).toThrow(
|
||||
'Path must be a non-empty string',
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle paths with array indexes', () => {
|
||||
|
||||
@@ -1,19 +1,41 @@
|
||||
import dayjs from 'dayjs';
|
||||
import timezone from 'dayjs/plugin/timezone.js';
|
||||
import utc from 'dayjs/plugin/utc.js';
|
||||
|
||||
export function formatDate(time: number | string, format = 'YYYY-MM-DD') {
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
|
||||
type FormatDate = Date | dayjs.Dayjs | number | string;
|
||||
|
||||
type Format =
|
||||
| 'HH'
|
||||
| 'HH:mm'
|
||||
| 'HH:mm:ss'
|
||||
| 'YYYY'
|
||||
| 'YYYY-MM'
|
||||
| 'YYYY-MM-DD'
|
||||
| 'YYYY-MM-DD HH'
|
||||
| 'YYYY-MM-DD HH:mm'
|
||||
| 'YYYY-MM-DD HH:mm:ss'
|
||||
| (string & {});
|
||||
|
||||
export function formatDate(time?: FormatDate, format: Format = 'YYYY-MM-DD') {
|
||||
if (time === undefined || time === null || time === '') {
|
||||
return '';
|
||||
}
|
||||
try {
|
||||
const date = dayjs(time);
|
||||
const date = dayjs.isDayjs(time) ? time : dayjs(time);
|
||||
if (!date.isValid()) {
|
||||
throw new Error('Invalid date');
|
||||
}
|
||||
return date.format(format);
|
||||
return date.tz().format(format);
|
||||
} catch (error) {
|
||||
console.error(`Error formatting date: ${error}`);
|
||||
return time;
|
||||
return String(time ?? '');
|
||||
}
|
||||
}
|
||||
|
||||
export function formatDateTime(time: number | string) {
|
||||
export function formatDateTime(time?: FormatDate) {
|
||||
return formatDate(time, 'YYYY-MM-DD HH:mm:ss');
|
||||
}
|
||||
|
||||
@@ -24,3 +46,33 @@ export function isDate(value: any): value is Date {
|
||||
export function isDayjsObject(value: any): value is dayjs.Dayjs {
|
||||
return dayjs.isDayjs(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前时区
|
||||
* @returns 当前时区
|
||||
*/
|
||||
export const getSystemTimezone = () => {
|
||||
return dayjs.tz.guess();
|
||||
};
|
||||
|
||||
/**
|
||||
* 自定义设置的时区
|
||||
*/
|
||||
let currentTimezone = getSystemTimezone();
|
||||
|
||||
/**
|
||||
* 设置默认时区
|
||||
* @param timezone
|
||||
*/
|
||||
export const setCurrentTimezone = (timezone?: string) => {
|
||||
currentTimezone = timezone || getSystemTimezone();
|
||||
dayjs.tz.setDefault(currentTimezone);
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取设置的时区
|
||||
* @returns 设置的时区
|
||||
*/
|
||||
export const getCurrentTimezone = () => {
|
||||
return currentTimezone;
|
||||
};
|
||||
|
||||
@@ -41,6 +41,18 @@ export function getElementVisibleRect(
|
||||
const left = Math.max(rect.left, 0);
|
||||
const right = Math.min(rect.right, viewWidth);
|
||||
|
||||
// 如果元素完全不可见,则返回一个空的矩形
|
||||
if (top >= viewHeight || bottom <= 0 || left >= viewWidth || right <= 0) {
|
||||
return {
|
||||
bottom: 0,
|
||||
height: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 0,
|
||||
width: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
bottom,
|
||||
height: Math.max(0, bottom - top),
|
||||
|
||||
@@ -8,6 +8,7 @@ export * from './letter';
|
||||
export * from './merge';
|
||||
export * from './nprogress';
|
||||
export * from './resources';
|
||||
export * from './stack';
|
||||
export * from './state-handler';
|
||||
export * from './to';
|
||||
export * from './tree';
|
||||
@@ -15,7 +16,6 @@ export * from './unique';
|
||||
export * from './update-css-variables';
|
||||
export * from './util';
|
||||
export * from './window';
|
||||
export { get, isEqual, set } from 'es-toolkit/compat';
|
||||
// export { cloneDeep } from 'es-toolkit/object';
|
||||
export { default as cloneDeep } from 'lodash.clonedeep';
|
||||
export { default as get } from 'lodash.get';
|
||||
export { default as isEqual } from 'lodash.isequal';
|
||||
export { default as set } from 'lodash.set';
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// eslint-disable-next-line vue/prefer-import-from-vue
|
||||
import { isFunction, isObject, isString } from '@vue/shared';
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* @zh_CN 栈数据结构
|
||||
*/
|
||||
export class Stack<T> {
|
||||
/**
|
||||
* @zh_CN 栈内元素数量
|
||||
*/
|
||||
get size() {
|
||||
return this.items.length;
|
||||
}
|
||||
/**
|
||||
* @zh_CN 是否去重
|
||||
*/
|
||||
private readonly dedup: boolean;
|
||||
/**
|
||||
* @zh_CN 栈内元素
|
||||
*/
|
||||
private items: T[] = [];
|
||||
|
||||
/**
|
||||
* @zh_CN 栈的最大容量
|
||||
*/
|
||||
private readonly maxSize?: number;
|
||||
|
||||
constructor(dedup = true, maxSize?: number) {
|
||||
this.maxSize = maxSize;
|
||||
this.dedup = dedup;
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh_CN 清空栈内元素
|
||||
*/
|
||||
clear() {
|
||||
this.items.length = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh_CN 查看栈顶元素
|
||||
* @returns 栈顶元素
|
||||
*/
|
||||
peek(): T | undefined {
|
||||
return this.items[this.items.length - 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh_CN 出栈
|
||||
* @returns 栈顶元素
|
||||
*/
|
||||
pop(): T | undefined {
|
||||
return this.items.pop();
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh_CN 入栈
|
||||
* @param items 要入栈的元素
|
||||
*/
|
||||
push(...items: T[]) {
|
||||
items.forEach((item) => {
|
||||
// 去重
|
||||
if (this.dedup) {
|
||||
const index = this.items.indexOf(item);
|
||||
if (index !== -1) {
|
||||
this.items.splice(index, 1);
|
||||
}
|
||||
}
|
||||
this.items.push(item);
|
||||
if (this.maxSize && this.items.length > this.maxSize) {
|
||||
this.items.splice(0, this.items.length - this.maxSize);
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @zh_CN 移除栈内元素
|
||||
* @param itemList 要移除的元素列表
|
||||
*/
|
||||
remove(...itemList: T[]) {
|
||||
this.items = this.items.filter((i) => !itemList.includes(i));
|
||||
}
|
||||
/**
|
||||
* @zh_CN 保留栈内元素
|
||||
* @param itemList 要保留的元素列表
|
||||
*/
|
||||
retain(itemList: T[]) {
|
||||
this.items = this.items.filter((i) => itemList.includes(i));
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh_CN 转换为数组
|
||||
* @returns 栈内元素数组
|
||||
*/
|
||||
toArray(): T[] {
|
||||
return [...this.items];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh_CN 创建一个栈实例
|
||||
* @param dedup 是否去重
|
||||
* @param maxSize 栈的最大容量
|
||||
* @returns 栈实例
|
||||
*/
|
||||
export const createStack = <T>(dedup = true, maxSize?: number) =>
|
||||
new Stack<T>(dedup, maxSize);
|
||||
@@ -1,6 +1,6 @@
|
||||
export class StateHandler {
|
||||
private condition: boolean = false;
|
||||
private rejectCondition: (() => void) | null = null;
|
||||
private rejectCondition: ((reason?: Error) => void) | null = null;
|
||||
private resolveCondition: (() => void) | null = null;
|
||||
|
||||
isConditionTrue(): boolean {
|
||||
@@ -16,7 +16,7 @@ export class StateHandler {
|
||||
setConditionFalse() {
|
||||
this.condition = false;
|
||||
if (this.rejectCondition) {
|
||||
this.rejectCondition();
|
||||
this.rejectCondition(new Error('Condition was set to false'));
|
||||
this.clearPromises();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,4 +94,33 @@ function mapTree<T, V extends Record<string, any>>(
|
||||
});
|
||||
}
|
||||
|
||||
export { filterTree, mapTree, traverseTreeValues };
|
||||
/**
|
||||
* 对树形结构数据进行递归排序
|
||||
* @param treeData - 树形数据数组
|
||||
* @param sortFunction - 排序函数,用于定义排序规则
|
||||
* @param options - 配置选项,包括子节点属性名
|
||||
* @returns 排序后的树形数据
|
||||
*/
|
||||
function sortTree<T extends Record<string, any>>(
|
||||
treeData: T[],
|
||||
sortFunction: (a: T, b: T) => number,
|
||||
options?: TreeConfigOptions,
|
||||
): T[] {
|
||||
const { childProps } = options || {
|
||||
childProps: 'children',
|
||||
};
|
||||
|
||||
// 不用 Array.toSorted:Chrome <110 无此 API,登录后生成菜单会直接抛错卡住
|
||||
return [...treeData].sort(sortFunction).map((item) => {
|
||||
const children = item[childProps];
|
||||
if (children && Array.isArray(children) && children.length > 0) {
|
||||
return {
|
||||
...item,
|
||||
[childProps]: sortTree(children, sortFunction, options),
|
||||
};
|
||||
}
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export { filterTree, mapTree, sortTree, traverseTreeValues };
|
||||
|
||||
@@ -30,7 +30,7 @@ function openWindow(url: string, options: OpenWindowOptions = {}): void {
|
||||
function openRouteInNewWindow(path: string) {
|
||||
const { hash, origin } = location;
|
||||
const fullPath = path.startsWith('/') ? path : `/${path}`;
|
||||
const url = `${origin}${hash ? '/#' : ''}${fullPath}`;
|
||||
const url = `${origin}${hash && !fullPath.startsWith('/#') ? '/#' : ''}${fullPath}`;
|
||||
openWindow(url, { target: '_blank' });
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { defineConfig } from 'tsdown';
|
||||
|
||||
export default defineConfig({
|
||||
clean: true,
|
||||
dts: true,
|
||||
entry: {
|
||||
'cache/index': 'src/cache/index.ts',
|
||||
'color/index': 'src/color/index.ts',
|
||||
'constants/index': 'src/constants/index.ts',
|
||||
'global-state': 'src/global-state.ts',
|
||||
store: 'src/store.ts',
|
||||
'utils/index': 'src/utils/index.ts',
|
||||
},
|
||||
format: ['esm'],
|
||||
outExtensions: () => ({
|
||||
dts: '.d.ts',
|
||||
}),
|
||||
});
|
||||
Reference in New Issue
Block a user