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: '时间戳转换',
|
label: '时间戳转换',
|
||||||
description: '日期与时间戳互转',
|
description: '日期与时间戳互转',
|
||||||
defaultVisible: true,
|
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}`)提供同步初始值,消除首屏闪烁。
|
Chrome Storage 读取是异步的。项目通过 `localStorage` 快照(键名 `snapshot/{storageKey}`)提供同步初始值,消除首屏闪烁。
|
||||||
|
|
||||||
| 模块 | 快照工具 | 防覆盖机制 |
|
| 模块 | 快照工具 | 防覆盖机制 |
|
||||||
| ---- | -------- | ---------- |
|
| ------------------- | ------------------ | ----------------------------------------------------------------------------------------- |
|
||||||
| `RouterProvider` | `syncSnapshot.ts` | `canPersistRef`(加载成功后才写入)、`hasUserNavigatedRef`(用户导航后不被 storage 覆盖) |
|
| `RouterProvider` | `syncSnapshot.ts` | `canPersistRef`(加载成功后才写入)、`hasUserNavigatedRef`(用户导航后不被 storage 覆盖) |
|
||||||
| `useStorageState` | `syncSnapshot.ts` | `loadSucceededRef` 或 `userModifiedRef` 为 true 时才写入 |
|
| `useStorageState` | `syncSnapshot.ts` | `loadSucceededRef` 或 `userModifiedRef` 为 true 时才写入 |
|
||||||
| `ThemeModeProvider` | `themeSnapshot.ts` | `hasUserSetMode`(用户切换主题后不被 storage 覆盖) |
|
| `ThemeModeProvider` | `themeSnapshot.ts` | `hasUserSetMode`(用户切换主题后不被 storage 覆盖) |
|
||||||
|
|||||||
@@ -57,7 +57,11 @@ export function ErrorFallback({
|
|||||||
<h3 className="text-base font-semibold text-foreground mb-1.5">{title}</h3>
|
<h3 className="text-base font-semibold text-foreground mb-1.5">{title}</h3>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<p 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}
|
{description}
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
@@ -83,7 +87,7 @@ export function ErrorFallback({
|
|||||||
variant="destructive"
|
variant="destructive"
|
||||||
size={isApp ? 'default' : 'sm'}
|
size={isApp ? 'default' : 'sm'}
|
||||||
onClick={onAction}
|
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'} />
|
<RefreshCw className={isApp ? 'mr-2 h-4 w-4' : 'mr-1.5 h-3.5 w-3.5'} />
|
||||||
{actionLabel}
|
{actionLabel}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { FEATURES, getEntryPointType } from '@/config/features';
|
import { FEATURES } from '@/config/features';
|
||||||
import { useRouter } from '@/providers/RouterProvider';
|
import { useRouter } from '@/providers/RouterProvider';
|
||||||
import { Suspense } from 'react';
|
import { Suspense } from 'react';
|
||||||
import PageErrorBoundary from '@/components/PageErrorBoundary';
|
import PageErrorBoundary from '@/components/PageErrorBoundary';
|
||||||
@@ -6,8 +6,6 @@ import PageSkeleton from '@/components/PageSkeleton';
|
|||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { AlertTriangle } from 'lucide-react';
|
import { AlertTriangle } from 'lucide-react';
|
||||||
|
|
||||||
const entryPointType = getEntryPointType();
|
|
||||||
|
|
||||||
export default function RouterContainer() {
|
export default function RouterContainer() {
|
||||||
const { currentPage, isLoaded } = useRouter();
|
const { currentPage, isLoaded } = useRouter();
|
||||||
|
|
||||||
@@ -19,7 +17,7 @@ export default function RouterContainer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const currentFeature = FEATURES.find((f) => f.key === currentPage);
|
const currentFeature = FEATURES.find((f) => f.key === currentPage);
|
||||||
const MatchedComponent = currentFeature?.components?.[entryPointType];
|
const MatchedComponent = currentFeature?.component;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
@@ -43,7 +41,7 @@ export default function RouterContainer() {
|
|||||||
</div>
|
</div>
|
||||||
<h3 className="text-sm font-semibold text-foreground">页面未找到</h3>
|
<h3 className="text-sm font-semibold text-foreground">页面未找到</h3>
|
||||||
<p className="text-xs text-muted-foreground mt-1 max-w-[240px]">
|
<p className="text-xs text-muted-foreground mt-1 max-w-[240px]">
|
||||||
{`该功能在当前运行环境(${entryPointType})下不可用或已被移除。`}
|
该功能不存在或已被移除。
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ const Checkbox = React.forwardRef<
|
|||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<CheckboxPrimitive.Indicator className={cn('grid place-content-center text-current')}>
|
<CheckboxPrimitive.Indicator className="grid place-content-center text-current">
|
||||||
<Check className="h-4 w-4" />
|
<Check className="h-4 w-4" />
|
||||||
</CheckboxPrimitive.Indicator>
|
</CheckboxPrimitive.Indicator>
|
||||||
</CheckboxPrimitive.Root>
|
</CheckboxPrimitive.Root>
|
||||||
|
|||||||
@@ -72,7 +72,7 @@ describe('features 懒加载', () => {
|
|||||||
const { render, waitFor } = await import('@testing-library/react');
|
const { render, waitFor } = await import('@testing-library/react');
|
||||||
const { FEATURES } = await import('@/config/features');
|
const { FEATURES } = await import('@/config/features');
|
||||||
|
|
||||||
const DashboardPage = FEATURES.find((f) => f.key === 'dashboard')!.components.popup;
|
const DashboardPage = FEATURES.find((f) => f.key === 'dashboard')!.component;
|
||||||
|
|
||||||
render(
|
render(
|
||||||
React.createElement(React.Suspense, { fallback: null }, React.createElement(DashboardPage)),
|
React.createElement(React.Suspense, { fallback: null }, React.createElement(DashboardPage)),
|
||||||
|
|||||||
@@ -19,15 +19,13 @@ describe('features', () => {
|
|||||||
expect(feature).toHaveProperty('label');
|
expect(feature).toHaveProperty('label');
|
||||||
expect(feature).toHaveProperty('description');
|
expect(feature).toHaveProperty('description');
|
||||||
expect(feature).toHaveProperty('defaultVisible');
|
expect(feature).toHaveProperty('defaultVisible');
|
||||||
expect(feature).toHaveProperty('components');
|
expect(feature).toHaveProperty('component');
|
||||||
expect(typeof feature.key).toBe('string');
|
expect(typeof feature.key).toBe('string');
|
||||||
expect(typeof feature.label).toBe('string');
|
expect(typeof feature.label).toBe('string');
|
||||||
expect(typeof feature.description).toBe('string');
|
expect(typeof feature.description).toBe('string');
|
||||||
expect(typeof feature.defaultVisible).toBe('boolean');
|
expect(typeof feature.defaultVisible).toBe('boolean');
|
||||||
expect(typeof feature.components).toBe('object');
|
expect(feature.component).toBeDefined();
|
||||||
expect(feature.components).toHaveProperty('popup');
|
expect(['function', 'object']).toContain(typeof feature.component);
|
||||||
expect(feature.components).toHaveProperty('sidepanel');
|
|
||||||
expect(feature.components).toHaveProperty('tab');
|
|
||||||
|
|
||||||
if (feature.key !== 'dashboard') {
|
if (feature.key !== 'dashboard') {
|
||||||
expect(feature).toHaveProperty('icon');
|
expect(feature).toHaveProperty('icon');
|
||||||
|
|||||||
+11
-55
@@ -34,11 +34,7 @@ export interface FeatureConfig {
|
|||||||
themeColorKey?: PaletteColorKey;
|
themeColorKey?: PaletteColorKey;
|
||||||
icon?: ComponentType<LucideProps>;
|
icon?: ComponentType<LucideProps>;
|
||||||
defaultVisible: boolean;
|
defaultVisible: boolean;
|
||||||
components: {
|
component: ComponentType;
|
||||||
popup: ComponentType;
|
|
||||||
sidepanel: ComponentType;
|
|
||||||
tab: ComponentType;
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const FEATURES: FeatureConfig[] = [
|
export const FEATURES: FeatureConfig[] = [
|
||||||
@@ -47,11 +43,7 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
label: '仪表盘',
|
label: '仪表盘',
|
||||||
description: '',
|
description: '',
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
components: {
|
component: DashboardPage,
|
||||||
popup: DashboardPage,
|
|
||||||
sidepanel: DashboardPage,
|
|
||||||
tab: DashboardPage,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'timestamp',
|
key: 'timestamp',
|
||||||
@@ -60,11 +52,7 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'primary',
|
themeColorKey: 'primary',
|
||||||
icon: Clock,
|
icon: Clock,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
components: {
|
component: TimestampPage,
|
||||||
popup: TimestampPage,
|
|
||||||
sidepanel: TimestampPage,
|
|
||||||
tab: TimestampPage,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'storageCleaner',
|
key: 'storageCleaner',
|
||||||
@@ -73,11 +61,7 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'warning',
|
themeColorKey: 'warning',
|
||||||
icon: Database,
|
icon: Database,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
components: {
|
component: StorageCleanerPage,
|
||||||
popup: StorageCleanerPage,
|
|
||||||
sidepanel: StorageCleanerPage,
|
|
||||||
tab: StorageCleanerPage,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'qrCode',
|
key: 'qrCode',
|
||||||
@@ -86,11 +70,7 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'success',
|
themeColorKey: 'success',
|
||||||
icon: QrCode,
|
icon: QrCode,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
components: {
|
component: QrCodePage,
|
||||||
popup: QrCodePage,
|
|
||||||
sidepanel: QrCodePage,
|
|
||||||
tab: QrCodePage,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'textStatistics',
|
key: 'textStatistics',
|
||||||
@@ -99,11 +79,7 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'secondary',
|
themeColorKey: 'secondary',
|
||||||
icon: FileText,
|
icon: FileText,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
components: {
|
component: TextStatisticsPage,
|
||||||
popup: TextStatisticsPage,
|
|
||||||
sidepanel: TextStatisticsPage,
|
|
||||||
tab: TextStatisticsPage,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'jwt',
|
key: 'jwt',
|
||||||
@@ -112,11 +88,7 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'info',
|
themeColorKey: 'info',
|
||||||
icon: Key,
|
icon: Key,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
components: {
|
component: JwtPage,
|
||||||
popup: JwtPage,
|
|
||||||
sidepanel: JwtPage,
|
|
||||||
tab: JwtPage,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'jsonTools',
|
key: 'jsonTools',
|
||||||
@@ -125,11 +97,7 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'primary',
|
themeColorKey: 'primary',
|
||||||
icon: GitCompareArrows,
|
icon: GitCompareArrows,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
components: {
|
component: JsonToolsPage,
|
||||||
popup: JsonToolsPage,
|
|
||||||
sidepanel: JsonToolsPage,
|
|
||||||
tab: JsonToolsPage,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'base64Converter',
|
key: 'base64Converter',
|
||||||
@@ -138,11 +106,7 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'info',
|
themeColorKey: 'info',
|
||||||
icon: ArrowLeftRight,
|
icon: ArrowLeftRight,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
components: {
|
component: Base64ConverterPage,
|
||||||
popup: Base64ConverterPage,
|
|
||||||
sidepanel: Base64ConverterPage,
|
|
||||||
tab: Base64ConverterPage,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'rightClickRestorer',
|
key: 'rightClickRestorer',
|
||||||
@@ -151,11 +115,7 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'success',
|
themeColorKey: 'success',
|
||||||
icon: MousePointerClick,
|
icon: MousePointerClick,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
components: {
|
component: RightClickRestorerPage,
|
||||||
popup: RightClickRestorerPage,
|
|
||||||
sidepanel: RightClickRestorerPage,
|
|
||||||
tab: RightClickRestorerPage,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'testDataGenerator',
|
key: 'testDataGenerator',
|
||||||
@@ -164,11 +124,7 @@ export const FEATURES: FeatureConfig[] = [
|
|||||||
themeColorKey: 'warning',
|
themeColorKey: 'warning',
|
||||||
icon: FileSpreadsheet,
|
icon: FileSpreadsheet,
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
components: {
|
component: TestDataGeneratorPage,
|
||||||
popup: TestDataGeneratorPage,
|
|
||||||
sidepanel: TestDataGeneratorPage,
|
|
||||||
tab: TestDataGeneratorPage,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -16,16 +16,16 @@ export default function SearchDropdown({
|
|||||||
selectedIndex,
|
selectedIndex,
|
||||||
onSelect,
|
onSelect,
|
||||||
}: SearchDropdownProps) {
|
}: SearchDropdownProps) {
|
||||||
const isSearching = searchQuery.trim().length > 0;
|
const isSearching = !!searchQuery.trim();
|
||||||
const items = isSearching ? searchResults : recentFeatures;
|
const items = isSearching ? searchResults : recentFeatures;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="absolute left-0 right-0 top-full z-50 mt-1.5 max-h-80 overflow-y-auto rounded-lg border border-border bg-popover text-popover-foreground shadow-lg animate-in fade-in slide-in-from-top-2 duration-150">
|
<div className="absolute left-0 right-0 top-full z-50 mt-1.5 max-h-80 overflow-y-auto rounded-lg border border-border bg-popover text-popover-foreground shadow-lg animate-in fade-in slide-in-from-top-2 duration-150">
|
||||||
<ul role="listbox" className="p-1.5">
|
<ul role="listbox" className="p-1.5">
|
||||||
{!isSearching && items.length > 0 && (
|
{!isSearching && items.length > 0 && (
|
||||||
<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 ? (
|
{isSearching && items.length === 0 ? (
|
||||||
<li className="px-4 py-6 text-center text-sm text-muted-foreground">未找到相关工具</li>
|
<li className="px-4 py-6 text-center text-sm text-muted-foreground">未找到相关工具</li>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { type RefObject } from 'react';
|
import { type KeyboardEvent, type RefObject } from 'react';
|
||||||
import { Search, X } from 'lucide-react';
|
import { Search, X } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
@@ -9,7 +9,7 @@ interface SearchInputProps {
|
|||||||
searchQuery: string;
|
searchQuery: string;
|
||||||
onSearchQueryChange: (value: string) => void;
|
onSearchQueryChange: (value: string) => void;
|
||||||
onFocus: () => void;
|
onFocus: () => void;
|
||||||
onKeyDown: (e: React.KeyboardEvent) => void;
|
onKeyDown: (e: KeyboardEvent) => void;
|
||||||
onClear: () => 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" />
|
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/60 transition-colors group-focus-within:text-muted-foreground" />
|
||||||
<Input
|
<Input
|
||||||
ref={inputRef}
|
ref={inputRef}
|
||||||
type="text"
|
|
||||||
placeholder="搜索工具..."
|
placeholder="搜索工具..."
|
||||||
value={searchQuery}
|
value={searchQuery}
|
||||||
onChange={(e) => onSearchQueryChange(e.target.value)}
|
onChange={(e) => onSearchQueryChange(e.target.value)}
|
||||||
@@ -35,12 +34,7 @@ export default function SearchInput({
|
|||||||
aria-label="搜索工具..."
|
aria-label="搜索工具..."
|
||||||
className="h-9 rounded-lg border-border/60 bg-muted/40 pl-9 pr-16 shadow-none focus-visible:ring-1 focus-visible:ring-offset-0 placeholder:text-muted-foreground/50"
|
className="h-9 rounded-lg border-border/60 bg-muted/40 pl-9 pr-16 shadow-none focus-visible:ring-1 focus-visible:ring-offset-0 placeholder:text-muted-foreground/50"
|
||||||
/>
|
/>
|
||||||
{!searchQuery && (
|
{searchQuery ? (
|
||||||
<kbd className="pointer-events-none absolute right-3 top-1/2 hidden h-5 -translate-y-1/2 items-center gap-0.5 rounded border border-border/60 bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground/60 sm:inline-flex">
|
|
||||||
{getSearchShortcutLabel()}
|
|
||||||
</kbd>
|
|
||||||
)}
|
|
||||||
{searchQuery && (
|
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
@@ -51,6 +45,10 @@ export default function SearchInput({
|
|||||||
>
|
>
|
||||||
<X className="h-3 w-3" />
|
<X className="h-3 w-3" />
|
||||||
</Button>
|
</Button>
|
||||||
|
) : (
|
||||||
|
<kbd className="pointer-events-none absolute right-3 top-1/2 hidden h-5 -translate-y-1/2 items-center rounded border border-border/60 bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground/60 sm:inline-flex">
|
||||||
|
{getSearchShortcutLabel()}
|
||||||
|
</kbd>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -33,9 +33,7 @@ export default function TopBar() {
|
|||||||
id: 'open-in-tab',
|
id: 'open-in-tab',
|
||||||
icon: ExternalLink,
|
icon: ExternalLink,
|
||||||
title: '在标签页打开',
|
title: '在标签页打开',
|
||||||
onClick: () => {
|
onClick: () => void handleOpenInTab(),
|
||||||
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 { Monitor, Moon, Sun } from 'lucide-react';
|
||||||
import { useRouter } from '@/providers/RouterProvider';
|
import { useRouter } from '@/providers/RouterProvider';
|
||||||
import { useThemeMode } from '@/providers/ThemeModeProvider';
|
import { useThemeMode } from '@/providers/ThemeModeProvider';
|
||||||
@@ -21,7 +28,7 @@ export interface UseTopBarReturn {
|
|||||||
handleSearchQueryChange: (value: string) => void;
|
handleSearchQueryChange: (value: string) => void;
|
||||||
handleSearchFocus: () => void;
|
handleSearchFocus: () => void;
|
||||||
handleSelectFeature: (feature: FeatureConfig) => void;
|
handleSelectFeature: (feature: FeatureConfig) => void;
|
||||||
handleKeyDown: (e: React.KeyboardEvent) => void;
|
handleKeyDown: (e: ReactKeyboardEvent) => void;
|
||||||
cycleThemeMode: () => void;
|
cycleThemeMode: () => void;
|
||||||
handleOpenInTab: () => Promise<void>;
|
handleOpenInTab: () => Promise<void>;
|
||||||
goHome: () => void;
|
goHome: () => void;
|
||||||
@@ -80,7 +87,7 @@ export function useTopBar(): UseTopBarReturn {
|
|||||||
});
|
});
|
||||||
}, [searchQuery]);
|
}, [searchQuery]);
|
||||||
|
|
||||||
const displayedHistory = useMemo(() => {
|
const recentFeatures = useMemo(() => {
|
||||||
if (searchQuery.trim()) return [];
|
if (searchQuery.trim()) return [];
|
||||||
return searchHistory
|
return searchHistory
|
||||||
.slice(0, SEARCH_HISTORY_DISPLAY)
|
.slice(0, SEARCH_HISTORY_DISPLAY)
|
||||||
@@ -111,8 +118,10 @@ export function useTopBar(): UseTopBarReturn {
|
|||||||
const themeTitle =
|
const themeTitle =
|
||||||
mode === 'light' ? '切换到深色模式' : mode === 'dark' ? '切换到系统模式' : '切换到浅色模式';
|
mode === 'light' ? '切换到深色模式' : mode === 'dark' ? '切换到系统模式' : '切换到浅色模式';
|
||||||
|
|
||||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
const handleKeyDown = (e: ReactKeyboardEvent) => {
|
||||||
const totalItems = searchQuery.trim() ? searchResults.length : displayedHistory.length;
|
const isSearching = !!searchQuery.trim();
|
||||||
|
const items = isSearching ? searchResults : recentFeatures;
|
||||||
|
const totalItems = items.length;
|
||||||
|
|
||||||
if (e.key === 'ArrowDown') {
|
if (e.key === 'ArrowDown') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -122,13 +131,12 @@ export function useTopBar(): UseTopBarReturn {
|
|||||||
setSelectedIndex((prev) => (prev > 0 ? prev - 1 : prev));
|
setSelectedIndex((prev) => (prev > 0 ? prev - 1 : prev));
|
||||||
} else if (e.key === 'Enter') {
|
} else if (e.key === 'Enter') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const items = searchQuery.trim() ? searchResults : displayedHistory;
|
let feature: FeatureConfig | undefined;
|
||||||
const feature =
|
if (selectedIndex >= 0 && selectedIndex < totalItems) {
|
||||||
selectedIndex >= 0 && selectedIndex < totalItems
|
feature = items[selectedIndex];
|
||||||
? items[selectedIndex]
|
} else if (isSearching && searchResults.length > 0) {
|
||||||
: searchQuery.trim() && searchResults.length > 0
|
feature = searchResults[0];
|
||||||
? searchResults[0]
|
}
|
||||||
: undefined;
|
|
||||||
if (feature) handleSelectFeature(feature);
|
if (feature) handleSelectFeature(feature);
|
||||||
} else if (e.key === 'Escape') {
|
} else if (e.key === 'Escape') {
|
||||||
setShowResults(false);
|
setShowResults(false);
|
||||||
@@ -149,13 +157,12 @@ export function useTopBar(): UseTopBarReturn {
|
|||||||
|
|
||||||
const handleSearchFocus = () => setShowResults(true);
|
const handleSearchFocus = () => setShowResults(true);
|
||||||
|
|
||||||
const showDropdown =
|
const showDropdown = showResults && (!!searchQuery.trim() || recentFeatures.length > 0);
|
||||||
showResults && (searchQuery.trim().length > 0 || displayedHistory.length > 0);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
searchQuery,
|
searchQuery,
|
||||||
searchResults,
|
searchResults,
|
||||||
recentFeatures: displayedHistory,
|
recentFeatures,
|
||||||
selectedIndex,
|
selectedIndex,
|
||||||
showDropdown,
|
showDropdown,
|
||||||
isDashboard: currentPage === 'dashboard',
|
isDashboard: currentPage === 'dashboard',
|
||||||
|
|||||||
+1
-2
@@ -1,6 +1,5 @@
|
|||||||
import { type ClassValue, clsx } from 'clsx';
|
import { type ClassValue, clsx } from 'clsx';
|
||||||
import { twMerge } from 'tailwind-merge';
|
|
||||||
|
|
||||||
export function cn(...inputs: ClassValue[]) {
|
export function cn(...inputs: ClassValue[]) {
|
||||||
return twMerge(clsx(inputs));
|
return clsx(inputs);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,7 +22,9 @@ vi.mock('../components/TextMode', () => ({
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock('../components/Base64ConverterSection', () => ({
|
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 = () =>
|
const waitForStorageInit = () =>
|
||||||
|
|||||||
@@ -50,10 +50,6 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
|
|||||||
setDirection(next);
|
setDirection(next);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDownload = () => {
|
|
||||||
if (decoded) downloadBlob(decoded.blob, decodedFileName);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-full flex flex-col space-y-4 px-2">
|
<div className="w-full flex flex-col space-y-4 px-2">
|
||||||
<div className="flex h-11 items-center px-1.5 bg-secondary/40 rounded-xl border border-border/60 w-fit">
|
<div className="flex h-11 items-center px-1.5 bg-secondary/40 rounded-xl border border-border/60 w-fit">
|
||||||
@@ -115,7 +111,7 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
|
|||||||
/>
|
/>
|
||||||
</div>
|
</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">
|
<span className="text-sm font-bold text-foreground/90 max-w-[280px] truncate">
|
||||||
{info.name}
|
{info.name}
|
||||||
</span>
|
</span>
|
||||||
@@ -137,11 +133,11 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
|
|||||||
{mode === 'image' ? '点击或拖拽图像到此处' : '点击或拖拽文件到此处'}
|
{mode === 'image' ? '点击或拖拽图像到此处' : '点击或拖拽文件到此处'}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-[10px] font-medium text-muted-foreground/60">
|
<span className="text-[10px] font-medium text-muted-foreground/60">
|
||||||
{`最大文件大小:${maxFileSizeStr}`}
|
最大文件大小:{maxFileSizeStr}
|
||||||
</span>
|
</span>
|
||||||
{mode === 'image' && (
|
{mode === 'image' && (
|
||||||
<span className="text-[10px] font-medium text-muted-foreground/50">
|
<span className="text-[10px] font-medium text-muted-foreground/50">
|
||||||
{'支持 PNG、JPG、WEBP、GIF、BMP、SVG 等格式'}
|
支持 PNG、JPG、WEBP、GIF、BMP、SVG 等格式
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -231,7 +227,7 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
|
|||||||
blobSize={decoded.blob.size}
|
blobSize={decoded.blob.size}
|
||||||
fileName={decodedFileName}
|
fileName={decodedFileName}
|
||||||
onFileNameChange={setCustomFileName}
|
onFileNameChange={setCustomFileName}
|
||||||
onDownload={handleDownload}
|
onDownload={() => downloadBlob(decoded.blob, decodedFileName)}
|
||||||
>
|
>
|
||||||
{mode === 'image' && (
|
{mode === 'image' && (
|
||||||
<div className="relative p-1.5 border border-border bg-background dark:bg-muted/10 rounded-xl max-w-[220px] mb-3 overflow-hidden shadow-sm">
|
<div className="relative p-1.5 border border-border bg-background dark:bg-muted/10 rounded-xl max-w-[220px] mb-3 overflow-hidden shadow-sm">
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import { cn } from '@/lib/utils';
|
|
||||||
import { useDashboard } from './useDashboard';
|
import { useDashboard } from './useDashboard';
|
||||||
|
|
||||||
export default function Index() {
|
export default function Index() {
|
||||||
const { visibleFeatures, recentFeatures, showRecent, navigateTo } = useDashboard();
|
const { visibleFeatures, recentFeatures, showRecent, navigateTo } = useDashboard();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={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 && (
|
{showRecent && (
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
<h3 className="text-xs font-semibold text-muted-foreground/80 uppercase tracking-wider">
|
<h3 className="text-xs font-semibold text-muted-foreground/80 uppercase tracking-wider">
|
||||||
@@ -19,12 +18,7 @@ export default function Index() {
|
|||||||
key={key}
|
key={key}
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => navigateTo(key)}
|
onClick={() => navigateTo(key)}
|
||||||
className={cn(
|
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"
|
||||||
'inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium',
|
|
||||||
'border border-border/60 bg-card text-card-foreground',
|
|
||||||
'hover:bg-muted/40 hover:border-primary/30',
|
|
||||||
'transition-colors cursor-pointer',
|
|
||||||
)}
|
|
||||||
>
|
>
|
||||||
<IconComponent className="h-3.5 w-3.5 text-muted-foreground/70" />
|
<IconComponent className="h-3.5 w-3.5 text-muted-foreground/70" />
|
||||||
{feature.label}
|
{feature.label}
|
||||||
@@ -42,9 +36,7 @@ export default function Index() {
|
|||||||
{visibleFeatures.length === 0 ? (
|
{visibleFeatures.length === 0 ? (
|
||||||
<p className="text-sm text-muted-foreground py-4 text-center">没有可用的工具</p>
|
<p className="text-sm text-muted-foreground py-4 text-center">没有可用的工具</p>
|
||||||
) : (
|
) : (
|
||||||
<div
|
<div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 gap-2">
|
||||||
className={cn('grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 gap-2')}
|
|
||||||
>
|
|
||||||
{visibleFeatures.map(({ key, feature }) => {
|
{visibleFeatures.map(({ key, feature }) => {
|
||||||
const IconComponent = feature.icon;
|
const IconComponent = feature.icon;
|
||||||
return (
|
return (
|
||||||
@@ -52,20 +44,9 @@ export default function Index() {
|
|||||||
key={key}
|
key={key}
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => navigateTo(key)}
|
onClick={() => navigateTo(key)}
|
||||||
className={cn(
|
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"
|
||||||
'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
|
<IconComponent className="h-5 w-5 text-muted-foreground/70 group-hover:text-foreground transition-colors" />
|
||||||
className={cn(
|
|
||||||
'h-5 w-5 text-muted-foreground/70',
|
|
||||||
'group-hover:text-foreground',
|
|
||||||
'transition-colors',
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<span className="text-[11px] font-medium text-muted-foreground/80 group-hover:text-foreground leading-tight text-center truncate w-full transition-colors">
|
<span className="text-[11px] font-medium text-muted-foreground/80 group-hover:text-foreground leading-tight text-center truncate w-full transition-colors">
|
||||||
{feature.label}
|
{feature.label}
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -126,7 +126,34 @@ describe('StorageCleaner 页面', () => {
|
|||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(clearStorage).not.toHaveBeenCalled();
|
expect(clearStorage).not.toHaveBeenCalled();
|
||||||
expect(toast.warning).toHaveBeenCalledWith('当前标签页已切换,请等待数据刷新后再清理');
|
expect(toast.warning).toHaveBeenCalledWith('当前页面已变更,请等待数据刷新后再清理');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('同一标签页 URL 变更后、数据刷新完成前不应执行清理', async () => {
|
||||||
|
let currentUrl = 'https://a.example.com';
|
||||||
|
vi.mocked(getCurrentTab).mockImplementation(
|
||||||
|
async () =>
|
||||||
|
({
|
||||||
|
id: 1,
|
||||||
|
url: currentUrl,
|
||||||
|
}) as any,
|
||||||
|
);
|
||||||
|
|
||||||
|
render(<Index />);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByRole('button', { name: /立即清理/ })).not.toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
currentUrl = 'https://b.example.com';
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /立即清理/ }));
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /确认清理/ }));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(clearStorage).not.toHaveBeenCalled();
|
||||||
|
expect(toast.warning).toHaveBeenCalledWith('当前页面已变更,请等待数据刷新后再清理');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -258,8 +258,8 @@ export function useStorageCleaner(): UseStorageCleanerReturn {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const boundTab = boundTabRef.current;
|
const boundTab = boundTabRef.current;
|
||||||
if (!boundTab || boundTab.id !== tab.id) {
|
if (!boundTab || boundTab.id !== tab.id || boundTab.url !== tab.url) {
|
||||||
toast.warning('当前标签页已切换,请等待数据刷新后再清理');
|
toast.warning('当前页面已变更,请等待数据刷新后再清理');
|
||||||
setShowConfirm(false);
|
setShowConfirm(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -234,29 +234,38 @@ export default function FieldList({
|
|||||||
if (!ruleName.trim()) return;
|
if (!ruleName.trim()) return;
|
||||||
|
|
||||||
const trimmedName = ruleName.trim();
|
const trimmedName = ruleName.trim();
|
||||||
|
const existingRule = ruleStorage.getByName(trimmedName);
|
||||||
|
|
||||||
// 检查名称是否重复
|
// 检查名称是否重复
|
||||||
if (!overwrite) {
|
if (!overwrite && existingRule) {
|
||||||
const existingRule = ruleStorage.getByName(trimmedName);
|
|
||||||
if (existingRule) {
|
|
||||||
setShowConfirmOverwrite(true);
|
setShowConfirmOverwrite(true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
const newRule = ruleStorage.save({
|
const savedRule = ruleStorage.save(
|
||||||
|
overwrite && existingRule
|
||||||
|
? {
|
||||||
|
id: existingRule.id,
|
||||||
name: trimmedName,
|
name: trimmedName,
|
||||||
description: ruleDescription.trim(),
|
description: ruleDescription.trim(),
|
||||||
fields: fields,
|
fields: fields,
|
||||||
});
|
}
|
||||||
|
: {
|
||||||
|
name: trimmedName,
|
||||||
|
description: ruleDescription.trim(),
|
||||||
|
fields: fields,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
if (newRule) {
|
if (savedRule) {
|
||||||
setShowSaveDialog(false);
|
setShowSaveDialog(false);
|
||||||
setShowConfirmOverwrite(false);
|
setShowConfirmOverwrite(false);
|
||||||
setRuleName('');
|
setRuleName('');
|
||||||
setRuleDescription('');
|
setRuleDescription('');
|
||||||
toast.success('规则已保存');
|
toast.success(overwrite ? '规则已覆盖' : '规则已保存');
|
||||||
onRuleSaved?.();
|
onRuleSaved?.();
|
||||||
|
} else {
|
||||||
|
toast.error('规则保存失败');
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[ruleName, ruleDescription, fields, onRuleSaved],
|
[ruleName, ruleDescription, fields, onRuleSaved],
|
||||||
@@ -277,7 +286,7 @@ export default function FieldList({
|
|||||||
onClick={handleUpdateRule}
|
onClick={handleUpdateRule}
|
||||||
disabled={fields.length === 0}
|
disabled={fields.length === 0}
|
||||||
className="h-8 gap-1.5 px-2.5"
|
className="h-8 gap-1.5 px-2.5"
|
||||||
title={`编辑中: ${editingRule.name}`}
|
title={editingRule ? `编辑中: ${editingRule.name}` : ''}
|
||||||
>
|
>
|
||||||
<Save className="h-3.5 w-3.5" />
|
<Save className="h-3.5 w-3.5" />
|
||||||
更新规则
|
更新规则
|
||||||
|
|||||||
@@ -33,7 +33,10 @@ export default function GenerateButton({
|
|||||||
{progress && (
|
{progress && (
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||||
<span>{`已生成 ${progress.generated.toLocaleString()} / ${progress.total.toLocaleString()} 条`}</span>
|
<span>
|
||||||
|
已生成 {progress.generated.toLocaleString()} / {progress.total.toLocaleString()}{' '}
|
||||||
|
条
|
||||||
|
</span>
|
||||||
<span>{progress.progress}%</span>
|
<span>{progress.progress}%</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="h-2 bg-muted rounded-full overflow-hidden">
|
<div className="h-2 bg-muted rounded-full overflow-hidden">
|
||||||
@@ -44,7 +47,7 @@ export default function GenerateButton({
|
|||||||
</div>
|
</div>
|
||||||
{progress.estimatedTimeLeft !== undefined && (
|
{progress.estimatedTimeLeft !== undefined && (
|
||||||
<p className="text-xs text-muted-foreground text-center">
|
<p className="text-xs text-muted-foreground text-center">
|
||||||
{`预计剩余 ${Math.ceil(progress.estimatedTimeLeft / 1000)} 秒`}
|
预计剩余 {Math.ceil(progress.estimatedTimeLeft / 1000)} 秒
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ export default function ResultPanel({ result }: ResultPanelProps) {
|
|||||||
))}
|
))}
|
||||||
{result.warnings.length > 5 && (
|
{result.warnings.length > 5 && (
|
||||||
<li className="text-xs text-yellow-500/80">
|
<li className="text-xs text-yellow-500/80">
|
||||||
{`... 还有 ${result.warnings.length - 5} 条警告`}
|
... 还有 {result.warnings.length - 5} 条警告
|
||||||
</li>
|
</li>
|
||||||
)}
|
)}
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -227,7 +227,7 @@ export default function RuleManager({ onLoad, onEdit, onRulesChanged }: RuleMana
|
|||||||
maxLength={20}
|
maxLength={20}
|
||||||
/>
|
/>
|
||||||
<span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground pointer-events-none tabular-nums">
|
<span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground pointer-events-none tabular-nums">
|
||||||
{`已保存 ${rules.length}/${ruleStorage.MAX_RULES} 条`}
|
已保存 {rules.length}/{ruleStorage.MAX_RULES} 条
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -260,7 +260,7 @@ export default function RuleManager({ onLoad, onEdit, onRulesChanged }: RuleMana
|
|||||||
<Clock className="h-3 w-3" />
|
<Clock className="h-3 w-3" />
|
||||||
{formatDate(rule.updatedAt)}
|
{formatDate(rule.updatedAt)}
|
||||||
</span>
|
</span>
|
||||||
<span>{`使用 ${rule.useCount} 次`}</span>
|
<span>使用 {rule.useCount} 次</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -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(result.current.isGenerating).toBe(false);
|
||||||
expect(worker.postedMessages).toEqual(expect.arrayContaining([{ type: 'cancel' }]));
|
expect(worker.postedMessages).toEqual(expect.arrayContaining([{ type: 'cancel' }]));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('正在生成时不应重复发送 start 消息', () => {
|
||||||
|
const { result } = renderHook(() => useGenerator());
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
result.current.generate([mockField], 10);
|
||||||
|
result.current.generate([mockField], 20);
|
||||||
|
});
|
||||||
|
|
||||||
|
const worker = MockWorker.instances[0];
|
||||||
|
const startMessages = worker.postedMessages.filter(
|
||||||
|
(message): message is { type: 'start'; payload: { count: number } } =>
|
||||||
|
typeof message === 'object' &&
|
||||||
|
message !== null &&
|
||||||
|
'type' in message &&
|
||||||
|
message.type === 'start',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(startMessages).toHaveLength(1);
|
||||||
|
expect(startMessages[0]?.payload.count).toBe(10);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -37,6 +37,12 @@ export function useGenerator(): UseGeneratorReturn {
|
|||||||
|
|
||||||
const workerRef = useRef<Worker | null>(null);
|
const workerRef = useRef<Worker | null>(null);
|
||||||
const generationIdRef = useRef(0);
|
const generationIdRef = useRef(0);
|
||||||
|
const isGeneratingRef = useRef(false);
|
||||||
|
|
||||||
|
const finishGenerating = useCallback(() => {
|
||||||
|
isGeneratingRef.current = false;
|
||||||
|
setIsGenerating(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
// 清理 Worker
|
// 清理 Worker
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -73,7 +79,7 @@ export function useGenerator(): UseGeneratorReturn {
|
|||||||
setProgress(data.payload);
|
setProgress(data.payload);
|
||||||
break;
|
break;
|
||||||
case 'complete':
|
case 'complete':
|
||||||
setIsGenerating(false);
|
finishGenerating();
|
||||||
if (data.payload.success) {
|
if (data.payload.success) {
|
||||||
setResult(data.payload);
|
setResult(data.payload);
|
||||||
} else if (data.payload.error && data.payload.error !== '生成已取消') {
|
} else if (data.payload.error && data.payload.error !== '生成已取消') {
|
||||||
@@ -82,7 +88,7 @@ export function useGenerator(): UseGeneratorReturn {
|
|||||||
setProgress(null);
|
setProgress(null);
|
||||||
break;
|
break;
|
||||||
case 'error':
|
case 'error':
|
||||||
setIsGenerating(false);
|
finishGenerating();
|
||||||
setError(data.payload.error);
|
setError(data.payload.error);
|
||||||
setProgress(null);
|
setProgress(null);
|
||||||
break;
|
break;
|
||||||
@@ -91,7 +97,7 @@ export function useGenerator(): UseGeneratorReturn {
|
|||||||
|
|
||||||
worker.onerror = (err) => {
|
worker.onerror = (err) => {
|
||||||
console.error('[useGenerator] Worker 错误:', err);
|
console.error('[useGenerator] Worker 错误:', err);
|
||||||
setIsGenerating(false);
|
finishGenerating();
|
||||||
setError(err.message || 'Worker 运行错误');
|
setError(err.message || 'Worker 运行错误');
|
||||||
setProgress(null);
|
setProgress(null);
|
||||||
// Worker 出错后销毁,下次重新创建
|
// Worker 出错后销毁,下次重新创建
|
||||||
@@ -101,16 +107,17 @@ export function useGenerator(): UseGeneratorReturn {
|
|||||||
|
|
||||||
workerRef.current = worker;
|
workerRef.current = worker;
|
||||||
return worker;
|
return worker;
|
||||||
}, []);
|
}, [finishGenerating]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 开始生成
|
* 开始生成
|
||||||
*/
|
*/
|
||||||
const generate = useCallback(
|
const generate = useCallback(
|
||||||
(fields: FieldConfig[], count: number, csvMode = false) => {
|
(fields: FieldConfig[], count: number, csvMode = false) => {
|
||||||
if (isGenerating) return;
|
if (isGeneratingRef.current) return;
|
||||||
|
|
||||||
const generationId = ++generationIdRef.current;
|
const generationId = ++generationIdRef.current;
|
||||||
|
isGeneratingRef.current = true;
|
||||||
|
|
||||||
setIsGenerating(true);
|
setIsGenerating(true);
|
||||||
setProgress(null);
|
setProgress(null);
|
||||||
@@ -124,21 +131,22 @@ export function useGenerator(): UseGeneratorReturn {
|
|||||||
};
|
};
|
||||||
worker.postMessage(message);
|
worker.postMessage(message);
|
||||||
},
|
},
|
||||||
[isGenerating, getWorker],
|
[getWorker],
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 取消生成
|
* 取消生成
|
||||||
*/
|
*/
|
||||||
const cancel = useCallback(() => {
|
const cancel = useCallback(() => {
|
||||||
if (workerRef.current && isGenerating) {
|
if (workerRef.current && isGeneratingRef.current) {
|
||||||
++generationIdRef.current;
|
++generationIdRef.current;
|
||||||
const message: WorkerRequestMessage = { type: 'cancel' };
|
const message: WorkerRequestMessage = { type: 'cancel' };
|
||||||
workerRef.current.postMessage(message);
|
workerRef.current.postMessage(message);
|
||||||
|
isGeneratingRef.current = false;
|
||||||
setIsGenerating(false);
|
setIsGenerating(false);
|
||||||
setProgress(null);
|
setProgress(null);
|
||||||
}
|
}
|
||||||
}, [isGenerating]);
|
}, []);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 清除结果
|
* 清除结果
|
||||||
|
|||||||
@@ -48,6 +48,27 @@ describe('ruleStorage', () => {
|
|||||||
expect(updated).toBeNull();
|
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', () => {
|
it('deleteRule 在 localStorage 写入失败时应返回 false', () => {
|
||||||
const saved = ruleStorage.save({
|
const saved = ruleStorage.save({
|
||||||
name: 'Test Rule',
|
name: 'Test Rule',
|
||||||
|
|||||||
@@ -14,10 +14,14 @@ import type {
|
|||||||
/** 每生成 N 行让出一次事件循环,以便处理 cancel 消息 */
|
/** 每生成 N 行让出一次事件循环,以便处理 cancel 消息 */
|
||||||
const YIELD_EVERY = 100;
|
const YIELD_EVERY = 100;
|
||||||
|
|
||||||
// 生成结果缓存
|
/** 当前活跃生成任务 ID;新 start 会 supersede 旧任务 */
|
||||||
let generatedData: Record<string, unknown>[] = [];
|
let activeGenerationId: number | null = null;
|
||||||
let isCancelled = false;
|
let isCancelled = false;
|
||||||
|
|
||||||
|
function shouldAbort(generationId: number): boolean {
|
||||||
|
return isCancelled || generationId !== activeGenerationId;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Worker 消息处理器
|
* Worker 消息处理器
|
||||||
*/
|
*/
|
||||||
@@ -27,12 +31,17 @@ self.onmessage = async (e: MessageEvent<WorkerRequestMessage>) => {
|
|||||||
|
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case 'start':
|
case 'start':
|
||||||
|
activeGenerationId = data.payload.generationId;
|
||||||
isCancelled = false;
|
isCancelled = false;
|
||||||
await handleStart(data.payload);
|
await handleStart(data.payload);
|
||||||
break;
|
break;
|
||||||
case 'cancel':
|
case 'cancel':
|
||||||
isCancelled = true;
|
isCancelled = true;
|
||||||
break;
|
break;
|
||||||
|
default: {
|
||||||
|
const _exhaustive: never = type;
|
||||||
|
return _exhaustive;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -46,7 +55,7 @@ async function handleStart(payload: {
|
|||||||
csvMode: boolean;
|
csvMode: boolean;
|
||||||
}): Promise<void> {
|
}): Promise<void> {
|
||||||
const { generationId, fields, count } = payload;
|
const { generationId, fields, count } = payload;
|
||||||
generatedData = [];
|
const generatedData: Record<string, unknown>[] = [];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 验证所有生成器是否存在
|
// 验证所有生成器是否存在
|
||||||
@@ -67,7 +76,8 @@ async function handleStart(payload: {
|
|||||||
|
|
||||||
// 生成数据
|
// 生成数据
|
||||||
for (let i = 0; i < count; i++) {
|
for (let i = 0; i < count; i++) {
|
||||||
if (isCancelled) {
|
if (shouldAbort(generationId)) {
|
||||||
|
if (generationId === activeGenerationId) {
|
||||||
self.postMessage({
|
self.postMessage({
|
||||||
type: 'complete',
|
type: 'complete',
|
||||||
generationId,
|
generationId,
|
||||||
@@ -76,6 +86,7 @@ async function handleStart(payload: {
|
|||||||
error: '生成已取消',
|
error: '生成已取消',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,7 +159,8 @@ async function handleStart(payload: {
|
|||||||
// 定期让出事件循环,使 cancel 消息能被处理
|
// 定期让出事件循环,使 cancel 消息能被处理
|
||||||
if ((i + 1) % YIELD_EVERY === 0) {
|
if ((i + 1) % YIELD_EVERY === 0) {
|
||||||
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
||||||
if (isCancelled) {
|
if (shouldAbort(generationId)) {
|
||||||
|
if (generationId === activeGenerationId) {
|
||||||
self.postMessage({
|
self.postMessage({
|
||||||
type: 'complete',
|
type: 'complete',
|
||||||
generationId,
|
generationId,
|
||||||
@@ -157,11 +169,16 @@ async function handleStart(payload: {
|
|||||||
error: '生成已取消',
|
error: '生成已取消',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (shouldAbort(generationId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const duration = Date.now() - startTime;
|
const duration = Date.now() - startTime;
|
||||||
const successCount = generatedData.filter((item) => Object.keys(item).length > 0).length;
|
const successCount = generatedData.filter((item) => Object.keys(item).length > 0).length;
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user