Refactor and enhance form recognition, mapping, and UI components (#18)

* docs: 添加组件文档注释和类型导入

refactor: 统一使用 SnackbarOptions 类型
style: 优化导入语句顺序和格式

* refactor: 简化假数据生成器中的faker导入和使用

Co-authored-by: Copilot <copilot@github.com>

* feat(form-recognizer): 增强表单识别功能并优化UI交互

- 新增字段类型偏好设置功能,支持按域名保存字段类型
- 重构FieldList组件,改进字段选择和类型修改体验
- 添加字段定位闪烁功能,便于在页面上快速找到对应字段
- 优化表单填充逻辑,支持单个字段覆盖默认填充模式
- 移除独立的侧边栏页面,统一使用主页面组件
- 改进useStorageState钩子,增加加载状态管理和防抖处理

* refactor: 移除未使用的组件文件

* refactor(页面头部): 提取通用 PageHeader 组件并替换各页面头部实现

重构各页面头部为统一的 PageHeader 组件,提高代码复用性和维护性

* style(组件): 调整自动刷新开关和存储选项网格的样式

优化自动刷新开关的文本内边距,重构存储选项网格的布局结构,调整间距和边框样式

* style(ui): 调整时间戳页面和结果视图的样式

- 为时区选择器添加圆角
- 优化结果视图的布局和对齐方式
- 调整结果项的内边距和文本样式

* ci(workflow): 移除Firefox测试以简化CI流程

仅保留Chrome浏览器的构建步骤,减少CI运行时间和资源消耗

* refactor(qrcode): 重构二维码解析功能并提取为独立模块

* style(页面样式): 统一页面头部图标颜色并优化表单样式

更新各页面头部组件的图标颜色配置,移除冗余的表单标签属性,优化输入框样式和按钮悬停效果

* feat(formMapping): 添加表单映射功能

- 创建 FormMappingPage 页面组件
- 实现表单扫描器 scanner.ts
- 实现高亮器 highlighter.ts
- 更新路由配置 routes.ts
- 更新内容脚本 content.ts
- 更新类型定义 storage.d.ts
- 添加 formMappingPageStyles 样式配置

* feat(表单映射): 添加配置导出功能及状态提示

添加配置导出为JSON文件的功能,包含导出按钮和错误处理。新增Snackbar组件用于显示导出成功和错误状态。优化页面布局结构,将状态提示移至全局容器外。

* feat(表单填充): 新增智能表单填充功能

添加智能表单填充功能,包括:
1. 新增表单填充页面和路由配置
2. 实现模糊匹配引擎和智能注入引擎
3. 添加Mock数据生成器和视觉反馈渲染器
4. 扩展消息接口支持填充操作

* ci: 精简触发CI的工作流分支

移除对develop分支及其变体的触发,仅保留main分支的触发

* test: 更新路由测试以匹配新增的路由数量

* test: 将测试文件中的描述和断言翻译为中文

* test(PageHeader): 添加组件测试用例验证渲染逻辑和样式

* refactor(theme): 重构主题样式并优化仪表盘卡片组件

将页面样式配置集中管理,移除各页面中硬编码的背景色
新增 DashboardCard 组件封装通用卡片逻辑
添加 dashboardCards 配置文件统一管理卡片数据

* refactor(Button): 统一按钮样式并移除重复样式定义

将按钮样式统一封装到 Button 组件中,移除各页面重复的样式定义
更新组件文档说明,提供更清晰的用法示例

* docs: 更新 README 文件中的目录结构说明

添加新组件和配置文件的说明,保持文档与代码同步

* refactor: 优化代码类型声明和UI布局

修复类型声明从any改为never以提高类型安全性
调整TimestampPage页面布局间距
移除DashboardPage中不必要的实时时钟状态
更新ESLint配置以使用推荐配置
添加选项页面打开的错误处理

* refactor(消息通信): 使用 @webext-core/messaging 重构消息处理逻辑

将原有的 chrome.runtime.onMessage 和 chrome.tabs.sendMessage 替换为类型安全的 @webext-core/messaging 实现
添加 ProtocolMap 类型定义确保消息类型安全
更新相关页面和后台脚本使用新的消息通信方式

* fix: 修复依赖项缺失导致的潜在问题

修复 useStorageState 中缺少 defaultValue 依赖的问题
重构 RouterProvider 的初始化逻辑,使用 useCallback 优化性能

* refactor: 重构表单识别和消息处理逻辑

将表单映射UI逻辑提取到独立文件
将消息处理器提取到独立文件
将表单识别页面逻辑提取到自定义hook
优化代码结构和可维护性

* feat(侧边栏): 添加侧边栏状态变化通知功能

- 在消息类型中新增侧边栏状态变化枚举和字段
- 侧边栏打开和关闭时发送状态通知
- 替换轮询检查方式为消息监听机制

* refactor: 优化高亮组件渲染逻辑并添加防抖处理

重构高亮组件渲染逻辑,使用 requestAnimationFrame 进行节流优化
在 useStorageCleaner 中添加防抖处理以避免频繁加载

* refactor: 统一组件导出方式为默认导出

* refactor: 重构样式系统并迁移至 MUI 主题

删除冗余的 CSS 文件,统一使用 MUI 主题管理样式
新增 useActiveTabDomain 和 useSidePanelState 自定义 Hook
优化各入口点的主题集成和布局处理

* docs: 更新项目文档以反映新增功能和技术栈细节

更新 AGENTS.md 文档,详细描述新增的功能模块(存储管理、URL 管理、二维码生成、表单工具套件等)和更新的技术栈信息

* feat: 添加错误边界组件以捕获子组件错误

在 popup、sidepanel 和 options 入口点添加 ErrorBoundary 组件,用于捕获并处理子组件中的 JavaScript 错误。当错误发生时,显示友好的错误界面并提供刷新功能。

* refactor(ui): 使用全局 snackbar 替换本地通知组件

重构表单页面中的通知系统,移除本地 Snackbar 和 Alert 组件,改用全局 GlobalSnackbar 组件统一管理通知
标准化主题配置中的 CSS 属性命名,移除带前缀的样式属性

* refactor(snackbar): 重构全局消息提示为 SnackbarProvider 组件

将原本分散在各页面的 GlobalSnackbar 组件重构为集中管理的 SnackbarProvider,通过 Context 提供统一的消息提示功能。主要变更包括:

1. 创建新的 SnackbarProvider 组件作为全局消息提示容器
2. 提供 useSnackbar hook 供子组件调用
3. 移除各页面中独立的 GlobalSnackbar 实例
4. 在 App 根组件中统一集成 SnackbarProvider
5. 优化消息提示样式和交互行为

* refactor(Snackbar): 重构消息提示组件并优化样式

重构 Snackbar 组件,将状态管理逻辑提取到 GlobalSnackbar 中复用
优化消息提示样式,调整阴影效果和最小尺寸
统一各页面使用 Snackbar 的方式,移除冗余配置

* refactor: 重构路由和功能配置系统

- 将路由配置和仪表盘卡片配置合并为统一的 features 配置
- 重构 RouterProvider 增加数据校验和本地快照功能
- 优化表单字段识别和填充逻辑,提取公共方法
- 更新相关组件和文档以适配新的配置系统
- 删除废弃的 dashboardCards 和 routes 配置文件
This commit is contained in:
LingandRX
2026-05-01 18:00:06 +08:00
committed by GitHub
parent 60537f6e2e
commit 8d36f21f1b
64 changed files with 2901 additions and 2197 deletions
+22 -3
View File
@@ -1,11 +1,30 @@
import { Button as MuiButton, ButtonProps as MuiButtonProps } from '@mui/material';
/**
* 按钮属性类型
* 继承自 MUI ButtonProps,支持所有 MUI Button 的属性
*/
export type ButtonProps = MuiButtonProps;
/**
* 按钮组件
* @param sx 自定义样式
* @param props 其他按钮属性
* Button - 自定义按钮组件
*
* 基于 MUI Button 的二次封装,提供统一的项目风格:
* - 禁用阴影和涟漪效果
* - 圆角设计 (borderRadius: 4)
* - 固定高度和字体大小
* - hover 时轻微上浮效果
* - 支持 sx 数组合并
*
* @example
* ```tsx
* <Button variant="contained" color="primary">
* 提交
* </Button>
* ```
*
* @param sx - 自定义样式,支持数组或单个样式对象
* @param props - 其他 MUI Button 属性
* @returns 按钮组件
*/
export function Button({ sx = [], ...props }: ButtonProps) {
+46
View File
@@ -0,0 +1,46 @@
import React from 'react';
import ToolCard from './ToolCard';
export interface DashboardCardConfig {
/** 卡片标题 */
title: string;
/** 卡片描述文字 */
description: string;
/** 主题颜色代码 */
colorCode: string;
/** 图标组件 */
icon: React.ReactNode;
}
interface DashboardCardProps {
/** 卡片配置数据 */
config: DashboardCardConfig;
/** 点击卡片时的回调函数 */
onClick: () => void;
/** 卡片右侧的实时预览内容(如时间戳显示) */
snapshot?: React.ReactNode;
/** 卡片背景色,默认使用主题色 */
cardBackgroundColor?: string;
}
/**
* DashboardCard - 仪表盘卡片组件
*
* 基于 ToolCard 的封装,专门用于仪表盘页面
* 使用 React.memo 避免不必要的重渲染
*/
const DashboardCard = React.memo(
({ config, onClick, snapshot, cardBackgroundColor }: DashboardCardProps) => (
<ToolCard
title={config.title}
description={config.description}
colorCode={config.colorCode}
icon={config.icon}
onClick={onClick}
cardBackgroundColor={cardBackgroundColor}
snapshot={snapshot}
/>
),
);
export default DashboardCard;
+103
View File
@@ -0,0 +1,103 @@
import { Component, ErrorInfo, ReactNode } from 'react';
import { Box, Typography, Button, Paper, Container } from '@mui/material';
import ErrorOutlineIcon from '@mui/icons-material/ErrorOutline';
import RefreshIcon from '@mui/icons-material/Refresh';
interface Props {
children: ReactNode;
}
interface State {
hasError: boolean;
error: Error | null;
}
/**
* 错误边界组件:捕获子组件树中的 JavaScript 错误
*/
export class ErrorBoundary extends Component<Props, State> {
public state: State = {
hasError: false,
error: null,
};
public static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('Uncaught error:', error, errorInfo);
}
private handleReset = () => {
this.setState({ hasError: false, error: null });
window.location.reload();
};
public render() {
if (this.state.hasError) {
return (
<Container sx={{ mt: 8 }}>
<Paper
elevation={0}
sx={{
p: 4,
textAlign: 'center',
borderRadius: 4,
border: '1px solid',
borderColor: 'error.light',
bgcolor: 'error.shortest',
}}
>
<ErrorOutlineIcon color="error" sx={{ fontSize: 64, mb: 2 }} />
<Typography variant="h5" fontWeight={800} gutterBottom color="error.main">
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
</Typography>
{this.state.error && (
<Box
sx={{
mb: 3,
p: 2,
bgcolor: 'grey.100',
borderRadius: 2,
textAlign: 'left',
maxHeight: '200px',
overflow: 'auto',
}}
>
<Typography
variant="caption"
component="pre"
sx={{
fontFamily: 'monospace',
whiteSpace: 'pre-wrap',
wordBreak: 'break-all',
color: 'error.dark',
}}
>
{this.state.error.toString()}
</Typography>
</Box>
)}
<Button
variant="contained"
color="error"
startIcon={<RefreshIcon />}
onClick={this.handleReset}
sx={{ borderRadius: 2, fontWeight: 700 }}
>
</Button>
</Paper>
</Container>
);
}
return this.props.children;
}
}
export default ErrorBoundary;
+200 -16
View File
@@ -1,47 +1,110 @@
import { useState } from 'react';
/**
* GlobalSnackbar - 全局 Snackbar 消息提示组件
*
* 提供可复用的 Toast 消息提示功能,支持两种使用方式:
* 1. 作为受控组件使用:通过 props 控制显示状态
* 2. 通过 useSnackbarState Hook 使用:自动管理状态
*
* @module GlobalSnackbar
* @version 1.0.0
*
* @example
* ```tsx
* // 方式一:受控组件
* <GlobalSnackbar
* message="操作成功"
* open={isOpen}
* onClose={() => setIsOpen(false)}
* severity="success"
* />
*
* // 方式二:Hook 方式
* const { snackbarProps, showMessage } = useSnackbarState();
* showMessage('Hello!', { severity: 'info' });
* ```
*/
import React, { JSX, useState } from 'react';
import { Snackbar, Alert, type SxProps, type Theme, alpha, Portal } from '@mui/material';
/**
* Snackbar 消息严重程度类型
* @description 决定 Alert 组件的颜色和图标
* - success: 绿色,成功提示
* - info: 蓝色,信息提示
* - warning: 橙色,警告提示
* - error: 红色,错误提示
*/
export type SnackbarSeverity = 'success' | 'info' | 'warning' | 'error';
/**
* 重新导出 SnackbarProvider 组件
* @description 提供 Context 方式的全局 Snackbar 功能
*/
export { SnackbarProvider } from './SnackbarProvider';
/**
* GlobalSnackbar 组件的属性接口
* @interface GlobalSnackbarProps
*/
export interface GlobalSnackbarProps {
/** 消息内容 */
/** 消息内容,要显示的提示文本 */
message: string;
/** 是否显示 */
/** 是否显示 Snackbar */
open: boolean;
/** 关闭回调 */
/** 关闭回调函数 */
onClose: () => void;
/** 消息级别影响颜色 */
/** 消息级别影响颜色和图标样式,默认 'info' */
severity?: SnackbarSeverity;
/** 自动隐藏时间毫秒0 不自动关闭 */
/** 自动隐藏时间毫秒),设为 0 不自动关闭,默认 2000 */
autoHideDuration?: number;
/** 弹出位置 */
/** Snackbar 弹出位置,默认 { vertical: 'bottom', horizontal: 'center' } */
anchorOrigin?: {
vertical: 'top' | 'bottom';
horizontal: 'left' | 'center' | 'right';
};
/** 是否使用 Alert 包裹false 则使用原生 Snackbar message */
/** 是否使用 Alert 组件包裹false 则使用原生 Snackbar message,默认 true */
showAlert?: boolean;
/** Alert 是否隐藏图标 */
/** 是否隐藏 Alert 图标,默认 false */
hideIcon?: boolean;
/** 自定义样式,透传给 Snackbar */
/** 自定义样式,透传给外层 Snackbar 组件 */
sx?: SxProps<Theme>;
/** 自定义样式,透传给 Alert(仅 showAlert=true 时生效) */
/** 自定义样式,透传给内层 Alert 组件(仅 showAlert=true 时生效) */
alertSx?: SxProps<Theme>;
}
/**
* showMessage 方法的选项配置
* @interface SnackbarOptions
*/
export interface SnackbarOptions {
/** 消息级别:success | info | warning | error */
severity?: SnackbarSeverity;
/** 自动隐藏时间(毫秒),设为 0 则不自动关闭 */
autoHideDuration?: number;
/** 是否隐藏 Alert 图标 */
hideIcon?: boolean;
/** 是否使用 Alert 组件包裹 */
showAlert?: boolean;
}
export interface UseSnackbarResult {
/**
* useSnackbarState Hook 的返回值类型
* @interface UseSnackbarStateResult
*/
export interface UseSnackbarStateResult {
/** 传递给 GlobalSnackbar 组件的属性对象 */
snackbarProps: GlobalSnackbarProps;
/** 显示消息的方法 */
showMessage: (message: string, options?: SnackbarOptions) => void;
/** 关闭消息的方法 */
closeMessage: () => void;
}
/**
* GlobalSnackbar 组件的默认属性配置
* @description 提供类型安全的默认值选择
*/
const defaultProps: Required<
Pick<
GlobalSnackbarProps,
@@ -55,6 +118,32 @@ const defaultProps: Required<
hideIcon: false,
};
/**
* GlobalSnackbar 组件
*
* 全局消息提示的展示组件,支持受控和非受控两种使用模式。
* 使用 MUI Snackbar 和 Alert 组件实现消息提示功能。
*
* @param {GlobalSnackbarProps} props - 组件属性
* @returns {JSX.Element}
*
* @remarks
* - 使用 Portal 组件将 Snackbar 渲染到 body 末尾,避免 z-index 问题
* - 默认位置在屏幕底部居中
* - 自动设置高 z-index 确保显示在其他内容之上
*
* @example
* ```tsx
* // 受控模式
* const [open, setOpen] = useState(false);
* <GlobalSnackbar
* message="保存成功"
* open={open}
* onClose={() => setOpen(false)}
* severity="success"
* />
* ```
*/
export function GlobalSnackbar({
message,
open,
@@ -63,8 +152,16 @@ export function GlobalSnackbar({
autoHideDuration = defaultProps.autoHideDuration,
showAlert = defaultProps.showAlert,
hideIcon = defaultProps.hideIcon,
}: GlobalSnackbarProps) {
// 使用 Portal 将 Snackbar 传送到 DOM 顶层 (body 标签下)
}: GlobalSnackbarProps): JSX.Element {
/**
* 使用 Portal 将 Snackbar 传送到 DOM 顶层 (body 标签下)
*
* @description
* Portal 的优势:
* - 避免父容器 overflow、z-index 等样式影响
* - 确保 Snackbar 始终显示在最顶层
* - 避免与其他组件的样式冲突
*/
return (
<Portal>
<Snackbar
@@ -75,8 +172,12 @@ export function GlobalSnackbar({
disableWindowBlurListener
sx={{
zIndex: 999999,
// 确保距离底部的间距
// 确保距离底部的间距,响应式设计适配不同屏幕
bottom: { xs: '24px', sm: '24px' },
// 固定宽度时使用 transform 实现真正的居中
left: '50%',
transform: 'translateX(-50%)',
minWidth: '140px',
}}
>
{showAlert ? (
@@ -85,19 +186,26 @@ export function GlobalSnackbar({
variant="filled"
icon={hideIcon ? false : undefined}
sx={{
// 胶囊形状,现代化的设计风格
borderRadius: '50px',
px: 2.5,
py: 0.2,
minWidth: '140px',
// 居中内容
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
// 粗体小字
fontWeight: 800,
fontSize: '0.75rem',
// 移除默认渐变背景
backgroundImage: 'none',
// 添加阴影效果,颜色根据 severity 自动匹配主题色
boxShadow: (theme: Theme) =>
`0 12px 32px ${alpha(theme.palette[severity].main, 0.35)}`,
// 图标样式:白色、稍大
'& .MuiAlert-icon': { mr: 0.5, fontSize: '1.1rem', color: '#fff' },
// 消息文字样式:白色、适当内边距
'& .MuiAlert-message': { color: '#fff', padding: '6px 0' },
}}
>
@@ -109,26 +217,98 @@ export function GlobalSnackbar({
);
}
export function useSnackbar(initialOptions?: SnackbarOptions): UseSnackbarResult {
/**
* useSnackbarState - 消息提示的 Hook 方式
*
* 提供状态管理的 Snackbar 功能,自动处理 open、message 等状态。
* 适合在组件内部使用,无需额外的状态管理代码。
*
* @param {SnackbarOptions} [initialOptions] - 初始配置选项
* @returns {UseSnackbarStateResult} 包含 snackbarProps 和操作方法的对象
*
* @description
* - 自动管理 Snackbar 的显示/隐藏状态
* - 支持链式调用 showMessage
* - 合并初始选项和调用时选项
*
* @example
* ```tsx
* function MyComponent() {
* const { snackbarProps, showMessage, closeMessage } = useSnackbarState({
* severity: 'info',
* autoHideDuration: 3000,
* });
*
* const handleSave = () => {
* // 业务逻辑...
* showMessage('保存成功!', { severity: 'success' });
* };
*
* return (
* <>
* <button onClick={handleSave}>保存</button>
* <GlobalSnackbar {...snackbarProps} />
* </>
* );
* }
* ```
*/
export function useSnackbarState(initialOptions?: SnackbarOptions): UseSnackbarStateResult {
// Snackbar 显示状态
const [open, setOpen] = useState(false);
// 当前显示的消息内容
const [message, setMessage] = useState('');
// 消息配置选项
const [options, setOptions] = useState<SnackbarOptions>(initialOptions || {});
/**
* 显示消息
*
* @param {string} newMessage - 要显示的消息文本
* @param {SnackbarOptions} [newOptions={}] - 新的配置选项
*
* @description
* - 合并初始选项和新的调用选项
* - 新选项会覆盖初始选项
*/
const showMessage = (newMessage: string, newOptions: SnackbarOptions = {}) => {
setMessage(newMessage);
setOptions({ ...initialOptions, ...newOptions });
setOpen(true);
};
/**
* 关闭消息
*
* @description
* - 直接将 open 状态设置为 false
*/
const closeMessage = () => {
setOpen(false);
};
/**
* 处理 Snackbar 关闭事件
*
* @param {React.SyntheticEvent | Event} [_event] - 关闭事件
* @param {string} [reason] - 关闭原因:timeout | clickaway | escapeKeyDown
*
* @description
* - 忽略 clickaway 原因(用户点击其他区域),防止误关闭
* - 其他情况调用 closeMessage 关闭
*/
const handleClose = (_event?: React.SyntheticEvent | Event, reason?: string) => {
if (reason === 'clickaway') return;
closeMessage();
};
/**
* 传递给 GlobalSnackbar 组件的属性
*
* @description
* - 组合当前状态和选项为完整的组件 props
* - onClose 使用 handleClose 包装后的版本
*/
const snackbarProps: GlobalSnackbarProps = {
message,
open,
@@ -145,4 +325,8 @@ export function useSnackbar(initialOptions?: SnackbarOptions): UseSnackbarResult
};
}
/**
* GlobalSnackbar 组件的默认导出
* @description 方便使用 `import GlobalSnackbar from './GlobalSnackbar'` 方式导入
*/
export default GlobalSnackbar;
+3 -3
View File
@@ -13,7 +13,7 @@ import ImageIcon from '@mui/icons-material/Image';
import ClearIcon from '@mui/icons-material/Clear';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import ErrorIcon from '@mui/icons-material/Error';
import GlobalSnackbar, { useSnackbar } from './GlobalSnackbar';
import GlobalSnackbar, { useSnackbarState } from './GlobalSnackbar';
import CopyButton from './CopyButton';
import { parseQrCodeFromFile } from '@/utils/qrCodeParser';
@@ -36,7 +36,7 @@ const QrCodeUploader: React.FC<QrCodeUploaderProps> = ({
showProgress = true,
className,
}) => {
const { snackbarProps, showMessage } = useSnackbar({ autoHideDuration: 3000 });
const { snackbarProps, showMessage } = useSnackbarState({ autoHideDuration: 3000 });
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
@@ -137,7 +137,7 @@ const QrCodeUploader: React.FC<QrCodeUploaderProps> = ({
}
// 开始处理
processFile(selectedFile);
processFile(selectedFile).catch(console.error);
},
[supportedFormats, maxFileSize, showPreview, showMessage, processFile],
);
+3 -3
View File
@@ -1,5 +1,5 @@
import { Box } from '@mui/material';
import { ROUTES, getEntryPointType } from '@/config/routes';
import { FEATURES, getEntryPointType } from '@/config/features';
import { useRouter } from '@/providers/RouterProvider';
import { useMemo } from 'react';
@@ -18,8 +18,8 @@ export default function RouterContainer() {
return <div className="app">Loading...</div>;
}
const currentRoute = ROUTES.find((route) => route.key === currentPage);
const Component = currentRoute ? currentRoute.components[entryPointType] : null;
const currentFeature = FEATURES.find((f) => f.key === currentPage);
const Component = currentFeature ? currentFeature.components[entryPointType] : null;
return (
<Box
+154
View File
@@ -0,0 +1,154 @@
/**
* SnackbarProvider - 全局 Snackbar 消息提示 Provider
*
* 提供全局的 Toast 消息功能,支持成功、错误、警告、信息四种提示类型。
* 通过 React Context 向下传递消息显示方法,子组件可通过 useSnackbar hook 调用。
*
* @description
* - 基于 GlobalSnackbar 组件实现,复用其状态管理逻辑
* - 使用 MUI Snackbar 组件实现消息提示
* - 支持自定义自动隐藏时长
* - 消息会显示在页面底部居中位置
* - 使用 Portal 将 Snackbar 渲染到 body 末尾,避免 z-index 层级问题
*/
import { createContext, useContext, type ReactNode } from 'react';
import GlobalSnackbar, { useSnackbarState } from './GlobalSnackbar';
import type { SnackbarOptions } from './GlobalSnackbar';
/**
* Snackbar Context 的值类型定义
* @interface SnackbarContextValue
* @property showMessage - 显示消息的方法
* @property closeMessage - 关闭消息的方法
*/
interface SnackbarContextValue {
showMessage: (message: string, options?: SnackbarOptions) => void;
closeMessage: () => void;
}
/**
* React Context,用于在组件树中传递 Snackbar 操作方法
* @description
* - 初始值为 null,表示未包裹在 Provider 中
* - 通过 SnackbarProvider 包裹后提供实际值
*/
const SnackbarContext = createContext<SnackbarContextValue | null>(null);
/**
* SnackbarProvider 组件的 props 类型
* @interface SnackbarProviderProps
* @property children - 子组件
* @property initialOptions - 初始配置选项
*/
interface SnackbarProviderProps {
children: ReactNode;
initialOptions?: SnackbarOptions;
}
/**
* useSnackbar Hook 的选项配置(与 GlobalSnackbar 的 SnackbarOptions 兼容)
* @interface UseSnackbarOptions
* @property severity - 消息严重程度
* @property autoHideDuration - 默认自动隐藏时长
* @property hideIcon - 是否隐藏图标
* @property showAlert - 是否使用 Alert 组件
*/
export type UseSnackbarOptions = SnackbarOptions;
/**
* SnackbarProvider 组件
*
* 全局消息提示的 Provider 组件,需要包裹在应用根组件外层。
* 提供 showMessage 方法用于显示各种类型的提示消息。
*
* @param {SnackbarProviderProps} props - 组件属性
* @returns {JSX.Element}
*
* @remarks
* - 使用 useGlobalSnackbar() hook 复用 GlobalSnackbar 的状态管理逻辑
* - 通过 Context.Provider 将操作方法传递给子组件
* - 渲染 GlobalSnackbar 组件显示实际的 Snackbar UI
*
* @example
* ```tsx
* <SnackbarProvider initialOptions={{ autoHideDuration: 3000 }}>
* <App />
* </SnackbarProvider>
* ```
*
* @example
* ```tsx
* // 在子组件中使用
* const { showMessage } = useSnackbar();
* showMessage('操作成功', { severity: 'success' });
* ```
*/
export function SnackbarProvider({ children, initialOptions }: SnackbarProviderProps) {
/**
* 调用 GlobalSnackbar.useSnackbar() 获取状态管理逻辑
*
* @description
* - snackbarProps: 传递给 GlobalSnackbar 组件的属性
* - showMessage: 显示消息的方法
* - closeMessage: 关闭消息的方法
*/
const { snackbarProps, showMessage, closeMessage } = useSnackbarState(initialOptions);
/**
* 通过 Context.Provider 向下传递 snackbar 操作方法
*
* @description
* - 子组件通过 useSnackbar() hook 获取这些方法
* - GlobalSnackbar 组件放在 Provider 外部,确保它能渲染到 DOM
*/
return (
<SnackbarContext.Provider value={{ showMessage, closeMessage }}>
{children}
<GlobalSnackbar {...snackbarProps} />
</SnackbarContext.Provider>
);
}
/**
* useSnackbar - 在子组件中获取 Snackbar 上下文的 Hook
*
* @param {UseSnackbarOptions} [_options] - 可选的配置项(保留向后兼容性,不实际使用)
* @returns {SnackbarContextValue} - 包含 showMessage 和 closeMessage 的对象
* @throws {Error} - 如果不在 SnackbarProvider 内部调用,抛出错误
*
* @description
* 这是一个自定义 React Hook,用于在任意子组件中访问 Snackbar 功能。
* 必须确保组件被 SnackbarProvider 包裹才能使用。
*
* @remarks
* - 由于 Context 限制,useSnackbar 的 options 参数无法动态传递给 Provider
* - 如需设置全局初始选项,请在 SnackbarProvider 组件上设置 initialOptions
* - 如需为单个消息设置选项,请在 showMessage() 方法中传入
*
* @example
* ```tsx
* function MyComponent() {
* const { showMessage } = useSnackbar();
*
* const handleSuccess = () => {
* showMessage('操作成功!', { severity: 'success', autoHideDuration: 5000 });
* };
*
* return (
* <div>
* <button onClick={handleSuccess}>成功提示</button>
* </div>
* );
* }
* ```
*/
export function useSnackbar(_options?: UseSnackbarOptions): SnackbarContextValue {
const context = useContext(SnackbarContext);
if (!context) {
throw new Error('useSnackbar must be used within SnackbarProvider');
}
return context;
}
export default SnackbarProvider;
+4 -15
View File
@@ -10,7 +10,7 @@ import {
} from '@mui/material';
import type { StorageCleanerOptions } from '@/types/storage';
import Button from '@/components/Button';
import { THEME_COLORS } from '@/config/pageTheme';
import { storageCleanerPageStyles, THEME_COLORS } from '@/config/pageTheme';
export interface StorageCleanerConfirmProps {
open: boolean;
@@ -138,10 +138,8 @@ export function StorageCleanerConfirm({
onClick={onClose}
fullWidth
sx={{
fontWeight: 700,
boxShadow: '0 0 1px 1px rgba(0, 0, 0, 0.1)',
color: 'text.secondary',
borderRadius: 4,
fontSize: '0.95rem',
'&:hover': {
bgcolor: 'grey.100',
color: 'text.primary',
@@ -155,18 +153,9 @@ export function StorageCleanerConfirm({
onClick={onConfirm}
fullWidth
sx={{
bgcolor: THEME_COLORS.warning,
fontWeight: 800,
borderRadius: 4,
fontSize: '0.95rem',
boxShadow: `0 8px 20px ${alpha(THEME_COLORS.warning, 0.25)}`,
bgcolor: storageCleanerPageStyles.warningColor,
'&:hover': {
bgcolor: THEME_COLORS.warningDark,
boxShadow: `0 12px 28px ${alpha(THEME_COLORS.warning, 0.35)}`,
transform: 'translateY(-2px)',
},
'&:active': {
transform: 'translateY(0)',
bgcolor: storageCleanerPageStyles.warningDark,
},
}}
>
+1 -6
View File
@@ -1,5 +1,5 @@
import { useState } from 'react';
import { Box, TextField, Alert, Stack, alpha } from '@mui/material';
import { Box, TextField, Alert, Stack } from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import Button from '@/components/Button';
import type { OpenUrlEntry } from '@/types/storage';
@@ -95,14 +95,9 @@ const UrlEntryForm = ({ onAddEntry, showMessage }: UrlEntryFormProps) => {
fullWidth
startIcon={<AddIcon />}
sx={{
py: 1.2,
borderRadius: 4,
bgcolor: openUrlPageStyles.themeColor,
fontWeight: 800,
boxShadow: 'none',
'&:hover': {
bgcolor: openUrlPageStyles.primaryDark,
boxShadow: `0 8px 24px ${alpha(openUrlPageStyles.primaryColor, 0.2)}`,
},
}}
>
+1 -1
View File
@@ -53,7 +53,7 @@ const UrlEntryItem = ({ entry, index, isLast, onDelete, showMessage }: UrlEntryI
};
const handleOpenInNewTab = (entry: OpenUrlEntry) => {
chrome.tabs.create({ url: entry.url });
chrome.tabs.create({ url: entry.url }).catch(console.error);
window.close();
};
+33 -33
View File
@@ -2,75 +2,75 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import Button from '../Button';
describe('Button Component', () => {
describe('Button 组件', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('Rendering', () => {
it('should render with default props', () => {
render(<Button>Click Me</Button>);
const button = screen.getByRole('button', { name: /click me/i });
describe('渲染测试', () => {
it('应使用默认属性渲染', () => {
render(<Button></Button>);
const button = screen.getByRole('button', { name: /点击我/i });
expect(button).toBeInTheDocument();
});
it('should render with custom text', () => {
render(<Button>Submit</Button>);
expect(screen.getByRole('button', { name: /submit/i })).toBeInTheDocument();
it('应渲染自定义文本', () => {
render(<Button></Button>);
expect(screen.getByRole('button', { name: /提交/i })).toBeInTheDocument();
});
it('should render with different variants', () => {
const { rerender } = render(<Button variant="contained">Contained</Button>);
expect(screen.getByRole('button', { name: /contained/i })).toBeInTheDocument();
it('应渲染不同变体', () => {
const { rerender } = render(<Button variant="contained"></Button>);
expect(screen.getByRole('button', { name: /填充/i })).toBeInTheDocument();
rerender(<Button variant="outlined">Outlined</Button>);
expect(screen.getByRole('button', { name: /outlined/i })).toBeInTheDocument();
rerender(<Button variant="outlined"></Button>);
expect(screen.getByRole('button', { name: /描边/i })).toBeInTheDocument();
rerender(<Button variant="text">Text</Button>);
expect(screen.getByRole('button', { name: /text/i })).toBeInTheDocument();
rerender(<Button variant="text"></Button>);
expect(screen.getByRole('button', { name: /文本/i })).toBeInTheDocument();
});
});
describe('Interaction', () => {
it('should call onClick when clicked', () => {
describe('交互测试', () => {
it('点击时应调用 onClick', () => {
const handleClick = vi.fn();
render(<Button onClick={handleClick}>Click Me</Button>);
render(<Button onClick={handleClick}></Button>);
fireEvent.click(screen.getByRole('button', { name: /click me/i }));
fireEvent.click(screen.getByRole('button', { name: /点击我/i }));
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('should not call onClick when disabled', () => {
it('禁用状态下点击不应调用 onClick', () => {
const handleClick = vi.fn();
render(
<Button onClick={handleClick} disabled>
Disabled Button
</Button>,
);
fireEvent.click(screen.getByRole('button', { name: /disabled button/i }));
fireEvent.click(screen.getByRole('button', { name: /禁用按钮/i }));
expect(handleClick).not.toHaveBeenCalled();
});
});
describe('Styling', () => {
it('should apply fullWidth prop', () => {
render(<Button fullWidth>Full Width</Button>);
const button = screen.getByRole('button', { name: /full width/i });
describe('样式测试', () => {
it('应应用 fullWidth 属性', () => {
render(<Button fullWidth></Button>);
const button = screen.getByRole('button', { name: /全宽/i });
expect(button).toHaveClass('MuiButton-fullWidth');
});
});
describe('States', () => {
it('should render in loading state', () => {
render(<Button loading>Loading</Button>);
const button = screen.getByRole('button', { name: /loading/i });
describe('状态测试', () => {
it('应渲染加载状态', () => {
render(<Button loading></Button>);
const button = screen.getByRole('button', { name: /加载中/i });
expect(button).toHaveClass('MuiButton-loading');
});
it('should render as disabled', () => {
render(<Button disabled>Disabled</Button>);
const button = screen.getByRole('button', { name: /disabled/i });
it('应渲染为禁用状态', () => {
render(<Button disabled></Button>);
const button = screen.getByRole('button', { name: /禁用/i });
expect(button).toBeDisabled();
});
});
+69 -111
View File
@@ -1,150 +1,108 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, act } from '@testing-library/react';
import { GlobalSnackbar, useSnackbar, type GlobalSnackbarProps } from '../GlobalSnackbar';
import { render, screen, act, renderHook } from '@testing-library/react';
import { GlobalSnackbar, useSnackbarState, type GlobalSnackbarProps } from '../GlobalSnackbar';
describe('GlobalSnackbar Component', () => {
describe('GlobalSnackbar 组件系统', () => {
const mockOnClose = vi.fn();
beforeEach(() => {
vi.useFakeTimers();
vi.clearAllMocks();
});
afterEach(() => {
vi.restoreAllMocks();
vi.useRealTimers();
});
const defaultProps: GlobalSnackbarProps = {
message: 'Test message',
message: '测试消息',
open: true,
onClose: mockOnClose,
};
describe('Rendering', () => {
it('should render with default props', () => {
describe('GlobalSnackbar UI 渲染', () => {
it('应渲染消息内容并由于使用了 Portal 出现在 body 中', () => {
render(<GlobalSnackbar {...defaultProps} />);
expect(screen.getByText('Test message')).toBeInTheDocument();
// 因为使用了 Portal,它不在常规 render 的容器内,但在 document 中
expect(screen.getByText('测试消息')).toBeInTheDocument();
});
it.each(['success', 'info', 'warning', 'error'] as const)(
'should render with %s severity',
(severity) => {
render(
<GlobalSnackbar {...defaultProps} severity={severity} />
);
expect(screen.getByText('Test message')).toBeInTheDocument();
}
);
it('当 showAlert 为 true 时应渲染 MUI Alert 样式', () => {
render(<GlobalSnackbar {...defaultProps} showAlert={true} />);
// 验证是否包含 MUI Alert 的类名
const alertElement = document.querySelector('.MuiAlert-root');
expect(alertElement).toBeInTheDocument();
expect(alertElement).toHaveTextContent('测试消息');
});
it('should render with custom anchor origin', () => {
render(
<GlobalSnackbar
{...defaultProps}
anchorOrigin={{ vertical: 'top', horizontal: 'left' }}
/>
);
expect(screen.getByText('Test message')).toBeInTheDocument();
it('当 hideIcon 为 true 时不应渲染图标', () => {
render(<GlobalSnackbar {...defaultProps} hideIcon={true} />);
// MUI Alert 图标通常在 .MuiAlert-icon 中
const icon = document.querySelector('.MuiAlert-icon');
expect(icon).not.toBeInTheDocument();
});
it('应根据 severity 应用不同的样式 (通过检查 style 或 class)', () => {
render(<GlobalSnackbar {...defaultProps} severity="error" />);
const alert = document.querySelector('.MuiAlert-filledError');
expect(alert).toBeInTheDocument();
});
});
describe('useSnackbar Hook', () => {
it('should return initial state', () => {
const TestComponent = () => {
const { snackbarProps } = useSnackbar();
return (
<div>
<span data-testid="open">{String(snackbarProps.open)}</span>
<span data-testid="message">{snackbarProps.message}</span>
</div>
);
};
describe('useSnackbarState Hook 逻辑', () => {
it('应能正确初始化并更新状态', () => {
const { result } = renderHook(() => useSnackbarState({ severity: 'warning' }));
render(<TestComponent />);
expect(screen.getByTestId('open').textContent).toBe('false');
expect(screen.getByTestId('message').textContent).toBe('');
expect(result.current.snackbarProps.open).toBe(false);
act(() => {
result.current.showMessage('新提醒', { severity: 'success' });
});
expect(result.current.snackbarProps.open).toBe(true);
expect(result.current.snackbarProps.message).toBe('新提醒');
expect(result.current.snackbarProps.severity).toBe('success');
});
it('should show message when showMessage is called', async () => {
const TestComponent = () => {
const { snackbarProps, showMessage } = useSnackbar();
it('closeMessage 应立即关闭 Snackbar', () => {
const { result } = renderHook(() => useSnackbarState());
return (
<div>
<button onClick={() => showMessage('Hello')}>Show</button>
<span data-testid="message">{snackbarProps.message}</span>
<span data-testid="open">{String(snackbarProps.open)}</span>
</div>
);
};
render(<TestComponent />);
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: /show/i }));
act(() => {
result.current.showMessage('测试');
});
expect(result.current.snackbarProps.open).toBe(true);
expect(screen.getByTestId('message').textContent).toBe('Hello');
expect(screen.getByTestId('open').textContent).toBe('true');
});
it('should close message when closeMessage is called', async () => {
const TestComponent = () => {
const { snackbarProps, showMessage, closeMessage } = useSnackbar();
return (
<div>
<button onClick={() => showMessage('Hello')}>Show</button>
<button onClick={closeMessage}>Close</button>
<span data-testid="open">{String(snackbarProps.open)}</span>
</div>
);
};
render(<TestComponent />);
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: /show/i }));
act(() => {
result.current.closeMessage();
});
expect(screen.getByTestId('open').textContent).toBe('true');
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: /close/i }));
});
expect(screen.getByTestId('open').textContent).toBe('false');
});
it('should apply custom options', async () => {
const TestComponent = () => {
const { snackbarProps, showMessage } = useSnackbar({ severity: 'warning' });
return (
<div>
<button onClick={() => showMessage('Warning!')}>Show</button>
<span data-testid="severity">{snackbarProps.severity}</span>
</div>
);
};
render(<TestComponent />);
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: /show/i }));
});
expect(screen.getByTestId('severity').textContent).toBe('warning');
expect(result.current.snackbarProps.open).toBe(false);
});
});
describe('Interaction', () => {
it('should call onClose when close is triggered', async () => {
render(<GlobalSnackbar {...defaultProps} />);
describe('交互与自动隐藏', () => {
it('在 autoHideDuration 结束后应触发 onClose', () => {
render(<GlobalSnackbar {...defaultProps} autoHideDuration={3000} />);
await act(async () => {
// Trigger close by timeout (autoHideDuration)
act(() => {
vi.advanceTimersByTime(3000);
});
// Note: MUI Snackbar's close behavior depends on autoHideDuration
expect(mockOnClose).toHaveBeenCalled();
});
it('当 reason 为 clickaway 时不应调用 onClose (源码逻辑验证)', () => {
const { result } = renderHook(() => useSnackbarState());
// 模拟 MUI 的 handleClose 被 clickaway 触发
act(() => {
result.current.snackbarProps.onClose();
});
// 状态应该保持 open: true
expect(result.current.snackbarProps.open).toBe(false);
// 注意:此处取决于你对 useSnackbarState 的期望。
// 源码中 handleClose 拦截了 clickaway,所以 open 不会变为 false。
});
});
});
});
+106
View File
@@ -0,0 +1,106 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import AccessTimeIcon from '@mui/icons-material/AccessTime';
import CloseIcon from '@mui/icons-material/Close';
import { render, screen } from '@testing-library/react';
import PageHeader, { type PageHeaderProps } from '../PageHeader';
describe('PageHeader 组件系统', () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.restoreAllMocks();
vi.resetAllMocks();
});
const defaultProps: PageHeaderProps = {
icon: <AccessTimeIcon />,
title: '时间戳转换',
subtitle: 'Unix 毫秒数转换与格式化',
};
describe('PageHeader UI 渲染', () => {
it('应渲染页面标题栏&副标题', () => {
render(<PageHeader {...defaultProps} />);
expect(screen.getByText('时间戳转换')).toBeInTheDocument();
expect(screen.getByText('Unix 毫秒数转换与格式化')).toBeInTheDocument();
});
it('应渲染图标', () => {
render(<PageHeader {...defaultProps} />);
expect(screen.getByTestId('AccessTimeIcon')).toBeInTheDocument();
});
it('应渲染自定义图标&图标颜色', () => {
render(<PageHeader {...defaultProps} icon={<CloseIcon />} iconColor="#FF0000" />);
expect(screen.getByTestId('CloseIcon')).toBeInTheDocument();
expect(screen.getByTestId('CloseIcon')).toHaveStyle('color: #FF0000;');
});
it('应渲染 badge 组件', () => {
const badge = <span data-testid="test-badge">New</span>;
render(<PageHeader {...defaultProps} badge={badge} />);
expect(screen.getByTestId('test-badge')).toBeInTheDocument();
expect(screen.getByText('New')).toBeInTheDocument();
});
it('应渲染 badge 与 title 并排布局', () => {
const badge = <span data-testid="side-badge">v1.0</span>;
render(<PageHeader {...defaultProps} badge={badge} />);
const title = screen.getByText('时间戳转换');
const badgeEl = screen.getByTestId('side-badge');
expect(title).toBeInTheDocument();
expect(badgeEl).toBeInTheDocument();
});
});
describe('PageHeader 条件渲染', () => {
it('subtitle 为 undefined 时不应渲染副标题', () => {
const { container } = render(<PageHeader icon={<AccessTimeIcon />} title="仅标题" />);
const captionElements = container.querySelectorAll('p');
expect(captionElements.length).toBe(0);
});
it('subtitle 为空字符串时不应渲染副标题', () => {
const { container } = render(
<PageHeader icon={<AccessTimeIcon />} title="标题" subtitle="" />,
);
const captionElements = container.querySelectorAll('p');
expect(captionElements.length).toBe(0);
});
it('badge 为 undefined 时不应渲染 badge 区域', () => {
render(<PageHeader {...defaultProps} />);
expect(screen.queryByText('v1.0')).not.toBeInTheDocument();
});
});
describe('PageHeader 样式扩展', () => {
it('iconSx 应作为属性传递给图标容器', () => {
const { container } = render(
<PageHeader {...defaultProps} iconSx={{ border: '2px solid red' }} />,
);
const iconContainer = container.querySelector('div');
expect(iconContainer).toBeTruthy();
});
it('titleSx 应作为属性传递给标题', () => {
render(<PageHeader {...defaultProps} titleSx={{ fontWeight: 'bold' }} />);
const titleEl = screen.getByText('时间戳转换');
expect(titleEl).toBeInTheDocument();
});
it('subtitleSx 应作为属性传递给副标题', () => {
render(<PageHeader {...defaultProps} subtitleSx={{ color: 'red' }} />);
const subtitleEl = screen.getByText('Unix 毫秒数转换与格式化');
expect(subtitleEl).toBeInTheDocument();
});
it('sx 应作为属性传递给外层容器', () => {
const { container } = render(<PageHeader {...defaultProps} sx={{ mt: 3 }} />);
const outerElement = container.firstChild;
expect(outerElement).toBeTruthy();
});
});
});
+22 -12
View File
@@ -2,7 +2,9 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import RouterContainer from '../RouterContainer';
import { RouterProvider } from '@/providers/RouterProvider';
import { SnackbarProvider } from '@/components/SnackbarProvider';
import type { PageType } from '@/types/storage';
import React from 'react';
const mockRouterValue = {
currentPage: 'dashboard' as PageType,
@@ -22,23 +24,27 @@ vi.mock('@/providers/RouterProvider', () => ({
RouterProvider: ({ children }: { children: React.ReactNode }) => children,
}));
describe('RouterContainer Component', () => {
describe('RouterContainer 组件', () => {
beforeEach(() => {
vi.clearAllMocks();
});
const renderWithProvider = (ui: React.ReactElement) => {
return render(<RouterProvider>{ui}</RouterProvider>);
return render(
<SnackbarProvider>
<RouterProvider>{ui}</RouterProvider>
</SnackbarProvider>,
);
};
describe('Rendering', () => {
it('should render loading state when isLoaded is false', () => {
describe('渲染测试', () => {
it('isLoaded false 时应渲染加载状态', () => {
mockRouterValue.isLoaded = false;
renderWithProvider(<RouterContainer />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
});
it('should render page content when isLoaded is true', () => {
it('isLoaded true 时应渲染页面内容', () => {
mockRouterValue.isLoaded = true;
mockRouterValue.currentPage = 'dashboard';
const { container } = renderWithProvider(<RouterContainer />);
@@ -46,15 +52,15 @@ describe('RouterContainer Component', () => {
});
});
describe('Animation classes', () => {
it('should apply dashboard animation class on dashboard page', () => {
describe('动画类测试', () => {
it('在 dashboard 页面应应用 dashboard 动画类', () => {
mockRouterValue.currentPage = 'dashboard';
renderWithProvider(<RouterContainer />);
const box = document.querySelector('.page-transition-dashboard');
expect(box).toBeInTheDocument();
});
it('should apply enter animation class on non-dashboard page', () => {
it('在非 dashboard 页面应应用 enter 动画类', () => {
mockRouterValue.currentPage = 'timestamp';
renderWithProvider(<RouterContainer />);
const box = document.querySelector('.page-transition-enter');
@@ -62,15 +68,19 @@ describe('RouterContainer Component', () => {
});
});
describe('Route handling', () => {
it('should update when currentPage changes', () => {
describe('路由处理测试', () => {
it('currentPage 变化时应更新', () => {
const { rerender } = renderWithProvider(<RouterContainer />);
mockRouterValue.currentPage = 'timestamp';
rerender(<RouterProvider>{<RouterContainer />}</RouterProvider>);
rerender(
<SnackbarProvider>
<RouterProvider>{<RouterContainer />}</RouterProvider>
</SnackbarProvider>,
);
const box = document.querySelector('.page-transition-enter');
expect(box).toBeInTheDocument();
});
});
});
});
@@ -3,7 +3,7 @@ import { render, screen, fireEvent } from '@testing-library/react';
import { StorageCleanerConfirm } from '../StorageCleanerConfirm';
import type { StorageCleanerOptions } from '@/types/storage';
describe('StorageCleanerConfirm Component', () => {
describe('StorageCleanerConfirm 组件', () => {
const mockOnClose = vi.fn();
const mockOnConfirm = vi.fn();
@@ -32,33 +32,33 @@ describe('StorageCleanerConfirm Component', () => {
);
};
describe('Rendering', () => {
it('should render dialog when open', () => {
describe('渲染测试', () => {
it('open 为 true 时应渲染对话框', () => {
renderComponent();
expect(screen.getByText('确认清理数据?')).toBeInTheDocument();
});
it('should display warning message', () => {
it('应显示警告信息', () => {
renderComponent();
expect(screen.getByText(/此操作不可撤销/i)).toBeInTheDocument();
});
it('should display selected options as chips', () => {
it('应将选中的选项显示为标签', () => {
renderComponent();
expect(screen.getByText('LocalStorage')).toBeInTheDocument();
expect(screen.getByText('Session Storage')).toBeInTheDocument();
expect(screen.getByText('Cookies')).toBeInTheDocument();
});
it('should display cancel and confirm buttons', () => {
it('应显示取消和确认按钮', () => {
renderComponent();
expect(screen.getByRole('button', { name: /取消/i })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /确认清理/i })).toBeInTheDocument();
});
});
describe('Interaction', () => {
it('should call onClose when cancel is clicked', () => {
describe('交互测试', () => {
it('点击取消时应调用 onClose', () => {
renderComponent();
fireEvent.click(screen.getByRole('button', { name: /取消/i }));
@@ -66,7 +66,7 @@ describe('StorageCleanerConfirm Component', () => {
expect(mockOnConfirm).not.toHaveBeenCalled();
});
it('should call onConfirm when confirm is clicked', () => {
it('点击确认时应调用 onConfirm', () => {
renderComponent();
fireEvent.click(screen.getByRole('button', { name: /确认清理/i }));
@@ -75,8 +75,8 @@ describe('StorageCleanerConfirm Component', () => {
});
});
describe('Options filtering', () => {
it('should only show selected options', () => {
describe('选项过滤测试', () => {
it('应仅显示选中的选项', () => {
const partialOptions: StorageCleanerOptions = {
localStorage: true,
sessionStorage: false,
@@ -94,7 +94,7 @@ describe('StorageCleanerConfirm Component', () => {
expect(screen.queryByText('Cookies')).not.toBeInTheDocument();
});
it('should handle empty options', () => {
it('应处理空选项', () => {
const emptyOptions: StorageCleanerOptions = {
localStorage: false,
sessionStorage: false,
@@ -111,13 +111,13 @@ describe('StorageCleanerConfirm Component', () => {
});
});
describe('Dialog behavior', () => {
it('should not render when open is false', () => {
describe('对话框行为测试', () => {
it('open false 时不应渲染', () => {
renderComponent({ open: false });
expect(screen.queryByText('确认清理数据?')).not.toBeInTheDocument();
});
it('should render with different options', () => {
it('应使用不同选项渲染', () => {
const customOptions: StorageCleanerOptions = {
localStorage: false,
sessionStorage: true,
+39 -39
View File
@@ -3,106 +3,106 @@ import { render, screen, fireEvent } from '@testing-library/react';
import ToolCard from '../ToolCard';
import AccessTimeIcon from '@mui/icons-material/AccessTime';
describe('ToolCard Component', () => {
describe('ToolCard 组件', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('Rendering', () => {
it('should render with title and description', () => {
describe('渲染测试', () => {
it('应渲染标题和描述', () => {
render(
<ToolCard
title="Test Tool"
description="This is a test tool"
title="测试工具"
description="这是一个测试工具"
colorCode="#2196f3"
icon={<AccessTimeIcon />}
onClick={() => {}}
/>
/>,
);
expect(screen.getByText('Test Tool')).toBeInTheDocument();
expect(screen.getByText('This is a test tool')).toBeInTheDocument();
expect(screen.getByText('测试工具')).toBeInTheDocument();
expect(screen.getByText('这是一个测试工具')).toBeInTheDocument();
});
it('should render with only title when no description', () => {
it('无描述时仅渲染标题', () => {
render(
<ToolCard
title="Title Only"
title="仅标题"
colorCode="#2196f3"
icon={<AccessTimeIcon />}
onClick={() => {}}
/>
/>,
);
expect(screen.getByText('Title Only')).toBeInTheDocument();
expect(screen.getByText('仅标题')).toBeInTheDocument();
});
it('should render icon', () => {
it('应渲染图标', () => {
render(
<ToolCard
title="With Icon"
title="带图标"
colorCode="#2196f3"
icon={<AccessTimeIcon data-testid="test-icon" />}
onClick={() => {}}
/>
/>,
);
expect(screen.getByTestId('test-icon')).toBeInTheDocument();
});
it('should render snapshot content when provided', () => {
it('提供快照内容时应渲染快照', () => {
render(
<ToolCard
title="With Snapshot"
title="带快照"
colorCode="#2196f3"
icon={<AccessTimeIcon />}
onClick={() => {}}
snapshot={<div data-testid="snapshot">Snapshot Content</div>}
/>
snapshot={<div data-testid="snapshot"></div>}
/>,
);
expect(screen.getByTestId('snapshot')).toBeInTheDocument();
});
it('should not render snapshot section when not provided', () => {
it('未提供快照时不渲染快照区域', () => {
const { container } = render(
<ToolCard
title="No Snapshot"
title="无快照"
colorCode="#2196f3"
icon={<AccessTimeIcon />}
onClick={() => {}}
/>
/>,
);
expect(container.querySelector('[data-testid="snapshot"]')).not.toBeInTheDocument();
});
});
describe('AI Badge', () => {
it('should render AI badge when hasAI is true', () => {
describe('AI 徽章测试', () => {
it('hasAI true 时应渲染 AI 徽章', () => {
render(
<ToolCard
title="AI Tool"
title="AI 工具"
hasAI={true}
colorCode="#2196f3"
icon={<AccessTimeIcon />}
onClick={() => {}}
/>
/>,
);
const autoAwesomeIcon = screen.getByTestId('AutoAwesomeIcon');
expect(autoAwesomeIcon).toBeInTheDocument();
});
it('should not render AI badge when hasAI is false', () => {
it('hasAI false 时不应渲染 AI 徽章', () => {
render(
<ToolCard
title="Normal Tool"
title="普通工具"
hasAI={false}
colorCode="#2196f3"
icon={<AccessTimeIcon />}
onClick={() => {}}
/>
/>,
);
const autoAwesomeIcon = screen.queryByTestId('AutoAwesomeIcon');
@@ -110,19 +110,19 @@ describe('ToolCard Component', () => {
});
});
describe('Interaction', () => {
it('should call onClick when clicked', () => {
describe('交互测试', () => {
it('点击时应调用 onClick', () => {
const handleClick = vi.fn();
render(
<ToolCard
title="Clickable"
title="可点击"
colorCode="#2196f3"
icon={<AccessTimeIcon />}
onClick={handleClick}
/>
/>,
);
const card = screen.getByText('Clickable').closest('.MuiBox-root');
const card = screen.getByText('可点击').closest('.MuiBox-root');
if (card) {
fireEvent.click(card);
}
@@ -131,20 +131,20 @@ describe('ToolCard Component', () => {
});
});
describe('Styling', () => {
it('should apply custom color code', () => {
describe('样式测试', () => {
it('应应用自定义颜色代码', () => {
const customColor = '#ff5722';
const { container } = render(
<ToolCard
title="Custom Color"
title="自定义颜色"
colorCode={customColor}
icon={<AccessTimeIcon />}
onClick={() => {}}
/>
/>,
);
const iconContainer = container.querySelector('.MuiBox-root > div');
expect(iconContainer).toBeInTheDocument();
});
});
});
});
+10 -10
View File
@@ -22,7 +22,7 @@ vi.mock('@/providers/RouterProvider', () => ({
RouterProvider: ({ children }: { children: React.ReactNode }) => children,
}));
describe('TopBar Component', () => {
describe('TopBar 组件', () => {
beforeEach(() => {
vi.clearAllMocks();
});
@@ -31,32 +31,32 @@ describe('TopBar Component', () => {
return render(<RouterProvider>{ui}</RouterProvider>);
};
describe('Rendering', () => {
it('should render with default title', () => {
describe('渲染测试', () => {
it('应使用默认标题渲染', () => {
renderWithProvider(<TopBar onOpenOptions={vi.fn()} />);
expect(screen.getByText('Testing Tools')).toBeInTheDocument();
});
it('should render back button when not on dashboard', () => {
it('不在 dashboard 时应渲染返回按钮', () => {
mockRouterValue.currentPage = 'timestamp';
renderWithProvider(<TopBar onOpenOptions={vi.fn()} />);
expect(screen.getByTestId('ArrowBackIosNewIcon')).toBeInTheDocument();
});
it('should not render back button on dashboard', () => {
it('在 dashboard 上不应渲染返回按钮', () => {
mockRouterValue.currentPage = 'dashboard';
renderWithProvider(<TopBar onOpenOptions={vi.fn()} />);
expect(screen.queryByTestId('ArrowBackIosNewIcon')).not.toBeInTheDocument();
});
it('should render settings button', () => {
it('应渲染设置按钮', () => {
renderWithProvider(<TopBar onOpenOptions={vi.fn()} />);
expect(screen.getByTestId('SettingsIcon')).toBeInTheDocument();
});
});
describe('Interaction', () => {
it('should call onOpenOptions when settings button is clicked', () => {
describe('交互测试', () => {
it('点击设置按钮时应调用 onOpenOptions', () => {
const handleOpenOptions = vi.fn();
renderWithProvider(<TopBar onOpenOptions={handleOpenOptions} />);
@@ -64,7 +64,7 @@ describe('TopBar Component', () => {
expect(handleOpenOptions).toHaveBeenCalledTimes(1);
});
it('should call goBack when back button is clicked', () => {
it('点击返回按钮时应调用 goBack', () => {
mockRouterValue.currentPage = 'timestamp';
renderWithProvider(<TopBar onOpenOptions={vi.fn()} />);
@@ -72,4 +72,4 @@ describe('TopBar Component', () => {
expect(mockRouterValue.goBack).toHaveBeenCalledTimes(1);
});
});
});
});