Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d18ae5d41c | |||
| 47e08f80b3 | |||
| ece5c6135e | |||
| d0825c5ec0 | |||
| 149883565d | |||
| ff3c66531c | |||
| 4084dafc29 | |||
| 647e3dd308 |
@@ -677,7 +677,7 @@ src/pages/StorageCleaner/useStorageCleaner.ts — 页面级 Hook
|
||||
label: '时间戳转换',
|
||||
description: '日期与时间戳互转',
|
||||
defaultVisible: true,
|
||||
components: { popup: TimestampPage, sidepanel: TimestampPage, tab: TimestampPage },
|
||||
component: 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 → 加载成功或用户修改后才允许写入。
|
||||
|
||||
|
||||
@@ -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,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>
|
||||
)}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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)),
|
||||
|
||||
@@ -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
@@ -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,
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
@@ -33,9 +33,7 @@ export default function TopBar() {
|
||||
id: 'open-in-tab',
|
||||
icon: ExternalLink,
|
||||
title: '在标签页打开',
|
||||
onClick: () => {
|
||||
void handleOpenInTab();
|
||||
},
|
||||
onClick: () => void handleOpenInTab(),
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -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
@@ -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 等格式'}
|
||||
支持 PNG、JPG、WEBP、GIF、BMP、SVG 等格式
|
||||
</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">
|
||||
|
||||
@@ -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) {
|
||||
setShowConfirmOverwrite(true);
|
||||
return;
|
||||
}
|
||||
if (!overwrite && existingRule) {
|
||||
setShowConfirmOverwrite(true);
|
||||
return;
|
||||
}
|
||||
|
||||
const newRule = ruleStorage.save({
|
||||
name: trimmedName,
|
||||
description: ruleDescription.trim(),
|
||||
fields: fields,
|
||||
});
|
||||
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]);
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 清除结果
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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,15 +76,17 @@ async function handleStart(payload: {
|
||||
|
||||
// 生成数据
|
||||
for (let i = 0; i < count; i++) {
|
||||
if (isCancelled) {
|
||||
self.postMessage({
|
||||
type: 'complete',
|
||||
generationId,
|
||||
payload: {
|
||||
success: false,
|
||||
error: '生成已取消',
|
||||
},
|
||||
});
|
||||
if (shouldAbort(generationId)) {
|
||||
if (generationId === activeGenerationId) {
|
||||
self.postMessage({
|
||||
type: 'complete',
|
||||
generationId,
|
||||
payload: {
|
||||
success: false,
|
||||
error: '生成已取消',
|
||||
},
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -148,20 +159,26 @@ async function handleStart(payload: {
|
||||
// 定期让出事件循环,使 cancel 消息能被处理
|
||||
if ((i + 1) % YIELD_EVERY === 0) {
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
||||
if (isCancelled) {
|
||||
self.postMessage({
|
||||
type: 'complete',
|
||||
generationId,
|
||||
payload: {
|
||||
success: false,
|
||||
error: '生成已取消',
|
||||
},
|
||||
});
|
||||
if (shouldAbort(generationId)) {
|
||||
if (generationId === activeGenerationId) {
|
||||
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;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user