Compare commits

..

1 Commits

Author SHA1 Message Date
Cursor Agent 8ac7a92016 fix: 修复规则导入失败、Worker 过期响应与 popup 标签页解析错误
- ruleStorage.importRules:导出备份含 id 时按新规则导入,避免 save 误判为更新
- 移植 generationId 机制与 Worker 事件循环让出,修复取消后展示错误数据
- 将 getCurrentTab 提取至 chromeTabs,RightClickRestorer 与 messages 复用 lastFocusedWindow 查询
2026-06-26 11:08:23 +00:00
183 changed files with 3298 additions and 3966 deletions
+79 -84
View File
@@ -265,11 +265,12 @@ const visibleSet = useMemo(() => new Set<string>(visiblePages), [visiblePages]);
2. 第三方库(图标、UI 库等)
3. 业务 Provider / Context
4. 配置 / 存储
5. 本地页面组件
6. UI 组件
7. 工具函数 / Hook
8. 类型
9. 常量
5. i18n
6. 本地页面组件
7. UI 组件
8. 工具函数 / Hook
9. 类型
10. 常量
```typescript
// 1. React 核心
@@ -283,16 +284,19 @@ import { useThemeMode } from '@/providers/ThemeModeProvider';
// 4. 配置 / 存储
import { FeatureConfig, FEATURES } from '@/config/features';
import { storageUtil } from '@/utils/chromeStorage';
// 5. 本地组件
// 5. i18n
import { useTranslation } from 'react-i18next';
import { normalizeLanguage, SUPPORTED_LANGUAGES } from '@/i18n';
// 6. 本地组件
import TextMode from './TextMode';
import { ZONES } from './constants';
// 6. UI 组件
// 7. UI 组件
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
import { Button } from '@/components/ui/button';
// 7. 工具函数 / Hook
// 8. 工具函数 / Hook
import { cn } from '@/lib/utils';
import { useStorageState } from '@/utils/useStorageState';
// 8. 类型
import { useLazyTranslation } from '@/utils/useLazyTranslation';
// 9. 类型
import type { PageType, StorageSchema } from '@/types/storage';
```
@@ -397,22 +401,22 @@ className={cn(
## 5. 错误处理
### 5.1 工具函数:可恢复错误返回可判断结果
### 5.1 工具函数:结果对象模式
可恢复的解析/校验错误应返回可判断的结果,避免工具层直接弹 Toast。确需保留底层异常的函数
(如 `formatJson` / `minifyJson`)必须在页面 Hook 或 UI 层捕获并转换为用户提示:
工具函数**不抛异常**,返回包含 `hasError``error` 字段的结果对象:
```typescript
// ✅ 可恢复校验返回错误消息,调用方据此展示 UI
export function validateJson(text: string): string | null {
if (!text.trim()) {
return null;
}
// ✅ 结果对象模式
export function markdownToHtml(markdown: string): MarkdownToHtmlResult {
try {
JSON.parse(text.trim());
return null;
} catch (e) {
return e instanceof SyntaxError ? e.message : 'Invalid JSON';
...
return { html, originalLength, htmlLength, hasError: false };
} catch (error) {
return {
html: '', ...
hasError: true,
error: error instanceof Error ? error.message : 'Markdown 解析失败',
};
}
}
```
@@ -556,7 +560,7 @@ describe('SwitchButtonGroup 组件', () => {
- 使用 `vi.mock()` 进行模块级 Mock
- 使用 `vi.fn()` 进行函数级 Mock
- 使用 `vi.useFakeTimers()` 控制时间
- **避免重复 mock `vitest.setup.ts` 中已有的内容**chrome API、matchMedia 等)
- **避免重复 mock `vitest.setup.ts` 中已有的内容**chrome API、i18n、matchMedia 等)
```typescript
// ✅ 模块级 Mock
@@ -654,7 +658,7 @@ export function useTimestampConverter(): UseTimestampConverterReturn { ... }
```
src/utils/useStorageState.ts — Chrome Storage 状态持久化
src/utils/syncSnapshot.ts localStorage 快照读取
src/utils/useLazyTranslation.tsi18n 懒加载
src/utils/useContextMenuData.ts — 右键菜单数据
src/utils/useDebounce.ts — 防抖
src/pages/Timestamp/useTimestampConverter.ts — 页面级 Hook
@@ -663,51 +667,47 @@ src/pages/StorageCleaner/useStorageCleaner.ts — 页面级 Hook
---
## 9. UI 文案规范
## 9. 国际化规范
项目已移除 `chrome.i18n`,所有 UI 文案直接在代码中使用中文。
### 9.1 翻译键格式
### 9.1 功能元数据
- 命名空间:`common`(默认)、`features`
- 翻译键格式:`namespace:key`(如 `features:timestamp.title`
- 语言:`zh`(默认)、`en`
功能名称与描述在 `config/featureMeta.ts``FEATURES` 数组中定义:
### 9.2 翻译文件结构
```typescript
{
key: 'timestamp',
label: '时间戳转换',
description: '日期与时间戳互转',
defaultVisible: true,
}
```
i18n/locales/{zh,en}/common.json — 全局通用翻译
i18n/locales/{zh,en}/features.json — 功能模块标题和描述
i18n/locales/{zh,en}/{功能名}.json — 各功能独立翻译
```
页面组件通过 `config/pageLoaders/` 按需加载,不在 `FEATURES` 中引用。
Dashboard 卡片、TopBar 搜索等功能从此处读取 `label` / `description`
### 9.2 页面与组件文案
- 页面标题、按钮、提示信息等直接在 JSX 或 `constants.ts` 中写中文
- 错误消息可在 Hook 中定义,或使用常量映射
- Toast 通知使用 `sonner``toast()`,文案写在调用处或常量中
### 9.3 使用方式
```typescript
// ✅ 页面组件 — 直接写中文
// ✅ 页面组件 — 使用 useLazyTranslation
import { useLazyTranslation } from '@/utils/useLazyTranslation';
export default function Index() {
return <h1 className="font-bold text-sm"></h1>;
const { t } = useLazyTranslation('timestamp');
return <h1>{t('timestamp:title')}</h1>;
}
// ✅ 常量文件 — 可复用文案
export const ERROR_MESSAGES = {
invalidInput: '输入格式无效',
conversionFailed: '转换失败',
} as const;
// ✅ 全局组件 — 使用 useTranslation
import { useTranslation } from 'react-i18next';
export function TopBar() {
const { t } = useTranslation(['common', 'features']);
return <span>{t('common:settings')}</span>;
}
```
### 9.3 添加新功能文案
### 9.4 添加新翻译
1.`config/features.tsx` 填写 `label``description`
2. 在页面组件、`constants.ts` 或 Hook 中编写 UI 文案
3. 扩展名称与描述在 `wxt.config.ts``manifest`维护
1.`i18n/locales/{zh,en}/features.json` 添加功能标题和描述
2. 创建 `i18n/locales/{zh,en}/{功能名}.json` 添加功能专属翻译
3. `utils/useLazyTranslation.ts``localeModules`注册新命名空间
---
@@ -760,18 +760,6 @@ const [themeMode, setThemeMode, isInitialized] = useStorageState(
);
```
### 10.4 首屏快照与初始化防覆盖
Chrome Storage 读取是异步的。项目通过 `localStorage` 快照(键名 `snapshot/{storageKey}`)提供同步初始值,消除首屏闪烁。
| 模块 | 快照工具 | 防覆盖机制 |
| ------------------- | ------------------ | ----------------------------------------------------------------------------------------- |
| `RouterProvider` | `syncSnapshot.ts` | `canPersistRef`(加载成功后才写入)、`hasUserNavigatedRef`(用户导航后不被 storage 覆盖) |
| `useStorageState` | `syncSnapshot.ts` | `loadSucceededRef``userModifiedRef` 为 true 时才写入 |
| `ThemeModeProvider` | `themeSnapshot.ts` | `hasUserSetMode`(用户切换主题后不被 storage 覆盖) |
新增持久化状态时,应遵循相同模式:同步快照作初始 state → 异步加载 storage → 加载成功或用户修改后才允许写入。
---
## 11. 页面开发规范
@@ -854,21 +842,24 @@ export default function DashboardPage() { ... }
#### 组件职责
`index.tsx` 只负责件事:
`index.tsx` 只负责件事:
1. **调用业务 Hook** 获取状态和操作方法
2. **渲染 UI 布局**(纯展示,无业务逻辑)
1. **获取翻译函数**`useI18n`
2. **调用业务 Hook** 获取状态和操作方法
3. **渲染 UI 布局**(纯展示,无业务逻辑)
```typescript
// ✅ 标准页面入口模板
import { useI18n } from '@/utils/chromeI18n';
import { useFeatureName } from './useFeatureName';
export default function Index() {
const { t } = useI18n('featureName');
const { state, actions } = useFeatureName();
return (
<div className="p-4 w-full flex flex-col space-y-4 select-none">
{/* 纯 UI 渲染,文案直接写中文 */}
{/* 纯 UI 渲染 */}
</div>
);
}
@@ -912,22 +903,25 @@ export function useTimestampConverter(): UseTimestampConverterReturn {
```typescript
export function useFeatureName(): UseFeatureNameReturn {
// 1. 基础 stateuseState
// 1. i18n
const { t } = useI18n('featureName');
// 2. 基础 stateuseState
const [mode, setMode] = useState<Mode>('default');
const [input, setInput] = useState('');
// 2. 持久化 stateuseStorageState
// 3. 持久化 stateuseStorageState
const [pageMode, setPageMode] = useStorageState('feature/pageMode', 'default', isValidMode);
// 3. 衍生数据(useMemo)— 响应式计算管线
// 4. 衍生数据(useMemo)— 响应式计算管线
const result = useMemo(() => {
// 自动计算,无需手动点击"转换"按钮
}, [input, mode]);
// 4. 事件处理(useCallback
// 5. 事件处理(useCallback
const handleAction = useCallback(() => { ... }, [deps]);
// 5. 副作用(useEffect)— 防抖、初始化、清理
// 6. 副作用(useEffect)— 防抖、初始化、清理
useEffect(() => { ... }, [deps]);
// 7. 右键菜单数据(页面需要时)
@@ -997,7 +991,7 @@ interface ResultViewProps extends React.HTMLAttributes<HTMLDivElement> {
// ✅ 使用 React.memo + displayName
const ResultView = React.memo(
({ result, mode, showEmptyPlaceholder = false, className, ...props }: ResultViewProps) => {
// 文案直接写中文或使用 constants
const { t } = useI18n('featureName');
// ...
},
);
@@ -1007,7 +1001,7 @@ export default ResultView;
#### 子组件内可以使用 Hook
子组件可以独立调用 `useRouter``useThemeMode``toast` 等全局 Hook/API,**不需要**通过 props 从父组件传递。
子组件可以独立调用 `useI18n``useSnackbar` 等全局 Hook**不需要**通过 props 从父组件传递翻译函数或 toast 方法
---
@@ -1044,6 +1038,7 @@ const isValidMode = (val: unknown): val is PageMode =>
typeof val === 'string' && (VALID_MODES as readonly string[]).includes(val);
export default function Index() {
const { t } = useI18n('featureName');
const [pageMode, setPageMode] = useStorageState('feature/pageMode', 'modeA', isValidMode);
return (
@@ -1051,8 +1046,8 @@ export default function Index() {
<SwitchButtonGroup
value={pageMode}
options={[
{ value: 'modeA', label: '模式 A' },
{ value: 'modeB', label: '模式 B' },
{ value: 'modeA', label: t('feature:modeA') },
{ value: 'modeB', label: t('feature:modeB') },
]}
onChange={(v: PageMode) => setPageMode(v)}
size="small"
@@ -1083,12 +1078,12 @@ export default function Index() {
新增功能页面时,逐项确认:
1. ✅ 在 `types/storage.d.ts` 添加 `PageType` 联合类型
2. ✅ 在 `config/features.tsx` 注册 `FEATURES` 配置(key、label、description、icon、三种渲染模式组件)
2. ✅ 在 `config/features.tsx` 注册 `FEATURES` 配置(key、labelKey、icon、三种渲染模式组件)
3. ✅ 创建页面目录,使用 `Index` 作为组件名
4. ✅ 业务逻辑提取到 `useXxx.ts` Hookindex.tsx 不超过 150 行)
5. ✅ 需要持久化的 UI 状态使用 `useStorageState`
6. ✅ 常量 ≥3 个时提取到 `constants.ts`
7. ✅ 在页面组件或 `constants.ts` 中编写 UI 文案
7. ✅ 在 `i18n/locales/{zh,en}/` 添加翻译
8. ✅ 创建 `__tests__/index.test.tsx` 测试文件
9. ✅ 如需新权限,更新 `wxt.config.ts` 的 `manifest.permissions`
10. ✅ 运行 `npm run lint && npm run typecheck && npm run test` 全部通过
@@ -1108,8 +1103,8 @@ export default function Index() {
| `src/hooks/` | 自定义 React Hooks |
| `src/utils/` | 工具函数与服务抽象 |
| `src/types/` | TypeScript 类型声明 |
| `src/lib/` | 通用工具函数与生成器库cn、utils、generators |
| `public/` | 静态资源(图标等) |
| `src/lib/` | 通用工具函数(cn、utils |
| `public/` | 静态资源 |
---
+20 -56
View File
@@ -1,6 +1,23 @@
# AGENTS.md
WXT 浏览器扩展项目 (React 19 + TypeScript)。提供时间戳转换、存储清理、JWT 解析、JSON 工具、二维码、Base64、测试数据生成器等测试效率工具。
WXT 浏览器扩展项目 (React 19 + TypeScript)。为开发者和测试人员提供浏览器内效率工具
## 功能列表
功能定义见 `src/config/features.tsx``PageType``src/types/storage.d.ts`
| key | 页面目录 | 说明 |
| -------------------- | -------------------------- | ------------------------------------------- |
| `dashboard` | `pages/Dashboard` | 仪表盘首页,工具导航与最近使用 |
| `timestamp` | `pages/Timestamp` | Unix 时间戳转换与格式化 |
| `storageCleaner` | `pages/StorageCleaner` | 清理 Cookies、本地存储、IndexedDB、Cache 等 |
| `qrCode` | `pages/QrCode` | 二维码生成与解析 |
| `textStatistics` | `pages/TextStatistics` | 文本字符、单词、行数、字节统计 |
| `jwt` | `pages/Jwt` | JWT 解码与查看 |
| `jsonTools` | `pages/JsonTools` | JSON 差异比较、格式化、YAML/TOML 转换与压缩 |
| `base64Converter` | `pages/Base64Converter` | 文本、文件、图像 Base64 编解码 |
| `rightClickRestorer` | `pages/RightClickRestorer` | 恢复被网站禁用的右键菜单 |
| `testDataGenerator` | `pages/TestDataGenerator` | 自定义规则批量生成测试数据 |
## 核心命令
@@ -61,7 +78,7 @@ src/ # 源代码根目录
lib/ # 通用工具函数(cn、utils)及数据生成器定义
workers/ # Web Worker(数据生成等耗时任务)
spec/ # 功能规格、修复方案与验收标准(见 spec/README.md
public/ # 静态资源(图标等)
public/ # 静态资源(图标、_locales 等)
.wxt/ # wxt prepare 自动生成,含类型声明与扩展 tsconfig(勿手动编辑)
.output/ # 生产构建输出目录
```
@@ -93,38 +110,6 @@ src/pages/FeatureName/
-`index.tsx` 超过 150 行时,必须拆分为 UI + Hook 模式
- 复杂页面可增加 `contexts/``hooks/``components/` 子目录
### 测试数据生成器模块
```
src/pages/TestDataGenerator/
├── index.tsx # 主页面(字段配置 + 标签页切换)
├── hooks/useGenerator.ts # Web Worker 管理 Hook(创建、复用、通信、销毁)
└── components/
├── FieldList.tsx # 字段列表(虚拟滚动 + @dnd-kit 拖拽排序 + 规则保存)
├── FieldItem.tsx # 字段卡片展示
├── FieldEditor.tsx # 字段编辑器(名称校验、生成器选择、参数配置)
├── GeneratorSelector.tsx # 生成器选择器(分类 + 搜索)
├── GeneratorConfig.tsx # 生成器参数表单(动态渲染 string/number/boolean/select/array
├── GenerateOptions.tsx # 生成选项(数量、格式)
├── GenerateButton.tsx # 生成按钮 + 进度条
├── DataPreview.tsx # 示例数据预览(JSON 语法高亮)
├── ResultPanel.tsx # 生成结果状态面板
├── ExportPanel.tsx # 导出面板(复制/下载 JSON/CSV)
└── RuleManager.tsx # 规则管理(CRUD、搜索、导入/导出)
src/utils/
├── ruleStorage.ts # 规则持久化存储(localStorage
└── dataExporter.ts # 数据导出工具(JSON/CSV 转换、下载、剪贴板)
src/lib/generators/ # 内置生成器定义(个人信息、企业、技术、基础类型)
src/workers/
└── generator.worker.ts # 数据生成 Web Worker
src/types/
└── testDataGenerator.ts # 类型定义(FieldConfig, DataRule, GeneratorDefinition 等)
```
## 关键架构决策
**路由**: 不使用 React Router。通过 `src/config/features.tsx``FEATURES` 数组管理,`RouterProvider` 根据 `PageType`
@@ -132,8 +117,7 @@ src/types/
每种模式有独立的路由和可见页面配置(`app/popupRoute``app/sidepanelRoute``app/tabRoute` 等)。
**存储**: 所有 Chrome Storage 键必须在 `src/types/storage.d.ts``StorageSchema` 中定义,键名使用 kebab-case 格式(如 `app/currentRoute`)。
使用 `src/utils/chromeStorage.ts` 及其 Hook。Router 同时使用 `chrome.storage.local``localStorage` 快照`snapshot/{key}`消除首屏闪烁。
异步加载完成前禁止写入 storage(`RouterProvider``canPersistRef``useStorageState``loadSucceededRef`),避免默认值覆盖已有数据。
使用 `src/utils/chromeStorage.ts` 及其 Hook。Router 同时使用 `chrome.storage.local``localStorage` 快照消除首屏闪烁。
**通信**: 使用 `@webext-core/messaging`,协议定义在 `src/utils/messages.ts`
@@ -152,26 +136,6 @@ src/types/
- Mock 模式: 使用 `vi.mock()` 进行模块级 mock,避免在测试文件中重复 mock 代码
- 测试工具: `@testing-library/react` + `@testing-library/user-event` 进行组件测试
## UI 文案
项目已移除 `chrome.i18n`UI 文案直接在代码中使用中文。
- **功能元数据**: `src/config/features.tsx``FEATURES` 数组定义 `label``description`(用于 Dashboard 卡片与搜索)
- **页面文案**: 在组件 JSX、`constants.ts` 或 Hook 中直接写中文
- **Manifest 文案**: 扩展名称与描述在 `wxt.config.ts``manifest` 中维护
- **Toast / 错误提示**: 在 Hook 或 `constants.ts` 中定义,使用 `sonner``toast()` 展示
## 新功能开发清单
1.`src/types/storage.d.ts` 添加 `PageType` 联合类型
2.`src/config/features.tsx``FEATURES` 数组添加配置(指定 key、label、description、图标、三种渲染模式的组件)
3.`src/pages/` 创建页面组件 (懒加载)
- `index.tsx` — UI 组件(纯展示)
- `useFeatureName.ts` — 业务逻辑 Hook
- `constants.ts` — 常量定义(可选,≥3 个常量时创建)
4. 如需新权限,更新 `wxt.config.ts``manifest.permissions`
5. 添加对应的单元测试
## 代码规范
- 禁止使用 `any` (测试文件除外)
+4 -3
View File
@@ -81,7 +81,7 @@
- **UI 组件**: shadcn/ui (基于 Radix UI 的无头组件库)
- **样式**: Tailwind CSS + class-variance-authority + cn() 工具函数
- **日期处理**: dayjs (集成 UTC 和 Timezone 插件)
- **UI 文案**: 组件内直接使用中文字符串;功能名称与描述定义在 `src/config/features.tsx`
- **国际化**: i18next + react-i18next
- **通信**: @webext-core/messaging
- **存储**: Chrome Storage API (类型安全封装)
- **解析引擎**: qr-scanner (二维码解析), qrious (二维码生成)
@@ -107,8 +107,8 @@
│ ├── hooks/ # 自定义 React Hooks
│ ├── utils/ # 工具函数与服务抽象
│ ├── types/ # TypeScript 类型声明
│ └── lib/ # 通用工具函数与生成器库 (cn, utils, generators 等)
├── public/ # 静态资源 (图标等)
│ └── lib/ # 通用工具函数 (cn, utils 等)
├── public/ # 静态资源 (图标、manifest 资源等)
├── wxt.config.ts # WXT 框架核心配置
└── package.json # 项目元数据与依赖管理
```
@@ -155,6 +155,7 @@
- `sidePanel`: 支持在浏览器侧边栏中运行.
- `clipboardWrite`: 提供一键复制功能.
- `contextMenus`: 注册右键菜单,支持快捷操作.
- `alarms`: 管理后台定时任务(如清理后自动刷新).
## 浏览器支持
+1 -1
View File
@@ -5,7 +5,7 @@
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/styles/shell.css",
"css": "src/index.css",
"baseColor": "slate",
"cssVariables": true,
"prefix": ""
+5 -2
View File
@@ -724,14 +724,17 @@ src/
```tsx
// src/pages/NewTool/index.tsx
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
import { useI18n } from '@/utils/chromeI18n';
import { cn } from '@/lib/utils';
export default function Index() {
const { t } = useI18n('newTool');
return (
<div className="p-4 w-full flex flex-col space-y-4 select-none">
<div className="p-4 w-full flex flex-col space-y-4 min-h-[500px] select-none">
{/* 页面内容 */}
<div className="p-5 rounded-xl border border-border bg-card text-card-foreground shadow-sm">
<h4 className="font-bold text-sm tracking-tight"></h4>
<h4 className="font-bold text-sm tracking-tight">{t('newTool:title')}</h4>
</div>
</div>
);
@@ -1,356 +0,0 @@
# Popup 布局重构 — 功能导航与 Dashboard 移除
> 创建时间: 2026-07-05
> 状态: 待实施
> 关联模块: `src/entrypoints/popup/`、`src/layout/FeatureNav/`、`src/providers/RouterProvider.tsx`
> 影响范围: 仅 popup 入口(tab / sidepanel 不在本次布局范围)
## 背景与目标
当前 popup 采用 **Dashboard 首页 + TopBar 搜索跳转** 模式:用户打开扩展后先看到仪表盘卡片网格,再点击进入具体工具。布局为固定 400×600(见 `src/entrypoints/popup/App.tsx``src/entrypoints/popup/index.html`),TopBar 在非 dashboard 页面显示「返回首页」按钮。
该模式增加了一步选工具操作。本次重构将 popup 改为 **工具直达 + 右侧常驻导航**,并移除 Dashboard 页面。
| 维度 | 现状 | 目标 |
| ---------- | ----------------------------- | ----------------------------------------- |
| 默认页 | `dashboard` | 新用户默认 `timestamp` |
| 导航 | Dashboard 卡片网格 + 搜索跳转 | 右侧常驻纯图标导航栏 |
| 首页 | Dashboard 独立页 | 移除 |
| Popup 宽度 | 400px | 450px(内容区 ~402px + 导航栏 48px |
| 作用范围 | — | 仅 popup 改布局;tab / sidepanel 不加导航 |
---
## 布局设计
### 结构示意
```mermaid
flowchart LR
subgraph popup ["Popup 450x600"]
subgraph mainCol ["主列 flex-1"]
TopBar["TopBar"]
Content["RouterContainer"]
TopBar --> Content
end
NavCol["FeatureNav 48px"]
end
mainCol --- NavCol
```
### 尺寸约束
| 属性 | 值 | 说明 |
| -------- | ------ | ---------------------------------------------- |
| 总宽度 | 450px | `App.tsx` 容器 + `index.html` 内联样式同步修改 |
| 总高度 | 600px | 不变 |
| 主内容列 | flex-1 | 约 402px,需 `min-w-0` 防止 flex 子项溢出 |
| 导航栏 | 48px | Tailwind `w-12`,固定宽度,不参与 flex 收缩 |
### 视觉规范
- 导航栏:左侧 `border-l border-border`,垂直排列图标按钮
- 图标按钮:`h-9 w-9``h-10 w-10`,纯图标
- Tooltip:使用原生 `title` 属性 + `aria-label={feature.label}`,不引入 Tooltip 组件
- Active 态:背景 `bg-muted` + 左侧 `border-l-2 border-primary`
- 导航列表超出高度时:`overflow-y-auto`(600px 高度下 9 个工具通常无需滚动)
---
## FeatureNav 组件规格
新建 `src/layout/FeatureNav/`,遵循 UI + Hook 分离模式(见 `.github/CODING_STANDARDS.md` §11)。
### 文件结构
```
src/layout/FeatureNav/
├── index.tsx # 垂直图标按钮列表、active 高亮、无障碍属性
├── useFeatureNav.ts # 读路由状态,暴露 navItems / navigateTo / currentPage
├── resolveNavFeatures.ts # 从 Dashboard 迁出的功能列表解析逻辑
└── __tests__/
├── index.test.tsx
└── resolveNavFeatures.test.ts
```
### resolveNavFeatures.ts
`src/pages/Dashboard/dashboardFeatures.ts` 迁出并重命名:
```typescript
export interface NavFeatureItem {
key: PageType;
feature: FeatureConfig & { icon: NonNullable<FeatureConfig['icon']> };
}
export function resolveNavFeatures(keys: PageType[], visiblePages: PageType[]): NavFeatureItem[];
```
逻辑与旧 `resolveDashboardFeatures` 一致:
-`keys`(即 `pageOrder`)顺序遍历
- 跳过不在 `visiblePages` 中的项
- 跳过无 `icon` 的 featuredashboard 移除后不应出现)
### useFeatureNav.ts
```typescript
export interface UseFeatureNavReturn {
navItems: NavFeatureItem[];
currentPage: PageType;
navigateTo: (page: PageType) => void;
}
```
-`useRouter()` 读取 `currentPage``pageOrder``visiblePages``navigateTo`
-`useMemo` 调用 `resolveNavFeatures(pageOrder, visiblePages)` 生成 `navItems`
### index.tsx
- 渲染 `<nav aria-label="功能导航">` 包裹垂直按钮列表
- 每项为 `<button type="button">`,内含 Lucide 图标
- 点击调用 `navigateTo(item.key)`
- 当前项添加 active 样式与 `aria-current="page"`
### 引用范围
**仅** `src/entrypoints/popup/App.tsx` 引用 `FeatureNav`。sidepanel / tab 入口不引入该组件。
---
## popup/App.tsx 目标结构
```tsx
import RouterProvider from '@/providers/RouterProvider';
import TopBar from '@/layout/TopBar';
import FeatureNav from '@/layout/FeatureNav';
import RouterContainer from '@/components/RouterContainer';
import ErrorBoundary from '@/components/ErrorBoundary';
export default function App() {
return (
<RouterProvider
defaultRoute="timestamp"
syncKey="app/popupRoute"
visiblePagesKey="app/popupVisiblePages"
pageOrderKey="app/popupPageOrder"
>
<div className="flex w-[450px] max-w-[450px] min-w-[450px] h-[600px] min-h-[600px] overflow-hidden bg-background">
<div className="flex flex-col flex-1 min-w-0">
<TopBar />
<ErrorBoundary>
<RouterContainer />
</ErrorBoundary>
</div>
<FeatureNav />
</div>
</RouterProvider>
);
}
```
`src/entrypoints/popup/index.html` 内联样式中 `width: 400px` 改为 `width: 450px`
---
## 移除 Dashboard(全局类型变更)
布局仅改 popup,但 `dashboard``PageType` 移除会影响全项目类型与路由校验。
### 删除文件
| 路径 | 说明 |
| ------------------------------------- | ---------------- |
| `src/pages/Dashboard/` | 整目录(含测试) |
| `src/config/pageLoaders/dashboard.ts` | Dashboard 懒加载 |
### 修改文件
| 文件 | 改动 |
| ------------------------------------ | ----------------------------------------------------------- |
| `src/types/storage.d.ts` | 从 `PageType` 联合类型删除 `'dashboard'` |
| `src/config/featureMeta.ts` | 删除 dashboard 条目 |
| `src/config/pageLoaders/index.ts` | 删除 `case 'dashboard'` |
| `src/components/RouterContainer.tsx` | 去掉 dashboard 骨架屏分支;统一使用 `page-transition-enter` |
| `src/components/PageSkeleton.tsx` | 删除 `variant: 'dashboard'` 及对应 UI |
| `src/styles/shell.css` | 删除 `.page-transition-dashboard` |
### TopBar 精简
`src/layout/TopBar/index.tsx``useTopBar.ts`
- 删除「返回首页」按钮(`ArrowLeft` + `goHome`
- 删除 `isDashboard` 状态及相关导出
- 搜索过滤中 `f.key === 'dashboard'` 的特殊排除逻辑可删除
### RouterProvider 变更
`src/providers/RouterProvider.tsx`
- 删除 `goHome()` 方法及 Context 中的 `goHome` 字段
- 全局 `defaultRoute` 默认值由 `'dashboard'` 改为 `'timestamp'`
- popup 显式传入 `defaultRoute="timestamp"`(与全局默认一致,便于阅读)
### Sidepanel 最小修复
`src/entrypoints/sidepanel/App.tsx` 若仍存在:
- `defaultRoute="dashboard"` 改为 `defaultRoute="timestamp"`
- 不添加 FeatureNav 布局
---
## 默认路由策略(仅新用户)
利用现有 `RouterProvider` 机制,**无需额外迁移代码**。
```typescript
// 首屏(localStorage 快照,消除闪烁)
const [currentPage] = useState(() => getSyncSnapshot(syncKey, defaultRoute, isValidPage));
// 异步加载 chrome.storage
const savedRoute = (stored[syncKey] ?? defaultRoute) as PageType;
if (isValidPage(savedRoute) && syncRoute && !hasUserNavigatedRef.current) {
setCurrentPage(savedRoute);
}
```
| 场景 | 行为 |
| ------------------------------------------ | ---------------------------------------------------------------- |
| 新用户(无 `app/popupRoute`) | 首屏 + 持久化均为 `timestamp` |
| 老用户(如 `app/popupRoute: 'jsonTools'`) | 恢复上次路由 |
| 老用户曾存 `dashboard` | `isValidPage('dashboard')` 为 false → 回退 `timestamp`(软迁移) |
| 右键菜单 deep link | `?feature=&payload=` 优先级不变,高于默认路由 |
| 用户主动切换 | `navigateTo``hasUserNavigatedRef` 阻止异步覆盖 |
`visiblePages` / `pageOrder` 中残留的 `dashboard``mergeWithDefaults` 自动滤除(不在新默认列表中)。
### 边界说明
`recentlyUsedTools` 若含已移除的 `dashboard` 等非法项,当前 `isValidPageList` 校验要求数组**全部**合法,失败时整表回退为 `[]`。影响:TopBar 搜索历史中的「最近使用」可能被清空。此为已知低影响边界;实现时可选优化为「过滤非法项保留合法项」,**非必须**。
---
## 实施顺序
```
1. 迁出 resolveNavFeatures + 新建 FeatureNav 组件与测试
2. 修改 popup/App.tsx 布局 + popup/index.html 宽度
3. 全局移除 dashboardPageType → FEATURES → pageLoader → 删页面目录)
4. 精简 TopBar / RouterProvider / RouterContainer / PageSkeleton
5. 批量更新测试 → npm run typecheck && npm run test && npm run lint
```
---
## 验收标准
### A. 布局与导航(手动)
| 编号 | 步骤 | 期望 |
| ---- | ------------------------------------ | ---------------------------------------------- |
| A-1 | 首次安装(或清空 storage)打开 popup | 默认显示时间戳页,右侧导航 timestamp 项高亮 |
| A-2 | 依次点击各导航图标 | 切换到对应工具页,active 态跟随当前页 |
| A-3 | hover 各导航图标 | 显示中文功能名 tooltip(`title` 属性) |
| A-4 | 使用过某工具后关闭再打开 popup | 恢复上次路由(非 dashboard |
| A-5 | 检查 popup 尺寸 | 宽度 450px,高度 600px,内容区不被导航挤压溢出 |
### B. Dashboard 移除
| 编号 | 期望 |
| ---- | -------------------------------------------------------------------- |
| B-1 | TopBar 搜索下拉无 dashboard 项 |
| B-2 | TopBar 无「返回首页」按钮 |
| B-3 | `PageType``FEATURES``loadPage` 中无 dashboard |
| B-4 | storage 中 `app/popupRoute: 'dashboard'` 时打开 popup 落到 timestamp |
| B-5 | `visiblePages` 含 dashboard 时自动滤除,导航正常显示工具列表 |
### C. 单元测试
| 编号 | 覆盖 |
| ---- | -------------------------------------------------------------------------- |
| C-1 | `FeatureNav` 渲染全部可见工具图标 |
| C-2 | `FeatureNav` 点击图标调用 `navigateTo` |
| C-3 | `FeatureNav` 当前页对应项有 active 样式 / `aria-current` |
| C-4 | `resolveNavFeatures` 按 pageOrder 排序、respect visiblePages |
| C-5 | 更新 `RouterProvider` / `TopBar` / `RouterContainer` / `features` 相关测试 |
| C-6 | 删除 `src/pages/Dashboard/__tests__/` 下全部测试 |
### D. CI
| 编号 | 标准 |
| ---- | ------------------------ |
| D-1 | `npm run typecheck` 通过 |
| D-2 | `npm run test` 通过 |
| D-3 | `npm run lint` 通过 |
---
## 不在范围
- tab / sidepanel 布局改造(不加 FeatureNav
- `visiblePages` / `pageOrder` 可视化配置 UI
- Popup 高度变更(保持 600px
- 修改 `AGENTS.md` 中 spec 目录引用(实际 spec 位于 `docs/spec/`
---
## PR 检查清单
```markdown
## 功能
- [ ] 新建 FeatureNav 组件(index / useFeatureNav / resolveNavFeatures
- [ ] popup 布局改为双列(主内容 + 右侧导航)
- [ ] popup 宽度 450pxApp.tsx + index.html
- [ ] popup defaultRoute="timestamp"
- [ ] 全局移除 dashboardPageType、FEATURES、pageLoader、页面目录)
- [ ] TopBar 移除返回按钮与 goHome 相关逻辑
- [ ] RouterProvider 移除 goHomedefaultRoute 改为 timestamp
- [ ] sidepanel defaultRoute 最小修复(若文件存在)
## 测试
- [ ] FeatureNav / resolveNavFeatures 单元测试
- [ ] 更新 RouterProvider / TopBar / RouterContainer / features 测试
- [ ] 删除 Dashboard 相关测试
## 验收
- [ ] npm run typecheck / test / lint 通过
- [ ] 手动 A-1 ~ A-5、B-1 ~ B-4 通过
```
---
## 风险与边界说明
1. **Dashboard 移除为全局变更**:虽 FeatureNav 仅 popup 使用,但 `PageType` 删除 `dashboard` 会影响所有入口的类型校验与路由合法性。
2. **老用户 dashboard 路由软迁移**:依赖 `isValidPage` 回退到 `defaultRoute`,不会 crash,但用户会察觉「首页消失、默认变为时间戳」——符合预期。
3. **450px 宽度**Chrome popup 允许扩展较默认更宽;若未来 Firefox 有差异需在 Firefox 构建中手动验证。
4. **recentlyUsedTools 整表校验**:见「默认路由策略 → 边界说明」,可选后续优化。
---
## 相关文件索引
| 文件 | 说明 |
| ------------------------------------- | ------------------------------- |
| `src/entrypoints/popup/App.tsx` | popup 布局入口,引用 FeatureNav |
| `src/entrypoints/popup/index.html` | popup 初始尺寸 450px |
| `src/layout/FeatureNav/` | 新建:右侧图标导航 |
| `src/layout/TopBar/` | 精简:移除返回按钮 |
| `src/providers/RouterProvider.tsx` | 默认路由、移除 goHome |
| `src/config/featureMeta.ts` | FEATURES 定义,删除 dashboard |
| `src/types/storage.d.ts` | PageType 定义 |
| `src/config/pageLoaders/index.ts` | 页面懒加载路由 |
| `src/components/RouterContainer.tsx` | 页面渲染容器 |
| `src/components/PageSkeleton.tsx` | 加载骨架屏 |
| `src/styles/shell.css` | 页面过渡动画 |
| `src/pages/Dashboard/` | **删除** |
| `src/config/pageLoaders/dashboard.ts` | **删除** |
| `src/entrypoints/sidepanel/App.tsx` | 最小修复 defaultRoute |
---
> **注**:项目 spec 文档实际目录为 `docs/spec/`。`AGENTS.md` 中引用的根目录 `spec/README.md` 尚未建立,以本目录 [`README.md`](../README.md) 为索引。
+1 -28
View File
@@ -2,7 +2,7 @@
> 版本: v1.0
> 创建时间: 2024-01-20
> 状态: 已实现(见 `src/pages/TestDataGenerator/`、`src/lib/generators/`、`src/workers/generator.worker.ts`
> 状态: 待 Review
## 产品定位
@@ -19,30 +19,3 @@
- [规则管理](./rule-management.md)
- [界面设计](./ui-design.md)
- [技术实现](./technical-implementation.md)
## 当前实现入口
- 页面入口:`src/pages/TestDataGenerator/index.tsx`
- Worker`src/workers/generator.worker.ts`
- 生成器库:`src/lib/generators/`
- 规则存储:`src/utils/ruleStorage.ts`
- 导出工具:`src/utils/dataExporter.ts`
实现约束与任务完成状态记录在 [TASKS.md](./TASKS.md)。
## 开发者注意事项(与源码同步)
以下行为以 `src/` 源码为准;设计文档中的旧版 class API、`metadata`/`options` 嵌套结构已废弃。
### Worker 任务 ID`generationId`
`useGenerator` 每次调用 `generate()` 递增 `generationIdRef`,经 `start` 消息传入 Worker。Worker 所有响应(`progress` / `complete` / `error`)均携带同一 `generationId`
- **取消**`cancel()` 先递增 ID 再发送 `cancel`,使进行中的 Worker 响应被主线程忽略;Worker 每生成 100 行让出事件循环以处理 cancel。
- **快速重试**:新任务 ID 大于旧响应时,旧消息被丢弃,避免 UI 状态错乱。
类型见 `WorkerRequestMessage` / `WorkerResponseMessage``src/types/testDataGenerator.ts`)。
### 规则存储写入失败
`ruleStorage.save()` / `update()``localStorage.setItem` 失败时返回 `null`(不部分提交)。页面层(如 `FieldList.tsx`)仅在返回值非空时 Toast 成功。详见 [rule-management.md § 存储机制](./rule-management.md#存储机制) 与 `src/utils/README.md`
+114 -55
View File
@@ -24,20 +24,25 @@
## 数据结构
> **与源码对齐**:类型定义见 `src/types/testDataGenerator.ts`。规则**不**持久化生成数量与导出格式(由页面 `GenerateOptions` 状态管理)。
### 规则模板
```typescript
interface DataRule {
id: string;
name: string;
description?: string;
fields: FieldConfig[];
createdAt: number;
updatedAt: number;
lastUsedAt?: number;
useCount: number;
id: string; // 唯一标识
name: string; // 规则名称
description?: string; // 规则描述
fields: FieldConfig[]; // 字段配置
options: {
total: number; // 生成数量
format: 'json' | 'csv';
defaultEmptyRate: number; // 默认空值率(0-100
};
metadata: {
createdAt: number; // 创建时间
updatedAt: number; // 更新时间
lastUsedAt?: number; // 最后使用时间
useCount: number; // 使用次数
};
}
```
@@ -45,14 +50,13 @@ interface DataRule {
```typescript
interface FieldConfig {
id: string;
name: string;
description?: string;
generatorId: string; // 生成器 ID,对应 lib/generators 中的 id
params: Record<string, unknown>;
required: boolean;
nullRate: number; // 空值率 0-100,仅 required=false 时生效
unique: boolean;
id: string; // 字段唯一标识
name: string; // 字段名
generator: string; // 生成器名称
params: Record<string, any>; // 生成器参数
unique: boolean; // 唯一性约束
required: boolean; // 是否必填
emptyRate?: number; // 选填字段的空值概率(0-100)
}
```
@@ -106,9 +110,11 @@ interface FieldConfig {
1. 验证规则名称不为空
2. 检查规则数量是否达到上限(20 条)
3. 若达上限,`save()` 返回 `null`UI 应阻止或提示
4. 生成唯一 ID,写入 `createdAt`/`updatedAt``useCount` 初始为 0
5. 调用 `ruleStorage.save()`;仅当返回值非 `null` 时视为成功(`localStorage` 写入失败同样返回 `null`
3. 如果达到上限,显示提示"已达到最大规则数量"
4. 生成唯一 ID
5. 设置创建时间和更新时间
6. 初始化使用次数为 0
7. 保存到 localStorage
---
@@ -161,13 +167,17 @@ interface FieldConfig {
- 支持按规则描述搜索
- 搜索为模糊匹配,不区分大小写
**实现方式**`src/utils/ruleStorage.ts`:
**实现方式**:
```typescript
import * as ruleStorage from '@/utils/ruleStorage';
search(keyword: string): DataRule[] {
const rules = this.getAll();
const lowerKeyword = keyword.toLowerCase();
function searchRules(query: string): DataRule[] {
return ruleStorage.search(query);
return rules.filter(r =>
r.name.toLowerCase().includes(lowerKeyword) ||
r.description?.toLowerCase().includes(lowerKeyword)
);
}
```
@@ -214,7 +224,9 @@ function searchRules(query: string): DataRule[] {
1. 加载原规则配置到编辑器
2. 用户修改配置
3. 点击保存时调用 `ruleStorage.update()`;返回非 `null` 才更新 `updatedAt` 并提示成功
3. 点击保存时更新规则
4. 更新 metadata.updatedAt
5. 保存到 localStorage
---
@@ -257,12 +269,18 @@ function searchRules(query: string): DataRule[] {
**实现方式**:
```typescript
function loadRule(ruleId: string): void {
const rule = ruleStorage.getById(ruleId);
if (!rule) return;
loadRule(ruleId: string): void {
const rule = this.storage.getById(ruleId);
setFields(rule.fields);
ruleStorage.recordUse(ruleId);
// 应用规则配置
this.setFields(rule.fields);
this.setOptions(rule.options);
// 记录使用
this.storage.recordUse(ruleId);
// 更新预览
this.updatePreview();
}
```
@@ -274,7 +292,7 @@ function loadRule(ruleId: string): void {
1. 点击"复制"按钮
2. 创建规则的副本
3. 名称添加「(副本)」后缀(默认 `duplicate(id, '(副本)')`
3. 名称添加"(副本)"后缀
4. 生成新的 ID
5. 保存为新规则
@@ -309,20 +327,23 @@ function loadRule(ruleId: string): void {
└─────────────────────────────────────────────────────────────────────┘
```
**导出格式**`exportRules()` 返回 `DataRule[]` 的 JSON 字符串,无外层包装):
**导出格式**:
```json
[
{
"version": "1.0",
"exportedAt": "2024-01-20T10:15:45.000Z",
"rules": [
{
"id": "rule_123456",
"name": "电商用户数据 - 测试用",
"description": "用于测试用户注册功能",
"fields": [],
"createdAt": 1704067200000,
"updatedAt": 1704067200000,
"useCount": 0
"fields": [...],
"options": {...},
"metadata": {...}
}
]
]
}
```
---
@@ -380,25 +401,63 @@ function loadRule(ruleId: string): void {
### 本地存储
使用 `localStorage`,键名 `testDataGenerator_rules`。API 为**命名导出函数**(见 `src/utils/ruleStorage.ts`):
| 函数 | 说明 |
| ------------------------------------------------------ | ---------------------------------- |
| `getAll()` / `getById()` / `getByName()` | 读取 |
| `save()` / `update()` / `deleteRule()` / `duplicate()` | 写入;失败时返回 `null``false` |
| `recordUse()` | 递增 `useCount`、更新 `lastUsedAt` |
| `search()` / `getRecent()` | 搜索与最近使用 |
| `exportRules()` / `importRules()` | 导入导出 JSON 数组 |
| `clear()` | 清空全部规则 |
写入失败(如 `QuotaExceededError`)时,内部 `setAll()` 返回 `false``save`/`update` 返回 `null``deleteRule` 返回 `false`,并在控制台输出 `[ruleStorage] 保存规则失败`。调用方须检查返回值,避免误报成功。
使用 localStorage 存储规则数据:
```typescript
import * as ruleStorage from '@/utils/ruleStorage';
class RuleStorage {
private readonly STORAGE_KEY = 'testDataGenerator_rules';
const saved = ruleStorage.save({ name: '示例', fields });
if (!saved) {
// 达上限或 localStorage 不可用
// 获取所有规则
getAll(): DataRule[] {
const data = localStorage.getItem(this.STORAGE_KEY);
return data ? JSON.parse(data) : [];
}
// 保存规则
save(rule: DataRule): { success: boolean; message?: string } {
const rules = this.getAll();
// 规则数量限制:最多 20 条
const MAX_RULES = 20;
if (rules.length >= MAX_RULES) {
return {
success: false,
message: `已达到最大规则数量(${MAX_RULES}条),请删除一些规则后再保存`,
};
}
rules.push(rule);
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(rules));
return { success: true };
}
// 更新规则
update(id: string, updates: Partial<DataRule>): void {
const rules = this.getAll();
const index = rules.findIndex((r) => r.id === id);
if (index !== -1) {
rules[index] = { ...rules[index], ...updates };
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(rules));
}
}
// 删除规则
delete(id: string): void {
const rules = this.getAll();
const filtered = rules.filter((r) => r.id !== id);
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(filtered));
}
// 记录使用
recordUse(id: string): void {
const rules = this.getAll();
const rule = rules.find((r) => r.id === id);
if (rule) {
rule.metadata.lastUsedAt = Date.now();
rule.metadata.useCount++;
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(rules));
}
}
}
```
@@ -1,7 +1,5 @@
# 技术实现
> **文档同步说明**:本文档含早期设计稿代码示例,部分类型/API 已与实现偏离。开发时请以 `src/types/testDataGenerator.ts`、`src/workers/generator.worker.ts`、`src/pages/TestDataGenerator/hooks/useGenerator.ts`、`src/utils/ruleStorage.ts` 为准。近期变更摘要见 [README § 开发者注意事项](./README.md#开发者注意事项与源码同步)。
## 技术栈
| 技术 | 用途 | 版本 |
@@ -1500,67 +1498,6 @@ export class DataExporter {
## Web Worker 使用
### 消息协议
```typescript
// src/types/testDataGenerator.ts
type WorkerRequestMessage = { type: 'start'; payload: WorkerStartPayload } | { type: 'cancel' };
type WorkerResponseMessage =
| { type: 'progress'; generationId: number; payload: GenerateProgress }
| { type: 'complete'; generationId: number; payload: GenerateResult }
| { type: 'error'; generationId: number; payload: { error: string } };
interface WorkerStartPayload {
generationId: number; // 任务 ID,用于忽略过期响应
fields: FieldConfig[];
count: number;
csvMode: boolean;
}
```
### useGenerator Hook
`src/pages/TestDataGenerator/hooks/useGenerator.ts` 负责 Worker 生命周期与 `generationId` 管理:
- Worker **复用**:同一 Hook 实例内只创建一次,出错后 `terminate` 并在下次重建
- **开始生成**`generate(fields, count, csvMode?)` 递增 `generationId` 并 post `start`
- **取消**`cancel()` 递增 ID(使旧响应失效)并 post `cancel`;取消完成的 `complete` 不写入 `error` 状态
- **响应过滤**`onmessage` 中若 `data.generationId !== generationIdRef.current` 则忽略
```typescript
const generate = (fields: FieldConfig[], count: number, csvMode = false) => {
if (isGenerating) return;
const generationId = ++generationIdRef.current;
worker.postMessage({ type: 'start', payload: { generationId, fields, count, csvMode } });
};
const cancel = () => {
if (workerRef.current && isGenerating) {
++generationIdRef.current;
worker.postMessage({ type: 'cancel' });
setIsGenerating(false);
}
};
```
### Worker 实现要点
`src/workers/generator.worker.ts`
-`field.generatorId` 查找生成器;选填字段按 `nullRate` 随机置 `null`
- 唯一性:≤1000 条随机+重试;>1000 条优先 `generateAtIndex`
-`YIELD_EVERY`100)行 `await setTimeout(0)`,以便处理 `cancel`
- 进度:每 1000 条或最后一行 post `progress`
---
## Web Worker 使用(历史设计稿,仅供参考)
<details>
<summary>展开查看旧版设计示例(与当前实现不一致)</summary>
### 创建 Worker
```typescript
@@ -1656,7 +1593,7 @@ export function useGenerator() {
}
```
### 错误处理(设计稿,`useErrorHandler.ts` 未实现)
### 错误处理
```typescript
// src/pages/TestDataGenerator/hooks/useErrorHandler.ts
@@ -1699,12 +1636,8 @@ export function useErrorHandler(options: ErrorHandlerOptions = {}) {
---
</details>
## 错误提示机制
> 当前实现:`TestDataGenerator/index.tsx` 直接使用 `useGenerator` 的 `error`/`result` 与 `ResultPanel` 展示警告;下方示例引用未实现的 `useErrorHandler`,仅供对照。
### 错误类型分类
| 错误类型 | 严重程度 | 触发场景 | 提示方式 |
-1
View File
@@ -17,4 +17,3 @@
- 修改图标后需同步更新 `wxt.config.ts` 中的 manifest 配置
- 图标格式推荐使用 PNG,确保透明背景
- UI 文案不在此目录维护,见 `src/config/features.tsx` 与各页面组件
-1
View File
@@ -5,4 +5,3 @@
| 文档 | 状态 | 说明 |
| -------------------------------------------------------------------------------- | ----------------- | ---------------------------------------------------- |
| [storage-cleaner/indexeddb-fix-plan.md](./storage-cleaner/indexeddb-fix-plan.md) | ✅ Phase 3 已完成 | Storage Cleaner IndexedDB 清理逻辑修复方案与验收标准 |
| [popup-layout/feature-nav-layout.md](./popup-layout/feature-nav-layout.md) | 待实施 | Popup 右侧图标导航、移除 Dashboard、默认 timestamp |
+6 -3
View File
@@ -2,7 +2,6 @@ import React, { useEffect, useRef, useState } from 'react';
import { Check, Copy } from 'lucide-react';
import { copyTextToClipboard } from '@/utils/clipboard';
import { Button, type ButtonProps } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
interface CopyButtonProps extends Omit<ButtonProps, 'children' | 'onClick'> {
@@ -54,10 +53,14 @@ export const CopyButton: React.FC<CopyButtonProps> = ({
aria-label={tooltip ?? '复制'}
variant={variant}
size={size}
className={cn(className, copied && 'text-emerald-500')}
className={className}
{...props}
>
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
{copied ? (
<Check className="h-[1.2em] w-[1.2em]" />
) : (
<Copy className="h-[1.2em] w-[1.2em]" />
)}
</Button>
);
};
@@ -1,194 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { act, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
// unmock the globally-mocked component so we test the real implementation
vi.unmock('@/components/CopyButton');
vi.mock('@/utils/clipboard', () => ({
copyTextToClipboard: vi.fn(),
}));
vi.mock('sonner', () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
},
}));
import { CopyButton } from '@/components/CopyButton';
import { copyTextToClipboard } from '@/utils/clipboard';
import { toast } from 'sonner';
const mockedCopy = vi.mocked(copyTextToClipboard);
const mockedToast = vi.mocked(toast);
describe('CopyButton', () => {
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: true });
vi.clearAllMocks();
});
afterEach(() => {
vi.useRealTimers();
});
it('复制成功时调用 copyTextToClipboard 并传入正确 text', async () => {
mockedCopy.mockResolvedValue(true);
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
render(<CopyButton text="hello world" />);
await user.click(screen.getByRole('button'));
expect(mockedCopy).toHaveBeenCalledWith('hello world');
expect(mockedToast.success).toHaveBeenCalled();
});
it('复制成功后图标切换为 Check1.5 秒后恢复', async () => {
mockedCopy.mockResolvedValue(true);
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
render(<CopyButton text="test" />);
// 点击后复制成功,按钮获得 emerald 样式(说明切到了 Check 状态)
await user.click(screen.getByRole('button'));
await waitFor(() => {
expect(screen.getByRole('button').className).toContain('text-emerald');
});
// 1.5 秒后样式恢复
act(() => {
vi.advanceTimersByTime(1500);
});
await waitFor(() => {
expect(screen.getByRole('button').className).not.toContain('text-emerald');
});
});
it('复制空文本时弹出 error toast', async () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
render(<CopyButton text="" />);
await user.click(screen.getByRole('button'));
expect(mockedCopy).not.toHaveBeenCalled();
expect(mockedToast.error).toHaveBeenCalled();
});
it('复制失败时弹出 error toast', async () => {
mockedCopy.mockResolvedValue(false);
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
render(<CopyButton text="something" />);
await user.click(screen.getByRole('button'));
expect(mockedCopy).toHaveBeenCalledWith('something');
expect(mockedToast.error).toHaveBeenCalled();
});
// ==================== 新增测试 ====================
it('初始渲染时显示 Copy 图标且无 emerald 样式', () => {
render(<CopyButton text="initial" />);
const button = screen.getByRole('button');
expect(button.className).not.toContain('text-emerald');
// 通过 aria-label 确认按钮存在,图标由 lucide 渲染为 svg
expect(button).toHaveAttribute('aria-label');
});
it('自定义 tooltip 会覆盖默认 title 和 aria-label', () => {
render(<CopyButton text="tooltip-test" tooltip="自定义提示" />);
const button = screen.getByRole('button');
expect(button).toHaveAttribute('title', '自定义提示');
expect(button).toHaveAttribute('aria-label', '自定义提示');
});
it('className 被正确透传到按钮', () => {
render(<CopyButton text="class-test" className="my-custom-class" />);
const button = screen.getByRole('button');
expect(button.className).toContain('my-custom-class');
});
it('点击事件阻止冒泡', async () => {
mockedCopy.mockResolvedValue(true);
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
const parentClick = vi.fn();
render(
<div onClick={parentClick}>
<CopyButton text="stop-propagation" />
</div>,
);
await user.click(screen.getByRole('button'));
expect(mockedCopy).toHaveBeenCalled();
expect(parentClick).not.toHaveBeenCalled();
});
it('组件卸载时清除定时器,不触发状态更新警告', async () => {
mockedCopy.mockResolvedValue(true);
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
const { unmount } = render(<CopyButton text="unmount-test" />);
await user.click(screen.getByRole('button'));
// 在 1.5 秒超时到期前卸载组件
act(() => {
vi.advanceTimersByTime(500);
});
// 卸载不应抛出 "Can't perform a React state update on an unmounted component" 警告
expect(() => unmount()).not.toThrow();
// 前进剩余时间,确认没有异常
act(() => {
vi.advanceTimersByTime(2000);
});
});
it('快速连续点击不会创建多个重叠定时器', async () => {
mockedCopy.mockResolvedValue(true);
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
render(<CopyButton text="rapid-click" />);
const button = screen.getByRole('button');
// 快速点击 3 次
await user.click(button);
await user.click(button);
await user.click(button);
// copyTextToClipboard 应该被调用 3 次(每次点击都执行)
expect(mockedCopy).toHaveBeenCalledTimes(3);
// 但 setTimeout 相关的 clearTimeout + setTimeout 组合应正常工作
// advance 1.5 秒后,copied 状态应恢复为 false
act(() => {
vi.advanceTimersByTime(1500);
});
await waitFor(() => {
expect(button.className).not.toContain('text-emerald');
});
});
it('其他 button props 通过 ...props 透传', () => {
render(<CopyButton text="props-test" data-testid="copy-btn" disabled id="copy-button-id" />);
const button = screen.getByRole('button');
expect(button).toHaveAttribute('data-testid', 'copy-btn');
expect(button).toBeDisabled();
expect(button).toHaveAttribute('id', 'copy-button-id');
});
});
+5 -7
View File
@@ -30,7 +30,9 @@ export function ErrorFallback({
<div
className={cn(
'flex flex-col items-center justify-center',
isApp ? 'mt-16 mx-auto max-w-md' : 'flex-1 p-6 min-h-[300px] fade-in-zoom-95',
isApp
? 'mt-16 mx-auto max-w-md'
: 'flex-1 p-6 min-h-[300px] animate-in fade-in zoom-in-95 duration-200',
className,
)}
>
@@ -55,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>
@@ -85,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}
+78
View File
@@ -0,0 +1,78 @@
/**
* PageSkeleton 组件 - 页面加载骨架屏
*
* 用于 Suspense fallback 和初始加载状态,提供平滑的视觉过渡
* 避免白屏闪烁,减少布局偏移
*/
interface PageSkeletonProps {
/** 骨架屏类型 */
variant?: 'dashboard' | 'tool';
}
/**
* 仪表盘卡片骨架屏
*/
function DashboardCardSkeleton() {
return (
<div className="rounded-xl border border-border p-5 h-[100px]">
<div className="flex justify-between items-start">
<div className="flex gap-3 items-center">
<div className="w-10 h-10 rounded-lg bg-muted animate-pulse" />
<div>
<div className="w-24 h-5 bg-muted rounded animate-pulse" />
<div className="w-32 h-3.5 bg-muted rounded animate-pulse mt-1.5" />
</div>
</div>
<div className="w-3 h-3 rounded-full bg-muted animate-pulse" />
</div>
</div>
);
}
/**
* 工具页面骨架屏
*/
function ToolPageSkeleton() {
return (
<div className="p-5">
{/* 标题区域 */}
<div className="w-44 h-7 bg-muted rounded animate-pulse mb-4" />
{/* 输入区域 */}
<div className="w-full h-[120px] bg-muted rounded-xl animate-pulse mb-4" />
{/* 控制栏 */}
<div className="flex gap-2 mb-4">
<div className="w-24 h-9 bg-muted rounded-lg animate-pulse" />
<div className="w-20 h-9 bg-muted rounded-lg animate-pulse" />
<div className="flex-1" />
<div className="w-22 h-9 bg-muted rounded-lg animate-pulse" />
</div>
{/* 结果区域 */}
<div className="w-full h-[160px] bg-muted rounded-xl animate-pulse" />
</div>
);
}
/**
* 页面加载骨架屏
*
* @param props - PageSkeletonProps
* @returns 骨架屏 JSX 元素
*/
export default function PageSkeleton({ variant = 'dashboard' }: PageSkeletonProps) {
if (variant === 'tool') {
return <ToolPageSkeleton />;
}
return (
<div className="grid grid-cols-1 sm:grid-cols-[repeat(auto-fill,minmax(300px,1fr))] auto-rows-fr gap-4 p-4">
{Array.from({ length: 6 }).map((_, index) => (
<DashboardCardSkeleton key={index} />
))}
</div>
);
}
PageSkeleton.displayName = 'PageSkeleton';
+4 -3
View File
@@ -5,18 +5,19 @@
## 组件列表
| 组件 | 用途 |
| ----------------------- | ------------------------------------------------------------------------------------------------------ |
| `RouterContainer.tsx` | 路由容器,根据当前路由动态渲染对应页面组件,集成错误边界 |
| ----------------------- | ------------------------------------------------------------------------------ |
| `RouterContainer.tsx` | 路由容器,根据当前路由动态渲染对应页面组件,集成错误边界和骨架屏 |
| `SwitchButtonGroup.tsx` | 通用切换按钮组,支持 `small/medium/large` 三种尺寸,用于页面子模式切换 |
| `EmptyPlaceholder.tsx` | 虚线边框空状态占位,统一工具页「暂无结果」提示样式 |
| `TextInputArea.tsx` | 增强文本输入区域,支持校验规则、工具栏操作、字符计数、清空 |
| `CopyButton.tsx` | 一键复制按钮复制成功后 1.5s 内切换为 Check 图标并应用 `text-emerald-500`;空内容/失败时 `toast` 提示 |
| `CopyButton.tsx` | 一键复制按钮,支持复制成功状态动画,封装 `copyTextToClipboard` `toast` 反馈 |
| `ImageUploader.tsx` | 图片上传组件,支持拖拽上传、文件选择和预览 |
| `QrCodePreview.tsx` | 二维码预览组件,展示生成的二维码图片,提供复制和下载操作 |
| `DecodeResultPaper.tsx` | Base64 解码结果展示面板,显示 MIME 类型、文件大小、文件名输入和下载按钮 |
| `GlobalSnackbar.tsx` | 全局消息提示组件 + Context Provider,支持受控/Hook/全局单例三种使用方式 |
| `ErrorBoundary.tsx` | 全局错误边界(类组件),捕获子组件树 JS 错误并展示友好错误页面 |
| `PageErrorBoundary.tsx` | 页面级错误边界,适配 shadcn 暗黑模式,支持 `resetKey` 自动恢复 |
| `PageSkeleton.tsx` | 页面骨架屏,提供 `dashboard``tool` 两种变体,用于 Suspense fallback |
## 使用约定
+25 -39
View File
@@ -1,68 +1,54 @@
import { getFeatureByKey } from '@/config/features';
import { loadPage } from '@/config/pageLoaders/index';
import { FEATURES, getEntryPointType } from '@/config/features';
import { useRouter } from '@/providers/RouterProvider';
import type { PageType } from '@/types/storage';
import { type ComponentType, useEffect, useState } from 'react';
import { Suspense } from 'react';
import PageErrorBoundary from '@/components/PageErrorBoundary';
import PageSkeleton from '@/components/PageSkeleton';
import { cn } from '@/lib/utils';
import { AlertTriangle } from 'lucide-react';
function LoadedPage({ pageKey }: { pageKey: PageType }) {
const [Page, setPage] = useState<ComponentType | null>(null);
useEffect(() => {
let cancelled = false;
loadPage(pageKey)
.then((mod) => {
if (!cancelled) {
setPage(() => mod.default);
}
})
.catch((err) => {
console.error('[Router Page Load Error]', err);
});
return () => {
cancelled = true;
};
}, [pageKey]);
if (!Page) {
return <div className="flex-1" aria-hidden="true" />;
}
return <Page />;
}
const entryPointType = getEntryPointType();
export default function RouterContainer() {
const { currentPage } = useRouter();
const { currentPage, isLoaded } = useRouter();
const currentFeature = getFeatureByKey(currentPage);
const animationClass =
currentPage === 'dashboard' ? 'page-transition-dashboard' : 'page-transition-enter';
if (!isLoaded) {
return <PageSkeleton variant={currentPage === 'dashboard' ? 'dashboard' : 'tool'} />;
}
const currentFeature = FEATURES.find((f) => f.key === currentPage);
const MatchedComponent = currentFeature?.components?.[entryPointType];
return (
<div
key={currentPage}
className={cn(
'flex-1 flex flex-col overflow-x-hidden overflow-y-auto',
'motion-reduce:transition-none page-transition-enter',
'scrollbar-gutter-stable motion-reduce:transition-none',
animationClass,
)}
>
<Suspense
fallback={<PageSkeleton variant={currentPage === 'dashboard' ? 'dashboard' : 'tool'} />}
>
<PageErrorBoundary resetKey={currentPage}>
{currentFeature ? (
<LoadedPage key={currentPage} pageKey={currentPage} />
{MatchedComponent ? (
<MatchedComponent />
) : (
<div className="flex-1 flex flex-col items-center justify-center p-8 text-center fade-in-300">
<div className="flex-1 flex flex-col items-center justify-center p-8 text-center animate-in fade-in duration-300">
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-destructive/10 text-destructive mb-4">
<AlertTriangle className="h-6 w-6" />
</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]">
{`该功能在当前运行环境(${entryPointType})下不可用或已被移除。`}
</p>
</div>
)}
</PageErrorBoundary>
</Suspense>
</div>
);
}
+6 -7
View File
@@ -15,6 +15,7 @@ export interface SwitchButtonGroupProps<T extends string | number = string> exte
options: SwitchOption<T>[];
onChange: (value: T) => void;
size?: 'small' | 'medium' | 'large';
buttonClassName?: string;
}
const SIZE_CLASSES = {
@@ -23,12 +24,9 @@ const SIZE_CLASSES = {
large: 'text-base h-11 px-4 py-2 rounded-lg',
} as const;
const INTERACTIVE_CLASSES =
'active:scale-[0.98] focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-muted';
const SELECTED_CLASSES =
'bg-background text-foreground shadow-sm font-semibold hover:bg-background hover:text-foreground';
const UNSELECTED_CLASSES = 'text-muted-foreground hover:bg-accent hover:text-accent-foreground';
'bg-background text-foreground shadow-sm font-semibold animate-in fade-in-50 zoom-in-95 duration-150';
const UNSELECTED_CLASSES = 'hover:bg-background/50 hover:text-foreground/80';
export default function SwitchButtonGroup<T extends string | number = string>({
value,
@@ -36,12 +34,13 @@ export default function SwitchButtonGroup<T extends string | number = string>({
onChange,
size = 'medium',
className,
buttonClassName,
...props
}: SwitchButtonGroupProps<T>) {
return (
<div
className={cn(
'inline-flex w-full items-center justify-center rounded-lg bg-muted p-1',
'inline-flex w-full items-center justify-center rounded-lg bg-muted text-muted-foreground p-1',
className,
)}
{...props}
@@ -55,8 +54,8 @@ export default function SwitchButtonGroup<T extends string | number = string>({
className={cn(
'flex-1 transition-all',
SIZE_CLASSES[size],
INTERACTIVE_CLASSES,
value === option.value ? SELECTED_CLASSES : UNSELECTED_CLASSES,
buttonClassName,
)}
>
{option.label}
+15 -35
View File
@@ -1,7 +1,7 @@
import React, { forwardRef, useCallback, useImperativeHandle, useRef, useState } from 'react';
import { X } from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { toast } from 'sonner'; // 推荐使用 shadcn 的默认 Toast
import { CopyButton } from '@/components/CopyButton';
import { Button } from './ui/button';
@@ -42,17 +42,9 @@ export interface TextInputAreaProps extends Omit<
title?: string;
externalError?: string;
onClear?: () => void;
/**
* 撑满父容器高度并启用内部滚动(而非按 minRows/maxRows 自动撑高)。
* 用于需要固定高度 + 内部滚动的卡片面板。
*/
fill?: boolean;
/** 是否无边框、无阴影、无圆角(适用于嵌套在其他有边框的容器中) */
borderless?: boolean;
}
// 提炼基础的 ActionButton,全面向 shadcn 核心 Button 样式对齐
function ActionButton({
action,
value,
@@ -115,8 +107,6 @@ const TextInputArea = forwardRef<HTMLTextAreaElement, TextInputAreaProps>((props
title,
externalError,
onClear,
fill = false,
borderless = false,
...restProps
} = props;
@@ -133,10 +123,10 @@ const TextInputArea = forwardRef<HTMLTextAreaElement, TextInputAreaProps>((props
useImperativeHandle(ref, () => internalRef.current as HTMLTextAreaElement);
const adjustHeight = useCallback(() => {
if (fill) return;
const textArea = internalRef.current;
if (!textArea) return;
// 重置高度计算
textArea.style.height = 'auto';
const computedMin = minRows * 24;
@@ -144,7 +134,7 @@ const TextInputArea = forwardRef<HTMLTextAreaElement, TextInputAreaProps>((props
const nextHeight = Math.max(textArea.scrollHeight, computedMin);
textArea.style.height = `${Math.min(nextHeight, computedMax)}px`;
}, [minRows, maxRows, fill]);
}, [minRows, maxRows]);
React.useEffect(() => {
adjustHeight();
@@ -216,7 +206,7 @@ const TextInputArea = forwardRef<HTMLTextAreaElement, TextInputAreaProps>((props
const hasBottomBar = allowCopy || showClear || bottomActions.length > 0;
return (
<div className={cn('w-full flex flex-col gap-1.5', fill && 'flex-1 min-h-0', className)}>
<div className={cn('w-full flex flex-col gap-1.5', className)}>
{hasTopBar && (
<div className="flex items-center justify-between px-0.5">
<div className="flex items-center gap-2">
@@ -245,11 +235,7 @@ const TextInputArea = forwardRef<HTMLTextAreaElement, TextInputAreaProps>((props
<div
className={cn(
borderless
? 'bg-transparent overflow-hidden'
: 'rounded-md border border-input bg-background shadow-sm transition-all focus-within:ring-1 focus-within:ring-ring focus-within:border-input overflow-hidden',
fill && 'flex-1 min-h-0 flex flex-col',
!borderless &&
'rounded-md border border-input bg-background shadow-sm transition-all focus-within:ring-1 focus-within:ring-ring focus-within:border-input overflow-hidden',
displayError &&
'border-destructive focus-within:ring-destructive focus-within:border-destructive',
)}
@@ -263,15 +249,13 @@ const TextInputArea = forwardRef<HTMLTextAreaElement, TextInputAreaProps>((props
autoFocus={autoFocus}
readOnly={readOnly}
placeholder={placeholder}
className={cn(
'w-full bg-transparent px-4 py-3 font-mono text-sm leading-relaxed text-foreground placeholder:text-muted-foreground/50 focus:outline-none resize-none border-0 block',
fill && 'flex-1 h-full overflow-auto diff-scroll',
)}
className="w-full bg-transparent px-4 py-3 font-mono text-sm leading-relaxed text-foreground placeholder:text-muted-foreground/50 focus:outline-none resize-none border-0 block"
{...restProps}
/>
{hasBottomBar && (
<div className="flex h-10 items-center justify-between px-4 bg-muted/30 border-t border-border/50">
{/* 左侧自定义动作 */}
<div className="flex items-center gap-1.5 min-w-0">
{bottomActions.map((action) => (
<ActionButton
@@ -284,24 +268,19 @@ const TextInputArea = forwardRef<HTMLTextAreaElement, TextInputAreaProps>((props
))}
</div>
{/* 右侧系统按钮组 */}
<div className="flex items-center gap-1.5 ml-auto shrink-0">
{allowCopy && value && (
<CopyButton
text={value}
tooltip="复制内容"
variant="ghost"
size="iconSm"
className="text-muted-foreground hover:text-foreground"
/>
<CopyButton text={value} tooltip={'复制内容'} size="sm" className="h-7 w-7 p-1" />
)}
{showClear && value && !disabled && !readOnly && (
<Button
type="button"
onClick={handleClear}
aria-label="清空"
aria-label={'清空'}
variant="ghost"
size="iconSm"
className="text-muted-foreground hover:text-destructive hover:bg-destructive/10"
size="icon"
className="h-7 w-7 text-muted-foreground hover:text-destructive hover:bg-destructive/10"
>
<X className="h-4 w-4" />
</Button>
@@ -311,8 +290,9 @@ const TextInputArea = forwardRef<HTMLTextAreaElement, TextInputAreaProps>((props
)}
</div>
{/* 错误提示 */}
{displayError && (
<p className="text-xs font-medium text-destructive px-0.5 fade-in-slide-top-1">
<p className="text-xs font-medium text-destructive px-0.5 animate-in fade-in slide-in-from-top-1 duration-150">
{displayError}
</p>
)}
+19 -3
View File
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { act, render, screen } from '@testing-library/react';
import { act, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
// unmock the globally-mocked component so we test the real implementation
@@ -68,10 +68,15 @@ describe('CopyButton', () => {
expect(mockedToast.error).toHaveBeenCalled();
});
it('初始渲染时带有默认 aria-label', () => {
// ==================== 新增测试 ====================
it('初始渲染时显示 Copy 图标且无 emerald 样式', () => {
render(<CopyButton text="initial" />);
expect(screen.getByRole('button')).toHaveAttribute('aria-label', '复制');
const button = screen.getByRole('button');
expect(button.className).not.toContain('text-emerald');
// 通过 aria-label 确认按钮存在,图标由 lucide 渲染为 svg
expect(button).toHaveAttribute('aria-label');
});
it('自定义 tooltip 会覆盖默认 title 和 aria-label', () => {
@@ -114,12 +119,15 @@ describe('CopyButton', () => {
await user.click(screen.getByRole('button'));
// 在 1.5 秒超时到期前卸载组件
act(() => {
vi.advanceTimersByTime(500);
});
// 卸载不应抛出 "Can't perform a React state update on an unmounted component" 警告
expect(() => unmount()).not.toThrow();
// 前进剩余时间,确认没有异常
act(() => {
vi.advanceTimersByTime(2000);
});
@@ -133,15 +141,23 @@ describe('CopyButton', () => {
const button = screen.getByRole('button');
// 快速点击 3 次
await user.click(button);
await user.click(button);
await user.click(button);
// copyTextToClipboard 应该被调用 3 次(每次点击都执行)
expect(mockedCopy).toHaveBeenCalledTimes(3);
// 但 setTimeout 相关的 clearTimeout + setTimeout 组合应正常工作
// advance 1.5 秒后,copied 状态应恢复为 false
act(() => {
vi.advanceTimersByTime(1500);
});
await waitFor(() => {
expect(button.className).not.toContain('text-emerald');
});
});
it('其他 button props 通过 ...props 透传', () => {
@@ -4,13 +4,13 @@ import EmptyPlaceholder from '@/components/EmptyPlaceholder';
describe('EmptyPlaceholder 组件', () => {
it('应渲染字符串提示文本', () => {
render(<EmptyPlaceholder></EmptyPlaceholder>);
render(<EmptyPlaceholder>{'请输入内容'}</EmptyPlaceholder>);
expect(screen.getByText('请输入内容')).toBeInTheDocument();
});
it('应应用规范空状态容器样式', () => {
const { container } = render(<EmptyPlaceholder></EmptyPlaceholder>);
const { container } = render(<EmptyPlaceholder>{'提示'}</EmptyPlaceholder>);
const placeholder = container.firstChild;
expect(placeholder).toHaveClass(
@@ -24,14 +24,14 @@ describe('EmptyPlaceholder 组件', () => {
it('应支持 className 自定义容器样式', () => {
const { container } = render(
<EmptyPlaceholder className="flex-1 min-h-[320px]"></EmptyPlaceholder>,
<EmptyPlaceholder className="flex-1 min-h-[320px]">{'提示'}</EmptyPlaceholder>,
);
expect(container.firstChild).toHaveClass('flex-1', 'min-h-[320px]');
});
it('应支持 messageClassName 自定义文本样式', () => {
render(<EmptyPlaceholder messageClassName="text-sm max-w-none"></EmptyPlaceholder>);
render(<EmptyPlaceholder messageClassName="text-sm max-w-none">{'提示'}</EmptyPlaceholder>);
expect(screen.getByText('提示')).toHaveClass('text-sm', 'max-w-none');
});
@@ -0,0 +1,64 @@
import { describe, expect, it } from 'vitest';
import { render } from '@testing-library/react';
import PageSkeleton from '@/components/PageSkeleton';
describe('PageSkeleton 组件', () => {
describe('渲染测试', () => {
it('默认应渲染 dashboard 骨架屏', () => {
const { container } = render(<PageSkeleton />);
// dashboard 骨架屏包含 6 个卡片
const cards = container.querySelectorAll('.rounded-xl');
expect(cards.length).toBe(6);
});
it('variant 为 dashboard 时应渲染仪表盘卡片骨架', () => {
const { container } = render(<PageSkeleton variant="dashboard" />);
// 每个卡片有 2 个骨架元素(图标、文本),6 个卡片共 12 个
const cards = container.querySelectorAll('.rounded-xl');
expect(cards.length).toBe(6);
});
it('variant 为 tool 时应渲染工具页面骨架', () => {
const { container } = render(<PageSkeleton variant="tool" />);
// tool 骨架屏包含标题、输入区、控制栏 3 个按钮、结果区
const skeletons = container.querySelectorAll('.animate-pulse');
expect(skeletons.length).toBeGreaterThan(0);
});
});
describe('布局结构测试', () => {
it('dashboard 骨架屏应使用 grid 布局', () => {
const { container } = render(<PageSkeleton variant="dashboard" />);
const gridContainer = container.firstChild as HTMLElement;
expect(gridContainer).toHaveClass('grid');
});
it('tool 骨架屏应有内边距', () => {
const { container } = render(<PageSkeleton variant="tool" />);
const toolContainer = container.firstChild as HTMLElement;
expect(toolContainer).toHaveClass('p-5');
});
});
describe('骨架屏元素测试', () => {
it('dashboard 骨架屏应包含圆角和边框样式', () => {
const { container } = render(<PageSkeleton variant="dashboard" />);
// 获取第一个卡片容器
const card = container.querySelector('.rounded-xl.border');
expect(card).toBeInTheDocument();
});
it('tool 骨架屏应包含动画脉冲效果', () => {
const { container } = render(<PageSkeleton variant="tool" />);
const skeletons = container.querySelectorAll('.animate-pulse');
expect(skeletons.length).toBeGreaterThan(0);
});
});
});
@@ -6,14 +6,15 @@ import type { PageType } from '@/types/storage';
import React from 'react';
const mockRouterValue = {
currentPage: 'timestamp' as PageType,
visiblePages: ['timestamp', 'jwt'] as PageType[],
currentPage: 'dashboard' as PageType,
visiblePages: ['dashboard', 'timestamp'] as PageType[],
pageOrder: ['timestamp'] as PageType[],
isLoaded: true,
navigateTo: vi.fn(),
syncNavigation: vi.fn(),
goHome: vi.fn(),
setVisiblePages: vi.fn(),
setPageOrder: vi.fn(),
recentlyUsedTools: [] as PageType[],
isLoaded: true,
};
vi.mock('@/providers/RouterProvider', () => ({
@@ -31,15 +32,31 @@ describe('RouterContainer 组件', () => {
};
describe('渲染测试', () => {
it('mount 后应直接渲染页面结构(不等待 storage 加载)', () => {
mockRouterValue.currentPage = 'timestamp';
it('isLoaded 为 false 时应渲染骨架屏', () => {
mockRouterValue.isLoaded = false;
const { container } = renderWithProvider(<RouterContainer />);
expect(container.querySelector('.page-transition-enter')).toBeInTheDocument();
// 骨架屏使用 animate-pulse 类
const skeletons = container.querySelectorAll('.animate-pulse');
expect(skeletons.length).toBeGreaterThan(0);
});
it('isLoaded 为 true 时应渲染页面内容', () => {
mockRouterValue.isLoaded = true;
mockRouterValue.currentPage = 'dashboard';
const { container } = renderWithProvider(<RouterContainer />);
expect(container.querySelector('.page-transition-dashboard')).toBeInTheDocument();
});
});
describe('动画类测试', () => {
it('应应用 enter 动画类', () => {
it('在 dashboard 页面应应用 dashboard 动画类', () => {
mockRouterValue.currentPage = 'dashboard';
renderWithProvider(<RouterContainer />);
const box = document.querySelector('.page-transition-dashboard');
expect(box).toBeInTheDocument();
});
it('在非 dashboard 页面应应用 enter 动画类', () => {
mockRouterValue.currentPage = 'timestamp';
renderWithProvider(<RouterContainer />);
const box = document.querySelector('.page-transition-enter');
@@ -51,7 +68,7 @@ describe('RouterContainer 组件', () => {
it('currentPage 变化时应更新', () => {
const { rerender } = renderWithProvider(<RouterContainer />);
mockRouterValue.currentPage = 'jwt';
mockRouterValue.currentPage = 'timestamp';
rerender(<RouterProvider>{<RouterContainer />}</RouterProvider>);
const box = document.querySelector('.page-transition-enter');
@@ -60,11 +77,13 @@ describe('RouterContainer 组件', () => {
});
describe('页面级错误隔离', () => {
it('PageErrorBoundary 应包裹页面内容', () => {
mockRouterValue.currentPage = 'timestamp';
it('PageErrorBoundary 应包裹在 Suspense 内层', () => {
mockRouterValue.isLoaded = true;
mockRouterValue.currentPage = 'dashboard';
const { container } = renderWithProvider(<RouterContainer />);
const routerBox = container.querySelector('.page-transition-enter');
// 验证 RouterContainer 的 Box 结构存在
const routerBox = container.querySelector('.page-transition-dashboard');
expect(routerBox).toBeInTheDocument();
});
});
@@ -22,7 +22,7 @@ describe('SwitchButtonGroup 组件', () => {
const buttonB = screen.getByRole('button', { name: /选项B/i });
expect(buttonA).toHaveClass('bg-background', 'text-foreground', 'shadow-sm');
expect(buttonB).toHaveClass('hover:bg-accent', 'hover:text-accent-foreground');
expect(buttonB).toHaveClass('hover:bg-background/50');
});
it('点击未选中按钮时应触发 onChange 并传入选中值', () => {
@@ -34,12 +34,11 @@ describe('SwitchButtonGroup 组件', () => {
expect(handleChange).toHaveBeenCalledWith('b');
});
it('点击已选中按钮时仍会触发 onChange 并传回原值', () => {
it('点击已选中按钮时不应触发 onChange', () => {
const handleChange = vi.fn();
render(<SwitchButtonGroup value="a" options={options} onChange={handleChange} />);
fireEvent.click(screen.getByRole('button', { name: /选项A/i }));
expect(handleChange).toHaveBeenCalledTimes(1);
expect(handleChange).toHaveBeenCalledWith('a');
});
@@ -59,6 +58,13 @@ describe('SwitchButtonGroup 组件', () => {
expect(button).toHaveClass('text-xs');
});
it('应支持 buttonSx 自定义按钮样式', () => {
render(<SwitchButtonGroup value="a" options={options} onChange={vi.fn()} />);
const button = screen.getByRole('button', { name: /选项A/i });
expect(button).toBeInTheDocument();
});
it('应支持 ReactNode 类型的 label', () => {
const nodeOptions = [{ value: 'x', label: <span data-testid="custom-label"></span> }];
render(<SwitchButtonGroup value="x" options={nodeOptions} onChange={vi.fn()} />);
@@ -66,6 +72,20 @@ describe('SwitchButtonGroup 组件', () => {
expect(screen.getByTestId('custom-label')).toBeInTheDocument();
});
it('默认按钮样式应禁止文字换行', () => {
render(<SwitchButtonGroup value="a" options={options} onChange={vi.fn()} />);
const button = screen.getByRole('button', { name: /选项A/i });
expect(button).toHaveClass('whitespace-nowrap');
});
it('buttonSx 传入时应覆盖默认换行样式', () => {
render(<SwitchButtonGroup value="a" options={options} onChange={vi.fn()} />);
const button = screen.getByRole('button', { name: /选项A/i });
expect(button).toBeInTheDocument();
});
describe('number 类型支持', () => {
const numberOptions = [
{ value: 2, label: '2' },
@@ -85,7 +105,7 @@ describe('SwitchButtonGroup 组件', () => {
const button2 = screen.getByRole('button', { name: /^2$/i });
const button4 = screen.getByRole('button', { name: /^4$/i });
expect(button2).toHaveClass('hover:bg-accent', 'hover:text-accent-foreground');
expect(button2).toHaveClass('hover:bg-background/50');
expect(button4).toHaveClass('bg-background', 'text-foreground', 'shadow-sm');
});
+2 -2
View File
@@ -22,11 +22,11 @@ const badgeVariants = cva(
},
);
interface BadgeProps
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
}
export { Badge };
export { Badge, badgeVariants };
+1 -2
View File
@@ -21,7 +21,6 @@ const buttonVariants = cva(
sm: 'h-9 rounded-md px-3',
lg: 'h-11 rounded-md px-8',
icon: 'h-10 w-10',
iconSm: 'h-7 w-7',
},
},
defaultVariants: {
@@ -46,4 +45,4 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
);
Button.displayName = 'Button';
export { Button };
export { Button, buttonVariants };
+2 -2
View File
@@ -5,7 +5,7 @@ import { Check } from 'lucide-react';
import { cn } from '@/lib/utils';
const Checkbox = React.forwardRef<
React.ComponentRef<typeof CheckboxPrimitive.Root>,
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
@@ -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>
+6 -6
View File
@@ -12,13 +12,13 @@ const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ComponentRef<typeof DialogPrimitive.Overlay>,
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
'fixed inset-0 z-50 bg-black/80 dark:bg-black/60 transition-opacity duration-200 data-[state=closed]:opacity-0 data-[state=open]:opacity-100',
'fixed inset-0 z-50 bg-black/80 dark:bg-black/60 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className,
)}
{...props}
@@ -33,7 +33,7 @@ interface DialogContentProps extends React.ComponentPropsWithoutRef<
}
const DialogContent = React.forwardRef<
React.ComponentRef<typeof DialogPrimitive.Content>,
React.ElementRef<typeof DialogPrimitive.Content>,
DialogContentProps
>(({ className, children, showCloseButton = true, ...props }, ref) => (
<DialogPortal>
@@ -41,7 +41,7 @@ const DialogContent = React.forwardRef<
<DialogPrimitive.Content
ref={ref}
className={cn(
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-white dark:bg-gray-900 p-6 shadow-lg transition-all duration-200 data-[state=closed]:scale-95 data-[state=open]:scale-100 data-[state=closed]:opacity-0 data-[state=open]:opacity-100 sm:rounded-lg',
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-white dark:bg-gray-900 p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
className,
)}
{...props}
@@ -72,7 +72,7 @@ const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivEleme
DialogFooter.displayName = 'DialogFooter';
const DialogTitle = React.forwardRef<
React.ComponentRef<typeof DialogPrimitive.Title>,
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
@@ -84,7 +84,7 @@ const DialogTitle = React.forwardRef<
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ComponentRef<typeof DialogPrimitive.Description>,
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
+1 -1
View File
@@ -9,7 +9,7 @@ const labelVariants = cva(
);
const Label = React.forwardRef<
React.ComponentRef<typeof LabelPrimitive.Root>,
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} />
+31 -8
View File
@@ -10,7 +10,7 @@ const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ComponentRef<typeof SelectPrimitive.Trigger>,
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
@@ -30,7 +30,7 @@ const SelectTrigger = React.forwardRef<
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ComponentRef<typeof SelectPrimitive.ScrollUpButton>,
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
@@ -44,7 +44,7 @@ const SelectScrollUpButton = React.forwardRef<
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ComponentRef<typeof SelectPrimitive.ScrollDownButton>,
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
@@ -58,14 +58,14 @@ const SelectScrollDownButton = React.forwardRef<
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ComponentRef<typeof SelectPrimitive.Content>,
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = 'popper', ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md transition-all duration-200 data-[state=closed]:scale-95 data-[state=open]:scale-100 data-[state=closed]:opacity-0 data-[state=open]:opacity-100',
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
position === 'popper' &&
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className,
@@ -90,7 +90,7 @@ const SelectContent = React.forwardRef<
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ComponentRef<typeof SelectPrimitive.Label>,
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
@@ -102,7 +102,7 @@ const SelectLabel = React.forwardRef<
SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ComponentRef<typeof SelectPrimitive.Item>,
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
@@ -124,4 +124,27 @@ const SelectItem = React.forwardRef<
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
export { Select, SelectGroup, SelectValue, SelectTrigger, SelectContent, SelectLabel, SelectItem };
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn('-mx-1 my-1 h-px bg-muted', className)}
{...props}
/>
));
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
};
+1 -1
View File
@@ -4,7 +4,7 @@ import * as SwitchPrimitives from '@radix-ui/react-switch';
import { cn } from '@/lib/utils';
const Switch = React.forwardRef<
React.ComponentRef<typeof SwitchPrimitives.Root>,
React.ElementRef<typeof SwitchPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitives.Root
+16 -14
View File
@@ -4,6 +4,10 @@ const pageLoadTracker = vi.hoisted(() => ({
loaded: [] as string[],
}));
vi.mock('@/pages/Dashboard', () => {
pageLoadTracker.loaded.push('Dashboard');
return { default: () => null };
});
vi.mock('@/pages/Timestamp', () => {
pageLoadTracker.loaded.push('Timestamp');
return { default: () => null };
@@ -59,25 +63,23 @@ describe('features 懒加载', () => {
it('访问 FEATURES 元数据时不应加载任何页面模块', async () => {
const { FEATURES } = await import('@/config/features');
expect(FEATURES).toHaveLength(9);
expect(FEATURES).toHaveLength(10);
expect(pageLoadTracker.loaded).toEqual([]);
});
it('loadPage 应仅加载对应页面模块', async () => {
const { loadPage } = await import('@/config/pageLoaders/index');
it('渲染 lazy 组件时才应加载对应页面模块', async () => {
const React = await import('react');
const { render, waitFor } = await import('@testing-library/react');
const { FEATURES } = await import('@/config/features');
await loadPage('timestamp');
const DashboardPage = FEATURES.find((f) => f.key === 'dashboard')!.components.popup;
expect(pageLoadTracker.loaded).toEqual(['Timestamp']);
render(
React.createElement(React.Suspense, { fallback: null }, React.createElement(DashboardPage)),
);
await waitFor(() => {
expect(pageLoadTracker.loaded).toEqual(['Dashboard']);
});
it('loadPage 切换页面时不应加载无关页面模块', async () => {
const { loadPage } = await import('@/config/pageLoaders/index');
await loadPage('jwt');
expect(pageLoadTracker.loaded).toEqual(['Jwt']);
expect(pageLoadTracker.loaded).not.toContain('QrCode');
expect(pageLoadTracker.loaded).not.toContain('TestDataGenerator');
});
});
+28 -7
View File
@@ -9,8 +9,8 @@ import {
describe('features', () => {
describe('FEATURES', () => {
it('应该有9个功能定义', () => {
expect(FEATURES).toHaveLength(9);
it('应该有10个功能定义', () => {
expect(FEATURES).toHaveLength(10);
});
it('应该有每个功能的所有必需属性', () => {
@@ -19,14 +19,21 @@ describe('features', () => {
expect(feature).toHaveProperty('label');
expect(feature).toHaveProperty('description');
expect(feature).toHaveProperty('defaultVisible');
expect(feature).not.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(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');
expect(feature).toHaveProperty('themeColorKey');
expect(typeof feature.themeColorKey).toBe('string');
}
});
});
@@ -38,6 +45,13 @@ describe('features', () => {
});
describe('getFeatureByKey', () => {
it('应该返回dashboard功能', () => {
const feature = getFeatureByKey('dashboard');
expect(feature).toBeDefined();
expect(feature?.key).toBe('dashboard');
expect(feature?.label).toBe('仪表盘');
});
it('应该返回时间戳功能', () => {
const feature = getFeatureByKey('timestamp');
expect(feature).toBeDefined();
@@ -68,8 +82,9 @@ describe('features', () => {
});
});
it('应该包含时间戳、存储清理、二维码', () => {
it('应该包含仪表盘、时间戳、存储清理、二维码', () => {
const visibleKeys = getDefaultVisibleFeatureKeys();
expect(visibleKeys).toContain('dashboard');
expect(visibleKeys).toContain('timestamp');
expect(visibleKeys).toContain('storageCleaner');
expect(visibleKeys).toContain('qrCode');
@@ -79,7 +94,8 @@ describe('features', () => {
describe('getAllFeatureKeys', () => {
it('应该返回所有功能key', () => {
const allKeys = getAllFeatureKeys();
expect(allKeys).toHaveLength(9);
expect(allKeys).toHaveLength(10);
expect(allKeys).toContain('dashboard');
expect(allKeys).toContain('timestamp');
expect(allKeys).toContain('storageCleaner');
expect(allKeys).toContain('qrCode');
@@ -93,9 +109,9 @@ describe('features', () => {
});
describe('getDefaultPageOrder', () => {
it('应该包含所有工具页面', () => {
it('应该排除仪表盘从页面顺序', () => {
const pageOrder = getDefaultPageOrder();
expect(pageOrder).toHaveLength(9);
expect(pageOrder).not.toContain('dashboard');
});
it('应该包含时间戳、存储清理、二维码在页面顺序', () => {
@@ -104,5 +120,10 @@ describe('features', () => {
expect(pageOrder).toContain('storageCleaner');
expect(pageOrder).toContain('qrCode');
});
it('应该有9个项目在页面顺序', () => {
const pageOrder = getDefaultPageOrder();
expect(pageOrder).toHaveLength(9);
});
});
});
-8
View File
@@ -1,8 +0,0 @@
export type { FeatureConfig, PaletteColorKey } from '@/config/featureMeta';
export {
FEATURES,
getAllFeatureKeys,
getDefaultPageOrder,
getDefaultVisibleFeatureKeys,
getFeatureByKey,
} from '@/config/featureMeta';
@@ -1,4 +1,4 @@
import type { ComponentType } from 'react';
import { type ComponentType, lazy } from 'react';
import type { LucideProps } from 'lucide-react';
import type { PageType } from '@/types/storage';
import {
@@ -15,6 +15,18 @@ import {
export type PaletteColorKey = 'primary' | 'success' | 'warning' | 'error' | 'secondary' | 'info';
// 懒加载页面组件
const DashboardPage = lazy(() => import('@/pages/Dashboard'));
const TimestampPage = lazy(() => import('@/pages/Timestamp'));
const StorageCleanerPage = lazy(() => import('@/pages/StorageCleaner'));
const QrCodePage = lazy(() => import('@/pages/QrCode'));
const TextStatisticsPage = lazy(() => import('@/pages/TextStatistics'));
const JwtPage = lazy(() => import('@/pages/Jwt'));
const JsonToolsPage = lazy(() => import('@/pages/JsonTools'));
const Base64ConverterPage = lazy(() => import('@/pages/Base64Converter'));
const RightClickRestorerPage = lazy(() => import('@/pages/RightClickRestorer'));
const TestDataGeneratorPage = lazy(() => import('@/pages/TestDataGenerator'));
export interface FeatureConfig {
key: PageType;
label: string;
@@ -22,9 +34,25 @@ export interface FeatureConfig {
themeColorKey?: PaletteColorKey;
icon?: ComponentType<LucideProps>;
defaultVisible: boolean;
components: {
popup: ComponentType;
sidepanel: ComponentType;
tab: ComponentType;
};
}
export const FEATURES: FeatureConfig[] = [
{
key: 'dashboard',
label: '仪表盘',
description: '',
defaultVisible: true,
components: {
popup: DashboardPage,
sidepanel: DashboardPage,
tab: DashboardPage,
},
},
{
key: 'timestamp',
label: '时间戳',
@@ -32,6 +60,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'primary',
icon: Clock,
defaultVisible: true,
components: {
popup: TimestampPage,
sidepanel: TimestampPage,
tab: TimestampPage,
},
},
{
key: 'storageCleaner',
@@ -40,6 +73,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'warning',
icon: Database,
defaultVisible: true,
components: {
popup: StorageCleanerPage,
sidepanel: StorageCleanerPage,
tab: StorageCleanerPage,
},
},
{
key: 'qrCode',
@@ -48,6 +86,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'success',
icon: QrCode,
defaultVisible: true,
components: {
popup: QrCodePage,
sidepanel: QrCodePage,
tab: QrCodePage,
},
},
{
key: 'textStatistics',
@@ -56,6 +99,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'secondary',
icon: FileText,
defaultVisible: true,
components: {
popup: TextStatisticsPage,
sidepanel: TextStatisticsPage,
tab: TextStatisticsPage,
},
},
{
key: 'jwt',
@@ -64,6 +112,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'info',
icon: Key,
defaultVisible: true,
components: {
popup: JwtPage,
sidepanel: JwtPage,
tab: JwtPage,
},
},
{
key: 'jsonTools',
@@ -72,6 +125,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'primary',
icon: GitCompareArrows,
defaultVisible: true,
components: {
popup: JsonToolsPage,
sidepanel: JsonToolsPage,
tab: JsonToolsPage,
},
},
{
key: 'base64Converter',
@@ -80,6 +138,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'info',
icon: ArrowLeftRight,
defaultVisible: true,
components: {
popup: Base64ConverterPage,
sidepanel: Base64ConverterPage,
tab: Base64ConverterPage,
},
},
{
key: 'rightClickRestorer',
@@ -88,6 +151,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'success',
icon: MousePointerClick,
defaultVisible: true,
components: {
popup: RightClickRestorerPage,
sidepanel: RightClickRestorerPage,
tab: RightClickRestorerPage,
},
},
{
key: 'testDataGenerator',
@@ -96,6 +164,11 @@ export const FEATURES: FeatureConfig[] = [
themeColorKey: 'warning',
icon: FileSpreadsheet,
defaultVisible: true,
components: {
popup: TestDataGeneratorPage,
sidepanel: TestDataGeneratorPage,
tab: TestDataGeneratorPage,
},
},
];
@@ -112,5 +185,16 @@ export function getAllFeatureKeys(): PageType[] {
}
export function getDefaultPageOrder(): PageType[] {
return FEATURES.map((f) => f.key);
return FEATURES.filter((f) => f.key !== 'dashboard').map((f) => f.key);
}
export function getEntryPointType(): 'popup' | 'sidepanel' | 'tab' {
const pathname = window.location.pathname;
if (pathname.includes('sidepanel')) {
return 'sidepanel';
}
if (new URLSearchParams(window.location.search).get('mode') === 'tab') {
return 'tab';
}
return 'popup';
}
@@ -1,5 +0,0 @@
import type { ComponentType } from 'react';
export default function loadBase64Converter(): Promise<{ default: ComponentType }> {
return import('@/pages/Base64Converter');
}
-43
View File
@@ -1,43 +0,0 @@
import type { ComponentType } from 'react';
import type { PageType } from '@/types/storage';
type PageModule = { default: ComponentType };
let pagesStylesLoaded = false;
function ensurePagesStyles(): Promise<unknown> {
if (pagesStylesLoaded) {
return Promise.resolve();
}
pagesStylesLoaded = true;
return import('@/styles/pages.css');
}
export function loadPage(key: PageType): Promise<PageModule> {
return ensurePagesStyles().then(() => {
switch (key) {
case 'timestamp':
return import('@/config/pageLoaders/timestamp').then((m) => m.default());
case 'storageCleaner':
return import('@/config/pageLoaders/storageCleaner').then((m) => m.default());
case 'qrCode':
return import('@/config/pageLoaders/qrCode').then((m) => m.default());
case 'textStatistics':
return import('@/config/pageLoaders/textStatistics').then((m) => m.default());
case 'jwt':
return import('@/config/pageLoaders/jwt').then((m) => m.default());
case 'jsonTools':
return import('@/config/pageLoaders/jsonTools').then((m) => m.default());
case 'base64Converter':
return import('@/config/pageLoaders/base64Converter').then((m) => m.default());
case 'rightClickRestorer':
return import('@/config/pageLoaders/rightClickRestorer').then((m) => m.default());
case 'testDataGenerator':
return import('@/config/pageLoaders/testDataGenerator').then((m) => m.default());
default: {
const _exhaustive: never = key;
return Promise.reject(new Error(`Unknown page: ${String(_exhaustive)}`));
}
}
});
}
-5
View File
@@ -1,5 +0,0 @@
import type { ComponentType } from 'react';
export default function loadJsonTools(): Promise<{ default: ComponentType }> {
return import('@/pages/JsonTools');
}
-5
View File
@@ -1,5 +0,0 @@
import type { ComponentType } from 'react';
export default function loadJwt(): Promise<{ default: ComponentType }> {
return import('@/pages/Jwt');
}
-5
View File
@@ -1,5 +0,0 @@
import type { ComponentType } from 'react';
export default function loadQrCode(): Promise<{ default: ComponentType }> {
return import('@/pages/QrCode');
}
@@ -1,5 +0,0 @@
import type { ComponentType } from 'react';
export default function loadRightClickRestorer(): Promise<{ default: ComponentType }> {
return import('@/pages/RightClickRestorer');
}
-5
View File
@@ -1,5 +0,0 @@
import type { ComponentType } from 'react';
export default function loadStorageCleaner(): Promise<{ default: ComponentType }> {
return import('@/pages/StorageCleaner');
}
@@ -1,5 +0,0 @@
import type { ComponentType } from 'react';
export default function loadTestDataGenerator(): Promise<{ default: ComponentType }> {
return import('@/pages/TestDataGenerator');
}
-5
View File
@@ -1,5 +0,0 @@
import type { ComponentType } from 'react';
export default function loadTextStatistics(): Promise<{ default: ComponentType }> {
return import('@/pages/TextStatistics');
}
-5
View File
@@ -1,5 +0,0 @@
import type { ComponentType } from 'react';
export default function loadTimestamp(): Promise<{ default: ComponentType }> {
return import('@/pages/Timestamp');
}
+28 -2
View File
@@ -1,6 +1,6 @@
import '../../.wxt/types/imports.d.ts';
import { browser } from 'wxt/browser';
import { MessageAction, onMessage } from '@/utils/messages';
import { MessageAction, onMessage, sendMessage } from '@/utils/messages';
import { createAllContextMenus, parseContextMenuClick } from '@/utils/contextMenu';
import { saveContextMenuData } from '@/utils/useContextMenuData';
import { mainWorldInjectionScript } from '@/utils/rightClickInjection';
@@ -24,12 +24,38 @@ export default defineBackground(() => {
const { featureKey, payload } = result.data;
try {
const sidePanelState = await browser.storage.local.get('sidePanelOpen');
const isSidePanelOpen = sidePanelState.sidePanelOpen === true;
if (isSidePanelOpen) {
await sendMessage(MessageAction.CONTEXT_MENU_CLICKED, { featureKey, payload });
return;
}
} catch (err) {
console.debug('[Context Menu] Side panel pipeline is not available:', err);
}
await saveContextMenuData({ featureKey, payload });
try {
await browser.action.openPopup();
} catch (err) {
console.warn('[Context Menu] 自动打开 popup 失败,请手动点击扩展图标,数据已暂存:', err);
console.warn(
'[Context Menu] 自动打开 popup 失败,请手动点击扩展图标,暂存数据已安全保留:',
err,
);
}
});
// 监听扩展图标点击事件,安全激活侧边栏
browser.action.onClicked.addListener(async (tab) => {
if (tab.id) {
try {
await browser.sidePanel.open({ tabId: tab.id });
} catch (err) {
console.error('Failed to open side panel via extension action clicked:', err);
}
}
});
@@ -4,17 +4,18 @@ import { getTextStats } from '@/utils/textStatistics';
import { hidePopover, showTextStatsResult, showTimestampResult } from './uiPopover';
function convertTimestamp(input: string): string {
const invalidText = '无效时间戳';
const num = Number(input.trim());
if (isNaN(num)) {
return '无效时间戳';
return invalidText;
}
// 1e12 区分毫秒/秒级时间戳
// 1e12 判定毫秒/秒级时间戳兼容
const d = num > 1e12 ? new Date(num) : new Date(num * 1000);
if (isNaN(d.getTime())) {
return '无效时间戳';
return invalidText;
}
const year = d.getFullYear();
+22 -10
View File
@@ -1,24 +1,36 @@
import RouterProvider from '@/providers/RouterProvider';
import FeatureNav from '@/layout/FeatureNav';
import TopBar from '@/layout/TopBar';
import RouterContainer from '@/components/RouterContainer';
import ErrorBoundary from '@/components/ErrorBoundary';
import { getEntryPointType } from '@/config/features';
export default function App() {
const entryType = getEntryPointType();
const routerConfig =
entryType === 'tab'
? {
syncKey: 'app/tabRoute' as const,
visiblePagesKey: 'app/tabVisiblePages' as const,
pageOrderKey: 'app/tabPageOrder' as const,
}
: {
syncKey: 'app/popupRoute' as const,
visiblePagesKey: 'app/popupVisiblePages' as const,
pageOrderKey: 'app/popupPageOrder' as const,
};
return (
<RouterProvider
defaultRoute="timestamp"
syncKey="app/popupRoute"
visiblePagesKey="app/popupVisiblePages"
pageOrderKey="app/popupPageOrder"
syncKey={routerConfig.syncKey}
visiblePagesKey={routerConfig.visiblePagesKey}
pageOrderKey={routerConfig.pageOrderKey}
>
<div className="flex w-[450px] max-w-[450px] min-w-[450px] h-[600px] min-h-[600px] overflow-hidden bg-background">
<div className="flex flex-1 min-w-0 flex-col">
<div className="app flex flex-col w-[400px] max-w-[400px] min-w-[400px] h-[600px] min-h-[600px] overflow-hidden bg-background sm:w-screen sm:max-w-none sm:min-w-0 sm:h-screen sm:min-h-0">
<TopBar />
<ErrorBoundary>
<RouterContainer />
</ErrorBoundary>
</div>
<FeatureNav />
</div>
</RouterProvider>
);
}
+9 -2
View File
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Testing Tools</title>
<title>Testing Tools - 标签页</title>
<meta name="manifest.type" content="browser_action" />
<script>
(function () {
@@ -21,7 +21,7 @@
<style>
/* Force initial popup size before React hydration */
html, body {
width: 450px;
width: 400px;
height: 600px;
margin: 0;
padding: 0;
@@ -33,6 +33,13 @@
width: 100%;
height: 100%;
}
/* If opened in a tab (mode=tab), reset the fixed size */
@media screen and (min-width: 600px) {
html, body {
width: 100%;
height: 100%;
}
}
</style>
</head>
<body>
+4 -1
View File
@@ -1,8 +1,11 @@
import ReactDOM from 'react-dom/client';
import { applyThemeFromSnapshot } from '@/utils/themeSnapshot';
import AppRoot from '@/providers/AppRoot';
import '@/styles/shell.css';
import '@/index.css';
import App from './App.tsx';
applyThemeFromSnapshot();
ReactDOM.createRoot(document.getElementById('root')!).render(
<AppRoot>
<App />
+26
View File
@@ -0,0 +1,26 @@
import { useEffect } from 'react';
import RouterProvider from '@/providers/RouterProvider';
import TopBar from '@/layout/TopBar';
import RouterContainer from '@/components/RouterContainer';
import ErrorBoundary from '@/components/ErrorBoundary';
import { MessageAction, sendMessage } from '@/utils/messages';
export default function App() {
useEffect(() => {
sendMessage(MessageAction.SIDE_PANEL_STATE_CHANGED, { isOpen: true });
return () => {
sendMessage(MessageAction.SIDE_PANEL_STATE_CHANGED, { isOpen: false });
};
}, []);
return (
<RouterProvider defaultRoute="dashboard" syncKey="app/sidepanelRoute">
<div className="app flex flex-col h-screen w-full overflow-hidden">
<TopBar />
<ErrorBoundary>
<RouterContainer />
</ErrorBoundary>
</div>
</RouterProvider>
);
}
+25
View File
@@ -0,0 +1,25 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Testing Tools - Side Panel</title>
<script>
(function () {
try {
var raw = localStorage.getItem('snapshot/app/themeMode');
var mode = raw ? JSON.parse(raw) : 'system';
if (mode !== 'light' && mode !== 'dark' && mode !== 'system') mode = 'system';
var isDark =
mode === 'dark' ||
(mode === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);
if (isDark) document.documentElement.classList.add('dark');
} catch (_error) {}
})();
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="./main.tsx"></script>
</body>
</html>
+13
View File
@@ -0,0 +1,13 @@
import ReactDOM from 'react-dom/client';
import { applyThemeFromSnapshot } from '@/utils/themeSnapshot';
import AppRoot from '@/providers/AppRoot';
import '@/index.css';
import App from './App.tsx';
applyThemeFromSnapshot();
ReactDOM.createRoot(document.getElementById('root')!).render(
<AppRoot>
<App />
</AppRoot>,
);
-25
View File
@@ -1,25 +0,0 @@
import { useCallback, useSyncExternalStore } from 'react';
/**
* 监听媒体查询,返回是否匹配。
* 用于在窄屏(popup/sidepanel)与宽屏(tab)间切换布局。
*/
export function useMediaQuery(query: string): boolean {
const subscribe = useCallback(
(onChange: () => void) => {
if (typeof window === 'undefined' || !window.matchMedia) return () => {};
const mql = window.matchMedia(query);
mql.addEventListener('change', onChange);
return () => mql.removeEventListener('change', onChange);
},
[query],
);
const getSnapshot = useCallback(
() =>
typeof window !== 'undefined' && window.matchMedia ? window.matchMedia(query).matches : false,
[query],
);
return useSyncExternalStore(subscribe, getSnapshot, () => false);
}
-107
View File
@@ -1,5 +1,3 @@
@config "../../tailwind.shell.config.js";
@tailwind base;
@tailwind components;
@tailwind utilities;
@@ -92,108 +90,3 @@
::-webkit-scrollbar {
display: none;
}
/* 细滚动条:仅作用于需要内部滚动的面板/结果区(覆盖上方的全局隐藏) */
.diff-scroll {
scrollbar-width: thin;
scrollbar-color: rgba(0, 0, 0, 0.2) transparent;
}
.diff-scroll::-webkit-scrollbar {
display: block;
width: 6px;
height: 6px;
}
.diff-scroll::-webkit-scrollbar-track {
background: transparent;
}
.diff-scroll::-webkit-scrollbar-thumb {
background: rgba(0, 0, 0, 0.2);
border-radius: 3px;
}
.dark .diff-scroll::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.25);
}
@layer components {
.page-transition-enter {
@apply motion-reduce:transition-none;
animation: tt-page-enter 200ms ease-out;
}
}
@layer utilities {
.fade-in-150 {
animation: tt-fade-in 150ms ease-out forwards;
}
.fade-in-200 {
animation: tt-fade-in 200ms ease-out forwards;
}
.fade-in-300 {
animation: tt-fade-in 300ms ease-out forwards;
}
.fade-in-zoom-95 {
animation: tt-fade-in-zoom-95 150ms ease-out forwards;
}
.fade-in-slide-top-1 {
animation: tt-fade-in-slide-top-1 150ms ease-out forwards;
}
.fade-in-slide-top-2 {
animation: tt-fade-in-slide-top-2 150ms ease-out forwards;
}
}
@keyframes tt-fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes tt-fade-in-zoom-95 {
from {
opacity: 0;
transform: scale(0.95);
}
to {
opacity: 1;
transform: scale(1);
}
}
@keyframes tt-fade-in-slide-top-1 {
from {
opacity: 0;
transform: translateY(-0.25rem);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes tt-fade-in-slide-top-2 {
from {
opacity: 0;
transform: translateY(-0.5rem);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes tt-page-enter {
from {
opacity: 0.92;
}
to {
opacity: 1;
}
}
@@ -1,20 +0,0 @@
import { Button } from '@/components/ui/button';
import { useThemeToggle } from './useThemeToggle';
export default function ThemeToggleButton() {
const { ThemeIcon, themeTitle, cycleThemeMode } = useThemeToggle();
return (
<Button
type="button"
variant="ghost"
size="icon"
onClick={cycleThemeMode}
title={themeTitle}
aria-label={themeTitle}
className="h-9 w-9 text-muted-foreground hover:text-foreground"
>
<ThemeIcon className="h-4 w-4" aria-hidden="true" />
</Button>
);
}
@@ -1,82 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import type { PageType } from '@/types/storage';
import FeatureNav from '@/layout/FeatureNav';
import { ThemeModeProvider } from '@/providers/ThemeModeProvider';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn().mockImplementation((query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
const mockNavigateTo = vi.fn();
const mockRouterValue = {
currentPage: 'timestamp' as PageType,
visiblePages: ['timestamp', 'jwt', 'storageCleaner'] as PageType[],
pageOrder: ['jwt', 'timestamp', 'storageCleaner'] as PageType[],
recentlyUsedTools: [] as PageType[],
isLoaded: true,
navigateTo: mockNavigateTo,
setVisiblePages: vi.fn(),
setPageOrder: vi.fn(),
};
vi.mock('@/providers/RouterProvider', () => ({
useRouter: () => mockRouterValue,
}));
describe('FeatureNav 组件', () => {
beforeEach(() => {
vi.clearAllMocks();
mockRouterValue.currentPage = 'timestamp';
mockRouterValue.pageOrder = ['jwt', 'timestamp', 'storageCleaner'];
mockRouterValue.visiblePages = ['timestamp', 'jwt', 'storageCleaner'];
});
const renderFeatureNav = () =>
render(
<ThemeModeProvider>
<FeatureNav />
</ThemeModeProvider>,
);
it('应渲染全部可见工具图标', () => {
renderFeatureNav();
expect(screen.getByLabelText('JWT 解析')).toBeInTheDocument();
expect(screen.getByLabelText('时间戳')).toBeInTheDocument();
expect(screen.getByLabelText('存储清理')).toBeInTheDocument();
});
it('点击图标应调用 navigateTo', () => {
renderFeatureNav();
fireEvent.click(screen.getByLabelText('JWT 解析'));
expect(mockNavigateTo).toHaveBeenCalledWith('jwt');
});
it('当前页对应项应有 active 样式与 aria-current', () => {
renderFeatureNav();
const activeButton = screen.getByLabelText('时间戳');
expect(activeButton).toHaveAttribute('aria-current', 'page');
expect(activeButton).toHaveClass('bg-muted');
expect(activeButton).toHaveClass('border-primary');
});
it('应渲染主题切换按钮', () => {
renderFeatureNav();
expect(screen.getByLabelText(/切换到/)).toBeInTheDocument();
});
});
-39
View File
@@ -1,39 +0,0 @@
import { cn } from '@/lib/utils';
import ThemeToggleButton from './ThemeToggleButton';
import { useFeatureNav } from './useFeatureNav';
export default function FeatureNav() {
const { navItems, currentPage, navigateTo } = useFeatureNav();
return (
<nav aria-label="功能导航" className="flex w-12 shrink-0 flex-col border-l border-border py-2">
<div className="flex flex-1 flex-col items-center gap-1 overflow-y-auto">
{navItems.map(({ key, feature }) => {
const Icon = feature.icon;
const isActive = currentPage === key;
return (
<button
key={key}
type="button"
title={feature.label}
aria-label={feature.label}
aria-current={isActive ? 'page' : undefined}
onClick={() => navigateTo(key)}
className={cn(
'flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground',
isActive && 'border-l-2 border-primary bg-muted text-foreground',
)}
>
<Icon className="h-4 w-4" aria-hidden="true" />
</button>
);
})}
</div>
<div className="mt-1 flex shrink-0 items-center justify-center border-t border-border pt-1">
<ThemeToggleButton />
</div>
</nav>
);
}
@@ -1,27 +0,0 @@
import { getFeatureByKey, type FeatureConfig } from '@/config/features';
import type { PageType } from '@/types/storage';
export interface NavFeatureItem {
key: PageType;
feature: FeatureConfig & { icon: NonNullable<FeatureConfig['icon']> };
}
function isNavFeature(feature: FeatureConfig): feature is NavFeatureItem['feature'] {
return feature.icon != null;
}
export function resolveNavFeatures(keys: PageType[], visiblePages: PageType[]): NavFeatureItem[] {
const visibleSet = new Set(visiblePages);
const items: NavFeatureItem[] = [];
for (const key of keys) {
if (!visibleSet.has(key)) continue;
const feature = getFeatureByKey(key);
if (!feature || !isNavFeature(feature)) continue;
items.push({ key, feature });
}
return items;
}
-21
View File
@@ -1,21 +0,0 @@
import { useMemo } from 'react';
import { useRouter } from '@/providers/RouterProvider';
import type { PageType } from '@/types/storage';
import { resolveNavFeatures, type NavFeatureItem } from './resolveNavFeatures';
export interface UseFeatureNavReturn {
navItems: NavFeatureItem[];
currentPage: PageType;
navigateTo: (page: PageType) => void;
}
export function useFeatureNav(): UseFeatureNavReturn {
const { currentPage, pageOrder, visiblePages, navigateTo } = useRouter();
const navItems = useMemo(
() => resolveNavFeatures(pageOrder, visiblePages),
[pageOrder, visiblePages],
);
return { navItems, currentPage, navigateTo };
}
-24
View File
@@ -1,24 +0,0 @@
import { Monitor, Moon, Sun } from 'lucide-react';
import { useThemeMode } from '@/providers/ThemeModeProvider';
export interface UseThemeToggleReturn {
ThemeIcon: typeof Sun;
themeTitle: string;
cycleThemeMode: () => void;
}
export function useThemeToggle(): UseThemeToggleReturn {
const { mode, setMode } = useThemeMode();
const cycleThemeMode = () => {
const nextMap = { light: 'dark', dark: 'system', system: 'light' } as const;
setMode(nextMap[mode]);
};
const ThemeIcon = mode === 'light' ? Sun : mode === 'dark' ? Moon : Monitor;
const themeTitle =
mode === 'light' ? '切换到深色模式' : mode === 'dark' ? '切换到系统模式' : '切换到浅色模式';
return { ThemeIcon, themeTitle, cycleThemeMode };
}
+10 -8
View File
@@ -5,20 +5,22 @@
## 组件列表
| 目录 | 用途 |
| ------------- | ------------------------------------------ |
| `FeatureNav/` | 右侧功能导航栏:工具图标切换、底部主题切换 |
| --------- | -------------------------------------------------------------- |
| `TopBar/` | 顶部导航栏:搜索(含历史记录)、主题切换、返回导航、标签页打开 |
## 目录结构
遵循与 `pages/` 相同的 UI + Hook 分离模式:
```
layout/FeatureNav/
├── index.tsx # 垂直图标导航 + 底部主题按钮
├── useFeatureNav.ts # 读路由状态,暴露 navItems / navigateTo
├── useThemeToggle.ts # 主题模式循环切换逻辑
├── ThemeToggleButton.tsx # 主题切换按钮
├── resolveNavFeatures.ts # 功能列表解析
layout/TopBar/
├── index.tsx # 布局入口
├── useTopBar.ts # 业务逻辑 Hook
├── constants.ts # 常量
├── SearchInput.tsx # 搜索输入框
├── SearchDropdown.tsx # 搜索结果/历史下拉面板
├── SearchResultItem.tsx # 单条搜索结果项
├── TopBarActions.tsx # 右侧操作按钮组
└── __tests__/
└── index.test.tsx
```
+45
View File
@@ -0,0 +1,45 @@
import { type FeatureConfig } from '@/config/features';
import SearchResultItem from './SearchResultItem';
interface SearchDropdownProps {
searchQuery: string;
searchResults: FeatureConfig[];
recentFeatures: FeatureConfig[];
selectedIndex: number;
onSelect: (feature: FeatureConfig) => void;
}
export default function SearchDropdown({
searchQuery,
searchResults,
recentFeatures,
selectedIndex,
onSelect,
}: SearchDropdownProps) {
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 && (
<div className="px-3 py-1.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/60">
</div>
)}
{isSearching && items.length === 0 ? (
<li className="px-4 py-6 text-center text-sm text-muted-foreground"></li>
) : (
items.map((feature, index) => (
<SearchResultItem
key={feature.key}
feature={feature}
selected={selectedIndex === index}
onSelect={onSelect}
/>
))
)}
</ul>
</div>
);
}
+57
View File
@@ -0,0 +1,57 @@
import { type RefObject } from 'react';
import { Search, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { getSearchShortcutLabel } from './constants';
interface SearchInputProps {
inputRef: RefObject<HTMLInputElement | null>;
searchQuery: string;
onSearchQueryChange: (value: string) => void;
onFocus: () => void;
onKeyDown: (e: React.KeyboardEvent) => void;
onClear: () => void;
}
export default function SearchInput({
inputRef,
searchQuery,
onSearchQueryChange,
onFocus,
onKeyDown,
onClear,
}: SearchInputProps) {
return (
<div className="group relative">
<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)}
onFocus={onFocus}
onKeyDown={onKeyDown}
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 && (
<Button
type="button"
variant="ghost"
size="icon"
onClick={onClear}
aria-label="清除搜索"
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
<X className="h-3 w-3" />
</Button>
)}
</div>
);
}
+34
View File
@@ -0,0 +1,34 @@
import React from 'react';
import { type FeatureConfig } from '@/config/features';
import { cn } from '@/lib/utils';
interface SearchResultItemProps {
feature: FeatureConfig;
selected: boolean;
onSelect: (feature: FeatureConfig) => void;
}
const SearchResultItem = React.memo(({ feature, selected, onSelect }: SearchResultItemProps) => {
return (
<li
role="option"
aria-selected={selected}
onClick={() => onSelect(feature)}
className={cn(
'flex cursor-pointer items-center gap-3 rounded-md px-3 py-2.5 text-sm transition-colors',
selected ? 'bg-accent text-accent-foreground' : 'hover:bg-muted/60',
)}
>
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-muted/80 text-muted-foreground">
{feature.icon && <feature.icon className="h-4 w-4" />}
</div>
<div className="min-w-0 flex-1">
<p className="truncate font-medium text-foreground">{feature.label}</p>
<p className="mt-0.5 truncate text-xs text-muted-foreground">{feature.description}</p>
</div>
</li>
);
});
SearchResultItem.displayName = 'SearchResultItem';
export default SearchResultItem;
+34
View File
@@ -0,0 +1,34 @@
import { type LucideIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
interface TopBarAction {
id: string;
icon: LucideIcon;
title: string;
onClick: () => void;
}
interface TopBarActionsProps {
actions: TopBarAction[];
}
export default function TopBarActions({ actions }: TopBarActionsProps) {
return (
<div className="flex shrink-0 items-center gap-1">
{actions.map(({ id, icon: Icon, title, onClick }) => (
<Button
key={id}
type="button"
variant="ghost"
size="icon"
onClick={onClick}
title={title}
aria-label={title}
className="h-8 w-8 text-muted-foreground"
>
<Icon className="h-4 w-4" />
</Button>
))}
</div>
);
}
@@ -0,0 +1,37 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { getSearchShortcutLabel } from '@/layout/TopBar/constants';
describe('getSearchShortcutLabel', () => {
const originalUserAgent = navigator.userAgent;
afterEach(() => {
vi.stubGlobal('navigator', { ...navigator, userAgent: originalUserAgent });
});
it('macOS 应显示 ⌘K', () => {
vi.stubGlobal('navigator', {
...navigator,
userAgent:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
});
expect(getSearchShortcutLabel()).toBe('⌘K');
});
it('Windows 应显示 Ctrl+K', () => {
vi.stubGlobal('navigator', {
...navigator,
userAgent:
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
});
expect(getSearchShortcutLabel()).toBe('Ctrl+K');
});
it('Linux 应显示 Ctrl+K', () => {
vi.stubGlobal('navigator', {
...navigator,
userAgent:
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
});
expect(getSearchShortcutLabel()).toBe('Ctrl+K');
});
});
@@ -0,0 +1,76 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import type { PageType } from '@/types/storage';
import React from 'react';
import TopBar from '@/layout/TopBar';
import { RouterProvider } from '@/providers/RouterProvider';
import { ThemeModeProvider } from '@/providers/ThemeModeProvider';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn().mockImplementation((query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
const mockRouterValue = {
currentPage: 'dashboard' as PageType,
visiblePages: ['dashboard', 'timestamp'] as PageType[],
pageOrder: ['timestamp'] as PageType[],
isLoaded: true,
navigateTo: vi.fn(),
syncNavigation: vi.fn(),
goHome: vi.fn(),
setVisiblePages: vi.fn(),
setPageOrder: vi.fn(),
};
vi.mock('@/providers/RouterProvider', () => ({
useRouter: () => mockRouterValue,
RouterProvider: ({ children }: { children: React.ReactNode }) => children,
}));
describe('TopBar 组件', () => {
beforeEach(() => {
vi.clearAllMocks();
});
const renderWithProvider = (ui: React.ReactElement) => {
return render(
<ThemeModeProvider>
<RouterProvider>{ui}</RouterProvider>
</ThemeModeProvider>,
);
};
describe('渲染测试', () => {
it('不在 dashboard 时应渲染返回按钮', () => {
mockRouterValue.currentPage = 'timestamp';
renderWithProvider(<TopBar />);
expect(screen.getByLabelText('返回首页')).toBeInTheDocument();
});
it('在 dashboard 上不应渲染返回按钮', () => {
mockRouterValue.currentPage = 'dashboard';
renderWithProvider(<TopBar />);
expect(screen.queryByLabelText('返回首页')).not.toBeInTheDocument();
});
});
describe('交互测试', () => {
it('点击返回按钮时应调用 goHome', () => {
mockRouterValue.currentPage = 'timestamp';
renderWithProvider(<TopBar />);
fireEvent.click(screen.getByLabelText('返回首页'));
expect(mockRouterValue.goHome).toHaveBeenCalledTimes(1);
});
});
});
+11
View File
@@ -0,0 +1,11 @@
export const SEARCH_HISTORY_LIMIT = 10;
export const SEARCH_HISTORY_DISPLAY = 5;
export const isSearchHistory = (val: unknown): val is string[] =>
Array.isArray(val) && val.every((item) => typeof item === 'string');
/** 根据平台返回搜索框快捷键提示文案 */
export function getSearchShortcutLabel(): string {
if (typeof navigator === 'undefined') return 'Ctrl+K';
return /Mac|iPhone|iPad|iPod/i.test(navigator.userAgent) ? '⌘K' : 'Ctrl+K';
}
+91
View File
@@ -0,0 +1,91 @@
import { ArrowLeft, ExternalLink } from 'lucide-react';
import { Button } from '@/components/ui/button';
import SearchDropdown from './SearchDropdown';
import SearchInput from './SearchInput';
import TopBarActions from './TopBarActions';
import { useTopBar } from './useTopBar';
export default function TopBar() {
const {
searchQuery,
showResults,
searchResults,
recentFeatures,
selectedIndex,
isDashboard,
ThemeIcon,
themeTitle,
containerRef,
inputRef,
setSearchQuery,
setShowResults,
setSelectedIndex,
handleSelectFeature,
handleKeyDown,
cycleThemeMode,
handleOpenInTab,
goHome,
clearSearch,
} = useTopBar();
const actions = [
{ id: 'theme', icon: ThemeIcon, title: themeTitle, onClick: cycleThemeMode },
{
id: 'open-in-tab',
icon: ExternalLink,
title: '在标签页打开',
onClick: () => {
void handleOpenInTab();
},
},
];
const handleSearchQueryChange = (value: string) => {
setSearchQuery(value);
setShowResults(true);
setSelectedIndex(-1);
};
const showDropdown = showResults && (searchQuery.trim() || recentFeatures.length > 0);
return (
<header className="relative z-50 flex h-14 items-center justify-between border-b border-border bg-background px-4">
<div className="flex w-10 items-center justify-start">
{!isDashboard && (
<Button
type="button"
variant="outline"
size="icon"
onClick={goHome}
aria-label="返回首页"
className="h-8 w-8 shadow-sm text-muted-foreground"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
</div>
<div ref={containerRef} className="relative mx-4 max-w-md flex-1">
<SearchInput
inputRef={inputRef}
searchQuery={searchQuery}
onSearchQueryChange={handleSearchQueryChange}
onFocus={() => setShowResults(true)}
onKeyDown={handleKeyDown}
onClear={clearSearch}
/>
{showDropdown && (
<SearchDropdown
searchQuery={searchQuery}
searchResults={searchResults}
recentFeatures={recentFeatures}
selectedIndex={selectedIndex}
onSelect={handleSelectFeature}
/>
)}
</div>
<TopBarActions actions={actions} />
</header>
);
}
+171
View File
@@ -0,0 +1,171 @@
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';
import { type FeatureConfig, FEATURES } from '@/config/features';
import { useStorageState } from '@/utils/useStorageState';
import { openExtensionPage } from '@/utils/chromeTabs';
import { isSearchHistory, SEARCH_HISTORY_DISPLAY, SEARCH_HISTORY_LIMIT } from './constants';
export interface UseTopBarReturn {
searchQuery: string;
showResults: boolean;
searchResults: FeatureConfig[];
recentFeatures: FeatureConfig[];
selectedIndex: number;
isDashboard: boolean;
ThemeIcon: typeof Sun;
themeTitle: string;
containerRef: RefObject<HTMLDivElement | null>;
inputRef: RefObject<HTMLInputElement | null>;
setSearchQuery: (value: string) => void;
setShowResults: (value: boolean) => void;
setSelectedIndex: (value: number | ((prev: number) => number)) => void;
handleSelectFeature: (feature: FeatureConfig) => void;
handleKeyDown: (e: React.KeyboardEvent) => void;
cycleThemeMode: () => void;
handleOpenInTab: () => Promise<void>;
goHome: () => void;
clearSearch: () => void;
}
export function useTopBar(): UseTopBarReturn {
const { currentPage, goHome, navigateTo } = useRouter();
const { mode, setMode } = useThemeMode();
const [searchQuery, setSearchQuery] = useState('');
const [showResults, setShowResults] = useState(false);
const [searchHistory, setSearchHistory] = useStorageState(
'app/searchHistory',
[],
isSearchHistory,
);
const [selectedIndex, setSelectedIndex] = useState(-1);
const containerRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const handleOpenInTab = async () => {
await openExtensionPage('popup.html', { mode: 'tab' });
window.close();
};
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
setShowResults(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
useEffect(() => {
const handleGlobalKeyDown = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault();
inputRef.current?.focus();
setShowResults(true);
}
};
document.addEventListener('keydown', handleGlobalKeyDown);
return () => document.removeEventListener('keydown', handleGlobalKeyDown);
}, []);
const searchResults = useMemo(() => {
const query = searchQuery.trim().toLowerCase();
if (!query) return [];
return FEATURES.filter((f) => {
if (f.key === 'dashboard') return false;
return f.label.toLowerCase().includes(query) || f.description.toLowerCase().includes(query);
});
}, [searchQuery]);
const displayedHistory = useMemo(() => {
if (searchQuery.trim()) return [];
return searchHistory
.slice(0, SEARCH_HISTORY_DISPLAY)
.map((key) => FEATURES.find((f) => f.key === key))
.filter((feature): feature is FeatureConfig => !!feature && feature.key !== 'dashboard');
}, [searchHistory, searchQuery]);
const saveToHistory = (featureKey: string) => {
if (!featureKey.trim()) return;
setSearchHistory((prev) =>
[featureKey, ...prev.filter((h) => h !== featureKey)].slice(0, SEARCH_HISTORY_LIMIT),
);
};
const handleSelectFeature = (feature: FeatureConfig) => {
navigateTo(feature.key);
saveToHistory(feature.key);
setSearchQuery('');
setShowResults(false);
};
const cycleThemeMode = () => {
const nextMap = { light: 'dark', dark: 'system', system: 'light' } as const;
setMode(nextMap[mode]);
};
const ThemeIcon = mode === 'light' ? Sun : mode === 'dark' ? Moon : Monitor;
const themeTitle =
mode === 'light' ? '切换到深色模式' : mode === 'dark' ? '切换到系统模式' : '切换到浅色模式';
const handleKeyDown = (e: React.KeyboardEvent) => {
const totalItems = searchQuery.trim() ? searchResults.length : displayedHistory.length;
if (e.key === 'ArrowDown') {
e.preventDefault();
setSelectedIndex((prev) => (prev < totalItems - 1 ? prev + 1 : prev));
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setSelectedIndex((prev) => (prev > 0 ? prev - 1 : prev));
} else if (e.key === 'Enter') {
e.preventDefault();
if (selectedIndex >= 0 && selectedIndex < totalItems) {
if (searchQuery.trim()) {
handleSelectFeature(searchResults[selectedIndex]);
} else {
const selected = displayedHistory[selectedIndex];
if (selected) {
handleSelectFeature(selected);
}
}
} else if (searchQuery.trim() && searchResults.length > 0) {
handleSelectFeature(searchResults[0]);
}
} else if (e.key === 'Escape') {
setShowResults(false);
inputRef.current?.blur();
}
};
const clearSearch = () => {
setSearchQuery('');
setSelectedIndex(-1);
};
return {
searchQuery,
showResults,
searchResults,
recentFeatures: displayedHistory,
selectedIndex,
isDashboard: currentPage === 'dashboard',
ThemeIcon,
themeTitle,
containerRef,
inputRef,
setSearchQuery,
setShowResults,
setSelectedIndex,
handleSelectFeature,
handleKeyDown,
cycleThemeMode,
handleOpenInTab,
goHome,
clearSearch,
};
}
+2 -31
View File
@@ -4,10 +4,9 @@
## 文件说明
| 文件/目录 | 用途 |
| ------------- | -------------------------------------- |
| 文件 | 用途 |
| ---------- | ------------------------------------ |
| `utils.ts` | `cn()` 函数 — shadcn/ui 标准工具函数 |
| `generators/` | 测试数据生成器内置生成器库和分类注册表 |
## cn()
@@ -25,31 +24,3 @@ import { cn } from '@/lib/utils';
```
所有需要动态合并 Tailwind 类名的场景都应使用 `cn()`,而非手动拼接字符串。
## generators/
测试数据生成器的核心生成器库,供 `src/workers/generator.worker.ts` 在后台线程中按字段配置生成数据。
| 文件 | 用途 |
| -------------- | ---------------------------------------------- |
| `index.ts` | 聚合所有生成器,导出分类、查找和搜索函数 |
| `personal.ts` | 个人信息生成器(姓名、邮箱、手机号、身份证等) |
| `business.ts` | 业务数据生成器(订单号、价格、日期、状态等) |
| `technical.ts` | 技术数据生成器(UUID、IPv4、URL |
| `basic.ts` | 基础类型生成器(整数、浮点数、布尔值、字符串) |
使用示例:
```typescript
import { getGeneratorById, searchGenerators } from '@/lib/generators';
const generator = getGeneratorById('chineseName');
const value = generator?.generate({});
const matched = searchGenerators('uuid');
```
约束:
- 新增生成器必须实现 `GeneratorDefinition`,并加入所属分类文件的导出列表。
- 需要唯一值或大批量稳定输出时,优先实现 `generateAtIndex(params, index)`
- 新增分类时同步更新 `generatorCategories`,并确保 `GeneratorSelector` 能展示该分类。
+17
View File
@@ -1,6 +1,14 @@
/**
* 基础类型生成器
* 包含:随机整数、随机浮点数、随机字符串、从列表选择
*/
import type { GeneratorDefinition } from '@/types/testDataGenerator';
import { randomInt, randomPick } from './random';
/**
* 随机整数生成器
*/
export const randomIntGenerator: GeneratorDefinition = {
id: 'randomInt',
name: '随机整数',
@@ -35,6 +43,9 @@ export const randomIntGenerator: GeneratorDefinition = {
},
};
/**
* 随机浮点数生成器
*/
export const randomFloat: GeneratorDefinition = {
id: 'randomFloat',
name: '随机浮点数',
@@ -74,6 +85,9 @@ export const randomFloat: GeneratorDefinition = {
},
};
/**
* 随机字符串生成器
*/
export const randomString: GeneratorDefinition = {
id: 'randomString',
name: '随机字符串',
@@ -152,6 +166,9 @@ export const randomString: GeneratorDefinition = {
},
};
/**
* 从列表选择生成器
*/
export const fromList: GeneratorDefinition = {
id: 'fromList',
name: '从列表选择',
+47
View File
@@ -1,6 +1,14 @@
/**
* 业务数据生成器
* 包含:订单号、价格、日期、状态、数量、评分、折扣、库存
*/
import type { GeneratorDefinition } from '@/types/testDataGenerator';
import { randomInt, randomPick } from './random';
/**
* 格式化日期
*/
function formatDate(date: Date, format: string): string {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
@@ -18,6 +26,9 @@ function formatDate(date: Date, format: string): string {
.replace('ss', seconds);
}
/**
* 订单号生成器
*/
export const orderId: GeneratorDefinition = {
id: 'orderId',
name: '订单号',
@@ -57,6 +68,9 @@ export const orderId: GeneratorDefinition = {
},
};
/**
* 价格生成器
*/
export const price: GeneratorDefinition = {
id: 'price',
name: '价格',
@@ -128,6 +142,9 @@ export const price: GeneratorDefinition = {
},
};
/**
* 生成心理定价(如 9.99, 19.9, 99
*/
function generatePsychologicalPrice(min: number, max: number): number {
const patterns = [
() => {
@@ -150,6 +167,9 @@ function generatePsychologicalPrice(min: number, max: number): number {
return price;
}
/**
* 生成真实分布价格(对数正态分布)
*/
function generateRealisticPrice(min: number, max: number): number {
const mean = (Math.log(min) + Math.log(max)) / 2;
const stdDev = (Math.log(max) - Math.log(min)) / 4;
@@ -162,6 +182,9 @@ function generateRealisticPrice(min: number, max: number): number {
return Math.max(min, Math.min(max, value));
}
/**
* 日期生成器
*/
export const date: GeneratorDefinition = {
id: 'date',
name: '日期',
@@ -212,6 +235,9 @@ export const date: GeneratorDefinition = {
},
};
/**
* 状态生成器
*/
export const status: GeneratorDefinition = {
id: 'status',
name: '状态',
@@ -264,6 +290,9 @@ export const status: GeneratorDefinition = {
},
};
/**
* 数量生成器
*/
export const quantity: GeneratorDefinition = {
id: 'quantity',
name: '数量',
@@ -310,6 +339,9 @@ export const quantity: GeneratorDefinition = {
},
};
/**
* 泊松分布随机数
*/
function poissonRandom(lambda: number): number {
const L = Math.exp(-lambda);
let k = 0;
@@ -321,6 +353,9 @@ function poissonRandom(lambda: number): number {
return k - 1;
}
/**
* 评分生成器
*/
export const rating: GeneratorDefinition = {
id: 'rating',
name: '评分',
@@ -375,6 +410,9 @@ export const rating: GeneratorDefinition = {
},
};
/**
* 偏向高分的随机数(模拟真实评分分布)
*/
function skewedRandom(min: number, max: number): number {
// 使用 Beta 分布模拟评分偏向
const alpha = 3;
@@ -387,6 +425,9 @@ function skewedRandom(min: number, max: number): number {
return min + x * (max - min);
}
/**
* 折扣生成器
*/
export const discount: GeneratorDefinition = {
id: 'discount',
name: '折扣',
@@ -438,6 +479,9 @@ export const discount: GeneratorDefinition = {
},
};
/**
* 生成心理折扣(如 5%, 10%, 20%, 30%
*/
function generatePsychologicalDiscount(min: number, max: number): number {
const psychologicalDiscounts = [5, 10, 15, 20, 25, 30, 40, 50, 60, 70, 80];
const validDiscounts = psychologicalDiscounts.filter((d) => d >= min && d <= max);
@@ -447,6 +491,9 @@ function generatePsychologicalDiscount(min: number, max: number): number {
return randomInt(min, max);
}
/**
* 库存生成器
*/
export const stock: GeneratorDefinition = {
id: 'stock',
name: '库存',
+20
View File
@@ -1,9 +1,17 @@
/**
* 生成器库索引
* 导出所有生成器和分类配置
*/
import type { GeneratorDefinition, GeneratorCategory } from '@/types/testDataGenerator';
import { personalGenerators } from './personal';
import { businessGenerators } from './business';
import { technicalGenerators } from './technical';
import { basicGenerators } from './basic';
/**
* 生成器分类配置
*/
export const generatorCategories: GeneratorCategory[] = [
{ id: 'personal', name: '个人信息', icon: 'User' },
{ id: 'business', name: '业务数据', icon: 'Briefcase' },
@@ -11,6 +19,9 @@ export const generatorCategories: GeneratorCategory[] = [
{ id: 'basic', name: '基础类型', icon: 'Hash' },
];
/**
* 所有生成器列表
*/
export const allGenerators: GeneratorDefinition[] = [
...personalGenerators,
...businessGenerators,
@@ -18,14 +29,23 @@ export const allGenerators: GeneratorDefinition[] = [
...basicGenerators,
];
/**
* 根据 ID 获取生成器
*/
export function getGeneratorById(id: string): GeneratorDefinition | undefined {
return allGenerators.find((g) => g.id === id);
}
/**
* 根据分类 ID 获取生成器列表
*/
export function getGeneratorsByCategory(categoryId: string): GeneratorDefinition[] {
return allGenerators.filter((g) => g.categoryId === categoryId);
}
/**
* 搜索生成器
*/
export function searchGenerators(query: string): GeneratorDefinition[] {
const lowerQuery = query.toLowerCase();
return allGenerators.filter(
+42
View File
@@ -1,6 +1,12 @@
/**
* 个人信息生成器
* 包含:中文姓名、邮箱、手机号、身份证号、中文地址、年龄
*/
import type { GeneratorDefinition } from '@/types/testDataGenerator';
import { randomInt, randomPick } from './random';
// 中文姓氏
const SURNAMES = [
'王',
'李',
@@ -54,6 +60,7 @@ const SURNAMES = [
'阎',
];
// 中文名字常用字
const NAME_CHARS = [
'伟',
'芳',
@@ -107,8 +114,10 @@ const NAME_CHARS = [
'慧',
];
// 邮箱域名
const EMAIL_DOMAINS = ['qq.com', '163.com', '126.com', 'gmail.com', 'outlook.com', 'hotmail.com'];
// 省份
const PROVINCES = [
'北京市',
'天津市',
@@ -144,6 +153,7 @@ const PROVINCES = [
'新疆维吾尔自治区',
];
// 城市
const CITIES: Record<string, string[]> = {
: ['东城区', '西城区', '朝阳区', '海淀区'],
: ['黄浦区', '徐汇区', '长宁区', '静安区'],
@@ -153,6 +163,9 @@ const CITIES: Record<string, string[]> = {
: ['成都市', '绵阳市', '德阳市', '宜宾市'],
};
/**
* 中文姓名生成器
*/
export const chineseName: GeneratorDefinition = {
id: 'chineseName',
name: '中文姓名',
@@ -166,6 +179,9 @@ export const chineseName: GeneratorDefinition = {
},
};
/**
* 邮箱生成器
*/
export const email: GeneratorDefinition = {
id: 'email',
name: '邮箱',
@@ -192,6 +208,9 @@ export const email: GeneratorDefinition = {
},
};
/**
* 手机号生成器
*/
export const chinesePhone: GeneratorDefinition = {
id: 'chinesePhone',
name: '手机号',
@@ -222,6 +241,9 @@ export const chinesePhone: GeneratorDefinition = {
},
};
/**
* 身份证号生成器
*/
export const idCard: GeneratorDefinition = {
id: 'idCard',
name: '身份证号',
@@ -246,12 +268,20 @@ export const idCard: GeneratorDefinition = {
generate: (params) => {
const regions = ['110101', '310101', '440103', '440305', '510104', '330102'];
const region = params.region === 'random' ? randomPick(regions) : (params.region as string);
// 出生日期 1960-2005年
const year = randomInt(1960, 2005);
const month = String(randomInt(1, 12)).padStart(2, '0');
const day = String(randomInt(1, 28)).padStart(2, '0');
const birthday = `${year}${month}${day}`;
// 顺序码
const sequence = String(randomInt(1, 999)).padStart(3, '0');
// 前17位
const prefix17 = region + birthday + sequence;
// 校验码
const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
let sum = 0;
@@ -287,6 +317,9 @@ export const idCard: GeneratorDefinition = {
},
};
/**
* 中文地址生成器
*/
export const chineseAddress: GeneratorDefinition = {
id: 'chineseAddress',
name: '中文地址',
@@ -315,6 +348,9 @@ export const chineseAddress: GeneratorDefinition = {
},
};
/**
* 年龄生成器
*/
export const age: GeneratorDefinition = {
id: 'age',
name: '年龄',
@@ -366,6 +402,9 @@ export const age: GeneratorDefinition = {
},
};
/**
* 正态分布随机数
*/
function normalRandom(min: number, max: number): number {
const mean = (min + max) / 2;
const stdDev = (max - min) / 6;
@@ -378,6 +417,9 @@ function normalRandom(min: number, max: number): number {
return Math.max(min, Math.min(max, value));
}
/**
* 人口统计分布随机数(模拟真实年龄分布)
*/
function demographicRandom(): number {
const ageGroups = [
{ min: 0, max: 14, weight: 0.18 },
+31
View File
@@ -1,6 +1,14 @@
/**
* 技术数据生成器
* 包含:UUID、IPv4、URL
*/
import type { GeneratorDefinition } from '@/types/testDataGenerator';
import { randomInt, randomPick } from './random';
/**
* UUID 生成器
*/
export const uuid: GeneratorDefinition = {
id: 'uuid',
name: 'UUID',
@@ -57,6 +65,9 @@ export const uuid: GeneratorDefinition = {
},
};
/**
* 生成 UUID v4
*/
function generateUUIDv4(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
@@ -65,6 +76,9 @@ function generateUUIDv4(): string {
});
}
/**
* 生成 UUID v1(简化版本,模拟时间戳)
*/
function generateUUIDv1(): string {
const now = Date.now();
const timeLow = (now & 0xffffffff).toString(16).padStart(8, '0');
@@ -78,6 +92,9 @@ function generateUUIDv1(): string {
return `${timeLow}-${timeMid}-${timeHi.toString(16)}-${clockSeq.toString(16)}-${node}`;
}
/**
* IPv4 生成器
*/
export const ipv4: GeneratorDefinition = {
id: 'ipv4',
name: 'IPv4',
@@ -112,10 +129,16 @@ export const ipv4: GeneratorDefinition = {
},
};
/**
* 生成完全随机 IPv4
*/
function generateRandomIPv4(): string {
return Array.from({ length: 4 }, () => randomInt(0, 255)).join('.');
}
/**
* 生成内网 IPv4
*/
function generatePrivateIPv4(): string {
const ranges = [
{ prefix: '10', second: () => randomInt(0, 255) },
@@ -130,6 +153,9 @@ function generatePrivateIPv4(): string {
return `${range.prefix}.${range.second()}.${randomInt(1, 254)}.${randomInt(1, 254)}`;
}
/**
* 生成公网 IPv4
*/
function generatePublicIPv4(): string {
let first: number;
do {
@@ -139,6 +165,9 @@ function generatePublicIPv4(): string {
return `${first}.${randomInt(0, 255)}.${randomInt(0, 255)}.${randomInt(1, 254)}`;
}
/**
* URL 生成器
*/
export const url: GeneratorDefinition = {
id: 'url',
name: 'URL',
@@ -208,6 +237,8 @@ export const url: GeneratorDefinition = {
path = `/${randomPick(['about', 'contact', 'products', 'services', 'blog'])}`;
}
}
// 添加查询参数
let query = '';
if (Math.random() > 0.5) {
const params = new URLSearchParams();
@@ -2,6 +2,15 @@ import { describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import Base64ConverterPage from '../index';
// Mock getEntryPointType
vi.mock('@/config/features', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/config/features')>();
return {
...actual,
getEntryPointType: () => 'sidepanel',
};
});
// Mock 子组件
vi.mock('../components/TextMode', () => ({
default: ({ onSwitchToImageMode }: { onSwitchToImageMode?: () => void }) => (
@@ -13,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 = () =>
@@ -40,16 +40,20 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
decodedFileName,
setCustomFileName,
resetAll,
handleFileSelect,
safeFileSelect,
maxFileSizeStr,
} = useBase64Converter({ mode });
const handleDirectionChange = (next: Base64ConvertDirection) => {
if (next === direction) return;
if (!next || next === direction) return;
resetAll();
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">
@@ -76,7 +80,7 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
e.preventDefault();
setIsDragging(false);
const file = e.dataTransfer.files[0];
if (file) void handleFileSelect(file);
if (file) safeFileSelect(file);
}}
onClick={() => fileInputRef.current?.click()}
className={cn(
@@ -95,7 +99,7 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
hidden
onChange={(e) => {
const file = e.target.files?.[0];
if (file) void handleFileSelect(file);
if (file) safeFileSelect(file);
}}
/>
{isLoading ? (
@@ -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>
@@ -119,7 +123,7 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
{formatBytes(info.size)} · {info.type}
</span>
<span className="text-[11px] font-medium text-primary/80 mt-1">
{'点击或拖拽以替换文件'}
</span>
</div>
) : (
@@ -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>
@@ -154,17 +158,17 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
<div className="p-4 rounded-2xl bg-card border border-border shadow-sm flex flex-col space-y-3">
<div className="flex justify-between items-center select-none">
<span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/90">
Base64
{'Base64 编码结果'}
</span>
<div className="flex gap-2">
<CopyButton
text={result.rawBase64}
tooltip="复制纯 Base64"
tooltip={'复制纯 Base64'}
className="h-6 px-2 rounded-md border text-[10px] font-bold"
/>
<CopyButton
text={result.output}
tooltip="复制 Data URI"
tooltip={'复制 Data URI'}
className="h-6 px-2 rounded-md border text-[10px] font-bold"
/>
</div>
@@ -182,14 +186,14 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
<div className="flex items-center justify-between font-mono text-[10px] text-muted-foreground/70 select-none pt-1">
<div className="flex gap-4 items-center tabular-nums">
<span>
:{' '}
{'原始大小'}:{' '}
<span className="font-semibold text-foreground/80">
{formatBytes(result.originalBytes)}
</span>
</span>
<span className="text-border/60">|</span>
<span>
:{' '}
{'编码大小'}:{' '}
<span className="font-semibold text-foreground/80">
{formatBytes(result.outputBytes)}
</span>
@@ -202,7 +206,7 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
className="h-7 rounded-md text-muted-foreground hover:text-destructive text-[11px] gap-1 px-2"
>
<Trash2 className="w-3.5 h-3.5" />
{'清空'}
</Button>
</div>
</div>
@@ -211,7 +215,7 @@ export default function Base64ConverterSection({ mode }: Base64ConverterSectionP
) : (
<div className="flex flex-col space-y-4">
<TextInputArea
placeholder="输入需要解码的 Base64 或 data URI..."
placeholder={'输入需要解码的 Base64 或 data URI...'}
value={decodeInput}
onChange={setDecodeInput}
externalError={decodeError || undefined}
@@ -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">
@@ -1,3 +1,12 @@
/**
* DecodeResultPaper
*
* FileMode 与 ImageMode 通用的 decode 结果展示组件。
* 提取了二者 decode 输出区完全一致的结构:
* 标题 → 可选预览(children)→ 文件信息 → 文件名输入 → 下载按钮
*
* FileMode 直接使用,ImageMode 通过 children 传入图片预览。
*/
import { Download } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -5,12 +14,19 @@ import { Label } from '@/components/ui/label';
import { formatBytes } from '@/utils/format';
interface DecodeResultPaperProps {
/** 标题文案 */
title: string;
/** 解码后推断的 MIME 类型 */
mimeType: string;
/** 解码后 Blob 的大小(字节) */
blobSize: number;
/** 当前文件名 */
fileName: string;
/** 文件名变更回调 */
onFileNameChange: (name: string) => void;
/** 下载按钮点击回调 */
onDownload: () => void;
/** 可选的预览内容,ImageMode 用于渲染图片预览 */
children?: React.ReactNode;
}
@@ -25,20 +41,31 @@ export default function DecodeResultPaper({
}: DecodeResultPaperProps) {
return (
<div className="p-4 rounded-xl bg-primary/10 border border-primary/30">
{/* 标题 */}
<span className="block mb-2 text-xs font-bold text-muted-foreground">{title}</span>
{/* 可选预览内容(ImageMode 的图片) */}
{children}
{/* 文件信息 */}
<div className="flex gap-4 mb-3">
<span className="text-xs text-muted-foreground"> MIME : {mimeType}</span>
<span className="text-xs text-muted-foreground">: {formatBytes(blobSize)}</span>
<span className="text-xs text-muted-foreground">
{'推断的 MIME 类型'}: {mimeType}
</span>
<span className="text-xs text-muted-foreground">
{'解码大小'}: {formatBytes(blobSize)}
</span>
</div>
{/* 文件名输入 */}
<div className="mb-3">
<Label className="block text-xs font-medium text-muted-foreground mb-1"></Label>
<Label className="block text-xs font-medium text-muted-foreground mb-1">
{'解码后文件名'}
</Label>
<Input value={fileName} onChange={(e) => onFileNameChange(e.target.value)} />
</div>
{/* 下载按钮 */}
<Button
variant="default"
onClick={onDownload}
@@ -46,7 +73,7 @@ export default function DecodeResultPaper({
className="w-full rounded-lg font-bold"
>
<Download className="mr-2 h-4 w-4" />
{'下载'}
</Button>
</div>
);
@@ -8,7 +8,7 @@ interface TextModeProps {
onSwitchToImageMode?: () => void;
}
export default function TextMode({ onSwitchToImageMode }: TextModeProps) {
export default function TextMode({ onSwitchToImageMode }: TextModeProps = {}) {
const {
input,
setInput,
@@ -93,7 +93,16 @@ export function useBase64Converter({ mode }: UseBase64ConverterProps) {
[mode],
);
const decodeResult = useMemo(() => {
const safeFileSelect = useCallback(
(file: File) => {
handleFileSelect(file).catch((err) => {
console.error(`Base64 [${mode}] pipeline crash:`, err);
});
},
[handleFileSelect, mode],
);
const decodePipeline = useMemo(() => {
const cleanedInput = debouncedDecodeInput.replace(/^data:image\/[a-z+]+;base64,/i, '').trim();
if (!cleanedInput) return { decoded: null, error: null };
@@ -109,8 +118,8 @@ export function useBase64Converter({ mode }: UseBase64ConverterProps) {
}
}, [debouncedDecodeInput]);
const decoded = decodeResult.decoded;
const decodeError = decodeResult.error;
const decoded = decodePipeline.decoded;
const decodeError = decodePipeline.error;
const decodedFileName = useMemo(() => {
if (customFileName) return customFileName;
@@ -135,7 +144,7 @@ export function useBase64Converter({ mode }: UseBase64ConverterProps) {
decodedFileName,
setCustomFileName,
resetAll,
handleFileSelect,
safeFileSelect,
maxFileSizeStr,
};
}
+12 -7
View File
@@ -4,7 +4,7 @@ import { useContextMenuData } from '@/utils/useContextMenuData';
const IMAGE_DATA_URI_PATTERN = /^\s*data:image\//i;
const ERROR_MESSAGES: Record<string, string> = {
const ERROR_MESSAGE_TO_I18N: Record<string, string> = {
'Invalid Base64 string': '无效的 Base64 字符串',
'Input appears to be binary data (e.g. an image). Please use the Image tab instead.':
'检测到二进制数据(如图像),请使用图像选项卡',
@@ -30,7 +30,7 @@ export function useTextMode() {
useContextMenuData({ featureKey: 'base64Converter', onData: handleContextMenuData });
const conversion = useMemo(() => {
const conversionPipeline = useMemo(() => {
const trimmed = debouncedInput.trim();
if (!trimmed) return { output: '', error: null };
@@ -38,26 +38,31 @@ export function useTextMode() {
if (direction === 'encode') {
const result = textToBase64(debouncedInput);
return { output: result.output, error: null };
}
} else {
const decoded = base64ToText(trimmed);
return { output: decoded, error: null };
}
} catch (e) {
const message = e instanceof Error ? e.message : '';
const i18nKey = ERROR_MESSAGE_TO_I18N[message];
return {
output: '',
error: ERROR_MESSAGES[message] || message || '转换失败',
error: i18nKey || message || '转换失败',
};
}
}, [debouncedInput, direction]);
const output = conversion.output;
const error = conversion.error;
const output = conversionPipeline.output;
const error = conversionPipeline.error;
const placeholder =
direction === 'encode' ? '输入需要编码为 Base64 的文本...' : '输入需要解码的 Base64 字符串...';
const outputLabel = direction === 'encode' ? 'Base64 编码结果' : '解码文本结果';
const showImageHint = direction === 'decode' && IMAGE_DATA_URI_PATTERN.test(input);
const showImageHint = useMemo(
() => direction === 'decode' && IMAGE_DATA_URI_PATTERN.test(input),
[direction, input],
);
const handleDirectionChange = (value: 'encode' | 'decode') => {
if (value === direction) return;
@@ -1,14 +1,14 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import * as featureConfig from '@/config/features';
import { resolveNavFeatures } from '../resolveNavFeatures';
import { resolveDashboardFeatures } from '../dashboardFeatures';
describe('resolveNavFeatures', () => {
describe('resolveDashboardFeatures', () => {
beforeEach(() => {
vi.restoreAllMocks();
});
it('应按 keys 顺序返回可见工具', () => {
const items = resolveNavFeatures(['jwt', 'timestamp'], ['timestamp', 'jwt']);
it('应按 keys 顺序返回可见工具,并排除 dashboard', () => {
const items = resolveDashboardFeatures(['jwt', 'timestamp'], ['dashboard', 'timestamp', 'jwt']);
expect(items.map((item) => item.key)).toEqual(['jwt', 'timestamp']);
expect(items.map((item) => item.feature.label)).toEqual(['JWT 解析', '时间戳']);
@@ -24,34 +24,25 @@ describe('resolveNavFeatures', () => {
return feature;
});
const items = resolveNavFeatures(['timestamp'], ['timestamp']);
const items = resolveDashboardFeatures(['timestamp'], ['dashboard', 'timestamp']);
expect(items.map((item) => item.key)).toEqual(['timestamp']);
});
it('应过滤不在 visiblePages 中的工具', () => {
const items = resolveNavFeatures(['jwt', 'timestamp'], ['timestamp']);
const items = resolveDashboardFeatures(['jwt', 'timestamp'], ['dashboard', 'timestamp']);
expect(items.map((item) => item.key)).toEqual(['timestamp']);
});
it('visiblePages 无匹配工具时应返回空列表', () => {
const items = resolveNavFeatures(['jwt', 'timestamp'], []);
const items = resolveDashboardFeatures(['jwt', 'timestamp'], ['dashboard']);
expect(items).toEqual([]);
});
it('应过滤缺少 icon 的工具', () => {
const originalGetFeatureByKey = featureConfig.getFeatureByKey;
vi.spyOn(featureConfig, 'getFeatureByKey').mockImplementation((key) => {
const feature = originalGetFeatureByKey(key);
if (key === 'jwt' && feature) {
return { ...feature, icon: undefined };
}
return feature;
});
const items = resolveNavFeatures(['jwt', 'timestamp'], ['jwt', 'timestamp']);
const items = resolveDashboardFeatures(['dashboard', 'timestamp'], ['dashboard', 'timestamp']);
expect(items.map((item) => item.key)).toEqual(['timestamp']);
});
@@ -0,0 +1,100 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { getFeatureByKey } from '@/config/features';
import type { DashboardFeatureItem } from '../useDashboard';
import Index from '../index';
const mockNavigateTo = vi.fn();
const mockUseDashboard = vi.fn();
vi.mock('../useDashboard', () => ({
useDashboard: () => mockUseDashboard(),
}));
function buildFeatureItem(key: 'timestamp' | 'jwt'): DashboardFeatureItem {
const feature = getFeatureByKey(key)!;
return {
key,
feature: feature as DashboardFeatureItem['feature'],
};
}
describe('Dashboard 页面', () => {
beforeEach(() => {
vi.clearAllMocks();
mockUseDashboard.mockReturnValue({
visibleFeatures: [buildFeatureItem('timestamp'), buildFeatureItem('jwt')],
recentFeatures: [],
showRecent: false,
navigateTo: mockNavigateTo,
});
});
it('应渲染全部工具网格', () => {
render(<Index />);
expect(screen.getByText('全部工具')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '时间戳' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'JWT 解析' })).toBeInTheDocument();
});
it('点击工具卡片应触发 navigateTo', async () => {
const user = userEvent.setup();
render(<Index />);
await user.click(screen.getByRole('button', { name: '时间戳' }));
expect(mockNavigateTo).toHaveBeenCalledTimes(1);
expect(mockNavigateTo).toHaveBeenCalledWith('timestamp');
});
it('有最近使用数据时应显示最近使用区块', () => {
mockUseDashboard.mockReturnValue({
visibleFeatures: [buildFeatureItem('timestamp')],
recentFeatures: [buildFeatureItem('jwt')],
showRecent: true,
navigateTo: mockNavigateTo,
});
render(<Index />);
expect(screen.getByText('最近使用')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'JWT 解析' })).toBeInTheDocument();
});
it('无最近使用数据时不应显示最近使用区块', () => {
render(<Index />);
expect(screen.queryByText('最近使用')).not.toBeInTheDocument();
});
it('点击最近使用按钮应触发 navigateTo', async () => {
const user = userEvent.setup();
mockUseDashboard.mockReturnValue({
visibleFeatures: [buildFeatureItem('timestamp')],
recentFeatures: [buildFeatureItem('jwt')],
showRecent: true,
navigateTo: mockNavigateTo,
});
render(<Index />);
await user.click(screen.getByRole('button', { name: 'JWT 解析' }));
expect(mockNavigateTo).toHaveBeenCalledWith('jwt');
});
it('无可见工具时应显示空状态', () => {
mockUseDashboard.mockReturnValue({
visibleFeatures: [],
recentFeatures: [],
showRecent: false,
navigateTo: mockNavigateTo,
});
render(<Index />);
expect(screen.getByText('没有可用的工具')).toBeInTheDocument();
});
});
@@ -0,0 +1,78 @@
import { renderHook } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { useRouter } from '@/providers/RouterProvider';
import { useDashboard } from '../useDashboard';
import type { PageType } from '@/types/storage';
vi.mock('@/providers/RouterProvider', () => ({
useRouter: vi.fn(),
}));
const mockNavigateTo = vi.fn();
function mockRouterState(
overrides: {
visiblePages?: PageType[];
pageOrder?: PageType[];
recentlyUsedTools?: PageType[];
} = {},
) {
vi.mocked(useRouter).mockReturnValue({
currentPage: 'dashboard',
visiblePages: overrides.visiblePages ?? ['dashboard', 'timestamp', 'jwt'],
pageOrder: overrides.pageOrder ?? ['jwt', 'timestamp'],
recentlyUsedTools: overrides.recentlyUsedTools ?? [],
isLoaded: true,
navigateTo: mockNavigateTo,
goHome: vi.fn(),
setVisiblePages: vi.fn(),
setPageOrder: vi.fn(),
});
}
describe('useDashboard', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('应透传 router 中的 navigateTo', () => {
mockRouterState();
const { result } = renderHook(() => useDashboard());
expect(result.current.navigateTo).toBe(mockNavigateTo);
});
it('recentlyUsedTools 有可见工具时应显示最近使用', () => {
mockRouterState({
visiblePages: ['dashboard', 'timestamp', 'jwt'],
recentlyUsedTools: ['timestamp', 'jwt'],
});
const { result } = renderHook(() => useDashboard());
expect(result.current.showRecent).toBe(true);
expect(result.current.recentFeatures.map((item) => item.key)).toEqual(['timestamp', 'jwt']);
});
it('recentlyUsedTools 为空时不应显示最近使用', () => {
mockRouterState({ recentlyUsedTools: [] });
const { result } = renderHook(() => useDashboard());
expect(result.current.showRecent).toBe(false);
expect(result.current.recentFeatures).toEqual([]);
});
it('最近使用中的不可见工具应被过滤', () => {
mockRouterState({
visiblePages: ['dashboard', 'timestamp'],
recentlyUsedTools: ['jwt', 'timestamp'],
});
const { result } = renderHook(() => useDashboard());
expect(result.current.showRecent).toBe(true);
expect(result.current.recentFeatures.map((item) => item.key)).toEqual(['timestamp']);
});
});
+38
View File
@@ -0,0 +1,38 @@
import { getFeatureByKey, type FeatureConfig } from '@/config/features';
import type { PageType } from '@/types/storage';
export type DashboardFeature = FeatureConfig & {
icon: NonNullable<FeatureConfig['icon']>;
};
export interface DashboardFeatureItem {
key: PageType;
feature: DashboardFeature;
}
function isDashboardFeature(feature: FeatureConfig): feature is DashboardFeature {
return feature.icon != null;
}
/**
* 将页面 key 列表解析为 Dashboard 可展示的工具项。
* 过滤条件:在 visiblePages 中且 feature 配置了 icon。
*/
export function resolveDashboardFeatures(
keys: PageType[],
visiblePages: PageType[],
): DashboardFeatureItem[] {
const visibleSet = new Set(visiblePages);
const items: DashboardFeatureItem[] = [];
for (const key of keys) {
if (!visibleSet.has(key)) continue;
const feature = getFeatureByKey(key);
if (!feature || !isDashboardFeature(feature)) continue;
items.push({ key, feature });
}
return items;
}
+80
View File
@@ -0,0 +1,80 @@
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')}>
{showRecent && (
<div className="flex flex-col gap-2">
<h3 className="text-xs font-semibold text-muted-foreground/80 uppercase tracking-wider">
{'最近使用'}
</h3>
<div className="flex flex-wrap gap-2">
{recentFeatures.map(({ key, feature }) => {
const IconComponent = feature.icon;
return (
<button
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',
)}
>
<IconComponent className="h-3.5 w-3.5 text-muted-foreground/70" />
{feature.label}
</button>
);
})}
</div>
</div>
)}
<div className="flex flex-col gap-2">
<h3 className="text-xs font-semibold text-muted-foreground/80 uppercase tracking-wider">
{'全部工具'}
</h3>
{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')}
>
{visibleFeatures.map(({ key, feature }) => {
const IconComponent = feature.icon;
return (
<button
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',
)}
>
<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>
</button>
);
})}
</div>
)}
</div>
</div>
);
}
+31
View File
@@ -0,0 +1,31 @@
import { useMemo } from 'react';
import { useRouter } from '@/providers/RouterProvider';
import type { PageType } from '@/types/storage';
import { resolveDashboardFeatures, type DashboardFeatureItem } from './dashboardFeatures';
export type { DashboardFeatureItem } from './dashboardFeatures';
export interface UseDashboardReturn {
visibleFeatures: DashboardFeatureItem[];
recentFeatures: DashboardFeatureItem[];
showRecent: boolean;
navigateTo: (page: PageType) => void;
}
export function useDashboard(): UseDashboardReturn {
const { navigateTo, visiblePages, pageOrder, recentlyUsedTools } = useRouter();
const visibleFeatures = useMemo(
() => resolveDashboardFeatures(pageOrder, visiblePages),
[pageOrder, visiblePages],
);
const recentFeatures = useMemo(
() => resolveDashboardFeatures(recentlyUsedTools, visiblePages),
[recentlyUsedTools, visiblePages],
);
const showRecent = recentFeatures.length > 0;
return { visibleFeatures, recentFeatures, showRecent, navigateTo };
}
+2 -34
View File
@@ -1,43 +1,11 @@
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect } from 'vitest';
import Index from '../index';
const setWide = (wide: boolean) => {
window.matchMedia = vi.fn().mockImplementation((query: string) => ({
matches: wide,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
}));
};
describe('JsonTools 页面', () => {
beforeEach(() => {
// 默认窄屏(matches:false
setWide(false);
});
it('应该渲染模式切换按钮', () => {
render(<Index />);
// 基本渲染测试:页面含多个模式切换按钮,应至少渲染一个
expect(screen.getAllByRole('button').length).toBeGreaterThan(0);
});
it('窄屏渲染 A/B 数据面板与 Compare 按钮', () => {
setWide(false);
render(<Index />);
expect(screen.getByText('数据 A(原始)')).toBeInTheDocument();
expect(screen.getByText('数据 B(目标)')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Compare A & B/i })).toBeInTheDocument();
});
it('宽屏渲染原始/目标 JSON 标签', () => {
setWide(true);
render(<Index />);
expect(screen.getByText('原始 JSON')).toBeInTheDocument();
expect(screen.getByText('目标 JSON')).toBeInTheDocument();
});
});
@@ -1,78 +0,0 @@
import { renderHook, act } from '@testing-library/react';
import { describe, it, expect } from 'vitest';
import { useJsonTools } from '../useJsonTools';
describe('useJsonTools 窄屏手动比对', () => {
it('canCompare 在两侧输入合法前为 false', () => {
const { result } = renderHook(() => useJsonTools());
expect(result.current.canCompare).toBe(false);
act(() => result.current.setLeftInput('{"a":1}'));
expect(result.current.canCompare).toBe(false);
act(() => result.current.setRightInput('{"b":2}'));
expect(result.current.canCompare).toBe(true);
});
it('非法 JSON 时 canCompare 为 false', () => {
const { result } = renderHook(() => useJsonTools());
act(() => {
result.current.setLeftInput('{"a":1}');
result.current.setRightInput('not json');
});
expect(result.current.canCompare).toBe(false);
});
it('handleCompare 生成结果并自动折叠两侧面板', () => {
const { result } = renderHook(() => useJsonTools());
act(() => {
result.current.setLeftInput('{"a":1}');
result.current.setRightInput('{"a":2}');
});
act(() => result.current.handleCompare());
expect(result.current.hasCompared).toBe(true);
expect(result.current.activeResult).not.toBeNull();
expect(result.current.total).toBeGreaterThan(0);
expect(result.current.collapsedA).toBe(true);
expect(result.current.collapsedB).toBe(true);
});
it('比对后修改输入会重置结果,但保留折叠态', () => {
const { result } = renderHook(() => useJsonTools());
act(() => {
result.current.setLeftInput('{"a":1}');
result.current.setRightInput('{"a":2}');
});
act(() => result.current.handleCompare());
expect(result.current.hasCompared).toBe(true);
expect(result.current.collapsedA).toBe(true);
expect(result.current.collapsedB).toBe(true);
act(() => result.current.setLeftInput('{"a":3}'));
expect(result.current.hasCompared).toBe(false);
expect(result.current.activeResult).toBeNull();
expect(result.current.collapsedA).toBe(true);
expect(result.current.collapsedB).toBe(true);
});
it('toggleCollapseA/B 可逆切换折叠态', () => {
const { result } = renderHook(() => useJsonTools());
expect(result.current.collapsedA).toBe(false);
act(() => result.current.toggleCollapseA());
expect(result.current.collapsedA).toBe(true);
act(() => result.current.toggleCollapseA());
expect(result.current.collapsedA).toBe(false);
});
it('单输入经防抖后持久化,重挂载可恢复', async () => {
localStorage.clear();
const { result, unmount } = renderHook(() => useJsonTools());
act(() => result.current.setInput('{"x":1}'));
await new Promise((r) => setTimeout(r, 300));
unmount();
const { result: result2 } = renderHook(() => useJsonTools());
expect(result2.current.input).toBe('{"x":1}');
});
});
@@ -1,72 +0,0 @@
import React from 'react';
import { ChevronRight } from 'lucide-react';
import { cn } from '@/lib/utils';
export interface CollapsiblePanelProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'title'> {
/** 面板标题 */
title: string;
/** 是否处于折叠态 */
collapsed: boolean;
onToggleCollapse: () => void;
/** 折叠态展示的单行缩略预览文本 */
preview?: string;
/** 展开态内容 */
children?: React.ReactNode;
}
export default function CollapsiblePanel({
title,
collapsed,
onToggleCollapse,
preview,
children,
className,
...props
}: CollapsiblePanelProps) {
return (
<div
className={cn(
'flex flex-col overflow-hidden rounded-md border bg-card transition-all duration-300 ease-in-out',
className,
)}
style={{
flex: collapsed ? '0 0 36px' : '1 1 120px',
}}
{...props}
>
<button
type="button"
onClick={onToggleCollapse}
className={cn(
'flex h-[36px] w-full cursor-pointer select-none items-center justify-between bg-muted/20 hover:bg-muted/30 transition-colors px-3 shrink-0 text-left focus:outline-none focus:bg-muted/40',
!collapsed && 'border-b border-border/60',
)}
>
<span className="text-[11px] font-semibold text-foreground/90 shrink-0">{title}</span>
<span
className={cn(
'flex-1 truncate font-mono text-xs text-muted-foreground/70 ml-3 transition-all duration-300',
collapsed ? 'opacity-100 max-w-full' : 'opacity-0 max-w-0 pointer-events-none',
)}
>
{preview}
</span>
<ChevronRight
className={cn(
'h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground transition-transform duration-300',
!collapsed && 'rotate-90',
)}
/>
</button>
<div
className={cn(
'flex-1 min-h-0 flex flex-col transition-opacity duration-300',
collapsed ? 'opacity-0 pointer-events-none' : 'opacity-100',
)}
>
{children}
</div>
</div>
);
}
@@ -1,72 +0,0 @@
import React from 'react';
import { ArrowLeftRight } from 'lucide-react';
import DiffNavigator from './DiffNavigator';
import { cn } from '@/lib/utils';
export interface CompareActionBarProps extends React.HTMLAttributes<HTMLDivElement> {
canCompare: boolean;
onCompare: () => void;
hasCompared: boolean;
total: number;
currentIndex: number;
onPrev: () => void;
onNext: () => void;
resultsVisible?: boolean;
onShowResults?: () => void;
}
export default function CompareActionBar({
canCompare,
onCompare,
hasCompared,
total,
currentIndex,
onPrev,
onNext,
resultsVisible = true,
onShowResults,
className,
...props
}: CompareActionBarProps) {
return (
<div className={cn('flex shrink-0 items-center justify-center py-0.5', className)} {...props}>
{hasCompared ? (
resultsVisible ? (
<DiffNavigator
total={total}
currentIndex={currentIndex}
onPrev={onPrev}
onNext={onNext}
/>
) : (
<button
type="button"
onClick={onShowResults}
className={cn(
'inline-flex h-8 items-center gap-1.5 rounded-md px-3 text-xs font-semibold transition-colors bg-primary text-primary-foreground hover:bg-primary/90',
)}
>
<ArrowLeftRight className="h-3.5 w-3.5" />
</button>
)
) : (
<button
type="button"
disabled={!canCompare}
onClick={onCompare}
className={cn(
'inline-flex h-8 items-center gap-1.5 rounded-md px-3 text-xs font-semibold transition-colors',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-muted',
canCompare
? 'bg-primary text-primary-foreground hover:bg-primary/90'
: 'cursor-not-allowed bg-muted text-muted-foreground',
)}
>
<ArrowLeftRight className="h-3.5 w-3.5" />
Compare A &amp; B
</button>
)}
</div>
);
}
@@ -30,7 +30,7 @@ export default function DiffNavigator({
)}
{...props}
>
<span className="text-xs font-semibold text-muted-foreground/90"></span>
<span className="text-xs font-semibold text-muted-foreground/90">{'无差异'}</span>
</div>
);
}
@@ -43,10 +43,11 @@ export default function DiffNavigator({
)}
{...props}
>
{/* 上一处差异按钮 */}
<button
type="button"
disabled={isFirst}
aria-label="上一个"
aria-label={'上一个'}
onClick={onPrev}
className={cn(
'p-1 rounded-md text-muted-foreground hover:bg-accent hover:text-foreground',
@@ -62,10 +63,11 @@ export default function DiffNavigator({
{total}
</span>
{/* 下一处差异按钮 */}
<button
type="button"
disabled={isLast}
aria-label="下一个"
aria-label={'下一个'}
onClick={onNext}
className={cn(
'p-1 rounded-md text-muted-foreground hover:bg-accent hover:text-foreground',
+10 -83
View File
@@ -7,99 +7,28 @@ export interface DiffResultProps extends React.HTMLAttributes<HTMLDivElement> {
result: DiffResultType;
viewMode: ViewMode;
activePath?: string;
/** 窄屏填充模式:撑满父容器可用高度并内部滚动,而非使用固定最小/最大高度 */
fill?: boolean;
}
export default function DiffResult({
result,
viewMode,
activePath,
fill = false,
className,
...props
}: DiffResultProps) {
const [expandedPaths, setExpandedPaths] = React.useState<Record<string, 'open' | 'closed'>>({});
const togglePath = React.useCallback((path: string, currentExpanded: boolean) => {
setExpandedPaths((prev) => ({
...prev,
[path]: currentExpanded ? 'closed' : 'open',
}));
}, []);
const leftRef = React.useRef<HTMLDivElement | null>(null);
const rightRef = React.useRef<HTMLDivElement | null>(null);
React.useEffect(() => {
const leftEl = leftRef.current;
const rightEl = rightRef.current;
if (!leftEl || !rightEl) return;
let isSyncingLeftScroll = false;
let isSyncingRightScroll = false;
const handleLeftScroll = () => {
if (isSyncingLeftScroll) {
isSyncingLeftScroll = false;
return;
}
isSyncingRightScroll = true;
rightEl.scrollTop = leftEl.scrollTop;
rightEl.scrollLeft = leftEl.scrollLeft;
};
const handleRightScroll = () => {
if (isSyncingRightScroll) {
isSyncingRightScroll = false;
return;
}
isSyncingLeftScroll = true;
leftEl.scrollTop = rightEl.scrollTop;
leftEl.scrollLeft = rightEl.scrollLeft;
};
leftEl.addEventListener('scroll', handleLeftScroll);
rightEl.addEventListener('scroll', handleRightScroll);
return () => {
leftEl.removeEventListener('scroll', handleLeftScroll);
rightEl.removeEventListener('scroll', handleRightScroll);
};
}, [viewMode]);
if (viewMode === 'sideBySide') {
return (
<div
className={cn(
'flex flex-col md:flex-row gap-4 items-stretch rounded-xl border border-border bg-muted/30 p-1.5 w-full',
fill ? 'min-h-0 flex-1' : '',
className,
)}
className={cn('flex flex-col md:flex-row gap-4 items-stretch w-full', className)}
{...props}
>
<div className="flex-1 min-w-0 min-h-0 flex flex-col">
<SectionLabel text="原始 JSON" />
<JsonTree
ref={leftRef}
node={result.root}
side="left"
activePath={activePath}
fill={fill}
expandedPaths={expandedPaths}
onTogglePath={togglePath}
/>
<div className="flex-1 min-w-0">
<SectionLabel text={'原始 JSON'} />
<JsonTree node={result.root} side="left" activePath={activePath} />
</div>
<div className="flex-1 min-w-0 min-h-0 flex flex-col">
<SectionLabel text="目标 JSON" />
<JsonTree
ref={rightRef}
node={result.root}
side="right"
activePath={activePath}
fill={fill}
expandedPaths={expandedPaths}
onTogglePath={togglePath}
/>
<div className="flex-1 min-w-0">
<SectionLabel text={'目标 JSON'} />
<JsonTree node={result.root} side="right" activePath={activePath} />
</div>
</div>
);
@@ -108,16 +37,13 @@ export default function DiffResult({
return (
<div
className={cn(
'flex flex-col rounded-xl border border-border bg-muted/30 font-mono text-xs shadow-sm overflow-x-auto overflow-y-auto p-1.5',
fill ? 'min-h-0 flex-1' : 'min-h-[200px] max-h-[520px]',
'rounded-xl border border-border bg-card font-mono text-xs shadow-sm overflow-x-auto min-h-[200px] max-h-[520px] overflow-y-auto p-1.5',
className,
)}
{...props}
>
<div className="min-w-full w-fit">
<UnifiedView node={result.root} depth={0} activePath={activePath} />
</div>
</div>
);
}
@@ -207,6 +133,7 @@ const UnifiedView = ({ node, depth, activePath }: UnifiedViewProps) => {
);
}
// 容器节点整块渲染处理
if (node.type === 'added') {
return (
<UnifiedRow
@@ -263,7 +190,7 @@ const UnifiedRow = ({ depth, type, text, active, multiline }: UnifiedRowProps) =
currentTheme.bg,
currentTheme.text,
active &&
'bg-primary/10 relative before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1 before:bg-blue-500 before:content-[""]',
'bg-primary/10 relative before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1 before:bg-blue-500',
)}
style={{
paddingLeft: `${Math.max(0.5, depth * 1.25)}rem`,
@@ -1,154 +0,0 @@
import JsonDiffInput from './JsonDiffInput';
import JsonDiffPanel from './JsonDiffPanel';
import CompareActionBar from './CompareActionBar';
import DiffResult from './DiffResult';
import DiffNavigator from './DiffNavigator';
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import type { UseJsonToolsReturn } from '../useJsonTools';
import type { ViewMode } from '../types';
interface DiffWorkspaceProps {
tools: UseJsonToolsReturn;
}
const VIEW_OPTIONS: { value: ViewMode; label: string }[] = [
{ value: 'sideBySide', label: '并排' },
{ value: 'unified', label: '统一' },
];
export default function DiffWorkspace({ tools }: DiffWorkspaceProps) {
const {
isWide,
viewMode,
setViewMode,
leftInput,
rightInput,
setLeftInput,
setRightInput,
leftError,
rightError,
activeResult,
total,
currentDiffIndex,
handlePrev,
handleNext,
activePath,
hasCompared,
collapsedA,
collapsedB,
toggleCollapseA,
toggleCollapseB,
canCompare,
handleCompare,
previewA,
previewB,
} = tools;
const viewToggle = (
<div className="flex h-10 items-center justify-between rounded-xl border border-border/60 bg-secondary/40 px-1.5">
<SwitchButtonGroup
value={viewMode}
onChange={(v: ViewMode) => setViewMode(v)}
options={VIEW_OPTIONS}
size="small"
/>
</div>
);
if (isWide) {
return (
<div className="flex flex-1 min-h-0 flex-col space-y-4">
{viewToggle}
<div className="flex w-full flex-col items-stretch gap-4 md:flex-row shrink-0">
<JsonDiffInput
label="原始 JSON"
placeholder="输入原始 JSON..."
value={leftInput}
onChange={setLeftInput}
error={leftError}
minRows={9}
/>
<JsonDiffInput
label="目标 JSON"
placeholder="输入目标 JSON..."
value={rightInput}
onChange={setRightInput}
error={rightError}
minRows={9}
/>
</div>
{activeResult ? (
<div className="flex min-h-0 flex-1 flex-col space-y-3.5 pt-1">
<div className="flex w-full justify-center shrink-0">
<DiffNavigator
total={total}
currentIndex={currentDiffIndex}
onPrev={handlePrev}
onNext={handleNext}
/>
</div>
<DiffResult result={activeResult} viewMode={viewMode} activePath={activePath} fill />
</div>
) : (
<EmptyPlaceholder className="min-h-[140px] flex-1" messageClassName="max-w-[260px]">
{leftError || rightError
? '请修正上方 JSON 的语法错误以开启实时流式比对'
: '输入两侧 JSON 后点击比较'}
</EmptyPlaceholder>
)}
</div>
);
}
const resultsVisible = collapsedA && collapsedB;
const handleShowResults = () => {
if (!collapsedA) toggleCollapseA();
if (!collapsedB) toggleCollapseB();
};
return (
<div className="flex flex-1 min-h-0 flex-col gap-3">
<JsonDiffPanel
title="数据 A(原始)"
placeholder="输入原始 JSON..."
value={leftInput}
onChange={setLeftInput}
error={leftError}
collapsed={collapsedA}
onToggleCollapse={toggleCollapseA}
preview={previewA}
/>
<CompareActionBar
canCompare={canCompare}
onCompare={handleCompare}
hasCompared={hasCompared}
total={total}
currentIndex={currentDiffIndex}
onPrev={handlePrev}
onNext={handleNext}
resultsVisible={resultsVisible}
onShowResults={handleShowResults}
/>
<JsonDiffPanel
title="数据 B(目标)"
placeholder="输入目标 JSON..."
value={rightInput}
onChange={setRightInput}
error={rightError}
collapsed={collapsedB}
onToggleCollapse={toggleCollapseB}
preview={previewB}
/>
{activeResult && resultsVisible ? (
<div className="flex min-h-0 flex-1">
<DiffResult result={activeResult} viewMode={viewMode} activePath={activePath} fill />
</div>
) : null}
</div>
);
}
@@ -1,100 +1,113 @@
import React, { useMemo } from 'react';
import React, { useEffect, useMemo, useState } from 'react';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import TextInputArea from '@/components/TextInputArea';
import JsonResultPanel from './JsonResultPanel';
import CollapsiblePanel from './CollapsiblePanel';
import { validateJson } from '@/utils/jsonFormatter';
import { cn } from '@/lib/utils';
import { buildPreview, type UseJsonToolsReturn } from '../useJsonTools';
import type { ConvertFunction, ConvertResult } from '../types';
const CONVERT_LABELS: Record<string, { inputPlaceholder: string; outputLabel: string }> = {
const CONVERT_LABELS: Record<
string,
{ inputPlaceholder: string; outputLabel: string; emptyHint: string }
> = {
yaml: {
inputPlaceholder: '输入需要转换的 JSON...',
outputLabel: 'YAML 结果',
emptyHint: '输入 JSON 后点击转换',
},
toml: {
inputPlaceholder: '输入需要转换的 JSON...',
outputLabel: 'TOML 结果',
emptyHint: '输入 JSON 后点击转换',
},
minify: {
inputPlaceholder: '输入需要压缩的 JSON...',
outputLabel: '压缩结果',
emptyHint: '输入 JSON 后点击压缩',
},
};
interface JsonConvertSectionProps extends React.HTMLAttributes<HTMLDivElement> {
tools: UseJsonToolsReturn;
mode: string;
translationPrefix: string;
convertFunction: ConvertFunction;
}
export default function JsonConvertSection({
tools,
mode,
translationPrefix,
convertFunction,
className,
...props
}: JsonConvertSectionProps) {
const { input, setInput, debouncedInput } = tools;
const [inputCollapsed, setInputCollapsed] = useState(false);
const [input, setInput] = useState('');
const [debouncedInput, setDebouncedInput] = useState('');
const labels = CONVERT_LABELS[mode] ?? CONVERT_LABELS.yaml;
const pk = translationPrefix;
const labels = CONVERT_LABELS[pk] || CONVERT_LABELS.yaml;
// Debounce input
useEffect(() => {
const handle = setTimeout(() => {
setDebouncedInput(input);
}, 250);
return () => clearTimeout(handle);
}, [input]);
const error = useMemo(() => {
return validateJson(debouncedInput);
}, [debouncedInput]);
const { result, runtimeError } = useMemo((): {
result: ConvertResult | null;
runtimeError: string | null;
} => {
const conversionPipeline = useMemo(() => {
const trimmed = debouncedInput.trim();
if (!trimmed || error) return { result: null, runtimeError: null };
if (!trimmed || error) return null;
try {
return { result: convertFunction(debouncedInput), runtimeError: null };
return convertFunction(debouncedInput);
} catch (e) {
// 捕获可能从外部转换器(如 YAML.stringify)中抛出的底层异常
return {
result: null,
runtimeError: e instanceof Error ? e.message : String(e),
isRuntimeError: true,
errorMessage: e instanceof Error ? e.message : String(e),
};
}
}, [debouncedInput, error, convertFunction]);
const preview = useMemo(() => buildPreview(input), [input]);
const runtimeError =
conversionPipeline && 'isRuntimeError' in conversionPipeline
? conversionPipeline.errorMessage
: null;
const result =
conversionPipeline && !('isRuntimeError' in conversionPipeline)
? (conversionPipeline as ConvertResult)
: null;
return (
<div className={cn('w-full flex flex-1 min-h-0 flex-col gap-3', className)} {...props}>
<CollapsiblePanel
title="JSON 输入"
collapsed={inputCollapsed}
onToggleCollapse={() => setInputCollapsed((v) => !v)}
preview={preview}
>
<div className={cn('w-full flex flex-col gap-4', className)} {...props}>
{/* 输入区 */}
<TextInputArea
fill
borderless
placeholder={labels.inputPlaceholder}
value={input}
onChange={setInput}
externalError={error || runtimeError || undefined}
showClear={true}
allowCopy={true}
className="min-h-0 flex-1"
minRows={7}
maxRows={14}
onClear={() => setInput('')}
/>
</CollapsiblePanel>
{result?.output && (
<div className="flex min-h-0 flex-1">
{/* Result display */}
{result && result.output ? (
<JsonResultPanel
fill
title={labels.outputLabel}
content={result.output}
originalBytes={result.originalBytes}
outputBytes={result.outputBytes}
maxHeight="380px"
/>
</div>
) : (
<EmptyPlaceholder>
{error ? '请修正上方 JSON 的语法错误以开启实时流式格式化' : labels.emptyHint}
</EmptyPlaceholder>
)}
</div>
);
@@ -1,59 +0,0 @@
import React from 'react';
import TextInputArea from '@/components/TextInputArea';
import CollapsiblePanel from './CollapsiblePanel';
import { cn } from '@/lib/utils';
export interface JsonDiffPanelProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange'> {
/** 面板标题,如 "数据 A(原始)" */
title: string;
placeholder: string;
value: string;
onChange: (value: string) => void;
error?: string | null;
/** 是否处于折叠态 */
collapsed: boolean;
onToggleCollapse: () => void;
/** 折叠态展示的单行缩略预览文本 */
preview: string;
}
export default function JsonDiffPanel({
title,
placeholder,
value,
onChange,
error,
collapsed,
onToggleCollapse,
preview,
className,
...props
}: JsonDiffPanelProps) {
return (
<CollapsiblePanel
title={title}
collapsed={collapsed}
onToggleCollapse={onToggleCollapse}
preview={preview}
className={cn(
error
? 'border-destructive focus-within:ring-1 focus-within:ring-destructive focus-within:border-destructive'
: 'border-border focus-within:ring-1 focus-within:ring-ring focus-within:border-border/80',
className,
)}
{...props}
>
<TextInputArea
fill
value={value}
onChange={onChange}
placeholder={placeholder}
externalError={error ?? undefined}
showClear={true}
allowCopy={true}
borderless
className="min-h-0 flex-1"
/>
</CollapsiblePanel>
);
}
@@ -1,63 +1,73 @@
import { useMemo, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import {
formatJson,
type JsonFormatOptions,
type JsonFormatResult,
validateJson,
} from '@/utils/jsonFormatter';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
import TextInputArea from '@/components/TextInputArea';
import CollapsiblePanel from './CollapsiblePanel';
import JsonResultPanel from './JsonResultPanel';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { buildPreview, type UseJsonToolsReturn } from '../useJsonTools';
interface JsonFormatSectionProps {
tools: UseJsonToolsReturn;
}
export default function JsonFormatSection({ tools }: JsonFormatSectionProps) {
const { input, setInput, debouncedInput } = tools;
export default function JsonFormatSection() {
const [input, setInput] = useState('');
const [debouncedInput, setDebouncedInput] = useState('');
const [indentSize, setIndentSize] = useState<number>(2);
const [sortKeys, setSortKeys] = useState(false);
const [inputCollapsed, setInputCollapsed] = useState(false);
// Debounce input
useEffect(() => {
const handle = setTimeout(() => {
setDebouncedInput(input);
}, 250);
return () => clearTimeout(handle);
}, [input]);
const error = useMemo(() => {
return validateJson(debouncedInput);
}, [debouncedInput]);
const { result, runtimeError } = useMemo((): {
result: JsonFormatResult | null;
runtimeError: string | null;
} => {
// Real-time formatting pipeline
const formattedPipeline = useMemo(() => {
const trimmed = debouncedInput.trim();
if (!trimmed || error) return { result: null, runtimeError: null };
if (!trimmed || error) return null;
try {
const options: JsonFormatOptions = { indentSize, sortKeys };
return { result: formatJson(debouncedInput, options), runtimeError: null };
return formatJson(debouncedInput, options);
} catch (e) {
return {
result: null,
runtimeError: e instanceof SyntaxError ? e.message : String(e),
isRuntimeError: true,
errorMessage: e instanceof SyntaxError ? e.message : String(e),
};
}
}, [debouncedInput, error, indentSize, sortKeys]);
const preview = useMemo(() => buildPreview(input), [input]);
const runtimeError =
formattedPipeline && 'isRuntimeError' in formattedPipeline
? formattedPipeline.errorMessage
: null;
const result =
formattedPipeline && !('isRuntimeError' in formattedPipeline)
? (formattedPipeline as JsonFormatResult)
: null;
return (
<div className="w-full flex flex-1 min-h-0 flex-col gap-3">
<div className="flex h-10 items-center justify-between px-1.5 bg-secondary/40 rounded-xl border border-border/60 shrink-0">
<div className="w-full flex flex-col gap-4">
{/* 工具控制栏 */}
<div className="flex h-10 items-center justify-between px-1.5 bg-secondary/40 rounded-xl border border-border/60">
<div className="flex gap-4 items-center w-full">
{/* 缩进配置区 */}
<div className="flex gap-2 items-center shrink-0 select-none">
<span className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider">
{'缩进'}
</span>
<SwitchButtonGroup
value={indentSize}
onChange={(v: number) => setIndentSize(Number(v))}
onChange={(v) => setIndentSize(Number(v))}
options={[2, 4, 6, 8].map((size) => ({ value: size, label: String(size) }))}
size="small"
/>
@@ -65,6 +75,7 @@ export default function JsonFormatSection({ tools }: JsonFormatSectionProps) {
<div className="h-4 w-px bg-border/60" />
{/* 键名排序区 */}
<div
onClick={() => setSortKeys(!sortKeys)}
className="flex items-center gap-2 cursor-pointer select-none group py-1"
@@ -80,42 +91,37 @@ export default function JsonFormatSection({ tools }: JsonFormatSectionProps) {
htmlFor="sort-keys-checkbox"
className="text-xs font-bold text-foreground/80 cursor-pointer tracking-tight group-hover:text-foreground"
>
{'键名排序'}
</Label>
</div>
</div>
</div>
<CollapsiblePanel
title="JSON 输入"
collapsed={inputCollapsed}
onToggleCollapse={() => setInputCollapsed((v) => !v)}
preview={preview}
>
{/* 满血版输入终端 */}
<TextInputArea
fill
borderless
placeholder="输入需要格式化的 JSON..."
placeholder={'输入需要格式化的 JSON...'}
value={input}
onChange={setInput}
externalError={error || runtimeError || undefined}
showClear={true}
allowCopy={true}
className="min-h-0 flex-1"
minRows={8}
maxRows={15}
onClear={() => setInput('')}
/>
</CollapsiblePanel>
{result?.formatted && (
<div className="flex min-h-0 flex-1">
{/* 格式化结果流面板展示 */}
{result && result.formatted ? (
<JsonResultPanel
fill
title="格式化结果"
content={result.formatted}
originalBytes={result.originalBytes}
outputBytes={result.formattedBytes}
/>
</div>
) : (
<EmptyPlaceholder>
{error ? '请修正上方 JSON 的语法错误以开启实时流式格式化' : '输入 JSON 后点击格式化'}
</EmptyPlaceholder>
)}
</div>
);

Some files were not shown because too many files have changed in this diff Show More