Compare commits

...

8 Commits

Author SHA1 Message Date
rsgltzyd d18ae5d41c refactor: 移除 twMerge 以简化 cn() 函数实现 2026-06-30 22:00:08 +08:00
rsgltzyd 47e08f80b3 refactor: 统一功能组件结构,简化特性配置 2026-06-30 21:18:28 +08:00
rsgltzyd ece5c6135e fix: 更新中文提示信息格式以提升可读性
在多个组件中移除模板字符串,直接使用普通字符串格式化中文提示信息,增强了代码的可读性和一致性。
2026-06-30 21:06:39 +08:00
rsgltzyd d0825c5ec0 refactor: 移除无意义的 cn() 包装
对仅含静态类名或单一三元表达式的 className 改用普通字符串,保留有条件合并或 prop 覆盖场景下的 cn() 用法。

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