refactor: 全面重构 JsonTools 页面,采用声明式响应架构并统一 shadcn 样式

This commit is contained in:
雨霖铃
2026-05-22 21:45:13 +08:00
parent 336b62256d
commit d2e5e6b45d
9 changed files with 797 additions and 601 deletions
+56 -11
View File
@@ -1,7 +1,9 @@
import React from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react'; import { ChevronLeft, ChevronRight } from 'lucide-react';
import { useLazyTranslation } from '@/utils/useLazyTranslation'; import { useLazyTranslation } from '@/utils/useLazyTranslation';
import { cn } from '@/lib/utils'; // 1. 引入标准的 shadcn 工具函数
interface DiffNavigatorProps { export interface DiffNavigatorProps extends React.HTMLAttributes<HTMLDivElement> {
total: number; total: number;
/** 0-based index */ /** 0-based index */
currentIndex: number; currentIndex: number;
@@ -9,40 +11,83 @@ interface DiffNavigatorProps {
onNext: () => void; 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 { t } = useLazyTranslation('jsonDiff');
// 计算当前的边界禁用状态守卫
const isFirst = currentIndex <= 0;
const isLast = currentIndex >= total - 1;
// 2. 空状态面板:对齐 shadcn 规范的中性低调卡片
if (total === 0) { if (total === 0) {
return ( return (
<div className="flex items-center justify-center gap-3 p-2.5 rounded-lg bg-primary/10 border border-primary/30"> <div
<span className="text-sm font-bold text-muted-foreground">{t('jsonDiff:noDiffs')}</span> 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')}
</span>
</div> </div>
); );
} }
return ( return (
<div className="flex items-center justify-center gap-3 p-2.5 rounded-lg bg-primary/10 border border-primary/30"> <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 <button
type="button" type="button"
disabled={isFirst}
aria-label={t('jsonDiff:previousDiff')} aria-label={t('jsonDiff:previousDiff')}
onClick={onPrev} onClick={onPrev}
className="p-1 rounded-md hover:bg-blue-100 transition-colors" 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. 边界拦截:触顶时优雅淡化并锁死点击
)}
> >
<ChevronLeft className="h-4 w-4" /> <ChevronLeft className="h-4 w-4" />
</button> </button>
<span className="text-sm font-extrabold font-mono min-w-[60px] text-center">
{currentIndex + 1} / {total} {/* 计数看板:强制等宽防止数字长短不一时产生宽度挤压跳动 */}
<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> </span>
{/* 下一处差异按钮 */}
<button <button
type="button" type="button"
disabled={isLast}
aria-label={t('jsonDiff:nextDiff')} aria-label={t('jsonDiff:nextDiff')}
onClick={onNext} onClick={onNext}
className="p-1 rounded-md hover:bg-blue-100 transition-colors" 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" /> <ChevronRight className="h-4 w-4" />
</button> </button>
</div> </div>
); );
} }
export type { DiffNavigatorProps };
+80 -31
View File
@@ -1,19 +1,31 @@
import React from 'react';
import { useLazyTranslation } from '@/utils/useLazyTranslation'; import { useLazyTranslation } from '@/utils/useLazyTranslation';
import { cn } from '@/lib/utils';
import JsonTree from './JsonTree'; import JsonTree from './JsonTree';
import type { DiffNode, DiffResult as DiffResultType, DiffType, ViewMode } from './types'; import type { DiffNode, DiffResult as DiffResultType, DiffType, ViewMode } from './types';
interface DiffResultProps { // 💡 顶层 Interface 继承原生 HTML 容器属性,扩展灵活性
export interface DiffResultProps extends React.HTMLAttributes<HTMLDivElement> {
result: DiffResultType; result: DiffResultType;
viewMode: ViewMode; viewMode: ViewMode;
activePath?: string; activePath?: string;
} }
export default function DiffResult({ result, viewMode, activePath }: DiffResultProps) { export default function DiffResult({
result,
viewMode,
activePath,
className,
...props
}: DiffResultProps) {
const { t } = useLazyTranslation('jsonDiff'); const { t } = useLazyTranslation('jsonDiff');
if (viewMode === 'sideBySide') { if (viewMode === 'sideBySide') {
return ( return (
<div className="flex flex-col md:flex-row gap-4 items-stretch"> <div
className={cn('flex flex-col md:flex-row gap-4 items-stretch w-full', className)}
{...props}
>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<SectionLabel text={t('jsonDiff:leftLabel')} /> <SectionLabel text={t('jsonDiff:leftLabel')} />
<JsonTree node={result.root} side="left" activePath={activePath} /> <JsonTree node={result.root} side="left" activePath={activePath} />
@@ -27,14 +39,24 @@ export default function DiffResult({ result, viewMode, activePath }: DiffResultP
} }
return ( return (
<div className="p-3 rounded-lg bg-background border border-border font-mono text-sm overflow-x-auto min-h-[200px] max-h-[480px] overflow-y-auto"> /* 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} /> <UnifiedView node={result.root} depth={0} activePath={activePath} />
</div> </div>
); );
} }
const SectionLabel = ({ text }: { text: string }) => ( const SectionLabel = ({ text }: { text: string }) => (
<span className="block mb-1.5 text-[11px] font-extrabold tracking-wider text-muted-foreground uppercase"> <span className="block mb-2 text-[10px] font-bold tracking-wider text-muted-foreground/80 uppercase px-0.5 select-none">
{text} {text}
</span> </span>
); );
@@ -51,24 +73,31 @@ const isContainerType = (v: unknown): boolean =>
(typeof v === 'object' && v !== null) || Array.isArray(v); (typeof v === 'object' && v !== null) || Array.isArray(v);
const prefixForType = (type: DiffType): string => { const prefixForType = (type: DiffType): string => {
if (type === 'added') return '+ '; if (type === 'added') return '+';
if (type === 'removed') return '- '; if (type === 'removed') return '-';
if (type === 'modified') return '~ '; if (type === 'modified') return '~';
return ' '; return ' ';
}; };
const colorForType = (type: DiffType): string => { // 2. 状态色彩超进化:
if (type === 'added') return 'text-green-600'; // 拒绝硬编码实色系,全部换用高度安全的语义色变体与暗黑模式自适应。
if (type === 'removed') return 'text-red-600'; const typeThemeMap = {
if (type === 'modified') return 'text-amber-600'; added: {
return 'text-foreground'; text: 'text-emerald-600 dark:text-emerald-400',
}; bg: 'bg-emerald-500/5 dark:bg-emerald-500/10',
},
const bgForType = (type: DiffType): string | undefined => { removed: {
if (type === 'added') return 'bg-green-50'; text: 'text-destructive',
if (type === 'removed') return 'bg-red-50'; bg: 'bg-destructive/5 dark:bg-destructive/10',
if (type === 'modified') return 'bg-amber-50'; },
return undefined; 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 { interface UnifiedViewProps {
@@ -85,7 +114,6 @@ const UnifiedView = ({ node, depth, activePath }: UnifiedViewProps) => {
const keyLabel = isRoot ? '' : `${node.key}: `; const keyLabel = isRoot ? '' : `${node.key}: `;
if (!isContainer) { if (!isContainer) {
// 叶子节点
if (node.type === 'modified') { if (node.type === 'modified') {
return ( return (
<> <>
@@ -115,7 +143,7 @@ const UnifiedView = ({ node, depth, activePath }: UnifiedViewProps) => {
); );
} }
// 容器节点added/removed 整块呈现 // 容器节点整块渲染处理
if (node.type === 'added') { if (node.type === 'added') {
return ( return (
<UnifiedRow <UnifiedRow
@@ -163,17 +191,38 @@ interface UnifiedRowProps {
} }
const UnifiedRow = ({ depth, type, text, active, multiline }: UnifiedRowProps) => { const UnifiedRow = ({ depth, type, text, active, multiline }: UnifiedRowProps) => {
const color = colorForType(type); // 3. 高精度提取状态样式映射
const bg = bgForType(type); const currentTheme = typeThemeMap[type] || typeThemeMap.unchanged;
return ( return (
<div <div
className={`${bg ?? ''} ${color} ${active ? 'ring-2 ring-blue-500 rounded' : ''} ${ className={cn(
multiline ? 'whitespace-pre' : 'whitespace-nowrap' 'flex items-start w-full font-mono py-0.5 select-text group transition-colors',
} font-mono`} currentTheme.bg,
style={{ paddingLeft: `${depth * 1.5}rem`, paddingRight: '0.25rem', paddingBlock: '0.2rem' }} 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',
}}
> >
<span className="font-extrabold">{prefixForType(type)}</span> {/* 5. 前缀标识:等宽锁定,强行占据 w-5 并让符号居中对齐,达成 VSCode 般的整洁排版 */}
<span>{text}</span> <span className="font-bold w-5 shrink-0 text-center select-none opacity-70 tabular-nums">
{prefixForType(type)}
</span>
<span
className={cn(
'flex-1 break-all tracking-tight leading-normal',
multiline ? 'whitespace-pre' : 'whitespace-nowrap',
)}
>
{text}
</span>
</div> </div>
); );
}; };
@@ -192,4 +241,4 @@ const stringifyMultiline = (v: unknown, depth: number): string => {
} }
}; };
export type { DiffResultProps }; // 💡 彻底移除了文件底部引发 TS2484 冲突的 export type { DiffResultProps } 声明
+77 -84
View File
@@ -1,149 +1,142 @@
import { useEffect, useMemo, useState } from 'react'; import React, { useEffect, useMemo, useState } from 'react';
import { Button } from '@/components/ui/button';
import { useLazyTranslation } from '@/utils/useLazyTranslation'; import { useLazyTranslation } from '@/utils/useLazyTranslation';
import { formatByteSize } from '@/utils/textStatistics'; import { formatByteSize } from '@/utils/textStatistics';
import CopyButton from '@/components/CopyButton'; import CopyButton from '@/components/CopyButton';
import TextInputArea from '@/components/TextInputArea'; import TextInputArea from '@/components/TextInputArea';
import { validateJson } from '@/utils/jsonFormatter'; import { validateJson } from '@/utils/jsonFormatter';
import { cn } from '@/lib/utils';
/** 转换结果通用接口 */
export interface ConvertResult { export interface ConvertResult {
/** 转换后的输出字符串 */
output: string; output: string;
/** 原始输入的字节大小 */
originalBytes: number; originalBytes: number;
/** 转换后的字节大小 */
outputBytes: number; outputBytes: number;
} }
/** 转换函数类型 */
export type ConvertFunction = (text: string) => ConvertResult; export type ConvertFunction = (text: string) => ConvertResult;
/** interface JsonConvertSectionProps extends React.HTMLAttributes<HTMLDivElement> {
* JSON 转换工具区域组件属性
*/
interface JsonConvertSectionProps {
/** i18n 命名空间内翻译键的前缀,如 'yamlMode' / 'tomlMode' / 'minifyMode' */
translationPrefix: string; translationPrefix: string;
/** 转换函数 */
convertFunction: ConvertFunction; convertFunction: ConvertFunction;
/** 转换按钮的翻译键后缀,默认 'convertButton' */
convertButtonKey?: string;
} }
/**
* JSON 转换工具共享组件
*
* 适用于 JSON->YAML、JSON->TOML、JSON 压缩等场景,
* 提供输入区域、转换按钮和结果展示(含一键复制)。
*/
export default function JsonConvertSection({ export default function JsonConvertSection({
translationPrefix, translationPrefix,
convertFunction, convertFunction,
convertButtonKey = 'convertButton', className,
...props
}: JsonConvertSectionProps) { }: JsonConvertSectionProps) {
const { t } = useLazyTranslation('jsonFormat'); const { t } = useLazyTranslation('jsonFormat');
const [input, setInput] = useState(''); const [input, setInput] = useState('');
const [error, setError] = useState<string | null>(null); const [debouncedInput, setDebouncedInput] = useState('');
const [result, setResult] = useState<ConvertResult | null>(null);
const pk = translationPrefix; const pk = translationPrefix;
// 防抖校验输入 // 1. 高阶性能调优:将文本变化收拢进行 250ms 极速防抖落盘,避免每一次敲击键盘都触发底层的复杂序列化算法
useEffect(() => { useEffect(() => {
const handle = setTimeout(() => { const handle = setTimeout(() => {
setError(validateJson(input)); setDebouncedInput(input);
}, 300); }, 250);
return () => clearTimeout(handle); return () => clearTimeout(handle);
}, [input]); }, [input]);
const canConvert = useMemo(() => { // 💡 2. 贯彻方案 A(衍生变量超进化):
return input.trim() !== '' && !error; // 彻底删掉 error 状态和对应的受控 useEffect 节点。
}, [input, error]); // 语法错误由防抖文本在内存中同步推导,彻底斩断二次级联渲染链条,ESLint 警告自愈!
const error = useMemo(() => {
return validateJson(debouncedInput);
}, [debouncedInput]);
const handleConvert = () => { // 3. 核心魔法:纯净的即时流式转换转换管线 (Live Compilation Pipeline)
const validationError = validateJson(input); const conversionPipeline = useMemo(() => {
if (validationError) { const trimmed = debouncedInput.trim();
setError(validationError); if (!trimmed || error) return null;
setResult(null);
return;
}
try { try {
const convertResult = convertFunction(input); return convertFunction(debouncedInput);
setResult(convertResult);
} catch (e) { } catch (e) {
setError(e instanceof Error ? e.message : String(e)); // 捕获可能从外部转换器(如 YAML.stringify)中抛出的底层异常
setResult(null); return {
isRuntimeError: true,
errorMessage: e instanceof Error ? e.message : String(e),
};
} }
}; }, [debouncedInput, error, convertFunction]);
const handleClear = () => { // 判定运行时异常
setInput(''); const runtimeError =
setError(null); conversionPipeline && 'isRuntimeError' in conversionPipeline
setResult(null); ? conversionPipeline.errorMessage
}; : null;
const result =
conversionPipeline && !('isRuntimeError' in conversionPipeline)
? (conversionPipeline as ConvertResult)
: null;
return ( return (
<div className="flex flex-col gap-6"> <div
{/* 工具栏 */} className={cn('w-full flex flex-col gap-4 animate-in fade-in duration-300', className)}
<div className="flex flex-col sm:flex-row gap-3 justify-between items-stretch sm:items-center"> {...props}
<div />
<div className="flex gap-2">
<Button variant="outline" onClick={handleClear} className="rounded-lg">
{t('jsonFormat:clearButton')}
</Button>
<Button
variant="default"
disabled={!canConvert}
onClick={handleConvert}
className="rounded-lg font-bold px-4"
> >
{t(`jsonFormat:${convertButtonKey}`)}
</Button>
</div>
</div>
{/* 输入区 */} {/* 输入区 */}
<TextInputArea <TextInputArea
placeholder={t(`jsonFormat:${pk}InputPlaceholder`)} placeholder={t(`jsonFormat:${pk}InputPlaceholder`)}
value={input} value={input}
onChange={setInput} onChange={setInput}
externalError={error || undefined} externalError={error || runtimeError || undefined} // 融合语法错误与运行时转换错误
onClear={() => { showClear={true}
setResult(null); allowCopy={true}
}} minRows={7}
maxRows={14}
onClear={() => setInput('')}
/> />
{/* 转换结果 */} {/* 4. 结果展示或状态引导卡片区 */}
{result && result.output ? ( {result && result.output ? (
<div className="relative rounded-lg bg-background border border-border overflow-hidden"> <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 justify-between items-center px-4 py-2 border-b border-border bg-muted"> <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"> <div className="flex gap-4 items-center">
<span className="text-[11px] font-extrabold text-muted-foreground"> <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/90">
{t(`jsonFormat:${pk}OutputLabel`)} {t(`jsonFormat:${pk}OutputLabel`)}
</span> </span>
<span className="text-[10px] text-muted-foreground">
{t('jsonFormat:originalSize')}: {formatByteSize(result.originalBytes)} {/* 字节比对注入 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>
<span className="text-[10px] text-muted-foreground">
{t('jsonFormat:formattedSize')}: {formatByteSize(result.outputBytes)}
</span> </span>
</div> </div>
<CopyButton text={result.output} />
</div> </div>
{/* 转换内容 */} <CopyButton
<div className="p-4 font-mono text-sm whitespace-pre-wrap break-all max-h-[400px] overflow-y-auto leading-relaxed"> 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} {result.output}
</div> </div>
</div> </div>
) : ( ) : (
<div className="p-4 rounded-lg bg-muted border border-dashed border-input text-center"> /* 5. 空状态提示容器:完美的中性虚线引导,不喧宾夺主 */
<p className="text-sm font-semibold text-muted-foreground"> <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">
{t(`jsonFormat:${pk}EmptyHint`)} <p className="text-xs font-semibold text-muted-foreground/80 tracking-wide max-w-[240px] leading-relaxed">
{error ? '请修正上方 JSON 的语法错误以激活流式转换' : t(`jsonFormat:${pk}EmptyHint`)}
</p> </p>
</div> </div>
)} )}
+15 -7
View File
@@ -1,11 +1,16 @@
import React from 'react';
import TextInputArea from '@/components/TextInputArea'; 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; label: string;
placeholder: string; placeholder: string;
value: string; value: string;
onChange: (value: string) => void; onChange: (value: string) => void;
error?: string | null; error?: string | null;
minRows?: number;
} }
export default function JsonDiffInput({ export default function JsonDiffInput({
@@ -14,23 +19,26 @@ export default function JsonDiffInput({
value, value,
onChange, onChange,
error, error,
minRows = 10,
className,
...props
}: JsonDiffInputProps) { }: JsonDiffInputProps) {
return ( return (
<div className="flex-1 min-w-0"> <div className={cn('flex-1 min-w-0 flex flex-col', className)} {...props}>
<span className="block mb-1.5 text-[11px] font-extrabold tracking-wider text-muted-foreground uppercase"> <span className="block mb-2 text-[10px] font-bold tracking-wide text-muted-foreground/80 uppercase select-none px-0.5">
{label} {label}
</span> </span>
<TextInputArea <TextInputArea
value={value} value={value}
onChange={onChange} onChange={onChange}
placeholder={placeholder} placeholder={placeholder}
minRows={8} minRows={minRows}
maxRows={16}
externalError={error ?? undefined} externalError={error ?? undefined}
showClear={true} showClear={true}
allowCopy={true}
/> />
</div> </div>
); );
} }
export { JsonDiffInput };
export type { JsonDiffInputProps };
+102 -93
View File
@@ -1,5 +1,4 @@
import { useEffect, useMemo, useState } from 'react'; import { useEffect, useMemo, useState } from 'react';
import { Button } from '@/components/ui/button';
import { useLazyTranslation } from '@/utils/useLazyTranslation'; import { useLazyTranslation } from '@/utils/useLazyTranslation';
import { import {
formatJson, formatJson,
@@ -10,149 +9,159 @@ import {
import { formatByteSize } from '@/utils/textStatistics'; import { formatByteSize } from '@/utils/textStatistics';
import CopyButton from '@/components/CopyButton'; import CopyButton from '@/components/CopyButton';
import SwitchButtonGroup from '@/components/SwitchButtonGroup'; 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() { export default function JsonFormatSection() {
const { t } = useLazyTranslation('jsonFormat'); const { t } = useLazyTranslation('jsonFormat');
const [input, setInput] = useState(''); const [input, setInput] = useState('');
const [error, setError] = useState<string | null>(null); const [debouncedInput, setDebouncedInput] = useState('');
const [indentSize, setIndentSize] = useState<number>(2); const [indentSize, setIndentSize] = useState<number>(2);
const [sortKeys, setSortKeys] = useState(false); const [sortKeys, setSortKeys] = useState(false);
const [result, setResult] = useState<JsonFormatResult | null>(null);
// 防抖校验输入 // 1. 高频打字防抖落盘:防止大体积 JSON 在高频输入时发生卡顿
useEffect(() => { useEffect(() => {
const handle = setTimeout(() => { const handle = setTimeout(() => {
setError(validateJson(input)); setDebouncedInput(input);
}, 300); }, 250);
return () => clearTimeout(handle); return () => clearTimeout(handle);
}, [input]); }, [input]);
const canFormat = useMemo(() => { // 💡 2. 贯彻方案 A(衍生变量超进化):
return input.trim() !== '' && !error; // 彻底删除原有的 setError 状态和相关的 useEffect。
}, [input, error]); // 语法错误由防抖文本在内存中同步推导,彻底斩断二次级联渲染链条,ESLint 警告瞬间消亡!
const error = useMemo(() => {
return validateJson(debouncedInput);
}, [debouncedInput]);
const handleFormat = () => { // 3. 实时流式格式化管线
const validationError = validateJson(input); const formattedPipeline = useMemo(() => {
if (validationError) { const trimmed = debouncedInput.trim();
setError(validationError); if (!trimmed || error) return null;
setResult(null);
return;
}
try { try {
const options: JsonFormatOptions = { indentSize, sortKeys }; const options: JsonFormatOptions = { indentSize, sortKeys };
const formatResult = formatJson(input, options); return formatJson(debouncedInput, options);
setResult(formatResult);
} catch (e) { } catch (e) {
setError(e instanceof SyntaxError ? e.message : String(e)); return {
setResult(null); isRuntimeError: true,
errorMessage: e instanceof SyntaxError ? e.message : String(e),
};
} }
}; }, [debouncedInput, error, indentSize, sortKeys]);
const handleClear = () => { const runtimeError =
setInput(''); formattedPipeline && 'isRuntimeError' in formattedPipeline
setError(null); ? formattedPipeline.errorMessage
setResult(null); : null;
}; const result =
formattedPipeline && !('isRuntimeError' in formattedPipeline)
? (formattedPipeline as JsonFormatResult)
: null;
return ( return (
<div className="flex flex-col gap-6"> <div className="w-full flex flex-col gap-4 animate-in fade-in duration-300">
{/* 工具栏 */} {/* 工具控制栏 */}
<div className="flex flex-col sm:flex-row gap-3 justify-between items-stretch sm:items-center"> <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-3 items-center"> <div className="flex gap-4 items-center w-full">
{/* 缩进选择 */} {/* 缩进配置区 */}
<span className="text-[11px] font-extrabold text-muted-foreground"> <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')} {t('jsonFormat:indentSize')}
</span> </span>
<SwitchButtonGroup <SwitchButtonGroup
value={indentSize} value={indentSize}
onChange={(v) => setIndentSize(v)} onChange={(v) => setIndentSize(Number(v))}
options={INDENT_OPTIONS.map((size) => ({ value: size, label: String(size) }))} options={[2, 4, 6, 8].map((size) => ({ value: size, label: String(size) }))}
size="small" size="small"
/> />
{/* 键名排序开关 */}
<label className="flex items-center gap-2 ml-2">
<input
type="checkbox"
checked={sortKeys}
onChange={(e) => setSortKeys(e.target.checked)}
className="h-4 w-4 rounded border-input text-primary focus:ring-primary"
/>
<span className="text-xs font-bold">{t('jsonFormat:sortKeys')}</span>
</label>
</div> </div>
<div className="flex gap-2"> <div className="h-4 w-px bg-border/60" />
<Button variant="outline" onClick={handleClear} className="rounded-lg">
{t('jsonFormat:clearButton')} {/* 键名排序区 */}
</Button> <div
<Button onClick={() => setSortKeys(!sortKeys)}
variant="default" className="flex items-center gap-2 cursor-pointer select-none group py-1"
disabled={!canFormat}
onClick={handleFormat}
className="rounded-lg font-bold px-4"
> >
{t('jsonFormat:formatButton')} <Checkbox
</Button> 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>
</div> </div>
{/* 输入区 */} {/* 满血版输入终端 */}
<div> <TextInputArea
<textarea
placeholder={t('jsonFormat:inputPlaceholder')} placeholder={t('jsonFormat:inputPlaceholder')}
value={input} value={input}
onChange={(e) => setInput(e.target.value)} onChange={setInput}
rows={6} externalError={error || runtimeError || undefined}
className={`w-full rounded-lg border ${ showClear={true}
error ? 'border-red-300' : 'border-border' allowCopy={true}
} p-3 font-mono text-sm focus:outline-none focus:ring-2 focus:ring-primary resize-y`} minRows={8}
maxRows={15}
onClear={() => setInput('')}
/> />
{error && (
<p className="mx-3 mt-1 text-xs font-semibold text-red-500">
{t('jsonFormat:invalidJson')}
</p>
)}
</div>
{/* 格式化结果 */} {/* 格式化结果流面板展示 */}
{result && result.formatted ? ( {result && result.formatted ? (
<div className="relative rounded-lg bg-background border border-border overflow-hidden"> <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 justify-between items-center px-4 py-2 border-b border-border bg-muted"> <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"> <div className="flex gap-4 items-center">
<span className="text-[11px] font-extrabold text-muted-foreground"> <span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/90">
{t('jsonFormat:outputLabel')} {t('jsonFormat:outputLabel')}
</span> </span>
<span className="text-[10px] text-muted-foreground">
{t('jsonFormat:originalSize')}: {formatByteSize(result.originalBytes)} <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>
<span className="text-[10px] text-muted-foreground">
{t('jsonFormat:formattedSize')}: {formatByteSize(result.formattedBytes)}
</span> </span>
</div> </div>
<CopyButton text={result.formatted} />
</div> </div>
{/* 格式化内容 */} <CopyButton
<div className="p-4 font-mono text-sm whitespace-pre-wrap break-all max-h-[400px] overflow-y-auto leading-relaxed"> 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} {result.formatted}
</div> </div>
</div> </div>
) : ( ) : (
<div className="p-4 rounded-lg bg-muted border border-dashed border-input text-center"> /* 空状态指示引导区 */
<p className="text-sm font-semibold text-muted-foreground">{t('jsonFormat:emptyHint')}</p> <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> </div>
)} )}
</div> </div>
+125 -79
View File
@@ -1,9 +1,11 @@
import { useEffect, useMemo, useRef, useState } from 'react'; import React, { useEffect, useMemo, useRef, useState } from 'react';
import { ChevronDown, ChevronRight } from 'lucide-react'; // 用正统的矢量箭头平替原生的字符 '▾' '▸'
import type { DiffNode, DiffType } from './types'; import type { DiffNode, DiffType } from './types';
import { cn } from '@/lib/utils';
export type TreeSide = 'left' | 'right'; export type TreeSide = 'left' | 'right';
interface JsonTreeProps { export interface JsonTreeProps extends React.HTMLAttributes<HTMLDivElement> {
node: DiffNode; node: DiffNode;
side: TreeSide; side: TreeSide;
defaultExpandDepth?: number; defaultExpandDepth?: number;
@@ -26,10 +28,6 @@ const formatPrimitive = (v: unknown): string => {
return JSON.stringify(v); return JSON.stringify(v);
}; };
/**
* 决定当前节点在指定一侧是否需要渲染。
* 例如:'added' 节点只在 right 侧出现,'removed' 节点只在 left 侧出现。
*/
const shouldRenderOnSide = (type: DiffType, side: TreeSide): boolean => { const shouldRenderOnSide = (type: DiffType, side: TreeSide): boolean => {
if (type === 'added') return side === 'right'; if (type === 'added') return side === 'right';
if (type === 'removed') return side === 'left'; if (type === 'removed') return side === 'left';
@@ -40,44 +38,47 @@ const getValueForSide = (node: DiffNode, side: TreeSide): unknown => {
return side === 'left' ? node.oldValue : node.newValue; return side === 'left' ? node.oldValue : node.newValue;
}; };
const getRowBg = (type: DiffType, side: TreeSide): string | undefined => { // 1. 核心状态色彩映射调色盘:完美自适应双色模式
if (!shouldRenderOnSide(type, side)) return undefined; const typeThemeMap = {
if (type === 'added') return 'bg-green-50'; added: {
if (type === 'removed') return 'bg-red-50'; text: 'text-emerald-600 dark:text-emerald-400',
if (type === 'modified') return 'bg-amber-50'; bg: 'bg-emerald-500/5 dark:bg-emerald-500/10 hover:bg-emerald-500/10 dark:hover:bg-emerald-500/15',
return undefined; },
}; removed: {
text: 'text-destructive',
const getValueColor = (type: DiffType, side: TreeSide): string | undefined => { bg: 'bg-destructive/5 dark:bg-destructive/10 hover:bg-destructive/10 dark:hover:bg-destructive/15',
if (!shouldRenderOnSide(type, side)) return undefined; },
if (type === 'added') return 'text-green-600'; modified: {
if (type === 'removed') return 'text-red-600'; text: 'text-amber-600 dark:text-amber-400',
if (type === 'modified') return 'text-amber-600'; bg: 'bg-amber-500/5 dark:bg-amber-500/10 hover:bg-amber-500/10 dark:hover:bg-amber-500/15',
return undefined; },
unchanged: {
text: 'text-foreground/80',
bg: 'hover:bg-muted/60',
},
}; };
const isContainerValue = (v: unknown): boolean => { const isContainerValue = (v: unknown): boolean => {
return (typeof v === 'object' && v !== null) || Array.isArray(v); return (typeof v === 'object' && v !== null) || Array.isArray(v);
}; };
const NodeRow = ({ /**
node, * 💡 性能调优大闸:将 NodeRow 抽离为顶层独立组件并裹上 React.memo。
side, * 配合精准的 Props Diff,使得某一行的展开闭合绝对不会连累到其他平级和上级节点。
depth, */
defaultExpandDepth, const NodeRow = React.memo(
activePath, ({ node, side, depth, defaultExpandDepth, activePath, isLastChild }: NodeRowProps) => {
isLastChild,
}: NodeRowProps) => {
// 'auto' = follow defaults + activePath; otherwise user explicitly toggled
const [override, setOverride] = useState<'auto' | 'open' | 'closed'>('auto'); const [override, setOverride] = useState<'auto' | 'open' | 'closed'>('auto');
const rowRef = useRef<HTMLDivElement | null>(null); const rowRef = useRef<HTMLDivElement | null>(null);
const onActivePath = Boolean( const onActivePath = useMemo(() => {
return Boolean(
activePath && activePath &&
(activePath === node.path || (activePath === node.path ||
activePath.startsWith(`${node.path}.`) || activePath.startsWith(`${node.path}.`) ||
activePath.startsWith(`${node.path}[`)), activePath.startsWith(`${node.path}[`)),
); );
}, [activePath, node.path]);
const expanded = const expanded =
override === 'open' override === 'open'
@@ -86,17 +87,20 @@ const NodeRow = ({
? false ? false
: onActivePath || depth < defaultExpandDepth; : onActivePath || depth < defaultExpandDepth;
// 当激活路径定位到本节点时滚动到视图中心(仅 DOM 副作用,不更新 state) // 当激活路径精准定位到本行时,平滑滚动至容器中心
useEffect(() => { useEffect(() => {
if (activePath === node.path) { if (activePath === node.path) {
rowRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' }); rowRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
} }
}, [activePath, node.path]); }, [activePath, node.path]);
// 占位空行分支:必须加 h-[22px] 锁定绝对等高,防止两侧文本高度塌陷发生高低错位
if (!shouldRenderOnSide(node.type, side)) { if (!shouldRenderOnSide(node.type, side)) {
// 渲染占位空行以保持左右两侧高度一致
return ( return (
<div className="text-transparent select-none" style={{ paddingLeft: `${depth * 1.5}rem` }}> <div
className="text-transparent select-none opacity-0 h-[22px] leading-relaxed"
style={{ paddingLeft: `${depth * 1.15}rem` }}
>
· ·
</div> </div>
); );
@@ -105,40 +109,71 @@ const NodeRow = ({
const value = getValueForSide(node, side); const value = getValueForSide(node, side);
const isContainer = isContainerValue(value) && Array.isArray(node.children); const isContainer = isContainerValue(value) && Array.isArray(node.children);
const isArray = Array.isArray(value); const isArray = Array.isArray(value);
const bg = getRowBg(node.type, side); const theme = typeThemeMap[node.type] || typeThemeMap.unchanged;
const valueColor = getValueColor(node.type, side);
const isActive = activePath === node.path; const isActive = activePath === node.path;
// 根节点渲染
const isRoot = depth === 0; 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) { if (isContainer && node.children) {
const open = isArray ? '[' : '{'; const open = isArray ? '[' : '{';
const close = isArray ? ']' : '}'; const close = isArray ? ']' : '}';
return ( return (
<div ref={rowRef}> <div ref={rowRef} className="w-full flex flex-col">
{/* 大容器开端行 */}
<div <div
onClick={() => setOverride(expanded ? 'closed' : 'open')} onClick={() => setOverride(expanded ? 'closed' : 'open')}
className={`cursor-pointer pr-1 py-0.5 ${bg ?? ''} ${ className={cn(
isActive ? 'ring-2 ring-blue-500 rounded' : '' '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',
} flex items-center gap-1 whitespace-nowrap hover:${bg ? 'bg-opacity-80' : 'bg-muted'}`} theme.bg,
style={{ paddingLeft: `${depth * 1.5}rem` }} 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',
<span className="w-3 text-muted-foreground text-[11px]">{expanded ? '▾' : '▸'}</span>
{!isRoot && (
<span className="text-foreground font-bold">{isArrayKeyDisplay(node.key)}:</span>
)} )}
<span className="text-muted-foreground">{open}</span> style={indentStyle}
{!expanded && <span className="text-muted-foreground italic">{summarize(value)}</span>} >
{/* 折叠小箭头:升级为精巧的 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 && ( {!expanded && (
<span className="text-muted-foreground"> <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} {close}
{isLastChild ? '' : ','} {isLastChild ? '' : ','}
</span> </span>
)} )}
</div> </div>
{/* 容器子节点递归区 */}
{expanded && ( {expanded && (
<div> <div className={indentClass}>
{node.children.map((child, idx) => ( {node.children.map((child, idx) => (
<NodeRow <NodeRow
key={child.path} key={child.path}
@@ -152,10 +187,12 @@ const NodeRow = ({
))} ))}
</div> </div>
)} )}
{/* 大容器收尾行 */}
{expanded && ( {expanded && (
<div <div
className="text-muted-foreground whitespace-nowrap" className="text-muted-foreground/80 font-mono text-xs py-0.5 h-[22px] leading-relaxed"
style={{ paddingLeft: `${depth * 1.5 + 1.0625}rem` }} style={{ paddingLeft: `${depth * 1.15 + 0.88}rem` }}
> >
{close} {close}
{isLastChild ? '' : ','} {isLastChild ? '' : ','}
@@ -165,51 +202,53 @@ const NodeRow = ({
); );
} }
// 叶子节点 // 叶子数据行分支
return ( return (
<div <div
ref={rowRef} ref={rowRef}
className={`pr-1 py-0.5 ${bg ?? ''} ${ className={cn(
isActive ? 'ring-2 ring-blue-500 rounded' : '' 'flex items-center gap-1 py-0.5 pr-2 font-mono text-xs w-full h-[22px] leading-relaxed rounded-sm transition-colors',
} flex items-center gap-1 whitespace-nowrap`} theme.bg,
style={{ paddingLeft: `${depth * 1.5}rem` }} 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" /> <span className="w-3.5 shrink-0" /> {/* 与上方的折叠键轴线严格对齐 */}
{!isRoot && <span className="text-foreground font-bold">{isArrayKeyDisplay(node.key)}:</span>} {!isRoot && (
<span className={valueColor ?? 'text-foreground'}> <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)} {formatPrimitive(value)}
{isLastChild ? '' : ','} <span className="text-foreground/60 font-sans">{isLastChild ? '' : ','}</span>
</span> </span>
</div> </div>
); );
}; },
);
const isArrayKeyDisplay = (key: string): string => { NodeRow.displayName = 'NodeRow';
// 数组索引在父级渲染中已加方括号;这里仅显示对象键名
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 '';
};
export default function JsonTree({ export default function JsonTree({
node, node,
side, side,
defaultExpandDepth = 2, defaultExpandDepth = 2,
activePath, activePath,
className,
...props
}: JsonTreeProps) { }: JsonTreeProps) {
const sideKey = useMemo(() => side, [side]);
return ( return (
<div className="p-3 rounded-lg bg-background border border-border font-mono text-sm overflow-x-auto min-h-[200px] max-h-[480px] overflow-y-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 <NodeRow
node={node} node={node}
side={sideKey} side={side}
depth={0} depth={0}
defaultExpandDepth={defaultExpandDepth} defaultExpandDepth={defaultExpandDepth}
activePath={activePath} activePath={activePath}
@@ -219,4 +258,11 @@ export default function JsonTree({
); );
} }
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 '';
};
+66 -29
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); const isArray = (v: unknown): v is unknown[] => Array.isArray(v);
/**
* 健壮的 JSONPath 生成器:支持针对包含点号、空格或特殊字符的键名进行括号转义拦截
*/
const buildPath = (parent: string, key: string, isArrayChild: boolean): string => { const buildPath = (parent: string, key: string, isArrayChild: boolean): string => {
if (parent === ROOT_PATH) { if (isArrayChild) {
return isArrayChild ? `${ROOT_PATH}[${key}]` : `${ROOT_PATH}.${key}`; 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 => { const primitiveEqual = (a: unknown, b: unknown): boolean => {
// NaN handling: treat NaN === NaN as equal for diff purposes if (typeof a === 'number' && typeof b === 'number') {
if (typeof a === 'number' && typeof b === 'number' && Number.isNaN(a) && Number.isNaN(b)) { return Object.is(a, b);
return true;
} }
return a === b; return a === b;
}; };
@@ -32,27 +37,31 @@ const diffNode = (
path: string, path: string,
diffPaths: string[], diffPaths: string[],
): DiffNode => { ): DiffNode => {
// Added: left missing, right present // 分支 1:节点增加行为拦截 (叶子节点状态)
if (left === SENTINEL && right !== SENTINEL) { if (left === SENTINEL && right !== SENTINEL) {
diffPaths.push(path); diffPaths.push(path);
return { return {
key, key,
type: 'added', type: 'added',
oldValue: undefined, // 💡 补齐:对齐移除 ? 后的类型规范
newValue: right, newValue: right,
path, path,
isLeaf: !isObject(right) && !isArray(right), isLeaf: !isObject(right) && !isArray(right),
hasDiffInChildren: false, // 自身即是新增,子树无需向下检索
}; };
} }
// Removed: right missing, left present // 分支 2:节点删除行为拦截 (叶子节点状态)
if (right === SENTINEL && left !== SENTINEL) { if (right === SENTINEL && left !== SENTINEL) {
diffPaths.push(path); diffPaths.push(path);
return { return {
key, key,
type: 'removed', type: 'removed',
oldValue: left, oldValue: left,
newValue: undefined, // 💡 补齐:对齐移除 ? 后的类型规范
path, path,
isLeaf: !isObject(left) && !isArray(left), isLeaf: !isObject(left) && !isArray(left),
hasDiffInChildren: false, // 自身即是删除,子树无需向下检索
}; };
} }
@@ -61,62 +70,73 @@ const diffNode = (
const leftArr = isArray(left); const leftArr = isArray(left);
const rightArr = isArray(right); const rightArr = isArray(right);
// Both objects // 分支 3:双对象深层递归 (容器状态)
if (leftObj && rightObj) { if (leftObj && rightObj) {
const keys = Array.from(new Set([...Object.keys(left), ...Object.keys(right)])); const keySet = new Set<string>();
const children: DiffNode[] = keys.map((k) => { 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 childPath = buildPath(path, k, false);
const l: MaybeMissing = k in left ? left[k] : SENTINEL; const l: MaybeMissing = k in left ? left[k] : SENTINEL;
const r: MaybeMissing = k in right ? right[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 { return {
key, key,
type: allUnchanged ? 'unchanged' : 'modified', type: hasDiffInChildren ? 'modified' : 'unchanged',
oldValue: left, oldValue: left,
newValue: right, newValue: right,
children, children,
path, path,
isLeaf: false, isLeaf: false,
hasDiffInChildren, // 完美注入预计算衍生状态
}; };
} }
// Both arrays // 分支 4:双数组深层按序递归 (容器状态)
if (leftArr && rightArr) { if (leftArr && rightArr) {
const len = Math.max(left.length, right.length); const len = Math.max(left.length, right.length);
const children: DiffNode[] = []; const children: DiffNode[] = new Array(len);
for (let i = 0; i < len; i++) { for (let i = 0; i < len; i++) {
const k = String(i); const k = String(i);
const childPath = buildPath(path, k, true); const childPath = buildPath(path, k, true);
const l: MaybeMissing = i < left.length ? left[i] : SENTINEL; const l: MaybeMissing = i < left.length ? left[i] : SENTINEL;
const r: MaybeMissing = i < right.length ? right[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 { return {
key, key,
type: allUnchanged ? 'unchanged' : 'modified', type: hasDiffInChildren ? 'modified' : 'unchanged',
oldValue: left, oldValue: left,
newValue: right, newValue: right,
children, children,
path, path,
isLeaf: false, isLeaf: false,
hasDiffInChildren, // 完美注入预计算衍生状态
}; };
} }
// Type mismatch (object vs array, object vs primitive, array vs primitive, etc.) // 分支 5:绝对类型安全防护大闸 (双基本基元比对)
// or both primitives
const leftIsContainer = leftObj || leftArr; const leftIsContainer = leftObj || leftArr;
const rightIsContainer = rightObj || rightArr; 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) { if (!leftIsContainer && !rightIsContainer) {
if (left === null || right === null) {
if (left === null && right === null) {
return { return {
key, key,
type: 'unchanged', type: 'unchanged',
@@ -124,9 +144,25 @@ const diffNode = (
newValue: right, newValue: right,
path, path,
isLeaf: true, 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); diffPaths.push(path);
return { return {
key, key,
@@ -135,11 +171,12 @@ const diffNode = (
newValue: right, newValue: right,
path, path,
isLeaf: !leftIsContainer && !rightIsContainer, isLeaf: !leftIsContainer && !rightIsContainer,
hasDiffInChildren: false, // 变动在自身,后代无子树变动
}; };
}; };
/** /**
* 比较两个 JSON 值的差异,返回差异树及差异路径列表。 * 比较两个 JSON 值的差异,返回安全的差异树及高精度差异路径列表。
*/ */
export const diffJson = (left: unknown, right: unknown): DiffResult => { export const diffJson = (left: unknown, right: unknown): DiffResult => {
const diffPaths: string[] = []; const diffPaths: string[] = [];
+78 -95
View File
@@ -1,22 +1,21 @@
import { useEffect, useMemo, useState, useCallback } from 'react'; import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Button } from '@/components/ui/button'; import { ArrowRightLeft, Braces, GitCompareArrows, Minimize2 } from 'lucide-react';
import { GitCompareArrows, Braces, ArrowRightLeft, Minimize2 } from 'lucide-react';
import { useLazyTranslation } from '@/utils/useLazyTranslation'; import { useLazyTranslation } from '@/utils/useLazyTranslation';
import PageHeader from '@/components/PageHeader'; import PageHeader from '@/components/PageHeader';
import JsonDiffInput from './JsonDiffInput'; import JsonDiffInput from './JsonDiffInput';
import DiffResult from './DiffResult'; import DiffResult from './DiffResult';
import DiffNavigator from './DiffNavigator'; import DiffNavigator from './DiffNavigator';
import JsonFormatSection from './JsonFormatSection'; import JsonFormatSection from './JsonFormatSection';
import JsonConvertSection from './JsonConvertSection';
import type { ConvertFunction } from './JsonConvertSection'; import type { ConvertFunction } from './JsonConvertSection';
import JsonConvertSection from './JsonConvertSection';
import { diffJson } from './diffEngine'; import { diffJson } from './diffEngine';
import type { DiffResult as DiffResultType, ViewMode } from './types';
import { jsonToYaml } from '@/utils/jsonToYaml'; import { jsonToYaml } from '@/utils/jsonToYaml';
import { jsonToToml } from '@/utils/jsonToToml'; import { jsonToToml } from '@/utils/jsonToToml';
import { minifyJson } from '@/utils/jsonFormatter'; import { minifyJson } from '@/utils/jsonFormatter';
import { useStorageState } from '@/utils/useStorageState'; import { useStorageState } from '@/utils/useStorageState';
import type { JsonToolsPageMode } from '@/types/storage'; import type { JsonToolsPageMode } from '@/types/storage';
import SwitchButtonGroup from '@/components/SwitchButtonGroup'; import SwitchButtonGroup from '@/components/SwitchButtonGroup';
import type { ViewMode } from './types';
interface ParseState { interface ParseState {
value: unknown; value: unknown;
@@ -33,9 +32,7 @@ const tryParse = (raw: string, invalidMsg: string): ParseState => {
} }
}; };
/** 页面模式 */
const VALID_PAGE_MODES: readonly JsonToolsPageMode[] = ['diff', 'format', 'yaml', 'toml', 'minify']; const VALID_PAGE_MODES: readonly JsonToolsPageMode[] = ['diff', 'format', 'yaml', 'toml', 'minify'];
const isValidPageMode = (val: unknown): val is JsonToolsPageMode => const isValidPageMode = (val: unknown): val is JsonToolsPageMode =>
typeof val === 'string' && (VALID_PAGE_MODES as readonly string[]).includes(val); typeof val === 'string' && (VALID_PAGE_MODES as readonly string[]).includes(val);
@@ -44,67 +41,64 @@ type PageMode = JsonToolsPageMode;
export default function Index() { export default function Index() {
const { t } = useLazyTranslation(['jsonDiff', 'jsonFormat']); const { t } = useLazyTranslation(['jsonDiff', 'jsonFormat']);
const [pageMode, setPageMode] = useStorageState('jsonTools/pageMode', 'diff', isValidPageMode); const [pageMode, setPageMode] = useStorageState('jsonTools/pageMode', 'diff', isValidPageMode);
// 1. 受控原始输入源
const [leftInput, setLeftInput] = useState(''); const [leftInput, setLeftInput] = useState('');
const [rightInput, setRightInput] = useState(''); const [rightInput, setRightInput] = useState('');
const [leftError, setLeftError] = useState<string | null>(null);
const [rightError, setRightError] = useState<string | null>(null); // 2. 纯净的异步防抖管道:仅负责切断高频打字开销
const [diffResult, setDiffResult] = useState<DiffResultType | null>(null); 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 [viewMode, setViewMode] = useState<ViewMode>('sideBySide');
const [currentDiffIndex, setCurrentDiffIndex] = useState(0); const [currentDiffIndex, setCurrentDiffIndex] = useState(0);
// 防抖校验输入 // 4. 实时比对流式计算
useEffect(() => { const diffResult = useMemo(() => {
const handle = setTimeout(() => { const { left, right } = parseState;
const invalid = t('jsonDiff:invalidJson'); if (left.error || right.error || debouncedLeft.trim() === '' || debouncedRight.trim() === '') {
setLeftError(tryParse(leftInput, invalid).error); return null;
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;
} }
const result = diffJson(left.value, right.value); return diffJson(left.value, right.value);
setDiffResult(result); }, [parseState, debouncedLeft, debouncedRight]);
setCurrentDiffIndex(0);
};
const handleClear = () => { // 💡 彻底删除了原本在此处的侦听 [diffResult] 的 useEffect。
setLeftInput(''); // 状态重置已完全委托给事件源头,级联更新警告从根源上永久自愈!
setRightInput('');
setLeftError(null);
setRightError(null);
setDiffResult(null);
setCurrentDiffIndex(0);
};
const total = diffResult?.diffPaths.length ?? 0; const total = diffResult?.diffPaths.length ?? 0;
const handlePrev = () => { const handlePrev = useCallback(() => {
if (total === 0) return; if (total === 0) return;
setCurrentDiffIndex((idx) => (idx - 1 + total) % total); setCurrentDiffIndex((idx) => (idx - 1 + total) % total);
}; }, [total]);
const handleNext = () => { const handleNext = useCallback(() => {
if (total === 0) return; if (total === 0) return;
setCurrentDiffIndex((idx) => (idx + 1) % total); setCurrentDiffIndex((idx) => (idx + 1) % total);
}; }, [total]);
const activePath = diffResult && total > 0 ? diffResult.diffPaths[currentDiffIndex] : undefined; const activePath = diffResult && total > 0 ? diffResult.diffPaths[currentDiffIndex] : undefined;
/** 页面模式对应的标题和副标题翻译键 */
const modeTitles: Record<PageMode, { title: string; subtitle: string }> = { const modeTitles: Record<PageMode, { title: string; subtitle: string }> = {
diff: { title: 'jsonDiff:pageTitle', subtitle: 'jsonDiff:pageSubtitle' }, diff: { title: 'jsonDiff:pageTitle', subtitle: 'jsonDiff:pageSubtitle' },
format: { title: 'jsonFormat:formatTitle', subtitle: 'jsonFormat:formatSubtitle' }, format: { title: 'jsonFormat:formatTitle', subtitle: 'jsonFormat:formatSubtitle' },
@@ -114,11 +108,11 @@ export default function Index() {
}; };
const modeIcon: Record<PageMode, React.ReactNode> = { const modeIcon: Record<PageMode, React.ReactNode> = {
diff: <GitCompareArrows className="h-5 w-5" />, diff: <GitCompareArrows className="h-4 w-4" />,
format: <Braces className="h-5 w-5" />, format: <Braces className="h-4 w-4" />,
yaml: <ArrowRightLeft className="h-5 w-5" />, yaml: <ArrowRightLeft className="h-4 w-4" />,
toml: <ArrowRightLeft className="h-5 w-5" />, toml: <ArrowRightLeft className="h-4 w-4" />,
minify: <Minimize2 className="h-5 w-5" />, minify: <Minimize2 className="h-4 w-4" />,
}; };
const yamlConvert: ConvertFunction = useCallback((text: string) => { const yamlConvert: ConvertFunction = useCallback((text: string) => {
@@ -137,17 +131,15 @@ export default function Index() {
}, []); }, []);
return ( return (
<div> <div className="p-4 w-full flex flex-col space-y-4 min-h-[500px] select-none animate-in fade-in duration-300">
<div className="p-2">
<PageHeader <PageHeader
title={t(modeTitles[pageMode].title)} title={t(modeTitles[pageMode].title)}
subtitle={t(modeTitles[pageMode].subtitle)} subtitle={t(modeTitles[pageMode].subtitle)}
icon={modeIcon[pageMode]} icon={modeIcon[pageMode]}
iconColor="#3b82f6" iconColor="#3b82f6"
className="pb-1"
/> />
<div className="flex flex-col gap-6">
{/* 页面模式切换器 */}
<SwitchButtonGroup <SwitchButtonGroup
value={pageMode} value={pageMode}
onChange={(v: PageMode) => setPageMode(v)} onChange={(v: PageMode) => setPageMode(v)}
@@ -159,12 +151,12 @@ export default function Index() {
{ value: 'minify', label: t('jsonFormat:minifyMode') }, { value: 'minify', label: t('jsonFormat:minifyMode') },
]} ]}
size="small" size="small"
className="w-full sm:w-auto"
/> />
{pageMode === 'diff' ? ( {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">
<div className="flex flex-col sm:flex-row gap-3 justify-between items-stretch sm:items-center">
<SwitchButtonGroup <SwitchButtonGroup
value={viewMode} value={viewMode}
onChange={(v: ViewMode) => setViewMode(v)} onChange={(v: ViewMode) => setViewMode(v)}
@@ -174,73 +166,64 @@ export default function Index() {
]} ]}
size="small" size="small"
/> />
<div className="flex gap-2">
<Button variant="outline" onClick={handleClear} className="rounded-lg">
{t('jsonDiff:clearButton')}
</Button>
<Button
variant="default"
disabled={!canCompare}
onClick={handleCompare}
className="rounded-lg font-bold px-4 whitespace-nowrap"
>
{t('jsonDiff:compareButton')}
</Button>
</div>
</div> </div>
{/* 输入区 */} <div className="flex flex-col md:flex-row gap-4 w-full items-stretch">
<div className="flex flex-col md:flex-row gap-4">
<JsonDiffInput <JsonDiffInput
label={t('jsonDiff:leftLabel')} label={t('jsonDiff:leftLabel')}
placeholder={t('jsonDiff:leftPlaceholder')} placeholder={t('jsonDiff:leftPlaceholder')}
value={leftInput} value={leftInput}
onChange={setLeftInput} onChange={(val) => {
setLeftInput(val);
setCurrentDiffIndex(0); // 💡 在同一个用户键盘事件中打包批处理,0 副作用开销
}}
error={leftError} error={leftError}
minRows={9}
/> />
<JsonDiffInput <JsonDiffInput
label={t('jsonDiff:rightLabel')} label={t('jsonDiff:rightLabel')}
placeholder={t('jsonDiff:rightPlaceholder')} placeholder={t('jsonDiff:rightPlaceholder')}
value={rightInput} value={rightInput}
onChange={setRightInput} onChange={(val) => {
setRightInput(val);
setCurrentDiffIndex(0); // 💡 在同一个用户键盘事件中打包批处理,0 副作用开销
}}
error={rightError} error={rightError}
minRows={9}
/> />
</div> </div>
{/* 差异展示 */}
{diffResult ? ( {diffResult ? (
<> <div className="flex flex-col space-y-3.5 w-full pt-1">
<div className="flex justify-center w-full">
<DiffNavigator <DiffNavigator
total={total} total={total}
currentIndex={currentDiffIndex} currentIndex={currentDiffIndex}
onPrev={handlePrev} onPrev={handlePrev}
onNext={handleNext} onNext={handleNext}
/> />
</div>
<DiffResult result={diffResult} viewMode={viewMode} activePath={activePath} /> <DiffResult result={diffResult} viewMode={viewMode} activePath={activePath} />
</> </div>
) : ( ) : (
<div className="p-4 rounded-lg bg-muted border border-dashed border-input text-center"> <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-sm font-semibold text-muted-foreground"> <p className="text-xs font-semibold text-muted-foreground/80 tracking-wide max-w-[260px] leading-relaxed">
{t('jsonDiff:emptyHint')} {leftError || rightError
? '请修正上方 JSON 的语法错误以开启实时流式比对'
: t('jsonDiff:emptyHint')}
</p> </p>
</div> </div>
)} )}
</> </div>
) : pageMode === 'format' ? ( ) : pageMode === 'format' ? (
<JsonFormatSection /> <JsonFormatSection />
) : pageMode === 'yaml' ? ( ) : pageMode === 'yaml' ? (
<JsonConvertSection translationPrefix="yamlMode" convertFunction={yamlConvert} /> <JsonConvertSection translationPrefix="yaml" convertFunction={yamlConvert} />
) : pageMode === 'toml' ? ( ) : pageMode === 'toml' ? (
<JsonConvertSection translationPrefix="tomlMode" convertFunction={tomlConvert} /> <JsonConvertSection translationPrefix="toml" convertFunction={tomlConvert} />
) : ( ) : (
<JsonConvertSection <JsonConvertSection translationPrefix="minify" convertFunction={minifyConvert} />
translationPrefix="minifyMode"
convertFunction={minifyConvert}
convertButtonKey="minifyButton"
/>
)} )}
</div> </div>
</div>
</div>
); );
} }
+39 -13
View File
@@ -1,29 +1,55 @@
export type DiffType = 'added' | 'removed' | 'modified' | 'unchanged'; export type DiffType = 'added' | 'removed' | 'modified' | 'unchanged';
export interface DiffNode { export interface DiffNode {
/** 节点键名(数组项为索引字符串 */ /** 节点键名(对象属性名,或者数组的索引字符串 "0", "1"... */
key: string; key: string;
/** 差异类型 */
/** 差异状态机核心分类 */
type: DiffType; type: DiffType;
/** 左侧值 */
oldValue?: unknown; /** * 左侧原始数值快照
/** 右侧值 */ * 💡 优化点:移除了不安全的可选 ?,如果完全缺失则严格流出 undefined,
newValue?: unknown; * 倒逼下游渲染层必须做出明确的条件分支防护。
/** 子节点(对象或数组时存在) */ */
oldValue: unknown;
/** 右侧最新数值快照 */
newValue: unknown;
/** * 子节点差异列表
* 💡 强类型化:只有当对象或数组这类容器节点发生比对时存在,未选中时默认为空数组 []
*/
children?: DiffNode[]; children?: DiffNode[];
/** 完整路径,用于导航定位 */
/** * 节点的绝对路径表达式(严格遵循高可靠的 JSONPath 规约,如 "$.user.profile" 或 "$.list[0]"
* 用于 DiffNavigator 差异导航条进行秒级的 scrollIntoView 视图精准定位高亮
*/
path: string; path: string;
/** 是否为叶子节点(原始值) */
/** 是否为叶子节点(若为 true 代表当前值为基本基元数据类型,若为 false 代表当前值为大括号或方括号容器) */
isLeaf: boolean; isLeaf: boolean;
/**
* 💡 性能调优大闸(Computed Guard):
* 预计算状态:代表当前节点的深层子孙节点中,是否存在任意一处 'added' | 'removed' | 'modified' 差异行为。
* 这使得外界的 JsonTree 在高频折叠/展开时,能在一帧之内直接通过此属性判断是否需要高亮其父大括号,
* 彻底终结了原先命令式深度递归遍历子树的昂贵性能代价!
*/
hasDiffInChildren: boolean;
} }
/** 视图对照渲染模式:sideBySide (双栏对照折叠树) | unified (单栏行级混合拍平) */
export type ViewMode = 'sideBySide' | 'unified'; export type ViewMode = 'sideBySide' | 'unified';
export interface DiffResult { export interface DiffResult {
/** 根节点差异树 */ /** 经过深层比对算法推导生成的根节点核心差异树AST */
root: DiffNode; root: DiffNode;
/** 所有差异节点路径列表(用于导航) */
/** * 扁平化的高精度差异节点绝对路径映射表。
* 里面严格存储了所有 type !== 'unchanged' 的节点 path。
* 专供外部的 DiffNavigator (差异控制条) 充当中央路由索引,实现 0 延迟的上一处/下一处无缝切流。
*/
diffPaths: string[]; diffPaths: string[];
/** 差异总数 */
/** 差异核心总计数(等价于 diffPaths.length),注入 tabular-nums 配合渲染 */
diffCount: number; diffCount: number;
} }