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:
LingandRX
2026-05-23 00:02:43 +08:00
committed by GitHub
parent 689c3faf16
commit efbed7cf53
114 changed files with 7621 additions and 7262 deletions
+72 -25
View File
@@ -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 };
+88 -64
View File
@@ -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 } 声明
+89 -149
View File
@@ -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>
);
}
+17 -22
View File
@@ -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 };
+126 -193
View File
@@ -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
View File
@@ -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 '';
};
+74 -37
View File
@@ -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
View File
@@ -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
View File
@@ -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;
}