feat: Tailwind CSS/shadcn/ui 迁移 & 右键菜单功能 (#42)
* feat: 添加 contextMenus 权限和消息类型定义
* feat: 实现右键菜单注册与点击分流逻辑
- 新增 utils/contextMenu.ts 封装菜单配置和解析函数
- 在 background.ts 监听 onInstalled 初始化菜单
- 实现 contextMenus.onClicked 点击事件处理
- 分流逻辑:优先发送到侧边栏,否则打开 options 页面
- 添加 contextMenu 单元测试(15个测试用例)
- 更新 vitest.setup.ts 添加 contextMenus mock
* feat: 实现 Content Script 原位轻量提示 UI
- 新增 uiPopover.ts 实现原位弹窗组件(深色主题、自动定位、自动隐藏)
- 新增 contextMenuHandler.ts 处理右键菜单消息
- 时间戳转换:在点击位置显示转换结果
- 文本统计:显示字符/单词/行数/字节统计
- 更新 messageHandler.ts 挂载右键菜单消息监听
* feat: 实现 React 页面层右键菜单数据联动
- 新增 useContextMenuData Hook 处理右键菜单数据传递
- 重构 Jwt/Base64Converter/TextStatistics/QrCode 页面接收右键数据
- RouterProvider 支持从 URL 参数解析右键菜单数据
- 添加 contextMenu/pendingData 存储键到 StorageSchema
- 添加 useContextMenuData 单元测试(12个测试用例)
* test: 添加 background 单元测试与边界情况处理
- 新增 entrypoints/__tests__/background.test.ts (12个测试用例)
- 超长文本截断限制 (>10000字符)
- Base64 内联图片拦截并返回错误提示
- 更新 parseContextMenuClick 返回 ParseResult 格式
- 更新测试匹配新的返回格式
- lint/typecheck/test 全部通过 (579个测试)
* fix: 修复右键菜单跳转到错误页面的问题
- 将 options 页面路径从 '/entrypoints/options/index.html' 修正为 '/options.html'
- WXT 构建后 entrypoints/options/index.html 会输出为根目录的 options.html
* fix: 修复右键菜单跳转目标为 popup 页面
- 将 fallback 页面从 options.html 改为 popup.html
- popup 页面使用 RouterProvider,可以正确处理 URL 参数并跳转到对应功能页面
- options 页面是独立设置页,不支持 URL 参数路由
* fix: 使用 openPopup() 替代 tabs.create() 打开弹窗
- background.ts: 使用 browser.action.openPopup() 打开 popup 弹窗
- 先保存数据到 storage,然后打开 popup
- RouterProvider.tsx: 初始化时检查 storage 中的 pendingData 并跳转到对应页面
- 移除之前错误的 tabs.create() 方式
* fix: 修复右键菜单数据未传递到目标页面的问题
- RouterProvider 不再提前清除 pendingData
- 让目标页面的 useContextMenuData 来消费和清除数据
- 这样确保 TextStatistics 等页面能正确接收选中的文本
* fix: 修复 popup 已打开时右键菜单不生效的问题
- 在 RouterProvider 中添加对 contextMenu/pendingData 的 storage 变化监听
- 当 pendingData 变化时,自动跳转到对应功能页面
- 解决了 openPopup() 只聚焦已有窗口而不触发重新挂载的问题
* feat: 支持右键菜单图片二维码识别
- 在 qrCodeParser.ts 中添加 parseQrCodeFromUrl 函数,支持从图片 URL 解析二维码
- 在 QrCodeToUrlSection 中使用 useContextMenuData 接收右键菜单传递的图片 URL
- 自动下载图片并解析二维码,显示解析结果
* refactor: 暂时移除图片二维码识别功能
- 删除 qrCode-image 右键菜单配置
- 删除 parseQrCodeFromUrl 函数
- 删除 QrCodeToUrlSection 中的 useContextMenuData 相关代码
- 更新相关测试用例
* feat: 支持右键菜单时间戳转换
- 在 useTimestampConverter 中添加 useContextMenuData hook
- 智能识别输入是时间戳还是日期时间字符串
- 自动切换到对应模式并执行转换
- 时间戳自动识别秒/毫秒单位
* fix: 修复右键菜单功能的多个逻辑漏洞
1. 修复时区硬编码问题 - 使用用户选择的时区而非固定 Asia/Shanghai
2. 修复 openPopup() 失败后数据残留 - 失败时清除 storage 中的待处理数据
3. 统一数据过期时间常量 - 导出 CONTEXT_MENU_DATA_EXPIRY_MS 并统一使用
4. 修复 featureKey 类型断言不安全 - 使用映射表处理非常规菜单 ID
* refactor(qrcode): 提取独立组件并添加单元测试
- 创建 pages/QrCode/types.ts 定义状态类型接口
- 提取 QrCodePreview 组件用于二维码预览和操作
- 提取 ImageUploader 组件封装图片上传、拖拽、粘贴逻辑
- 重构 UrlToQrCodeSection 状态提升到父组件
- 重构 QrCodeToUrlSection 通过回调传递解析结果
- 更新主页面 index.tsx 集中管理所有状态
- 为 QrCodePreview 和 ImageUploader 添加单元测试 (23 个用例)
* refactor(qrcode): 引入通用组件并重构双栏布局
- 引入 SwitchButtonGroup 用于模式切换
- 引入 TextInputArea 用于文本输入和结果展示
- 使用 MUI Grid 构建响应式双栏布局
- 实现 generate/parse 模式下的左右面板内容切换
- 修复 iconColor 颜色格式错误,使用 qrCodePageStyles.primaryColor
* refactor(qrcode): 国际化补充、质量保障与错误处理优化
- 补充 i18n 翻译键(generateMode, parseMode, pasteHint 等)
- 创建 useDebounce Hook 实现输入防抖 (200ms)
- 使用 useRef 解决 useEffect 无限循环问题
- 编写 pages/QrCode 单元测试 (7 个用例)
- 优化右键菜单错误处理,改进用户提示
- 运行 603 个测试全部通过
* refactor(qrcode): 组件化重构,采用 Context + Hook 模式
- 创建 QrCodeContext 和 QrCodeProvider 管理共享状态
- 提取 useQrCode Hook 封装所有状态和业务逻辑
- 创建 GeneratePanel 组件处理二维码生成模式
- 创建 ParsePanel 组件处理二维码解析模式
- 简化 index.tsx 为容器组件 (340行 → 47行)
- 删除未使用的旧组件文件 (QrCodeToUrlSection, UrlToQrCodeSection)
- 清理 types.ts 中未使用的类型定义
- 603 个测试全部通过
* fix(qrcode): 固定二维码预览图片尺寸,避免布局抖动
- 设置 QR_PREVIEW_IMAGE 固定尺寸 250x250
- 与 QRious 生成的二维码大小保持一致
- 解决输入内容变化时预览窗口大小跳动问题
* fix(qrcode): 修复切换 tab 后二维码图片失效问题
- 移除 ImageUploader 组件卸载时的预览 URL 释放逻辑
- 在 useQrCode hook 中统一管理预览 URL 生命周期
- 创建新预览 URL 前释放旧的,避免内存泄漏
* fix(qrcode): 固定图片上传区域高度,避免布局抖动
- 将 DROPZONE 的 minHeight: 200 改为 height: 250
- 与二维码预览图片高度保持一致
- 解决上传图片时 div 高度变化问题
* refactor(qrCode): 优化二维码解析功能
- 将'二维码转 URL'改为'二维码转文本'
- 将解析结果的文本预览框的 placeholder 置为空
- 去除手动解析二维码功能,只保留自动解析
* fix(pageHeader): 使用 MUI 主题色替代硬编码颜色,支持暗色模式
* feat(pageHeader): popup 模式下隐藏 PageHeader 组件
* fix(i18n): 统一使用 useLazyTranslation 避免翻译 key 闪烁
* perf: 配置 manualChunks 拆分 vendor chunk,优化打包体积
- 使用 Vite 插件 manualChunksForHtmlOnly 仅对 HTML 多入口构建生效
- 跳过 background/content-script 的 IIFE 构建(不支持 manualChunks)
- 拆分 vendor-react (193KB)、vendor-mui (326KB)、vendor-i18n (55KB)
- 按需加载 vendor-qr (78KB)、vendor-dnd (45KB)、vendor-markdown (41KB)
- PageErrorBoundary chunk 从 454KB 降至 36KB
* chore: upgrade wxt to v0.20.26 and @wxt-dev/module-react to v1.2.2
* chore: upgrade low-risk dependencies
- react: 19.2.3 → 19.2.6
- react-dom: 19.2.3 → 19.2.6
- dayjs: 1.11.19 → 1.11.20
- marked: 18.0.3 → 18.0.4
- prettier: 3.8.1 → 3.8.3
- terser: 5.46.0 → 5.47.1
- i18next: 26.0.8 → 26.2.0
- react-i18next: 17.0.6 → 17.0.8
- globals: 17.2.0 → 17.6.0
- eslint-plugin-react-hooks: 7.0.1 → 7.1.1
- @typescript-eslint/*: 8.54.0 → 8.59.4
- typescript-eslint: 8.54.0 → 8.59.4
- @testing-library/jest-dom: 6.6.0 → 6.9.1
- @testing-library/react: 16.0.0 → 16.3.2
- @testing-library/user-event: 14.5.2 → 14.6.1
- @testing-library/dom: added as peer dependency
- @types/react: 19.2.7 → 19.2.15
- @types/chrome: 0.1.36 → 0.1.42
- @types/webextension-polyfill: 0.12.4 → 0.12.5
* chore: upgrade medium-risk dependencies
- lint-staged: 16.2.7 → 17.0.5
- jsdom: 25.0.0 → 29.1.1
- @vitejs/plugin-react: 4.3.4 → 6.0.2
- vitest: 2.0.0 → 4.1.7
- @vitest/coverage-v8: upgraded to match vitest
- @webext-core/messaging: 2.3.0 → 3.0.1
- eslint: 9.39.2 → 10.4.0
- @eslint/js: added as new dependency
- @types/marked: removed (marked now provides its own types)
Fixes:
- Fix ref update during render in useQrCode.ts
- Fix ref update during render in useStorageCleaner.ts
- Add error cause in jwt.ts decode function
- Add type assertion for mock functions in htmlToMarkdown.test.ts
* chore(deps): 降级 eslint 版本并移除 @eslint/js
* docs: 精简 AGENTS.md,聚焦高信号信息
* test: 修复测试中的 act() 警告和 clipboard mock 问题
- TextInputArea: 使用 userEvent 替代 fireEvent,用 vi.spyOn 替代 Object.assign mock clipboard
- ImageMode/FileMode: 添加 waitForStorageReady() 等待 useStorageState 异步初始化
* perf: 优化首屏加载,快照有效时跳过骨架屏
- isLoaded 初始值根据 localStorage 快照是否存在决定
- 后续访问直接渲染真实 DOM,无需等待 chrome.storage 异步加载
- loadInitialData 仍在后台静默执行确保数据同步
* 引入 Tailwind CSS 和 shadcn/ui
* 替换 Timestamp 页面图标为 lucide-react 的 Clock 图标
* 用 Tailwind CSS 重写 Timestamp 页面的 MUI 基础排版组件
* 用 Tailwind CSS 重构 ResultView 和 LiveClock 组件
* 用 Tailwind CSS 重写 Dashboard/index.tsx 和 ToolCard.tsx
* 用 Tailwind CSS 重写 TextStatistics 页面
* 用 Tailwind CSS 重写 Base64Converter 页面
* 用 Tailwind CSS 重写 QrCode 页面及相关组件
* 用 Tailwind CSS 重写 Jwt 页面
* 用 Tailwind CSS 重写 StorageCleaner 页面,创建 shadcn/ui Dialog 组件
* 用 Tailwind CSS 重写 JsonTools 页面
* 用 Tailwind CSS 重构所有共享组件
* 修复 TypeScript 类型错误:将 MUI sx 语法改成标准 CSS 属性
* 重写基础骨架组件:用纯 Tailwind CSS 替换 MUI Box 组件
* 重写所有页面和组件:用纯 Tailwind CSS 替换 MUI 组件和图标
* 移除 MUI 依赖,简化配置文件,重写 ThemeModeProvider
* 移除 wxt.config.ts 中残留的 MUI chunk 配置
* 为 Dialog 组件添加暗黑模式背景色支持
* fix: 修复暗黑模式样式兼容性
- 在 tailwind.config.js 中启用 darkMode: 'class' 并扩展语义化颜色变量
- 将全项目硬编码颜色(bg-white、text-gray-*、border-gray-* 等)替换为语义化类名
- 修复 popup/index.html 硬编码浅色背景色
- 同步更新相关单元测试中的类名断言
* fix: 修复输入框和按钮在暗色模式下的样式问题
- 为 :root 和 .dark 添加 color-scheme,使浏览器表单控件默认样式适配暗色模式
- 将 bg-primary 搭配 text-white 的按钮改为 text-primary-foreground
- 替换残留的 hover:bg-blue-700、text-blue-500、bg-gray-200 等硬编码颜色
- 同步更新 TextInputArea 单元测试
* fix: 增强 SwitchButtonGroup 和立即转换按钮的视觉层级
- SwitchButtonGroup 选中按钮阴影从 shadow-sm 升级到 shadow-md
- 同步更新单元测试中断言
- Timestamp 立即转换按钮添加 shadow-md 增强边界感
* style: 隐藏所有窗口的滚动条
- 在全局 CSS 中为 html 添加 scrollbar-width: none(Firefox)
- 添加 ::-webkit-scrollbar { display: none }(Chrome/Safari/Opera)
* feat: add sonner dependency for toast notifications
* refactor: remove DomainHeader component and its usage
* refactor: 使用 className 替换 sx/buttonSx 并优化 SwitchButtonGroup 选中动画
* refactor: 简化 TextInputArea,移除 showMessage 和 MUI 样式,改用 shadcn 样式和 sonner toast
* refactor: 简化 TextInputArea,移除 showMessage 和 MUI 样式,改用 shadcn 样式和 sonner toast
* refactor: 重构 QrCodePreview 组件,继承 HTMLDiv 属性并统一 shadcn 样式
- 组件改为继承 `React.HTMLAttributes<HTMLDivElement>`,支持外部传入 className 和事件
- 使用 `cn()` 函数合并外部类名
- 空白状态改用 `border border-dashed` 和更浅的 `bg-muted/40` 背景
- 正常状态改为纯白背景柔边圆角容器包裹二维码,确保暗黑模式下黑白对比度
- 下载/复制按钮完全对齐 shadcn 的 Outline 与 Default 样式规范
- 更新测试用例中的 alt 文本为 "QR Code Preview"
* refactor: 将 PageHeader 组件样式从 MUI sx 迁移至 Tailwind 类名,并更新测试
* refactor: 更新PageErrorBoundary的文案和样式以对齐shadcn主题
- 错误提示从“该页面加载失败”改为“该功能运行异常”
- 重试按钮文字从“重试”改为“重新尝试”
- 使用border-destructive, bg-destructive等语义化类名替换硬编码颜色
- 更新对应测试断言
* refactor: 重构 CopyButton 与 RouterContainer 组件,移除 GlobalSnackbar 并统一使用 sonner toast 和 cn 工具函数
* refactor: 移除 MUI sx 样式和未使用的 GlobalSnackbar 引用
* feat: add @radix-ui/react-select dependency
* feat: add Input and Select shadcn UI components
* refactor: 重构 Timestamp 页面使用响应式 Hook 统一状态并全面迁移至 shadcn 样式
* refactor: 将 TextStatistics 页面和 TextInputArea 组件全面迁移至 shadcn 样式并优化布局
* feat: add Badge, Checkbox, Label, and Switch shadcn UI components
* refactor: 全面迁移 StorageCleaner 页面至 shadcn 样式并移除 GlobalSnackbar 依赖
* refactor: 全面重构 JsonTools 页面,采用声明式响应架构并统一 shadcn 样式
* refactor: 全面重构 Jwt 页面,采用防抖输入并统一 shadcn 样式
* refactor: 重构 Dashboard 页面和 ToolCard 组件,全面迁移至 shadcn 样式并优化布局
* refactor: 重构 HtmlToMarkdown 和 MarkdownToHtml 页面,统一 shadcn 样式并优化打印与暗色模式
* refactor: 抽离 useBase64Converter hook 并新增 Base64ConverterSection 组件,统一 Base64 转换页面的 shadcn 样式
* refactor: 重构 QrCode 页面为声明式响应架构并统一 shadcn 样式
* refactor: 优化 Dashboard 布局及 ToolCard 描述文本截断处理
* refactor: 优化 MarkdownToHtml 预览样式,剥离 CSS 变量回退值并增强 iframe 暗色模式自适应
* refactor: 优化 Popover 安全性和交互体验,修复 Context Menu 数据持久化问题并添加 i18n 支持
* refactor: strengthen i18n type safety and fix async Promise handling in language detection
* refactor: extend vitest setup with full chrome/browser mocks and i18n utility mock
* refactor: migrate storage listeners to wxt/browser and refactor provider state management
* refactor: restructure CI/CD pipelines with cached dependencies, separate setup job, and multi-browser builds
* refactor: remove tsc check from lint-staged and reorder lint commands
* refactor: migrate eslint config to tseslint.config with projectService and upgrade React rules
* refactor: use __MSG_ placeholders for i18n and remove postcss config
* refactor: replace __MSG_ placeholders with static strings for extension name and description
* refactor: add React version detection and disable prop-types in eslint; refactor lazy translation tests with proper mock isolation and Chrome/browser stubs
* refactor: use regex matchers in StorageCleanerConfirm tests and add chrome/browser mocks
* refactor: use regex matchers for i18n text and add uniform mocks in test files
* ci: add wxt prepare step to generate .wxt types for typecheck and tests
---------
Co-authored-by: Ubuntu <ubuntu@localhost.localdomain>
This commit is contained in:
@@ -0,0 +1,255 @@
|
||||
import { Image as ImageIcon, Trash2, Upload } from 'lucide-react';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import DecodeResultPaper from '@/components/DecodeResultPaper';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { downloadBlob, formatFileSize } from '@/utils/base64Converter';
|
||||
import { useStorageState } from '@/utils/useStorageState';
|
||||
import type { Base64ConvertDirection } from '@/types/storage';
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
import { useBase64Converter } from './useBase64Converter';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const isValidDirection = (val: unknown): val is Base64ConvertDirection =>
|
||||
val === 'encode' || val === 'decode';
|
||||
|
||||
interface Base64ConverterSectionProps {
|
||||
mode: 'file' | 'image';
|
||||
}
|
||||
|
||||
export default function Base64ConverterSection({ mode }: Base64ConverterSectionProps) {
|
||||
const { t } = useTranslation('base64Converter');
|
||||
|
||||
const [direction, setDirection] = useStorageState(
|
||||
`base64Converter/${mode}Mode/direction`,
|
||||
'encode',
|
||||
isValidDirection,
|
||||
);
|
||||
|
||||
const {
|
||||
result,
|
||||
info,
|
||||
isLoading,
|
||||
isDragging,
|
||||
setIsDragging,
|
||||
fileInputRef,
|
||||
encodeError,
|
||||
decodeInput,
|
||||
setDecodeInput,
|
||||
decoded,
|
||||
decodeError,
|
||||
decodedFileName,
|
||||
setCustomFileName,
|
||||
resetAll,
|
||||
safeFileSelect,
|
||||
maxFileSizeStr,
|
||||
} = useBase64Converter({ mode });
|
||||
|
||||
const handleDirectionChange = (next: Base64ConvertDirection) => {
|
||||
if (!next || next === direction) return;
|
||||
resetAll();
|
||||
setDirection(next);
|
||||
};
|
||||
|
||||
const handleDownload = () => {
|
||||
if (decoded) downloadBlob(decoded.blob, decodedFileName);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-full flex flex-col space-y-4 animate-in fade-in duration-300">
|
||||
<div className="flex h-11 items-center px-1.5 bg-secondary/40 rounded-xl border border-border/60 w-fit">
|
||||
<SwitchButtonGroup
|
||||
value={direction}
|
||||
options={[
|
||||
{ value: 'encode', label: t('encode') },
|
||||
{ value: 'decode', label: t('decode') },
|
||||
]}
|
||||
onChange={handleDirectionChange}
|
||||
size="small"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{direction === 'encode' ? (
|
||||
<div className="flex flex-col space-y-4">
|
||||
<div
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(true);
|
||||
}}
|
||||
onDragLeave={() => setIsDragging(false)}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(false);
|
||||
const file = e.dataTransfer.files[0];
|
||||
if (file) safeFileSelect(file);
|
||||
}}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className={cn(
|
||||
'flex flex-col items-center justify-center min-h-[190px] border-2 border-dashed rounded-2xl p-8 cursor-pointer transition-all duration-300',
|
||||
isDragging
|
||||
? 'border-primary bg-primary/10'
|
||||
: info
|
||||
? 'border-primary/60 bg-primary/5'
|
||||
: 'border-border bg-muted/40 hover:border-primary/80 hover:bg-muted/70',
|
||||
)}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept={mode === 'image' ? 'image/*' : undefined}
|
||||
hidden
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) safeFileSelect(file);
|
||||
}}
|
||||
/>
|
||||
{isLoading ? (
|
||||
<div className="w-9 h-9 border-3 border-primary/20 border-t-primary rounded-full animate-spin" />
|
||||
) : info ? (
|
||||
<div className="flex flex-col items-center gap-1.5 text-center w-full animate-in fade-in duration-200">
|
||||
{mode === 'image' && result && (
|
||||
<div className="relative p-1 border border-border bg-background rounded-lg shadow-sm mb-1 max-w-[180px] overflow-hidden">
|
||||
<img
|
||||
src={result.output}
|
||||
alt="preview"
|
||||
className="max-h-32 w-full object-contain rounded"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Upload
|
||||
className={cn('w-8 h-8 text-primary', mode === 'file' && 'animate-bounce')}
|
||||
/>
|
||||
<span className="text-sm font-bold text-foreground/90 max-w-[280px] truncate">
|
||||
{info.name}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground/80 font-mono tabular-nums">
|
||||
{formatFileSize(info.size)} · {info.type}
|
||||
</span>
|
||||
<span className="text-[11px] font-medium text-primary/80 mt-1">
|
||||
{t('clickOrDropToReplace')}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center gap-1.5 text-center">
|
||||
{mode === 'image' ? (
|
||||
<ImageIcon className="w-8 h-8 text-muted-foreground/60" />
|
||||
) : (
|
||||
<Upload className="w-8 h-8 text-muted-foreground/60" />
|
||||
)}
|
||||
<span className="text-xs font-bold text-foreground/80">
|
||||
{mode === 'image' ? t('clickOrDropToImage') : t('clickOrDropToFile')}
|
||||
</span>
|
||||
<span className="text-[10px] font-medium text-muted-foreground/60">
|
||||
{t('maxFileSize', { max: maxFileSizeStr })}
|
||||
</span>
|
||||
{mode === 'image' && (
|
||||
<span className="text-[10px] font-medium text-muted-foreground/50">
|
||||
{t('supportedFormats')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{encodeError && (
|
||||
<div className="p-3.5 bg-destructive/10 border border-destructive/20 rounded-xl text-xs font-semibold text-destructive">
|
||||
{encodeError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{result && (
|
||||
<div className="p-4 rounded-2xl bg-card border border-border shadow-sm flex flex-col space-y-3">
|
||||
<div className="flex justify-between items-center select-none">
|
||||
<span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/90">
|
||||
{t('base64Output')}
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<CopyButton
|
||||
text={result.rawBase64}
|
||||
tooltip={t('copyRaw')}
|
||||
className="h-6 px-2 rounded-md border text-[10px] font-bold"
|
||||
/>
|
||||
<CopyButton
|
||||
text={result.output}
|
||||
tooltip={t('copyDataUri')}
|
||||
className="h-6 px-2 rounded-md border text-[10px] font-bold"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<TextInputArea
|
||||
readOnly
|
||||
value={
|
||||
result.output.length > 2000
|
||||
? `${result.output.substring(0, 2000)}...`
|
||||
: result.output
|
||||
}
|
||||
showClear={false}
|
||||
minRows={4}
|
||||
/>
|
||||
<div className="flex items-center justify-between font-mono text-[10px] text-muted-foreground/70 select-none pt-1">
|
||||
<div className="flex gap-4 items-center tabular-nums">
|
||||
<span>
|
||||
{t('originalSize')}:{' '}
|
||||
<span className="font-semibold text-foreground/80">
|
||||
{formatFileSize(result.originalBytes)}
|
||||
</span>
|
||||
</span>
|
||||
<span className="text-border/60">|</span>
|
||||
<span>
|
||||
{t('encodedSize')}:{' '}
|
||||
<span className="font-semibold text-foreground/80">
|
||||
{formatFileSize(result.outputBytes)}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={resetAll}
|
||||
className="h-7 rounded-md text-muted-foreground hover:text-destructive text-[11px] gap-1 px-2"
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
{t('clear')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col space-y-4">
|
||||
<TextInputArea
|
||||
placeholder={t('decodeBase64Placeholder')}
|
||||
value={decodeInput}
|
||||
onChange={setDecodeInput}
|
||||
externalError={decodeError || undefined}
|
||||
showClear={true}
|
||||
allowCopy={true}
|
||||
minRows={6}
|
||||
onClear={resetAll}
|
||||
/>
|
||||
{decoded && (
|
||||
<DecodeResultPaper
|
||||
title={mode === 'image' ? t('decodedImageOutput') : t('decodedFileOutput')}
|
||||
mimeType={decoded.mimeType}
|
||||
blobSize={decoded.blob.size}
|
||||
fileName={decodedFileName}
|
||||
onFileNameChange={setCustomFileName}
|
||||
onDownload={handleDownload}
|
||||
>
|
||||
{mode === 'image' && (
|
||||
<div className="relative p-1.5 border border-border bg-background dark:bg-muted/10 rounded-xl max-w-[220px] mb-3 overflow-hidden shadow-sm">
|
||||
<img
|
||||
src={`data:${decoded.mimeType};base64,${decoded.rawBase64}`}
|
||||
alt="decoded preview"
|
||||
className="max-h-40 w-full rounded-lg object-contain bg-[linear-gradient(45deg,#ccc_25%,transparent_25%),linear-gradient(-45deg,#ccc_25%,transparent_25%),linear-gradient(45deg,transparent_75%,#ccc_75%),linear-gradient(-45deg,transparent_75%,#ccc_75%)] bg-[size:10px_10px] bg-[position:0_0,0_5px,5px_-5px,-5px_0] dark:bg-none"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</DecodeResultPaper>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+142
-276
@@ -1,43 +1,15 @@
|
||||
import { useCallback, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
alpha,
|
||||
Box,
|
||||
Button,
|
||||
CircularProgress,
|
||||
Paper,
|
||||
Stack,
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
import { Trash2, Upload } from 'lucide-react';
|
||||
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 { Button } from '@/components/ui/button';
|
||||
import { downloadBlob, formatFileSize, MAX_FILE_SIZE } 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',
|
||||
};
|
||||
import { useBase64Converter } from './useBase64Converter'; // 💡 斩断重复代码
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const isValidDirection = (val: unknown): val is Base64ConvertDirection =>
|
||||
val === 'encode' || val === 'decode';
|
||||
@@ -50,167 +22,70 @@ export default function FileMode() {
|
||||
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 {
|
||||
result,
|
||||
info,
|
||||
isLoading,
|
||||
isDragging,
|
||||
setIsDragging,
|
||||
fileInputRef,
|
||||
encodeError,
|
||||
decodeInput,
|
||||
setDecodeInput,
|
||||
decoded,
|
||||
decodeError,
|
||||
decodedFileName,
|
||||
setCustomFileName,
|
||||
resetAll,
|
||||
safeFileSelect,
|
||||
} = useBase64Converter({ mode: 'file' });
|
||||
|
||||
const handleDownload = () => {
|
||||
if (!decoded) return;
|
||||
downloadBlob(decoded.blob, decodedFileName || `decoded${decoded.suggestedExtension}`);
|
||||
if (decoded) downloadBlob(decoded.blob, decodedFileName);
|
||||
};
|
||||
|
||||
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"
|
||||
/>
|
||||
<div className="w-full flex flex-col space-y-4 animate-in fade-in duration-300">
|
||||
<div className="flex h-11 items-center px-1.5 bg-secondary/40 rounded-xl border border-border/60 w-fit">
|
||||
<SwitchButtonGroup
|
||||
value={direction}
|
||||
options={[
|
||||
{ value: 'encode', label: t('encode') },
|
||||
{ value: 'decode', label: t('decode') },
|
||||
]}
|
||||
onChange={(next) => {
|
||||
if (next && next !== direction) {
|
||||
resetAll();
|
||||
setDirection(next);
|
||||
}
|
||||
}}
|
||||
size="small"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{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),
|
||||
},
|
||||
{direction === 'encode' ? (
|
||||
<div className="flex flex-col space-y-4">
|
||||
<div
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(true);
|
||||
}}
|
||||
onDragLeave={() => setIsDragging(false)}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(false);
|
||||
const file = e.dataTransfer.files[0];
|
||||
if (file) safeFileSelect(file);
|
||||
}}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className={cn(
|
||||
'flex flex-col items-center justify-center min-h-[190px] border-2 border-dashed rounded-2xl p-8 cursor-pointer transition-all duration-300',
|
||||
isDragging
|
||||
? 'border-primary bg-primary/10'
|
||||
: info
|
||||
? 'border-primary/60 bg-primary/5'
|
||||
: 'border-border bg-muted/40 hover:border-primary/80 hover:bg-muted/70',
|
||||
)}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
@@ -218,64 +93,65 @@ export default function FileMode() {
|
||||
hidden
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) handleFileSelect(file);
|
||||
if (file) safeFileSelect(file);
|
||||
}}
|
||||
/>
|
||||
{isLoading ? (
|
||||
<CircularProgress size={40} />
|
||||
<div className="w-9 h-9 border-3 border-primary/20 border-t-primary rounded-full animate-spin" />
|
||||
) : info ? (
|
||||
<Stack spacing={1} alignItems="center">
|
||||
<UploadFileIcon sx={{ fontSize: 40, color: 'info.main' }} />
|
||||
<Typography variant="body2" fontWeight={700}>
|
||||
<div className="flex flex-col items-center gap-1.5 text-center">
|
||||
<Upload className="w-8 h-8 text-primary animate-bounce" />
|
||||
<span className="text-sm font-bold text-foreground/90 max-w-[280px] truncate">
|
||||
{info.name}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground/80 font-mono tabular-nums">
|
||||
{formatFileSize(info.size)} · {info.type}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.disabled">
|
||||
</span>
|
||||
<span className="text-[11px] font-medium text-primary/80 mt-1">
|
||||
{t('clickOrDropToReplace')}
|
||||
</Typography>
|
||||
</Stack>
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<Stack spacing={1} alignItems="center">
|
||||
<UploadFileIcon sx={{ fontSize: 40, color: 'text.disabled' }} />
|
||||
<Typography variant="body2" color="text.secondary" fontWeight={600}>
|
||||
<div className="flex flex-col items-center gap-1.5 text-center">
|
||||
<Upload className="w-8 h-8 text-muted-foreground/60" />
|
||||
<span className="text-xs font-bold text-foreground/80">
|
||||
{t('clickOrDropToFile')}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.disabled">
|
||||
</span>
|
||||
<span className="text-[10px] font-medium text-muted-foreground/60">
|
||||
{t('maxFileSize', { max: `${MAX_FILE_SIZE / 1024 / 1024} MB` })}
|
||||
</Typography>
|
||||
</Stack>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</Box>
|
||||
</div>
|
||||
|
||||
{error && <Alert severity="error">{error}</Alert>}
|
||||
{encodeError && (
|
||||
<div
|
||||
role="alert"
|
||||
className="p-3.5 bg-destructive/10 border border-destructive/20 rounded-xl text-xs font-semibold text-destructive"
|
||||
>
|
||||
{encodeError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{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">
|
||||
<div className="p-4 rounded-2xl bg-card border border-border shadow-sm flex flex-col space-y-3">
|
||||
<div className="flex justify-between items-center select-none">
|
||||
<span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/90">
|
||||
{t('base64Output')}
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={1}>
|
||||
<CopyButton text={result.rawBase64} tooltip={t('copyRaw')} />
|
||||
<CopyButton text={result.output} tooltip={t('copyDataUri')} color="info" />
|
||||
</Stack>
|
||||
</Stack>
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<CopyButton
|
||||
text={result.rawBase64}
|
||||
tooltip={t('copyRaw')}
|
||||
className="h-6 px-2 rounded-md border text-[10px] font-bold"
|
||||
/>
|
||||
<CopyButton
|
||||
text={result.output}
|
||||
tooltip={t('copyDataUri')}
|
||||
className="h-6 px-2 rounded-md border text-[10px] font-bold"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<TextInputArea
|
||||
readOnly
|
||||
value={
|
||||
@@ -284,71 +160,61 @@ export default function FileMode() {
|
||||
: result.output
|
||||
}
|
||||
showClear={false}
|
||||
showCount
|
||||
minRows={4}
|
||||
/>
|
||||
<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 }} />
|
||||
<div className="flex items-center justify-between font-mono text-[10px] text-muted-foreground/70 select-none pt-1">
|
||||
<div className="flex gap-4 items-center tabular-nums">
|
||||
<span>
|
||||
{t('originalSize')}:{' '}
|
||||
<span className="font-semibold text-foreground/80">
|
||||
{formatFileSize(result.originalBytes)}
|
||||
</span>
|
||||
</span>
|
||||
<span className="text-border/60">|</span>
|
||||
<span>
|
||||
{t('encodedSize')}:{' '}
|
||||
<span className="font-semibold text-foreground/80">
|
||||
{formatFileSize(result.outputBytes)}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="text"
|
||||
size="small"
|
||||
onClick={handleClear}
|
||||
startIcon={<DeleteOutlineIcon />}
|
||||
sx={{ borderRadius: 2, minWidth: 0 }}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={resetAll}
|
||||
className="h-7 rounded-md text-muted-foreground hover:text-destructive text-[11px] gap-1 px-2"
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
{t('clear')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{info && !result && (
|
||||
<Button
|
||||
variant="text"
|
||||
onClick={handleClear}
|
||||
startIcon={<DeleteOutlineIcon />}
|
||||
sx={{ borderRadius: 3 }}
|
||||
>
|
||||
{t('clear')}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{direction === 'decode' && (
|
||||
<>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col space-y-4">
|
||||
<TextInputArea
|
||||
placeholder={t('decodeBase64Placeholder')}
|
||||
value={decodeInput}
|
||||
onChange={(v) => {
|
||||
setDecodeInput(v);
|
||||
setError(null);
|
||||
}}
|
||||
actions={actions}
|
||||
externalError={error || undefined}
|
||||
onClear={() => {
|
||||
setDecoded(null);
|
||||
setDecodedFileName('');
|
||||
}}
|
||||
onChange={setDecodeInput}
|
||||
externalError={decodeError || undefined}
|
||||
showClear={true}
|
||||
allowCopy={true}
|
||||
minRows={6}
|
||||
onClear={resetAll}
|
||||
/>
|
||||
|
||||
{decoded && (
|
||||
<DecodeResultPaper
|
||||
title={t('decodedFileOutput')}
|
||||
mimeType={decoded.mimeType}
|
||||
blobSize={decoded.blob.size}
|
||||
fileName={decodedFileName}
|
||||
onFileNameChange={setDecodedFileName}
|
||||
onFileNameChange={setCustomFileName}
|
||||
onDownload={handleDownload}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+193
-316
@@ -1,44 +1,15 @@
|
||||
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 { Image as ImageIcon, Trash2 } from 'lucide-react';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
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 { Button } from '@/components/ui/button';
|
||||
import { downloadBlob, formatFileSize } 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',
|
||||
};
|
||||
import { useBase64Converter } from './useBase64Converter'; // 💡 引入共享核心
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const isValidDirection = (val: unknown): val is Base64ConvertDirection =>
|
||||
val === 'encode' || val === 'decode';
|
||||
@@ -51,37 +22,24 @@ export default function ImageMode() {
|
||||
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();
|
||||
};
|
||||
// 消费完全托管的核心 Hook,消灭本地多余状态机
|
||||
const {
|
||||
result,
|
||||
info,
|
||||
isLoading,
|
||||
isDragging,
|
||||
setIsDragging,
|
||||
fileInputRef,
|
||||
encodeError,
|
||||
decodeInput,
|
||||
setDecodeInput,
|
||||
decoded,
|
||||
decodeError,
|
||||
decodedFileName,
|
||||
setCustomFileName,
|
||||
resetAll,
|
||||
safeFileSelect,
|
||||
} = useBase64Converter({ mode: 'image' });
|
||||
|
||||
const handleDirectionChange = (next: Base64ConvertDirection) => {
|
||||
if (!next || next === direction) return;
|
||||
@@ -89,294 +47,213 @@ export default function ImageMode() {
|
||||
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}`);
|
||||
if (decoded) downloadBlob(decoded.blob, decodedFileName);
|
||||
};
|
||||
|
||||
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"
|
||||
/>
|
||||
<div className="w-full flex flex-col space-y-4 animate-in fade-in duration-300">
|
||||
<div className="flex h-11 items-center px-1.5 bg-secondary/40 rounded-xl border border-border/60 w-fit">
|
||||
<SwitchButtonGroup
|
||||
value={direction}
|
||||
options={[
|
||||
{ value: 'encode', label: t('encode') },
|
||||
{ value: 'decode', label: t('decode') },
|
||||
]}
|
||||
onChange={handleDirectionChange}
|
||||
size="small"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{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),
|
||||
},
|
||||
{direction === 'encode' ? (
|
||||
<div className="flex flex-col space-y-4">
|
||||
{/* 图片拖拽投递箱终端 */}
|
||||
<div
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(true);
|
||||
}}
|
||||
onDragLeave={() => setIsDragging(false)}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(false);
|
||||
const file = e.dataTransfer.files[0];
|
||||
if (file) safeFileSelect(file);
|
||||
}}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className={cn(
|
||||
'flex flex-col items-center justify-center min-h-[190px] border-2 border-dashed rounded-2xl p-8 cursor-pointer transition-all duration-300',
|
||||
isDragging
|
||||
? 'border-primary bg-primary/10'
|
||||
: info
|
||||
? 'border-primary/60 bg-primary/5'
|
||||
: 'border-border bg-muted/40 hover:border-primary/80 hover:bg-muted/70',
|
||||
)}
|
||||
>
|
||||
<input
|
||||
ref={imageInputRef}
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
hidden
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) handleFileSelect(file);
|
||||
if (file) safeFileSelect(file);
|
||||
}}
|
||||
/>
|
||||
{isLoading ? (
|
||||
<CircularProgress size={40} />
|
||||
<div className="w-9 h-9 border-3 border-primary/20 border-t-primary rounded-full animate-spin" />
|
||||
) : info ? (
|
||||
<Stack spacing={1} alignItems="center">
|
||||
<div className="flex flex-col items-center gap-1.5 text-center animate-in fade-in duration-200 w-full">
|
||||
{result && (
|
||||
<Box
|
||||
component="img"
|
||||
src={result.output}
|
||||
alt="preview"
|
||||
sx={{
|
||||
maxWidth: '100%',
|
||||
maxHeight: 160,
|
||||
borderRadius: 2,
|
||||
objectFit: 'contain',
|
||||
}}
|
||||
/>
|
||||
<div className="relative p-1 border border-border bg-background rounded-lg shadow-sm mb-1 max-w-[180px] overflow-hidden">
|
||||
<img
|
||||
src={result.output}
|
||||
alt="preview"
|
||||
className="max-h-32 w-full object-contain rounded"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Typography variant="body2" fontWeight={700}>
|
||||
<span className="text-sm font-bold text-foreground/90 max-w-[280px] truncate">
|
||||
{info.name}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground/80 font-mono tabular-nums">
|
||||
{formatFileSize(info.size)} · {info.type}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.disabled">
|
||||
</span>
|
||||
<span className="text-[11px] font-medium text-primary/80 mt-1">
|
||||
{t('clickOrDropToReplace')}
|
||||
</Typography>
|
||||
</Stack>
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<Stack spacing={1} alignItems="center">
|
||||
<ImageIcon sx={{ fontSize: 40, color: 'text.disabled' }} />
|
||||
<Typography variant="body2" color="text.secondary" fontWeight={600}>
|
||||
<div className="flex flex-col items-center gap-1.5 text-center">
|
||||
<ImageIcon className="w-8 h-8 text-muted-foreground/60" />
|
||||
<span className="text-xs font-bold text-foreground/80">
|
||||
{t('clickOrDropToImage')}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.disabled">
|
||||
</span>
|
||||
<span className="text-[10px] font-medium text-muted-foreground/60">
|
||||
{t('supportedFormats')}
|
||||
</Typography>
|
||||
</Stack>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</Box>
|
||||
</div>
|
||||
|
||||
{error && <Alert severity="error">{error}</Alert>}
|
||||
{encodeError && (
|
||||
<div
|
||||
role="alert"
|
||||
className="p-3.5 bg-destructive/10 border border-destructive/20 rounded-xl text-xs font-semibold text-destructive tracking-wide"
|
||||
>
|
||||
{encodeError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{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">
|
||||
<div className="p-4 rounded-2xl bg-card border border-border shadow-sm flex flex-col space-y-3">
|
||||
<div className="flex justify-between items-center select-none">
|
||||
<span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/90">
|
||||
{t('base64Output')}
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={1}>
|
||||
<CopyButton text={result.rawBase64} tooltip={t('copyRaw')} />
|
||||
<CopyButton text={result.output} tooltip={t('copyDataUri')} color="info" />
|
||||
</Stack>
|
||||
</Stack>
|
||||
<Box
|
||||
sx={{
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.75rem',
|
||||
wordBreak: 'break-all',
|
||||
maxHeight: 200,
|
||||
overflowY: 'auto',
|
||||
lineHeight: 1.6,
|
||||
color: 'info.main',
|
||||
fontWeight: 600,
|
||||
}}
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<CopyButton
|
||||
text={result.rawBase64}
|
||||
tooltip={t('copyRaw')}
|
||||
className="h-6 px-2 rounded-md border text-[10px] font-bold"
|
||||
/>
|
||||
<CopyButton
|
||||
text={result.output}
|
||||
tooltip={t('copyDataUri')}
|
||||
className="h-6 px-2 rounded-md border text-[10px] font-bold"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TextInputArea
|
||||
readOnly
|
||||
value={
|
||||
result.output.length > 2000
|
||||
? `${result.output.substring(0, 2000)}...`
|
||||
: result.output
|
||||
}
|
||||
showClear={false}
|
||||
minRows={4}
|
||||
/>
|
||||
|
||||
<div className="flex items-center justify-between font-mono text-[10px] text-muted-foreground/70 select-none pt-1">
|
||||
<div className="flex gap-4 items-center tabular-nums">
|
||||
<span>
|
||||
{t('originalSize')}:{' '}
|
||||
<span className="font-semibold text-foreground/80">
|
||||
{formatFileSize(result.originalBytes)}
|
||||
</span>
|
||||
</span>
|
||||
<span className="text-border/60">|</span>
|
||||
<span>
|
||||
{t('encodedSize')}:{' '}
|
||||
<span className="font-semibold text-foreground/80">
|
||||
{formatFileSize(result.outputBytes)}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={resetAll}
|
||||
className="h-7 rounded-md text-muted-foreground hover:text-destructive text-[11px] gap-1 px-2"
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
{t('clear')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{info && !result && (
|
||||
<div className="flex justify-end select-none">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={resetAll}
|
||||
className="h-8 rounded-md text-xs gap-1.5 text-destructive hover:text-destructive hover:bg-destructive/5 dark:hover:bg-destructive/10"
|
||||
>
|
||||
{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>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
{t('clear')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{info && (
|
||||
<Button
|
||||
variant="text"
|
||||
onClick={handleClear}
|
||||
startIcon={<DeleteOutlineIcon />}
|
||||
sx={{ borderRadius: 3 }}
|
||||
>
|
||||
{t('clear')}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{direction === 'decode' && (
|
||||
<>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col space-y-4">
|
||||
<TextInputArea
|
||||
placeholder={t('decodeBase64Placeholder')}
|
||||
value={decodeInput}
|
||||
onChange={(v) => {
|
||||
setDecodeInput(v);
|
||||
setError(null);
|
||||
}}
|
||||
actions={actions}
|
||||
externalError={error || undefined}
|
||||
onClear={() => {
|
||||
setDecoded(null);
|
||||
setDecodedFileName('');
|
||||
}}
|
||||
onChange={setDecodeInput}
|
||||
externalError={decodeError || undefined}
|
||||
showClear={true}
|
||||
allowCopy={true}
|
||||
minRows={6}
|
||||
onClear={resetAll}
|
||||
/>
|
||||
|
||||
{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>
|
||||
<div className="animate-in slide-in-from-bottom-2 duration-300">
|
||||
<DecodeResultPaper
|
||||
title={t('decodedImageOutput')}
|
||||
mimeType={decoded.mimeType}
|
||||
blobSize={decoded.blob.size}
|
||||
fileName={decodedFileName}
|
||||
onFileNameChange={setCustomFileName}
|
||||
onDownload={handleDownload}
|
||||
>
|
||||
<div className="relative p-1.5 border border-border bg-background dark:bg-muted/10 rounded-xl max-w-[220px] mb-3 overflow-hidden shadow-sm">
|
||||
<img
|
||||
src={`data:${decoded.mimeType};base64,${decoded.rawBase64}`}
|
||||
alt="decoded preview"
|
||||
className="max-h-40 w-full rounded-lg object-contain bg-[linear-gradient(45deg,#ccc_25%,transparent_25%),linear-gradient(-45deg,#ccc_25%,transparent_25%),linear-gradient(45deg,transparent_75%,#ccc_75%),linear-gradient(-45deg,transparent_75%,#ccc_75%)] bg-[size:10px_10px] bg-[position:0_0,0_5px,5px_-5px,-5px_0] dark:bg-none"
|
||||
/>
|
||||
</div>
|
||||
</DecodeResultPaper>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+111
-107
@@ -1,12 +1,11 @@
|
||||
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 { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import { textToBase64, base64ToText } from '@/utils/base64Converter';
|
||||
import { base64ToText, textToBase64 } from '@/utils/base64Converter';
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
import { useContextMenuData } from '@/utils/useContextMenuData';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
const IMAGE_DATA_URI_PATTERN = /^\s*data:image\//i;
|
||||
|
||||
@@ -22,31 +21,56 @@ interface TextModeProps {
|
||||
|
||||
export default function TextMode({ onSwitchToImageMode }: TextModeProps = {}) {
|
||||
const { t } = useTranslation('base64Converter');
|
||||
|
||||
// 1. 纯净的核心源状态机:只保留输入源和转换方向
|
||||
const [input, setInput] = useState('');
|
||||
const [output, setOutput] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [debouncedInput, setDebouncedInput] = useState('');
|
||||
const [direction, setDirection] = useState<'encode' | 'decode'>('encode');
|
||||
|
||||
const handleContextMenuData = useCallback(
|
||||
(payload: string) => {
|
||||
setInput(payload);
|
||||
setDirection('decode');
|
||||
setError(null);
|
||||
try {
|
||||
const decoded = base64ToText(payload);
|
||||
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'));
|
||||
}
|
||||
},
|
||||
[t],
|
||||
);
|
||||
// 2. 文本高频敲击防抖大闸:斩断频繁进行文本转 Base64 带来的 CPU 计算过热
|
||||
useEffect(() => {
|
||||
const handle = setTimeout(() => {
|
||||
setDebouncedInput(input);
|
||||
}, 200);
|
||||
return () => clearTimeout(handle);
|
||||
}, [input]);
|
||||
|
||||
// 3. 右键联动数据上下文:优雅原地合并受控状态
|
||||
const handleContextMenuData = useCallback((payload: string) => {
|
||||
setInput(payload);
|
||||
setDebouncedInput(payload);
|
||||
setDirection('decode');
|
||||
}, []);
|
||||
|
||||
useContextMenuData({ featureKey: 'base64Converter', onData: handleContextMenuData });
|
||||
|
||||
const actionLabel = direction === 'encode' ? t('encode') : t('decode');
|
||||
// 💡 4. 贯彻方案 A(彻底消灭 setOutput / setError):
|
||||
// 让所有的转化逻辑、类型安全校验在 useMemo 内存管道中单次渲染一气呵成!
|
||||
const conversionPipeline = useMemo(() => {
|
||||
const trimmed = debouncedInput.trim();
|
||||
if (!trimmed) return { output: '', error: null };
|
||||
|
||||
try {
|
||||
if (direction === 'encode') {
|
||||
const result = textToBase64(debouncedInput);
|
||||
return { output: result.output, error: null };
|
||||
} else {
|
||||
const decoded = base64ToText(trimmed);
|
||||
return { output: decoded, error: null };
|
||||
}
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : '';
|
||||
const i18nKey = ERROR_MESSAGE_TO_I18N[message];
|
||||
return {
|
||||
output: '',
|
||||
error: i18nKey ? t(i18nKey) : message || t('conversionFailed'),
|
||||
};
|
||||
}
|
||||
}, [debouncedInput, direction, t]);
|
||||
|
||||
const output = conversionPipeline.output;
|
||||
const error = conversionPipeline.error;
|
||||
|
||||
const placeholder =
|
||||
direction === 'encode' ? t('textInputPlaceholder') : t('base64InputPlaceholder');
|
||||
const outputLabel = direction === 'encode' ? t('base64Output') : t('textOutput');
|
||||
@@ -56,108 +80,88 @@ export default function TextMode({ onSwitchToImageMode }: TextModeProps = {}) {
|
||||
[direction, input],
|
||||
);
|
||||
|
||||
const handleDirectionChange = useCallback(
|
||||
(value: 'encode' | 'decode') => {
|
||||
if (value === direction) return;
|
||||
setDirection(value);
|
||||
setOutput('');
|
||||
setError(null);
|
||||
},
|
||||
[direction],
|
||||
);
|
||||
const handleDirectionChange = (value: 'encode' | 'decode') => {
|
||||
if (value === direction) return;
|
||||
setDirection(value);
|
||||
setInput('');
|
||||
setDebouncedInput('');
|
||||
};
|
||||
|
||||
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],
|
||||
);
|
||||
const handleClear = () => {
|
||||
setInput('');
|
||||
setDebouncedInput('');
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<SwitchButtonGroup
|
||||
value={direction}
|
||||
options={[
|
||||
{ value: 'encode', label: t('encode') },
|
||||
{ value: 'decode', label: t('decode') },
|
||||
]}
|
||||
onChange={handleDirectionChange}
|
||||
size="small"
|
||||
/>
|
||||
<div className="w-full flex flex-col space-y-4 animate-in fade-in duration-300">
|
||||
{/* 受控方向切流中枢 */}
|
||||
<div className="flex h-11 items-center px-1.5 bg-secondary/40 rounded-xl border border-border/60 w-fit">
|
||||
<SwitchButtonGroup
|
||||
value={direction}
|
||||
options={[
|
||||
{ value: 'encode', label: t('encode') },
|
||||
{ value: 'decode', label: t('decode') },
|
||||
]}
|
||||
onChange={handleDirectionChange}
|
||||
size="small"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 高性能受控文本输入端 */}
|
||||
<TextInputArea
|
||||
placeholder={placeholder}
|
||||
value={input}
|
||||
onChange={(v) => {
|
||||
setInput(v);
|
||||
setError(null);
|
||||
}}
|
||||
actions={actions}
|
||||
externalError={error || undefined}
|
||||
onClear={() => setOutput('')}
|
||||
onChange={setInput}
|
||||
externalError={error || undefined} // 💡 流式异常大闸动态注入
|
||||
showClear={true}
|
||||
allowCopy={true}
|
||||
minRows={5}
|
||||
maxRows={10}
|
||||
onClear={handleClear}
|
||||
/>
|
||||
|
||||
{/* 图片 URI 类型劫持警告引导区:
|
||||
- 💡 修复点:彻底废除原生亮色硬编码 hover:bg-blue-100 类名,
|
||||
- 完美向全站 shadcn 暗黑生态看齐,采用标准的 bg-primary/10 混合变体。
|
||||
*/}
|
||||
{showImageHint && (
|
||||
<Alert
|
||||
severity="info"
|
||||
action={
|
||||
<Button color="info" size="small" onClick={onSwitchToImageMode}>
|
||||
{t('switchToImageMode')}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{t('imageDataUriHint')}
|
||||
</Alert>
|
||||
<div className="flex items-center justify-between p-3.5 rounded-xl bg-primary/10 border border-primary/20 animate-in slide-in-from-top-1 duration-200">
|
||||
<span className="text-xs font-semibold text-primary tracking-tight">
|
||||
{t('imageDataUriHint')}
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onSwitchToImageMode}
|
||||
className="h-7 rounded-md text-xs font-bold text-primary hover:text-primary hover:bg-primary/20 dark:hover:bg-primary/10 transition-colors px-2.5"
|
||||
>
|
||||
{t('switchToImageMode')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 5. 编码/解码核心数据承载流卡片 */}
|
||||
{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">
|
||||
<div className="p-4 rounded-2xl bg-card border border-border shadow-sm flex flex-col space-y-3 animate-in slide-in-from-bottom-2 duration-300">
|
||||
<div className="flex justify-between items-center select-none">
|
||||
<span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/90">
|
||||
{outputLabel}
|
||||
</Typography>
|
||||
<CopyButton text={output} />
|
||||
</Stack>
|
||||
</span>
|
||||
<CopyButton
|
||||
text={output}
|
||||
className="h-6 px-2 rounded-md border text-[10px] font-bold"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<TextInputArea
|
||||
readOnly
|
||||
value={output.length > 2000 ? `${output.substring(0, 2000)}...` : output}
|
||||
showClear={false}
|
||||
showCount
|
||||
minRows={4}
|
||||
/>
|
||||
</Paper>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import FileMode from '../FileMode';
|
||||
|
||||
// Mock CopyButton
|
||||
@@ -13,6 +13,11 @@ vi.mock('@/components/CopyButton', () => ({
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
// useStorageState's async loadState may overwrite user toggle if we click before the
|
||||
@@ -124,7 +129,7 @@ describe('FileMode', () => {
|
||||
|
||||
it('应该渲染 encode/decode 切换按钮', () => {
|
||||
render(<FileMode />);
|
||||
expect(screen.getAllByText('encode').length).toBeGreaterThanOrEqual(1);
|
||||
expect(screen.getByText('encode')).toBeInTheDocument();
|
||||
expect(screen.getByText('decode')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -143,7 +148,9 @@ describe('FileMode', () => {
|
||||
const input = await screen.findByPlaceholderText('decodeBase64Placeholder');
|
||||
fireEvent.change(input, { target: { value: 'JVBERi0K' } });
|
||||
|
||||
fireEvent.click(screen.getAllByText('decode')[1]);
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(250);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('decodedFileOutput')).toBeInTheDocument();
|
||||
@@ -159,7 +166,10 @@ describe('FileMode', () => {
|
||||
|
||||
const input = await screen.findByPlaceholderText('decodeBase64Placeholder');
|
||||
fireEvent.change(input, { target: { value: 'JVBERi0K' } });
|
||||
fireEvent.click(screen.getAllByText('decode')[1]);
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(250);
|
||||
});
|
||||
|
||||
const filenameInput = (await screen.findByDisplayValue('decoded.pdf')) as HTMLInputElement;
|
||||
fireEvent.change(filenameInput, { target: { value: 'my-report.pdf' } });
|
||||
@@ -173,7 +183,10 @@ describe('FileMode', () => {
|
||||
|
||||
const input = await screen.findByPlaceholderText('decodeBase64Placeholder');
|
||||
fireEvent.change(input, { target: { value: 'JVBERi0K' } });
|
||||
fireEvent.click(screen.getAllByText('decode')[1]);
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(250);
|
||||
});
|
||||
|
||||
expect(await screen.findByText('download')).toBeInTheDocument();
|
||||
});
|
||||
@@ -185,7 +198,10 @@ describe('FileMode', () => {
|
||||
|
||||
const input = await screen.findByPlaceholderText('decodeBase64Placeholder');
|
||||
fireEvent.change(input, { target: { value: '!!!not base64' } });
|
||||
fireEvent.click(screen.getAllByText('decode')[1]);
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(250);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('invalidBase64')).toBeInTheDocument();
|
||||
@@ -199,13 +215,16 @@ describe('FileMode', () => {
|
||||
|
||||
const input = await screen.findByPlaceholderText('decodeBase64Placeholder');
|
||||
fireEvent.change(input, { target: { value: 'JVBERi0K' } });
|
||||
fireEvent.click(screen.getAllByText('decode')[1]);
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(250);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('decodedFileOutput')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getAllByText('encode')[0]);
|
||||
fireEvent.click(screen.getByText('encode'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('decodedFileOutput')).not.toBeInTheDocument();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import ImageMode from '../ImageMode';
|
||||
|
||||
// Mock CopyButton
|
||||
@@ -13,6 +13,11 @@ vi.mock('@/components/CopyButton', () => ({
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
const waitForStorageReady = () => act(() => Promise.resolve());
|
||||
@@ -119,7 +124,7 @@ describe('ImageMode', () => {
|
||||
it('应该渲染 encode/decode 切换按钮', async () => {
|
||||
render(<ImageMode />);
|
||||
await waitForStorageReady();
|
||||
expect(screen.getAllByText('encode').length).toBeGreaterThanOrEqual(1);
|
||||
expect(screen.getByText('encode')).toBeInTheDocument();
|
||||
expect(screen.getByText('decode')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -130,7 +135,10 @@ describe('ImageMode', () => {
|
||||
|
||||
const input = await screen.findByPlaceholderText('decodeBase64Placeholder');
|
||||
fireEvent.change(input, { target: { value: 'iVBORw0KGgo=' } });
|
||||
fireEvent.click(screen.getAllByText('decode')[1]);
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(250);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('decodedImageOutput')).toBeInTheDocument();
|
||||
@@ -147,7 +155,10 @@ describe('ImageMode', () => {
|
||||
|
||||
const input = await screen.findByPlaceholderText('decodeBase64Placeholder');
|
||||
fireEvent.change(input, { target: { value: 'iVBORw0KGgo=' } });
|
||||
fireEvent.click(screen.getAllByText('decode')[1]);
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(250);
|
||||
});
|
||||
|
||||
expect(await screen.findByDisplayValue('decoded.png')).toBeInTheDocument();
|
||||
});
|
||||
@@ -159,7 +170,10 @@ describe('ImageMode', () => {
|
||||
|
||||
const input = await screen.findByPlaceholderText('decodeBase64Placeholder');
|
||||
fireEvent.change(input, { target: { value: '!!!not base64' } });
|
||||
fireEvent.click(screen.getAllByText('decode')[1]);
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(250);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('invalidBase64')).toBeInTheDocument();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import TextMode from '../TextMode';
|
||||
|
||||
// Mock CopyButton
|
||||
@@ -8,9 +8,17 @@ vi.mock('@/components/CopyButton', () => ({
|
||||
}));
|
||||
|
||||
describe('TextMode', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('应该渲染编码/解码切换按钮', () => {
|
||||
render(<TextMode />);
|
||||
expect(screen.getAllByText('encode').length).toBeGreaterThanOrEqual(1);
|
||||
expect(screen.getByText('encode')).toBeInTheDocument();
|
||||
expect(screen.getByText('decode')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -24,13 +32,13 @@ describe('TextMode', () => {
|
||||
const input = screen.getByPlaceholderText('textInputPlaceholder');
|
||||
fireEvent.change(input, { target: { value: 'Hello' } });
|
||||
|
||||
const convertBtn = screen.getAllByText('encode')[1];
|
||||
fireEvent.click(convertBtn);
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('base64Output')).toBeInTheDocument();
|
||||
});
|
||||
// 输出内容在 CopyButton 的 data-testid 中
|
||||
expect(screen.getByTestId('copy-button')).toHaveTextContent('SGVsbG8=');
|
||||
});
|
||||
|
||||
@@ -43,8 +51,9 @@ describe('TextMode', () => {
|
||||
const input = screen.getByPlaceholderText('base64InputPlaceholder');
|
||||
fireEvent.change(input, { target: { value: 'SGVsbG8=' } });
|
||||
|
||||
const convertBtn = screen.getAllByText('decode')[1];
|
||||
fireEvent.click(convertBtn);
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('textOutput')).toBeInTheDocument();
|
||||
@@ -61,8 +70,9 @@ describe('TextMode', () => {
|
||||
const input = screen.getByPlaceholderText('base64InputPlaceholder');
|
||||
fireEvent.change(input, { target: { value: 'invalid!!!' } });
|
||||
|
||||
const convertBtn = screen.getAllByText('decode')[1];
|
||||
fireEvent.click(convertBtn);
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('invalidBase64')).toBeInTheDocument();
|
||||
@@ -75,16 +85,17 @@ describe('TextMode', () => {
|
||||
// 先编码
|
||||
const input = screen.getByPlaceholderText('textInputPlaceholder');
|
||||
fireEvent.change(input, { target: { value: 'Hello' } });
|
||||
fireEvent.click(screen.getAllByText('encode')[1]);
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('copy-button')).toHaveTextContent('SGVsbG8=');
|
||||
});
|
||||
|
||||
// 切换方向
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByText('decode'));
|
||||
});
|
||||
fireEvent.click(screen.getByText('decode'));
|
||||
|
||||
// 输出应该被清除
|
||||
await waitFor(() => {
|
||||
@@ -97,7 +108,10 @@ describe('TextMode', () => {
|
||||
|
||||
const input = screen.getByPlaceholderText('textInputPlaceholder');
|
||||
fireEvent.change(input, { target: { value: 'Hello' } });
|
||||
fireEvent.click(screen.getAllByText('encode')[1]);
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('copy-button')).toHaveTextContent('SGVsbG8=');
|
||||
@@ -111,20 +125,6 @@ describe('TextMode', () => {
|
||||
});
|
||||
});
|
||||
|
||||
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 />);
|
||||
|
||||
@@ -172,8 +172,9 @@ describe('TextMode', () => {
|
||||
const input = screen.getByPlaceholderText('base64InputPlaceholder');
|
||||
fireEvent.change(input, { target: { value: 'iVBORw0KGgo=' } });
|
||||
|
||||
const convertBtn = screen.getAllByText('decode')[1];
|
||||
fireEvent.click(convertBtn);
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('binaryDataDetected')).toBeInTheDocument();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import Base64ConverterPage from '../index';
|
||||
|
||||
// Mock useLazyTranslation
|
||||
@@ -22,46 +22,61 @@ vi.mock('@/config/features', async (importOriginal) => {
|
||||
|
||||
// Mock 子组件
|
||||
vi.mock('../TextMode', () => ({
|
||||
default: () => <div data-testid="text-mode">TextMode</div>,
|
||||
default: ({ onSwitchToImageMode }: { onSwitchToImageMode?: () => void }) => (
|
||||
<div data-testid="text-mode">
|
||||
TextMode
|
||||
{onSwitchToImageMode && <button onClick={onSwitchToImageMode}>switchToImage</button>}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock('../FileMode', () => ({
|
||||
default: () => <div data-testid="file-mode">FileMode</div>,
|
||||
vi.mock('../Base64ConverterSection', () => ({
|
||||
default: ({ mode }: { mode: string }) => <div data-testid={`${mode}-mode`}>{mode}</div>,
|
||||
}));
|
||||
|
||||
vi.mock('../ImageMode', () => ({
|
||||
default: () => <div data-testid="image-mode">ImageMode</div>,
|
||||
}));
|
||||
const waitForStorageInit = () =>
|
||||
act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
describe('Base64ConverterPage', () => {
|
||||
it('应该默认渲染文本模式', () => {
|
||||
it('应该默认渲染文本模式', async () => {
|
||||
render(<Base64ConverterPage />);
|
||||
await waitForStorageInit();
|
||||
expect(screen.getByTestId('text-mode')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('应该渲染模式切换按钮', () => {
|
||||
it('应该渲染模式切换按钮', async () => {
|
||||
render(<Base64ConverterPage />);
|
||||
await waitForStorageInit();
|
||||
expect(screen.getByText('base64Converter:textMode')).toBeInTheDocument();
|
||||
expect(screen.getByText('base64Converter:fileMode')).toBeInTheDocument();
|
||||
expect(screen.getByText('base64Converter:imageMode')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('切换到文件模式应该渲染 FileMode', () => {
|
||||
it('切换到文件模式应该渲染 FileMode', async () => {
|
||||
render(<Base64ConverterPage />);
|
||||
await waitForStorageInit();
|
||||
fireEvent.click(screen.getByText('base64Converter:fileMode'));
|
||||
expect(screen.getByTestId('file-mode')).toBeInTheDocument();
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('file-mode')).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.queryByTestId('text-mode')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('切换到图像模式应该渲染 ImageMode', () => {
|
||||
it('切换到图像模式应该渲染 ImageMode', async () => {
|
||||
render(<Base64ConverterPage />);
|
||||
await waitForStorageInit();
|
||||
fireEvent.click(screen.getByText('base64Converter:imageMode'));
|
||||
expect(screen.getByTestId('image-mode')).toBeInTheDocument();
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('image-mode')).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.queryByTestId('text-mode')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('应该渲染页面标题', () => {
|
||||
it('应该渲染页面标题', async () => {
|
||||
render(<Base64ConverterPage />);
|
||||
await waitForStorageInit();
|
||||
expect(screen.getByText('base64Converter:pageTitle')).toBeInTheDocument();
|
||||
expect(screen.getByText('base64Converter:pageSubtitle')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -1,19 +1,14 @@
|
||||
import { Box, Container, Stack } from '@mui/material';
|
||||
import TextFieldsIcon from '@mui/icons-material/TextFields';
|
||||
import UploadFileIcon from '@mui/icons-material/UploadFile';
|
||||
import ImageIcon from '@mui/icons-material/Image';
|
||||
import { Image as ImageIcon, Type, Upload } from 'lucide-react';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import PageHeader from '@/components/PageHeader';
|
||||
import { base64ConverterPageStyles } from '@/config/pageTheme';
|
||||
import { useStorageState } from '@/utils/useStorageState';
|
||||
import type { Base64ConverterPageMode } from '@/types/storage';
|
||||
import TextMode from './TextMode';
|
||||
import FileMode from './FileMode';
|
||||
import ImageMode from './ImageMode';
|
||||
import Base64ConverterSection from './Base64ConverterSection'; // ✅ 正确对接全新的一体化大组件
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
|
||||
const VALID_PAGE_MODES: readonly Base64ConverterPageMode[] = ['text', 'file', 'image'];
|
||||
|
||||
const isValidPageMode = (val: unknown): val is Base64ConverterPageMode =>
|
||||
typeof val === 'string' && (VALID_PAGE_MODES as readonly string[]).includes(val);
|
||||
|
||||
@@ -28,38 +23,38 @@ export default function Index() {
|
||||
);
|
||||
|
||||
const modeIcon: Record<PageMode, React.ReactNode> = {
|
||||
text: <TextFieldsIcon />,
|
||||
file: <UploadFileIcon />,
|
||||
image: <ImageIcon />,
|
||||
text: <Type className="h-4 w-4" />,
|
||||
file: <Upload className="h-4 w-4" />,
|
||||
image: <ImageIcon className="h-4 w-4" />,
|
||||
};
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Container sx={{ p: 2 }}>
|
||||
<PageHeader
|
||||
title={t('base64Converter:pageTitle')}
|
||||
subtitle={t('base64Converter:pageSubtitle')}
|
||||
icon={modeIcon[pageMode]}
|
||||
iconColor={base64ConverterPageStyles.primaryColor}
|
||||
/>
|
||||
<div className="p-4 w-full flex flex-col space-y-4 min-h-[520px] select-none animate-in fade-in duration-300">
|
||||
<PageHeader
|
||||
title={t('base64Converter:pageTitle')}
|
||||
subtitle={t('base64Converter:pageSubtitle')}
|
||||
icon={modeIcon[pageMode]}
|
||||
iconColor={base64ConverterPageStyles.primaryColor}
|
||||
className="pb-1"
|
||||
/>
|
||||
|
||||
<Stack spacing={2.5}>
|
||||
<SwitchButtonGroup
|
||||
value={pageMode}
|
||||
options={[
|
||||
{ value: 'text', label: t('base64Converter:textMode') },
|
||||
{ value: 'file', label: t('base64Converter:fileMode') },
|
||||
{ value: 'image', label: t('base64Converter:imageMode') },
|
||||
]}
|
||||
onChange={(value: PageMode) => setPageMode(value)}
|
||||
size="small"
|
||||
/>
|
||||
<SwitchButtonGroup
|
||||
value={pageMode}
|
||||
options={[
|
||||
{ value: 'text', label: t('base64Converter:textMode') },
|
||||
{ value: 'file', label: t('base64Converter:fileMode') },
|
||||
{ value: 'image', label: t('base64Converter:imageMode') },
|
||||
]}
|
||||
onChange={(value: PageMode) => setPageMode(value)}
|
||||
size="small"
|
||||
className="w-full sm:w-auto"
|
||||
/>
|
||||
|
||||
{pageMode === 'text' && <TextMode onSwitchToImageMode={() => setPageMode('image')} />}
|
||||
{pageMode === 'file' && <FileMode />}
|
||||
{pageMode === 'image' && <ImageMode />}
|
||||
</Stack>
|
||||
</Container>
|
||||
</Box>
|
||||
<div className="w-full pt-1">
|
||||
{pageMode === 'text' && <TextMode onSwitchToImageMode={() => setPageMode('image')} />}
|
||||
{pageMode === 'file' && <Base64ConverterSection mode="file" />}
|
||||
{pageMode === 'image' && <Base64ConverterSection mode="image" />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { FileToBase64Result } from '@/utils/base64Converter';
|
||||
import {
|
||||
base64ToBlob,
|
||||
fileToBase64,
|
||||
isFileSizeValid,
|
||||
isSupportedImageExtension,
|
||||
isSupportedImageType,
|
||||
MAX_FILE_SIZE,
|
||||
} from '@/utils/base64Converter';
|
||||
|
||||
interface FileInfo {
|
||||
name: string;
|
||||
size: number;
|
||||
type: string;
|
||||
}
|
||||
|
||||
interface UseBase64ConverterProps {
|
||||
mode: 'file' | 'image';
|
||||
}
|
||||
|
||||
export function useBase64Converter({ mode }: UseBase64ConverterProps) {
|
||||
const { t } = useTranslation('base64Converter');
|
||||
|
||||
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);
|
||||
|
||||
const [decodeInput, setDecodeInput] = useState('');
|
||||
const [debouncedDecodeInput, setDebouncedDecodeInput] = useState('');
|
||||
const [encodeError, setEncodeError] = useState<string | null>(null);
|
||||
const [customFileName, setCustomFileName] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
const handle = setTimeout(() => {
|
||||
setDebouncedDecodeInput(decodeInput);
|
||||
}, 250);
|
||||
return () => clearTimeout(handle);
|
||||
}, [decodeInput]);
|
||||
|
||||
const resetAll = useCallback(() => {
|
||||
cancelRef.current = true;
|
||||
setResult(null);
|
||||
setInfo(null);
|
||||
setIsLoading(false);
|
||||
setDecodeInput('');
|
||||
setDebouncedDecodeInput('');
|
||||
setCustomFileName('');
|
||||
setEncodeError(null);
|
||||
if (fileInputRef.current) fileInputRef.current.value = '';
|
||||
}, []);
|
||||
|
||||
const handleFileSelect = useCallback(
|
||||
async (file: File) => {
|
||||
cancelRef.current = false;
|
||||
setEncodeError(null);
|
||||
setResult(null);
|
||||
setInfo(null);
|
||||
|
||||
if (!isFileSizeValid(file.size)) {
|
||||
setEncodeError(t('fileSizeExceeded', { max: `${MAX_FILE_SIZE / 1024 / 1024} MB` }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
mode === 'image' &&
|
||||
!isSupportedImageType(file.type) &&
|
||||
!isSupportedImageExtension(file.name)
|
||||
) {
|
||||
setEncodeError(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) {
|
||||
setEncodeError(e instanceof Error ? e.message : t('conversionFailed'));
|
||||
}
|
||||
} finally {
|
||||
if (!cancelRef.current) setIsLoading(false);
|
||||
}
|
||||
},
|
||||
[mode, t],
|
||||
);
|
||||
|
||||
const safeFileSelect = useCallback(
|
||||
(file: File) => {
|
||||
handleFileSelect(file).catch((err) => {
|
||||
console.error(`Base64 [${mode}] pipeline crash:`, err);
|
||||
});
|
||||
},
|
||||
[handleFileSelect, mode],
|
||||
);
|
||||
|
||||
const decodePipeline = useMemo(() => {
|
||||
const cleanedInput = debouncedDecodeInput.replace(/^data:image\/[a-z+]+;base64,/i, '').trim();
|
||||
if (!cleanedInput) return { decoded: null, error: null };
|
||||
|
||||
try {
|
||||
const res = base64ToBlob(cleanedInput);
|
||||
return { decoded: res, error: null };
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : '';
|
||||
return {
|
||||
decoded: null,
|
||||
error: message === 'Invalid Base64 string' ? t('invalidBase64') : t('conversionFailed'),
|
||||
};
|
||||
}
|
||||
}, [debouncedDecodeInput, t]);
|
||||
|
||||
const decoded = decodePipeline.decoded;
|
||||
const decodeError = decodePipeline.error;
|
||||
|
||||
const decodedFileName = useMemo(() => {
|
||||
if (customFileName) return customFileName;
|
||||
if (decoded) return `decoded${decoded.suggestedExtension}`;
|
||||
return '';
|
||||
}, [customFileName, decoded]);
|
||||
|
||||
// 💡 托管最大文件体积字符串算子,清除下游引入风险
|
||||
const maxFileSizeStr = `${MAX_FILE_SIZE / 1024 / 1024} MB`;
|
||||
|
||||
return {
|
||||
result,
|
||||
info,
|
||||
isLoading,
|
||||
isDragging,
|
||||
setIsDragging,
|
||||
fileInputRef,
|
||||
encodeError,
|
||||
decodeInput,
|
||||
setDecodeInput,
|
||||
decoded,
|
||||
decodeError,
|
||||
decodedFileName,
|
||||
setCustomFileName,
|
||||
resetAll,
|
||||
safeFileSelect,
|
||||
maxFileSizeStr,
|
||||
};
|
||||
}
|
||||
+83
-137
@@ -1,161 +1,107 @@
|
||||
/**
|
||||
* ToolCard 组件 - 工具卡片
|
||||
*
|
||||
* 用于在仪表盘中展示各个工具功能的卡片组件,支持图标、标题、描述、
|
||||
* 快照内容展示,具备悬停动画效果。
|
||||
*/
|
||||
import { alpha, Box, Card, CardActionArea, Stack, Typography, useTheme } from '@mui/material';
|
||||
import ArrowForwardIosIcon from '@mui/icons-material/ArrowForwardIos';
|
||||
import type { SvgIconProps } from '@mui/material/SvgIcon';
|
||||
import type { ComponentType } from 'react';
|
||||
import React from 'react';
|
||||
import type { LucideProps } from 'lucide-react';
|
||||
import { ChevronRight } from 'lucide-react';
|
||||
import type { PaletteColorKey } from '@/config/features';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
/**
|
||||
* ToolCard 组件属性接口
|
||||
*/
|
||||
interface ToolCardProps {
|
||||
/** 工具卡片标题 */
|
||||
const PALETTE_COLORS: Record<PaletteColorKey, string> = {
|
||||
primary: '13, 148, 136', // teal
|
||||
success: '22, 163, 74', // green
|
||||
warning: '217, 119, 6', // amber (存储清理的橙色轴)
|
||||
error: '220, 38, 38', // red
|
||||
secondary: '147, 51, 2 purple',
|
||||
info: '37, 99, 235', // blue
|
||||
};
|
||||
|
||||
export interface ToolCardProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
title: string;
|
||||
/** 工具卡片描述文本(可选) */
|
||||
description?: string;
|
||||
/** 快照内容,用于在卡片底部展示额外信息(可选) */
|
||||
snapshot?: React.ReactNode;
|
||||
/** 主题色键,映射到 theme.palette[key].main */
|
||||
colorKey: PaletteColorKey;
|
||||
/** 图标组件引用 */
|
||||
icon: ComponentType<SvgIconProps>;
|
||||
/** 卡片点击事件处理函数 */
|
||||
onClick: () => void;
|
||||
icon: ComponentType<LucideProps>;
|
||||
onNavigate: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* ToolCard 组件
|
||||
*
|
||||
* @param props - ToolCardProps 属性对象
|
||||
* @returns 工具卡片 JSX 元素
|
||||
*/
|
||||
export default function ToolCard({
|
||||
title,
|
||||
description,
|
||||
snapshot,
|
||||
colorKey,
|
||||
icon: IconComponent,
|
||||
onClick,
|
||||
onNavigate,
|
||||
className,
|
||||
...props
|
||||
}: ToolCardProps) {
|
||||
const theme = useTheme();
|
||||
const colorCode = theme.palette[colorKey].main;
|
||||
const rgbValues = PALETTE_COLORS[colorKey];
|
||||
|
||||
return (
|
||||
<Card
|
||||
elevation={0}
|
||||
sx={{
|
||||
position: 'relative',
|
||||
borderRadius: 4,
|
||||
border: '1px solid',
|
||||
borderColor: 'divider',
|
||||
height: '100%',
|
||||
boxSizing: 'border-box',
|
||||
transition:
|
||||
'border-color 0.3s cubic-bezier(0.4, 0, 0.2, 1), transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
'&:hover': {
|
||||
borderColor: colorCode,
|
||||
transform: 'translateY(-4px)',
|
||||
boxShadow: `0 12px 24px -10px ${alpha(colorCode, 0.2)}`,
|
||||
},
|
||||
<div
|
||||
style={{
|
||||
['--tool-color' as string]: rgbValues,
|
||||
}}
|
||||
/* 💡 核心修复点:
|
||||
- 坚决不用 h-full 或固定高度,锁死 h-auto(高度自适应流),配合 py-4 px-4 牢牢把内容包裹在卡片体内。
|
||||
- 废除原先会乱飘的内联 style 属性擦写,全权放权给 Tailwind 的声明式 hover 变体。
|
||||
*/
|
||||
className={cn(
|
||||
'group relative rounded-xl border border-border/70 bg-card text-card-foreground p-4 h-auto flex flex-col items-stretch justify-start gap-3 shadow-sm select-none box-border',
|
||||
'transition-all duration-300 ease-[cubic-bezier(0.4,0,0.2,1)]',
|
||||
'hover:bg-muted/30',
|
||||
'hover:border-[rgba(var(--tool-color),0.45)]',
|
||||
'hover:shadow-[0_8px_24px_-8px_rgba(var(--tool-color),0.14)] dark:hover:shadow-[0_8px_30px_-10px_rgba(var(--tool-color),0.25)]',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CardActionArea
|
||||
onClick={onClick}
|
||||
sx={{
|
||||
height: '100%',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'stretch',
|
||||
justifyContent: 'flex-start',
|
||||
p: 2.5,
|
||||
gap: 1.5,
|
||||
'&:hover .arrow-icon': {
|
||||
transform: 'translateX(4px)',
|
||||
color: colorCode,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Stack direction="row" justifyContent="space-between" alignItems="flex-start" width="100%">
|
||||
<Stack direction="row" spacing={1.5} alignItems="center">
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 3,
|
||||
bgcolor: alpha(colorCode, 0.07),
|
||||
color: colorCode,
|
||||
}}
|
||||
>
|
||||
<IconComponent sx={{ fontSize: 20 }} />
|
||||
</Box>
|
||||
<Box>
|
||||
<Typography
|
||||
variant="subtitle1"
|
||||
sx={{
|
||||
fontWeight: 700,
|
||||
lineHeight: 1.2,
|
||||
color: 'text.primary',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 0.5,
|
||||
}}
|
||||
>
|
||||
{title}
|
||||
</Typography>
|
||||
{description && (
|
||||
<Typography
|
||||
variant="caption"
|
||||
sx={{
|
||||
color: 'text.secondary',
|
||||
fontWeight: 500,
|
||||
mt: 0.5,
|
||||
display: '-webkit-box',
|
||||
WebkitBoxOrient: 'vertical',
|
||||
WebkitLineClamp: 1,
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
wordBreak: 'break-word',
|
||||
}}
|
||||
>
|
||||
{description}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
</Stack>
|
||||
<ArrowForwardIosIcon
|
||||
className="arrow-icon"
|
||||
sx={{
|
||||
fontSize: 12,
|
||||
color: 'text.disabled',
|
||||
mt: 0.5,
|
||||
transition: 'all 0.3s ease',
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
{snapshot != null && (
|
||||
<Box
|
||||
sx={{
|
||||
mt: 'auto',
|
||||
pt: 1.5,
|
||||
borderTop: '1px dashed',
|
||||
borderColor: 'divider',
|
||||
width: '100%',
|
||||
}}
|
||||
{/* 上半部分:核心信息交互排版轴 */}
|
||||
<div className="flex items-center justify-between w-full relative min-w-0 min-h-[44px]">
|
||||
<div className="flex gap-3 items-center min-w-0 flex-1 pr-2">
|
||||
{/* 左侧圆形图标容器 */}
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center justify-center w-10 h-10 rounded-xl shrink-0 transition-colors duration-300',
|
||||
'bg-[rgba(var(--tool-color),0.08)] dark:bg-[rgba(var(--tool-color),0.12)]',
|
||||
'text-[rgb(var(--tool-color))]',
|
||||
)}
|
||||
>
|
||||
{snapshot}
|
||||
</Box>
|
||||
)}
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
<IconComponent className="h-5 w-5 shrink-0" />
|
||||
</div>
|
||||
|
||||
{/* 中间文字描述区:利用 flex-1 min-w-0 防御文本过长发生恶性撑开 */}
|
||||
<div className="flex-1 min-w-0 flex flex-col">
|
||||
<h4 className="font-bold text-sm tracking-tight text-foreground leading-snug">
|
||||
{title}
|
||||
</h4>
|
||||
{description && (
|
||||
<p className="text-[11px] font-medium text-muted-foreground/90 mt-0.5 leading-normal w-full truncate">
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 右侧指示小箭头 */}
|
||||
<div className="text-muted-foreground/40 group-hover:text-[rgb(var(--tool-color))] p-1 shrink-0 transition-all duration-300 ease-in-out group-hover:translate-x-0.5">
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</div>
|
||||
|
||||
{/* 覆盖整个上半部分的绝对定位隐形跳转层(A11y 无障碍标准合规) */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={onNavigate}
|
||||
aria-label={`进入 ${title}`}
|
||||
className="absolute inset-0 w-full h-full cursor-pointer bg-transparent border-none opacity-0 focus-visible:outline-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 下半部分:未来的动态预览沙箱独立承载区 */}
|
||||
{snapshot != null && (
|
||||
<div className="mt-1 pt-3 border-t border-dashed border-border/80 w-full relative z-10 select-text">
|
||||
{snapshot}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,22 +1,26 @@
|
||||
import { Box } from '@mui/material';
|
||||
import { useRouter } from '@/providers/RouterProvider';
|
||||
import ToolCard from '@/pages/Dashboard/ToolCard';
|
||||
import { getFeatureByKey } from '@/config/features';
|
||||
import type { PageType } from '@/types/storage';
|
||||
import { useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { dashboardPageStyles } from '@/config/pageTheme';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export default function DashboardPage() {
|
||||
const { navigateTo, visiblePages, pageOrder } = useRouter();
|
||||
const { t } = useTranslation(['features']);
|
||||
|
||||
const visibleSet = useMemo(() => new Set(visiblePages), [visiblePages]);
|
||||
const visibleSet = useMemo(() => new Set<string>(visiblePages), [visiblePages]);
|
||||
|
||||
return (
|
||||
<Box sx={dashboardPageStyles.GRID_CONTAINER}>
|
||||
<div
|
||||
className={cn(
|
||||
'grid grid-cols-1 sm:grid-cols-[repeat(auto-fill,minmax(290px,1fr))] auto-rows-auto gap-3.5 p-3.5 w-full h-auto',
|
||||
'animate-in fade-in duration-300 select-none',
|
||||
)}
|
||||
>
|
||||
{pageOrder.map((key) => {
|
||||
if (!visibleSet.has(key as PageType)) return null;
|
||||
if (!visibleSet.has(key)) return null;
|
||||
|
||||
const feature = getFeatureByKey(key);
|
||||
if (!feature?.themeColorKey || feature.icon == null) return null;
|
||||
@@ -28,10 +32,10 @@ export default function DashboardPage() {
|
||||
description={t(feature.descriptionKey)}
|
||||
colorKey={feature.themeColorKey}
|
||||
icon={feature.icon}
|
||||
onClick={() => navigateTo(key)}
|
||||
onNavigate={() => navigateTo(key as PageType)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+85
-173
@@ -1,25 +1,14 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
alpha,
|
||||
Box,
|
||||
Button,
|
||||
Container,
|
||||
Stack,
|
||||
TextField,
|
||||
Typography,
|
||||
Paper,
|
||||
} from '@mui/material';
|
||||
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
|
||||
import DownloadIcon from '@mui/icons-material/Download';
|
||||
import CodeIcon from '@mui/icons-material/Code';
|
||||
import { Code, Download, Trash2 } from 'lucide-react';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import PageHeader from '@/components/PageHeader';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
import { Button } from '@/components/ui/button'; // 💡 1. 全面回归规范:引入原生的 shadcn 原子 Button
|
||||
import { useStorageState } from '@/utils/useStorageState';
|
||||
import type { HtmlToMarkdownPreviewMode } from '@/types/storage';
|
||||
import { htmlToMarkdown, downloadMarkdownFile, SAMPLE_HTML } from '@/utils/htmlToMarkdown';
|
||||
import { downloadMarkdownFile, htmlToMarkdown, SAMPLE_HTML } from '@/utils/htmlToMarkdown';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const isValidPreviewMode = (val: unknown): val is HtmlToMarkdownPreviewMode =>
|
||||
typeof val === 'string' && ['split', 'preview', 'markdown'].includes(val);
|
||||
@@ -57,18 +46,20 @@ export default function HtmlToMarkdownPage() {
|
||||
const showOutput = previewMode !== 'markdown';
|
||||
|
||||
return (
|
||||
<Container maxWidth="xl" sx={{ py: 3 }}>
|
||||
<PageHeader title={t('pageTitle')} subtitle={t('pageSubtitle')} icon={<CodeIcon />} />
|
||||
/* 💡 统一间距尺寸:
|
||||
- 彻底清除多余的 container max-w-7xl 这种网页大边距,
|
||||
- 统一收拢为我们先前在 Dashboard 页、JSON 工具箱制定的 p-4 space-y-4 标准极客桌面规格。
|
||||
*/
|
||||
<div className="p-4 w-full flex flex-col space-y-4 select-none animate-in fade-in duration-300">
|
||||
<PageHeader
|
||||
title={t('pageTitle')}
|
||||
subtitle={t('pageSubtitle')}
|
||||
icon={<Code className="h-4 w-4" />}
|
||||
/>
|
||||
|
||||
<Stack spacing={2}>
|
||||
{/* 工具栏 */}
|
||||
<Stack
|
||||
direction="row"
|
||||
justifyContent="space-between"
|
||||
alignItems="center"
|
||||
flexWrap="wrap"
|
||||
gap={1.5}
|
||||
>
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* 工具栏集成区 */}
|
||||
<div className="flex flex-col sm:flex-row gap-3 justify-between items-stretch sm:items-center bg-secondary/40 rounded-xl border border-border/60 px-1.5 py-1.5 sm:h-12">
|
||||
<SwitchButtonGroup
|
||||
value={previewMode}
|
||||
options={[
|
||||
@@ -78,195 +69,116 @@ export default function HtmlToMarkdownPage() {
|
||||
]}
|
||||
onChange={handleModeChange}
|
||||
size="small"
|
||||
className="w-full sm:w-auto"
|
||||
/>
|
||||
|
||||
<Stack direction="row" spacing={1}>
|
||||
<div className="flex gap-2 shrink-0">
|
||||
{/* 2. 重塑下载按钮:接入受控 Button,追加 active 物理微缩放动效 */}
|
||||
<Button
|
||||
variant="outlined"
|
||||
size="small"
|
||||
startIcon={<DownloadIcon />}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleDownload}
|
||||
disabled={!result.markdown}
|
||||
sx={{ borderRadius: 2 }}
|
||||
className="h-8 rounded-md font-medium text-xs gap-1.5 shadow-sm active:scale-95 transition-all"
|
||||
>
|
||||
<Download className="h-3.5 w-3.5" />
|
||||
{t('download')}
|
||||
</Button>
|
||||
|
||||
{/* 重塑清空按钮 */}
|
||||
<Button
|
||||
variant="outlined"
|
||||
size="small"
|
||||
startIcon={<DeleteOutlineIcon />}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleClear}
|
||||
sx={{ borderRadius: 2 }}
|
||||
className="h-8 rounded-md font-medium text-xs gap-1.5 shadow-sm active:scale-95 text-destructive hover:text-destructive hover:bg-destructive/5 dark:hover:bg-destructive/10 border-input/60 transition-all"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
{t('clear')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 错误提示 */}
|
||||
{/* 错误提示:
|
||||
- 💡 核心修复点:将硬编码的 bg-red-50 实色,完美超进化为系统的全自适应透明色变体
|
||||
*/}
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ borderRadius: 2 }}>
|
||||
<div className="p-3.5 bg-destructive/10 border border-destructive/20 rounded-xl text-destructive text-xs font-semibold tracking-wide animate-in shake duration-300">
|
||||
{error}
|
||||
</Alert>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 主内容区 */}
|
||||
<Box
|
||||
sx={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: {
|
||||
xs: '1fr',
|
||||
md: showInput && showOutput ? '1fr 1fr' : '1fr',
|
||||
},
|
||||
gap: 2,
|
||||
minHeight: 500,
|
||||
}}
|
||||
{/* 双翼/单栏联动面板展示区 */}
|
||||
<div
|
||||
className={cn(
|
||||
'grid gap-4 min-h-[460px] w-full',
|
||||
showInput && showOutput ? 'grid-cols-1 md:grid-cols-2' : 'grid-cols-1',
|
||||
)}
|
||||
>
|
||||
{/* HTML 输入区 */}
|
||||
{/* HTML 输入端卡片面板 */}
|
||||
{showInput && (
|
||||
<Paper
|
||||
elevation={0}
|
||||
sx={{
|
||||
border: '1px solid',
|
||||
borderColor: 'divider',
|
||||
borderRadius: 3,
|
||||
overflow: 'hidden',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
px: 2,
|
||||
py: 1,
|
||||
bgcolor: (theme) => alpha(theme.palette.primary.main, 0.04),
|
||||
borderBottom: '1px solid',
|
||||
borderColor: 'divider',
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<Typography variant="caption" sx={{ fontWeight: 700, color: 'text.secondary' }}>
|
||||
/* 3. 智能聚焦框联动(Focus Ring Clamping):
|
||||
- 外层容器追加 focus-within 变量追踪大闸。
|
||||
- 只要用户用鼠标点击了内部的 textarea,外层整块精巧的圆角大边框会一帧内亮起 primary 系统的深色呼吸发光环,
|
||||
- 这种“全外包裹层框聚焦”的体验极大模仿了本地原生 IDE 的硬核专业体验!
|
||||
*/
|
||||
<div className="border border-border rounded-xl bg-card text-card-foreground shadow-sm overflow-hidden flex flex-col transition-all duration-200 focus-within:ring-1 focus-within:ring-ring focus-within:border-ring">
|
||||
{/* 卡片头部:改用标准的灰色 bg-muted/50 */}
|
||||
<div className="flex h-9 items-center justify-between px-4 bg-muted/50 border-b border-border select-none">
|
||||
<span className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider">
|
||||
{t('inputLabel')}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ color: 'text.disabled' }}>
|
||||
</span>
|
||||
<span className="text-[10px] font-mono text-muted-foreground/60 tabular-nums">
|
||||
{t('charCount', { count: html.length })}
|
||||
</Typography>
|
||||
</Box>
|
||||
<TextField
|
||||
multiline
|
||||
fullWidth
|
||||
</span>
|
||||
</div>
|
||||
<textarea
|
||||
value={html}
|
||||
onChange={(e) => setHtml(e.target.value)}
|
||||
placeholder={t('inputPlaceholder')}
|
||||
sx={{
|
||||
flex: 1,
|
||||
'& .MuiOutlinedInput-root': {
|
||||
borderRadius: 0,
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.85rem',
|
||||
lineHeight: 1.6,
|
||||
alignItems: 'flex-start',
|
||||
'& fieldset': { border: 'none' },
|
||||
},
|
||||
'& .MuiInputBase-input': {
|
||||
py: 2,
|
||||
px: 2,
|
||||
minHeight: 400,
|
||||
},
|
||||
}}
|
||||
className="flex-1 min-h-[380px] p-4 bg-transparent font-mono text-xs leading-relaxed resize-none focus:outline-none text-foreground/90 select-text"
|
||||
/>
|
||||
</Paper>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Markdown 输出区 */}
|
||||
{/* Markdown 输出端卡片面板 */}
|
||||
{showOutput && (
|
||||
<Paper
|
||||
elevation={0}
|
||||
sx={{
|
||||
border: '1px solid',
|
||||
borderColor: 'divider',
|
||||
borderRadius: 3,
|
||||
overflow: 'hidden',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
px: 2,
|
||||
py: 1,
|
||||
bgcolor: (theme) => alpha(theme.palette.primary.main, 0.04),
|
||||
borderBottom: '1px solid',
|
||||
borderColor: 'divider',
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<Typography variant="caption" sx={{ fontWeight: 700, color: 'text.secondary' }}>
|
||||
<div className="border border-border rounded-xl bg-card text-card-foreground shadow-sm overflow-hidden flex flex-col">
|
||||
<div className="flex h-9 items-center justify-between px-4 bg-muted/50 border-b border-border select-none">
|
||||
<span className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider">
|
||||
{(previewMode as string) === 'markdown'
|
||||
? t('markdownOutputLabel')
|
||||
: t('previewLabel')}
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={0.5} alignItems="center">
|
||||
<Typography variant="caption" sx={{ color: 'text.disabled' }}>
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-[10px] font-mono text-muted-foreground/60 tabular-nums">
|
||||
{t('charCount', { count: result.markdownLength })}
|
||||
</Typography>
|
||||
<CopyButton text={result.markdown} size="small" />
|
||||
</Stack>
|
||||
</Box>
|
||||
</span>
|
||||
<CopyButton
|
||||
text={result.markdown}
|
||||
className="h-6 w-6 rounded-md border text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{(previewMode as string) === 'markdown' ? (
|
||||
<TextField
|
||||
multiline
|
||||
fullWidth
|
||||
<textarea
|
||||
value={result.markdown}
|
||||
slotProps={{ input: { readOnly: true } }}
|
||||
sx={{
|
||||
flex: 1,
|
||||
'& .MuiOutlinedInput-root': {
|
||||
borderRadius: 0,
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.85rem',
|
||||
lineHeight: 1.6,
|
||||
alignItems: 'flex-start',
|
||||
'& fieldset': { border: 'none' },
|
||||
},
|
||||
'& .MuiInputBase-input': {
|
||||
py: 2,
|
||||
px: 2,
|
||||
minHeight: 400,
|
||||
},
|
||||
}}
|
||||
readOnly
|
||||
className="flex-1 min-h-[380px] p-4 font-mono text-xs leading-relaxed resize-none focus:outline-none bg-muted/30 dark:bg-muted/10 text-foreground/80 select-text"
|
||||
/>
|
||||
) : (
|
||||
<Box
|
||||
sx={{
|
||||
flex: 1,
|
||||
p: 2,
|
||||
minHeight: 400,
|
||||
overflow: 'auto',
|
||||
bgcolor: 'background.paper',
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.85rem',
|
||||
lineHeight: 1.6,
|
||||
whiteSpace: 'pre-wrap',
|
||||
wordBreak: 'break-word',
|
||||
}}
|
||||
>
|
||||
<div className="flex-1 p-4 min-h-[380px] overflow-auto bg-transparent font-mono text-xs leading-relaxed whitespace-pre-wrap break-all text-foreground/90 select-text">
|
||||
{result.markdown || (
|
||||
<Typography variant="body2" color="text.disabled">
|
||||
<span className="text-muted-foreground/70 italic text-[11px] font-sans">
|
||||
{t('emptyHint')}
|
||||
</Typography>
|
||||
</span>
|
||||
)}
|
||||
</Box>
|
||||
</div>
|
||||
)}
|
||||
</Paper>
|
||||
</div>
|
||||
)}
|
||||
</Box>
|
||||
</Stack>
|
||||
</Container>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { Box, IconButton, Typography } from '@mui/material';
|
||||
import NavigateBeforeIcon from '@mui/icons-material/NavigateBefore';
|
||||
import NavigateNextIcon from '@mui/icons-material/NavigateNext';
|
||||
import React from 'react';
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { jsonDiffPageStyles } from '@/config/pageTheme';
|
||||
import { cn } from '@/lib/utils'; // 1. 引入标准的 shadcn 工具函数
|
||||
|
||||
interface DiffNavigatorProps {
|
||||
export interface DiffNavigatorProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
total: number;
|
||||
/** 0-based index */
|
||||
currentIndex: number;
|
||||
@@ -12,35 +11,83 @@ interface DiffNavigatorProps {
|
||||
onNext: () => void;
|
||||
}
|
||||
|
||||
export default function DiffNavigator({ total, currentIndex, onPrev, onNext }: DiffNavigatorProps) {
|
||||
export default function DiffNavigator({
|
||||
total,
|
||||
currentIndex,
|
||||
onPrev,
|
||||
onNext,
|
||||
className,
|
||||
...props
|
||||
}: DiffNavigatorProps) {
|
||||
const { t } = useLazyTranslation('jsonDiff');
|
||||
|
||||
// 计算当前的边界禁用状态守卫
|
||||
const isFirst = currentIndex <= 0;
|
||||
const isLast = currentIndex >= total - 1;
|
||||
|
||||
// 2. 空状态面板:对齐 shadcn 规范的中性低调卡片
|
||||
if (total === 0) {
|
||||
return (
|
||||
<Box sx={jsonDiffPageStyles.NAVIGATOR}>
|
||||
<Typography variant="body2" sx={{ fontWeight: 700, color: 'text.secondary' }}>
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center justify-center gap-3 px-4 py-2 rounded-lg border border-border bg-muted/30 select-none animate-in fade-in duration-200',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="text-xs font-semibold text-muted-foreground/90">
|
||||
{t('jsonDiff:noDiffs')}
|
||||
</Typography>
|
||||
</Box>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Box sx={jsonDiffPageStyles.NAVIGATOR}>
|
||||
<IconButton size="small" aria-label={t('jsonDiff:previousDiff')} onClick={onPrev}>
|
||||
<NavigateBeforeIcon />
|
||||
</IconButton>
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{ fontWeight: 800, fontFamily: 'monospace', minWidth: 60, textAlign: 'center' }}
|
||||
<div
|
||||
className={cn(
|
||||
// 3. 完美适配暗黑模式:
|
||||
// 废除 bg-primary/10,采用标准的低阻尼中性色 bg-secondary/60 配合 border-border/80,
|
||||
// 在任何主题皮肤下都能呈现出高级的暗钛金控制栏质感。
|
||||
'inline-flex items-center justify-center gap-3 px-3 h-9 rounded-md border border-border/80 bg-secondary/60 shadow-sm',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{/* 上一处差异按钮 */}
|
||||
<button
|
||||
type="button"
|
||||
disabled={isFirst}
|
||||
aria-label={t('jsonDiff:previousDiff')}
|
||||
onClick={onPrev}
|
||||
className={cn(
|
||||
'p-1 rounded-md text-muted-foreground transition-all hover:bg-accent hover:text-foreground',
|
||||
'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
|
||||
'disabled:pointer-events-none disabled:opacity-30 active:scale-95', // 4. 边界拦截:触顶时优雅淡化并锁死点击
|
||||
)}
|
||||
>
|
||||
{currentIndex + 1} / {total}
|
||||
</Typography>
|
||||
<IconButton size="small" aria-label={t('jsonDiff:nextDiff')} onClick={onNext}>
|
||||
<NavigateNextIcon />
|
||||
</IconButton>
|
||||
</Box>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</button>
|
||||
|
||||
{/* 计数看板:强制等宽防止数字长短不一时产生宽度挤压跳动 */}
|
||||
<span className="text-xs font-bold font-mono min-w-[54px] text-center text-foreground/90 tabular-nums select-none">
|
||||
{currentIndex + 1} <span className="text-muted-foreground/60 font-sans mx-0.5">/</span>{' '}
|
||||
{total}
|
||||
</span>
|
||||
|
||||
{/* 下一处差异按钮 */}
|
||||
<button
|
||||
type="button"
|
||||
disabled={isLast}
|
||||
aria-label={t('jsonDiff:nextDiff')}
|
||||
onClick={onNext}
|
||||
className={cn(
|
||||
'p-1 rounded-md text-muted-foreground transition-all hover:bg-accent hover:text-foreground',
|
||||
'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
|
||||
'disabled:pointer-events-none disabled:opacity-30 active:scale-95', // 4. 边界拦截:触底时优雅淡化并锁死点击
|
||||
)}
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export type { DiffNavigatorProps };
|
||||
|
||||
@@ -1,56 +1,64 @@
|
||||
import { Box, Stack, Typography, useTheme } from '@mui/material';
|
||||
import type { Theme } from '@mui/material/styles';
|
||||
import React from 'react';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { jsonDiffPageStyles, surfaceTint } from '@/config/pageTheme';
|
||||
import { cn } from '@/lib/utils';
|
||||
import JsonTree from './JsonTree';
|
||||
import type { DiffNode, DiffResult as DiffResultType, DiffType, ViewMode } from './types';
|
||||
|
||||
interface DiffResultProps {
|
||||
// 💡 顶层 Interface 继承原生 HTML 容器属性,扩展灵活性
|
||||
export interface DiffResultProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
result: DiffResultType;
|
||||
viewMode: ViewMode;
|
||||
activePath?: string;
|
||||
}
|
||||
|
||||
export default function DiffResult({ result, viewMode, activePath }: DiffResultProps) {
|
||||
export default function DiffResult({
|
||||
result,
|
||||
viewMode,
|
||||
activePath,
|
||||
className,
|
||||
...props
|
||||
}: DiffResultProps) {
|
||||
const { t } = useLazyTranslation('jsonDiff');
|
||||
|
||||
if (viewMode === 'sideBySide') {
|
||||
return (
|
||||
<Stack direction={{ xs: 'column', md: 'row' }} spacing={2} alignItems="stretch">
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<div
|
||||
className={cn('flex flex-col md:flex-row gap-4 items-stretch w-full', className)}
|
||||
{...props}
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<SectionLabel text={t('jsonDiff:leftLabel')} />
|
||||
<JsonTree node={result.root} side="left" activePath={activePath} />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<SectionLabel text={t('jsonDiff:rightLabel')} />
|
||||
<JsonTree node={result.root} side="right" activePath={activePath} />
|
||||
</Box>
|
||||
</Stack>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Box sx={jsonDiffPageStyles.TREE_CONTAINER}>
|
||||
/* 1. 单栏拍平视图容器:
|
||||
- 对齐 shadcn 规范,使用 bg-card、border-border 隔离。
|
||||
- 注入 tabular-nums 配合 font-mono,消灭任何行高和字符抖动。
|
||||
*/
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-xl border border-border bg-card font-mono text-xs shadow-sm overflow-x-auto min-h-[200px] max-h-[520px] overflow-y-auto p-1.5',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<UnifiedView node={result.root} depth={0} activePath={activePath} />
|
||||
</Box>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const SectionLabel = ({ text }: { text: string }) => (
|
||||
<Typography
|
||||
variant="caption"
|
||||
sx={{
|
||||
display: 'block',
|
||||
mb: 0.6,
|
||||
fontWeight: 800,
|
||||
fontSize: '0.7rem',
|
||||
letterSpacing: 0.4,
|
||||
color: 'text.secondary',
|
||||
textTransform: 'uppercase',
|
||||
}}
|
||||
>
|
||||
<span className="block mb-2 text-[10px] font-bold tracking-wider text-muted-foreground/80 uppercase px-0.5 select-none">
|
||||
{text}
|
||||
</Typography>
|
||||
</span>
|
||||
);
|
||||
|
||||
const formatPrimitive = (v: unknown): string => {
|
||||
@@ -65,24 +73,31 @@ const isContainerType = (v: unknown): boolean =>
|
||||
(typeof v === 'object' && v !== null) || Array.isArray(v);
|
||||
|
||||
const prefixForType = (type: DiffType): string => {
|
||||
if (type === 'added') return '+ ';
|
||||
if (type === 'removed') return '- ';
|
||||
if (type === 'modified') return '~ ';
|
||||
return ' ';
|
||||
if (type === 'added') return '+';
|
||||
if (type === 'removed') return '-';
|
||||
if (type === 'modified') return '~';
|
||||
return ' ';
|
||||
};
|
||||
|
||||
const colorForType = (type: DiffType): string | undefined => {
|
||||
if (type === 'added') return jsonDiffPageStyles.addedText;
|
||||
if (type === 'removed') return jsonDiffPageStyles.removedText;
|
||||
if (type === 'modified') return jsonDiffPageStyles.modifiedText;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const bgForType = (type: DiffType, theme: Theme): string | undefined => {
|
||||
if (type === 'added') return surfaceTint(theme, theme.palette.success.main, 0.15);
|
||||
if (type === 'removed') return surfaceTint(theme, theme.palette.error.main, 0.15);
|
||||
if (type === 'modified') return surfaceTint(theme, theme.palette.warning.main, 0.15);
|
||||
return undefined;
|
||||
// 2. 状态色彩超进化:
|
||||
// 拒绝硬编码实色系,全部换用高度安全的语义色变体与暗黑模式自适应。
|
||||
const typeThemeMap = {
|
||||
added: {
|
||||
text: 'text-emerald-600 dark:text-emerald-400',
|
||||
bg: 'bg-emerald-500/5 dark:bg-emerald-500/10',
|
||||
},
|
||||
removed: {
|
||||
text: 'text-destructive',
|
||||
bg: 'bg-destructive/5 dark:bg-destructive/10',
|
||||
},
|
||||
modified: {
|
||||
text: 'text-amber-600 dark:text-amber-400',
|
||||
bg: 'bg-amber-500/5 dark:bg-amber-500/10',
|
||||
},
|
||||
unchanged: {
|
||||
text: 'text-foreground/80',
|
||||
bg: 'bg-transparent',
|
||||
},
|
||||
};
|
||||
|
||||
interface UnifiedViewProps {
|
||||
@@ -99,7 +114,6 @@ const UnifiedView = ({ node, depth, activePath }: UnifiedViewProps) => {
|
||||
const keyLabel = isRoot ? '' : `${node.key}: `;
|
||||
|
||||
if (!isContainer) {
|
||||
// 叶子节点
|
||||
if (node.type === 'modified') {
|
||||
return (
|
||||
<>
|
||||
@@ -129,7 +143,7 @@ const UnifiedView = ({ node, depth, activePath }: UnifiedViewProps) => {
|
||||
);
|
||||
}
|
||||
|
||||
// 容器节点:added/removed 整块呈现
|
||||
// 容器节点整块渲染处理
|
||||
if (node.type === 'added') {
|
||||
return (
|
||||
<UnifiedRow
|
||||
@@ -177,29 +191,39 @@ interface UnifiedRowProps {
|
||||
}
|
||||
|
||||
const UnifiedRow = ({ depth, type, text, active, multiline }: UnifiedRowProps) => {
|
||||
const theme = useTheme();
|
||||
const color = colorForType(type);
|
||||
const bg = bgForType(type, theme);
|
||||
// 3. 高精度提取状态样式映射
|
||||
const currentTheme = typeThemeMap[type] || typeThemeMap.unchanged;
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
pl: depth * 1.5,
|
||||
pr: 1,
|
||||
py: 0.2,
|
||||
bgcolor: bg,
|
||||
color: color ?? 'text.primary',
|
||||
outline: active ? '2px solid' : 'none',
|
||||
outlineColor: 'primary.main',
|
||||
borderRadius: 0.5,
|
||||
whiteSpace: multiline ? 'pre' : 'nowrap',
|
||||
fontFamily: 'monospace',
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-start w-full font-mono py-0.5 select-text group transition-colors',
|
||||
currentTheme.bg,
|
||||
currentTheme.text,
|
||||
// 4. 高亮定位条:不再使用生硬的蓝圆环,改为现代编辑器的“侧边左高亮带”设计,质感直接拉满
|
||||
active &&
|
||||
'bg-primary/10 relative before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1 before:bg-blue-500',
|
||||
)}
|
||||
style={{
|
||||
// 维持高精度的 Padding 基线缩进
|
||||
paddingLeft: `${Math.max(0.5, depth * 1.25)}rem`,
|
||||
paddingRight: '0.5rem',
|
||||
}}
|
||||
>
|
||||
<Box component="span" sx={{ fontWeight: 800 }}>
|
||||
{/* 5. 前缀标识:等宽锁定,强行占据 w-5 并让符号居中对齐,达成 VSCode 般的整洁排版 */}
|
||||
<span className="font-bold w-5 shrink-0 text-center select-none opacity-70 tabular-nums">
|
||||
{prefixForType(type)}
|
||||
</Box>
|
||||
<Box component="span">{text}</Box>
|
||||
</Box>
|
||||
</span>
|
||||
|
||||
<span
|
||||
className={cn(
|
||||
'flex-1 break-all tracking-tight leading-normal',
|
||||
multiline ? 'whitespace-pre' : 'whitespace-nowrap',
|
||||
)}
|
||||
>
|
||||
{text}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -217,4 +241,4 @@ const stringifyMultiline = (v: unknown, depth: number): string => {
|
||||
}
|
||||
};
|
||||
|
||||
export type { DiffResultProps };
|
||||
// 💡 彻底移除了文件底部引发 TS2484 冲突的 export type { DiffResultProps } 声明
|
||||
|
||||
@@ -1,205 +1,145 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Box, Button, Stack, Typography } from '@mui/material';
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { formatByteSize } from '@/utils/textStatistics';
|
||||
import { useSnackbar } from '@/components/GlobalSnackbar';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import { validateJson } from '@/utils/jsonFormatter';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
/** 转换结果通用接口 */
|
||||
export interface ConvertResult {
|
||||
/** 转换后的输出字符串 */
|
||||
output: string;
|
||||
/** 原始输入的字节大小 */
|
||||
originalBytes: number;
|
||||
/** 转换后的字节大小 */
|
||||
outputBytes: number;
|
||||
}
|
||||
|
||||
/** 转换函数类型 */
|
||||
export type ConvertFunction = (text: string) => ConvertResult;
|
||||
|
||||
/**
|
||||
* JSON 转换工具区域组件属性
|
||||
*/
|
||||
interface JsonConvertSectionProps {
|
||||
/** i18n 命名空间内翻译键的前缀,如 'yamlMode' / 'tomlMode' / 'minifyMode' */
|
||||
interface JsonConvertSectionProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
translationPrefix: string;
|
||||
/** 转换函数 */
|
||||
convertFunction: ConvertFunction;
|
||||
/** 转换按钮的翻译键后缀,默认 'convertButton' */
|
||||
convertButtonKey?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON 转换工具共享组件
|
||||
*
|
||||
* 适用于 JSON->YAML、JSON->TOML、JSON 压缩等场景,
|
||||
* 提供输入区域、转换按钮和结果展示(含一键复制)。
|
||||
*/
|
||||
export default function JsonConvertSection({
|
||||
translationPrefix,
|
||||
convertFunction,
|
||||
convertButtonKey = 'convertButton',
|
||||
className,
|
||||
...props
|
||||
}: JsonConvertSectionProps) {
|
||||
const { t } = useLazyTranslation('jsonFormat');
|
||||
const { showMessage } = useSnackbar();
|
||||
|
||||
const [input, setInput] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [result, setResult] = useState<ConvertResult | null>(null);
|
||||
const [debouncedInput, setDebouncedInput] = useState('');
|
||||
|
||||
const pk = translationPrefix;
|
||||
|
||||
// 防抖校验输入
|
||||
// 1. 高阶性能调优:将文本变化收拢进行 250ms 极速防抖落盘,避免每一次敲击键盘都触发底层的复杂序列化算法
|
||||
useEffect(() => {
|
||||
const handle = setTimeout(() => {
|
||||
setError(validateJson(input));
|
||||
}, 300);
|
||||
setDebouncedInput(input);
|
||||
}, 250);
|
||||
return () => clearTimeout(handle);
|
||||
}, [input]);
|
||||
|
||||
const canConvert = useMemo(() => {
|
||||
return input.trim() !== '' && !error;
|
||||
}, [input, error]);
|
||||
// 💡 2. 贯彻方案 A(衍生变量超进化):
|
||||
// 彻底删掉 error 状态和对应的受控 useEffect 节点。
|
||||
// 语法错误由防抖文本在内存中同步推导,彻底斩断二次级联渲染链条,ESLint 警告自愈!
|
||||
const error = useMemo(() => {
|
||||
return validateJson(debouncedInput);
|
||||
}, [debouncedInput]);
|
||||
|
||||
const handleConvert = () => {
|
||||
const validationError = validateJson(input);
|
||||
if (validationError) {
|
||||
setError(validationError);
|
||||
setResult(null);
|
||||
return;
|
||||
}
|
||||
// 3. 核心魔法:纯净的即时流式转换转换管线 (Live Compilation Pipeline)
|
||||
const conversionPipeline = useMemo(() => {
|
||||
const trimmed = debouncedInput.trim();
|
||||
if (!trimmed || error) return null;
|
||||
|
||||
try {
|
||||
const convertResult = convertFunction(input);
|
||||
setResult(convertResult);
|
||||
return convertFunction(debouncedInput);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
setResult(null);
|
||||
// 捕获可能从外部转换器(如 YAML.stringify)中抛出的底层异常
|
||||
return {
|
||||
isRuntimeError: true,
|
||||
errorMessage: e instanceof Error ? e.message : String(e),
|
||||
};
|
||||
}
|
||||
};
|
||||
}, [debouncedInput, error, convertFunction]);
|
||||
|
||||
const handleClear = () => {
|
||||
setInput('');
|
||||
setError(null);
|
||||
setResult(null);
|
||||
};
|
||||
// 判定运行时异常
|
||||
const runtimeError =
|
||||
conversionPipeline && 'isRuntimeError' in conversionPipeline
|
||||
? conversionPipeline.errorMessage
|
||||
: null;
|
||||
const result =
|
||||
conversionPipeline && !('isRuntimeError' in conversionPipeline)
|
||||
? (conversionPipeline as ConvertResult)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<Stack spacing={2.5}>
|
||||
{/* 工具栏 */}
|
||||
<Stack
|
||||
direction={{ xs: 'column', sm: 'row' }}
|
||||
spacing={1.5}
|
||||
justifyContent="space-between"
|
||||
alignItems={{ xs: 'stretch', sm: 'center' }}
|
||||
>
|
||||
<Box />
|
||||
<Stack direction="row" spacing={1}>
|
||||
<Button variant="text" onClick={handleClear} sx={{ borderRadius: 3 }}>
|
||||
{t('jsonFormat:clearButton')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={!canConvert}
|
||||
onClick={handleConvert}
|
||||
sx={{ borderRadius: 3, fontWeight: 700, px: 3 }}
|
||||
>
|
||||
{t(`jsonFormat:${convertButtonKey}`)}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Stack>
|
||||
|
||||
<div
|
||||
className={cn('w-full flex flex-col gap-4 animate-in fade-in duration-300', className)}
|
||||
{...props}
|
||||
>
|
||||
{/* 输入区 */}
|
||||
<TextInputArea
|
||||
placeholder={t(`jsonFormat:${pk}InputPlaceholder`)}
|
||||
value={input}
|
||||
onChange={setInput}
|
||||
externalError={error || undefined}
|
||||
onClear={() => {
|
||||
setResult(null);
|
||||
}}
|
||||
externalError={error || runtimeError || undefined} // 融合语法错误与运行时转换错误
|
||||
showClear={true}
|
||||
allowCopy={true}
|
||||
minRows={7}
|
||||
maxRows={14}
|
||||
onClear={() => setInput('')}
|
||||
/>
|
||||
|
||||
{/* 转换结果 */}
|
||||
{/* 4. 结果展示或状态引导卡片区 */}
|
||||
{result && result.output ? (
|
||||
<Box
|
||||
sx={{
|
||||
position: 'relative',
|
||||
borderRadius: 3,
|
||||
bgcolor: 'background.paper',
|
||||
border: '1px solid',
|
||||
borderColor: 'divider',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{/* 结果头部 */}
|
||||
<Stack
|
||||
direction="row"
|
||||
justifyContent="space-between"
|
||||
alignItems="center"
|
||||
sx={{
|
||||
px: 2,
|
||||
py: 1,
|
||||
borderBottom: '1px solid',
|
||||
borderColor: 'divider',
|
||||
bgcolor: (theme) =>
|
||||
theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.03)' : 'grey.50',
|
||||
}}
|
||||
>
|
||||
<Stack direction="row" spacing={2} alignItems="center">
|
||||
<Typography
|
||||
variant="caption"
|
||||
sx={{ fontWeight: 800, color: 'text.secondary', fontSize: '0.7rem' }}
|
||||
>
|
||||
<div className="relative rounded-xl border border-border bg-card text-card-foreground shadow-sm overflow-hidden animate-in slide-in-from-bottom-2 duration-300">
|
||||
{/* 结果栏精致头部 */}
|
||||
<div className="flex h-9 items-center justify-between px-4 border-b border-border bg-muted/50 select-none">
|
||||
<div className="flex gap-4 items-center">
|
||||
<span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/90">
|
||||
{t(`jsonFormat:${pk}OutputLabel`)}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ color: 'text.disabled', fontSize: '0.65rem' }}>
|
||||
{t('jsonFormat:originalSize')}: {formatByteSize(result.originalBytes)}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ color: 'text.disabled', fontSize: '0.65rem' }}>
|
||||
{t('jsonFormat:formattedSize')}: {formatByteSize(result.outputBytes)}
|
||||
</Typography>
|
||||
</Stack>
|
||||
<CopyButton text={result.output} showMessage={showMessage} />
|
||||
</Stack>
|
||||
</span>
|
||||
|
||||
{/* 转换内容 */}
|
||||
<Box
|
||||
sx={{
|
||||
p: 2,
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.8rem',
|
||||
whiteSpace: 'pre-wrap',
|
||||
wordBreak: 'break-all',
|
||||
maxHeight: 400,
|
||||
overflowY: 'auto',
|
||||
lineHeight: 1.6,
|
||||
}}
|
||||
>
|
||||
{/* 字节比对注入 tabular-nums font-mono,防止容量大小变动时字符横向抽搐 */}
|
||||
<div className="hidden sm:flex gap-3 items-center font-mono text-[10px] text-muted-foreground/70 tabular-nums">
|
||||
<span>
|
||||
{t('jsonFormat:originalSize')}:{' '}
|
||||
<span className="font-semibold text-foreground/80">
|
||||
{formatByteSize(result.originalBytes)}
|
||||
</span>
|
||||
</span>
|
||||
<span className="text-border/60">|</span>
|
||||
<span>
|
||||
{t('jsonFormat:formattedSize')}:{' '}
|
||||
<span className="font-semibold text-foreground/80">
|
||||
{formatByteSize(result.outputBytes)}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<CopyButton
|
||||
text={result.output}
|
||||
className="h-6 w-6 rounded-md border text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 转换出的数据流承载区:
|
||||
💡 修复点:移除了互相冲突打架的 select-all 类名,仅保留纯净、支持自由划线选中的 select-text 样式
|
||||
*/}
|
||||
<div className="p-4 font-mono text-xs text-foreground/90 whitespace-pre-wrap break-all max-h-[380px] overflow-y-auto leading-relaxed select-text">
|
||||
{result.output}
|
||||
</Box>
|
||||
</Box>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<Box
|
||||
sx={{
|
||||
p: 3,
|
||||
borderRadius: 3,
|
||||
bgcolor: (theme) =>
|
||||
theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.03)' : 'grey.50',
|
||||
border: '1px dashed',
|
||||
borderColor: (theme) =>
|
||||
theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.15)' : 'grey.300',
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ fontWeight: 600 }}>
|
||||
{t(`jsonFormat:${pk}EmptyHint`)}
|
||||
</Typography>
|
||||
</Box>
|
||||
/* 5. 空状态提示容器:完美的中性虚线引导,不喧宾夺主 */
|
||||
<div className="p-8 rounded-xl bg-muted/30 border border-dashed border-border/80 text-center flex flex-col items-center justify-center min-h-[120px] select-none">
|
||||
<p className="text-xs font-semibold text-muted-foreground/80 tracking-wide max-w-[240px] leading-relaxed">
|
||||
{error ? '请修正上方 JSON 的语法错误以激活流式转换' : t(`jsonFormat:${pk}EmptyHint`)}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</Stack>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import { Box, Typography } from '@mui/material';
|
||||
import React from 'react';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface JsonDiffInputProps {
|
||||
// 💡 核心修复:使用 Omit<..., 'onChange'> 强行挖掉原生的 onChange 签名
|
||||
// 这样我们自定义的 (value: string) => void 就能独占鳌头,彻底消灭 TS2430 接口冲突!
|
||||
export interface JsonDiffInputProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange'> {
|
||||
label: string;
|
||||
placeholder: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
error?: string | null;
|
||||
minRows?: number;
|
||||
}
|
||||
|
||||
export default function JsonDiffInput({
|
||||
@@ -15,35 +19,26 @@ export default function JsonDiffInput({
|
||||
value,
|
||||
onChange,
|
||||
error,
|
||||
minRows = 10,
|
||||
className,
|
||||
...props
|
||||
}: JsonDiffInputProps) {
|
||||
return (
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Typography
|
||||
variant="caption"
|
||||
sx={{
|
||||
display: 'block',
|
||||
mb: 0.6,
|
||||
fontWeight: 800,
|
||||
fontSize: '0.7rem',
|
||||
letterSpacing: 0.4,
|
||||
color: 'text.secondary',
|
||||
textTransform: 'uppercase',
|
||||
}}
|
||||
>
|
||||
<div className={cn('flex-1 min-w-0 flex flex-col', className)} {...props}>
|
||||
<span className="block mb-2 text-[10px] font-bold tracking-wide text-muted-foreground/80 uppercase select-none px-0.5">
|
||||
{label}
|
||||
</Typography>
|
||||
</span>
|
||||
|
||||
<TextInputArea
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
placeholder={placeholder}
|
||||
minRows={8}
|
||||
autoResize={false}
|
||||
minRows={minRows}
|
||||
maxRows={16}
|
||||
externalError={error ?? undefined}
|
||||
showClear={true}
|
||||
allowCopy={true}
|
||||
/>
|
||||
</Box>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export { JsonDiffInput };
|
||||
export type { JsonDiffInputProps };
|
||||
|
||||
@@ -1,236 +1,169 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
FormControlLabel,
|
||||
FormHelperText,
|
||||
Stack,
|
||||
Switch,
|
||||
TextField,
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import {
|
||||
formatJson,
|
||||
validateJson,
|
||||
type JsonFormatOptions,
|
||||
type JsonFormatResult,
|
||||
validateJson,
|
||||
} from '@/utils/jsonFormatter';
|
||||
import { formatByteSize } from '@/utils/textStatistics';
|
||||
import { useSnackbar } from '@/components/GlobalSnackbar';
|
||||
import { jsonDiffPageStyles } from '@/config/pageTheme';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Label } from '@/components/ui/label';
|
||||
|
||||
/** 缩进大小选项 */
|
||||
const INDENT_OPTIONS = [2, 4, 6, 8] as const;
|
||||
|
||||
/**
|
||||
* JSON 格式化工具区域组件
|
||||
*
|
||||
* 提供输入区域、格式化选项(缩进大小、键名排序)和格式化结果展示,
|
||||
* 支持一键复制格式化后的 JSON。
|
||||
*/
|
||||
export default function JsonFormatSection() {
|
||||
const { t } = useLazyTranslation('jsonFormat');
|
||||
const { showMessage } = useSnackbar();
|
||||
|
||||
const [input, setInput] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [debouncedInput, setDebouncedInput] = useState('');
|
||||
const [indentSize, setIndentSize] = useState<number>(2);
|
||||
const [sortKeys, setSortKeys] = useState(false);
|
||||
const [result, setResult] = useState<JsonFormatResult | null>(null);
|
||||
|
||||
// 防抖校验输入
|
||||
// 1. 高频打字防抖落盘:防止大体积 JSON 在高频输入时发生卡顿
|
||||
useEffect(() => {
|
||||
const handle = setTimeout(() => {
|
||||
setError(validateJson(input));
|
||||
}, 300);
|
||||
setDebouncedInput(input);
|
||||
}, 250);
|
||||
return () => clearTimeout(handle);
|
||||
}, [input]);
|
||||
|
||||
const canFormat = useMemo(() => {
|
||||
return input.trim() !== '' && !error;
|
||||
}, [input, error]);
|
||||
// 💡 2. 贯彻方案 A(衍生变量超进化):
|
||||
// 彻底删除原有的 setError 状态和相关的 useEffect。
|
||||
// 语法错误由防抖文本在内存中同步推导,彻底斩断二次级联渲染链条,ESLint 警告瞬间消亡!
|
||||
const error = useMemo(() => {
|
||||
return validateJson(debouncedInput);
|
||||
}, [debouncedInput]);
|
||||
|
||||
const handleFormat = () => {
|
||||
const validationError = validateJson(input);
|
||||
if (validationError) {
|
||||
setError(validationError);
|
||||
setResult(null);
|
||||
return;
|
||||
}
|
||||
// 3. 实时流式格式化管线
|
||||
const formattedPipeline = useMemo(() => {
|
||||
const trimmed = debouncedInput.trim();
|
||||
if (!trimmed || error) return null;
|
||||
|
||||
try {
|
||||
const options: JsonFormatOptions = { indentSize, sortKeys };
|
||||
const formatResult = formatJson(input, options);
|
||||
setResult(formatResult);
|
||||
return formatJson(debouncedInput, options);
|
||||
} catch (e) {
|
||||
setError(e instanceof SyntaxError ? e.message : String(e));
|
||||
setResult(null);
|
||||
return {
|
||||
isRuntimeError: true,
|
||||
errorMessage: e instanceof SyntaxError ? e.message : String(e),
|
||||
};
|
||||
}
|
||||
};
|
||||
}, [debouncedInput, error, indentSize, sortKeys]);
|
||||
|
||||
const handleClear = () => {
|
||||
setInput('');
|
||||
setError(null);
|
||||
setResult(null);
|
||||
};
|
||||
const runtimeError =
|
||||
formattedPipeline && 'isRuntimeError' in formattedPipeline
|
||||
? formattedPipeline.errorMessage
|
||||
: null;
|
||||
const result =
|
||||
formattedPipeline && !('isRuntimeError' in formattedPipeline)
|
||||
? (formattedPipeline as JsonFormatResult)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<Stack spacing={2.5}>
|
||||
{/* 工具栏 */}
|
||||
<Stack
|
||||
direction={{ xs: 'column', sm: 'row' }}
|
||||
spacing={1.5}
|
||||
justifyContent="space-between"
|
||||
alignItems={{ xs: 'stretch', sm: 'center' }}
|
||||
>
|
||||
<Stack direction="row" spacing={1.5} alignItems="center">
|
||||
{/* 缩进选择 */}
|
||||
<Typography
|
||||
variant="caption"
|
||||
sx={{ fontWeight: 800, color: 'text.secondary', fontSize: '0.7rem' }}
|
||||
<div className="w-full flex flex-col gap-4 animate-in fade-in duration-300">
|
||||
{/* 工具控制栏 */}
|
||||
<div className="flex h-10 items-center justify-between px-1.5 bg-secondary/40 rounded-xl border border-border/60">
|
||||
<div className="flex gap-4 items-center w-full">
|
||||
{/* 缩进配置区 */}
|
||||
<div className="flex gap-2 items-center shrink-0 select-none">
|
||||
<span className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider">
|
||||
{t('jsonFormat:indentSize')}
|
||||
</span>
|
||||
<SwitchButtonGroup
|
||||
value={indentSize}
|
||||
onChange={(v) => setIndentSize(Number(v))}
|
||||
options={[2, 4, 6, 8].map((size) => ({ value: size, label: String(size) }))}
|
||||
size="small"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="h-4 w-px bg-border/60" />
|
||||
|
||||
{/* 键名排序区 */}
|
||||
<div
|
||||
onClick={() => setSortKeys(!sortKeys)}
|
||||
className="flex items-center gap-2 cursor-pointer select-none group py-1"
|
||||
>
|
||||
{t('jsonFormat:indentSize')}
|
||||
</Typography>
|
||||
<SwitchButtonGroup
|
||||
value={indentSize}
|
||||
onChange={(v) => setIndentSize(v)}
|
||||
options={INDENT_OPTIONS.map((size) => ({ value: size, label: String(size) }))}
|
||||
sx={{ width: 'auto', mb: 0, flexShrink: 0 }}
|
||||
size="small"
|
||||
/>
|
||||
<Checkbox
|
||||
id="sort-keys-checkbox"
|
||||
checked={sortKeys}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onCheckedChange={(checked) => setSortKeys(checked === true)}
|
||||
className="h-3.5 w-3.5 rounded border-input data-[state=checked]:bg-primary shadow-sm"
|
||||
/>
|
||||
<Label
|
||||
htmlFor="sort-keys-checkbox"
|
||||
className="text-xs font-bold text-foreground/80 cursor-pointer tracking-tight group-hover:text-foreground transition-colors"
|
||||
>
|
||||
{t('jsonFormat:sortKeys')}
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 键名排序开关 */}
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch
|
||||
size="small"
|
||||
checked={sortKeys}
|
||||
onChange={(e) => setSortKeys(e.target.checked)}
|
||||
/>
|
||||
}
|
||||
label={
|
||||
<Typography variant="caption" sx={{ fontWeight: 700, fontSize: '0.7rem' }}>
|
||||
{t('jsonFormat:sortKeys')}
|
||||
</Typography>
|
||||
}
|
||||
sx={{ ml: 1 }}
|
||||
/>
|
||||
</Stack>
|
||||
{/* 满血版输入终端 */}
|
||||
<TextInputArea
|
||||
placeholder={t('jsonFormat:inputPlaceholder')}
|
||||
value={input}
|
||||
onChange={setInput}
|
||||
externalError={error || runtimeError || undefined}
|
||||
showClear={true}
|
||||
allowCopy={true}
|
||||
minRows={8}
|
||||
maxRows={15}
|
||||
onClear={() => setInput('')}
|
||||
/>
|
||||
|
||||
<Stack direction="row" spacing={1}>
|
||||
<Button variant="text" onClick={handleClear} sx={{ borderRadius: 3 }}>
|
||||
{t('jsonFormat:clearButton')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={!canFormat}
|
||||
onClick={handleFormat}
|
||||
sx={{ borderRadius: 3, fontWeight: 700, px: 3 }}
|
||||
>
|
||||
{t('jsonFormat:formatButton')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Stack>
|
||||
|
||||
{/* 输入区 */}
|
||||
<Box>
|
||||
<TextField
|
||||
multiline
|
||||
rows={6}
|
||||
fullWidth
|
||||
placeholder={t('jsonFormat:inputPlaceholder')}
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
error={Boolean(error)}
|
||||
sx={jsonDiffPageStyles.INPUT_STYLE}
|
||||
/>
|
||||
{error && (
|
||||
<FormHelperText error sx={{ mx: 1.5, mt: 0.5, fontWeight: 600 }}>
|
||||
{t('jsonFormat:invalidJson')}
|
||||
</FormHelperText>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* 格式化结果 */}
|
||||
{/* 格式化结果流面板展示 */}
|
||||
{result && result.formatted ? (
|
||||
<Box
|
||||
sx={{
|
||||
position: 'relative',
|
||||
borderRadius: 3,
|
||||
bgcolor: 'background.paper',
|
||||
border: '1px solid',
|
||||
borderColor: 'divider',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{/* 结果头部 */}
|
||||
<Stack
|
||||
direction="row"
|
||||
justifyContent="space-between"
|
||||
alignItems="center"
|
||||
sx={{
|
||||
px: 2,
|
||||
py: 1,
|
||||
borderBottom: '1px solid',
|
||||
borderColor: 'divider',
|
||||
bgcolor: (theme) =>
|
||||
theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.03)' : 'grey.50',
|
||||
}}
|
||||
>
|
||||
<Stack direction="row" spacing={2} alignItems="center">
|
||||
<Typography
|
||||
variant="caption"
|
||||
sx={{ fontWeight: 800, color: 'text.secondary', fontSize: '0.7rem' }}
|
||||
>
|
||||
<div className="relative rounded-xl border border-border bg-card text-card-foreground shadow-sm overflow-hidden animate-in slide-in-from-bottom-2 duration-300">
|
||||
{/* 结果栏头部 */}
|
||||
<div className="flex h-9 items-center justify-between px-4 border-b border-border bg-muted/50 select-none">
|
||||
<div className="flex gap-4 items-center">
|
||||
<span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/90">
|
||||
{t('jsonFormat:outputLabel')}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ color: 'text.disabled', fontSize: '0.65rem' }}>
|
||||
{t('jsonFormat:originalSize')}: {formatByteSize(result.originalBytes)}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ color: 'text.disabled', fontSize: '0.65rem' }}>
|
||||
{t('jsonFormat:formattedSize')}: {formatByteSize(result.formattedBytes)}
|
||||
</Typography>
|
||||
</Stack>
|
||||
<CopyButton text={result.formatted} showMessage={showMessage} />
|
||||
</Stack>
|
||||
</span>
|
||||
|
||||
{/* 格式化内容 */}
|
||||
<Box
|
||||
sx={{
|
||||
p: 2,
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.8rem',
|
||||
whiteSpace: 'pre-wrap',
|
||||
wordBreak: 'break-all',
|
||||
maxHeight: 400,
|
||||
overflowY: 'auto',
|
||||
lineHeight: 1.6,
|
||||
}}
|
||||
>
|
||||
<div className="hidden sm:flex gap-3 items-center font-mono text-[10px] text-muted-foreground/70 tabular-nums">
|
||||
<span>
|
||||
{t('jsonFormat:originalSize')}:{' '}
|
||||
<span className="font-semibold text-foreground/80">
|
||||
{formatByteSize(result.originalBytes)}
|
||||
</span>
|
||||
</span>
|
||||
<span className="text-border/60">|</span>
|
||||
<span>
|
||||
{t('jsonFormat:formattedSize')}:{' '}
|
||||
<span className="font-semibold text-foreground/80">
|
||||
{formatByteSize(result.formattedBytes)}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<CopyButton
|
||||
text={result.formatted}
|
||||
className="h-6 w-6 rounded-md border text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 核心格式化数据面板:
|
||||
💡 修复点:移除了互相打架的 select-all 类名,仅保留纯正的代码高亮可选样式 select-text
|
||||
*/}
|
||||
<div className="p-4 font-mono text-xs text-foreground/90 whitespace-pre-wrap break-all max-h-[420px] overflow-y-auto leading-relaxed select-text">
|
||||
{result.formatted}
|
||||
</Box>
|
||||
</Box>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<Box
|
||||
sx={{
|
||||
p: 3,
|
||||
borderRadius: 3,
|
||||
bgcolor: (theme) =>
|
||||
theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.03)' : 'grey.50',
|
||||
border: '1px dashed',
|
||||
borderColor: (theme) =>
|
||||
theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.15)' : 'grey.300',
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ fontWeight: 600 }}>
|
||||
{t('jsonFormat:emptyHint')}
|
||||
</Typography>
|
||||
</Box>
|
||||
/* 空状态指示引导区 */
|
||||
<div className="p-8 rounded-xl bg-muted/30 border border-dashed border-border/80 text-center flex flex-col items-center justify-center min-h-[120px] select-none">
|
||||
<p className="text-xs font-semibold text-muted-foreground/80 tracking-wide max-w-[240px] leading-relaxed">
|
||||
{error ? '请修正上方 JSON 语法错误以开启实时流式格式化' : t('jsonFormat:emptyHint')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</Stack>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+196
-200
@@ -1,12 +1,11 @@
|
||||
import { Box, Collapse, useTheme } from '@mui/material';
|
||||
import type { Theme } from '@mui/material/styles';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { surfaceTint } from '@/config/pageTheme';
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { ChevronDown, ChevronRight } from 'lucide-react'; // 用正统的矢量箭头平替原生的字符 '▾' '▸'
|
||||
import type { DiffNode, DiffType } from './types';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export type TreeSide = 'left' | 'right';
|
||||
|
||||
interface JsonTreeProps {
|
||||
export interface JsonTreeProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
node: DiffNode;
|
||||
side: TreeSide;
|
||||
defaultExpandDepth?: number;
|
||||
@@ -29,10 +28,6 @@ const formatPrimitive = (v: unknown): string => {
|
||||
return JSON.stringify(v);
|
||||
};
|
||||
|
||||
/**
|
||||
* 决定当前节点在指定一侧是否需要渲染。
|
||||
* 例如:'added' 节点只在 right 侧出现,'removed' 节点只在 left 侧出现。
|
||||
*/
|
||||
const shouldRenderOnSide = (type: DiffType, side: TreeSide): boolean => {
|
||||
if (type === 'added') return side === 'right';
|
||||
if (type === 'removed') return side === 'left';
|
||||
@@ -43,230 +38,231 @@ const getValueForSide = (node: DiffNode, side: TreeSide): unknown => {
|
||||
return side === 'left' ? node.oldValue : node.newValue;
|
||||
};
|
||||
|
||||
const getRowBg = (type: DiffType, side: TreeSide, theme: Theme): string | undefined => {
|
||||
if (!shouldRenderOnSide(type, side)) return undefined;
|
||||
if (type === 'added') return surfaceTint(theme, theme.palette.success.main, 0.15);
|
||||
if (type === 'removed') return surfaceTint(theme, theme.palette.error.main, 0.15);
|
||||
if (type === 'modified') return surfaceTint(theme, theme.palette.warning.main, 0.15);
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const getValueColor = (type: DiffType, side: TreeSide): string | undefined => {
|
||||
if (!shouldRenderOnSide(type, side)) return undefined;
|
||||
if (type === 'added') return 'success.main';
|
||||
if (type === 'removed') return 'error.main';
|
||||
if (type === 'modified') return 'warning.main';
|
||||
return undefined;
|
||||
// 1. 核心状态色彩映射调色盘:完美自适应双色模式
|
||||
const typeThemeMap = {
|
||||
added: {
|
||||
text: 'text-emerald-600 dark:text-emerald-400',
|
||||
bg: 'bg-emerald-500/5 dark:bg-emerald-500/10 hover:bg-emerald-500/10 dark:hover:bg-emerald-500/15',
|
||||
},
|
||||
removed: {
|
||||
text: 'text-destructive',
|
||||
bg: 'bg-destructive/5 dark:bg-destructive/10 hover:bg-destructive/10 dark:hover:bg-destructive/15',
|
||||
},
|
||||
modified: {
|
||||
text: 'text-amber-600 dark:text-amber-400',
|
||||
bg: 'bg-amber-500/5 dark:bg-amber-500/10 hover:bg-amber-500/10 dark:hover:bg-amber-500/15',
|
||||
},
|
||||
unchanged: {
|
||||
text: 'text-foreground/80',
|
||||
bg: 'hover:bg-muted/60',
|
||||
},
|
||||
};
|
||||
|
||||
const isContainerValue = (v: unknown): boolean => {
|
||||
return (typeof v === 'object' && v !== null) || Array.isArray(v);
|
||||
};
|
||||
|
||||
const NodeRow = ({
|
||||
node,
|
||||
side,
|
||||
depth,
|
||||
defaultExpandDepth,
|
||||
activePath,
|
||||
isLastChild,
|
||||
}: NodeRowProps) => {
|
||||
// 'auto' = follow defaults + activePath; otherwise user explicitly toggled
|
||||
const [override, setOverride] = useState<'auto' | 'open' | 'closed'>('auto');
|
||||
const rowRef = useRef<HTMLDivElement | null>(null);
|
||||
const theme = useTheme();
|
||||
/**
|
||||
* 💡 性能调优大闸:将 NodeRow 抽离为顶层独立组件并裹上 React.memo。
|
||||
* 配合精准的 Props Diff,使得某一行的展开闭合绝对不会连累到其他平级和上级节点。
|
||||
*/
|
||||
const NodeRow = React.memo(
|
||||
({ node, side, depth, defaultExpandDepth, activePath, isLastChild }: NodeRowProps) => {
|
||||
const [override, setOverride] = useState<'auto' | 'open' | 'closed'>('auto');
|
||||
const rowRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
const onActivePath = Boolean(
|
||||
activePath &&
|
||||
(activePath === node.path ||
|
||||
activePath.startsWith(`${node.path}.`) ||
|
||||
activePath.startsWith(`${node.path}[`)),
|
||||
);
|
||||
const onActivePath = useMemo(() => {
|
||||
return Boolean(
|
||||
activePath &&
|
||||
(activePath === node.path ||
|
||||
activePath.startsWith(`${node.path}.`) ||
|
||||
activePath.startsWith(`${node.path}[`)),
|
||||
);
|
||||
}, [activePath, node.path]);
|
||||
|
||||
const expanded =
|
||||
override === 'open'
|
||||
? true
|
||||
: override === 'closed'
|
||||
? false
|
||||
: onActivePath || depth < defaultExpandDepth;
|
||||
const expanded =
|
||||
override === 'open'
|
||||
? true
|
||||
: override === 'closed'
|
||||
? false
|
||||
: onActivePath || depth < defaultExpandDepth;
|
||||
|
||||
// 当激活路径定位到本节点时滚动到视图中心(仅 DOM 副作用,不更新 state)
|
||||
useEffect(() => {
|
||||
if (activePath === node.path) {
|
||||
rowRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
}
|
||||
}, [activePath, node.path]);
|
||||
// 当激活路径精准定位到本行时,平滑滚动至容器中心
|
||||
useEffect(() => {
|
||||
if (activePath === node.path) {
|
||||
rowRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
}
|
||||
}, [activePath, node.path]);
|
||||
|
||||
if (!shouldRenderOnSide(node.type, side)) {
|
||||
// 渲染占位空行以保持左右两侧高度一致
|
||||
return <Box sx={{ pl: depth * 1.5, color: 'transparent', userSelect: 'none' }}>·</Box>;
|
||||
}
|
||||
|
||||
const value = getValueForSide(node, side);
|
||||
const isContainer = isContainerValue(value) && Array.isArray(node.children);
|
||||
const isArray = Array.isArray(value);
|
||||
const bg = getRowBg(node.type, side, theme);
|
||||
const valueColor = getValueColor(node.type, side);
|
||||
const isActive = activePath === node.path;
|
||||
|
||||
// 根节点渲染
|
||||
const isRoot = depth === 0;
|
||||
|
||||
if (isContainer && node.children) {
|
||||
const open = isArray ? '[' : '{';
|
||||
const close = isArray ? ']' : '}';
|
||||
return (
|
||||
<Box ref={rowRef}>
|
||||
<Box
|
||||
onClick={() => setOverride(expanded ? 'closed' : 'open')}
|
||||
sx={{
|
||||
cursor: 'pointer',
|
||||
pl: depth * 1.5,
|
||||
pr: 1,
|
||||
py: 0.2,
|
||||
bgcolor: bg,
|
||||
outline: isActive ? '2px solid' : 'none',
|
||||
outlineColor: 'primary.main',
|
||||
borderRadius: 0.5,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 0.5,
|
||||
whiteSpace: 'nowrap',
|
||||
'&:hover': { bgcolor: bg ?? 'action.hover' },
|
||||
}}
|
||||
// 占位空行分支:必须加 h-[22px] 锁定绝对等高,防止两侧文本高度塌陷发生高低错位
|
||||
if (!shouldRenderOnSide(node.type, side)) {
|
||||
return (
|
||||
<div
|
||||
className="text-transparent select-none opacity-0 h-[22px] leading-relaxed"
|
||||
style={{ paddingLeft: `${depth * 1.15}rem` }}
|
||||
>
|
||||
<Box component="span" sx={{ width: 12, color: 'text.secondary', fontSize: '0.7rem' }}>
|
||||
{expanded ? '▾' : '▸'}
|
||||
</Box>
|
||||
{!isRoot && (
|
||||
<Box component="span" sx={{ color: 'text.primary', fontWeight: 700 }}>
|
||||
{isArrayKeyDisplay(node.key)}:
|
||||
</Box>
|
||||
·
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const value = getValueForSide(node, side);
|
||||
const isContainer = isContainerValue(value) && Array.isArray(node.children);
|
||||
const isArray = Array.isArray(value);
|
||||
const theme = typeThemeMap[node.type] || typeThemeMap.unchanged;
|
||||
const isActive = activePath === node.path;
|
||||
const isRoot = depth === 0;
|
||||
|
||||
// 缩进样式封装:
|
||||
// 💡 视觉魔法:通过在左侧追加 before 细线,在每一层级下自动垂下一条优雅的 IDE 级“缩进指引线”
|
||||
const indentStyle = {
|
||||
paddingLeft: `${Math.max(0.25, depth * 1.15)}rem`,
|
||||
};
|
||||
|
||||
const indentClass = cn(
|
||||
'relative',
|
||||
depth > 0 &&
|
||||
'before:absolute before:left-[4px] before:top-0 before:bottom-0 before:w-[1px] before:bg-border/40',
|
||||
);
|
||||
|
||||
if (isContainer && node.children) {
|
||||
const open = isArray ? '[' : '{';
|
||||
const close = isArray ? ']' : '}';
|
||||
|
||||
return (
|
||||
<div ref={rowRef} className="w-full flex flex-col">
|
||||
{/* 大容器开端行 */}
|
||||
<div
|
||||
onClick={() => setOverride(expanded ? 'closed' : 'open')}
|
||||
className={cn(
|
||||
'group flex items-center gap-1 py-0.5 pr-2 text-xs font-mono select-none cursor-pointer rounded-sm transition-colors w-full h-[22px] leading-relaxed',
|
||||
theme.bg,
|
||||
isActive &&
|
||||
'bg-primary/10 relative before:absolute before:left-0 before:top-0 before:bottom-0 before:w-0.5 before:bg-blue-500 rounded-none ring-0',
|
||||
)}
|
||||
style={indentStyle}
|
||||
>
|
||||
{/* 折叠小箭头:升级为精巧的 Lucide SVG 矢量微动效 */}
|
||||
<span className="w-3.5 h-3.5 flex items-center justify-center text-muted-foreground/80 shrink-0">
|
||||
{expanded ? (
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
) : (
|
||||
<ChevronRight className="h-3 w-3" />
|
||||
)}
|
||||
</span>
|
||||
|
||||
{!isRoot && (
|
||||
<span className="text-foreground/90 font-bold tracking-tight">{node.key}:</span>
|
||||
)}
|
||||
|
||||
<span className="text-muted-foreground/80 font-semibold">{open}</span>
|
||||
|
||||
{!expanded && (
|
||||
<span className="text-[10px] px-1.5 py-0.2 rounded bg-muted/80 text-muted-foreground font-sans font-medium mx-1 select-none">
|
||||
{summarize(value)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{!expanded && (
|
||||
<span className="text-muted-foreground/80 font-semibold">
|
||||
{close}
|
||||
{isLastChild ? '' : ','}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 容器子节点递归区 */}
|
||||
{expanded && (
|
||||
<div className={indentClass}>
|
||||
{node.children.map((child, idx) => (
|
||||
<NodeRow
|
||||
key={child.path}
|
||||
node={child}
|
||||
side={side}
|
||||
depth={depth + 1}
|
||||
defaultExpandDepth={defaultExpandDepth}
|
||||
activePath={activePath}
|
||||
isLastChild={idx === node.children!.length - 1}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<Box component="span" sx={{ color: 'text.secondary' }}>
|
||||
{open}
|
||||
</Box>
|
||||
{!expanded && (
|
||||
<Box component="span" sx={{ color: 'text.disabled', fontStyle: 'italic' }}>
|
||||
{summarize(value)}
|
||||
</Box>
|
||||
)}
|
||||
{!expanded && (
|
||||
<Box component="span" sx={{ color: 'text.secondary' }}>
|
||||
|
||||
{/* 大容器收尾行 */}
|
||||
{expanded && (
|
||||
<div
|
||||
className="text-muted-foreground/80 font-mono text-xs py-0.5 h-[22px] leading-relaxed"
|
||||
style={{ paddingLeft: `${depth * 1.15 + 0.88}rem` }}
|
||||
>
|
||||
{close}
|
||||
{isLastChild ? '' : ','}
|
||||
</Box>
|
||||
</div>
|
||||
)}
|
||||
</Box>
|
||||
<Collapse in={expanded} unmountOnExit>
|
||||
<Box>
|
||||
{node.children.map((child, idx) => (
|
||||
<NodeRow
|
||||
key={child.path}
|
||||
node={child}
|
||||
side={side}
|
||||
depth={depth + 1}
|
||||
defaultExpandDepth={defaultExpandDepth}
|
||||
activePath={activePath}
|
||||
isLastChild={idx === node.children!.length - 1}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
pl: depth * 1.5,
|
||||
color: 'text.secondary',
|
||||
whiteSpace: 'nowrap',
|
||||
ml: '17px',
|
||||
}}
|
||||
>
|
||||
{close}
|
||||
{isLastChild ? '' : ','}
|
||||
</Box>
|
||||
</Collapse>
|
||||
</Box>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 叶子数据行分支
|
||||
return (
|
||||
<div
|
||||
ref={rowRef}
|
||||
className={cn(
|
||||
'flex items-center gap-1 py-0.5 pr-2 font-mono text-xs w-full h-[22px] leading-relaxed rounded-sm transition-colors',
|
||||
theme.bg,
|
||||
isActive &&
|
||||
'bg-primary/10 relative before:absolute before:left-0 before:top-0 before:bottom-0 before:w-0.5 before:bg-blue-500 rounded-none ring-0',
|
||||
)}
|
||||
style={indentStyle}
|
||||
>
|
||||
<span className="w-3.5 shrink-0" /> {/* 与上方的折叠键轴线严格对齐 */}
|
||||
{!isRoot && (
|
||||
<span className="text-foreground/90 font-bold tracking-tight">{node.key}:</span>
|
||||
)}
|
||||
<span className={cn('font-medium tracking-tight truncate flex-1', theme.text)}>
|
||||
{formatPrimitive(value)}
|
||||
<span className="text-foreground/60 font-sans">{isLastChild ? '' : ','}</span>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// 叶子节点
|
||||
return (
|
||||
<Box
|
||||
ref={rowRef}
|
||||
sx={{
|
||||
pl: depth * 1.5,
|
||||
pr: 1,
|
||||
py: 0.2,
|
||||
bgcolor: bg,
|
||||
outline: isActive ? '2px solid' : 'none',
|
||||
outlineColor: 'primary.main',
|
||||
borderRadius: 0.5,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 0.5,
|
||||
whiteSpace: 'nowrap',
|
||||
}}
|
||||
>
|
||||
<Box component="span" sx={{ width: 12 }} />
|
||||
{!isRoot && (
|
||||
<Box component="span" sx={{ color: 'text.primary', fontWeight: 700 }}>
|
||||
{isArrayKeyDisplay(node.key)}:
|
||||
</Box>
|
||||
)}
|
||||
<Box component="span" sx={{ color: valueColor ?? 'text.primary' }}>
|
||||
{formatPrimitive(value)}
|
||||
{isLastChild ? '' : ','}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const isArrayKeyDisplay = (key: string): string => {
|
||||
// 数组索引在父级渲染中已加方括号;这里仅显示对象键名
|
||||
return key;
|
||||
};
|
||||
|
||||
const summarize = (v: unknown): string => {
|
||||
if (Array.isArray(v)) return ` ${v.length} ${v.length === 1 ? 'item' : 'items'} `;
|
||||
if (v && typeof v === 'object') {
|
||||
const n = Object.keys(v).length;
|
||||
return ` ${n} ${n === 1 ? 'key' : 'keys'} `;
|
||||
}
|
||||
return '';
|
||||
};
|
||||
NodeRow.displayName = 'NodeRow';
|
||||
|
||||
export default function JsonTree({
|
||||
node,
|
||||
side,
|
||||
defaultExpandDepth = 2,
|
||||
activePath,
|
||||
className,
|
||||
...props
|
||||
}: JsonTreeProps) {
|
||||
const sideKey = useMemo(() => side, [side]);
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
p: 1.5,
|
||||
borderRadius: 3,
|
||||
bgcolor: 'background.paper',
|
||||
border: '1px solid',
|
||||
borderColor: 'divider',
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.8rem',
|
||||
overflowX: 'auto',
|
||||
minHeight: 200,
|
||||
maxHeight: 480,
|
||||
overflowY: 'auto',
|
||||
}}
|
||||
/* 最外层承载器:统一收拢至标准的 bg-card 与等宽 tabular-nums 控制轴 */
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-xl border border-border bg-card text-card-foreground font-mono text-xs shadow-sm overflow-x-auto min-h-[200px] max-h-[520px] overflow-y-auto p-2.5 tabular-nums select-text',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<NodeRow
|
||||
node={node}
|
||||
side={sideKey}
|
||||
side={side}
|
||||
depth={0}
|
||||
defaultExpandDepth={defaultExpandDepth}
|
||||
activePath={activePath}
|
||||
isLastChild
|
||||
/>
|
||||
</Box>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export type { JsonTreeProps };
|
||||
const summarize = (v: unknown): string => {
|
||||
if (Array.isArray(v)) return `${v.length} ${v.length === 1 ? 'item' : 'items'}`;
|
||||
if (v && typeof v === 'object') {
|
||||
const n = Object.keys(v).length;
|
||||
return `${n} ${n === 1 ? 'key' : 'keys'}`;
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
@@ -10,17 +10,22 @@ const isObject = (v: unknown): v is Record<string, unknown> =>
|
||||
|
||||
const isArray = (v: unknown): v is unknown[] => Array.isArray(v);
|
||||
|
||||
/**
|
||||
* 健壮的 JSONPath 生成器:支持针对包含点号、空格或特殊字符的键名进行括号转义拦截
|
||||
*/
|
||||
const buildPath = (parent: string, key: string, isArrayChild: boolean): string => {
|
||||
if (parent === ROOT_PATH) {
|
||||
return isArrayChild ? `${ROOT_PATH}[${key}]` : `${ROOT_PATH}.${key}`;
|
||||
if (isArrayChild) {
|
||||
return `${parent}[${key}]`;
|
||||
}
|
||||
return isArrayChild ? `${parent}[${key}]` : `${parent}.${key}`;
|
||||
const needsEscaping = key.includes('.') || key.includes('[') || key.includes(' ');
|
||||
const formattedKey = needsEscaping ? `["${key}"]` : `.${key}`;
|
||||
|
||||
return parent === ROOT_PATH ? `${ROOT_PATH}${formattedKey}` : `${parent}${formattedKey}`;
|
||||
};
|
||||
|
||||
const primitiveEqual = (a: unknown, b: unknown): boolean => {
|
||||
// NaN handling: treat NaN === NaN as equal for diff purposes
|
||||
if (typeof a === 'number' && typeof b === 'number' && Number.isNaN(a) && Number.isNaN(b)) {
|
||||
return true;
|
||||
if (typeof a === 'number' && typeof b === 'number') {
|
||||
return Object.is(a, b);
|
||||
}
|
||||
return a === b;
|
||||
};
|
||||
@@ -32,27 +37,31 @@ const diffNode = (
|
||||
path: string,
|
||||
diffPaths: string[],
|
||||
): DiffNode => {
|
||||
// Added: left missing, right present
|
||||
// 分支 1:节点增加行为拦截 (叶子节点状态)
|
||||
if (left === SENTINEL && right !== SENTINEL) {
|
||||
diffPaths.push(path);
|
||||
return {
|
||||
key,
|
||||
type: 'added',
|
||||
oldValue: undefined, // 💡 补齐:对齐移除 ? 后的类型规范
|
||||
newValue: right,
|
||||
path,
|
||||
isLeaf: !isObject(right) && !isArray(right),
|
||||
hasDiffInChildren: false, // 自身即是新增,子树无需向下检索
|
||||
};
|
||||
}
|
||||
|
||||
// Removed: right missing, left present
|
||||
// 分支 2:节点删除行为拦截 (叶子节点状态)
|
||||
if (right === SENTINEL && left !== SENTINEL) {
|
||||
diffPaths.push(path);
|
||||
return {
|
||||
key,
|
||||
type: 'removed',
|
||||
oldValue: left,
|
||||
newValue: undefined, // 💡 补齐:对齐移除 ? 后的类型规范
|
||||
path,
|
||||
isLeaf: !isObject(left) && !isArray(left),
|
||||
hasDiffInChildren: false, // 自身即是删除,子树无需向下检索
|
||||
};
|
||||
}
|
||||
|
||||
@@ -61,72 +70,99 @@ const diffNode = (
|
||||
const leftArr = isArray(left);
|
||||
const rightArr = isArray(right);
|
||||
|
||||
// Both objects
|
||||
// 分支 3:双对象深层递归 (容器状态)
|
||||
if (leftObj && rightObj) {
|
||||
const keys = Array.from(new Set([...Object.keys(left), ...Object.keys(right)]));
|
||||
const children: DiffNode[] = keys.map((k) => {
|
||||
const keySet = new Set<string>();
|
||||
const leftKeys = Object.keys(left);
|
||||
const rightKeys = Object.keys(right);
|
||||
|
||||
for (let i = 0; i < leftKeys.length; i++) keySet.add(leftKeys[i]);
|
||||
for (let i = 0; i < rightKeys.length; i++) keySet.add(rightKeys[i]);
|
||||
|
||||
const children: DiffNode[] = [];
|
||||
keySet.forEach((k) => {
|
||||
const childPath = buildPath(path, k, false);
|
||||
const l: MaybeMissing = k in left ? left[k] : SENTINEL;
|
||||
const r: MaybeMissing = k in right ? right[k] : SENTINEL;
|
||||
return diffNode(l, r, k, childPath, diffPaths);
|
||||
children.push(diffNode(l, r, k, childPath, diffPaths));
|
||||
});
|
||||
const allUnchanged = children.every((c) => c.type === 'unchanged');
|
||||
|
||||
// 💡 核心改良:判定子节点中是否存在任何变动
|
||||
const hasDiffInChildren = children.some((c) => c.type !== 'unchanged' || c.hasDiffInChildren);
|
||||
|
||||
return {
|
||||
key,
|
||||
type: allUnchanged ? 'unchanged' : 'modified',
|
||||
type: hasDiffInChildren ? 'modified' : 'unchanged',
|
||||
oldValue: left,
|
||||
newValue: right,
|
||||
children,
|
||||
path,
|
||||
isLeaf: false,
|
||||
hasDiffInChildren, // 完美注入预计算衍生状态
|
||||
};
|
||||
}
|
||||
|
||||
// Both arrays
|
||||
// 分支 4:双数组深层按序递归 (容器状态)
|
||||
if (leftArr && rightArr) {
|
||||
const len = Math.max(left.length, right.length);
|
||||
const children: DiffNode[] = [];
|
||||
const children: DiffNode[] = new Array(len);
|
||||
|
||||
for (let i = 0; i < len; i++) {
|
||||
const k = String(i);
|
||||
const childPath = buildPath(path, k, true);
|
||||
const l: MaybeMissing = i < left.length ? left[i] : SENTINEL;
|
||||
const r: MaybeMissing = i < right.length ? right[i] : SENTINEL;
|
||||
children.push(diffNode(l, r, k, childPath, diffPaths));
|
||||
children[i] = diffNode(l, r, k, childPath, diffPaths);
|
||||
}
|
||||
const allUnchanged = children.every((c) => c.type === 'unchanged');
|
||||
|
||||
// 💡 核心改良:判定子项中是否存在任何变动
|
||||
const hasDiffInChildren = children.some((c) => c.type !== 'unchanged' || c.hasDiffInChildren);
|
||||
|
||||
return {
|
||||
key,
|
||||
type: allUnchanged ? 'unchanged' : 'modified',
|
||||
type: hasDiffInChildren ? 'modified' : 'unchanged',
|
||||
oldValue: left,
|
||||
newValue: right,
|
||||
children,
|
||||
path,
|
||||
isLeaf: false,
|
||||
hasDiffInChildren, // 完美注入预计算衍生状态
|
||||
};
|
||||
}
|
||||
|
||||
// Type mismatch (object vs array, object vs primitive, array vs primitive, etc.)
|
||||
// or both primitives
|
||||
// 分支 5:绝对类型安全防护大闸 (双基本基元比对)
|
||||
const leftIsContainer = leftObj || leftArr;
|
||||
const rightIsContainer = rightObj || rightArr;
|
||||
const sameKind =
|
||||
!leftIsContainer && !rightIsContainer && typeof left === typeof right && left !== null
|
||||
? primitiveEqual(left, right)
|
||||
: left === null && right === null
|
||||
? true
|
||||
: false;
|
||||
|
||||
if (sameKind) {
|
||||
return {
|
||||
key,
|
||||
type: 'unchanged',
|
||||
oldValue: left,
|
||||
newValue: right,
|
||||
path,
|
||||
isLeaf: true,
|
||||
};
|
||||
if (!leftIsContainer && !rightIsContainer) {
|
||||
if (left === null || right === null) {
|
||||
if (left === null && right === null) {
|
||||
return {
|
||||
key,
|
||||
type: 'unchanged',
|
||||
oldValue: left,
|
||||
newValue: right,
|
||||
path,
|
||||
isLeaf: true,
|
||||
hasDiffInChildren: false,
|
||||
};
|
||||
}
|
||||
} else if (typeof left === typeof right) {
|
||||
if (primitiveEqual(left, right)) {
|
||||
return {
|
||||
key,
|
||||
type: 'unchanged',
|
||||
oldValue: left,
|
||||
newValue: right,
|
||||
path,
|
||||
isLeaf: true,
|
||||
hasDiffInChildren: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 类型完全发生突变错配,或者基本数值不相等
|
||||
diffPaths.push(path);
|
||||
return {
|
||||
key,
|
||||
@@ -135,11 +171,12 @@ const diffNode = (
|
||||
newValue: right,
|
||||
path,
|
||||
isLeaf: !leftIsContainer && !rightIsContainer,
|
||||
hasDiffInChildren: false, // 变动在自身,后代无子树变动
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 比较两个 JSON 值的差异,返回差异树及差异路径列表。
|
||||
* 比较两个 JSON 值的差异,返回安全的差异树及高精度差异路径列表。
|
||||
*/
|
||||
export const diffJson = (left: unknown, right: unknown): DiffResult => {
|
||||
const diffPaths: string[] = [];
|
||||
|
||||
+140
-177
@@ -1,26 +1,21 @@
|
||||
import { useEffect, useMemo, useState, useCallback } from 'react';
|
||||
import { Box, Button, Container, Stack, Typography } from '@mui/material';
|
||||
import CompareArrowsIcon from '@mui/icons-material/CompareArrows';
|
||||
import DataObjectIcon from '@mui/icons-material/DataObject';
|
||||
import TransformIcon from '@mui/icons-material/Transform';
|
||||
import CompressIcon from '@mui/icons-material/Compress';
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { ArrowRightLeft, Braces, GitCompareArrows, Minimize2 } from 'lucide-react';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import PageHeader from '@/components/PageHeader';
|
||||
import { jsonDiffPageStyles } from '@/config/pageTheme';
|
||||
import JsonDiffInput from './JsonDiffInput';
|
||||
import DiffResult from './DiffResult';
|
||||
import DiffNavigator from './DiffNavigator';
|
||||
import JsonFormatSection from './JsonFormatSection';
|
||||
import JsonConvertSection from './JsonConvertSection';
|
||||
import type { ConvertFunction } from './JsonConvertSection';
|
||||
import JsonConvertSection from './JsonConvertSection';
|
||||
import { diffJson } from './diffEngine';
|
||||
import type { DiffResult as DiffResultType, ViewMode } from './types';
|
||||
import { jsonToYaml } from '@/utils/jsonToYaml';
|
||||
import { jsonToToml } from '@/utils/jsonToToml';
|
||||
import { minifyJson } from '@/utils/jsonFormatter';
|
||||
import { useStorageState } from '@/utils/useStorageState';
|
||||
import type { JsonToolsPageMode } from '@/types/storage';
|
||||
import SwtichButtonGroup from '@/components/SwitchButtonGroup';
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
import type { ViewMode } from './types';
|
||||
|
||||
interface ParseState {
|
||||
value: unknown;
|
||||
@@ -37,9 +32,7 @@ const tryParse = (raw: string, invalidMsg: string): ParseState => {
|
||||
}
|
||||
};
|
||||
|
||||
/** 页面模式 */
|
||||
const VALID_PAGE_MODES: readonly JsonToolsPageMode[] = ['diff', 'format', 'yaml', 'toml', 'minify'];
|
||||
|
||||
const isValidPageMode = (val: unknown): val is JsonToolsPageMode =>
|
||||
typeof val === 'string' && (VALID_PAGE_MODES as readonly string[]).includes(val);
|
||||
|
||||
@@ -48,67 +41,64 @@ type PageMode = JsonToolsPageMode;
|
||||
export default function Index() {
|
||||
const { t } = useLazyTranslation(['jsonDiff', 'jsonFormat']);
|
||||
const [pageMode, setPageMode] = useStorageState('jsonTools/pageMode', 'diff', isValidPageMode);
|
||||
|
||||
// 1. 受控原始输入源
|
||||
const [leftInput, setLeftInput] = useState('');
|
||||
const [rightInput, setRightInput] = useState('');
|
||||
const [leftError, setLeftError] = useState<string | null>(null);
|
||||
const [rightError, setRightError] = useState<string | null>(null);
|
||||
const [diffResult, setDiffResult] = useState<DiffResultType | null>(null);
|
||||
|
||||
// 2. 纯净的异步防抖管道:仅负责切断高频打字开销
|
||||
const [debouncedLeft, setDebouncedLeft] = useState('');
|
||||
const [debouncedRight, setDebouncedRight] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
const handle = setTimeout(() => {
|
||||
setDebouncedLeft(leftInput);
|
||||
setDebouncedRight(rightInput);
|
||||
}, 250);
|
||||
return () => clearTimeout(handle);
|
||||
}, [leftInput, rightInput]);
|
||||
|
||||
// 3. 贯彻方案A:利用 useMemo 将防抖文本同步转化为解析树和错误提示
|
||||
const parseState = useMemo(() => {
|
||||
const invalidMsg = t('jsonDiff:invalidJson');
|
||||
return {
|
||||
left: tryParse(debouncedLeft, invalidMsg),
|
||||
right: tryParse(debouncedRight, invalidMsg),
|
||||
};
|
||||
}, [debouncedLeft, debouncedRight, t]);
|
||||
|
||||
const leftError = parseState.left.error;
|
||||
const rightError = parseState.right.error;
|
||||
|
||||
const [viewMode, setViewMode] = useState<ViewMode>('sideBySide');
|
||||
const [currentDiffIndex, setCurrentDiffIndex] = useState(0);
|
||||
|
||||
// 防抖校验输入
|
||||
useEffect(() => {
|
||||
const handle = setTimeout(() => {
|
||||
const invalid = t('jsonDiff:invalidJson');
|
||||
setLeftError(tryParse(leftInput, invalid).error);
|
||||
setRightError(tryParse(rightInput, invalid).error);
|
||||
}, 300);
|
||||
return () => clearTimeout(handle);
|
||||
}, [leftInput, rightInput, t]);
|
||||
|
||||
const canCompare = useMemo(() => {
|
||||
return leftInput.trim() !== '' && rightInput.trim() !== '' && !leftError && !rightError;
|
||||
}, [leftInput, rightInput, leftError, rightError]);
|
||||
|
||||
const handleCompare = () => {
|
||||
const invalid = t('jsonDiff:invalidJson');
|
||||
const left = tryParse(leftInput, invalid);
|
||||
const right = tryParse(rightInput, invalid);
|
||||
setLeftError(left.error);
|
||||
setRightError(right.error);
|
||||
if (left.error || right.error) {
|
||||
setDiffResult(null);
|
||||
return;
|
||||
// 4. 实时比对流式计算
|
||||
const diffResult = useMemo(() => {
|
||||
const { left, right } = parseState;
|
||||
if (left.error || right.error || debouncedLeft.trim() === '' || debouncedRight.trim() === '') {
|
||||
return null;
|
||||
}
|
||||
const result = diffJson(left.value, right.value);
|
||||
setDiffResult(result);
|
||||
setCurrentDiffIndex(0);
|
||||
};
|
||||
return diffJson(left.value, right.value);
|
||||
}, [parseState, debouncedLeft, debouncedRight]);
|
||||
|
||||
const handleClear = () => {
|
||||
setLeftInput('');
|
||||
setRightInput('');
|
||||
setLeftError(null);
|
||||
setRightError(null);
|
||||
setDiffResult(null);
|
||||
setCurrentDiffIndex(0);
|
||||
};
|
||||
// 💡 彻底删除了原本在此处的侦听 [diffResult] 的 useEffect。
|
||||
// 状态重置已完全委托给事件源头,级联更新警告从根源上永久自愈!
|
||||
|
||||
const total = diffResult?.diffPaths.length ?? 0;
|
||||
|
||||
const handlePrev = () => {
|
||||
const handlePrev = useCallback(() => {
|
||||
if (total === 0) return;
|
||||
setCurrentDiffIndex((idx) => (idx - 1 + total) % total);
|
||||
};
|
||||
}, [total]);
|
||||
|
||||
const handleNext = () => {
|
||||
const handleNext = useCallback(() => {
|
||||
if (total === 0) return;
|
||||
setCurrentDiffIndex((idx) => (idx + 1) % total);
|
||||
};
|
||||
}, [total]);
|
||||
|
||||
const activePath = diffResult && total > 0 ? diffResult.diffPaths[currentDiffIndex] : undefined;
|
||||
|
||||
/** 页面模式对应的标题和副标题翻译键 */
|
||||
const modeTitles: Record<PageMode, { title: string; subtitle: string }> = {
|
||||
diff: { title: 'jsonDiff:pageTitle', subtitle: 'jsonDiff:pageSubtitle' },
|
||||
format: { title: 'jsonFormat:formatTitle', subtitle: 'jsonFormat:formatSubtitle' },
|
||||
@@ -118,11 +108,11 @@ export default function Index() {
|
||||
};
|
||||
|
||||
const modeIcon: Record<PageMode, React.ReactNode> = {
|
||||
diff: <CompareArrowsIcon />,
|
||||
format: <DataObjectIcon />,
|
||||
yaml: <TransformIcon />,
|
||||
toml: <TransformIcon />,
|
||||
minify: <CompressIcon />,
|
||||
diff: <GitCompareArrows className="h-4 w-4" />,
|
||||
format: <Braces className="h-4 w-4" />,
|
||||
yaml: <ArrowRightLeft className="h-4 w-4" />,
|
||||
toml: <ArrowRightLeft className="h-4 w-4" />,
|
||||
minify: <Minimize2 className="h-4 w-4" />,
|
||||
};
|
||||
|
||||
const yamlConvert: ConvertFunction = useCallback((text: string) => {
|
||||
@@ -141,126 +131,99 @@ export default function Index() {
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Container sx={{ p: 2 }}>
|
||||
<PageHeader
|
||||
title={t(modeTitles[pageMode].title)}
|
||||
subtitle={t(modeTitles[pageMode].subtitle)}
|
||||
icon={modeIcon[pageMode]}
|
||||
iconColor={jsonDiffPageStyles.primaryColor}
|
||||
/>
|
||||
<div className="p-4 w-full flex flex-col space-y-4 min-h-[500px] select-none animate-in fade-in duration-300">
|
||||
<PageHeader
|
||||
title={t(modeTitles[pageMode].title)}
|
||||
subtitle={t(modeTitles[pageMode].subtitle)}
|
||||
icon={modeIcon[pageMode]}
|
||||
iconColor="#3b82f6"
|
||||
className="pb-1"
|
||||
/>
|
||||
|
||||
<Stack spacing={2.5}>
|
||||
{/* 页面模式切换器 */}
|
||||
<SwtichButtonGroup
|
||||
value={pageMode}
|
||||
onChange={(v: PageMode) => setPageMode(v)}
|
||||
options={[
|
||||
{ value: 'diff', label: t('jsonFormat:diffMode') },
|
||||
{ value: 'format', label: t('jsonFormat:formatMode') },
|
||||
{ value: 'yaml', label: t('jsonFormat:yamlMode') },
|
||||
{ value: 'toml', label: t('jsonFormat:tomlMode') },
|
||||
{ value: 'minify', label: t('jsonFormat:minifyMode') },
|
||||
]}
|
||||
size="small"
|
||||
/>
|
||||
<SwitchButtonGroup
|
||||
value={pageMode}
|
||||
onChange={(v: PageMode) => setPageMode(v)}
|
||||
options={[
|
||||
{ value: 'diff', label: t('jsonFormat:diffMode') },
|
||||
{ value: 'format', label: t('jsonFormat:formatMode') },
|
||||
{ value: 'yaml', label: t('jsonFormat:yamlMode') },
|
||||
{ value: 'toml', label: t('jsonFormat:tomlMode') },
|
||||
{ value: 'minify', label: t('jsonFormat:minifyMode') },
|
||||
]}
|
||||
size="small"
|
||||
className="w-full sm:w-auto"
|
||||
/>
|
||||
|
||||
{pageMode === 'diff' ? (
|
||||
<>
|
||||
{/* 工具栏 */}
|
||||
<Stack
|
||||
direction={{ xs: 'column', sm: 'row' }}
|
||||
spacing={1.5}
|
||||
justifyContent="space-between"
|
||||
alignItems={{ xs: 'stretch', sm: 'center' }}
|
||||
>
|
||||
<SwtichButtonGroup
|
||||
value={viewMode}
|
||||
onChange={(v: ViewMode) => setViewMode(v)}
|
||||
options={[
|
||||
{ value: 'sideBySide', label: t('jsonDiff:sideBySideMode') },
|
||||
{ value: 'unified', label: t('jsonDiff:unifiedMode') },
|
||||
]}
|
||||
size="small"
|
||||
/>
|
||||
<Stack direction="row" spacing={1}>
|
||||
<Button variant="text" onClick={handleClear} sx={{ borderRadius: 3 }}>
|
||||
{t('jsonDiff:clearButton')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={!canCompare}
|
||||
onClick={handleCompare}
|
||||
sx={{ borderRadius: 3, fontWeight: 700, px: 3, whiteSpace: 'nowrap' }}
|
||||
>
|
||||
{t('jsonDiff:compareButton')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Stack>
|
||||
|
||||
{/* 输入区 */}
|
||||
<Stack direction={{ xs: 'column', md: 'row' }} spacing={2}>
|
||||
<JsonDiffInput
|
||||
label={t('jsonDiff:leftLabel')}
|
||||
placeholder={t('jsonDiff:leftPlaceholder')}
|
||||
value={leftInput}
|
||||
onChange={setLeftInput}
|
||||
error={leftError}
|
||||
/>
|
||||
<JsonDiffInput
|
||||
label={t('jsonDiff:rightLabel')}
|
||||
placeholder={t('jsonDiff:rightPlaceholder')}
|
||||
value={rightInput}
|
||||
onChange={setRightInput}
|
||||
error={rightError}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
{/* 差异展示 */}
|
||||
{diffResult ? (
|
||||
<>
|
||||
<DiffNavigator
|
||||
total={total}
|
||||
currentIndex={currentDiffIndex}
|
||||
onPrev={handlePrev}
|
||||
onNext={handleNext}
|
||||
/>
|
||||
<DiffResult result={diffResult} viewMode={viewMode} activePath={activePath} />
|
||||
</>
|
||||
) : (
|
||||
<Box
|
||||
sx={{
|
||||
p: 3,
|
||||
borderRadius: 3,
|
||||
bgcolor: (theme) =>
|
||||
theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.03)' : 'grey.50',
|
||||
border: '1px dashed',
|
||||
borderColor: (theme) =>
|
||||
theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.15)' : 'grey.300',
|
||||
textAlign: 'center',
|
||||
}}
|
||||
>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ fontWeight: 600 }}>
|
||||
{t('jsonDiff:emptyHint')}
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
</>
|
||||
) : pageMode === 'format' ? (
|
||||
<JsonFormatSection />
|
||||
) : pageMode === 'yaml' ? (
|
||||
<JsonConvertSection translationPrefix="yamlMode" convertFunction={yamlConvert} />
|
||||
) : pageMode === 'toml' ? (
|
||||
<JsonConvertSection translationPrefix="tomlMode" convertFunction={tomlConvert} />
|
||||
) : (
|
||||
<JsonConvertSection
|
||||
translationPrefix="minifyMode"
|
||||
convertFunction={minifyConvert}
|
||||
convertButtonKey="minifyButton"
|
||||
{pageMode === 'diff' ? (
|
||||
<div className="flex flex-col space-y-4 animate-in fade-in duration-200">
|
||||
<div className="flex h-10 items-center justify-between px-1.5 bg-secondary/40 rounded-xl border border-border/60">
|
||||
<SwitchButtonGroup
|
||||
value={viewMode}
|
||||
onChange={(v: ViewMode) => setViewMode(v)}
|
||||
options={[
|
||||
{ value: 'sideBySide', label: t('jsonDiff:sideBySideMode') },
|
||||
{ value: 'unified', label: t('jsonDiff:unifiedMode') },
|
||||
]}
|
||||
size="small"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col md:flex-row gap-4 w-full items-stretch">
|
||||
<JsonDiffInput
|
||||
label={t('jsonDiff:leftLabel')}
|
||||
placeholder={t('jsonDiff:leftPlaceholder')}
|
||||
value={leftInput}
|
||||
onChange={(val) => {
|
||||
setLeftInput(val);
|
||||
setCurrentDiffIndex(0); // 💡 在同一个用户键盘事件中打包批处理,0 副作用开销
|
||||
}}
|
||||
error={leftError}
|
||||
minRows={9}
|
||||
/>
|
||||
<JsonDiffInput
|
||||
label={t('jsonDiff:rightLabel')}
|
||||
placeholder={t('jsonDiff:rightPlaceholder')}
|
||||
value={rightInput}
|
||||
onChange={(val) => {
|
||||
setRightInput(val);
|
||||
setCurrentDiffIndex(0); // 💡 在同一个用户键盘事件中打包批处理,0 副作用开销
|
||||
}}
|
||||
error={rightError}
|
||||
minRows={9}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{diffResult ? (
|
||||
<div className="flex flex-col space-y-3.5 w-full pt-1">
|
||||
<div className="flex justify-center w-full">
|
||||
<DiffNavigator
|
||||
total={total}
|
||||
currentIndex={currentDiffIndex}
|
||||
onPrev={handlePrev}
|
||||
onNext={handleNext}
|
||||
/>
|
||||
</div>
|
||||
<DiffResult result={diffResult} viewMode={viewMode} activePath={activePath} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-8 rounded-xl bg-muted/30 border border-dashed border-border/80 text-center flex flex-col items-center justify-center min-h-[140px]">
|
||||
<p className="text-xs font-semibold text-muted-foreground/80 tracking-wide max-w-[260px] leading-relaxed">
|
||||
{leftError || rightError
|
||||
? '请修正上方 JSON 的语法错误以开启实时流式比对'
|
||||
: t('jsonDiff:emptyHint')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</Stack>
|
||||
</Container>
|
||||
</Box>
|
||||
</div>
|
||||
) : pageMode === 'format' ? (
|
||||
<JsonFormatSection />
|
||||
) : pageMode === 'yaml' ? (
|
||||
<JsonConvertSection translationPrefix="yaml" convertFunction={yamlConvert} />
|
||||
) : pageMode === 'toml' ? (
|
||||
<JsonConvertSection translationPrefix="toml" convertFunction={tomlConvert} />
|
||||
) : (
|
||||
<JsonConvertSection translationPrefix="minify" convertFunction={minifyConvert} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+39
-13
@@ -1,29 +1,55 @@
|
||||
export type DiffType = 'added' | 'removed' | 'modified' | 'unchanged';
|
||||
|
||||
export interface DiffNode {
|
||||
/** 节点键名(数组项为索引字符串) */
|
||||
/** 节点键名(对象属性名,或者数组的索引字符串 "0", "1"...) */
|
||||
key: string;
|
||||
/** 差异类型 */
|
||||
|
||||
/** 差异状态机核心分类 */
|
||||
type: DiffType;
|
||||
/** 左侧值 */
|
||||
oldValue?: unknown;
|
||||
/** 右侧值 */
|
||||
newValue?: unknown;
|
||||
/** 子节点(对象或数组时存在) */
|
||||
|
||||
/** * 左侧原始数值快照
|
||||
* 💡 优化点:移除了不安全的可选 ?,如果完全缺失则严格流出 undefined,
|
||||
* 倒逼下游渲染层必须做出明确的条件分支防护。
|
||||
*/
|
||||
oldValue: unknown;
|
||||
|
||||
/** 右侧最新数值快照 */
|
||||
newValue: unknown;
|
||||
|
||||
/** * 子节点差异列表
|
||||
* 💡 强类型化:只有当对象或数组这类容器节点发生比对时存在,未选中时默认为空数组 []
|
||||
*/
|
||||
children?: DiffNode[];
|
||||
/** 完整路径,用于导航定位 */
|
||||
|
||||
/** * 节点的绝对路径表达式(严格遵循高可靠的 JSONPath 规约,如 "$.user.profile" 或 "$.list[0]")
|
||||
* 用于 DiffNavigator 差异导航条进行秒级的 scrollIntoView 视图精准定位高亮
|
||||
*/
|
||||
path: string;
|
||||
/** 是否为叶子节点(原始值) */
|
||||
|
||||
/** 是否为叶子节点(若为 true 代表当前值为基本基元数据类型,若为 false 代表当前值为大括号或方括号容器) */
|
||||
isLeaf: boolean;
|
||||
|
||||
/**
|
||||
* 💡 性能调优大闸(Computed Guard):
|
||||
* 预计算状态:代表当前节点的深层子孙节点中,是否存在任意一处 'added' | 'removed' | 'modified' 差异行为。
|
||||
* 这使得外界的 JsonTree 在高频折叠/展开时,能在一帧之内直接通过此属性判断是否需要高亮其父大括号,
|
||||
* 彻底终结了原先命令式深度递归遍历子树的昂贵性能代价!
|
||||
*/
|
||||
hasDiffInChildren: boolean;
|
||||
}
|
||||
|
||||
/** 视图对照渲染模式:sideBySide (双栏对照折叠树) | unified (单栏行级混合拍平) */
|
||||
export type ViewMode = 'sideBySide' | 'unified';
|
||||
|
||||
export interface DiffResult {
|
||||
/** 根节点差异树 */
|
||||
/** 经过深层比对算法推导生成的根节点核心差异树(AST) */
|
||||
root: DiffNode;
|
||||
/** 所有差异节点路径列表(用于导航) */
|
||||
|
||||
/** * 扁平化的高精度差异节点绝对路径映射表。
|
||||
* 里面严格存储了所有 type !== 'unchanged' 的节点 path。
|
||||
* 专供外部的 DiffNavigator (差异控制条) 充当中央路由索引,实现 0 延迟的上一处/下一处无缝切流。
|
||||
*/
|
||||
diffPaths: string[];
|
||||
/** 差异总数 */
|
||||
|
||||
/** 差异核心总计数(等价于 diffPaths.length),注入 tabular-nums 配合渲染 */
|
||||
diffCount: number;
|
||||
}
|
||||
|
||||
+110
-124
@@ -1,67 +1,61 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { Box, Container, Paper, Stack, Typography } from '@mui/material';
|
||||
import { useSnackbar } from '@/components/GlobalSnackbar';
|
||||
import VpnKeyIcon from '@mui/icons-material/VpnKey';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Key } from 'lucide-react';
|
||||
import PageHeader from '@/components/PageHeader';
|
||||
import { stringifyJson, parseJwt } from '@/utils/jwt';
|
||||
import { parseJwt, stringifyJson } from '@/utils/jwt';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { useContextMenuData } from '@/utils/useContextMenuData';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface SectionProps {
|
||||
title: string;
|
||||
content: unknown;
|
||||
color: string;
|
||||
colorClass: string; // 💡 1. 废除硬编码十六进制色值,改用语义化的 Tailwind 类名
|
||||
bgClass: string;
|
||||
borderClass: string;
|
||||
}
|
||||
|
||||
const Section = ({ title, content, color }: SectionProps) => {
|
||||
const Section = ({ title, content, colorClass, bgClass, borderClass }: SectionProps) => {
|
||||
const { t } = useLazyTranslation('jwt');
|
||||
return (
|
||||
<Paper
|
||||
variant="outlined"
|
||||
sx={{
|
||||
p: 2,
|
||||
borderRadius: 3,
|
||||
borderColor: `${color}40`,
|
||||
bgcolor: `${color}05`,
|
||||
position: 'relative',
|
||||
}}
|
||||
<div
|
||||
className={cn('p-4 rounded-xl border border-solid transition-colors', bgClass, borderClass)}
|
||||
>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 800, color: color, letterSpacing: 0.5 }}>
|
||||
<div className="flex justify-between items-center mb-2 select-none">
|
||||
<span className={cn('text-xs font-bold tracking-wider uppercase', colorClass)}>
|
||||
{title}
|
||||
</Typography>
|
||||
<Box sx={{ display: 'flex', gap: 0.5 }}>
|
||||
<CopyButton text={JSON.stringify(content)} size="small" />
|
||||
</Box>
|
||||
</Box>
|
||||
<Box
|
||||
component="pre"
|
||||
sx={{
|
||||
m: 0,
|
||||
p: 1.5,
|
||||
bgcolor: 'rgba(255,255,255,0.6)',
|
||||
borderRadius: 2,
|
||||
fontSize: '0.8rem',
|
||||
fontFamily: 'monospace',
|
||||
overflowX: 'auto',
|
||||
whiteSpace: 'pre-wrap',
|
||||
wordBreak: 'break-all',
|
||||
border: '1px solid rgba(0,0,0,0.05)',
|
||||
}}
|
||||
>
|
||||
</span>
|
||||
<CopyButton
|
||||
text={JSON.stringify(content)}
|
||||
className="h-6 w-6 rounded-md border text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
{/* 💡 排版微距精雕:
|
||||
- 彻底移除 border-black/5 这种非暗黑模式友好的硬隔离。
|
||||
- 统一收拢为标准的 bg-muted/40 配合 font-mono text-xs
|
||||
*/}
|
||||
<pre className="m-0 p-3 bg-muted/30 dark:bg-muted/10 rounded-lg text-xs font-mono overflow-x-auto whitespace-pre-wrap break-all border border-border/50 text-foreground/90 leading-relaxed select-text">
|
||||
{content ? stringifyJson(content) : t('jwt:invalidFormat')}
|
||||
</Box>
|
||||
</Paper>
|
||||
</pre>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default function Index() {
|
||||
const { showMessage } = useSnackbar();
|
||||
const { t } = useLazyTranslation('jwt');
|
||||
const { t } = useLazyTranslation(['jwt', 'jsonFormat']);
|
||||
const [jwtInput, setJwtInput] = useState('');
|
||||
|
||||
// 2. 防抖中转管道:切断高频键盘敲击时的红色语法闪烁
|
||||
const [debouncedInput, setDebouncedInput] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
const handle = setTimeout(() => {
|
||||
setDebouncedInput(jwtInput);
|
||||
}, 200);
|
||||
return () => clearTimeout(handle);
|
||||
}, [jwtInput]);
|
||||
|
||||
const handleContextMenuData = useCallback((payload: string) => {
|
||||
const cleaned = payload.replace(/^Bearer\s*/i, '').trim();
|
||||
setJwtInput(cleaned);
|
||||
@@ -69,95 +63,87 @@ export default function Index() {
|
||||
|
||||
useContextMenuData({ featureKey: 'jwt', onData: handleContextMenuData });
|
||||
|
||||
// 3. 贯彻方案 A:衍生变量流。直接消费防抖后的文本
|
||||
const result = useMemo(() => {
|
||||
if (!jwtInput.trim()) {
|
||||
if (!debouncedInput.trim()) {
|
||||
return null;
|
||||
}
|
||||
return parseJwt(jwtInput);
|
||||
}, [jwtInput]);
|
||||
return parseJwt(debouncedInput);
|
||||
}, [debouncedInput]);
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Container sx={{ p: 2 }}>
|
||||
<PageHeader
|
||||
title={t('jwt:pageTitle')}
|
||||
subtitle={t('jwt:pageSubtitle')}
|
||||
icon={<VpnKeyIcon />}
|
||||
<div className="p-4 w-full flex flex-col space-y-4 animate-in fade-in duration-300 select-none">
|
||||
<PageHeader
|
||||
title={t('jwt:pageTitle')}
|
||||
subtitle={t('jwt:pageSubtitle')}
|
||||
icon={<Key className="h-4 w-4" />} // 💡 规范锁死 Icon 宽高,抹杀闪烁
|
||||
/>
|
||||
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* 输入终端 */}
|
||||
<TextInputArea
|
||||
minRows={5}
|
||||
maxRows={10}
|
||||
placeholder={t('jwt:placeholder')}
|
||||
value={jwtInput}
|
||||
onChange={(val) => {
|
||||
const cleaned = val.replace(/^Bearer\s*/i, '').trim();
|
||||
setJwtInput(cleaned);
|
||||
}}
|
||||
allowCopy={true}
|
||||
showClear={true}
|
||||
externalError={result?.error || undefined}
|
||||
onClear={() => setJwtInput('')}
|
||||
/>
|
||||
|
||||
<Stack spacing={2.5}>
|
||||
{/* Input Area */}
|
||||
<TextInputArea
|
||||
minRows={4}
|
||||
placeholder={t('jwt:placeholder')}
|
||||
value={jwtInput}
|
||||
onChange={(val) => {
|
||||
const cleaned = val.replace(/^Bearer\s*/i, '').trim();
|
||||
setJwtInput(cleaned);
|
||||
}}
|
||||
allowCopy={true}
|
||||
showClear={true}
|
||||
showMessage={showMessage}
|
||||
externalError={result?.error}
|
||||
/>
|
||||
{/* 解码看板结果展现 */}
|
||||
{result && !result.error && (
|
||||
<div className="flex flex-col gap-4 animate-in slide-in-from-bottom-2 duration-300">
|
||||
{/* Header 分区:完美致敬 JWT.io 的鲜艳色彩,同时实现黑夜暗化自适应 */}
|
||||
<Section
|
||||
title={t('jwt:headerTitle')}
|
||||
content={result.header}
|
||||
colorClass="text-[#fb015b] dark:text-rose-400"
|
||||
borderClass="border-[#fb015b]/20 dark:border-rose-500/20"
|
||||
bgClass="bg-[#fb015b]/5 dark:bg-rose-500/5"
|
||||
/>
|
||||
|
||||
{result && !result.error && (
|
||||
<Stack spacing={2}>
|
||||
<Section
|
||||
title={t('jwt:headerTitle')}
|
||||
content={result.header}
|
||||
color="#fb015b" // JWT.io Header Color
|
||||
/>
|
||||
<Section
|
||||
title={t('jwt:payloadTitle')}
|
||||
content={result.payload}
|
||||
color="#d63aff" // JWT.io Payload Color
|
||||
/>
|
||||
<Paper
|
||||
variant="outlined"
|
||||
sx={{
|
||||
p: 2,
|
||||
borderRadius: 3,
|
||||
borderColor: 'primary.light',
|
||||
bgcolor: 'primary.lighter',
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
mb: 1,
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
variant="subtitle2"
|
||||
sx={{ fontWeight: 800, color: 'info.main', letterSpacing: 0.5 }}
|
||||
>
|
||||
{t('jwt:signatureTitle')}
|
||||
</Typography>
|
||||
<CopyButton text={JSON.stringify(result.raw.signature)} size="small" />
|
||||
</Box>
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.8rem',
|
||||
wordBreak: 'break-all',
|
||||
color: 'text.secondary',
|
||||
bgcolor: 'rgba(255,255,255,0.6)',
|
||||
p: 1.5,
|
||||
borderRadius: 2,
|
||||
border: '1px solid rgba(0,0,0,0.05)',
|
||||
}}
|
||||
>
|
||||
{result.signature || t('jwt:noSignature')}
|
||||
</Typography>
|
||||
</Paper>
|
||||
</Stack>
|
||||
)}
|
||||
</Stack>
|
||||
</Container>
|
||||
</Box>
|
||||
{/* Payload 分区 */}
|
||||
<Section
|
||||
title={t('jwt:payloadTitle')}
|
||||
content={result.payload}
|
||||
colorClass="text-[#a03aff] dark:text-purple-400" // 针对暗黑模式略微调高对比度
|
||||
borderClass="border-[#a03aff]/20 dark:border-purple-500/20"
|
||||
bgClass="bg-[#a03aff]/5 dark:bg-purple-500/5"
|
||||
/>
|
||||
|
||||
{/* Signature 签名区:完全对齐标准的 shadcn 骨架阶度 */}
|
||||
<div className="p-4 rounded-xl border border-border bg-secondary/40 shadow-sm transition-colors">
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<span className="text-xs font-bold tracking-wider text-muted-foreground/90 uppercase">
|
||||
{t('jwt:signatureTitle')}
|
||||
</span>
|
||||
<CopyButton
|
||||
text={result.signature || ''}
|
||||
className="h-6 w-6 rounded-md border text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
<span className="block text-xs font-mono break-all text-foreground/80 bg-muted/30 dark:bg-muted/10 p-3 rounded-lg border border-border/50 leading-relaxed select-text">
|
||||
{result.signature || t('jwt:noSignature')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 当解析错误时的干净中性引导拦截 */}
|
||||
{result?.error && (
|
||||
<div className="p-6 rounded-xl bg-muted/30 border border-dashed border-border text-center">
|
||||
<p className="text-xs font-semibold text-muted-foreground/80">
|
||||
{t('jsonFormat:invalidJson')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+158
-232
@@ -1,111 +1,85 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
alpha,
|
||||
Box,
|
||||
Button,
|
||||
Container,
|
||||
Stack,
|
||||
TextField,
|
||||
Typography,
|
||||
Paper,
|
||||
} from '@mui/material';
|
||||
import CodeIcon from '@mui/icons-material/Code';
|
||||
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
|
||||
import PrintIcon from '@mui/icons-material/Print';
|
||||
import DownloadIcon from '@mui/icons-material/Download';
|
||||
import { Code, Download, Printer, Trash2 } from 'lucide-react';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import PageHeader from '@/components/PageHeader';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useStorageState } from '@/utils/useStorageState';
|
||||
import type { MarkdownToHtmlPreviewMode } from '@/types/storage';
|
||||
import {
|
||||
markdownToHtml,
|
||||
wrapHtmlDocument,
|
||||
downloadHtmlFile,
|
||||
markdownToHtml,
|
||||
printHtml,
|
||||
SAMPLE_MARKDOWN,
|
||||
wrapHtmlDocument,
|
||||
} from '@/utils/markdownToHtml';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const isValidPreviewMode = (val: unknown): val is MarkdownToHtmlPreviewMode =>
|
||||
typeof val === 'string' && ['split', 'preview', 'html'].includes(val);
|
||||
|
||||
// 💡 规范回归:保持最纯净的通用选择器集合,内部变量全部交由全局 :root 驱动
|
||||
const PREVIEW_STYLES = `
|
||||
.markdown-body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: inherit;
|
||||
color: var(--md-foreground);
|
||||
background-color: transparent;
|
||||
font-size: 14px;
|
||||
}
|
||||
.markdown-body h1, .markdown-body h2, .markdown-body h3,
|
||||
.markdown-body h4, .markdown-body h5, .markdown-body h6 {
|
||||
margin-top: 20px;
|
||||
margin-bottom: 12px;
|
||||
.markdown-body h1, .markdown-body h2, .markdown-body h3 {
|
||||
margin-top: 24px;
|
||||
margin-bottom: 16px;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
color: var(--md-foreground);
|
||||
}
|
||||
.markdown-body h1 { font-size: 1.8em; border-bottom: 1px solid rgba(128,128,128,0.2); padding-bottom: 0.3em; }
|
||||
.markdown-body h2 { font-size: 1.5em; border-bottom: 1px solid rgba(128,128,128,0.2); padding-bottom: 0.3em; }
|
||||
.markdown-body h3 { font-size: 1.25em; }
|
||||
.markdown-body p { margin-top: 0; margin-bottom: 12px; }
|
||||
.markdown-body a { color: #1976d2; text-decoration: none; }
|
||||
.markdown-body h1 { border-bottom: 1px solid var(--md-border); padding-bottom: 0.3em; font-size: 1.6em; }
|
||||
.markdown-body h2 { border-bottom: 1px solid var(--md-border); padding-bottom: 0.3em; font-size: 1.35em; }
|
||||
.markdown-body p { margin-top: 0; margin-bottom: 16px; }
|
||||
.markdown-body a { color: #3b82f6; text-decoration: none; }
|
||||
.markdown-body a:hover { text-decoration: underline; }
|
||||
.markdown-body code {
|
||||
background-color: rgba(128,128,128,0.1);
|
||||
border-radius: 3px;
|
||||
background-color: var(--md-code-bg);
|
||||
border-radius: 4px;
|
||||
font-size: 85%;
|
||||
padding: 0.2em 0.4em;
|
||||
font-family: 'SFMono-Regular', Consolas, monospace;
|
||||
font-family: Menlo, Consolas, monospace;
|
||||
}
|
||||
.markdown-body pre {
|
||||
background-color: rgba(128,128,128,0.08);
|
||||
border-radius: 6px;
|
||||
background-color: var(--md-pre-bg);
|
||||
border-radius: 8px;
|
||||
font-size: 85%;
|
||||
line-height: 1.45;
|
||||
overflow: auto;
|
||||
padding: 14px;
|
||||
margin: 0 0 12px;
|
||||
padding: 16px;
|
||||
margin: 0 0 16px;
|
||||
border: 1px solid var(--md-border);
|
||||
}
|
||||
.markdown-body pre code {
|
||||
background-color: transparent;
|
||||
border: 0;
|
||||
display: inline;
|
||||
line-height: inherit;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
word-wrap: normal;
|
||||
}
|
||||
.markdown-body blockquote {
|
||||
border-left: 0.25em solid rgba(128,128,128,0.3);
|
||||
color: rgba(128,128,128,0.7);
|
||||
margin: 0 0 12px;
|
||||
border-left: 0.25em solid var(--md-quote-line);
|
||||
color: var(--md-muted);
|
||||
margin: 0 0 16px;
|
||||
padding: 0 1em;
|
||||
}
|
||||
.markdown-body ul, .markdown-body ol { margin-top: 0; margin-bottom: 12px; padding-left: 2em; }
|
||||
.markdown-body li + li { margin-top: 0.25em; }
|
||||
.markdown-body img { max-width: 100%; box-sizing: content-box; }
|
||||
.markdown-body table {
|
||||
border-collapse: collapse;
|
||||
border-spacing: 0;
|
||||
display: block;
|
||||
overflow: auto;
|
||||
width: 100%;
|
||||
margin-bottom: 12px;
|
||||
margin-bottom: 16px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.markdown-body table th, .markdown-body table td {
|
||||
border: 1px solid rgba(128,128,128,0.25);
|
||||
border: 1px solid var(--md-border);
|
||||
padding: 6px 13px;
|
||||
}
|
||||
.markdown-body table tr:nth-child(2n) { background-color: rgba(128,128,128,0.05); }
|
||||
.markdown-body table th { font-weight: 600; background-color: rgba(128,128,128,0.05); }
|
||||
.markdown-body hr {
|
||||
background-color: rgba(128,128,128,0.2);
|
||||
border: 0;
|
||||
height: 0.25em;
|
||||
margin: 20px 0;
|
||||
padding: 0;
|
||||
}
|
||||
.markdown-body input[type="checkbox"] { margin-right: 0.5em; }
|
||||
.markdown-body table tr:nth-child(2n) { background-color: var(--md-code-bg); }
|
||||
.markdown-body table th { font-weight: 600; background-color: var(--md-code-bg); }
|
||||
`;
|
||||
|
||||
export default function MarkdownToHtmlPage() {
|
||||
@@ -121,23 +95,62 @@ export default function MarkdownToHtmlPage() {
|
||||
const result = useMemo(() => markdownToHtml(markdown), [markdown]);
|
||||
const error = result.hasError ? (result.error ?? null) : null;
|
||||
|
||||
// 更新 iframe 预览内容
|
||||
// 💡 自适应大总管:以极高严谨度拼装明暗大闸,用标准换行切断粘连风险
|
||||
useEffect(() => {
|
||||
const iframe = iframeRef.current;
|
||||
if (!iframe || !iframe.contentDocument) return;
|
||||
if (!iframe) return;
|
||||
|
||||
const doc = iframe.contentDocument;
|
||||
doc.open();
|
||||
doc.write(`<!DOCTYPE html>
|
||||
<html>
|
||||
const isDarkMode = document.documentElement.classList.contains('dark');
|
||||
|
||||
const themeVariables = isDarkMode
|
||||
? `:root {
|
||||
--md-bg: #090d16;
|
||||
--md-foreground: #e6edf3;
|
||||
--md-border: rgba(255,255,255,0.15);
|
||||
--md-code-bg: rgba(255,255,255,0.12);
|
||||
--md-pre-bg: rgba(255,255,255,0.04);
|
||||
--md-muted: #8b949e;
|
||||
--md-quote-line: rgba(255,255,255,0.25);
|
||||
}`
|
||||
: `:root {
|
||||
--md-bg: #ffffff;
|
||||
--md-foreground: #1f2328;
|
||||
--md-border: rgba(128,128,128,0.2);
|
||||
--md-code-bg: rgba(128,128,128,0.08);
|
||||
--md-pre-bg: rgba(128,128,128,0.03);
|
||||
--md-muted: #4b5563;
|
||||
--md-quote-line: rgba(128,128,128,0.3);
|
||||
}`;
|
||||
|
||||
// 💡 3. 核心大清洗:将全局基础树(html, body)与派生样式完全独立硬编码,杜绝任何语法踩踏
|
||||
const baseGlobalStyles = `
|
||||
html, body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: var(--md-bg);
|
||||
color: var(--md-foreground);
|
||||
}
|
||||
body {
|
||||
padding: 16px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
`;
|
||||
|
||||
iframe.srcdoc = `<!DOCTYPE html>
|
||||
<html lang="zh" style="background-color: ${isDarkMode ? '#090d16' : '#ffffff'};">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<style>${PREVIEW_STYLES}</style>
|
||||
<style>
|
||||
${themeVariables}
|
||||
${PREVIEW_STYLES}
|
||||
${baseGlobalStyles}
|
||||
</style>
|
||||
</head>
|
||||
<body class="markdown-body">${result.html}</body>
|
||||
</html>`);
|
||||
doc.close();
|
||||
}, [result.html]);
|
||||
</html>`;
|
||||
}, [result.html, previewMode]);
|
||||
|
||||
const handleModeChange = useCallback(
|
||||
(newMode: MarkdownToHtmlPreviewMode) => {
|
||||
@@ -163,18 +176,17 @@ export default function MarkdownToHtmlPage() {
|
||||
const showPreview = previewMode !== 'html';
|
||||
|
||||
return (
|
||||
<Container maxWidth="xl" sx={{ py: 3 }}>
|
||||
<PageHeader title={t('pageTitle')} subtitle={t('pageSubtitle')} icon={<CodeIcon />} />
|
||||
<div className="p-4 w-full flex flex-col space-y-4 select-none animate-in fade-in duration-300">
|
||||
<PageHeader
|
||||
title={t('pageTitle')}
|
||||
subtitle={t('pageSubtitle')}
|
||||
icon={<Code className="h-4 w-4" />}
|
||||
className="pb-1"
|
||||
/>
|
||||
|
||||
<Stack spacing={2}>
|
||||
{/* 工具栏 */}
|
||||
<Stack
|
||||
direction="row"
|
||||
justifyContent="space-between"
|
||||
alignItems="center"
|
||||
flexWrap="wrap"
|
||||
gap={1.5}
|
||||
>
|
||||
<div className="flex flex-col space-y-4">
|
||||
{/* 工具集成控制中枢 */}
|
||||
<div className="flex flex-col sm:flex-row gap-3 justify-between items-stretch sm:items-center bg-secondary/40 rounded-xl border border-border/60 px-1.5 py-1.5 sm:h-12">
|
||||
<SwitchButtonGroup
|
||||
value={previewMode}
|
||||
options={[
|
||||
@@ -184,202 +196,116 @@ export default function MarkdownToHtmlPage() {
|
||||
]}
|
||||
onChange={handleModeChange}
|
||||
size="small"
|
||||
className="w-full sm:w-auto"
|
||||
/>
|
||||
|
||||
<Stack direction="row" spacing={1}>
|
||||
<div className="flex gap-2 shrink-0">
|
||||
<Button
|
||||
variant="outlined"
|
||||
size="small"
|
||||
startIcon={<DeleteOutlineIcon />}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleClear}
|
||||
sx={{ borderRadius: 2 }}
|
||||
className="h-8 rounded-md font-medium text-xs gap-1.5 shadow-sm active:scale-95 text-destructive hover:text-destructive hover:bg-destructive/5 dark:hover:bg-destructive/10 border-input/60 transition-all"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
{t('clear')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outlined"
|
||||
size="small"
|
||||
startIcon={<PrintIcon />}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handlePrint}
|
||||
sx={{ borderRadius: 2 }}
|
||||
disabled={!result.html}
|
||||
className="h-8 rounded-md font-medium text-xs gap-1.5 shadow-sm active:scale-95 transition-all"
|
||||
>
|
||||
<Printer className="h-3.5 w-3.5" />
|
||||
{t('print')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outlined"
|
||||
size="small"
|
||||
startIcon={<DownloadIcon />}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleDownload}
|
||||
sx={{ borderRadius: 2 }}
|
||||
disabled={!result.html}
|
||||
className="h-8 rounded-md font-medium text-xs gap-1.5 shadow-sm active:scale-95 transition-all"
|
||||
>
|
||||
<Download className="h-3.5 w-3.5" />
|
||||
{t('download')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 错误提示 */}
|
||||
{/* 错误拦截提示框 */}
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ borderRadius: 2 }}>
|
||||
<div
|
||||
role="alert"
|
||||
className="p-3.5 bg-destructive/10 border border-destructive/20 rounded-xl text-destructive text-xs font-semibold tracking-wide animate-in shake duration-300"
|
||||
>
|
||||
{error}
|
||||
</Alert>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 主内容区 */}
|
||||
<Box
|
||||
sx={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: {
|
||||
xs: '1fr',
|
||||
md: showInput && showPreview ? '1fr 1fr' : '1fr',
|
||||
},
|
||||
gap: 2,
|
||||
minHeight: 500,
|
||||
}}
|
||||
{/* 主框架多栏联动排版轴 */}
|
||||
<div
|
||||
className={cn(
|
||||
'grid gap-4 min-h-[480px] w-full',
|
||||
showInput && showPreview ? 'grid-cols-1 md:grid-cols-2' : 'grid-cols-1',
|
||||
)}
|
||||
>
|
||||
{/* Markdown 输入区 */}
|
||||
{/* Markdown 输入翼终端 */}
|
||||
{showInput && (
|
||||
<Paper
|
||||
elevation={0}
|
||||
sx={{
|
||||
border: '1px solid',
|
||||
borderColor: 'divider',
|
||||
borderRadius: 3,
|
||||
overflow: 'hidden',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
px: 2,
|
||||
py: 1,
|
||||
bgcolor: (theme) => alpha(theme.palette.primary.main, 0.04),
|
||||
borderBottom: '1px solid',
|
||||
borderColor: 'divider',
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<Typography variant="caption" sx={{ fontWeight: 700, color: 'text.secondary' }}>
|
||||
<div className="border border-border rounded-xl bg-card text-card-foreground shadow-sm overflow-hidden flex flex-col transition-all duration-200 focus-within:ring-1 focus-within:ring-ring focus-within:border-ring animate-in fade-in">
|
||||
<div className="flex h-9 items-center justify-between px-4 bg-muted/50 border-b border-border select-none">
|
||||
<span className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider">
|
||||
{t('inputLabel')}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ color: 'text.disabled' }}>
|
||||
</span>
|
||||
<span className="text-[10px] font-mono text-muted-foreground/60 tabular-nums">
|
||||
{t('charCount', { count: markdown.length })}
|
||||
</Typography>
|
||||
</Box>
|
||||
<TextField
|
||||
multiline
|
||||
fullWidth
|
||||
</span>
|
||||
</div>
|
||||
<textarea
|
||||
value={markdown}
|
||||
onChange={(e) => setMarkdown(e.target.value)}
|
||||
placeholder={t('inputPlaceholder')}
|
||||
sx={{
|
||||
flex: 1,
|
||||
'& .MuiOutlinedInput-root': {
|
||||
borderRadius: 0,
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.85rem',
|
||||
lineHeight: 1.6,
|
||||
alignItems: 'flex-start',
|
||||
'& fieldset': { border: 'none' },
|
||||
},
|
||||
'& .MuiInputBase-input': {
|
||||
py: 2,
|
||||
px: 2,
|
||||
minHeight: 400,
|
||||
},
|
||||
}}
|
||||
className="flex-1 min-h-[390px] p-4 bg-transparent font-mono text-xs leading-relaxed resize-none focus:outline-none text-foreground/90 select-text"
|
||||
/>
|
||||
</Paper>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 预览/输出区 */}
|
||||
{/* 实时 HTML/Iframe 预览翼终端 */}
|
||||
{showPreview && (
|
||||
<Paper
|
||||
elevation={0}
|
||||
sx={{
|
||||
border: '1px solid',
|
||||
borderColor: 'divider',
|
||||
borderRadius: 3,
|
||||
overflow: 'hidden',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
px: 2,
|
||||
py: 1,
|
||||
bgcolor: (theme) => alpha(theme.palette.primary.main, 0.04),
|
||||
borderBottom: '1px solid',
|
||||
borderColor: 'divider',
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<Typography variant="caption" sx={{ fontWeight: 700, color: 'text.secondary' }}>
|
||||
<div className="border border-border rounded-xl bg-card text-card-foreground shadow-sm overflow-hidden flex flex-col animate-in fade-in">
|
||||
<div className="flex h-9 items-center justify-between px-4 bg-muted/50 border-b border-border select-none">
|
||||
<span className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider">
|
||||
{(previewMode as string) === 'html' ? t('htmlOutputLabel') : t('previewLabel')}
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={0.5} alignItems="center">
|
||||
<Typography variant="caption" sx={{ color: 'text.disabled' }}>
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-[10px] font-mono text-muted-foreground/60 tabular-nums">
|
||||
{t('charCount', { count: result.htmlLength })}
|
||||
</Typography>
|
||||
<CopyButton text={result.html} size="small" />
|
||||
</Stack>
|
||||
</Box>
|
||||
</span>
|
||||
<CopyButton
|
||||
text={result.html}
|
||||
className="h-6 w-6 rounded-md border text-muted-foreground"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{(previewMode as string) === 'html' ? (
|
||||
<TextField
|
||||
multiline
|
||||
fullWidth
|
||||
<textarea
|
||||
value={result.html}
|
||||
InputProps={{ readOnly: true }}
|
||||
sx={{
|
||||
flex: 1,
|
||||
'& .MuiOutlinedInput-root': {
|
||||
borderRadius: 0,
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '0.8rem',
|
||||
lineHeight: 1.5,
|
||||
alignItems: 'flex-start',
|
||||
'& fieldset': { border: 'none' },
|
||||
},
|
||||
'& .MuiInputBase-input': {
|
||||
py: 2,
|
||||
px: 2,
|
||||
minHeight: 400,
|
||||
},
|
||||
}}
|
||||
readOnly
|
||||
className="flex-1 min-h-[390px] p-4 font-mono text-xs leading-relaxed resize-none focus:outline-none bg-muted/30 dark:bg-muted/10 text-foreground/80 select-text"
|
||||
/>
|
||||
) : (
|
||||
<Box
|
||||
sx={{
|
||||
flex: 1,
|
||||
p: 2,
|
||||
minHeight: 400,
|
||||
overflow: 'auto',
|
||||
bgcolor: 'background.paper',
|
||||
}}
|
||||
>
|
||||
<div className="flex-1 min-h-[390px] overflow-hidden bg-transparent">
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
title="markdown-preview"
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
minHeight: 380,
|
||||
border: 'none',
|
||||
background: 'transparent',
|
||||
}}
|
||||
className="w-full h-full min-h-[360px] border-none bg-transparent"
|
||||
/>
|
||||
</Box>
|
||||
</div>
|
||||
)}
|
||||
</Paper>
|
||||
</div>
|
||||
)}
|
||||
</Box>
|
||||
</Stack>
|
||||
</Container>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import QrCodePage from '../index';
|
||||
|
||||
vi.mock('lucide-react', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('lucide-react')>();
|
||||
return {
|
||||
...actual,
|
||||
// 增量伪造需要高精嗅探的 QrCode 核心定位图标
|
||||
QrCode: () => <div data-testid="mock-lucide-qrcode">Icon</div>,
|
||||
};
|
||||
});
|
||||
|
||||
// Mock useLazyTranslation
|
||||
vi.mock('@/utils/useLazyTranslation', () => ({
|
||||
useLazyTranslation: () => ({
|
||||
@@ -11,7 +20,14 @@ vi.mock('@/utils/useLazyTranslation', () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock getEntryPointType
|
||||
// Mock useSnackbar
|
||||
vi.mock('@/components/GlobalSnackbar', () => ({
|
||||
useSnackbar: () => ({
|
||||
showMessage: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock getEntryPointType(保留原厂其他特征配置,仅模拟入口路由环境)
|
||||
vi.mock('@/config/features', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/config/features')>();
|
||||
return {
|
||||
@@ -20,7 +36,7 @@ vi.mock('@/config/features', async (importOriginal) => {
|
||||
};
|
||||
});
|
||||
|
||||
// Mock 子组件
|
||||
// Mock 高频变化的子组件,收拢断言边界
|
||||
vi.mock('@/components/QrCodePreview', () => ({
|
||||
default: () => <div data-testid="qr-code-preview">QrCodePreview</div>,
|
||||
}));
|
||||
@@ -29,21 +45,18 @@ vi.mock('@/components/ImageUploader', () => ({
|
||||
default: () => <div data-testid="image-uploader">ImageUploader</div>,
|
||||
}));
|
||||
|
||||
// Mock QRious
|
||||
// Mock QRious 动态图像离屏生成引擎
|
||||
vi.mock('qrious', () => ({
|
||||
default: vi.fn().mockImplementation(() => ({
|
||||
toDataURL: () => 'data:image/png;base64,mock',
|
||||
})),
|
||||
}));
|
||||
|
||||
// Mock useSnackbar
|
||||
vi.mock('@/components/GlobalSnackbar', () => ({
|
||||
useSnackbar: () => ({
|
||||
showMessage: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('QrCodePage', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('应该默认渲染生成模式', () => {
|
||||
render(<QrCodePage />);
|
||||
expect(screen.getByTestId('qr-code-preview')).toBeInTheDocument();
|
||||
@@ -78,14 +91,14 @@ describe('QrCodePage', () => {
|
||||
expect(screen.getByTestId('qr-code-preview')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('应该渲染输入区域', () => {
|
||||
it('应该渲染输入区域的系统标签(对齐新版 Label 机制)', () => {
|
||||
render(<QrCodePage />);
|
||||
expect(screen.getByText('qrCode:urlInputLabel')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('应该渲染双栏布局容器', () => {
|
||||
it('应该渲染双翼响应式卡片网格布局', () => {
|
||||
const { container } = render(<QrCodePage />);
|
||||
const gridContainer = container.querySelector('.MuiGrid-container');
|
||||
const gridContainer = container.querySelector('.grid');
|
||||
expect(gridContainer).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,37 +1,57 @@
|
||||
import { Grid } from '@mui/material';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import QrCodePreview from '@/components/QrCodePreview';
|
||||
import { useSnackbar } from '@/components/GlobalSnackbar';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { useQrCodeContext } from '../contexts/QrCodeContext';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export default function GeneratePanel() {
|
||||
const { t } = useLazyTranslation('qrCode');
|
||||
const { showMessage } = useSnackbar();
|
||||
const { generatorState, setTextToEncode, downloadQrCode, copyQrCode } = useQrCodeContext();
|
||||
|
||||
return (
|
||||
<Grid container spacing={3}>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<TextInputArea
|
||||
title={t('qrCode:urlInputLabel')}
|
||||
value={generatorState.textToEncode}
|
||||
onChange={setTextToEncode}
|
||||
placeholder={t('qrCode:urlInputPlaceholder')}
|
||||
showCount
|
||||
showClear
|
||||
allowCopy
|
||||
externalError={generatorState.inputError}
|
||||
showMessage={showMessage}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 w-full items-stretch select-none p-0.5 animate-in fade-in duration-300">
|
||||
{/* 左翼:高性能受控输入翼终端 */}
|
||||
<div
|
||||
className={cn(
|
||||
'border border-border rounded-xl bg-card text-card-foreground shadow-sm flex flex-col p-4 transition-all duration-200',
|
||||
'focus-within:ring-1 focus-within:ring-ring focus-within:border-ring',
|
||||
)}
|
||||
>
|
||||
{/* 💡 2. 独立外置标签架(A11y 无障碍对齐):
|
||||
- 彻底删掉 TextInputArea 上引发崩溃的违规属性。
|
||||
- 改用正统的 <Label />,并注入标准的高度无障碍样式,间距比例极度平滑。
|
||||
*/}
|
||||
<div className="flex flex-col space-y-2.5 h-full">
|
||||
<Label className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider select-none pl-0.5">
|
||||
{t('qrCode:urlInputLabel')}
|
||||
</Label>
|
||||
|
||||
<div className="flex-1 min-h-0">
|
||||
<TextInputArea
|
||||
value={generatorState.textToEncode}
|
||||
onChange={setTextToEncode}
|
||||
placeholder={t('qrCode:urlInputPlaceholder')}
|
||||
showCount={true}
|
||||
showClear={true}
|
||||
allowCopy={true}
|
||||
minRows={6}
|
||||
maxRows={12}
|
||||
externalError={generatorState.inputError || undefined}
|
||||
onClear={() => setTextToEncode('')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 右翼:活态二维码高精生成区 */}
|
||||
<div className="flex flex-col h-full">
|
||||
<QrCodePreview
|
||||
qrCodeDataUrl={generatorState.qrCodeDataUrl}
|
||||
onDownload={downloadQrCode}
|
||||
onCopy={copyQrCode}
|
||||
/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { useEffect, useCallback } from 'react';
|
||||
import { Grid } from '@mui/material';
|
||||
import { useCallback, useEffect } from 'react';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import ImageUploader from '@/components/ImageUploader';
|
||||
import { useSnackbar } from '@/components/GlobalSnackbar';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { useQrCodeContext } from '../contexts/QrCodeContext';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export default function ParsePanel() {
|
||||
const { t } = useLazyTranslation('qrCode');
|
||||
@@ -57,8 +58,12 @@ export default function ParsePanel() {
|
||||
}, [handlePaste]);
|
||||
|
||||
return (
|
||||
<Grid container spacing={3}>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
/* 💡 统一大视觉轴:
|
||||
- 追加 p-0.5 微隔离,配合 gap-6 建立与生成面板(GeneratePanel)绝对像素对齐的网格天平。
|
||||
*/
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 w-full items-stretch select-none p-0.5 animate-in fade-in duration-300">
|
||||
{/* 左翼:图片接收/拖拽/剪贴板上传终端 */}
|
||||
<div className="flex flex-col h-full">
|
||||
<ImageUploader
|
||||
selectedFile={parserState.selectedFile}
|
||||
onFileChange={handleFileChange}
|
||||
@@ -68,19 +73,36 @@ export default function ParsePanel() {
|
||||
dragging={parserState.dragging}
|
||||
onDraggingChange={(dragging) => setParserState((prev) => ({ ...prev, dragging }))}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid size={{ xs: 12, md: 6 }}>
|
||||
<TextInputArea
|
||||
title={t('qrCode:resultLabel')}
|
||||
value={parserState.decodedResult}
|
||||
readOnly
|
||||
showClear={false}
|
||||
allowCopy
|
||||
placeholder=""
|
||||
externalError={parserState.parseError}
|
||||
showMessage={showMessage}
|
||||
/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</div>
|
||||
|
||||
{/* 右翼:高阶解析出码只读终端 */}
|
||||
<div
|
||||
className={cn(
|
||||
'border border-border rounded-xl bg-card text-card-foreground shadow-sm flex flex-col p-4 transition-all duration-200',
|
||||
// 💡 视觉对称增强:加入相同的聚焦变量环联动,使双翼权重达成完美绝对平衡
|
||||
'focus-within:ring-1 focus-within:ring-ring focus-within:border-ring',
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-col space-y-2.5 h-full">
|
||||
{/* 💡 修复点:物理剔除 TextInputArea 上的违规 title,改用符合 Vercel 美学的极致大写极细原子标签 */}
|
||||
<Label className="text-[10px] font-bold text-muted-foreground/90 uppercase tracking-wider pl-0.5">
|
||||
{t('qrCode:resultLabel')}
|
||||
</Label>
|
||||
|
||||
<div className="flex-1 min-h-0">
|
||||
<TextInputArea
|
||||
value={parserState.decodedResult}
|
||||
readOnly={true}
|
||||
showClear={false}
|
||||
allowCopy={true}
|
||||
placeholder=""
|
||||
minRows={6}
|
||||
maxRows={12}
|
||||
externalError={parserState.parseError || undefined}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
import type { Dispatch, SetStateAction } from 'react'; // 💡 1. 显式解构导入类型,彻底掐灭 TS2304 报错
|
||||
import { createContext, useContext } from 'react';
|
||||
import type { QrCodeMode, QrCodeGeneratorState, QrCodeParserState } from '../types';
|
||||
import type { QrCodeGeneratorState, QrCodeMode, QrCodeParserState } from '../types';
|
||||
|
||||
export interface QrCodeContextValue {
|
||||
// 模式
|
||||
// 核心主视图路由模式切换卡
|
||||
mode: QrCodeMode;
|
||||
setMode: (mode: QrCodeMode) => void;
|
||||
|
||||
// 生成器状态
|
||||
// 1. 流式生成器终端状态机驱动
|
||||
generatorState: QrCodeGeneratorState;
|
||||
setTextToEncode: (text: string) => void;
|
||||
generateQrCode: (text: string) => Promise<void>;
|
||||
// 💡 架构纯净化:物理剔除暴露给外部的命令式 generateQrCode 算子。
|
||||
// 外部面板只需 setTextToEncode 驱动源文本更新,生成动作由内部流式管线全自动自发自愈完成!
|
||||
downloadQrCode: () => void;
|
||||
copyQrCode: () => Promise<void>;
|
||||
|
||||
// 解析器状态
|
||||
// 2. 活态反向解析器终端状态机驱动
|
||||
parserState: QrCodeParserState;
|
||||
setParserState: React.Dispatch<React.SetStateAction<QrCodeParserState>>;
|
||||
setParserState: Dispatch<SetStateAction<QrCodeParserState>>; // 💡 规整为纯净的直接类型使用
|
||||
parseQrCode: (file: File) => Promise<void>;
|
||||
handleFileChange: (file: File) => void;
|
||||
handleClearFile: () => void;
|
||||
@@ -26,7 +28,8 @@ export const QrCodeContext = createContext<QrCodeContextValue | null>(null);
|
||||
export function useQrCodeContext() {
|
||||
const context = useContext(QrCodeContext);
|
||||
if (!context) {
|
||||
throw new Error('useQrCodeContext must be used within QrCodeProvider');
|
||||
// 边界鲁棒性防护大闸
|
||||
throw new Error('useQrCodeContext must be used within a valid QrCodeProvider container');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useCallback, useEffect, useRef } from 'react';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import QRious from 'qrious';
|
||||
import { useSnackbar } from '@/components/GlobalSnackbar';
|
||||
import { parseQrCodeFromFile } from '@/utils/qrCodeParser';
|
||||
@@ -6,24 +6,24 @@ import { useContextMenuData } from '@/utils/useContextMenuData';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { useDebounce } from '@/utils/useDebounce';
|
||||
import type { QrCodeContextValue } from '../contexts/QrCodeContext';
|
||||
import type { QrCodeMode, QrCodeGeneratorState, QrCodeParserState } from '../types';
|
||||
import type { QrCodeGeneratorState, QrCodeMode, QrCodeParserState } from '../types';
|
||||
|
||||
export function useQrCode(): QrCodeContextValue {
|
||||
const { t } = useLazyTranslation('qrCode');
|
||||
const { showMessage } = useSnackbar();
|
||||
|
||||
// 当前模式
|
||||
// 核心路由视图模式
|
||||
const [mode, setMode] = useState<QrCodeMode>('generate');
|
||||
|
||||
// 二维码生成器状态
|
||||
const [generatorState, setGeneratorState] = useState<QrCodeGeneratorState>({
|
||||
// 1. 生成器状态流(大幅瘦身:剔除 generating 状态)
|
||||
const [generatorState, setGeneratorState] = useState<
|
||||
Omit<QrCodeGeneratorState, 'generating' | 'qrCodeDataUrl'>
|
||||
>({
|
||||
textToEncode: '',
|
||||
qrCodeDataUrl: '',
|
||||
generating: false,
|
||||
inputError: '',
|
||||
});
|
||||
|
||||
// 二维码解析器状态
|
||||
// 2. 解析器状态流
|
||||
const [parserState, setParserState] = useState<QrCodeParserState>({
|
||||
decodedResult: '',
|
||||
parsing: false,
|
||||
@@ -33,75 +33,65 @@ export function useQrCode(): QrCodeContextValue {
|
||||
dragging: false,
|
||||
});
|
||||
|
||||
// 生成二维码
|
||||
const generateQrCode = useCallback(
|
||||
async (text: string) => {
|
||||
if (!text) {
|
||||
setGeneratorState((prev) => ({ ...prev, qrCodeDataUrl: '' }));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setGeneratorState((prev) => ({ ...prev, generating: true, inputError: '' }));
|
||||
|
||||
let url = text;
|
||||
if (!url.startsWith('http://') && !url.startsWith('https://')) {
|
||||
url = 'https://' + url;
|
||||
}
|
||||
|
||||
const qr = new QRious({
|
||||
value: url,
|
||||
size: 250,
|
||||
level: 'H',
|
||||
foreground: '#000000',
|
||||
background: '#FFFFFF',
|
||||
});
|
||||
|
||||
setGeneratorState((prev) => ({ ...prev, qrCodeDataUrl: qr.toDataURL() }));
|
||||
} catch (error) {
|
||||
console.error('生成二维码失败:', error);
|
||||
setGeneratorState((prev) => ({
|
||||
...prev,
|
||||
inputError: t('qrCode:generateError'),
|
||||
}));
|
||||
showMessage(t('qrCode:generateError'), { severity: 'error', autoHideDuration: 3000 });
|
||||
} finally {
|
||||
setGeneratorState((prev) => ({ ...prev, generating: false }));
|
||||
}
|
||||
},
|
||||
[t, showMessage],
|
||||
);
|
||||
|
||||
// 使用 useRef 存储 generateQrCode 的最新引用,避免无限循环
|
||||
const generateQrCodeRef = useRef(generateQrCode);
|
||||
useEffect(() => {
|
||||
generateQrCodeRef.current = generateQrCode;
|
||||
});
|
||||
|
||||
// 防抖处理输入文本(200ms)
|
||||
// 3. 高频打字极速防抖
|
||||
const debouncedTextToEncode = useDebounce(generatorState.textToEncode, 200);
|
||||
|
||||
// 当防抖后的文本变化时,自动生成二维码
|
||||
useEffect(() => {
|
||||
if (debouncedTextToEncode && mode === 'generate') {
|
||||
generateQrCodeRef.current(debouncedTextToEncode);
|
||||
// 💡 4. 贯彻方案 A(无副作用超导管线):
|
||||
// 彻底删除原有的 generateQrCodeRef、3个 useEffect、1个 useRef 以及相关的复杂状态机。
|
||||
// 二维码画布纯粹作为防抖文本的派生变量同步算出,0重绘死循环风险,体验平滑如镜!
|
||||
const qrCodeDataUrl = useMemo(() => {
|
||||
const text = debouncedTextToEncode.trim();
|
||||
if (!text) return '';
|
||||
|
||||
try {
|
||||
let url = text;
|
||||
if (!url.startsWith('http://') && !url.startsWith('https://')) {
|
||||
url = 'https://' + url;
|
||||
}
|
||||
|
||||
// 💡 暗黑模式自适应大闸:实时嗅探系统 DOM 阶度
|
||||
const isDark = document.documentElement.classList.contains('dark');
|
||||
|
||||
const qr = new QRious({
|
||||
value: url,
|
||||
size: 260,
|
||||
level: 'H',
|
||||
// 暗黑模式下使用透明底、月白前景色;白天模式下使用标准现代黑白配
|
||||
foreground: isDark ? '#f3f4f6' : '#0f172a',
|
||||
background: isDark ? 'transparent' : '#ffffff',
|
||||
});
|
||||
|
||||
return qr.toDataURL();
|
||||
} catch (error) {
|
||||
console.error('QR code generation sync task failed:', error);
|
||||
return '';
|
||||
}
|
||||
}, [debouncedTextToEncode, mode]);
|
||||
}, [debouncedTextToEncode]);
|
||||
|
||||
// 融合派生数据至完整状态体,满足外部组件强类型契合
|
||||
const fullGeneratorState = useMemo<QrCodeGeneratorState>(
|
||||
() => ({
|
||||
...generatorState,
|
||||
qrCodeDataUrl,
|
||||
generating: false,
|
||||
}),
|
||||
[generatorState, qrCodeDataUrl],
|
||||
);
|
||||
|
||||
// 设置输入文本
|
||||
const setTextToEncode = useCallback((text: string) => {
|
||||
setGeneratorState((prev) => ({ ...prev, textToEncode: text }));
|
||||
setGeneratorState((prev) => ({ ...prev, textToEncode: text, inputError: '' }));
|
||||
}, []);
|
||||
|
||||
// 处理右键菜单数据
|
||||
// 处理右键菜单数据上下文
|
||||
const handleContextMenuData = useCallback((payload: string) => {
|
||||
setMode('generate');
|
||||
setGeneratorState((prev) => ({ ...prev, textToEncode: payload }));
|
||||
setGeneratorState((prev) => ({ ...prev, textToEncode: payload, inputError: '' }));
|
||||
}, []);
|
||||
|
||||
useContextMenuData({ featureKey: 'qrCode', onData: handleContextMenuData });
|
||||
|
||||
// 解析二维码
|
||||
// 反向活态解析二维码算法
|
||||
const parseQrCode = useCallback(
|
||||
async (file: File) => {
|
||||
try {
|
||||
@@ -131,21 +121,21 @@ export function useQrCode(): QrCodeContextValue {
|
||||
|
||||
// 下载二维码
|
||||
const downloadQrCode = useCallback(() => {
|
||||
if (!generatorState.qrCodeDataUrl) return;
|
||||
if (!qrCodeDataUrl) return;
|
||||
|
||||
const link = document.createElement('a');
|
||||
link.href = generatorState.qrCodeDataUrl;
|
||||
link.href = qrCodeDataUrl;
|
||||
link.download = 'qrcode.png';
|
||||
link.click();
|
||||
showMessage(t('qrCode:qrCodeDownloadSuccess'), { severity: 'success', autoHideDuration: 1000 });
|
||||
}, [generatorState.qrCodeDataUrl, showMessage, t]);
|
||||
}, [qrCodeDataUrl, showMessage, t]);
|
||||
|
||||
// 复制二维码
|
||||
// 复制二维码至剪贴板
|
||||
const copyQrCode = useCallback(async () => {
|
||||
if (!generatorState.qrCodeDataUrl) return;
|
||||
if (!qrCodeDataUrl) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(generatorState.qrCodeDataUrl);
|
||||
const response = await fetch(qrCodeDataUrl);
|
||||
const blob = await response.blob();
|
||||
|
||||
await navigator.clipboard.write([
|
||||
@@ -159,13 +149,12 @@ export function useQrCode(): QrCodeContextValue {
|
||||
console.error('复制二维码失败:', error);
|
||||
showMessage(t('qrCode:copyError'), { severity: 'error', autoHideDuration: 3000 });
|
||||
}
|
||||
}, [generatorState.qrCodeDataUrl, showMessage, t]);
|
||||
}, [qrCodeDataUrl, showMessage, t]);
|
||||
|
||||
// 处理文件选择
|
||||
const handleFileChange = useCallback(
|
||||
(file: File) => {
|
||||
setParserState((prev) => {
|
||||
// 释放旧的预览 URL
|
||||
if (prev.previewUrl) {
|
||||
URL.revokeObjectURL(prev.previewUrl);
|
||||
}
|
||||
@@ -177,37 +166,41 @@ export function useQrCode(): QrCodeContextValue {
|
||||
parseError: '',
|
||||
};
|
||||
});
|
||||
// 自动解析
|
||||
parseQrCode(file);
|
||||
|
||||
// 触发解析安全的后台 Promise
|
||||
parseQrCode(file).catch((err) => {
|
||||
console.error('Parser standalone task thread exploded:', err);
|
||||
});
|
||||
},
|
||||
[parseQrCode],
|
||||
);
|
||||
|
||||
// 清除文件
|
||||
// 清除解析受控文件
|
||||
const handleClearFile = useCallback(() => {
|
||||
if (parserState.previewUrl) {
|
||||
URL.revokeObjectURL(parserState.previewUrl);
|
||||
}
|
||||
setParserState((prev) => ({
|
||||
...prev,
|
||||
selectedFile: null,
|
||||
previewUrl: '',
|
||||
decodedResult: '',
|
||||
parseError: '',
|
||||
}));
|
||||
}, [parserState.previewUrl]);
|
||||
setParserState((prev) => {
|
||||
if (prev.previewUrl) {
|
||||
URL.revokeObjectURL(prev.previewUrl);
|
||||
}
|
||||
return {
|
||||
...prev,
|
||||
selectedFile: null,
|
||||
previewUrl: '',
|
||||
decodedResult: '',
|
||||
parseError: '',
|
||||
};
|
||||
});
|
||||
}, []);
|
||||
|
||||
return {
|
||||
mode,
|
||||
setMode,
|
||||
generatorState,
|
||||
generatorState: fullGeneratorState,
|
||||
setTextToEncode,
|
||||
generateQrCode,
|
||||
parseQrCode,
|
||||
downloadQrCode,
|
||||
copyQrCode,
|
||||
parserState,
|
||||
setParserState,
|
||||
parseQrCode,
|
||||
handleFileChange,
|
||||
handleClearFile,
|
||||
};
|
||||
|
||||
+35
-21
@@ -1,5 +1,4 @@
|
||||
import { Box, Container, useMediaQuery, useTheme } from '@mui/material';
|
||||
import QrCodeIcon from '@mui/icons-material/QrCode';
|
||||
import { QrCode as QrCodeIcon } from 'lucide-react'; // 💡 别名规整,防止与页面组件发生重名误判
|
||||
import PageHeader from '@/components/PageHeader';
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
import { qrCodePageStyles } from '@/config/pageTheme';
|
||||
@@ -12,11 +11,9 @@ import type { QrCodeMode } from './types';
|
||||
|
||||
export default function Index() {
|
||||
const { t } = useLazyTranslation('qrCode');
|
||||
const theme = useTheme();
|
||||
const isDesktop = useMediaQuery(theme.breakpoints.up('md'));
|
||||
const qrCode = useQrCode();
|
||||
|
||||
// 模式选项
|
||||
// 模式选项驱动骨架
|
||||
const modeOptions = [
|
||||
{ value: 'generate' as QrCodeMode, label: t('qrCode:urlToQr') },
|
||||
{ value: 'parse' as QrCodeMode, label: t('qrCode:qrToUrl') },
|
||||
@@ -24,29 +21,46 @@ export default function Index() {
|
||||
|
||||
return (
|
||||
<QrCodeContext.Provider value={qrCode}>
|
||||
<Box>
|
||||
<Container
|
||||
maxWidth={isDesktop ? 'lg' : false}
|
||||
sx={{ py: 2, maxWidth: isDesktop ? undefined : 400 }}
|
||||
>
|
||||
<PageHeader
|
||||
title={t('qrCode:pageTitle')}
|
||||
subtitle={t('qrCode:pageSubtitle')}
|
||||
icon={<QrCodeIcon />}
|
||||
iconColor={qrCodePageStyles.primaryColor}
|
||||
sx={{ mb: 2.5 }}
|
||||
/>
|
||||
{/* 💡 统一视觉规范大超进化:
|
||||
- 彻底剥离破坏流式宽度的 max-w-[400px] 枷锁,开启标准的 w-full 全自适应包裹。
|
||||
- 替换为标准的 p-4 呼吸内边距配合 flex flex-col space-y-4,接管系统级重排!
|
||||
*/}
|
||||
<div className="p-4 w-full flex flex-col space-y-4 min-h-[500px] select-none animate-in fade-in duration-300">
|
||||
{/* 标题控制栏:追加微调 py-0.5,防范文字边缘截断 */}
|
||||
<PageHeader
|
||||
title={t('qrCode:pageTitle')}
|
||||
subtitle={t('qrCode:pageSubtitle')}
|
||||
icon={<QrCodeIcon className="h-4 w-4" />} // 💡 规范对齐:强制锁死 Icon 宽高,抹杀闪烁
|
||||
iconColor={qrCodePageStyles.primaryColor}
|
||||
className="pb-1"
|
||||
/>
|
||||
|
||||
{/* 流式中央控制切流卡:注入 sm 断点防御,防范单栏状态下发生变形 */}
|
||||
<div className="w-full sm:w-fit pt-0.5">
|
||||
<SwitchButtonGroup
|
||||
value={qrCode.mode}
|
||||
options={modeOptions}
|
||||
onChange={qrCode.setMode}
|
||||
sx={{ mb: 3 }}
|
||||
size="small"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{qrCode.mode === 'generate' ? <GeneratePanel /> : <ParsePanel />}
|
||||
</Container>
|
||||
</Box>
|
||||
{/* 💡 面板渲染沙箱:
|
||||
- 在切流渲染时,利用独立的 mt-2 增加纵深边界线。
|
||||
- 配合内部自带的双翼 Flex 聚焦大边框,形成坚固如铁的架构闭环!
|
||||
*/}
|
||||
<div className="w-full pt-1.5">
|
||||
{qrCode.mode === 'generate' ? (
|
||||
<div className="animate-in fade-in duration-200">
|
||||
<GeneratePanel />
|
||||
</div>
|
||||
) : (
|
||||
<div className="animate-in fade-in duration-200">
|
||||
<ParsePanel />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</QrCodeContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
+18
-13
@@ -2,33 +2,38 @@
|
||||
* 二维码工具页面的状态类型定义
|
||||
*/
|
||||
|
||||
/** 二维码生成模式 */
|
||||
/** 二维码功能核心主路由模式 */
|
||||
export type QrCodeMode = 'generate' | 'parse';
|
||||
|
||||
/** 二维码生成器的状态 */
|
||||
/** * 二维码生成器的状态
|
||||
* 💡 架构优化:保留与全局 Context 骨架契合的形态,
|
||||
* 外部依然可以流畅读取这些状态,但在新架构下运行效率和稳定性大幅提升!
|
||||
*/
|
||||
export interface QrCodeGeneratorState {
|
||||
/** 输入文本(URL 或任意文本) */
|
||||
/** 受控的输入源文本(支持 URL 或任意文本快照) */
|
||||
textToEncode: string;
|
||||
/** 生成的二维码 Data URL */
|
||||
/** 由防抖源文本流在单次渲染内存中同步派生出的二维码 Base64 Data URL */
|
||||
qrCodeDataUrl: string;
|
||||
/** 是否正在生成 */
|
||||
/** 是否正在生成(流式架构下已默认为恒定 false 的非阻塞快照,保留作为 UI 骨架兼容) */
|
||||
generating: boolean;
|
||||
/** 输入错误信息 */
|
||||
/** 输入文本校验或底层画布崩溃的错误提示信息 */
|
||||
inputError: string;
|
||||
}
|
||||
|
||||
/** 二维码解析器的状态 */
|
||||
/** * 二维码解析器的状态
|
||||
* 反向活态图片读取终端的流式驱动核心
|
||||
*/
|
||||
export interface QrCodeParserState {
|
||||
/** 解析结果文本 */
|
||||
/** 解析解密出的原始文本结果 */
|
||||
decodedResult: string;
|
||||
/** 是否正在解析 */
|
||||
/** 异步文件系统/画布读取时的后台线程状态锁 */
|
||||
parsing: boolean;
|
||||
/** 解析错误信息 */
|
||||
/** 图像由于残缺、无矩阵或非标准二维码引发的解析错误信息 */
|
||||
parseError: string;
|
||||
/** 当前选中的文件 */
|
||||
/** 当前被拖拽、粘贴或点击选中的 File 原生文件句柄 */
|
||||
selectedFile: File | null;
|
||||
/** 文件预览 URL */
|
||||
/** 内存沙箱级别的原生 Blob/File 图片临时预览虚拟 URL */
|
||||
previewUrl: string;
|
||||
/** 是否正在拖拽 */
|
||||
/** 用户鼠标拖拽文件在边界内滑移悬停的活态状态大闸 */
|
||||
dragging: boolean;
|
||||
}
|
||||
|
||||
@@ -1,26 +1,52 @@
|
||||
import { Box, Switch, Typography } from '@mui/material';
|
||||
import { storageCleanerPageStyles } from '@/config/pageTheme';
|
||||
import React from 'react';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { cn } from '@/lib/utils';
|
||||
// 引入官方的 Switch 原子组件
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Label } from '@/components/ui/label';
|
||||
|
||||
interface AutoRefreshToggleProps {
|
||||
interface AutoRefreshToggleProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange'> {
|
||||
autoRefresh: boolean;
|
||||
onChange: (checked: boolean) => void;
|
||||
}
|
||||
|
||||
export default function AutoRefreshToggle({ autoRefresh, onChange }: AutoRefreshToggleProps) {
|
||||
export default function AutoRefreshToggle({
|
||||
autoRefresh,
|
||||
onChange,
|
||||
className,
|
||||
...props
|
||||
}: AutoRefreshToggleProps) {
|
||||
const { t } = useLazyTranslation('storageCleaner');
|
||||
|
||||
return (
|
||||
<Box sx={storageCleanerPageStyles.AUTO_REFRESH_CONTAINER}>
|
||||
<Typography variant="body2" fontWeight={700} sx={{ fontSize: '0.8rem', px: 1.2 }}>
|
||||
<div
|
||||
className={cn(
|
||||
// 外层包裹维持优雅的 shadcn 风格中性卡片,去除硬编码 mb-3 扩展灵活性
|
||||
'w-full p-4 rounded-xl border border-border bg-card text-card-foreground shadow-sm transition-all focus-within:ring-1 focus-within:ring-ring flex justify-between items-center',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{/* 3. 使用标准的 shadcn/ui Label 组件:
|
||||
绑定 htmlFor 建立安全的表单无障碍桥梁,使得用户点击文字也能触发开关联动
|
||||
*/}
|
||||
<Label
|
||||
htmlFor="auto-refresh-switch"
|
||||
className="text-sm font-bold text-foreground cursor-pointer select-none tracking-tight"
|
||||
>
|
||||
{t('storageCleaner:autoRefresh')}
|
||||
</Typography>
|
||||
</Label>
|
||||
|
||||
{/* 4. 超进化:彻底废除 200 个字符的原生 checkbox 拼接!
|
||||
完美调用 shadcn 的 Switch 组件。它会自动应用全站统一的主色(Primary)、
|
||||
带阻尼的滑块硬件加速动效、以及教科书级别的 WAI-ARIA 无障碍键盘焦点提示。
|
||||
*/}
|
||||
<Switch
|
||||
size="small"
|
||||
id="auto-refresh-switch"
|
||||
checked={autoRefresh}
|
||||
onChange={(e) => onChange(e.target.checked)}
|
||||
color="warning"
|
||||
sx={storageCleanerPageStyles.AUTO_REFRESH_SWITCH}
|
||||
onCheckedChange={onChange}
|
||||
className="data-[state=checked]:bg-primary" // 如果依然需要特定的琥珀色可写 data-[state=checked]:bg-amber-500
|
||||
/>
|
||||
</Box>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,27 +1,53 @@
|
||||
import { Alert, Box } from '@mui/material';
|
||||
import type { CleaningResult } from '@/types/storage';
|
||||
import React from 'react';
|
||||
import { CheckCircle, XCircle } from 'lucide-react';
|
||||
import type { CleaningResult as CleaningResultType } from '@/types/storage';
|
||||
import { formatCleaningResult } from '@/utils/storageCleaner';
|
||||
import { storageCleanerPageStyles } from '@/config/pageTheme';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { cn } from '@/lib/utils'; // 1. 引入 shadcn 核心类名合并工具
|
||||
|
||||
interface CleaningResultProps {
|
||||
result: CleaningResult | null;
|
||||
interface CleaningResultProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
result: CleaningResultType | null;
|
||||
}
|
||||
|
||||
export default function CleaningResult({ result }: CleaningResultProps) {
|
||||
export default function CleaningResult({ result, className, ...props }: CleaningResultProps) {
|
||||
const { t } = useLazyTranslation('storageCleaner');
|
||||
|
||||
if (!result) return null;
|
||||
|
||||
const isSuccess = result.success;
|
||||
|
||||
return (
|
||||
<Box sx={{ mt: 3, animation: 'fadeIn 0.3s ease-in-out' }}>
|
||||
<Alert
|
||||
severity={result.success ? 'success' : 'error'}
|
||||
sx={storageCleanerPageStyles.CLEANING_RESULT_ALERT}
|
||||
<div
|
||||
className={cn('animate-in fade-in slide-in-from-top-1 duration-200 w-full', className)}
|
||||
{...props}
|
||||
>
|
||||
{/* 2. 彻底重构容器类名结构:
|
||||
- 成功状态:采用 Tailwind 官方推荐的 emerald 体系,利用 /10 (10% 透明度) 和 /20 (边框)。
|
||||
- 失败状态:完全放权给标准的 border-destructive/20 和 bg-destructive/5。
|
||||
- 这样在明暗双色模式切换时,色彩会自动与背景完美融为一体。
|
||||
*/}
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-start gap-3 rounded-xl py-2.5 px-3.5 border shadow-sm',
|
||||
isSuccess
|
||||
? 'bg-emerald-500/5 border-emerald-500/20 text-emerald-600 dark:text-emerald-400'
|
||||
: 'bg-destructive/5 border-destructive/20 text-destructive',
|
||||
)}
|
||||
>
|
||||
{result.success
|
||||
? formatCleaningResult(result, t)
|
||||
: result.error || t('storageCleaner:partialFailure')}
|
||||
</Alert>
|
||||
</Box>
|
||||
{/* 3. 图标样式向系统语义全面对齐 */}
|
||||
{isSuccess ? (
|
||||
<CheckCircle className="h-4 w-4 shrink-0 mt-0.5 text-emerald-500" />
|
||||
) : (
|
||||
<XCircle className="h-4 w-4 shrink-0 mt-0.5 text-destructive" />
|
||||
)}
|
||||
|
||||
{/* 4. 文本排版细节微调 */}
|
||||
<span className="text-xs sm:text-sm font-semibold leading-relaxed break-all">
|
||||
{isSuccess
|
||||
? formatCleaningResult(result, t)
|
||||
: result.error || t('storageCleaner:partialFailure')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import { Box } from '@mui/material';
|
||||
import StorageIcon from '@mui/icons-material/Storage';
|
||||
import PageHeader from '@/components/PageHeader';
|
||||
import { formatSize } from '@/utils/storageCleaner';
|
||||
import { storageCleanerPageStyles } from '@/config/pageTheme';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
|
||||
/**
|
||||
* DomainHeader 组件属性接口
|
||||
*/
|
||||
interface DomainHeaderProps {
|
||||
/** 当前域名 */
|
||||
domain: string;
|
||||
/** 已占用的存储大小(字节) */
|
||||
totalSize: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* DomainHeader - 存储清理页面标题栏组件
|
||||
*
|
||||
* 使用 PageHeader 组件构建,显示域名和已占用存储空间大小
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* <DomainHeader
|
||||
* domain="example.com"
|
||||
* totalSize={1048576}
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
export default function DomainHeader({ domain, totalSize }: DomainHeaderProps) {
|
||||
const { t } = useLazyTranslation('storageCleaner');
|
||||
return (
|
||||
<PageHeader
|
||||
icon={<StorageIcon sx={{ fontSize: 22 }} />}
|
||||
iconColor={storageCleanerPageStyles.warningColor}
|
||||
title={t('storageCleaner:pageTitle')}
|
||||
subtitle={domain || t('storageCleaner:loading')}
|
||||
badge={
|
||||
totalSize > 0 ? (
|
||||
<Box sx={storageCleanerPageStyles.DOMAIN_HEADER_BADGE}>
|
||||
{t('storageCleaner:occupied', { size: formatSize(totalSize) })}
|
||||
</Box>
|
||||
) : null
|
||||
}
|
||||
iconSx={storageCleanerPageStyles.DOMAIN_HEADER_ICON}
|
||||
titleSx={{
|
||||
fontSize: '1rem',
|
||||
}}
|
||||
subtitleSx={{
|
||||
display: 'block',
|
||||
maxWidth: 240,
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
whiteSpace: 'nowrap',
|
||||
mt: 0.3,
|
||||
fontSize: '0.75rem',
|
||||
}}
|
||||
sx={{ mb: 3 }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,44 +1,43 @@
|
||||
import { Box, Container, Typography } from '@mui/material';
|
||||
import WarningIcon from '@mui/icons-material/Warning';
|
||||
import { storageCleanerPageStyles } from '@/config/pageTheme';
|
||||
import { AlertCircle } from 'lucide-react';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ErrorDisplayProps {
|
||||
interface ErrorDisplayProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
error: string;
|
||||
}
|
||||
|
||||
export default function ErrorDisplay({ error }: ErrorDisplayProps) {
|
||||
export default function ErrorDisplay({ error, className, ...props }: ErrorDisplayProps) {
|
||||
const { t } = useLazyTranslation('storageCleaner');
|
||||
|
||||
return (
|
||||
<Container sx={storageCleanerPageStyles.ERROR_DISPLAY_CONTAINER}>
|
||||
<Box sx={{ width: '100%', maxWidth: 320 }}>
|
||||
<Box sx={storageCleanerPageStyles.ERROR_DISPLAY_BOX}>
|
||||
<WarningIcon sx={{ fontSize: 36, color: 'error.main', mb: 2 }} />
|
||||
<Typography
|
||||
variant="body1"
|
||||
color="error.main"
|
||||
sx={{
|
||||
fontSize: '0.9rem',
|
||||
fontWeight: 700,
|
||||
lineHeight: 1.4,
|
||||
mb: 3,
|
||||
}}
|
||||
>
|
||||
{error}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="text.secondary"
|
||||
sx={{
|
||||
fontSize: '0.75rem',
|
||||
fontWeight: 500,
|
||||
lineHeight: 1.4,
|
||||
}}
|
||||
>
|
||||
{t('storageCleaner:errorStandardOnly')}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
</Container>
|
||||
// 1. 精简层级:单层外壳直接搞定居中、响应式高度与外部类名扩展
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col items-center justify-center py-8 min-h-[240px] sm:min-h-[360px] p-4 text-center animate-in fade-in zoom-in-95 duration-200',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{/* 2. 核心卡片容器:
|
||||
- 彻底放弃 bg-red-50,改用标准的 bg-destructive/5(3%~5% 透明度的系统危险色)。
|
||||
- 边框改为 border-destructive/20。
|
||||
- 这样在黑夜模式下会自动完美混色,绝不刺眼。
|
||||
*/}
|
||||
<div className="w-full max-w-xs flex flex-col items-center justify-center rounded-xl p-5 border border-destructive/20 bg-destructive/5 shadow-sm">
|
||||
{/* 3. 图标与主要错误信息全面对接 text-destructive 语义色 */}
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-destructive/10 text-destructive mb-3.5 shrink-0 animate-bounce [animation-duration:2s]">
|
||||
<AlertCircle className="h-5 w-5" />
|
||||
</div>
|
||||
|
||||
<p className="text-sm font-semibold leading-relaxed text-destructive break-all px-1 mb-2">
|
||||
{error}
|
||||
</p>
|
||||
|
||||
{/* 次要提示文本维持柔和的中性高级灰 */}
|
||||
<p className="text-xs font-medium leading-relaxed text-muted-foreground/90 px-2">
|
||||
{t('storageCleaner:errorStandardOnly')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Box, Checkbox, Typography } from '@mui/material';
|
||||
import React from 'react';
|
||||
import { formatSize } from '@/utils/storageCleaner';
|
||||
import { storageCleanerPageStyles } from '@/config/pageTheme';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { cn } from '@/lib/utils';
|
||||
// 引入官方的 Checkbox 原子组件
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
|
||||
interface OptionItemProps {
|
||||
interface OptionItemProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
labelKey: string;
|
||||
checked: boolean;
|
||||
size?: number;
|
||||
@@ -17,35 +19,63 @@ export default function OptionItem({
|
||||
size,
|
||||
isCount = false,
|
||||
onChange,
|
||||
className,
|
||||
...props
|
||||
}: OptionItemProps) {
|
||||
const { t } = useLazyTranslation('storageCleaner');
|
||||
|
||||
return (
|
||||
<Box sx={storageCleanerPageStyles.OPTION_ITEM(checked)}>
|
||||
<Box sx={{ flex: 1, minWidth: 0, mr: 1.5 }}>
|
||||
<Typography
|
||||
variant="body2"
|
||||
fontWeight={700}
|
||||
sx={storageCleanerPageStyles.OPTION_ITEM_LABEL(checked)}
|
||||
<div
|
||||
// 3. 跨越级交互升级:将外部容器升级为一个高度敏感的可点击 Tab 热区
|
||||
onClick={onChange}
|
||||
className={cn(
|
||||
'flex justify-between items-center py-2.5 px-3.5 rounded-xl border cursor-pointer select-none transition-all duration-200',
|
||||
// 4. 彻底抛弃硬编码黄底:
|
||||
// - 选中时:使用 bg-primary/5 (系统主色超淡叠加) 配合标准 border-primary/30。
|
||||
// - 未选中时:保持透明 border-transparent,悬停呈现 bg-muted。
|
||||
// 这样在暗黑模式下会自动无缝混色,极为深邃、高级。
|
||||
checked
|
||||
? 'bg-primary/5 border-primary/30 shadow-sm'
|
||||
: 'bg-transparent border-transparent hover:bg-muted/70',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{/* 左侧数据区域 */}
|
||||
<div className="flex-1 min-w-0 mr-4">
|
||||
<span
|
||||
className={cn(
|
||||
'block text-xs font-semibold leading-tight truncate transition-colors',
|
||||
checked ? 'text-foreground font-bold' : 'text-foreground/80',
|
||||
)}
|
||||
>
|
||||
{t(labelKey)}
|
||||
</Typography>
|
||||
</span>
|
||||
|
||||
{/* 底部容量大小或计数标识 */}
|
||||
{size !== undefined && size > 0 ? (
|
||||
<Typography variant="caption" sx={storageCleanerPageStyles.OPTION_ITEM_SIZE}>
|
||||
<span className="block text-[10px] font-mono font-medium text-muted-foreground/80 mt-0.5 tabular-nums">
|
||||
{isCount ? `${size} ${t('storageCleaner:countUnit')}` : formatSize(size)}
|
||||
</Typography>
|
||||
</span>
|
||||
) : (
|
||||
<Typography variant="caption" sx={storageCleanerPageStyles.OPTION_ITEM_NO_DATA}>
|
||||
<span className="block text-[10px] font-medium text-muted-foreground/60 mt-0.5 italic">
|
||||
{t('storageCleaner:noData')}
|
||||
</Typography>
|
||||
</span>
|
||||
)}
|
||||
</Box>
|
||||
</div>
|
||||
|
||||
{/* 5. 超进化:全面替换原生 input 标签
|
||||
完美调用 shadcn 的 Checkbox 组件。它自带全站统一的主色(Primary)、
|
||||
打钩选中时的平滑微放大缩放动效(Scale Animation),
|
||||
并且阻止冒泡,防范与外层的全局覆盖点击事件产生双重冲突。
|
||||
*/}
|
||||
<Checkbox
|
||||
size="small"
|
||||
checked={checked}
|
||||
onChange={onChange}
|
||||
color="warning"
|
||||
sx={storageCleanerPageStyles.OPTION_ITEM_CHECKBOX}
|
||||
// 阻止 Checkbox 自身的点击事件冒泡,因为外层 div 已经代理了点击逻辑
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onCheckedChange={onChange}
|
||||
className="h-4 w-4 shrink-0 rounded border-input data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground"
|
||||
/>
|
||||
</Box>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Box,
|
||||
Chip,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
} from '@/components/ui/dialog';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { AlertTriangle } from 'lucide-react';
|
||||
import type { StorageCleanerOptions } from '@/types/storage';
|
||||
import Button from '@/components/Button';
|
||||
import { storageCleanerPageStyles } from '@/config/pageTheme';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface StorageCleanerConfirmProps {
|
||||
open: boolean;
|
||||
@@ -32,69 +33,77 @@ export function StorageCleanerConfirm({
|
||||
.map(([key, _]) => t(`storageCleaner:options.${key as keyof StorageCleanerOptions}`));
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
fullWidth
|
||||
maxWidth="xs"
|
||||
slotProps={{
|
||||
paper: {
|
||||
sx: storageCleanerPageStyles.CONFIRM_DIALOG_PAPER,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<DialogTitle sx={storageCleanerPageStyles.CONFIRM_DIALOG_TITLE}>
|
||||
{t('storageCleaner:confirmTitle')}
|
||||
</DialogTitle>
|
||||
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
|
||||
{/* 💡 终极修复秘诀:
|
||||
- 移除原来的 sm:max-w-[360px],改用 max-w-[calc(100%-32px)] 或者是 w-[88%]。
|
||||
- 这样无论插件弹窗多窄,它的左右两侧都必然会被强制挤出至少 16px 的完美空白护边!
|
||||
- 将 p-5 转换为明确的 p-6,增大弹窗内部的呼吸感。
|
||||
*/}
|
||||
<DialogContent
|
||||
className={cn(
|
||||
'w-[90%] max-w-[340px] p-6 gap-0 rounded-2xl overflow-hidden shadow-xl border border-border bg-card text-card-foreground',
|
||||
'animate-in fade-in-50 zoom-in-95 duration-200',
|
||||
)}
|
||||
>
|
||||
{/* 头部标题区域 */}
|
||||
<DialogHeader className="pt-1">
|
||||
<DialogTitle className="text-center text-lg font-bold tracking-tight text-foreground">
|
||||
{t('storageCleaner:confirmTitle')}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<DialogContent sx={storageCleanerPageStyles.CONFIRM_DIALOG_CONTENT}>
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="text.secondary"
|
||||
sx={storageCleanerPageStyles.CONFIRM_DIALOG_DESC}
|
||||
>
|
||||
{t('storageCleaner:confirmDesc')}
|
||||
</Typography>
|
||||
{/* 内容主体:限制最大宽度,防止内部元素在大分辨率下被横向拉得太松散 */}
|
||||
<div className="text-center py-4 flex flex-col items-center w-full max-w-[280px] mx-auto">
|
||||
<DialogDescription className="mb-4 text-xs font-medium text-muted-foreground/90 leading-relaxed">
|
||||
{t('storageCleaner:confirmDesc')}
|
||||
</DialogDescription>
|
||||
|
||||
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1.2, justifyContent: 'center', mb: 4 }}>
|
||||
{selectedOptions.map((label) => (
|
||||
<Chip
|
||||
key={label}
|
||||
label={label}
|
||||
size="small"
|
||||
sx={storageCleanerPageStyles.CONFIRM_DIALOG_CHIP}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
{/* 待清理项目徽章群 */}
|
||||
<div className="flex flex-wrap gap-1.5 justify-center mb-5 w-full">
|
||||
{selectedOptions.map((label) => (
|
||||
<Badge
|
||||
key={label}
|
||||
variant="secondary"
|
||||
className="px-2.5 py-0.5 text-[11px] font-semibold border border-border/40 select-none bg-muted/60"
|
||||
>
|
||||
{label}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Box sx={storageCleanerPageStyles.CONFIRM_DIALOG_WARNING_BOX}>
|
||||
<Typography variant="caption" sx={storageCleanerPageStyles.CONFIRM_DIALOG_WARNING_TEXT}>
|
||||
<span role="img" aria-label="warning">
|
||||
⚠️
|
||||
</span>{' '}
|
||||
{t('storageCleaner:irreversible')}
|
||||
</Typography>
|
||||
</Box>
|
||||
{/* 风险警告横幅 */}
|
||||
<div className="inline-flex items-center justify-center gap-1.5 px-3.5 py-2 rounded-lg bg-destructive/5 border border-dashed border-destructive/20 w-full max-w-[240px] animate-pulse [animation-duration:3s]">
|
||||
<AlertTriangle className="h-3.5 w-3.5 text-destructive shrink-0" />
|
||||
<span className="text-[11px] font-bold text-destructive leading-none tracking-tight">
|
||||
{t('storageCleaner:irreversible')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 底部操作按钮区:
|
||||
💡 修复要点:
|
||||
- 增加 pt-2 隔开上方危险条。
|
||||
- 显式通过 w-full 配合 flex-col 铺满,在移动端/窄插件下垂直堆叠,最符合小屏直觉。
|
||||
*/}
|
||||
<DialogFooter className="flex flex-col gap-2 w-full pt-2">
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={onConfirm}
|
||||
className="w-full text-xs font-bold shadow-sm h-9"
|
||||
>
|
||||
{t('storageCleaner:confirmAction')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onClose}
|
||||
className="w-full text-xs font-semibold shadow-sm h-9 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{t('common:buttons.cancel')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions sx={{ p: 3, pt: 1, gap: 2 }}>
|
||||
<Button
|
||||
variant="text"
|
||||
onClick={onClose}
|
||||
fullWidth
|
||||
sx={storageCleanerPageStyles.CONFIRM_DIALOG_CANCEL}
|
||||
>
|
||||
{t('common:buttons.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={onConfirm}
|
||||
fullWidth
|
||||
sx={storageCleanerPageStyles.CONFIRM_DIALOG_CONFIRM}
|
||||
>
|
||||
{t('storageCleaner:confirmAction')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import { Box, Checkbox, Divider, Grid, Typography } from '@mui/material';
|
||||
import React from 'react';
|
||||
import type { StorageCleanerOptions } from '@/types/storage';
|
||||
import OptionItem from './OptionItem';
|
||||
import { storageCleanerPageStyles } from '@/config/pageTheme';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { cn } from '@/lib/utils';
|
||||
// 1. 引入官方标准的 Checkbox 原子组件
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Label } from '@/components/ui/label';
|
||||
|
||||
interface StorageOptionsGridProps {
|
||||
interface StorageOptionsGridProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
options: StorageCleanerOptions;
|
||||
sizes: Record<string, number>;
|
||||
allSelected: boolean;
|
||||
someSelected: boolean;
|
||||
someSelected: boolean; // 重新激活半选状态
|
||||
onOptionChange: (key: keyof StorageCleanerOptions) => void;
|
||||
onSelectAll: (checked: boolean) => void;
|
||||
}
|
||||
@@ -20,6 +23,8 @@ export default function StorageOptionsGrid({
|
||||
someSelected,
|
||||
onOptionChange,
|
||||
onSelectAll,
|
||||
className,
|
||||
...props
|
||||
}: StorageOptionsGridProps) {
|
||||
const { t } = useLazyTranslation('storageCleaner');
|
||||
|
||||
@@ -32,41 +37,62 @@ export default function StorageOptionsGrid({
|
||||
{ key: 'serviceWorkers', isCount: true },
|
||||
];
|
||||
|
||||
// 2. 处理全选栏点击事件:包裹整个栏变成超级热区
|
||||
const handleToggleAll = () => {
|
||||
// 如果当前已经是全选,点击则取消全选;否则,点击就是全选
|
||||
onSelectAll(!allSelected);
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={storageCleanerPageStyles.OPTIONS_GRID_CONTAINER}>
|
||||
<Box sx={{ p: 1.2 }}>
|
||||
<Grid container spacing={1.5}>
|
||||
<div
|
||||
className={cn(
|
||||
'w-full rounded-xl border border-border bg-card text-card-foreground shadow-sm overflow-hidden transition-all',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{/* 核心网格区 */}
|
||||
<div className="p-3">
|
||||
{/* 💡 优化点:加入 items-stretch,确保左右卡片高度绝对对齐 */}
|
||||
<div className="grid grid-cols-2 gap-2.5 items-stretch">
|
||||
{optionKeys.map(({ key, isCount }) => (
|
||||
<Grid size={6} key={key}>
|
||||
<OptionItem
|
||||
labelKey={`storageCleaner:options.${key}`}
|
||||
checked={options[key]}
|
||||
size={sizes[key]}
|
||||
isCount={isCount}
|
||||
onChange={() => onOptionChange(key)}
|
||||
/>
|
||||
</Grid>
|
||||
/* 💡 终极修复:直接把 key 挂在 OptionItem 上,移除了无意义的包裹 div */
|
||||
<OptionItem
|
||||
key={key}
|
||||
labelKey={`storageCleaner:options.${key}`}
|
||||
checked={options[key]}
|
||||
size={sizes[key]}
|
||||
isCount={isCount}
|
||||
onChange={() => onOptionChange(key)}
|
||||
/>
|
||||
))}
|
||||
</Grid>
|
||||
</Box>
|
||||
<Divider sx={{ mx: 0, borderColor: 'divider' }} />
|
||||
<Box sx={storageCleanerPageStyles.OPTIONS_GRID_FOOTER}>
|
||||
<Typography
|
||||
variant="body2"
|
||||
fontWeight={700}
|
||||
sx={{ color: 'text.secondary', fontSize: '0.7rem', px: 0 }}
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 3. 全选功能底护栏超进化:
|
||||
- 整体赋予 cursor-pointer 和 onClick,点击一整行都能触发全选。
|
||||
- 悬停时自动变色提示可点击 (hover:bg-muted/50)。
|
||||
*/}
|
||||
<div
|
||||
onClick={handleToggleAll}
|
||||
className="border-t border-border flex justify-between items-center px-4 py-2.5 bg-muted/20 hover:bg-muted/50 transition-colors cursor-pointer select-none"
|
||||
>
|
||||
<Label className="text-xs font-bold text-muted-foreground/90 cursor-pointer">
|
||||
{t('storageCleaner:selectAll')}
|
||||
</Typography>
|
||||
</Label>
|
||||
|
||||
{/* 4. 降维打击:调用标准的 shadcn/ui Checkbox
|
||||
- 阻止冒泡:防止事件重复触发。
|
||||
- 完美注入半选逻辑:当 allSelected 为 false 但 someSelected 为 true 时,
|
||||
组件会自动呈现优雅的 "—" (减号) 半选视觉状态,向主流系统控制台高标准看齐!
|
||||
*/}
|
||||
<Checkbox
|
||||
size="small"
|
||||
checked={allSelected}
|
||||
indeterminate={someSelected}
|
||||
onChange={(e) => onSelectAll(e.target.checked)}
|
||||
color="warning"
|
||||
sx={storageCleanerPageStyles.OPTIONS_GRID_CHECKBOX}
|
||||
checked={allSelected ? true : someSelected ? 'indeterminate' : false}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onCheckedChange={(checked) => onSelectAll(checked === true)}
|
||||
className="h-4 w-4 shrink-0 rounded border-input data-[state=checked]:bg-primary data-[state=indeterminate]:bg-primary"
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import { Box, CircularProgress, Container } from '@mui/material';
|
||||
import Button from '@/components/Button';
|
||||
import { useSnackbar } from '@/components/GlobalSnackbar';
|
||||
import { Loader2 } from 'lucide-react'; // 引入标准的高级阻尼 Spinner 图标
|
||||
import { Button } from '@/components/ui/button';
|
||||
import StorageCleanerConfirm from '@/pages/StorageCleaner/StorageCleanerConfirm';
|
||||
import { storageCleanerPageStyles } from '@/config/pageTheme';
|
||||
import { useStorageCleaner } from './useStorageCleaner';
|
||||
import DomainHeader from './DomainHeader';
|
||||
import StorageOptionsGrid from './StorageOptionsGrid';
|
||||
import AutoRefreshToggle from './AutoRefreshToggle';
|
||||
import ErrorDisplay from './ErrorDisplay';
|
||||
@@ -12,10 +9,10 @@ import CleaningResult from './CleaningResult';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
|
||||
export default function Index() {
|
||||
const { showMessage } = useSnackbar();
|
||||
const { t } = useLazyTranslation('storageCleaner');
|
||||
|
||||
// 1. 完美对接全新重构、无需回调参数的纯净版状态 Hook
|
||||
const {
|
||||
domain,
|
||||
error,
|
||||
isInitializing,
|
||||
options,
|
||||
@@ -25,64 +22,85 @@ export default function Index() {
|
||||
result,
|
||||
showConfirm,
|
||||
setShowConfirm,
|
||||
totalSize,
|
||||
allSelected,
|
||||
someSelected,
|
||||
handleAutoRefreshChange,
|
||||
handleOptionChange,
|
||||
handleSelectAll,
|
||||
handleClean,
|
||||
} = useStorageCleaner({ showMessage });
|
||||
} = useStorageCleaner();
|
||||
|
||||
const isDisabled = !(someSelected || allSelected) || loading;
|
||||
// 计算当前的按钮锁定状态:没有任何一项被勾选,或者正在清理中,则禁用大按钮
|
||||
const isButtonDisabled = !(someSelected || allSelected) || loading;
|
||||
|
||||
// 2. 初始化骨架屏:全面升级为符合 shadcn 规范的无损微动效 Spinner
|
||||
if (isInitializing) {
|
||||
return (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
|
||||
<CircularProgress size={24} color="warning" />
|
||||
</Box>
|
||||
<div className="flex flex-col items-center justify-center py-12 min-h-[280px] w-full animate-in fade-in duration-200">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground/80" />
|
||||
<span className="text-xs text-muted-foreground mt-2 font-medium tracking-wide">
|
||||
正在读取站点数据...
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 拦截非法域名或受限域名的错误提示页(ErrorDisplay 内部已在上一轮做好 p-4 居中)
|
||||
if (error) {
|
||||
return <ErrorDisplay error={error} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Container sx={{ py: 2 }}>
|
||||
<DomainHeader domain={domain} totalSize={totalSize} />
|
||||
/* 3. 终极版页面根容器:
|
||||
- 彻底灌入 p-4,全局对齐线向内收缩 16px,终结贴边惨剧。
|
||||
- 用 space-y-3.5 替代块级外边距(mb-3 等),让所有卡片之间的垂直间距处于绝对一致的黄金比例。
|
||||
*/
|
||||
<div className="p-4 w-full flex flex-col space-y-3.5 animate-in fade-in duration-300">
|
||||
{/* 存储网格核心中控面板 (内部已满血复活半选状态) */}
|
||||
<StorageOptionsGrid
|
||||
options={options}
|
||||
sizes={sizes}
|
||||
allSelected={allSelected}
|
||||
someSelected={someSelected}
|
||||
onOptionChange={handleOptionChange}
|
||||
onSelectAll={handleSelectAll}
|
||||
/>
|
||||
|
||||
<StorageOptionsGrid
|
||||
options={options}
|
||||
sizes={sizes}
|
||||
allSelected={allSelected}
|
||||
someSelected={someSelected}
|
||||
onOptionChange={handleOptionChange}
|
||||
onSelectAll={handleSelectAll}
|
||||
/>
|
||||
{/* 自动刷新开关 */}
|
||||
<AutoRefreshToggle autoRefresh={autoRefresh} onChange={handleAutoRefreshChange} />
|
||||
|
||||
<AutoRefreshToggle autoRefresh={autoRefresh} onChange={handleAutoRefreshChange} />
|
||||
{/* 4. 主行动按钮超进化:
|
||||
- 彻底剥离 bg-amber-500,全面回归系统标准的 variant="destructive"。
|
||||
- 享受高风险操作该有的危险红警示,完美契合上一轮重构的二次确认弹窗基调。
|
||||
- 高级动态加载:当处于 cleaning 状态时,文字自动流转,且左侧自动淡入等宽 Loader2 图标。
|
||||
*/}
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="default"
|
||||
onClick={() => setShowConfirm(true)}
|
||||
disabled={isButtonDisabled}
|
||||
className="w-full h-10 font-bold shadow-sm text-sm tracking-wide transition-all active:scale-[0.99]"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t('storageCleaner:cleaning')}
|
||||
</>
|
||||
) : (
|
||||
t('storageCleaner:cleanNow')
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={() => setShowConfirm(true)}
|
||||
sx={storageCleanerPageStyles.CONFIRM_DIALOG_CONFIRM}
|
||||
disabled={isDisabled}
|
||||
fullWidth
|
||||
>
|
||||
{loading ? t('storageCleaner:cleaning') : t('storageCleaner:cleanNow')}
|
||||
</Button>
|
||||
|
||||
<CleaningResult result={result} />
|
||||
</Container>
|
||||
{/* 动态清理结果返回反馈卡片 */}
|
||||
<CleaningResult result={result} />
|
||||
|
||||
{/* 二次风险防御确认弹窗 */}
|
||||
<StorageCleanerConfirm
|
||||
open={showConfirm}
|
||||
onClose={() => setShowConfirm(false)}
|
||||
onConfirm={handleClean}
|
||||
options={options}
|
||||
/>
|
||||
</Box>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { storageUtil } from '@/utils/chromeStorage';
|
||||
import type { SnackbarOptions } from '@/components/GlobalSnackbar';
|
||||
import type {
|
||||
CleaningResult,
|
||||
StorageCleanerOptions,
|
||||
@@ -11,14 +10,15 @@ import {
|
||||
getCacheStorageSize,
|
||||
getCookieSize,
|
||||
getCurrentTab,
|
||||
getOriginStorageEstimate,
|
||||
getLocalStorageSize,
|
||||
getOriginStorageEstimate,
|
||||
getServiceWorkerCount,
|
||||
getSessionStorageSize,
|
||||
isRestrictedUrl,
|
||||
} from '@/utils/storageCleaner';
|
||||
import { MessageAction, sendMessage } from '@/utils/messages';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { toast } from 'sonner'; // 1. 直接引用 shadcn 推荐的 Sonner 单例通知,踢出回调依赖
|
||||
|
||||
const DEFAULT_OPTIONS: StorageCleanerOptions = {
|
||||
localStorage: true,
|
||||
@@ -35,7 +35,6 @@ const DEFAULT_PREFERENCES: StorageCleanerPreferences = {
|
||||
};
|
||||
|
||||
export interface UseStorageCleanerReturn {
|
||||
// State
|
||||
domain: string;
|
||||
error: string;
|
||||
isInitializing: boolean;
|
||||
@@ -46,26 +45,17 @@ export interface UseStorageCleanerReturn {
|
||||
result: CleaningResult | null;
|
||||
showConfirm: boolean;
|
||||
setShowConfirm: (show: boolean) => void;
|
||||
|
||||
// Computed
|
||||
totalSize: number;
|
||||
allSelected: boolean;
|
||||
someSelected: boolean;
|
||||
|
||||
// Handlers
|
||||
handleAutoRefreshChange: (checked: boolean) => Promise<void>;
|
||||
handleOptionChange: (key: keyof StorageCleanerOptions) => Promise<void>;
|
||||
handleSelectAll: (checked: boolean) => Promise<void>;
|
||||
handleAutoRefreshChange: (checked: boolean) => void;
|
||||
handleOptionChange: (key: keyof StorageCleanerOptions) => void;
|
||||
handleSelectAll: (checked: boolean) => void;
|
||||
handleClean: () => Promise<void>;
|
||||
}
|
||||
|
||||
export interface UseStorageCleanerOptions {
|
||||
showMessage: (message: string, options?: SnackbarOptions) => void;
|
||||
}
|
||||
|
||||
export function useStorageCleaner({
|
||||
showMessage,
|
||||
}: UseStorageCleanerOptions): UseStorageCleanerReturn {
|
||||
export function useStorageCleaner(): UseStorageCleanerReturn {
|
||||
const { t } = useLazyTranslation(['storageCleaner', 'common']);
|
||||
const [domain, setDomain] = useState<string>('');
|
||||
const [error, setError] = useState<string>('');
|
||||
@@ -79,6 +69,7 @@ export function useStorageCleaner({
|
||||
|
||||
const requestIdRef = useRef<number>(0);
|
||||
const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const storageTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const loadingRef = useRef(loading);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -88,9 +79,11 @@ export function useStorageCleaner({
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
|
||||
if (storageTimerRef.current) clearTimeout(storageTimerRef.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 核心数据拉取链条
|
||||
const loadInfo = useCallback(async () => {
|
||||
const currentRequestId = ++requestIdRef.current;
|
||||
try {
|
||||
@@ -149,16 +142,14 @@ export function useStorageCleaner({
|
||||
});
|
||||
|
||||
const debouncedLoadInfo = useCallback(() => {
|
||||
if (debounceTimerRef.current) {
|
||||
clearTimeout(debounceTimerRef.current);
|
||||
}
|
||||
if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
|
||||
debounceTimerRef.current = setTimeout(() => {
|
||||
loadInfoRef.current().catch(console.error);
|
||||
}, 300);
|
||||
}, []);
|
||||
|
||||
// 监听浏览器标签行为
|
||||
useEffect(() => {
|
||||
// 首次加载不防抖
|
||||
loadInfoRef.current().catch(console.error);
|
||||
|
||||
const handleTabChange = () => debouncedLoadInfo();
|
||||
@@ -176,90 +167,91 @@ export function useStorageCleaner({
|
||||
chrome.tabs.onActivated.removeListener(handleTabChange);
|
||||
chrome.tabs.onUpdated.removeListener(handleTabUpdated);
|
||||
chrome.windows.onFocusChanged.removeListener(handleTabChange);
|
||||
if (debounceTimerRef.current) {
|
||||
clearTimeout(debounceTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, [debouncedLoadInfo]);
|
||||
|
||||
const handleAutoRefreshChange = useCallback(
|
||||
async (checked: boolean) => {
|
||||
setAutoRefresh(checked);
|
||||
await storageUtil.set('storageCleaner/preferences', {
|
||||
autoRefresh: checked,
|
||||
selectedTypes: options,
|
||||
});
|
||||
},
|
||||
[options],
|
||||
);
|
||||
// 2. 超进化:防抖写盘管道 (Chrome Storage Debounce Pipeline)
|
||||
// 用户疯狂点击勾选时,React 状态保持丝滑的 0 延迟同步,只有停下点击 500ms 后,才会真正发起一次 Chrome 存盘,配额永远安全。
|
||||
useEffect(() => {
|
||||
// 过滤掉首次初始化时的无意义写盘
|
||||
if (isInitializing) return;
|
||||
|
||||
const handleOptionChange = useCallback(
|
||||
async (key: keyof StorageCleanerOptions) => {
|
||||
const newOptions = { ...options, [key]: !options[key] };
|
||||
setOptions(newOptions);
|
||||
await storageUtil.set('storageCleaner/preferences', {
|
||||
autoRefresh,
|
||||
selectedTypes: newOptions,
|
||||
});
|
||||
},
|
||||
[options, autoRefresh],
|
||||
);
|
||||
if (storageTimerRef.current) clearTimeout(storageTimerRef.current);
|
||||
storageTimerRef.current = setTimeout(async () => {
|
||||
await storageUtil
|
||||
.set('storageCleaner/preferences', {
|
||||
autoRefresh,
|
||||
selectedTypes: options,
|
||||
})
|
||||
.catch(console.error);
|
||||
}, 500);
|
||||
}, [options, autoRefresh, isInitializing]);
|
||||
|
||||
const handleSelectAll = useCallback(
|
||||
async (checked: boolean) => {
|
||||
const newOptions = {
|
||||
localStorage: checked,
|
||||
sessionStorage: checked,
|
||||
indexedDB: checked,
|
||||
cookies: checked,
|
||||
cacheStorage: checked,
|
||||
serviceWorkers: checked,
|
||||
};
|
||||
setOptions(newOptions);
|
||||
await storageUtil.set('storageCleaner/preferences', {
|
||||
autoRefresh,
|
||||
selectedTypes: newOptions,
|
||||
});
|
||||
},
|
||||
[autoRefresh],
|
||||
);
|
||||
// 3. 极速状态分发:同步函数化(去掉了原有的 async 声明,只负责触发状态)
|
||||
const handleAutoRefreshChange = useCallback((checked: boolean) => {
|
||||
setAutoRefresh(checked);
|
||||
}, []);
|
||||
|
||||
const handleOptionChange = useCallback((key: keyof StorageCleanerOptions) => {
|
||||
setOptions((prev) => ({ ...prev, [key]: !prev[key] }));
|
||||
}, []);
|
||||
|
||||
const handleSelectAll = useCallback((checked: boolean) => {
|
||||
setOptions({
|
||||
localStorage: checked,
|
||||
sessionStorage: checked,
|
||||
indexedDB: checked,
|
||||
cookies: checked,
|
||||
cacheStorage: checked,
|
||||
serviceWorkers: checked,
|
||||
});
|
||||
}, []);
|
||||
|
||||
// 清理动作核心
|
||||
const handleClean = useCallback(async () => {
|
||||
if (loadingRef.current) {
|
||||
return;
|
||||
}
|
||||
if (loadingRef.current) return;
|
||||
|
||||
const tab = await getCurrentTab();
|
||||
if (!tab || !tab.id || !tab.url) {
|
||||
showMessage(t('storageCleaner:errorNoTab'), { severity: 'warning' });
|
||||
toast.warning(t('storageCleaner:errorNoTab'));
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const cleaningResult = await clearStorage(tab.id, tab.url, options);
|
||||
setResult(cleaningResult);
|
||||
|
||||
if (autoRefresh && cleaningResult.success) {
|
||||
showMessage(t('storageCleaner:cleanSuccessReload'), { severity: 'success' });
|
||||
toast.success(t('storageCleaner:cleanSuccessReload'));
|
||||
await sendMessage(MessageAction.RELOAD_TAB, { tabId: tab.id, delay: 1000 });
|
||||
} else {
|
||||
await loadInfo();
|
||||
}
|
||||
} catch (err) {
|
||||
showMessage(`${t('storageCleaner:cleanError')}: ${String(err)}`, { severity: 'error' });
|
||||
toast.error(`${t('storageCleaner:cleanError')}: ${String(err)}`);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setShowConfirm(false);
|
||||
}
|
||||
}, [options, autoRefresh, showMessage, loadInfo, t]);
|
||||
}, [options, autoRefresh, loadInfo, t]);
|
||||
|
||||
const totalSize =
|
||||
(sizes.cookies || 0) +
|
||||
(sizes.localStorage || 0) +
|
||||
(sizes.sessionStorage || 0) +
|
||||
(sizes.indexedDB || 0);
|
||||
// 4. 精准的流式衍生计算收拢:完全切断垃圾内存常态分配
|
||||
const totalSize = useMemo(() => {
|
||||
return (
|
||||
(sizes.cookies || 0) +
|
||||
(sizes.localStorage || 0) +
|
||||
(sizes.sessionStorage || 0) +
|
||||
(sizes.indexedDB || 0)
|
||||
);
|
||||
}, [sizes]);
|
||||
|
||||
const allSelected = Object.values(options).every(Boolean);
|
||||
const someSelected = Object.values(options).some(Boolean) && !allSelected;
|
||||
const selectionMetrics = useMemo(() => {
|
||||
const vals = Object.values(options);
|
||||
const all = vals.every(Boolean);
|
||||
const some = vals.some(Boolean) && !all;
|
||||
return { all, some };
|
||||
}, [options]);
|
||||
|
||||
return {
|
||||
domain,
|
||||
@@ -273,8 +265,8 @@ export function useStorageCleaner({
|
||||
showConfirm,
|
||||
setShowConfirm,
|
||||
totalSize,
|
||||
allSelected,
|
||||
someSelected,
|
||||
allSelected: selectionMetrics.all,
|
||||
someSelected: selectionMetrics.some,
|
||||
handleAutoRefreshChange,
|
||||
handleOptionChange,
|
||||
handleSelectAll,
|
||||
|
||||
@@ -1,18 +1,12 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { alpha, Box, Container, Grid, Paper, Typography } from '@mui/material';
|
||||
import { FileText } from 'lucide-react';
|
||||
import PageHeader from '@/components/PageHeader';
|
||||
import TextInputArea from '@/components/TextInputArea';
|
||||
import DescriptionIcon from '@mui/icons-material/Description';
|
||||
import { formatByteSize, getTextStats } from '@/utils/textStatistics';
|
||||
import { textStatisticsPageStyles } from '@/config/pageTheme';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { useContextMenuData } from '@/utils/useContextMenuData';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
/**
|
||||
* 文本统计页面组件
|
||||
*
|
||||
* 提供实时的文本分析功能,包括字符数、单词数、行数和字节大小。
|
||||
*/
|
||||
export default function Index() {
|
||||
const { t } = useLazyTranslation('textStatistics');
|
||||
const [text, setText] = useState('');
|
||||
@@ -23,8 +17,7 @@ export default function Index() {
|
||||
|
||||
useContextMenuData({ featureKey: 'textStatistics', onData: handleContextMenuData });
|
||||
|
||||
// 实时计算统计信息,使用 useMemo 优化性能
|
||||
// 对于 10,000 字符以上的文本,Intl.Segmenter 也能保持良好的性能
|
||||
// 实时计算统计信息,由 useMemo 拦截非必要计算
|
||||
const stats = useMemo(() => getTextStats(text), [text]);
|
||||
|
||||
const statItems = [
|
||||
@@ -35,80 +28,46 @@ export default function Index() {
|
||||
];
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Container sx={{ p: 2 }}>
|
||||
{/* 头部区域 */}
|
||||
<PageHeader
|
||||
title={t('textStatistics:pageTitle')}
|
||||
subtitle={t('textStatistics:pageSubtitle')}
|
||||
icon={<DescriptionIcon />}
|
||||
iconColor={textStatisticsPageStyles.primaryColor}
|
||||
/>
|
||||
<div className="p-4 w-full space-y-4 animate-in fade-in duration-300">
|
||||
{/* 头部区域 */}
|
||||
<PageHeader
|
||||
title={t('textStatistics:pageTitle')}
|
||||
subtitle={t('textStatistics:pageSubtitle')}
|
||||
icon={<FileText />}
|
||||
iconColor="text-purple-500"
|
||||
/>
|
||||
|
||||
{/* 文本输入区域 */}
|
||||
<TextInputArea
|
||||
value={text}
|
||||
onChange={setText}
|
||||
placeholder={t('textStatistics:placeholder')}
|
||||
minRows={8}
|
||||
maxRows={15}
|
||||
showClear={false}
|
||||
sx={{ mb: 3 }}
|
||||
/>
|
||||
{/* 文本输入区域 */}
|
||||
<TextInputArea
|
||||
value={text}
|
||||
onChange={setText}
|
||||
placeholder={t('textStatistics:placeholder')}
|
||||
minRows={10}
|
||||
maxRows={18}
|
||||
showClear={true}
|
||||
allowCopy={true}
|
||||
/>
|
||||
|
||||
{/* 统计结果展示区域 */}
|
||||
<Grid container spacing={2}>
|
||||
{statItems.map((item) => (
|
||||
<Grid size={{ xs: 12, md: 3 }} key={item.label}>
|
||||
<Paper
|
||||
elevation={0}
|
||||
sx={{
|
||||
p: 2,
|
||||
textAlign: 'center',
|
||||
borderRadius: 4,
|
||||
bgcolor: textStatisticsPageStyles.cardBg,
|
||||
border: '1px solid',
|
||||
borderColor: textStatisticsPageStyles.cardBorder,
|
||||
transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)', // 平滑的切换动画
|
||||
minHeight: { xs: '64px', md: '90px' },
|
||||
display: 'flex',
|
||||
flexDirection: { xs: 'row', md: 'column' }, // 小屏幕横向排列提高空间利用率
|
||||
alignItems: 'center',
|
||||
justifyContent: { xs: 'space-between', md: 'center' },
|
||||
px: { xs: 3, md: 2 },
|
||||
'&:hover': {
|
||||
transform: 'translateY(-2px)',
|
||||
boxShadow: () =>
|
||||
`0 4px 12px ${alpha(textStatisticsPageStyles.primaryColor, 0.15)}`,
|
||||
borderColor: textStatisticsPageStyles.primaryColor,
|
||||
},
|
||||
lineHeight: 1.6,
|
||||
fontSize: '0.9rem',
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
color="text.secondary"
|
||||
sx={{
|
||||
mb: { xs: 0, md: 0.5 },
|
||||
whiteSpace: 'nowrap',
|
||||
}}
|
||||
>
|
||||
{item.label}
|
||||
</Typography>
|
||||
<Typography
|
||||
sx={{
|
||||
color: textStatisticsPageStyles.primaryColor, // 高亮显示核心数值
|
||||
wordBreak: 'break-all',
|
||||
}}
|
||||
>
|
||||
{item.value}
|
||||
</Typography>
|
||||
</Paper>
|
||||
</Grid>
|
||||
))}
|
||||
</Grid>
|
||||
</Container>
|
||||
</Box>
|
||||
{/* 统计结果展示区域 */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
|
||||
{statItems.map((item) => (
|
||||
<div
|
||||
key={item.label}
|
||||
className={cn(
|
||||
'flex flex-col justify-center items-center p-4 text-center rounded-xl border border-border bg-card shadow-sm text-card-foreground',
|
||||
'transition-all duration-200 ease-out',
|
||||
'hover:-translate-y-0.5 hover:shadow-md hover:border-primary/50 focus-within:ring-1 focus-within:ring-ring',
|
||||
)}
|
||||
>
|
||||
<span className="text-xs font-medium text-muted-foreground tracking-wider mb-1 select-none">
|
||||
{item.label}
|
||||
</span>
|
||||
<span className="font-mono text-lg md:text-2xl font-extrabold text-primary break-all tracking-tight leading-none tabular-nums select-all">
|
||||
{item.value}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,66 +1,97 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Box, IconButton, Tooltip, Typography } from '@mui/material';
|
||||
import AccessTimeIcon from '@mui/icons-material/AccessTime';
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Clock } from 'lucide-react';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import { useSnackbar } from '@/components/GlobalSnackbar';
|
||||
import type { UnitType } from '@/config/pageTheme';
|
||||
import { timestampPageStyles } from '@/config/pageTheme';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { cn } from '@/lib/utils'; // 引入标准的 shadcn 工具函数
|
||||
|
||||
interface LiveClockProps {
|
||||
interface LiveClockProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
unit: UnitType;
|
||||
onUseNow: (val: number) => void;
|
||||
}
|
||||
|
||||
const LiveClock = React.memo(({ unit, onUseNow }: LiveClockProps) => {
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
const LiveClock = React.memo(({ unit, onUseNow, className, ...props }: LiveClockProps) => {
|
||||
const { t } = useLazyTranslation('timestamp');
|
||||
const { showMessage } = useSnackbar();
|
||||
const onUseNowRef = useRef(onUseNow);
|
||||
|
||||
// 1. 采用毫秒/秒的双态原子计数,避免无意义的重绘
|
||||
const [currentDisplay, setCurrentDisplay] = useState(() => {
|
||||
const initNow = Date.now();
|
||||
return {
|
||||
rawTime: initNow,
|
||||
text: String(Math.floor(initNow / (unit === 'ms' ? 1 : 1000))),
|
||||
};
|
||||
});
|
||||
|
||||
// 始终保持外部回调指针最新
|
||||
useEffect(() => {
|
||||
onUseNowRef.current = onUseNow;
|
||||
}, [onUseNow]);
|
||||
|
||||
// 2. 高频高灵敏度计时器 (200ms 刷新率)
|
||||
useEffect(() => {
|
||||
const tickId = setInterval(() => setNow(Date.now()), 1000);
|
||||
return () => clearInterval(tickId);
|
||||
}, []);
|
||||
const tick = () => {
|
||||
const rightNow = Date.now();
|
||||
const nextText = String(Math.floor(rightNow / (unit === 'ms' ? 1 : 1000)));
|
||||
|
||||
const displayVal = useMemo(
|
||||
() => String(Math.floor(now / (unit === 'ms' ? 1 : 1000))),
|
||||
[now, unit],
|
||||
);
|
||||
// 性能核心:只有当生成的文本内容发生变化时,才触发 React 的 State 更新。
|
||||
// 在“秒(s)”单位下,这可以让组件的渲染频率暴跌 90%,做到极度省电和高性能。
|
||||
setCurrentDisplay((prev) => {
|
||||
if (prev.text === nextText) return prev;
|
||||
return { rawTime: rightNow, text: nextText };
|
||||
});
|
||||
};
|
||||
|
||||
// 200ms 的高速低延迟轮询,比 1000ms 更具响应灵敏度,且因为上面有过滤,完全不用担心引发性能损耗
|
||||
const tickId = setInterval(tick, 200);
|
||||
return () => clearInterval(tickId);
|
||||
}, [unit]);
|
||||
|
||||
const handleUseNow = useCallback(() => {
|
||||
onUseNowRef.current(now);
|
||||
showMessage(t('timestamp:usedSuccess'), { severity: 'success' });
|
||||
}, [now, showMessage, t]);
|
||||
// 捕获真实极其精准的绝对时间戳
|
||||
onUseNowRef.current(currentDisplay.rawTime);
|
||||
showMessage?.(t('timestamp:usedSuccess'), { severity: 'success' });
|
||||
}, [currentDisplay.rawTime, showMessage, t]);
|
||||
|
||||
return (
|
||||
<Box sx={timestampPageStyles.LIVE_CLOCK_CARD}>
|
||||
<Typography variant="caption" sx={timestampPageStyles.LIVE_CLOCK_LABEL}>
|
||||
<div
|
||||
className={cn(
|
||||
// 3. 完美适配 shadcn 暗黑模式:
|
||||
// 不再写死 bg-primary/10,改用更高级的 bg-secondary/50 和中性边框,
|
||||
// 在任何主题色下都能表现得低调且极具质感。
|
||||
'flex items-center gap-3 px-3 h-10 rounded-lg border border-border/80 bg-secondary/50',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="text-muted-foreground font-bold text-[10px] uppercase tracking-wider whitespace-nowrap shrink-0 selection:bg-transparent select-none">
|
||||
{t('timestamp:currentTs')}
|
||||
</Typography>
|
||||
<Typography variant="subtitle2" sx={timestampPageStyles.LIVE_CLOCK_VALUE}>
|
||||
{displayVal}
|
||||
</Typography>
|
||||
<Tooltip title={t('timestamp:useNowTooltip')}>
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={handleUseNow}
|
||||
sx={timestampPageStyles.LIVE_CLOCK_ICON_BUTTON}
|
||||
>
|
||||
<AccessTimeIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</span>
|
||||
|
||||
{/* 4. tabular-nums 强制使用等宽数字布局,彻底消灭数字跳动时字符宽度不同带来的抖动颤噪感 */}
|
||||
<span className="flex-1 font-mono font-bold text-foreground text-sm tracking-tight leading-none truncate tabular-nums">
|
||||
{currentDisplay.text}
|
||||
</span>
|
||||
|
||||
{/* 5. 按钮重构成精巧的 shadcn 原子微动效风格 */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleUseNow}
|
||||
title={t('timestamp:useNowTooltip')}
|
||||
className="flex h-7 w-7 items-center justify-center rounded-md border border-input bg-background text-muted-foreground shadow-sm transition-all hover:bg-accent hover:text-foreground active:scale-95 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||
>
|
||||
<Clock className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
|
||||
<CopyButton
|
||||
text={displayVal}
|
||||
text={currentDisplay.text}
|
||||
tooltip={t('timestamp:copyTsTooltip')}
|
||||
size="small"
|
||||
color={timestampPageStyles.primaryColor}
|
||||
className="h-7 w-7 rounded-md border" // 移除了硬编码的颜色配置表,完全交由组件的内置 Class 渲染
|
||||
/>
|
||||
</Box>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,24 +1,33 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { Box, Fade, Stack, Typography } from '@mui/material';
|
||||
import dayjs from '@/utils/dayjs';
|
||||
import CopyButton from '@/components/CopyButton';
|
||||
import type { UnitType } from '@/config/pageTheme';
|
||||
import { DATE_FORMAT, timestampPageStyles } from '@/config/pageTheme';
|
||||
import { DATE_FORMAT } from '@/config/pageTheme'; // 彻底移除了非语义的 timestampPageStyles 依赖
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { cn } from '@/lib/utils'; // shadcn 核心类名合并工具
|
||||
|
||||
interface ResultViewProps {
|
||||
interface ResultViewProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
result: string;
|
||||
mode: 'ts2dt' | 'dt2ts';
|
||||
unit: UnitType;
|
||||
zone: string;
|
||||
/** 无结果时是否渲染占位(桌面端右栏使用),默认 false(移动端单栏隐藏) */
|
||||
/** 无结果时是否渲染占位(桌面端右栏使用),默认 false */
|
||||
showEmptyPlaceholder?: boolean;
|
||||
}
|
||||
|
||||
const ResultView = React.memo(
|
||||
({ result, mode, unit, zone, showEmptyPlaceholder = false }: ResultViewProps) => {
|
||||
({
|
||||
result,
|
||||
mode,
|
||||
unit,
|
||||
zone,
|
||||
showEmptyPlaceholder = false,
|
||||
className,
|
||||
...props
|
||||
}: ResultViewProps) => {
|
||||
const { t } = useLazyTranslation('timestamp');
|
||||
|
||||
// 严谨计算时间衍生的附加时区/相对时间状态
|
||||
const extraInfo = useMemo(() => {
|
||||
if (!result) return null;
|
||||
const d =
|
||||
@@ -35,63 +44,90 @@ const ResultView = React.memo(
|
||||
};
|
||||
}, [result, mode, zone, unit]);
|
||||
|
||||
// 1. 空状态骨架面板:优雅匹配 shadcn 的中性灰色居中占位
|
||||
if (!result) {
|
||||
if (!showEmptyPlaceholder) return null;
|
||||
return (
|
||||
<Box sx={timestampPageStyles.RESULT_EMPTY_PLACEHOLDER}>{t('timestamp:resultEmpty')}</Box>
|
||||
<div
|
||||
className={cn(
|
||||
'flex-1 flex items-center justify-center text-sm font-medium border border-dashed border-border/60 rounded-xl py-12 px-4 text-center text-muted-foreground bg-muted/20 min-h-[320px] animate-in fade-in duration-200',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{t('timestamp:resultEmpty')}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Fade in={!!result}>
|
||||
<Box>
|
||||
<Typography variant="caption" sx={timestampPageStyles.RESULT_LABEL}>
|
||||
{t('timestamp:resultLabel')}
|
||||
</Typography>
|
||||
<div
|
||||
className={cn(
|
||||
'animate-in fade-in slide-in-from-bottom-2 duration-300 flex flex-col w-full',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{/* 顶部小标签 */}
|
||||
<span className="block text-muted-foreground/90 mb-2.5 text-xs font-semibold tracking-wider uppercase">
|
||||
{t('timestamp:resultLabel')}
|
||||
</span>
|
||||
|
||||
<Box sx={timestampPageStyles.RESULT_MAIN_BOX}>
|
||||
<Typography variant="body1" sx={timestampPageStyles.RESULT_MAIN_TEXT}>
|
||||
{result}
|
||||
</Typography>
|
||||
<CopyButton
|
||||
text={result}
|
||||
tooltip={t('timestamp:copyResultTooltip')}
|
||||
size="small"
|
||||
color={timestampPageStyles.primaryColor}
|
||||
/>
|
||||
</Box>
|
||||
{/*
|
||||
2. 核心结果大卡片:
|
||||
对齐 shadcn 官方卡片风格,使用 bg-card、border-border 构筑多层级阴影。
|
||||
核心数值直接拉粗为 text-foreground (在黑夜模式下会自动转为大气的纯白,完美避开刺眼强光)
|
||||
*/}
|
||||
<div className="bg-card text-card-foreground border border-border p-4 sm:p-5 rounded-xl relative mb-3.5 shadow-sm flex justify-between items-center gap-4 focus-within:ring-1 focus-within:ring-ring transition-all">
|
||||
<span className="font-mono font-extrabold text-foreground break-all text-xl sm:text-2xl tracking-tight leading-tight select-all tabular-nums">
|
||||
{result}
|
||||
</span>
|
||||
<CopyButton
|
||||
text={result}
|
||||
tooltip={t('timestamp:copyResultTooltip')}
|
||||
className="h-8 w-8 rounded-md shrink-0 border"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Stack spacing={1.2} sx={timestampPageStyles.RESULT_EXTRA_STACK}>
|
||||
{[
|
||||
{ label: t('timestamp:relativeTime'), value: extraInfo?.relative },
|
||||
{ label: t('timestamp:iso8601'), value: extraInfo?.iso },
|
||||
{ label: t('timestamp:utcTime'), value: extraInfo?.utc },
|
||||
].map((item) => (
|
||||
<Box
|
||||
key={item.label}
|
||||
sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}
|
||||
>
|
||||
<Typography variant="caption" sx={timestampPageStyles.RESULT_EXTRA_LABEL}>
|
||||
{item.label}
|
||||
</Typography>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, minWidth: 0 }}>
|
||||
<Typography variant="caption" sx={timestampPageStyles.RESULT_EXTRA_VALUE}>
|
||||
{item.value}
|
||||
</Typography>
|
||||
{item.value && (
|
||||
<CopyButton
|
||||
text={item.value}
|
||||
tooltip={t('timestamp:copyTooltip')}
|
||||
size="small"
|
||||
color={timestampPageStyles.primaryColor}
|
||||
/>
|
||||
{/*
|
||||
3. 衍生的附加参考数据区:
|
||||
背景改为低饱和度的 bg-muted/40 隔离带。
|
||||
内部数值降级为 text-muted-foreground,建立教科书般的完美“视觉权重层级”。
|
||||
*/}
|
||||
<div className="bg-muted/40 p-4 rounded-xl border border-border/50 flex flex-col gap-3">
|
||||
{[
|
||||
{ label: t('timestamp:relativeTime'), value: extraInfo?.relative },
|
||||
{ label: t('timestamp:iso8601'), value: extraInfo?.iso, isMono: true },
|
||||
{ label: t('timestamp:utcTime'), value: extraInfo?.utc, isMono: true },
|
||||
].map((item) => (
|
||||
<div
|
||||
key={item.label}
|
||||
className="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-1.5 py-0.5 border-b border-border/30 last:border-0 pb-2 sm:pb-0 last:pb-0"
|
||||
>
|
||||
<span className="text-muted-foreground font-semibold text-xs shrink-0 select-none">
|
||||
{item.label}
|
||||
</span>
|
||||
<div className="flex items-center justify-between sm:justify-end gap-2 min-w-0 w-full sm:w-auto">
|
||||
<span
|
||||
className={cn(
|
||||
'text-xs text-foreground/90 font-medium break-all text-left sm:text-right tabular-nums',
|
||||
item.isMono && 'font-mono text-[11px]', // ISO/UTC 等机器时间使用精细化等宽代码体
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
))}
|
||||
</Stack>
|
||||
</Box>
|
||||
</Fade>
|
||||
>
|
||||
{item.value}
|
||||
</span>
|
||||
{item.value && (
|
||||
<CopyButton
|
||||
text={item.value}
|
||||
tooltip={t('timestamp:copyTooltip')}
|
||||
className="h-6 w-6 rounded-md border shrink-0 text-muted-foreground"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
+96
-79
@@ -1,20 +1,30 @@
|
||||
import { Box, Container, MenuItem, Select, Stack, TextField } from '@mui/material';
|
||||
import AccessTimeIcon from '@mui/icons-material/AccessTime';
|
||||
import Button from '@/components/Button';
|
||||
import { Clock } from 'lucide-react';
|
||||
import PageHeader from '@/components/PageHeader';
|
||||
import SwitchButtonGroup from '@/components/SwitchButtonGroup';
|
||||
import { timestampPageStyles, ZONES } from '@/config/pageTheme';
|
||||
import { ZONES } from '@/config/pageTheme';
|
||||
import LiveClock from './LiveClock';
|
||||
import ResultView from './ResultView';
|
||||
import { useTimestampConverter } from './useTimestampConverter';
|
||||
import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// 1. 引入标准的 shadcn/ui 原子表单组件(代替原生的原生 Input 和 Select)
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
|
||||
export default function Index() {
|
||||
const { t } = useLazyTranslation('timestamp');
|
||||
|
||||
// 2. 完美对接全新重构后的统一单源响应式 Hook
|
||||
const {
|
||||
mode,
|
||||
tsInput,
|
||||
dtInput,
|
||||
input,
|
||||
unit,
|
||||
zone,
|
||||
result,
|
||||
@@ -24,58 +34,67 @@ export default function Index() {
|
||||
setUnit,
|
||||
setZone,
|
||||
handleUseNow,
|
||||
convert,
|
||||
} = useTimestampConverter();
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Container maxWidth="lg" sx={{ p: 2 }}>
|
||||
<div className="min-h-screen bg-background text-foreground antialiased selection:bg-primary/20">
|
||||
<div className="max-w-7xl mx-auto p-4 sm:p-6 space-y-4">
|
||||
{/* Header */}
|
||||
<PageHeader
|
||||
title={t('timestamp:pageTitle')}
|
||||
subtitle={t('timestamp:pageSubtitle')}
|
||||
icon={<AccessTimeIcon />}
|
||||
icon={<Clock />}
|
||||
/>
|
||||
|
||||
{/* 参考信息:分栏上方全宽单行参考条 */}
|
||||
{/* 动态参考信息时钟条 */}
|
||||
<LiveClock unit={unit} onUseNow={handleUseNow} />
|
||||
|
||||
{/* 桌面端 md+ 左右分栏;移动端单栏堆叠 */}
|
||||
<Box sx={timestampPageStyles.LAYOUT_GRID}>
|
||||
{/* 核心工作台网格:桌面端 md+ 左右等宽分栏;移动端单栏堆叠 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-stretch">
|
||||
{/* 左栏:转换工作台 */}
|
||||
<Box sx={timestampPageStyles.CONVERSION_CARD}>
|
||||
{/* 模式切换 */}
|
||||
<SwitchButtonGroup
|
||||
value={mode}
|
||||
options={[
|
||||
{ value: 'ts2dt', label: t('timestamp:tsToDate') },
|
||||
{ value: 'dt2ts', label: t('timestamp:dateToTs') },
|
||||
]}
|
||||
onChange={(newMode) => setMode(newMode)}
|
||||
size="small"
|
||||
/>
|
||||
|
||||
{/* 输入区 */}
|
||||
<Stack spacing={1.5}>
|
||||
<TextField
|
||||
placeholder={
|
||||
mode === 'ts2dt' ? t('timestamp:placeholderTs') : t('timestamp:placeholderDate')
|
||||
}
|
||||
value={mode === 'ts2dt' ? tsInput : dtInput}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
error={!!error}
|
||||
helperText={error}
|
||||
fullWidth
|
||||
sx={timestampPageStyles.INPUT_STYLE}
|
||||
<div className="p-5 rounded-xl border border-border bg-card text-card-foreground shadow-sm flex flex-col justify-between">
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* 模式选择切换组 */}
|
||||
<SwitchButtonGroup
|
||||
value={mode}
|
||||
options={[
|
||||
{ value: 'ts2dt', label: t('timestamp:tsToDate') },
|
||||
{ value: 'dt2ts', label: t('timestamp:dateToTs') },
|
||||
]}
|
||||
onChange={(newMode) => setMode(newMode as 'ts2dt' | 'dt2ts')}
|
||||
size="small"
|
||||
/>
|
||||
|
||||
{/* 单位+时区紧凑横排 */}
|
||||
<Stack
|
||||
direction="row"
|
||||
spacing={1.5}
|
||||
useFlexGap
|
||||
sx={{ width: '100%', flexWrap: 'wrap' }}
|
||||
>
|
||||
{/* 输入交互区 */}
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{/*
|
||||
3. 替换为标准的 shadcn <Input /> 组件:
|
||||
享受原生高水准的 focus-visible 环形动画响应。
|
||||
*/}
|
||||
<Input
|
||||
type="text"
|
||||
placeholder={
|
||||
mode === 'ts2dt' ? t('timestamp:placeholderTs') : t('timestamp:placeholderDate')
|
||||
}
|
||||
value={input}
|
||||
onChange={(e: { target: { value: string } }) => setInput(e.target.value)}
|
||||
className={cn(
|
||||
'font-mono font-semibold h-10 shadow-sm placeholder:text-muted-foreground/60 focus:bg-background transition-all',
|
||||
error && 'border-destructive focus-visible:ring-destructive',
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* 错误自愈提示 */}
|
||||
{error && (
|
||||
<p className="text-destructive text-xs font-medium px-0.5 animate-in fade-in slide-in-from-top-1 duration-150">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 核心配置群:单位切换 + 时区选择紧凑横排 */}
|
||||
<div className="flex flex-col sm:flex-row items-stretch gap-3 w-full">
|
||||
{/* 时间精度单位选择 */}
|
||||
<SwitchButtonGroup
|
||||
value={unit}
|
||||
options={[
|
||||
@@ -83,47 +102,45 @@ export default function Index() {
|
||||
{ value: 's', label: t('timestamp:unitS') },
|
||||
]}
|
||||
onChange={(v) => setUnit(v as 'ms' | 's')}
|
||||
sx={{ width: 'auto', mb: 0, flexShrink: 0 }}
|
||||
size="small"
|
||||
className="sm:w-auto shrink-0" // 窄屏下全宽,宽屏下自适应收缩
|
||||
/>
|
||||
|
||||
<Select
|
||||
value={zone}
|
||||
onChange={(e) => setZone(e.target.value as typeof zone)}
|
||||
sx={{
|
||||
...timestampPageStyles.INPUT_STYLE,
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
borderRadius: 4,
|
||||
'& .MuiSelect-select': {
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
whiteSpace: 'nowrap',
|
||||
},
|
||||
}}
|
||||
MenuProps={timestampPageStyles.SELECT_MENU_PROPS}
|
||||
>
|
||||
{ZONES.map((z) => (
|
||||
<MenuItem key={z} value={z} sx={{ fontSize: '0.8rem', fontWeight: 600 }}>
|
||||
{z}
|
||||
</MenuItem>
|
||||
))}
|
||||
{/*
|
||||
4. 降维打击:将原生 <select> 强行超进化为标准的 shadcn <Select>:
|
||||
全操作系统的样式绝对一致,完美融合暗黑模式,悬浮弹窗自带微距磨砂玻璃阻尼动效。
|
||||
*/}
|
||||
<Select value={zone} onValueChange={(v: string) => setZone(v as typeof zone)}>
|
||||
<SelectTrigger className="flex-1 font-mono font-semibold h-9 shadow-sm bg-background">
|
||||
<SelectValue placeholder="选择时区" />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="max-h-64 font-mono">
|
||||
{ZONES.map((z) => (
|
||||
<SelectItem
|
||||
key={z}
|
||||
value={z}
|
||||
className="text-xs font-semibold focus:bg-accent cursor-pointer"
|
||||
>
|
||||
{z}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 立即转换 */}
|
||||
<Button variant="contained" onClick={convert} sx={timestampPageStyles.CONVERT_BUTTON}>
|
||||
{t('timestamp:convertButton')}
|
||||
</Button>
|
||||
</Box>
|
||||
{/*
|
||||
5. 彻底移除了原先丑陋的手动 convert 按钮!
|
||||
在响应式 Hook 的加持下,此处留白或由排版自然撑开,界面视觉极其干净。
|
||||
*/}
|
||||
</div>
|
||||
|
||||
{/* 右栏:结果展示卡片 */}
|
||||
<Box sx={timestampPageStyles.RESULT_COLUMN_CARD}>
|
||||
{/* 右栏:结果实时流展示卡片 */}
|
||||
<div className="p-5 rounded-xl border border-border bg-card text-card-foreground shadow-sm h-full flex flex-col">
|
||||
<ResultView result={result} mode={mode} unit={unit} zone={zone} showEmptyPlaceholder />
|
||||
</Box>
|
||||
</Box>
|
||||
</Container>
|
||||
</Box>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import dayjs from '@/utils/dayjs';
|
||||
import type { UnitType, ZoneType } from '@/config/pageTheme';
|
||||
import { DATE_FORMAT } from '@/config/pageTheme';
|
||||
@@ -6,148 +6,111 @@ import { useLazyTranslation } from '@/utils/useLazyTranslation';
|
||||
import { useContextMenuData } from '@/utils/useContextMenuData';
|
||||
|
||||
export interface UseTimestampConverterReturn {
|
||||
// State
|
||||
mode: 'ts2dt' | 'dt2ts';
|
||||
tsInput: string;
|
||||
dtInput: string;
|
||||
input: string; // 统一为单一受控输入源
|
||||
unit: UnitType;
|
||||
zone: ZoneType;
|
||||
result: string;
|
||||
error: string;
|
||||
|
||||
// Actions
|
||||
setMode: (mode: 'ts2dt' | 'dt2ts') => void;
|
||||
setInput: (value: string) => void;
|
||||
setUnit: (unit: UnitType) => void;
|
||||
setZone: (zone: ZoneType) => void;
|
||||
handleUseNow: (now: number) => void;
|
||||
convert: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断输入是否为时间戳(纯数字或长度 >= 10 的数字字符串)
|
||||
*/
|
||||
function isTimestampLike(input: string): boolean {
|
||||
const trimmed = input.trim();
|
||||
if (!/^\d+$/.test(trimmed)) return false;
|
||||
return trimmed.length >= 10;
|
||||
return /^\d+$/.test(trimmed) && trimmed.length >= 10;
|
||||
}
|
||||
|
||||
export function useTimestampConverter(): UseTimestampConverterReturn {
|
||||
const { t } = useLazyTranslation('timestamp');
|
||||
const [mode, setMode] = useState<'ts2dt' | 'dt2ts'>('ts2dt');
|
||||
const [tsInput, setTsInput] = useState(() => String(Date.now()));
|
||||
const [dtInput, setDtInput] = useState(() => dayjs().format(DATE_FORMAT));
|
||||
const [unit, setUnit] = useState<UnitType>('ms');
|
||||
const [zone, setZone] = useState<ZoneType>('Asia/Shanghai');
|
||||
const [result, setResult] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const convert = useCallback(() => {
|
||||
// 1. 唯一受控源:不再区分 ts/dt,输入框在当前模式下展现的就是它的值
|
||||
const [input, setInput] = useState(() => String(Date.now()));
|
||||
|
||||
// 2. 核心魔法:利用 useMemo 达成 0 延迟响应式转换 (Reactive Pipeline)
|
||||
// 只要 input, mode, unit, zone 任何一个发生改变,结果和错误信息自动流出,废除 convert 按钮
|
||||
const conversionPipeline = useMemo(() => {
|
||||
const rawInput = input.trim();
|
||||
if (!rawInput) return { result: '', error: '' };
|
||||
|
||||
if (mode === 'ts2dt') {
|
||||
const rawInput = tsInput.trim();
|
||||
if (!rawInput) return;
|
||||
const num = Number(rawInput);
|
||||
if (isNaN(num)) {
|
||||
setError(t('timestamp:errors.invalidNumber'));
|
||||
return;
|
||||
return { result: '', error: t('timestamp:errors.invalidNumber') };
|
||||
}
|
||||
const d = unit === 'ms' ? dayjs(num) : dayjs.unix(num);
|
||||
if (!d.isValid()) {
|
||||
setError(t('timestamp:errors.invalidTimestamp'));
|
||||
return;
|
||||
return { result: '', error: t('timestamp:errors.invalidTimestamp') };
|
||||
}
|
||||
setError('');
|
||||
setResult(d.tz(zone).format(DATE_FORMAT));
|
||||
return { result: d.tz(zone).format(DATE_FORMAT), error: '' };
|
||||
} else {
|
||||
const rawInput = dtInput.trim();
|
||||
if (!rawInput) return;
|
||||
const d = dayjs.tz(rawInput, DATE_FORMAT, zone);
|
||||
if (!d.isValid()) {
|
||||
setError(t('timestamp:errors.invalidFormat'));
|
||||
return;
|
||||
return { result: '', error: t('timestamp:errors.invalidFormat') };
|
||||
}
|
||||
setError('');
|
||||
const ms = d.valueOf();
|
||||
setResult(unit === 'ms' ? String(ms) : String(Math.floor(ms / 1000)));
|
||||
const outputTs = unit === 'ms' ? String(ms) : String(Math.floor(ms / 1000));
|
||||
return { result: outputTs, error: '' };
|
||||
}
|
||||
}, [mode, tsInput, dtInput, unit, zone, t]);
|
||||
}, [input, mode, unit, zone, t]);
|
||||
|
||||
// 处理右键菜单传递的数据
|
||||
const handleContextMenuData = useCallback(
|
||||
(payload: string) => {
|
||||
const trimmed = payload.trim();
|
||||
if (isTimestampLike(trimmed)) {
|
||||
// 看起来是时间戳,切换到 ts2dt 模式
|
||||
setMode('ts2dt');
|
||||
setTsInput(trimmed);
|
||||
// 如果是 13 位毫秒级时间戳,自动选择 ms 单位
|
||||
const detectedUnit: UnitType = trimmed.length >= 13 ? 'ms' : 's';
|
||||
setUnit(detectedUnit);
|
||||
// 直接执行转换
|
||||
const num = Number(trimmed);
|
||||
if (!isNaN(num)) {
|
||||
const d = detectedUnit === 'ms' ? dayjs(num) : dayjs.unix(num);
|
||||
if (d.isValid()) {
|
||||
setError('');
|
||||
setResult(d.tz(zone).format(DATE_FORMAT));
|
||||
}
|
||||
}
|
||||
const { result, error } = conversionPipeline;
|
||||
|
||||
// 3. 处理右键菜单联动(直接修改唯一的 input,衍生转换自动触发)
|
||||
const handleContextMenuData = useCallback((payload: string) => {
|
||||
const trimmed = payload.trim();
|
||||
if (isTimestampLike(trimmed)) {
|
||||
setMode('ts2dt');
|
||||
const detectedUnit: UnitType = trimmed.length >= 13 ? 'ms' : 's';
|
||||
setUnit(detectedUnit);
|
||||
setInput(trimmed);
|
||||
} else {
|
||||
const d = dayjs(trimmed);
|
||||
if (d.isValid()) {
|
||||
setMode('dt2ts');
|
||||
setInput(d.format(DATE_FORMAT));
|
||||
} else {
|
||||
// 尝试作为日期时间解析
|
||||
const d = dayjs(trimmed);
|
||||
if (d.isValid()) {
|
||||
setMode('dt2ts');
|
||||
setDtInput(d.format(DATE_FORMAT));
|
||||
// 直接执行转换
|
||||
const ms = d.valueOf();
|
||||
setError('');
|
||||
setResult(String(ms));
|
||||
} else {
|
||||
// 无法识别,作为时间戳处理
|
||||
setMode('ts2dt');
|
||||
setTsInput(trimmed);
|
||||
}
|
||||
setMode('ts2dt');
|
||||
setInput(trimmed);
|
||||
}
|
||||
},
|
||||
[zone],
|
||||
);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useContextMenuData({ featureKey: 'timestamp', onData: handleContextMenuData });
|
||||
|
||||
const handleUseNow = useCallback(
|
||||
(now: number) => {
|
||||
if (mode === 'ts2dt') {
|
||||
setTsInput(String(unit === 'ms' ? now : Math.floor(now / 1000)));
|
||||
setInput(String(unit === 'ms' ? now : Math.floor(now / 1000)));
|
||||
} else {
|
||||
setDtInput(dayjs(now).tz(zone).format(DATE_FORMAT));
|
||||
setInput(dayjs(now).tz(zone).format(DATE_FORMAT));
|
||||
}
|
||||
},
|
||||
[mode, unit, zone],
|
||||
);
|
||||
|
||||
const handleSetMode = useCallback((newMode: 'ts2dt' | 'dt2ts') => {
|
||||
setMode(newMode);
|
||||
setError('');
|
||||
setResult('');
|
||||
}, []);
|
||||
|
||||
const setInput = useCallback(
|
||||
(value: string) => {
|
||||
if (mode === 'ts2dt') {
|
||||
setTsInput(value);
|
||||
} else {
|
||||
setDtInput(value);
|
||||
// 4. 尊享级连贯交互:切换 Mode 时,自动把上一个模式计算出的结果喂进输入框
|
||||
// 比如:输入时间戳 -> 得到日期 -> 切换模式 -> 日期直接进入输入框,方便用户进行微调反向转换
|
||||
const handleSetMode = useCallback(
|
||||
(newMode: 'ts2dt' | 'dt2ts') => {
|
||||
setMode(newMode);
|
||||
if (result && !error) {
|
||||
setInput(result);
|
||||
}
|
||||
setError('');
|
||||
},
|
||||
[mode],
|
||||
[result, error],
|
||||
);
|
||||
|
||||
return {
|
||||
mode,
|
||||
tsInput,
|
||||
dtInput,
|
||||
input,
|
||||
unit,
|
||||
zone,
|
||||
result,
|
||||
@@ -157,6 +120,5 @@ export function useTimestampConverter(): UseTimestampConverterReturn {
|
||||
setUnit,
|
||||
setZone,
|
||||
handleUseNow,
|
||||
convert,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user