* 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 配置文件

* refactor(GlobalSnackbar): 合并SnackbarProvider到GlobalSnackbar组件

重构Snackbar相关代码,将SnackbarProvider合并到GlobalSnackbar组件中,简化代码结构
更新相关组件引用路径,从SnackbarProvider改为GlobalSnackbar
修复StorageCleanerPage禁用状态逻辑问题

* feat(表单映射): 增强高亮器功能并优化元素定位

- 新增高亮器闪烁功能,支持自定义持续时间
- 改进元素定位算法,支持 Shadow DOM 穿透
- 优化拾取模式,支持连续拾取和悬停预览
- 增强错误处理和信息反馈
- 添加测试用例确保核心功能稳定性

* refactor: 移除表单映射相关功能

删除表单映射相关的UI、逻辑和测试代码,包括表单识别、智能填充和高亮功能
简化消息处理逻辑和配置文件,保留核心功能

* feat: 实现页面组件懒加载并优化加载状态显示

refactor: 移除未使用的数据生成和验证工具类

chore: 更新应用图标文件

* refactor(qrcode): 替换二维码生成和解析库以减小体积

使用 qr-scanner 替代 jsqr 进行二维码解析,使用 qrious 替代 qrcode 进行二维码生成
新的库体积更小且性能更好,同时移除了不再使用的 @faker-js/faker 依赖

* feat: 添加在标签页打开功能并优化错误处理

修复测试中的加载状态检查
将控制台日志改为错误捕获
添加全局消息提示组件

* feat: 支持独立标签页模式并重构路由配置

重构路由系统以支持独立标签页模式,替换原有的独立窗口模式
- 新增标签页路由、可见页面列表和页面顺序的存储键
- 修改 RouterProvider 以支持不同窗口类型的独立配置
- 更新选项页面以支持为不同窗口类型单独配置
- 添加相关单元测试

* feat(ui): 优化响应式布局和样式设计

重构选项页面布局,增强移动端适配性
更新主题配置和组件样式,提升用户体验

* refactor: 移除URL工具相关代码

移除不再需要的URL工具功能,包括组件、页面、样式和类型定义

* refactor: 简化页面标题和存储选项网格的响应式布局

* refactor: 优化样式和错误处理

- 简化 chrome.runtime.openOptionsPage 的错误处理
- 拆分 html, body, #root 的样式定义,使用 minHeight 替代 height

* refactor: 重构页面组件结构
- 将页面组件从 entrypoints/popup/pages 移动到 pages 目录
- 更新文档中的路径引用

* style(DashboardPage): 优化仪表盘布局为响应式网格

refactor(ToolCard): 重构工具卡片组件并添加详细注释

* feat: 新增文本统计功能

添加文本统计工具页面及相关功能,包括:
- 文本统计工具页面组件
- 文本统计计算工具函数
- 相关类型定义和样式配置
- 单元测试覆盖核心功能

* feat(jwt): 添加 JWT 解析工具功能

新增 JWT 解析工具页面,包含以下内容:
- 添加 JWT 类型定义和页面样式配置
- 实现 JWT 解析核心功能及测试用例
- 创建 JWT 解析页面组件
- 在功能配置中注册 JWT 工具

* docs: 更新 README 以更清晰地描述项目功能和结构

- 重构功能描述部分,使用更简洁的列表形式展示
- 更新技术栈和项目结构说明
- 优化开发流程部分的描述
- 移除冗余的权限和依赖说明

* docs: 更新AGENTS.md文档以反映项目最新状态

- 重写项目概述和核心命令部分,使其更简洁准确
- 重构目录结构描述,采用更清晰的树状格式
- 移除过时的功能模块描述,聚焦当前核心功能
- 更新AI代理开发准则和权限管理说明
- 优化文档整体结构和可读性

* test: 更新特征计数测试以匹配新增 textStatistics 和 jwt 工具

* style: 统一导入语句顺序

* refactor(pages): 重构工具页面组件结构并优化功能实现

- 将各工具页面组件迁移至独立目录并重构为模块化结构
- 新增存储清理工具相关组件及状态管理逻辑
- 实现时间戳转换工具的自定义hook和UI组件
- 优化JWT解析工具的代码结构和样式
- 更新文本统计工具的性能计算逻辑
- 调整配置文件中的页面引用路径
- 删除无用文件和过时文档

* feat(顶部栏): 添加搜索功能和历史记录

实现顶部栏搜索框功能,支持模糊搜索工具并显示搜索结果列表
添加搜索历史记录功能,自动保存最近搜索并显示
支持键盘导航和选择搜索结果

* feat: 添加多语言支持(i18n)

实现应用的多语言功能,支持中英文切换
添加i18next和相关依赖
创建语言资源文件
更新组件以使用翻译功能
重构文本统计工具页面
完善测试和构建配置

* feat(顶部栏): 添加语言切换功能并优化国际化支持
feat(i18n): 增加语言归一化和同步功能
fix(剪贴板): 使用国际化文本替换剪贴板消息
test(顶部栏): 更新测试以匹配国际化标题

* refactor: 重构组件目录结构,将组件移动到对应功能页面目录

将多个组件从通用组件目录移动到各自功能页面目录下,包括 ToolCard、StorageCleanerConfirm、UrlToQrCodeSection 和 QrCodeToUrlSection。同时新增 Dashboard 页面相关组件 DashboardCard 和 ToolCard,并优化了组件导入路径。

重构旨在提高代码组织性,使组件与其所属功能页面更紧密关联,便于维护和理解代码结构。所有组件功能保持不变,仅调整文件位置和导入路径。

* refactor(Dashboard): 优化卡片组件结构并移除无用属性

重构 DashboardCard 组件接口,直接传递属性而非配置对象
移除 ToolCard 中无用的 hasAI 属性
使用 useMemo 优化可见性判断性能
统一使用 alpha 函数处理颜色透明度

* refactor(timestamp): 合并输入处理函数并优化样式结构

重构时间戳转换器的输入处理逻辑,将 setTsInput 和 setDtInput 合并为统一的 setInput 函数
将组件样式提取到 pageTheme 配置中统一管理
使用 ToggleButtonGroup 替换自定义模式切换器实现
移除不必要的 showMessage 属性传递,改用 useSnackbar 钩子

* refactor(dashboard): 重构仪表盘卡片组件并优化布局

- 删除冗余的 DashboardCard 组件,直接使用 ToolCard
- 将网格布局样式移至主题配置
- 使用 CardActionArea 增强可访问性
- 简化点击事件处理逻辑
- 更新相关测试用例

* refactor(storageCleaner): 重构样式代码并优化国际化处理

将分散的样式代码集中到pageTheme.ts中统一管理
优化组件中的国际化文本引用
修复useStorageCleaner中的状态同步问题
更新测试用例以匹配国际化文本

* refactor(StorageCleaner): 优化条件判断和清理未使用的代码

简化禁用按钮的条件判断逻辑
移除未使用的 resultTimeoutRef 及相关清理代码

* refactor(QrCode): 重构二维码页面样式和组件结构

将内联样式提取到主题配置文件中
移除未使用的全局消息提示依赖
优化组件结构和代码复用
删除未使用的QrCodeUploader组件

* refactor(ErrorBoundary): 移除冗余状态更新并调整错误背景色

移除 componentDidCatch 中的冗余 setState 调用
将错误背景色从 'error.shortest' 改为 rgba 格式

* feat(TopBar): 优化顶部导航栏功能并添加样式配置

- 新增 openExtensionPage 工具函数用于打开扩展页面
- 将顶部导航栏样式配置提取到 pageTheme 中统一管理
- 改进搜索历史功能,增加错误处理和配置化限制
- 优化键盘导航和搜索结果的交互逻辑

* chore: 在.gitignore中添加docs目录

避免将文档生成目录提交到版本控制

* feat(JsonDiff): add type definitions for diff engine

* feat: 新增 JSON 差异比较工具功能

添加 JSON 差异比较工具页面,支持并排和统一视图模式,包含以下功能:
- 左右两侧 JSON 输入框及校验
- 差异高亮显示及导航
- 支持对象和数组的深度比较
- 国际化支持
- 单元测试覆盖核心差异算法

* feat(主题): 添加暗色模式支持并重构主题系统

- 新增 ThemeModeProvider 提供亮色/暗色/系统模式切换功能
- 重构所有组件使用 MUI 主题变量替代硬编码颜色
- 更新测试用例以适配新的主题系统
- 添加 i18n 翻译支持主题切换相关文本
- 统一入口点使用 AppRoot 组件封装主题和路由提供者

* feat(jsonDiff): 新增 JSON 格式化功能模块

- 新增 jsonFormat 语言资源,支持中英文文本
- 新增 JsonFormatSection 组件,提供 JSON 格式化输入与结果展示
- 在 JsonDiff 页面加入模式切换,支持差异比较与格式化双模式
- 实现 formatJson 和 validateJson 工具方法,支持缩进大小和键名排序选项
- 增加格式化结果显示大小统计和一键复制功能
- 写入大量单元测试,覆盖格式化和校验功能边界
- 优化页面布局与交互,提升用户体验和功能集成度

* feat(jsonDiff): 新增 JSON 转 YAML/TOML 及压缩功能

- 在语言文件(en/zh)中添加 YAML、TOML 和 JSON 压缩模式相关文案
- 扩展 JsonDiff 页面,新增 yaml、toml、minify 三种页面模式
- 新增 JsonConvertSection 组件,提供输入校验、转换操作及结果展示
- 实现 jsonToYaml 工具函数,将 JSON 转换为符合规范的 YAML 格式
- 实现 jsonToToml 工具函数,将 JSON 转换为符合规范且支持嵌套的 TOML 格式
- 实现 minifyJson 工具函数,实现 JSON 字符串压缩为单行格式
- 为所有新功能增加单元测试,覆盖正常及异常场景,保证转换正确性和稳定性
- 在页面中添加对应的切换按钮和图标,提升用户体验和操作便捷性

* refactor(jsonTools): 重命名 JSON 差异比较为 JSON 工具

- 将 JsonDiff 页面组件重命名为 JsonTools 并更新相关引用
- 修改功能配置中对应组件的名称以匹配新命名
- 更新英文和中文语言包中该功能的标题及描述
- 调整测试文件中导入路径以使用新的 JsonTools 文件夹名

* feat(storage): 优化本地存储状态管理和 JSON 工具页模式持久化

- 添加 useStorageState 钩子,支持同步快照和异步加载存储状态
- 实现快照机制,防止页面首屏闪烁现象
- 增加状态值验证器功能,保证恢复数据合法性
- JSON 工具页面模式改用受控存储状态持久化
- 新增 JsonToolsPageMode 类型定义,统一页面模式类型
- 为 useStorageState 编写完整单元测试,覆盖快照、校验及存储同步场景

* feat(base64Converter): 新增 Base64 转换器功能模块

- 添加 Base64 转换器页面及相关样式配置
- 支持文本、文件及图像三种转换模式,含编码和解码功能
- 实现拖拽、文件选择及图像预览功能
- 增加中文与英文多语言资源文件支持
- 补充相关工具函数,支持编码解码及格式校验
- 扩展路由提供者逻辑,合并已保存列表与默认功能集合
- 更新测试用例,覆盖合并新功能的场景验证
- 在特性配置中加入 Base64 转换器信息,支持图标和默认显示配置

* feat(markdown): 新增 Markdown 转 HTML 功能模块

- 添加 marked 依赖及类型定义支持 Markdown 解析
- 新增 MarkdownToHtml 页面,支持实时编辑、预览及 HTML 输出三种模式切换
- 实现 markdownToHtml 工具函数进行 Markdown 转 HTML 操作,含错误处理
- 包装完整 HTML 文档功能,支持打印和下载导出
- 配置全局主题样式,优化 Markdown 渲染视觉效果
- 完善 i18n 国际化资源,支持多语言页面展示
- 统一类型定义,新增 MarkdownToHtml 相关存储状态类型
- 添加相关单元测试,覆盖转换逻辑及功能组件
- 在功能配置中注册 Markdown 转 HTML 工具,支持界面调用和路由访问

* feat(htmlToMarkdown): 添加 HTML 转 Markdown 功能页面及转换工具

- 新增 HtmlToMarkdownPage 组件,支持实时转换 HTML 为 Markdown
- 增加 htmlToMarkdown 工具函数,实现基于 DOM 解析的转换逻辑
- 新增下载 Markdown 文件功能,支持一键导出转换结果
- 配置文件增加 htmlToMarkdown 相关功能项和页面样式
- 国际化资源添加对应中英文文案
- 更新类型定义,新增 HTML 转 Markdown 相关类型和存储键
- 补充对应的单元测试,覆盖转换逻辑和导出功能
- 修正路由提供器测试,确保新增页面被正确识别和排序

* refactor(jwt): 替换 JSON 格式化函数名称及优化代码表达

- 将 jwt 解析工具中的 formatJson 函数重命名为 stringifyJson
- 更新 Jwt 页面中相关的格式化函数调用,保持命名一致
- 统一注释风格,增强代码可读性
- 保持功能不变,改进代码语义表达

* refactor(timestamp): 优化时间戳页面布局与样式,简化组件结构

- 调整模式切换器和单位切换器样式,增加统一转换工作卡片和转换按钮样式
- 精简LiveClock组件,移除单位切换功能,瘦身为单行参考条
- 优化Timestamp页面布局,输入区、单位选择、时区选择及结果区并入统一卡片中
- 移除ResultView中多余的额外时间格式展示,仅保留转换结果显示
- 精简useTimestampConverter,删除自动转换的防抖useEffect逻辑
- 更新多处样式细节以提升界面紧凑度和一致性
- 删除国际化文件中未使用的时间相关文案键值

* feat(layout): 优化二维码与时间戳页面响应式布局

- 新增桌面端左右分栏布局样式,实现 md 断点后等宽分栏二卡片等高
- 调整二维码页面,移动端折叠,桌面端两个面板强制展开且隐藏折叠交互
- 时间戳页面新增左右分栏样式,左侧为转换工作台,右侧为结果展示卡片
- 结果展示新增空状态占位提示,支持显示额外时间格式信息及复制按钮
- 国际化资源补充时间戳转换相关文本,包括相对时间、ISO8601、UTC时间等标签
- 统一各布局区容器高度及内联样式,强化桌面端用户体验与视觉一致性

* fix(style): 优化页面布局与文字溢出显示

- 为页面主题配置添加 gridAutoRows 属性,统一自动行高
- 修改 ToolCard 中描述文本样式,实现单行溢出省略号显示
- 解决文本换行和截断,避免内容超出指定范围
- 改善视觉效果和布局一致性,提高用户体验

* feat(options): 支持功能列表拖拽排序

- 新增 @dnd-kit 相关依赖包,实现拖拽排序功能
- 将原先的上下移动按钮替换为拖拽交互
- 封装 SortableFeatureRow 组件,支持拖拽排序与开关切换
- 使用 DndContext 和 SortableContext 管理拖拽逻辑与排序状态
- 拖拽时高亮显示拖动项,优化用户体验
- 调整恢复默认按钮位置,与 Tab 同行展示
- 优化 UI 样式及相关交互提示信息
- 保存排序结果至存储,保证配置持久化

* fix(router): 防止组件卸载后更新状态导致竞态条件

- 修改 loadInitialData 调用逻辑,添加 cancelled 标志防止卸载后更新状态
- 确保组件卸载时取消状态更新,避免 React 警告和无效操作
- 新增测试覆盖组件卸载时不应更新 isLoaded 状态的竞态条件防护
- 修复加载初始路由数据失败时的错误处理代码逻辑

* refactor(router): 移除不再使用的本地导航相关代码

- 删除 RouterProvider 中的 navigateLocal 和 syncNavigation 方法及相关注释
- 清理对应的类型定义,移除不再使用的接口成员
- 更新测试文件,移除对 navigateLocal 的模拟函数调用
- 精简导航逻辑,保持代码整洁和一致性

* refactor(clipboard): 优化剪贴板复制函数并添加测试用例

- 将复制文本和复制图片的函数改为 async/await 形式,简化代码结构
- 删除 Promise 构造函数中多余的 then/catch,改用 try/catch 返回布尔值表示成功与否
- 修改 CopyButton 组件使用新的异步复制函数写法,提升代码可读性
- 添加剪贴板复制功能的单元测试,覆盖成功与失败两种场景
- 在测试环境中模拟 ClipboardItem 以支持图片复制测试

* fix(options): 验证配置数据有效性并恢复默认值

- 添加 isValidPage 和 isValidPageList 函数验证 visiblePages 和 pageOrder 的数据有效性
- 当读取到非法数据时,自动恢复为默认配置,避免异常状态
- 更新异步加载配置逻辑,确保界面状态稳定
- 新增单元测试,覆盖合法与非法数据的加载场景
- 修正 .gitignore 文件

* refactor(storage): 替换 IndexedDB 大小计算为通用存储估算

- 将获取 IndexedDB 大小的方法更名为获取源存储估算
- 修改调用处使用新的通用存储估算函数
- 更新错误日志信息以反映新的统计方法
- 统一存储空间估算接口,提升扩展能力

* fix(utils): 解决打印重复触发问题

- 添加 printed 标志防止多次执行打印
- 在 onload 和 setTimeout 中判断 printed 状态
- 防止部分浏览器 onload 不触发导致重复打印
- 增强打印逻辑的稳定性和兼容性

* fix(ErrorBoundary): 修复错误状态未随子组件变化重置的问题

- 增加 componentDidUpdate 钩子,子组件变化时重置错误状态
- 添加完整的单元测试覆盖正常渲染、错误捕获、状态重置和刷新按钮功能
- 修改 background.ts,调用 reload 时添加异常捕获并打印错误
- 修改 sidepanel/App.tsx,调用 openOptionsPage 时添加异常捕获并打印错误
- tsconfig.json 开启 noImplicitAny 检查,提高代码类型安全
- 添加 qrious 模块类型声明文件,完善类型定义

* fix(utils): 修复存储状态和主题模式加载的竞态条件问题

- 在 ThemeModeProvider 中取消异步操作防止内存泄漏
- 在 useStorageState 钩子中添加取消标志,避免状态更新竞态
- 修正 TopBar 搜索历史持久化,添加 useEffect 副作用同步存储
- 扩展 storageCleaner 支持 TB 单位,防止格式化错误
- GlobalSnackbar 组件支持自定义 anchorOrigin 属性,增强弹窗位置灵活性
- 优化 jsonToToml 和 jsonToYaml 中多余的字符判断逻辑,提升序列化准确性

* fix(Base64Converter): 修复切换模式时文件状态未及时重置问题

- 添加取消标志避免文件选择异步状态错乱
- 切换页面模式时清空文件和加载状态
- 切换文本编码方向时清空输出和错误状态
- 阻止重复选择同一模式导致不必要状态更新
- 确保异步转换过程中若取消选择不更新状态

* refactor(Base64Converter): 拆分文本、文件和图像转换模式为独立组件

- 将文本编码/解码逻辑提取至 TextMode 组件,简化主页面代码
- 将文件转Base64相关处理封装到 FileMode 组件,提升代码模块化
- 将图像转Base64相关处理封装到 ImageMode 组件,增强功能分离
- 主页面根据当前模式动态渲染对应组件,移除大量重复状态及逻辑
- 优化模式切换逻辑,取消不必要的状态重置,简化事件处理
- 清理未使用的导入和废弃代码,减少页面体积与复杂度

* test(toolcard): 调整键盘触发事件模拟

- 替换点击事件为键盘按下和释放事件模拟
- 修正测试用例以更真实地模拟键盘交互
- 确保事件处理函数被正确调用
- 移除eslint配置文件中对测试文件的忽略设置

* test(ToolCard): 优化键盘事件测试逻辑

- 引入 userEvent 以模拟更真实的用户键盘输入
- 使用 act 包裹异步操作确保测试稳定性
- 修改按 Enter 键测试为异步函数以支持 await
- 替换 fireEvent 键盘事件为 userEvent.keyboard 模拟Enter键
- 在触发键盘事件前手动聚焦目标按钮,确保事件正确触发

* docs: 添加页面级 ErrorBoundary 设计文档

为懒加载页面组件添加独立 ErrorBoundary 保护的设计方案。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(PageErrorBoundary): 添加页面级错误边界组件

轻量内嵌错误卡片,支持 resetKey 自动重置和重试按钮。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(PageErrorBoundary): 添加页面级错误边界单元测试

覆盖正常渲染、错误捕获、重试恢复、resetKey 自动重置等场景。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(RouterContainer): 在 Suspense 内层添加 PageErrorBoundary

以 currentPage 为 resetKey,页面切换时自动重置错误状态。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(options): 使用 PageErrorBoundary 替换全局 ErrorBoundary

options 页面统一使用页面级错误卡片,与 RouterContainer 体验一致。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(utils): add unified formatBytes function

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(utils): add formatBytes unit tests

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(utils): delegate formatByteSize to formatBytes

- Add unified formatBytes to utils/format.ts
- Update textStatistics.ts to re-export
- Update test expectations for consistent decimal formatting

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(utils): delegate formatFileSize and formatSize to formatBytes

- Update base64Converter.ts to re-export formatBytes as formatFileSize
- Update storageCleaner.ts to re-export formatBytes as formatSize

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(base64Converter): 支持 data URI 解码并优化错误提示

- base64ToText 支持自动剥离 data:<mime>;base64, 前缀进行正确解码
- 解码非 UTF-8 数据(如图片)时抛出友好错误,提示切换至图像模式
- TextMode 组件增加基于输入内容智能提示,解码图片类型时显示切换图像模式按钮
- 添加切换图像模式的回调支持及对应 UI 提示
- 增加对应单元测试覆盖新增功能和错误处理
- 更新中英文国际化文案,增加新的错误和提示信息
- eslint 配置调整,允许测试文件使用 any 类型警告关闭

* feat(base64Converter): 添加文件与图像模式的Base64解码及下载功能

- 增加文件模式的Base64解码功能,支持手动输入Base64内容进行解码
- 添加解码后的文件名编辑与下载按钮,提升用户操作便捷性
- 实现文件模式中编码与解码的切换按钮,并保留用户选择状态
- 图像模式同步新增解码功能,支持Base64字符串或数据URI的转换
- 图像解码结果显示预览图像、推断MIME类型、解码大小信息
- 增设统一错误处理机制,提示无效Base64字符串错误
- 更新i18n翻译词条,新增解码相关UI文字描述
- 扩展单元测试覆盖编码/解码切换及解码异常处理场景

* feat(eslint): 在测试文件规则中添加对未使用变量的警告配置

* fix(storageCleaner): 更新错误消息以反映清理操作的上下文

* feat(RouterProvider): 使用 ref 持有最新 currentPage,优化 chrome.storage 监听器注册

* fix(StorageSchema): 更新 RouterProvider 相关路由键的注释以反映默认行为

* feat(base64Converter): 添加对 BMP 和 WebP 文件类型的支持,更新魔数签名匹配规则

* fix(LiveClock): 修复定时器变量命名以提高代码可读性

* fix(storageCleaner): 使用 TextEncoder 准确计算 UTF-8 字节数

将 getCookieSize、getLocalStorageSize 和 getSessionStorageSize
中的字符串 .length 替换为 TextEncoder.encode().length,
避免 Unicode 字符导致的大小低估问题。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor: 移除不必要的样式定义,简化模式切换按钮的样式

* feat(SwitchButtonGroup): 添加 SwitchButtonGroup 组件及其测试用例,替换现有的 ToggleButtonGroup

* feat(SwitchButtonGroup): 添加 size 和 buttonSx 属性支持,并更新测试用例

* feat(MarkdownToHtml): 替换 ToggleButtonGroup 为 SwitchButtonGroup,简化模式切换逻辑

* feat: 替换 ToggleButtonGroup 为 SwitchButtonGroup,简化模式切换逻辑

* chore: 移除不必要的 compile 脚本

* feat: 更新 SwitchButtonGroup 组件,支持 number 类型和自定义样式,替换多个 ToggleButtonGroup 实现

* feat(Timestamp): 更新单位和时区选择样式,支持自适应宽度和换行

* feat: 更新比较按钮样式,添加 nowrap 属性以防止换行

* style(HTML转Markdown页): 替换旧版InputProps为新版slotProps

将Material UI组件的InputProps属性更新为slotProps语法,适配最新组件API

* feat: 添加 TextInputArea 多行文本输入组件及配套测试

新增功能完整的 TextInputArea 组件,支持受控/非受控模式、字符计数、复制清空、表单验证、自定义操作按钮等特性,同时编写了全面的单元测试覆盖所有核心功能。

* refactor(TopBar,JWT): 移动常量定义并重构JWT页面

1. 将TopBar的常量从pageTheme.ts移至组件内
2. 移除pageTheme.ts中废弃的topBarStyles定义
3. 重构JWT页面:替换TextField为TextInputArea组件
4. 简化JWT页面的输入处理逻辑

* feat(TextInputArea): 添加 sx 样式透传支持

新增 TextInputArea 组件的 sx 属性,支持透传样式到外层容器,新增对应测试用例验证样式生效

* refactor(TextStatistics): 抽离文本输入区域为公共组件

将原页面内的TextField文本输入框抽离为TextInputArea公共组件,简化当前页面代码,复用组件样式与逻辑

* feat(TextInputArea): 添加外部错误属性,支持父组件控制错误展示

- 新增externalError属性,优先级高于内部验证错误
- 新增配套测试用例验证外部错误的展示和优先级逻辑

* feat(textInputArea): 实现国际化适配并完善组件功能

1. 为文本输入区域组件添加多语言支持,新增中英文字段
2. 重构清空和复制按钮,使用国际化文案替代硬编码
3. 新增onClear回调属性,新增对应测试用例
4. 调整底部操作栏布局,合并操作按钮显示逻辑
5. 优化字符计数提示文案为国际化形式

* refactor(utils/jwt): 替换硬编码错误提示为国际化文案

1. 新增中英文多语言错误提示文案
2. 将decodeBase64Url和parseJwt中的硬编码错误信息替换为i18n翻译内容
3. 更新JWT格式错误的校验提示文案
4. 调整测试用例适配新的错误信息校验逻辑

* feat(components): 添加 DecodeResultPaper 通用结果展示组件及测试用例

提取 FileMode 和 ImageMode 共用的解码结果展示Paper结构,包含标题、预览区、文件信息、文件名输入和下载按钮,同时补充完整的单元测试覆盖渲染和交互逻辑

* refactor(Base64Converter): 重构页面组件,统一使用TextInputArea组件

1.  替换原有TextField为公共TextInputArea组件,减少重复代码
2.  抽离工具栏操作逻辑,使用useMemo缓存动作配置
3.  统一错误提示和输出区域的渲染逻辑,复用DecodeResultPaper组件
4.  更新测试用例,适配新的元素选择方式

* refactor(JsonTools): 替换原生TextField为复用的TextInputArea组件

统一JSON工具页面的输入框组件,移除冗余的样式和错误提示代码,简化页面代码结构

* refactor(Jwt页面): 优化错误提示实现方式

将手动实现的错误提示组件替换为通过externalError属性传递的方式,移除未使用的ErrorOutlineIcon导入,简化代码结构

* ci(github workflow): 修正CI脚本中的类型检查命令

将原本执行编译的npm run compile替换为正确的类型检查命令npm run typecheck
This commit is contained in:
LingandRX
2026-05-17 18:42:01 +08:00
committed by GitHub
parent a6dcdddf66
commit 0cf8bae9f1
87 changed files with 5865 additions and 1594 deletions
+363
View File
@@ -0,0 +1,363 @@
import { useCallback, useMemo, useRef, useState } from 'react';
import {
Alert,
alpha,
Box,
Button,
CircularProgress,
Paper,
Stack,
Typography,
} from '@mui/material';
import TextInputArea from '@/components/TextInputArea';
import type { ToolbarAction } from '@/components/TextInputArea';
import UploadFileIcon from '@mui/icons-material/UploadFile';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import { useTranslation } from 'react-i18next';
import CopyButton from '@/components/CopyButton';
import DecodeResultPaper from '@/components/DecodeResultPaper';
import {
fileToBase64,
isFileSizeValid,
formatFileSize,
base64ToBlob,
downloadBlob,
MAX_FILE_SIZE,
} from '@/utils/base64Converter';
import type { Base64ToBlobResult, FileToBase64Result } from '@/utils/base64Converter';
import { useStorageState } from '@/utils/useStorageState';
import type { Base64ConvertDirection } from '@/types/storage';
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
interface FileInfo {
name: string;
size: number;
type: string;
}
const ERROR_MESSAGE_TO_I18N: Record<string, string> = {
'Invalid Base64 string': 'invalidBase64',
};
const isValidDirection = (val: unknown): val is Base64ConvertDirection =>
val === 'encode' || val === 'decode';
export default function FileMode() {
const { t } = useTranslation('base64Converter');
const [direction, setDirection] = useStorageState(
'base64Converter/fileMode/direction',
'encode',
isValidDirection,
);
// encode state
const [result, setResult] = useState<FileToBase64Result | null>(null);
const [info, setInfo] = useState<FileInfo | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isDragging, setIsDragging] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const cancelRef = useRef(false);
// decode state
const [decodeInput, setDecodeInput] = useState('');
const [decoded, setDecoded] = useState<Base64ToBlobResult | null>(null);
const [decodedFileName, setDecodedFileName] = useState('');
// shared
const [error, setError] = useState<string | null>(null);
const resetAll = useCallback(() => {
cancelRef.current = true;
setResult(null);
setInfo(null);
setIsLoading(false);
setDecodeInput('');
setDecoded(null);
setDecodedFileName('');
setError(null);
if (fileInputRef.current) fileInputRef.current.value = '';
}, []);
const handleClear = () => {
resetAll();
};
const handleDirectionChange = (next: Base64ConvertDirection) => {
if (next === direction) return;
resetAll();
setDirection(next);
};
const handleFileSelect = async (file: File) => {
cancelRef.current = false;
setError(null);
setResult(null);
setInfo(null);
if (!isFileSizeValid(file.size)) {
setError(t('fileSizeExceeded', { max: `${MAX_FILE_SIZE / 1024 / 1024} MB` }));
return;
}
setInfo({
name: file.name,
size: file.size,
type: file.type || 'application/octet-stream',
});
setIsLoading(true);
try {
const res = await fileToBase64(file);
if (!cancelRef.current) setResult(res);
} catch (e) {
if (!cancelRef.current) {
setError(e instanceof Error ? e.message : t('conversionFailed'));
}
} finally {
if (!cancelRef.current) setIsLoading(false);
}
};
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(true);
};
const handleDragLeave = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(false);
};
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(false);
const file = e.dataTransfer.files[0];
if (file) handleFileSelect(file);
};
const handleDownload = () => {
if (!decoded) return;
downloadBlob(decoded.blob, decodedFileName || `decoded${decoded.suggestedExtension}`);
};
const actions: ToolbarAction[] = useMemo(
() => [
{
key: 'decode',
label: t('decode'),
type: 'primary',
position: 'bottom',
disabled: (value: string) => !value.trim(),
onClick: (value: string, helpers) => {
helpers.setError('');
setDecoded(null);
try {
const res = base64ToBlob(value);
setDecoded(res);
setDecodedFileName(`decoded${res.suggestedExtension}`);
} catch (e) {
const message = e instanceof Error ? e.message : '';
const i18nKey = ERROR_MESSAGE_TO_I18N[message];
helpers.setError(i18nKey ? t(i18nKey) : message || t('conversionFailed'));
}
},
},
],
[t],
);
return (
<>
<SwitchButtonGroup
value={direction}
options={[
{ value: 'encode', label: t('encode') },
{ value: 'decode', label: t('decode') },
]}
onChange={handleDirectionChange}
size="small"
/>
{direction === 'encode' && (
<>
<Box
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
onClick={() => fileInputRef.current?.click()}
sx={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
minHeight: 180,
border: '2px dashed',
borderColor: isDragging ? 'info.main' : info ? 'info.main' : 'divider',
borderRadius: 3,
p: 4,
bgcolor: (theme) =>
isDragging
? alpha(theme.palette.info.main, 0.08)
: info
? alpha(theme.palette.info.main, 0.04)
: 'action.hover',
cursor: 'pointer',
transition: 'all 0.2s',
'&:hover': {
borderColor: 'info.main',
bgcolor: (theme) => alpha(theme.palette.info.main, 0.04),
},
}}
>
<input
ref={fileInputRef}
type="file"
hidden
onChange={(e) => {
const file = e.target.files?.[0];
if (file) handleFileSelect(file);
}}
/>
{isLoading ? (
<CircularProgress size={40} />
) : info ? (
<Stack spacing={1} alignItems="center">
<UploadFileIcon sx={{ fontSize: 40, color: 'info.main' }} />
<Typography variant="body2" fontWeight={700}>
{info.name}
</Typography>
<Typography variant="caption" color="text.secondary">
{formatFileSize(info.size)} · {info.type}
</Typography>
<Typography variant="caption" color="text.disabled">
{t('clickOrDropToReplace')}
</Typography>
</Stack>
) : (
<Stack spacing={1} alignItems="center">
<UploadFileIcon sx={{ fontSize: 40, color: 'text.disabled' }} />
<Typography variant="body2" color="text.secondary" fontWeight={600}>
{t('clickOrDropToFile')}
</Typography>
<Typography variant="caption" color="text.disabled">
{t('maxFileSize', { max: `${MAX_FILE_SIZE / 1024 / 1024} MB` })}
</Typography>
</Stack>
)}
</Box>
{error && <Alert severity="error">{error}</Alert>}
{result && (
<Paper
elevation={0}
sx={{
p: 2,
borderRadius: 3,
bgcolor: (theme) => alpha(theme.palette.info.main, 0.04),
border: '1px solid',
borderColor: (theme) => alpha(theme.palette.info.main, 0.15),
}}
>
<Stack
direction="row"
justifyContent="space-between"
alignItems="center"
sx={{ mb: 1 }}
>
<Typography variant="caption" fontWeight={700} color="text.secondary">
{t('base64Output')}
</Typography>
<Stack direction="row" spacing={1}>
<CopyButton
text={result.rawBase64}
tooltip={t('copyRaw')}
showMessage={() => {}}
/>
<CopyButton
text={result.output}
tooltip={t('copyDataUri')}
color="info"
showMessage={() => {}}
/>
</Stack>
</Stack>
<TextInputArea
readOnly
value={
result.output.length > 2000
? `${result.output.substring(0, 2000)}...`
: result.output
}
showClear={false}
showCount
/>
<Stack direction="row" alignItems="center" spacing={2} sx={{ mt: 1 }}>
<Typography variant="caption" color="text.disabled">
{t('originalSize')}: {formatFileSize(result.originalBytes)}
</Typography>
<Typography variant="caption" color="text.disabled">
{t('encodedSize')}: {formatFileSize(result.outputBytes)}
</Typography>
<Box sx={{ flex: 1 }} />
<Button
variant="text"
size="small"
onClick={handleClear}
startIcon={<DeleteOutlineIcon />}
sx={{ borderRadius: 2, minWidth: 0 }}
>
{t('clear')}
</Button>
</Stack>
</Paper>
)}
{info && !result && (
<Button
variant="text"
onClick={handleClear}
startIcon={<DeleteOutlineIcon />}
sx={{ borderRadius: 3 }}
>
{t('clear')}
</Button>
)}
</>
)}
{direction === 'decode' && (
<>
<TextInputArea
placeholder={t('decodeBase64Placeholder')}
value={decodeInput}
onChange={(v) => {
setDecodeInput(v);
setError(null);
}}
actions={actions}
externalError={error || undefined}
onClear={() => {
setDecoded(null);
setDecodedFileName('');
}}
/>
{decoded && (
<DecodeResultPaper
title={t('decodedFileOutput')}
mimeType={decoded.mimeType}
blobSize={decoded.blob.size}
fileName={decodedFileName}
onFileNameChange={setDecodedFileName}
onDownload={handleDownload}
/>
)}
</>
)}
</>
);
}
+391
View File
@@ -0,0 +1,391 @@
import { useCallback, useMemo, useRef, useState } from 'react';
import {
Alert,
alpha,
Box,
Button,
CircularProgress,
Paper,
Stack,
Typography,
} from '@mui/material';
import TextInputArea, { type ToolbarAction } from '@/components/TextInputArea';
import ImageIcon from '@mui/icons-material/Image';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import { useTranslation } from 'react-i18next';
import CopyButton from '@/components/CopyButton';
import DecodeResultPaper from '@/components/DecodeResultPaper';
import {
fileToBase64,
isFileSizeValid,
isSupportedImageType,
isSupportedImageExtension,
formatFileSize,
base64ToBlob,
downloadBlob,
MAX_FILE_SIZE,
} from '@/utils/base64Converter';
import type { Base64ToBlobResult, FileToBase64Result } from '@/utils/base64Converter';
import { useStorageState } from '@/utils/useStorageState';
import type { Base64ConvertDirection } from '@/types/storage';
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
interface FileInfo {
name: string;
size: number;
type: string;
}
const ERROR_MESSAGE_TO_I18N: Record<string, string> = {
'Invalid Base64 string': 'invalidBase64',
};
const isValidDirection = (val: unknown): val is Base64ConvertDirection =>
val === 'encode' || val === 'decode';
export default function ImageMode() {
const { t } = useTranslation('base64Converter');
const [direction, setDirection] = useStorageState(
'base64Converter/imageMode/direction',
'encode',
isValidDirection,
);
// encode state
const [result, setResult] = useState<FileToBase64Result | null>(null);
const [info, setInfo] = useState<FileInfo | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isDragging, setIsDragging] = useState(false);
const imageInputRef = useRef<HTMLInputElement>(null);
const cancelRef = useRef(false);
// decode state
const [decodeInput, setDecodeInput] = useState('');
const [decoded, setDecoded] = useState<Base64ToBlobResult | null>(null);
const [decodedFileName, setDecodedFileName] = useState('');
// shared
const [error, setError] = useState<string | null>(null);
const resetAll = useCallback(() => {
cancelRef.current = true;
setResult(null);
setInfo(null);
setIsLoading(false);
setDecodeInput('');
setDecoded(null);
setDecodedFileName('');
setError(null);
if (imageInputRef.current) imageInputRef.current.value = '';
}, []);
const handleClear = () => {
resetAll();
};
const handleDirectionChange = (next: Base64ConvertDirection) => {
if (!next || next === direction) return;
resetAll();
setDirection(next);
};
const handleFileSelect = async (file: File) => {
cancelRef.current = false;
setError(null);
setResult(null);
setInfo(null);
if (!isFileSizeValid(file.size)) {
setError(t('fileSizeExceeded', { max: `${MAX_FILE_SIZE / 1024 / 1024} MB` }));
return;
}
if (!isSupportedImageType(file.type) && !isSupportedImageExtension(file.name)) {
setError(t('unsupportedImageType'));
return;
}
setInfo({
name: file.name,
size: file.size,
type: file.type || 'application/octet-stream',
});
setIsLoading(true);
try {
const res = await fileToBase64(file);
if (!cancelRef.current) setResult(res);
} catch (e) {
if (!cancelRef.current) {
setError(e instanceof Error ? e.message : t('conversionFailed'));
}
} finally {
if (!cancelRef.current) setIsLoading(false);
}
};
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(true);
};
const handleDragLeave = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(false);
};
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(false);
const file = e.dataTransfer.files[0];
if (file) handleFileSelect(file);
};
const handleDownload = () => {
if (!decoded) return;
downloadBlob(decoded.blob, decodedFileName || `decoded${decoded.suggestedExtension}`);
};
const actions: ToolbarAction[] = useMemo(
() => [
{
key: 'decode',
label: t('decode'),
type: 'primary',
position: 'bottom',
disabled: (value: string) => !value.trim(),
onClick: (value: string, helpers) => {
helpers.setError('');
setDecoded(null);
try {
const res = base64ToBlob(value);
setDecoded(res);
setDecodedFileName(`decoded${res.suggestedExtension}`);
} catch (e) {
const message = e instanceof Error ? e.message : '';
const i18nKey = ERROR_MESSAGE_TO_I18N[message];
helpers.setError(i18nKey ? t(i18nKey) : message || t('conversionFailed'));
}
},
},
],
[t],
);
return (
<>
<SwitchButtonGroup
value={direction}
options={[
{ value: 'encode', label: t('encode') },
{ value: 'decode', label: t('decode') },
]}
onChange={handleDirectionChange}
size="small"
/>
{direction === 'encode' && (
<>
<Box
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
onClick={() => imageInputRef.current?.click()}
sx={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
minHeight: 180,
border: '2px dashed',
borderColor: isDragging ? 'info.main' : info ? 'info.main' : 'divider',
borderRadius: 3,
p: 4,
bgcolor: (theme) =>
isDragging
? alpha(theme.palette.info.main, 0.08)
: info
? alpha(theme.palette.info.main, 0.04)
: 'action.hover',
cursor: 'pointer',
transition: 'all 0.2s',
'&:hover': {
borderColor: 'info.main',
bgcolor: (theme) => alpha(theme.palette.info.main, 0.04),
},
}}
>
<input
ref={imageInputRef}
type="file"
accept="image/*"
hidden
onChange={(e) => {
const file = e.target.files?.[0];
if (file) handleFileSelect(file);
}}
/>
{isLoading ? (
<CircularProgress size={40} />
) : info ? (
<Stack spacing={1} alignItems="center">
{result && (
<Box
component="img"
src={result.output}
alt="preview"
sx={{
maxWidth: '100%',
maxHeight: 160,
borderRadius: 2,
objectFit: 'contain',
}}
/>
)}
<Typography variant="body2" fontWeight={700}>
{info.name}
</Typography>
<Typography variant="caption" color="text.secondary">
{formatFileSize(info.size)} · {info.type}
</Typography>
<Typography variant="caption" color="text.disabled">
{t('clickOrDropToReplace')}
</Typography>
</Stack>
) : (
<Stack spacing={1} alignItems="center">
<ImageIcon sx={{ fontSize: 40, color: 'text.disabled' }} />
<Typography variant="body2" color="text.secondary" fontWeight={600}>
{t('clickOrDropToImage')}
</Typography>
<Typography variant="caption" color="text.disabled">
{t('supportedFormats')}
</Typography>
</Stack>
)}
</Box>
{error && <Alert severity="error">{error}</Alert>}
{result && (
<Paper
elevation={0}
sx={{
p: 2,
borderRadius: 3,
bgcolor: (theme) => alpha(theme.palette.info.main, 0.04),
border: '1px solid',
borderColor: (theme) => alpha(theme.palette.info.main, 0.15),
}}
>
<Stack
direction="row"
justifyContent="space-between"
alignItems="center"
sx={{ mb: 1 }}
>
<Typography variant="caption" fontWeight={700} color="text.secondary">
{t('base64Output')}
</Typography>
<Stack direction="row" spacing={1}>
<CopyButton
text={result.rawBase64}
tooltip={t('copyRaw')}
showMessage={() => {}}
/>
<CopyButton
text={result.output}
tooltip={t('copyDataUri')}
color="info"
showMessage={() => {}}
/>
</Stack>
</Stack>
<Box
sx={{
fontFamily: 'monospace',
fontSize: '0.75rem',
wordBreak: 'break-all',
maxHeight: 200,
overflowY: 'auto',
lineHeight: 1.6,
color: 'info.main',
fontWeight: 600,
}}
>
{result.output.length > 2000
? `${result.output.substring(0, 2000)}...`
: result.output}
</Box>
<Stack direction="row" spacing={2} sx={{ mt: 1 }}>
<Typography variant="caption" color="text.disabled">
{t('originalSize')}: {formatFileSize(result.originalBytes)}
</Typography>
<Typography variant="caption" color="text.disabled">
{t('encodedSize')}: {formatFileSize(result.outputBytes)}
</Typography>
</Stack>
</Paper>
)}
{info && (
<Button
variant="text"
onClick={handleClear}
startIcon={<DeleteOutlineIcon />}
sx={{ borderRadius: 3 }}
>
{t('clear')}
</Button>
)}
</>
)}
{direction === 'decode' && (
<>
<TextInputArea
placeholder={t('decodeBase64Placeholder')}
value={decodeInput}
onChange={(v) => {
setDecodeInput(v);
setError(null);
}}
actions={actions}
externalError={error || undefined}
onClear={() => {
setDecoded(null);
setDecodedFileName('');
}}
/>
{decoded && (
<DecodeResultPaper
title={t('decodedImageOutput')}
mimeType={decoded.mimeType}
blobSize={decoded.blob.size}
fileName={decodedFileName}
onFileNameChange={setDecodedFileName}
onDownload={handleDownload}
>
<Box
component="img"
src={`data:${decoded.mimeType};base64,${decoded.rawBase64}`}
alt="decoded preview"
sx={{
maxWidth: '100%',
maxHeight: 160,
borderRadius: 2,
objectFit: 'contain',
mb: 1.5,
}}
/>
</DecodeResultPaper>
)}
</>
)}
</>
);
}
+143
View File
@@ -0,0 +1,143 @@
import { useCallback, useMemo, useState } from 'react';
import { Alert, alpha, Button, Paper, Stack, Typography } from '@mui/material';
import TextInputArea, { type ToolbarAction } from '@/components/TextInputArea';
import SwapHorizIcon from '@mui/icons-material/SwapHoriz';
import { useTranslation } from 'react-i18next';
import CopyButton from '@/components/CopyButton';
import { textToBase64, base64ToText } from '@/utils/base64Converter';
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
const IMAGE_DATA_URI_PATTERN = /^\s*data:image\//i;
const ERROR_MESSAGE_TO_I18N: Record<string, string> = {
'Invalid Base64 string': 'invalidBase64',
'Input appears to be binary data (e.g. an image). Please use the Image tab instead.':
'binaryDataDetected',
};
interface TextModeProps {
onSwitchToImageMode?: () => void;
}
export default function TextMode({ onSwitchToImageMode }: TextModeProps = {}) {
const { t } = useTranslation('base64Converter');
const [input, setInput] = useState('');
const [output, setOutput] = useState('');
const [error, setError] = useState<string | null>(null);
const [direction, setDirection] = useState<'encode' | 'decode'>('encode');
const actionLabel = direction === 'encode' ? t('encode') : t('decode');
const placeholder =
direction === 'encode' ? t('textInputPlaceholder') : t('base64InputPlaceholder');
const outputLabel = direction === 'encode' ? t('base64Output') : t('textOutput');
const showImageHint = useMemo(
() => direction === 'decode' && IMAGE_DATA_URI_PATTERN.test(input),
[direction, input],
);
const handleDirectionChange = useCallback(
(value: 'encode' | 'decode') => {
if (value === direction) return;
setDirection(value);
setOutput('');
setError(null);
},
[direction],
);
const actions: ToolbarAction[] = useMemo(
() => [
{
key: 'convert',
label: actionLabel,
icon: <SwapHorizIcon />,
type: 'primary',
position: 'bottom',
disabled: (value: string) => !value.trim(),
onClick: (value: string) => {
setError(null);
try {
if (direction === 'encode') {
const result = textToBase64(value);
setOutput(result.output);
} else {
const decoded = base64ToText(value);
setOutput(decoded);
}
} catch (e) {
const message = e instanceof Error ? e.message : '';
const i18nKey = ERROR_MESSAGE_TO_I18N[message];
setError(i18nKey ? t(i18nKey) : message || t('conversionFailed'));
}
},
},
],
[direction, t, actionLabel],
);
return (
<>
<SwitchButtonGroup
value={direction}
options={[
{ value: 'encode', label: t('encode') },
{ value: 'decode', label: t('decode') },
]}
onChange={handleDirectionChange}
size="small"
/>
<TextInputArea
placeholder={placeholder}
value={input}
onChange={(v) => {
setInput(v);
setError(null);
}}
actions={actions}
externalError={error || undefined}
onClear={() => setOutput('')}
/>
{showImageHint && (
<Alert
severity="info"
action={
<Button color="info" size="small" onClick={onSwitchToImageMode}>
{t('switchToImageMode')}
</Button>
}
>
{t('imageDataUriHint')}
</Alert>
)}
{output && (
<Paper
elevation={0}
sx={{
p: 2,
borderRadius: 3,
bgcolor: (theme) => alpha(theme.palette.info.main, 0.04),
border: '1px solid',
borderColor: (theme) => alpha(theme.palette.info.main, 0.15),
}}
>
<Stack direction="row" justifyContent="space-between" alignItems="center" sx={{ mb: 1 }}>
<Typography variant="caption" fontWeight={700} color="text.secondary">
{outputLabel}
</Typography>
<CopyButton text={output} showMessage={(_msg, _opts) => {}} />
</Stack>
<TextInputArea
readOnly
value={output.length > 2000 ? `${output.substring(0, 2000)}...` : output}
showClear={false}
showCount
/>
</Paper>
)}
</>
);
}
@@ -0,0 +1,207 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
import FileMode from '../FileMode';
// Mock CopyButton
vi.mock('@/components/CopyButton', () => ({
default: ({ text, tooltip }: { text: string; tooltip?: string }) => (
<button data-testid="copy-button" data-tooltip={tooltip}>
{text.slice(0, 20)}
</button>
),
}));
beforeEach(() => {
localStorage.clear();
});
// useStorageState's async loadState may overwrite user toggle if we click before the
// initial chrome.storage read settles. Flush pending microtasks first.
const waitForStorageReady = () => act(() => Promise.resolve());
describe('FileMode', () => {
it('应该渲染文件上传区域', () => {
render(<FileMode />);
expect(screen.getByText('clickOrDropToFile')).toBeInTheDocument();
expect(screen.getByText('maxFileSize')).toBeInTheDocument();
});
it('应该处理有效的文件选择', async () => {
render(<FileMode />);
const file = new File(['test content'], 'test.txt', { type: 'text/plain' });
// 文件输入是隐藏的,直接触发 change 事件
const hiddenInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(hiddenInput, { target: { files: [file] } });
await waitFor(() => {
expect(screen.getByText('test.txt')).toBeInTheDocument();
expect(screen.getByText('base64Output')).toBeInTheDocument();
});
});
it('应该拒绝超出大小限制的文件', async () => {
render(<FileMode />);
// 创建一个超过 10MB 的文件
const largeContent = new Uint8Array(11 * 1024 * 1024);
const file = new File([largeContent], 'large.bin', { type: 'application/octet-stream' });
const hiddenInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(hiddenInput, { target: { files: [file] } });
await waitFor(() => {
expect(screen.getByRole('alert')).toHaveTextContent('fileSizeExceeded');
});
});
it('点击清除按钮应该清空文件状态', async () => {
render(<FileMode />);
const file = new File(['test'], 'test.txt', { type: 'text/plain' });
const hiddenInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(hiddenInput, { target: { files: [file] } });
await waitFor(() => {
expect(screen.getByText('test.txt')).toBeInTheDocument();
});
fireEvent.click(screen.getByText('clear'));
await waitFor(() => {
expect(screen.queryByText('test.txt')).not.toBeInTheDocument();
expect(screen.getByText('clickOrDropToFile')).toBeInTheDocument();
});
});
it('应该显示文件大小和类型信息', async () => {
render(<FileMode />);
const file = new File(['test content'], 'test.txt', { type: 'text/plain' });
const hiddenInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(hiddenInput, { target: { files: [file] } });
await waitFor(() => {
expect(screen.getByText('test.txt')).toBeInTheDocument();
});
// 文件类型显示在 caption 中,格式为 "size · type"
expect(screen.getByText(/test\.txt/)).toBeInTheDocument();
});
it('应该显示原始大小和编码大小', async () => {
render(<FileMode />);
const file = new File(['test content'], 'test.txt', { type: 'text/plain' });
const hiddenInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(hiddenInput, { target: { files: [file] } });
await waitFor(() => {
expect(screen.getByText(/originalSize/)).toBeInTheDocument();
expect(screen.getByText(/encodedSize/)).toBeInTheDocument();
});
});
it('应该提供复制按钮', async () => {
render(<FileMode />);
const file = new File(['test'], 'test.txt', { type: 'text/plain' });
const hiddenInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(hiddenInput, { target: { files: [file] } });
await waitFor(() => {
const copyButtons = screen.getAllByTestId('copy-button');
expect(copyButtons.length).toBeGreaterThanOrEqual(2);
});
});
it('应该渲染 encode/decode 切换按钮', () => {
render(<FileMode />);
expect(screen.getAllByText('encode').length).toBeGreaterThanOrEqual(1);
expect(screen.getByText('decode')).toBeInTheDocument();
});
it('切到 decode 应该显示 Base64 输入框', async () => {
render(<FileMode />);
await waitForStorageReady();
fireEvent.click(screen.getByText('decode'));
expect(await screen.findByPlaceholderText('decodeBase64Placeholder')).toBeInTheDocument();
});
it('解码 PDF Base64 后应该显示 application/pdf 与默认文件名 decoded.pdf', async () => {
render(<FileMode />);
await waitForStorageReady();
fireEvent.click(screen.getByText('decode'));
const input = await screen.findByPlaceholderText('decodeBase64Placeholder');
fireEvent.change(input, { target: { value: 'JVBERi0K' } });
fireEvent.click(screen.getAllByText('decode')[1]);
await waitFor(() => {
expect(screen.getByText('decodedFileOutput')).toBeInTheDocument();
expect(screen.getByText(/application\/pdf/)).toBeInTheDocument();
expect(screen.getByDisplayValue('decoded.pdf')).toBeInTheDocument();
});
});
it('解码后的文件名应该可编辑', async () => {
render(<FileMode />);
await waitForStorageReady();
fireEvent.click(screen.getByText('decode'));
const input = await screen.findByPlaceholderText('decodeBase64Placeholder');
fireEvent.change(input, { target: { value: 'JVBERi0K' } });
fireEvent.click(screen.getAllByText('decode')[1]);
const filenameInput = (await screen.findByDisplayValue('decoded.pdf')) as HTMLInputElement;
fireEvent.change(filenameInput, { target: { value: 'my-report.pdf' } });
expect(filenameInput.value).toBe('my-report.pdf');
});
it('解码后应该显示下载按钮', async () => {
render(<FileMode />);
await waitForStorageReady();
fireEvent.click(screen.getByText('decode'));
const input = await screen.findByPlaceholderText('decodeBase64Placeholder');
fireEvent.change(input, { target: { value: 'JVBERi0K' } });
fireEvent.click(screen.getAllByText('decode')[1]);
expect(await screen.findByText('download')).toBeInTheDocument();
});
it('解码非法 Base64 应该显示 invalidBase64 错误', async () => {
render(<FileMode />);
await waitForStorageReady();
fireEvent.click(screen.getByText('decode'));
const input = await screen.findByPlaceholderText('decodeBase64Placeholder');
fireEvent.change(input, { target: { value: '!!!not base64' } });
fireEvent.click(screen.getAllByText('decode')[1]);
await waitFor(() => {
expect(screen.getByText('invalidBase64')).toBeInTheDocument();
});
});
it('切换方向时应该清空解码状态', async () => {
render(<FileMode />);
await waitForStorageReady();
fireEvent.click(screen.getByText('decode'));
const input = await screen.findByPlaceholderText('decodeBase64Placeholder');
fireEvent.change(input, { target: { value: 'JVBERi0K' } });
fireEvent.click(screen.getAllByText('decode')[1]);
await waitFor(() => {
expect(screen.getByText('decodedFileOutput')).toBeInTheDocument();
});
fireEvent.click(screen.getAllByText('encode')[0]);
await waitFor(() => {
expect(screen.queryByText('decodedFileOutput')).not.toBeInTheDocument();
});
});
});
@@ -0,0 +1,161 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
import ImageMode from '../ImageMode';
// Mock CopyButton
vi.mock('@/components/CopyButton', () => ({
default: ({ text, tooltip }: { text: string; tooltip?: string }) => (
<button data-testid="copy-button" data-tooltip={tooltip}>
{text.slice(0, 20)}
</button>
),
}));
beforeEach(() => {
localStorage.clear();
});
const waitForStorageReady = () => act(() => Promise.resolve());
describe('ImageMode', () => {
it('应该渲染图像上传区域', () => {
render(<ImageMode />);
expect(screen.getByText('clickOrDropToImage')).toBeInTheDocument();
expect(screen.getByText('supportedFormats')).toBeInTheDocument();
});
it('应该接受有效的图像文件', async () => {
render(<ImageMode />);
const file = new File(['fake-image-data'], 'test.png', { type: 'image/png' });
const hiddenInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(hiddenInput, { target: { files: [file] } });
await waitFor(() => {
expect(screen.getByText('test.png')).toBeInTheDocument();
expect(screen.getByText('base64Output')).toBeInTheDocument();
});
});
it('应该拒绝非图像文件', async () => {
render(<ImageMode />);
const file = new File(['not an image'], 'test.txt', { type: 'text/plain' });
const hiddenInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(hiddenInput, { target: { files: [file] } });
await waitFor(() => {
expect(screen.getByRole('alert')).toHaveTextContent('unsupportedImageType');
});
});
it('应该拒绝超出大小限制的图像', async () => {
render(<ImageMode />);
const largeContent = new Uint8Array(11 * 1024 * 1024);
const file = new File([largeContent], 'large.png', { type: 'image/png' });
const hiddenInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(hiddenInput, { target: { files: [file] } });
await waitFor(() => {
expect(screen.getByRole('alert')).toHaveTextContent('fileSizeExceeded');
});
});
it('应该通过扩展名识别图像', async () => {
render(<ImageMode />);
// 没有 MIME 类型但有正确扩展名
const file = new File(['fake'], 'test.jpg');
const hiddenInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(hiddenInput, { target: { files: [file] } });
await waitFor(() => {
expect(screen.getByText('test.jpg')).toBeInTheDocument();
});
});
it('点击清除按钮应该清空图像状态', async () => {
render(<ImageMode />);
const file = new File(['fake'], 'test.png', { type: 'image/png' });
const hiddenInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(hiddenInput, { target: { files: [file] } });
await waitFor(() => {
expect(screen.getByText('test.png')).toBeInTheDocument();
});
fireEvent.click(screen.getByText('clear'));
await waitFor(() => {
expect(screen.queryByText('test.png')).not.toBeInTheDocument();
expect(screen.getByText('clickOrDropToImage')).toBeInTheDocument();
});
});
it('应该显示图像预览', async () => {
render(<ImageMode />);
const file = new File(['fake-image'], 'test.png', { type: 'image/png' });
const hiddenInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fireEvent.change(hiddenInput, { target: { files: [file] } });
await waitFor(() => {
const img = screen.getByAltText('preview');
expect(img).toBeInTheDocument();
expect(img.tagName.toLowerCase()).toBe('img');
});
});
it('应该渲染 encode/decode 切换按钮', async () => {
render(<ImageMode />);
await waitForStorageReady();
expect(screen.getAllByText('encode').length).toBeGreaterThanOrEqual(1);
expect(screen.getByText('decode')).toBeInTheDocument();
});
it('解码 PNG Base64 后应该显示图像预览', async () => {
render(<ImageMode />);
await waitForStorageReady();
fireEvent.click(screen.getByText('decode'));
const input = await screen.findByPlaceholderText('decodeBase64Placeholder');
fireEvent.change(input, { target: { value: 'iVBORw0KGgo=' } });
fireEvent.click(screen.getAllByText('decode')[1]);
await waitFor(() => {
expect(screen.getByText('decodedImageOutput')).toBeInTheDocument();
const img = screen.getByAltText('decoded preview');
expect(img).toBeInTheDocument();
expect(img.tagName.toLowerCase()).toBe('img');
});
});
it('解码后默认文件名应该为 decoded.png', async () => {
render(<ImageMode />);
await waitForStorageReady();
fireEvent.click(screen.getByText('decode'));
const input = await screen.findByPlaceholderText('decodeBase64Placeholder');
fireEvent.change(input, { target: { value: 'iVBORw0KGgo=' } });
fireEvent.click(screen.getAllByText('decode')[1]);
expect(await screen.findByDisplayValue('decoded.png')).toBeInTheDocument();
});
it('解码非法 Base64 应该显示 invalidBase64 错误', async () => {
render(<ImageMode />);
await waitForStorageReady();
fireEvent.click(screen.getByText('decode'));
const input = await screen.findByPlaceholderText('decodeBase64Placeholder');
fireEvent.change(input, { target: { value: '!!!not base64' } });
fireEvent.click(screen.getAllByText('decode')[1]);
await waitFor(() => {
expect(screen.getByText('invalidBase64')).toBeInTheDocument();
});
});
});
@@ -0,0 +1,182 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
import TextMode from '../TextMode';
// Mock CopyButton
vi.mock('@/components/CopyButton', () => ({
default: ({ text }: { text: string }) => <button data-testid="copy-button">{text}</button>,
}));
describe('TextMode', () => {
it('应该渲染编码/解码切换按钮', () => {
render(<TextMode />);
expect(screen.getAllByText('encode').length).toBeGreaterThanOrEqual(1);
expect(screen.getByText('decode')).toBeInTheDocument();
});
it('应该渲染输入框和转换按钮', () => {
render(<TextMode />);
expect(screen.getByPlaceholderText('textInputPlaceholder')).toBeInTheDocument();
});
it('应该将文本编码为 Base64', async () => {
render(<TextMode />);
const input = screen.getByPlaceholderText('textInputPlaceholder');
fireEvent.change(input, { target: { value: 'Hello' } });
const convertBtn = screen.getAllByText('encode')[1];
fireEvent.click(convertBtn);
await waitFor(() => {
expect(screen.getByText('base64Output')).toBeInTheDocument();
});
// 输出内容在 CopyButton 的 data-testid 中
expect(screen.getByTestId('copy-button')).toHaveTextContent('SGVsbG8=');
});
it('应该解码 Base64 文本', async () => {
render(<TextMode />);
// 切换到解码模式
fireEvent.click(screen.getByText('decode'));
const input = screen.getByPlaceholderText('base64InputPlaceholder');
fireEvent.change(input, { target: { value: 'SGVsbG8=' } });
const convertBtn = screen.getAllByText('decode')[1];
fireEvent.click(convertBtn);
await waitFor(() => {
expect(screen.getByText('textOutput')).toBeInTheDocument();
});
expect(screen.getByTestId('copy-button')).toHaveTextContent('Hello');
});
it('应该对无效 Base64 显示错误', async () => {
render(<TextMode />);
// 切换到解码模式
fireEvent.click(screen.getByText('decode'));
const input = screen.getByPlaceholderText('base64InputPlaceholder');
fireEvent.change(input, { target: { value: 'invalid!!!' } });
const convertBtn = screen.getAllByText('decode')[1];
fireEvent.click(convertBtn);
await waitFor(() => {
expect(screen.getByText('invalidBase64')).toBeInTheDocument();
});
});
it('切换方向时应该清除输出', async () => {
render(<TextMode />);
// 先编码
const input = screen.getByPlaceholderText('textInputPlaceholder');
fireEvent.change(input, { target: { value: 'Hello' } });
fireEvent.click(screen.getAllByText('encode')[1]);
await waitFor(() => {
expect(screen.getByTestId('copy-button')).toHaveTextContent('SGVsbG8=');
});
// 切换方向
await act(async () => {
fireEvent.click(screen.getByText('decode'));
});
// 输出应该被清除
await waitFor(() => {
expect(screen.queryByTestId('copy-button')).not.toBeInTheDocument();
});
});
it('点击清除按钮应该清空所有内容', async () => {
render(<TextMode />);
const input = screen.getByPlaceholderText('textInputPlaceholder');
fireEvent.change(input, { target: { value: 'Hello' } });
fireEvent.click(screen.getAllByText('encode')[1]);
await waitFor(() => {
expect(screen.getByTestId('copy-button')).toHaveTextContent('SGVsbG8=');
});
fireEvent.click(screen.getByRole('button', { name: 'textInputArea.clear' }));
await waitFor(() => {
expect(screen.queryByTestId('copy-button')).not.toBeInTheDocument();
expect(input).toHaveValue('');
});
});
it('空输入时转换按钮应该禁用', () => {
render(<TextMode />);
const convertBtn = screen.getAllByText('encode')[1];
expect(convertBtn).toBeDisabled();
});
it('输入非空时转换按钮应该启用', () => {
render(<TextMode />);
const input = screen.getByPlaceholderText('textInputPlaceholder');
fireEvent.change(input, { target: { value: 'Hello' } });
const convertBtn = screen.getAllByText('encode')[1];
expect(convertBtn).not.toBeDisabled();
});
it('解码模式下粘贴图片 data URI 时应该显示切换图像模式的提示', () => {
render(<TextMode />);
fireEvent.click(screen.getByText('decode'));
const input = screen.getByPlaceholderText('base64InputPlaceholder');
fireEvent.change(input, {
target: { value: 'data:image/png;base64,iVBORw0KGgo=' },
});
expect(screen.getByText('imageDataUriHint')).toBeInTheDocument();
expect(screen.getByText('switchToImageMode')).toBeInTheDocument();
});
it('粘贴非图片 data URI 时不应该显示图像模式提示', () => {
render(<TextMode />);
fireEvent.click(screen.getByText('decode'));
const input = screen.getByPlaceholderText('base64InputPlaceholder');
fireEvent.change(input, { target: { value: 'SGVsbG8=' } });
expect(screen.queryByText('imageDataUriHint')).not.toBeInTheDocument();
});
it('点击切换图像模式按钮应该调用 onSwitchToImageMode 回调', () => {
const onSwitch = vi.fn();
render(<TextMode onSwitchToImageMode={onSwitch} />);
fireEvent.click(screen.getByText('decode'));
const input = screen.getByPlaceholderText('base64InputPlaceholder');
fireEvent.change(input, {
target: { value: 'data:image/png;base64,iVBORw0KGgo=' },
});
fireEvent.click(screen.getByText('switchToImageMode'));
expect(onSwitch).toHaveBeenCalledTimes(1);
});
it('解码模式下对二进制数据应该显示更清晰的错误', async () => {
render(<TextMode />);
fireEvent.click(screen.getByText('decode'));
const input = screen.getByPlaceholderText('base64InputPlaceholder');
fireEvent.change(input, { target: { value: 'iVBORw0KGgo=' } });
const convertBtn = screen.getAllByText('decode')[1];
fireEvent.click(convertBtn);
await waitFor(() => {
expect(screen.getByText('binaryDataDetected')).toBeInTheDocument();
});
});
});
@@ -0,0 +1,50 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import Base64ConverterPage from '../index';
// Mock 子组件
vi.mock('../TextMode', () => ({
default: () => <div data-testid="text-mode">TextMode</div>,
}));
vi.mock('../FileMode', () => ({
default: () => <div data-testid="file-mode">FileMode</div>,
}));
vi.mock('../ImageMode', () => ({
default: () => <div data-testid="image-mode">ImageMode</div>,
}));
describe('Base64ConverterPage', () => {
it('应该默认渲染文本模式', () => {
render(<Base64ConverterPage />);
expect(screen.getByTestId('text-mode')).toBeInTheDocument();
});
it('应该渲染模式切换按钮', () => {
render(<Base64ConverterPage />);
expect(screen.getByText('base64Converter:textMode')).toBeInTheDocument();
expect(screen.getByText('base64Converter:fileMode')).toBeInTheDocument();
expect(screen.getByText('base64Converter:imageMode')).toBeInTheDocument();
});
it('切换到文件模式应该渲染 FileMode', () => {
render(<Base64ConverterPage />);
fireEvent.click(screen.getByText('base64Converter:fileMode'));
expect(screen.getByTestId('file-mode')).toBeInTheDocument();
expect(screen.queryByTestId('text-mode')).not.toBeInTheDocument();
});
it('切换到图像模式应该渲染 ImageMode', () => {
render(<Base64ConverterPage />);
fireEvent.click(screen.getByText('base64Converter:imageMode'));
expect(screen.getByTestId('image-mode')).toBeInTheDocument();
expect(screen.queryByTestId('text-mode')).not.toBeInTheDocument();
});
it('应该渲染页面标题', () => {
render(<Base64ConverterPage />);
expect(screen.getByText('base64Converter:pageTitle')).toBeInTheDocument();
expect(screen.getByText('base64Converter:pageSubtitle')).toBeInTheDocument();
});
});
+19 -609
View File
@@ -1,40 +1,16 @@
import { useCallback, useRef, useState } from 'react';
import {
Alert,
alpha,
Box,
Button,
Container,
Stack,
TextField,
ToggleButton,
ToggleButtonGroup,
Typography,
CircularProgress,
Paper,
} from '@mui/material';
import { Box, Container, Stack } from '@mui/material';
import TextFieldsIcon from '@mui/icons-material/TextFields';
import UploadFileIcon from '@mui/icons-material/UploadFile';
import ImageIcon from '@mui/icons-material/Image';
import SwapHorizIcon from '@mui/icons-material/SwapHoriz';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import { useTranslation } from 'react-i18next';
import PageHeader from '@/components/PageHeader';
import CopyButton from '@/components/CopyButton';
import { base64ConverterPageStyles } from '@/config/pageTheme';
import { useStorageState } from '@/utils/useStorageState';
import type { Base64ConverterPageMode } from '@/types/storage';
import {
textToBase64,
base64ToText,
fileToBase64,
isFileSizeValid,
isSupportedImageType,
isSupportedImageExtension,
formatFileSize,
MAX_FILE_SIZE,
} from '@/utils/base64Converter';
import type { FileToBase64Result } from '@/utils/base64Converter';
import TextMode from './TextMode';
import FileMode from './FileMode';
import ImageMode from './ImageMode';
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
const VALID_PAGE_MODES: readonly Base64ConverterPageMode[] = ['text', 'file', 'image'];
@@ -43,13 +19,6 @@ const isValidPageMode = (val: unknown): val is Base64ConverterPageMode =>
type PageMode = Base64ConverterPageMode;
/** 文件信息 */
interface FileInfo {
name: string;
size: number;
type: string;
}
export default function Index() {
const { t } = useTranslation(['base64Converter']);
const [pageMode, setPageMode] = useStorageState(
@@ -58,129 +27,6 @@ export default function Index() {
isValidPageMode,
);
// 文本模式状态
const [textInput, setTextInput] = useState('');
const [textOutput, setTextOutput] = useState('');
const [textError, setTextError] = useState<string | null>(null);
const [textDirection, setTextDirection] = useState<'encode' | 'decode'>('encode');
// 文件/图像模式状态
const [fileResult, setFileResult] = useState<FileToBase64Result | null>(null);
const [fileInfo, setFileInfo] = useState<FileInfo | null>(null);
const [fileError, setFileError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isDragging, setIsDragging] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const imageInputRef = useRef<HTMLInputElement>(null);
/** 清空文本模式 */
const handleClearText = useCallback(() => {
setTextInput('');
setTextOutput('');
setTextError(null);
}, []);
/** 文本编码/解码 */
const handleTextConvert = useCallback(() => {
setTextError(null);
try {
if (textDirection === 'encode') {
const result = textToBase64(textInput);
setTextOutput(result.output);
} else {
const decoded = base64ToText(textInput);
setTextOutput(decoded);
}
} catch (e) {
setTextError(e instanceof Error ? e.message : t('base64Converter:conversionFailed'));
}
}, [textInput, textDirection, t]);
/** 处理文件选择 */
const handleFileSelect = useCallback(
async (file: File, isImageMode: boolean) => {
setFileError(null);
setFileResult(null);
setFileInfo(null);
if (!isFileSizeValid(file.size)) {
setFileError(
t('base64Converter:fileSizeExceeded', { max: `${MAX_FILE_SIZE / 1024 / 1024} MB` }),
);
return;
}
if (
isImageMode &&
!isSupportedImageType(file.type) &&
!isSupportedImageExtension(file.name)
) {
setFileError(t('base64Converter:unsupportedImageType'));
return;
}
setFileInfo({
name: file.name,
size: file.size,
type: file.type || 'application/octet-stream',
});
setIsLoading(true);
try {
const result = await fileToBase64(file);
setFileResult(result);
} catch (e) {
setFileError(e instanceof Error ? e.message : t('base64Converter:conversionFailed'));
} finally {
setIsLoading(false);
}
},
[t],
);
/** 清空文件/图像模式 */
const handleClearFile = useCallback(() => {
setFileResult(null);
setFileInfo(null);
setFileError(null);
if (fileInputRef.current) fileInputRef.current.value = '';
if (imageInputRef.current) imageInputRef.current.value = '';
}, []);
/** 拖拽处理 */
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(true);
}, []);
const handleDragLeave = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(false);
}, []);
const handleDrop = useCallback(
(e: React.DragEvent, isImageMode: boolean) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(false);
const file = e.dataTransfer.files[0];
if (file) {
handleFileSelect(file, isImageMode);
}
},
[handleFileSelect],
);
/** 页面模式元数据 */
const modeTitles: Record<PageMode, { title: string; subtitle: string }> = {
text: { title: 'base64Converter:pageTitle', subtitle: 'base64Converter:pageSubtitle' },
file: { title: 'base64Converter:pageTitle', subtitle: 'base64Converter:pageSubtitle' },
image: { title: 'base64Converter:pageTitle', subtitle: 'base64Converter:pageSubtitle' },
};
const modeIcon: Record<PageMode, React.ReactNode> = {
text: <TextFieldsIcon />,
file: <UploadFileIcon />,
@@ -191,463 +37,27 @@ export default function Index() {
<Box>
<Container sx={{ p: 2 }}>
<PageHeader
title={t(modeTitles[pageMode].title)}
subtitle={t(modeTitles[pageMode].subtitle)}
title={t('base64Converter:pageTitle')}
subtitle={t('base64Converter:pageSubtitle')}
icon={modeIcon[pageMode]}
iconColor={base64ConverterPageStyles.primaryColor}
/>
<Stack spacing={2.5}>
{/* 模式切换器 */}
<ToggleButtonGroup
size="small"
exclusive
<SwitchButtonGroup
value={pageMode}
onChange={(_, v: PageMode | null) => v && setPageMode(v)}
sx={{ borderRadius: 3, flexWrap: 'wrap', gap: 0.5 }}
>
<ToggleButton value="text" sx={{ px: 2, fontWeight: 700, fontSize: '0.75rem' }}>
{t('base64Converter:textMode')}
</ToggleButton>
<ToggleButton value="file" sx={{ px: 2, fontWeight: 700, fontSize: '0.75rem' }}>
{t('base64Converter:fileMode')}
</ToggleButton>
<ToggleButton value="image" sx={{ px: 2, fontWeight: 700, fontSize: '0.75rem' }}>
{t('base64Converter:imageMode')}
</ToggleButton>
</ToggleButtonGroup>
options={[
{ value: 'text', label: t('base64Converter:textMode') },
{ value: 'file', label: t('base64Converter:fileMode') },
{ value: 'image', label: t('base64Converter:imageMode') },
]}
onChange={(value: PageMode) => setPageMode(value)}
size="small"
/>
{/* ===== 文本模式 ===== */}
{pageMode === 'text' && (
<>
{/* 编码/解码切换 */}
<Stack direction="row" spacing={1} justifyContent="space-between" alignItems="center">
<ToggleButtonGroup
size="small"
exclusive
value={textDirection}
onChange={(_, v: 'encode' | 'decode' | null) => v && setTextDirection(v)}
sx={{ borderRadius: 3 }}
>
<ToggleButton value="encode" sx={{ px: 2, fontWeight: 700, fontSize: '0.75rem' }}>
{t('base64Converter:encode')}
</ToggleButton>
<ToggleButton value="decode" sx={{ px: 2, fontWeight: 700, fontSize: '0.75rem' }}>
{t('base64Converter:decode')}
</ToggleButton>
</ToggleButtonGroup>
<Stack direction="row" spacing={1}>
<Button
variant="text"
onClick={handleClearText}
startIcon={<DeleteOutlineIcon />}
sx={{ borderRadius: 3 }}
>
{t('base64Converter:clear')}
</Button>
<Button
variant="contained"
onClick={handleTextConvert}
disabled={!textInput.trim()}
startIcon={<SwapHorizIcon />}
sx={{ borderRadius: 3, fontWeight: 700, px: 3 }}
>
{textDirection === 'encode'
? t('base64Converter:encode')
: t('base64Converter:decode')}
</Button>
</Stack>
</Stack>
{/* 输入区 */}
<TextField
multiline
fullWidth
minRows={4}
maxRows={10}
placeholder={
textDirection === 'encode'
? t('base64Converter:textInputPlaceholder')
: t('base64Converter:base64InputPlaceholder')
}
value={textInput}
onChange={(e) => {
setTextInput(e.target.value);
setTextError(null);
}}
sx={{
'& .MuiOutlinedInput-root': {
bgcolor: 'background.paper',
borderRadius: 3,
fontSize: '0.85rem',
fontFamily: 'monospace',
transition: 'all 0.2s',
'&:hover': { bgcolor: 'action.hover' },
'&.Mui-focused': {
bgcolor: 'background.paper',
boxShadow: (theme) => `0 0 0 4px ${alpha(theme.palette.info.main, 0.1)}`,
},
},
}}
/>
{textError && <Alert severity="error">{textError}</Alert>}
{/* 输出区 */}
{textOutput && (
<Paper
elevation={0}
sx={{
p: 2,
borderRadius: 3,
bgcolor: (theme) => alpha(theme.palette.info.main, 0.04),
border: '1px solid',
borderColor: (theme) => alpha(theme.palette.info.main, 0.15),
}}
>
<Stack
direction="row"
justifyContent="space-between"
alignItems="center"
sx={{ mb: 1 }}
>
<Typography variant="caption" fontWeight={700} color="text.secondary">
{textDirection === 'encode'
? t('base64Converter:base64Output')
: t('base64Converter:textOutput')}
</Typography>
<CopyButton text={textOutput} showMessage={(_msg, _opts) => {}} />
</Stack>
<Box
sx={{
fontFamily: 'monospace',
fontSize: '0.8rem',
wordBreak: 'break-all',
maxHeight: 300,
overflowY: 'auto',
lineHeight: 1.6,
color: 'info.main',
fontWeight: 600,
}}
>
{textOutput}
</Box>
</Paper>
)}
</>
)}
{/* ===== 文件模式 ===== */}
{pageMode === 'file' && (
<>
{/* 拖拽/上传区 */}
<Box
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={(e) => handleDrop(e, false)}
onClick={() => fileInputRef.current?.click()}
sx={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
minHeight: 180,
border: '2px dashed',
borderColor: isDragging ? 'info.main' : fileInfo ? 'info.main' : 'divider',
borderRadius: 3,
p: 4,
bgcolor: (theme) =>
isDragging
? alpha(theme.palette.info.main, 0.08)
: fileInfo
? alpha(theme.palette.info.main, 0.04)
: 'action.hover',
cursor: 'pointer',
transition: 'all 0.2s',
'&:hover': {
borderColor: 'info.main',
bgcolor: (theme) => alpha(theme.palette.info.main, 0.04),
},
}}
>
<input
ref={fileInputRef}
type="file"
hidden
onChange={(e) => {
const file = e.target.files?.[0];
if (file) handleFileSelect(file, false);
}}
/>
{isLoading ? (
<CircularProgress size={40} />
) : fileInfo ? (
<Stack spacing={1} alignItems="center">
<UploadFileIcon sx={{ fontSize: 40, color: 'info.main' }} />
<Typography variant="body2" fontWeight={700}>
{fileInfo.name}
</Typography>
<Typography variant="caption" color="text.secondary">
{formatFileSize(fileInfo.size)} · {fileInfo.type}
</Typography>
<Typography variant="caption" color="text.disabled">
{t('base64Converter:clickOrDropToReplace')}
</Typography>
</Stack>
) : (
<Stack spacing={1} alignItems="center">
<UploadFileIcon sx={{ fontSize: 40, color: 'text.disabled' }} />
<Typography variant="body2" color="text.secondary" fontWeight={600}>
{t('base64Converter:clickOrDropToFile')}
</Typography>
<Typography variant="caption" color="text.disabled">
{t('base64Converter:maxFileSize', {
max: `${MAX_FILE_SIZE / 1024 / 1024} MB`,
})}
</Typography>
</Stack>
)}
</Box>
{fileError && <Alert severity="error">{fileError}</Alert>}
{/* 文件转换结果 */}
{fileResult && (
<Paper
elevation={0}
sx={{
p: 2,
borderRadius: 3,
bgcolor: (theme) => alpha(theme.palette.info.main, 0.04),
border: '1px solid',
borderColor: (theme) => alpha(theme.palette.info.main, 0.15),
}}
>
<Stack
direction="row"
justifyContent="space-between"
alignItems="center"
sx={{ mb: 1 }}
>
<Typography variant="caption" fontWeight={700} color="text.secondary">
{t('base64Converter:base64Output')}
</Typography>
<Stack direction="row" spacing={1}>
<CopyButton
text={fileResult.rawBase64}
tooltip={t('base64Converter:copyRaw')}
showMessage={() => {}}
/>
<CopyButton
text={fileResult.output}
tooltip={t('base64Converter:copyDataUri')}
color="info"
showMessage={() => {}}
/>
</Stack>
</Stack>
<Box
sx={{
fontFamily: 'monospace',
fontSize: '0.75rem',
wordBreak: 'break-all',
maxHeight: 200,
overflowY: 'auto',
lineHeight: 1.6,
color: 'info.main',
fontWeight: 600,
}}
>
{fileResult.output.length > 2000
? `${fileResult.output.substring(0, 2000)}...`
: fileResult.output}
</Box>
<Stack direction="row" spacing={2} sx={{ mt: 1 }}>
<Typography variant="caption" color="text.disabled">
{t('base64Converter:originalSize')}:{' '}
{formatFileSize(fileResult.originalBytes)}
</Typography>
<Typography variant="caption" color="text.disabled">
{t('base64Converter:encodedSize')}: {formatFileSize(fileResult.outputBytes)}
</Typography>
</Stack>
</Paper>
)}
{fileInfo && (
<Button
variant="text"
onClick={handleClearFile}
startIcon={<DeleteOutlineIcon />}
sx={{ borderRadius: 3 }}
>
{t('base64Converter:clear')}
</Button>
)}
</>
)}
{/* ===== 图像模式 ===== */}
{pageMode === 'image' && (
<>
{/* 拖拽/上传区 */}
<Box
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={(e) => handleDrop(e, true)}
onClick={() => imageInputRef.current?.click()}
sx={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
minHeight: 180,
border: '2px dashed',
borderColor: isDragging ? 'info.main' : fileInfo ? 'info.main' : 'divider',
borderRadius: 3,
p: 4,
bgcolor: (theme) =>
isDragging
? alpha(theme.palette.info.main, 0.08)
: fileInfo
? alpha(theme.palette.info.main, 0.04)
: 'action.hover',
cursor: 'pointer',
transition: 'all 0.2s',
'&:hover': {
borderColor: 'info.main',
bgcolor: (theme) => alpha(theme.palette.info.main, 0.04),
},
}}
>
<input
ref={imageInputRef}
type="file"
accept="image/*"
hidden
onChange={(e) => {
const file = e.target.files?.[0];
if (file) handleFileSelect(file, true);
}}
/>
{isLoading ? (
<CircularProgress size={40} />
) : fileInfo ? (
<Stack spacing={1} alignItems="center">
{fileResult && (
<Box
component="img"
src={fileResult.output}
alt="preview"
sx={{
maxWidth: '100%',
maxHeight: 160,
borderRadius: 2,
objectFit: 'contain',
}}
/>
)}
<Typography variant="body2" fontWeight={700}>
{fileInfo.name}
</Typography>
<Typography variant="caption" color="text.secondary">
{formatFileSize(fileInfo.size)} · {fileInfo.type}
</Typography>
<Typography variant="caption" color="text.disabled">
{t('base64Converter:clickOrDropToReplace')}
</Typography>
</Stack>
) : (
<Stack spacing={1} alignItems="center">
<ImageIcon sx={{ fontSize: 40, color: 'text.disabled' }} />
<Typography variant="body2" color="text.secondary" fontWeight={600}>
{t('base64Converter:clickOrDropToImage')}
</Typography>
<Typography variant="caption" color="text.disabled">
{t('base64Converter:supportedFormats')}
</Typography>
</Stack>
)}
</Box>
{fileError && <Alert severity="error">{fileError}</Alert>}
{/* 图像转换结果 */}
{fileResult && (
<Paper
elevation={0}
sx={{
p: 2,
borderRadius: 3,
bgcolor: (theme) => alpha(theme.palette.info.main, 0.04),
border: '1px solid',
borderColor: (theme) => alpha(theme.palette.info.main, 0.15),
}}
>
<Stack
direction="row"
justifyContent="space-between"
alignItems="center"
sx={{ mb: 1 }}
>
<Typography variant="caption" fontWeight={700} color="text.secondary">
{t('base64Converter:base64Output')}
</Typography>
<Stack direction="row" spacing={1}>
<CopyButton
text={fileResult.rawBase64}
tooltip={t('base64Converter:copyRaw')}
showMessage={() => {}}
/>
<CopyButton
text={fileResult.output}
tooltip={t('base64Converter:copyDataUri')}
color="info"
showMessage={() => {}}
/>
</Stack>
</Stack>
<Box
sx={{
fontFamily: 'monospace',
fontSize: '0.75rem',
wordBreak: 'break-all',
maxHeight: 200,
overflowY: 'auto',
lineHeight: 1.6,
color: 'info.main',
fontWeight: 600,
}}
>
{fileResult.output.length > 2000
? `${fileResult.output.substring(0, 2000)}...`
: fileResult.output}
</Box>
<Stack direction="row" spacing={2} sx={{ mt: 1 }}>
<Typography variant="caption" color="text.disabled">
{t('base64Converter:originalSize')}:{' '}
{formatFileSize(fileResult.originalBytes)}
</Typography>
<Typography variant="caption" color="text.disabled">
{t('base64Converter:encodedSize')}: {formatFileSize(fileResult.outputBytes)}
</Typography>
</Stack>
</Paper>
)}
{fileInfo && (
<Button
variant="text"
onClick={handleClearFile}
startIcon={<DeleteOutlineIcon />}
sx={{ borderRadius: 3 }}
>
{t('base64Converter:clear')}
</Button>
)}
</>
)}
{pageMode === 'text' && <TextMode onSwitchToImageMode={() => setPageMode('image')} />}
{pageMode === 'file' && <FileMode />}
{pageMode === 'image' && <ImageMode />}
</Stack>
</Container>
</Box>