Develop (#24)
* 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:
@@ -49,7 +49,7 @@ jobs:
|
|||||||
run: npm ci
|
run: npm ci
|
||||||
|
|
||||||
- name: Run TypeScript type check
|
- name: Run TypeScript type check
|
||||||
run: npm run compile
|
run: npm run typecheck
|
||||||
|
|
||||||
test:
|
test:
|
||||||
name: Unit Tests
|
name: Unit Tests
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ stats.html
|
|||||||
stats-*.json
|
stats-*.json
|
||||||
.wxt
|
.wxt
|
||||||
.vitest
|
.vitest
|
||||||
.claude
|
|
||||||
|
|
||||||
# Editor directories and files
|
# Editor directories and files
|
||||||
.vscode/*
|
.vscode/*
|
||||||
|
|||||||
@@ -45,15 +45,14 @@ export const CopyButton: React.FC<CopyButtonProps> = ({
|
|||||||
|
|
||||||
const handleCopy = async () => {
|
const handleCopy = async () => {
|
||||||
if (text) {
|
if (text) {
|
||||||
await copyTextToClipboard(text)
|
const success = await copyTextToClipboard(text);
|
||||||
.then(() => {
|
if (success) {
|
||||||
showMessage?.('复制成功', { severity: 'success' });
|
showMessage?.('复制成功', { severity: 'success' });
|
||||||
setCopied(true);
|
setCopied(true);
|
||||||
setTimeout(() => setCopied(false), 1500);
|
setTimeout(() => setCopied(false), 1500);
|
||||||
})
|
} else {
|
||||||
.catch(() => {
|
|
||||||
showMessage?.('复制失败', { severity: 'error' });
|
showMessage?.('复制失败', { severity: 'error' });
|
||||||
});
|
}
|
||||||
} else {
|
} else {
|
||||||
showMessage?.('无内容可复制', { severity: 'error' });
|
showMessage?.('无内容可复制', { severity: 'error' });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
/**
|
||||||
|
* DecodeResultPaper
|
||||||
|
*
|
||||||
|
* FileMode 与 ImageMode 通用的 decode 结果展示组件。
|
||||||
|
* 提取了二者 decode 输出区完全一致的 Paper 结构:
|
||||||
|
* 标题 → 可选预览(children)→ 文件信息 → 文件名输入 → 下载按钮
|
||||||
|
*
|
||||||
|
* FileMode 直接使用,ImageMode 通过 children 传入图片预览。
|
||||||
|
*/
|
||||||
|
import { alpha, Button, Paper, Stack, TextField, Typography } from '@mui/material';
|
||||||
|
import DownloadIcon from '@mui/icons-material/Download';
|
||||||
|
import { formatFileSize } from '@/utils/base64Converter';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
|
interface DecodeResultPaperProps {
|
||||||
|
/** 标题文案,由调用方传入 i18n key 对应的值(如 decodedFileOutput / decodedImageOutput) */
|
||||||
|
title: string;
|
||||||
|
/** 解码后推断的 MIME 类型 */
|
||||||
|
mimeType: string;
|
||||||
|
/** 解码后 Blob 的大小(字节) */
|
||||||
|
blobSize: number;
|
||||||
|
/** 当前文件名 */
|
||||||
|
fileName: string;
|
||||||
|
/** 文件名变更回调 */
|
||||||
|
onFileNameChange: (name: string) => void;
|
||||||
|
/** 下载按钮点击回调 */
|
||||||
|
onDownload: () => void;
|
||||||
|
/** 可选的预览内容,ImageMode 用于渲染图片预览 */
|
||||||
|
children?: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DecodeResultPaper({
|
||||||
|
title,
|
||||||
|
mimeType,
|
||||||
|
blobSize,
|
||||||
|
fileName,
|
||||||
|
onFileNameChange,
|
||||||
|
onDownload,
|
||||||
|
children,
|
||||||
|
}: DecodeResultPaperProps) {
|
||||||
|
const { t } = useTranslation('base64Converter');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<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),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* 标题 */}
|
||||||
|
<Typography
|
||||||
|
variant="caption"
|
||||||
|
fontWeight={700}
|
||||||
|
color="text.secondary"
|
||||||
|
sx={{ mb: 1, display: 'block' }}
|
||||||
|
>
|
||||||
|
{title}
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
{/* 可选预览内容(ImageMode 的图片) */}
|
||||||
|
{children}
|
||||||
|
|
||||||
|
{/* 文件信息 */}
|
||||||
|
<Stack direction="row" spacing={2} sx={{ mb: 1.5 }}>
|
||||||
|
<Typography variant="caption" color="text.disabled">
|
||||||
|
{t('inferredMimeType')}: {mimeType}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="caption" color="text.disabled">
|
||||||
|
{t('decodedSize')}: {formatFileSize(blobSize)}
|
||||||
|
</Typography>
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
{/* 文件名输入 */}
|
||||||
|
<TextField
|
||||||
|
size="small"
|
||||||
|
fullWidth
|
||||||
|
label={t('decodedFileName')}
|
||||||
|
value={fileName}
|
||||||
|
onChange={(e) => onFileNameChange(e.target.value)}
|
||||||
|
sx={{ mb: 1.5 }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* 下载按钮 */}
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
onClick={onDownload}
|
||||||
|
startIcon={<DownloadIcon />}
|
||||||
|
disabled={!fileName.trim()}
|
||||||
|
sx={{ borderRadius: 3, fontWeight: 700 }}
|
||||||
|
>
|
||||||
|
{t('download')}
|
||||||
|
</Button>
|
||||||
|
</Paper>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -30,6 +30,12 @@ export class ErrorBoundary extends Component<Props, State> {
|
|||||||
console.error('Uncaught error:', error, errorInfo);
|
console.error('Uncaught error:', error, errorInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
componentDidUpdate(prevProps: Props) {
|
||||||
|
if (this.state.hasError && prevProps.children !== this.props.children) {
|
||||||
|
this.setState({ hasError: false, error: null });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private handleReset = () => {
|
private handleReset = () => {
|
||||||
window.location.reload();
|
window.location.reload();
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -145,6 +145,7 @@ export function GlobalSnackbar({
|
|||||||
onClose,
|
onClose,
|
||||||
severity = defaultProps.severity,
|
severity = defaultProps.severity,
|
||||||
autoHideDuration = defaultProps.autoHideDuration,
|
autoHideDuration = defaultProps.autoHideDuration,
|
||||||
|
anchorOrigin = defaultProps.anchorOrigin,
|
||||||
showAlert = defaultProps.showAlert,
|
showAlert = defaultProps.showAlert,
|
||||||
hideIcon = defaultProps.hideIcon,
|
hideIcon = defaultProps.hideIcon,
|
||||||
}: GlobalSnackbarProps): JSX.Element {
|
}: GlobalSnackbarProps): JSX.Element {
|
||||||
@@ -154,7 +155,7 @@ export function GlobalSnackbar({
|
|||||||
open={open}
|
open={open}
|
||||||
autoHideDuration={autoHideDuration}
|
autoHideDuration={autoHideDuration}
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
|
anchorOrigin={anchorOrigin}
|
||||||
disableWindowBlurListener
|
disableWindowBlurListener
|
||||||
sx={{
|
sx={{
|
||||||
zIndex: 999999,
|
zIndex: 999999,
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import { Component, ErrorInfo, ReactNode } from 'react';
|
||||||
|
import { Box, Button, Paper, Typography } from '@mui/material';
|
||||||
|
import type { Theme } from '@mui/material/styles';
|
||||||
|
import ErrorOutlineIcon from '@mui/icons-material/ErrorOutline';
|
||||||
|
import RefreshIcon from '@mui/icons-material/Refresh';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
children: ReactNode;
|
||||||
|
resetKey?: string | number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface State {
|
||||||
|
hasError: boolean;
|
||||||
|
error: Error | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 页面级错误边界组件:捕获子组件树中的 JavaScript 错误
|
||||||
|
* 与全局 ErrorBoundary 的区别:使用轻量内嵌卡片 UI,提供重试按钮
|
||||||
|
*/
|
||||||
|
export class PageErrorBoundary extends Component<Props, State> {
|
||||||
|
state: State = {
|
||||||
|
hasError: false,
|
||||||
|
error: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
static getDerivedStateFromError(error: Error): State {
|
||||||
|
return { hasError: true, error };
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
|
||||||
|
console.error('Uncaught error in page:', error, errorInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidUpdate(prevProps: Props) {
|
||||||
|
if (this.state.hasError && prevProps.resetKey !== this.props.resetKey) {
|
||||||
|
this.setState({ hasError: false, error: null });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleRetry = () => {
|
||||||
|
this.setState({ hasError: false, error: null });
|
||||||
|
};
|
||||||
|
|
||||||
|
render() {
|
||||||
|
if (this.state.hasError) {
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
flex: 1,
|
||||||
|
p: 3,
|
||||||
|
minHeight: 200,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Paper
|
||||||
|
elevation={0}
|
||||||
|
sx={{
|
||||||
|
p: 3,
|
||||||
|
textAlign: 'center',
|
||||||
|
borderRadius: 4,
|
||||||
|
border: '1px solid',
|
||||||
|
borderColor: 'error.light',
|
||||||
|
bgcolor: 'rgba(211, 47, 47, 0.04)',
|
||||||
|
maxWidth: 400,
|
||||||
|
width: '100%',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<ErrorOutlineIcon color="error" sx={{ fontSize: 48, mb: 1.5 }} />
|
||||||
|
<Typography variant="h6" fontWeight={700} gutterBottom color="error.main">
|
||||||
|
该页面加载失败
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
|
||||||
|
页面在加载或渲染时遇到错误,您可以重试或切换到其他工具。
|
||||||
|
</Typography>
|
||||||
|
{this.state.error && (
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
mb: 2,
|
||||||
|
p: 1.5,
|
||||||
|
bgcolor: (theme: Theme) =>
|
||||||
|
theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'grey.100',
|
||||||
|
borderRadius: 2,
|
||||||
|
textAlign: 'left',
|
||||||
|
maxHeight: '160px',
|
||||||
|
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.handleRetry}
|
||||||
|
sx={{ borderRadius: 2, fontWeight: 700 }}
|
||||||
|
>
|
||||||
|
重试
|
||||||
|
</Button>
|
||||||
|
</Paper>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.props.children;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default PageErrorBoundary;
|
||||||
@@ -2,6 +2,7 @@ import { Box, CircularProgress } from '@mui/material';
|
|||||||
import { FEATURES, getEntryPointType } from '@/config/features';
|
import { FEATURES, getEntryPointType } from '@/config/features';
|
||||||
import { useRouter } from '@/providers/RouterProvider';
|
import { useRouter } from '@/providers/RouterProvider';
|
||||||
import { Suspense, useMemo } from 'react';
|
import { Suspense, useMemo } from 'react';
|
||||||
|
import PageErrorBoundary from '@/components/PageErrorBoundary';
|
||||||
|
|
||||||
export default function RouterContainer() {
|
export default function RouterContainer() {
|
||||||
const { currentPage, isLoaded } = useRouter();
|
const { currentPage, isLoaded } = useRouter();
|
||||||
@@ -60,7 +61,7 @@ export default function RouterContainer() {
|
|||||||
</Box>
|
</Box>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
{Component && <Component />}
|
<PageErrorBoundary resetKey={currentPage}>{Component && <Component />}</PageErrorBoundary>
|
||||||
</Suspense>
|
</Suspense>
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import { ToggleButton, ToggleButtonGroup, type SxProps, type Theme } from '@mui/material';
|
||||||
|
|
||||||
|
export interface SwitchOption<T extends string | number = string> {
|
||||||
|
value: T;
|
||||||
|
label: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SwitchButtonGroupProps<T extends string | number = string> {
|
||||||
|
value: T;
|
||||||
|
options: SwitchOption<T>[];
|
||||||
|
onChange: (value: T) => void;
|
||||||
|
sx?: SxProps<Theme>;
|
||||||
|
size?: 'small' | 'medium' | 'large';
|
||||||
|
buttonSx?: SxProps<Theme>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function SwitchButtonGroup<T extends string | number = string>({
|
||||||
|
value,
|
||||||
|
options,
|
||||||
|
onChange,
|
||||||
|
sx,
|
||||||
|
size,
|
||||||
|
buttonSx,
|
||||||
|
}: SwitchButtonGroupProps<T>) {
|
||||||
|
return (
|
||||||
|
<ToggleButtonGroup
|
||||||
|
value={value}
|
||||||
|
exclusive
|
||||||
|
size={size}
|
||||||
|
onChange={(_, v) => v && onChange(v)}
|
||||||
|
sx={{
|
||||||
|
width: '100%',
|
||||||
|
mb: 2,
|
||||||
|
borderRadius: 4,
|
||||||
|
bgcolor: (theme: Theme) => (theme.palette.mode === 'light' ? 'grey.100' : 'grey.900'),
|
||||||
|
border: '1px solid',
|
||||||
|
borderColor: 'divider',
|
||||||
|
p: 0.6,
|
||||||
|
'& .MuiToggleButtonGroup-grouped': {
|
||||||
|
flex: 1,
|
||||||
|
border: 'none',
|
||||||
|
borderRadius: 3.5,
|
||||||
|
mx: 0.3,
|
||||||
|
fontWeight: 800,
|
||||||
|
color: 'text.secondary',
|
||||||
|
transition: 'color 0.3s',
|
||||||
|
'&:not(:first-of-type)': {
|
||||||
|
borderLeft: 'none',
|
||||||
|
marginLeft: 0.6,
|
||||||
|
},
|
||||||
|
'&.Mui-selected': {
|
||||||
|
bgcolor: 'background.paper',
|
||||||
|
color: 'primary.main',
|
||||||
|
boxShadow: '0 4px 12px rgba(0,0,0,0.05)',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
...sx,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{options.map((option) => (
|
||||||
|
<ToggleButton
|
||||||
|
key={option.value}
|
||||||
|
value={option.value}
|
||||||
|
sx={buttonSx ?? { px: 1.5, fontWeight: 700, whiteSpace: 'nowrap' }}
|
||||||
|
>
|
||||||
|
{option.label}
|
||||||
|
</ToggleButton>
|
||||||
|
))}
|
||||||
|
</ToggleButtonGroup>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,515 @@
|
|||||||
|
/**
|
||||||
|
* TextInputArea - 多行文本输入组件
|
||||||
|
*
|
||||||
|
* 提供功能丰富的多行文本输入体验,支持受控/非受控模式、验证规则、
|
||||||
|
* 字符计数、工具栏操作、复制/清空等交互能力。
|
||||||
|
*
|
||||||
|
* @module TextInputArea
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* // 基础用法
|
||||||
|
* <TextInputArea placeholder="请输入内容..." />
|
||||||
|
*
|
||||||
|
* // 受控模式
|
||||||
|
* <TextInputArea value={text} onChange={setText} />
|
||||||
|
*
|
||||||
|
* // 带验证规则
|
||||||
|
* <TextInputArea
|
||||||
|
* rules={[{ validator: (v) => v.length >= 3, message: '至少3个字符' }]}
|
||||||
|
* validateTrigger="onBlur"
|
||||||
|
* />
|
||||||
|
*
|
||||||
|
* // 带操作按钮
|
||||||
|
* <TextInputArea
|
||||||
|
* actions={[
|
||||||
|
* { key: 'submit', label: '提交', type: 'primary', onClick: handleSubmit },
|
||||||
|
* ]}
|
||||||
|
* />
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { useRef, useState, useCallback, forwardRef, RefObject } from 'react';
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Button,
|
||||||
|
IconButton,
|
||||||
|
TextField,
|
||||||
|
Tooltip,
|
||||||
|
Typography,
|
||||||
|
alpha,
|
||||||
|
type SxProps,
|
||||||
|
} from '@mui/material';
|
||||||
|
import type { Theme } from '@mui/material/styles';
|
||||||
|
import CloseIcon from '@mui/icons-material/Close';
|
||||||
|
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import type { SnackbarOptions } from '@/components/GlobalSnackbar';
|
||||||
|
|
||||||
|
/** 文本验证规则 */
|
||||||
|
export type ValidateRule = {
|
||||||
|
/** 验证函数,返回 true 表示通过 */
|
||||||
|
validator: (value: string) => boolean;
|
||||||
|
/** 验证失败时的提示消息 */
|
||||||
|
message: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 工具栏操作按钮配置 */
|
||||||
|
export type ToolbarAction = {
|
||||||
|
/** 唯一标识 */
|
||||||
|
key: string;
|
||||||
|
/** 按钮显示文本 */
|
||||||
|
label: string;
|
||||||
|
/** 按钮图标 */
|
||||||
|
icon?: React.ReactNode;
|
||||||
|
/** 按钮位置:顶部或底部,默认顶部 */
|
||||||
|
position?: 'top' | 'bottom';
|
||||||
|
/** 按钮样式类型:主要/默认/危险 */
|
||||||
|
type?: 'primary' | 'default' | 'danger';
|
||||||
|
/** 禁用条件,可以是布尔值或根据当前值动态判断的函数 */
|
||||||
|
disabled?: boolean | ((value: string) => boolean);
|
||||||
|
/** 点击回调,接收当前值和操作辅助方法 */
|
||||||
|
onClick: (value: string, helpers: { clear: () => void; setError: (msg: string) => void }) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface TextInputAreaProps {
|
||||||
|
/** 受控模式下的当前值 */
|
||||||
|
value?: string;
|
||||||
|
/** 非受控模式下的初始值,组件挂载时有效 */
|
||||||
|
defaultValue?: string;
|
||||||
|
/** 值变化回调 */
|
||||||
|
onChange?: (value: string) => void;
|
||||||
|
/** 占位文本 */
|
||||||
|
placeholder?: string;
|
||||||
|
/** 是否禁用 */
|
||||||
|
disabled?: boolean;
|
||||||
|
/** 是否只读 */
|
||||||
|
readOnly?: boolean;
|
||||||
|
/** 是否自动聚焦 */
|
||||||
|
autoFocus?: boolean;
|
||||||
|
|
||||||
|
/** 最小行数(autoResize 为 true 时生效) */
|
||||||
|
minRows?: number;
|
||||||
|
/** 最大行数(autoResize 为 true 时生效) */
|
||||||
|
maxRows?: number;
|
||||||
|
/** 最大字符数限制 */
|
||||||
|
maxLength?: number;
|
||||||
|
/** 外层容器类名 */
|
||||||
|
className?: string;
|
||||||
|
/** 外层容器样式 */
|
||||||
|
style?: React.CSSProperties;
|
||||||
|
/** 外层容器 sx */
|
||||||
|
sx?: SxProps<Theme>;
|
||||||
|
|
||||||
|
/** 是否显示字符计数 */
|
||||||
|
showCount?: boolean;
|
||||||
|
/** 是否显示清空按钮,默认 true */
|
||||||
|
showClear?: boolean;
|
||||||
|
/** 是否允许复制内容 */
|
||||||
|
allowCopy?: boolean;
|
||||||
|
/** 是否启用自动调整高度,默认 true */
|
||||||
|
autoResize?: boolean;
|
||||||
|
|
||||||
|
/** 验证规则列表 */
|
||||||
|
rules?: ValidateRule[];
|
||||||
|
/** 验证触发时机:失焦(onBlur) / 输入时(onChange) / 操作前(onAction),默认 onAction */
|
||||||
|
validateTrigger?: 'onBlur' | 'onChange' | 'onAction';
|
||||||
|
|
||||||
|
/** 工具栏操作按钮列表 */
|
||||||
|
actions?: ToolbarAction[];
|
||||||
|
/** 顶部栏左侧额外内容 */
|
||||||
|
topExtra?: React.ReactNode;
|
||||||
|
|
||||||
|
/** 顶部栏标题 */
|
||||||
|
title?: string;
|
||||||
|
|
||||||
|
/** 消息提示回调,用于展示 Toast 通知 */
|
||||||
|
showMessage?: (message: string, options?: SnackbarOptions) => void;
|
||||||
|
|
||||||
|
/** 外部错误消息,由父组件控制,优先于内部验证错误 */
|
||||||
|
externalError?: string;
|
||||||
|
|
||||||
|
/** 清空按钮点击后的额外回调 */
|
||||||
|
onClear?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ActionButton 内部组件的属性 */
|
||||||
|
interface ActionButtonProps {
|
||||||
|
action: ToolbarAction;
|
||||||
|
value: string;
|
||||||
|
globalDisabled: boolean;
|
||||||
|
variant?: 'text' | 'contained';
|
||||||
|
onAction: (action: ToolbarAction) => void;
|
||||||
|
size?: 'small' | 'medium';
|
||||||
|
compact?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 工具栏操作按钮 - 根据 action.type 自动应用样式
|
||||||
|
*
|
||||||
|
* - primary:填充主色背景
|
||||||
|
* - danger:红色文字 + 悬停红色背景
|
||||||
|
* - default(默认):灰色文字 + 悬停灰色背景
|
||||||
|
*/
|
||||||
|
function ActionButton({
|
||||||
|
action,
|
||||||
|
value,
|
||||||
|
globalDisabled,
|
||||||
|
variant = 'text',
|
||||||
|
onAction,
|
||||||
|
size = 'small',
|
||||||
|
compact,
|
||||||
|
}: ActionButtonProps) {
|
||||||
|
const isBtnDisabled =
|
||||||
|
typeof action.disabled === 'function' ? action.disabled(value) : action.disabled || !value;
|
||||||
|
|
||||||
|
const typeStyles: Record<string, unknown> = {};
|
||||||
|
|
||||||
|
if (action.type === 'primary') {
|
||||||
|
if (variant !== 'contained') {
|
||||||
|
typeStyles.bgcolor = 'primary.main';
|
||||||
|
typeStyles.color = 'primary.contrastText';
|
||||||
|
typeStyles['&:hover'] = { bgcolor: 'primary.dark' };
|
||||||
|
}
|
||||||
|
} else if (action.type === 'danger') {
|
||||||
|
typeStyles.color = 'error.main';
|
||||||
|
typeStyles['&:hover'] = {
|
||||||
|
bgcolor: (theme: Theme) => alpha(theme.palette.error.main, 0.08),
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
typeStyles.color = 'text.secondary';
|
||||||
|
typeStyles['&:hover'] = {
|
||||||
|
bgcolor: (theme: Theme) => alpha(theme.palette.grey[500], 0.1),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
onClick={() => onAction(action)}
|
||||||
|
disabled={isBtnDisabled || globalDisabled}
|
||||||
|
size={size}
|
||||||
|
variant={variant}
|
||||||
|
startIcon={action.icon}
|
||||||
|
sx={{
|
||||||
|
fontWeight: 600,
|
||||||
|
borderRadius: 2,
|
||||||
|
...typeStyles,
|
||||||
|
...(compact ? { fontSize: '0.75rem', px: 1.5, minWidth: 0 } : { fontSize: '0.8rem' }),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{action.label}
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TextInputArea 组件
|
||||||
|
*
|
||||||
|
* 多行文本输入组件,支持受控/非受控双模式、验证规则、工具栏操作等。
|
||||||
|
* 使用 forwardRef 暴露底层 textarea DOM 节点。
|
||||||
|
*/
|
||||||
|
const TextInputArea = forwardRef<HTMLTextAreaElement, TextInputAreaProps>((props, ref) => {
|
||||||
|
const {
|
||||||
|
value: controlledValue,
|
||||||
|
defaultValue = '',
|
||||||
|
onChange,
|
||||||
|
placeholder: placeholderProp,
|
||||||
|
disabled = false,
|
||||||
|
readOnly = false,
|
||||||
|
autoFocus = false,
|
||||||
|
minRows = 4,
|
||||||
|
maxRows = 12,
|
||||||
|
maxLength,
|
||||||
|
className = '',
|
||||||
|
style,
|
||||||
|
sx: containerSx,
|
||||||
|
showCount = false,
|
||||||
|
showClear = true,
|
||||||
|
allowCopy = false,
|
||||||
|
autoResize = true,
|
||||||
|
rules = [],
|
||||||
|
validateTrigger = 'onAction',
|
||||||
|
actions = [],
|
||||||
|
topExtra,
|
||||||
|
title,
|
||||||
|
showMessage,
|
||||||
|
externalError,
|
||||||
|
onClear,
|
||||||
|
} = props;
|
||||||
|
|
||||||
|
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||||||
|
const [internalValue, setInternalValue] = useState(defaultValue);
|
||||||
|
const [error, setError] = useState<string>('');
|
||||||
|
|
||||||
|
const { t } = useTranslation('common');
|
||||||
|
const placeholder = placeholderProp ?? t('textInputArea.placeholder');
|
||||||
|
|
||||||
|
/** 通过 value prop 是否存在来判断是否为受控模式 */
|
||||||
|
const isControlled = controlledValue !== undefined;
|
||||||
|
const value = isControlled ? controlledValue : internalValue;
|
||||||
|
|
||||||
|
/** 外部错误优先级高于内部验证错误 */
|
||||||
|
const displayError = externalError ?? error;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行所有验证规则
|
||||||
|
* @param trigger - 触发验证的事件类型,用于匹配 validateTrigger
|
||||||
|
*/
|
||||||
|
const validate = useCallback(
|
||||||
|
(val: string, trigger?: string): boolean => {
|
||||||
|
if (validateTrigger !== trigger && trigger) return true;
|
||||||
|
for (const rule of rules) {
|
||||||
|
if (!rule.validator(val)) {
|
||||||
|
setError(rule.message);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setError('');
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
[rules, validateTrigger],
|
||||||
|
);
|
||||||
|
|
||||||
|
/** 输入变化处理:更新值、清空错误、按需触发验证 */
|
||||||
|
const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||||
|
const newVal = e.target.value;
|
||||||
|
if (maxLength && newVal.length > maxLength) {
|
||||||
|
const msg = t('charCount', { count: maxLength });
|
||||||
|
setError(msg);
|
||||||
|
showMessage?.(msg, { severity: 'warning' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isControlled) setInternalValue(newVal);
|
||||||
|
onChange?.(newVal);
|
||||||
|
|
||||||
|
if (error) setError('');
|
||||||
|
if (validateTrigger === 'onChange') validate(newVal, 'onChange');
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 失焦时按需触发验证 */
|
||||||
|
const handleBlur = () => {
|
||||||
|
if (validateTrigger === 'onBlur') validate(value, 'onBlur');
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 清空输入内容并重新聚焦 */
|
||||||
|
const handleClear = useCallback(() => {
|
||||||
|
if (!isControlled) setInternalValue('');
|
||||||
|
onChange?.('');
|
||||||
|
setError('');
|
||||||
|
textareaRef.current?.focus();
|
||||||
|
showMessage?.(t('textInputArea.cleared'), { severity: 'success' });
|
||||||
|
onClear?.();
|
||||||
|
}, [isControlled, onChange, showMessage, t, onClear]);
|
||||||
|
|
||||||
|
/** 复制当前内容到剪贴板 */
|
||||||
|
const handleCopy = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(value);
|
||||||
|
showMessage?.(t('messages.copySuccess'), { severity: 'success' });
|
||||||
|
} catch {
|
||||||
|
setError(t('messages.copyError'));
|
||||||
|
showMessage?.(t('messages.copyError'), { severity: 'error' });
|
||||||
|
}
|
||||||
|
}, [value, showMessage, t]);
|
||||||
|
|
||||||
|
/** 执行工具栏操作:检查禁用状态、验证、调用 onClick */
|
||||||
|
const handleAction = useCallback(
|
||||||
|
(action: ToolbarAction) => {
|
||||||
|
const isDisabled =
|
||||||
|
typeof action.disabled === 'function' ? action.disabled(value) : action.disabled;
|
||||||
|
|
||||||
|
if (isDisabled || disabled) return;
|
||||||
|
|
||||||
|
if (validateTrigger === 'onAction' && !validate(value, 'onAction')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
action.onClick(value, {
|
||||||
|
clear: handleClear,
|
||||||
|
setError,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[value, disabled, validate, validateTrigger, handleClear],
|
||||||
|
);
|
||||||
|
|
||||||
|
/** 合并内部 ref 和外部传入的 forwardRef */
|
||||||
|
const handleInputRef = useCallback(
|
||||||
|
(node: HTMLTextAreaElement | null) => {
|
||||||
|
textareaRef.current = node;
|
||||||
|
if (typeof ref === 'function') {
|
||||||
|
ref(node);
|
||||||
|
} else if (ref) {
|
||||||
|
(ref as RefObject<HTMLTextAreaElement | null>).current = node;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[ref],
|
||||||
|
);
|
||||||
|
|
||||||
|
const topActions = actions.filter((a) => a.position !== 'bottom');
|
||||||
|
const bottomActions = actions.filter((a) => a.position === 'bottom');
|
||||||
|
|
||||||
|
const hasTopBar = title || showCount || topActions.length > 0 || topExtra;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box className={className} style={style} sx={containerSx}>
|
||||||
|
{hasTopBar && (
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
mb: 1,
|
||||||
|
px: 0.5,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
|
||||||
|
{title && (
|
||||||
|
<Typography variant="body2" sx={{ fontWeight: 600, color: 'text.secondary' }}>
|
||||||
|
{title}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
{topExtra}
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
|
||||||
|
{topActions.map((action) => (
|
||||||
|
<ActionButton
|
||||||
|
key={action.key}
|
||||||
|
action={action}
|
||||||
|
value={value}
|
||||||
|
globalDisabled={disabled}
|
||||||
|
onAction={handleAction}
|
||||||
|
compact
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
{showCount && (
|
||||||
|
<Typography
|
||||||
|
variant="caption"
|
||||||
|
sx={{ color: 'text.disabled', fontVariantNumeric: 'tabular-nums', ml: 0.5 }}
|
||||||
|
>
|
||||||
|
{value.length}
|
||||||
|
{maxLength ? ` / ${maxLength}` : ''}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Box sx={{ position: 'relative' }}>
|
||||||
|
<TextField
|
||||||
|
inputRef={handleInputRef}
|
||||||
|
multiline
|
||||||
|
fullWidth
|
||||||
|
minRows={autoResize ? minRows : undefined}
|
||||||
|
maxRows={autoResize ? maxRows : undefined}
|
||||||
|
rows={autoResize ? undefined : minRows}
|
||||||
|
placeholder={placeholder}
|
||||||
|
value={value}
|
||||||
|
onChange={handleChange}
|
||||||
|
onBlur={handleBlur}
|
||||||
|
disabled={disabled}
|
||||||
|
autoFocus={autoFocus}
|
||||||
|
error={Boolean(displayError)}
|
||||||
|
helperText={displayError || undefined}
|
||||||
|
slotProps={{
|
||||||
|
input: { readOnly },
|
||||||
|
formHelperText: {
|
||||||
|
sx: { mx: 1.5, fontWeight: 600, '&.Mui-error': { color: 'error.main' } },
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
sx={{
|
||||||
|
'& .MuiOutlinedInput-root': {
|
||||||
|
bgcolor: 'background.paper',
|
||||||
|
borderRadius: 3,
|
||||||
|
fontSize: '0.875rem',
|
||||||
|
fontFamily: 'monospace',
|
||||||
|
lineHeight: 1.6,
|
||||||
|
transition: 'all 0.2s',
|
||||||
|
'&:hover': { bgcolor: 'action.hover' },
|
||||||
|
'&.Mui-focused': {
|
||||||
|
bgcolor: 'background.paper',
|
||||||
|
boxShadow: (theme) => `${alpha(theme.palette.primary.main, 0.08)} 0 0 0 3px`,
|
||||||
|
},
|
||||||
|
'&.Mui-error': {
|
||||||
|
boxShadow: (theme) => `${alpha(theme.palette.error.main, 0.08)} 0 0 0 3px`,
|
||||||
|
},
|
||||||
|
'& textarea': {
|
||||||
|
py: 1.5,
|
||||||
|
px: 1.5,
|
||||||
|
...(showClear || allowCopy || bottomActions.length > 0 ? { pb: 4 } : {}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'& .MuiFormHelperText-root': {
|
||||||
|
mx: 0,
|
||||||
|
mt: 0.5,
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{(showClear || allowCopy || bottomActions.length > 0) && (
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
position: 'absolute',
|
||||||
|
bottom: displayError ? 32 : 8,
|
||||||
|
right: 12,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: 0.5,
|
||||||
|
zIndex: 1,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{bottomActions.map((action) => (
|
||||||
|
<ActionButton
|
||||||
|
key={action.key}
|
||||||
|
action={action}
|
||||||
|
value={value}
|
||||||
|
globalDisabled={disabled}
|
||||||
|
variant={action.type === 'primary' ? 'contained' : 'text'}
|
||||||
|
onAction={handleAction}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
{allowCopy && value && (
|
||||||
|
<Tooltip title={t('textInputArea.copyContent')}>
|
||||||
|
<IconButton
|
||||||
|
onClick={handleCopy}
|
||||||
|
size="small"
|
||||||
|
sx={{
|
||||||
|
color: 'text.disabled',
|
||||||
|
'&:hover': {
|
||||||
|
color: 'primary.main',
|
||||||
|
bgcolor: (theme) => alpha(theme.palette.primary.main, 0.08),
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<ContentCopyIcon sx={{ fontSize: 16 }} />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
{showClear && value && !disabled && !readOnly && (
|
||||||
|
<Tooltip title={t('textInputArea.clear')}>
|
||||||
|
<IconButton
|
||||||
|
onClick={handleClear}
|
||||||
|
size="small"
|
||||||
|
sx={{
|
||||||
|
color: 'text.disabled',
|
||||||
|
'&:hover': {
|
||||||
|
color: 'error.main',
|
||||||
|
bgcolor: (theme) => alpha(theme.palette.error.main, 0.08),
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<CloseIcon sx={{ fontSize: 16 }} />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
TextInputArea.displayName = 'TextInputArea';
|
||||||
|
|
||||||
|
export default TextInputArea;
|
||||||
+16
-4
@@ -31,7 +31,15 @@ import { openExtensionPage } from '@/utils/chromeTabs';
|
|||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { alpha } from '@mui/material/styles';
|
import { alpha } from '@mui/material/styles';
|
||||||
import { SUPPORTED_LANGUAGES, normalizeLanguage } from '@/i18n';
|
import { SUPPORTED_LANGUAGES, normalizeLanguage } from '@/i18n';
|
||||||
import { topBarStyles } from '@/config/pageTheme';
|
|
||||||
|
const topBarStyles = {
|
||||||
|
SEARCH_MAX_WIDTH: 400,
|
||||||
|
DROPDOWN_MAX_HEIGHT: 300,
|
||||||
|
Z_INDEX: 1100,
|
||||||
|
DROPDOWN_Z_INDEX: 1200,
|
||||||
|
SEARCH_HISTORY_LIMIT: 10,
|
||||||
|
SEARCH_HISTORY_DISPLAY: 5,
|
||||||
|
};
|
||||||
|
|
||||||
export default function TopBar({ onOpenOptions }: { onOpenOptions: () => void }) {
|
export default function TopBar({ onOpenOptions }: { onOpenOptions: () => void }) {
|
||||||
const { currentPage, goBack, navigateTo } = useRouter();
|
const { currentPage, goBack, navigateTo } = useRouter();
|
||||||
@@ -90,13 +98,17 @@ export default function TopBar({ onOpenOptions }: { onOpenOptions: () => void })
|
|||||||
0,
|
0,
|
||||||
topBarStyles.SEARCH_HISTORY_LIMIT,
|
topBarStyles.SEARCH_HISTORY_LIMIT,
|
||||||
);
|
);
|
||||||
storageUtil.set('app/searchHistory', newHistory).catch((error) => {
|
|
||||||
console.error('保存搜索历史失败:', error);
|
|
||||||
});
|
|
||||||
return newHistory;
|
return newHistory;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 副作用:搜索历史变化后持久化到 storage
|
||||||
|
useEffect(() => {
|
||||||
|
storageUtil.set('app/searchHistory', searchHistory).catch((error) => {
|
||||||
|
console.error('保存搜索历史失败:', error);
|
||||||
|
});
|
||||||
|
}, [searchHistory]);
|
||||||
|
|
||||||
const handleSelectFeature = (feature: FeatureConfig) => {
|
const handleSelectFeature = (feature: FeatureConfig) => {
|
||||||
navigateTo(feature.key);
|
navigateTo(feature.key);
|
||||||
saveToHistory(t(feature.labelKey));
|
saveToHistory(t(feature.labelKey));
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { fireEvent, render, screen } from '@testing-library/react';
|
||||||
|
import DecodeResultPaper from '@/components/DecodeResultPaper';
|
||||||
|
|
||||||
|
describe('DecodeResultPaper 组件', () => {
|
||||||
|
const defaultProps = {
|
||||||
|
title: 'decodedFileOutput',
|
||||||
|
mimeType: 'image/png',
|
||||||
|
blobSize: 1024,
|
||||||
|
fileName: 'decoded.png',
|
||||||
|
onFileNameChange: vi.fn(),
|
||||||
|
onDownload: vi.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('渲染测试', () => {
|
||||||
|
it('应渲染标题', () => {
|
||||||
|
render(<DecodeResultPaper {...defaultProps} />);
|
||||||
|
expect(screen.getByText('decodedFileOutput')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应渲染 MIME 类型信息', () => {
|
||||||
|
render(<DecodeResultPaper {...defaultProps} />);
|
||||||
|
expect(screen.getByText(/image\/png/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应通过 formatFileSize 渲染文件大小', () => {
|
||||||
|
render(<DecodeResultPaper {...{ ...defaultProps, blobSize: 1536 }} />);
|
||||||
|
expect(screen.getByText(/1\.5 KB/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应渲染文件名输入框', () => {
|
||||||
|
render(<DecodeResultPaper {...defaultProps} />);
|
||||||
|
const input = screen.getByDisplayValue('decoded.png');
|
||||||
|
expect(input).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应渲染下载按钮', () => {
|
||||||
|
render(<DecodeResultPaper {...defaultProps} />);
|
||||||
|
expect(screen.getByRole('button', { name: 'download' })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应渲染 children 内容', () => {
|
||||||
|
render(
|
||||||
|
<DecodeResultPaper {...defaultProps}>
|
||||||
|
<div data-testid="preview">预览内容</div>
|
||||||
|
</DecodeResultPaper>,
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId('preview')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('预览内容')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('交互测试', () => {
|
||||||
|
it('修改文件名时应调用 onFileNameChange', () => {
|
||||||
|
render(<DecodeResultPaper {...defaultProps} />);
|
||||||
|
const input = screen.getByDisplayValue('decoded.png');
|
||||||
|
fireEvent.change(input, { target: { value: 'new-name.png' } });
|
||||||
|
expect(defaultProps.onFileNameChange).toHaveBeenCalledWith('new-name.png');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('点击下载按钮时应调用 onDownload', () => {
|
||||||
|
render(<DecodeResultPaper {...defaultProps} />);
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'download' }));
|
||||||
|
expect(defaultProps.onDownload).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('按钮状态', () => {
|
||||||
|
it('文件名为空时下载按钮应禁用', () => {
|
||||||
|
render(<DecodeResultPaper {...{ ...defaultProps, fileName: '' }} />);
|
||||||
|
expect(screen.getByRole('button', { name: 'download' })).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('文件名不为空时下载按钮应启用', () => {
|
||||||
|
render(<DecodeResultPaper {...defaultProps} />);
|
||||||
|
expect(screen.getByRole('button', { name: 'download' })).toBeEnabled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { render, screen, waitFor } from '@testing-library/react';
|
||||||
|
import { ErrorBoundary } from '@/components/ErrorBoundary';
|
||||||
|
|
||||||
|
// 用于触发错误的测试子组件
|
||||||
|
function ThrowError({ message }: { message: string }): never {
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 正常渲染的子组件
|
||||||
|
function NormalComponent({ text }: { text: string }) {
|
||||||
|
return <div data-testid="normal-content">{text}</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('ErrorBoundary', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
// 抑制测试中故意抛出的错误日志
|
||||||
|
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('正常渲染子组件', () => {
|
||||||
|
render(
|
||||||
|
<ErrorBoundary>
|
||||||
|
<NormalComponent text="正常内容" />
|
||||||
|
</ErrorBoundary>,
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId('normal-content')).toHaveTextContent('正常内容');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('子组件抛出错误时显示错误 UI', () => {
|
||||||
|
render(
|
||||||
|
<ErrorBoundary>
|
||||||
|
<ThrowError message="测试错误" />
|
||||||
|
</ErrorBoundary>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('糟糕,出了点问题')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/测试错误/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('children 变化时重置错误状态', async () => {
|
||||||
|
const { rerender } = render(
|
||||||
|
<ErrorBoundary>
|
||||||
|
<ThrowError message="初始错误" />
|
||||||
|
</ErrorBoundary>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('糟糕,出了点问题')).toBeInTheDocument();
|
||||||
|
|
||||||
|
// 切换到正常子组件
|
||||||
|
rerender(
|
||||||
|
<ErrorBoundary>
|
||||||
|
<NormalComponent text="恢复后的内容" />
|
||||||
|
</ErrorBoundary>,
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByTestId('normal-content')).toHaveTextContent('恢复后的内容');
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(screen.queryByText('糟糕,出了点问题')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('相同的 children 不重置错误状态', () => {
|
||||||
|
const { rerender } = render(
|
||||||
|
<ErrorBoundary>
|
||||||
|
<ThrowError message="相同子组件错误" />
|
||||||
|
</ErrorBoundary>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('糟糕,出了点问题')).toBeInTheDocument();
|
||||||
|
|
||||||
|
// 用相同的 children rerender
|
||||||
|
rerender(
|
||||||
|
<ErrorBoundary>
|
||||||
|
<ThrowError message="相同子组件错误" />
|
||||||
|
</ErrorBoundary>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('糟糕,出了点问题')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('错误 UI 包含刷新按钮', () => {
|
||||||
|
const reloadMock = vi.fn();
|
||||||
|
Object.defineProperty(window, 'location', {
|
||||||
|
value: { reload: reloadMock },
|
||||||
|
writable: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
render(
|
||||||
|
<ErrorBoundary>
|
||||||
|
<ThrowError message="按钮测试" />
|
||||||
|
</ErrorBoundary>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const refreshButton = screen.getByRole('button', { name: /刷新应用/ });
|
||||||
|
expect(refreshButton).toBeInTheDocument();
|
||||||
|
|
||||||
|
refreshButton.click();
|
||||||
|
expect(reloadMock).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { render, screen, waitFor } from '@testing-library/react';
|
||||||
|
import { PageErrorBoundary } from '@/components/PageErrorBoundary';
|
||||||
|
|
||||||
|
// 用于触发错误的测试子组件
|
||||||
|
function ThrowError({ message }: { message: string }): never {
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 正常渲染的子组件
|
||||||
|
function NormalComponent({ text }: { text: string }) {
|
||||||
|
return <div data-testid="normal-content">{text}</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('PageErrorBoundary', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
// 抑制测试中故意抛出的错误日志
|
||||||
|
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('正常渲染子组件', () => {
|
||||||
|
render(
|
||||||
|
<PageErrorBoundary>
|
||||||
|
<NormalComponent text="正常内容" />
|
||||||
|
</PageErrorBoundary>,
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId('normal-content')).toHaveTextContent('正常内容');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('子组件抛出错误时显示错误卡片 UI', () => {
|
||||||
|
render(
|
||||||
|
<PageErrorBoundary>
|
||||||
|
<ThrowError message="测试错误" />
|
||||||
|
</PageErrorBoundary>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('该页面加载失败')).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/测试错误/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('点击重试按钮后恢复', async () => {
|
||||||
|
const { rerender } = render(
|
||||||
|
<PageErrorBoundary>
|
||||||
|
<ThrowError message="可恢复错误" />
|
||||||
|
</PageErrorBoundary>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('该页面加载失败')).toBeInTheDocument();
|
||||||
|
|
||||||
|
// 将子组件替换为正常组件,然后点击重试
|
||||||
|
rerender(
|
||||||
|
<PageErrorBoundary>
|
||||||
|
<NormalComponent text="恢复后的内容" />
|
||||||
|
</PageErrorBoundary>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const retryButton = screen.getByRole('button', { name: /重试/ });
|
||||||
|
retryButton.click();
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByTestId('normal-content')).toHaveTextContent('恢复后的内容');
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(screen.queryByText('该页面加载失败')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resetKey 变化时自动重置错误状态', async () => {
|
||||||
|
const { rerender } = render(
|
||||||
|
<PageErrorBoundary resetKey="page-a">
|
||||||
|
<ThrowError message="页面 A 错误" />
|
||||||
|
</PageErrorBoundary>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('该页面加载失败')).toBeInTheDocument();
|
||||||
|
|
||||||
|
// 切换 resetKey,同时提供正常子组件
|
||||||
|
rerender(
|
||||||
|
<PageErrorBoundary resetKey="page-b">
|
||||||
|
<NormalComponent text="页面 B 内容" />
|
||||||
|
</PageErrorBoundary>,
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByTestId('normal-content')).toHaveTextContent('页面 B 内容');
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(screen.queryByText('该页面加载失败')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resetKey 不变时保持错误状态', () => {
|
||||||
|
const { rerender } = render(
|
||||||
|
<PageErrorBoundary resetKey="page-a">
|
||||||
|
<ThrowError message="初始错误" />
|
||||||
|
</PageErrorBoundary>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('该页面加载失败')).toBeInTheDocument();
|
||||||
|
|
||||||
|
// 仅 children 变化,resetKey 不变,错误应保持
|
||||||
|
rerender(
|
||||||
|
<PageErrorBoundary resetKey="page-a">
|
||||||
|
<NormalComponent text="新内容" />
|
||||||
|
</PageErrorBoundary>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('该页面加载失败')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('错误 UI 包含重试按钮', () => {
|
||||||
|
render(
|
||||||
|
<PageErrorBoundary>
|
||||||
|
<ThrowError message="按钮测试" />
|
||||||
|
</PageErrorBoundary>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const retryButton = screen.getByRole('button', { name: /重试/ });
|
||||||
|
expect(retryButton).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('错误信息以 monospace 格式显示', () => {
|
||||||
|
render(
|
||||||
|
<PageErrorBoundary>
|
||||||
|
<ThrowError message="格式化测试" />
|
||||||
|
</PageErrorBoundary>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const errorText = screen.getByText(/格式化测试/);
|
||||||
|
expect(errorText).toBeInTheDocument();
|
||||||
|
expect(errorText.tagName.toLowerCase()).toBe('pre');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -12,7 +12,6 @@ const mockRouterValue = {
|
|||||||
pageOrder: ['timestamp'] as PageType[],
|
pageOrder: ['timestamp'] as PageType[],
|
||||||
isLoaded: true,
|
isLoaded: true,
|
||||||
navigateTo: vi.fn(),
|
navigateTo: vi.fn(),
|
||||||
navigateLocal: vi.fn(),
|
|
||||||
syncNavigation: vi.fn(),
|
syncNavigation: vi.fn(),
|
||||||
goBack: vi.fn(),
|
goBack: vi.fn(),
|
||||||
setVisiblePages: vi.fn(),
|
setVisiblePages: vi.fn(),
|
||||||
@@ -83,4 +82,16 @@ describe('RouterContainer 组件', () => {
|
|||||||
expect(box).toBeInTheDocument();
|
expect(box).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('页面级错误隔离', () => {
|
||||||
|
it('PageErrorBoundary 应包裹在 Suspense 内层', () => {
|
||||||
|
mockRouterValue.isLoaded = true;
|
||||||
|
mockRouterValue.currentPage = 'dashboard';
|
||||||
|
const { container } = renderWithProvider(<RouterContainer />);
|
||||||
|
|
||||||
|
// 验证 RouterContainer 的 Box 结构存在
|
||||||
|
const routerBox = container.querySelector('.page-transition-dashboard');
|
||||||
|
expect(routerBox).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import { fireEvent, render, screen } from '@testing-library/react';
|
||||||
|
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||||
|
|
||||||
|
describe('SwitchButtonGroup 组件', () => {
|
||||||
|
const options = [
|
||||||
|
{ value: 'a', label: '选项A' },
|
||||||
|
{ value: 'b', label: '选项B' },
|
||||||
|
];
|
||||||
|
|
||||||
|
it('应渲染所有选项按钮', () => {
|
||||||
|
render(<SwitchButtonGroup value="a" options={options} onChange={vi.fn()} />);
|
||||||
|
|
||||||
|
expect(screen.getByRole('button', { name: /选项A/i })).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('button', { name: /选项B/i })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应高亮当前选中的按钮', () => {
|
||||||
|
render(<SwitchButtonGroup value="a" options={options} onChange={vi.fn()} />);
|
||||||
|
|
||||||
|
const buttonA = screen.getByRole('button', { name: /选项A/i });
|
||||||
|
const buttonB = screen.getByRole('button', { name: /选项B/i });
|
||||||
|
|
||||||
|
expect(buttonA).toHaveClass('Mui-selected');
|
||||||
|
expect(buttonB).not.toHaveClass('Mui-selected');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('点击未选中按钮时应触发 onChange 并传入选中值', () => {
|
||||||
|
const handleChange = vi.fn();
|
||||||
|
render(<SwitchButtonGroup value="a" options={options} onChange={handleChange} />);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /选项B/i }));
|
||||||
|
expect(handleChange).toHaveBeenCalledTimes(1);
|
||||||
|
expect(handleChange).toHaveBeenCalledWith('b');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('点击已选中按钮时不应触发 onChange', () => {
|
||||||
|
const handleChange = vi.fn();
|
||||||
|
render(<SwitchButtonGroup value="a" options={options} onChange={handleChange} />);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /选项A/i }));
|
||||||
|
expect(handleChange).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持通过 sx 自定义样式', () => {
|
||||||
|
const { container } = render(
|
||||||
|
<SwitchButtonGroup value="a" options={options} onChange={vi.fn()} sx={{ width: 200 }} />,
|
||||||
|
);
|
||||||
|
|
||||||
|
const group = container.querySelector('.MuiToggleButtonGroup-root');
|
||||||
|
expect(group).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持 size 属性', () => {
|
||||||
|
const { container } = render(
|
||||||
|
<SwitchButtonGroup value="a" options={options} onChange={vi.fn()} size="small" />,
|
||||||
|
);
|
||||||
|
|
||||||
|
const group = container.querySelector('.MuiToggleButtonGroup-root');
|
||||||
|
expect(group).toBeInTheDocument();
|
||||||
|
expect(group).toHaveClass('MuiToggleButtonGroup-root');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持 buttonSx 自定义按钮样式', () => {
|
||||||
|
render(
|
||||||
|
<SwitchButtonGroup
|
||||||
|
value="a"
|
||||||
|
options={options}
|
||||||
|
onChange={vi.fn()}
|
||||||
|
buttonSx={{ textTransform: 'uppercase' }}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const button = screen.getByRole('button', { name: /选项A/i });
|
||||||
|
expect(button).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持 ReactNode 类型的 label', () => {
|
||||||
|
const nodeOptions = [{ value: 'x', label: <span data-testid="custom-label">自定义</span> }];
|
||||||
|
render(<SwitchButtonGroup value="x" options={nodeOptions} onChange={vi.fn()} />);
|
||||||
|
|
||||||
|
expect(screen.getByTestId('custom-label')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('默认按钮样式应禁止文字换行', () => {
|
||||||
|
render(<SwitchButtonGroup value="a" options={options} onChange={vi.fn()} />);
|
||||||
|
|
||||||
|
const button = screen.getByRole('button', { name: /选项A/i });
|
||||||
|
expect(button).toHaveStyle('white-space: nowrap');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('buttonSx 传入时应覆盖默认换行样式', () => {
|
||||||
|
render(
|
||||||
|
<SwitchButtonGroup
|
||||||
|
value="a"
|
||||||
|
options={options}
|
||||||
|
onChange={vi.fn()}
|
||||||
|
buttonSx={{ whiteSpace: 'normal' }}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const button = screen.getByRole('button', { name: /选项A/i });
|
||||||
|
expect(button).toBeInTheDocument();
|
||||||
|
expect(window.getComputedStyle(button).whiteSpace).toBe('normal');
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('number 类型支持', () => {
|
||||||
|
const numberOptions = [
|
||||||
|
{ value: 2, label: '2' },
|
||||||
|
{ value: 4, label: '4' },
|
||||||
|
];
|
||||||
|
|
||||||
|
it('应支持 number 类型的 value 渲染', () => {
|
||||||
|
render(<SwitchButtonGroup value={2} options={numberOptions} onChange={vi.fn()} />);
|
||||||
|
|
||||||
|
expect(screen.getByRole('button', { name: /2/i })).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('button', { name: /4/i })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应高亮 number 类型的当前选中项', () => {
|
||||||
|
render(<SwitchButtonGroup value={4} options={numberOptions} onChange={vi.fn()} />);
|
||||||
|
|
||||||
|
const button2 = screen.getByRole('button', { name: /2/i });
|
||||||
|
const button4 = screen.getByRole('button', { name: /4/i });
|
||||||
|
|
||||||
|
expect(button2).not.toHaveClass('Mui-selected');
|
||||||
|
expect(button4).toHaveClass('Mui-selected');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('点击 number 选项时应传回 number 值', () => {
|
||||||
|
const handleChange = vi.fn();
|
||||||
|
render(<SwitchButtonGroup value={2} options={numberOptions} onChange={handleChange} />);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: /4/i }));
|
||||||
|
expect(handleChange).toHaveBeenCalledTimes(1);
|
||||||
|
expect(handleChange).toHaveBeenCalledWith(4);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,523 @@
|
|||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import { fireEvent, render, screen } from '@testing-library/react';
|
||||||
|
import TextInputArea from '@/components/TextInputArea';
|
||||||
|
|
||||||
|
describe('TextInputArea 组件', () => {
|
||||||
|
describe('基础渲染', () => {
|
||||||
|
it('应渲染 placeholder', () => {
|
||||||
|
render(<TextInputArea placeholder="请输入文本..." />);
|
||||||
|
expect(screen.getByPlaceholderText('请输入文本...')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应渲染传入的 value', () => {
|
||||||
|
render(<TextInputArea value="测试内容" onChange={() => {}} />);
|
||||||
|
const textarea = screen.getByRole('textbox');
|
||||||
|
expect(textarea).toHaveValue('测试内容');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('默认显示清空按钮', () => {
|
||||||
|
render(<TextInputArea value="有内容" onChange={() => {}} />);
|
||||||
|
expect(screen.getByRole('button', { name: 'textInputArea.clear' })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('无内容时清空按钮应隐藏', () => {
|
||||||
|
render(<TextInputArea value="" onChange={() => {}} />);
|
||||||
|
expect(screen.queryByRole('button', { name: 'textInputArea.clear' })).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('disabled 时清空按钮应隐藏', () => {
|
||||||
|
render(<TextInputArea value="内容" onChange={() => {}} disabled />);
|
||||||
|
expect(screen.queryByTitle('清空')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('readOnly 时清空按钮应隐藏', () => {
|
||||||
|
render(<TextInputArea value="内容" onChange={() => {}} readOnly />);
|
||||||
|
expect(screen.queryByTitle('清空')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('showClear=false 时不显示清空按钮', () => {
|
||||||
|
render(<TextInputArea value="内容" onChange={() => {}} showClear={false} />);
|
||||||
|
expect(screen.queryByTitle('清空')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('受控模式', () => {
|
||||||
|
it('输入时触发 onChange', () => {
|
||||||
|
const handleChange = vi.fn();
|
||||||
|
render(<TextInputArea value="" onChange={handleChange} />);
|
||||||
|
|
||||||
|
const textarea = screen.getByRole('textbox');
|
||||||
|
fireEvent.change(textarea, { target: { value: '新内容' } });
|
||||||
|
|
||||||
|
expect(handleChange).toHaveBeenCalledWith('新内容');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('清空按钮触发 onChange("")', () => {
|
||||||
|
const handleChange = vi.fn();
|
||||||
|
render(<TextInputArea value="内容" onChange={handleChange} />);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'textInputArea.clear' }));
|
||||||
|
|
||||||
|
expect(handleChange).toHaveBeenCalledWith('');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('非受控模式', () => {
|
||||||
|
it('defaultValue 应显示初始值', () => {
|
||||||
|
render(<TextInputArea defaultValue="初始值" />);
|
||||||
|
expect(screen.getByRole('textbox')).toHaveValue('初始值');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('输入后应更新内部值', () => {
|
||||||
|
render(<TextInputArea defaultValue="" />);
|
||||||
|
|
||||||
|
const textarea = screen.getByRole('textbox');
|
||||||
|
fireEvent.change(textarea, { target: { value: '新内容' } });
|
||||||
|
|
||||||
|
expect(textarea).toHaveValue('新内容');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('清空按钮应清空内容', () => {
|
||||||
|
render(<TextInputArea defaultValue="内容" />);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'textInputArea.clear' }));
|
||||||
|
|
||||||
|
expect(screen.getByRole('textbox')).toHaveValue('');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('allowCopy 复制功能', () => {
|
||||||
|
it('allowCopy 且有内容时显示复制按钮', () => {
|
||||||
|
render(<TextInputArea value="可复制的内容" onChange={() => {}} allowCopy />);
|
||||||
|
expect(screen.getByRole('button', { name: 'textInputArea.copyContent' })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allowCopy 但无内容时隐藏复制按钮', () => {
|
||||||
|
render(<TextInputArea value="" onChange={() => {}} allowCopy />);
|
||||||
|
expect(
|
||||||
|
screen.queryByRole('button', { name: 'textInputArea.copyContent' }),
|
||||||
|
).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allowCopy=false 时不显示复制按钮', () => {
|
||||||
|
render(<TextInputArea value="内容" onChange={() => {}} />);
|
||||||
|
expect(
|
||||||
|
screen.queryByRole('button', { name: 'textInputArea.copyContent' }),
|
||||||
|
).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('复制时调用 showMessage', async () => {
|
||||||
|
const showMessage = vi.fn();
|
||||||
|
Object.assign(navigator, {
|
||||||
|
clipboard: { writeText: vi.fn().mockResolvedValue(undefined) },
|
||||||
|
});
|
||||||
|
|
||||||
|
render(
|
||||||
|
<TextInputArea value="测试" onChange={() => {}} allowCopy showMessage={showMessage} />,
|
||||||
|
);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'textInputArea.copyContent' }));
|
||||||
|
|
||||||
|
expect(navigator.clipboard.writeText).toHaveBeenCalledWith('测试');
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(showMessage).toHaveBeenCalledWith('messages.copySuccess', { severity: 'success' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('复制失败时调用 showMessage 错误提示', async () => {
|
||||||
|
const showMessage = vi.fn();
|
||||||
|
Object.assign(navigator, {
|
||||||
|
clipboard: { writeText: vi.fn().mockRejectedValue(new Error('失败')) },
|
||||||
|
});
|
||||||
|
|
||||||
|
render(
|
||||||
|
<TextInputArea value="测试" onChange={() => {}} allowCopy showMessage={showMessage} />,
|
||||||
|
);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'textInputArea.copyContent' }));
|
||||||
|
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(showMessage).toHaveBeenCalledWith('messages.copyError', { severity: 'error' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('showCount 字符计数', () => {
|
||||||
|
it('显示当前字符数', () => {
|
||||||
|
render(<TextInputArea value="hello" onChange={() => {}} showCount />);
|
||||||
|
expect(screen.getByText('5')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('空内容时显示 0', () => {
|
||||||
|
render(<TextInputArea value="" onChange={() => {}} showCount />);
|
||||||
|
expect(screen.getByText('0')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('设置 maxLength 时显示计数上限', () => {
|
||||||
|
render(<TextInputArea value="ab" onChange={() => {}} showCount maxLength={10} />);
|
||||||
|
expect(screen.getByText('2 / 10')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('maxLength', () => {
|
||||||
|
it('超出 maxLength 的输入应被截断', () => {
|
||||||
|
const handleChange = vi.fn();
|
||||||
|
render(<TextInputArea value="" onChange={handleChange} maxLength={5} />);
|
||||||
|
|
||||||
|
const textarea = screen.getByRole('textbox');
|
||||||
|
fireEvent.change(textarea, { target: { value: '123456' } });
|
||||||
|
|
||||||
|
expect(handleChange).not.toHaveBeenCalledWith('123456');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('未超出 maxLength 的输入应正常触发', () => {
|
||||||
|
const handleChange = vi.fn();
|
||||||
|
render(<TextInputArea value="" onChange={handleChange} maxLength={5} />);
|
||||||
|
|
||||||
|
const textarea = screen.getByRole('textbox');
|
||||||
|
fireEvent.change(textarea, { target: { value: '123' } });
|
||||||
|
|
||||||
|
expect(handleChange).toHaveBeenCalledWith('123');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('验证规则', () => {
|
||||||
|
it('onChange 触发时验证失败应设置 error', () => {
|
||||||
|
render(
|
||||||
|
<TextInputArea
|
||||||
|
value=""
|
||||||
|
onChange={() => {}}
|
||||||
|
validateTrigger="onChange"
|
||||||
|
rules={[{ validator: (v) => v.length >= 3, message: '至少3个字符' }]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const textarea = screen.getByRole('textbox');
|
||||||
|
fireEvent.change(textarea, { target: { value: 'ab' } });
|
||||||
|
|
||||||
|
expect(screen.getByText('至少3个字符')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('onBlur 触发时验证失败应设置 error', () => {
|
||||||
|
render(
|
||||||
|
<TextInputArea
|
||||||
|
value="ab"
|
||||||
|
onChange={() => {}}
|
||||||
|
validateTrigger="onBlur"
|
||||||
|
rules={[{ validator: (v) => v.length >= 3, message: '至少3个字符' }]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const textarea = screen.getByRole('textbox');
|
||||||
|
fireEvent.blur(textarea);
|
||||||
|
|
||||||
|
expect(screen.getByText('至少3个字符')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('验证通过不应显示错误', () => {
|
||||||
|
render(
|
||||||
|
<TextInputArea
|
||||||
|
value="abc"
|
||||||
|
onChange={() => {}}
|
||||||
|
validateTrigger="onChange"
|
||||||
|
rules={[{ validator: (v) => v.length >= 3, message: '至少3个字符' }]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const textarea = screen.getByRole('textbox');
|
||||||
|
fireEvent.change(textarea, { target: { value: 'abcd' } });
|
||||||
|
|
||||||
|
expect(screen.queryByText('至少3个字符')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('onAction 触发时验证失败应阻止 action 执行', () => {
|
||||||
|
const handleAction = vi.fn();
|
||||||
|
render(
|
||||||
|
<TextInputArea
|
||||||
|
value="ab"
|
||||||
|
onChange={() => {}}
|
||||||
|
validateTrigger="onAction"
|
||||||
|
rules={[{ validator: (v) => v.length >= 3, message: '至少3个字符' }]}
|
||||||
|
actions={[
|
||||||
|
{
|
||||||
|
key: 'test',
|
||||||
|
label: '执行',
|
||||||
|
onClick: handleAction,
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByText('执行'));
|
||||||
|
|
||||||
|
expect(handleAction).not.toHaveBeenCalled();
|
||||||
|
expect(screen.getByText('至少3个字符')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('操作栏 actions', () => {
|
||||||
|
it('应渲染顶部操作按钮', () => {
|
||||||
|
render(
|
||||||
|
<TextInputArea
|
||||||
|
value="内容"
|
||||||
|
onChange={() => {}}
|
||||||
|
actions={[{ key: 'top-action', label: '顶部操作', onClick: vi.fn() }]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('顶部操作')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应渲染底部操作按钮', () => {
|
||||||
|
render(
|
||||||
|
<TextInputArea
|
||||||
|
value="内容"
|
||||||
|
onChange={() => {}}
|
||||||
|
actions={[
|
||||||
|
{ key: 'bottom-action', label: '底部操作', position: 'bottom', onClick: vi.fn() },
|
||||||
|
]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('底部操作')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('点击操作按钮触发 onClick', () => {
|
||||||
|
const handleClick = vi.fn();
|
||||||
|
render(
|
||||||
|
<TextInputArea
|
||||||
|
value="内容"
|
||||||
|
onChange={() => {}}
|
||||||
|
actions={[{ key: 'act', label: '操作', onClick: handleClick }]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByText('操作'));
|
||||||
|
|
||||||
|
expect(handleClick).toHaveBeenCalledWith(
|
||||||
|
'内容',
|
||||||
|
expect.objectContaining({
|
||||||
|
clear: expect.any(Function),
|
||||||
|
setError: expect.any(Function),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('disabled 为 true 时按钮应禁用', () => {
|
||||||
|
render(
|
||||||
|
<TextInputArea
|
||||||
|
value=""
|
||||||
|
onChange={() => {}}
|
||||||
|
actions={[{ key: 'act', label: '操作', onClick: vi.fn(), disabled: true }]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('操作')).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('disabled 为函数且返回 true 时按钮应禁用', () => {
|
||||||
|
render(
|
||||||
|
<TextInputArea
|
||||||
|
value=""
|
||||||
|
onChange={() => {}}
|
||||||
|
actions={[{ key: 'act', label: '操作', onClick: vi.fn(), disabled: (v) => !v }]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('操作')).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('primary 类型按钮应使用 contained 样式', () => {
|
||||||
|
render(
|
||||||
|
<TextInputArea
|
||||||
|
value="内容"
|
||||||
|
onChange={() => {}}
|
||||||
|
actions={[
|
||||||
|
{ key: 'p', label: '主要', type: 'primary', position: 'bottom', onClick: vi.fn() },
|
||||||
|
]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const btn = screen.getByText('主要');
|
||||||
|
expect(btn).toHaveClass('MuiButton-contained');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('title', () => {
|
||||||
|
it('应渲染 title', () => {
|
||||||
|
render(<TextInputArea title="输入区域" value="" onChange={() => {}} />);
|
||||||
|
expect(screen.getByText('输入区域')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('不设置 title 时不渲染标题', () => {
|
||||||
|
const { container } = render(<TextInputArea value="" onChange={() => {}} />);
|
||||||
|
expect(container.querySelector('.MuiTypography-body2')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('disabled 和 readOnly', () => {
|
||||||
|
it('disabled 时输入框应禁用', () => {
|
||||||
|
render(<TextInputArea value="内容" onChange={() => {}} disabled />);
|
||||||
|
expect(screen.getByRole('textbox')).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('readOnly 时输入框应只读', () => {
|
||||||
|
render(<TextInputArea value="内容" onChange={() => {}} readOnly />);
|
||||||
|
// MUI TextField 的 readOnly 通过 inputProps 设置,textarea 不会被禁用
|
||||||
|
expect(screen.getByRole('textbox')).not.toBeDisabled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('autoFocus', () => {
|
||||||
|
it('autoFocus 应自动聚焦', () => {
|
||||||
|
render(<TextInputArea autoFocus value="" onChange={() => {}} />);
|
||||||
|
expect(document.activeElement).toBe(screen.getByRole('textbox'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('showMessage prop', () => {
|
||||||
|
it('复制成功时调用 showMessage', async () => {
|
||||||
|
const showMessage = vi.fn();
|
||||||
|
Object.assign(navigator, {
|
||||||
|
clipboard: { writeText: vi.fn().mockResolvedValue(undefined) },
|
||||||
|
});
|
||||||
|
|
||||||
|
render(
|
||||||
|
<TextInputArea value="测试" onChange={() => {}} allowCopy showMessage={showMessage} />,
|
||||||
|
);
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'textInputArea.copyContent' }));
|
||||||
|
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(showMessage).toHaveBeenCalledWith('messages.copySuccess', { severity: 'success' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('onClear 回调', () => {
|
||||||
|
it('点击清空按钮时应调用 onClear', () => {
|
||||||
|
const handleClear = vi.fn();
|
||||||
|
render(<TextInputArea value="内容" onChange={() => {}} onClear={handleClear} />);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'textInputArea.clear' }));
|
||||||
|
|
||||||
|
expect(handleClear).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('不传 onClear 时清空按钮应正常工作', () => {
|
||||||
|
render(<TextInputArea defaultValue="内容" />);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'textInputArea.clear' }));
|
||||||
|
|
||||||
|
expect(screen.getByRole('textbox')).toHaveValue('');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('externalError 外部错误', () => {
|
||||||
|
it('设置 externalError 时应显示错误状态', () => {
|
||||||
|
render(<TextInputArea value="内容" onChange={() => {}} externalError="JSON 格式无效" />);
|
||||||
|
|
||||||
|
expect(screen.getByText('JSON 格式无效')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('externalError 为空时应隐藏错误状态', () => {
|
||||||
|
const { rerender } = render(
|
||||||
|
<TextInputArea value="内容" onChange={() => {}} externalError="错误" />,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('错误')).toBeInTheDocument();
|
||||||
|
|
||||||
|
rerender(<TextInputArea value="内容" onChange={() => {}} externalError="" />);
|
||||||
|
|
||||||
|
expect(screen.queryByText('错误')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('externalError 优先级高于内部验证错误', () => {
|
||||||
|
render(
|
||||||
|
<TextInputArea
|
||||||
|
value="ab"
|
||||||
|
onChange={() => {}}
|
||||||
|
externalError="外部错误"
|
||||||
|
validateTrigger="onChange"
|
||||||
|
rules={[{ validator: (v) => v.length >= 3, message: '内部验证错误' }]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('外部错误')).toBeInTheDocument();
|
||||||
|
expect(screen.queryByText('内部验证错误')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('externalError 清除后应显示内部验证错误', () => {
|
||||||
|
const { rerender } = render(
|
||||||
|
<TextInputArea
|
||||||
|
value="ab"
|
||||||
|
onChange={() => {}}
|
||||||
|
externalError="外部错误"
|
||||||
|
validateTrigger="onChange"
|
||||||
|
rules={[{ validator: (v) => v.length >= 3, message: '至少3个字符' }]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText('外部错误')).toBeInTheDocument();
|
||||||
|
|
||||||
|
rerender(
|
||||||
|
<TextInputArea
|
||||||
|
value="ab"
|
||||||
|
onChange={() => {}}
|
||||||
|
validateTrigger="onChange"
|
||||||
|
rules={[{ validator: (v) => v.length >= 3, message: '至少3个字符' }]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.queryByText('外部错误')).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
const textarea = screen.getByRole('textbox');
|
||||||
|
fireEvent.change(textarea, { target: { value: 'a' } });
|
||||||
|
|
||||||
|
expect(screen.getByText('至少3个字符')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('autoResize', () => {
|
||||||
|
it('autoResize=true 时设置 minRows/maxRows', () => {
|
||||||
|
const { container } = render(
|
||||||
|
<TextInputArea value="" onChange={() => {}} autoResize minRows={3} maxRows={8} />,
|
||||||
|
);
|
||||||
|
|
||||||
|
const textarea = container.querySelector('textarea');
|
||||||
|
expect(textarea).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('autoResize=false 时设置固定 rows', () => {
|
||||||
|
const { container } = render(
|
||||||
|
<TextInputArea value="" onChange={() => {}} autoResize={false} minRows={5} />,
|
||||||
|
);
|
||||||
|
|
||||||
|
const textarea = container.querySelector('textarea');
|
||||||
|
expect(textarea).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('样式集成', () => {
|
||||||
|
it('应透传 className', () => {
|
||||||
|
const { container } = render(
|
||||||
|
<TextInputArea value="" onChange={() => {}} className="custom-class" />,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(container.firstChild).toHaveClass('custom-class');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应透传 style', () => {
|
||||||
|
const { container } = render(
|
||||||
|
<TextInputArea value="" onChange={() => {}} style={{ marginTop: 10 }} />,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(container.firstChild).toHaveStyle({ marginTop: '10px' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应透传 sx 样式', () => {
|
||||||
|
const { container } = render(<TextInputArea value="" onChange={() => {}} sx={{ mb: 3 }} />);
|
||||||
|
|
||||||
|
expect(container.firstChild).toHaveStyle({ marginBottom: '24px' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { fireEvent, render, screen } from '@testing-library/react';
|
import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||||
|
import userEvent from '@testing-library/user-event';
|
||||||
import ToolCard from '@/pages/Dashboard/ToolCard';
|
import ToolCard from '@/pages/Dashboard/ToolCard';
|
||||||
import AccessTimeIcon from '@mui/icons-material/AccessTime';
|
import AccessTimeIcon from '@mui/icons-material/AccessTime';
|
||||||
|
|
||||||
@@ -96,7 +97,7 @@ describe('ToolCard 组件', () => {
|
|||||||
expect(handleClick).toHaveBeenCalledTimes(1);
|
expect(handleClick).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('按 Enter 键时应调用 onClick', () => {
|
it('按 Enter 键时应调用 onClick', async () => {
|
||||||
const handleClick = vi.fn();
|
const handleClick = vi.fn();
|
||||||
render(
|
render(
|
||||||
<ToolCard
|
<ToolCard
|
||||||
@@ -108,7 +109,10 @@ describe('ToolCard 组件', () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const button = screen.getByRole('button', { name: /键盘可触发/ });
|
const button = screen.getByRole('button', { name: /键盘可触发/ });
|
||||||
fireEvent.click(button);
|
await act(async () => {
|
||||||
|
button.focus();
|
||||||
|
await userEvent.keyboard('{Enter}');
|
||||||
|
});
|
||||||
|
|
||||||
expect(handleClick).toHaveBeenCalledTimes(1);
|
expect(handleClick).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -28,7 +28,6 @@ const mockRouterValue = {
|
|||||||
pageOrder: ['timestamp'] as PageType[],
|
pageOrder: ['timestamp'] as PageType[],
|
||||||
isLoaded: true,
|
isLoaded: true,
|
||||||
navigateTo: vi.fn(),
|
navigateTo: vi.fn(),
|
||||||
navigateLocal: vi.fn(),
|
|
||||||
syncNavigation: vi.fn(),
|
syncNavigation: vi.fn(),
|
||||||
goBack: vi.fn(),
|
goBack: vi.fn(),
|
||||||
setVisiblePages: vi.fn(),
|
setVisiblePages: vi.fn(),
|
||||||
|
|||||||
+145
-137
@@ -118,34 +118,62 @@ export const timestampPageStyles = {
|
|||||||
mutedText: (theme: Theme) => alpha(theme.palette.primary.main, 0.4),
|
mutedText: (theme: Theme) => alpha(theme.palette.primary.main, 0.4),
|
||||||
resultBg: (theme: Theme) => alpha(theme.palette.primary.main, 0.05),
|
resultBg: (theme: Theme) => alpha(theme.palette.primary.main, 0.05),
|
||||||
buttonHover: (theme: Theme) => `0 8px 24px ${alpha(theme.palette.primary.main, 0.2)}`,
|
buttonHover: (theme: Theme) => `0 8px 24px ${alpha(theme.palette.primary.main, 0.2)}`,
|
||||||
/** 模式切换器 (ToggleButtonGroup) 样式 */
|
/** 统一转换工作台外卡 */
|
||||||
MODE_SWITCHER: {
|
CONVERSION_CARD: {
|
||||||
width: '100%',
|
p: 2.5,
|
||||||
mb: 2.5,
|
|
||||||
borderRadius: 4,
|
borderRadius: 4,
|
||||||
bgcolor: (theme: Theme) => (theme.palette.mode === 'light' ? 'grey.100' : 'grey.900'),
|
bgcolor: 'background.paper',
|
||||||
border: '1px solid',
|
border: '1px solid',
|
||||||
borderColor: 'divider',
|
borderColor: 'divider',
|
||||||
p: 0.6,
|
boxShadow: '0 4px 16px rgba(0,0,0,0.04)',
|
||||||
'& .MuiToggleButtonGroup-grouped': {
|
},
|
||||||
flex: 1,
|
/** 桌面端左右分栏布局 (md 断点开始等宽分栏,两栏卡片等高) */
|
||||||
border: 'none',
|
LAYOUT_GRID: {
|
||||||
borderRadius: 3.5,
|
display: 'grid',
|
||||||
py: 1,
|
gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' },
|
||||||
fontWeight: 800,
|
gap: 2,
|
||||||
fontSize: '0.75rem',
|
alignItems: 'stretch',
|
||||||
color: 'text.secondary',
|
},
|
||||||
transition: 'color 0.3s',
|
/** 右栏结果卡片(独立卡片样式,与左栏等高) */
|
||||||
'&.Mui-selected': {
|
RESULT_COLUMN_CARD: {
|
||||||
|
p: 2.5,
|
||||||
|
borderRadius: 4,
|
||||||
bgcolor: 'background.paper',
|
bgcolor: 'background.paper',
|
||||||
color: 'primary.main',
|
border: '1px solid',
|
||||||
boxShadow: '0 4px 12px rgba(0,0,0,0.05)',
|
borderColor: 'divider',
|
||||||
|
boxShadow: '0 4px 16px rgba(0,0,0,0.04)',
|
||||||
|
height: '100%',
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
},
|
},
|
||||||
|
/** 结果区空状态占位(桌面端右栏未转换时) */
|
||||||
|
RESULT_EMPTY_PLACEHOLDER: {
|
||||||
|
flex: 1,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
color: 'text.disabled',
|
||||||
|
fontSize: '0.85rem',
|
||||||
|
fontWeight: 600,
|
||||||
|
py: 6,
|
||||||
|
textAlign: 'center',
|
||||||
},
|
},
|
||||||
|
/** 立即转换按钮(缩小+居中,融入卡片) */
|
||||||
|
CONVERT_BUTTON: {
|
||||||
|
display: 'block',
|
||||||
|
mx: 'auto',
|
||||||
|
mt: 2,
|
||||||
|
mb: 0.5,
|
||||||
|
maxWidth: 240,
|
||||||
|
width: '100%',
|
||||||
|
py: 1.1,
|
||||||
|
fontSize: '0.85rem',
|
||||||
|
borderRadius: 3,
|
||||||
},
|
},
|
||||||
/** 单位切换器样式 */
|
/** 单位切换器样式 */
|
||||||
UNIT_SWITCHER_CONTAINER: {
|
UNIT_SWITCHER_CONTAINER: {
|
||||||
flex: 1,
|
flexShrink: 0,
|
||||||
|
width: 160,
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
bgcolor: 'action.hover',
|
bgcolor: 'action.hover',
|
||||||
p: 0.5,
|
p: 0.5,
|
||||||
@@ -156,6 +184,9 @@ export const timestampPageStyles = {
|
|||||||
UNIT_SWITCHER_ITEM: (active: boolean) => ({
|
UNIT_SWITCHER_ITEM: (active: boolean) => ({
|
||||||
flex: 1,
|
flex: 1,
|
||||||
py: 0.8,
|
py: 0.8,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
textAlign: 'center',
|
textAlign: 'center',
|
||||||
borderRadius: 3,
|
borderRadius: 3,
|
||||||
cursor: 'pointer',
|
cursor: 'pointer',
|
||||||
@@ -166,66 +197,44 @@ export const timestampPageStyles = {
|
|||||||
color: active ? 'primary.main' : 'text.disabled',
|
color: active ? 'primary.main' : 'text.disabled',
|
||||||
boxShadow: active ? '0 2px 8px rgba(0,0,0,0.05)' : 'none',
|
boxShadow: active ? '0 2px 8px rgba(0,0,0,0.05)' : 'none',
|
||||||
}),
|
}),
|
||||||
/** LiveClock 卡片样式 */
|
/** LiveClock 参考条样式(瘦身为单行) */
|
||||||
LIVE_CLOCK_CARD: (theme: Theme) => ({
|
LIVE_CLOCK_CARD: (theme: Theme) => ({
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
justifyContent: 'space-between',
|
|
||||||
flexWrap: 'wrap',
|
|
||||||
gap: 1.5,
|
gap: 1.5,
|
||||||
p: 1.8,
|
px: 1.6,
|
||||||
mb: 2.5,
|
py: 0.8,
|
||||||
|
mb: 2,
|
||||||
bgcolor: alpha(theme.palette.primary.main, 0.04),
|
bgcolor: alpha(theme.palette.primary.main, 0.04),
|
||||||
borderRadius: 4,
|
borderRadius: 3,
|
||||||
border: '1px solid',
|
border: '1px solid',
|
||||||
borderColor: alpha(theme.palette.primary.main, 0.1),
|
borderColor: alpha(theme.palette.primary.main, 0.1),
|
||||||
}),
|
}),
|
||||||
LIVE_CLOCK_LABEL: {
|
LIVE_CLOCK_LABEL: {
|
||||||
color: 'primary.main',
|
color: 'primary.main',
|
||||||
fontWeight: 800,
|
fontWeight: 800,
|
||||||
fontSize: '0.6rem',
|
fontSize: '0.65rem',
|
||||||
textTransform: 'uppercase',
|
textTransform: 'uppercase',
|
||||||
letterSpacing: 1,
|
letterSpacing: 1,
|
||||||
|
whiteSpace: 'nowrap',
|
||||||
},
|
},
|
||||||
LIVE_CLOCK_VALUE: {
|
LIVE_CLOCK_VALUE: {
|
||||||
|
flex: 1,
|
||||||
fontWeight: 800,
|
fontWeight: 800,
|
||||||
color: 'primary.main',
|
color: 'primary.main',
|
||||||
fontFamily: 'monospace',
|
fontFamily: 'monospace',
|
||||||
fontSize: { xs: '1.1rem', sm: '1.2rem' },
|
fontSize: '0.95rem',
|
||||||
letterSpacing: '-0.5px',
|
letterSpacing: '-0.5px',
|
||||||
lineHeight: 1.2,
|
lineHeight: 1.2,
|
||||||
|
overflow: 'hidden',
|
||||||
|
textOverflow: 'ellipsis',
|
||||||
},
|
},
|
||||||
LIVE_CLOCK_UNIT_SWITCHER: (theme: Theme) => ({
|
|
||||||
display: 'flex',
|
|
||||||
p: 0.4,
|
|
||||||
bgcolor: alpha(theme.palette.primary.main, 0.08),
|
|
||||||
borderRadius: 2.5,
|
|
||||||
border: '1px solid',
|
|
||||||
borderColor: alpha(theme.palette.primary.main, 0.1),
|
|
||||||
}),
|
|
||||||
LIVE_CLOCK_UNIT_ITEM: (active: boolean) => (theme: Theme) => ({
|
|
||||||
px: { xs: 1, sm: 1.2 },
|
|
||||||
py: 0.35,
|
|
||||||
borderRadius: 2,
|
|
||||||
cursor: 'pointer',
|
|
||||||
fontSize: '0.65rem',
|
|
||||||
fontWeight: 900,
|
|
||||||
transition: 'all 0.2s',
|
|
||||||
bgcolor: active ? 'background.paper' : 'transparent',
|
|
||||||
color: active ? 'primary.main' : alpha(theme.palette.primary.main, 0.4),
|
|
||||||
boxShadow: active ? '0 2px 6px rgba(33, 150, 243, 0.2)' : 'none',
|
|
||||||
}),
|
|
||||||
LIVE_CLOCK_ICON_BUTTON: {
|
LIVE_CLOCK_ICON_BUTTON: {
|
||||||
color: 'primary.main',
|
color: 'primary.main',
|
||||||
bgcolor: 'background.paper',
|
bgcolor: 'background.paper',
|
||||||
boxShadow: '0 2px 4px rgba(0,0,0,0.05)',
|
boxShadow: '0 2px 4px rgba(0,0,0,0.05)',
|
||||||
'&:hover': { bgcolor: 'primary.main', color: 'primary.contrastText' },
|
'&:hover': { bgcolor: 'primary.main', color: 'primary.contrastText' },
|
||||||
},
|
},
|
||||||
LIVE_CLOCK_DIVIDER: {
|
|
||||||
mx: 0.5,
|
|
||||||
my: 1,
|
|
||||||
borderColor: (theme: Theme) => alpha(theme.palette.primary.main, 0.1),
|
|
||||||
},
|
|
||||||
/** ResultView 样式 */
|
/** ResultView 样式 */
|
||||||
RESULT_LABEL: {
|
RESULT_LABEL: {
|
||||||
color: 'text.secondary',
|
color: 'text.secondary',
|
||||||
@@ -235,24 +244,26 @@ export const timestampPageStyles = {
|
|||||||
fontSize: '0.7rem',
|
fontSize: '0.7rem',
|
||||||
},
|
},
|
||||||
RESULT_MAIN_BOX: (theme: Theme) => ({
|
RESULT_MAIN_BOX: (theme: Theme) => ({
|
||||||
bgcolor: alpha(theme.palette.primary.main, 0.05),
|
bgcolor: alpha(theme.palette.primary.main, 0.12),
|
||||||
p: 2,
|
p: 2.2,
|
||||||
borderRadius: 4,
|
borderRadius: 4,
|
||||||
position: 'relative',
|
position: 'relative',
|
||||||
mb: 2.5,
|
mb: 2,
|
||||||
border: '1px solid',
|
border: '1px solid',
|
||||||
borderColor: alpha(theme.palette.primary.main, 0.1),
|
borderColor: alpha(theme.palette.primary.main, 0.2),
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
justifyContent: 'space-between',
|
justifyContent: 'space-between',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
}),
|
}),
|
||||||
RESULT_MAIN_TEXT: {
|
RESULT_MAIN_TEXT: {
|
||||||
fontFamily: 'monospace',
|
fontFamily: 'monospace',
|
||||||
fontWeight: 700,
|
fontWeight: 800,
|
||||||
color: 'primary.main',
|
color: 'primary.main',
|
||||||
wordBreak: 'break-all',
|
wordBreak: 'break-all',
|
||||||
pr: 4,
|
pr: 4,
|
||||||
fontSize: '1rem',
|
fontSize: '1.35rem',
|
||||||
|
letterSpacing: '-0.5px',
|
||||||
|
lineHeight: 1.2,
|
||||||
},
|
},
|
||||||
RESULT_EXTRA_STACK: (theme: Theme) => ({
|
RESULT_EXTRA_STACK: (theme: Theme) => ({
|
||||||
bgcolor: alpha(theme.palette.primary.main, 0.05),
|
bgcolor: alpha(theme.palette.primary.main, 0.05),
|
||||||
@@ -264,14 +275,17 @@ export const timestampPageStyles = {
|
|||||||
RESULT_EXTRA_LABEL: {
|
RESULT_EXTRA_LABEL: {
|
||||||
color: 'text.disabled',
|
color: 'text.disabled',
|
||||||
fontWeight: 700,
|
fontWeight: 700,
|
||||||
fontSize: '0.65rem',
|
fontSize: '0.7rem',
|
||||||
pr: 4,
|
pr: 2,
|
||||||
|
whiteSpace: 'nowrap',
|
||||||
},
|
},
|
||||||
RESULT_EXTRA_VALUE: {
|
RESULT_EXTRA_VALUE: {
|
||||||
fontFamily: 'monospace',
|
fontFamily: 'monospace',
|
||||||
color: 'primary.main',
|
color: 'primary.main',
|
||||||
fontWeight: 600,
|
fontWeight: 600,
|
||||||
fontSize: '0.65rem',
|
fontSize: '0.75rem',
|
||||||
|
wordBreak: 'break-all',
|
||||||
|
textAlign: 'right',
|
||||||
},
|
},
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
@@ -546,6 +560,74 @@ export const storageCleanerPageStyles = {
|
|||||||
*/
|
*/
|
||||||
export const qrCodePageStyles = {
|
export const qrCodePageStyles = {
|
||||||
primaryColor: THEME_COLORS.success,
|
primaryColor: THEME_COLORS.success,
|
||||||
|
/** 桌面端左右分栏布局 (md 断点开始等宽分栏,两栏卡片等高) */
|
||||||
|
LAYOUT_GRID: {
|
||||||
|
display: 'grid',
|
||||||
|
gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' },
|
||||||
|
gap: 2,
|
||||||
|
alignItems: 'stretch',
|
||||||
|
},
|
||||||
|
/** 桌面端 grid item 包装:撑满 grid row 并把高度传给 Accordion */
|
||||||
|
GRID_CELL: {
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
height: '100%',
|
||||||
|
'& > .MuiAccordion-root': {
|
||||||
|
flex: 1,
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
},
|
||||||
|
} as const,
|
||||||
|
/** 桌面端 Accordion 强展开样式:隐藏箭头,禁用 hover/cursor,等高填充 */
|
||||||
|
ACCORDION_DESKTOP: {
|
||||||
|
borderRadius: 4,
|
||||||
|
boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)',
|
||||||
|
height: '100%',
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
overflow: 'hidden',
|
||||||
|
'&:before': { display: 'none' },
|
||||||
|
'& .MuiAccordionSummary-root': {
|
||||||
|
cursor: 'default',
|
||||||
|
},
|
||||||
|
'& .MuiAccordionSummary-expandIconWrapper': {
|
||||||
|
display: 'none',
|
||||||
|
},
|
||||||
|
// 让 Collapse 整条链都 flex 撑满,否则 Details 拿不到剩余高度
|
||||||
|
'& .MuiCollapse-root': {
|
||||||
|
flex: 1,
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
},
|
||||||
|
'& .MuiCollapse-wrapper': {
|
||||||
|
flex: 1,
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
},
|
||||||
|
'& .MuiCollapse-wrapperInner': {
|
||||||
|
flex: 1,
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
},
|
||||||
|
'& .MuiAccordion-region': {
|
||||||
|
flex: 1,
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
},
|
||||||
|
'& .MuiAccordionDetails-root': {
|
||||||
|
flex: 1,
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
},
|
||||||
|
'& .MuiAccordionDetails-root > .MuiStack-root': {
|
||||||
|
flex: 1,
|
||||||
|
},
|
||||||
|
'& .qr-flex-grow': {
|
||||||
|
flex: 1,
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
},
|
||||||
|
} as const,
|
||||||
/** 加载状态容器 */
|
/** 加载状态容器 */
|
||||||
LOADING_CONTAINER: {
|
LOADING_CONTAINER: {
|
||||||
py: 4,
|
py: 4,
|
||||||
@@ -559,6 +641,7 @@ export const qrCodePageStyles = {
|
|||||||
ACCORDION: {
|
ACCORDION: {
|
||||||
borderRadius: 4,
|
borderRadius: 4,
|
||||||
boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)',
|
boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)',
|
||||||
|
overflow: 'hidden',
|
||||||
'&:before': { display: 'none' },
|
'&:before': { display: 'none' },
|
||||||
} as const,
|
} as const,
|
||||||
ACCORDION_SUMMARY: {
|
ACCORDION_SUMMARY: {
|
||||||
@@ -702,6 +785,7 @@ export const dashboardPageStyles = {
|
|||||||
xs: '1fr',
|
xs: '1fr',
|
||||||
sm: 'repeat(auto-fill, minmax(300px, 1fr))',
|
sm: 'repeat(auto-fill, minmax(300px, 1fr))',
|
||||||
},
|
},
|
||||||
|
gridAutoRows: '1fr',
|
||||||
gap: 2,
|
gap: 2,
|
||||||
p: 2,
|
p: 2,
|
||||||
},
|
},
|
||||||
@@ -743,38 +827,6 @@ export const textStatisticsPageStyles = {
|
|||||||
cardBorder: (theme: Theme) => alpha(theme.palette.secondary.main, 0.1),
|
cardBorder: (theme: Theme) => alpha(theme.palette.secondary.main, 0.1),
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
/**
|
|
||||||
* TopBar 组件样式
|
|
||||||
*/
|
|
||||||
export const topBarStyles = {
|
|
||||||
SEARCH_MAX_WIDTH: 400,
|
|
||||||
DROPDOWN_MAX_HEIGHT: 300,
|
|
||||||
Z_INDEX: 1100,
|
|
||||||
DROPDOWN_Z_INDEX: 1200,
|
|
||||||
SEARCH_HISTORY_LIMIT: 10,
|
|
||||||
SEARCH_HISTORY_DISPLAY: 5,
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* JWT 解析工具页面样式
|
|
||||||
*/
|
|
||||||
export const jwtPageStyles = {
|
|
||||||
primaryColor: THEME_COLORS.indigo,
|
|
||||||
cardBg: (theme: Theme) => alpha(theme.palette.info.main, 0.04),
|
|
||||||
cardBorder: (theme: Theme) => alpha(theme.palette.info.main, 0.1),
|
|
||||||
INPUT_STYLE: {
|
|
||||||
'& .MuiOutlinedInput-root': {
|
|
||||||
bgcolor: 'background.paper',
|
|
||||||
borderRadius: 4,
|
|
||||||
fontSize: '0.85rem',
|
|
||||||
fontFamily: 'monospace',
|
|
||||||
transition: 'all 0.2s',
|
|
||||||
'&:hover': { bgcolor: 'action.hover' },
|
|
||||||
'&.Mui-focused': { bgcolor: 'background.paper' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Base64 转换器页面样式
|
* Base64 转换器页面样式
|
||||||
*/
|
*/
|
||||||
@@ -791,28 +843,6 @@ export const markdownToHtmlPageStyles = {
|
|||||||
primaryColor: THEME_COLORS.purple,
|
primaryColor: THEME_COLORS.purple,
|
||||||
cardBg: (theme: Theme) => alpha(theme.palette.secondary.main, 0.04),
|
cardBg: (theme: Theme) => alpha(theme.palette.secondary.main, 0.04),
|
||||||
cardBorder: (theme: Theme) => alpha(theme.palette.secondary.main, 0.1),
|
cardBorder: (theme: Theme) => alpha(theme.palette.secondary.main, 0.1),
|
||||||
MODE_SWITCHER: {
|
|
||||||
borderRadius: 4,
|
|
||||||
bgcolor: (theme: Theme) => (theme.palette.mode === 'light' ? 'grey.100' : 'grey.900'),
|
|
||||||
border: '1px solid',
|
|
||||||
borderColor: 'divider',
|
|
||||||
p: 0.6,
|
|
||||||
'& .MuiToggleButtonGroup-grouped': {
|
|
||||||
border: 'none',
|
|
||||||
borderRadius: 3.5,
|
|
||||||
py: 0.8,
|
|
||||||
px: 1.5,
|
|
||||||
fontWeight: 700,
|
|
||||||
fontSize: '0.75rem',
|
|
||||||
color: 'text.secondary',
|
|
||||||
transition: 'color 0.3s',
|
|
||||||
'&.Mui-selected': {
|
|
||||||
bgcolor: 'background.paper',
|
|
||||||
color: 'primary.main',
|
|
||||||
boxShadow: '0 4px 12px rgba(0,0,0,0.05)',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -822,28 +852,6 @@ export const htmlToMarkdownPageStyles = {
|
|||||||
primaryColor: THEME_COLORS.purple,
|
primaryColor: THEME_COLORS.purple,
|
||||||
cardBg: (theme: Theme) => alpha(theme.palette.secondary.main, 0.04),
|
cardBg: (theme: Theme) => alpha(theme.palette.secondary.main, 0.04),
|
||||||
cardBorder: (theme: Theme) => alpha(theme.palette.secondary.main, 0.1),
|
cardBorder: (theme: Theme) => alpha(theme.palette.secondary.main, 0.1),
|
||||||
MODE_SWITCHER: {
|
|
||||||
borderRadius: 4,
|
|
||||||
bgcolor: (theme: Theme) => (theme.palette.mode === 'light' ? 'grey.100' : 'grey.900'),
|
|
||||||
border: '1px solid',
|
|
||||||
borderColor: 'divider',
|
|
||||||
p: 0.6,
|
|
||||||
'& .MuiToggleButtonGroup-grouped': {
|
|
||||||
border: 'none',
|
|
||||||
borderRadius: 3.5,
|
|
||||||
py: 0.8,
|
|
||||||
px: 1.5,
|
|
||||||
fontWeight: 700,
|
|
||||||
fontSize: '0.75rem',
|
|
||||||
color: 'text.secondary',
|
|
||||||
transition: 'color 0.3s',
|
|
||||||
'&.Mui-selected': {
|
|
||||||
bgcolor: 'background.paper',
|
|
||||||
color: 'primary.main',
|
|
||||||
boxShadow: '0 4px 12px rgba(0,0,0,0.05)',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
# 为懒加载页面组件添加独立 ErrorBoundary 保护 — 设计文档
|
||||||
|
|
||||||
|
- 日期:2026-05-13
|
||||||
|
- 范围:popup / sidepanel / tab / options 入口下的页面错误隔离
|
||||||
|
|
||||||
|
## 背景与目标
|
||||||
|
|
||||||
|
当前应用通过 `config/features.tsx` 中的 `React.lazy()` 懒加载所有页面组件。`RouterContainer` 使用 `Suspense` 包裹动态组件,而错误边界仅在外层 `entrypoints/popup/App.tsx`、`entrypoints/sidepanel/App.tsx` 中包裹 `RouterContainer`、以及 `entrypoints/options/App.tsx` 顶层。
|
||||||
|
|
||||||
|
问题:单个懒加载页面在加载或渲染时一旦抛错,错误会冒泡到全局 `ErrorBoundary`,触发全屏错误 UI,整个路由容器和 TopBar 一起被替换。用户必须刷新页面才能继续使用其他工具,体验受损。
|
||||||
|
|
||||||
|
目标:将错误影响范围限制在当前页面区域;其他页面、TopBar、导航、Snackbar 不受影响;用户可在错误状态下切换到其他工具或重试当前页。
|
||||||
|
|
||||||
|
## 设计概要
|
||||||
|
|
||||||
|
新增 `PageErrorBoundary` 组件,专门用于页面级错误隔离,在 `RouterContainer` 的 `Suspense` 内层使用;`options/App.tsx` 也替换为同款页面级边界。现有全局 `ErrorBoundary` 保留作为兜底,覆盖 TopBar / Snackbar / RouterProvider 等同级组件。
|
||||||
|
|
||||||
|
## 组件设计
|
||||||
|
|
||||||
|
### `components/PageErrorBoundary.tsx`(新增)
|
||||||
|
|
||||||
|
复用现有 `ErrorBoundary` 的错误捕获机制(`getDerivedStateFromError` + `componentDidCatch`),但具备以下差异:
|
||||||
|
|
||||||
|
- **轻量内嵌 UI**:使用 `Paper` + 居中文本,去除全屏 `Container` + `mt:8` 布局,适配 popup 400×600 与 sidepanel 等窄屏环境。结构:
|
||||||
|
- 图标 (`ErrorOutlineIcon`)
|
||||||
|
- 标题:"该页面加载失败"
|
||||||
|
- 副标题:"页面在加载或渲染时遇到错误,您可以重试或切换到其他工具。"
|
||||||
|
- 折叠错误信息块(沿用现有错误展示样式,使用 monospace、可滚动)
|
||||||
|
- 主操作按钮:"重试"(`RefreshIcon`)—— 重置内部 state,让子树重新挂载
|
||||||
|
- **`resetKey` prop**:可选;当 `resetKey` 在 `componentDidUpdate` 中变化时,自动重置 `hasError` / `error`,无需用户手动操作
|
||||||
|
- **`componentDidCatch`**:仍使用 `console.error('Uncaught error in page:', error, errorInfo)` 输出,不引入额外上报
|
||||||
|
|
||||||
|
接口:
|
||||||
|
```ts
|
||||||
|
interface PageErrorBoundaryProps {
|
||||||
|
children: ReactNode;
|
||||||
|
resetKey?: string | number; // 变化时自动重置
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `components/ErrorBoundary.tsx`(不变)
|
||||||
|
|
||||||
|
保留作为全局兜底。负责捕获 TopBar、SnackbarProvider、RouterProvider 等同级组件中可能出现的错误,沿用全屏 `Container` 样式与"刷新应用"操作。
|
||||||
|
|
||||||
|
## 集成点
|
||||||
|
|
||||||
|
### `components/RouterContainer.tsx`(修改)
|
||||||
|
|
||||||
|
在 `Suspense` 内层插入 `PageErrorBoundary`,传入 `resetKey={currentPage}`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
<Suspense fallback={<Spinner />}>
|
||||||
|
<PageErrorBoundary resetKey={currentPage}>
|
||||||
|
{Component && <Component />}
|
||||||
|
</PageErrorBoundary>
|
||||||
|
</Suspense>
|
||||||
|
```
|
||||||
|
|
||||||
|
说明:
|
||||||
|
- `PageErrorBoundary` 置于 `Suspense` 内部,可同时捕获懒加载 chunk 加载失败(异步异常)与页面渲染期同步错误
|
||||||
|
- `resetKey={currentPage}` 使页面切换时自动清除错误状态,无需用户干预
|
||||||
|
- 保留外层 `Box key={currentPage}` 与动画 className,不改变页面切换语义
|
||||||
|
|
||||||
|
### `entrypoints/options/App.tsx`(修改)
|
||||||
|
|
||||||
|
将顶层 `<ErrorBoundary>` 替换为 `<PageErrorBoundary>`。options 是单页应用,统一使用页面级错误卡片即可。
|
||||||
|
|
||||||
|
### `entrypoints/popup/App.tsx`、`entrypoints/sidepanel/App.tsx`(不变)
|
||||||
|
|
||||||
|
保留外层 `<ErrorBoundary>` 包裹 `<RouterContainer />`,作为同级组件(TopBar 等)的兜底。`PageErrorBoundary` 与全局 `ErrorBoundary` 各司其职:
|
||||||
|
|
||||||
|
- 页面级(`PageErrorBoundary`):捕获懒加载页面内部错误,隔离影响范围,仅替换页面区域
|
||||||
|
- 全局(`ErrorBoundary`):捕获 RouterContainer 自身、TopBar、Snackbar 等组件错误,作为最后兜底
|
||||||
|
|
||||||
|
## 数据流 / 错误处理
|
||||||
|
|
||||||
|
### 捕获路径
|
||||||
|
- 懒加载 chunk 加载失败(网络 / CSP / chunk 缺失) → `Suspense` 内部 promise reject → `PageErrorBoundary` 捕获
|
||||||
|
- 页面渲染期同步错误(组件抛错、null 引用等) → `PageErrorBoundary` 捕获
|
||||||
|
- 事件回调或 Promise 中的异步错误 → React 错误边界不捕获(固有行为,本次不处理)
|
||||||
|
|
||||||
|
### 恢复路径
|
||||||
|
- **页面切换自动重置**:用户从错误页切换到其他页面 → `currentPage` 变化 → `resetKey` 变化 → `PageErrorBoundary.componentDidUpdate` 重置 → 新页面正常渲染
|
||||||
|
- **当前页重试**:用户点击"重试" → 内部 state 重置 → 子树重新挂载 → React 重新触发 `lazy()` 加载(懒加载失败时也会重新发起 `import()`)
|
||||||
|
- **持续错误**:若 `lazy()` chunk 始终无法加载(例如永久 404),重试会再次显示错误卡片;用户可切换到其他页面继续使用其他工具
|
||||||
|
|
||||||
|
### 日志
|
||||||
|
沿用 `console.error`;不引入 Sentry / 外部上报。
|
||||||
|
|
||||||
|
## 测试策略
|
||||||
|
|
||||||
|
### 新增 `components/__tests__/PageErrorBoundary.test.tsx`
|
||||||
|
|
||||||
|
1. 正常渲染:子组件正常渲染时,输出原始 children
|
||||||
|
2. 同步错误捕获:子组件抛错时,显示错误卡片(标题"该页面加载失败"、错误信息)
|
||||||
|
3. 重试按钮恢复:错误状态下,将 children 替换为正常组件,点击"重试"按钮,重置状态并显示正常内容
|
||||||
|
4. `resetKey` 变化自动重置:错误状态下 `resetKey` 变化时,自动清空错误并渲染新 children
|
||||||
|
5. `resetKey` 不变保持错误:children 变化但 `resetKey` 未变化时,保持错误状态(避免误重置)
|
||||||
|
6. 错误信息显示:错误的 `toString()` 内容能在 UI 中可见
|
||||||
|
|
||||||
|
### 新增 `components/__tests__/RouterContainer.test.tsx`
|
||||||
|
|
||||||
|
- 通过 mock `useRouter` 与 `FEATURES`,注入一个会抛错的懒加载组件,验证 `PageErrorBoundary` 捕获错误且 TopBar / 父容器 DOM 仍存在
|
||||||
|
- 切换 `currentPage`(重新触发 hook 返回值)后验证错误自动清除、新页面正常渲染
|
||||||
|
|
||||||
|
### 不变
|
||||||
|
- `components/__tests__/ErrorBoundary.test.tsx` 不需改动(全局边界行为未变)
|
||||||
|
|
||||||
|
### 风格
|
||||||
|
遵循现有 `ErrorBoundary.test.tsx` 模式:`vi.spyOn(console, 'error')` 抑制噪声 + `@testing-library/react` 的 `render` + `screen.getByText` 断言。
|
||||||
|
|
||||||
|
## 文件清单
|
||||||
|
|
||||||
|
**新增:**
|
||||||
|
- `components/PageErrorBoundary.tsx`
|
||||||
|
- `components/__tests__/PageErrorBoundary.test.tsx`
|
||||||
|
- `components/__tests__/RouterContainer.test.tsx`
|
||||||
|
|
||||||
|
**修改:**
|
||||||
|
- `components/RouterContainer.tsx` — 在 `Suspense` 内层包裹 `PageErrorBoundary resetKey={currentPage}`
|
||||||
|
- `entrypoints/options/App.tsx` — 将 `<ErrorBoundary>` 替换为 `<PageErrorBoundary>`
|
||||||
|
|
||||||
|
**不变:**
|
||||||
|
- `components/ErrorBoundary.tsx`
|
||||||
|
- `components/__tests__/ErrorBoundary.test.tsx`
|
||||||
|
- `entrypoints/popup/App.tsx`、`entrypoints/sidepanel/App.tsx`
|
||||||
|
- `config/features.tsx`
|
||||||
|
|
||||||
|
## 验收标准
|
||||||
|
|
||||||
|
1. 单页面在懒加载或渲染时抛错,仅当前页面区域显示错误卡片,TopBar 与导航仍可点击
|
||||||
|
2. 在错误状态下切换到其他工具,新页面能正常加载与显示
|
||||||
|
3. 点击错误卡片中的"重试"按钮,子树重新挂载并重新触发懒加载
|
||||||
|
4. 全局 `ErrorBoundary` 仍能捕获 TopBar / Snackbar 等同级组件的错误
|
||||||
|
5. 所有新增测试通过;现有 `ErrorBoundary` 测试不受影响;`npm run compile`、`npm run lint`、`npm run test` 均通过
|
||||||
@@ -19,7 +19,9 @@ export default defineBackground(() => {
|
|||||||
const { tabId, delay = 0 } = message.data;
|
const { tabId, delay = 0 } = message.data;
|
||||||
|
|
||||||
const executeReload = () => {
|
const executeReload = () => {
|
||||||
browser.tabs.reload(tabId);
|
browser.tabs.reload(tabId).catch((err) => {
|
||||||
|
console.error('Failed to reload tab:', err);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
if (delay > 0) {
|
if (delay > 0) {
|
||||||
|
|||||||
+239
-210
@@ -2,42 +2,208 @@ import { SyntheticEvent, useEffect, useMemo, useState } from 'react';
|
|||||||
import {
|
import {
|
||||||
alpha,
|
alpha,
|
||||||
Box,
|
Box,
|
||||||
Button,
|
|
||||||
CircularProgress,
|
CircularProgress,
|
||||||
Divider,
|
|
||||||
IconButton,
|
IconButton,
|
||||||
Paper,
|
Paper,
|
||||||
Stack,
|
Stack,
|
||||||
Switch,
|
Switch,
|
||||||
Tab,
|
Tab,
|
||||||
Tabs,
|
Tabs,
|
||||||
|
Tooltip,
|
||||||
Typography,
|
Typography,
|
||||||
} from '@mui/material';
|
} from '@mui/material';
|
||||||
import SettingsIcon from '@mui/icons-material/Settings';
|
import SettingsIcon from '@mui/icons-material/Settings';
|
||||||
import RefreshIcon from '@mui/icons-material/Refresh';
|
import RefreshIcon from '@mui/icons-material/Refresh';
|
||||||
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
|
|
||||||
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
|
|
||||||
import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
|
import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
|
||||||
|
import {
|
||||||
|
DndContext,
|
||||||
|
closestCenter,
|
||||||
|
PointerSensor,
|
||||||
|
KeyboardSensor,
|
||||||
|
useSensor,
|
||||||
|
useSensors,
|
||||||
|
type DragEndEvent,
|
||||||
|
} from '@dnd-kit/core';
|
||||||
|
import {
|
||||||
|
arrayMove,
|
||||||
|
SortableContext,
|
||||||
|
sortableKeyboardCoordinates,
|
||||||
|
useSortable,
|
||||||
|
verticalListSortingStrategy,
|
||||||
|
} from '@dnd-kit/sortable';
|
||||||
|
import { CSS } from '@dnd-kit/utilities';
|
||||||
import type { PageType, StorageSchema } from '@/types/storage';
|
import type { PageType, StorageSchema } from '@/types/storage';
|
||||||
import { storageUtil } from '@/utils/chromeStorage';
|
import { storageUtil } from '@/utils/chromeStorage';
|
||||||
import {
|
import {
|
||||||
|
getAllFeatureKeys,
|
||||||
getDefaultPageOrder,
|
getDefaultPageOrder,
|
||||||
getDefaultVisibleFeatureKeys,
|
getDefaultVisibleFeatureKeys,
|
||||||
getFeatureByKey,
|
getFeatureByKey,
|
||||||
} from '@/config/features';
|
} from '@/config/features';
|
||||||
import GlobalSnackbar, { useSnackbarState } from '@/components/GlobalSnackbar';
|
import GlobalSnackbar, { useSnackbarState } from '@/components/GlobalSnackbar';
|
||||||
import ErrorBoundary from '@/components/ErrorBoundary';
|
import PageErrorBoundary from '@/components/PageErrorBoundary';
|
||||||
import PageHeader from '@/components/PageHeader';
|
import PageHeader from '@/components/PageHeader';
|
||||||
import { useTheme, type PaletteColor, type Theme } from '@mui/material/styles';
|
import { useTheme, type PaletteColor, type Theme } from '@mui/material/styles';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import type { PaletteColorKey } from '@/config/features';
|
import type { PaletteColorKey } from '@/config/features';
|
||||||
|
|
||||||
/** 安全地从 theme.palette 中取 PaletteColor */
|
|
||||||
const getPaletteColor = (theme: Theme, key: PaletteColorKey): PaletteColor =>
|
const getPaletteColor = (theme: Theme, key: PaletteColorKey): PaletteColor =>
|
||||||
(theme.palette as unknown as Record<string, PaletteColor>)[key];
|
(theme.palette as unknown as Record<string, PaletteColor>)[key];
|
||||||
|
|
||||||
|
const isValidPage = (page: unknown): page is PageType => {
|
||||||
|
return typeof page === 'string' && (getAllFeatureKeys() as string[]).includes(page);
|
||||||
|
};
|
||||||
|
|
||||||
|
const isValidPageList = (pages: unknown): pages is PageType[] => {
|
||||||
|
return Array.isArray(pages) && pages.every(isValidPage);
|
||||||
|
};
|
||||||
|
|
||||||
type WindowType = 'popup' | 'sidepanel' | 'tab';
|
type WindowType = 'popup' | 'sidepanel' | 'tab';
|
||||||
|
|
||||||
|
interface SortableFeatureRowProps {
|
||||||
|
pageKey: PageType;
|
||||||
|
isLast: boolean;
|
||||||
|
isChecked: boolean;
|
||||||
|
isDisabled: boolean;
|
||||||
|
onToggle: (key: PageType) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SortableFeatureRow({
|
||||||
|
pageKey,
|
||||||
|
isLast,
|
||||||
|
isChecked,
|
||||||
|
isDisabled,
|
||||||
|
onToggle,
|
||||||
|
}: SortableFeatureRowProps) {
|
||||||
|
const theme = useTheme();
|
||||||
|
const { t } = useTranslation(['features']);
|
||||||
|
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
|
||||||
|
id: pageKey,
|
||||||
|
});
|
||||||
|
|
||||||
|
const feature = getFeatureByKey(pageKey);
|
||||||
|
if (!feature) return null;
|
||||||
|
|
||||||
|
const colorKey = feature.themeColorKey ?? 'primary';
|
||||||
|
const colorCode = getPaletteColor(theme, colorKey).main;
|
||||||
|
|
||||||
|
const style = {
|
||||||
|
transform: CSS.Transform.toString(transform),
|
||||||
|
transition,
|
||||||
|
zIndex: isDragging ? 1 : 'auto',
|
||||||
|
position: 'relative' as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
ref={setNodeRef}
|
||||||
|
style={style}
|
||||||
|
sx={{
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
p: { xs: 2, sm: 2.5 },
|
||||||
|
borderBottom: isLast ? 'none' : '1px solid',
|
||||||
|
borderColor: 'divider',
|
||||||
|
bgcolor: isDragging ? alpha(colorCode, 0.04) : 'transparent',
|
||||||
|
boxShadow: isDragging ? `0 8px 20px ${alpha('#000', 0.08)}` : 'none',
|
||||||
|
transition: 'background-color 0.2s, box-shadow 0.2s',
|
||||||
|
'&:hover': {
|
||||||
|
bgcolor: alpha(colorCode, 0.02),
|
||||||
|
},
|
||||||
|
'&:hover .drag-handle': {
|
||||||
|
color: 'text.secondary',
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
spacing={{ xs: 1.5, sm: 2 }}
|
||||||
|
alignItems="center"
|
||||||
|
sx={{ flex: 1, minWidth: 0 }}
|
||||||
|
>
|
||||||
|
{/* 拖拽手柄 - 整行可拖,手柄是视觉暗示 */}
|
||||||
|
<Box
|
||||||
|
className="drag-handle"
|
||||||
|
{...attributes}
|
||||||
|
{...listeners}
|
||||||
|
sx={{
|
||||||
|
color: alpha(theme.palette.text.primary, 0.2),
|
||||||
|
display: 'flex',
|
||||||
|
cursor: 'grab',
|
||||||
|
touchAction: 'none',
|
||||||
|
transition: 'color 0.2s',
|
||||||
|
'&:active': { cursor: 'grabbing' },
|
||||||
|
'&:hover': { color: 'text.secondary' },
|
||||||
|
}}
|
||||||
|
aria-label={`拖拽以调整 ${t(feature.labelKey)} 的位置`}
|
||||||
|
>
|
||||||
|
<DragIndicatorIcon fontSize="small" />
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{/* 功能图标 */}
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
width: 36,
|
||||||
|
height: 36,
|
||||||
|
borderRadius: 2.5,
|
||||||
|
bgcolor: alpha(colorCode, 0.1),
|
||||||
|
color: colorCode,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{feature.icon}
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{/* 文本信息 */}
|
||||||
|
<Box sx={{ minWidth: 0, flex: 1 }}>
|
||||||
|
<Typography
|
||||||
|
variant="subtitle2"
|
||||||
|
sx={{
|
||||||
|
fontWeight: 700,
|
||||||
|
color: 'text.primary',
|
||||||
|
fontSize: '0.95rem',
|
||||||
|
lineHeight: 1.3,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t(feature.labelKey)}
|
||||||
|
</Typography>
|
||||||
|
{feature.descriptionKey && (
|
||||||
|
<Tooltip title={t(feature.descriptionKey)} placement="top-start" enterDelay={400}>
|
||||||
|
<Typography
|
||||||
|
variant="caption"
|
||||||
|
color="text.secondary"
|
||||||
|
sx={{
|
||||||
|
fontWeight: 500,
|
||||||
|
mt: 0.25,
|
||||||
|
display: '-webkit-box',
|
||||||
|
WebkitBoxOrient: 'vertical',
|
||||||
|
WebkitLineClamp: 1,
|
||||||
|
overflow: 'hidden',
|
||||||
|
textOverflow: 'ellipsis',
|
||||||
|
wordBreak: 'break-word',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t(feature.descriptionKey)}
|
||||||
|
</Typography>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
<Switch
|
||||||
|
color="primary"
|
||||||
|
checked={isChecked}
|
||||||
|
onChange={() => onToggle(pageKey)}
|
||||||
|
disabled={isDisabled}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Options 设置页面主组件
|
* Options 设置页面主组件
|
||||||
* 支持对不同窗口入口的功能显示和排序进行独立配置
|
* 支持对不同窗口入口的功能显示和排序进行独立配置
|
||||||
@@ -45,7 +211,7 @@ type WindowType = 'popup' | 'sidepanel' | 'tab';
|
|||||||
export default function App() {
|
export default function App() {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const { t } = useTranslation(['features', 'common']);
|
const { t } = useTranslation(['features', 'common']);
|
||||||
// 从 URL 参数中初始化当前的 Tab 类型
|
|
||||||
const initialWindowType = useMemo(() => {
|
const initialWindowType = useMemo(() => {
|
||||||
if (typeof window === 'undefined') return 'popup';
|
if (typeof window === 'undefined') return 'popup';
|
||||||
const params = new URLSearchParams(window.location.search);
|
const params = new URLSearchParams(window.location.search);
|
||||||
@@ -62,7 +228,11 @@ export default function App() {
|
|||||||
const [isLoaded, setIsLoaded] = useState(false);
|
const [isLoaded, setIsLoaded] = useState(false);
|
||||||
const { snackbarProps, showMessage } = useSnackbarState();
|
const { snackbarProps, showMessage } = useSnackbarState();
|
||||||
|
|
||||||
// 根据当前选择的窗口类型确定对应的 Storage Key
|
const sensors = useSensors(
|
||||||
|
useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
|
||||||
|
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
|
||||||
|
);
|
||||||
|
|
||||||
const configKeys = useMemo(() => {
|
const configKeys = useMemo(() => {
|
||||||
switch (windowType) {
|
switch (windowType) {
|
||||||
case 'sidepanel':
|
case 'sidepanel':
|
||||||
@@ -84,14 +254,12 @@ export default function App() {
|
|||||||
}
|
}
|
||||||
}, [windowType]);
|
}, [windowType]);
|
||||||
|
|
||||||
// 当 windowType 改变时,同步更新 URL 参数
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const url = new URL(window.location.href);
|
const url = new URL(window.location.href);
|
||||||
url.searchParams.set('tab', windowType);
|
url.searchParams.set('tab', windowType);
|
||||||
window.history.replaceState({}, '', url.toString());
|
window.history.replaceState({}, '', url.toString());
|
||||||
}, [windowType]);
|
}, [windowType]);
|
||||||
|
|
||||||
// 加载配置数据
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const loadConfig = async () => {
|
const loadConfig = async () => {
|
||||||
setIsLoaded(false);
|
setIsLoaded(false);
|
||||||
@@ -100,8 +268,10 @@ export default function App() {
|
|||||||
storageUtil.get(configKeys.visible, getDefaultVisibleFeatureKeys()),
|
storageUtil.get(configKeys.visible, getDefaultVisibleFeatureKeys()),
|
||||||
storageUtil.get(configKeys.order, getDefaultPageOrder()),
|
storageUtil.get(configKeys.order, getDefaultPageOrder()),
|
||||||
]);
|
]);
|
||||||
setVisiblePages((savedVisible as PageType[]) ?? getDefaultVisibleFeatureKeys());
|
setVisiblePages(
|
||||||
setPageOrder((savedOrder as PageType[]) ?? getDefaultPageOrder());
|
isValidPageList(savedVisible) ? savedVisible : getDefaultVisibleFeatureKeys(),
|
||||||
|
);
|
||||||
|
setPageOrder(isValidPageList(savedOrder) ? savedOrder : getDefaultPageOrder());
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to load config:', error);
|
console.error('Failed to load config:', error);
|
||||||
setVisiblePages(getDefaultVisibleFeatureKeys());
|
setVisiblePages(getDefaultVisibleFeatureKeys());
|
||||||
@@ -114,9 +284,10 @@ export default function App() {
|
|||||||
loadConfig().catch(console.error);
|
loadConfig().catch(console.error);
|
||||||
}, [configKeys]);
|
}, [configKeys]);
|
||||||
|
|
||||||
/**
|
const showToast = (message: string, severity: 'success' | 'info' | 'warning') => {
|
||||||
* 切换页面可见性
|
showMessage(message, { severity });
|
||||||
*/
|
};
|
||||||
|
|
||||||
const handlePageToggle = async (page: PageType) => {
|
const handlePageToggle = async (page: PageType) => {
|
||||||
const isCurrentlyVisible = visiblePages.includes(page);
|
const isCurrentlyVisible = visiblePages.includes(page);
|
||||||
let newPages: PageType[];
|
let newPages: PageType[];
|
||||||
@@ -143,29 +314,25 @@ export default function App() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
const handleDragEnd = async (event: DragEndEvent) => {
|
||||||
* 调整页面显示顺序
|
const { active, over } = event;
|
||||||
*/
|
if (!over || active.id === over.id) return;
|
||||||
const handleMove = async (index: number, direction: 'up' | 'down') => {
|
|
||||||
if (direction === 'up' && index === 0) return;
|
|
||||||
if (direction === 'down' && index === pageOrder.length - 1) return;
|
|
||||||
|
|
||||||
const newOrder = [...pageOrder];
|
const oldIndex = pageOrder.indexOf(active.id as PageType);
|
||||||
const swapIndex = direction === 'up' ? index - 1 : index + 1;
|
const newIndex = pageOrder.indexOf(over.id as PageType);
|
||||||
[newOrder[index], newOrder[swapIndex]] = [newOrder[swapIndex], newOrder[index]];
|
if (oldIndex < 0 || newIndex < 0) return;
|
||||||
|
|
||||||
|
const newOrder = arrayMove(pageOrder, oldIndex, newIndex);
|
||||||
|
setPageOrder(newOrder);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await storageUtil.set(configKeys.order, newOrder);
|
await storageUtil.set(configKeys.order, newOrder);
|
||||||
setPageOrder(newOrder);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to save order:', error);
|
console.error('Failed to save order:', error);
|
||||||
showToast('排序保存失败', 'warning');
|
showToast('排序保存失败', 'warning');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* 恢复默认设置
|
|
||||||
*/
|
|
||||||
const handleRestoreDefaults = async () => {
|
const handleRestoreDefaults = async () => {
|
||||||
try {
|
try {
|
||||||
const defaults = getDefaultVisibleFeatureKeys();
|
const defaults = getDefaultVisibleFeatureKeys();
|
||||||
@@ -191,10 +358,6 @@ export default function App() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const showToast = (message: string, severity: 'success' | 'info' | 'warning') => {
|
|
||||||
showMessage(message, { severity });
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!isLoaded) {
|
if (!isLoaded) {
|
||||||
return (
|
return (
|
||||||
<Box
|
<Box
|
||||||
@@ -215,7 +378,7 @@ export default function App() {
|
|||||||
flexDirection: 'column',
|
flexDirection: 'column',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<ErrorBoundary>
|
<PageErrorBoundary>
|
||||||
{/* 顶部标题与导航栏 */}
|
{/* 顶部标题与导航栏 */}
|
||||||
<Box
|
<Box
|
||||||
sx={{
|
sx={{
|
||||||
@@ -236,12 +399,21 @@ export default function App() {
|
|||||||
subtitle="针对不同窗口类型独立配置 Dashboard 中显示的功能及其排序"
|
subtitle="针对不同窗口类型独立配置 Dashboard 中显示的功能及其排序"
|
||||||
sx={{ mb: 4 }}
|
sx={{ mb: 4 }}
|
||||||
/>
|
/>
|
||||||
|
{/* Tab 与恢复按钮同行 */}
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
alignItems="flex-end"
|
||||||
|
justifyContent="space-between"
|
||||||
|
sx={{ borderBottom: 'none' }}
|
||||||
|
>
|
||||||
<Tabs
|
<Tabs
|
||||||
value={windowType}
|
value={windowType}
|
||||||
onChange={handleWindowTypeChange}
|
onChange={handleWindowTypeChange}
|
||||||
indicatorColor="primary"
|
indicatorColor="primary"
|
||||||
textColor="primary"
|
textColor="primary"
|
||||||
sx={{
|
sx={{
|
||||||
|
flex: 1,
|
||||||
|
minHeight: 'auto',
|
||||||
'& .MuiTab-root': {
|
'& .MuiTab-root': {
|
||||||
fontWeight: 700,
|
fontWeight: 700,
|
||||||
fontSize: '0.9rem',
|
fontSize: '0.9rem',
|
||||||
@@ -259,41 +431,31 @@ export default function App() {
|
|||||||
<Tab value="sidepanel" label="侧边栏" />
|
<Tab value="sidepanel" label="侧边栏" />
|
||||||
<Tab value="tab" label="标签页" />
|
<Tab value="tab" label="标签页" />
|
||||||
</Tabs>
|
</Tabs>
|
||||||
|
<Tooltip title="恢复当前模式默认" placement="top">
|
||||||
|
<IconButton
|
||||||
|
onClick={handleRestoreDefaults}
|
||||||
|
size="small"
|
||||||
|
sx={{
|
||||||
|
mb: 1,
|
||||||
|
ml: 1,
|
||||||
|
color: 'text.secondary',
|
||||||
|
'&:hover': {
|
||||||
|
color: 'primary.main',
|
||||||
|
bgcolor: alpha(theme.palette.primary.main, 0.08),
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
aria-label="恢复当前模式默认"
|
||||||
|
>
|
||||||
|
<RefreshIcon fontSize="small" />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
</Stack>
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
{/* 主内容区域 */}
|
{/* 主内容区域 */}
|
||||||
<Box sx={{ flex: 1, p: { xs: 2, sm: 4 } }}>
|
<Box sx={{ flex: 1, p: { xs: 2, sm: 4 } }}>
|
||||||
<Box sx={{ maxWidth: 800, mx: 'auto' }}>
|
<Box sx={{ maxWidth: 800, mx: 'auto' }}>
|
||||||
<Stack direction="row" justifyContent="flex-end" sx={{ mb: 2.5 }}>
|
|
||||||
<Button
|
|
||||||
variant="outlined"
|
|
||||||
color="primary"
|
|
||||||
size="small"
|
|
||||||
onClick={handleRestoreDefaults}
|
|
||||||
startIcon={<RefreshIcon sx={{ fontSize: 18 }} />}
|
|
||||||
sx={{
|
|
||||||
borderRadius: 2.5,
|
|
||||||
fontWeight: 700,
|
|
||||||
textTransform: 'none',
|
|
||||||
borderColor: 'divider',
|
|
||||||
color: 'text.secondary',
|
|
||||||
'&:hover': {
|
|
||||||
borderColor: 'primary.main',
|
|
||||||
color: 'primary.main',
|
|
||||||
bgcolor: alpha(theme.palette.primary.main, 0.04),
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
恢复当前模式默认
|
|
||||||
</Button>
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
{!isLoaded ? (
|
|
||||||
<Box sx={{ display: 'flex', justifyContent: 'center', py: 12 }}>
|
|
||||||
<CircularProgress size={32} thickness={5} />
|
|
||||||
</Box>
|
|
||||||
) : (
|
|
||||||
<Paper
|
<Paper
|
||||||
elevation={0}
|
elevation={0}
|
||||||
sx={{
|
sx={{
|
||||||
@@ -305,167 +467,34 @@ export default function App() {
|
|||||||
boxShadow: '0 4px 24px rgba(0,0,0,0.03)',
|
boxShadow: '0 4px 24px rgba(0,0,0,0.03)',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
<DndContext
|
||||||
|
sensors={sensors}
|
||||||
|
collisionDetection={closestCenter}
|
||||||
|
onDragEnd={handleDragEnd}
|
||||||
|
>
|
||||||
|
<SortableContext items={pageOrder} strategy={verticalListSortingStrategy}>
|
||||||
<Box sx={{ display: 'flex', flexDirection: 'column' }}>
|
<Box sx={{ display: 'flex', flexDirection: 'column' }}>
|
||||||
{pageOrder.map((key, index, array) => {
|
{pageOrder.map((key, index, array) => {
|
||||||
const feature = getFeatureByKey(key);
|
|
||||||
if (!feature) return null;
|
|
||||||
|
|
||||||
const isChecked = visiblePages.includes(key);
|
const isChecked = visiblePages.includes(key);
|
||||||
const isDisabled = isChecked && visiblePages.length === 1;
|
const isDisabled = isChecked && visiblePages.length === 1;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box
|
<SortableFeatureRow
|
||||||
key={key}
|
key={key}
|
||||||
sx={{
|
pageKey={key}
|
||||||
display: 'flex',
|
isLast={index === array.length - 1}
|
||||||
alignItems: 'center',
|
isChecked={isChecked}
|
||||||
justifyContent: 'space-between',
|
isDisabled={isDisabled}
|
||||||
p: { xs: 2, sm: 2.5 },
|
onToggle={handlePageToggle}
|
||||||
borderBottom: index === array.length - 1 ? 'none' : '1px solid',
|
|
||||||
borderColor: 'divider',
|
|
||||||
transition: 'all 0.2s cubic-bezier(0.4, 0, 0.2, 1)',
|
|
||||||
'&:hover': {
|
|
||||||
bgcolor: alpha(
|
|
||||||
getPaletteColor(theme, feature.themeColorKey ?? 'primary').main,
|
|
||||||
0.02,
|
|
||||||
),
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Stack
|
|
||||||
direction="row"
|
|
||||||
spacing={{ xs: 1.5, sm: 2.5 }}
|
|
||||||
alignItems="center"
|
|
||||||
sx={{ flex: 1, minWidth: 0 }}
|
|
||||||
>
|
|
||||||
{/* 拖拽/排序暗示图标 */}
|
|
||||||
<Box sx={{ color: 'text.disabled', display: 'flex' }}>
|
|
||||||
<DragIndicatorIcon fontSize="small" />
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
{/* 功能图标容器 */}
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
p: 1.2,
|
|
||||||
borderRadius: 2.5,
|
|
||||||
bgcolor: alpha(
|
|
||||||
getPaletteColor(theme, feature.themeColorKey ?? 'primary').main,
|
|
||||||
0.1,
|
|
||||||
),
|
|
||||||
color: getPaletteColor(theme, feature.themeColorKey ?? 'primary')
|
|
||||||
.main,
|
|
||||||
display: 'flex',
|
|
||||||
flexShrink: 0,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{feature.icon}
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
{/* 文本信息 */}
|
|
||||||
<Box sx={{ minWidth: 0 }}>
|
|
||||||
<Typography
|
|
||||||
variant="subtitle2"
|
|
||||||
sx={{
|
|
||||||
fontWeight: 800,
|
|
||||||
color: 'text.primary',
|
|
||||||
fontSize: '0.95rem',
|
|
||||||
lineHeight: 1.2,
|
|
||||||
mb: 0.5,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{t(feature.labelKey)}
|
|
||||||
</Typography>
|
|
||||||
<Typography
|
|
||||||
variant="caption"
|
|
||||||
color="text.secondary"
|
|
||||||
sx={{
|
|
||||||
fontWeight: 600,
|
|
||||||
display: 'block',
|
|
||||||
overflow: 'hidden',
|
|
||||||
textOverflow: 'ellipsis',
|
|
||||||
whiteSpace: 'nowrap',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{feature.descriptionKey ? t(feature.descriptionKey) : '暂无描述'}
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
<Box sx={{ display: 'flex', alignItems: 'center', ml: { xs: 1, sm: 2 } }}>
|
|
||||||
{/* 移动操作按钮 */}
|
|
||||||
<Stack direction="row" sx={{ display: 'flex', mr: { xs: 0, sm: 1 } }}>
|
|
||||||
<IconButton
|
|
||||||
size="small"
|
|
||||||
onClick={() => handleMove(index, 'up')}
|
|
||||||
disabled={index === 0}
|
|
||||||
sx={{
|
|
||||||
color: 'text.disabled',
|
|
||||||
p: { xs: 0.5, sm: 1 },
|
|
||||||
'&:hover': {
|
|
||||||
color: 'primary.main',
|
|
||||||
bgcolor: alpha(theme.palette.primary.main, 0.08),
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<KeyboardArrowUpIcon fontSize="small" />
|
|
||||||
</IconButton>
|
|
||||||
<IconButton
|
|
||||||
size="small"
|
|
||||||
onClick={() => handleMove(index, 'down')}
|
|
||||||
disabled={index === array.length - 1}
|
|
||||||
sx={{
|
|
||||||
color: 'text.disabled',
|
|
||||||
p: { xs: 0.5, sm: 1 },
|
|
||||||
'&:hover': {
|
|
||||||
color: 'primary.main',
|
|
||||||
bgcolor: alpha(theme.palette.primary.main, 0.08),
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<KeyboardArrowDownIcon fontSize="small" />
|
|
||||||
</IconButton>
|
|
||||||
</Stack>
|
|
||||||
|
|
||||||
<Divider
|
|
||||||
orientation="vertical"
|
|
||||||
flexItem
|
|
||||||
sx={{
|
|
||||||
mx: { xs: 0.5, sm: 1 },
|
|
||||||
display: 'block',
|
|
||||||
height: 24,
|
|
||||||
alignSelf: 'center',
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* 显示切换开关 */}
|
|
||||||
<Switch
|
|
||||||
color="primary"
|
|
||||||
checked={isChecked}
|
|
||||||
onChange={() => handlePageToggle(key)}
|
|
||||||
disabled={isDisabled}
|
|
||||||
sx={{
|
|
||||||
'& .MuiSwitch-switchBase.Mui-checked': {
|
|
||||||
color: getPaletteColor(theme, feature.themeColorKey ?? 'primary')
|
|
||||||
.main,
|
|
||||||
},
|
|
||||||
'& .MuiSwitch-switchBase.Mui-checked + .MuiSwitch-track': {
|
|
||||||
backgroundColor: getPaletteColor(
|
|
||||||
theme,
|
|
||||||
feature.themeColorKey ?? 'primary',
|
|
||||||
).main,
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</Box>
|
</Box>
|
||||||
|
</SortableContext>
|
||||||
|
</DndContext>
|
||||||
</Paper>
|
</Paper>
|
||||||
)}
|
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
</ErrorBoundary>
|
</PageErrorBoundary>
|
||||||
|
|
||||||
<GlobalSnackbar {...snackbarProps} />
|
<GlobalSnackbar {...snackbarProps} />
|
||||||
</Box>
|
</Box>
|
||||||
|
|||||||
@@ -0,0 +1,131 @@
|
|||||||
|
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||||
|
import { render, screen, waitFor } from '@testing-library/react';
|
||||||
|
import App from '../App';
|
||||||
|
import { storageUtil } from '@/utils/chromeStorage';
|
||||||
|
import {
|
||||||
|
getDefaultVisibleFeatureKeys,
|
||||||
|
getDefaultPageOrder,
|
||||||
|
getFeatureByKey,
|
||||||
|
} from '@/config/features';
|
||||||
|
|
||||||
|
// Mock storageUtil
|
||||||
|
vi.mock('@/utils/chromeStorage', () => ({
|
||||||
|
storageUtil: {
|
||||||
|
get: vi.fn(),
|
||||||
|
set: vi.fn(() => Promise.resolve()),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Mock i18next
|
||||||
|
vi.mock('react-i18next', () => ({
|
||||||
|
useTranslation: () => ({
|
||||||
|
t: (key: string) => key,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('Options App', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
localStorage.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('合法数据应正常加载并显示正确的功能列表', async () => {
|
||||||
|
const defaultOrder = getDefaultPageOrder();
|
||||||
|
|
||||||
|
(storageUtil.get as any).mockImplementation((_key: string, defaultValue: any) =>
|
||||||
|
Promise.resolve(defaultValue),
|
||||||
|
);
|
||||||
|
|
||||||
|
render(<App />);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 验证默认可见的功能都被渲染出来了
|
||||||
|
for (const key of defaultOrder) {
|
||||||
|
const feature = getFeatureByKey(key);
|
||||||
|
if (feature) {
|
||||||
|
expect(screen.getByText(feature.labelKey)).toBeInTheDocument();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('非法 visiblePages 数据应回退到默认值', async () => {
|
||||||
|
const defaultVisible = getDefaultVisibleFeatureKeys();
|
||||||
|
|
||||||
|
(storageUtil.get as any).mockImplementation((key: string, defaultValue: any) => {
|
||||||
|
if (key.includes('VisiblePages')) {
|
||||||
|
return Promise.resolve(['invalidPage', 'anotherInvalid']);
|
||||||
|
}
|
||||||
|
return Promise.resolve(defaultValue);
|
||||||
|
});
|
||||||
|
|
||||||
|
render(<App />);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 验证默认值的功能仍然被渲染(非法数据被回退)
|
||||||
|
for (const key of defaultVisible) {
|
||||||
|
const feature = getFeatureByKey(key);
|
||||||
|
if (feature && key !== 'dashboard') {
|
||||||
|
expect(screen.getByText(feature.labelKey)).toBeInTheDocument();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('非法 pageOrder 数据应回退到默认值', async () => {
|
||||||
|
const defaultOrder = getDefaultPageOrder();
|
||||||
|
|
||||||
|
(storageUtil.get as any).mockImplementation((key: string, defaultValue: any) => {
|
||||||
|
if (key.includes('PageOrder')) {
|
||||||
|
return Promise.resolve(['notARealPage', 123, null]);
|
||||||
|
}
|
||||||
|
return Promise.resolve(defaultValue);
|
||||||
|
});
|
||||||
|
|
||||||
|
render(<App />);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 验证默认顺序的功能都被渲染
|
||||||
|
for (const key of defaultOrder) {
|
||||||
|
const feature = getFeatureByKey(key);
|
||||||
|
if (feature) {
|
||||||
|
expect(screen.getByText(feature.labelKey)).toBeInTheDocument();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('非数组数据应回退到默认值', async () => {
|
||||||
|
const defaultOrder = getDefaultPageOrder();
|
||||||
|
|
||||||
|
(storageUtil.get as any).mockImplementation((key: string, defaultValue: any) => {
|
||||||
|
if (key.includes('VisiblePages')) {
|
||||||
|
return Promise.resolve('not-an-array');
|
||||||
|
}
|
||||||
|
if (key.includes('PageOrder')) {
|
||||||
|
return Promise.resolve({ foo: 'bar' });
|
||||||
|
}
|
||||||
|
return Promise.resolve(defaultValue);
|
||||||
|
});
|
||||||
|
|
||||||
|
render(<App />);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 验证默认功能都被渲染
|
||||||
|
for (const key of defaultOrder) {
|
||||||
|
const feature = getFeatureByKey(key);
|
||||||
|
if (feature) {
|
||||||
|
expect(screen.getByText(feature.labelKey)).toBeInTheDocument();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -9,7 +9,9 @@ import { Box } from '@mui/material';
|
|||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
const handleOpenOptions = () => {
|
const handleOpenOptions = () => {
|
||||||
chrome.runtime.openOptionsPage();
|
chrome.runtime.openOptionsPage().catch((err) => {
|
||||||
|
console.error('Failed to open options page:', err);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// 通知侧边栏已打开
|
// 通知侧边栏已打开
|
||||||
|
|||||||
+12
-10
@@ -6,19 +6,20 @@ import globals from 'globals';
|
|||||||
|
|
||||||
export default [
|
export default [
|
||||||
{
|
{
|
||||||
ignores: [
|
ignores: ['dist', '.output', '.wxt', 'node_modules', 'eslint.config.ts'],
|
||||||
'dist',
|
|
||||||
'.output',
|
|
||||||
'.wxt',
|
|
||||||
'node_modules',
|
|
||||||
'eslint.config.ts',
|
|
||||||
'**/*.test.tsx',
|
|
||||||
'**/*.test.ts',
|
|
||||||
'**/__tests__/**',
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
js.configs.recommended,
|
js.configs.recommended,
|
||||||
...tseslint.configs.recommended,
|
...tseslint.configs.recommended,
|
||||||
|
{
|
||||||
|
files: ['**/__tests__/**', '**/*.test.{ts,tsx}'],
|
||||||
|
rules: {
|
||||||
|
'@typescript-eslint/no-explicit-any': 'off',
|
||||||
|
'@typescript-eslint/no-unused-vars': [
|
||||||
|
'warn',
|
||||||
|
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
files: [
|
files: [
|
||||||
'hooks/**/*.{ts,tsx}',
|
'hooks/**/*.{ts,tsx}',
|
||||||
@@ -28,6 +29,7 @@ export default [
|
|||||||
'components/**/*.{ts,tsx}',
|
'components/**/*.{ts,tsx}',
|
||||||
'services/**/*.{ts,tsx}',
|
'services/**/*.{ts,tsx}',
|
||||||
],
|
],
|
||||||
|
ignores: ['**/__tests__/**', '**/*.test.{ts,tsx}'],
|
||||||
languageOptions: {
|
languageOptions: {
|
||||||
ecmaVersion: 2020,
|
ecmaVersion: 2020,
|
||||||
globals: {
|
globals: {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"pageTitle": "Base64 Converter",
|
"pageTitle": "Base64 Converter",
|
||||||
"pageSubtitle": "Encode text, files, and images to Base64",
|
"pageSubtitle": "Encode and decode text, files, and images with Base64",
|
||||||
"textMode": "Text",
|
"textMode": "Text",
|
||||||
"fileMode": "File",
|
"fileMode": "File",
|
||||||
"imageMode": "Image",
|
"imageMode": "Image",
|
||||||
@@ -22,5 +22,16 @@
|
|||||||
"unsupportedImageType": "Unsupported image format",
|
"unsupportedImageType": "Unsupported image format",
|
||||||
"conversionFailed": "Conversion failed",
|
"conversionFailed": "Conversion failed",
|
||||||
"originalSize": "Original Size",
|
"originalSize": "Original Size",
|
||||||
"encodedSize": "Encoded Size"
|
"encodedSize": "Encoded Size",
|
||||||
|
"invalidBase64": "Invalid Base64 string",
|
||||||
|
"binaryDataDetected": "Input appears to be binary data (e.g. an image). Please switch to the Image tab.",
|
||||||
|
"imageDataUriHint": "Detected an image data URI — please use the Image tab to decode it.",
|
||||||
|
"switchToImageMode": "Switch to Image mode",
|
||||||
|
"download": "Download",
|
||||||
|
"decodedFileName": "Decoded file name",
|
||||||
|
"decodeBase64Placeholder": "Enter Base64 or data URI to decode...",
|
||||||
|
"decodedFileOutput": "Decoded File",
|
||||||
|
"decodedImageOutput": "Decoded Image",
|
||||||
|
"inferredMimeType": "Inferred MIME type",
|
||||||
|
"decodedSize": "Decoded size"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,5 +25,11 @@
|
|||||||
"messages": {
|
"messages": {
|
||||||
"copySuccess": "Copied to clipboard",
|
"copySuccess": "Copied to clipboard",
|
||||||
"copyError": "Copy failed"
|
"copyError": "Copy failed"
|
||||||
|
},
|
||||||
|
"textInputArea": {
|
||||||
|
"clear": "Clear",
|
||||||
|
"copyContent": "Copy content",
|
||||||
|
"cleared": "Cleared",
|
||||||
|
"placeholder": "placeholder text"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,5 +6,12 @@
|
|||||||
"payloadTitle": "PAYLOAD: Data",
|
"payloadTitle": "PAYLOAD: Data",
|
||||||
"signatureTitle": "Signature",
|
"signatureTitle": "Signature",
|
||||||
"noSignature": "No Signature",
|
"noSignature": "No Signature",
|
||||||
"invalidFormat": "Unable to parse"
|
"invalidFormat": "Unable to parse",
|
||||||
|
"errors": {
|
||||||
|
"invalidBase64String": "Invalid base64url string",
|
||||||
|
"failedToDecode": "Failed to decode base64url: ",
|
||||||
|
"invalidFormat": "Invalid JWT format: expected 3 parts separated by .",
|
||||||
|
"parseHeaderFailed": "Failed to parse Header: ",
|
||||||
|
"parsePayloadFailed": "Failed to parse Payload: "
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
"iso8601": "ISO 8601",
|
"iso8601": "ISO 8601",
|
||||||
"utcTime": "UTC Time",
|
"utcTime": "UTC Time",
|
||||||
"copyTooltip": "Copy",
|
"copyTooltip": "Copy",
|
||||||
|
"resultEmpty": "Enter a value and click convert",
|
||||||
"errors": {
|
"errors": {
|
||||||
"invalidNumber": "Invalid number",
|
"invalidNumber": "Invalid number",
|
||||||
"invalidTimestamp": "Invalid timestamp",
|
"invalidTimestamp": "Invalid timestamp",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"pageTitle": "Base64 转换器",
|
"pageTitle": "Base64 转换器",
|
||||||
"pageSubtitle": "文本、文件与图像的 Base64 编码转换",
|
"pageSubtitle": "文本、文件与图像的 Base64 编码与解码",
|
||||||
"textMode": "文本",
|
"textMode": "文本",
|
||||||
"fileMode": "文件",
|
"fileMode": "文件",
|
||||||
"imageMode": "图像",
|
"imageMode": "图像",
|
||||||
@@ -22,5 +22,16 @@
|
|||||||
"unsupportedImageType": "不支持的图像格式",
|
"unsupportedImageType": "不支持的图像格式",
|
||||||
"conversionFailed": "转换失败",
|
"conversionFailed": "转换失败",
|
||||||
"originalSize": "原始大小",
|
"originalSize": "原始大小",
|
||||||
"encodedSize": "编码大小"
|
"encodedSize": "编码大小",
|
||||||
|
"invalidBase64": "Base64 字符串无效",
|
||||||
|
"binaryDataDetected": "输入似乎是二进制数据(如图片)。请切换到「图像」选项卡。",
|
||||||
|
"imageDataUriHint": "检测到图片的 data URI,请使用「图像」选项卡进行解码。",
|
||||||
|
"switchToImageMode": "切换到图像模式",
|
||||||
|
"download": "下载",
|
||||||
|
"decodedFileName": "解码后文件名",
|
||||||
|
"decodeBase64Placeholder": "输入需要解码的 Base64 或 data URI...",
|
||||||
|
"decodedFileOutput": "解码文件",
|
||||||
|
"decodedImageOutput": "解码图像",
|
||||||
|
"inferredMimeType": "推断的 MIME 类型",
|
||||||
|
"decodedSize": "解码大小"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,5 +25,11 @@
|
|||||||
"messages": {
|
"messages": {
|
||||||
"copySuccess": "已复制到剪贴板",
|
"copySuccess": "已复制到剪贴板",
|
||||||
"copyError": "复制失败"
|
"copyError": "复制失败"
|
||||||
|
},
|
||||||
|
"textInputArea": {
|
||||||
|
"clear": "清空",
|
||||||
|
"copyContent": "复制内容",
|
||||||
|
"cleared": "已清空",
|
||||||
|
"placeholder": "请输入文本"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,5 +6,12 @@
|
|||||||
"payloadTitle": "PAYLOAD: 数据",
|
"payloadTitle": "PAYLOAD: 数据",
|
||||||
"signatureTitle": "签名",
|
"signatureTitle": "签名",
|
||||||
"noSignature": "无签名",
|
"noSignature": "无签名",
|
||||||
"invalidFormat": "无法解析"
|
"invalidFormat": "无法解析",
|
||||||
|
"errors": {
|
||||||
|
"invalidBase64String": "无效的 Base64URL 字符串",
|
||||||
|
"failedToDecode": "Base64URL 解码失败:",
|
||||||
|
"invalidFormat": "JWT 格式错误:必须包含三个由 . 分隔的部分",
|
||||||
|
"parseHeaderFailed": "解析 Header 失败:",
|
||||||
|
"parsePayloadFailed": "解析 Payload 失败:"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
"iso8601": "ISO 8601",
|
"iso8601": "ISO 8601",
|
||||||
"utcTime": "UTC 时间",
|
"utcTime": "UTC 时间",
|
||||||
"copyTooltip": "复制",
|
"copyTooltip": "复制",
|
||||||
|
"resultEmpty": "请输入并点击转换",
|
||||||
"errors": {
|
"errors": {
|
||||||
"invalidNumber": "无效数字",
|
"invalidNumber": "无效数字",
|
||||||
"invalidTimestamp": "无效时间戳",
|
"invalidTimestamp": "无效时间戳",
|
||||||
|
|||||||
Generated
+56
-1
@@ -10,6 +10,9 @@
|
|||||||
"hasInstallScript": true,
|
"hasInstallScript": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@dnd-kit/core": "^6.3.1",
|
||||||
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
"@emotion/react": "^11.14.0",
|
"@emotion/react": "^11.14.0",
|
||||||
"@emotion/styled": "^11.14.1",
|
"@emotion/styled": "^11.14.1",
|
||||||
"@mui/icons-material": "^7.3.8",
|
"@mui/icons-material": "^7.3.8",
|
||||||
@@ -645,6 +648,59 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@dnd-kit/accessibility": {
|
||||||
|
"version": "3.1.1",
|
||||||
|
"resolved": "https://mirrors.cloud.tencent.com/npm/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
|
||||||
|
"integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": ">=16.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@dnd-kit/core": {
|
||||||
|
"version": "6.3.1",
|
||||||
|
"resolved": "https://mirrors.cloud.tencent.com/npm/@dnd-kit/core/-/core-6.3.1.tgz",
|
||||||
|
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@dnd-kit/accessibility": "^3.1.1",
|
||||||
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
|
"tslib": "^2.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": ">=16.8.0",
|
||||||
|
"react-dom": ">=16.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@dnd-kit/sortable": {
|
||||||
|
"version": "10.0.0",
|
||||||
|
"resolved": "https://mirrors.cloud.tencent.com/npm/@dnd-kit/sortable/-/sortable-10.0.0.tgz",
|
||||||
|
"integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
|
"tslib": "^2.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@dnd-kit/core": "^6.3.0",
|
||||||
|
"react": ">=16.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@dnd-kit/utilities": {
|
||||||
|
"version": "3.2.2",
|
||||||
|
"resolved": "https://mirrors.cloud.tencent.com/npm/@dnd-kit/utilities/-/utilities-3.2.2.tgz",
|
||||||
|
"integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": ">=16.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@emotion/babel-plugin": {
|
"node_modules/@emotion/babel-plugin": {
|
||||||
"version": "11.13.5",
|
"version": "11.13.5",
|
||||||
"resolved": "https://registry.npmmirror.com/@emotion/babel-plugin/-/babel-plugin-11.13.5.tgz",
|
"resolved": "https://registry.npmmirror.com/@emotion/babel-plugin/-/babel-plugin-11.13.5.tgz",
|
||||||
@@ -10184,7 +10240,6 @@
|
|||||||
"version": "2.8.1",
|
"version": "2.8.1",
|
||||||
"resolved": "https://registry.npmmirror.com/tslib/-/tslib-2.8.1.tgz",
|
"resolved": "https://registry.npmmirror.com/tslib/-/tslib-2.8.1.tgz",
|
||||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||||
"dev": true,
|
|
||||||
"license": "0BSD"
|
"license": "0BSD"
|
||||||
},
|
},
|
||||||
"node_modules/type-check": {
|
"node_modules/type-check": {
|
||||||
|
|||||||
+3
-1
@@ -12,7 +12,6 @@
|
|||||||
"build:firefox": "wxt build -b firefox",
|
"build:firefox": "wxt build -b firefox",
|
||||||
"zip": "wxt zip",
|
"zip": "wxt zip",
|
||||||
"zip:firefox": "wxt zip -b firefox",
|
"zip:firefox": "wxt zip -b firefox",
|
||||||
"compile": "tsc --noEmit",
|
|
||||||
"postinstall": "wxt prepare",
|
"postinstall": "wxt prepare",
|
||||||
"prepare": "husky",
|
"prepare": "husky",
|
||||||
"lint": "eslint . --max-warnings=0",
|
"lint": "eslint . --max-warnings=0",
|
||||||
@@ -22,6 +21,9 @@
|
|||||||
"typecheck": "tsc --noEmit"
|
"typecheck": "tsc --noEmit"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@dnd-kit/core": "^6.3.1",
|
||||||
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
"@emotion/react": "^11.14.0",
|
"@emotion/react": "^11.14.0",
|
||||||
"@emotion/styled": "^11.14.1",
|
"@emotion/styled": "^11.14.1",
|
||||||
"@mui/icons-material": "^7.3.8",
|
"@mui/icons-material": "^7.3.8",
|
||||||
|
|||||||
@@ -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}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
+17
-607
@@ -1,40 +1,16 @@
|
|||||||
import { useCallback, useRef, useState } from 'react';
|
import { Box, Container, Stack } from '@mui/material';
|
||||||
import {
|
|
||||||
Alert,
|
|
||||||
alpha,
|
|
||||||
Box,
|
|
||||||
Button,
|
|
||||||
Container,
|
|
||||||
Stack,
|
|
||||||
TextField,
|
|
||||||
ToggleButton,
|
|
||||||
ToggleButtonGroup,
|
|
||||||
Typography,
|
|
||||||
CircularProgress,
|
|
||||||
Paper,
|
|
||||||
} from '@mui/material';
|
|
||||||
import TextFieldsIcon from '@mui/icons-material/TextFields';
|
import TextFieldsIcon from '@mui/icons-material/TextFields';
|
||||||
import UploadFileIcon from '@mui/icons-material/UploadFile';
|
import UploadFileIcon from '@mui/icons-material/UploadFile';
|
||||||
import ImageIcon from '@mui/icons-material/Image';
|
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 { useTranslation } from 'react-i18next';
|
||||||
import PageHeader from '@/components/PageHeader';
|
import PageHeader from '@/components/PageHeader';
|
||||||
import CopyButton from '@/components/CopyButton';
|
|
||||||
import { base64ConverterPageStyles } from '@/config/pageTheme';
|
import { base64ConverterPageStyles } from '@/config/pageTheme';
|
||||||
import { useStorageState } from '@/utils/useStorageState';
|
import { useStorageState } from '@/utils/useStorageState';
|
||||||
import type { Base64ConverterPageMode } from '@/types/storage';
|
import type { Base64ConverterPageMode } from '@/types/storage';
|
||||||
import {
|
import TextMode from './TextMode';
|
||||||
textToBase64,
|
import FileMode from './FileMode';
|
||||||
base64ToText,
|
import ImageMode from './ImageMode';
|
||||||
fileToBase64,
|
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||||
isFileSizeValid,
|
|
||||||
isSupportedImageType,
|
|
||||||
isSupportedImageExtension,
|
|
||||||
formatFileSize,
|
|
||||||
MAX_FILE_SIZE,
|
|
||||||
} from '@/utils/base64Converter';
|
|
||||||
import type { FileToBase64Result } from '@/utils/base64Converter';
|
|
||||||
|
|
||||||
const VALID_PAGE_MODES: readonly Base64ConverterPageMode[] = ['text', 'file', 'image'];
|
const VALID_PAGE_MODES: readonly Base64ConverterPageMode[] = ['text', 'file', 'image'];
|
||||||
|
|
||||||
@@ -43,13 +19,6 @@ const isValidPageMode = (val: unknown): val is Base64ConverterPageMode =>
|
|||||||
|
|
||||||
type PageMode = Base64ConverterPageMode;
|
type PageMode = Base64ConverterPageMode;
|
||||||
|
|
||||||
/** 文件信息 */
|
|
||||||
interface FileInfo {
|
|
||||||
name: string;
|
|
||||||
size: number;
|
|
||||||
type: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Index() {
|
export default function Index() {
|
||||||
const { t } = useTranslation(['base64Converter']);
|
const { t } = useTranslation(['base64Converter']);
|
||||||
const [pageMode, setPageMode] = useStorageState(
|
const [pageMode, setPageMode] = useStorageState(
|
||||||
@@ -58,129 +27,6 @@ export default function Index() {
|
|||||||
isValidPageMode,
|
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> = {
|
const modeIcon: Record<PageMode, React.ReactNode> = {
|
||||||
text: <TextFieldsIcon />,
|
text: <TextFieldsIcon />,
|
||||||
file: <UploadFileIcon />,
|
file: <UploadFileIcon />,
|
||||||
@@ -191,463 +37,27 @@ export default function Index() {
|
|||||||
<Box>
|
<Box>
|
||||||
<Container sx={{ p: 2 }}>
|
<Container sx={{ p: 2 }}>
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title={t(modeTitles[pageMode].title)}
|
title={t('base64Converter:pageTitle')}
|
||||||
subtitle={t(modeTitles[pageMode].subtitle)}
|
subtitle={t('base64Converter:pageSubtitle')}
|
||||||
icon={modeIcon[pageMode]}
|
icon={modeIcon[pageMode]}
|
||||||
iconColor={base64ConverterPageStyles.primaryColor}
|
iconColor={base64ConverterPageStyles.primaryColor}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Stack spacing={2.5}>
|
<Stack spacing={2.5}>
|
||||||
{/* 模式切换器 */}
|
<SwitchButtonGroup
|
||||||
<ToggleButtonGroup
|
|
||||||
size="small"
|
|
||||||
exclusive
|
|
||||||
value={pageMode}
|
value={pageMode}
|
||||||
onChange={(_, v: PageMode | null) => v && setPageMode(v)}
|
options={[
|
||||||
sx={{ borderRadius: 3, flexWrap: 'wrap', gap: 0.5 }}
|
{ value: 'text', label: t('base64Converter:textMode') },
|
||||||
>
|
{ value: 'file', label: t('base64Converter:fileMode') },
|
||||||
<ToggleButton value="text" sx={{ px: 2, fontWeight: 700, fontSize: '0.75rem' }}>
|
{ value: 'image', label: t('base64Converter:imageMode') },
|
||||||
{t('base64Converter:textMode')}
|
]}
|
||||||
</ToggleButton>
|
onChange={(value: PageMode) => setPageMode(value)}
|
||||||
<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>
|
|
||||||
|
|
||||||
{/* ===== 文本模式 ===== */}
|
|
||||||
{pageMode === 'text' && (
|
|
||||||
<>
|
|
||||||
{/* 编码/解码切换 */}
|
|
||||||
<Stack direction="row" spacing={1} justifyContent="space-between" alignItems="center">
|
|
||||||
<ToggleButtonGroup
|
|
||||||
size="small"
|
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>}
|
{pageMode === 'text' && <TextMode onSwitchToImageMode={() => setPageMode('image')} />}
|
||||||
|
{pageMode === 'file' && <FileMode />}
|
||||||
{/* 输出区 */}
|
{pageMode === 'image' && <ImageMode />}
|
||||||
{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>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Stack>
|
</Stack>
|
||||||
</Container>
|
</Container>
|
||||||
</Box>
|
</Box>
|
||||||
|
|||||||
@@ -115,8 +115,13 @@ export default function ToolCard({
|
|||||||
sx={{
|
sx={{
|
||||||
color: 'text.secondary',
|
color: 'text.secondary',
|
||||||
fontWeight: 500,
|
fontWeight: 500,
|
||||||
display: 'block',
|
|
||||||
mt: 0.5,
|
mt: 0.5,
|
||||||
|
display: '-webkit-box',
|
||||||
|
WebkitBoxOrient: 'vertical',
|
||||||
|
WebkitLineClamp: 1,
|
||||||
|
overflow: 'hidden',
|
||||||
|
textOverflow: 'ellipsis',
|
||||||
|
wordBreak: 'break-word',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{description}
|
{description}
|
||||||
|
|||||||
@@ -7,21 +7,16 @@ import {
|
|||||||
Container,
|
Container,
|
||||||
Stack,
|
Stack,
|
||||||
TextField,
|
TextField,
|
||||||
ToggleButton,
|
|
||||||
ToggleButtonGroup,
|
|
||||||
Typography,
|
Typography,
|
||||||
Paper,
|
Paper,
|
||||||
} from '@mui/material';
|
} from '@mui/material';
|
||||||
import SplitscreenIcon from '@mui/icons-material/Splitscreen';
|
|
||||||
import VisibilityIcon from '@mui/icons-material/Visibility';
|
|
||||||
import ArticleIcon from '@mui/icons-material/Article';
|
|
||||||
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
|
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
|
||||||
import DownloadIcon from '@mui/icons-material/Download';
|
import DownloadIcon from '@mui/icons-material/Download';
|
||||||
import CodeIcon from '@mui/icons-material/Code';
|
import CodeIcon from '@mui/icons-material/Code';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import PageHeader from '@/components/PageHeader';
|
import PageHeader from '@/components/PageHeader';
|
||||||
import CopyButton from '@/components/CopyButton';
|
import CopyButton from '@/components/CopyButton';
|
||||||
import { htmlToMarkdownPageStyles } from '@/config/pageTheme';
|
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||||
import { useStorageState } from '@/utils/useStorageState';
|
import { useStorageState } from '@/utils/useStorageState';
|
||||||
import type { HtmlToMarkdownPreviewMode } from '@/types/storage';
|
import type { HtmlToMarkdownPreviewMode } from '@/types/storage';
|
||||||
import { htmlToMarkdown, downloadMarkdownFile, SAMPLE_HTML } from '@/utils/htmlToMarkdown';
|
import { htmlToMarkdown, downloadMarkdownFile, SAMPLE_HTML } from '@/utils/htmlToMarkdown';
|
||||||
@@ -42,8 +37,8 @@ export default function HtmlToMarkdownPage() {
|
|||||||
const error = result.hasError ? (result.error ?? null) : null;
|
const error = result.hasError ? (result.error ?? null) : null;
|
||||||
|
|
||||||
const handleModeChange = useCallback(
|
const handleModeChange = useCallback(
|
||||||
(_event: React.MouseEvent<HTMLElement>, newMode: HtmlToMarkdownPreviewMode | null) => {
|
(newMode: HtmlToMarkdownPreviewMode) => {
|
||||||
if (newMode) setPreviewMode(newMode);
|
setPreviewMode(newMode);
|
||||||
},
|
},
|
||||||
[setPreviewMode],
|
[setPreviewMode],
|
||||||
);
|
);
|
||||||
@@ -74,26 +69,16 @@ export default function HtmlToMarkdownPage() {
|
|||||||
flexWrap="wrap"
|
flexWrap="wrap"
|
||||||
gap={1.5}
|
gap={1.5}
|
||||||
>
|
>
|
||||||
<ToggleButtonGroup
|
<SwitchButtonGroup
|
||||||
value={previewMode}
|
value={previewMode}
|
||||||
exclusive
|
options={[
|
||||||
|
{ value: 'split', label: t('splitMode') },
|
||||||
|
{ value: 'preview', label: t('previewMode') },
|
||||||
|
{ value: 'markdown', label: t('markdownMode') },
|
||||||
|
]}
|
||||||
onChange={handleModeChange}
|
onChange={handleModeChange}
|
||||||
size="small"
|
size="small"
|
||||||
sx={htmlToMarkdownPageStyles.MODE_SWITCHER}
|
/>
|
||||||
>
|
|
||||||
<ToggleButton value="split">
|
|
||||||
<SplitscreenIcon sx={{ fontSize: 16, mr: 0.5 }} />
|
|
||||||
{t('splitMode')}
|
|
||||||
</ToggleButton>
|
|
||||||
<ToggleButton value="preview">
|
|
||||||
<VisibilityIcon sx={{ fontSize: 16, mr: 0.5 }} />
|
|
||||||
{t('previewMode')}
|
|
||||||
</ToggleButton>
|
|
||||||
<ToggleButton value="markdown">
|
|
||||||
<ArticleIcon sx={{ fontSize: 16, mr: 0.5 }} />
|
|
||||||
{t('markdownMode')}
|
|
||||||
</ToggleButton>
|
|
||||||
</ToggleButtonGroup>
|
|
||||||
|
|
||||||
<Stack direction="row" spacing={1}>
|
<Stack direction="row" spacing={1}>
|
||||||
<Button
|
<Button
|
||||||
@@ -242,7 +227,7 @@ export default function HtmlToMarkdownPage() {
|
|||||||
multiline
|
multiline
|
||||||
fullWidth
|
fullWidth
|
||||||
value={result.markdown}
|
value={result.markdown}
|
||||||
InputProps={{ readOnly: true }}
|
slotProps={{ input: { readOnly: true } }}
|
||||||
sx={{
|
sx={{
|
||||||
flex: 1,
|
flex: 1,
|
||||||
'& .MuiOutlinedInput-root': {
|
'& .MuiOutlinedInput-root': {
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { useEffect, useMemo, useState } from 'react';
|
import { useEffect, useMemo, useState } from 'react';
|
||||||
import { Box, Button, FormHelperText, Stack, TextField, Typography } from '@mui/material';
|
import { Box, Button, Stack, Typography } from '@mui/material';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { formatByteSize } from '@/utils/textStatistics';
|
import { formatByteSize } from '@/utils/textStatistics';
|
||||||
import { useSnackbar } from '@/components/GlobalSnackbar';
|
import { useSnackbar } from '@/components/GlobalSnackbar';
|
||||||
import { jsonDiffPageStyles } from '@/config/pageTheme';
|
|
||||||
import CopyButton from '@/components/CopyButton';
|
import CopyButton from '@/components/CopyButton';
|
||||||
|
import TextInputArea from '@/components/TextInputArea';
|
||||||
import { validateJson } from '@/utils/jsonFormatter';
|
import { validateJson } from '@/utils/jsonFormatter';
|
||||||
|
|
||||||
/** 转换结果通用接口 */
|
/** 转换结果通用接口 */
|
||||||
@@ -113,23 +113,15 @@ export default function JsonConvertSection({
|
|||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
{/* 输入区 */}
|
{/* 输入区 */}
|
||||||
<Box>
|
<TextInputArea
|
||||||
<TextField
|
|
||||||
multiline
|
|
||||||
rows={6}
|
|
||||||
fullWidth
|
|
||||||
placeholder={t(`jsonFormat:${pk}InputPlaceholder`)}
|
placeholder={t(`jsonFormat:${pk}InputPlaceholder`)}
|
||||||
value={input}
|
value={input}
|
||||||
onChange={(e) => setInput(e.target.value)}
|
onChange={setInput}
|
||||||
error={Boolean(error)}
|
externalError={error || undefined}
|
||||||
sx={jsonDiffPageStyles.INPUT_STYLE}
|
onClear={() => {
|
||||||
|
setResult(null);
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
{error && (
|
|
||||||
<FormHelperText error sx={{ mx: 1.5, mt: 0.5, fontWeight: 600 }}>
|
|
||||||
{t('jsonFormat:invalidJson')}
|
|
||||||
</FormHelperText>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
{/* 转换结果 */}
|
{/* 转换结果 */}
|
||||||
{result && result.output ? (
|
{result && result.output ? (
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Box, FormHelperText, TextField, Typography } from '@mui/material';
|
import { Box, Typography } from '@mui/material';
|
||||||
import { jsonDiffPageStyles } from '@/config/pageTheme';
|
import TextInputArea from '@/components/TextInputArea';
|
||||||
|
|
||||||
interface JsonDiffInputProps {
|
interface JsonDiffInputProps {
|
||||||
label: string;
|
label: string;
|
||||||
@@ -32,21 +32,15 @@ export default function JsonDiffInput({
|
|||||||
>
|
>
|
||||||
{label}
|
{label}
|
||||||
</Typography>
|
</Typography>
|
||||||
<TextField
|
<TextInputArea
|
||||||
multiline
|
|
||||||
rows={8}
|
|
||||||
fullWidth
|
|
||||||
placeholder={placeholder}
|
|
||||||
value={value}
|
value={value}
|
||||||
onChange={(e) => onChange(e.target.value)}
|
onChange={onChange}
|
||||||
error={Boolean(error)}
|
placeholder={placeholder}
|
||||||
sx={jsonDiffPageStyles.INPUT_STYLE}
|
minRows={8}
|
||||||
|
autoResize={false}
|
||||||
|
externalError={error ?? undefined}
|
||||||
|
showClear={true}
|
||||||
/>
|
/>
|
||||||
{error && (
|
|
||||||
<FormHelperText error sx={{ mx: 1.5, mt: 0.5, fontWeight: 600 }}>
|
|
||||||
{error}
|
|
||||||
</FormHelperText>
|
|
||||||
)}
|
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,8 +7,6 @@ import {
|
|||||||
Stack,
|
Stack,
|
||||||
Switch,
|
Switch,
|
||||||
TextField,
|
TextField,
|
||||||
ToggleButton,
|
|
||||||
ToggleButtonGroup,
|
|
||||||
Typography,
|
Typography,
|
||||||
} from '@mui/material';
|
} from '@mui/material';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
@@ -22,6 +20,7 @@ import { formatByteSize } from '@/utils/textStatistics';
|
|||||||
import { useSnackbar } from '@/components/GlobalSnackbar';
|
import { useSnackbar } from '@/components/GlobalSnackbar';
|
||||||
import { jsonDiffPageStyles } from '@/config/pageTheme';
|
import { jsonDiffPageStyles } from '@/config/pageTheme';
|
||||||
import CopyButton from '@/components/CopyButton';
|
import CopyButton from '@/components/CopyButton';
|
||||||
|
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||||
|
|
||||||
/** 缩进大小选项 */
|
/** 缩进大小选项 */
|
||||||
const INDENT_OPTIONS = [2, 4, 6, 8] as const;
|
const INDENT_OPTIONS = [2, 4, 6, 8] as const;
|
||||||
@@ -95,23 +94,13 @@ export default function JsonFormatSection() {
|
|||||||
>
|
>
|
||||||
{t('jsonFormat:indentSize')}
|
{t('jsonFormat:indentSize')}
|
||||||
</Typography>
|
</Typography>
|
||||||
<ToggleButtonGroup
|
<SwitchButtonGroup
|
||||||
size="small"
|
|
||||||
exclusive
|
|
||||||
value={indentSize}
|
value={indentSize}
|
||||||
onChange={(_, v: number | null) => v !== null && setIndentSize(v)}
|
onChange={(v) => setIndentSize(v)}
|
||||||
sx={{ borderRadius: 3 }}
|
options={INDENT_OPTIONS.map((size) => ({ value: size, label: String(size) }))}
|
||||||
>
|
sx={{ width: 'auto', mb: 0, flexShrink: 0 }}
|
||||||
{INDENT_OPTIONS.map((size) => (
|
size="small"
|
||||||
<ToggleButton
|
/>
|
||||||
key={size}
|
|
||||||
value={size}
|
|
||||||
sx={{ px: 1.5, fontWeight: 700, fontSize: '0.75rem' }}
|
|
||||||
>
|
|
||||||
{size}
|
|
||||||
</ToggleButton>
|
|
||||||
))}
|
|
||||||
</ToggleButtonGroup>
|
|
||||||
|
|
||||||
{/* 键名排序开关 */}
|
{/* 键名排序开关 */}
|
||||||
<FormControlLabel
|
<FormControlLabel
|
||||||
|
|||||||
+22
-45
@@ -1,13 +1,5 @@
|
|||||||
import { useEffect, useMemo, useState, useCallback } from 'react';
|
import { useEffect, useMemo, useState, useCallback } from 'react';
|
||||||
import {
|
import { Box, Button, Container, Stack, Typography } from '@mui/material';
|
||||||
Box,
|
|
||||||
Button,
|
|
||||||
Container,
|
|
||||||
Stack,
|
|
||||||
ToggleButton,
|
|
||||||
ToggleButtonGroup,
|
|
||||||
Typography,
|
|
||||||
} from '@mui/material';
|
|
||||||
import CompareArrowsIcon from '@mui/icons-material/CompareArrows';
|
import CompareArrowsIcon from '@mui/icons-material/CompareArrows';
|
||||||
import DataObjectIcon from '@mui/icons-material/DataObject';
|
import DataObjectIcon from '@mui/icons-material/DataObject';
|
||||||
import TransformIcon from '@mui/icons-material/Transform';
|
import TransformIcon from '@mui/icons-material/Transform';
|
||||||
@@ -28,6 +20,7 @@ import { jsonToToml } from '@/utils/jsonToToml';
|
|||||||
import { minifyJson } from '@/utils/jsonFormatter';
|
import { minifyJson } from '@/utils/jsonFormatter';
|
||||||
import { useStorageState } from '@/utils/useStorageState';
|
import { useStorageState } from '@/utils/useStorageState';
|
||||||
import type { JsonToolsPageMode } from '@/types/storage';
|
import type { JsonToolsPageMode } from '@/types/storage';
|
||||||
|
import SwtichButtonGroup from '@/components/SwitchButtonGroup';
|
||||||
|
|
||||||
interface ParseState {
|
interface ParseState {
|
||||||
value: unknown;
|
value: unknown;
|
||||||
@@ -159,29 +152,18 @@ export default function Index() {
|
|||||||
|
|
||||||
<Stack spacing={2.5}>
|
<Stack spacing={2.5}>
|
||||||
{/* 页面模式切换器 */}
|
{/* 页面模式切换器 */}
|
||||||
<ToggleButtonGroup
|
<SwtichButtonGroup
|
||||||
size="small"
|
|
||||||
exclusive
|
|
||||||
value={pageMode}
|
value={pageMode}
|
||||||
onChange={(_, v: PageMode | null) => v && setPageMode(v)}
|
onChange={(v: PageMode) => setPageMode(v)}
|
||||||
sx={{ borderRadius: 3, flexWrap: 'wrap', gap: 0.5 }}
|
options={[
|
||||||
>
|
{ value: 'diff', label: t('jsonFormat:diffMode') },
|
||||||
<ToggleButton value="diff" sx={{ px: 2, fontWeight: 700, fontSize: '0.75rem' }}>
|
{ value: 'format', label: t('jsonFormat:formatMode') },
|
||||||
{t('jsonFormat:diffMode')}
|
{ value: 'yaml', label: t('jsonFormat:yamlMode') },
|
||||||
</ToggleButton>
|
{ value: 'toml', label: t('jsonFormat:tomlMode') },
|
||||||
<ToggleButton value="format" sx={{ px: 2, fontWeight: 700, fontSize: '0.75rem' }}>
|
{ value: 'minify', label: t('jsonFormat:minifyMode') },
|
||||||
{t('jsonFormat:formatMode')}
|
]}
|
||||||
</ToggleButton>
|
size="small"
|
||||||
<ToggleButton value="yaml" sx={{ px: 2, fontWeight: 700, fontSize: '0.75rem' }}>
|
/>
|
||||||
{t('jsonFormat:yamlMode')}
|
|
||||||
</ToggleButton>
|
|
||||||
<ToggleButton value="toml" sx={{ px: 2, fontWeight: 700, fontSize: '0.75rem' }}>
|
|
||||||
{t('jsonFormat:tomlMode')}
|
|
||||||
</ToggleButton>
|
|
||||||
<ToggleButton value="minify" sx={{ px: 2, fontWeight: 700, fontSize: '0.75rem' }}>
|
|
||||||
{t('jsonFormat:minifyMode')}
|
|
||||||
</ToggleButton>
|
|
||||||
</ToggleButtonGroup>
|
|
||||||
|
|
||||||
{pageMode === 'diff' ? (
|
{pageMode === 'diff' ? (
|
||||||
<>
|
<>
|
||||||
@@ -192,20 +174,15 @@ export default function Index() {
|
|||||||
justifyContent="space-between"
|
justifyContent="space-between"
|
||||||
alignItems={{ xs: 'stretch', sm: 'center' }}
|
alignItems={{ xs: 'stretch', sm: 'center' }}
|
||||||
>
|
>
|
||||||
<ToggleButtonGroup
|
<SwtichButtonGroup
|
||||||
size="small"
|
|
||||||
exclusive
|
|
||||||
value={viewMode}
|
value={viewMode}
|
||||||
onChange={(_, v: ViewMode | null) => v && setViewMode(v)}
|
onChange={(v: ViewMode) => setViewMode(v)}
|
||||||
sx={{ borderRadius: 3 }}
|
options={[
|
||||||
>
|
{ value: 'sideBySide', label: t('jsonDiff:sideBySideMode') },
|
||||||
<ToggleButton value="sideBySide" sx={{ px: 2, fontWeight: 700 }}>
|
{ value: 'unified', label: t('jsonDiff:unifiedMode') },
|
||||||
{t('jsonDiff:sideBySideMode')}
|
]}
|
||||||
</ToggleButton>
|
size="small"
|
||||||
<ToggleButton value="unified" sx={{ px: 2, fontWeight: 700 }}>
|
/>
|
||||||
{t('jsonDiff:unifiedMode')}
|
|
||||||
</ToggleButton>
|
|
||||||
</ToggleButtonGroup>
|
|
||||||
<Stack direction="row" spacing={1}>
|
<Stack direction="row" spacing={1}>
|
||||||
<Button variant="text" onClick={handleClear} sx={{ borderRadius: 3 }}>
|
<Button variant="text" onClick={handleClear} sx={{ borderRadius: 3 }}>
|
||||||
{t('jsonDiff:clearButton')}
|
{t('jsonDiff:clearButton')}
|
||||||
@@ -214,7 +191,7 @@ export default function Index() {
|
|||||||
variant="contained"
|
variant="contained"
|
||||||
disabled={!canCompare}
|
disabled={!canCompare}
|
||||||
onClick={handleCompare}
|
onClick={handleCompare}
|
||||||
sx={{ borderRadius: 3, fontWeight: 700, px: 3 }}
|
sx={{ borderRadius: 3, fontWeight: 700, px: 3, whiteSpace: 'nowrap' }}
|
||||||
>
|
>
|
||||||
{t('jsonDiff:compareButton')}
|
{t('jsonDiff:compareButton')}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
+14
-36
@@ -1,12 +1,11 @@
|
|||||||
import { useMemo, useState } from 'react';
|
import { useMemo, useState } from 'react';
|
||||||
import { Box, Container, Paper, Stack, TextField, Typography } from '@mui/material';
|
import { Box, Container, Paper, Stack, Typography } from '@mui/material';
|
||||||
import { useSnackbar } from '@/components/GlobalSnackbar';
|
import { useSnackbar } from '@/components/GlobalSnackbar';
|
||||||
import VpnKeyIcon from '@mui/icons-material/VpnKey';
|
import VpnKeyIcon from '@mui/icons-material/VpnKey';
|
||||||
import ErrorOutlineIcon from '@mui/icons-material/ErrorOutline';
|
|
||||||
import PageHeader from '@/components/PageHeader';
|
import PageHeader from '@/components/PageHeader';
|
||||||
import { jwtPageStyles } from '@/config/pageTheme';
|
import { stringifyJson, parseJwt } from '@/utils/jwt';
|
||||||
import { formatJson, parseJwt } from '@/utils/jwt';
|
|
||||||
import CopyButton from '@/components/CopyButton';
|
import CopyButton from '@/components/CopyButton';
|
||||||
|
import TextInputArea from '@/components/TextInputArea';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
interface SectionProps {
|
interface SectionProps {
|
||||||
@@ -52,14 +51,14 @@ const Section = ({ title, content, color }: SectionProps) => {
|
|||||||
border: '1px solid rgba(0,0,0,0.05)',
|
border: '1px solid rgba(0,0,0,0.05)',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{content ? formatJson(content) : t('jwt:invalidFormat')}
|
{content ? stringifyJson(content) : t('jwt:invalidFormat')}
|
||||||
</Box>
|
</Box>
|
||||||
</Paper>
|
</Paper>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function Index() {
|
export default function Index() {
|
||||||
useSnackbar();
|
const { showMessage } = useSnackbar();
|
||||||
const { t } = useTranslation(['jwt']);
|
const { t } = useTranslation(['jwt']);
|
||||||
const [jwtInput, setJwtInput] = useState('');
|
const [jwtInput, setJwtInput] = useState('');
|
||||||
|
|
||||||
@@ -81,41 +80,20 @@ export default function Index() {
|
|||||||
|
|
||||||
<Stack spacing={2.5}>
|
<Stack spacing={2.5}>
|
||||||
{/* Input Area */}
|
{/* Input Area */}
|
||||||
<TextField
|
<TextInputArea
|
||||||
multiline
|
minRows={4}
|
||||||
rows={4}
|
|
||||||
placeholder={t('jwt:placeholder')}
|
placeholder={t('jwt:placeholder')}
|
||||||
value={jwtInput}
|
value={jwtInput}
|
||||||
onChange={(e) => {
|
onChange={(val) => {
|
||||||
// 自动去除 Bearer 前缀及首尾空白字符/换行
|
const cleaned = val.replace(/^Bearer\s*/i, '').trim();
|
||||||
const val = e.target.value.replace(/^Bearer\s*/i, '').trim();
|
setJwtInput(cleaned);
|
||||||
setJwtInput(val);
|
|
||||||
}}
|
}}
|
||||||
fullWidth
|
allowCopy={true}
|
||||||
sx={jwtPageStyles.INPUT_STYLE}
|
showClear={true}
|
||||||
|
showMessage={showMessage}
|
||||||
|
externalError={result?.error}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{result?.error && (
|
|
||||||
<Paper
|
|
||||||
sx={{
|
|
||||||
p: 2,
|
|
||||||
bgcolor: 'error.lighter',
|
|
||||||
color: 'error.main',
|
|
||||||
borderRadius: 3,
|
|
||||||
display: 'flex',
|
|
||||||
alignItems: 'flex-start',
|
|
||||||
gap: 1.5,
|
|
||||||
border: '1px solid',
|
|
||||||
borderColor: 'error.light',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<ErrorOutlineIcon sx={{ mt: 0.2 }} fontSize="small" />
|
|
||||||
<Typography variant="body2" sx={{ fontWeight: 600 }}>
|
|
||||||
{result.error}
|
|
||||||
</Typography>
|
|
||||||
</Paper>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{result && !result.error && (
|
{result && !result.error && (
|
||||||
<Stack spacing={2}>
|
<Stack spacing={2}>
|
||||||
<Section
|
<Section
|
||||||
|
|||||||
@@ -7,13 +7,9 @@ import {
|
|||||||
Container,
|
Container,
|
||||||
Stack,
|
Stack,
|
||||||
TextField,
|
TextField,
|
||||||
ToggleButton,
|
|
||||||
ToggleButtonGroup,
|
|
||||||
Typography,
|
Typography,
|
||||||
Paper,
|
Paper,
|
||||||
} from '@mui/material';
|
} from '@mui/material';
|
||||||
import SplitscreenIcon from '@mui/icons-material/Splitscreen';
|
|
||||||
import VisibilityIcon from '@mui/icons-material/Visibility';
|
|
||||||
import CodeIcon from '@mui/icons-material/Code';
|
import CodeIcon from '@mui/icons-material/Code';
|
||||||
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
|
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
|
||||||
import PrintIcon from '@mui/icons-material/Print';
|
import PrintIcon from '@mui/icons-material/Print';
|
||||||
@@ -21,7 +17,7 @@ import DownloadIcon from '@mui/icons-material/Download';
|
|||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import PageHeader from '@/components/PageHeader';
|
import PageHeader from '@/components/PageHeader';
|
||||||
import CopyButton from '@/components/CopyButton';
|
import CopyButton from '@/components/CopyButton';
|
||||||
import { markdownToHtmlPageStyles } from '@/config/pageTheme';
|
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||||
import { useStorageState } from '@/utils/useStorageState';
|
import { useStorageState } from '@/utils/useStorageState';
|
||||||
import type { MarkdownToHtmlPreviewMode } from '@/types/storage';
|
import type { MarkdownToHtmlPreviewMode } from '@/types/storage';
|
||||||
import {
|
import {
|
||||||
@@ -144,8 +140,8 @@ export default function MarkdownToHtmlPage() {
|
|||||||
}, [result.html]);
|
}, [result.html]);
|
||||||
|
|
||||||
const handleModeChange = useCallback(
|
const handleModeChange = useCallback(
|
||||||
(_event: React.MouseEvent<HTMLElement>, newMode: MarkdownToHtmlPreviewMode | null) => {
|
(newMode: MarkdownToHtmlPreviewMode) => {
|
||||||
if (newMode) setPreviewMode(newMode);
|
setPreviewMode(newMode);
|
||||||
},
|
},
|
||||||
[setPreviewMode],
|
[setPreviewMode],
|
||||||
);
|
);
|
||||||
@@ -179,26 +175,16 @@ export default function MarkdownToHtmlPage() {
|
|||||||
flexWrap="wrap"
|
flexWrap="wrap"
|
||||||
gap={1.5}
|
gap={1.5}
|
||||||
>
|
>
|
||||||
<ToggleButtonGroup
|
<SwitchButtonGroup
|
||||||
value={previewMode}
|
value={previewMode}
|
||||||
exclusive
|
options={[
|
||||||
|
{ value: 'split', label: t('splitMode') },
|
||||||
|
{ value: 'preview', label: t('previewMode') },
|
||||||
|
{ value: 'html', label: t('htmlMode') },
|
||||||
|
]}
|
||||||
onChange={handleModeChange}
|
onChange={handleModeChange}
|
||||||
size="small"
|
size="small"
|
||||||
sx={markdownToHtmlPageStyles.MODE_SWITCHER}
|
/>
|
||||||
>
|
|
||||||
<ToggleButton value="split">
|
|
||||||
<SplitscreenIcon sx={{ fontSize: 16, mr: 0.5 }} />
|
|
||||||
{t('splitMode')}
|
|
||||||
</ToggleButton>
|
|
||||||
<ToggleButton value="preview">
|
|
||||||
<VisibilityIcon sx={{ fontSize: 16, mr: 0.5 }} />
|
|
||||||
{t('previewMode')}
|
|
||||||
</ToggleButton>
|
|
||||||
<ToggleButton value="html">
|
|
||||||
<CodeIcon sx={{ fontSize: 16, mr: 0.5 }} />
|
|
||||||
{t('htmlMode')}
|
|
||||||
</ToggleButton>
|
|
||||||
</ToggleButtonGroup>
|
|
||||||
|
|
||||||
<Stack direction="row" spacing={1}>
|
<Stack direction="row" spacing={1}>
|
||||||
<Button
|
<Button
|
||||||
|
|||||||
@@ -26,9 +26,15 @@ import { useTranslation } from 'react-i18next';
|
|||||||
interface QrCodeToUrlSectionProps {
|
interface QrCodeToUrlSectionProps {
|
||||||
expanded: boolean;
|
expanded: boolean;
|
||||||
onExpandedChange: (expanded: boolean) => void;
|
onExpandedChange: (expanded: boolean) => void;
|
||||||
|
/** 桌面端强制展开(隐藏折叠交互) */
|
||||||
|
forceExpanded?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const QrCodeToUrlSection = ({ expanded, onExpandedChange }: QrCodeToUrlSectionProps) => {
|
const QrCodeToUrlSection = ({
|
||||||
|
expanded,
|
||||||
|
onExpandedChange,
|
||||||
|
forceExpanded = false,
|
||||||
|
}: QrCodeToUrlSectionProps) => {
|
||||||
const { t } = useTranslation(['qrCode']);
|
const { t } = useTranslation(['qrCode']);
|
||||||
const { showMessage } = useSnackbar();
|
const { showMessage } = useSnackbar();
|
||||||
const [qrCodeFile, setQrCodeFile] = useState<File | null>(null);
|
const [qrCodeFile, setQrCodeFile] = useState<File | null>(null);
|
||||||
@@ -163,9 +169,9 @@ const QrCodeToUrlSection = ({ expanded, onExpandedChange }: QrCodeToUrlSectionPr
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Accordion
|
<Accordion
|
||||||
expanded={expanded}
|
expanded={forceExpanded ? true : expanded}
|
||||||
onChange={(_, isExpanded) => onExpandedChange(isExpanded)}
|
onChange={forceExpanded ? undefined : (_, isExpanded) => onExpandedChange(isExpanded)}
|
||||||
sx={qrCodePageStyles.ACCORDION}
|
sx={forceExpanded ? qrCodePageStyles.ACCORDION_DESKTOP : qrCodePageStyles.ACCORDION}
|
||||||
>
|
>
|
||||||
<AccordionSummary expandIcon={<ExpandMoreIcon />} sx={qrCodePageStyles.ACCORDION_SUMMARY}>
|
<AccordionSummary expandIcon={<ExpandMoreIcon />} sx={qrCodePageStyles.ACCORDION_SUMMARY}>
|
||||||
<Box sx={qrCodePageStyles.ACCORDION_TITLE_ICON}>
|
<Box sx={qrCodePageStyles.ACCORDION_TITLE_ICON}>
|
||||||
@@ -178,6 +184,7 @@ const QrCodeToUrlSection = ({ expanded, onExpandedChange }: QrCodeToUrlSectionPr
|
|||||||
<AccordionDetails>
|
<AccordionDetails>
|
||||||
<Stack spacing={3}>
|
<Stack spacing={3}>
|
||||||
<Box
|
<Box
|
||||||
|
className="qr-flex-grow"
|
||||||
sx={qrCodePageStyles.DROPZONE(dragging, !!qrCodeFile)}
|
sx={qrCodePageStyles.DROPZONE(dragging, !!qrCodeFile)}
|
||||||
onDragOver={handleDragOver}
|
onDragOver={handleDragOver}
|
||||||
onDragLeave={handleDragLeave}
|
onDragLeave={handleDragLeave}
|
||||||
|
|||||||
@@ -22,9 +22,15 @@ import { useTranslation } from 'react-i18next';
|
|||||||
interface UrlToQrCodeSectionProps {
|
interface UrlToQrCodeSectionProps {
|
||||||
expanded: boolean;
|
expanded: boolean;
|
||||||
onExpandedChange: (expanded: boolean) => void;
|
onExpandedChange: (expanded: boolean) => void;
|
||||||
|
/** 桌面端强制展开(隐藏折叠交互) */
|
||||||
|
forceExpanded?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const UrlToQrCodeSection = ({ expanded, onExpandedChange }: UrlToQrCodeSectionProps) => {
|
const UrlToQrCodeSection = ({
|
||||||
|
expanded,
|
||||||
|
onExpandedChange,
|
||||||
|
forceExpanded = false,
|
||||||
|
}: UrlToQrCodeSectionProps) => {
|
||||||
const { t } = useTranslation(['qrCode']);
|
const { t } = useTranslation(['qrCode']);
|
||||||
const { showMessage } = useSnackbar();
|
const { showMessage } = useSnackbar();
|
||||||
const [urlInput, setUrlInput] = useState('');
|
const [urlInput, setUrlInput] = useState('');
|
||||||
@@ -103,9 +109,9 @@ const UrlToQrCodeSection = ({ expanded, onExpandedChange }: UrlToQrCodeSectionPr
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Accordion
|
<Accordion
|
||||||
expanded={expanded}
|
expanded={forceExpanded ? true : expanded}
|
||||||
onChange={(_, isExpanded) => onExpandedChange(isExpanded)}
|
onChange={forceExpanded ? undefined : (_, isExpanded) => onExpandedChange(isExpanded)}
|
||||||
sx={qrCodePageStyles.ACCORDION}
|
sx={forceExpanded ? qrCodePageStyles.ACCORDION_DESKTOP : qrCodePageStyles.ACCORDION}
|
||||||
>
|
>
|
||||||
<AccordionSummary expandIcon={<ExpandMoreIcon />} sx={qrCodePageStyles.ACCORDION_SUMMARY}>
|
<AccordionSummary expandIcon={<ExpandMoreIcon />} sx={qrCodePageStyles.ACCORDION_SUMMARY}>
|
||||||
<Box sx={qrCodePageStyles.ACCORDION_TITLE_ICON}>
|
<Box sx={qrCodePageStyles.ACCORDION_TITLE_ICON}>
|
||||||
@@ -139,7 +145,7 @@ const UrlToQrCodeSection = ({ expanded, onExpandedChange }: UrlToQrCodeSectionPr
|
|||||||
{generating ? t('qrCode:generating') : t('qrCode:generateButton')}
|
{generating ? t('qrCode:generating') : t('qrCode:generateButton')}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<Box sx={qrCodePageStyles.QR_PREVIEW_CONTAINER}>
|
<Box className="qr-flex-grow" sx={qrCodePageStyles.QR_PREVIEW_CONTAINER}>
|
||||||
{qrCodeDataUrl ? (
|
{qrCodeDataUrl ? (
|
||||||
<Box sx={qrCodePageStyles.QR_PREVIEW_INNER}>
|
<Box sx={qrCodePageStyles.QR_PREVIEW_INNER}>
|
||||||
<img src={qrCodeDataUrl} alt="QR Code" style={qrCodePageStyles.QR_PREVIEW_IMAGE} />
|
<img src={qrCodeDataUrl} alt="QR Code" style={qrCodePageStyles.QR_PREVIEW_IMAGE} />
|
||||||
|
|||||||
+37
-8
@@ -1,4 +1,4 @@
|
|||||||
import { Box, CircularProgress, Container, Stack } from '@mui/material';
|
import { Box, CircularProgress, Container, Stack, useMediaQuery, useTheme } from '@mui/material';
|
||||||
import QrCodeIcon from '@mui/icons-material/QrCode';
|
import QrCodeIcon from '@mui/icons-material/QrCode';
|
||||||
import UrlToQrCodeSection from '@/pages/QrCode/UrlToQrCodeSection';
|
import UrlToQrCodeSection from '@/pages/QrCode/UrlToQrCodeSection';
|
||||||
import QrCodeToUrlSection from '@/pages/QrCode/QrCodeToUrlSection';
|
import QrCodeToUrlSection from '@/pages/QrCode/QrCodeToUrlSection';
|
||||||
@@ -9,8 +9,10 @@ import { useTranslation } from 'react-i18next';
|
|||||||
|
|
||||||
export default function Index() {
|
export default function Index() {
|
||||||
const { t } = useTranslation(['qrCode']);
|
const { t } = useTranslation(['qrCode']);
|
||||||
|
const theme = useTheme();
|
||||||
|
const isDesktop = useMediaQuery(theme.breakpoints.up('md'));
|
||||||
|
|
||||||
// 使用自定义钩子管理展开状态
|
// 使用自定义钩子管理展开状态(移动端使用)
|
||||||
const [urlExpanded, setUrlExpanded, urlInitialized] = useStorageState('qrCode/urlExpanded', true);
|
const [urlExpanded, setUrlExpanded, urlInitialized] = useStorageState('qrCode/urlExpanded', true);
|
||||||
const [qrExpanded, setQrExpanded, qrInitialized] = useStorageState('qrCode/qrExpanded', false);
|
const [qrExpanded, setQrExpanded, qrInitialized] = useStorageState('qrCode/qrExpanded', false);
|
||||||
|
|
||||||
@@ -23,9 +25,36 @@ export default function Index() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const sections = isDesktop ? (
|
||||||
|
<>
|
||||||
|
<Box sx={qrCodePageStyles.GRID_CELL}>
|
||||||
|
<UrlToQrCodeSection
|
||||||
|
expanded={urlExpanded}
|
||||||
|
onExpandedChange={setUrlExpanded}
|
||||||
|
forceExpanded={isDesktop}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
<Box sx={qrCodePageStyles.GRID_CELL}>
|
||||||
|
<QrCodeToUrlSection
|
||||||
|
expanded={qrExpanded}
|
||||||
|
onExpandedChange={setQrExpanded}
|
||||||
|
forceExpanded={isDesktop}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<UrlToQrCodeSection expanded={urlExpanded} onExpandedChange={setUrlExpanded} />
|
||||||
|
<QrCodeToUrlSection expanded={qrExpanded} onExpandedChange={setQrExpanded} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box>
|
<Box>
|
||||||
<Container sx={{ py: 2, maxWidth: 400 }}>
|
<Container
|
||||||
|
maxWidth={isDesktop ? 'lg' : false}
|
||||||
|
sx={{ py: 2, maxWidth: isDesktop ? undefined : 400 }}
|
||||||
|
>
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title={t('qrCode:pageTitle')}
|
title={t('qrCode:pageTitle')}
|
||||||
subtitle={t('qrCode:pageSubtitle')}
|
subtitle={t('qrCode:pageSubtitle')}
|
||||||
@@ -34,11 +63,11 @@ export default function Index() {
|
|||||||
sx={{ mb: 2.5 }}
|
sx={{ mb: 2.5 }}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Stack spacing={3}>
|
{isDesktop ? (
|
||||||
<UrlToQrCodeSection expanded={urlExpanded} onExpandedChange={setUrlExpanded} />
|
<Box sx={qrCodePageStyles.LAYOUT_GRID}>{sections}</Box>
|
||||||
|
) : (
|
||||||
<QrCodeToUrlSection expanded={qrExpanded} onExpandedChange={setQrExpanded} />
|
<Stack spacing={3}>{sections}</Stack>
|
||||||
</Stack>
|
)}
|
||||||
</Container>
|
</Container>
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import {
|
|||||||
getCacheStorageSize,
|
getCacheStorageSize,
|
||||||
getCookieSize,
|
getCookieSize,
|
||||||
getCurrentTab,
|
getCurrentTab,
|
||||||
getIndexedDBSize,
|
getOriginStorageEstimate,
|
||||||
getLocalStorageSize,
|
getLocalStorageSize,
|
||||||
getServiceWorkerCount,
|
getServiceWorkerCount,
|
||||||
getSessionStorageSize,
|
getSessionStorageSize,
|
||||||
@@ -116,7 +116,7 @@ export function useStorageCleaner({
|
|||||||
getCookieSize(url),
|
getCookieSize(url),
|
||||||
getLocalStorageSize(tabId),
|
getLocalStorageSize(tabId),
|
||||||
getSessionStorageSize(tabId),
|
getSessionStorageSize(tabId),
|
||||||
getIndexedDBSize(tabId),
|
getOriginStorageEstimate(tabId),
|
||||||
getCacheStorageSize(tabId),
|
getCacheStorageSize(tabId),
|
||||||
getServiceWorkerCount(tabId),
|
getServiceWorkerCount(tabId),
|
||||||
]);
|
]);
|
||||||
@@ -243,7 +243,7 @@ export function useStorageCleaner({
|
|||||||
await loadInfo();
|
await loadInfo();
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
showMessage(`${t('common:messages.copyError')}: ${String(err)}`, { severity: 'error' });
|
showMessage(`${t('storageCleaner:cleanError')}: ${String(err)}`, { severity: 'error' });
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
setShowConfirm(false);
|
setShowConfirm(false);
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useMemo, useState } from 'react';
|
import { useMemo, useState } from 'react';
|
||||||
import { alpha, Box, Container, Grid, Paper, TextField, Typography } from '@mui/material';
|
import { alpha, Box, Container, Grid, Paper, Typography } from '@mui/material';
|
||||||
import PageHeader from '@/components/PageHeader';
|
import PageHeader from '@/components/PageHeader';
|
||||||
|
import TextInputArea from '@/components/TextInputArea';
|
||||||
import DescriptionIcon from '@mui/icons-material/Description';
|
import DescriptionIcon from '@mui/icons-material/Description';
|
||||||
import { formatByteSize, getTextStats } from '@/utils/textStatistics';
|
import { formatByteSize, getTextStats } from '@/utils/textStatistics';
|
||||||
import { textStatisticsPageStyles } from '@/config/pageTheme';
|
import { textStatisticsPageStyles } from '@/config/pageTheme';
|
||||||
@@ -38,38 +39,14 @@ export default function Index() {
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
{/* 文本输入区域 */}
|
{/* 文本输入区域 */}
|
||||||
<TextField
|
<TextInputArea
|
||||||
multiline
|
value={text}
|
||||||
fullWidth
|
onChange={setText}
|
||||||
|
placeholder={t('textStatistics:placeholder')}
|
||||||
minRows={8}
|
minRows={8}
|
||||||
maxRows={15}
|
maxRows={15}
|
||||||
placeholder={t('textStatistics:placeholder')}
|
showClear={false}
|
||||||
value={text}
|
sx={{ mb: 3 }}
|
||||||
onChange={(e) => setText(e.target.value)}
|
|
||||||
sx={{
|
|
||||||
mb: 3,
|
|
||||||
'& .MuiOutlinedInput-root': {
|
|
||||||
borderRadius: 4,
|
|
||||||
bgcolor: (theme) =>
|
|
||||||
theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.03)' : 'grey.50',
|
|
||||||
transition: 'all 0.2s',
|
|
||||||
'& fieldset': {
|
|
||||||
borderColor: (theme) =>
|
|
||||||
theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.1)' : 'grey.200',
|
|
||||||
},
|
|
||||||
'&:hover fieldset': {
|
|
||||||
borderColor: (theme) =>
|
|
||||||
theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.2)' : 'grey.300',
|
|
||||||
},
|
|
||||||
'&.Mui-focused fieldset': {
|
|
||||||
borderColor: textStatisticsPageStyles.primaryColor,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
'& .MuiInputBase-input': {
|
|
||||||
fontSize: '0.9rem',
|
|
||||||
lineHeight: 1.6,
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* 统计结果展示区域 */}
|
{/* 统计结果展示区域 */}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { Box, Divider, IconButton, Stack, Tooltip, Typography } from '@mui/material';
|
import { Box, IconButton, Tooltip, Typography } from '@mui/material';
|
||||||
import AccessTimeIcon from '@mui/icons-material/AccessTime';
|
import AccessTimeIcon from '@mui/icons-material/AccessTime';
|
||||||
import CopyButton from '@/components/CopyButton';
|
import CopyButton from '@/components/CopyButton';
|
||||||
import { useSnackbar } from '@/components/GlobalSnackbar';
|
import { useSnackbar } from '@/components/GlobalSnackbar';
|
||||||
@@ -10,10 +10,9 @@ import { useTranslation } from 'react-i18next';
|
|||||||
interface LiveClockProps {
|
interface LiveClockProps {
|
||||||
unit: UnitType;
|
unit: UnitType;
|
||||||
onUseNow: (val: number) => void;
|
onUseNow: (val: number) => void;
|
||||||
onUnitChange: (u: UnitType) => void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const LiveClock = React.memo(({ unit, onUseNow, onUnitChange }: LiveClockProps) => {
|
const LiveClock = React.memo(({ unit, onUseNow }: LiveClockProps) => {
|
||||||
const [now, setNow] = useState(() => Date.now());
|
const [now, setNow] = useState(() => Date.now());
|
||||||
const { t } = useTranslation(['timestamp']);
|
const { t } = useTranslation(['timestamp']);
|
||||||
const { showMessage } = useSnackbar();
|
const { showMessage } = useSnackbar();
|
||||||
@@ -24,8 +23,8 @@ const LiveClock = React.memo(({ unit, onUseNow, onUnitChange }: LiveClockProps)
|
|||||||
}, [onUseNow]);
|
}, [onUseNow]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const t = setInterval(() => setNow(Date.now()), 1000);
|
const tickId = setInterval(() => setNow(Date.now()), 1000);
|
||||||
return () => clearInterval(t);
|
return () => clearInterval(tickId);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const displayVal = useMemo(
|
const displayVal = useMemo(
|
||||||
@@ -40,32 +39,12 @@ const LiveClock = React.memo(({ unit, onUseNow, onUnitChange }: LiveClockProps)
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Box sx={timestampPageStyles.LIVE_CLOCK_CARD}>
|
<Box sx={timestampPageStyles.LIVE_CLOCK_CARD}>
|
||||||
<Stack spacing={0.5} sx={{ minWidth: { xs: 100, sm: 120 } }}>
|
|
||||||
<Typography variant="caption" sx={timestampPageStyles.LIVE_CLOCK_LABEL}>
|
<Typography variant="caption" sx={timestampPageStyles.LIVE_CLOCK_LABEL}>
|
||||||
{t('timestamp:currentTs')}
|
{t('timestamp:currentTs')}
|
||||||
</Typography>
|
</Typography>
|
||||||
<Typography variant="subtitle2" sx={timestampPageStyles.LIVE_CLOCK_VALUE}>
|
<Typography variant="subtitle2" sx={timestampPageStyles.LIVE_CLOCK_VALUE}>
|
||||||
{displayVal}
|
{displayVal}
|
||||||
</Typography>
|
</Typography>
|
||||||
</Stack>
|
|
||||||
|
|
||||||
<Stack direction="row" spacing={1} alignItems="center" sx={{ flexShrink: 0 }}>
|
|
||||||
{/* 胶囊式单位切换器 */}
|
|
||||||
<Box sx={timestampPageStyles.LIVE_CLOCK_UNIT_SWITCHER}>
|
|
||||||
{(['ms', 's'] as const).map((u) => (
|
|
||||||
<Box
|
|
||||||
key={u}
|
|
||||||
onClick={() => onUnitChange(u)}
|
|
||||||
sx={timestampPageStyles.LIVE_CLOCK_UNIT_ITEM(unit === u)}
|
|
||||||
>
|
|
||||||
{u.toUpperCase()}
|
|
||||||
</Box>
|
|
||||||
))}
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Divider orientation="vertical" flexItem sx={timestampPageStyles.LIVE_CLOCK_DIVIDER} />
|
|
||||||
|
|
||||||
<Stack direction="row" spacing={0.5}>
|
|
||||||
<Tooltip title={t('timestamp:useNowTooltip')}>
|
<Tooltip title={t('timestamp:useNowTooltip')}>
|
||||||
<IconButton
|
<IconButton
|
||||||
size="small"
|
size="small"
|
||||||
@@ -81,8 +60,6 @@ const LiveClock = React.memo(({ unit, onUseNow, onUnitChange }: LiveClockProps)
|
|||||||
size="small"
|
size="small"
|
||||||
color={timestampPageStyles.primaryColor}
|
color={timestampPageStyles.primaryColor}
|
||||||
/>
|
/>
|
||||||
</Stack>
|
|
||||||
</Stack>
|
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -11,10 +11,14 @@ interface ResultViewProps {
|
|||||||
mode: 'ts2dt' | 'dt2ts';
|
mode: 'ts2dt' | 'dt2ts';
|
||||||
unit: UnitType;
|
unit: UnitType;
|
||||||
zone: string;
|
zone: string;
|
||||||
|
/** 无结果时是否渲染占位(桌面端右栏使用),默认 false(移动端单栏隐藏) */
|
||||||
|
showEmptyPlaceholder?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ResultView = React.memo(({ result, mode, unit, zone }: ResultViewProps) => {
|
const ResultView = React.memo(
|
||||||
|
({ result, mode, unit, zone, showEmptyPlaceholder = false }: ResultViewProps) => {
|
||||||
const { t } = useTranslation(['timestamp']);
|
const { t } = useTranslation(['timestamp']);
|
||||||
|
|
||||||
const extraInfo = useMemo(() => {
|
const extraInfo = useMemo(() => {
|
||||||
if (!result) return null;
|
if (!result) return null;
|
||||||
const d =
|
const d =
|
||||||
@@ -31,11 +35,16 @@ const ResultView = React.memo(({ result, mode, unit, zone }: ResultViewProps) =>
|
|||||||
};
|
};
|
||||||
}, [result, mode, zone, unit]);
|
}, [result, mode, zone, unit]);
|
||||||
|
|
||||||
if (!result) return null;
|
if (!result) {
|
||||||
|
if (!showEmptyPlaceholder) return null;
|
||||||
|
return (
|
||||||
|
<Box sx={timestampPageStyles.RESULT_EMPTY_PLACEHOLDER}>{t('timestamp:resultEmpty')}</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Fade in={!!result}>
|
<Fade in={!!result}>
|
||||||
<Box sx={{ mt: 3, pt: 2.5, borderTop: '1px solid', borderColor: 'divider' }}>
|
<Box>
|
||||||
<Typography variant="caption" sx={timestampPageStyles.RESULT_LABEL}>
|
<Typography variant="caption" sx={timestampPageStyles.RESULT_LABEL}>
|
||||||
{t('timestamp:resultLabel')}
|
{t('timestamp:resultLabel')}
|
||||||
</Typography>
|
</Typography>
|
||||||
@@ -65,7 +74,7 @@ const ResultView = React.memo(({ result, mode, unit, zone }: ResultViewProps) =>
|
|||||||
<Typography variant="caption" sx={timestampPageStyles.RESULT_EXTRA_LABEL}>
|
<Typography variant="caption" sx={timestampPageStyles.RESULT_EXTRA_LABEL}>
|
||||||
{item.label}
|
{item.label}
|
||||||
</Typography>
|
</Typography>
|
||||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, minWidth: 0 }}>
|
||||||
<Typography variant="caption" sx={timestampPageStyles.RESULT_EXTRA_VALUE}>
|
<Typography variant="caption" sx={timestampPageStyles.RESULT_EXTRA_VALUE}>
|
||||||
{item.value}
|
{item.value}
|
||||||
</Typography>
|
</Typography>
|
||||||
@@ -84,7 +93,8 @@ const ResultView = React.memo(({ result, mode, unit, zone }: ResultViewProps) =>
|
|||||||
</Box>
|
</Box>
|
||||||
</Fade>
|
</Fade>
|
||||||
);
|
);
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
ResultView.displayName = 'ResultView';
|
ResultView.displayName = 'ResultView';
|
||||||
|
|
||||||
|
|||||||
+55
-42
@@ -1,16 +1,8 @@
|
|||||||
import {
|
import { Box, Container, MenuItem, Select, Stack, TextField } from '@mui/material';
|
||||||
Box,
|
|
||||||
Container,
|
|
||||||
MenuItem,
|
|
||||||
Select,
|
|
||||||
Stack,
|
|
||||||
TextField,
|
|
||||||
ToggleButton,
|
|
||||||
ToggleButtonGroup,
|
|
||||||
} from '@mui/material';
|
|
||||||
import AccessTimeIcon from '@mui/icons-material/AccessTime';
|
import AccessTimeIcon from '@mui/icons-material/AccessTime';
|
||||||
import Button from '@/components/Button';
|
import Button from '@/components/Button';
|
||||||
import PageHeader from '@/components/PageHeader';
|
import PageHeader from '@/components/PageHeader';
|
||||||
|
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||||
import { timestampPageStyles, ZONES } from '@/config/pageTheme';
|
import { timestampPageStyles, ZONES } from '@/config/pageTheme';
|
||||||
import LiveClock from './LiveClock';
|
import LiveClock from './LiveClock';
|
||||||
import ResultView from './ResultView';
|
import ResultView from './ResultView';
|
||||||
@@ -37,7 +29,7 @@ export default function Index() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Box>
|
<Box>
|
||||||
<Container sx={{ p: 2 }}>
|
<Container maxWidth="lg" sx={{ p: 2 }}>
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<PageHeader
|
<PageHeader
|
||||||
title={t('timestamp:pageTitle')}
|
title={t('timestamp:pageTitle')}
|
||||||
@@ -45,22 +37,26 @@ export default function Index() {
|
|||||||
icon={<AccessTimeIcon />}
|
icon={<AccessTimeIcon />}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Live Clock Card */}
|
{/* 参考信息:分栏上方全宽单行参考条 */}
|
||||||
<LiveClock unit={unit} onUseNow={handleUseNow} onUnitChange={setUnit} />
|
<LiveClock unit={unit} onUseNow={handleUseNow} />
|
||||||
|
|
||||||
{/* Mode Switcher */}
|
{/* 桌面端 md+ 左右分栏;移动端单栏堆叠 */}
|
||||||
<ToggleButtonGroup
|
<Box sx={timestampPageStyles.LAYOUT_GRID}>
|
||||||
|
{/* 左栏:转换工作台 */}
|
||||||
|
<Box sx={timestampPageStyles.CONVERSION_CARD}>
|
||||||
|
{/* 模式切换 */}
|
||||||
|
<SwitchButtonGroup
|
||||||
value={mode}
|
value={mode}
|
||||||
exclusive
|
options={[
|
||||||
onChange={(_, newMode) => newMode && setMode(newMode)}
|
{ value: 'ts2dt', label: t('timestamp:tsToDate') },
|
||||||
sx={timestampPageStyles.MODE_SWITCHER}
|
{ value: 'dt2ts', label: t('timestamp:dateToTs') },
|
||||||
>
|
]}
|
||||||
<ToggleButton value="ts2dt">{t('timestamp:tsToDate')}</ToggleButton>
|
onChange={(newMode) => setMode(newMode)}
|
||||||
<ToggleButton value="dt2ts">{t('timestamp:dateToTs')}</ToggleButton>
|
size="small"
|
||||||
</ToggleButtonGroup>
|
/>
|
||||||
|
|
||||||
{/* Input Area */}
|
{/* 输入区 */}
|
||||||
<Stack spacing={2} sx={{ mb: 3 }}>
|
<Stack spacing={1.5}>
|
||||||
<TextField
|
<TextField
|
||||||
placeholder={
|
placeholder={
|
||||||
mode === 'ts2dt' ? t('timestamp:placeholderTs') : t('timestamp:placeholderDate')
|
mode === 'ts2dt' ? t('timestamp:placeholderTs') : t('timestamp:placeholderDate')
|
||||||
@@ -73,25 +69,38 @@ export default function Index() {
|
|||||||
sx={timestampPageStyles.INPUT_STYLE}
|
sx={timestampPageStyles.INPUT_STYLE}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Stack direction="row" spacing={1.5}>
|
{/* 单位+时区紧凑横排 */}
|
||||||
{/* 单位选择按钮组 */}
|
<Stack
|
||||||
<Box sx={timestampPageStyles.UNIT_SWITCHER_CONTAINER}>
|
direction="row"
|
||||||
{(['ms', 's'] as const).map((u) => (
|
spacing={1.5}
|
||||||
<Box
|
useFlexGap
|
||||||
key={u}
|
sx={{ width: '100%', flexWrap: 'wrap' }}
|
||||||
onClick={() => setUnit(u)}
|
|
||||||
sx={timestampPageStyles.UNIT_SWITCHER_ITEM(unit === u)}
|
|
||||||
>
|
>
|
||||||
{u === 'ms' ? t('timestamp:unitMs') : t('timestamp:unitS')}
|
<SwitchButtonGroup
|
||||||
</Box>
|
value={unit}
|
||||||
))}
|
options={[
|
||||||
</Box>
|
{ value: 'ms', label: t('timestamp:unitMs') },
|
||||||
|
{ value: 's', label: t('timestamp:unitS') },
|
||||||
|
]}
|
||||||
|
onChange={(v) => setUnit(v as 'ms' | 's')}
|
||||||
|
sx={{ width: 'auto', mb: 0, flexShrink: 0 }}
|
||||||
|
size="small"
|
||||||
|
/>
|
||||||
|
|
||||||
<Select
|
<Select
|
||||||
fullWidth
|
|
||||||
value={zone}
|
value={zone}
|
||||||
onChange={(e) => setZone(e.target.value as typeof zone)}
|
onChange={(e) => setZone(e.target.value as typeof zone)}
|
||||||
sx={{ ...timestampPageStyles.INPUT_STYLE, flex: 1, borderRadius: 4 }}
|
sx={{
|
||||||
|
...timestampPageStyles.INPUT_STYLE,
|
||||||
|
flex: 1,
|
||||||
|
minWidth: 0,
|
||||||
|
borderRadius: 4,
|
||||||
|
'& .MuiSelect-select': {
|
||||||
|
overflow: 'hidden',
|
||||||
|
textOverflow: 'ellipsis',
|
||||||
|
whiteSpace: 'nowrap',
|
||||||
|
},
|
||||||
|
}}
|
||||||
MenuProps={timestampPageStyles.SELECT_MENU_PROPS}
|
MenuProps={timestampPageStyles.SELECT_MENU_PROPS}
|
||||||
>
|
>
|
||||||
{ZONES.map((z) => (
|
{ZONES.map((z) => (
|
||||||
@@ -103,13 +112,17 @@ export default function Index() {
|
|||||||
</Stack>
|
</Stack>
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
||||||
{/* Main Action */}
|
{/* 立即转换 */}
|
||||||
<Button fullWidth variant="contained" onClick={convert}>
|
<Button variant="contained" onClick={convert} sx={timestampPageStyles.CONVERT_BUTTON}>
|
||||||
{t('timestamp:convertButton')}
|
{t('timestamp:convertButton')}
|
||||||
</Button>
|
</Button>
|
||||||
|
</Box>
|
||||||
|
|
||||||
{/* Result View */}
|
{/* 右栏:结果展示卡片 */}
|
||||||
<ResultView result={result} mode={mode} unit={unit} zone={zone} />
|
<Box sx={timestampPageStyles.RESULT_COLUMN_CARD}>
|
||||||
|
<ResultView result={result} mode={mode} unit={unit} zone={zone} showEmptyPlaceholder />
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
</Container>
|
</Container>
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useCallback, useEffect, useState } from 'react';
|
import { useCallback, useState } from 'react';
|
||||||
import dayjs from '@/utils/dayjs';
|
import dayjs from '@/utils/dayjs';
|
||||||
import type { UnitType, ZoneType } from '@/config/pageTheme';
|
import type { UnitType, ZoneType } from '@/config/pageTheme';
|
||||||
import { DATE_FORMAT } from '@/config/pageTheme';
|
import { DATE_FORMAT } from '@/config/pageTheme';
|
||||||
@@ -63,11 +63,6 @@ export function useTimestampConverter(): UseTimestampConverterReturn {
|
|||||||
}
|
}
|
||||||
}, [mode, tsInput, dtInput, unit, zone, t]);
|
}, [mode, tsInput, dtInput, unit, zone, t]);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const timer = setTimeout(convert, 400);
|
|
||||||
return () => clearTimeout(timer);
|
|
||||||
}, [convert]);
|
|
||||||
|
|
||||||
const handleUseNow = useCallback(
|
const handleUseNow = useCallback(
|
||||||
(now: number) => {
|
(now: number) => {
|
||||||
if (mode === 'ts2dt') {
|
if (mode === 'ts2dt') {
|
||||||
|
|||||||
@@ -1,4 +1,12 @@
|
|||||||
import { createContext, ReactNode, useCallback, useContext, useEffect, useState } from 'react';
|
import {
|
||||||
|
createContext,
|
||||||
|
ReactNode,
|
||||||
|
useCallback,
|
||||||
|
useContext,
|
||||||
|
useEffect,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
} from 'react';
|
||||||
import type { PageType, StorageSchema } from '@/types/storage';
|
import type { PageType, StorageSchema } from '@/types/storage';
|
||||||
import { storageUtil } from '@/utils/chromeStorage';
|
import { storageUtil } from '@/utils/chromeStorage';
|
||||||
import {
|
import {
|
||||||
@@ -56,10 +64,6 @@ interface RouterContextType {
|
|||||||
isLoaded: boolean;
|
isLoaded: boolean;
|
||||||
/** 导航到指定页面 */
|
/** 导航到指定页面 */
|
||||||
navigateTo: (page: PageType) => void;
|
navigateTo: (page: PageType) => void;
|
||||||
/** 仅在本地(当前组件状态)跳转,不影响其他同步端 */
|
|
||||||
navigateLocal: (page: PageType) => void;
|
|
||||||
/** 强制同步当前路由到存储 */
|
|
||||||
syncNavigation: (page: PageType) => void;
|
|
||||||
/** 返回仪表盘 */
|
/** 返回仪表盘 */
|
||||||
goBack: () => void;
|
goBack: () => void;
|
||||||
/** 设置可见页面列表 */
|
/** 设置可见页面列表 */
|
||||||
@@ -173,14 +177,22 @@ export function RouterProvider({
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('加载初始路由数据失败:', error);
|
console.error('加载初始路由数据失败:', error);
|
||||||
} finally {
|
|
||||||
setIsLoaded(true);
|
|
||||||
}
|
}
|
||||||
}, [defaultRoute, syncKey, syncRoute, visiblePagesKey, pageOrderKey]);
|
}, [defaultRoute, syncKey, syncRoute, visiblePagesKey, pageOrderKey]);
|
||||||
|
|
||||||
// 组件挂载时加载初始数据
|
// 组件挂载时加载初始数据
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadInitialData().catch(console.error);
|
let cancelled = false;
|
||||||
|
loadInitialData()
|
||||||
|
.then(() => {
|
||||||
|
if (!cancelled) {
|
||||||
|
setIsLoaded(true);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(console.error);
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
}, [loadInitialData]);
|
}, [loadInitialData]);
|
||||||
|
|
||||||
// 当 currentPage 改变时,如果开启了同步,则持久化到存储和本地快照
|
// 当 currentPage 改变时,如果开启了同步,则持久化到存储和本地快照
|
||||||
@@ -207,6 +219,12 @@ export function RouterProvider({
|
|||||||
}
|
}
|
||||||
}, [pageOrder, isLoaded, pageOrderKey]);
|
}, [pageOrder, isLoaded, pageOrderKey]);
|
||||||
|
|
||||||
|
// 用 ref 持有最新 currentPage,避免每次路由跳转都重注册 chrome.storage 监听器
|
||||||
|
const currentPageRef = useRef(currentPage);
|
||||||
|
useEffect(() => {
|
||||||
|
currentPageRef.current = currentPage;
|
||||||
|
}, [currentPage]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 监听存储变化,以便在多个入口(如 Popup 和 Options)之间同步路由和设置
|
* 监听存储变化,以便在多个入口(如 Popup 和 Options)之间同步路由和设置
|
||||||
*/
|
*/
|
||||||
@@ -217,7 +235,7 @@ export function RouterProvider({
|
|||||||
// 同步当前路由
|
// 同步当前路由
|
||||||
if (syncRoute && changes[syncKey as string]) {
|
if (syncRoute && changes[syncKey as string]) {
|
||||||
const newRoute = changes[syncKey as string].newValue as PageType;
|
const newRoute = changes[syncKey as string].newValue as PageType;
|
||||||
if (newRoute && newRoute !== currentPage && isValidPage(newRoute)) {
|
if (newRoute && newRoute !== currentPageRef.current && isValidPage(newRoute)) {
|
||||||
setCurrentPage(newRoute);
|
setCurrentPage(newRoute);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -239,7 +257,7 @@ export function RouterProvider({
|
|||||||
|
|
||||||
chrome.storage.onChanged.addListener(handleStorageChange);
|
chrome.storage.onChanged.addListener(handleStorageChange);
|
||||||
return () => chrome.storage.onChanged.removeListener(handleStorageChange);
|
return () => chrome.storage.onChanged.removeListener(handleStorageChange);
|
||||||
}, [syncRoute, currentPage, syncKey, visiblePagesKey, pageOrderKey]);
|
}, [syncRoute, syncKey, visiblePagesKey, pageOrderKey]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 跳转到指定页面
|
* 跳转到指定页面
|
||||||
@@ -248,20 +266,6 @@ export function RouterProvider({
|
|||||||
setCurrentPage(page);
|
setCurrentPage(page);
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* 仅在本地跳转,不触发自动同步(通常由 handleStorageChange 内部调用)
|
|
||||||
*/
|
|
||||||
const navigateLocal = (page: PageType) => {
|
|
||||||
setCurrentPage(page);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 手动同步导航状态到存储
|
|
||||||
*/
|
|
||||||
const syncNavigation = (page: PageType) => {
|
|
||||||
storageUtil.set(syncKey, page as StorageSchema[typeof syncKey]).catch(console.error);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 返回主仪表盘
|
* 返回主仪表盘
|
||||||
*/
|
*/
|
||||||
@@ -277,8 +281,6 @@ export function RouterProvider({
|
|||||||
pageOrder,
|
pageOrder,
|
||||||
isLoaded,
|
isLoaded,
|
||||||
navigateTo,
|
navigateTo,
|
||||||
navigateLocal,
|
|
||||||
syncNavigation,
|
|
||||||
goBack,
|
goBack,
|
||||||
setVisiblePages,
|
setVisiblePages,
|
||||||
setPageOrder,
|
setPageOrder,
|
||||||
|
|||||||
@@ -77,16 +77,23 @@ export function ThemeModeProvider({ children }: ThemeModeProviderProps) {
|
|||||||
|
|
||||||
// 异步校准:从 chrome.storage 读取持久化值
|
// 异步校准:从 chrome.storage 读取持久化值
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
storageUtil
|
storageUtil
|
||||||
.get(THEME_MODE_KEY, 'system')
|
.get(THEME_MODE_KEY, 'system')
|
||||||
.then((saved) => {
|
.then((saved) => {
|
||||||
|
if (cancelled) return;
|
||||||
if (isValidMode(saved)) {
|
if (isValidMode(saved)) {
|
||||||
setModeState(saved);
|
setModeState(saved);
|
||||||
updateResolved(saved);
|
updateResolved(saved);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch(console.error)
|
.catch(console.error)
|
||||||
.finally(() => setIsLoaded(true));
|
.finally(() => {
|
||||||
|
if (!cancelled) setIsLoaded(true);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
}, [updateResolved]);
|
}, [updateResolved]);
|
||||||
|
|
||||||
// 监听系统主题变化(仅在 system 模式下生效)
|
// 监听系统主题变化(仅在 system 模式下生效)
|
||||||
|
|||||||
@@ -235,4 +235,33 @@ describe('RouterProvider', () => {
|
|||||||
expect(visiblePages).toContain('base64Converter');
|
expect(visiblePages).toContain('base64Converter');
|
||||||
expect(pageOrder).toContain('base64Converter');
|
expect(pageOrder).toContain('base64Converter');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('组件卸载时不应设置 isLoaded 状态(竞态条件防护)', async () => {
|
||||||
|
let resolveStorage: (value: unknown) => void;
|
||||||
|
const storagePromise = new Promise((resolve) => {
|
||||||
|
resolveStorage = resolve;
|
||||||
|
});
|
||||||
|
|
||||||
|
(storageUtil.get as any).mockImplementation(() => storagePromise);
|
||||||
|
|
||||||
|
const { unmount } = render(
|
||||||
|
<RouterProvider>
|
||||||
|
<TestComponent />
|
||||||
|
</RouterProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
// 在存储读取完成前卸载组件
|
||||||
|
unmount();
|
||||||
|
|
||||||
|
// 现在让存储读取完成
|
||||||
|
resolveStorage!('dashboard');
|
||||||
|
|
||||||
|
// 等待一段时间确保如果 setState 被调用会触发警告
|
||||||
|
await act(async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||||
|
});
|
||||||
|
|
||||||
|
// 测试通过的标准:没有 React "Can't perform a React state update on an unmounted component" 警告
|
||||||
|
// 如果有竞态条件,这里会输出警告(React 18+ 中已移除该警告,但状态更新仍是无效操作)
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+1
-1
@@ -26,7 +26,7 @@
|
|||||||
"target": "ESNext",
|
"target": "ESNext",
|
||||||
|
|
||||||
"types": ["chrome", "webextension-polyfill", "@testing-library/jest-dom", "vitest/globals"],
|
"types": ["chrome", "webextension-polyfill", "@testing-library/jest-dom", "vitest/globals"],
|
||||||
"noImplicitAny": false
|
"noImplicitAny": true
|
||||||
},
|
},
|
||||||
// 确保包含你的源代码目录
|
// 确保包含你的源代码目录
|
||||||
"include": [
|
"include": [
|
||||||
|
|||||||
Vendored
+19
@@ -0,0 +1,19 @@
|
|||||||
|
declare module 'qrious' {
|
||||||
|
interface QRiousOptions {
|
||||||
|
value?: string;
|
||||||
|
size?: number;
|
||||||
|
level?: 'L' | 'M' | 'Q' | 'H';
|
||||||
|
foreground?: string;
|
||||||
|
background?: string;
|
||||||
|
padding?: number;
|
||||||
|
mime?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
class QRious {
|
||||||
|
constructor(options?: QRiousOptions);
|
||||||
|
toDataURL(mime?: string): string;
|
||||||
|
set(options: QRiousOptions): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export = QRious;
|
||||||
|
}
|
||||||
Vendored
+12
-5
@@ -23,6 +23,11 @@ export type JsonToolsPageMode = 'diff' | 'format' | 'yaml' | 'toml' | 'minify';
|
|||||||
*/
|
*/
|
||||||
export type Base64ConverterPageMode = 'text' | 'file' | 'image';
|
export type Base64ConverterPageMode = 'text' | 'file' | 'image';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base64 转换器中各子模式的编码/解码方向
|
||||||
|
*/
|
||||||
|
export type Base64ConvertDirection = 'encode' | 'decode';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Markdown 转 HTML 页面预览模式类型定义
|
* Markdown 转 HTML 页面预览模式类型定义
|
||||||
*/
|
*/
|
||||||
@@ -71,7 +76,7 @@ export interface FormMapEntry {
|
|||||||
* 定义了所有持久化在客户端的数据结构
|
* 定义了所有持久化在客户端的数据结构
|
||||||
*/
|
*/
|
||||||
export interface StorageSchema {
|
export interface StorageSchema {
|
||||||
/** 全局当前路由 */
|
/** RouterProvider 的默认路由键,仅当未显式传入 syncKey 时使用(popup/sidepanel/tab 入口已各自覆盖) */
|
||||||
'app/currentRoute': PageType;
|
'app/currentRoute': PageType;
|
||||||
/** Popup 窗口的当前路由 */
|
/** Popup 窗口的当前路由 */
|
||||||
'app/popupRoute': PageType;
|
'app/popupRoute': PageType;
|
||||||
@@ -79,9 +84,9 @@ export interface StorageSchema {
|
|||||||
'app/sidepanelRoute': PageType;
|
'app/sidepanelRoute': PageType;
|
||||||
/** 标签页的当前路由 */
|
/** 标签页的当前路由 */
|
||||||
'app/tabRoute': PageType;
|
'app/tabRoute': PageType;
|
||||||
/** 在菜单中可见的页面列表 (通用/旧版) */
|
/** RouterProvider 的默认可见页面列表键,仅当未显式传入 visiblePagesKey 时使用 */
|
||||||
'app/visiblePages': PageType[];
|
'app/visiblePages': PageType[];
|
||||||
/** 菜单页面的显示顺序 (通用/旧版) */
|
/** RouterProvider 的默认页面排序键,仅当未显式传入 pageOrderKey 时使用 */
|
||||||
'app/pageOrder': PageType[];
|
'app/pageOrder': PageType[];
|
||||||
/** Popup 窗口可见的页面列表 */
|
/** Popup 窗口可见的页面列表 */
|
||||||
'app/popupVisiblePages': PageType[];
|
'app/popupVisiblePages': PageType[];
|
||||||
@@ -95,8 +100,6 @@ export interface StorageSchema {
|
|||||||
'app/tabVisiblePages': PageType[];
|
'app/tabVisiblePages': PageType[];
|
||||||
/** 标签页页面的显示顺序 */
|
/** 标签页页面的显示顺序 */
|
||||||
'app/tabPageOrder': PageType[];
|
'app/tabPageOrder': PageType[];
|
||||||
/** 上一次访问的路由路径(备用) */
|
|
||||||
'app/lastRoute': string;
|
|
||||||
/** 应用主题配置 */
|
/** 应用主题配置 */
|
||||||
'app/theme': string;
|
'app/theme': string;
|
||||||
/** 主题模式偏好(light/dark/system) */
|
/** 主题模式偏好(light/dark/system) */
|
||||||
@@ -113,6 +116,10 @@ export interface StorageSchema {
|
|||||||
'jsonTools/pageMode': JsonToolsPageMode;
|
'jsonTools/pageMode': JsonToolsPageMode;
|
||||||
/** Base64 转换器页面当前子模式 */
|
/** Base64 转换器页面当前子模式 */
|
||||||
'base64Converter/pageMode': Base64ConverterPageMode;
|
'base64Converter/pageMode': Base64ConverterPageMode;
|
||||||
|
/** Base64 转换器「文件」子模式当前方向 */
|
||||||
|
'base64Converter/fileMode/direction': Base64ConvertDirection;
|
||||||
|
/** Base64 转换器「图像」子模式当前方向 */
|
||||||
|
'base64Converter/imageMode/direction': Base64ConvertDirection;
|
||||||
/** Markdown 转 HTML 页面当前预览模式 */
|
/** Markdown 转 HTML 页面当前预览模式 */
|
||||||
'markdownToHtml/previewMode': MarkdownToHtmlPreviewMode;
|
'markdownToHtml/previewMode': MarkdownToHtmlPreviewMode;
|
||||||
/** HTML 转 Markdown 页面当前预览模式 */
|
/** HTML 转 Markdown 页面当前预览模式 */
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ import {
|
|||||||
isSupportedImageExtension,
|
isSupportedImageExtension,
|
||||||
extractMimeTypeFromDataUri,
|
extractMimeTypeFromDataUri,
|
||||||
formatFileSize,
|
formatFileSize,
|
||||||
|
base64ToBytes,
|
||||||
|
sniffMimeFromBytes,
|
||||||
|
base64ToBlob,
|
||||||
MAX_FILE_SIZE,
|
MAX_FILE_SIZE,
|
||||||
} from '@/utils/base64Converter';
|
} from '@/utils/base64Converter';
|
||||||
|
|
||||||
@@ -67,6 +70,28 @@ describe('base64ToText', () => {
|
|||||||
const result = base64ToText(' SGVsbG8= ');
|
const result = base64ToText(' SGVsbG8= ');
|
||||||
expect(result).toBe('Hello');
|
expect(result).toBe('Hello');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('应该自动剥离 data:<mime>;base64, 前缀后再解码', () => {
|
||||||
|
// "hello" -> base64 "aGVsbG8="
|
||||||
|
const result = base64ToText('data:text/plain;base64,aGVsbG8=');
|
||||||
|
expect(result).toBe('hello');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该剥离带空白的 data URI 前缀', () => {
|
||||||
|
const result = base64ToText(' data:text/plain;base64,aGVsbG8= ');
|
||||||
|
expect(result).toBe('hello');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该对二进制(如 PNG)数据抛出更清晰的错误', () => {
|
||||||
|
// PNG 文件签名 89 50 4E 47 0D 0A 1A 0A 的 Base64 编码
|
||||||
|
const pngSignatureBase64 = 'iVBORw0KGgo=';
|
||||||
|
expect(() => base64ToText(pngSignatureBase64)).toThrow(/binary|二进制|image|图像/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该对带 data:image/png 前缀的 PNG 数据抛出二进制错误', () => {
|
||||||
|
const pngDataUri = 'data:image/png;base64,iVBORw0KGgo=';
|
||||||
|
expect(() => base64ToText(pngDataUri)).toThrow(/binary|二进制|image|图像/i);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('isValidBase64', () => {
|
describe('isValidBase64', () => {
|
||||||
@@ -167,3 +192,149 @@ describe('formatFileSize', () => {
|
|||||||
expect(formatFileSize(1073741824)).toBe('1.00 GB');
|
expect(formatFileSize(1073741824)).toBe('1.00 GB');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('base64ToBytes', () => {
|
||||||
|
it('应该解码标准 ASCII Base64 为字节序列', () => {
|
||||||
|
const bytes = base64ToBytes('aGVsbG8=');
|
||||||
|
expect(Array.from(bytes)).toEqual([0x68, 0x65, 0x6c, 0x6c, 0x6f]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该正确解码 PNG 文件签名', () => {
|
||||||
|
// PNG 签名:89 50 4E 47 0D 0A 1A 0A
|
||||||
|
const bytes = base64ToBytes('iVBORw0KGgo=');
|
||||||
|
expect(Array.from(bytes)).toEqual([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该返回空 Uint8Array 对于空字符串输入', () => {
|
||||||
|
const bytes = base64ToBytes('');
|
||||||
|
expect(bytes.length).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('sniffMimeFromBytes', () => {
|
||||||
|
it('应该识别 PNG', () => {
|
||||||
|
const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||||
|
expect(sniffMimeFromBytes(bytes)).toEqual({ mime: 'image/png', ext: '.png' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该识别 JPEG', () => {
|
||||||
|
const bytes = new Uint8Array([0xff, 0xd8, 0xff, 0xe0]);
|
||||||
|
expect(sniffMimeFromBytes(bytes)).toEqual({ mime: 'image/jpeg', ext: '.jpg' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该识别 GIF', () => {
|
||||||
|
const bytes = new Uint8Array([0x47, 0x49, 0x46, 0x38, 0x39, 0x61]);
|
||||||
|
expect(sniffMimeFromBytes(bytes)).toEqual({ mime: 'image/gif', ext: '.gif' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该识别 BMP', () => {
|
||||||
|
const bytes = new Uint8Array([0x42, 0x4d, 0x36, 0x00, 0x00, 0x00]);
|
||||||
|
expect(sniffMimeFromBytes(bytes)).toEqual({ mime: 'image/bmp', ext: '.bmp' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该识别 WebP(RIFF....WEBP 复合签名)', () => {
|
||||||
|
const bytes = new Uint8Array([
|
||||||
|
0x52,
|
||||||
|
0x49,
|
||||||
|
0x46,
|
||||||
|
0x46, // "RIFF"
|
||||||
|
0x24,
|
||||||
|
0x00,
|
||||||
|
0x00,
|
||||||
|
0x00, // 文件大小占位
|
||||||
|
0x57,
|
||||||
|
0x45,
|
||||||
|
0x42,
|
||||||
|
0x50, // "WEBP"
|
||||||
|
0x56,
|
||||||
|
0x50,
|
||||||
|
0x38,
|
||||||
|
0x20, // "VP8 " 子块
|
||||||
|
]);
|
||||||
|
expect(sniffMimeFromBytes(bytes)).toEqual({ mime: 'image/webp', ext: '.webp' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('不应将 WAV(RIFF 容器但非 WEBP)识别为 WebP', () => {
|
||||||
|
const bytes = new Uint8Array([
|
||||||
|
0x52,
|
||||||
|
0x49,
|
||||||
|
0x46,
|
||||||
|
0x46, // "RIFF"
|
||||||
|
0x24,
|
||||||
|
0x00,
|
||||||
|
0x00,
|
||||||
|
0x00,
|
||||||
|
0x57,
|
||||||
|
0x41,
|
||||||
|
0x56,
|
||||||
|
0x45, // "WAVE"
|
||||||
|
]);
|
||||||
|
expect(sniffMimeFromBytes(bytes)).toBeNull();
|
||||||
|
});
|
||||||
|
it('应该识别 PDF', () => {
|
||||||
|
const bytes = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x2d]);
|
||||||
|
expect(sniffMimeFromBytes(bytes)).toEqual({ mime: 'application/pdf', ext: '.pdf' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该识别 ZIP', () => {
|
||||||
|
const bytes = new Uint8Array([0x50, 0x4b, 0x03, 0x04]);
|
||||||
|
expect(sniffMimeFromBytes(bytes)).toEqual({ mime: 'application/zip', ext: '.zip' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该对未匹配的字节返回 null', () => {
|
||||||
|
const bytes = new Uint8Array([0x00, 0x01, 0x02, 0x03]);
|
||||||
|
expect(sniffMimeFromBytes(bytes)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该对过短的字节返回 null', () => {
|
||||||
|
const bytes = new Uint8Array([0x89]);
|
||||||
|
expect(sniffMimeFromBytes(bytes)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('base64ToBlob', () => {
|
||||||
|
it('应该优先使用 data URI 中的 MIME 类型', () => {
|
||||||
|
const result = base64ToBlob('data:application/json;base64,eyJhIjoxfQ==');
|
||||||
|
expect(result.mimeType).toBe('application/json');
|
||||||
|
expect(result.blob).toBeInstanceOf(Blob);
|
||||||
|
expect(result.blob.size).toBe(7);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该通过魔数识别 PNG', () => {
|
||||||
|
const result = base64ToBlob('iVBORw0KGgo=');
|
||||||
|
expect(result.mimeType).toBe('image/png');
|
||||||
|
expect(result.suggestedExtension).toBe('.png');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该通过魔数识别 PDF', () => {
|
||||||
|
// "%PDF-" + 一些字节
|
||||||
|
const result = base64ToBlob('JVBERi0K');
|
||||||
|
expect(result.mimeType).toBe('application/pdf');
|
||||||
|
expect(result.suggestedExtension).toBe('.pdf');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该对未匹配的纯 Base64 回退为 application/octet-stream + .bin', () => {
|
||||||
|
const result = base64ToBlob('AAECAwQF');
|
||||||
|
expect(result.mimeType).toBe('application/octet-stream');
|
||||||
|
expect(result.suggestedExtension).toBe('.bin');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该 trim 前后空白', () => {
|
||||||
|
const result = base64ToBlob(' iVBORw0KGgo= ');
|
||||||
|
expect(result.mimeType).toBe('image/png');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该对非法 Base64 抛出 Invalid Base64 string', () => {
|
||||||
|
expect(() => base64ToBlob('这不是 base64!')).toThrow('Invalid Base64 string');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该返回原始 Base64(已去除 data URI 前缀)', () => {
|
||||||
|
const result = base64ToBlob('data:image/png;base64,iVBORw0KGgo=');
|
||||||
|
expect(result.rawBase64).toBe('iVBORw0KGgo=');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('blob 大小应该等于解码后的字节数', () => {
|
||||||
|
const result = base64ToBlob('aGVsbG8=');
|
||||||
|
expect(result.blob.size).toBe(5);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { storageUtil } from '@/utils/chromeStorage';
|
||||||
|
|
||||||
|
describe('chromeStorage', () => {
|
||||||
|
describe('get', () => {
|
||||||
|
it('应该返回存储的值', async () => {
|
||||||
|
(chrome.storage.local.get as any).mockResolvedValue({ 'app/theme': 'dark' });
|
||||||
|
|
||||||
|
const result = await storageUtil.get('app/theme');
|
||||||
|
|
||||||
|
expect(result).toBe('dark');
|
||||||
|
expect(chrome.storage.local.get).toHaveBeenCalledWith(['app/theme']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当键不存在时应返回默认值', async () => {
|
||||||
|
(chrome.storage.local.get as any).mockResolvedValue({});
|
||||||
|
|
||||||
|
const result = await storageUtil.get('app/theme', 'light');
|
||||||
|
|
||||||
|
expect(result).toBe('light');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当键不存在且未提供默认值时应返回 undefined', async () => {
|
||||||
|
(chrome.storage.local.get as any).mockResolvedValue({});
|
||||||
|
|
||||||
|
const result = await storageUtil.get('app/theme');
|
||||||
|
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该支持布尔类型值', async () => {
|
||||||
|
(chrome.storage.local.get as any).mockResolvedValue({ 'qrCode/qrExpanded': true });
|
||||||
|
|
||||||
|
const result = await storageUtil.get('qrCode/qrExpanded');
|
||||||
|
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该支持数组类型值', async () => {
|
||||||
|
const pages = ['dashboard', 'timestamp'] as const;
|
||||||
|
(chrome.storage.local.get as any).mockResolvedValue({ 'app/visiblePages': pages });
|
||||||
|
|
||||||
|
const result = await storageUtil.get('app/visiblePages');
|
||||||
|
|
||||||
|
expect(result).toEqual(pages);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该支持复杂对象类型值', async () => {
|
||||||
|
const preferences = {
|
||||||
|
autoRefresh: true,
|
||||||
|
selectedTypes: {
|
||||||
|
localStorage: true,
|
||||||
|
sessionStorage: false,
|
||||||
|
indexedDB: true,
|
||||||
|
cookies: false,
|
||||||
|
cacheStorage: false,
|
||||||
|
serviceWorkers: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
(chrome.storage.local.get as any).mockResolvedValue({
|
||||||
|
'storageCleaner/preferences': preferences,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await storageUtil.get('storageCleaner/preferences');
|
||||||
|
|
||||||
|
expect(result).toEqual(preferences);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当存储值为 null 时应返回默认值', async () => {
|
||||||
|
(chrome.storage.local.get as any).mockResolvedValue({ 'app/theme': null });
|
||||||
|
|
||||||
|
const result = await storageUtil.get('app/theme', 'light');
|
||||||
|
|
||||||
|
expect(result).toBe('light');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('set', () => {
|
||||||
|
it('应该成功设置字符串值', async () => {
|
||||||
|
(chrome.storage.local.set as any).mockResolvedValue(undefined);
|
||||||
|
|
||||||
|
await storageUtil.set('app/theme', 'dark');
|
||||||
|
|
||||||
|
expect(chrome.storage.local.set).toHaveBeenCalledWith({ 'app/theme': 'dark' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该成功设置布尔值', async () => {
|
||||||
|
await storageUtil.set('qrCode/qrExpanded', true);
|
||||||
|
|
||||||
|
expect(chrome.storage.local.set).toHaveBeenCalledWith({ 'qrCode/qrExpanded': true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该成功设置数组值', async () => {
|
||||||
|
const pages: Array<'dashboard' | 'timestamp'> = ['dashboard', 'timestamp'];
|
||||||
|
await storageUtil.set('app/visiblePages', pages);
|
||||||
|
|
||||||
|
expect(chrome.storage.local.set).toHaveBeenCalledWith({ 'app/visiblePages': pages });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该成功设置复杂对象值', async () => {
|
||||||
|
const preferences = {
|
||||||
|
autoRefresh: false,
|
||||||
|
selectedTypes: {
|
||||||
|
localStorage: true,
|
||||||
|
sessionStorage: true,
|
||||||
|
indexedDB: false,
|
||||||
|
cookies: false,
|
||||||
|
cacheStorage: false,
|
||||||
|
serviceWorkers: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
await storageUtil.set('storageCleaner/preferences', preferences);
|
||||||
|
|
||||||
|
expect(chrome.storage.local.set).toHaveBeenCalledWith({
|
||||||
|
'storageCleaner/preferences': preferences,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该成功设置枚举类型值', async () => {
|
||||||
|
await storageUtil.set('jsonTools/pageMode', 'yaml');
|
||||||
|
|
||||||
|
expect(chrome.storage.local.set).toHaveBeenCalledWith({ 'jsonTools/pageMode': 'yaml' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('remove', () => {
|
||||||
|
it('应该成功删除指定键', async () => {
|
||||||
|
await storageUtil.remove('app/theme');
|
||||||
|
|
||||||
|
expect(chrome.storage.local.remove).toHaveBeenCalledWith(['app/theme']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该成功删除不同键', async () => {
|
||||||
|
await storageUtil.remove('qrCode/qrExpanded');
|
||||||
|
|
||||||
|
expect(chrome.storage.local.remove).toHaveBeenCalledWith(['qrCode/qrExpanded']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import {
|
||||||
|
getActiveTab,
|
||||||
|
getActiveTabDomain,
|
||||||
|
openExtensionPage,
|
||||||
|
ensureContentScriptInjected,
|
||||||
|
} from '@/utils/chromeTabs';
|
||||||
|
|
||||||
|
describe('chromeTabs', () => {
|
||||||
|
describe('getActiveTab', () => {
|
||||||
|
it('应该返回当前活动标签页', async () => {
|
||||||
|
const mockTab = { id: 1, url: 'https://example.com', title: 'Example' } as chrome.tabs.Tab;
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await getActiveTab();
|
||||||
|
|
||||||
|
expect(result).toEqual(mockTab);
|
||||||
|
expect(chrome.tabs.query).toHaveBeenCalledWith({ active: true, currentWindow: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当没有活动标签页时应返回 null', async () => {
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([]);
|
||||||
|
|
||||||
|
const result = await getActiveTab();
|
||||||
|
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当查询失败时应返回 null 并记录错误', async () => {
|
||||||
|
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||||
|
(chrome.tabs.query as any).mockRejectedValue(new Error('Permission denied'));
|
||||||
|
|
||||||
|
const result = await getActiveTab();
|
||||||
|
|
||||||
|
expect(result).toBeNull();
|
||||||
|
expect(consoleSpy).toHaveBeenCalledWith('获取活动标签页失败:', expect.any(Error));
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getActiveTabDomain', () => {
|
||||||
|
it('应该返回当前活动标签页的域名', async () => {
|
||||||
|
const mockTab = { id: 1, url: 'https://example.com/path?query=1' } as chrome.tabs.Tab;
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await getActiveTabDomain();
|
||||||
|
|
||||||
|
expect(result).toBe('example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该处理带有端口的 URL', async () => {
|
||||||
|
const mockTab = { id: 1, url: 'https://example.com:8080/path' } as chrome.tabs.Tab;
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await getActiveTabDomain();
|
||||||
|
|
||||||
|
expect(result).toBe('example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当标签页没有 URL 时应返回空字符串', async () => {
|
||||||
|
const mockTab = { id: 1 } as chrome.tabs.Tab;
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await getActiveTabDomain();
|
||||||
|
|
||||||
|
expect(result).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当没有活动标签页时应返回空字符串', async () => {
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([]);
|
||||||
|
|
||||||
|
const result = await getActiveTabDomain();
|
||||||
|
|
||||||
|
expect(result).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当 URL 解析失败时应返回空字符串并记录错误', async () => {
|
||||||
|
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||||
|
const mockTab = { id: 1, url: 'not-a-valid-url' } as chrome.tabs.Tab;
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await getActiveTabDomain();
|
||||||
|
|
||||||
|
expect(result).toBe('');
|
||||||
|
expect(consoleSpy).toHaveBeenCalledWith('解析域名失败:', expect.any(Error));
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该处理 chrome-extension URL', async () => {
|
||||||
|
const mockTab = { id: 1, url: 'chrome-extension://abc123/popup.html' } as chrome.tabs.Tab;
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await getActiveTabDomain();
|
||||||
|
|
||||||
|
expect(result).toBe('abc123');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('openExtensionPage', () => {
|
||||||
|
it('应该在新标签页中打开扩展页面', async () => {
|
||||||
|
await openExtensionPage('popup.html');
|
||||||
|
|
||||||
|
expect(chrome.runtime.getURL).toHaveBeenCalledWith('popup.html');
|
||||||
|
expect(chrome.tabs.create).toHaveBeenCalledWith({
|
||||||
|
url: 'chrome-extension://test-extension-id/popup.html',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该支持带查询参数的扩展页面', async () => {
|
||||||
|
await openExtensionPage('options.html', { tab: 'settings', id: '123' });
|
||||||
|
|
||||||
|
expect(chrome.tabs.create).toHaveBeenCalledWith({
|
||||||
|
url: 'chrome-extension://test-extension-id/options.html?tab=settings&id=123',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当创建标签页失败时应记录错误', async () => {
|
||||||
|
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||||
|
(chrome.tabs.create as any).mockRejectedValue(new Error('Tab creation failed'));
|
||||||
|
|
||||||
|
await openExtensionPage('popup.html');
|
||||||
|
|
||||||
|
expect(consoleSpy).toHaveBeenCalledWith('打开扩展页面失败:', expect.any(Error));
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ensureContentScriptInjected', () => {
|
||||||
|
it('当存在活动标签页时应返回 true', async () => {
|
||||||
|
const mockTab = { id: 123, url: 'https://example.com' } as chrome.tabs.Tab;
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await ensureContentScriptInjected();
|
||||||
|
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当没有活动标签页时应返回 false', async () => {
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([]);
|
||||||
|
|
||||||
|
const result = await ensureContentScriptInjected();
|
||||||
|
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当标签页没有 id 时应返回 false', async () => {
|
||||||
|
const mockTab = { url: 'https://example.com' } as chrome.tabs.Tab;
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await ensureContentScriptInjected();
|
||||||
|
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当整体操作失败时应返回 false 并记录错误', async () => {
|
||||||
|
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||||
|
(chrome.tabs.query as any).mockRejectedValue(new Error('Query failed'));
|
||||||
|
|
||||||
|
const result = await ensureContentScriptInjected();
|
||||||
|
|
||||||
|
expect(result).toBe(false);
|
||||||
|
// getActiveTab catches the error and logs "获取活动标签页失败"
|
||||||
|
expect(consoleSpy).toHaveBeenCalledWith('获取活动标签页失败:', expect.any(Error));
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { describe, expect, it, vi, beforeAll } from 'vitest';
|
||||||
|
import { copyTextToClipboard, copyImageToClipboard } from '@/utils/clipboard';
|
||||||
|
|
||||||
|
// Mock ClipboardItem for test environment
|
||||||
|
class MockClipboardItem {
|
||||||
|
constructor(public items: Record<string, Blob>) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
(globalThis as any).ClipboardItem = MockClipboardItem;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('clipboard', () => {
|
||||||
|
describe('copyTextToClipboard', () => {
|
||||||
|
it('复制成功时应返回 true', async () => {
|
||||||
|
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||||
|
Object.assign(navigator, { clipboard: { writeText } });
|
||||||
|
|
||||||
|
const result = await copyTextToClipboard('test text');
|
||||||
|
|
||||||
|
expect(result).toBe(true);
|
||||||
|
expect(writeText).toHaveBeenCalledWith('test text');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('复制失败时应返回 false', async () => {
|
||||||
|
const writeText = vi.fn().mockRejectedValue(new Error('Permission denied'));
|
||||||
|
Object.assign(navigator, { clipboard: { writeText } });
|
||||||
|
|
||||||
|
const result = await copyTextToClipboard('test text');
|
||||||
|
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('copyImageToClipboard', () => {
|
||||||
|
it('复制成功时应返回 true', async () => {
|
||||||
|
const write = vi.fn().mockResolvedValue(undefined);
|
||||||
|
Object.assign(navigator, { clipboard: { write } });
|
||||||
|
|
||||||
|
const blob = new Blob(['png data'], { type: 'image/png' });
|
||||||
|
const result = await copyImageToClipboard(blob);
|
||||||
|
|
||||||
|
expect(result).toBe(true);
|
||||||
|
expect(write).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('复制失败时应返回 false', async () => {
|
||||||
|
const write = vi.fn().mockRejectedValue(new Error('Permission denied'));
|
||||||
|
Object.assign(navigator, { clipboard: { write } });
|
||||||
|
|
||||||
|
const blob = new Blob(['png data'], { type: 'image/png' });
|
||||||
|
const result = await copyImageToClipboard(blob);
|
||||||
|
|
||||||
|
expect(result).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import dayjs from '@/utils/dayjs';
|
||||||
|
|
||||||
|
describe('dayjs', () => {
|
||||||
|
it('应该正确导出 dayjs 实例', () => {
|
||||||
|
expect(dayjs).toBeDefined();
|
||||||
|
expect(typeof dayjs).toBe('function');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该支持基本日期解析', () => {
|
||||||
|
const date = dayjs('2024-01-15');
|
||||||
|
expect(date.isValid()).toBe(true);
|
||||||
|
expect(date.year()).toBe(2024);
|
||||||
|
expect(date.month()).toBe(0);
|
||||||
|
expect(date.date()).toBe(15);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该支持 UTC 插件', () => {
|
||||||
|
const utcDate = dayjs.utc('2024-01-15T12:00:00Z');
|
||||||
|
expect(utcDate.isValid()).toBe(true);
|
||||||
|
expect(utcDate.format()).toContain('2024-01-15');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该支持时区插件', () => {
|
||||||
|
const date = dayjs('2024-01-15T12:00:00');
|
||||||
|
expect(date.tz).toBeDefined();
|
||||||
|
expect(typeof date.tz).toBe('function');
|
||||||
|
|
||||||
|
const shanghaiDate = date.tz('Asia/Shanghai');
|
||||||
|
expect(shanghaiDate.isValid()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该支持相对时间插件', () => {
|
||||||
|
const now = dayjs();
|
||||||
|
expect(now.fromNow).toBeDefined();
|
||||||
|
expect(typeof now.fromNow).toBe('function');
|
||||||
|
|
||||||
|
const yesterday = dayjs().subtract(1, 'day');
|
||||||
|
const fromNow = yesterday.fromNow();
|
||||||
|
expect(typeof fromNow).toBe('string');
|
||||||
|
expect(fromNow.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该使用中文 locale', () => {
|
||||||
|
// 显式设置中文 locale
|
||||||
|
dayjs.locale('zh-cn');
|
||||||
|
const yesterday = dayjs().subtract(1, 'day');
|
||||||
|
const fromNow = yesterday.fromNow();
|
||||||
|
|
||||||
|
// 中文相对时间应包含 "天前"
|
||||||
|
expect(fromNow).toContain('天前');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该支持日期格式化', () => {
|
||||||
|
const date = dayjs('2024-01-15T10:30:00');
|
||||||
|
expect(date.format('YYYY-MM-DD')).toBe('2024-01-15');
|
||||||
|
expect(date.format('YYYY年MM月DD日')).toBe('2024年01月15日');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该支持日期计算', () => {
|
||||||
|
const date = dayjs('2024-01-15');
|
||||||
|
const nextDay = date.add(1, 'day');
|
||||||
|
expect(nextDay.date()).toBe(16);
|
||||||
|
|
||||||
|
const prevMonth = date.subtract(1, 'month');
|
||||||
|
expect(prevMonth.month()).toBe(11);
|
||||||
|
expect(prevMonth.year()).toBe(2023);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该支持日期比较', () => {
|
||||||
|
const date1 = dayjs('2024-01-15');
|
||||||
|
const date2 = dayjs('2024-01-20');
|
||||||
|
|
||||||
|
expect(date1.isBefore(date2)).toBe(true);
|
||||||
|
expect(date2.isAfter(date1)).toBe(true);
|
||||||
|
expect(date1.isSame(date2)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该支持 Unix 时间戳转换', () => {
|
||||||
|
const timestamp = 1705315200; // 2024-01-15 12:00:00 UTC
|
||||||
|
const date = dayjs.unix(timestamp);
|
||||||
|
|
||||||
|
expect(date.isValid()).toBe(true);
|
||||||
|
expect(date.year()).toBe(2024);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该支持毫秒时间戳', () => {
|
||||||
|
const timestamp = 1705315200000;
|
||||||
|
const date = dayjs(timestamp);
|
||||||
|
|
||||||
|
expect(date.isValid()).toBe(true);
|
||||||
|
expect(date.year()).toBe(2024);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { formatBytes } from '@/utils/format';
|
||||||
|
|
||||||
|
describe('formatBytes', () => {
|
||||||
|
it('should format 0 bytes', () => {
|
||||||
|
expect(formatBytes(0)).toBe('0 B');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should format bytes less than 1024', () => {
|
||||||
|
expect(formatBytes(1)).toBe('1 B');
|
||||||
|
expect(formatBytes(100)).toBe('100 B');
|
||||||
|
expect(formatBytes(500)).toBe('500 B');
|
||||||
|
expect(formatBytes(512)).toBe('512 B');
|
||||||
|
expect(formatBytes(1023)).toBe('1023 B');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should format kilobytes', () => {
|
||||||
|
expect(formatBytes(1024)).toBe('1.0 KB');
|
||||||
|
expect(formatBytes(1025)).toBe('1.0 KB');
|
||||||
|
expect(formatBytes(1536)).toBe('1.5 KB');
|
||||||
|
expect(formatBytes(2048)).toBe('2.0 KB');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should format megabytes', () => {
|
||||||
|
expect(formatBytes(1048576)).toBe('1.00 MB');
|
||||||
|
expect(formatBytes(1572864)).toBe('1.50 MB');
|
||||||
|
expect(formatBytes(5242880)).toBe('5.00 MB');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should format gigabytes', () => {
|
||||||
|
expect(formatBytes(1073741824)).toBe('1.00 GB');
|
||||||
|
expect(formatBytes(2147483648)).toBe('2.00 GB');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should format terabytes', () => {
|
||||||
|
expect(formatBytes(1099511627776)).toBe('1.00 TB');
|
||||||
|
expect(formatBytes(2199023255552)).toBe('2.00 TB');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle large values beyond TB', () => {
|
||||||
|
// Should cap at TB
|
||||||
|
expect(formatBytes(1125899906842624)).toBe('1024.00 TB');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -37,7 +37,8 @@ describe('jwt utils', () => {
|
|||||||
describe('parseJwt', () => {
|
describe('parseJwt', () => {
|
||||||
it('should return error for invalid format', () => {
|
it('should return error for invalid format', () => {
|
||||||
const result = parseJwt('invalid-token');
|
const result = parseJwt('invalid-token');
|
||||||
expect(result.error).toContain('格式错误');
|
expect(result.error).toBeDefined();
|
||||||
|
expect(result.error?.length).toBeGreaterThan(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should parse a valid JWT structure', () => {
|
it('should parse a valid JWT structure', () => {
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||||
|
import { sendMessageToContent, MessageAction } from '@/utils/messages';
|
||||||
|
|
||||||
|
// Mock @webext-core/messaging - vi.mock is hoisted, so we define mock inside factory
|
||||||
|
vi.mock('@webext-core/messaging', () => {
|
||||||
|
const mockSendMessage = vi.fn();
|
||||||
|
return {
|
||||||
|
defineExtensionMessaging: () => ({
|
||||||
|
sendMessage: mockSendMessage,
|
||||||
|
onMessage: vi.fn(),
|
||||||
|
}),
|
||||||
|
// Export the mock so we can access it in tests
|
||||||
|
__mockSendMessage: mockSendMessage,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Helper to get the mock function from the mocked module
|
||||||
|
async function getMockSendMessage() {
|
||||||
|
const mod = await import('@webext-core/messaging');
|
||||||
|
return (mod as any).__mockSendMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('messages', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('sendMessageToContent', () => {
|
||||||
|
it('应该成功发送消息到内容脚本并返回响应', async () => {
|
||||||
|
const mockSendMessage = await getMockSendMessage();
|
||||||
|
const mockResponse = { success: true };
|
||||||
|
mockSendMessage.mockResolvedValue(mockResponse);
|
||||||
|
|
||||||
|
const mockTab = { id: 123, url: 'https://example.com' };
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await sendMessageToContent(MessageAction.RELOAD_TAB, { tabId: 123 });
|
||||||
|
|
||||||
|
expect(result).toEqual(mockResponse);
|
||||||
|
expect(mockSendMessage).toHaveBeenCalledWith(MessageAction.RELOAD_TAB, { tabId: 123 }, 123);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该支持不带数据的消息发送', async () => {
|
||||||
|
const mockSendMessage = await getMockSendMessage();
|
||||||
|
mockSendMessage.mockResolvedValue(undefined);
|
||||||
|
|
||||||
|
const mockTab = { id: 456, url: 'https://example.com' };
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
await sendMessageToContent(MessageAction.SIDE_PANEL_STATE_CHANGED, { isOpen: true });
|
||||||
|
|
||||||
|
expect(mockSendMessage).toHaveBeenCalledWith(
|
||||||
|
MessageAction.SIDE_PANEL_STATE_CHANGED,
|
||||||
|
{ isOpen: true },
|
||||||
|
456,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当无法获取当前标签页时应返回错误', async () => {
|
||||||
|
const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([]);
|
||||||
|
|
||||||
|
const result = await sendMessageToContent(MessageAction.RELOAD_TAB, { tabId: 123 });
|
||||||
|
|
||||||
|
expect(result).toEqual({ success: false, message: '无法获取当前标签页' });
|
||||||
|
expect(consoleSpy).toHaveBeenCalledWith(
|
||||||
|
'[Messaging] 无法获取当前标签页,无法发送动作: reloadTab',
|
||||||
|
);
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当标签页没有 id 时应返回错误', async () => {
|
||||||
|
const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([{ url: 'https://example.com' }]);
|
||||||
|
|
||||||
|
const result = await sendMessageToContent(MessageAction.RELOAD_TAB, { tabId: 123 });
|
||||||
|
|
||||||
|
expect(result).toEqual({ success: false, message: '无法获取当前标签页' });
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当连接无法建立时应返回特定错误消息', async () => {
|
||||||
|
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||||
|
const mockSendMessage = await getMockSendMessage();
|
||||||
|
mockSendMessage.mockRejectedValue(new Error('Could not establish connection'));
|
||||||
|
|
||||||
|
const mockTab = { id: 123, url: 'https://example.com' };
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await sendMessageToContent(MessageAction.RELOAD_TAB, { tabId: 123 });
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
success: false,
|
||||||
|
message: '无法连接到网页,请刷新页面后再试',
|
||||||
|
});
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当响应超时时应返回特定错误消息', async () => {
|
||||||
|
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||||
|
const mockSendMessage = await getMockSendMessage();
|
||||||
|
mockSendMessage.mockRejectedValue(new Error('No response received'));
|
||||||
|
|
||||||
|
const mockTab = { id: 123, url: 'https://example.com' };
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await sendMessageToContent(MessageAction.RELOAD_TAB, { tabId: 123 });
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
success: false,
|
||||||
|
message: '网页响应超时,请重试',
|
||||||
|
});
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当发生其他错误时应返回通用错误消息', async () => {
|
||||||
|
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||||
|
const mockSendMessage = await getMockSendMessage();
|
||||||
|
mockSendMessage.mockRejectedValue(new Error('Unknown error'));
|
||||||
|
|
||||||
|
const mockTab = { id: 123, url: 'https://example.com' };
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await sendMessageToContent(MessageAction.RELOAD_TAB, { tabId: 123 });
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
success: false,
|
||||||
|
message: '通信失败: Unknown error',
|
||||||
|
});
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当错误不是 Error 实例时应正确处理字符串错误', async () => {
|
||||||
|
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||||
|
const mockSendMessage = await getMockSendMessage();
|
||||||
|
mockSendMessage.mockRejectedValue('string error');
|
||||||
|
|
||||||
|
const mockTab = { id: 123, url: 'https://example.com' };
|
||||||
|
(chrome.tabs.query as any).mockResolvedValue([mockTab]);
|
||||||
|
|
||||||
|
const result = await sendMessageToContent(MessageAction.RELOAD_TAB, { tabId: 123 });
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
success: false,
|
||||||
|
message: '通信失败: string error',
|
||||||
|
});
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当 tabs.query 失败时应返回错误', async () => {
|
||||||
|
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||||
|
(chrome.tabs.query as any).mockRejectedValue(new Error('Query failed'));
|
||||||
|
|
||||||
|
const result = await sendMessageToContent(MessageAction.RELOAD_TAB, { tabId: 123 });
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
success: false,
|
||||||
|
message: '通信失败: Query failed',
|
||||||
|
});
|
||||||
|
consoleSpy.mockRestore();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import { parseQrCodeFromFile } from '@/utils/qrCodeParser';
|
||||||
|
import QrScanner from 'qr-scanner';
|
||||||
|
|
||||||
|
// Mock qr-scanner
|
||||||
|
vi.mock('qr-scanner', () => ({
|
||||||
|
default: {
|
||||||
|
scanImage: vi.fn(),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('qrCodeParser', () => {
|
||||||
|
describe('parseQrCodeFromFile', () => {
|
||||||
|
it('应该成功解析二维码并返回数据', async () => {
|
||||||
|
const mockResult = { data: 'https://example.com', cornerPoints: [] };
|
||||||
|
(QrScanner.scanImage as any).mockResolvedValue(mockResult);
|
||||||
|
|
||||||
|
const mockFile = new File(['mock-image-data'], 'qrcode.png', { type: 'image/png' });
|
||||||
|
const result = await parseQrCodeFromFile(mockFile);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.data).toBe('https://example.com');
|
||||||
|
expect(QrScanner.scanImage).toHaveBeenCalledWith(mockFile, {
|
||||||
|
returnDetailedScanResult: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当未检测到二维码时应返回错误', async () => {
|
||||||
|
const mockResult = { data: '', cornerPoints: [] };
|
||||||
|
(QrScanner.scanImage as any).mockResolvedValue(mockResult);
|
||||||
|
|
||||||
|
const mockFile = new File(['mock-image-data'], 'no-qr.png', { type: 'image/png' });
|
||||||
|
const result = await parseQrCodeFromFile(mockFile);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toBe('未检测到二维码');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当 scanImage 返回 null 时应返回错误', async () => {
|
||||||
|
(QrScanner.scanImage as any).mockResolvedValue(null);
|
||||||
|
|
||||||
|
const mockFile = new File(['mock-image-data'], 'empty.png', { type: 'image/png' });
|
||||||
|
const result = await parseQrCodeFromFile(mockFile);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toBe('未检测到二维码');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当抛出 "No QR code found" 时应返回中文错误', async () => {
|
||||||
|
(QrScanner.scanImage as any).mockRejectedValue('No QR code found');
|
||||||
|
|
||||||
|
const mockFile = new File(['mock-image-data'], 'no-qr.png', { type: 'image/png' });
|
||||||
|
const result = await parseQrCodeFromFile(mockFile);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toBe('未检测到二维码');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当抛出 Error 实例时应返回错误消息', async () => {
|
||||||
|
(QrScanner.scanImage as any).mockRejectedValue(new Error('Image format not supported'));
|
||||||
|
|
||||||
|
const mockFile = new File(['mock-image-data'], 'bad.png', { type: 'image/png' });
|
||||||
|
const result = await parseQrCodeFromFile(mockFile);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toBe('Image format not supported');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当抛出非 Error 非字符串值时应正确转换', async () => {
|
||||||
|
(QrScanner.scanImage as any).mockRejectedValue(12345);
|
||||||
|
|
||||||
|
const mockFile = new File(['mock-image-data'], 'error.png', { type: 'image/png' });
|
||||||
|
const result = await parseQrCodeFromFile(mockFile);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toBe('12345');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('当抛出对象时应正确转换为字符串', async () => {
|
||||||
|
(QrScanner.scanImage as any).mockRejectedValue({ message: 'custom error' });
|
||||||
|
|
||||||
|
const mockFile = new File(['mock-image-data'], 'error.png', { type: 'image/png' });
|
||||||
|
const result = await parseQrCodeFromFile(mockFile);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toBe('[object Object]');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该处理包含中文内容的二维码', async () => {
|
||||||
|
const mockResult = { data: 'https://example.com/中文路径', cornerPoints: [] };
|
||||||
|
(QrScanner.scanImage as any).mockResolvedValue(mockResult);
|
||||||
|
|
||||||
|
const mockFile = new File(['mock-image-data'], 'chinese.png', { type: 'image/png' });
|
||||||
|
const result = await parseQrCodeFromFile(mockFile);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.data).toBe('https://example.com/中文路径');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应该处理纯文本二维码', async () => {
|
||||||
|
const mockResult = { data: 'WIFI:T:WPA;S:MyNetwork;P:password;;', cornerPoints: [] };
|
||||||
|
(QrScanner.scanImage as any).mockResolvedValue(mockResult);
|
||||||
|
|
||||||
|
const mockFile = new File(['mock-image-data'], 'wifi.png', { type: 'image/png' });
|
||||||
|
const result = await parseQrCodeFromFile(mockFile);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.data).toBe('WIFI:T:WPA;S:MyNetwork;P:password;;');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -58,26 +58,26 @@ describe('storageCleaner utils', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should format kilobytes correctly', () => {
|
it('should format kilobytes correctly', () => {
|
||||||
expect(formatSize(1024)).toBe('1 KB');
|
expect(formatSize(1024)).toBe('1.0 KB');
|
||||||
expect(formatSize(1536)).toBe('1.5 KB');
|
expect(formatSize(1536)).toBe('1.5 KB');
|
||||||
expect(formatSize(2048)).toBe('2 KB');
|
expect(formatSize(2048)).toBe('2.0 KB');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should format megabytes correctly', () => {
|
it('should format megabytes correctly', () => {
|
||||||
expect(formatSize(1048576)).toBe('1 MB');
|
expect(formatSize(1048576)).toBe('1.00 MB');
|
||||||
expect(formatSize(1572864)).toBe('1.5 MB');
|
expect(formatSize(1572864)).toBe('1.50 MB');
|
||||||
expect(formatSize(5242880)).toBe('5 MB');
|
expect(formatSize(5242880)).toBe('5.00 MB');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should format gigabytes correctly', () => {
|
it('should format gigabytes correctly', () => {
|
||||||
expect(formatSize(1073741824)).toBe('1 GB');
|
expect(formatSize(1073741824)).toBe('1.00 GB');
|
||||||
expect(formatSize(2147483648)).toBe('2 GB');
|
expect(formatSize(2147483648)).toBe('2.00 GB');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle edge cases', () => {
|
it('should handle edge cases', () => {
|
||||||
expect(formatSize(1)).toBe('1 B');
|
expect(formatSize(1)).toBe('1 B');
|
||||||
expect(formatSize(1023)).toBe('1023 B');
|
expect(formatSize(1023)).toBe('1023 B');
|
||||||
expect(formatSize(1025)).toBe('1 KB');
|
expect(formatSize(1025)).toBe('1.0 KB');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+175
-11
@@ -2,6 +2,8 @@
|
|||||||
* Base64 转换器工具函数
|
* Base64 转换器工具函数
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { formatBytes } from './format';
|
||||||
|
|
||||||
/** 最大文件大小限制(10 MB) */
|
/** 最大文件大小限制(10 MB) */
|
||||||
export const MAX_FILE_SIZE = 10 * 1024 * 1024;
|
export const MAX_FILE_SIZE = 10 * 1024 * 1024;
|
||||||
|
|
||||||
@@ -76,19 +78,33 @@ export function textToBase64(text: string): TextToBase64Result {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 匹配 data URI 的 base64 前缀,如 "data:image/png;base64," */
|
||||||
|
const DATA_URI_BASE64_PREFIX = /^data:[^;,]+;base64,/i;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 将 Base64 字符串解码为文本
|
* 将 Base64 字符串解码为文本
|
||||||
*
|
*
|
||||||
|
* 支持 data:<mime>;base64,<payload> 形式:会自动剥离前缀后再解码。
|
||||||
|
* 若解码出的字节不是合法 UTF-8(典型如图片等二进制数据),抛出更易懂的错误。
|
||||||
|
*
|
||||||
* @param base64 Base64 编码字符串
|
* @param base64 Base64 编码字符串
|
||||||
* @returns 解码后的文本
|
* @returns 解码后的文本
|
||||||
* @throws {Error} 如果输入不是有效的 Base64 字符串
|
* @throws {Error} 输入不是合法的 Base64 字符串
|
||||||
|
* @throws {Error} 输入解码后是二进制数据,无法作为文本展示
|
||||||
*/
|
*/
|
||||||
export function base64ToText(base64: string): string {
|
export function base64ToText(base64: string): string {
|
||||||
const cleaned = base64.trim();
|
const trimmed = base64.trim();
|
||||||
|
const cleaned = trimmed.replace(DATA_URI_BASE64_PREFIX, '');
|
||||||
if (!isValidBase64(cleaned)) {
|
if (!isValidBase64(cleaned)) {
|
||||||
throw new Error('Invalid Base64 string');
|
throw new Error('Invalid Base64 string');
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
return decodeURIComponent(escape(atob(cleaned)));
|
return decodeURIComponent(escape(atob(cleaned)));
|
||||||
|
} catch {
|
||||||
|
throw new Error(
|
||||||
|
'Input appears to be binary data (e.g. an image). Please use the Image tab instead.',
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -197,19 +213,167 @@ export function extractMimeTypeFromDataUri(dataUri: string): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 格式化文件大小显示
|
* 格式化文件大小显示(兼容旧接口,内部委托给 formatBytes)
|
||||||
*
|
*
|
||||||
* @param bytes 字节数
|
* @param bytes 字节数
|
||||||
* @returns 格式化后的字符串
|
* @returns 格式化后的字符串
|
||||||
*/
|
*/
|
||||||
export function formatFileSize(bytes: number): string {
|
export function formatFileSize(bytes: number): string {
|
||||||
if (bytes < 1024) return `${bytes} B`;
|
return formatBytes(bytes);
|
||||||
const units = ['KB', 'MB', 'GB'];
|
|
||||||
let size = bytes / 1024;
|
|
||||||
let unitIndex = 0;
|
|
||||||
while (size >= 1024 && unitIndex < units.length - 1) {
|
|
||||||
size /= 1024;
|
|
||||||
unitIndex++;
|
|
||||||
}
|
}
|
||||||
return `${size.toFixed(unitIndex > 0 ? 2 : 1)} ${units[unitIndex]}`;
|
|
||||||
|
/**
|
||||||
|
* Base64 解码为二进制后的产物
|
||||||
|
*/
|
||||||
|
export interface Base64ToBlobResult {
|
||||||
|
/** 解码后的 Blob */
|
||||||
|
blob: Blob;
|
||||||
|
/** 推断出的 MIME 类型 */
|
||||||
|
mimeType: string;
|
||||||
|
/** 推荐的扩展名,含点(如 `.png`),无法识别时为 `.bin` */
|
||||||
|
suggestedExtension: string;
|
||||||
|
/** 已去除 data URI 前缀的纯 Base64 字符串 */
|
||||||
|
rawBase64: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 已知文件类型魔数签名表。注意:ZIP 头同样会匹配 .docx/.xlsx/.pptx/.apk
|
||||||
|
*
|
||||||
|
* 签名匹配规则:
|
||||||
|
* - `bytes` 必须匹配文件起始
|
||||||
|
* - 可选的 `tail` 用于多段签名(如 WebP:"RIFF" + 偏移 8 处的 "WEBP")
|
||||||
|
*/
|
||||||
|
const MAGIC_BYTE_SIGNATURES: ReadonlyArray<{
|
||||||
|
bytes: readonly number[];
|
||||||
|
tail?: { offset: number; bytes: readonly number[] };
|
||||||
|
mime: string;
|
||||||
|
ext: string;
|
||||||
|
}> = [
|
||||||
|
{ bytes: [0x89, 0x50, 0x4e, 0x47], mime: 'image/png', ext: '.png' },
|
||||||
|
{ bytes: [0xff, 0xd8, 0xff], mime: 'image/jpeg', ext: '.jpg' },
|
||||||
|
{ bytes: [0x47, 0x49, 0x46, 0x38], mime: 'image/gif', ext: '.gif' },
|
||||||
|
{ bytes: [0x42, 0x4d], mime: 'image/bmp', ext: '.bmp' },
|
||||||
|
{
|
||||||
|
bytes: [0x52, 0x49, 0x46, 0x46],
|
||||||
|
tail: { offset: 8, bytes: [0x57, 0x45, 0x42, 0x50] },
|
||||||
|
mime: 'image/webp',
|
||||||
|
ext: '.webp',
|
||||||
|
},
|
||||||
|
{ bytes: [0x25, 0x50, 0x44, 0x46], mime: 'application/pdf', ext: '.pdf' },
|
||||||
|
{ bytes: [0x50, 0x4b, 0x03, 0x04], mime: 'application/zip', ext: '.zip' },
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将 Base64 字符串解码为 Uint8Array
|
||||||
|
*
|
||||||
|
* @param b64 纯 Base64 字符串(不含 data URI 前缀)
|
||||||
|
* @returns 字节序列
|
||||||
|
*/
|
||||||
|
export function base64ToBytes(b64: string): Uint8Array {
|
||||||
|
const binary = atob(b64);
|
||||||
|
const bytes = new Uint8Array(binary.length);
|
||||||
|
for (let i = 0; i < binary.length; i += 1) {
|
||||||
|
bytes[i] = binary.charCodeAt(i);
|
||||||
|
}
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据字节序列前缀识别已知文件类型
|
||||||
|
*
|
||||||
|
* @param bytes 解码后的字节序列
|
||||||
|
* @returns 匹配到的 MIME + 扩展名;未匹配返回 null
|
||||||
|
*/
|
||||||
|
export function sniffMimeFromBytes(bytes: Uint8Array): { mime: string; ext: string } | null {
|
||||||
|
for (const sig of MAGIC_BYTE_SIGNATURES) {
|
||||||
|
if (bytes.length < sig.bytes.length) continue;
|
||||||
|
let matched = true;
|
||||||
|
for (let i = 0; i < sig.bytes.length; i += 1) {
|
||||||
|
if (bytes[i] !== sig.bytes[i]) {
|
||||||
|
matched = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!matched) continue;
|
||||||
|
if (sig.tail) {
|
||||||
|
const { offset, bytes: tailBytes } = sig.tail;
|
||||||
|
if (bytes.length < offset + tailBytes.length) continue;
|
||||||
|
let tailMatched = true;
|
||||||
|
for (let i = 0; i < tailBytes.length; i += 1) {
|
||||||
|
if (bytes[offset + i] !== tailBytes[i]) {
|
||||||
|
tailMatched = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!tailMatched) continue;
|
||||||
|
}
|
||||||
|
return { mime: sig.mime, ext: sig.ext };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将 Base64 / data URI 字符串解码为 Blob,自动推断 MIME 与扩展名
|
||||||
|
*
|
||||||
|
* MIME 推断优先级:data URI 前缀 → 字节魔数 → `application/octet-stream`
|
||||||
|
*
|
||||||
|
* @param input Base64 字符串或 data URI
|
||||||
|
* @returns 解码结果
|
||||||
|
* @throws {Error} 输入不是合法 Base64
|
||||||
|
*/
|
||||||
|
export function base64ToBlob(input: string): Base64ToBlobResult {
|
||||||
|
const trimmed = input.trim();
|
||||||
|
const prefixMatch = trimmed.match(DATA_URI_BASE64_PREFIX);
|
||||||
|
const cleaned = prefixMatch ? trimmed.slice(prefixMatch[0].length) : trimmed;
|
||||||
|
|
||||||
|
if (!isValidBase64(cleaned)) {
|
||||||
|
throw new Error('Invalid Base64 string');
|
||||||
|
}
|
||||||
|
|
||||||
|
const bytes = base64ToBytes(cleaned);
|
||||||
|
|
||||||
|
let mimeType: string;
|
||||||
|
let suggestedExtension: string;
|
||||||
|
if (prefixMatch) {
|
||||||
|
mimeType = extractMimeTypeFromDataUri(trimmed);
|
||||||
|
const sniffed = sniffMimeFromBytes(bytes);
|
||||||
|
suggestedExtension = sniffed?.ext ?? mimeTypeToExtension(mimeType);
|
||||||
|
} else {
|
||||||
|
const sniffed = sniffMimeFromBytes(bytes);
|
||||||
|
mimeType = sniffed?.mime ?? 'application/octet-stream';
|
||||||
|
suggestedExtension = sniffed?.ext ?? '.bin';
|
||||||
|
}
|
||||||
|
|
||||||
|
const blob = new Blob([bytes.buffer as ArrayBuffer], { type: mimeType });
|
||||||
|
return { blob, mimeType, suggestedExtension, rawBase64: cleaned };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 极小的 MIME -> 扩展名映射,仅用于带 data URI 前缀但魔数无法识别时 */
|
||||||
|
function mimeTypeToExtension(mime: string): string {
|
||||||
|
if (mime.startsWith('image/svg')) return '.svg';
|
||||||
|
if (mime === 'image/webp') return '.webp';
|
||||||
|
if (mime === 'image/bmp') return '.bmp';
|
||||||
|
if (mime === 'image/x-icon' || mime === 'image/vnd.microsoft.icon') return '.ico';
|
||||||
|
if (mime === 'text/plain') return '.txt';
|
||||||
|
if (mime === 'application/json') return '.json';
|
||||||
|
if (mime === 'text/html') return '.html';
|
||||||
|
if (mime === 'text/css') return '.css';
|
||||||
|
return '.bin';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 触发浏览器下载指定 Blob
|
||||||
|
*
|
||||||
|
* @param blob 要下载的 Blob
|
||||||
|
* @param filename 下载文件名
|
||||||
|
*/
|
||||||
|
export function downloadBlob(blob: Blob, filename: string): void {
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = filename;
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
document.body.removeChild(a);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-25
@@ -3,37 +3,29 @@
|
|||||||
* @param text 要复制的文本
|
* @param text 要复制的文本
|
||||||
* @returns Promise<boolean> 是否复制成功
|
* @returns Promise<boolean> 是否复制成功
|
||||||
*/
|
*/
|
||||||
export const copyTextToClipboard = async (text: string): Promise<boolean> => {
|
export async function copyTextToClipboard(text: string): Promise<boolean> {
|
||||||
return new Promise((resolve, reject) => {
|
try {
|
||||||
navigator.clipboard
|
await navigator.clipboard.writeText(text);
|
||||||
.writeText(text)
|
return true;
|
||||||
.then(() => {
|
} catch {
|
||||||
resolve(true);
|
return false;
|
||||||
})
|
}
|
||||||
.catch((error) => {
|
}
|
||||||
reject(new Error(`复制文本到剪贴板失败,错误: ${error?.message || 'Unknown error'}`));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 复制图片到剪贴板
|
* 复制图片到剪贴板
|
||||||
* @param blob 要复制的图片
|
* @param blob 要复制的图片
|
||||||
* @returns Promise<boolean> 是否复制成功
|
* @returns Promise<boolean> 是否复制成功
|
||||||
*/
|
*/
|
||||||
export const copyImageToClipboard = async (blob: Blob): Promise<boolean> => {
|
export async function copyImageToClipboard(blob: Blob): Promise<boolean> {
|
||||||
return new Promise((resolve, reject) => {
|
try {
|
||||||
navigator.clipboard
|
await navigator.clipboard.write([
|
||||||
.write([
|
|
||||||
new ClipboardItem({
|
new ClipboardItem({
|
||||||
'image/png': blob,
|
'image/png': blob,
|
||||||
}),
|
}),
|
||||||
])
|
]);
|
||||||
.then(() => {
|
return true;
|
||||||
resolve(true);
|
} catch {
|
||||||
})
|
return false;
|
||||||
.catch((error) => {
|
}
|
||||||
reject(new Error(`复制图片到剪贴板失败,错误: ${error?.message || 'Unknown error'}`));
|
}
|
||||||
});
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
/**
|
||||||
|
* 格式化字节大小为易读字符串
|
||||||
|
*
|
||||||
|
* @param bytes 字节数
|
||||||
|
* @returns 格式化后的字符串,例如 "1.5 KB" 或 "100 B"
|
||||||
|
*/
|
||||||
|
export function formatBytes(bytes: number): string {
|
||||||
|
if (bytes === 0) return '0 B';
|
||||||
|
if (bytes < 1024) return `${bytes} B`;
|
||||||
|
|
||||||
|
const units = ['KB', 'MB', 'GB', 'TB'];
|
||||||
|
let size = bytes / 1024;
|
||||||
|
let unitIndex = 0;
|
||||||
|
|
||||||
|
while (size >= 1024 && unitIndex < units.length - 1) {
|
||||||
|
size /= 1024;
|
||||||
|
unitIndex++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// KB uses 1 decimal, MB/GB/TB use 2 decimals
|
||||||
|
const decimals = unitIndex === 0 ? 1 : 2;
|
||||||
|
|
||||||
|
return `${size.toFixed(decimals)} ${units[unitIndex]}`;
|
||||||
|
}
|
||||||
@@ -47,9 +47,6 @@ function toTomlValue(value: unknown): string {
|
|||||||
return value ? 'true' : 'false';
|
return value ? 'true' : 'false';
|
||||||
}
|
}
|
||||||
if (typeof value === 'number') {
|
if (typeof value === 'number') {
|
||||||
if (Number.isInteger(value)) {
|
|
||||||
return String(value);
|
|
||||||
}
|
|
||||||
return String(value);
|
return String(value);
|
||||||
}
|
}
|
||||||
if (typeof value === 'string') {
|
if (typeof value === 'string') {
|
||||||
|
|||||||
@@ -54,8 +54,6 @@ function stringifyYamlString(str: string): string {
|
|||||||
str === 'true' ||
|
str === 'true' ||
|
||||||
str === 'false' ||
|
str === 'false' ||
|
||||||
/[:#{}[\],&*?|>\-!%@`]/.test(str) ||
|
/[:#{}[\],&*?|>\-!%@`]/.test(str) ||
|
||||||
str.startsWith(' ') ||
|
|
||||||
str.endsWith(' ') ||
|
|
||||||
str.includes(' ') ||
|
str.includes(' ') ||
|
||||||
str.includes('\n') ||
|
str.includes('\n') ||
|
||||||
/^\d/.test(str);
|
/^\d/.test(str);
|
||||||
|
|||||||
+13
-10
@@ -2,6 +2,8 @@
|
|||||||
* JWT 解析工具
|
* JWT 解析工具
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import i18n from '@/i18n';
|
||||||
|
|
||||||
export interface JwtHeader {
|
export interface JwtHeader {
|
||||||
alg: string;
|
alg: string;
|
||||||
typ?: string;
|
typ?: string;
|
||||||
@@ -36,20 +38,17 @@ export interface JwtResult {
|
|||||||
* @param str Base64URL 编码字符串
|
* @param str Base64URL 编码字符串
|
||||||
*/
|
*/
|
||||||
export function decodeBase64Url(str: string): string {
|
export function decodeBase64Url(str: string): string {
|
||||||
// 将 Base64URL 转换为 标准 Base64
|
|
||||||
let base64 = str.replace(/-/g, '+').replace(/_/g, '/');
|
let base64 = str.replace(/-/g, '+').replace(/_/g, '/');
|
||||||
|
|
||||||
// 添加填充
|
|
||||||
const pad = base64.length % 4;
|
const pad = base64.length % 4;
|
||||||
if (pad) {
|
if (pad) {
|
||||||
if (pad === 1) {
|
if (pad === 1) {
|
||||||
throw new Error('Invalid base64url string');
|
throw new Error(i18n.t('jwt:errors.invalidBase64String'));
|
||||||
}
|
}
|
||||||
base64 += new Array(5 - pad).join('=');
|
base64 += new Array(5 - pad).join('=');
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 使用 TextDecoder 处理 UTF-8 字符
|
|
||||||
const binStr = atob(base64);
|
const binStr = atob(base64);
|
||||||
const binLen = binStr.length;
|
const binLen = binStr.length;
|
||||||
const bytes = new Uint8Array(binLen);
|
const bytes = new Uint8Array(binLen);
|
||||||
@@ -59,7 +58,9 @@ export function decodeBase64Url(str: string): string {
|
|||||||
const decoder = new TextDecoder('utf-8');
|
const decoder = new TextDecoder('utf-8');
|
||||||
return decoder.decode(bytes);
|
return decoder.decode(bytes);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw new Error('Failed to decode base64url: ' + (e instanceof Error ? e.message : String(e)));
|
throw new Error(
|
||||||
|
i18n.t('jwt:errors.failedToDecode') + (e instanceof Error ? e.message : String(e)),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,7 +77,7 @@ export function parseJwt(token: string): JwtResult {
|
|||||||
payload: null,
|
payload: null,
|
||||||
signature: '',
|
signature: '',
|
||||||
raw: { header: '', payload: '', signature: '' },
|
raw: { header: '', payload: '', signature: '' },
|
||||||
error: 'JWT 格式错误:必须包含三个由 "." 分隔的部分',
|
error: i18n.t('jwt:errors.invalidFormat'),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,7 +97,8 @@ export function parseJwt(token: string): JwtResult {
|
|||||||
const headerJson = decodeBase64Url(headerB64);
|
const headerJson = decodeBase64Url(headerB64);
|
||||||
result.header = JSON.parse(headerJson);
|
result.header = JSON.parse(headerJson);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
result.error = '解析 Header 失败:' + (e instanceof Error ? e.message : String(e));
|
result.error =
|
||||||
|
i18n.t('jwt:errors.parseHeaderFailed') + (e instanceof Error ? e.message : String(e));
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,7 +106,8 @@ export function parseJwt(token: string): JwtResult {
|
|||||||
const payloadJson = decodeBase64Url(payloadB64);
|
const payloadJson = decodeBase64Url(payloadB64);
|
||||||
result.payload = JSON.parse(payloadJson);
|
result.payload = JSON.parse(payloadJson);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
result.error = '解析 Payload 失败:' + (e instanceof Error ? e.message : String(e));
|
result.error =
|
||||||
|
i18n.t('jwt:errors.parsePayloadFailed') + (e instanceof Error ? e.message : String(e));
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,10 +115,10 @@ export function parseJwt(token: string): JwtResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 格式化 JSON
|
* 将对象格式化为 JSON 字符串
|
||||||
* @param obj 对象
|
* @param obj 对象
|
||||||
*/
|
*/
|
||||||
export function formatJson(obj: unknown): string {
|
export function stringifyJson(obj: unknown): string {
|
||||||
try {
|
try {
|
||||||
return JSON.stringify(obj, null, 2);
|
return JSON.stringify(obj, null, 2);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
@@ -206,12 +206,19 @@ export function printHtml(html: string, title: string = 'Markdown Preview'): voi
|
|||||||
printWindow.document.close();
|
printWindow.document.close();
|
||||||
|
|
||||||
// 等待样式加载完成后打印
|
// 等待样式加载完成后打印
|
||||||
|
let printed = false;
|
||||||
printWindow.onload = () => {
|
printWindow.onload = () => {
|
||||||
|
if (!printed) {
|
||||||
|
printed = true;
|
||||||
printWindow.print();
|
printWindow.print();
|
||||||
|
}
|
||||||
};
|
};
|
||||||
// 部分浏览器 onload 不触发,使用延迟回退
|
// 部分浏览器 onload 不触发,使用延迟回退
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
|
if (!printed) {
|
||||||
|
printed = true;
|
||||||
printWindow.print();
|
printWindow.print();
|
||||||
|
}
|
||||||
}, 500);
|
}, 500);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+24
-12
@@ -1,4 +1,5 @@
|
|||||||
import type { CleaningResult, StorageCleanerOptions, StorageCleanResult } from '@/types/storage';
|
import type { CleaningResult, StorageCleanerOptions, StorageCleanResult } from '@/types/storage';
|
||||||
|
import { formatBytes } from './format';
|
||||||
|
|
||||||
const RESTRICTED_PROTOCOLS = [
|
const RESTRICTED_PROTOCOLS = [
|
||||||
'chrome:',
|
'chrome:',
|
||||||
@@ -41,10 +42,15 @@ export function isRestrictedUrl(url?: string): boolean {
|
|||||||
export async function getCookieSize(url: string): Promise<number> {
|
export async function getCookieSize(url: string): Promise<number> {
|
||||||
try {
|
try {
|
||||||
const cookies = await chrome.cookies.getAll({ url });
|
const cookies = await chrome.cookies.getAll({ url });
|
||||||
// 估算:名称 + 值 + 域名 + 路径 的长度
|
const encoder = new TextEncoder();
|
||||||
|
// 估算:名称 + 值 + 域名 + 路径 的 UTF-8 字节数
|
||||||
return cookies.reduce(
|
return cookies.reduce(
|
||||||
(acc, c) =>
|
(acc, c) =>
|
||||||
acc + c.name.length + c.value.length + (c.domain?.length || 0) + (c.path?.length || 0),
|
acc +
|
||||||
|
encoder.encode(c.name).length +
|
||||||
|
encoder.encode(c.value).length +
|
||||||
|
encoder.encode(c.domain ?? '').length +
|
||||||
|
encoder.encode(c.path ?? '').length,
|
||||||
0,
|
0,
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -59,7 +65,11 @@ export async function getLocalStorageSize(tabId: number): Promise<number> {
|
|||||||
target: { tabId },
|
target: { tabId },
|
||||||
func: () => {
|
func: () => {
|
||||||
try {
|
try {
|
||||||
return Object.entries(localStorage).reduce((acc, [k, v]) => acc + k.length + v.length, 0);
|
const encoder = new TextEncoder();
|
||||||
|
return Object.entries(localStorage).reduce(
|
||||||
|
(acc, [k, v]) => acc + encoder.encode(k).length + encoder.encode(v).length,
|
||||||
|
0,
|
||||||
|
);
|
||||||
} catch {
|
} catch {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@@ -78,8 +88,9 @@ export async function getSessionStorageSize(tabId: number): Promise<number> {
|
|||||||
target: { tabId },
|
target: { tabId },
|
||||||
func: () => {
|
func: () => {
|
||||||
try {
|
try {
|
||||||
|
const encoder = new TextEncoder();
|
||||||
return Object.entries(sessionStorage).reduce(
|
return Object.entries(sessionStorage).reduce(
|
||||||
(acc, [k, v]) => acc + k.length + v.length,
|
(acc, [k, v]) => acc + encoder.encode(k).length + encoder.encode(v).length,
|
||||||
0,
|
0,
|
||||||
);
|
);
|
||||||
} catch {
|
} catch {
|
||||||
@@ -94,7 +105,7 @@ export async function getSessionStorageSize(tabId: number): Promise<number> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getIndexedDBSize(tabId: number): Promise<number> {
|
export async function getOriginStorageEstimate(tabId: number): Promise<number> {
|
||||||
try {
|
try {
|
||||||
const [result] = await chrome.scripting.executeScript({
|
const [result] = await chrome.scripting.executeScript({
|
||||||
target: { tabId },
|
target: { tabId },
|
||||||
@@ -114,7 +125,7 @@ export async function getIndexedDBSize(tabId: number): Promise<number> {
|
|||||||
});
|
});
|
||||||
return (result?.result as number) || 0;
|
return (result?.result as number) || 0;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to get IndexedDB size:', error);
|
console.error('Failed to get origin storage estimate:', error);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -166,13 +177,14 @@ export async function getServiceWorkerCount(tabId: number): Promise<number> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式化字节大小显示(兼容旧接口,内部委托给 formatBytes)
|
||||||
|
*
|
||||||
|
* @param bytes 字节数
|
||||||
|
* @returns 格式化后的字符串
|
||||||
|
*/
|
||||||
export function formatSize(bytes: number): string {
|
export function formatSize(bytes: number): string {
|
||||||
if (bytes === 0) return '0 B';
|
return formatBytes(bytes);
|
||||||
if (bytes < 1024) return `${bytes} B`; // 处理小于 1KB 的情况
|
|
||||||
const k = 1024;
|
|
||||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
|
||||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
||||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function clearCookies(url: string): Promise<StorageCleanResult> {
|
export async function clearCookies(url: string): Promise<StorageCleanResult> {
|
||||||
|
|||||||
+5
-13
@@ -1,3 +1,5 @@
|
|||||||
|
import { formatBytes } from './format';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 文本统计信息接口
|
* 文本统计信息接口
|
||||||
*/
|
*/
|
||||||
@@ -57,21 +59,11 @@ export function getTextStats(text: string): TextStats {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 格式化字节大小显示
|
* 格式化字节大小显示(兼容旧接口,内部委托给 formatBytes)
|
||||||
*
|
*
|
||||||
* @param bytes 字节数
|
* @param bytes 字节数
|
||||||
* @returns 格式化后的字符串,例如 "1.2 KB" 或 "100 B"
|
* @returns 格式化后的字符串
|
||||||
*/
|
*/
|
||||||
export function formatByteSize(bytes: number): string {
|
export function formatByteSize(bytes: number): string {
|
||||||
if (bytes < 1024) {
|
return formatBytes(bytes);
|
||||||
return `${bytes} B`;
|
|
||||||
}
|
|
||||||
const units = ['KB', 'MB', 'GB', 'TB'];
|
|
||||||
let size = bytes / 1024;
|
|
||||||
let unitIndex = 0;
|
|
||||||
while (size >= 1024 && unitIndex < units.length - 1) {
|
|
||||||
size /= 1024;
|
|
||||||
unitIndex++;
|
|
||||||
}
|
|
||||||
return `${size.toFixed(unitIndex > 0 ? 2 : 1)} ${units[unitIndex]}`;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,9 +38,12 @@ export const useStorageState = <K extends keyof StorageSchema>(
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (hasLoadedFromStorage.current) return;
|
if (hasLoadedFromStorage.current) return;
|
||||||
|
|
||||||
|
let cancelled = false;
|
||||||
|
|
||||||
const loadState = async () => {
|
const loadState = async () => {
|
||||||
try {
|
try {
|
||||||
const savedValue = await storageUtil.get(key, defaultValue);
|
const savedValue = await storageUtil.get(key, defaultValue);
|
||||||
|
if (cancelled) return;
|
||||||
if (savedValue !== undefined) {
|
if (savedValue !== undefined) {
|
||||||
if (validator) {
|
if (validator) {
|
||||||
setValue(validator(savedValue) ? savedValue : defaultValue);
|
setValue(validator(savedValue) ? savedValue : defaultValue);
|
||||||
@@ -51,12 +54,18 @@ export const useStorageState = <K extends keyof StorageSchema>(
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`加载状态失败 (${key}):`, error);
|
console.error(`加载状态失败 (${key}):`, error);
|
||||||
} finally {
|
} finally {
|
||||||
|
if (!cancelled) {
|
||||||
setIsInitialized(true);
|
setIsInitialized(true);
|
||||||
hasLoadedFromStorage.current = true;
|
hasLoadedFromStorage.current = true;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
loadState().catch(console.error);
|
loadState().catch(console.error);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
}, [defaultValue, key, validator]);
|
}, [defaultValue, key, validator]);
|
||||||
|
|
||||||
// Save to storage and localStorage snapshot when value changes (after initial load)
|
// Save to storage and localStorage snapshot when value changes (after initial load)
|
||||||
|
|||||||
Reference in New Issue
Block a user