Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 41c36f111c |
@@ -677,7 +677,7 @@ src/pages/StorageCleaner/useStorageCleaner.ts — 页面级 Hook
|
|||||||
label: '时间戳转换',
|
label: '时间戳转换',
|
||||||
description: '日期与时间戳互转',
|
description: '日期与时间戳互转',
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
component: TimestampPage,
|
components: { popup: TimestampPage, sidepanel: TimestampPage, tab: TimestampPage },
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -764,7 +764,7 @@ const [themeMode, setThemeMode, isInitialized] = useStorageState(
|
|||||||
Chrome Storage 读取是异步的。项目通过 `localStorage` 快照(键名 `snapshot/{storageKey}`)提供同步初始值,消除首屏闪烁。
|
Chrome Storage 读取是异步的。项目通过 `localStorage` 快照(键名 `snapshot/{storageKey}`)提供同步初始值,消除首屏闪烁。
|
||||||
|
|
||||||
| 模块 | 快照工具 | 防覆盖机制 |
|
| 模块 | 快照工具 | 防覆盖机制 |
|
||||||
| ------------------- | ------------------ | ----------------------------------------------------------------------------------------- |
|
| ---- | -------- | ---------- |
|
||||||
| `RouterProvider` | `syncSnapshot.ts` | `canPersistRef`(加载成功后才写入)、`hasUserNavigatedRef`(用户导航后不被 storage 覆盖) |
|
| `RouterProvider` | `syncSnapshot.ts` | `canPersistRef`(加载成功后才写入)、`hasUserNavigatedRef`(用户导航后不被 storage 覆盖) |
|
||||||
| `useStorageState` | `syncSnapshot.ts` | `loadSucceededRef` 或 `userModifiedRef` 为 true 时才写入 |
|
| `useStorageState` | `syncSnapshot.ts` | `loadSucceededRef` 或 `userModifiedRef` 为 true 时才写入 |
|
||||||
| `ThemeModeProvider` | `themeSnapshot.ts` | `hasUserSetMode`(用户切换主题后不被 storage 覆盖) |
|
| `ThemeModeProvider` | `themeSnapshot.ts` | `hasUserSetMode`(用户切换主题后不被 storage 覆盖) |
|
||||||
|
|||||||
@@ -29,20 +29,3 @@
|
|||||||
- 导出工具:`src/utils/dataExporter.ts`
|
- 导出工具:`src/utils/dataExporter.ts`
|
||||||
|
|
||||||
实现约束与任务完成状态记录在 [TASKS.md](./TASKS.md)。
|
实现约束与任务完成状态记录在 [TASKS.md](./TASKS.md)。
|
||||||
|
|
||||||
## 开发者注意事项(与源码同步)
|
|
||||||
|
|
||||||
以下行为以 `src/` 源码为准;设计文档中的旧版 class API、`metadata`/`options` 嵌套结构已废弃。
|
|
||||||
|
|
||||||
### Worker 任务 ID(`generationId`)
|
|
||||||
|
|
||||||
`useGenerator` 每次调用 `generate()` 递增 `generationIdRef`,经 `start` 消息传入 Worker。Worker 所有响应(`progress` / `complete` / `error`)均携带同一 `generationId`。
|
|
||||||
|
|
||||||
- **取消**:`cancel()` 先递增 ID 再发送 `cancel`,使进行中的 Worker 响应被主线程忽略;Worker 每生成 100 行让出事件循环以处理 cancel。
|
|
||||||
- **快速重试**:新任务 ID 大于旧响应时,旧消息被丢弃,避免 UI 状态错乱。
|
|
||||||
|
|
||||||
类型见 `WorkerRequestMessage` / `WorkerResponseMessage`(`src/types/testDataGenerator.ts`)。
|
|
||||||
|
|
||||||
### 规则存储写入失败
|
|
||||||
|
|
||||||
`ruleStorage.save()` / `update()` 在 `localStorage.setItem` 失败时返回 `null`(不部分提交)。页面层(如 `FieldList.tsx`)仅在返回值非空时 Toast 成功。详见 [rule-management.md § 存储机制](./rule-management.md#存储机制) 与 `src/utils/README.md`。
|
|
||||||
|
|||||||
@@ -24,20 +24,25 @@
|
|||||||
|
|
||||||
## 数据结构
|
## 数据结构
|
||||||
|
|
||||||
> **与源码对齐**:类型定义见 `src/types/testDataGenerator.ts`。规则**不**持久化生成数量与导出格式(由页面 `GenerateOptions` 状态管理)。
|
|
||||||
|
|
||||||
### 规则模板
|
### 规则模板
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
interface DataRule {
|
interface DataRule {
|
||||||
id: string;
|
id: string; // 唯一标识
|
||||||
name: string;
|
name: string; // 规则名称
|
||||||
description?: string;
|
description?: string; // 规则描述
|
||||||
fields: FieldConfig[];
|
fields: FieldConfig[]; // 字段配置
|
||||||
createdAt: number;
|
options: {
|
||||||
updatedAt: number;
|
total: number; // 生成数量
|
||||||
lastUsedAt?: number;
|
format: 'json' | 'csv';
|
||||||
useCount: number;
|
defaultEmptyRate: number; // 默认空值率(0-100)
|
||||||
|
};
|
||||||
|
metadata: {
|
||||||
|
createdAt: number; // 创建时间
|
||||||
|
updatedAt: number; // 更新时间
|
||||||
|
lastUsedAt?: number; // 最后使用时间
|
||||||
|
useCount: number; // 使用次数
|
||||||
|
};
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -45,14 +50,13 @@ interface DataRule {
|
|||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
interface FieldConfig {
|
interface FieldConfig {
|
||||||
id: string;
|
id: string; // 字段唯一标识
|
||||||
name: string;
|
name: string; // 字段名
|
||||||
description?: string;
|
generator: string; // 生成器名称
|
||||||
generatorId: string; // 生成器 ID,对应 lib/generators 中的 id
|
params: Record<string, any>; // 生成器参数
|
||||||
params: Record<string, unknown>;
|
unique: boolean; // 唯一性约束
|
||||||
required: boolean;
|
required: boolean; // 是否必填
|
||||||
nullRate: number; // 空值率 0-100,仅 required=false 时生效
|
emptyRate?: number; // 选填字段的空值概率(0-100)
|
||||||
unique: boolean;
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -106,9 +110,11 @@ interface FieldConfig {
|
|||||||
|
|
||||||
1. 验证规则名称不为空
|
1. 验证规则名称不为空
|
||||||
2. 检查规则数量是否达到上限(20 条)
|
2. 检查规则数量是否达到上限(20 条)
|
||||||
3. 若达上限,`save()` 返回 `null`,UI 应阻止或提示
|
3. 如果达到上限,显示提示"已达到最大规则数量"
|
||||||
4. 生成唯一 ID,写入 `createdAt`/`updatedAt`,`useCount` 初始为 0
|
4. 生成唯一 ID
|
||||||
5. 调用 `ruleStorage.save()`;仅当返回值非 `null` 时视为成功(`localStorage` 写入失败同样返回 `null`)
|
5. 设置创建时间和更新时间
|
||||||
|
6. 初始化使用次数为 0
|
||||||
|
7. 保存到 localStorage
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -161,13 +167,17 @@ interface FieldConfig {
|
|||||||
- 支持按规则描述搜索
|
- 支持按规则描述搜索
|
||||||
- 搜索为模糊匹配,不区分大小写
|
- 搜索为模糊匹配,不区分大小写
|
||||||
|
|
||||||
**实现方式**(`src/utils/ruleStorage.ts`):
|
**实现方式**:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import * as ruleStorage from '@/utils/ruleStorage';
|
search(keyword: string): DataRule[] {
|
||||||
|
const rules = this.getAll();
|
||||||
|
const lowerKeyword = keyword.toLowerCase();
|
||||||
|
|
||||||
function searchRules(query: string): DataRule[] {
|
return rules.filter(r =>
|
||||||
return ruleStorage.search(query);
|
r.name.toLowerCase().includes(lowerKeyword) ||
|
||||||
|
r.description?.toLowerCase().includes(lowerKeyword)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -214,7 +224,9 @@ function searchRules(query: string): DataRule[] {
|
|||||||
|
|
||||||
1. 加载原规则配置到编辑器
|
1. 加载原规则配置到编辑器
|
||||||
2. 用户修改配置
|
2. 用户修改配置
|
||||||
3. 点击保存时调用 `ruleStorage.update()`;返回非 `null` 才更新 `updatedAt` 并提示成功
|
3. 点击保存时更新规则
|
||||||
|
4. 更新 metadata.updatedAt
|
||||||
|
5. 保存到 localStorage
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -257,12 +269,18 @@ function searchRules(query: string): DataRule[] {
|
|||||||
**实现方式**:
|
**实现方式**:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
function loadRule(ruleId: string): void {
|
loadRule(ruleId: string): void {
|
||||||
const rule = ruleStorage.getById(ruleId);
|
const rule = this.storage.getById(ruleId);
|
||||||
if (!rule) return;
|
|
||||||
|
|
||||||
setFields(rule.fields);
|
// 应用规则配置
|
||||||
ruleStorage.recordUse(ruleId);
|
this.setFields(rule.fields);
|
||||||
|
this.setOptions(rule.options);
|
||||||
|
|
||||||
|
// 记录使用
|
||||||
|
this.storage.recordUse(ruleId);
|
||||||
|
|
||||||
|
// 更新预览
|
||||||
|
this.updatePreview();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -274,7 +292,7 @@ function loadRule(ruleId: string): void {
|
|||||||
|
|
||||||
1. 点击"复制"按钮
|
1. 点击"复制"按钮
|
||||||
2. 创建规则的副本
|
2. 创建规则的副本
|
||||||
3. 名称添加「(副本)」后缀(默认 `duplicate(id, '(副本)')`)
|
3. 名称添加"(副本)"后缀
|
||||||
4. 生成新的 ID
|
4. 生成新的 ID
|
||||||
5. 保存为新规则
|
5. 保存为新规则
|
||||||
|
|
||||||
@@ -309,20 +327,23 @@ function loadRule(ruleId: string): void {
|
|||||||
└─────────────────────────────────────────────────────────────────────┘
|
└─────────────────────────────────────────────────────────────────────┘
|
||||||
```
|
```
|
||||||
|
|
||||||
**导出格式**(`exportRules()` 返回 `DataRule[]` 的 JSON 字符串,无外层包装):
|
**导出格式**:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
[
|
{
|
||||||
|
"version": "1.0",
|
||||||
|
"exportedAt": "2024-01-20T10:15:45.000Z",
|
||||||
|
"rules": [
|
||||||
{
|
{
|
||||||
"id": "rule_123456",
|
"id": "rule_123456",
|
||||||
"name": "电商用户数据 - 测试用",
|
"name": "电商用户数据 - 测试用",
|
||||||
"description": "用于测试用户注册功能",
|
"description": "用于测试用户注册功能",
|
||||||
"fields": [],
|
"fields": [...],
|
||||||
"createdAt": 1704067200000,
|
"options": {...},
|
||||||
"updatedAt": 1704067200000,
|
"metadata": {...}
|
||||||
"useCount": 0
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -380,25 +401,63 @@ function loadRule(ruleId: string): void {
|
|||||||
|
|
||||||
### 本地存储
|
### 本地存储
|
||||||
|
|
||||||
使用 `localStorage`,键名 `testDataGenerator_rules`。API 为**命名导出函数**(见 `src/utils/ruleStorage.ts`):
|
使用 localStorage 存储规则数据:
|
||||||
|
|
||||||
| 函数 | 说明 |
|
|
||||||
| ---- | ---- |
|
|
||||||
| `getAll()` / `getById()` / `getByName()` | 读取 |
|
|
||||||
| `save()` / `update()` / `deleteRule()` / `duplicate()` | 写入;失败时返回 `null` 或 `false` |
|
|
||||||
| `recordUse()` | 递增 `useCount`、更新 `lastUsedAt` |
|
|
||||||
| `search()` / `getRecent()` | 搜索与最近使用 |
|
|
||||||
| `exportRules()` / `importRules()` | 导入导出 JSON 数组 |
|
|
||||||
| `clear()` | 清空全部规则 |
|
|
||||||
|
|
||||||
写入失败(如 `QuotaExceededError`)时,内部 `setAll()` 返回 `false`,`save`/`update` 返回 `null`,`deleteRule` 返回 `false`,并在控制台输出 `[ruleStorage] 保存规则失败`。调用方须检查返回值,避免误报成功。
|
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import * as ruleStorage from '@/utils/ruleStorage';
|
class RuleStorage {
|
||||||
|
private readonly STORAGE_KEY = 'testDataGenerator_rules';
|
||||||
|
|
||||||
const saved = ruleStorage.save({ name: '示例', fields });
|
// 获取所有规则
|
||||||
if (!saved) {
|
getAll(): DataRule[] {
|
||||||
// 达上限或 localStorage 不可用
|
const data = localStorage.getItem(this.STORAGE_KEY);
|
||||||
|
return data ? JSON.parse(data) : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 保存规则
|
||||||
|
save(rule: DataRule): { success: boolean; message?: string } {
|
||||||
|
const rules = this.getAll();
|
||||||
|
|
||||||
|
// 规则数量限制:最多 20 条
|
||||||
|
const MAX_RULES = 20;
|
||||||
|
if (rules.length >= MAX_RULES) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: `已达到最大规则数量(${MAX_RULES}条),请删除一些规则后再保存`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
rules.push(rule);
|
||||||
|
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(rules));
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新规则
|
||||||
|
update(id: string, updates: Partial<DataRule>): void {
|
||||||
|
const rules = this.getAll();
|
||||||
|
const index = rules.findIndex((r) => r.id === id);
|
||||||
|
if (index !== -1) {
|
||||||
|
rules[index] = { ...rules[index], ...updates };
|
||||||
|
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(rules));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 删除规则
|
||||||
|
delete(id: string): void {
|
||||||
|
const rules = this.getAll();
|
||||||
|
const filtered = rules.filter((r) => r.id !== id);
|
||||||
|
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(filtered));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 记录使用
|
||||||
|
recordUse(id: string): void {
|
||||||
|
const rules = this.getAll();
|
||||||
|
const rule = rules.find((r) => r.id === id);
|
||||||
|
if (rule) {
|
||||||
|
rule.metadata.lastUsedAt = Date.now();
|
||||||
|
rule.metadata.useCount++;
|
||||||
|
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(rules));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
# 技术实现
|
# 技术实现
|
||||||
|
|
||||||
> **文档同步说明**:本文档含早期设计稿代码示例,部分类型/API 已与实现偏离。开发时请以 `src/types/testDataGenerator.ts`、`src/workers/generator.worker.ts`、`src/pages/TestDataGenerator/hooks/useGenerator.ts`、`src/utils/ruleStorage.ts` 为准。近期变更摘要见 [README § 开发者注意事项](./README.md#开发者注意事项与源码同步)。
|
|
||||||
|
|
||||||
## 技术栈
|
## 技术栈
|
||||||
|
|
||||||
| 技术 | 用途 | 版本 |
|
| 技术 | 用途 | 版本 |
|
||||||
@@ -1500,69 +1498,6 @@ export class DataExporter {
|
|||||||
|
|
||||||
## Web Worker 使用
|
## Web Worker 使用
|
||||||
|
|
||||||
### 消息协议
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
// src/types/testDataGenerator.ts
|
|
||||||
|
|
||||||
type WorkerRequestMessage =
|
|
||||||
| { type: 'start'; payload: WorkerStartPayload }
|
|
||||||
| { type: 'cancel' };
|
|
||||||
|
|
||||||
type WorkerResponseMessage =
|
|
||||||
| { type: 'progress'; generationId: number; payload: GenerateProgress }
|
|
||||||
| { type: 'complete'; generationId: number; payload: GenerateResult }
|
|
||||||
| { type: 'error'; generationId: number; payload: { error: string } };
|
|
||||||
|
|
||||||
interface WorkerStartPayload {
|
|
||||||
generationId: number; // 任务 ID,用于忽略过期响应
|
|
||||||
fields: FieldConfig[];
|
|
||||||
count: number;
|
|
||||||
csvMode: boolean;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### useGenerator Hook
|
|
||||||
|
|
||||||
`src/pages/TestDataGenerator/hooks/useGenerator.ts` 负责 Worker 生命周期与 `generationId` 管理:
|
|
||||||
|
|
||||||
- Worker **复用**:同一 Hook 实例内只创建一次,出错后 `terminate` 并在下次重建
|
|
||||||
- **开始生成**:`generate(fields, count, csvMode?)` 递增 `generationId` 并 post `start`
|
|
||||||
- **取消**:`cancel()` 递增 ID(使旧响应失效)并 post `cancel`;取消完成的 `complete` 不写入 `error` 状态
|
|
||||||
- **响应过滤**:`onmessage` 中若 `data.generationId !== generationIdRef.current` 则忽略
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
const generate = (fields: FieldConfig[], count: number, csvMode = false) => {
|
|
||||||
if (isGenerating) return;
|
|
||||||
const generationId = ++generationIdRef.current;
|
|
||||||
worker.postMessage({ type: 'start', payload: { generationId, fields, count, csvMode } });
|
|
||||||
};
|
|
||||||
|
|
||||||
const cancel = () => {
|
|
||||||
if (workerRef.current && isGenerating) {
|
|
||||||
++generationIdRef.current;
|
|
||||||
worker.postMessage({ type: 'cancel' });
|
|
||||||
setIsGenerating(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
### Worker 实现要点
|
|
||||||
|
|
||||||
`src/workers/generator.worker.ts`:
|
|
||||||
|
|
||||||
- 按 `field.generatorId` 查找生成器;选填字段按 `nullRate` 随机置 `null`
|
|
||||||
- 唯一性:≤1000 条随机+重试;>1000 条优先 `generateAtIndex`
|
|
||||||
- 每 `YIELD_EVERY`(100)行 `await setTimeout(0)`,以便处理 `cancel`
|
|
||||||
- 进度:每 1000 条或最后一行 post `progress`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Web Worker 使用(历史设计稿,仅供参考)
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>展开查看旧版设计示例(与当前实现不一致)</summary>
|
|
||||||
|
|
||||||
### 创建 Worker
|
### 创建 Worker
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
@@ -1658,7 +1593,7 @@ export function useGenerator() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 错误处理(设计稿,`useErrorHandler.ts` 未实现)
|
### 错误处理
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// src/pages/TestDataGenerator/hooks/useErrorHandler.ts
|
// src/pages/TestDataGenerator/hooks/useErrorHandler.ts
|
||||||
@@ -1701,12 +1636,8 @@ export function useErrorHandler(options: ErrorHandlerOptions = {}) {
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
## 错误提示机制
|
## 错误提示机制
|
||||||
|
|
||||||
> 当前实现:`TestDataGenerator/index.tsx` 直接使用 `useGenerator` 的 `error`/`result` 与 `ResultPanel` 展示警告;下方示例引用未实现的 `useErrorHandler`,仅供对照。
|
|
||||||
|
|
||||||
### 错误类型分类
|
### 错误类型分类
|
||||||
|
|
||||||
| 错误类型 | 严重程度 | 触发场景 | 提示方式 |
|
| 错误类型 | 严重程度 | 触发场景 | 提示方式 |
|
||||||
|
|||||||
@@ -57,11 +57,7 @@ export function ErrorFallback({
|
|||||||
<h3 className="text-base font-semibold text-foreground mb-1.5">{title}</h3>
|
<h3 className="text-base font-semibold text-foreground mb-1.5">{title}</h3>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<p
|
<p className={cn('text-muted-foreground', isApp ? 'text-sm mb-6' : 'text-xs mb-5')}>
|
||||||
className={
|
|
||||||
isApp ? 'text-sm text-muted-foreground mb-6' : 'text-xs text-muted-foreground mb-5'
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{description}
|
{description}
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
@@ -87,7 +83,7 @@ export function ErrorFallback({
|
|||||||
variant="destructive"
|
variant="destructive"
|
||||||
size={isApp ? 'default' : 'sm'}
|
size={isApp ? 'default' : 'sm'}
|
||||||
onClick={onAction}
|
onClick={onAction}
|
||||||
className={isApp ? 'rounded-lg font-bold shadow-sm' : 'font-medium shadow-sm'}
|
className={cn(isApp ? 'rounded-lg font-bold shadow-sm' : 'font-medium shadow-sm')}
|
||||||
>
|
>
|
||||||
<RefreshCw className={isApp ? 'mr-2 h-4 w-4' : 'mr-1.5 h-3.5 w-3.5'} />
|
<RefreshCw className={isApp ? 'mr-2 h-4 w-4' : 'mr-1.5 h-3.5 w-3.5'} />
|
||||||
{actionLabel}
|
{actionLabel}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
| `SwitchButtonGroup.tsx` | 通用切换按钮组,支持 `small/medium/large` 三种尺寸,用于页面子模式切换 |
|
| `SwitchButtonGroup.tsx` | 通用切换按钮组,支持 `small/medium/large` 三种尺寸,用于页面子模式切换 |
|
||||||
| `EmptyPlaceholder.tsx` | 虚线边框空状态占位,统一工具页「暂无结果」提示样式 |
|
| `EmptyPlaceholder.tsx` | 虚线边框空状态占位,统一工具页「暂无结果」提示样式 |
|
||||||
| `TextInputArea.tsx` | 增强文本输入区域,支持校验规则、工具栏操作、字符计数、清空 |
|
| `TextInputArea.tsx` | 增强文本输入区域,支持校验规则、工具栏操作、字符计数、清空 |
|
||||||
| `CopyButton.tsx` | 一键复制按钮:复制成功后 1.5s 内切换为 Check 图标并应用 `text-emerald-500`;空内容/失败时 `toast` 提示 |
|
| `CopyButton.tsx` | 一键复制按钮,支持复制成功状态动画,封装 `copyTextToClipboard` 和 `toast` 反馈 |
|
||||||
| `ImageUploader.tsx` | 图片上传组件,支持拖拽上传、文件选择和预览 |
|
| `ImageUploader.tsx` | 图片上传组件,支持拖拽上传、文件选择和预览 |
|
||||||
| `QrCodePreview.tsx` | 二维码预览组件,展示生成的二维码图片,提供复制和下载操作 |
|
| `QrCodePreview.tsx` | 二维码预览组件,展示生成的二维码图片,提供复制和下载操作 |
|
||||||
| `DecodeResultPaper.tsx` | Base64 解码结果展示面板,显示 MIME 类型、文件大小、文件名输入和下载按钮 |
|
| `DecodeResultPaper.tsx` | Base64 解码结果展示面板,显示 MIME 类型、文件大小、文件名输入和下载按钮 |
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { FEATURES } from '@/config/features';
|
import { FEATURES, getEntryPointType } from '@/config/features';
|
||||||
import { useRouter } from '@/providers/RouterProvider';
|
import { useRouter } from '@/providers/RouterProvider';
|
||||||
import { Suspense } from 'react';
|
import { Suspense } from 'react';
|
||||||
import PageErrorBoundary from '@/components/PageErrorBoundary';
|
import PageErrorBoundary from '@/components/PageErrorBoundary';
|
||||||
@@ -6,6 +6,8 @@ import PageSkeleton from '@/components/PageSkeleton';
|
|||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { AlertTriangle } from 'lucide-react';
|
import { AlertTriangle } from 'lucide-react';
|
||||||
|
|
||||||
|
const entryPointType = getEntryPointType();
|
||||||
|
|
||||||
export default function RouterContainer() {
|
export default function RouterContainer() {
|
||||||
const { currentPage, isLoaded } = useRouter();
|
const { currentPage, isLoaded } = useRouter();
|
||||||
|
|
||||||
@@ -17,7 +19,7 @@ export default function RouterContainer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const currentFeature = FEATURES.find((f) => f.key === currentPage);
|
const currentFeature = FEATURES.find((f) => f.key === currentPage);
|
||||||
const MatchedComponent = currentFeature?.component;
|
const MatchedComponent = currentFeature?.components?.[entryPointType];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
@@ -41,7 +43,7 @@ export default function RouterContainer() {
|
|||||||
</div>
|
</div>
|
||||||
<h3 className="text-sm font-semibold text-foreground">页面未找到</h3>
|
<h3 className="text-sm font-semibold text-foreground">页面未找到</h3>
|
||||||
<p className="text-xs text-muted-foreground mt-1 max-w-[240px]">
|
<p className="text-xs text-muted-foreground mt-1 max-w-[240px]">
|
||||||
该功能不存在或已被移除。
|
{`该功能在当前运行环境(${entryPointType})下不可用或已被移除。`}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ const Checkbox = React.forwardRef<
|
|||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<CheckboxPrimitive.Indicator className="grid place-content-center text-current">
|
<CheckboxPrimitive.Indicator className={cn('grid place-content-center text-current')}>
|
||||||
<Check className="h-4 w-4" />
|
<Check className="h-4 w-4" />
|
||||||
</CheckboxPrimitive.Indicator>
|
</CheckboxPrimitive.Indicator>
|
||||||
</CheckboxPrimitive.Root>
|
</CheckboxPrimitive.Root>
|
||||||
|
|||||||
@@ -72,7 +72,7 @@ describe('features 懒加载', () => {
|
|||||||
const { render, waitFor } = await import('@testing-library/react');
|
const { render, waitFor } = await import('@testing-library/react');
|
||||||
const { FEATURES } = await import('@/config/features');
|
const { FEATURES } = await import('@/config/features');
|
||||||
|
|
||||||
const DashboardPage = FEATURES.find((f) => f.key === 'dashboard')!.component;
|
const DashboardPage = FEATURES.find((f) => f.key === 'dashboard')!.components.popup;
|
||||||
|
|
||||||
render(
|
render(
|
||||||
React.createElement(React.Suspense, { fallback: null }, React.createElement(DashboardPage)),
|
React.createElement(React.Suspense, { fallback: null }, React.createElement(DashboardPage)),
|
||||||
|
|||||||
@@ -19,13 +19,15 @@ describe('features', () => {
|
|||||||
expect(feature).toHaveProperty('label');
|
expect(feature).toHaveProperty('label');
|
||||||
expect(feature).toHaveProperty('description');
|
expect(feature).toHaveProperty('description');
|
||||||
expect(feature).toHaveProperty('defaultVisible');
|
expect(feature).toHaveProperty('defaultVisible');
|
||||||
expect(feature).toHaveProperty('component');
|
expect(feature).toHaveProperty('components');
|
||||||
expect(typeof feature.key).toBe('string');
|
expect(typeof feature.key).toBe('string');
|
||||||
expect(typeof feature.label).toBe('string');
|
expect(typeof feature.label).toBe('string');
|
||||||
expect(typeof feature.description).toBe('string');
|
expect(typeof feature.description).toBe('string');
|
||||||
expect(typeof feature.defaultVisible).toBe('boolean');
|
expect(typeof feature.defaultVisible).toBe('boolean');
|
||||||
expect(feature.component).toBeDefined();
|
expect(typeof feature.components).toBe('object');
|
||||||
expect(['function', 'object']).toContain(typeof feature.component);
|
expect(feature.components).toHaveProperty('popup');
|
||||||
|
expect(feature.components).toHaveProperty('sidepanel');
|
||||||
|
expect(feature.components).toHaveProperty('tab');
|
||||||
|
|
||||||
if (feature.key !== 'dashboard') {
|
if (feature.key !== 'dashboard') {
|
||||||
expect(feature).toHaveProperty('icon');
|
expect(feature).toHaveProperty('icon');
|
||||||
|
|||||||
+55
-11
@@ -34,7 +34,11 @@ export interface FeatureConfig {
|
|||||||
themeColorKey?: PaletteColorKey;
|
themeColorKey?: PaletteColorKey;
|
||||||
icon?: ComponentType<LucideProps>;
|
icon?: ComponentType<LucideProps>;
|
||||||
defaultVisible: boolean;
|
defaultVisible: boolean;
|
||||||
component: ComponentType;
|
components: {
|
||||||
|
popup: ComponentType;
|
||||||
|
sidepanel: ComponentType;
|
||||||
|
tab: ComponentType;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export const FEATURES: FeatureConfig[] = [
|
export const FEATURES: FeatureConfig[] = [
|
||||||
@@ -43,7 +47,11 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
label: '仪表盘',
|
label: '仪表盘',
|
||||||
description: '',
|
description: '',
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
component: DashboardPage,
|
components: {
|
||||||
|
popup: DashboardPage,
|
||||||
|
sidepanel: DashboardPage,
|
||||||
|
tab: DashboardPage,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'timestamp',
|
key: 'timestamp',
|
||||||
@@ -52,7 +60,11 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'primary',
|
themeColorKey: 'primary',
|
||||||
icon: Clock,
|
icon: Clock,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
component: TimestampPage,
|
components: {
|
||||||
|
popup: TimestampPage,
|
||||||
|
sidepanel: TimestampPage,
|
||||||
|
tab: TimestampPage,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'storageCleaner',
|
key: 'storageCleaner',
|
||||||
@@ -61,7 +73,11 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'warning',
|
themeColorKey: 'warning',
|
||||||
icon: Database,
|
icon: Database,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
component: StorageCleanerPage,
|
components: {
|
||||||
|
popup: StorageCleanerPage,
|
||||||
|
sidepanel: StorageCleanerPage,
|
||||||
|
tab: StorageCleanerPage,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'qrCode',
|
key: 'qrCode',
|
||||||
@@ -70,7 +86,11 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'success',
|
themeColorKey: 'success',
|
||||||
icon: QrCode,
|
icon: QrCode,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
component: QrCodePage,
|
components: {
|
||||||
|
popup: QrCodePage,
|
||||||
|
sidepanel: QrCodePage,
|
||||||
|
tab: QrCodePage,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'textStatistics',
|
key: 'textStatistics',
|
||||||
@@ -79,7 +99,11 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'secondary',
|
themeColorKey: 'secondary',
|
||||||
icon: FileText,
|
icon: FileText,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
component: TextStatisticsPage,
|
components: {
|
||||||
|
popup: TextStatisticsPage,
|
||||||
|
sidepanel: TextStatisticsPage,
|
||||||
|
tab: TextStatisticsPage,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'jwt',
|
key: 'jwt',
|
||||||
@@ -88,7 +112,11 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'info',
|
themeColorKey: 'info',
|
||||||
icon: Key,
|
icon: Key,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
component: JwtPage,
|
components: {
|
||||||
|
popup: JwtPage,
|
||||||
|
sidepanel: JwtPage,
|
||||||
|
tab: JwtPage,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'jsonTools',
|
key: 'jsonTools',
|
||||||
@@ -97,7 +125,11 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'primary',
|
themeColorKey: 'primary',
|
||||||
icon: GitCompareArrows,
|
icon: GitCompareArrows,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
component: JsonToolsPage,
|
components: {
|
||||||
|
popup: JsonToolsPage,
|
||||||
|
sidepanel: JsonToolsPage,
|
||||||
|
tab: JsonToolsPage,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'base64Converter',
|
key: 'base64Converter',
|
||||||
@@ -106,7 +138,11 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'info',
|
themeColorKey: 'info',
|
||||||
icon: ArrowLeftRight,
|
icon: ArrowLeftRight,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
component: Base64ConverterPage,
|
components: {
|
||||||
|
popup: Base64ConverterPage,
|
||||||
|
sidepanel: Base64ConverterPage,
|
||||||
|
tab: Base64ConverterPage,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'rightClickRestorer',
|
key: 'rightClickRestorer',
|
||||||
@@ -115,7 +151,11 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'success',
|
themeColorKey: 'success',
|
||||||
icon: MousePointerClick,
|
icon: MousePointerClick,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
component: RightClickRestorerPage,
|
components: {
|
||||||
|
popup: RightClickRestorerPage,
|
||||||
|
sidepanel: RightClickRestorerPage,
|
||||||
|
tab: RightClickRestorerPage,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'testDataGenerator',
|
key: 'testDataGenerator',
|
||||||
@@ -124,7 +164,11 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'warning',
|
themeColorKey: 'warning',
|
||||||
icon: FileSpreadsheet,
|
icon: FileSpreadsheet,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
component: TestDataGeneratorPage,
|
components: {
|
||||||
|
popup: TestDataGeneratorPage,
|
||||||
|
sidepanel: TestDataGeneratorPage,
|
||||||
|
tab: TestDataGeneratorPage,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -16,16 +16,16 @@ export default function SearchDropdown({
|
|||||||
selectedIndex,
|
selectedIndex,
|
||||||
onSelect,
|
onSelect,
|
||||||
}: SearchDropdownProps) {
|
}: SearchDropdownProps) {
|
||||||
const isSearching = !!searchQuery.trim();
|
const isSearching = searchQuery.trim().length > 0;
|
||||||
const items = isSearching ? searchResults : recentFeatures;
|
const items = isSearching ? searchResults : recentFeatures;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="absolute left-0 right-0 top-full z-50 mt-1.5 max-h-80 overflow-y-auto rounded-lg border border-border bg-popover text-popover-foreground shadow-lg animate-in fade-in slide-in-from-top-2 duration-150">
|
<div className="absolute left-0 right-0 top-full z-50 mt-1.5 max-h-80 overflow-y-auto rounded-lg border border-border bg-popover text-popover-foreground shadow-lg animate-in fade-in slide-in-from-top-2 duration-150">
|
||||||
<ul role="listbox" className="p-1.5">
|
<ul role="listbox" className="p-1.5">
|
||||||
{!isSearching && items.length > 0 && (
|
{!isSearching && items.length > 0 && (
|
||||||
<li className="px-3 py-1.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/60">
|
<div className="px-3 py-1.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/60">
|
||||||
最近搜索
|
最近搜索
|
||||||
</li>
|
</div>
|
||||||
)}
|
)}
|
||||||
{isSearching && items.length === 0 ? (
|
{isSearching && items.length === 0 ? (
|
||||||
<li className="px-4 py-6 text-center text-sm text-muted-foreground">未找到相关工具</li>
|
<li className="px-4 py-6 text-center text-sm text-muted-foreground">未找到相关工具</li>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { type KeyboardEvent, type RefObject } from 'react';
|
import { type RefObject } from 'react';
|
||||||
import { Search, X } from 'lucide-react';
|
import { Search, X } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
@@ -9,7 +9,7 @@ interface SearchInputProps {
|
|||||||
searchQuery: string;
|
searchQuery: string;
|
||||||
onSearchQueryChange: (value: string) => void;
|
onSearchQueryChange: (value: string) => void;
|
||||||
onFocus: () => void;
|
onFocus: () => void;
|
||||||
onKeyDown: (e: KeyboardEvent) => void;
|
onKeyDown: (e: React.KeyboardEvent) => void;
|
||||||
onClear: () => void;
|
onClear: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,6 +26,7 @@ export default function SearchInput({
|
|||||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/60 transition-colors group-focus-within:text-muted-foreground" />
|
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/60 transition-colors group-focus-within:text-muted-foreground" />
|
||||||
<Input
|
<Input
|
||||||
ref={inputRef}
|
ref={inputRef}
|
||||||
|
type="text"
|
||||||
placeholder="搜索工具..."
|
placeholder="搜索工具..."
|
||||||
value={searchQuery}
|
value={searchQuery}
|
||||||
onChange={(e) => onSearchQueryChange(e.target.value)}
|
onChange={(e) => onSearchQueryChange(e.target.value)}
|
||||||
@@ -34,7 +35,12 @@ export default function SearchInput({
|
|||||||
aria-label="搜索工具..."
|
aria-label="搜索工具..."
|
||||||
className="h-9 rounded-lg border-border/60 bg-muted/40 pl-9 pr-16 shadow-none focus-visible:ring-1 focus-visible:ring-offset-0 placeholder:text-muted-foreground/50"
|
className="h-9 rounded-lg border-border/60 bg-muted/40 pl-9 pr-16 shadow-none focus-visible:ring-1 focus-visible:ring-offset-0 placeholder:text-muted-foreground/50"
|
||||||
/>
|
/>
|
||||||
{searchQuery ? (
|
{!searchQuery && (
|
||||||
|
<kbd className="pointer-events-none absolute right-3 top-1/2 hidden h-5 -translate-y-1/2 items-center gap-0.5 rounded border border-border/60 bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground/60 sm:inline-flex">
|
||||||
|
{getSearchShortcutLabel()}
|
||||||
|
</kbd>
|
||||||
|
)}
|
||||||
|
{searchQuery && (
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
@@ -45,10 +51,6 @@ export default function SearchInput({
|
|||||||
>
|
>
|
||||||
<X className="h-3 w-3" />
|
<X className="h-3 w-3" />
|
||||||
</Button>
|
</Button>
|
||||||
) : (
|
|
||||||
<kbd className="pointer-events-none absolute right-3 top-1/2 hidden h-5 -translate-y-1/2 items-center rounded border border-border/60 bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground/60 sm:inline-flex">
|
|
||||||
{getSearchShortcutLabel()}
|
|
||||||
</kbd>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -33,7 +33,9 @@ export default function TopBar() {
|
|||||||
id: 'open-in-tab',
|
id: 'open-in-tab',
|
||||||
icon: ExternalLink,
|
icon: ExternalLink,
|
||||||
title: '在标签页打开',
|
title: '在标签页打开',
|
||||||
onClick: () => void handleOpenInTab(),
|
onClick: () => {
|
||||||
|
void handleOpenInTab();
|
||||||
|
},
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,4 @@
|
|||||||
import {
|
import { useEffect, useMemo, useRef, useState, type RefObject } from 'react';
|
||||||
useEffect,
|
|
||||||
useMemo,
|
|
||||||
useRef,
|
|
||||||
useState,
|
|
||||||
type KeyboardEvent as ReactKeyboardEvent,
|
|
||||||
type RefObject,
|
|
||||||
} from 'react';
|
|
||||||
import { Monitor, Moon, Sun } from 'lucide-react';
|
import { Monitor, Moon, Sun } from 'lucide-react';
|
||||||
import { useRouter } from '@/providers/RouterProvider';
|
import { useRouter } from '@/providers/RouterProvider';
|
||||||
import { useThemeMode } from '@/providers/ThemeModeProvider';
|
import { useThemeMode } from '@/providers/ThemeModeProvider';
|
||||||
@@ -28,7 +21,7 @@ export interface UseTopBarReturn {
|
|||||||
handleSearchQueryChange: (value: string) => void;
|
handleSearchQueryChange: (value: string) => void;
|
||||||
handleSearchFocus: () => void;
|
handleSearchFocus: () => void;
|
||||||
handleSelectFeature: (feature: FeatureConfig) => void;
|
handleSelectFeature: (feature: FeatureConfig) => void;
|
||||||
handleKeyDown: (e: ReactKeyboardEvent) => void;
|
handleKeyDown: (e: React.KeyboardEvent) => void;
|
||||||
cycleThemeMode: () => void;
|
cycleThemeMode: () => void;
|
||||||
handleOpenInTab: () => Promise<void>;
|
handleOpenInTab: () => Promise<void>;
|
||||||
goHome: () => void;
|
goHome: () => void;
|
||||||
@@ -87,7 +80,7 @@ export function useTopBar(): UseTopBarReturn {
|
|||||||
});
|
});
|
||||||
}, [searchQuery]);
|
}, [searchQuery]);
|
||||||
|
|
||||||
const recentFeatures = useMemo(() => {
|
const displayedHistory = useMemo(() => {
|
||||||
if (searchQuery.trim()) return [];
|
if (searchQuery.trim()) return [];
|
||||||
return searchHistory
|
return searchHistory
|
||||||
.slice(0, SEARCH_HISTORY_DISPLAY)
|
.slice(0, SEARCH_HISTORY_DISPLAY)
|
||||||
@@ -118,10 +111,8 @@ export function useTopBar(): UseTopBarReturn {
|
|||||||
const themeTitle =
|
const themeTitle =
|
||||||
mode === 'light' ? '切换到深色模式' : mode === 'dark' ? '切换到系统模式' : '切换到浅色模式';
|
mode === 'light' ? '切换到深色模式' : mode === 'dark' ? '切换到系统模式' : '切换到浅色模式';
|
||||||
|
|
||||||
const handleKeyDown = (e: ReactKeyboardEvent) => {
|
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||||
const isSearching = !!searchQuery.trim();
|
const totalItems = searchQuery.trim() ? searchResults.length : displayedHistory.length;
|
||||||
const items = isSearching ? searchResults : recentFeatures;
|
|
||||||
const totalItems = items.length;
|
|
||||||
|
|
||||||
if (e.key === 'ArrowDown') {
|
if (e.key === 'ArrowDown') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -131,12 +122,13 @@ export function useTopBar(): UseTopBarReturn {
|
|||||||
setSelectedIndex((prev) => (prev > 0 ? prev - 1 : prev));
|
setSelectedIndex((prev) => (prev > 0 ? prev - 1 : prev));
|
||||||
} else if (e.key === 'Enter') {
|
} else if (e.key === 'Enter') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
let feature: FeatureConfig | undefined;
|
const items = searchQuery.trim() ? searchResults : displayedHistory;
|
||||||
if (selectedIndex >= 0 && selectedIndex < totalItems) {
|
const feature =
|
||||||
feature = items[selectedIndex];
|
selectedIndex >= 0 && selectedIndex < totalItems
|
||||||
} else if (isSearching && searchResults.length > 0) {
|
? items[selectedIndex]
|
||||||
feature = searchResults[0];
|
: searchQuery.trim() && searchResults.length > 0
|
||||||
}
|
? searchResults[0]
|
||||||
|
: undefined;
|
||||||
if (feature) handleSelectFeature(feature);
|
if (feature) handleSelectFeature(feature);
|
||||||
} else if (e.key === 'Escape') {
|
} else if (e.key === 'Escape') {
|
||||||
setShowResults(false);
|
setShowResults(false);
|
||||||
@@ -157,12 +149,13 @@ export function useTopBar(): UseTopBarReturn {
|
|||||||
|
|
||||||
const handleSearchFocus = () => setShowResults(true);
|
const handleSearchFocus = () => setShowResults(true);
|
||||||
|
|
||||||
const showDropdown = showResults && (!!searchQuery.trim() || recentFeatures.length > 0);
|
const showDropdown =
|
||||||
|
showResults && (searchQuery.trim().length > 0 || displayedHistory.length > 0);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
searchQuery,
|
searchQuery,
|
||||||
searchResults,
|
searchResults,
|
||||||
recentFeatures,
|
recentFeatures: displayedHistory,
|
||||||
selectedIndex,
|
selectedIndex,
|
||||||
showDropdown,
|
showDropdown,
|
||||||
isDashboard: currentPage === 'dashboard',
|
isDashboard: currentPage === 'dashboard',
|
||||||
|
|||||||
+2
-1
@@ -1,5 +1,6 @@
|
|||||||
import { type ClassValue, clsx } from 'clsx';
|
import { type ClassValue, clsx } from 'clsx';
|
||||||
|
import { twMerge } from 'tailwind-merge';
|
||||||
|
|
||||||
export function cn(...inputs: ClassValue[]) {
|
export function cn(...inputs: ClassValue[]) {
|
||||||
return clsx(inputs);
|
return twMerge(clsx(inputs));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,9 +22,7 @@ vi.mock('../components/TextMode', () => ({
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock('../components/Base64ConverterSection', () => ({
|
vi.mock('../components/Base64ConverterSection', () => ({
|
||||||
default: ({ mode }: { mode: 'file' | 'image' }) => (
|
default: ({ mode }: { mode: string }) => <div data-testid={`${mode}-mode`}>{mode}</div>,
|
||||||
<div data-testid={`${mode}-mode`}>{mode.toUpperCase()} Mode</div>
|
|
||||||
),
|
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const waitForStorageInit = () =>
|
const waitForStorageInit = () =>
|
||||||
|
|||||||
@@ -50,6 +50,10 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
|
|||||||
setDirection(next);
|
setDirection(next);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleDownload = () => {
|
||||||
|
if (decoded) downloadBlob(decoded.blob, decodedFileName);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-full flex flex-col space-y-4 px-2">
|
<div className="w-full flex flex-col space-y-4 px-2">
|
||||||
<div className="flex h-11 items-center px-1.5 bg-secondary/40 rounded-xl border border-border/60 w-fit">
|
<div className="flex h-11 items-center px-1.5 bg-secondary/40 rounded-xl border border-border/60 w-fit">
|
||||||
@@ -111,7 +115,7 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<Upload className="w-8 h-8 text-primary" />
|
<Upload className={cn('w-8 h-8 text-primary')} />
|
||||||
<span className="text-sm font-bold text-foreground/90 max-w-[280px] truncate">
|
<span className="text-sm font-bold text-foreground/90 max-w-[280px] truncate">
|
||||||
{info.name}
|
{info.name}
|
||||||
</span>
|
</span>
|
||||||
@@ -133,11 +137,11 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
|
|||||||
{mode === 'image' ? '点击或拖拽图像到此处' : '点击或拖拽文件到此处'}
|
{mode === 'image' ? '点击或拖拽图像到此处' : '点击或拖拽文件到此处'}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-[10px] font-medium text-muted-foreground/60">
|
<span className="text-[10px] font-medium text-muted-foreground/60">
|
||||||
最大文件大小:{maxFileSizeStr}
|
{`最大文件大小:${maxFileSizeStr}`}
|
||||||
</span>
|
</span>
|
||||||
{mode === 'image' && (
|
{mode === 'image' && (
|
||||||
<span className="text-[10px] font-medium text-muted-foreground/50">
|
<span className="text-[10px] font-medium text-muted-foreground/50">
|
||||||
支持 PNG、JPG、WEBP、GIF、BMP、SVG 等格式
|
{'支持 PNG、JPG、WEBP、GIF、BMP、SVG 等格式'}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -227,7 +231,7 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
|
|||||||
blobSize={decoded.blob.size}
|
blobSize={decoded.blob.size}
|
||||||
fileName={decodedFileName}
|
fileName={decodedFileName}
|
||||||
onFileNameChange={setCustomFileName}
|
onFileNameChange={setCustomFileName}
|
||||||
onDownload={() => downloadBlob(decoded.blob, decodedFileName)}
|
onDownload={handleDownload}
|
||||||
>
|
>
|
||||||
{mode === 'image' && (
|
{mode === 'image' && (
|
||||||
<div className="relative p-1.5 border border-border bg-background dark:bg-muted/10 rounded-xl max-w-[220px] mb-3 overflow-hidden shadow-sm">
|
<div className="relative p-1.5 border border-border bg-background dark:bg-muted/10 rounded-xl max-w-[220px] mb-3 overflow-hidden shadow-sm">
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
|
import { cn } from '@/lib/utils';
|
||||||
import { useDashboard } from './useDashboard';
|
import { useDashboard } from './useDashboard';
|
||||||
|
|
||||||
export default function Index() {
|
export default function Index() {
|
||||||
const { visibleFeatures, recentFeatures, showRecent, navigateTo } = useDashboard();
|
const { visibleFeatures, recentFeatures, showRecent, navigateTo } = useDashboard();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-4 p-3.5 w-full h-auto select-none">
|
<div className={cn('flex flex-col gap-4 p-3.5 w-full h-auto select-none')}>
|
||||||
{showRecent && (
|
{showRecent && (
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
<h3 className="text-xs font-semibold text-muted-foreground/80 uppercase tracking-wider">
|
<h3 className="text-xs font-semibold text-muted-foreground/80 uppercase tracking-wider">
|
||||||
@@ -18,7 +19,12 @@ export default function Index() {
|
|||||||
key={key}
|
key={key}
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => navigateTo(key)}
|
onClick={() => navigateTo(key)}
|
||||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium border border-border/60 bg-card text-card-foreground hover:bg-muted/40 hover:border-primary/30 transition-colors cursor-pointer"
|
className={cn(
|
||||||
|
'inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium',
|
||||||
|
'border border-border/60 bg-card text-card-foreground',
|
||||||
|
'hover:bg-muted/40 hover:border-primary/30',
|
||||||
|
'transition-colors cursor-pointer',
|
||||||
|
)}
|
||||||
>
|
>
|
||||||
<IconComponent className="h-3.5 w-3.5 text-muted-foreground/70" />
|
<IconComponent className="h-3.5 w-3.5 text-muted-foreground/70" />
|
||||||
{feature.label}
|
{feature.label}
|
||||||
@@ -36,7 +42,9 @@ export default function Index() {
|
|||||||
{visibleFeatures.length === 0 ? (
|
{visibleFeatures.length === 0 ? (
|
||||||
<p className="text-sm text-muted-foreground py-4 text-center">没有可用的工具</p>
|
<p className="text-sm text-muted-foreground py-4 text-center">没有可用的工具</p>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 gap-2">
|
<div
|
||||||
|
className={cn('grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 gap-2')}
|
||||||
|
>
|
||||||
{visibleFeatures.map(({ key, feature }) => {
|
{visibleFeatures.map(({ key, feature }) => {
|
||||||
const IconComponent = feature.icon;
|
const IconComponent = feature.icon;
|
||||||
return (
|
return (
|
||||||
@@ -44,9 +52,20 @@ export default function Index() {
|
|||||||
key={key}
|
key={key}
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => navigateTo(key)}
|
onClick={() => navigateTo(key)}
|
||||||
className="group flex flex-col items-center justify-center gap-1.5 py-3 px-2 rounded-xl border border-border/50 bg-card hover:bg-muted/40 hover:border-primary/30 transition-colors cursor-pointer"
|
className={cn(
|
||||||
|
'group flex flex-col items-center justify-center gap-1.5',
|
||||||
|
'py-3 px-2 rounded-xl border border-border/50 bg-card',
|
||||||
|
'hover:bg-muted/40 hover:border-primary/30',
|
||||||
|
'transition-colors cursor-pointer',
|
||||||
|
)}
|
||||||
>
|
>
|
||||||
<IconComponent className="h-5 w-5 text-muted-foreground/70 group-hover:text-foreground transition-colors" />
|
<IconComponent
|
||||||
|
className={cn(
|
||||||
|
'h-5 w-5 text-muted-foreground/70',
|
||||||
|
'group-hover:text-foreground',
|
||||||
|
'transition-colors',
|
||||||
|
)}
|
||||||
|
/>
|
||||||
<span className="text-[11px] font-medium text-muted-foreground/80 group-hover:text-foreground leading-tight text-center truncate w-full transition-colors">
|
<span className="text-[11px] font-medium text-muted-foreground/80 group-hover:text-foreground leading-tight text-center truncate w-full transition-colors">
|
||||||
{feature.label}
|
{feature.label}
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -126,34 +126,7 @@ describe('StorageCleaner 页面', () => {
|
|||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(clearStorage).not.toHaveBeenCalled();
|
expect(clearStorage).not.toHaveBeenCalled();
|
||||||
expect(toast.warning).toHaveBeenCalledWith('当前页面已变更,请等待数据刷新后再清理');
|
expect(toast.warning).toHaveBeenCalledWith('当前标签页已切换,请等待数据刷新后再清理');
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('同一标签页 URL 变更后、数据刷新完成前不应执行清理', async () => {
|
|
||||||
let currentUrl = 'https://a.example.com';
|
|
||||||
vi.mocked(getCurrentTab).mockImplementation(
|
|
||||||
async () =>
|
|
||||||
({
|
|
||||||
id: 1,
|
|
||||||
url: currentUrl,
|
|
||||||
}) as any,
|
|
||||||
);
|
|
||||||
|
|
||||||
render(<Index />);
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(screen.getByRole('button', { name: /立即清理/ })).not.toBeDisabled();
|
|
||||||
});
|
|
||||||
|
|
||||||
currentUrl = 'https://b.example.com';
|
|
||||||
|
|
||||||
fireEvent.click(screen.getByRole('button', { name: /立即清理/ }));
|
|
||||||
fireEvent.click(screen.getByRole('button', { name: /确认清理/ }));
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(clearStorage).not.toHaveBeenCalled();
|
|
||||||
expect(toast.warning).toHaveBeenCalledWith('当前页面已变更,请等待数据刷新后再清理');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -258,8 +258,8 @@ export function useStorageCleaner(): UseStorageCleanerReturn {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const boundTab = boundTabRef.current;
|
const boundTab = boundTabRef.current;
|
||||||
if (!boundTab || boundTab.id !== tab.id || boundTab.url !== tab.url) {
|
if (!boundTab || boundTab.id !== tab.id) {
|
||||||
toast.warning('当前页面已变更,请等待数据刷新后再清理');
|
toast.warning('当前标签页已切换,请等待数据刷新后再清理');
|
||||||
setShowConfirm(false);
|
setShowConfirm(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -286,7 +286,7 @@ export default function FieldList({
|
|||||||
onClick={handleUpdateRule}
|
onClick={handleUpdateRule}
|
||||||
disabled={fields.length === 0}
|
disabled={fields.length === 0}
|
||||||
className="h-8 gap-1.5 px-2.5"
|
className="h-8 gap-1.5 px-2.5"
|
||||||
title={editingRule ? `编辑中: ${editingRule.name}` : ''}
|
title={`编辑中: ${editingRule.name}`}
|
||||||
>
|
>
|
||||||
<Save className="h-3.5 w-3.5" />
|
<Save className="h-3.5 w-3.5" />
|
||||||
更新规则
|
更新规则
|
||||||
|
|||||||
@@ -33,10 +33,7 @@ export default function GenerateButton({
|
|||||||
{progress && (
|
{progress && (
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||||
<span>
|
<span>{`已生成 ${progress.generated.toLocaleString()} / ${progress.total.toLocaleString()} 条`}</span>
|
||||||
已生成 {progress.generated.toLocaleString()} / {progress.total.toLocaleString()}{' '}
|
|
||||||
条
|
|
||||||
</span>
|
|
||||||
<span>{progress.progress}%</span>
|
<span>{progress.progress}%</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="h-2 bg-muted rounded-full overflow-hidden">
|
<div className="h-2 bg-muted rounded-full overflow-hidden">
|
||||||
@@ -47,7 +44,7 @@ export default function GenerateButton({
|
|||||||
</div>
|
</div>
|
||||||
{progress.estimatedTimeLeft !== undefined && (
|
{progress.estimatedTimeLeft !== undefined && (
|
||||||
<p className="text-xs text-muted-foreground text-center">
|
<p className="text-xs text-muted-foreground text-center">
|
||||||
预计剩余 {Math.ceil(progress.estimatedTimeLeft / 1000)} 秒
|
{`预计剩余 ${Math.ceil(progress.estimatedTimeLeft / 1000)} 秒`}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ export default function ResultPanel({ result }: ResultPanelProps) {
|
|||||||
))}
|
))}
|
||||||
{result.warnings.length > 5 && (
|
{result.warnings.length > 5 && (
|
||||||
<li className="text-xs text-yellow-500/80">
|
<li className="text-xs text-yellow-500/80">
|
||||||
... 还有 {result.warnings.length - 5} 条警告
|
{`... 还有 ${result.warnings.length - 5} 条警告`}
|
||||||
</li>
|
</li>
|
||||||
)}
|
)}
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -227,7 +227,7 @@ export default function RuleManager({ onLoad, onEdit, onRulesChanged }: RuleMana
|
|||||||
maxLength={20}
|
maxLength={20}
|
||||||
/>
|
/>
|
||||||
<span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground pointer-events-none tabular-nums">
|
<span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground pointer-events-none tabular-nums">
|
||||||
已保存 {rules.length}/{ruleStorage.MAX_RULES} 条
|
{`已保存 ${rules.length}/${ruleStorage.MAX_RULES} 条`}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -260,7 +260,7 @@ export default function RuleManager({ onLoad, onEdit, onRulesChanged }: RuleMana
|
|||||||
<Clock className="h-3 w-3" />
|
<Clock className="h-3 w-3" />
|
||||||
{formatDate(rule.updatedAt)}
|
{formatDate(rule.updatedAt)}
|
||||||
</span>
|
</span>
|
||||||
<span>使用 {rule.useCount} 次</span>
|
<span>{`使用 ${rule.useCount} 次`}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -114,25 +114,4 @@ describe('useGenerator', () => {
|
|||||||
expect(result.current.isGenerating).toBe(false);
|
expect(result.current.isGenerating).toBe(false);
|
||||||
expect(worker.postedMessages).toEqual(expect.arrayContaining([{ type: 'cancel' }]));
|
expect(worker.postedMessages).toEqual(expect.arrayContaining([{ type: 'cancel' }]));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('正在生成时不应重复发送 start 消息', () => {
|
|
||||||
const { result } = renderHook(() => useGenerator());
|
|
||||||
|
|
||||||
act(() => {
|
|
||||||
result.current.generate([mockField], 10);
|
|
||||||
result.current.generate([mockField], 20);
|
|
||||||
});
|
|
||||||
|
|
||||||
const worker = MockWorker.instances[0];
|
|
||||||
const startMessages = worker.postedMessages.filter(
|
|
||||||
(message): message is { type: 'start'; payload: { count: number } } =>
|
|
||||||
typeof message === 'object' &&
|
|
||||||
message !== null &&
|
|
||||||
'type' in message &&
|
|
||||||
message.type === 'start',
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(startMessages).toHaveLength(1);
|
|
||||||
expect(startMessages[0]?.payload.count).toBe(10);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -37,12 +37,6 @@ export function useGenerator(): UseGeneratorReturn {
|
|||||||
|
|
||||||
const workerRef = useRef<Worker | null>(null);
|
const workerRef = useRef<Worker | null>(null);
|
||||||
const generationIdRef = useRef(0);
|
const generationIdRef = useRef(0);
|
||||||
const isGeneratingRef = useRef(false);
|
|
||||||
|
|
||||||
const finishGenerating = useCallback(() => {
|
|
||||||
isGeneratingRef.current = false;
|
|
||||||
setIsGenerating(false);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// 清理 Worker
|
// 清理 Worker
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -79,7 +73,7 @@ export function useGenerator(): UseGeneratorReturn {
|
|||||||
setProgress(data.payload);
|
setProgress(data.payload);
|
||||||
break;
|
break;
|
||||||
case 'complete':
|
case 'complete':
|
||||||
finishGenerating();
|
setIsGenerating(false);
|
||||||
if (data.payload.success) {
|
if (data.payload.success) {
|
||||||
setResult(data.payload);
|
setResult(data.payload);
|
||||||
} else if (data.payload.error && data.payload.error !== '生成已取消') {
|
} else if (data.payload.error && data.payload.error !== '生成已取消') {
|
||||||
@@ -88,7 +82,7 @@ export function useGenerator(): UseGeneratorReturn {
|
|||||||
setProgress(null);
|
setProgress(null);
|
||||||
break;
|
break;
|
||||||
case 'error':
|
case 'error':
|
||||||
finishGenerating();
|
setIsGenerating(false);
|
||||||
setError(data.payload.error);
|
setError(data.payload.error);
|
||||||
setProgress(null);
|
setProgress(null);
|
||||||
break;
|
break;
|
||||||
@@ -97,7 +91,7 @@ export function useGenerator(): UseGeneratorReturn {
|
|||||||
|
|
||||||
worker.onerror = (err) => {
|
worker.onerror = (err) => {
|
||||||
console.error('[useGenerator] Worker 错误:', err);
|
console.error('[useGenerator] Worker 错误:', err);
|
||||||
finishGenerating();
|
setIsGenerating(false);
|
||||||
setError(err.message || 'Worker 运行错误');
|
setError(err.message || 'Worker 运行错误');
|
||||||
setProgress(null);
|
setProgress(null);
|
||||||
// Worker 出错后销毁,下次重新创建
|
// Worker 出错后销毁,下次重新创建
|
||||||
@@ -107,17 +101,16 @@ export function useGenerator(): UseGeneratorReturn {
|
|||||||
|
|
||||||
workerRef.current = worker;
|
workerRef.current = worker;
|
||||||
return worker;
|
return worker;
|
||||||
}, [finishGenerating]);
|
}, []);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 开始生成
|
* 开始生成
|
||||||
*/
|
*/
|
||||||
const generate = useCallback(
|
const generate = useCallback(
|
||||||
(fields: FieldConfig[], count: number, csvMode = false) => {
|
(fields: FieldConfig[], count: number, csvMode = false) => {
|
||||||
if (isGeneratingRef.current) return;
|
if (isGenerating) return;
|
||||||
|
|
||||||
const generationId = ++generationIdRef.current;
|
const generationId = ++generationIdRef.current;
|
||||||
isGeneratingRef.current = true;
|
|
||||||
|
|
||||||
setIsGenerating(true);
|
setIsGenerating(true);
|
||||||
setProgress(null);
|
setProgress(null);
|
||||||
@@ -131,22 +124,21 @@ export function useGenerator(): UseGeneratorReturn {
|
|||||||
};
|
};
|
||||||
worker.postMessage(message);
|
worker.postMessage(message);
|
||||||
},
|
},
|
||||||
[getWorker],
|
[isGenerating, getWorker],
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 取消生成
|
* 取消生成
|
||||||
*/
|
*/
|
||||||
const cancel = useCallback(() => {
|
const cancel = useCallback(() => {
|
||||||
if (workerRef.current && isGeneratingRef.current) {
|
if (workerRef.current && isGenerating) {
|
||||||
++generationIdRef.current;
|
++generationIdRef.current;
|
||||||
const message: WorkerRequestMessage = { type: 'cancel' };
|
const message: WorkerRequestMessage = { type: 'cancel' };
|
||||||
workerRef.current.postMessage(message);
|
workerRef.current.postMessage(message);
|
||||||
isGeneratingRef.current = false;
|
|
||||||
setIsGenerating(false);
|
setIsGenerating(false);
|
||||||
setProgress(null);
|
setProgress(null);
|
||||||
}
|
}
|
||||||
}, []);
|
}, [isGenerating]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 清除结果
|
* 清除结果
|
||||||
|
|||||||
+1
-3
@@ -39,9 +39,7 @@
|
|||||||
- `FieldConfig` — 字段配置(字段名、生成器、参数、必填、空值率、唯一性)
|
- `FieldConfig` — 字段配置(字段名、生成器、参数、必填、空值率、唯一性)
|
||||||
- `DataRule` — 可保存/导入/导出的字段规则
|
- `DataRule` — 可保存/导入/导出的字段规则
|
||||||
- `GeneratorDefinition` / `GeneratorParam` — 内置生成器定义和参数 Schema
|
- `GeneratorDefinition` / `GeneratorParam` — 内置生成器定义和参数 Schema
|
||||||
- `GenerateResult` / `GenerateProgress` — Worker 生成结果与进度
|
- `GenerateResult` / `GenerateProgress` / `WorkerMessage` — Worker 生成结果、进度和消息协议
|
||||||
- `WorkerRequestMessage` / `WorkerResponseMessage` — Worker 消息协议;每条响应携带 `generationId`,用于忽略过期任务(取消或快速重试时)
|
|
||||||
- `WorkerMessage` — 已废弃,请使用上述两种消息类型
|
|
||||||
- `ExportFile` — JSON/CSV 导出文件描述
|
- `ExportFile` — JSON/CSV 导出文件描述
|
||||||
|
|
||||||
## 修改 StorageSchema 的注意事项
|
## 修改 StorageSchema 的注意事项
|
||||||
|
|||||||
+1
-18
@@ -24,7 +24,7 @@
|
|||||||
| `textStatistics.ts` | 文本统计:使用 `Intl.Segmenter` 计算字符数/单词数/行数/字节大小 |
|
| `textStatistics.ts` | 文本统计:使用 `Intl.Segmenter` 计算字符数/单词数/行数/字节大小 |
|
||||||
| `format.ts` | 通用格式化:`formatBytes` 将字节转为可读字符串(B/KB/MB/GB/TB) |
|
| `format.ts` | 通用格式化:`formatBytes` 将字节转为可读字符串(B/KB/MB/GB/TB) |
|
||||||
| `dayjs.ts` | Day.js 初始化:扩展 UTC、Timezone、RelativeTime 插件,加载中文本地化 |
|
| `dayjs.ts` | Day.js 初始化:扩展 UTC、Timezone、RelativeTime 插件,加载中文本地化 |
|
||||||
| `ruleStorage.ts` | 测试数据生成器规则存储:基于 `localStorage` 的 CRUD、搜索、导入/导出和数量限制(见下方说明) |
|
| `ruleStorage.ts` | 测试数据生成器规则存储:基于 `localStorage` 的 CRUD、搜索、导入/导出和数量限制 |
|
||||||
| `dataExporter.ts` | 测试数据导出:JSON/CSV 转换、文件下载和复制到剪贴板 |
|
| `dataExporter.ts` | 测试数据导出:JSON/CSV 转换、文件下载和复制到剪贴板 |
|
||||||
| `rightClickInjection.ts` | 右键恢复注入脚本:在页面上下文恢复 contextmenu/copy/paste 等事件默认行为 |
|
| `rightClickInjection.ts` | 右键恢复注入脚本:在页面上下文恢复 contextmenu/copy/paste 等事件默认行为 |
|
||||||
|
|
||||||
@@ -36,23 +36,6 @@
|
|||||||
| `useContextMenuData.ts` | 右键菜单数据 Hook:从 storage 读取待处理数据,匹配 featureKey 后消费并触发回调 |
|
| `useContextMenuData.ts` | 右键菜单数据 Hook:从 storage 读取待处理数据,匹配 featureKey 后消费并触发回调 |
|
||||||
| `useDebounce.ts` | 防抖 Hook:对值进行延迟更新,避免频繁触发 |
|
| `useDebounce.ts` | 防抖 Hook:对值进行延迟更新,避免频繁触发 |
|
||||||
|
|
||||||
### ruleStorage 写入失败处理
|
|
||||||
|
|
||||||
`ruleStorage.ts` 使用函数式导出(非 class),存储键为 `testDataGenerator_rules`,最多 `MAX_RULES = 20` 条。
|
|
||||||
|
|
||||||
写入经内部 `setAll()` 完成;`localStorage.setItem` 抛错(如配额超限)时返回 `false`,并 `console.error`,**不会部分提交**:
|
|
||||||
|
|
||||||
| 方法 | 写入失败返回值 | 常见失败原因 |
|
|
||||||
| ---- | -------------- | ------------ |
|
|
||||||
| `save()` | `null` | 达上限、规则不存在(更新时)、`setItem` 异常 |
|
|
||||||
| `update()` | `null` | 规则不存在、`setItem` 异常 |
|
|
||||||
| `deleteRule()` | `false` | 规则不存在、`setItem` 异常 |
|
|
||||||
| `duplicate()` | 仍可能返回对象但数据未持久化 | 见源码:`duplicate` 未检查 `setAll` 返回值(已知缺口) |
|
|
||||||
|
|
||||||
调用方应检查返回值后再展示成功 Toast。页面层参考 `FieldList.tsx`:`save`/`update` 返回非空才提示「规则已保存/已更新」。
|
|
||||||
|
|
||||||
规则仅持久化 `name`、`description`、`fields` 及时间戳/使用统计;生成数量与导出格式由页面状态管理,不写入规则。
|
|
||||||
|
|
||||||
### useStorageState 初始化防覆盖
|
### useStorageState 初始化防覆盖
|
||||||
|
|
||||||
`useStorageState` 在挂载时从 storage 异步加载。写入 storage 需满足以下任一条件:
|
`useStorageState` 在挂载时从 storage 异步加载。写入 storage 需满足以下任一条件:
|
||||||
|
|||||||
@@ -14,14 +14,10 @@ import type {
|
|||||||
/** 每生成 N 行让出一次事件循环,以便处理 cancel 消息 */
|
/** 每生成 N 行让出一次事件循环,以便处理 cancel 消息 */
|
||||||
const YIELD_EVERY = 100;
|
const YIELD_EVERY = 100;
|
||||||
|
|
||||||
/** 当前活跃生成任务 ID;新 start 会 supersede 旧任务 */
|
// 生成结果缓存
|
||||||
let activeGenerationId: number | null = null;
|
let generatedData: Record<string, unknown>[] = [];
|
||||||
let isCancelled = false;
|
let isCancelled = false;
|
||||||
|
|
||||||
function shouldAbort(generationId: number): boolean {
|
|
||||||
return isCancelled || generationId !== activeGenerationId;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Worker 消息处理器
|
* Worker 消息处理器
|
||||||
*/
|
*/
|
||||||
@@ -31,17 +27,12 @@ self.onmessage = async (e: MessageEvent<WorkerRequestMessage>) => {
|
|||||||
|
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case 'start':
|
case 'start':
|
||||||
activeGenerationId = data.payload.generationId;
|
|
||||||
isCancelled = false;
|
isCancelled = false;
|
||||||
await handleStart(data.payload);
|
await handleStart(data.payload);
|
||||||
break;
|
break;
|
||||||
case 'cancel':
|
case 'cancel':
|
||||||
isCancelled = true;
|
isCancelled = true;
|
||||||
break;
|
break;
|
||||||
default: {
|
|
||||||
const _exhaustive: never = type;
|
|
||||||
return _exhaustive;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -55,7 +46,7 @@ async function handleStart(payload: {
|
|||||||
csvMode: boolean;
|
csvMode: boolean;
|
||||||
}): Promise<void> {
|
}): Promise<void> {
|
||||||
const { generationId, fields, count } = payload;
|
const { generationId, fields, count } = payload;
|
||||||
const generatedData: Record<string, unknown>[] = [];
|
generatedData = [];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 验证所有生成器是否存在
|
// 验证所有生成器是否存在
|
||||||
@@ -76,8 +67,7 @@ async function handleStart(payload: {
|
|||||||
|
|
||||||
// 生成数据
|
// 生成数据
|
||||||
for (let i = 0; i < count; i++) {
|
for (let i = 0; i < count; i++) {
|
||||||
if (shouldAbort(generationId)) {
|
if (isCancelled) {
|
||||||
if (generationId === activeGenerationId) {
|
|
||||||
self.postMessage({
|
self.postMessage({
|
||||||
type: 'complete',
|
type: 'complete',
|
||||||
generationId,
|
generationId,
|
||||||
@@ -86,7 +76,6 @@ async function handleStart(payload: {
|
|||||||
error: '生成已取消',
|
error: '生成已取消',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,8 +148,7 @@ async function handleStart(payload: {
|
|||||||
// 定期让出事件循环,使 cancel 消息能被处理
|
// 定期让出事件循环,使 cancel 消息能被处理
|
||||||
if ((i + 1) % YIELD_EVERY === 0) {
|
if ((i + 1) % YIELD_EVERY === 0) {
|
||||||
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
||||||
if (shouldAbort(generationId)) {
|
if (isCancelled) {
|
||||||
if (generationId === activeGenerationId) {
|
|
||||||
self.postMessage({
|
self.postMessage({
|
||||||
type: 'complete',
|
type: 'complete',
|
||||||
generationId,
|
generationId,
|
||||||
@@ -169,16 +157,11 @@ async function handleStart(payload: {
|
|||||||
error: '生成已取消',
|
error: '生成已取消',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (shouldAbort(generationId)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const duration = Date.now() - startTime;
|
const duration = Date.now() - startTime;
|
||||||
const successCount = generatedData.filter((item) => Object.keys(item).length > 0).length;
|
const successCount = generatedData.filter((item) => Object.keys(item).length > 0).length;
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user