Compare commits

..

1 Commits

Author SHA1 Message Date
Cursor Agent b2db05a922 docs: 同步测试数据生成器 Worker 任务 ID 与 ruleStorage 写入失败说明
Co-authored-by: LingandRX <LingandRX@users.noreply.github.com>
2026-06-29 16:08:10 +00:00
26 changed files with 191 additions and 326 deletions
+6 -6
View File
@@ -677,7 +677,7 @@ src/pages/StorageCleaner/useStorageCleaner.ts — 页面级 Hook
label: '时间戳转换',
description: '日期与时间戳互转',
defaultVisible: true,
component: TimestampPage,
components: { popup: TimestampPage, sidepanel: TimestampPage, tab: TimestampPage },
}
```
@@ -763,11 +763,11 @@ 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 覆盖) |
| 模块 | 快照工具 | 防覆盖机制 |
| ---- | -------- | ---------- |
| `RouterProvider` | `syncSnapshot.ts` | `canPersistRef`(加载成功后才写入)、`hasUserNavigatedRef`(用户导航后不被 storage 覆盖) |
| `useStorageState` | `syncSnapshot.ts` | `loadSucceededRef``userModifiedRef` 为 true 时才写入 |
| `ThemeModeProvider` | `themeSnapshot.ts` | `hasUserSetMode`(用户切换主题后不被 storage 覆盖) |
新增持久化状态时,应遵循相同模式:同步快照作初始 state → 异步加载 storage → 加载成功或用户修改后才允许写入。
+2 -6
View File
@@ -57,11 +57,7 @@ export function ErrorFallback({
<h3 className="text-base font-semibold text-foreground mb-1.5">{title}</h3>
)}
<p
className={
isApp ? 'text-sm text-muted-foreground mb-6' : 'text-xs text-muted-foreground mb-5'
}
>
<p className={cn('text-muted-foreground', isApp ? 'text-sm mb-6' : 'text-xs mb-5')}>
{description}
</p>
@@ -87,7 +83,7 @@ export function ErrorFallback({
variant="destructive"
size={isApp ? 'default' : 'sm'}
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'} />
{actionLabel}
+5 -3
View File
@@ -1,4 +1,4 @@
import { FEATURES } from '@/config/features';
import { FEATURES, getEntryPointType } from '@/config/features';
import { useRouter } from '@/providers/RouterProvider';
import { Suspense } from 'react';
import PageErrorBoundary from '@/components/PageErrorBoundary';
@@ -6,6 +6,8 @@ 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();
@@ -17,7 +19,7 @@ export default function RouterContainer() {
}
const currentFeature = FEATURES.find((f) => f.key === currentPage);
const MatchedComponent = currentFeature?.component;
const MatchedComponent = currentFeature?.components?.[entryPointType];
return (
<div
@@ -41,7 +43,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="grid place-content-center text-current">
<CheckboxPrimitive.Indicator className={cn('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')!.component;
const DashboardPage = FEATURES.find((f) => f.key === 'dashboard')!.components.popup;
render(
React.createElement(React.Suspense, { fallback: null }, React.createElement(DashboardPage)),
+5 -3
View File
@@ -19,13 +19,15 @@ describe('features', () => {
expect(feature).toHaveProperty('label');
expect(feature).toHaveProperty('description');
expect(feature).toHaveProperty('defaultVisible');
expect(feature).toHaveProperty('component');
expect(feature).toHaveProperty('components');
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(feature.component).toBeDefined();
expect(['function', 'object']).toContain(typeof feature.component);
expect(typeof feature.components).toBe('object');
expect(feature.components).toHaveProperty('popup');
expect(feature.components).toHaveProperty('sidepanel');
expect(feature.components).toHaveProperty('tab');
if (feature.key !== 'dashboard') {
expect(feature).toHaveProperty('icon');
+55 -11
View File
@@ -34,7 +34,11 @@ export interface FeatureConfig {
themeColorKey?: PaletteColorKey;
icon?: ComponentType<LucideProps>;
defaultVisible: boolean;
component: ComponentType;
components: {
popup: ComponentType;
sidepanel: ComponentType;
tab: ComponentType;
};
}
export const FEATURES: FeatureConfig[] = [
@@ -43,7 +47,11 @@ export const FEATURES: FeatureConfig[] = [
label: '仪表盘',
description: '',
defaultVisible: true,
component: DashboardPage,
components: {
popup: DashboardPage,
sidepanel: DashboardPage,
tab: DashboardPage,
},
},
{
key: 'timestamp',
@@ -52,7 +60,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'primary',
icon: Clock,
defaultVisible: true,
component: TimestampPage,
components: {
popup: TimestampPage,
sidepanel: TimestampPage,
tab: TimestampPage,
},
},
{
key: 'storageCleaner',
@@ -61,7 +73,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'warning',
icon: Database,
defaultVisible: true,
component: StorageCleanerPage,
components: {
popup: StorageCleanerPage,
sidepanel: StorageCleanerPage,
tab: StorageCleanerPage,
},
},
{
key: 'qrCode',
@@ -70,7 +86,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'success',
icon: QrCode,
defaultVisible: true,
component: QrCodePage,
components: {
popup: QrCodePage,
sidepanel: QrCodePage,
tab: QrCodePage,
},
},
{
key: 'textStatistics',
@@ -79,7 +99,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'secondary',
icon: FileText,
defaultVisible: true,
component: TextStatisticsPage,
components: {
popup: TextStatisticsPage,
sidepanel: TextStatisticsPage,
tab: TextStatisticsPage,
},
},
{
key: 'jwt',
@@ -88,7 +112,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'info',
icon: Key,
defaultVisible: true,
component: JwtPage,
components: {
popup: JwtPage,
sidepanel: JwtPage,
tab: JwtPage,
},
},
{
key: 'jsonTools',
@@ -97,7 +125,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'primary',
icon: GitCompareArrows,
defaultVisible: true,
component: JsonToolsPage,
components: {
popup: JsonToolsPage,
sidepanel: JsonToolsPage,
tab: JsonToolsPage,
},
},
{
key: 'base64Converter',
@@ -106,7 +138,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'info',
icon: ArrowLeftRight,
defaultVisible: true,
component: Base64ConverterPage,
components: {
popup: Base64ConverterPage,
sidepanel: Base64ConverterPage,
tab: Base64ConverterPage,
},
},
{
key: 'rightClickRestorer',
@@ -115,7 +151,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'success',
icon: MousePointerClick,
defaultVisible: true,
component: RightClickRestorerPage,
components: {
popup: RightClickRestorerPage,
sidepanel: RightClickRestorerPage,
tab: RightClickRestorerPage,
},
},
{
key: 'testDataGenerator',
@@ -124,7 +164,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'warning',
icon: FileSpreadsheet,
defaultVisible: true,
component: TestDataGeneratorPage,
components: {
popup: TestDataGeneratorPage,
sidepanel: TestDataGeneratorPage,
tab: TestDataGeneratorPage,
},
},
];
+3 -3
View File
@@ -16,16 +16,16 @@ export default function SearchDropdown({
selectedIndex,
onSelect,
}: SearchDropdownProps) {
const isSearching = !!searchQuery.trim();
const isSearching = searchQuery.trim().length > 0;
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 && (
<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 ? (
<li className="px-4 py-6 text-center text-sm text-muted-foreground"></li>
+9 -7
View File
@@ -1,4 +1,4 @@
import { type KeyboardEvent, type RefObject } from 'react';
import { 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: KeyboardEvent) => void;
onKeyDown: (e: React.KeyboardEvent) => 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" />
<Input
ref={inputRef}
type="text"
placeholder="搜索工具..."
value={searchQuery}
onChange={(e) => onSearchQueryChange(e.target.value)}
@@ -34,7 +35,12 @@ 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 ? (
{!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
type="button"
variant="ghost"
@@ -45,10 +51,6 @@ 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>
);
+3 -1
View File
@@ -33,7 +33,9 @@ export default function TopBar() {
id: 'open-in-tab',
icon: ExternalLink,
title: '在标签页打开',
onClick: () => void handleOpenInTab(),
onClick: () => {
void handleOpenInTab();
},
},
];
+15 -22
View File
@@ -1,11 +1,4 @@
import {
useEffect,
useMemo,
useRef,
useState,
type KeyboardEvent as ReactKeyboardEvent,
type RefObject,
} from 'react';
import { useEffect, useMemo, useRef, useState, type RefObject } from 'react';
import { Monitor, Moon, Sun } from 'lucide-react';
import { useRouter } from '@/providers/RouterProvider';
import { useThemeMode } from '@/providers/ThemeModeProvider';
@@ -28,7 +21,7 @@ export interface UseTopBarReturn {
handleSearchQueryChange: (value: string) => void;
handleSearchFocus: () => void;
handleSelectFeature: (feature: FeatureConfig) => void;
handleKeyDown: (e: ReactKeyboardEvent) => void;
handleKeyDown: (e: React.KeyboardEvent) => void;
cycleThemeMode: () => void;
handleOpenInTab: () => Promise<void>;
goHome: () => void;
@@ -87,7 +80,7 @@ export function useTopBar(): UseTopBarReturn {
});
}, [searchQuery]);
const recentFeatures = useMemo(() => {
const displayedHistory = useMemo(() => {
if (searchQuery.trim()) return [];
return searchHistory
.slice(0, SEARCH_HISTORY_DISPLAY)
@@ -118,10 +111,8 @@ export function useTopBar(): UseTopBarReturn {
const themeTitle =
mode === 'light' ? '切换到深色模式' : mode === 'dark' ? '切换到系统模式' : '切换到浅色模式';
const handleKeyDown = (e: ReactKeyboardEvent) => {
const isSearching = !!searchQuery.trim();
const items = isSearching ? searchResults : recentFeatures;
const totalItems = items.length;
const handleKeyDown = (e: React.KeyboardEvent) => {
const totalItems = searchQuery.trim() ? searchResults.length : displayedHistory.length;
if (e.key === 'ArrowDown') {
e.preventDefault();
@@ -131,12 +122,13 @@ export function useTopBar(): UseTopBarReturn {
setSelectedIndex((prev) => (prev > 0 ? prev - 1 : prev));
} else if (e.key === 'Enter') {
e.preventDefault();
let feature: FeatureConfig | undefined;
if (selectedIndex >= 0 && selectedIndex < totalItems) {
feature = items[selectedIndex];
} else if (isSearching && searchResults.length > 0) {
feature = searchResults[0];
}
const items = searchQuery.trim() ? searchResults : displayedHistory;
const feature =
selectedIndex >= 0 && selectedIndex < totalItems
? items[selectedIndex]
: searchQuery.trim() && searchResults.length > 0
? searchResults[0]
: undefined;
if (feature) handleSelectFeature(feature);
} else if (e.key === 'Escape') {
setShowResults(false);
@@ -157,12 +149,13 @@ export function useTopBar(): UseTopBarReturn {
const handleSearchFocus = () => setShowResults(true);
const showDropdown = showResults && (!!searchQuery.trim() || recentFeatures.length > 0);
const showDropdown =
showResults && (searchQuery.trim().length > 0 || displayedHistory.length > 0);
return {
searchQuery,
searchResults,
recentFeatures,
recentFeatures: displayedHistory,
selectedIndex,
showDropdown,
isDashboard: currentPage === 'dashboard',
+2 -1
View File
@@ -1,5 +1,6 @@
import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return clsx(inputs);
return twMerge(clsx(inputs));
}
@@ -22,9 +22,7 @@ vi.mock('../components/TextMode', () => ({
}));
vi.mock('../components/Base64ConverterSection', () => ({
default: ({ mode }: { mode: 'file' | 'image' }) => (
<div data-testid={`${mode}-mode`}>{mode.toUpperCase()} Mode</div>
),
default: ({ mode }: { mode: string }) => <div data-testid={`${mode}-mode`}>{mode}</div>,
}));
const waitForStorageInit = () =>
@@ -50,6 +50,10 @@ 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">
@@ -111,7 +115,7 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
/>
</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">
{info.name}
</span>
@@ -133,11 +137,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">
PNGJPGWEBPGIFBMPSVG
{'支持 PNG、JPG、WEBP、GIF、BMP、SVG 等格式'}
</span>
)}
</div>
@@ -227,7 +231,7 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
blobSize={decoded.blob.size}
fileName={decodedFileName}
onFileNameChange={setCustomFileName}
onDownload={() => downloadBlob(decoded.blob, decodedFileName)}
onDownload={handleDownload}
>
{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">
+24 -5
View File
@@ -1,10 +1,11 @@
import { cn } from '@/lib/utils';
import { useDashboard } from './useDashboard';
export default function Index() {
const { visibleFeatures, recentFeatures, showRecent, navigateTo } = useDashboard();
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 && (
<div className="flex flex-col gap-2">
<h3 className="text-xs font-semibold text-muted-foreground/80 uppercase tracking-wider">
@@ -18,7 +19,12 @@ export default function Index() {
key={key}
type="button"
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" />
{feature.label}
@@ -36,7 +42,9 @@ export default function Index() {
{visibleFeatures.length === 0 ? (
<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 }) => {
const IconComponent = feature.icon;
return (
@@ -44,9 +52,20 @@ export default function Index() {
key={key}
type="button"
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">
{feature.label}
</span>
@@ -126,34 +126,7 @@ describe('StorageCleaner 页面', () => {
await waitFor(() => {
expect(clearStorage).not.toHaveBeenCalled();
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('当前页面已变更,请等待数据刷新后再清理');
expect(toast.warning).toHaveBeenCalledWith('当前标签页已切换,请等待数据刷新后再清理');
});
});
});
@@ -258,8 +258,8 @@ export function useStorageCleaner(): UseStorageCleanerReturn {
}
const boundTab = boundTabRef.current;
if (!boundTab || boundTab.id !== tab.id || boundTab.url !== tab.url) {
toast.warning('当前页面已变更,请等待数据刷新后再清理');
if (!boundTab || boundTab.id !== tab.id) {
toast.warning('当前标签页已切换,请等待数据刷新后再清理');
setShowConfirm(false);
return;
}
@@ -234,38 +234,29 @@ export default function FieldList({
if (!ruleName.trim()) return;
const trimmedName = ruleName.trim();
const existingRule = ruleStorage.getByName(trimmedName);
// 检查名称是否重复
if (!overwrite && existingRule) {
setShowConfirmOverwrite(true);
return;
if (!overwrite) {
const existingRule = ruleStorage.getByName(trimmedName);
if (existingRule) {
setShowConfirmOverwrite(true);
return;
}
}
const savedRule = ruleStorage.save(
overwrite && existingRule
? {
id: existingRule.id,
name: trimmedName,
description: ruleDescription.trim(),
fields: fields,
}
: {
name: trimmedName,
description: ruleDescription.trim(),
fields: fields,
},
);
const newRule = ruleStorage.save({
name: trimmedName,
description: ruleDescription.trim(),
fields: fields,
});
if (savedRule) {
if (newRule) {
setShowSaveDialog(false);
setShowConfirmOverwrite(false);
setRuleName('');
setRuleDescription('');
toast.success(overwrite ? '规则已覆盖' : '规则已保存');
toast.success('规则已保存');
onRuleSaved?.();
} else {
toast.error('规则保存失败');
}
},
[ruleName, ruleDescription, fields, onRuleSaved],
@@ -286,7 +277,7 @@ export default function FieldList({
onClick={handleUpdateRule}
disabled={fields.length === 0}
className="h-8 gap-1.5 px-2.5"
title={editingRule ? `编辑中: ${editingRule.name}` : ''}
title={`编辑中: ${editingRule.name}`}
>
<Save className="h-3.5 w-3.5" />
@@ -33,10 +33,7 @@ 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">
@@ -47,7 +44,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>
@@ -1,92 +0,0 @@
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,25 +114,4 @@ 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,12 +37,6 @@ 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(() => {
@@ -79,7 +73,7 @@ export function useGenerator(): UseGeneratorReturn {
setProgress(data.payload);
break;
case 'complete':
finishGenerating();
setIsGenerating(false);
if (data.payload.success) {
setResult(data.payload);
} else if (data.payload.error && data.payload.error !== '生成已取消') {
@@ -88,7 +82,7 @@ export function useGenerator(): UseGeneratorReturn {
setProgress(null);
break;
case 'error':
finishGenerating();
setIsGenerating(false);
setError(data.payload.error);
setProgress(null);
break;
@@ -97,7 +91,7 @@ export function useGenerator(): UseGeneratorReturn {
worker.onerror = (err) => {
console.error('[useGenerator] Worker 错误:', err);
finishGenerating();
setIsGenerating(false);
setError(err.message || 'Worker 运行错误');
setProgress(null);
// Worker 出错后销毁,下次重新创建
@@ -107,17 +101,16 @@ export function useGenerator(): UseGeneratorReturn {
workerRef.current = worker;
return worker;
}, [finishGenerating]);
}, []);
/**
* 开始生成
*/
const generate = useCallback(
(fields: FieldConfig[], count: number, csvMode = false) => {
if (isGeneratingRef.current) return;
if (isGenerating) return;
const generationId = ++generationIdRef.current;
isGeneratingRef.current = true;
setIsGenerating(true);
setProgress(null);
@@ -131,22 +124,21 @@ export function useGenerator(): UseGeneratorReturn {
};
worker.postMessage(message);
},
[getWorker],
[isGenerating, getWorker],
);
/**
* 取消生成
*/
const cancel = useCallback(() => {
if (workerRef.current && isGeneratingRef.current) {
if (workerRef.current && isGenerating) {
++generationIdRef.current;
const message: WorkerRequestMessage = { type: 'cancel' };
workerRef.current.postMessage(message);
isGeneratingRef.current = false;
setIsGenerating(false);
setProgress(null);
}
}, []);
}, [isGenerating]);
/**
* 清除结果
-21
View File
@@ -48,27 +48,6 @@ 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',
+21 -38
View File
@@ -14,14 +14,10 @@ import type {
/** 每生成 N 行让出一次事件循环,以便处理 cancel 消息 */
const YIELD_EVERY = 100;
/** 当前活跃生成任务 ID;新 start 会 supersede 旧任务 */
let activeGenerationId: number | null = null;
// 生成结果缓存
let generatedData: Record<string, unknown>[] = [];
let isCancelled = false;
function shouldAbort(generationId: number): boolean {
return isCancelled || generationId !== activeGenerationId;
}
/**
* Worker 消息处理器
*/
@@ -31,17 +27,12 @@ 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;
}
}
};
@@ -55,7 +46,7 @@ async function handleStart(payload: {
csvMode: boolean;
}): Promise<void> {
const { generationId, fields, count } = payload;
const generatedData: Record<string, unknown>[] = [];
generatedData = [];
try {
// 验证所有生成器是否存在
@@ -76,17 +67,15 @@ async function handleStart(payload: {
// 生成数据
for (let i = 0; i < count; i++) {
if (shouldAbort(generationId)) {
if (generationId === activeGenerationId) {
self.postMessage({
type: 'complete',
generationId,
payload: {
success: false,
error: '生成已取消',
},
});
}
if (isCancelled) {
self.postMessage({
type: 'complete',
generationId,
payload: {
success: false,
error: '生成已取消',
},
});
return;
}
@@ -159,26 +148,20 @@ async function handleStart(payload: {
// 定期让出事件循环,使 cancel 消息能被处理
if ((i + 1) % YIELD_EVERY === 0) {
await new Promise<void>((resolve) => setTimeout(resolve, 0));
if (shouldAbort(generationId)) {
if (generationId === activeGenerationId) {
self.postMessage({
type: 'complete',
generationId,
payload: {
success: false,
error: '生成已取消',
},
});
}
if (isCancelled) {
self.postMessage({
type: 'complete',
generationId,
payload: {
success: false,
error: '生成已取消',
},
});
return;
}
}
}
if (shouldAbort(generationId)) {
return;
}
const duration = Date.now() - startTime;
const successCount = generatedData.filter((item) => Object.keys(item).length > 0).length;